From 98c0aa0fcf0047ac8e18682d9985bf4691c51306 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Fri, 27 Nov 2026 22:38:33 +1100 Subject: [PATCH] Support floating date-times in TaskNotes model --- CHANGELOG.md | 3 +- scripts/sync-tasknotes-pack.mjs | 2 +- src/calendar-date.ts | 13 +++++- src/conformance.ts | 11 +++-- src/date.ts | 59 ++++++++++++------------ src/generated/tasknotes-data-contract.ts | 36 ++++++++++++--- src/generated/tasknotes-type-pack.json | 46 ++++++++++++------ src/mdbase.ts | 31 +++++++------ src/operations.ts | 14 ++++-- src/recurrence.ts | 1 - src/starter.ts | 4 +- src/time.ts | 25 +++++----- src/types.ts | 2 +- src/validation.ts | 31 +++++++------ test/assignments.test.mjs | 4 +- test/calendar.test.mjs | 4 ++ test/mdbase.test.mjs | 56 ++++++++++++---------- test/model.test.mjs | 46 ++++++++++++++++++ test/settings.test.mjs | 2 +- test/starter.test.mjs | 17 ++++--- 20 files changed, 265 insertions(+), 142 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1792df5..6fd4529 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,8 @@ ### Fixed - `planCalendarEdit` no longer clears other occurrences' completed or skipped history when moving a scheduled-anchored recurring task. Moves without a `recurrence_original_date` (such as Google-synced or legacy off-pattern tasks) clear only the landing day when it is already recorded; completion-anchored tasks keep clearing recorded instances on or after the new date. Thanks to @martin-forge for reporting (TaskNotes #2691). -- Generated mdbase task types accept floating scheduled and due times written by TaskNotes. Thanks to @iantierney for reporting (TaskNotes #2706). +- Generated mdbase task types and the `tasknotes.task` 0.3.0-rc.7 contract accept floating `due`, `scheduled`, `dateCreated`, and `dateModified` values through the `local-date-time` format. Pack 0.3.0-rc.23 upgrades all earlier starters, including the TaskNotes #2706 fix. +- Calendar conversion accepts fractional seconds of any length and truncates to millisecond precision. Timestamp validation, task updates, and time tracking calculations use the collection timezone when callers supply it. ## 0.3.2 - 2026-11-20 diff --git a/scripts/sync-tasknotes-pack.mjs b/scripts/sync-tasknotes-pack.mjs index 4c3b924..132ac4b 100644 --- a/scripts/sync-tasknotes-pack.mjs +++ b/scripts/sync-tasknotes-pack.mjs @@ -9,7 +9,7 @@ const generatedPath = path.resolve( "../src/generated/tasknotes-type-pack.json" ); const source = await readFile( - path.join(contractsRoot, "dist/packs/tasknotes.task/0.3.0-rc.22.json"), + path.join(contractsRoot, "dist/packs/tasknotes.task/0.3.0-rc.23.json"), "utf8" ); diff --git a/src/calendar-date.ts b/src/calendar-date.ts index 787813f..155b60c 100644 --- a/src/calendar-date.ts +++ b/src/calendar-date.ts @@ -1,6 +1,6 @@ // Calendar dates are civil values in an explicit IANA zone, never the process zone. const DAY = 86_400_000; -const CIVIL = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?)?$/; +const CIVIL = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?$/; export function calendarDay(value: string): string { return value.slice(0, 10); @@ -65,6 +65,15 @@ export function calendarDateToInstant(value: string, timezone: string): number { return cached !== undefined ? cached : remember(toInstant, key, dateToInstant(value, timezone)); } +export function timestampForComparison(value: string, timezone?: string): number { + if (timezone === undefined) return Date.parse(value); + try { + return calendarDateToInstant(value.trim(), timezone); + } catch { + return NaN; + } +} + function dateToInstant(value: string, timezone: string): number { const match = CIVIL.exec(value); if (!match) { @@ -89,7 +98,7 @@ function dateToInstant(value: string, timezone: string): number { const matching = candidates.filter((ms) => civilAt(ms, format) === civil); return ( (matching.length ? Math.min(...matching) : Math.max(...candidates)) + - Number(fraction.padEnd(3, "0")) + Number(fraction.slice(0, 3).padEnd(3, "0")) ); } diff --git a/src/conformance.ts b/src/conformance.ts index e621489..a0d1e54 100644 --- a/src/conformance.ts +++ b/src/conformance.ts @@ -222,7 +222,7 @@ export function executeConformanceOperation( case "validation.core_evaluate": return ok(validateCoreConformance(input)); case "validation.time_entries": - return ok(validateTimeEntries(input.entries)); + return ok(validateTimeEntries(input.entries, stringOrUndefined(input.timezone))); case "op.mutate_with_validation": return mutateWithValidation(input); case "op.update_patch": @@ -289,7 +289,9 @@ export function executeConformanceOperation( case "time.auto_stop_on_complete": return ok({ value: true }); case "time.report_totals": - return ok({ minutes: calculateTotalTrackedMinutes(arrayValue(input.entries) as TimeEntry[]) }); + return ok({ + minutes: calculateTotalTrackedMinutes(arrayValue(input.entries) as TimeEntry[], stringOrUndefined(input.timezone)), + }); default: return err(`Unsupported operation: ${operation}`, { operation, code: "unsupported_operation" }); } @@ -500,6 +502,7 @@ function addConformanceIssue( function validateCoreConformance(input: Record): Record { const fields = asRecord(input.fields); const frontmatter = asRecord(input.frontmatter); + const timezone = stringOrUndefined(input.timezone); const mapping = buildSpecFieldMapping(fields, stringOrUndefined(input.displayNameKey)); const normalized = normalizeSpecFrontmatter(frontmatter, mapping); const issues: Record[] = []; @@ -542,7 +545,9 @@ function validateCoreConformance(input: Record): Record> = { + "0.3.0-rc.6": "sha256:c400ead6e218b715d86ad31125bb3d4b2e276817da6ba8065449fd0947b24d67", "0.3.0-rc.5": "sha256:dde71d0d776aa0069ee627fe3c10b1a20f87ba36929a16790598ebfb4e8ebf04", }; /** Contract versions a TaskNotes type may implement, newest first. */ @@ -695,11 +696,11 @@ export function buildTaskNotesMdbaseResources( integerSchema({ minimum: 0 }, legacyCompatibility) ); addField("completedDate", mapping.completedDate, dateSchema(legacyCompatibility)); - addField("dateCreated", mapping.dateCreated, dateTimeSchema(legacyCompatibility), { + addField("dateCreated", mapping.dateCreated, taskTimestampSchema(legacyCompatibility), { required: true, createValue: { now: true }, }); - addField("dateModified", mapping.dateModified, dateTimeSchema(legacyCompatibility), { + addField("dateModified", mapping.dateModified, taskTimestampSchema(legacyCompatibility), { createValue: { now: true }, updateValue: { now: true }, }); @@ -995,8 +996,7 @@ export function buildTaskNotesMdbaseResources( bindingSchemaDocument, paths: { config: "mdbase.yaml", - // Versioned, so the rc.5 contract at tasknotes.task.md stays for - // types that still implement it. + // Versioned, so existing contracts stay available to types that implement them. contract: `${contractsFolder}/tasknotes.task/${TASKNOTES_SPEC_VERSION}.md`, type: `${typesFolder}/${typeName}.md`, taskSchema: `${schemasFolder}/tasknotes-task.schema.json`, @@ -1039,7 +1039,7 @@ export async function buildTaskNotesMdbaseTypePack( [`contracts/tasknotes.task/${TASKNOTES_SPEC_VERSION}.md`, { target: resources.paths.contract, document: resources.contractDocument, }], - ["types/tasknotes-task/7.md", { + ["types/tasknotes-task/8.md", { target: resources.paths.type, document: resources.typeDocument, }], [`schemas/tasknotes.task/${TASKNOTES_SPEC_VERSION}.schema.json`, { @@ -1741,15 +1741,18 @@ function taskDateSchema(legacyCompatibility: boolean): Record { anyOf: [ dateSchema(legacyCompatibility), dateTimeSchema(legacyCompatibility), - { - type: "string", - // TaskNotes also stores wall-clock times without a UTC offset. - pattern: "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$", - }, + { type: "string", format: "local-date-time" }, ], }; } +function taskTimestampSchema(legacyCompatibility: boolean): Record { + const instant = dateTimeSchema(legacyCompatibility); + return legacyCompatibility + ? instant + : { anyOf: [instant, { type: "string", format: "local-date-time" }] }; +} + function dateTimeSchema(legacyCompatibility: boolean): Record { return legacyCompatibility ? { diff --git a/src/operations.ts b/src/operations.ts index 9874441..8842d32 100644 --- a/src/operations.ts +++ b/src/operations.ts @@ -1,4 +1,5 @@ import { formatDateForStorage, getDatePart, parseDateToUTC, validateDateString } from "./date"; +import { timestampForComparison } from "./calendar-date"; import { isCompletedStatus } from "./config"; import { addDTSTARTToRecurrenceRule, @@ -49,6 +50,8 @@ export interface BuildTaskUpdatePlanInput { userFields?: readonly UserMappedField[]; statuses?: readonly StatusConfig[]; now?: string; + /** Collection timezone for reading floating created and modified timestamps. */ + timezone?: string; currentDateString?: string; maintainDueDateOffsetInRecurring?: boolean; } @@ -212,6 +215,7 @@ export function buildTaskUpdatePlan({ userFields = [], statuses = [], now = new Date().toISOString(), + timezone, currentDateString = formatDateForStorage(parseDateToUTC(getDatePart(now))), maintainDueDateOffsetInRecurring = true, }: BuildTaskUpdatePlanInput): TaskOperationPlan { @@ -219,7 +223,8 @@ export function buildTaskUpdatePlan({ const dateModified = nextModifiedTimestamp( now, originalTask.dateCreated, - originalTask.dateModified + originalTask.dateModified, + timezone ); const recurrenceUpdates = buildTaskUpdateRecurrenceUpdates({ originalTask, @@ -263,12 +268,13 @@ export function buildTaskUpdatePlan({ function nextModifiedTimestamp( candidate: string, dateCreated?: string, - previousModified?: string + previousModified?: string, + timezone?: string ): string { - const candidateTime = Date.parse(candidate); + const candidateTime = timestampForComparison(candidate, timezone); if (!Number.isFinite(candidateTime)) return candidate; const storedTimes = [dateCreated, previousModified] - .map((value) => (value ? Date.parse(value) : Number.NaN)) + .map((value) => (value ? timestampForComparison(value, timezone) : Number.NaN)) .filter((value) => Number.isFinite(value)); if (storedTimes.length === 0) return candidate; const floor = Math.max(...storedTimes); diff --git a/src/recurrence.ts b/src/recurrence.ts index 5698730..4284ae7 100644 --- a/src/recurrence.ts +++ b/src/recurrence.ts @@ -453,7 +453,6 @@ function getLookAheadDays(recurrence: string): number { function formatDtstartValue(dateStr: string): string { if (hasTimeComponent(dateStr)) { - // Task dates are often minute precision ("2026-06-04T10:30"), which the strict parser rejects. const dateTime = resolveDateTimeRangeBound(dateStr, "from"); const year = dateTime.getFullYear(); const month = String(dateTime.getMonth() + 1).padStart(2, "0"); diff --git a/src/starter.ts b/src/starter.ts index 6c11277..0dee6b2 100644 --- a/src/starter.ts +++ b/src/starter.ts @@ -11,7 +11,7 @@ import { TASKNOTES_SPEC_VERSION, type TaskNotesModelConfig } from "./types"; /** * The published TaskNotes starter: the `tasknotes.task` pack's seed type that * applications install into new collections (mdbase-contracts - * `types/tasknotes-task/.md`). + * `types/tasknotes-task/.md`). * * It differs from the plugin defaults in `DEFAULT_STATUSES`: it adds the * skipped `cancelled` status, uses its own palette and declares only the @@ -28,7 +28,7 @@ export const TASKNOTES_STARTER_TYPE_VERSION = TASKNOTES_MDBASE_TYPE_VERSION; * type's data keeps TASKNOTES_STARTER_TYPE_VERSION, so collections that already * have that version do not see a conflicting version change on upgrade. */ -export const TASKNOTES_STARTER_REVISION = 7; +export const TASKNOTES_STARTER_REVISION = 8; /** * The generator bookkeeping published in the first starter. Collections keep diff --git a/src/time.ts b/src/time.ts index 57b5f95..f557840 100644 --- a/src/time.ts +++ b/src/time.ts @@ -1,3 +1,4 @@ +import { timestampForComparison } from "./calendar-date"; import type { TaskInfo, TimeEntry } from "./types"; export interface StartTimeTrackingPlan { @@ -32,30 +33,26 @@ export function getActiveTimeEntry(task: Pick): TimeEnt return sanitizeTimeEntries(task.timeEntries).find((entry) => !entry.endTime); } -export function calculateTimeEntryMinutes(entry: TimeEntry): number { +export function calculateTimeEntryMinutes(entry: TimeEntry, timezone?: string): number { if (!entry.endTime) return 0; - const start = new Date(entry.startTime); - const end = new Date(entry.endTime); - if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end < start) { - return 0; - } - return Math.round((end.getTime() - start.getTime()) / 60000); + return calculateElapsedTimeEntryMinutes(entry, entry.endTime, timezone); } export function calculateElapsedTimeEntryMinutes( entry: TimeEntry, - now = new Date().toISOString() + now = new Date().toISOString(), + timezone?: string ): number { - const start = new Date(entry.startTime); - const end = new Date(entry.endTime || now); - if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end < start) { + const start = timestampForComparison(entry.startTime, timezone); + const end = timestampForComparison(entry.endTime || now, timezone); + if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) { return 0; } - return Math.round((end.getTime() - start.getTime()) / 60000); + return Math.round((end - start) / 60000); } -export function calculateTotalTrackedMinutes(entries: readonly TimeEntry[] | undefined): number { - return sanitizeTimeEntries(entries).reduce((total, entry) => total + calculateTimeEntryMinutes(entry), 0); +export function calculateTotalTrackedMinutes(entries: readonly TimeEntry[] | undefined, timezone?: string): number { + return sanitizeTimeEntries(entries).reduce((total, entry) => total + calculateTimeEntryMinutes(entry, timezone), 0); } export function buildStartTimeTrackingPlan( diff --git a/src/types.ts b/src/types.ts index 0b26ca6..e0f71da 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,4 @@ -export const TASKNOTES_SPEC_VERSION = "0.3.0-rc.6"; +export const TASKNOTES_SPEC_VERSION = "0.3.0-rc.7"; export type JsonPrimitive = string | number | boolean | null; export type JsonValue = JsonPrimitive | JsonObject | JsonValue[]; diff --git a/src/validation.ts b/src/validation.ts index 7c61230..6ccbffb 100644 --- a/src/validation.ts +++ b/src/validation.ts @@ -1,4 +1,5 @@ import { getDatePart, validateDateString } from "./date"; +import { timestampForComparison } from "./calendar-date"; import { validateAttachmentReferences } from "./attachments"; import { isCompletedStatus } from "./config"; import { taskInfoSchema, timeEntrySchema } from "./schema"; @@ -10,7 +11,7 @@ import type { TimeEntry, } from "./types"; -export function validateTask(task: Partial): TaskValidationResult { +export function validateTask(task: Partial, timezone?: string): TaskValidationResult { const issues: TaskValidationIssue[] = []; const parsed = taskInfoSchema.partial().safeParse(task); if (!parsed.success) { @@ -71,7 +72,7 @@ export function validateTask(task: Partial): TaskValidationResult { } if (task.timeEntries) { - issues.push(...validateTimeEntries(task.timeEntries).issues); + issues.push(...validateTimeEntries(task.timeEntries, timezone).issues); } for (const issue of validateAttachmentReferences(task.attachments, task.path).issues) { @@ -90,7 +91,8 @@ export function validateTask(task: Partial): TaskValidationResult { }; } -export function validateTimeEntries(entries: unknown): TaskValidationResult { +/** Floating timestamps use the collection timezone when supplied, otherwise the system zone. */ +export function validateTimeEntries(entries: unknown, timezone?: string): TaskValidationResult { const issues: TaskValidationIssue[] = []; if (!Array.isArray(entries)) { return { @@ -119,7 +121,7 @@ export function validateTimeEntries(entries: unknown): TaskValidationResult { } return; } - validateTimeEntryOrder(parsed.data, index, issues); + validateTimeEntryOrder(parsed.data, index, issues, timezone); }); const activeCount = (entries as TimeEntry[]).filter((entry) => entry && !entry.endTime).length; @@ -138,11 +140,13 @@ export function validateTimeEntries(entries: unknown): TaskValidationResult { }; } +/** Floating timestamps use the collection timezone when supplied, otherwise the system zone. */ export function evaluateCoreValidation( task: Partial, - statuses: readonly StatusConfig[] + statuses: readonly StatusConfig[], + timezone?: string ): TaskValidationResult { - const result = validateTask(task); + const result = validateTask(task, timezone); for (const field of ["title", "status", "dateCreated", "dateModified"] as const) { const value = task[field]; if (typeof value !== "string" || value.trim().length === 0) { @@ -188,8 +192,8 @@ export function evaluateCoreValidation( } if (task.dateCreated && task.dateModified) { - const created = Date.parse(task.dateCreated); - const modified = Date.parse(task.dateModified); + const created = timestampForComparison(task.dateCreated, timezone); + const modified = timestampForComparison(task.dateModified, timezone); if (Number.isFinite(created) && Number.isFinite(modified) && modified < created) { result.issues.push({ code: "date_modified_before_created", @@ -216,10 +220,11 @@ export function evaluateCoreValidation( function validateTimeEntryOrder( entry: TimeEntry, index: number, - issues: TaskValidationIssue[] + issues: TaskValidationIssue[], + timezone?: string ): void { - const start = new Date(entry.startTime); - if (Number.isNaN(start.getTime())) { + const start = timestampForComparison(entry.startTime, timezone); + if (!Number.isFinite(start)) { issues.push({ code: "invalid_time_entry_start", message: "Time entry startTime must be a valid datetime", @@ -233,8 +238,8 @@ function validateTimeEntryOrder( return; } - const end = new Date(entry.endTime); - if (Number.isNaN(end.getTime())) { + const end = timestampForComparison(entry.endTime, timezone); + if (!Number.isFinite(end)) { issues.push({ code: "invalid_time_entry_end", message: "Time entry endTime must be a valid datetime", diff --git a/test/assignments.test.mjs b/test/assignments.test.mjs index d414e46..7df7ccb 100644 --- a/test/assignments.test.mjs +++ b/test/assignments.test.mjs @@ -20,8 +20,8 @@ test("ordinary task updates retain unresolved assignments and explicitly clear t test("the task contract declares assignments as links resolved by the collection", () => { const resources = buildTaskNotesMdbaseResources(); - assert.equal(resources.contract.version, "0.3.0-rc.6"); - assert.equal(resources.type.version, 5); + assert.equal(resources.contract.version, "0.3.0-rc.7"); + assert.equal(resources.type.version, 6); assert.equal(resources.taskSchema.properties.assignees.uniqueItems, true); assert.equal(resources.type.implements[0].fields.assignees, "assignees"); // No target_type: several local types may implement mdbase.person. diff --git a/test/calendar.test.mjs b/test/calendar.test.mjs index 9395cca..e162f81 100644 --- a/test/calendar.test.mjs +++ b/test/calendar.test.mjs @@ -177,6 +177,10 @@ test("civil DST disambiguation and offset instants have explicit compatible sema new Date(calendarDateToInstant("2026-11-01T01:30", "America/New_York")).toISOString(), "2026-11-01T05:30:00.000Z", ); + assert.equal( + new Date(calendarDateToInstant("2026-11-01T01:30:00.123987", "America/New_York")).toISOString(), + "2026-11-01T05:30:00.123Z", + ); assert.equal( calendarInstantToDate( calendarDateToInstant("2026-03-08T15:30:00+13:00", "UTC"), diff --git a/test/mdbase.test.mjs b/test/mdbase.test.mjs index 3d96b39..e460393 100644 --- a/test/mdbase.test.mjs +++ b/test/mdbase.test.mjs @@ -7,13 +7,16 @@ import { buildTaskNotesMdbaseTypePack, patchTaskNotesMdbaseTypeSettings, resolveTaskNotesModelConfigFromMdbaseType, + TASKNOTES_LEGACY_CONTRACT_DIGESTS, + TASKNOTES_LEGACY_CONTRACT_VERSIONS, TASKNOTES_MDBASE_PACK_VERSION, + TASKNOTES_MDBASE_TYPE_VERSION, } from "../dist/esm/mdbase.js"; function implementation(type) { return type.implements.find( (entry) => - entry.contract === "tasknotes.task" && entry.version === "0.3.0-rc.6" + entry.contract === "tasknotes.task" && entry.version === "0.3.0-rc.7" ); } @@ -31,15 +34,17 @@ test("builds one canonical TaskNotes and mdbase collection contract", () => { assert.equal(resources.config.spec_version, "0.3.0"); assert.equal(resources.config.settings.types_folder, "_mdbase/types"); assert.equal(resources.config.settings.contracts_folder, "_mdbase/contracts"); - assert.equal(resources.paths.contract, "_mdbase/contracts/tasknotes.task/0.3.0-rc.6.md"); + assert.equal(resources.paths.contract, "_mdbase/contracts/tasknotes.task/0.3.0-rc.7.md"); assert.equal(resources.paths.type, "_mdbase/types/task.md"); assert.equal(resources.paths.taskSchema, "_mdbase/_schemas/tasknotes/tasknotes-task.schema.json"); assert.equal(resources.contract.id, "tasknotes.task"); assert.equal(resources.contract.contract_type, "record"); - assert.equal(resources.contract.version, "0.3.0-rc.6"); + assert.equal(resources.contract.version, "0.3.0-rc.7"); assert.ok(resources.contract.record_schema); assert.equal(taskImplementation.contract, "tasknotes.task"); - assert.equal(taskImplementation.version, "0.3.0-rc.6"); + assert.equal(taskImplementation.version, "0.3.0-rc.7"); + assert.equal(type.version, TASKNOTES_MDBASE_TYPE_VERSION); + assert.equal(TASKNOTES_MDBASE_TYPE_VERSION, 6); assert.deepEqual(extension.profiles, [ "core-lite", "recurrence", @@ -71,24 +76,22 @@ test("builds one canonical TaskNotes and mdbase collection contract", () => { assert.deepEqual(type.collection.links["attachments[]"], { validate_exists: false, }); - const taskDateSchema = { - anyOf: [ - { type: "string", format: "date" }, - { type: "string", format: "date-time" }, - ], - }; - assert.deepEqual(schema.properties.due, schema.properties.scheduled); - assert.deepEqual(schema.properties.due.anyOf.slice(0, 2), taskDateSchema.anyOf); - const localTime = new RegExp(schema.properties.due.anyOf[2].pattern); - assert.match("2026-11-30T16:00", localTime); - assert.match("2026-11-30T16:00:59", localTime); - assert.doesNotMatch("2026-11-30T25:00", localTime); - assert.deepEqual(resources.taskSchema.properties.due, taskDateSchema); - assert.deepEqual(resources.taskSchema.properties.scheduled, taskDateSchema); + const instant = { type: "string", format: "date-time" }; + const floating = { type: "string", format: "local-date-time" }; + const taskDateSchema = { anyOf: [{ type: "string", format: "date" }, instant, floating] }; + const taskTimestampSchema = { anyOf: [instant, floating] }; + for (const { properties } of [schema, resources.taskSchema]) { + assert.deepEqual(properties.due, taskDateSchema); + assert.deepEqual(properties.scheduled, taskDateSchema); + assert.deepEqual(properties.dateCreated, taskTimestampSchema); + assert.deepEqual(properties.dateModified, taskTimestampSchema); + } + assert.deepEqual(schema.properties.timeEntries.items.properties.startTime, instant); + assert.deepEqual(schema.properties.timeEntries.items.properties.endTime, instant); + assert.deepEqual(schema.properties.reminders.items.oneOf[0].properties.absoluteTime, instant); assert.deepEqual(type.collection.unique, [{ field: "id", scope: "type" }]); assert.deepEqual(type.lifecycle.on_create.set.id, { uuid: true }); assert.deepEqual(schema.properties.completedDate, { type: "string", format: "date" }); - assert.deepEqual(schema.properties.dateModified, { type: "string", format: "date-time" }); assert.deepEqual(YAML.parse(resources.configDocument), resources.config); assert.deepEqual(JSON.parse(resources.taskSchemaDocument), resources.taskSchema); assert.deepEqual( @@ -132,7 +135,7 @@ test("packages the contract, implementation, and schemas as one digest-pinned ty const pack = await buildTaskNotesMdbaseTypePack(resources); assert.deepEqual(pack.provides.map(({ id, version }) => [id, version]), [ - ["tasknotes.task", "0.3.0-rc.6"], + ["tasknotes.task", "0.3.0-rc.7"], ["tasknotes.settings", "1.1.0"], ["mdbase.app-settings", "2.0.0"], ]); @@ -140,15 +143,18 @@ test("packages the contract, implementation, and schemas as one digest-pinned ty assert.equal(pack.manifest.kind, "mdbase.type-pack"); assert.equal(pack.manifest.id, "tasknotes.task"); assert.equal(pack.manifest.version, TASKNOTES_MDBASE_PACK_VERSION); - assert.equal(TASKNOTES_MDBASE_PACK_VERSION, "0.3.0-rc.22"); - assert.equal(pack.manifest.resources.length, 14); + assert.equal(TASKNOTES_MDBASE_PACK_VERSION, "0.3.0-rc.23"); + assert.equal(pack.manifest.resources.length, 15); + assert.ok(TASKNOTES_LEGACY_CONTRACT_VERSIONS.includes("0.3.0-rc.6")); + assert.equal(TASKNOTES_LEGACY_CONTRACT_DIGESTS["0.3.0-rc.6"], "sha256:c400ead6e218b715d86ad31125bb3d4b2e276817da6ba8065449fd0947b24d67"); + assert.ok(pack.manifest.resources.some(({ source }) => source === "contracts/tasknotes.task/0.3.0-rc.6.md")); assert.deepEqual( pack.manifest.resources.filter(({ source }) => [ - "contracts/tasknotes.task/0.3.0-rc.6.md", "types/tasknotes-task/7.md", - "schemas/tasknotes.task/0.3.0-rc.6.schema.json", "schemas/tasknotes.task.binding/0.3.0-rc.6.schema.json", + "contracts/tasknotes.task/0.3.0-rc.7.md", "types/tasknotes-task/8.md", + "schemas/tasknotes.task/0.3.0-rc.7.schema.json", "schemas/tasknotes.task.binding/0.3.0-rc.7.schema.json", ].includes(source)).map(({ kind, mode, target }) => [kind, mode, target]), [ - ["contract", "managed", "_mdbase/contracts/tasknotes.task/0.3.0-rc.6.md"], + ["contract", "managed", "_mdbase/contracts/tasknotes.task/0.3.0-rc.7.md"], ["type", "seed", "_mdbase/types/action.md"], ["schema", "managed", "_mdbase/_schemas/tasknotes/tasknotes-task.schema.json"], [ diff --git a/test/model.test.mjs b/test/model.test.mjs index dd906c6..9c9865d 100644 --- a/test/model.test.mjs +++ b/test/model.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { DEFAULT_FIELD_MAPPING, + DEFAULT_STATUSES, buildMaterializeOccurrencePlan, buildMaterializedOccurrenceCompletePlan, buildMaterializedOccurrenceUncompletePlan, @@ -15,6 +16,7 @@ import { canonicalAttachmentReference, calculateTotalTrackedMinutes, executeConformanceOperation, + evaluateCoreValidation, formatDateForStorage, getDatePart, mapTaskFromFrontmatter, @@ -23,9 +25,11 @@ import { parseDateToUTC, parseTaskDocument, recalculateRecurringSchedule, + resolveDateTimeRangeBound, serializeTaskDocument, validateAttachmentReferences, validateTask, + validateTimeEntries, } from "../dist/esm/index.js"; test("maps TaskNotes frontmatter to normalized task data", () => { @@ -159,6 +163,48 @@ test("parses dates with UTC storage semantics", () => { assert.throws(() => parseDateToUTC("2026-02-30"), /Invalid date/); }); +test("parses floating minutes and fractional seconds without relaxing offset syntax", () => { + assert.equal(parseDateToUTC("2026-11-01T01:30", "America/New_York").toISOString(), "2026-11-01T05:30:00.000Z"); + assert.equal(parseDateToUTC("2026-11-01T01:30:00.123987Z").toISOString(), "2026-11-01T01:30:00.123Z"); + assert.equal(resolveDateTimeRangeBound("2026-11-01 01:30:00.123987Z", "from").toISOString(), "2026-11-01T01:30:00.123Z"); + assert.throws(() => parseDateToUTC("2026-11-01T01:30Z"), /Invalid date/); + assert.throws(() => parseDateToUTC("2026-11-01T24:00"), /Invalid date/); +}); + +test("orders floating timestamps in the supplied collection timezone", () => { + const task = { + title: "Mixed timestamps", + status: "open", + priority: "normal", + path: "Tasks/mixed.md", + archived: false, + dateCreated: "2026-11-01T01:30:00.123987", + dateModified: "2026-11-01T05:45:00Z", + }; + const timezone = "America/New_York"; + assert.equal(evaluateCoreValidation(task, DEFAULT_STATUSES, timezone).valid, true); + assert.deepEqual( + evaluateCoreValidation(task, DEFAULT_STATUSES, "America/Los_Angeles").issues.map(({ code }) => code), + ["date_modified_before_created"], + ); + + const entries = [{ startTime: task.dateCreated, endTime: task.dateModified }]; + assert.equal(validateTimeEntries(entries, timezone).valid, true); + assert.equal(validateTimeEntries(entries, "America/Los_Angeles").valid, false); + assert.equal(calculateTotalTrackedMinutes(entries, timezone), 15); + assert.equal(calculateTotalTrackedMinutes(entries, "America/Los_Angeles"), 0); + + const plan = buildTaskUpdatePlan({ + originalTask: task, + updates: { title: "Edited" }, + fieldMapping: DEFAULT_FIELD_MAPPING, + now: "2026-11-01T05:40:00Z", + timezone: "America/Los_Angeles", + }); + assert.equal(plan.updatedTask.dateCreated, task.dateCreated); + assert.equal(plan.dateModified, "2026-11-01T08:30:00.124Z"); +}); + test("keeps modification timestamps valid when a device clock moves backwards", () => { const plan = buildTaskUpdatePlan({ originalTask: { diff --git a/test/settings.test.mjs b/test/settings.test.mjs index 886cc93..5377831 100644 --- a/test/settings.test.mjs +++ b/test/settings.test.mjs @@ -111,7 +111,7 @@ test("upgrades an rc.5 type by moving its settings out of the binding", () => { const { type: upgraded, appSettings, upgraded: changed } = upgradeTaskNotesMdbaseTypeContract(type); const binding = upgraded.implements[0].binding; assert.equal(changed, true); - assert.equal(upgraded.implements[0].version, "0.3.0-rc.6"); + assert.equal(upgraded.implements[0].version, "0.3.0-rc.7"); assert.equal(binding.templating, undefined); assert.equal(binding.time_tracking, undefined); assert.equal(binding.nlp, undefined); diff --git a/test/starter.test.mjs b/test/starter.test.mjs index b7d0ff5..a481057 100644 --- a/test/starter.test.mjs +++ b/test/starter.test.mjs @@ -4,22 +4,24 @@ import test from "node:test"; import { buildTaskNotesMdbaseResources, buildTaskNotesMdbaseTypePack } from "../dist/esm/mdbase.js"; import { buildTaskNotesStarterResources, + TASKNOTES_STARTER_REVISION, TASKNOTES_STARTER_TYPE_VERSION, } from "../dist/esm/starter.js"; -// The tasknotes.task 0.3.0-rc.22 pack, vendored from the mdbase-contracts +// The tasknotes.task 0.3.0-rc.23 pack, vendored from the mdbase-contracts // dist/ in src/generated/tasknotes-type-pack.json. If the // starter changes, publish a new starter revision in mdbase-contracts and // update these digests together; collections upgrade by merging against the // previous starter, so an unintended change here reaches every collection. -const PUBLISHED_RC22_RESOURCES = { +const PUBLISHED_RC23_RESOURCES = { "_mdbase/contracts/tasknotes.task.md": "sha256:ecadd00700e249940f4244aaa5b5985a96557d13340463ec491dfa5e89b032a4", "_mdbase/contracts/tasknotes.task/0.3.0-rc.4.md": "sha256:91165b7664f936bba9289aca984e2638901db7fedf68642ab755e8d0b424e734", "_mdbase/contracts/tasknotes.task/0.3.0-rc.3.md": "sha256:4761ee78615882170cae6e52590f98917f549bd89d852a0c40568583394d7264", "_mdbase/contracts/tasknotes.task/0.3.0-rc.6.md": "sha256:3f4eb90782948ed68112ffcc99575911036020544cf501de3d2265b588b38456", - "_mdbase/types/task.md": "sha256:83bfd806bfbda7b99f1eb057b26cf6e0fbc1db6958a0ed3e610f0b20ff9b7aef", - "_mdbase/_schemas/tasknotes/tasknotes-task.schema.json": "sha256:ac78a55f46669d6e8bd08d608b7c25338fec8ba7606dbf54ebd6b8d4e66b7035", - "_mdbase/_schemas/tasknotes/tasknotes-task-binding.schema.json": "sha256:4f8f3288f593ce06a04525697308173147ff957e7066f83d9a922468d06be659", + "_mdbase/contracts/tasknotes.task/0.3.0-rc.7.md": "sha256:1e78767a7d24d5e2a6e8279879b619450a3750677f523804be61ddc4e1a88824", + "_mdbase/types/task.md": "sha256:2c2ce46f74e1058556095753dcc7784ba5dd4c997cb6a0791643fbb51e76f3d0", + "_mdbase/_schemas/tasknotes/tasknotes-task.schema.json": "sha256:c496ec537805d0a265923e8f748e2a4c7ec88fc531fa1d771943ba84b4a5598b", + "_mdbase/_schemas/tasknotes/tasknotes-task-binding.schema.json": "sha256:e4eb60d768b4de3511b897002706c91a7d852d0b031a801772eef5a819e1bb24", "_mdbase/schemas/mdbase.app-settings/1.0.0.schema.json": "sha256:f37ed43b57fe86465b5bb67216da71d6e351bc1b85bf55a20f95edf886f0749e", "_mdbase/contracts/mdbase.app-settings/1.0.0.md": "sha256:9028d8ccd99cfbb4034399777376315486eb8e699aea7757a6b193743f1084c8", "_mdbase/schemas/tasknotes.settings/1.0.0.schema.json": "sha256:3a4fc207e14ab1579ca478ce84b25cb8dd85b804b3aa79d01eda08e4554dfbb1", @@ -31,10 +33,10 @@ const PUBLISHED_RC22_RESOURCES = { test("the starter reproduces the published TaskNotes pack resource bytes", async () => { const pack = await buildTaskNotesMdbaseTypePack(buildTaskNotesStarterResources()); - assert.equal(pack.manifest.version, "0.3.0-rc.22"); + assert.equal(pack.manifest.version, "0.3.0-rc.23"); assert.deepEqual( Object.fromEntries(pack.manifest.resources.map((resource) => [resource.target, resource.digest])), - PUBLISHED_RC22_RESOURCES, + PUBLISHED_RC23_RESOURCES, ); }); @@ -50,6 +52,7 @@ test("the starter keeps cancelled as a skipped status and declares only implemen const { type } = buildTaskNotesStarterResources(); const binding = type.implements.find((entry) => entry.contract === "tasknotes.task").binding; assert.equal(type.version, TASKNOTES_STARTER_TYPE_VERSION); + assert.equal(TASKNOTES_STARTER_REVISION, 8); assert.ok(type.schema.value.properties.status.enum.includes("cancelled")); assert.deepEqual(binding.status.skipped_values, ["cancelled"]); assert.equal(binding.status.default_skipped, "cancelled");