From 9e006d62988212f460fdaf2e9e010698c9ecf6a6 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Tue, 17 Nov 2026 18:22:53 +1100 Subject: [PATCH 1/5] fix: connect to published mdbase-sync and stable runtime packages --- package-lock.json | 83 +++++++++++++++--- package.json | 7 +- src/tasknotesBridge.ts | 10 ++- tests/tasknotesBridge.test.ts | 24 +++++ ...callumalpass-mdbase-runtime-0.2.0-rc.1.tgz | Bin 24178 -> 0 bytes 5 files changed, 106 insertions(+), 18 deletions(-) create mode 100644 tests/tasknotesBridge.test.ts delete mode 100644 vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz diff --git a/package-lock.json b/package-lock.json index 6108b4c..ab3b54b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,12 @@ "version": "0.1.6", "license": "MIT", "dependencies": { - "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@callumalpass/mdbase-runtime": "file:vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz", + "@callumalpass/mdbase-interop": "0.1.0", + "@callumalpass/mdbase-runtime": "0.2.0", + "@marcbachmann/cel-js": "8.0.0", "obsidian-bases-expression": "^0.3.0-rc.5", "obsidian-bases-expression-builder": "^0.2.0-rc.3", + "semver": "7.7.3", "yaml": "^2.8.1" }, "devDependencies": { @@ -20,6 +22,7 @@ "@codemirror/view": "6.38.6", "@eslint/js": "^9.39.4", "@types/node": "^24.3.0", + "@types/semver": "7.7.1", "@typescript-eslint/eslint-plugin": "^8.59.3", "@typescript-eslint/parser": "^8.59.3", "esbuild": "^0.25.9", @@ -123,9 +126,9 @@ } }, "node_modules/@callumalpass/mdbase-interop": { - "version": "0.1.0-rc.2", - "resolved": "https://registry.npmjs.org/@callumalpass/mdbase-interop/-/mdbase-interop-0.1.0-rc.2.tgz", - "integrity": "sha512-Le3wYZpuUS17HOVNT8eu/SJ8rCVsRGSJ9fMw79M9DcaeekO+Kavj1pnp9nOtP7HM5alP/raAzOi/T1ELci68GQ==", + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@callumalpass/mdbase-interop/-/mdbase-interop-0.1.0.tgz", + "integrity": "sha512-K5PNbvRb+VIDL0bTfmSSRJMdEIigHK08ocohPmLFHC0VePDtrybKIew7hHXkE6sFXvMqSK/NNrry3A642htOZQ==", "license": "MIT", "dependencies": { "ajv": "^8.17.1", @@ -133,10 +136,22 @@ "semver": "^7.8.5" } }, + "node_modules/@callumalpass/mdbase-interop/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@callumalpass/mdbase-runtime": { - "version": "0.2.0-rc.1", - "resolved": "file:vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz", - "integrity": "sha512-XsUYpK+DOiR4/+FDdpbfMese7wzmXZRNOS0wybqLL8HO1rOVIniRLO7ZP0hvDYKdPGtgQGCynKR41C7Ijo8XQQ==", + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@callumalpass/mdbase-runtime/-/mdbase-runtime-0.2.0.tgz", + "integrity": "sha512-H1PveinfgL6yX5ffjiO+kVee5jCT/3svfkezXw46VrpiJ2yMr0dIV8FwM1Q38dX0KMnY7CJ4rJzUIzle5HuY+A==", "license": "MIT", "dependencies": { "ajv": "^8.17.1", @@ -144,7 +159,19 @@ "semver": "^7.8.5" }, "peerDependencies": { - "@callumalpass/mdbase-interop": ">=0.1.0-rc.2 <0.2.0" + "@callumalpass/mdbase-interop": ">=0.1.0 <0.2.0" + } + }, + "node_modules/@callumalpass/mdbase-runtime/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, "node_modules/@codemirror/autocomplete": { @@ -1275,6 +1302,18 @@ "@lezer/common": "^1.0.0" } }, + "node_modules/@marcbachmann/cel-js": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@marcbachmann/cel-js/-/cel-js-8.0.0.tgz", + "integrity": "sha512-oaTrAziGr3zDLFiMt/yLU3nZuRMawyWQB5X1a0I7s9eGy3JYzX9l8ZXXHyMd64nzbeVFZTewuUShwsZQdK6UCA==", + "license": "MIT", + "bin": { + "cel-evaluate": "bin/cel-evaluate.js" + }, + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/@marijn/find-cluster-break": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz", @@ -1789,6 +1828,13 @@ "undici-types": "~7.18.0" } }, + "node_modules/@types/semver": { + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.1.tgz", + "integrity": "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/tern": { "version": "0.23.9", "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.9.tgz", @@ -3648,6 +3694,19 @@ "@codemirror/view": "6.38.6" } }, + "node_modules/eslint-plugin-obsidianmd/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/eslint-plugin-obsidianmd/node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -6548,9 +6607,9 @@ } }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", "license": "ISC", "bin": { "semver": "bin/semver.js" diff --git a/package.json b/package.json index d97b339..c3798f0 100644 --- a/package.json +++ b/package.json @@ -34,10 +34,12 @@ "author": "Callum Alpass", "license": "MIT", "dependencies": { - "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@callumalpass/mdbase-runtime": "file:vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz", + "@callumalpass/mdbase-interop": "0.1.0", + "@callumalpass/mdbase-runtime": "0.2.0", + "@marcbachmann/cel-js": "8.0.0", "obsidian-bases-expression": "^0.3.0-rc.5", "obsidian-bases-expression-builder": "^0.2.0-rc.3", + "semver": "7.7.3", "yaml": "^2.8.1" }, "devDependencies": { @@ -45,6 +47,7 @@ "@codemirror/view": "6.38.6", "@eslint/js": "^9.39.4", "@types/node": "^24.3.0", + "@types/semver": "7.7.1", "@typescript-eslint/eslint-plugin": "^8.59.3", "@typescript-eslint/parser": "^8.59.3", "esbuild": "^0.25.9", diff --git a/src/tasknotesBridge.ts b/src/tasknotesBridge.ts index f05ded4..ea12f23 100644 --- a/src/tasknotesBridge.ts +++ b/src/tasknotesBridge.ts @@ -33,6 +33,7 @@ interface MdbasePluginWithApi { api?: { apiVersion: number; interop?: { + profileVersion: string; connect(plugin: Plugin): InteropClient; describe(): BridgeDescription; }; @@ -69,14 +70,15 @@ export class TaskNotesBridge { const mdbase = this.mdbasePlugin(); return Boolean( this.plugin - && mdbase?.api?.interop + && mdbase?.api?.apiVersion === 1 + && mdbase.api.interop?.profileVersion === "0.1" && mdbase.api.getInteropStatus?.().enabled !== false ); } connectInterop(): InteropClient | null { - if (this.interopClient) return this.interopClient; if (!this.interopAvailable || !this.plugin) return null; + if (this.interopClient) return this.interopClient; const mdbase = this.mdbasePlugin(); if (!mdbase?.api?.interop) return null; this.interopClient = mdbase.api.interop.connect(this.plugin); @@ -84,7 +86,7 @@ export class TaskNotesBridge { } interopDescription(): BridgeDescription | null { - return this.mdbasePlugin()?.api?.interop?.describe() ?? null; + return this.interopAvailable ? this.mdbasePlugin()?.api?.interop?.describe() ?? null : null; } async onContractEvent( @@ -225,7 +227,7 @@ export class TaskNotesBridge { const app = this.app as App & { plugins?: { getPlugin(id: string): unknown }; }; - return app.plugins?.getPlugin("mdbase-obsidian") as MdbasePluginWithApi | null; + return app.plugins?.getPlugin("mdbase-sync") as MdbasePluginWithApi | null; } } diff --git a/tests/tasknotesBridge.test.ts b/tests/tasknotesBridge.test.ts new file mode 100644 index 0000000..50c9d29 --- /dev/null +++ b/tests/tasknotesBridge.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it, vi } from "vitest"; +import { InMemoryInteropBridge } from "@callumalpass/mdbase-interop"; +import { TaskNotesBridge } from "../src/tasknotesBridge"; +import { WORKFLOW_RUN_CONTRACT } from "../src/interopProvider"; + +describe("published mdbase-sync integration", () => { + it("uses mdbase-sync API v1/profile 0.1 with an actual bridge", async () => { + const bridge = new InMemoryInteropBridge({ authorize: () => true }); + const client = bridge.connect({ application: "tasknotes-workflows", implementation: "test", version: "1.0.0" }); + const provider = bridge.connect({ application: "provider", implementation: "test", version: "1.0.0" }); + await provider.registerActionProvider({ declaration_id: "actions", handlers: [{ handler_id: "run", contract: WORKFLOW_RUN_CONTRACT, handler: () => ({ done: true }) }] }); + const getPlugin = vi.fn((id) => id === "mdbase-sync" ? { api: { apiVersion: 1, interop: { profileVersion: "0.1", connect: () => client, describe: () => bridge.describe() }, getInteropStatus: () => ({ enabled: true }) } } : null); + const pluginBridge = new TaskNotesBridge({ plugins: { getPlugin } } as never, {} as never); + expect(pluginBridge.interopAvailable).toBe(true); + expect((await pluginBridge.invokeContractAction({ contract: { id: WORKFLOW_RUN_CONTRACT.id, version: "1.0.0" }, input: { workflow_id: "test" } })).status).toBe("succeeded"); + expect(getPlugin).toHaveBeenCalledWith("mdbase-sync"); + expect(getPlugin).not.toHaveBeenCalledWith("mdbase-obsidian"); + await pluginBridge.disposeInterop(); await bridge.dispose(); + }); + it.each([[2, "0.1", true], [1, "0.2", true], [1, "0.1", false]])("rejects incompatible or disabled integration %s/%s/%s", (apiVersion, profileVersion, enabled) => { + const getPlugin = () => ({ api: { apiVersion, interop: { profileVersion }, getInteropStatus: () => ({ enabled }) } }); + expect(new TaskNotesBridge({ plugins: { getPlugin } } as never, {} as never).interopAvailable).toBe(false); + }); +}); diff --git a/vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz b/vendor/callumalpass-mdbase-runtime-0.2.0-rc.1.tgz deleted file mode 100644 index a5527a3b8a7dd6972286888c09fd38a7491b9db2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 24178 zcmaHyV{~Ov)~-{rU9oMO72BwaZQB*w)`{&@>{P6ZZQDHYxz*iY-@f1d(fh|c-nr)5 zKlUDLY|Lja;%Hc~e;nYTOFuiE_2D^3p||h0e#d8KKpZ1j8Euz&0wa0Z>~HYJf`aW{ z1V%Nn=vvN{xT0{Nk9PMbjjB|}U{Ve}A&Q14J9l?;_bqqMTWI2LG=0D3<;zRrN21Lk zgU-#LEx!Wguh%c1yx&gQA5O;REiRjzEvDD-PgHzrx<9*OiJFNw2evsTyAD)3yF+AJ z)*&sQK-&k`k6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NNm9D>8Rq)YwUw|q03^uO^ok~a#-PdZ!Y(X z5sLA-G0kXVySwxLPgi1dbg-Fe#T1A}PcxYGDcL zl9L2umn(4}7K{{Q1aJf>mFGo^Fykh=nQG#cGCPueRMGR@P=?~Lwc;|+!!9U?1$0Am zlmwI%N7uKsC=ywv)?de9kYZRz2$;`A;h-DC^5-@%Z_Cat+vFwbuF>kEu3aS_b%u#e z;4Slo*QF)u7CNW&Gr79V@{8!89<~<7*U0ryslXyAx{wWdLd3gq9OXUYHW zzi$Y74hrqWqy~Ytbs~Qw(!sKH!{H3DFpfniDJMx^ zA%_?#PhEuq3bzCPBg9}X+-sw={WXk-u_!Q_n&Qe=^79bT_btu8?4iky&&yhK|(q zOXOm5uRnWxvPY()b%l=9+*^qKC711_VWv+;B&9}1Y?=h*zqY$P5yWlEG1=o9PU~sP zm~fJwmcSr|wKL$3P1;E8Pf2oaES%xQr6!ET>@6M>)UO~$pDSpfG+MamquOlvP179s z_3zA1Wwt6Z+82ji|HW(XI#dqx(51;Z>l_sB%AwTn59~brdws$%VJ7L5I6OtdwTE!0 z?ByE5_tJg)vMCkWakj=itD5!$ma&O!(?Zy@g?pr2iT;_w8*IE$dwppvh;-i4`9L}+ zXE9Ibj%>@Aq@FzHG_gd2shqe^U!R;4obZ7Uv*}U#7(1WwKmA!<0(_lvm$2ob^zqXvLw Date: Tue, 17 Nov 2026 18:24:42 +1100 Subject: [PATCH 2/5] feat: execute runtime workflows with CEL and persistent client admission --- CHANGELOG.md | 16 ++ README.md | 33 ++- docs/ai-agent-authoring-script.md | 12 +- docs/workflow-schema.md | 351 +++++++------------------- main.ts | 39 ++- manifest.json | 2 +- src/cel-host/LICENSE | 21 ++ src/cel-host/activation.ts | 237 +++++++++++++++++ src/cel-host/dates.ts | 133 ++++++++++ src/cel-host/evaluate.ts | 181 +++++++++++++ src/cel-host/index.ts | 28 ++ src/cel-host/markdown.ts | 33 +++ src/cel.ts | 59 +++++ src/collection.ts | 44 ++++ src/cron.ts | 18 +- src/defaultWorkflowsService.ts | 15 +- src/i18n/resources/en.ts | 4 + src/migrateExpressions.ts | 178 +++++++++++++ src/recordModifiedContract.ts | 211 ++++++++++++++++ src/runLogService.ts | 36 ++- src/runtimeExecutor.ts | 310 +++++++++++++++++++++++ src/runtimeHistory.ts | 67 +++++ src/runtimeState.ts | 51 ++++ src/scheduler.ts | 138 +++++++--- src/settingsTab.ts | 7 + src/stepRegistry.ts | 15 +- src/template.ts | 2 +- src/types.ts | 11 + src/workflowEditModal.ts | 5 + src/workflowEngine.ts | 8 +- src/workflowFormat.ts | 6 + src/workflowMigration.ts | 17 +- src/workflowMigrationModal.ts | 1 + src/workflowNoteCard.ts | 4 +- src/workflowParser.ts | 26 +- src/workflowRepository.ts | 16 +- src/workflowScaffolding.ts | 3 +- tests/celMigration.test.ts | 44 ++++ tests/collection.test.ts | 26 ++ tests/defaultWorkflowsService.test.ts | 4 +- tests/runLogService.test.ts | 15 ++ tests/runtimeExecutor.test.ts | 151 +++++++++++ tests/runtimeInterop.test.ts | 50 ++++ tests/runtimeScheduler.test.ts | 71 ++++++ tests/scheduler.test.ts | 4 +- versions.json | 2 +- 46 files changed, 2349 insertions(+), 356 deletions(-) create mode 100644 src/cel-host/LICENSE create mode 100644 src/cel-host/activation.ts create mode 100644 src/cel-host/dates.ts create mode 100644 src/cel-host/evaluate.ts create mode 100644 src/cel-host/index.ts create mode 100644 src/cel-host/markdown.ts create mode 100644 src/cel.ts create mode 100644 src/collection.ts create mode 100644 src/migrateExpressions.ts create mode 100644 src/recordModifiedContract.ts create mode 100644 src/runtimeExecutor.ts create mode 100644 src/runtimeHistory.ts create mode 100644 src/runtimeState.ts create mode 100644 tests/celMigration.test.ts create mode 100644 tests/collection.test.ts create mode 100644 tests/runtimeExecutor.test.ts create mode 100644 tests/runtimeInterop.test.ts create mode 100644 tests/runtimeScheduler.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a5f71a..59ae2aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +### Changed + +- Execute Runtime 0.2 workflow records directly with CEL expressions, trigger guards, ordered variables/iteration, persistent seven-day idempotency reservations, concurrency policies, debounce/minimum intervals, deadlines and item limits. Missed cron/interval schedules fire once after downtime; cron respects its timezone. +- Migrate Bases expressions, templates and structured conditions through the reviewed backup/apply/rollback flow. Unsupported conversions disable the workflow with an explanation. Unmigrated v1 files keep the original evaluator; CEL notes open directly for YAML editing. +- Store runtime run and action-attempt evidence in plugin configuration storage while retaining the history UI and read-only compatibility with old history. Interrupted work is not replayed. +- Add the device-local “Run workflows on this device” setting, enabled by default on desktop and disabled on mobile. Manual runs remain available. Obsidian 1.8.7 is now required for its local-storage API. +- Use stable mdbase interop 0.1.0 and runtime 0.2.0 packages; remove the vendored prerelease archive. Connect to the published `mdbase-sync` plugin and validate API/profile versions. Settings and documentation use “Allow plugin integrations”. +- Preserve TaskNotes v5 task IDs in event data; support stable-ID task reads/mutations and correct the scaffolded time-entry DTO. Metadata-change events use the `mdbase.record.modified` data shape. New/migrated workflows respect collection type keys and suggest the runtime standard pack when its type is missing. +- Generate disabled CEL starter workflows and recognize runtime notes in the workflow Base/note cards. + +### Fixed + +- Disabled workflows no longer execute or create skipped-run history on contract events. +- Interop step idempotency derives from the run idempotency key, step ID and item index. + + ## [0.1.6] - 2026-11-11 ### Changed diff --git a/README.md b/README.md index 0447866..d080723 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ Use it for things like: ## Requirements -- Obsidian 1.8.0 or newer +- Obsidian 1.8.7 or newer - TaskNotes installed and enabled -- `mdbase-obsidian` is optional for local TaskNotes-only workflows and required +- `mdbase-sync` is optional for local TaskNotes-only workflows and required for cross-application contract events and contract actions ## Install @@ -37,6 +37,12 @@ Useful commands: - **Migrate workflow files to the mdbase runtime format** - `Run: ` for enabled workflows that include a manual trigger +Automatic execution is controlled by **Run workflows on this device**, a device-local setting that defaults on for desktop and off for mobile. Manual runs remain available when it is off. Keep automatic execution enabled on one device for a synced vault. + +Run idempotency reservations persist for seven days; cron/interval downtime coalesces into one firing. Concurrency supports skip, queue, replace, and allow. This client does not provide distributed leases, a transactional event journal, or interrupted-run replay; see the [schema and execution limits](docs/workflow-schema.md). + +In an mdbase 0.3 collection, new/migrated notes use its configured explicit type key (including TaskNotes v5's `mdbase_type`). If the runtime type is missing, the plugin suggests installing the **mdbase runtime standard** pack. + ## Included Workflows The default set includes disabled examples for time tracking, status-triggered date cleanup, started timestamps, overdue review, scheduled-date rollover, due-date priority escalation, blocked-task review, folder movement, subtask inheritance, dependency inheritance, and parent-to-subtask mirroring. @@ -60,7 +66,8 @@ triggers: version: 1.0.0 x-tasknotes: type: tasknotes.event - to: active + if: + $expr: 'event.data.after.status == "active"' steps: - id: start-time @@ -69,17 +76,18 @@ steps: version: 1.0.0 input: task: - $expr: event.after.path + $expr: event.data.after.path run: concurrency: - group: workflow + group: + $expr: workflow.id policy: skip limits: max_items: 25 on_error: stop x-tasknotes: - format_version: 1 + format_version: 2 source: tasknotes-workflows --- ``` @@ -102,7 +110,7 @@ New files and editor saves validate against the canonical mdbase runtime `runtime_workflow` schema from Runtime profile 0.2. Files created by TaskNotes Workflows 0.1.x continue to run through the compatibility reader. The migration command shows a per-file diff, checks for changes after analysis, and creates a backup before rewriting -legacy frontmatter; it never runs automatically during plugin startup. +legacy frontmatter; it never runs automatically during plugin startup. It also converts format v1 expressions to CEL. Unsupported conversions disable the workflow and explain the required manual work. ## Contract Events And Actions @@ -131,16 +139,15 @@ steps: canvas_path: TaskNotes/Canvases/Completed tasks.canvas card: kind: file - file: "{{event.data.task_path}}" + file: + $expr: event.data.task_path ``` The included **Add completed tasks to a canvas** workflow demonstrates this -flow and is disabled by default. Enable **Allow local application -interoperability** in mdbase settings before enabling it. +flow and is disabled by default. Enable **Allow plugin integrations** in mdbase settings before enabling it. Contract events use CloudEvents and are multicast. Action execution requires -exactly one compatible provider. Run details preserve the exact contract, -source, provider, request, attempt, and outcome evidence. Compatibility never +exactly one compatible provider. Run details preserve contract, provider, request, attempt, and outcome evidence. Compatibility never acts as authorization; the mdbase host grant remains default-deny. ## Editing Workflows @@ -149,7 +156,7 @@ Use the workflow Base as the primary UI. Workflow cards open a modal editor for The Markdown note remains the source of truth. Use the card's note action when direct YAML editing is useful. -Workflows are typed YAML pipelines. Advanced guards and computed input values use Obsidian Bases formulas via the same expression engine as Bases. Date fields in the editor include fixed, workflow value, relative date, and formula modes, and run history shows both the source input and resolved input for dry-run review. +Workflows execute in this client using Runtime 0.2 records and CEL expressions. CEL workflows open their YAML note for editing; v1 workflows keep the original visual editor and Bases evaluator until migrated. Plain strings are literals in CEL workflows. Run history keeps its existing interface and stores runtime run/action-attempt evidence. See [Workflow Schema](docs/workflow-schema.md) and [AI Agent Authoring Script](docs/ai-agent-authoring-script.md) for the full format. diff --git a/docs/ai-agent-authoring-script.md b/docs/ai-agent-authoring-script.md index aa662df..aedb43e 100644 --- a/docs/ai-agent-authoring-script.md +++ b/docs/ai-agent-authoring-script.md @@ -17,13 +17,15 @@ safe testing steps. `maxItems`, or `onError` in a new file. 4. Put TaskNotes-only trigger configuration under `x-tasknotes`. 5. Prefer `enabled: false` for workflows that mutate tasks or vault files. -6. Use `$expr` objects for computed values. Plain strings are literals. +6. Set `x-tasknotes.format_version: 2`. Use CEL `$expr` objects for computed values. Plain strings, including `{{...}}`, are literals. Runtime payloads are under `event.data`. 7. Give every trigger and step a stable runtime identifier. 8. Keep `run.limits.max_items` bounded. 9. Do not use arbitrary JavaScript, shell commands, or unrestricted HTTP. 10. Use the TaskNotes action catalog rather than editing task frontmatter. 11. Explain dry-run checks and mutations in the Markdown body. +In an mdbase 0.3 collection, use the first configured `settings.explicit_type_keys` key (for example `mdbase_type`) instead of `type`. Cross-application actions require `mdbase-sync` and **Allow plugin integrations**. Run automatic workflows on one device using the device-local executor setting. + TaskNotes-specific trigger metadata is a runtime extension: ```yaml @@ -34,7 +36,8 @@ triggers: version: 1.0.0 x-tasknotes: type: tasknotes.event - to: active + if: + $expr: 'event.data.after.status == "active"' ``` Scheduled triggers use a canonical event ID plus executor metadata: @@ -87,13 +90,14 @@ steps: message: Workflow is wired. run: concurrency: - group: workflow + group: + $expr: workflow.id policy: skip limits: max_items: 25 on_error: stop x-tasknotes: - format_version: 1 + format_version: 2 source: tasknotes-workflows --- diff --git a/docs/workflow-schema.md b/docs/workflow-schema.md index 88b7619..6bae86b 100644 --- a/docs/workflow-schema.md +++ b/docs/workflow-schema.md @@ -1,338 +1,171 @@ -# Workflow Schema +# Workflow schema -TaskNotes Workflows persists canonical mdbase Runtime profile 0.2 -`runtime_workflow` records. -The normative JSON Schema is shipped by `@callumalpass/mdbase-runtime`; the -plugin validates every newly created, edited, or migrated record before writing -it. - -Workflow notes live in `TaskNotes/Workflows/` by default. The Markdown body is -user-owned documentation and is preserved when frontmatter is edited or -migrated. - -## Core Record +Workflow notes contain mdbase Runtime 0.2 `runtime_workflow` frontmatter and a user-owned Markdown body. New files use CEL and `x-tasknotes.format_version: 2`. The published `@callumalpass/mdbase-runtime@0.2.0` schema validates records. ```yaml type: runtime_workflow id: auto-start-time version: 1.0.0 name: Auto-start time tracking -description: Start a timer when a task becomes active. enabled: false - -requires: - capabilities: - - time.write - triggers: - id: status-active event: id: task.status.changed version: 1.0.0 + if: + $expr: 'event.data.after.status == "active"' + debounce: 500ms + minimum_interval: 5s x-tasknotes: type: tasknotes.event - to: active - steps: - id: start-time action: id: time.start version: 1.0.0 input: - path: - $expr: event.after.path - + taskId: + $expr: event.data.taskId run: concurrency: group: - $expr: event.after.path - policy: skip + $expr: event.data.taskId + policy: queue limits: - max_items: 1 + max_items: 25 timeout: 30s on_error: stop - x-tasknotes: - format_version: 1 - source: tasknotes-workflows + format_version: 2 ``` -Required core fields are `type`, `id`, `version`, `name`, `enabled`, -`triggers`, and `steps`. Unknown core fields are invalid unless their name -starts with `x-`. +Required fields are `type`, `id`, `version`, `name`, `enabled`, `triggers`, and `steps`. Trigger and step IDs must each be unique. Unknown fields require an `x-` prefix. In an mdbase 0.3 collection, new and migrated files use the first configured `settings.explicit_type_keys` key instead of `type` (for example `mdbase_type` in a new TaskNotes v5 collection). Omitted settings use `type`; an explicitly empty list requires collection configuration before writing workflows. A missing `runtime_workflow` type produces a hint to install the **mdbase runtime standard** pack; the plugin does not install it. -## Triggers +## Expressions -Every trigger has a unique `id` and references a runtime `event` contract. -Portable events use a contract requirement object. The TaskNotes extension is -only needed for executor-specific behavior: +An object with exactly one `$expr` key evaluates CEL using the mdbase CEL host. Every plain string is literal, including `{{...}}`. Evaluation errors fail execution. Conditions must produce a boolean; only `true` continues. -```yaml -triggers: - - id: canvas-drop - event: - id: canvas.drop - version: ^1.0.0 - if: - $expr: 'has(event.data.record.path)' -``` +The activation contains: -TaskNotes Workflows stores executor-specific scheduling and filters under -`x-tasknotes` while retaining a canonical event ID: +| Name | Value | +| --- | --- | +| `event` | CloudEvent; payload is under `event.data` | +| `workflow` | Runtime workflow record | +| `trigger` | Selected runtime trigger record | +| `vars` | Variables evaluated once in dependency order | +| `steps..output` | Completed output; use brackets for IDs containing hyphens | +| `item` | Current `for_each` item; optional `as` adds an alias | + +Use `today()` and `now()` for the captured execution date/instant. `today().addDays(3)` returns a full-date string. Variable cycles fail before dispatch. Variable dependencies use named selections (`vars.name` or `vars["name"]`); dynamic variable keys are rejected. The clock uses the cron timezone when supplied, otherwise the device timezone. ```yaml -triggers: - - id: every-morning - event: - id: tasknotes-workflows.schedule.cron - version: 1.0.0 - x-tasknotes: - type: cron - schedule: "0 9 * * *" - timezone: local +vars: + greeting: + $expr: '"Review " + workflow.name' +steps: + - id: notify + action: { id: notice.show, version: 1.0.0 } + input: + message: + $expr: 'vars.greeting + ": " + string(steps["task-query"].output.count)' +``` - - id: every-half-hour - event: - id: tasknotes-workflows.schedule.interval - version: 1.0.0 - x-tasknotes: - type: interval - every: 30m +## Events and triggers - - id: manual - event: - id: tasknotes-workflows.manual - version: 1.0.0 - x-tasknotes: - type: manual +`tasknotes.event` uses the TaskNotes runtime API, including v5's additive task identity. Its `event.data` is the plain-data TaskNotes API payload: - - id: note-modified - event: - id: obsidian.vault.modify - version: 1.0.0 - x-tasknotes: - type: obsidian.vault - event: modify - path: - glob: "Projects/**/*.md" +```text +event, timestamp, taskId, taskPath, +task, before, after, deletedTask, +changes: { : { before, after } }, +data, context, source, correlationId, reason, rawEvent ``` -Supported TaskNotes executor trigger types are `tasknotes.event`, -`contract.event`, `cron`, `interval`, `manual`, `obsidian.vault`, -`obsidian.metadata`, and `obsidian.workspace`. +Fields absent in the original event remain absent. `before`/`after` are semantic task snapshots, not raw frontmatter. Configured field mappings continue to work. Custom values are under `customProperties`. Write status guards as `event.data.after.status == "active"`, and transitions as `event.data.before.status == "open" && event.data.after.status == "active"`. The older `from`/`to` extension filters remain accepted. Self-generated task events are ignored unless `x-tasknotes.allowSelfTrigger: true`. -Contract event triggers select a portable event contract by ID and semantic -version range. `source` optionally narrows the publishing application: +`contract.event` is the default when no trigger extension type is given. It uses the exact incoming CloudEvent, preserving its ID, data, contract version and digest. Optional extension `source` selects `mdbaseapplication`; `path.glob`/`path.extension` filter the event subject/path. ```yaml triggers: - id: completed - event: - id: tasknotes.task.completed - version: ^1.0.0 + event: { id: tasknotes.task.completed, version: ^1.0.0 } x-tasknotes: type: contract.event source: tasknotes ``` -## Steps - -Every step has a unique `id` and references an `action` contract. Input values -are literals unless represented by an expression object. +Other supported extension types: ```yaml -steps: - - id: schedule-task - action: - id: task.setScheduled - version: 1.0.0 - input: - task: - $expr: event.after.path - date: - $expr: 'date(event.after.due) - duration("7d")' -``` - -TaskNotes Workflows owns and executes its typed local action catalog. An action -that is not local is invoked through the mdbase interoperability bridge using -its contract requirement. These are deliberately separate execution paths. - -Portable action steps put the contract requirement and provider selection in -the canonical step fields: - -```yaml -steps: - - id: add-card - action: - id: canvas.card.create - version: ^1.0.0 - provider: - application: canvas-bases - input: - canvas_path: TaskNotes/Canvases/Completed tasks.canvas - card: - kind: file - file: - $expr: event.data.task_path -``` - -The bridge admits the request only when exactly one compatible provider is -selected. Run logs preserve the exact resolved contract digest and provider -identity. - -The current TaskNotes action catalog includes task reads and mutations, task -relationships, time tracking, notices, selected Obsidian file operations, and -workflow control. Inspect the exact installed catalog through the TaskNotes -extension API: - -```js -const workflows = app.plugins.getPlugin("tasknotes")?.api.extensions.get("tasknotes-workflows"); -workflows?.listStepDefinitions(); -``` - -## Expressions - -Only `{ $expr: "..." }` objects are evaluated. Plain strings are literals. -Expressions receive `workflow`, `trigger`, `event`, `vars`, `steps`, `item`, -`today`, and `now`. - -```yaml -input: - path: - $expr: event.after.path - message: - $expr: '"Review " + workflow.name' -``` - -Step results use the canonical wrapper: - -```text -steps.query.status -steps.query.output.tasks -steps.query.error -``` - -TaskNotes exposes its configured core fields through stable semantic names. -For example, `event.after.projects` and `event.after.scheduled` continue to work -when those properties are stored in frontmatter as `parent` and `do`. Task paths -may point into any vault folder, including nested year and month folders. - -Custom frontmatter values are available under `customProperties`. To copy a -custom `area` field from a parent task, then write it to the triggering task: - -```yaml -steps: - - id: read-parent - action: - id: task.parents - version: 1.0.0 - input: - task: - $expr: event.after.path - - - id: inherit-area - action: - id: task.patch - version: 1.0.0 - input: - task: - $expr: event.after.path - patch: - customFrontmatter: - area: - $expr: steps.read-parent.output.tasks[0].customProperties.area +triggers: + - id: daily + event: { id: tasknotes-workflows.schedule.cron, version: 1.0.0 } + x-tasknotes: + type: cron + schedule: "0 9 * * *" + timezone: Australia/Melbourne # IANA zone, or local + catchUp: true + - id: interval + event: { id: tasknotes-workflows.schedule.interval, version: 1.0.0 } + x-tasknotes: { type: interval, every: 30m } + - id: manual + event: { id: tasknotes-workflows.manual, version: 1.0.0 } + x-tasknotes: { type: manual } + - id: metadata + event: { id: mdbase.record.modified, version: 1.0.0 } + x-tasknotes: + type: obsidian.metadata + event: changed + path: { glob: "Projects/**/*.md" } ``` -Use semantic names such as `projects` and `scheduled` inside `patch`; TaskNotes -writes them through the configured property mappings. Put arbitrary properties -inside `customFrontmatter`. Setting a custom frontmatter value to `null` removes -that property from the task note. +Cron and interval state persists under the plugin directory. On restart, missed schedules coalesce into one firing (`fire_once`), not one execution per missed slot. Cron `catchUp: false` disables missed-slot firing. New schedules have no pre-installation backlog. Debounce is trailing-edge and keeps the latest event; pending debounce timers are in memory and disappear on reload. Minimum-interval admission timestamps persist. Schedule state records the fire decision before executing; a crash between that write and dispatch can lose that firing. -## Conditions +`obsidian.metadata` `changed` observes metadata cache snapshots and emits local `mdbase.record.modified@1.0.0` data: `path`, `before`, `after`, `changed_fields`, `previous_revision`, `revision`, `previous_types`, `types`. Revisions hash metadata snapshots, not full mdbase record revisions. Type lists read configured explicit type keys; they do not include automatic type matches. Other metadata events (`deleted`, `resolve`, `resolved`) retain their original payload. `obsidian.vault` (`create`, `modify`, `delete`, `rename`) and `obsidian.workspace` (`file-open`, `active-leaf-change`, `layout-change`) keep their existing local payloads under `event.data`. -Workflow, trigger, and step guards use the canonical `if` expression: +## Actions and iteration -```yaml -if: - $expr: 'event.after.due != null && event.after.status != "done"' -``` - -The visual editor may retain its structured condition representation under -`x-tasknotes.conditions`. It also writes the equivalent canonical `if` field, -so generic tools can inspect the guard. - -## Iteration - -Use canonical `for_each` for bounded batch work: +Steps execute in document order. Local actions use the TaskNotes runtime API for task reads and writes; Obsidian actions use Obsidian APIs. `task.get` accepts `taskId` through v5 `tasks.getById`, or `task` as a path through `getByPath`/the v4-compatible `get`. Mutations accept `taskId`, resolve its current path immediately before calling the path-based TaskNotes mutation, and otherwise accept `task` paths. `time.appendEntry.entry` uses TaskNotes `TimeEntry` fields (`startTime`, optional `endTime` and `description`). ```yaml steps: - id: patch-each - action: - id: task.patch - version: 1.0.0 + action: { id: task.patch, version: 1.0.0 } for_each: items: $expr: steps.query.output.tasks - as: task + if: + $expr: 'item.status != "done"' input: - task: - $expr: task.path + taskId: + $expr: item.id patch: - status: open + customFrontmatter: + reviewed: true ``` -`for_each.items` must resolve to an array. TaskNotes Workflows stops the step -when the item count exceeds `run.limits.max_items`. +`for_each.items` must be a list and may not exceed `run.limits.max_items` (default 25). Items execute in order and step output is an ordered list. A step `if` is evaluated for each item. Arbitrary task properties belong in `patch.customFrontmatter`; `null` removes a custom property. TaskNotes semantic fields such as `projects` and `scheduled` use TaskNotes' configured field mappings. -## Run Policy +Unknown local action IDs, or steps with an explicit `provider`, use the mdbase bridge. The executor resolves exactly one provider, pins its contract and declaration, and rechecks that binding before dispatch. Contract requirements accept SemVer ranges. Enabling **Allow plugin integrations** in **mdbase** (`mdbase-sync`, API v1/profile 0.1) is required. The bridge applies its own authorization and schema validation. -```yaml -run: - idempotency: - key: - $expr: 'workflow.id + ":" + event.id + ":" + trigger.id' - concurrency: - group: workflow - policy: skip - limits: - max_items: 50 - timeout: 5m - on_error: stop -``` +## Run policy and history -Executor selection is deployment policy and does not belong in the workflow -record. +- `run.idempotency.key` is a literal or CEL expression producing a string. Default: `workflow.id + ":" + event.id + ":" + trigger.id`. Reservations persist for seven days before any actions; clearing history does not clear them. Dry runs do not reserve keys. +- `run.concurrency.group` is a literal or expression producing a string; default is the workflow ID. `skip` records a cancelled admission, `queue` waits in order, `replace` requests cooperative cancellation and waits for active work to settle, and `allow` runs concurrently. Queue positions and active execution are device-memory state. +- `run.limits.timeout` prevents new dispatch after the deadline. An in-flight local action must settle; interop receives deadline/cancellation requests. Completed effects are retained. +- `run.on_error: stop|continue` controls later dispatch. A run with any failed action remains failed even with `continue`. -## Compatibility And Migration +The history UI remains available. New details store `runtime_run` with `queued|running|waiting|succeeded|failed|cancelled|indeterminate` status and nested `runtime_action_attempt` records with `admitted|dispatching|succeeded|rejected|failed|cancelled|indeterminate`. UI summaries live in `x-tasknotes`; old history is read-only compatible. Intent and outcome snapshots are written before/after dispatch under the configured run-log directory. Local bindings identify this plugin's local handlers. The ephemeral bridge supplies invocation/attempt identities only with its outcome, so intent identities are provisional until then. Unknown interop outcomes become `indeterminate` and are not replayed. -TaskNotes Workflows 0.1.x used an incompatible product format with fields such -as: +This client executor does not claim full durable Runtime 0.2 conformance: it has no distributed lease, transactional event journal, durable queue/checkpoint recovery, or exactly-once external effects. Reservations suppress repeat events across restarts, but interrupted work is not resumed. On startup, incomplete queued history becomes cancelled and in-flight history becomes indeterminate. Run this plugin on one device per vault for automatic automation. -```yaml -type: tasknotes-workflow -schemaVersion: 1 -steps: - - id: notify - type: notice.show -run: - noOverlap: true - maxTasks: 25 - onError: stop -``` +**Run workflows on this device** is stored through Obsidian local storage, defaults on for desktop and off for mobile, and gates all automatic trigger kinds. Manual runs remain available. The setting is excluded from synced `data.json`. -The compatibility parser continues to execute these files and the later -noncanonical `type: workflow` plus `schemaVersion: 1` variant. Loading a legacy -file never rewrites it. +## Migration and editing -Use **Migrate workflow files to the mdbase runtime format** to produce a -non-mutating analysis. The review modal shows every changed block and every -invalid file. Applying the report: +Format v1 and older `workflow`/`tasknotes-workflow` records continue to use the original Bases evaluator until migrated. One startup notice offers the migration command. CEL records open their YAML note for editing; the existing visual formula builder remains available for v1 workflows. -1. verifies that no candidate changed after analysis -2. writes originals and a manifest under `.obsidian/tasknotes-workflows/workflow-migrations/` -3. replaces only analyzed frontmatter while preserving Markdown bodies -4. restores already changed files if a later write fails +**Migrate workflow files to the mdbase runtime format** analyzes without modifying files, displays diffs and conversion warnings, then checks source hashes, backs up originals under `.obsidian/tasknotes-workflows/workflow-migrations/`, applies only reviewed frontmatter, and rolls back earlier writes on failure. Markdown bodies are preserved. -Saving an individual legacy workflow through the visual editor also writes the -canonical format, because that save is already an explicit user action. +Migration converts clear Bases expressions, `{{reference}}` strings, scalar string interpolation, and `x-tasknotes.conditions` into CEL. Unsupported functions, ambiguous field `contains` semantics, and unsupported date arithmetic disable that workflow and add `x-tasknotes.comment` explaining required manual work. Original source remains in the backup and review diff. Migration never runs automatically. Editing v1 files retains v1 evaluation until the migration is applied. diff --git a/main.ts b/main.ts index 44bbd96..057157b 100644 --- a/main.ts +++ b/main.ts @@ -1,4 +1,6 @@ -import { Notice, Plugin, TFile } from "obsidian"; +import { RuntimeStateStore } from "./src/runtimeState"; +import { collectionSettings, hasRuntimeType } from "./src/collection"; +import { Notice, Platform, Plugin, TFile } from "obsidian"; import type { BasesViewRegistration } from "obsidian"; import { DefaultWorkflowsService } from "./src/defaultWorkflowsService"; import { RunLogService } from "./src/runLogService"; @@ -42,6 +44,9 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { runLogs!: RunLogService; stepRegistry!: StepRegistry; + runOnThisDevice = true; + private migrationNoticeShown = false; + private runtimeTypeHintShown = false; private bridge!: TaskNotesBridge; private engine!: WorkflowEngine; private scheduler!: WorkflowScheduler; @@ -97,6 +102,9 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { override async onload(): Promise { await this.loadSettings(); + const deviceSetting = this.app.loadLocalStorage("tasknotes-workflows:run-on-this-device") as boolean | null; + this.runOnThisDevice = deviceSetting ?? !Platform.isMobile; + this.runtimeTypeHintShown = this.app.loadLocalStorage("tasknotes-workflows:runtime-type-hint") === true; this.i18n = createI18nService({ initialLocale: this.settings.uiLanguage, @@ -111,20 +119,26 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { this.bridge = new TaskNotesBridge(this.app, this); this.repository = new WorkflowRepository(this.app, () => this.settings); this.runLogs = new RunLogService(this.app, () => this.settings); + await this.runLogs.recoverInterrupted(); this.stepRegistry = new StepRegistry((key, params) => this.t(key, params)); + const runtimeState = new RuntimeStateStore(this.app); this.engine = new WorkflowEngine( this.stepRegistry, () => this.bridge.api, () => this.app, (key, params) => this.t(key, params), () => this.bridge, + runtimeState, + (detail) => this.runLogs.checkpoint(this.redactRunDetail(detail)), ); this.scheduler = new WorkflowScheduler( this, this.bridge, () => this.settings, () => this.loadedWorkflows, - (workflow, options) => this.executeWorkflow(workflow, options) + (workflow, options) => this.executeWorkflow(workflow, options), + () => this.runOnThisDevice, + runtimeState, ); this.defaults = new DefaultWorkflowsService(this.app, () => this.settings); this.workflowMigrations = new WorkflowMigrationService(this.app, this.repository); @@ -168,6 +182,12 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { this.settings = normalizeSettings(loaded ?? {}); } + async setRunOnThisDevice(value: boolean): Promise { + this.runOnThisDevice = value; + this.app.saveLocalStorage("tasknotes-workflows:run-on-this-device", value); + await this.reloadWorkflows(); + } + async saveSettings(): Promise { await this.saveData(this.settings); } @@ -191,6 +211,16 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { async reloadWorkflows(): Promise { this.loadedWorkflows = await this.repository.reload(); + if (!this.migrationNoticeShown && this.loadedWorkflows.some((loaded) => loaded.workflow && (!loaded.runtime || (loaded.runtime["x-tasknotes"] as Record | undefined)?.format_version === 1))) { + this.migrationNoticeShown = true; + new Notice(this.t("notices.celMigration"), 12000); + } + const collection = await collectionSettings(this.app); + if (!this.runtimeTypeHintShown && collection && !await hasRuntimeType(this.app, collection)) { + this.runtimeTypeHintShown = true; + this.app.saveLocalStorage("tasknotes-workflows:runtime-type-hint", true); + new Notice(this.t("notices.runtimeTypeHint"), 12000); + } this.loadedWorkflows = await this.withLastRunSummaries(this.loadedWorkflows); if (this.bridge?.interopAvailable) await this.refreshActionProvider(); this.scheduler.start(); @@ -665,6 +695,11 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { if (this.settings.runLogLevel === "inputs-and-outputs") return detail; return { ...detail, + attempts: detail.attempts?.map((attempt) => ({ + ...attempt, + request: { ...attempt.request, input: this.settings.runLogLevel === "summary" ? undefined : attempt.request.input }, + outcome: this.settings.runLogLevel === "summary" && attempt.outcome?.status === "succeeded" ? { ...attempt.outcome, output: undefined } : attempt.outcome, + })), steps: detail.steps.map((step) => ({ ...step, output: this.settings.runLogLevel === "summary" ? undefined : step.output, diff --git a/manifest.json b/manifest.json index 72b20be..8104c6a 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "id": "tasknotes-workflows", "name": "TaskNotes Workflows", "version": "0.1.6", - "minAppVersion": "1.8.0", + "minAppVersion": "1.8.7", "description": "Markdown-defined workflow automation for TaskNotes.", "author": "Callum Alpass", "authorUrl": "https://github.com/callumalpass", diff --git a/src/cel-host/LICENSE b/src/cel-host/LICENSE new file mode 100644 index 0000000..32d4e6b --- /dev/null +++ b/src/cel-host/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Callum Alpass + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/cel-host/activation.ts b/src/cel-host/activation.ts new file mode 100644 index 0000000..e927f49 --- /dev/null +++ b/src/cel-host/activation.ts @@ -0,0 +1,237 @@ +// Copied from mdbase-spec packages/cel-host/src/activation.ts +// Origin commit: 47d257d6a56e34c7279e5ebb959af0b0f49744b2 (MIT). +// Mobile adaptation: vault paths are slash-separated, without Node APIs. +const basename = (path: string): string => path.split("/").pop() ?? ""; +const dirname = (path: string): string => path.split("/").slice(0, -1).join("/") || "."; +const extname = (name: string): string => name.lastIndexOf(".") > 0 ? name.slice(name.lastIndexOf(".")) : ""; +import { isPlainObject, type MarkdownRecord } from "./markdown.js"; + +export interface BuildRecordActivationOptions { + readDefaults?: Record; + /** Top-level fields that every matched schema declares `format: date-time`. */ + dateTimeFields?: Iterable; + includeBody?: boolean; +} + +export interface BuildWorkflowActivationOptions { + event?: Record; + steps?: Record; + vars?: Record; + item?: unknown; +} + +export interface MdbaseFileActivation { + path: string; + name: string; + basename: string; + ext: string; + folder: string; + body?: string; + tags: string[]; + links: string[]; + embeds: string[]; +} + +export interface RecordActivation { + [key: string]: unknown; + raw: Record; + record: Record; + file: MdbaseFileActivation; +} + +export interface WorkflowActivation { + event?: Record; + steps: Record; + vars: Record; + item?: unknown; +} + +/** System names that frontmatter fields never shadow (Chapter 10). */ +export const RESERVED_NAMES = new Set([ + "record", + "raw", + "file", + "projection", + "this", + "values", + "old", + "operation", + "event", + "workflow", + "trigger", + "steps", + "vars", + "item" +]); + +export function buildRecordActivation( + record: MarkdownRecord, + options: BuildRecordActivationOptions = {} +): RecordActivation { + const dateTimeFields = new Set(options.dateTimeFields ?? []); + const raw = typeFields(cloneObject(record.frontmatter), dateTimeFields); + const effective = typeFields(applyReadDefaults(record.frontmatter, options.readDefaults ?? {}), dateTimeFields); + const topLevel: Record = {}; + for (const [key, value] of Object.entries(effective)) { + if (!RESERVED_NAMES.has(key)) { + topLevel[key] = value; + } + } + return { + ...topLevel, + raw, + record: effective, + file: buildFileActivation(record, options) + }; +} + +export function buildWorkflowActivation(options: BuildWorkflowActivationOptions): WorkflowActivation { + return { + event: options.event, + steps: options.steps ?? {}, + vars: options.vars ?? {}, + ...(Object.prototype.hasOwnProperty.call(options, "item") ? { item: options.item } : {}) + }; +} + +/** + * Wrap a record activation so that an unreserved top-level identifier naming a + * missing field evaluates to null, while map selection keeps CEL's no-such-key + * behavior. + */ +export function withMissingFieldsAsNull(activation: Record): Record { + return new Proxy(activation, { + get(target, key) { + if (typeof key !== "string" || Object.prototype.hasOwnProperty.call(target, key)) { + return Reflect.get(target, key) as unknown; + } + return RESERVED_NAMES.has(key) ? undefined : null; + } + }); +} + +export function evaluateTemplate( + value: unknown, + activation: Record, + evaluate: (expr: string, activation: Record) => unknown +): unknown { + if (isExpressionObject(value)) { + return evaluate(value.$expr, activation); + } + if (Array.isArray(value)) { + return value.map((item) => evaluateTemplate(item, activation, evaluate)); + } + if (isPlainObject(value)) { + const result: Record = {}; + for (const [key, child] of Object.entries(value)) { + result[key] = evaluateTemplate(child, activation, evaluate); + } + return result; + } + return value; +} + +export function applyReadDefaults(raw: Record, readDefaults: Record): Record { + const effective = cloneObject(raw); + for (const [key, value] of Object.entries(readDefaults)) { + if (!Object.prototype.hasOwnProperty.call(effective, key)) { + effective[key] = value; + } + } + return effective; +} + +export function buildFileActivation( + record: MarkdownRecord, + options: BuildRecordActivationOptions = {} +): MdbaseFileActivation { + const name = basename(record.path); + const ext = extname(name).replace(/^\./, ""); + const base = ext ? name.slice(0, -(ext.length + 1)) : name; + const folder = dirname(record.path) === "." ? "" : dirname(record.path); + const body = options.includeBody === false ? undefined : record.body; + return { + path: record.path, + name, + basename: base, + ext, + folder, + ...(body === undefined ? {} : { body }), + tags: extractTags(record.frontmatter, record.body), + links: [], + embeds: [] + }; +} + +export function extractTags(frontmatter: Record, body: string): string[] { + const tags = new Set(); + const frontmatterTags = frontmatter.tags; + if (typeof frontmatterTags === "string") { + tags.add(normalizeTag(frontmatterTags)); + } else if (Array.isArray(frontmatterTags)) { + for (const tag of frontmatterTags) { + if (typeof tag === "string") { + tags.add(normalizeTag(tag)); + } + } + } + + for (const tag of extractBodyTags(body)) { + tags.add(tag); + } + + return [...tags].filter(Boolean).sort(); +} + +export function extractBodyTags(body: string): string[] { + const tags = new Set(); + const withoutCodeBlocks = body.replace(/```[\s\S]*?```/g, ""); + const pattern = /(^|\s)#([A-Za-z0-9_/-]+)/g; + let match: RegExpExecArray | null; + while ((match = pattern.exec(withoutCodeBlocks))) { + tags.add(match[2]); + } + return [...tags]; +} + +export function hasTag(tags: readonly string[], query: string): boolean { + const normalized = normalizeTag(query); + return tags.some((tag) => tag === normalized || tag.startsWith(`${normalized}/`)); +} + +export function inFolder(fileFolder: string, query: string): boolean { + const normalizedFolder = trimSlashes(fileFolder); + const normalizedQuery = trimSlashes(query); + return normalizedFolder === normalizedQuery || normalizedFolder.startsWith(`${normalizedQuery}/`); +} + +/** Convert `format: date-time` strings to timestamps; other values are unchanged. */ +function typeFields(fields: Record, dateTimeFields: ReadonlySet): Record { + const typed = cloneObject(fields); + for (const field of dateTimeFields) { + const value = typed[field]; + if (typeof value === "string") { + const instant = new Date(value); + if (!Number.isNaN(instant.getTime()) && /(?:Z|[+-]\d{2}:\d{2})$/i.test(value)) { + typed[field] = instant; + } + } + } + return typed; +} + +function cloneObject(value: Record): Record { + return { ...value }; +} + +function normalizeTag(tag: string): string { + return tag.replace(/^#/, ""); +} + +function trimSlashes(value: string): string { + return value.replace(/^\/+|\/+$/g, ""); +} + +function isExpressionObject(value: unknown): value is { $expr: string } { + return isPlainObject(value) && typeof value.$expr === "string" && Object.keys(value).length === 1; +} diff --git a/src/cel-host/dates.ts b/src/cel-host/dates.ts new file mode 100644 index 0000000..883e766 --- /dev/null +++ b/src/cel-host/dates.ts @@ -0,0 +1,133 @@ +// Copied from mdbase-spec packages/cel-host/src/dates.ts +// Origin commit: 47d257d6a56e34c7279e5ebb959af0b0f49744b2 (MIT). +// Date-string helpers for the mdbase CEL profile (Chapter 10, "Temporal Values"). +// Dates are RFC 3339 full-date strings; timestamps are JS Date values. + +const FULL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/; + +export class DateValueError extends Error {} + +interface CivilDate { + year: number; + month: number; + day: number; +} + +export function parseFullDate(value: unknown): CivilDate { + if (typeof value !== "string") { + throw new DateValueError(`expected an RFC 3339 full-date string, got ${typeof value}`); + } + const match = FULL_DATE.exec(value); + if (!match) { + throw new DateValueError(`"${value}" is not an RFC 3339 full-date`); + } + const date = { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]) }; + if (date.month < 1 || date.month > 12 || date.day < 1 || date.day > daysInMonth(date.year, date.month)) { + throw new DateValueError(`"${value}" is not a valid calendar date`); + } + return date; +} + +export function formatFullDate(date: CivilDate): string { + return `${String(date.year).padStart(4, "0")}-${pad(date.month)}-${pad(date.day)}`; +} + +export function addDays(value: string, days: number): string { + const date = parseFullDate(value); + return fromEpochDay(toEpochDay(date) + days); +} + +export function addMonths(value: string, months: number): string { + const date = parseFullDate(value); + const index = date.year * 12 + (date.month - 1) + months; + const year = Math.floor(index / 12); + const month = index - year * 12 + 1; + return formatFullDate({ year, month, day: Math.min(date.day, daysInMonth(year, month)) }); +} + +export function addYears(value: string, years: number): string { + return addMonths(value, years * 12); +} + +export function daysUntil(value: string, other: string): number { + return toEpochDay(parseFullDate(other)) - toEpochDay(parseFullDate(value)); +} + +export function isoWeekday(value: string): number { + const weekday = new Date(toEpochDay(parseFullDate(value)) * 86_400_000).getUTCDay(); + return weekday === 0 ? 7 : weekday; +} + +/** Calendar date of an instant in an IANA timezone. */ +export function dateOfInstant(instant: Date, timezone: string): string { + const parts = zonedParts(instant, timezone); + return formatFullDate({ year: parts.year, month: parts.month, day: parts.day }); +} + +/** First instant of a calendar date in an IANA timezone. */ +export function startOfDay(value: string, timezone: string): Date { + const date = parseFullDate(value); + const utcMidnight = Date.UTC(date.year, date.month - 1, date.day); + // Iterate because the offset at local midnight can differ from the offset at + // the UTC guess, for example across a daylight-saving transition. + let guess = utcMidnight; + for (let i = 0; i < 3; i += 1) { + const parts = zonedParts(new Date(guess), timezone); + const asUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second); + const offset = asUtc - guess; + const next = utcMidnight - offset; + if (next === guess) { + break; + } + guess = next; + } + return new Date(guess); +} + +function zonedParts(instant: Date, timezone: string) { + const formatter = new Intl.DateTimeFormat("en-CA", { + timeZone: timezone, + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit" + }); + const parts: Record = {}; + for (const part of formatter.formatToParts(instant)) { + if (part.type !== "literal") { + parts[part.type] = Number(part.value); + } + } + return { + year: parts.year, + month: parts.month, + day: parts.day, + hour: parts.hour, + minute: parts.minute, + second: parts.second + }; +} + +function toEpochDay(date: CivilDate): number { + return Date.UTC(date.year, date.month - 1, date.day) / 86_400_000; +} + +function fromEpochDay(day: number): string { + const date = new Date(day * 86_400_000); + return formatFullDate({ + year: date.getUTCFullYear(), + month: date.getUTCMonth() + 1, + day: date.getUTCDate() + }); +} + +function daysInMonth(year: number, month: number): number { + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +function pad(value: number): string { + return String(value).padStart(2, "0"); +} diff --git a/src/cel-host/evaluate.ts b/src/cel-host/evaluate.ts new file mode 100644 index 0000000..21a421c --- /dev/null +++ b/src/cel-host/evaluate.ts @@ -0,0 +1,181 @@ +// Copied from mdbase-spec packages/cel-host/src/evaluate.ts +// Origin commit: 47d257d6a56e34c7279e5ebb959af0b0f49744b2 (MIT). +import { Environment } from "@marcbachmann/cel-js"; +import { evaluateTemplate, hasTag, inFolder, withMissingFieldsAsNull } from "./activation.js"; +import { + addDays, + addMonths, + addYears, + dateOfInstant, + daysUntil, + isoWeekday, + parseFullDate, + startOfDay +} from "./dates.js"; + +export interface CelDiagnostic { + code: string; + message: string; +} + +export interface CelEvaluationResult { + valid: boolean; + value: unknown; + diagnostics: CelDiagnostic[]; +} + +export interface EvaluateCelOptions { + /** IANA timezone used by `today()`, `date(timestamp)`, and `startOfDay()`. */ + timezone?: string; + /** The operation's captured current instant. */ + now?: Date; +} + +interface Clock { + now: Date; + timezone: string; +} + +// Functions read the active clock; evaluation is synchronous, so a module-level +// slot scoped by evaluateCel is sufficient. +let activeClock: Clock | undefined; + +function clock(): Clock { + if (!activeClock) { + throw new Error("no evaluation clock is active"); + } + return activeClock; +} + +function integer(value: bigint): number { + return Number(value); +} + +const environment = new Environment({ + unlistedVariablesAreDyn: true, + enableOptionalTypes: true, + homogeneousAggregateLiterals: false, + limits: { maxDepth: 100 } +}) + .registerFunction("now(): google.protobuf.Timestamp", () => new Date(clock().now.getTime())) + .registerFunction("today(): string", () => dateOfInstant(clock().now, clock().timezone)) + .registerFunction("date(string): string", (value: string) => (parseFullDate(value), value)) + .registerFunction("date(google.protobuf.Timestamp): string", (value: Date) => + dateOfInstant(value, clock().timezone) + ) + .registerFunction("startOfDay(string): google.protobuf.Timestamp", (value: string) => + startOfDay(value, clock().timezone) + ) + .registerFunction("string.addDays(int): string", (value: string, days: bigint) => addDays(value, integer(days))) + .registerFunction("string.addMonths(int): string", (value: string, months: bigint) => + addMonths(value, integer(months)) + ) + .registerFunction("string.addYears(int): string", (value: string, years: bigint) => + addYears(value, integer(years)) + ) + .registerFunction("string.daysUntil(string): int", (value: string, other: string) => + BigInt(daysUntil(value, other)) + ) + .registerFunction("string.year(): int", (value: string) => BigInt(parseFullDate(value).year)) + .registerFunction("string.month(): int", (value: string) => BigInt(parseFullDate(value).month)) + .registerFunction("string.day(): int", (value: string) => BigInt(parseFullDate(value).day)) + .registerFunction("string.dayOfWeek(): int", (value: string) => BigInt(isoWeekday(value))) + // Unicode default full case mappings, without locale tailoring. + .registerFunction("string.lower(): string", (value: string) => value.toLowerCase()) + .registerFunction("string.upper(): string", (value: string) => value.toUpperCase()) + .registerFunction("map.inFolder(string): bool", (file: Record, folder: string) => + typeof file.folder === "string" && inFolder(file.folder, folder) + ) + .registerFunction("map.hasTag(string): bool", (file: Record, tag: string) => + Array.isArray(file.tags) && hasTag(file.tags.filter((item): item is string => typeof item === "string"), tag) + ); + +export function evaluateCel( + expression: string, + activation: Record, + options: EvaluateCelOptions = {} +): CelEvaluationResult { + let program: ReturnType; + try { + program = environment.parse(expression); + } catch (error) { + return { + valid: false, + value: null, + diagnostics: [{ code: "expression_compile_error", message: messageOf(error) }] + }; + } + + const previous = activeClock; + activeClock = { now: options.now ?? new Date(), timezone: options.timezone ?? "UTC" }; + try { + const value: unknown = program(withMissingFieldsAsNull(activation)); + return { valid: true, value: normalizeCelValue(value), diagnostics: [] }; + } catch (error) { + // Chapter 10: a top-level evaluation error in a query or projection value + // yields null for that value plus a diagnostic. + return { + valid: true, + value: null, + diagnostics: [{ code: "expression_evaluation_error", message: messageOf(error) }] + }; + } finally { + activeClock = previous; + } +} + +export function evaluateExpressionValueTemplate( + value: unknown, + activation: Record, + options: EvaluateCelOptions = {} +): unknown { + return evaluateTemplate(value, activation, (expr, nestedActivation) => + evaluateCel(expr, nestedActivation, options).value + ); +} + +/** Serialize a CEL result using the Chapter 10 serialization rules. */ +export function normalizeCelValue(value: unknown): unknown { + if (typeof value === "bigint") { + const asNumber = Number(value); + return Number.isSafeInteger(asNumber) ? asNumber : value.toString(); + } + if (value instanceof Date) { + return value.toISOString().replace(/\.000Z$/, "Z"); + } + if (isDuration(value)) { + return String(value); + } + if (Array.isArray(value)) { + return value.map((item) => normalizeCelValue(item)); + } + if (value instanceof Map) { + const result: Record = {}; + for (const [key, child] of value.entries()) { + result[String(key)] = normalizeCelValue(child); + } + return result; + } + if (value !== null && typeof value === "object") { + const result: Record = {}; + for (const [key, child] of Object.entries(value)) { + result[key] = normalizeCelValue(child); + } + return result; + } + return value; +} + +function isDuration(value: unknown): boolean { + return ( + value !== null && + typeof value === "object" && + "seconds" in value && + "nanos" in value && + value.constructor?.name === "Duration" + ); +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message.split("\n")[0] : String(error); +} diff --git a/src/cel-host/index.ts b/src/cel-host/index.ts new file mode 100644 index 0000000..f60748b --- /dev/null +++ b/src/cel-host/index.ts @@ -0,0 +1,28 @@ +// Copied from mdbase-spec packages/cel-host/src/index.ts +// Origin commit: 47d257d6a56e34c7279e5ebb959af0b0f49744b2 (MIT). +export { + applyReadDefaults, + buildFileActivation, + buildRecordActivation, + buildWorkflowActivation, + evaluateTemplate, + extractBodyTags, + extractTags, + hasTag, + inFolder, + RESERVED_NAMES, + withMissingFieldsAsNull +} from "./activation.js"; +export type { + BuildRecordActivationOptions, + BuildWorkflowActivationOptions, + MdbaseFileActivation, + RecordActivation, + WorkflowActivation +} from "./activation.js"; +export { evaluateCel, evaluateExpressionValueTemplate, normalizeCelValue } from "./evaluate.js"; +export type { CelDiagnostic, CelEvaluationResult, EvaluateCelOptions } from "./evaluate.js"; +export * as dates from "./dates.js"; +export { parseMarkdownRecord } from "./markdown.js"; +export type { MarkdownRecord } from "./markdown.js"; + diff --git a/src/cel-host/markdown.ts b/src/cel-host/markdown.ts new file mode 100644 index 0000000..ec1d52d --- /dev/null +++ b/src/cel-host/markdown.ts @@ -0,0 +1,33 @@ +// Copied from mdbase-spec packages/cel-host/src/markdown.ts +// Origin commit: 47d257d6a56e34c7279e5ebb959af0b0f49744b2 (MIT). +import { parse } from "yaml"; + +export interface MarkdownRecord { + path: string; + frontmatter: Record; + body: string; +} + +const frontmatterPattern = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/; + +export function parseMarkdownRecord(path: string, text: string): MarkdownRecord { + const match = text.match(frontmatterPattern); + if (!match) { + return { path, frontmatter: {}, body: text }; + } + // YAML integers stay CEL `int` values; other numbers become `double`. + const parsed = parse(match[1] ?? "", { intAsBigInt: true }) as unknown; + if (parsed != null && !isPlainObject(parsed)) { + throw new Error(`Frontmatter for ${path} must be an object.`); + } + return { + path, + frontmatter: parsed ?? {}, + body: match[2] ?? "" + }; +} + +export function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + diff --git a/src/cel.ts b/src/cel.ts new file mode 100644 index 0000000..186277f --- /dev/null +++ b/src/cel.ts @@ -0,0 +1,59 @@ +import { parse as parseCelExpression, type ASTNode } from "@marcbachmann/cel-js"; +import { evaluateCel, evaluateTemplate } from "./cel-host"; +import type { EvaluateCelOptions } from "./cel-host"; + +export function resolveCel(value: unknown, context: Record, options: EvaluateCelOptions = {}): unknown { + return evaluateTemplate(value, context, (source, activation) => { + const result = evaluateCel(source, activation, options); + if (result.diagnostics.length) throw new Error(result.diagnostics.map(({ message }) => message).join("; ")); + return result.value; + }); +} + +export function celCondition(condition: { $expr: string } | undefined, context: Record, options: EvaluateCelOptions = {}): boolean { + if (!condition) return true; + const value = resolveCel(condition, context, options); + if (typeof value !== "boolean") throw new Error("Workflow condition must evaluate to a boolean."); + return value; +} + +export function evaluateVariables(vars: Record, context: Record, options: EvaluateCelOptions = {}): Record { + const resolved: Record = {}; + const visiting = new Set(); + const visit = (name: string): void => { + if (Object.prototype.hasOwnProperty.call(resolved, name)) return; + if (visiting.has(name)) throw new Error(`Cyclic workflow variable: ${name}`); + if (!Object.prototype.hasOwnProperty.call(vars, name)) throw new Error(`Unknown workflow variable: ${name}`); + visiting.add(name); + for (const source of expressionSources(vars[name])) { + for (const dependency of variableDependencies(parseCelExpression(source).ast)) visit(dependency); + } + resolved[name] = resolveCel(vars[name], { ...context, vars: resolved }, options); + visiting.delete(name); + }; + for (const name of Object.keys(vars)) visit(name); + return resolved; +} + +export function expressionSources(value: unknown): string[] { + if (Array.isArray(value)) return value.flatMap(expressionSources); + if (!value || typeof value !== "object") return []; + const object = value as Record; + if (Object.keys(object).length === 1 && typeof object.$expr === "string") return [object.$expr]; + return Object.values(object).flatMap(expressionSources); +} + +function variableDependencies(node: ASTNode): string[] { + const result: string[] = []; + if (node.op === "." && node.args[0].op === "id" && node.args[0].args === "vars") result.push(node.args[1]); + if (node.op === "[]" && node.args[0].op === "id" && node.args[0].args === "vars") { + if (node.args[1].op !== "value" || typeof node.args[1].args !== "string") throw new Error("Variable dependencies require literal keys."); + result.push(node.args[1].args); + } + const visit = (value: unknown): void => { + if (Array.isArray(value)) for (const child of value) visit(child); + else if (value && typeof value === "object" && "op" in value) result.push(...variableDependencies(value as ASTNode)); + }; + visit(node.args); + return result; +} diff --git a/src/collection.ts b/src/collection.ts new file mode 100644 index 0000000..8696970 --- /dev/null +++ b/src/collection.ts @@ -0,0 +1,44 @@ +import { parse, stringify } from "yaml"; +import type { App } from "obsidian"; +import type { RuntimeWorkflow } from "@callumalpass/mdbase-runtime"; + +export interface CollectionSettings { typeKeys: string[]; typesFolder: string; } +export async function collectionSettings(app: App): Promise { + if (!await app.vault.adapter.exists("mdbase.yaml")) return null; + const config = parse(await app.vault.adapter.read("mdbase.yaml")) as { settings?: { explicit_type_keys?: string[]; types_folder?: string } }; + return { typeKeys: config.settings?.explicit_type_keys ?? ["type", "types"], typesFolder: config.settings?.types_folder ?? "_types" }; +} +export function normalizeWorkflowType(data: unknown, config: CollectionSettings | null): unknown { + if (!data || typeof data !== "object" || Array.isArray(data)) return data; + const record = data as Record; + if (config?.typeKeys.some((key) => record[key] === "runtime_workflow" || Array.isArray(record[key]) && (record[key] as unknown[]).includes("runtime_workflow"))) { + const normalized = { ...record, type: "runtime_workflow" }; + for (const key of config.typeKeys) if (key !== "type") delete (normalized as Record)[key]; + return normalized; + } + return data; +} +export async function runtimeFrontmatter(app: App, record: RuntimeWorkflow): Promise { + const config = await collectionSettings(app); + const key = config?.typeKeys[0] ?? "type"; + if (config && config.typeKeys.length === 0) throw new Error("Collection explicit_type_keys is empty; configure a type key before writing workflows."); + const { type, ...fields } = record; + return stringify({ [key]: type, ...fields }, { lineWidth: 100 }); +} +export async function hasRuntimeType(app: App, config: CollectionSettings): Promise { + const visit = async (folder: string): Promise => { + if (!await app.vault.adapter.exists(folder)) return false; + const listing = await app.vault.adapter.list(folder); + for (const file of listing.files) { + if (!/\.(md|yaml|yml)$/u.test(file)) continue; + const text = await app.vault.adapter.read(file); + const match = /^---\r?\n([\s\S]*?)\r?\n---/u.exec(text); + if (file.endsWith(".md") && !match) continue; + const type = parse(match?.[1] ?? text) as { kind?: string; name?: string } | null; + if (type?.kind === "mdbase.type" && type.name === "runtime_workflow") return true; + } + for (const child of listing.folders) if (await visit(child)) return true; + return false; + }; + return await visit(config.typesFolder); +} diff --git a/src/cron.ts b/src/cron.ts index c56896f..39d5944 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -1,14 +1,20 @@ -export function cronMatches(schedule: string, date: Date): boolean { +export function cronMatches(schedule: string, date: Date, timezone?: string): boolean { const fields = schedule.trim().split(/\s+/u); if (fields.length !== 5) return false; const [minute, hour, dayOfMonth, month, dayOfWeek] = fields; + let values = [date.getMinutes(), date.getHours(), date.getDate(), date.getMonth() + 1, date.getDay()]; + if (timezone && timezone !== "local") { + const parts = new Intl.DateTimeFormat("en-US", { timeZone: timezone, minute: "numeric", hour: "numeric", day: "numeric", month: "numeric", weekday: "short", hourCycle: "h23" }).formatToParts(date); + const get = (type: string): string => parts.find((part) => part.type === type)?.value ?? ""; + values = [Number(get("minute")), Number(get("hour")), Number(get("day")), Number(get("month")), ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(get("weekday"))]; + } return ( - fieldMatches(minute, date.getMinutes(), 0, 59) && - fieldMatches(hour, date.getHours(), 0, 23) && - fieldMatches(dayOfMonth, date.getDate(), 1, 31) && - fieldMatches(month, date.getMonth() + 1, 1, 12) && - fieldMatches(dayOfWeek, date.getDay(), 0, 7) + fieldMatches(minute, values[0] ?? 0, 0, 59) && + fieldMatches(hour, values[1] ?? 0, 0, 23) && + fieldMatches(dayOfMonth, values[2] ?? 1, 1, 31) && + fieldMatches(month, values[3] ?? 1, 1, 12) && + fieldMatches(dayOfWeek, values[4] ?? 0, 0, 7) ); } diff --git a/src/defaultWorkflowsService.ts b/src/defaultWorkflowsService.ts index f7fbad5..3399e79 100644 --- a/src/defaultWorkflowsService.ts +++ b/src/defaultWorkflowsService.ts @@ -1,7 +1,9 @@ +import { runtimeFrontmatter } from "./collection"; +import { workflowToCelRecord } from "./migrateExpressions"; import { normalizePath, type App } from "obsidian"; import { DEFAULT_WORKFLOW_FOLDER, DEFAULT_WORKFLOW_VIEW_PATH, WORKFLOW_BASE_VIEW_TYPE } from "./constants"; import { parseMarkdownFrontmatter, replaceMarkdownFrontmatter } from "./frontmatter"; -import { parseWorkflowDefinition, workflowToFrontmatter } from "./workflowParser"; +import { parseWorkflowDefinition } from "./workflowParser"; import type { TaskNotesWorkflowsSettings } from "./types"; interface DefaultWorkflow { @@ -27,7 +29,7 @@ export class DefaultWorkflowsService { const written: string[] = []; for (const workflow of defaultWorkflows(folder)) { if (await this.app.vault.adapter.exists(workflow.path)) continue; - await this.app.vault.create(workflow.path, canonicalWorkflowMarkdown(workflow.content)); + await this.app.vault.create(workflow.path, await canonicalWorkflowMarkdown(this.app, workflow.content)); written.push(workflow.path); } return written; @@ -55,21 +57,21 @@ export class DefaultWorkflowsService { } } -function canonicalWorkflowMarkdown(markdown: string): string { +async function canonicalWorkflowMarkdown(app: App, markdown: string): Promise { const parsed = parseMarkdownFrontmatter(markdown); if (parsed.error) throw new Error(parsed.error); const result = parseWorkflowDefinition(parsed.data, markdown); if (!result.workflow) { throw new Error(result.diagnostics.map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`).join("; ")); } - return replaceMarkdownFrontmatter(markdown, workflowToFrontmatter(result.workflow)); + return replaceMarkdownFrontmatter(markdown, await runtimeFrontmatter(app, workflowToCelRecord(result.workflow))); } function workflowViewFile(workflowFolder: string): string { const folder = normalizePath(workflowFolder || DEFAULT_WORKFLOW_FOLDER); return `filters: and: - - note["type"] == "workflow" || note["type"] == "tasknotes-workflow" + - note["type"] == "runtime_workflow" || note["mdbase_type"] == "runtime_workflow" || note["type"] == "workflow" || note["type"] == "tasknotes-workflow" - file.inFolder("${escapeBasesString(folder)}") views: @@ -129,8 +131,7 @@ run: This disabled example is the smallest end-to-end interoperability flow: TaskNotes publishes a contract event, this workflow consumes it, and Canvas -Bases provides the selected card-creation action. Enable local application -interoperability in mdbase settings before enabling the workflow. +Bases provides the selected card-creation action. Enable Allow plugin integrations in mdbase settings before enabling the workflow. `, }, { diff --git a/src/i18n/resources/en.ts b/src/i18n/resources/en.ts index bac3e7f..370da47 100644 --- a/src/i18n/resources/en.ts +++ b/src/i18n/resources/en.ts @@ -50,6 +50,8 @@ export const en: TranslationTree = { completed: "Migrated {count} workflows. Backup: {path}", }, notices: { + celMigration: "Some workflows still use Bases expressions. Use ‘Review workflow migration’ to review and migrate them to CEL.", + runtimeTypeHint: "Install the ‘mdbase runtime standard’ pack from mdbase to add the runtime_workflow type.", languageChanged: "Language changed to {language}.", workflowsReloaded: "Workflows reloaded.", defaultFilesCreated: "Created {count} default {fileLabel}.", @@ -64,6 +66,8 @@ export const en: TranslationTree = { discardAndOpenNote: "Unsaved changes. Press Open note again to discard and open the note.", }, settings: { + deviceExecutor: { name: "Run workflows on this device", description: "Enable automatic triggers here. Manual runs remain available. This setting stays on this device." }, + interop: "Enable ‘Allow plugin integrations’ in mdbase settings for contract events and actions.", workflowFiles: { heading: "Workflow files", folder: { diff --git a/src/migrateExpressions.ts b/src/migrateExpressions.ts new file mode 100644 index 0000000..847dd10 --- /dev/null +++ b/src/migrateExpressions.ts @@ -0,0 +1,178 @@ +import { parseExpression, type Expression } from "obsidian-bases-expression"; +import type { RuntimeWorkflow } from "@callumalpass/mdbase-runtime"; +import { evaluateCel } from "./cel-host"; +import { parseReferencePath } from "./template"; +import { workflowToRuntimeRecord } from "./workflowFormat"; +import type { LoadedWorkflow, WorkflowCondition, WorkflowDefinition } from "./types"; + +type Dict = Record; +export function migrateExpressions(loaded: Pick): { record: RuntimeWorkflow; warnings: string[] } { + if (!loaded.workflow) throw new Error("Invalid workflow."); + const record = structuredClone(loaded.runtime ?? workflowToRuntimeRecord(loaded.workflow)); + const warnings: string[] = []; + const convert = (value: unknown, path: string): unknown => { + try { + if (typeof value === "string" && value.includes("{{")) return convertTemplate(value); + if (Array.isArray(value)) return value.map((item, index) => convert(item, `${path}[${index}]`)); + if (!isRecord(value)) return value; + if (typeof value.$expr === "string") return { $expr: convertBases(value.$expr) }; + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, convert(item, `${path}.${key}`)])); + } catch (error) { + warnings.push(`${path}: ${error instanceof Error ? error.message : String(error)}`); + return null; + } + }; + const condition = (conditions: WorkflowCondition[], path: string): { $expr: string } | undefined => { + if (!conditions.length) return undefined; + try { return { $expr: conditions.map(conditionToCel).map((source) => `(${source})`).join(" && ") }; } + catch (error) { warnings.push(`${path}: ${error instanceof Error ? error.message : String(error)}`); return { $expr: "false" }; } + }; + const workflowConditions = condition(loaded.workflow.conditions, "conditions"); + record.vars = convert(loaded.workflow.vars, "vars") as RuntimeWorkflow["vars"]; + for (const [index, trigger] of record.triggers.entries()) { + const projected = loaded.workflow.triggers[index]; + const filters: string[] = []; + if (trigger.if) filters.push(((convert(trigger.if, `triggers[${index}].if`) as { $expr: string } | null)?.$expr ?? "false")); + if (workflowConditions) filters.push(workflowConditions.$expr); + if (projected?.type === "tasknotes.event") { + if (projected.from !== undefined) filters.push(`event.data.before.status == ${JSON.stringify(projected.from)}`); + if (projected.to !== undefined) filters.push(`event.data.after.status == ${JSON.stringify(projected.to)}`); + const ext = extension(trigger); + delete ext.from; delete ext.to; + } + if (filters.length) trigger.if = { $expr: filters.map((source) => `(${source})`).join(" && ") }; + } + for (const [index, step] of record.steps.entries()) { + step.input = convert(loaded.workflow.steps[index]?.input, `steps[${index}].input`) as typeof step.input; + if (step.for_each) step.for_each.items = convert(loaded.workflow.steps[index]?.forEach?.items, `steps[${index}].for_each.items`) as typeof step.for_each.items; + const oldStep = loaded.workflow.steps[index]; + const conditions = oldStep?.if ? Array.isArray(oldStep.if) ? oldStep.if : [oldStep.if] : []; + step.if = conditions.length ? condition(conditions, `steps[${index}].if`) : step.if ? convert(step.if, `steps[${index}].if`) as typeof step.if : undefined; + const ext = extension(step); + delete ext.conditions; + } + if (record.run?.idempotency) record.run.idempotency.key = convert(record.run.idempotency.key, "run.idempotency.key") as typeof record.run.idempotency.key; + if (record.run?.concurrency) { + const group = record.run.concurrency.group; + record.run.concurrency.group = group === "workflow" ? { $expr: "workflow.id" } : group === "global" ? "global" : convert(group, "run.concurrency.group") as typeof group; + } + const ext = extension(record); + delete ext.conditions; + ext.format_version = 2; + record["x-tasknotes"] = ext; + if (warnings.length) { + record.enabled = false; + ext.comment = `Disabled during CEL migration. Manual conversion required: ${warnings.join("; ")}`; + } + return { record, warnings }; +} + +export function convertBases(source: string): string { + const parsed = parseExpression(source); + if (!parsed.ast || parsed.diagnostics.some(({ severity }) => severity === "error")) throw new Error(`Cannot parse Bases expression: ${source}`); + const result = printCel(parsed.ast); + const compiled = evaluateCel(result, {}); + if (!compiled.valid) throw new Error(compiled.diagnostics.map(({ message }) => message).join("; ")); + return result; +} +function printCel(node: Expression): string { + switch (node.type) { + case "Literal": return JSON.stringify(node.value); + case "Identifier": return node.name === "today" ? "today()" : node.name === "now" ? "now()" : node.name; + case "Array": return `[${node.elements.map(printCel).join(", ")}]`; + case "Member": { + if (node.object.type === "Identifier" && node.object.name === "event" && typeof node.property === "string" && node.property !== "data") { + return `event.data[${JSON.stringify(node.property)}]`; + } + const object = printCel(node.object); + if (!node.computed && node.property === "length") return `size(${object})`; + return `${object}[${typeof node.property === "string" ? JSON.stringify(node.property) : printCel(node.property)}]`; + } + case "Unary": + if (node.operator === "+") throw new Error("Unary plus requires manual conversion."); + return `${node.operator}(${printCel(node.argument)})`; + case "Binary": { + if ((node.operator === "+" || node.operator === "-") && node.right.type === "Call" && node.right.callee.type === "Identifier" && node.right.callee.name === "duration") { + const value = node.right.args[0]; + const match = value?.type === "Literal" && typeof value.value === "string" ? /^(\d+)(d|w)$/u.exec(value.value) : null; + if (match) return `(${printCel(node.left)}).addDays(${Number(match[1]) * (match[2] === "w" ? 7 : 1) * (node.operator === "-" ? -1 : 1)})`; + throw new Error("Duration arithmetic requires manual conversion."); + } + return `(${printCel(node.left)} ${node.operator} ${printCel(node.right)})`; + } + case "Call": { + const args = node.args.map(printCel); + if (node.callee.type === "Identifier") { + const name = node.callee.name; + if (name === "if" && args.length === 3) return `(${args[0]} ? ${args[1]} : ${args[2]})`; + if (["today", "now", "date", "string", "number"].includes(name)) return `${name === "number" ? "double" : name}(${args.join(", ")})`; + } + if (node.callee.type === "Member" && typeof node.callee.property === "string") { + const method = node.callee.property; + if (["contains", "startsWith", "endsWith", "lower", "upper", "size"].includes(method)) return `${printCel(node.callee.object)}.${method}(${args.join(", ")})`; + } + throw new Error("Bases function requires manual conversion."); + } + default: throw new Error(`Bases ${node.type} requires manual conversion.`); + } +} +function reference(source: string): string { + const parts = parseReferencePath(source.trim()); + let root = parts.shift() ?? ""; + if (root === "today" || root === "now") root += "()"; + if (root === "event" && parts[0] !== "data") parts.unshift("data"); + return root + parts.map((part) => /^\d+$/u.test(part) ? `[${part}]` : `[${JSON.stringify(part)}]`).join(""); +} +function convertTemplate(value: string): { $expr: string } { + const full = /^\s*\{\{\s*([^{}]+?)\s*\}\}\s*$/u.exec(value); + if (full) return { $expr: reference(full[1] ?? "") }; + const parts: string[] = []; + let offset = 0; + for (const match of value.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/gu)) { + if ((match.index ?? 0) > offset) parts.push(JSON.stringify(value.slice(offset, match.index))); + parts.push(`string(${reference(match[1] ?? "")})`); + offset = (match.index ?? 0) + match[0].length; + } + if (offset === 0) throw new Error("Unclosed template requires manual conversion."); + if (offset < value.length) parts.push(JSON.stringify(value.slice(offset))); + return { $expr: parts.join(" + ") }; +} +function referencePresence(source: string): string { + const parts = parseReferencePath(source); + let parent = parts.shift() ?? ""; + if (parent === "event" && parts[0] !== "data") parts.unshift("data"); + const checks: string[] = []; + for (const part of parts) { + checks.push(`${parent} != null`); + checks.push(/^\d+$/u.test(part) ? `size(${parent}) > ${part}` : `${JSON.stringify(part)} in ${parent}`); + parent += /^\d+$/u.test(part) ? `[${part}]` : `[${JSON.stringify(part)}]`; + } + return checks.join(" && ") || "true"; +} +function conditionToCel(condition: WorkflowCondition): string { + if ("$expr" in condition) return convertBases(condition.$expr); + const field = reference(condition.field); + const value = typeof condition.value === "string" && condition.value.includes("{{") ? convertTemplate(condition.value).$expr : JSON.stringify(condition.value ?? null); + switch (condition.operator) { + case "is": return `${field} == ${value}`; + case "isNot": return `${field} != ${value}`; + case "in": return `${field} in ${value}`; + case "notIn": return `!(${field} in ${value})`; + case "exists": return `(${referencePresence(condition.field)}) && ${field} != null && ${field} != ""`; + case "missing": return `!(${referencePresence(condition.field)}) || ${field} == null || ${field} == ""`; + case "startsWith": return `${field}.startsWith(${value})`; + case "contains": throw new Error("contains on a field may refer to a list or string; choose CEL 'in' or '.contains()' explicitly."); + default: { + const op = { before: "<", after: ">", onOrBefore: "<=", onOrAfter: ">=" }[condition.operator]; + return `date(${field}) ${op} date(${value})`; + } + } +} +function extension(value: unknown): Dict { + return isRecord(value) && isRecord(value["x-tasknotes"]) ? value["x-tasknotes"] : {}; +} +function isRecord(value: unknown): value is Dict { return value !== null && typeof value === "object" && !Array.isArray(value); } + +export function workflowToCelRecord(workflow: WorkflowDefinition): RuntimeWorkflow { + return migrateExpressions({ workflow }).record; +} diff --git a/src/recordModifiedContract.ts b/src/recordModifiedContract.ts new file mode 100644 index 0000000..f7fcff2 --- /dev/null +++ b/src/recordModifiedContract.ts @@ -0,0 +1,211 @@ +import type { EventContractArtifact } from "@callumalpass/mdbase-interop"; + +// mdbase-contracts schemas/mdbase.record.modified/1.0.0.schema.json (MIT). +// Origin commit: b4881e792eca47e5d7539335cfa09af93f707bb0. +export const RECORD_MODIFIED_CONTRACT: EventContractArtifact = { + "kind": "mdbase.contract", + "contract_type": "event", + "id": "mdbase.record.modified", + "version": "1.0.0", + "data_schema": { + "dialect": "json-schema-2020-12", + "value": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "mdbase record-modified event data", + "type": "object", + "required": [ + "path", + "before", + "after", + "changed_fields", + "previous_revision", + "revision", + "previous_types", + "types" + ], + "properties": { + "path": { + "type": "string", + "minLength": 1 + }, + "before": { + "type": "object" + }, + "after": { + "type": "object" + }, + "changed_fields": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string" + } + }, + "previous_revision": { + "type": "string", + "minLength": 1 + }, + "revision": { + "type": "string", + "minLength": 1 + }, + "previous_types": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + } + }, + "types": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + } + } + }, + "patternProperties": { + "^x-[A-Za-z0-9._:-]+$": true + }, + "additionalProperties": false, + "$defs": { + "identifier": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "semanticVersion": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" + }, + "digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "dateTime": { + "type": "string", + "format": "date-time" + }, + "contractRequirement": { + "type": "object", + "required": [ + "id", + "version" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "version": { + "type": "string", + "minLength": 1 + }, + "digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } + }, + "patternProperties": { + "^x-[A-Za-z0-9._:-]+$": true + }, + "additionalProperties": false + }, + "exactContractReference": { + "type": "object", + "required": [ + "id", + "version", + "digest" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "version": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" + }, + "digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } + }, + "patternProperties": { + "^x-[A-Za-z0-9._:-]+$": true + }, + "additionalProperties": false + }, + "identity": { + "type": "object", + "required": [ + "application", + "implementation", + "version" + ], + "properties": { + "application": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "implementation": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "version": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" + }, + "instance_id": { + "type": "string", + "minLength": 1 + } + }, + "patternProperties": { + "^x-[A-Za-z0-9._:-]+$": true + }, + "additionalProperties": false + }, + "providerSelector": { + "type": "object", + "required": [], + "properties": { + "application": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "implementation": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9._:-]*$" + }, + "instance_id": { + "type": "string", + "minLength": 1 + } + }, + "patternProperties": { + "^x-[A-Za-z0-9._:-]+$": true + }, + "additionalProperties": false, + "minProperties": 1 + }, + "expression": { + "type": "object", + "required": [ + "$expr" + ], + "properties": { + "$expr": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "$id": "https://mdbase.dev/schemas/runtime/v0.2/mdbase.record.modified/1.0.0.schema.json" + } + } +}; diff --git a/src/runLogService.ts b/src/runLogService.ts index a903abd..b66c43e 100644 --- a/src/runLogService.ts +++ b/src/runLogService.ts @@ -1,3 +1,4 @@ +import { historyDetail, historyRecord } from "./runtimeHistory"; import type { App } from "obsidian"; import { PLUGIN_ID } from "./constants"; import { safePathSegment } from "./path"; @@ -12,6 +13,37 @@ export class RunLogService { private readonly getSettings: () => TaskNotesWorkflowsSettings ) {} + async recoverInterrupted(): Promise { + const root = `${this.rootPath()}/workflows`; + if (!await this.exists(root)) return; + const interrupted: WorkflowRunDetail[] = []; + for (const folder of (await this.app.vault.adapter.list(root)).folders) { + for (const file of (await this.app.vault.adapter.list(folder)).files.filter((path) => path.endsWith(".json"))) { + const detail = historyDetail(JSON.parse(await this.app.vault.adapter.read(file))); + if (!detail.runtime || !["queued", "running", "waiting"].includes(detail.runtime.status)) continue; + const now = new Date().toISOString(); + detail.runtime.status = detail.runtime.status === "queued" ? "cancelled" : "indeterminate"; + detail.runtime.updated_at = now; + detail.runtime.finished_at = now; + detail.status = "failed"; + detail.error = "Interrupted client execution; no actions were replayed."; + detail.endedAt = now; + for (const attempt of detail.attempts ?? []) { + if (attempt.status !== "admitted" && attempt.status !== "dispatching") continue; + attempt.status = attempt.status === "admitted" ? "cancelled" : "indeterminate"; + attempt.updated_at = now; + attempt.completed_at = now; + } + interrupted.push(detail); + } + } + for (const detail of interrupted) await this.recordRun(detail); + } + + async checkpoint(detail: WorkflowRunDetail): Promise { + await this.enqueueWrite(() => this.writeDetail(detail)); + } + async recordRun(detail: WorkflowRunDetail): Promise { const summary: RunSummary = { ts: detail.startedAt, @@ -60,7 +92,7 @@ export class RunLogService { const path = this.detailPath(workflowId, runId); try { if (!(await this.exists(path))) return null; - return JSON.parse(await this.app.vault.adapter.read(path)) as WorkflowRunDetail; + return historyDetail(JSON.parse(await this.app.vault.adapter.read(path))); } catch { return null; } @@ -99,7 +131,7 @@ export class RunLogService { await this.ensureFolder(folder); await this.app.vault.adapter.write( this.detailPath(detail.workflowId, detail.runId), - stringifyWorkflowData(detail, 2) + stringifyWorkflowData(historyRecord(detail), 2) ); } diff --git a/src/runtimeExecutor.ts b/src/runtimeExecutor.ts new file mode 100644 index 0000000..f17fd9e --- /dev/null +++ b/src/runtimeExecutor.ts @@ -0,0 +1,310 @@ +import { resolveTemplateValue } from "./template"; +import { conditionsMatch } from "./conditions"; +import { RECORD_MODIFIED_CONTRACT } from "./recordModifiedContract"; +import { satisfies } from "semver"; +import { exactContractReference, type ActionContractArtifact, type CloudEvent, type EventContractArtifact, type InvokeActionInput } from "@callumalpass/mdbase-interop"; +import type { AdmittedActionBinding, RuntimeWorkflowStep } from "@callumalpass/mdbase-runtime"; +import type { App } from "obsidian"; +import { celCondition, evaluateVariables, expressionSources, resolveCel } from "./cel"; +import { evaluateCel } from "./cel-host"; +import { parseDurationMs } from "./duration"; +import { createStepExecutionContext, type StepRegistry } from "./stepRegistry"; +import type { TaskNotesBridge } from "./tasknotesBridge"; +import { digest, LOCAL_EXECUTOR, type RuntimeAttemptRecord, type RuntimeRunStatus } from "./runtimeHistory"; +import { RuntimeStateStore } from "./runtimeState"; +import { toWorkflowData } from "./workflowData"; +import type { LoadedWorkflow, StepRunDetail, TaskNotesRuntimeApi, WorkflowRunDetail, WorkflowRunOptions, WorkflowRunContext, WorkflowCondition } from "./types"; + +interface ActiveRun { cancel: AbortController; done: Promise; } + +/** Client execution, with durable reservations and evidence; no distributed leases or replay. */ +export class RuntimeWorkflowExecutor { + private groups = new Map>(); + constructor( + private readonly registry: StepRegistry, + private readonly tasknotes: () => TaskNotesRuntimeApi | null, + private readonly app: () => App | null, + private readonly bridge: () => TaskNotesBridge | null, + private readonly state = new RuntimeStateStore(), + private readonly persist: (detail: WorkflowRunDetail) => Promise = async () => {}, + ) {} + + async run(loaded: LoadedWorkflow, options: WorkflowRunOptions): Promise { + const workflow = loaded.runtime; + if (!workflow) throw new Error("Missing runtime workflow record."); + const runId = `run:${crypto.randomUUID()}`; + const now = new Date(); + const detail: WorkflowRunDetail = { + runId, workflowId: workflow.id, workflowName: workflow.name, workflowPath: loaded.file.path, + dryRun: options.dryRun === true, startedAt: now.toISOString(), status: "success", + trigger: toWorkflowData(options.trigger) as WorkflowRunOptions["trigger"], steps: [], attempts: [], + }; + const finish = async (status: RuntimeRunStatus, error?: string): Promise => { + detail.status = status === "succeeded" ? "success" : status === "cancelled" ? "skipped" : "failed"; + detail.error = error; + detail.endedAt = new Date().toISOString(); + detail.durationMs = Date.now() - now.getTime(); + if (detail.runtime) { + detail.runtime.status = status; + detail.runtime.updated_at = detail.endedAt; + detail.runtime.finished_at = detail.endedAt; + } + await this.persist(detail); + return detail; + }; + let active: ActiveRun | undefined; + let group = ""; + let release: (() => void) | undefined; + let timer: number | undefined; + try { + if (!workflow.enabled && !options.dryRun) return await finish("cancelled", "Workflow is disabled."); + const legacy = extension(workflow).format_version === 1; + for (const source of legacy ? [] : expressionSources(workflow)) { + const result = evaluateCel(source, {}); + if (!result.valid) throw new Error(result.diagnostics.map(({ message }) => message).join("; ")); + } + const trigger = workflow.triggers.find(({ id }) => id === options.trigger.id) + ?? (options.manual ? workflow.triggers.find((candidate) => extension(candidate).type === "manual") : undefined); + const event = options.trigger.cloudEvent ?? await localCloudEvent(options, trigger?.event.id); + const clock = { now, timezone: scheduleTimezone(trigger) }; + const context: Record = { + workflow: legacy ? { ...workflow, filePath: loaded.file.path } : workflow, + trigger: legacy ? { ...trigger, ...extension(trigger) } : trigger ?? { id: "manual" }, + event: legacy ? detail.trigger : event, steps: {}, vars: workflow.vars ?? {}, now: now.toISOString(), today: now.toISOString().slice(0, 10), + }; + const resolve = (value: unknown, activation = context): unknown => legacy + ? resolveTemplateValue(value, activation as WorkflowRunContext) + : resolveCel(value, activation, clock); + const matches = (condition: RuntimeWorkflowStep["if"], activation = context): boolean => { + if (!condition) return true; + if (!legacy) return celCondition(condition, activation, clock); + return conditionsMatch([{ $expr: condition.$expr }], activation as WorkflowRunContext); + }; + if (!legacy) context.vars = evaluateVariables(workflow.vars ?? {}, context, clock); + const legacyConditions = legacy ? extension(workflow).conditions as WorkflowCondition[] | undefined : undefined; + const matched = matches(trigger?.if) && (!legacyConditions || conditionsMatch(legacyConditions, context as WorkflowRunContext)); + const key = stringValue(resolve(workflow.run?.idempotency?.key ?? `${workflow.id}:${event.id}:${trigger?.id ?? "manual"}`), "Idempotency key"); + const groupValue = workflow.run?.concurrency?.group; + group = stringValue(resolve(legacy && groupValue === "workflow" ? workflow.id : groupValue ?? workflow.id), "Concurrency group"); + const revision = await digest(workflow); + detail.runtime = { + type: "runtime_run", id: runId, workflow_id: workflow.id, workflow_version: workflow.version, + workflow_revision: revision, event_id: event.id, + event_contract: { id: event.type, version: event.mdbasecontractversion, digest: event.mdbasecontractdigest }, + admitted_plan: { profile_version: "0.2", workflow_revision: revision, event: { + contract: { id: event.type, version: event.mdbasecontractversion, digest: event.mdbasecontractdigest }, + source: { application: event.mdbaseapplication, implementation: event.mdbaseimplementation, version: event.mdbaseimplementationversion }, + source_declaration_digest: this.bridge()?.interopDescription()?.event_sources.find((source) => + source.source.application === event.mdbaseapplication && source.source.implementation === event.mdbaseimplementation + && source.contracts.some(({ resolved }) => resolved.digest === event.mdbasecontractdigest))?.declaration_digest, + }, steps: [] }, + trigger_id: trigger?.id ?? "manual", idempotency_key: key, concurrency_group: group, + status: "queued", created_at: now.toISOString(), updated_at: now.toISOString(), + }; + if (!matched) return await finish("cancelled", "Trigger condition did not match."); + const bindings = await Promise.all(workflow.steps.map((step) => this.binding(step))); + detail.runtime.admitted_plan.steps = bindings; + this.checkCapabilities(workflow.requires?.capabilities); + const minimumInterval = !options.manual && trigger?.minimum_interval ? { key: `${workflow.id}:${trigger.id}`, minimumIntervalMs: parseDurationMs(trigger.minimum_interval, 0) } : undefined; + if (!options.dryRun && !await this.state.reserve(key, Date.now(), minimumInterval)) return await finish("cancelled", "Duplicate idempotency key or minimum interval has not elapsed."); + const policy = workflow.run?.concurrency?.policy ?? "skip"; + const existing = [...this.groups.get(group) ?? []]; + if (policy === "skip" && existing.length) return await finish("cancelled", "Concurrency group is active."); + const cancel = new AbortController(); + const done = new Promise((resolve) => { release = resolve; }); + active = { cancel, done }; + const members = this.groups.get(group) ?? new Set(); + members.add(active); + this.groups.set(group, members); + await this.persist(detail); + if (policy === "replace") for (const previous of existing) previous.cancel.abort("replaced"); + if (policy === "queue" || policy === "replace") await Promise.all(existing.map(({ done }) => done)); + if (cancel.signal.aborted) return await finish("cancelled", "Replaced by a newer run."); + const timeout = workflow.run?.limits?.timeout; + const deadline = timeout ? Date.now() + parseDurationMs(timeout, 0) : undefined; + if (deadline !== undefined) timer = window.setTimeout(() => cancel.abort("deadline"), Math.max(0, deadline - Date.now())); + detail.runtime.status = "running"; + detail.runtime.started_at = new Date().toISOString(); + await this.persist(detail); + let failed = false; + for (const [index, step] of workflow.steps.entries()) { + if (cancel.signal.aborted || (deadline !== undefined && Date.now() >= deadline)) { + return await finish(cancel.signal.reason === "replaced" ? "cancelled" : "failed", "Execution cancelled or deadline exceeded."); + } + const stepMatches = (activation = context): boolean => legacy && Array.isArray(extension(step).conditions) + ? conditionsMatch(extension(step).conditions as WorkflowCondition[], activation as WorkflowRunContext) + : matches(step.if, activation); + if (!step.for_each && !stepMatches()) { + (context.steps as Record)[step.id] = { status: "cancelled", output: null }; + continue; + } + const items: unknown = step.for_each ? resolve(step.for_each.items) : [undefined]; + if (!Array.isArray(items)) throw new Error(`for_each of ${step.id} must resolve to a list.`); + if (items.length > (workflow.run?.limits?.max_items ?? 25)) throw new Error(`for_each exceeds max_items for ${step.id}.`); + const outputs: unknown[] = []; + for (const [itemIndex, item] of (items as unknown[]).entries()) { + if (cancel.signal.aborted || (deadline !== undefined && Date.now() >= deadline)) break; + const activation = step.for_each ? { ...context, item, ...(step.for_each.as ? { [step.for_each.as]: item } : {}) } : context; + if (step.for_each && !stepMatches(activation)) continue; + const input = resolve(step.input ?? {}, activation); + this.checkCapabilities(workflow.requires?.capabilities); + this.checkCapabilities(step.requires?.capabilities); + const result = await this.dispatch(step, bindings[index], input, detail, key, event, step.for_each ? itemIndex : undefined, deadline, cancel.signal); + detail.steps.push(result); + outputs.push(result.output); + (context.steps as Record)[step.id] = { status: result.status === "success" && !legacy ? "succeeded" : result.status, output: step.for_each ? outputs : result.output }; + if (result.status === "failed") { + failed = true; + const attemptStatus = detail.attempts?.[detail.attempts.length - 1]?.status; + if (attemptStatus === "indeterminate") return await finish("indeterminate", result.error); + if (attemptStatus === "cancelled") return await finish("cancelled", result.error); + if (workflow.run?.on_error !== "continue") return await finish("failed", result.error); + break; + } + await this.persist(detail); + } + if (step.for_each && items.length === 0) (context.steps as Record)[step.id] = { status: "succeeded", output: [] }; + if (step.action.id === "workflow.stop") break; + } + if (cancel.signal.aborted || (deadline !== undefined && Date.now() >= deadline)) return await finish(cancel.signal.reason === "replaced" ? "cancelled" : "failed", "Execution cancelled or deadline exceeded."); + return await finish(failed ? "failed" : "succeeded"); + } catch (error) { + return await finish("failed", error instanceof Error ? error.message : String(error)); + } finally { + if (timer) window.clearTimeout(timer); + if (active) { + this.groups.get(group)?.delete(active); + if (!this.groups.get(group)?.size) this.groups.delete(group); + } + release?.(); + } + } + + private async binding(step: RuntimeWorkflowStep): Promise { + if (this.registry.get(step.action.id) && !step.provider) { + const artifact: ActionContractArtifact = { + kind: "mdbase.contract", contract_type: "action", id: step.action.id, version: "1.0.0", + input_schema: { dialect: "json-schema-2020-12", value: { type: "object" } }, + }; + const contract = await exactContractReference(artifact); + if (step.action.digest && step.action.digest !== contract.digest) throw new Error(`Contract digest conflict: ${step.action.id}`); + if (!versionMatches(contract.version, step.action.version)) throw new Error(`Unsupported local action version: ${step.action.version}`); + return { id: step.id, contract, provider: LOCAL_EXECUTOR, provider_declaration_digest: await digest({ provider: LOCAL_EXECUTOR, handler: artifact }), handler_id: step.action.id }; + } + const providers = this.bridge()?.interopDescription()?.action_providers ?? []; + const candidates = providers.flatMap((provider) => provider.handlers + .filter((handler) => handler.resolved.id === step.action.id && versionMatches(handler.resolved.version, step.action.version) + && (!step.action.digest || handler.resolved.digest === step.action.digest) + && Object.entries(step.provider ?? {}).every(([key, value]) => provider.provider[key as keyof typeof provider.provider] === value)) + .map((handler) => ({ id: step.id, contract: handler.resolved, provider: provider.provider, provider_declaration_digest: provider.declaration_digest, handler_id: handler.handler_id }))); + if (candidates.length !== 1) throw new Error(`${candidates.length ? "ambiguous_provider" : "no_provider"}: ${step.action.id}`); + return candidates[0]; + } + + private checkCapabilities(capabilities?: string[]): void { + for (const capability of capabilities ?? []) { + if (!this.tasknotes()?.hasCapability(capability)) throw new Error(`capability_denied: ${capability}`); + } + } + + private async dispatch(step: RuntimeWorkflowStep, binding: AdmittedActionBinding, input: unknown, run: WorkflowRunDetail, key: string, event: CloudEvent, itemIndex: number | undefined, deadline: number | undefined, signal: AbortSignal): Promise { + const startedAt = new Date().toISOString(); + const requestId = `${run.runId}:${step.id}${itemIndex === undefined ? "" : `:${itemIndex}`}`; + const idempotencyKey = `${key}:${step.id}${itemIndex === undefined ? "" : `:${itemIndex}`}`; + const request: InvokeActionInput = { + request_id: requestId, contract: binding.contract, input, idempotency_key: idempotencyKey, + correlation_id: event.correlationid ?? run.runId, causation_id: event.id, subject: event.subject, + requested_provider: { application: binding.provider.application, implementation: binding.provider.implementation, ...(binding.provider.instance_id ? { instance_id: binding.provider.instance_id } : {}) }, ...(deadline === undefined ? {} : { deadline: new Date(deadline).toISOString() }), + }; + const attempt: RuntimeAttemptRecord = { + type: "runtime_action_attempt", id: `attempt:${crypto.randomUUID()}`, run_id: run.runId, step_id: step.id, + request_id: requestId, invocation_id: `pending:${requestId}`, attempt_id: `pending:${requestId}`, + contract: binding.contract, provider: binding.provider, provider_declaration_digest: binding.provider_declaration_digest, + handler_id: binding.handler_id, idempotency_key: idempotencyKey, status: "admitted", request: { kind: "mdbase.action.request", profile_version: "0.1", caller: this.bridge()?.connectInterop()?.identity ?? LOCAL_EXECUTOR, created_at: startedAt, ...request }, + created_at: startedAt, updated_at: startedAt, + "x-tasknotes": { local: !step.provider && Boolean(this.registry.get(step.action.id)), dry_run: run.dryRun, item_index: itemIndex }, + }; + run.attempts?.push(attempt); + await this.persist(run); + const result: StepRunDetail = { id: step.id, type: step.action.id, status: "success", startedAt, sourceInput: step.input, input, itemIndex }; + let dispatched = false; + try { + attempt.status = "dispatching"; + await this.persist(run); + if (signal.aborted || (deadline !== undefined && Date.now() >= deadline)) throw new Error("Execution cancelled or deadline exceeded."); + const local = !step.provider ? this.registry.get(step.action.id) : undefined; + if (run.dryRun) result.output = { dryRun: true, wouldInvoke: step.action.id, input }; + else if (local) { + result.output = toWorkflowData(await local.run(input, createStepExecutionContext(run.runId, false, this.tasknotes(), this.app(), "tasknotes-workflows"))); + } else { + const bridge = this.bridge(); + if (!bridge) throw new Error("Interop bridge unavailable."); + const current = await this.binding(step); + if (JSON.stringify(current) !== JSON.stringify(binding)) throw new Error("Admitted provider declaration changed."); + if (signal.aborted || (deadline !== undefined && Date.now() >= deadline)) throw new Error("Execution cancelled or deadline exceeded."); + const cancel = (): void => { + void (async () => { + attempt["x-tasknotes"] = { ...extension(attempt), cancellation_requested_at: new Date().toISOString(), reason: signal.reason as unknown }; + await this.persist(run); + await bridge.connectInterop()?.cancelAction(requestId, String(signal.reason)); + })().catch(console.error); + }; + signal.addEventListener("abort", cancel, { once: true }); + try { + dispatched = true; + const outcome = await bridge.invokeContractAction(request); + attempt.outcome = outcome; + attempt.invocation_id = outcome.invocation_id; + attempt.attempt_id = outcome.attempt_id; + attempt.status = outcome.status === "outcome_indeterminate" ? "indeterminate" : outcome.status; + result.evidence = outcome; + if (outcome.status !== "succeeded") throw new Error(`${outcome.error.code}: ${outcome.error.message}`); + result.output = toWorkflowData(outcome.output); + } finally { signal.removeEventListener("abort", cancel); } + } + attempt.status = "succeeded"; + } catch (error) { + if (!attempt.outcome) attempt.status = dispatched ? "indeterminate" : "failed"; + result.status = "failed"; + result.error = error instanceof Error ? error.message : String(error); + } + result.endedAt = new Date().toISOString(); + result.durationMs = Date.now() - new Date(startedAt).getTime(); + attempt.updated_at = result.endedAt; + attempt.completed_at = result.endedAt; + await this.persist(run); + return result; + } +} + +export async function localCloudEvent(options: WorkflowRunOptions, contractId?: string): Promise { + const payload = toWorkflowData(options.trigger) as WorkflowRunOptions["trigger"]; + const type = contractId ?? `tasknotes-workflows.${payload.triggerType ?? payload.type}`; + const artifact: EventContractArtifact = { + kind: "mdbase.contract", contract_type: "event", id: type, version: "1.0.0", + data_schema: { dialect: "json-schema-2020-12", value: { type: "object" } }, + }; + const reference = await exactContractReference(type === "mdbase.record.modified" ? RECORD_MODIFIED_CONTRACT : artifact); + return { + specversion: "1.0", id: `event:${crypto.randomUUID()}`, source: "obsidian://tasknotes-workflows", type, + time: payload.actualAt ?? new Date().toISOString(), datacontenttype: "application/json", dataschema: `${type}/1.0.0`, + data: payload.data ?? payload, subject: payload.path, mdbaseprofile: "0.1", mdbasecontractversion: "1.0.0", + mdbasecontractdigest: reference.digest, mdbaseapplication: LOCAL_EXECUTOR.application, + mdbaseimplementation: LOCAL_EXECUTOR.implementation, mdbaseimplementationversion: LOCAL_EXECUTOR.version, + ...(payload.correlationId ? { correlationid: payload.correlationId } : {}), + }; +} +function extension(value: unknown): Record { + return (value as Record> | undefined)?.["x-tasknotes"] ?? {}; +} +function scheduleTimezone(trigger: unknown): string { + const timezone = extension(trigger).timezone; + return typeof timezone === "string" && timezone !== "local" ? timezone : Intl.DateTimeFormat().resolvedOptions().timeZone; +} +function stringValue(value: unknown, label: string): string { + if (typeof value !== "string") throw new Error(`${label} must evaluate to a string.`); + return value; +} +function versionMatches(version: string, requirement: string): boolean { + return satisfies(version, requirement); +} diff --git a/src/runtimeHistory.ts b/src/runtimeHistory.ts new file mode 100644 index 0000000..f41b973 --- /dev/null +++ b/src/runtimeHistory.ts @@ -0,0 +1,67 @@ +import { portableDigest, type ExactContractReference, type ImplementationIdentity, type ActionOutcome } from "@callumalpass/mdbase-interop"; +import type { AdmittedWorkflowPlan } from "@callumalpass/mdbase-runtime"; +import type { WorkflowRunDetail } from "./types"; + +export type RuntimeRunStatus = "queued" | "running" | "waiting" | "succeeded" | "failed" | "cancelled" | "indeterminate"; +export type RuntimeAttemptStatus = "admitted" | "dispatching" | "succeeded" | "rejected" | "failed" | "cancelled" | "indeterminate"; +export interface RuntimeRunRecord { + type: "runtime_run"; + id: string; + workflow_id: string; + workflow_version: string; + workflow_revision: string; + event_id: string; + event_contract: ExactContractReference; + admitted_plan: Omit & { event: Omit & { source_declaration_digest?: string } }; + trigger_id: string; + idempotency_key: string; + concurrency_group: string; + status: RuntimeRunStatus; + created_at: string; + updated_at: string; + started_at?: string; + finished_at?: string; + "x-tasknotes"?: unknown; +} +export interface RuntimeAttemptRecord { + type: "runtime_action_attempt"; + id: string; + run_id: string; + step_id: string; + request_id: string; + invocation_id: string; + attempt_id: string; + contract: ExactContractReference; + provider: ImplementationIdentity; + provider_declaration_digest: string; + handler_id: string; + idempotency_key: string; + status: RuntimeAttemptStatus; + request: Record; + outcome?: ActionOutcome; + created_at: string; + updated_at: string; + completed_at?: string; + "x-tasknotes"?: unknown; +} +export const LOCAL_EXECUTOR: ImplementationIdentity = { + application: "tasknotes-workflows", implementation: "obsidian-client", version: "0.1.6", +}; +export const digest = (value: unknown): Promise => portableDigest(value); + +/** Keep the existing UI DTO inside a named extension, not the portable fields. */ +export function historyRecord(detail: WorkflowRunDetail): unknown { + if (!detail.runtime) return detail; + const { runtime, attempts, ...view } = detail; + return { ...runtime, "x-tasknotes": { ...asRecord(runtime["x-tasknotes"]), view, attempts } }; +} +export function historyDetail(record: unknown): WorkflowRunDetail { + const raw = asRecord(record); + if (raw.type !== "runtime_run") return record as WorkflowRunDetail; + const extension = asRecord(raw["x-tasknotes"]); + const { "x-tasknotes": _extension, ...runtime } = raw; + return { ...asRecord(extension.view), runtime, attempts: extension.attempts } as unknown as WorkflowRunDetail; +} +function asRecord(value: unknown): Record { + return value && typeof value === "object" ? value as Record : {}; +} diff --git a/src/runtimeState.ts b/src/runtimeState.ts new file mode 100644 index 0000000..e3b8da1 --- /dev/null +++ b/src/runtimeState.ts @@ -0,0 +1,51 @@ +import type { App } from "obsidian"; + +export const RESERVATION_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; +interface RuntimeState { + reservations: Record; + lastFire: Record; + lastAdmission: Record; +} + +/** One serialized state file, independent of history retention and data.json. */ +export class RuntimeStateStore { + private state: RuntimeState = { reservations: {}, lastFire: {}, lastAdmission: {} }; + private queue: Promise = Promise.resolve(); + private loaded = false; + constructor(private readonly app: App | null = null) {} + + update(operation: (state: RuntimeState) => T): Promise { + const result = this.queue.then(async () => { + const path = `${this.app?.vault.configDir}/plugins/tasknotes-workflows/runtime-state.json`; + if (!this.loaded) { + if (this.app && await this.app.vault.adapter.exists(path)) { + this.state = JSON.parse(await this.app.vault.adapter.read(path)) as RuntimeState; + } + this.loaded = true; + } + const next = structuredClone(this.state); + const value = operation(next); + if (this.app) await this.app.vault.adapter.write(path, JSON.stringify(next)); + this.state = next; + return value; + }); + this.queue = result.catch(() => undefined); + return result; + } + + reserve(key: string, now = Date.now(), trigger?: { key: string; minimumIntervalMs: number }): Promise { + return this.update((state) => { + for (const [candidate, expires] of Object.entries(state.reservations)) { + if (expires <= now) delete state.reservations[candidate]; + } + if (Object.prototype.hasOwnProperty.call(state.reservations, key)) return false; + if (trigger) { + const last = state.lastAdmission[trigger.key]; + if (last !== undefined && now - last < trigger.minimumIntervalMs) return false; + state.lastAdmission[trigger.key] = now; + } + Object.defineProperty(state.reservations, key, { value: now + RESERVATION_RETENTION_MS, enumerable: true, configurable: true, writable: true }); + return true; + }); + } +} diff --git a/src/scheduler.ts b/src/scheduler.ts index 25665f4..3a2d392 100644 --- a/src/scheduler.ts +++ b/src/scheduler.ts @@ -1,3 +1,7 @@ +import { collectionSettings } from "./collection"; +import { RuntimeStateStore } from "./runtimeState"; +import { localCloudEvent } from "./runtimeExecutor"; +import { digest } from "./runtimeHistory"; import { Notice, TFile, type EventRef, type Plugin } from "obsidian"; import type { CloudEvent } from "@callumalpass/mdbase-interop"; import { cronMatches } from "./cron"; @@ -25,8 +29,8 @@ export class WorkflowScheduler { private taskEventRefs: EventRef[] = []; private intervalIds: number[] = []; private cleanupCallbacks: Array<() => void> = []; - private cronLastRun = new Map(); - private intervalLastRun = new Map(); + private debounceTimers = new Map void }>(); + private metadataSnapshots = new Map>(); private registrationEpoch = 0; constructor( @@ -34,11 +38,14 @@ export class WorkflowScheduler { private readonly bridge: TaskNotesBridge, private readonly getSettings: () => TaskNotesWorkflowsSettings, private readonly getWorkflows: () => LoadedWorkflow[], - private readonly runWorkflow: RunWorkflow + private readonly runWorkflow: RunWorkflow, + private readonly automaticEnabled: () => boolean = () => true, + private readonly state = new RuntimeStateStore(), ) {} start(): void { this.stop(); + if (!this.automaticEnabled()) return; const epoch = this.registrationEpoch; this.registerTaskEvents(); this.registerContractEvents(epoch); @@ -48,6 +55,8 @@ export class WorkflowScheduler { stop(): void { this.registrationEpoch += 1; + for (const pending of this.debounceTimers.values()) { window.clearTimeout(pending.timer); pending.resolve(); } + this.debounceTimers.clear(); for (const ref of this.taskEventRefs) { this.bridge.api?.events.off(ref); } @@ -161,6 +170,9 @@ export class WorkflowScheduler { }); this.cleanupCallbacks.push(() => this.plugin.app.workspace.offref(layoutChangeRef)); + for (const file of this.plugin.app.vault.getMarkdownFiles()) { + this.metadataSnapshots.set(file.path, structuredClone(this.plugin.app.metadataCache.getFileCache(file)?.frontmatter ?? {})); + } const metadataChangedRef = this.plugin.app.metadataCache.on("changed", (file, _data, cache) => { void this.handleMetadataEvent("changed", file, { cache }).catch(showError); }); @@ -195,12 +207,13 @@ export class WorkflowScheduler { private async handleTaskEvent(event: string, rawPayload: unknown): Promise { const payload = normalizeTaskNotesEventPayload(event, rawPayload); + payload.cloudEvent = await localCloudEvent({ trigger: payload }, event); for (const workflow of this.getWorkflows()) { if (!workflow.workflow?.enabled) continue; for (const trigger of workflow.workflow.triggers) { if (!isTaskNotesEventTrigger(trigger)) continue; if (!this.taskNotesTriggerMatches(trigger, payload)) continue; - await this.runWorkflow(workflow, { trigger: { ...payload, id: trigger.id } }); + await this.runAutomatic(workflow, { trigger: { ...payload, id: trigger.id } }); } } } @@ -208,12 +221,13 @@ export class WorkflowScheduler { private async handleContractEvent(key: string, event: CloudEvent): Promise { const payload = normalizeContractEventPayload(event); for (const workflow of this.getWorkflows()) { - for (const trigger of workflow.workflow?.triggers ?? []) { + if (!workflow.workflow?.enabled) continue; + for (const trigger of workflow.workflow.triggers) { if (trigger.type !== "contract.event") continue; if (contractTriggerKey(trigger) !== key) continue; if (trigger.source && trigger.source !== event.mdbaseapplication) continue; if (trigger.path && (!payload.path || !pathMatchesFilter(payload.path, trigger.path))) continue; - await this.runWorkflow(workflow, { trigger: { ...payload, id: trigger.id } }); + await this.runAutomatic(workflow, { trigger: { ...payload, id: trigger.id } }); } } } @@ -223,8 +237,8 @@ export class WorkflowScheduler { for (const workflow of this.getWorkflows()) { if (!workflow.workflow?.enabled) continue; for (const trigger of workflow.workflow.triggers) { - if (trigger.type === "cron" && this.shouldRunCron(workflow.workflow.id, trigger.id, trigger.schedule, now)) { - await this.runWorkflow(workflow, { + if (trigger.type === "cron" && await this.shouldRunCron(workflow.workflow.id, trigger.id, trigger.schedule, now, trigger.timezone, trigger.catchUp)) { + await this.runAutomatic(workflow, { trigger: { type: "cron", triggerType: "cron", @@ -235,8 +249,8 @@ export class WorkflowScheduler { }, }); } - if (trigger.type === "interval" && this.shouldRunInterval(workflow.workflow.id, trigger.id, trigger.every)) { - await this.runWorkflow(workflow, { + if (trigger.type === "interval" && await this.shouldRunInterval(workflow.workflow.id, trigger.id, trigger.every)) { + await this.runAutomatic(workflow, { trigger: { type: "interval", triggerType: "interval", @@ -262,7 +276,7 @@ export class WorkflowScheduler { for (const trigger of workflow.workflow.triggers) { if (trigger.type !== "obsidian.vault" || trigger.event !== event) continue; if (!pathMatchesFilter(file.path, trigger.path)) continue; - await this.runWorkflow(workflow, { + await this.runAutomatic(workflow, { trigger: { type: event, triggerType: "obsidian.vault", @@ -288,7 +302,7 @@ export class WorkflowScheduler { if (trigger.type !== "obsidian.workspace" || trigger.event !== event) continue; if (file && !pathMatchesFilter(file.path, trigger.path)) continue; if (!file && trigger.path) continue; - await this.runWorkflow(workflow, { + await this.runAutomatic(workflow, { trigger: { type: event, triggerType: "obsidian.workspace", @@ -308,16 +322,31 @@ export class WorkflowScheduler { file: TFile | null, data?: unknown ): Promise { + let cloudEvent: CloudEvent | undefined; + if (event === "changed" && file) { + const before = this.metadataSnapshots.get(file.path) ?? {}; + const cache = (data as { cache?: { frontmatter?: Record } } | undefined)?.cache; + const after = structuredClone(cache?.frontmatter ?? {}); + delete after.position; + delete before.position; + this.metadataSnapshots.set(file.path, after); + const changed_fields = [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key])); + const keys = (await collectionSettings(this.plugin.app))?.typeKeys ?? ["type", "types"]; + const types = (record: Record): string[] => [...new Set(keys.flatMap((key) => typeof record[key] === "string" ? [record[key]] : Array.isArray(record[key]) ? record[key] as unknown[] : []).filter((value): value is string => typeof value === "string"))]; + data = { path: file.path, before, after, changed_fields, previous_revision: await digest(before), revision: await digest(after), previous_types: types(before), types: types(after) }; + cloudEvent = await localCloudEvent({ trigger: { type: event, data, path: file.path } }, "mdbase.record.modified"); + } for (const workflow of this.getWorkflows()) { if (!workflow.workflow?.enabled) continue; for (const trigger of workflow.workflow.triggers) { if (trigger.type !== "obsidian.metadata" || trigger.event !== event) continue; if (file && !pathMatchesFilter(file.path, trigger.path)) continue; if (!file && trigger.path) continue; - await this.runWorkflow(workflow, { + await this.runAutomatic(workflow, { trigger: { type: event, triggerType: "obsidian.metadata", + cloudEvent, id: trigger.id, event, path: file?.path, @@ -346,32 +375,65 @@ export class WorkflowScheduler { return true; } - private shouldRunCron( - workflowId: string, - triggerId: string, - schedule: string, - now: Date - ): boolean { - if (!cronMatches(schedule, now)) return false; - const key = `${workflowId}:${triggerId}`; - const minuteKey = now.toISOString().slice(0, 16); - if (this.cronLastRun.get(key) === minuteKey) return false; - this.cronLastRun.set(key, minuteKey); - return true; + private async runAutomatic(workflow: LoadedWorkflow, options: WorkflowRunOptions): Promise { + if (!this.automaticEnabled() || !workflow.workflow?.enabled) return; + const trigger = workflow.workflow.triggers.find(({ id }) => id === options.trigger.id); + const key = `${workflow.workflow.id}:${trigger?.id ?? "unknown"}`; + const execute = async (): Promise => { + if (!this.automaticEnabled()) return; + if (trigger?.minimumInterval && !workflow.runtime) { + const interval = parseDurationMs(trigger.minimumInterval, 0); + const admitted = await this.state.update((state) => { + const now = Date.now(); + if (state.lastAdmission[key] !== undefined && now - state.lastAdmission[key] < interval) return false; + state.lastAdmission[key] = now; + return true; + }); + if (!admitted) return; + } + await this.runWorkflow(workflow, options); + }; + const delay = parseDurationMs(trigger?.debounce, 0); + if (!delay) return execute(); + const previous = this.debounceTimers.get(key); + if (previous) { window.clearTimeout(previous.timer); previous.resolve(); } + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + this.debounceTimers.delete(key); + void execute().then(resolve, reject); + }, delay); + this.debounceTimers.set(key, { timer, resolve }); + }); } - private shouldRunInterval(workflowId: string, triggerId: string, every: string): boolean { - const interval = Math.max( - parseDurationMs(every, this.getSettings().minIntervalMs), - this.getSettings().minIntervalMs - ); - const key = `${workflowId}:${triggerId}`; - const now = Date.now(); - const lastRun = this.intervalLastRun.get(key) ?? 0; - if (now - lastRun < interval) return false; - this.intervalLastRun.set(key, now); - return true; + private async shouldRunCron(workflowId: string, triggerId: string, schedule: string, now: Date, timezone?: string, catchUp = true): Promise { + return this.state.update((state) => { + const key = `cron:${workflowId}:${triggerId}`; + const minute = Math.floor(now.getTime() / 60_000) * 60_000; + const last = state.lastFire[key]; + if (last === minute) return false; + let due = cronMatches(schedule, now, timezone); + if (!due && catchUp && last !== undefined) { + for (let instant = last + 60_000; instant < minute; instant += 60_000) { + if (cronMatches(schedule, new Date(instant), timezone)) { due = true; break; } + } + } + state.lastFire[key] = minute; + return due; + }); } + + private async shouldRunInterval(workflowId: string, triggerId: string, every: string): Promise { + const interval = Math.max(parseDurationMs(every, this.getSettings().minIntervalMs), this.getSettings().minIntervalMs); + return this.state.update((state) => { + const key = `interval:${workflowId}:${triggerId}`; + const now = Date.now(); + if (state.lastFire[key] !== undefined && now - state.lastFire[key] < interval) return false; + state.lastFire[key] = now; + return true; + }); + } + } function normalizeTaskNotesEventPayload(event: string, rawPayload: unknown): WorkflowTriggerPayload { @@ -387,6 +449,7 @@ function normalizeTaskNotesEventPayload(event: string, rawPayload: unknown): Wor ? (payload.changes as Record) : undefined, source: typeof payload.source === "string" ? payload.source : undefined, + taskId: typeof payload.taskId === "string" ? payload.taskId : undefined, correlationId: typeof payload.correlationId === "string" ? payload.correlationId : undefined, path: typeof payload.taskPath === "string" ? payload.taskPath : undefined, data: payload, @@ -396,13 +459,14 @@ function normalizeTaskNotesEventPayload(event: string, rawPayload: unknown): Wor function normalizeContractEventPayload(event: CloudEvent): WorkflowTriggerPayload { const data = isRecord(event.data) ? event.data : {}; - const path = typeof data.task_path === "string" + const path = typeof data.path === "string" ? data.path : typeof data.task_path === "string" ? data.task_path : typeof event.subject === "string" ? event.subject : undefined; return { type: event.type, + cloudEvent: event, triggerType: "contract.event", event: event.type, path, diff --git a/src/settingsTab.ts b/src/settingsTab.ts index 1a8c9e2..0fbffd5 100644 --- a/src/settingsTab.ts +++ b/src/settingsTab.ts @@ -102,6 +102,13 @@ export class WorkflowsSettingsTab extends PluginSettingTab { ); new Setting(containerEl).setName(this.workflowsPlugin.t("settings.triggers.heading")).setHeading(); + new Setting(containerEl).setDesc(this.workflowsPlugin.t("settings.interop")); + new Setting(containerEl) + .setName(this.workflowsPlugin.t("settings.deviceExecutor.name")) + .setDesc(this.workflowsPlugin.t("settings.deviceExecutor.description")) + .addToggle((toggle) => toggle.setValue(this.workflowsPlugin.runOnThisDevice).onChange((value) => { + void this.workflowsPlugin.setRunOnThisDevice(value); + })); new Setting(containerEl) .setName(this.workflowsPlugin.t("settings.triggers.tasknotesEvents.name")) diff --git a/src/stepRegistry.ts b/src/stepRegistry.ts index c9e6886..d134f72 100644 --- a/src/stepRegistry.ts +++ b/src/stepRegistry.ts @@ -198,7 +198,9 @@ export function shouldRunStep(step: WorkflowStep, context: WorkflowRunContext): function createDefaultSteps(): StepDefinition[] { return [ taskReadStep("task.get", "Get task", "Reads one task by path.", async (api, input) => ({ - task: await api.tasks.get(requiredString(input, "task")), + task: typeof asRecord(input).taskId === "string" && api.tasks.getById + ? await api.tasks.getById(requiredString(input, "taskId")) + : await (api.tasks.getByPath ?? api.tasks.get)(requiredString(input, "task")), }), { inputFields: [taskPathField()], examples: [{ label: "Read the triggering task", input: { task: "{{event.after.path}}" } }], @@ -552,7 +554,7 @@ function createDefaultSteps(): StepDefinition[] { type: "json", required: true, wide: true, - defaultValue: { minutes: 25, date: "{{today}}" }, + defaultValue: { startTime: "{{now}}", description: "Workflow time entry" }, }, ], }), @@ -841,7 +843,14 @@ function taskMutationStep( if (context.dryRun) { return { dryRun: true, wouldRun: type, input }; } - return run(requireTaskNotes(context.tasknotes), input, context); + const api = requireTaskNotes(context.tasknotes); + const record = asRecord(input); + if (typeof record.taskId === "string" && api.tasks.getById) { + const task = await api.tasks.getById(record.taskId); + if (!task || typeof task.path !== "string") throw new Error(`Task not found: ${record.taskId}`); + return run(api, { ...record, task: task.path }, context); + } + return run(api, input, context); }, }; } diff --git a/src/template.ts b/src/template.ts index ea6c9cb..826349a 100644 --- a/src/template.ts +++ b/src/template.ts @@ -58,7 +58,7 @@ export function readReference(root: unknown, expression: string): unknown { return current; } -function parseReferencePath(path: string): string[] { +export function parseReferencePath(path: string): string[] { const parts: string[] = []; let index = 0; const readIdentifier = (): string | null => { diff --git a/src/types.ts b/src/types.ts index e9dfbe0..97b0eb6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,4 @@ +import type { RuntimeWorkflow } from "@callumalpass/mdbase-runtime"; import type { App, EventRef, TFile } from "obsidian"; import type { ProviderSelector } from "@callumalpass/mdbase-interop"; @@ -27,6 +28,7 @@ export interface WorkflowFile { } export interface LoadedWorkflow { + runtime?: RuntimeWorkflow; file: TFile; body: string; source: string; @@ -45,6 +47,9 @@ export interface WorkflowDiagnostic { } export interface WorkflowDefinition { + expressionLanguage?: "cel"; + /** Original record retained by the editor; execution uses LoadedWorkflow.runtime. */ + runtime?: RuntimeWorkflow; type: "workflow"; schemaVersion: 1; id: string; @@ -217,6 +222,8 @@ export interface WorkflowDebugSettings { } export interface WorkflowTriggerPayload { + cloudEvent?: import("@callumalpass/mdbase-interop").CloudEvent; + taskId?: string; type: string; id?: string; triggerType?: string; @@ -265,6 +272,8 @@ export interface WorkflowStepResult { } export interface WorkflowRunDetail { + runtime?: import("./runtimeHistory").RuntimeRunRecord; + attempts?: import("./runtimeHistory").RuntimeAttemptRecord[]; runId: string; workflowId: string; workflowName: string; @@ -422,6 +431,8 @@ export interface TaskNotesRuntimeApi { }; tasks: { get(path: string): Promise | null>; + getByPath?(path: string): Promise | null>; + getById?(id: string): Promise | null>; list(query?: TaskNotesRuntimeTaskQuery): Promise[]>; create(input: Record, context?: TaskNotesMutationContext): Promise>; update(path: string, patch: Record, context?: TaskNotesMutationContext): Promise>; diff --git a/src/workflowEditModal.ts b/src/workflowEditModal.ts index 32db08c..b18c9f9 100644 --- a/src/workflowEditModal.ts +++ b/src/workflowEditModal.ts @@ -193,6 +193,11 @@ export class WorkflowEditModal extends Modal { } override onOpen(): void { + if (this.loaded?.runtime && (this.loaded.runtime["x-tasknotes"] as Record | undefined)?.format_version !== 1) { + void this.plugin.openWorkflowFile(this.loaded.file); + super.close(); + return; + } this.modalEl.addClass("tnw-modal"); this.render(); } diff --git a/src/workflowEngine.ts b/src/workflowEngine.ts index 71b9585..a44dd13 100644 --- a/src/workflowEngine.ts +++ b/src/workflowEngine.ts @@ -1,3 +1,5 @@ +import { RuntimeWorkflowExecutor } from "./runtimeExecutor"; +import { RuntimeStateStore } from "./runtimeState"; import { conditionsMatch } from "./conditions"; import { todayString } from "./duration"; import { createStepExecutionContext, shouldRunStep, StepRegistry } from "./stepRegistry"; @@ -32,6 +34,7 @@ const ENGINE_FALLBACK_MESSAGES: Record = { }; export class WorkflowEngine { + private readonly runtimeExecutor: RuntimeWorkflowExecutor; private readonly runningGroups = new Set(); constructor( @@ -40,12 +43,15 @@ export class WorkflowEngine { private readonly obsidian: () => App | null = () => null, private readonly translate: TranslateFn = (key) => key, private readonly interopBridge: () => TaskNotesBridge | null = () => null, - ) {} + state?: RuntimeStateStore, + persist?: (detail: WorkflowRunDetail) => Promise, + ) { this.runtimeExecutor = new RuntimeWorkflowExecutor(stepRegistry, tasknotes, obsidian, interopBridge, state, persist); } async runWorkflow( loadedWorkflow: LoadedWorkflow, options: WorkflowRunOptions ): Promise { + if (loadedWorkflow.runtime) return this.runtimeExecutor.run(loadedWorkflow, options); const workflow = loadedWorkflow.workflow; if (!workflow) { throw new Error(this.t("engine.workflowInvalid", { path: loadedWorkflow.file.path })); diff --git a/src/workflowFormat.ts b/src/workflowFormat.ts index d195f89..188154c 100644 --- a/src/workflowFormat.ts +++ b/src/workflowFormat.ts @@ -1,3 +1,4 @@ +import { workflowToCelRecord } from "./migrateExpressions"; import { validateRuntimeRecord, type RuntimeWorkflow } from "@callumalpass/mdbase-runtime"; import { DEFAULT_SOURCE, LEGACY_WORKFLOW_TYPE, RUNTIME_WORKFLOW_TYPE, WORKFLOW_TYPE } from "./constants"; import type { @@ -82,6 +83,7 @@ export function runtimeRecordToTaskNotesInput(record: Dict): Dict { } export function workflowToRuntimeRecord(workflow: WorkflowDefinition): RuntimeWorkflow & Dict { + if (workflow.expressionLanguage === "cel" && !workflow.runtime) return workflowToCelRecord({ ...workflow, expressionLanguage: undefined }) as RuntimeWorkflow & Dict; assertRuntimeIdentifier(workflow.id, "workflow id"); const tasknotes = compact({ format_version: 1, @@ -115,6 +117,7 @@ export function workflowToRuntimeRecord(workflow: WorkflowDefinition): RuntimeWo }, [TASKNOTES_EXTENSION]: tasknotes, }; + if (workflow.runtime) Object.assign(record, workflow.runtime, { id: workflow.id, name: workflow.name, description: workflow.description, enabled: workflow.enabled }); const cleaned = removeUndefined(record); const diagnostics = validateRuntimeWorkflowRecord(cleaned); if (diagnostics.length > 0) { @@ -135,6 +138,7 @@ function runtimeTriggerToTaskNotesInput(raw: unknown): unknown { ...(type === "contract.event" ? { contract: event.id, version: event.version } : { event: runtimeEventForTaskNotesTrigger(type, event.id, tasknotes) }), + if: raw.if, debounce: raw.debounce, minimumInterval: raw.minimum_interval, extensions: otherExtensions(raw), @@ -174,6 +178,7 @@ function workflowTriggerToRuntimeRecord(trigger: WorkflowTrigger): Dict { id: eventId, version: trigger.type === "contract.event" ? trigger.version : "1.0.0", }), + if: (trigger as unknown as Dict).if, debounce: trigger.debounce, minimum_interval: trigger.minimumInterval, [TASKNOTES_EXTENSION]: tasknotes, @@ -223,6 +228,7 @@ function triggerTaskNotesExtension(trigger: WorkflowTrigger): Dict { function runtimeEventForWorkflowTrigger(trigger: WorkflowTrigger): string { if (trigger.type === "tasknotes.event") return trigger.event; + if (trigger.type === "obsidian.metadata" && trigger.event === "changed") return "mdbase.record.modified"; if (trigger.type === "contract.event") return trigger.contract; if (trigger.type === "cron") return "tasknotes-workflows.schedule.cron"; if (trigger.type === "interval") return "tasknotes-workflows.schedule.interval"; diff --git a/src/workflowMigration.ts b/src/workflowMigration.ts index 25c7bf1..20e61f0 100644 --- a/src/workflowMigration.ts +++ b/src/workflowMigration.ts @@ -1,17 +1,20 @@ +import { collectionSettings, normalizeWorkflowType } from "./collection"; import { normalizePath, TFile, type App } from "obsidian"; import { parseMarkdownFrontmatter, replaceMarkdownFrontmatter } from "./frontmatter"; import type { WorkflowRepository } from "./workflowRepository"; -import { parseWorkflowDefinition, workflowToFrontmatter } from "./workflowParser"; +import { migrateExpressions } from "./migrateExpressions"; +import { parseWorkflowDefinition } from "./workflowParser"; import type { WorkflowSourceFormat } from "./types"; export interface WorkflowMigrationCandidate { path: string; - sourceFormat: Exclude; + sourceFormat: Exclude; sourceSha256: string; targetSha256: string; source: string; target: string; diff: string; + warnings: string[]; } export interface WorkflowMigrationIssue { @@ -46,7 +49,7 @@ export class WorkflowMigrationService { const invalid: WorkflowMigrationIssue[] = []; for (const loaded of loadedWorkflows) { - if (loaded.sourceFormat === "runtime-v0.2" && loaded.workflow) { + if (loaded.sourceFormat === "runtime-v0.2" && loaded.workflow && (loaded.runtime?.["x-tasknotes"] as Record | undefined)?.format_version !== 1) { alreadyCanonical.push(loaded.file.path); continue; } @@ -57,16 +60,17 @@ export class WorkflowMigrationService { }); continue; } - if (loaded.sourceFormat !== "tasknotes-v1" && loaded.sourceFormat !== "tasknotes-v0.1") { + if (loaded.sourceFormat !== "tasknotes-v1" && loaded.sourceFormat !== "tasknotes-v0.1" && loaded.sourceFormat !== "runtime-v0.2") { invalid.push({ path: loaded.file.path, messages: ["The workflow format could not be migrated safely."] }); continue; } - const target = replaceMarkdownFrontmatter(loaded.source, workflowToFrontmatter(loaded.workflow)); + const { record, warnings } = migrateExpressions(loaded); + const target = replaceMarkdownFrontmatter(loaded.source, await this.repository.runtimeFrontmatter(record)); const parsedTarget = parseMarkdownFrontmatter(target); const verified = parsedTarget.error ? null - : parseWorkflowDefinition(parsedTarget.data, target); + : parseWorkflowDefinition(normalizeWorkflowType(parsedTarget.data, await collectionSettings(this.app)), target); if (!verified?.workflow || verified.sourceFormat !== "runtime-v0.2") { invalid.push({ path: loaded.file.path, @@ -84,6 +88,7 @@ export class WorkflowMigrationService { targetSha256: await sha256(target), source: loaded.source, target, + warnings, diff: replacementDiff(loaded.file.path, loaded.source, target), }); } diff --git a/src/workflowMigrationModal.ts b/src/workflowMigrationModal.ts index 559639f..82d7ea3 100644 --- a/src/workflowMigrationModal.ts +++ b/src/workflowMigrationModal.ts @@ -28,6 +28,7 @@ export class WorkflowMigrationModal extends Modal { for (const candidate of this.report.candidates) { const details = this.contentEl.createEl("details", { cls: "tnw-workflow-migration-file" }); details.createEl("summary", { text: candidate.path }); + if (candidate.warnings.length) details.createEl("p", { text: candidate.warnings.join("; ") }); details.createEl("pre", { text: candidate.diff }); } if (this.report.invalid.length > 0) { diff --git a/src/workflowNoteCard.ts b/src/workflowNoteCard.ts index 309ff25..32dd0d1 100644 --- a/src/workflowNoteCard.ts +++ b/src/workflowNoteCard.ts @@ -20,7 +20,7 @@ export function registerWorkflowNoteCards(plugin: TaskNotesWorkflowsPlugin): voi }, 100); plugin.registerMarkdownPostProcessor((_el, ctx) => { - if (!isWorkflowFrontmatter(ctx.frontmatter)) return; + if (!isWorkflowFrontmatter(ctx.frontmatter) && !plugin.workflows.some((loaded) => loaded.file.path === ctx.sourcePath)) return; scheduleReadingModeWorkflowCards(plugin, ctx.sourcePath); }, -10); @@ -294,6 +294,6 @@ function isWorkflowFrontmatter(frontmatter: unknown): boolean { frontmatter !== null && typeof frontmatter === "object" && "type" in frontmatter && - (frontmatter as { type?: unknown }).type === WORKFLOW_TYPE + [WORKFLOW_TYPE, "runtime_workflow", "tasknotes-workflow"].includes(String((frontmatter as { type?: unknown }).type)) ); } diff --git a/src/workflowParser.ts b/src/workflowParser.ts index a38ce1f..179613e 100644 --- a/src/workflowParser.ts +++ b/src/workflowParser.ts @@ -50,6 +50,7 @@ export function parseWorkflowDefinition( _source: string ): { workflow: WorkflowDefinition | null; + runtime?: import("@callumalpass/mdbase-runtime").RuntimeWorkflow; diagnostics: WorkflowDiagnostic[]; sourceFormat: WorkflowSourceFormat; } { @@ -75,6 +76,29 @@ export function parseWorkflowDefinition( return { workflow: null, diagnostics, sourceFormat }; } } + if (sourceFormat === "runtime-v0.2" && (data["x-tasknotes"] as Record | undefined)?.format_version !== 1) { + const runtime = data as unknown as import("@callumalpass/mdbase-runtime").RuntimeWorkflow; + const formatVersion = (runtime["x-tasknotes"] as Record | undefined)?.format_version; + if (formatVersion !== undefined && formatVersion !== 2) diagnostics.push({ severity: "error", path: "x-tasknotes.format_version", message: "Unsupported workflow expression format." }); + for (const [name, entries] of [["triggers", runtime.triggers], ["steps", runtime.steps]] as const) { + if (new Set(entries.map(({ id }) => id)).size !== entries.length) diagnostics.push({ severity: "error", path: name, message: `Duplicate ${name} IDs.` }); + } + if (diagnostics.some(({ severity }) => severity === "error")) return { workflow: null, diagnostics, sourceFormat }; + const projected = runtimeRecordToTaskNotesInput(data); + const workflow = { + ...projected, + runtime, + vars: runtime.vars ?? {}, + conditions: [], + steps: projected.steps as WorkflowStep[], + run: { + mode: "sequential", source: "tasknotes-workflows", onError: runtime.run?.on_error ?? "stop", + concurrency: { group: "workflow", policy: runtime.run?.concurrency?.policy ?? "skip" }, + limits: { maxItems: runtime.run?.limits?.max_items ?? 25, timeout: runtime.run?.limits?.timeout }, + }, + } as unknown as WorkflowDefinition; + return { workflow, runtime, diagnostics, sourceFormat }; + } const normalizedData = sourceFormat === "runtime-v0.2" ? runtimeRecordToTaskNotesInput(data) : normalizeLegacyWorkflowObject(data); @@ -156,7 +180,7 @@ export function parseWorkflowDefinition( extensions: collectExtensions(data, normalizedData, sourceFormat), }; - return { workflow, diagnostics, sourceFormat }; + return { workflow, runtime: sourceFormat === "runtime-v0.2" ? data as unknown as import("@callumalpass/mdbase-runtime").RuntimeWorkflow : undefined, diagnostics, sourceFormat }; } export function workflowToFrontmatter(workflow: WorkflowDefinition): string { diff --git a/src/workflowRepository.ts b/src/workflowRepository.ts index eca6b73..d14e30a 100644 --- a/src/workflowRepository.ts +++ b/src/workflowRepository.ts @@ -1,7 +1,10 @@ +import { collectionSettings, normalizeWorkflowType, runtimeFrontmatter } from "./collection"; +import { workflowToRuntimeRecord } from "./workflowFormat"; +import type { RuntimeWorkflow } from "@callumalpass/mdbase-runtime"; import { normalizePath, TFile, type App } from "obsidian"; import { parseMarkdownFrontmatter, replaceMarkdownFrontmatter } from "./frontmatter"; import { isMarkdownFile, isWorkflowPath, safePathSegment } from "./path"; -import { parseWorkflowDefinition, workflowToFrontmatter } from "./workflowParser"; +import { parseWorkflowDefinition } from "./workflowParser"; import type { LoadedWorkflow, TaskNotesWorkflowsSettings, @@ -46,9 +49,9 @@ export class WorkflowRepository { const parseDiagnostics: WorkflowDiagnostic[] = parsed.error ? [{ severity: "error", path: "$frontmatter", message: parsed.error }] : []; - const { workflow, diagnostics, sourceFormat } = parsed.error + const { workflow, runtime, diagnostics, sourceFormat } = parsed.error ? { workflow: null, diagnostics: [], sourceFormat: "unknown" as const } - : parseWorkflowDefinition(parsed.data, source); + : parseWorkflowDefinition(normalizeWorkflowType(parsed.data, await collectionSettings(this.app)), source); return { file, @@ -56,13 +59,16 @@ export class WorkflowRepository { source, sourceFormat, workflow, + runtime, diagnostics: [...parseDiagnostics, ...diagnostics], }; } + async runtimeFrontmatter(record: RuntimeWorkflow): Promise { return runtimeFrontmatter(this.app, record); } + async saveWorkflow(file: TFile, workflow: WorkflowDefinition): Promise { const source = await this.app.vault.read(file); - const updated = replaceMarkdownFrontmatter(source, workflowToFrontmatter(workflow)); + const updated = replaceMarkdownFrontmatter(source, await this.runtimeFrontmatter(workflowToRuntimeRecord(workflow))); await this.app.vault.modify(file, updated); await this.reload(); } @@ -71,7 +77,7 @@ export class WorkflowRepository { const folder = normalizePath(this.getSettings().workflowFolder); await this.ensureFolder(folder); const path = await this.uniqueWorkflowPath(folder, workflow.id); - const content = `---\n${workflowToFrontmatter(workflow)}---\n\n${body.trim()}\n`; + const content = `---\n${await this.runtimeFrontmatter(workflowToRuntimeRecord(workflow))}---\n\n${body.trim()}\n`; const file = await this.app.vault.create(path, content); await this.reload(); return await this.loadFile(file); diff --git a/src/workflowScaffolding.ts b/src/workflowScaffolding.ts index 3f2d5b6..a5f6c23 100644 --- a/src/workflowScaffolding.ts +++ b/src/workflowScaffolding.ts @@ -28,6 +28,7 @@ export function createWorkflowDefinition(input: { return { type: "workflow", schemaVersion: 1, + expressionLanguage: "cel", id: input.id, name: input.name, description: input.description, @@ -147,7 +148,7 @@ export function defaultInputForStep(type: string): Record { if (type === "task.removeDependency") return { task: "{{event.after.path}}", uid: "dependency-id" }; if (type === "time.start") return { task: "{{event.after.path}}", options: { description: "Started by {{workflow.name}}" } }; if (type === "time.stop") return { task: "{{event.after.path}}" }; - if (type === "time.appendEntry") return { task: "{{event.after.path}}", entry: { minutes: 25, date: "{{today}}" } }; + if (type === "time.appendEntry") return { task: "{{event.after.path}}", entry: { startTime: "{{now}}", description: "Workflow time entry" } }; if (type === "obsidian.openFile") return { path: "{{event.path}}", newLeaf: "tab" }; if (type === "obsidian.createNote") return { path: "Notes/new-note.md", content: "" }; if (type === "obsidian.appendNote") return { path: "{{event.path}}", text: "\n- Workflow ran at {{now}}\n" }; diff --git a/tests/celMigration.test.ts b/tests/celMigration.test.ts new file mode 100644 index 0000000..c0f61a2 --- /dev/null +++ b/tests/celMigration.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { convertBases, migrateExpressions } from "../src/migrateExpressions"; +import { parseWorkflowDefinition } from "../src/workflowParser"; +import { resolveCel } from "../src/cel"; + +function legacy(input: unknown, conditions: unknown[] = []) { + const parsed = parseWorkflowDefinition({ type: "workflow", schemaVersion: 1, id: "legacy", name: "Legacy", enabled: true, triggers: [{ id: "change", type: "tasknotes.event", event: "task.status.changed", from: "open", to: "active" }], conditions, steps: [{ id: "show", type: "notice.show", input }], run: { mode: "sequential", concurrency: { group: "workflow", policy: "skip" }, limits: { maxItems: 5 }, source: "tasknotes-workflows", onError: "stop" } }, ""); + if (!parsed.workflow) throw new Error(JSON.stringify(parsed.diagnostics)); + return parsed; +} +describe("CEL workflow migration", () => { + it("converts templates including hyphenated ids, mixed text, Bases dates and conditions", () => { + const { record, warnings } = migrateExpressions(legacy({ message: 'Task {{event.after.title}} ({{steps.some-step.output.count}})', due: { $expr: 'today() + duration("3d")' } }, [{ field: "event.after.status", operator: "is", value: "active" }])); + expect(warnings).toEqual([]); + expect(record.enabled).toBe(true); + expect(record["x-tasknotes"]).toMatchObject({ format_version: 2 }); + expect(record.triggers[0]?.if?.$expr).toContain('event.data.after.status == "active"'); + expect(resolveCel(record.steps[0]?.input, { event: { data: { after: { title: "Review" } } }, steps: { "some-step": { output: { count: 2 } } } }, { now: new Date("2026-11-17T00:00:00Z") })).toEqual({ message: "Task Review (2)", due: "2026-11-20" }); + }); + it("converts exists/missing guards without invalid CEL has(index) macros", () => { + const present = migrateExpressions(legacy({}, [{ field: "event.after.due", operator: "exists" }])); + const absent = migrateExpressions(legacy({}, [{ field: "event.after.due", operator: "missing" }])); + expect(resolveCel(present.record.triggers[0]?.if, { event: { data: { before: { status: "open" }, after: { status: "active", due: "2026-11-17" } } } })).toBe(true); + expect(resolveCel(absent.record.triggers[0]?.if, { event: { data: { before: { status: "open" }, after: { status: "active" } } } })).toBe(true); + }); + it("disables and explains unsupported Bases expressions without losing the review candidate", () => { + const { record, warnings } = migrateExpressions(legacy({ message: { $expr: 'file("Notes/a.md").asFile().name' } })); + expect(record.enabled).toBe(false); + expect(warnings).toHaveLength(1); + expect(record["x-tasknotes"]).toMatchObject({ format_version: 2, comment: expect.stringContaining("Manual conversion required") }); + }); + it("migrates runtime format v1 while retaining native policies and trigger conditions", () => { + const parsed = legacy({ message: "{{event.after.title}}" }); + const runtime = { type: "runtime_workflow" as const, id: "legacy", version: "1.0.0", name: "Legacy", enabled: true, "x-tasknotes": { format_version: 1 }, triggers: [{ id: "change", event: { id: "task.status.changed", version: "1.0.0" }, if: { $expr: 'event.after.status == "active"' } }], steps: [{ id: "show", action: { id: "notice.show", version: "1.0.0" }, input: { message: "{{event.after.title}}" } }], run: { idempotency: { key: { $expr: "event.path" } } } }; + const { record } = migrateExpressions({ ...parsed, runtime }); + expect(record.run?.idempotency?.key).toEqual({ $expr: 'event.data["path"]' }); + expect(record.triggers[0]?.if?.$expr).toContain('event.data["after"]["status"]'); + }); + it("keeps format v1 on its legacy evaluator and recognizes v2 CEL without Bases validation", () => { + const base = { type: "runtime_workflow", id: "cel", name: "CEL", version: "1.0.0", enabled: true, triggers: [{ id: "m", event: { id: "manual", version: "1.0.0" } }], steps: [{ id: "m", action: { id: "notice.show", version: "1.0.0" }, input: { message: { $expr: '[1,2].map(x, x + 1)' } } }] }; + expect(parseWorkflowDefinition({ ...base, "x-tasknotes": { format_version: 2 } }, "").workflow).not.toBeNull(); + expect(convertBases('date(event.after.due) - duration("1w")')).toBe('(date(event.data["after"]["due"])).addDays(-7)'); + }); +}); diff --git a/tests/collection.test.ts b/tests/collection.test.ts new file mode 100644 index 0000000..164cdb9 --- /dev/null +++ b/tests/collection.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import { parse } from "yaml"; +import { collectionSettings, normalizeWorkflowType, runtimeFrontmatter } from "../src/collection"; +import { parseWorkflowDefinition } from "../src/workflowParser"; +import { workflowToCelRecord } from "../src/migrateExpressions"; +import { createWorkflowDefinition } from "../src/workflowScaffolding"; + +function app(config: string | undefined) { + return { vault: { adapter: { exists: async () => config !== undefined, read: async () => config } } } as never; +} +describe("mdbase 0.3 type keys", () => { + it.each(["mdbase_type", "custom_type", "type"])("writes and loads the configured %s key", async (key) => { + const vault = app(`spec_version: 0.3.0\nsettings:\n explicit_type_keys: [${key}]\n types_folder: _mdbase/types\n`); + const record = workflowToCelRecord(createWorkflowDefinition({ id: "test", name: "Test" })); + const frontmatter = parse(await runtimeFrontmatter(vault, record)); + expect(frontmatter[key]).toBe("runtime_workflow"); + if (key !== "type") expect(frontmatter.type).toBeUndefined(); + const loaded = parseWorkflowDefinition(normalizeWorkflowType(frontmatter, await collectionSettings(vault)), ""); + expect(loaded.runtime?.id).toBe("test"); expect(loaded.diagnostics).toEqual([]); + }); + it("uses type by default and respects an empty explicit type key list", async () => { + const record = workflowToCelRecord(createWorkflowDefinition({ id: "test", name: "Test" })); + expect(parse(await runtimeFrontmatter(app(undefined), record)).type).toBe("runtime_workflow"); + await expect(runtimeFrontmatter(app("settings:\n explicit_type_keys: []"), record)).rejects.toThrow(/explicit_type_keys is empty/); + }); +}); diff --git a/tests/defaultWorkflowsService.test.ts b/tests/defaultWorkflowsService.test.ts index c828ff5..b4fd6e7 100644 --- a/tests/defaultWorkflowsService.test.ts +++ b/tests/defaultWorkflowsService.test.ts @@ -39,12 +39,12 @@ describe("default workflows service", () => { expect(vault.files.get("TaskNotes/Workflows/clear-scheduled-when-started.md")).toContain("id: task.clearScheduled"); expect(vault.files.get("TaskNotes/Workflows/stamp-started-at.md")).toContain("startedAt"); expect(vault.files.get("TaskNotes/Workflows/rollover-overdue-scheduled-tasks.md")).toContain("id: task.reschedule"); - expect(vault.files.get("TaskNotes/Workflows/escalate-upcoming-due-tasks.md")).toContain('today() + duration("3d")'); + expect(vault.files.get("TaskNotes/Workflows/escalate-upcoming-due-tasks.md")).toContain('(today()).addDays(3)'); expect(vault.files.get("TaskNotes/Workflows/blocked-task-review.md")).toContain("task.isBlocked"); expect(vault.files.get("TaskNotes/Workflows/inherit-subtask-dependencies.md")).toContain("id: task.dependencies"); expect(vault.files.get("TaskNotes/Workflows/mirror-parent-dependencies-to-subtasks.md")).toContain("blockedBy"); expect(vault.files.get("TaskNotes/Workflows/schedule-subtasks-before-parent-due.md")).toContain( - 'date(event.after.due) - duration("1w")' + '(date(event.data["after"]["due"])).addDays(-7)' ); expect(vault.files.get("TaskNotes/Views/workflows.base")).toContain("type: tasknotesWorkflows"); expect(vault.files.get("TaskNotes/Views/workflows.base")).toContain('note["type"] == "workflow"'); diff --git a/tests/runLogService.test.ts b/tests/runLogService.test.ts index c186130..4650cec 100644 --- a/tests/runLogService.test.ts +++ b/tests/runLogService.test.ts @@ -102,6 +102,21 @@ describe("RunLogService", () => { expect(await adapter.exists(`${RUNS_ROOT}/workflows/wf/run-1.json`)).toBe(true); }); + it("marks interrupted runtime work indeterminate without replay and retains the history UI", async () => { + const { service, adapter } = createService(); + const detail = runDetail("run:interrupted"); + detail.runtime = { type: "runtime_run", id: detail.runId, workflow_id: "wf", status: "running" } as never; + detail.attempts = [{ type: "runtime_action_attempt", status: "dispatching" }] as never; + await service.checkpoint(detail); + expect(await service.recentRuns()).toEqual([]); + await service.recoverInterrupted(); + expect(await service.recentRuns()).toHaveLength(1); + expect((await service.readRunDetail("wf", detail.runId))?.runtime?.status).toBe("indeterminate"); + expect((await service.readRunDetail("wf", detail.runId))?.attempts?.[0]?.status).toBe("indeterminate"); + expect([...adapter.files.values()].some(({ content }) => content.includes('"type": "runtime_run"'))).toBe(true); + await service.recoverInterrupted(); + expect(await service.recentRuns()).toHaveLength(1); + }); it("prunes the oldest runs by mtime, not by file name", async () => { const { adapter, service } = createService({ maxRunsPerWorkflow: 2 }); // Written oldest to newest; lexicographic order would keep the wrong files. diff --git a/tests/runtimeExecutor.test.ts b/tests/runtimeExecutor.test.ts new file mode 100644 index 0000000..e755552 --- /dev/null +++ b/tests/runtimeExecutor.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { validateRuntimeRecord } from "@callumalpass/mdbase-runtime"; +import { StepRegistry } from "../src/stepRegistry"; +import { RuntimeWorkflowExecutor } from "../src/runtimeExecutor"; +import { parseWorkflowDefinition } from "../src/workflowParser"; +import { RuntimeStateStore, RESERVATION_RETENTION_MS } from "../src/runtimeState"; +import { resolveCel, evaluateVariables } from "../src/cel"; +import type { LoadedWorkflow, StepDefinition, WorkflowRunDetail, WorkflowRunOptions } from "../src/types"; +import type { CloudEvent } from "@callumalpass/mdbase-interop"; + +function loaded(overrides: Record = {}): LoadedWorkflow { + const parsed = parseWorkflowDefinition({ + type: "runtime_workflow", id: "test", version: "1.0.0", name: "Test", enabled: true, + "x-tasknotes": { format_version: 2 }, + triggers: [{ id: "event", event: { id: "task.updated", version: "1.0.0" } }], + steps: [{ id: "first", action: { id: "test.action", version: "1.0.0" }, input: { message: { $expr: "event.data.after.status" } } }], + ...overrides, + }, ""); + expect(parsed.diagnostics).toEqual([]); + return { ...parsed, file: { path: "Workflows/test.md" }, body: "", source: "" } as LoadedWorkflow; +} +function event(id = "one"): WorkflowRunOptions { + return { trigger: { id: "event", type: "task.updated", cloudEvent: { + id, type: "task.updated", time: "2026-11-17T01:00:00Z", source: "obsidian://tasknotes", specversion: "1.0", + data: { after: { status: "active" } }, datacontenttype: "application/json", dataschema: "task.updated/1.0.0", + mdbaseprofile: "0.1", mdbasecontractversion: "1.0.0", mdbasecontractdigest: `sha256:${"a".repeat(64)}`, + mdbaseapplication: "tasknotes", mdbaseimplementation: "tasknotes-v5", mdbaseimplementationversion: "5.0.0-beta.13", + } satisfies CloudEvent } }; +} +function setup(run: StepDefinition["run"] = async (input) => input, store = new RuntimeStateStore()) { + const registry = new StepRegistry(); + registry.register({ type: "test.action", run } as StepDefinition); + const evidence: WorkflowRunDetail[] = []; + const executor = new RuntimeWorkflowExecutor(registry, () => null, () => null, () => null, store, async (detail) => { evidence.push(structuredClone(detail)); }); + return { executor, evidence }; +} +function deferred() { + let resolve: (value?: unknown) => void = () => {}; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +beforeEach(() => { vi.stubGlobal("window", globalThis); }); +afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); +describe("CEL runtime", () => { + it("evaluates CEL maps, lists, macros, dates and literal strings with strict expression objects", () => { + expect(resolveCel({ $expr: '[1, 2, 3].filter(x, x > 1).map(x, x * 2)' }, {})).toEqual([4, 6]); + expect(resolveCel({ $expr: 'today().addDays(2)' }, {}, { now: new Date("2026-11-17T00:00:00Z"), timezone: "UTC" })).toBe("2026-11-19"); + expect(resolveCel("{{event.after.path}}", {})).toBe("{{event.after.path}}"); + expect(resolveCel({ $expr: "bad", literal: true }, {})).toEqual({ $expr: "bad", literal: true }); + expect(() => resolveCel({ $expr: "1 / 0" }, {})).toThrow(); + }); + it("orders dependent variables and rejects cycles", () => { + expect(evaluateVariables({ b: { $expr: 'vars.a + "!"' }, a: "hello" }, {})).toEqual({ a: "hello", b: "hello!" }); + expect(() => evaluateVariables({ a: { $expr: "vars.b" }, b: { $expr: "vars.a" } }, {})).toThrow(/Cyclic/); + }); + it("executes runtime fields directly and writes schema-valid run and attempt evidence before dispatch", async () => { + const run = vi.fn(async (input) => input); + const { executor, evidence } = setup(run); + const result = await executor.run(loaded(), event()); + expect(result.runtime?.status).toBe("succeeded"); + expect(run.mock.calls[0]?.[0]).toEqual({ message: "active" }); + expect(evidence.some((detail) => detail.attempts?.[0]?.status === "dispatching")).toBe(true); + expect(validateRuntimeRecord(result.runtime)).toMatchObject({ valid: true }); + expect(validateRuntimeRecord(result.attempts?.[0])).toMatchObject({ valid: true }); + }); + it("honors trigger if and rejects non-boolean conditions", async () => { + const run = vi.fn(); const { executor } = setup(run); + const trigger = (source: string) => [{ id: "event", event: { id: "task.updated", version: "1.0.0" }, if: { $expr: source } }]; + expect((await executor.run(loaded({ triggers: trigger('event.data.after.status == "done"') }), event())).runtime?.status).toBe("cancelled"); + expect((await executor.run(loaded({ triggers: trigger('"active"') }), event())).status).toBe("failed"); + expect(run).not.toHaveBeenCalled(); + }); + it("does not consume minimum interval on a false guard, and manual runs bypass automatic throttling", async () => { + const run = vi.fn(async () => "done"); const { executor } = setup(run); + const trigger = { id: "event", event: { id: "task.updated", version: "1.0.0" }, minimum_interval: "1h", if: { $expr: 'event.data.after.status == "active"' } }; + const current = loaded({ triggers: [trigger] }); + const unmatched = event("false"); + if (unmatched.trigger.cloudEvent) unmatched.trigger.cloudEvent.data = { after: { status: "open" } }; + await executor.run(current, unmatched); + expect((await executor.run(current, event("one"))).runtime?.status).toBe("succeeded"); + expect((await executor.run(current, event("two"))).runtime?.status).toBe("cancelled"); + await executor.run(current, { ...event("three"), manual: true }); + expect(run).toHaveBeenCalledTimes(2); + }); + it("keeps each for_each output in order and enforces max_items", async () => { + const { executor } = setup(async (input) => input); + const steps = [{ id: "items", action: { id: "test.action", version: "1.0.0" }, for_each: { items: ["a", "b"] }, input: { value: { $expr: "item" } } }, { id: "after", action: { id: "test.action", version: "1.0.0" }, input: { output: { $expr: "steps.items.output" } } }]; + const result = await executor.run(loaded({ steps }), event()); + expect(result.steps[2]?.input).toEqual({ output: [{ value: "a" }, { value: "b" }] }); + const capped = await executor.run(loaded({ steps, run: { limits: { max_items: 1 } } }), event("two")); + expect(capped.error).toMatch(/max_items/); + }); + it("continues after failed actions with on_error but retains a failed run", async () => { + const run = vi.fn(async () => { if (run.mock.calls.length === 1) throw new Error("rejected"); return "done"; }); + const { executor } = setup(run); + const steps = ["a", "b"].map((id) => ({ id, action: { id: "test.action", version: "1.0.0" } })); + const result = await executor.run(loaded({ steps, run: { on_error: "continue" } }), event()); + // Local failures are known failures, not lost transport outcomes. + expect(result.runtime?.status).toBe("failed"); + expect(run).toHaveBeenCalledTimes(2); + }); + it("checks timeout before dispatching subsequent steps", async () => { + vi.useFakeTimers(); + const run = vi.fn(async () => { vi.advanceTimersByTime(20); return "done"; }); + const { executor } = setup(run); + const steps = ["a", "b"].map((id) => ({ id, action: { id: "test.action", version: "1.0.0" } })); + const result = await executor.run(loaded({ steps, run: { limits: { timeout: "10ms" } } }), event()); + expect(result.runtime?.status).toBe("failed"); expect(run).toHaveBeenCalledTimes(1); + }); +}); + +describe("persistent reservations", () => { + it("survives restart, serializes competing admission, expires after retention, and persists before action", async () => { + const files = new Map(); + const app = { vault: { configDir: ".obsidian", adapter: { exists: async (path: string) => files.has(path), read: async (path: string) => files.get(path), write: async (path: string, text: string) => { files.set(path, text); } } } } as never; + const store = new RuntimeStateStore(app); + expect(await Promise.all([store.reserve("same", 0), store.reserve("same", 0)])).toEqual([true, false]); + expect(await new RuntimeStateStore(app).reserve("same", 1)).toBe(false); + expect(await store.reserve("same", RESERVATION_RETENTION_MS)).toBe(true); + const run = vi.fn(async () => { expect([...files.values()].join()).toContain("test:one:event"); }); + await setup(run, store).executor.run(loaded(), event()); + await setup(run, new RuntimeStateStore(app)).executor.run(loaded(), event()); + expect(run).toHaveBeenCalledTimes(1); + }); + it("does not dispatch if reservation persistence fails", async () => { + const app = { vault: { configDir: ".obsidian", adapter: { exists: async () => false, write: async () => { throw new Error("disk full"); } } } } as never; + const run = vi.fn(); + const result = await setup(run, new RuntimeStateStore(app)).executor.run(loaded(), event()); + expect(result.error).toBe("disk full"); expect(run).not.toHaveBeenCalled(); + }); +}); + +describe("concurrency policies with expression-valued groups", () => { + it.each(["skip", "queue", "replace", "allow"] as const)("implements %s", async (policy) => { + const blocked = deferred(); + const run = vi.fn(async () => { if (run.mock.calls.length === 1) await blocked.promise; return "done"; }); + const { executor, evidence } = setup(run); + const workflow = loaded({ run: { concurrency: { policy, group: { $expr: '"status:" + event.data.after.status' } } } }); + const first = executor.run(workflow, event("one")); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + const second = executor.run(workflow, event("two")); + await vi.waitFor(() => expect(evidence.some((detail) => detail.runtime?.event_id === "two")).toBe(true)); + if (policy !== "allow") expect(run).toHaveBeenCalledTimes(1); + blocked.resolve(); + const results = await Promise.all([first, second]); + expect(run).toHaveBeenCalledTimes(policy === "skip" ? 1 : 2); + expect(results[0]?.runtime?.status).toBe(policy === "replace" ? "cancelled" : "succeeded"); + expect(results[1]?.runtime?.status).toBe(policy === "skip" ? "cancelled" : "succeeded"); + }); +}); diff --git a/tests/runtimeInterop.test.ts b/tests/runtimeInterop.test.ts new file mode 100644 index 0000000..359cd60 --- /dev/null +++ b/tests/runtimeInterop.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it, vi } from "vitest"; +import { InMemoryInteropBridge, type ActionContractArtifact, type ActionHandlerContext } from "@callumalpass/mdbase-interop"; +import { validateRuntimeRecord } from "@callumalpass/mdbase-runtime"; +import { RuntimeWorkflowExecutor } from "../src/runtimeExecutor"; +import { TaskNotesBridge } from "../src/tasknotesBridge"; +import { StepRegistry } from "../src/stepRegistry"; +import { parseWorkflowDefinition } from "../src/workflowParser"; +import type { LoadedWorkflow } from "../src/types"; + +it("derives interop item keys from run idempotency and keeps exact outcome identities", async () => { + const bridge = new InMemoryInteropBridge({ authorize: () => true }); + const client = bridge.connect({ application: "workflows", implementation: "client", version: "1.0.0" }); + const provider = bridge.connect({ application: "provider", implementation: "client", version: "1.0.0" }); + const contract: ActionContractArtifact = { kind: "mdbase.contract", contract_type: "action", id: "test.action", version: "1.0.0", input_schema: { dialect: "json-schema-2020-12", value: { type: "object" } } }; + const handler = vi.fn(async (_input: unknown, context: ActionHandlerContext) => ({ key: context.invocation.idempotency_key })); + await provider.registerActionProvider({ declaration_id: "actions", handlers: [{ handler_id: "action", contract, handler }] }); + const pluginBridge = new TaskNotesBridge({ plugins: { getPlugin: () => ({ api: { apiVersion: 1, interop: { profileVersion: "0.1", connect: () => client, describe: () => bridge.describe() }, getInteropStatus: () => ({ enabled: true }) } }) } } as never, {} as never); + const workflow = { ...parseWorkflowDefinition({ type: "runtime_workflow", id: "test", version: "1.0.0", name: "Test", enabled: true, + triggers: [{ id: "m", event: { id: "manual", version: "1.0.0" }, "x-tasknotes": { type: "manual" } }], + steps: [{ id: "each", action: { id: "test.action", version: "^1.0.0" }, for_each: { items: ["a", "b"] }, input: { item: { $expr: "item" } } }], + run: { idempotency: { key: "business-key" } }, "x-tasknotes": { format_version: 2 } }, ""), file: { path: "test.md" }, body: "", source: "" } as LoadedWorkflow; + const executor = new RuntimeWorkflowExecutor(new StepRegistry(), () => null, () => null, () => pluginBridge); + const result = await executor.run(workflow, { manual: true, trigger: { type: "manual" } }); + expect(result.error).toBeUndefined(); + expect(result.runtime?.status).toBe("succeeded"); + expect(result.steps.map((step) => step.output)).toEqual([{ key: "business-key:each:0" }, { key: "business-key:each:1" }]); + for (const attempt of result.attempts ?? []) { + expect(attempt.invocation_id).toBe(attempt.outcome?.invocation_id); + expect(attempt.provider.application).toBe("provider"); + expect(validateRuntimeRecord(attempt).valid).toBe(true); + } + await bridge.dispose(); +}); + +describe("legacy expression execution", () => { + it("executes v1 runtime records directly with the Bases evaluator", async () => { + const parsed = parseWorkflowDefinition({ type: "runtime_workflow", id: "legacy", version: "1.0.0", name: "Legacy", enabled: true, + "x-tasknotes": { format_version: 1 }, + triggers: [{ id: "manual", event: { id: "manual", version: "1.0.0" }, "x-tasknotes": { type: "manual" } }], + steps: [{ id: "show", action: { id: "notice.show", version: "1.0.0" }, input: { message: { $expr: 'if(true, "Bases", "other")' } } }], + }, ""); + expect(parsed.workflow).not.toBeNull(); + const loaded = { ...parsed, file: { path: "legacy.md" }, body: "", source: "" } as LoadedWorkflow; + if (loaded.workflow) loaded.workflow.steps = []; // The UI projection must not drive execution. + const registry = new StepRegistry(); const handler = vi.fn(async (input: unknown) => input); + registry.register({ ...registry.get("notice.show")!, run: handler }); + const result = await new RuntimeWorkflowExecutor(registry, () => null, () => null, () => null).run(loaded, { manual: true, trigger: { type: "manual" } }); + expect(result.runtime?.status).toBe("succeeded"); expect(handler.mock.calls[0]?.[0]).toEqual({ message: "Bases" }); + }); +}); diff --git a/tests/runtimeScheduler.test.ts b/tests/runtimeScheduler.test.ts new file mode 100644 index 0000000..5e8daee --- /dev/null +++ b/tests/runtimeScheduler.test.ts @@ -0,0 +1,71 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { CloudEvent } from "@callumalpass/mdbase-interop"; +import { WorkflowScheduler } from "../src/scheduler"; +import { RuntimeStateStore } from "../src/runtimeState"; +import { parseWorkflowDefinition } from "../src/workflowParser"; +import { DEFAULT_SETTINGS } from "../src/settings"; +import { cronMatches } from "../src/cron"; +import type { LoadedWorkflow, WorkflowRunOptions } from "../src/types"; + +function workflow(enabled = true): LoadedWorkflow { + return { ...parseWorkflowDefinition({ type: "runtime_workflow", id: "test", version: "1.0.0", name: "Test", enabled, + triggers: [{ id: "change", event: { id: "test.changed", version: "1.0.0" } }], steps: [{ id: "show", action: { id: "notice.show", version: "1.0.0" } }], "x-tasknotes": { format_version: 2 } }, ""), file: { path: "test.md" }, body: "", source: "" } as LoadedWorkflow; +} +function setup(workflows = [workflow()], automaticEnabled = () => true, state = new RuntimeStateStore()) { + const run = vi.fn<(workflow: LoadedWorkflow, options: WorkflowRunOptions) => Promise>().mockResolvedValue({} as never); + const scheduler = new WorkflowScheduler({} as never, {} as never, () => DEFAULT_SETTINGS, () => workflows, run, automaticEnabled, state); + return { scheduler, run }; +} +beforeEach(() => { vi.stubGlobal("window", globalThis); }); +afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); +describe("runtime trigger admission", () => { + it("does not run or log disabled contract event workflows", async () => { + const { scheduler, run } = setup([workflow(false), workflow(true)]); + await scheduler["handleContractEvent"]("test.changed\u00001.0.0", { id: "event", type: "test.changed", data: {}, mdbaseapplication: "test" } as CloudEvent); + expect(run).toHaveBeenCalledTimes(1); + }); + it("allows manual runs with automatic execution off", async () => { + const current = workflow(); + const { scheduler, run } = setup([current], () => false); + await scheduler["handleContractEvent"]("test.changed\u00001.0.0", { id: "event", type: "test.changed", data: {} } as CloudEvent); + expect(run).not.toHaveBeenCalled(); + await scheduler.runManual(current); + expect(run).toHaveBeenCalledTimes(1); + }); + it("debounces to the latest event and persists minimum interval suppression", async () => { + vi.useFakeTimers(); + const current = workflow(); + delete current.runtime; + Object.assign(current.workflow!.triggers[0]!, { debounce: "100ms", minimumInterval: "1s" }); + const store = new RuntimeStateStore(); + const { scheduler, run } = setup([current], () => true, store); + const first = scheduler["runAutomatic"](current, { trigger: { id: "change", type: "event", data: 1 } }); + const second = scheduler["runAutomatic"](current, { trigger: { id: "change", type: "event", data: 2 } }); + await vi.advanceTimersByTimeAsync(100); await Promise.all([first, second]); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]?.[1]).toMatchObject({ trigger: { data: 2 } }); + const restarted = setup([current], () => true, store); + const third = restarted.scheduler["runAutomatic"](current, { trigger: { id: "change", type: "event" } }); + await vi.advanceTimersByTimeAsync(100); await third; + expect(restarted.run).not.toHaveBeenCalled(); + }); + it("fires a missed cron once after restart and observes timezone", async () => { + const state = new RuntimeStateStore(); + const first = setup([], () => true, state).scheduler; + expect(await first["shouldRunCron"]("w", "t", "0 9 * * *", new Date("2026-11-16T21:30:00Z"), "Australia/Melbourne")).toBe(false); + const restarted = setup([], () => true, state).scheduler; + const now = new Date("2026-11-17T01:00:00Z"); + expect(await restarted["shouldRunCron"]("w", "t", "0 9 * * *", now, "Australia/Melbourne")).toBe(true); + expect(await restarted["shouldRunCron"]("w", "t", "0 9 * * *", now, "Australia/Melbourne")).toBe(false); + expect(cronMatches("0 9 * * *", new Date("2026-11-16T22:00:00Z"), "Australia/Melbourne")).toBe(true); + }); + it("coalesces interval downtime into one fire", async () => { + vi.useFakeTimers(); vi.setSystemTime(1000); + const state = new RuntimeStateStore(); const first = setup([], () => true, state).scheduler; + expect(await first["shouldRunInterval"]("w", "t", "1m")).toBe(true); + vi.setSystemTime(1000 + 12 * 60_000); + const next = setup([], () => true, state).scheduler; + expect(await next["shouldRunInterval"]("w", "t", "1m")).toBe(true); + expect(await next["shouldRunInterval"]("w", "t", "1m")).toBe(false); + }); +}); diff --git a/tests/scheduler.test.ts b/tests/scheduler.test.ts index 58ba009..23b4030 100644 --- a/tests/scheduler.test.ts +++ b/tests/scheduler.test.ts @@ -73,7 +73,7 @@ describe("WorkflowScheduler task events", () => { scheduler.start(); handlers.get("task.created")?.({ task: { path: "Tasks/a.md" } }); - await Promise.resolve(); + await vi.waitFor(() => expect(runWorkflow).toHaveBeenCalledTimes(1)); expect(runWorkflow).toHaveBeenCalledTimes(1); }); @@ -86,7 +86,7 @@ describe("WorkflowScheduler task events", () => { scheduler.start(); handlers.get("task.created")?.({ task: { path: "Tasks/a.md" } }); - await Promise.resolve(); + await vi.waitFor(() => expect(runWorkflow).toHaveBeenCalledTimes(1)); expect(runWorkflow).toHaveBeenCalledTimes(1); expect(runWorkflow.mock.calls[0][0].workflow?.id).toBe("active"); diff --git a/versions.json b/versions.json index 2d87aa7..efb1d7a 100644 --- a/versions.json +++ b/versions.json @@ -5,5 +5,5 @@ "0.1.3": "1.8.0", "0.1.4": "1.8.0", "0.1.5": "1.8.0", - "0.1.6": "1.8.0" + "0.1.6": "1.8.7" } From 1e608bb6900fc64ad32232a8285f31fad76608dd Mon Sep 17 00:00:00 2001 From: callumalpass Date: Tue, 17 Nov 2026 18:30:59 +1100 Subject: [PATCH 3/5] fix: don't record automatic runs that are not admitted; skip metadata work without metadata triggers --- CHANGELOG.md | 3 +++ main.ts | 1 + src/runtimeExecutor.ts | 10 +++++++--- src/scheduler.ts | 18 +++++++++++++++--- src/types.ts | 2 ++ tests/runtimeExecutor.test.ts | 12 ++++++++++++ 6 files changed, 40 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59ae2aa..c9840a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- Automatic triggers whose condition does not match, or that are suppressed by an idempotency key or minimum interval, no longer write a skipped run to history. Manual runs are still recorded. +- Migrated CEL conditions are strict: reading a field that is missing is an evaluation error and fails the run, where the old Bases expressions treated it as false. Use `has()` or optional selection (`event.data.?after.?status.orValue("")`) when a field may be absent. + ### Changed - Execute Runtime 0.2 workflow records directly with CEL expressions, trigger guards, ordered variables/iteration, persistent seven-day idempotency reservations, concurrency policies, debounce/minimum intervals, deadlines and item limits. Missed cron/interval schedules fire once after downtime; cron respects its timezone. diff --git a/main.ts b/main.ts index 057157b..7e6a4c6 100644 --- a/main.ts +++ b/main.ts @@ -308,6 +308,7 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { options: WorkflowRunOptions ): Promise { const detail = await this.engine.runWorkflow(workflow, options); + if (detail.notAdmitted) return detail; await this.runLogs.recordRun(this.redactRunDetail(detail)); await this.refreshWorkflowLastRun(detail.workflowId); await this.renderWorkflowBaseViews(); diff --git a/src/runtimeExecutor.ts b/src/runtimeExecutor.ts index f17fd9e..616ec2d 100644 --- a/src/runtimeExecutor.ts +++ b/src/runtimeExecutor.ts @@ -49,9 +49,13 @@ export class RuntimeWorkflowExecutor { detail.runtime.updated_at = detail.endedAt; detail.runtime.finished_at = detail.endedAt; } - await this.persist(detail); + if (!detail.notAdmitted) await this.persist(detail); return detail; }; + const notAdmitted = async (reason: string): Promise => { + detail.notAdmitted = !options.manual; + return await finish("cancelled", reason); + }; let active: ActiveRun | undefined; let group = ""; let release: (() => void) | undefined; @@ -101,12 +105,12 @@ export class RuntimeWorkflowExecutor { trigger_id: trigger?.id ?? "manual", idempotency_key: key, concurrency_group: group, status: "queued", created_at: now.toISOString(), updated_at: now.toISOString(), }; - if (!matched) return await finish("cancelled", "Trigger condition did not match."); + if (!matched) return await notAdmitted("Trigger condition did not match."); const bindings = await Promise.all(workflow.steps.map((step) => this.binding(step))); detail.runtime.admitted_plan.steps = bindings; this.checkCapabilities(workflow.requires?.capabilities); const minimumInterval = !options.manual && trigger?.minimum_interval ? { key: `${workflow.id}:${trigger.id}`, minimumIntervalMs: parseDurationMs(trigger.minimum_interval, 0) } : undefined; - if (!options.dryRun && !await this.state.reserve(key, Date.now(), minimumInterval)) return await finish("cancelled", "Duplicate idempotency key or minimum interval has not elapsed."); + if (!options.dryRun && !await this.state.reserve(key, Date.now(), minimumInterval)) return await notAdmitted("Duplicate idempotency key or minimum interval has not elapsed."); const policy = workflow.run?.concurrency?.policy ?? "skip"; const existing = [...this.groups.get(group) ?? []]; if (policy === "skip" && existing.length) return await finish("cancelled", "Concurrency group is active."); diff --git a/src/scheduler.ts b/src/scheduler.ts index 3a2d392..1fed75c 100644 --- a/src/scheduler.ts +++ b/src/scheduler.ts @@ -31,6 +31,7 @@ export class WorkflowScheduler { private cleanupCallbacks: Array<() => void> = []; private debounceTimers = new Map void }>(); private metadataSnapshots = new Map>(); + private typeKeys: Promise | null = null; private registrationEpoch = 0; constructor( @@ -170,8 +171,12 @@ export class WorkflowScheduler { }); this.cleanupCallbacks.push(() => this.plugin.app.workspace.offref(layoutChangeRef)); - for (const file of this.plugin.app.vault.getMarkdownFiles()) { - this.metadataSnapshots.set(file.path, structuredClone(this.plugin.app.metadataCache.getFileCache(file)?.frontmatter ?? {})); + this.metadataSnapshots.clear(); + this.typeKeys = null; + if (this.hasMetadataTrigger("changed")) { + for (const file of this.plugin.app.vault.getMarkdownFiles()) { + this.metadataSnapshots.set(file.path, structuredClone(this.plugin.app.metadataCache.getFileCache(file)?.frontmatter ?? {})); + } } const metadataChangedRef = this.plugin.app.metadataCache.on("changed", (file, _data, cache) => { void this.handleMetadataEvent("changed", file, { cache }).catch(showError); @@ -322,6 +327,7 @@ export class WorkflowScheduler { file: TFile | null, data?: unknown ): Promise { + if (!this.hasMetadataTrigger(event)) return; let cloudEvent: CloudEvent | undefined; if (event === "changed" && file) { const before = this.metadataSnapshots.get(file.path) ?? {}; @@ -331,7 +337,8 @@ export class WorkflowScheduler { delete before.position; this.metadataSnapshots.set(file.path, after); const changed_fields = [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key])); - const keys = (await collectionSettings(this.plugin.app))?.typeKeys ?? ["type", "types"]; + this.typeKeys ??= collectionSettings(this.plugin.app).then((config) => config?.typeKeys ?? ["type", "types"]); + const keys = await this.typeKeys; const types = (record: Record): string[] => [...new Set(keys.flatMap((key) => typeof record[key] === "string" ? [record[key]] : Array.isArray(record[key]) ? record[key] as unknown[] : []).filter((value): value is string => typeof value === "string"))]; data = { path: file.path, before, after, changed_fields, previous_revision: await digest(before), revision: await digest(after), previous_types: types(before), types: types(after) }; cloudEvent = await localCloudEvent({ trigger: { type: event, data, path: file.path } }, "mdbase.record.modified"); @@ -359,6 +366,11 @@ export class WorkflowScheduler { } } + private hasMetadataTrigger(event: ObsidianMetadataTrigger["event"]): boolean { + return this.getWorkflows().some((workflow) => workflow.workflow?.enabled + && workflow.workflow.triggers.some((trigger) => trigger.type === "obsidian.metadata" && trigger.event === event)); + } + private taskNotesTriggerMatches(trigger: TaskNotesEventTrigger, payload: WorkflowTriggerPayload): boolean { if (trigger.event !== (payload.event ?? payload.type)) return false; if (!trigger.allowSelfTrigger && payload.source === "tasknotes-workflows") return false; diff --git a/src/types.ts b/src/types.ts index 97b0eb6..1c708a7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -286,6 +286,8 @@ export interface WorkflowRunDetail { trigger: WorkflowTriggerPayload; steps: StepRunDetail[]; error?: string; + /** Set when an automatic trigger did not admit a run (condition, duplicate key or minimum interval); such runs are not recorded. */ + notAdmitted?: boolean; } export type WorkflowRunStatus = "success" | "failed" | "skipped" | "stopped"; diff --git a/tests/runtimeExecutor.test.ts b/tests/runtimeExecutor.test.ts index e755552..530d444 100644 --- a/tests/runtimeExecutor.test.ts +++ b/tests/runtimeExecutor.test.ts @@ -54,6 +54,18 @@ describe("CEL runtime", () => { expect(evaluateVariables({ b: { $expr: 'vars.a + "!"' }, a: "hello" }, {})).toEqual({ a: "hello", b: "hello!" }); expect(() => evaluateVariables({ a: { $expr: "vars.b" }, b: { $expr: "vars.a" } }, {})).toThrow(/Cyclic/); }); + it("does not record automatic runs whose trigger condition does not match", async () => { + const run = vi.fn(async (input) => input); + const { executor, evidence } = setup(run); + const workflow = loaded({ triggers: [{ id: "event", event: { id: "task.updated", version: "1.0.0" }, if: { $expr: 'event.data.after.status == "done"' } }] }); + const result = await executor.run(workflow, event()); + expect(result.notAdmitted).toBe(true); + expect(evidence).toEqual([]); + expect(run).not.toHaveBeenCalled(); + const manual = await executor.run(workflow, { ...event("two"), manual: true }); + expect(manual.notAdmitted).toBe(false); + expect(evidence).toHaveLength(1); + }); it("executes runtime fields directly and writes schema-valid run and attempt evidence before dispatch", async () => { const run = vi.fn(async (input) => input); const { executor, evidence } = setup(run); From 5c5d854447e1c63ef99ab549dfdc5e6b6808c991 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Tue, 17 Nov 2026 18:31:04 +1100 Subject: [PATCH 4/5] docs: file changelog entries under Changed --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9840a4..66fee84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,11 @@ ## Unreleased -- Automatic triggers whose condition does not match, or that are suppressed by an idempotency key or minimum interval, no longer write a skipped run to history. Manual runs are still recorded. -- Migrated CEL conditions are strict: reading a field that is missing is an evaluation error and fails the run, where the old Bases expressions treated it as false. Use `has()` or optional selection (`event.data.?after.?status.orValue("")`) when a field may be absent. ### Changed +- Automatic triggers whose condition does not match, or that are suppressed by an idempotency key or minimum interval, no longer write a skipped run to history. Manual runs are still recorded. +- Migrated CEL conditions are strict: reading a field that is missing is an evaluation error and fails the run, where the old Bases expressions treated it as false. Use `has()` or optional selection (`event.data.?after.?status.orValue("")`) when a field may be absent. - Execute Runtime 0.2 workflow records directly with CEL expressions, trigger guards, ordered variables/iteration, persistent seven-day idempotency reservations, concurrency policies, debounce/minimum intervals, deadlines and item limits. Missed cron/interval schedules fire once after downtime; cron respects its timezone. - Migrate Bases expressions, templates and structured conditions through the reviewed backup/apply/rollback flow. Unsupported conversions disable the workflow with an explanation. Unmigrated v1 files keep the original evaluator; CEL notes open directly for YAML editing. - Store runtime run and action-attempt evidence in plugin configuration storage while retaining the history UI and read-only compatibility with old history. Interrupted work is not replayed. From 33f2abc05ccd61b988f8f12a726e7b2cbd617fba Mon Sep 17 00:00:00 2001 From: callumalpass Date: Tue, 17 Nov 2026 18:44:10 +1100 Subject: [PATCH 5/5] fix: persist "Run workflows on this device" = off across restarts --- CHANGELOG.md | 2 +- main.ts | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66fee84..59ec4c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ - Execute Runtime 0.2 workflow records directly with CEL expressions, trigger guards, ordered variables/iteration, persistent seven-day idempotency reservations, concurrency policies, debounce/minimum intervals, deadlines and item limits. Missed cron/interval schedules fire once after downtime; cron respects its timezone. - Migrate Bases expressions, templates and structured conditions through the reviewed backup/apply/rollback flow. Unsupported conversions disable the workflow with an explanation. Unmigrated v1 files keep the original evaluator; CEL notes open directly for YAML editing. - Store runtime run and action-attempt evidence in plugin configuration storage while retaining the history UI and read-only compatibility with old history. Interrupted work is not replayed. -- Add the device-local “Run workflows on this device” setting, enabled by default on desktop and disabled on mobile. Manual runs remain available. Obsidian 1.8.7 is now required for its local-storage API. +- Add the device-local “Run workflows on this device” setting, enabled by default on desktop and disabled on mobile. Manual runs remain available. Obsidian 1.8.7 is now required for its local-storage API. Turning it off persists across restarts. - Use stable mdbase interop 0.1.0 and runtime 0.2.0 packages; remove the vendored prerelease archive. Connect to the published `mdbase-sync` plugin and validate API/profile versions. Settings and documentation use “Allow plugin integrations”. - Preserve TaskNotes v5 task IDs in event data; support stable-ID task reads/mutations and correct the scaffolded time-entry DTO. Metadata-change events use the `mdbase.record.modified` data shape. New/migrated workflows respect collection type keys and suggest the runtime standard pack when its type is missing. - Generate disabled CEL starter workflows and recognize runtime notes in the workflow Base/note cards. diff --git a/main.ts b/main.ts index 7e6a4c6..057c90c 100644 --- a/main.ts +++ b/main.ts @@ -102,8 +102,9 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { override async onload(): Promise { await this.loadSettings(); - const deviceSetting = this.app.loadLocalStorage("tasknotes-workflows:run-on-this-device") as boolean | null; - this.runOnThisDevice = deviceSetting ?? !Platform.isMobile; + // Obsidian drops falsy local-storage values, so the setting is stored as "on"/"off". + const deviceSetting: unknown = this.app.loadLocalStorage("tasknotes-workflows:run-on-this-device"); + this.runOnThisDevice = deviceSetting === "on" || deviceSetting === true ? true : deviceSetting === "off" ? false : !Platform.isMobile; this.runtimeTypeHintShown = this.app.loadLocalStorage("tasknotes-workflows:runtime-type-hint") === true; this.i18n = createI18nService({ @@ -184,7 +185,7 @@ export default class TaskNotesWorkflowsPlugin extends Plugin { async setRunOnThisDevice(value: boolean): Promise { this.runOnThisDevice = value; - this.app.saveLocalStorage("tasknotes-workflows:run-on-this-device", value); + this.app.saveLocalStorage("tasknotes-workflows:run-on-this-device", value ? "on" : "off"); await this.reloadWorkflows(); }