From c59d1ccb8f2fd927230f9cacef6067d1f8f03cb5 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Wed, 11 Nov 2026 03:40:34 +1100 Subject: [PATCH] Keep step outputs and trigger events to plain data (#22) TaskNotes attaches `basesData` (a Bases entry that reaches the Obsidian App) to the cached TaskInfo once a task is rendered in a Bases view, and `tasks.get`/`tasks.patch` and task events hand that object over. The graph is circular, so any `$expr` that reads `steps` or `event` overflowed the stack in obsidian-bases-expression's `fromJs`, and the run log then failed with "Converting circular structure to JSON", hiding the real error. Add toWorkflowData, which copies values to plain data (plain objects, arrays, primitives and Dates; class instances, functions and cyclic back-references are dropped as JSON would), and apply it to the trigger payload and to every step output before they enter the run context. The run log serialises through the same function, so a stray runtime object can no longer stop the detail log from being written. Root cause diagnosed by konstantinopolka. Reported by rougeayrn (#22) and chrabia (TaskNotes #2119). --- CHANGELOG.md | 4 + src/runLogService.ts | 5 +- src/workflowData.ts | 80 ++++++++ src/workflowEngine.ts | 21 +- tests/issue-22-circular-step-output.test.ts | 213 ++++++++++++++++++++ tests/workflowData.test.ts | 75 +++++++ 6 files changed, 388 insertions(+), 10 deletions(-) create mode 100644 src/workflowData.ts create mode 100644 tests/issue-22-circular-step-output.test.ts create mode 100644 tests/workflowData.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 45284c1..b4ce07d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Fixed + +- (#22, TaskNotes #2119) Workflows triggered by moving a task on a Kanban board, or by editing any task shown in a Bases view, no longer fail with "Maximum call stack size exceeded" when an expression reads `steps` or `event`. The run log no longer fails with "Converting circular structure to JSON", so the real error is now recorded. Step outputs and trigger events now contain only plain task data. Thanks to @rougeayrn and @chrabia for reporting this, and to @konstantinopolka for finding the cause. + ## [0.1.4] - 2026-08-09 ### Fixed diff --git a/src/runLogService.ts b/src/runLogService.ts index c305e58..a903abd 100644 --- a/src/runLogService.ts +++ b/src/runLogService.ts @@ -2,6 +2,7 @@ import type { App } from "obsidian"; import { PLUGIN_ID } from "./constants"; import { safePathSegment } from "./path"; import type { RunSummary, TaskNotesWorkflowsSettings, WorkflowRunDetail } from "./types"; +import { stringifyWorkflowData } from "./workflowData"; export class RunLogService { private writeQueue: Promise = Promise.resolve(); @@ -87,7 +88,7 @@ export class RunLogService { const existing = (await this.exists(historyPath)) ? await this.app.vault.adapter.read(historyPath) : ""; - const lines = [...existing.split("\n").filter(Boolean), JSON.stringify(summary)].slice( + const lines = [...existing.split("\n").filter(Boolean), stringifyWorkflowData(summary)].slice( -settings.maxHistoryEntries ); await this.app.vault.adapter.write(historyPath, `${lines.join("\n")}\n`); @@ -98,7 +99,7 @@ export class RunLogService { await this.ensureFolder(folder); await this.app.vault.adapter.write( this.detailPath(detail.workflowId, detail.runId), - JSON.stringify(detail, null, 2) + stringifyWorkflowData(detail, 2) ); } diff --git a/src/workflowData.ts b/src/workflowData.ts new file mode 100644 index 0000000..0027cd0 --- /dev/null +++ b/src/workflowData.ts @@ -0,0 +1,80 @@ +/** + * Converts values that enter a workflow run (trigger events, step outputs) + * into plain data: the shape that expressions, templates and the JSON run log + * can safely walk. + * + * Step outputs come from TaskNotes, Obsidian and other plugins and can carry + * live runtime objects. For example, TaskNotes attaches `basesData` (a Bases + * entry that reaches the Obsidian `App`) to tasks rendered in a Bases view. + * Those graphs are circular and not data, so they are dropped: + * + * - plain objects and arrays are copied recursively; + * - strings, finite numbers, booleans and null are kept, and Dates are kept; + * - class instances (anything whose prototype is not `Object.prototype` or + * `null`), functions, symbols and undefined are omitted from objects and + * become null inside arrays, matching JSON; + * - a reference back to an object that is still being copied (a cycle) is + * omitted in the same way. Repeated references to the same value that are + * not cycles are copied each time. + */ +export function toWorkflowData(value: unknown): unknown { + const copied = copyValue(value, new Set()); + return copied === OMIT ? undefined : copied; +} + +/** + * JSON.stringify that cannot throw on cycles or runtime objects, for the run + * log. Values are passed through `toWorkflowData` first. + */ +export function stringifyWorkflowData(value: unknown, space?: number): string { + return JSON.stringify(toWorkflowData(value), null, space) ?? "null"; +} + +const OMIT = Symbol("omit"); + +function copyValue(value: unknown, ancestors: Set): unknown { + if (value === null) return null; + switch (typeof value) { + case "string": + case "boolean": + return value; + case "number": + return Number.isFinite(value) ? value : null; + case "bigint": + return value.toString(); + case "object": + break; + default: + return OMIT; + } + + const object = value; + if (object instanceof Date) return Number.isNaN(object.getTime()) ? null : new Date(object.getTime()); + if (ancestors.has(object)) return OMIT; + + if (Array.isArray(object)) { + ancestors.add(object); + const copy = object.map((entry) => { + const copied = copyValue(entry, ancestors); + return copied === OMIT ? null : copied; + }); + ancestors.delete(object); + return copy; + } + + if (!isPlainObject(object)) return OMIT; + + ancestors.add(object); + const copy: Record = {}; + for (const [key, entry] of Object.entries(object)) { + const copied = copyValue(entry, ancestors); + if (copied !== OMIT) copy[key] = copied; + } + ancestors.delete(object); + return copy; +} + +function isPlainObject(value: object): boolean { + const prototype = Object.getPrototypeOf(value) as unknown; + return prototype === Object.prototype || prototype === null; +} diff --git a/src/workflowEngine.ts b/src/workflowEngine.ts index 6f0791f..71b9585 100644 --- a/src/workflowEngine.ts +++ b/src/workflowEngine.ts @@ -2,6 +2,7 @@ import { conditionsMatch } from "./conditions"; import { todayString } from "./duration"; import { createStepExecutionContext, shouldRunStep, StepRegistry } from "./stepRegistry"; import { resolveTemplateValue } from "./template"; +import { toWorkflowData } from "./workflowData"; import type { App } from "obsidian"; import type { ActionOutcome } from "@callumalpass/mdbase-interop"; import type { TaskNotesBridge } from "./tasknotesBridge"; @@ -52,6 +53,9 @@ export class WorkflowEngine { const runId = createRunId(); const startedAt = new Date(); + // Trigger payloads can carry live runtime objects (for example TaskNotes' + // Bases `basesData`), which break expressions and the run log. + const trigger = toWorkflowData(options.trigger) as WorkflowRunOptions["trigger"]; const detail: WorkflowRunDetail = { runId, workflowId: workflow.id, @@ -60,7 +64,7 @@ export class WorkflowEngine { dryRun: options.dryRun === true, startedAt: startedAt.toISOString(), status: "success", - trigger: options.trigger, + trigger, steps: [], }; const preflightError = this.preflightError(workflow.requires); @@ -85,11 +89,11 @@ export class WorkflowEngine { name: workflow.name, filePath: loadedWorkflow.file.path, }, - trigger: workflow.triggers.find((trigger) => trigger.id === options.trigger.id) ?? { - id: options.trigger.id, - type: options.trigger.triggerType ?? options.trigger.type, + trigger: workflow.triggers.find((candidate) => candidate.id === trigger.id) ?? { + id: trigger.id, + type: trigger.triggerType ?? trigger.type, }, - event: options.trigger, + event: trigger, vars: workflow.vars, steps: {}, now: startedAt.toISOString(), @@ -255,13 +259,14 @@ export class WorkflowEngine { input, }); detail.evidence = outcome; - detail.output = successfulInteropOutput(outcome); + detail.output = toWorkflowData(successfulInteropOutput(outcome)); } } else if (definition) { - detail.output = await definition.run( + // Keep step outputs to plain data before they reach `steps.*`. + detail.output = toWorkflowData(await definition.run( input, createStepExecutionContext(runId, dryRun, this.tasknotes(), this.obsidian(), source) - ); + )); } else { throw new Error(this.t("engine.unknownStepType", { type: step.type })); } diff --git a/tests/issue-22-circular-step-output.test.ts b/tests/issue-22-circular-step-output.test.ts new file mode 100644 index 0000000..67d1225 --- /dev/null +++ b/tests/issue-22-circular-step-output.test.ts @@ -0,0 +1,213 @@ +import { describe, expect, it, vi } from "vitest"; +import type { App } from "obsidian"; +import { RunLogService } from "../src/runLogService"; +import { DEFAULT_SETTINGS } from "../src/settings"; +import { StepRegistry } from "../src/stepRegistry"; +import { WorkflowEngine } from "../src/workflowEngine"; +import type { LoadedWorkflow, TaskNotesRuntimeApi, WorkflowRunDetail } from "../src/types"; + +// Issue #22: once TaskNotes renders a task in a Bases view it attaches +// `basesData` (a Bases entry that reaches the Obsidian `app`) to the cached +// TaskInfo, and `tasks.get` returns that object. The app graph is circular. +class FakeApp { + appMenuBarManager: { app: FakeApp }; + constructor() { + this.appMenuBarManager = { app: this }; + } +} + +class FakeBasesEntry { + constructor(readonly app: FakeApp, readonly file: { path: string }) {} +} + +function taskInfoRenderedInBases(): Record { + return { + path: "Tasks/a.md", + title: "Write report", + status: "in-progress", + due: "2026-10-08", + tags: ["task"], + customProperties: { area: ["Work"] }, + basesData: new FakeBasesEntry(new FakeApp(), { path: "Tasks/a.md" }), + }; +} + +function workflow(): LoadedWorkflow { + return { + file: { path: "TaskNotes/Workflows/test.md", basename: "test" } as LoadedWorkflow["file"], + body: "", + source: "", + sourceFormat: "runtime-v0.2", + diagnostics: [], + workflow: { + type: "workflow", + schemaVersion: 1, + id: "test", + name: "Test", + enabled: true, + triggers: [{ id: "status", type: "tasknotes.event", event: "task.status.changed" }], + vars: {}, + conditions: [], + steps: [ + { id: "read", type: "task.get", input: { task: "{{event.after.path}}" } }, + { + id: "tag", + type: "task.patch", + input: { + task: { $expr: "steps.read.output.task.path" }, + patch: { title: { $expr: 'steps.read.output.task.title + " (started)"' } }, + }, + }, + ], + run: { + mode: "sequential", + concurrency: { group: "workflow", policy: "skip" }, + source: "tasknotes-workflows", + limits: { maxItems: 5 }, + onError: "stop", + }, + }, + }; +} + +function statusChangedTrigger() { + return { + id: "status", + type: "task.status.changed", + triggerType: "tasknotes.event", + event: "task.status.changed", + path: "Tasks/a.md", + after: taskInfoRenderedInBases(), + changes: { status: { before: "open", after: "in-progress" } }, + }; +} + +function engineWithTask(): { engine: WorkflowEngine; patch: ReturnType } { + // TaskNotes returns the cached TaskInfo from writes too. + const patch = vi.fn(async () => taskInfoRenderedInBases()); + const api = { + tasks: { + get: vi.fn(async () => taskInfoRenderedInBases()), + patch, + }, + } as unknown as TaskNotesRuntimeApi; + return { engine: new WorkflowEngine(new StepRegistry(), () => api), patch }; +} + +function recordingService() { + const files = new Map(); + const folders = new Set(); + const adapter = { + exists: async (path: string) => files.has(path) || folders.has(path), + read: async (path: string) => files.get(path) ?? "", + write: async (path: string, content: string) => { + files.set(path, content); + }, + mkdir: async (path: string) => { + folders.add(path); + }, + list: async () => ({ files: [], folders: [] }), + stat: async () => null, + }; + const app = { vault: { adapter, configDir: "config" } } as unknown as App; + return { files, service: new RunLogService(app, () => DEFAULT_SETTINGS) }; +} + +describe("issue #22: TaskInfo carrying circular basesData", () => { + it("evaluates expressions over a step output whose task carries basesData", async () => { + const { engine, patch } = engineWithTask(); + + const run = await engine.runWorkflow(workflow(), { trigger: statusChangedTrigger() }); + + expect(run.steps.map((step) => [step.id, step.status, step.error])).toEqual([ + ["read", "success", undefined], + ["tag", "success", undefined], + ]); + expect(run.status).toBe("success"); + expect(patch).toHaveBeenCalledWith( + "Tasks/a.md", + { title: "Write report (started)" }, + expect.anything() + ); + }); + + it("evaluates expressions over a trigger event task that carries basesData", async () => { + const { engine } = engineWithTask(); + const loaded = workflow(); + loaded.workflow!.steps = [ + { + id: "notice", + type: "notice.show", + input: { message: { $expr: 'event.after.title + " (" + event.after.status + ")"' } }, + }, + ]; + + const run = await engine.runWorkflow(loaded, { dryRun: true, trigger: statusChangedTrigger() }); + + expect(run.status).toBe("success"); + expect(run.steps[0]?.input).toEqual({ message: "Write report (in-progress)" }); + }); + + it("keeps plain task data in step outputs and drops runtime internals", async () => { + const { engine } = engineWithTask(); + + const run = await engine.runWorkflow(workflow(), { trigger: statusChangedTrigger() }); + + expect(run.steps[0]?.output).toEqual({ + task: { + path: "Tasks/a.md", + title: "Write report", + status: "in-progress", + due: "2026-10-08", + tags: ["task"], + customProperties: { area: ["Work"] }, + }, + }); + expect(run.trigger.after).not.toHaveProperty("basesData"); + }); + + it("records the run detail log for a run that touched basesData", async () => { + const { engine } = engineWithTask(); + const { files, service } = recordingService(); + const run = await engine.runWorkflow(workflow(), { trigger: statusChangedTrigger() }); + + await expect(service.recordRun(run)).resolves.toMatchObject({ status: "success" }); + + const detailPath = `config/plugins/tasknotes-workflows/runs/workflows/test/${run.runId}.json`; + const stored = JSON.parse(files.get(detailPath) ?? "null") as WorkflowRunDetail; + expect(stored.steps[0]?.output).toEqual(run.steps[0]?.output); + }); + + it("still writes a detail log if a circular value reaches the run log", async () => { + const { files, service } = recordingService(); + const app = new FakeApp(); + const detail: WorkflowRunDetail = { + runId: "run-1", + workflowId: "wf", + workflowName: "Workflow", + workflowPath: "TaskNotes/Workflows/wf.md", + dryRun: false, + startedAt: "2026-10-06T00:00:00.000Z", + status: "failed", + error: "Real step error", + trigger: { type: "manual", event: "manual" }, + steps: [ + { + id: "read", + type: "task.get", + status: "failed", + startedAt: "2026-10-06T00:00:00.000Z", + error: "Real step error", + errorDetails: { app }, + }, + ], + }; + + await expect(service.recordRun(detail)).resolves.toMatchObject({ error: "Real step error" }); + + const stored = JSON.parse( + files.get("config/plugins/tasknotes-workflows/runs/workflows/wf/run-1.json") ?? "null" + ) as WorkflowRunDetail; + expect(stored.steps[0]?.error).toBe("Real step error"); + }); +}); diff --git a/tests/workflowData.test.ts b/tests/workflowData.test.ts new file mode 100644 index 0000000..c14b65f --- /dev/null +++ b/tests/workflowData.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { stringifyWorkflowData, toWorkflowData } from "../src/workflowData"; + +class RuntimeObject { + value = 1; +} + +describe("toWorkflowData", () => { + it("copies plain data unchanged", () => { + const value = { + path: "Tasks/a.md", + count: 2, + done: false, + due: null, + tags: ["a", "b"], + nested: { list: [{ x: 1 }] }, + }; + const copied = toWorkflowData(value); + expect(copied).toEqual(value); + expect(copied).not.toBe(value); + }); + + it("keeps dates and objects without a prototype", () => { + const bare = Object.assign(Object.create(null) as Record, { a: 1 }); + const at = new Date("2026-10-06T00:00:00.000Z"); + expect(toWorkflowData({ at, bare })).toEqual({ at, bare: { a: 1 } }); + }); + + it("omits class instances, functions and undefined like JSON does", () => { + expect( + toWorkflowData({ + keep: "yes", + instance: new RuntimeObject(), + map: new Map([["a", 1]]), + fn: () => 1, + missing: undefined, + list: [new RuntimeObject(), () => 1, undefined, "x"], + }) + ).toEqual({ keep: "yes", list: [null, null, null, "x"] }); + }); + + it("breaks cycles but copies repeated non-cyclic references", () => { + const shared = { name: "shared" }; + const root: Record = { a: shared, b: shared, list: [shared] }; + root.self = root; + (root.list as unknown[]).push(root.list); + + expect(toWorkflowData(root)).toEqual({ + a: { name: "shared" }, + b: { name: "shared" }, + list: [{ name: "shared" }, null], + }); + }); + + it("normalises numbers and bigints to JSON-safe values", () => { + expect(toWorkflowData([Number.NaN, Infinity, 3, BigInt(10)])).toEqual([null, null, 3, "10"]); + }); + + it("returns undefined for a top-level value that is not data", () => { + expect(toWorkflowData(new RuntimeObject())).toBeUndefined(); + expect(toWorkflowData(() => 1)).toBeUndefined(); + }); +}); + +describe("stringifyWorkflowData", () => { + it("serialises circular structures without throwing", () => { + const root: Record = { id: "run" }; + root.self = root; + expect(JSON.parse(stringifyWorkflowData(root, 2))).toEqual({ id: "run" }); + }); + + it("serialises a non-data value as null", () => { + expect(stringifyWorkflowData(undefined)).toBe("null"); + }); +});