Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/runLogService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown> = Promise.resolve();
Expand Down Expand Up @@ -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`);
Expand All @@ -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)
);
}

Expand Down
80 changes: 80 additions & 0 deletions src/workflowData.ts
Original file line number Diff line number Diff line change
@@ -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<object>): 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<string, unknown> = {};
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;
}
21 changes: 13 additions & 8 deletions src/workflowEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand All @@ -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);
Expand All @@ -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(),
Expand Down Expand Up @@ -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 }));
}
Expand Down
213 changes: 213 additions & 0 deletions tests/issue-22-circular-step-output.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
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<typeof vi.fn> } {
// 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<string, string>();
const folders = new Set<string>();
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");
});
});
Loading
Loading