diff --git a/docs/javascript-api.md b/docs/javascript-api.md index 0b5baa7bb..b8e975fc2 100644 --- a/docs/javascript-api.md +++ b/docs/javascript-api.md @@ -203,7 +203,7 @@ const operators = api.catalog.filterOperators(); ## Tasks All paths are vault-relative Markdown file paths. New tasks created or converted by TaskNotes v5 -receive a UUID in the standard `id` frontmatter field. That ID remains unchanged when a task file +receive a UUID in the `id` frontmatter field (or the property key configured for **Task ID**). That ID remains unchanged when a task file moves or is renamed, while `path` continues to identify the task's current location. Existing tasks without an ID remain valid and are not migrated automatically. diff --git a/docs/migration-v4-to-v5.md b/docs/migration-v4-to-v5.md index 60780dab4..b388863ad 100644 --- a/docs/migration-v4-to-v5.md +++ b/docs/migration-v4-to-v5.md @@ -76,7 +76,7 @@ Values saved for these settings stay in `data.json`, so devices still on 4.x kee ## Stable task IDs -New and converted tasks receive a UUID in the `id` frontmatter property. The ID stays the same when a task file is renamed or moved, so integrations can refer to a task without depending on its path. +New and converted tasks receive a UUID in the `id` frontmatter property. The property key can be changed under **Settings → TaskNotes → Properties → Metadata & integration properties → Task ID**. The ID stays the same when a task file is renamed or moved, so integrations can refer to a task without depending on its path. Existing tasks without an `id` remain valid and are not changed. Path-based integrations continue to work. The JavaScript API adds `getByPath()` and `getById()`; see [JavaScript API](javascript-api.md). diff --git a/docs/releases/unreleased.md b/docs/releases/unreleased.md index 5588ec348..6ac247acf 100644 --- a/docs/releases/unreleased.md +++ b/docs/releases/unreleased.md @@ -40,6 +40,8 @@ When a change has user-facing documentation, include a canonical tasknotes.dev l - (#2615) Added **Hide top-level subtasks** to the Calendar view's list (Agenda) layout and the month view's selected day panel, as in Task List and Kanban. When on, a subtask whose parent task is listed on the same day shows only under the parent's expanded subtasks instead of also as its own row. A subtask whose parent isn't listed that day keeps its own row. See [Agenda View](https://tasknotes.dev/views/agenda-view/#customization). - Thanks to @tistieom for the request +- (#2574) The task ID property can now be remapped like other task properties, under **Settings → TaskNotes → Properties → Metadata & integration properties → Task ID**. It defaults to `id`, so existing vaults are unchanged. When a collection's task type maps the ID to another property, TaskNotes uses that property. See [Task Properties](https://tasknotes.dev/settings/task-properties/#metadata-properties). + - Thanks to @minchinweb for the request ## Changed diff --git a/docs/settings/task-properties.md b/docs/settings/task-properties.md index 80142b443..aa3381ebd 100644 --- a/docs/settings/task-properties.md +++ b/docs/settings/task-properties.md @@ -213,6 +213,7 @@ Each default reminder can be: These properties are system-managed and typically only require property key configuration: +- **Task ID**: The task's stable ID (default: `id`). Change it if your notes already use `id` for something else, for example `tasknote_id`. Existing notes keep their IDs under the old key until you rename it in them. - **Date Created**: When the task was created - **Date Modified**: When the task was last modified - **Completed Date**: When the task was completed diff --git a/e2e/issues/issue-2574-remappable-id.spec.ts b/e2e/issues/issue-2574-remappable-id.spec.ts new file mode 100644 index 000000000..e8db2eb55 --- /dev/null +++ b/e2e/issues/issue-2574-remappable-id.spec.ts @@ -0,0 +1,75 @@ +/** + * Issue #2574: the stable task ID property can be remapped like other fields. + * + * Remaps `id` to `tasknote_id`, then checks the settings page, a newly + * created task and ID lookup. (The e2e vault has no mdbase collection; the + * generated task type is covered by unit tests.) The mapping is restored and + * the created task deleted afterwards. + * + * @see https://github.com/callumalpass/tasknotes/issues/2574 + */ + +import { test, expect } from '@playwright/test'; +import { launchObsidian, closeObsidian, ObsidianApp, openTaskNotesSettings } from '../obsidian'; + +let app: ObsidianApp; + +test.describe('Issue #2574: remappable task ID', () => { + test.beforeAll(async () => { + app = await launchObsidian(); + }); + + test.afterAll(async () => { + if (app) { + await app.page.evaluate(async () => { + const plugin = (window as any).app.plugins.plugins.tasknotes; + if (plugin.settings.fieldMapping.id !== 'id') { + plugin.settings.fieldMapping.id = 'id'; + await plugin.saveSettings(); + } + }); + await closeObsidian(app); + } + }); + + test('writes and reads the ID under the mapped property', async () => { + const page = app.page; + + expect( + await page.evaluate(() => (window as any).app.plugins.plugins.tasknotes.settings.fieldMapping.id) + ).toBe('id'); + + await page.evaluate(async () => { + const plugin = (window as any).app.plugins.plugins.tasknotes; + plugin.settings.fieldMapping.id = 'tasknote_id'; + await plugin.saveSettings(); + }); + + const result = await page.evaluate(async () => { + const obsidian = (window as any).app; + const plugin = obsidian.plugins.plugins.tasknotes; + const { file, taskInfo } = await plugin.taskService.createTask( + { title: 'Issue 2574 remapped id' }, + { applyDefaults: false } + ); + const content: string = await obsidian.vault.read(file); + let byId: string[] = []; + for (let attempt = 0; attempt < 20 && byId.length === 0; attempt++) { + byId = (await plugin.cacheManager.getTasksById(taskInfo.id)).map((task: any) => task.path); + if (byId.length === 0) await new Promise((resolve) => setTimeout(resolve, 100)); + } + await obsidian.vault.delete(file); + return { id: taskInfo.id as string, path: file.path as string, content, byId }; + }); + + expect(result.id).toMatch(/^[0-9a-f-]{36}$/); + expect(result.content).toContain(`tasknote_id: ${result.id}`); + expect(result.content).not.toMatch(/^id:/m); + expect(result.byId).toEqual([result.path]); + + const settings = await openTaskNotesSettings(page, 'Properties/Metadata & integration properties'); + await expect( + settings.locator('.vertical-tab-content:visible').getByText('Task ID', { exact: true }) + ).toBeVisible(); + }); +}); diff --git a/package-lock.json b/package-lock.json index b5a8d9eb4..50555b29f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,7 @@ "@modelcontextprotocol/sdk": "1.32.1", "@tasknotes/calendar": "0.1.12", "@tasknotes/calendar-service-client": "0.1.2", - "@tasknotes/model": "0.3.0-rc.22", + "@tasknotes/model": "0.3.1", "ajv": "8.20.0", "ajv-formats": "3.0.1", "chrono-node": "^2.7.5", @@ -5120,9 +5120,9 @@ } }, "node_modules/@tasknotes/model": { - "version": "0.3.0-rc.22", - "resolved": "https://registry.npmjs.org/@tasknotes/model/-/model-0.3.0-rc.22.tgz", - "integrity": "sha512-V7zlNwnMJ8OAxnB73Lwqz+/pSc6/gB/788Sk062nfJXxuLMaQOePUytzSF2WG2DREGghVwv7pEVmf+4Kk+EgEQ==", + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@tasknotes/model/-/model-0.3.1.tgz", + "integrity": "sha512-LEFpiTO4o37Z83JqzfvsI5GSjgOVYKyjIrIjiJylVk/bcQJgoUp/NgN+EsvOPNlxSqJRJk2QQHjf9gW7/MeNhA==", "license": "MIT", "dependencies": { "rrule": "^2.8.1", diff --git a/package.json b/package.json index 6e2a542e4..71c5a077f 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "@modelcontextprotocol/sdk": "1.32.1", "@tasknotes/calendar": "0.1.12", "@tasknotes/calendar-service-client": "0.1.2", - "@tasknotes/model": "0.3.0-rc.22", + "@tasknotes/model": "0.3.1", "ajv": "8.20.0", "ajv-formats": "3.0.1", "chrono-node": "^2.7.5", diff --git a/src/api/TaskNotesAPI.ts b/src/api/TaskNotesAPI.ts index 8802962a4..d43567f95 100644 --- a/src/api/TaskNotesAPI.ts +++ b/src/api/TaskNotesAPI.ts @@ -35,6 +35,8 @@ import { FILTER_PROPERTIES, } from "../types"; import type { TaskNotesSettings } from "../types/settings"; +import { DEFAULT_FIELD_MAPPING } from "../core/defaultFieldMapping"; +import { toUserField } from "../core/fieldMapping"; import { ensureFolderExists } from "../utils/helpers"; import { parseLinkToPath } from "../utils/linkUtils"; import { computeTaskTimeData, computeTimeSummary } from "../utils/timeTrackingUtils"; @@ -353,6 +355,7 @@ const CORE_FIELD_DEFINITIONS: ReadonlyArray< const FIELD_MAPPING_KEY_BY_FIELD_ID: Partial< Record > = { + id: "id", title: "title", status: "status", priority: "priority", @@ -1062,14 +1065,15 @@ export class TaskNotesAPI implements TaskNotesRuntimeApiV1 { } private getFieldDefinitions(): TaskNotesRuntimeFieldDefinition[] { - const mapping = this.plugin.settings.fieldMapping ?? {}; + const mapping = this.plugin.settings.fieldMapping ?? DEFAULT_FIELD_MAPPING; const coreFields = CORE_FIELD_DEFINITIONS.map((field) => { const mappingKey = FIELD_MAPPING_KEY_BY_FIELD_ID[field.id]; const queryField = runtimeFilterPropertyForInternal(field.id); return { ...field, - frontmatterKey: - field.id === "id" ? "id" : mappingKey ? mapping[mappingKey] : undefined, + frontmatterKey: mappingKey + ? toUserField(mapping, mappingKey) + : undefined, queryable: !!queryField, sortable: queryField?.sortable ?? false, groupable: queryField?.groupable ?? false, diff --git a/src/core/defaultFieldMapping.ts b/src/core/defaultFieldMapping.ts index 8a0dd0fb2..b3817f1c7 100644 --- a/src/core/defaultFieldMapping.ts +++ b/src/core/defaultFieldMapping.ts @@ -4,7 +4,11 @@ import type { FieldMapping } from "../types"; /** Default frontmatter property for a pending moved recurring occurrence's original rule date. */ export const DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY = "recurrence_original_date"; +/** Default frontmatter property for a task's stable identity. */ +export const DEFAULT_ID_PROPERTY = "id"; + export const DEFAULT_FIELD_MAPPING: FieldMapping = { ...MODEL_DEFAULT_FIELD_MAPPING, + id: DEFAULT_ID_PROPERTY, recurrenceOriginalDate: DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY, }; diff --git a/src/core/fieldMapping.ts b/src/core/fieldMapping.ts index 2fc19541d..f2d3f33c7 100644 --- a/src/core/fieldMapping.ts +++ b/src/core/fieldMapping.ts @@ -28,7 +28,7 @@ import type { TaskInfo, } from "../types"; import type { UserMappedField } from "../types/settings"; -import { DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY } from "./defaultFieldMapping"; +import { DEFAULT_ID_PROPERTY, DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY } from "./defaultFieldMapping"; import { normalizeStringArrayValue } from "./nullableListNormalization"; export { @@ -47,17 +47,23 @@ export { VALID_DEPENDENCY_RELTYPES, }; -// The shared model mapping does not know about `recurrenceOriginalDate`, and settings saved -// before the field existed do not contain it. These wrappers resolve the property name -// (falling back to the default) and handle the field around the model functions. +// Settings saved before `id` and `recurrenceOriginalDate` were mappable do not contain +// them. These wrappers resolve both property names (falling back to the defaults) and +// handle `recurrenceOriginalDate` around the model functions. -type ResolvedFieldMapping = FieldMapping & { recurrenceOriginalDate: string }; +type ResolvedFieldMapping = FieldMapping & { id: string; recurrenceOriginalDate: string }; function withResolvedMapping(mapping: FieldMapping): ResolvedFieldMapping { - if (typeof mapping.recurrenceOriginalDate === "string") { + const hasId = typeof mapping.id === "string" && mapping.id.trim().length > 0; + if (hasId && typeof mapping.recurrenceOriginalDate === "string") { return mapping as ResolvedFieldMapping; } - return { ...mapping, recurrenceOriginalDate: DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY }; + return { + ...mapping, + id: hasId ? (mapping.id as string) : DEFAULT_ID_PROPERTY, + recurrenceOriginalDate: + mapping.recurrenceOriginalDate ?? DEFAULT_RECURRENCE_ORIGINAL_DATE_PROPERTY, + }; } /** diff --git a/src/i18n/locales/de/messages.po b/src/i18n/locales/de/messages.po index f893923f4..bfe4f11c4 100644 --- a/src/i18n/locales/de/messages.po +++ b/src/i18n/locales/de/messages.po @@ -11307,6 +11307,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "Die Aufgabe hat weder ein Planungs- noch ein Fälligkeitsdatum für die Synchronisierung" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "Aufgaben-ID" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/en/messages.po b/src/i18n/locales/en/messages.po index c4bbd839f..07ad78124 100644 --- a/src/i18n/locales/en/messages.po +++ b/src/i18n/locales/en/messages.po @@ -11309,6 +11309,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "Task has no scheduled or due date to sync" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "Task ID" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/es/messages.po b/src/i18n/locales/es/messages.po index 821aaf34e..d16348cff 100644 --- a/src/i18n/locales/es/messages.po +++ b/src/i18n/locales/es/messages.po @@ -11309,6 +11309,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "La tarea no tiene fecha programada o de vencimiento para sincronizar" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "ID de la tarea" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/fr/messages.po b/src/i18n/locales/fr/messages.po index 926eb9602..f0eebe4c3 100644 --- a/src/i18n/locales/fr/messages.po +++ b/src/i18n/locales/fr/messages.po @@ -11309,6 +11309,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "La tâche n''a pas de date planifiée ou d''échéance à synchroniser" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "ID de la tâche" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/it/messages.po b/src/i18n/locales/it/messages.po index a395a83d8..42e7c1b50 100644 --- a/src/i18n/locales/it/messages.po +++ b/src/i18n/locales/it/messages.po @@ -11309,6 +11309,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "L'attività non ha una data pianificata o una data di scadenza per la sincronizzazione" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "ID attività" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/ja/messages.po b/src/i18n/locales/ja/messages.po index 9b32a4fbc..452ce4b0e 100644 --- a/src/i18n/locales/ja/messages.po +++ b/src/i18n/locales/ja/messages.po @@ -11308,6 +11308,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "タスクに同期する予定日または期限がありません" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "タスクID" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/ko/messages.po b/src/i18n/locales/ko/messages.po index 3cd86e8f9..82b6298f5 100644 --- a/src/i18n/locales/ko/messages.po +++ b/src/i18n/locales/ko/messages.po @@ -11308,6 +11308,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "동기화할 예정일 또는 마감일이 없습니다" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "작업 ID" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/pt/messages.po b/src/i18n/locales/pt/messages.po index 3bb1b0bf4..f5701ffbc 100644 --- a/src/i18n/locales/pt/messages.po +++ b/src/i18n/locales/pt/messages.po @@ -11310,6 +11310,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "Tarefa não tem data agendada ou de vencimento para sincronizar" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "ID da tarefa" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/ru/messages.po b/src/i18n/locales/ru/messages.po index ab9791ea0..cfca72947 100644 --- a/src/i18n/locales/ru/messages.po +++ b/src/i18n/locales/ru/messages.po @@ -11309,6 +11309,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "У задачи нет запланированной даты или срока для синхронизации" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "ID задачи" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/i18n/locales/zh/messages.po b/src/i18n/locales/zh/messages.po index 63d6248f6..93d554acb 100644 --- a/src/i18n/locales/zh/messages.po +++ b/src/i18n/locales/zh/messages.po @@ -11306,6 +11306,11 @@ msgctxt "settings.integrations.googleCalendarExport.notices.noDateToSync" msgid "Task has no scheduled or due date to sync" msgstr "任务没有可同步的计划日期或截止日期" +#: src/settings/native/properties.ts +msgctxt "settings.taskProperties.properties.id.name" +msgid "Task ID" +msgstr "任务 ID" + #: src/settings/native/general.ts msgctxt "settings.general.taskIdentification.header" msgid "Task identification" diff --git a/src/services/mdbase/preserveCanonical.ts b/src/services/mdbase/preserveCanonical.ts index 1bfa1b8f0..2fe73f539 100644 --- a/src/services/mdbase/preserveCanonical.ts +++ b/src/services/mdbase/preserveCanonical.ts @@ -101,37 +101,43 @@ export function preserveUnownedCanonicalSettings(existing: ObjectValue, generate } const fields = { ...object(previous.fields), ...object(next.fields) }; Object.assign(next, { ...previous, version: next.version, fields, binding }); - // Stable IDs are not a plugin field-mapping setting. Keep its schema and lifecycle. - const idField = object(previous.fields).id; + // The ID property follows the field mapping. A type that never had a stable + // ID keeps none, and an existing ID generator is kept (under the new name + // when the mapping renames the property). + const previousIdField = object(previous.fields).id; + const idField = object(next.fields).id; const collection = object(desired.collection); - if (object(existing.collection).unique !== undefined) collection.unique = copy(object(existing.collection).unique); - else delete collection.unique; - if (typeof idField === "string") { + const existingUnique = object(existing.collection).unique; + if (existingUnique !== undefined) { + const unique = copy(existingUnique); + if (Array.isArray(unique) && typeof previousIdField === "string" && typeof idField === "string") { + for (const rule of unique.map(object)) if (rule.field === previousIdField) rule.field = idField; + } + collection.unique = unique; + } else delete collection.unique; + const createSet = object(object(object(desired.lifecycle).on_create).set); + const previousSet = object(object(object(existing.lifecycle).on_create).set); + const properties = object(object(object(desired.schema).value).properties); + if (typeof previousIdField === "string" && typeof idField === "string") { fields.id = idField; - const createSet = object(object(object(desired.lifecycle).on_create).set); - delete createSet.id; - const previousSet = object(object(object(existing.lifecycle).on_create).set); - if (previousSet[idField]) createSet[idField] = copy(previousSet[idField]); - if (idField !== "id") { - delete object(object(object(desired.schema).value).properties).id; - const generator = object(desired["x-tasknotes-generator"]); - generator.managed_fields = [...(generator.managed_fields as string[]).filter((field) => field !== "id"), idField]; + delete createSet[idField]; + if (previousSet[previousIdField] !== undefined) createSet[idField] = copy(previousSet[previousIdField]); + if (idField !== previousIdField) { + const previousIdProperty = object(object(object(existing.schema).value).properties)[previousIdField]; + if (previousIdProperty !== undefined) properties[idField] = copy(previousIdProperty); } - } - if (idField === undefined) { + } else if (previousIdField === undefined) { delete fields.id; - const properties = object(object(object(desired.schema).value).properties); - const previousId = object(object(object(existing.schema).value).properties).id; - if (previousId !== undefined) properties.id = copy(previousId); - else delete properties.id; - const set = object(object(object(desired.lifecycle).on_create).set); - const previousIdGenerator = object(object(object(existing.lifecycle).on_create).set).id; - if (previousIdGenerator !== undefined) set.id = copy(previousIdGenerator); - else delete set.id; + if (typeof idField === "string") { + const previousId = object(object(object(existing.schema).value).properties)[idField]; + if (previousId !== undefined) properties[idField] = copy(previousId); + else delete properties[idField]; + if (previousSet[idField] !== undefined) createSet[idField] = copy(previousSet[idField]); + else delete createSet[idField]; + } } if (object(previous.fields).tags === undefined) delete fields.tags; // Do not replace custom constraints with model defaults on retained properties. - const properties = object(object(object(desired.schema).value).properties); const previousProperties = object(object(object(existing.schema).value).properties); for (const [field, definition] of Object.entries(properties)) { const prior = previousProperties[field]; diff --git a/src/services/mdbase/resolveUserFields.ts b/src/services/mdbase/resolveUserFields.ts index 62cabb8b8..de8618bd1 100644 --- a/src/services/mdbase/resolveUserFields.ts +++ b/src/services/mdbase/resolveUserFields.ts @@ -35,7 +35,8 @@ export function resolveRetainedUserFields( const properties = object(object(object(type.schema).value).properties); const generator = object(type["x-tasknotes-generator"]); const managed = new Set(Array.isArray(generator.managed_fields) ? generator.managed_fields : []); - const reserved = new Set([...reservedFields, "id", "tags"]); + // reservedFields includes the mapped ID property, so a plain `id` is a user field once ID is remapped. + const reserved = new Set([...reservedFields, "tags"]); const fields = new Map(resolved.map((field) => [field.key, field])); for (const [key, schema] of Object.entries(properties)) { if (reserved.has(key) || fields.has(key)) continue; diff --git a/src/services/mdbaseCanonicalConfig.ts b/src/services/mdbaseCanonicalConfig.ts index e3cb366aa..f053d7f8d 100644 --- a/src/services/mdbaseCanonicalConfig.ts +++ b/src/services/mdbaseCanonicalConfig.ts @@ -435,6 +435,9 @@ export function mergeCanonicalTaskTypeDocument( throw new Error("The existing mdbase type frontmatter must be an object."); } + const previousIdField = asRecord( + existingImplementationsFor(existingValue).find((entry) => entry.contract === "tasknotes.task")?.fields + )?.id; const desired = preserveUnownedCanonicalSettings(existingValue, generated.type); const existingImplementations = Array.isArray(existingValue.implements) ? existingValue.implements.filter(isRecord) @@ -450,6 +453,10 @@ export function mergeCanonicalTaskTypeDocument( document.setIn(["implements"], mergedImplementations); deleteStaleManagedFields(document, existingValue, desired); + // A renamed ID property keeps one generator: the one preserved under the new name. + if (typeof previousIdField === "string" && previousIdField !== asRecord(desiredImplementation.fields)?.id) { + document.deleteIn(["lifecycle", "on_create", "set", previousIdField]); + } for (const path of MANAGED_OPTIONAL_PATHS) { if (!hasPath(desired, path)) { document.deleteIn(path); @@ -522,6 +529,10 @@ function validateUniqueStrings(values: string[], label: string, issues: string[] } } +function existingImplementationsFor(type: UnknownRecord): UnknownRecord[] { + return Array.isArray(type.implements) ? type.implements.filter(isRecord) : []; +} + function deleteStaleManagedFields( document: YAML.Document, existing: UnknownRecord, diff --git a/src/services/task-service/TaskCreationService.ts b/src/services/task-service/TaskCreationService.ts index 82db3a8d9..9b5a47bc5 100644 --- a/src/services/task-service/TaskCreationService.ts +++ b/src/services/task-service/TaskCreationService.ts @@ -354,7 +354,7 @@ export class TaskCreationService { } // Identity is assigned by the creation boundary. Templates and ordinary // custom frontmatter must never copy or replace another task's ID. - finalFrontmatter.id = id; + finalFrontmatter[runtime.fieldMapper.toUserField("id")] = id; tagsArray = getFrontmatterTags(finalFrontmatter.tags); const yamlHeader = stringifyYaml(finalFrontmatter); diff --git a/src/services/task-service/taskUpdatePlanning.ts b/src/services/task-service/taskUpdatePlanning.ts index 1792651c1..5d3692f6b 100644 --- a/src/services/task-service/taskUpdatePlanning.ts +++ b/src/services/task-service/taskUpdatePlanning.ts @@ -364,9 +364,10 @@ export function applyTaskUpdateFrontmatterChange({ applyConfiguredPropertyTaskIdentifier(frontmatter, taskIdentification); } + const idField = fieldMapper.toUserField("id"); if (updates.customFrontmatter) { Object.entries(updates.customFrontmatter).forEach(([key, value]) => { - if (key === "id") return; + if (key === idField) return; if (value === null) { delete frontmatter[key]; } else { @@ -375,11 +376,11 @@ export function applyTaskUpdateFrontmatterChange({ }); } - // The shared mapper deliberately leaves the fixed identity field alone. + // The shared mapper deliberately leaves the mapped identity field alone. // Reassert an existing ID so converting a note persists its newly assigned // identity and ordinary edits cannot replace it through a patch/template. if (originalTask.id) { - frontmatter.id = originalTask.id; + frontmatter[idField] = originalTask.id; } removeUnsetMappedFields(frontmatter, { ...updates, ...recurrenceUpdates }, fieldMapper); diff --git a/src/settings/native/properties.ts b/src/settings/native/properties.ts index 1fdda9d4e..9870482d9 100644 --- a/src/settings/native/properties.ts +++ b/src/settings/native/properties.ts @@ -609,6 +609,10 @@ export function propertyDefinitions(ctx: SettingsContext): SettingDefinitionItem recurrence: ctx.t(msg({ message: "Recurrence", context: "settings.taskProperties.properties.recurrence.name" })), reminders: ctx.t(msg({ message: "Reminders", context: "settings.taskProperties.properties.reminders.name" })), }; + // Named here rather than in `labels`, which lists the core properties. + const names: Partial> = { + id: ctx.t(msg({ message: "Task ID", context: "settings.taskProperties.properties.id.name" })), + }; const triggers: Record = { status: "status:", priority: "!", @@ -674,6 +678,7 @@ export function propertyDefinitions(ctx: SettingsContext): SettingDefinitionItem type: "page", name: labels[property] ?? + names[property] ?? property.replace(/([A-Z])/g, " $1").replace(/^./, (char) => char.toUpperCase()), displayValue: () => mapping[property] ?? "", items, diff --git a/src/types.ts b/src/types.ts index fa8783135..56bcd876f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -695,6 +695,7 @@ export type FieldMappingKey = keyof FieldMapping; export type TaskCardPropertyId = string; export interface FieldMapping { + id?: string; // Stable task identity. Optional so settings saved before this field existed keep working; defaults to id title: string; status: string; priority: string; diff --git a/tests/unit/api/tasknotes-api-v1.test.ts b/tests/unit/api/tasknotes-api-v1.test.ts index 3102db728..fa5a8d996 100644 --- a/tests/unit/api/tasknotes-api-v1.test.ts +++ b/tests/unit/api/tasknotes-api-v1.test.ts @@ -639,6 +639,16 @@ describe("TaskNotesApiV1", () => { ); }); + it("reports a remapped ID property in the field catalog (#2574)", () => { + const { plugin } = createPluginContext(); + plugin.settings.fieldMapping = { ...plugin.settings.fieldMapping, id: "tasknote_id" }; + const api = new TaskNotesAPI(plugin); + + expect(api.catalog.fields()).toContainEqual( + expect.objectContaining({ id: "id", frontmatterKey: "tasknote_id" }) + ); + }); + it("exposes catalog metadata for companion plugin editors", () => { const { plugin } = createPluginContext(); const api = new TaskNotesAPI(plugin); diff --git a/tests/unit/issues/issue-2574-remappable-id.test.ts b/tests/unit/issues/issue-2574-remappable-id.test.ts new file mode 100644 index 000000000..fdd0c0872 --- /dev/null +++ b/tests/unit/issues/issue-2574-remappable-id.test.ts @@ -0,0 +1,92 @@ +/** + * Issue #2574: the stable task ID property can be remapped like other fields. + * + * @see https://github.com/callumalpass/tasknotes/issues/2574 + */ + +import { describe, expect, it, jest } from "@jest/globals"; +import { FieldMapper } from "../../../src/core/FieldMapper"; +import { PluginFactory } from "../../helpers/mock-factories"; +import { TaskCreationService } from "../../../src/services/task-service/TaskCreationService"; +import { applyTaskUpdateFrontmatterChange } from "../../../src/services/task-service/taskUpdatePlanning"; +import { DEFAULT_FIELD_MAPPING } from "../../../src/settings/defaults"; +import type { TaskInfo } from "../../../src/types"; + +jest.mock("../../../src/utils/dateUtils", () => ({ + getCurrentTimestamp: jest.fn(() => "2026-11-18T00:00:00+10:00"), +})); + +jest.mock("../../../src/utils/filenameGenerator", () => ({ + generateTaskFilename: jest.fn(() => "remapped-id"), + generateUniqueFilename: jest.fn(() => "remapped-id"), +})); + +jest.mock("../../../src/utils/helpers", () => ({ + ensureFolderExists: jest.fn().mockResolvedValue(undefined), +})); + +jest.mock("../../../src/utils/templateProcessor", () => ({ + mergeTemplateFrontmatter: jest.fn((base: object, template: object) => ({ ...base, ...template })), +})); + +const mapping = { ...DEFAULT_FIELD_MAPPING, id: "tasknote_id" }; + +describe("Issue #2574: remappable task ID", () => { + it("defaults to id", () => { + expect(DEFAULT_FIELD_MAPPING.id).toBe("id"); + expect(new FieldMapper(DEFAULT_FIELD_MAPPING).mapFromFrontmatter({ id: "abc" }, "T.md").id).toBe("abc"); + }); + + it("reads the ID from the mapped property and leaves a plain id alone", () => { + const mapper = new FieldMapper(mapping); + const task = mapper.mapFromFrontmatter({ tasknote_id: "abc", id: "mine" }, "T.md"); + expect(task.id).toBe("abc"); + expect(mapper.mapFromFrontmatter({ id: "mine" }, "T.md").id).toBeUndefined(); + }); + + it("updates write the ID to the mapped property and cannot replace it", () => { + const frontmatter: Record = { id: "mine" }; + const originalTask: TaskInfo = { + id: "abc", + title: "Task", + status: "open", + priority: "normal", + path: "T.md", + archived: false, + tags: [], + }; + applyTaskUpdateFrontmatterChange({ + frontmatter, + originalTask, + updates: { customFrontmatter: { tasknote_id: "other", id: "changed" } }, + recurrenceUpdates: {}, + dateModified: "2026-11-18T00:00:00Z", + fieldMapper: new FieldMapper(mapping), + taskIdentification: { method: "tag", tag: "task", propertyName: "", propertyValue: "" }, + storeTitleInFilename: false, + updateCompletedDateInFrontmatter: jest.fn(), + }); + expect(frontmatter.tasknote_id).toBe("abc"); + expect(frontmatter.id).toBe("changed"); + }); + + it("creation writes the new ID to the mapped property", async () => { + const plugin = PluginFactory.createMockPlugin(); + plugin.fieldMapper = new FieldMapper(mapping); + const service = new TaskCreationService({ + runtime: plugin, + applyTaskCreationDefaults: jest.fn(async (taskData) => taskData), + applyTemplate: jest.fn(async () => ({ frontmatter: { id: "from-template" }, body: "" })), + processFolderTemplate: jest.fn((folderTemplate) => folderTemplate), + sanitizeTitleForFilename: jest.fn((input) => input), + sanitizeTitleForStorage: jest.fn((input) => input), + } as never); + + const { taskInfo } = await service.createTask({ title: "Remapped" }, { applyDefaults: false }); + + const content = (plugin.app.vault.create as jest.Mock).mock.calls[0][1] as string; + expect(taskInfo.id).toMatch(/^[0-9a-f-]{36}$/); + expect(content).toContain(`tasknote_id: ${taskInfo.id}`); + expect(content).toContain("id: from-template"); + }); +}); diff --git a/tests/unit/services/mdbaseMeaning.test.ts b/tests/unit/services/mdbaseMeaning.test.ts index a5ee59b2b..c8b13a792 100644 --- a/tests/unit/services/mdbaseMeaning.test.ts +++ b/tests/unit/services/mdbaseMeaning.test.ts @@ -124,7 +124,8 @@ describe("migration meaning preservation", () => { prior.schema.value.properties.title.minLength = 12; prior.schema.value.allOf.push({ properties: { title: { maxLength: 200 } } }); prior.schema.value.required.push("due"); - const generated = buildTaskNotesMdbaseResources({ archive: { moveOnArchive: true, folder: "New archive" } }); + // Settings read from this type map the ID to its `uid` property. + const generated = buildTaskNotesMdbaseResources({ modelConfig: { fieldMapping: { id: "uid" } }, archive: { moveOnArchive: true, folder: "New archive" } }); expect(generated.appSettings).toMatchObject({ move_on_archive: true, archive_folder: "New archive" }); const after = typeOf(mergeCanonicalTaskTypeDocument(doc(prior), generated)); expect(after.implements[0].fields.id).toBe("uid"); @@ -138,6 +139,22 @@ describe("migration meaning preservation", () => { expect(after.schema.value.required).toContain("due"); }); + it("#2574: remapping the ID in settings moves its schema, generator and uniqueness rule", () => { + const prior = typeOf(capture("meaning-policy")["_types/task.md"]); + // This type maps its ID to `uid`; give `uid` the generator and uniqueness rule too. + const generator = { uuid: true }; + delete prior.lifecycle.on_create.set.id; + prior.lifecycle.on_create.set.uid = generator; + prior.collection.unique = [{ field: "uid", scope: "type" }]; + const generated = buildTaskNotesMdbaseResources({ modelConfig: { fieldMapping: { id: "tasknote_id" } } }); + const after = typeOf(mergeCanonicalTaskTypeDocument(doc(prior), generated)); + expect(after.implements[0].fields.id).toBe("tasknote_id"); + expect(after.lifecycle.on_create.set.tasknote_id).toEqual(generator); + expect(after.lifecycle.on_create.set.uid).toBeUndefined(); + expect(after.schema.value.properties.tasknote_id).toEqual(prior.schema.value.properties.uid); + expect(after.collection.unique).toEqual([{ field: "tasknote_id", scope: "type" }]); + }); + it.each([undefined, [], ["custom_type"]])("COMPAT-06: preserves effective existing keys %j", async (keys) => { const entries = capture("meaning-policy"); const config = YAML.parse(entries["mdbase.yaml"]);