Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(trigger): shared schema + strict validation + machine-local arm store (#493 phase 1)
enesbfba2c89e984
diff --git a/CLAUDE.md b/CLAUDE.mdindex b0a4fd840..d55f2e114 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -136,8 +136,13 @@ factories (`createTerminalNode`, `createSshTerminalNode`, `createAgentNode(agentgroup transforms (`groupSelectedNodes`, `ungroupNodes`, `duplicateNode`), and the`nodeStatesToFlow` / `flowToNodeStates` serializers. Node kinds (`NodeKind` in`src/shared/types.ts`): `terminal | sticky | group | editor | diff | video | web | browser |-subagent | loop | dino` — `subagent` and `loop` are render-only (ephemeral hook-driven viz) and-never persisted. A node's `data`+subagent | loop | dino | trigger` — `subagent` and `loop` are render-only (ephemeral hook-driven+viz) and never persisted. `trigger` (issue #493, landing in phases — schema only so far, no+renderer/scheduler yet) is a first-class PERSISTED kind: its spec (`CanvasNodeState.trigger`,+@shared/trigger) is git-shared CONTENT sanitized as hostile input on every load path+(`sanitizeNodeTriggers`), and the definition alone never fires — execution consent is the+machine-local, content-bound `core/trigger-arm-store.ts` (a spec that arrives or CHANGES via git+reads as disarmed until armed on this machine). A node's `data`carries `title, color, group, tags, collapsed, expandedHeight, shell, cwd, text,initialCommand, filePath, diffStaged`, `agentId` (which agent CLI a terminal node runs —persisted), and `accountId` (which managed Claude account a terminal node runs under — immutable,diff --git a/src/core/trigger-arm-store.test.ts b/src/core/trigger-arm-store.test.tsnew file mode 100644index 000000000..0597c6edf--- /dev/null+++ b/src/core/trigger-arm-store.test.ts@@ -0,0 +1,130 @@+import { promises as fs } from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import type { TriggerSpec } from '../shared/trigger'+import { TriggerArmStore } from './trigger-arm-store'++const spec = (payload = 'npm test'): TriggerSpec => ({+ schedule: { kind: 'cron', expr: '0 9 * * *' },+ payload,+ target: 'term-tgt-1'+})++describe('TriggerArmStore', () => {+ let dir: string+ let store: TriggerArmStore++ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-trigger-arm-'))+ store = new TriggerArmStore(dir)+ await store.load()+ })++ afterEach(async () => {+ await fs.rm(dir, { recursive: true, force: true })+ })++ it('a trigger that just arrived from git is DISARMED — loading a project mints no consent', async () => {+ // The invariant the whole store exists for: nothing in a shared project.json can arm itself.+ // A fresh store (this machine never armed anything) answers false for any spec it is shown.+ expect(store.isArmed('project-1', 'trigger-a-1', spec())).toBe(false)+ expect(store.armedRecord('project-1', 'trigger-a-1')).toBeUndefined()+ })++ it('arm → isArmed → disarm round trip, persisted across a reload', async () => {+ expect(await store.arm('project-1', 'trigger-a-1', spec())).toBe(true)+ expect(store.isArmed('project-1', 'trigger-a-1', spec())).toBe(true)++ const reloaded = new TriggerArmStore(dir)+ await reloaded.load()+ expect(reloaded.isArmed('project-1', 'trigger-a-1', spec())).toBe(true)++ await reloaded.disarm('project-1', 'trigger-a-1')+ expect(reloaded.isArmed('project-1', 'trigger-a-1', spec())).toBe(false)+ const again = new TriggerArmStore(dir)+ await again.load()+ expect(again.isArmed('project-1', 'trigger-a-1', spec())).toBe(false)+ })++ it('the arm binds to CONTENT: a spec edited after arming reads as disarmed', async () => {+ await store.arm('project-1', 'trigger-a-1', spec('npm test'))+ // A git pull rewrote the payload — the old consent must not cover the new content.+ expect(store.isArmed('project-1', 'trigger-a-1', spec('rm -rf /'))).toBe(false)+ // The stale record is still visible so the UI can say "changed since armed".+ expect(store.armedRecord('project-1', 'trigger-a-1')).toBeDefined()+ // The original content is still armed.+ expect(store.isArmed('project-1', 'trigger-a-1', spec('npm test'))).toBe(true)+ })++ it('refuses to arm an invalid spec or unsafe keys, recording nothing', async () => {+ const bad = { ...spec(), payload: '' } as TriggerSpec+ expect(await store.arm('project-1', 'trigger-a-1', bad)).toBe(false)+ expect(store.armedRecord('project-1', 'trigger-a-1')).toBeUndefined()+ expect(await store.arm('p;rm', 'trigger-a-1', spec())).toBe(false)+ expect(await store.arm('project-1', 'bad id', spec())).toBe(false)+ })++ it('an invalid CURRENT spec never reads as armed, whatever is recorded', async () => {+ await store.arm('project-1', 'trigger-a-1', spec())+ const hostile = { ...spec(), payload: 'x\u001b[201~y' } as TriggerSpec+ expect(store.isArmed('project-1', 'trigger-a-1', hostile)).toBe(false)+ })++ it('a corrupt or foreign-shaped file loads as an empty store (all disarmed)', async () => {+ await store.arm('project-1', 'trigger-a-1', spec())+ await fs.writeFile(path.join(dir, 'trigger-arms.json'), 'not json{', 'utf-8')+ const reloaded = new TriggerArmStore(dir)+ await reloaded.load()+ expect(reloaded.isArmed('project-1', 'trigger-a-1', spec())).toBe(false)++ await fs.writeFile(+ path.join(dir, 'trigger-arms.json'),+ JSON.stringify({ version: 99, projects: { p: { n: { armedAt: 1, spec: 's' } } } }),+ 'utf-8'+ )+ const wrongVersion = new TriggerArmStore(dir)+ await wrongVersion.load()+ expect(wrongVersion.armedRecord('p', 'n')).toBeUndefined()+ })++ it('drops dangerous or malformed keys and records on load instead of importing them', async () => {+ // Built as a raw string: a `__proto__` key in a JS object literal would set the prototype+ // instead of writing the property, and the point is what a hostile FILE can carry.+ const hostileFile =+ '{"version":1,"projects":{' ++ '"__proto__":{"trigger-a-1":{"armedAt":1,"spec":"s"}},' ++ '"project-1":{' ++ '"bad id":{"armedAt":1,"spec":"s"},' ++ '"trigger-ok-1":{"armedAt":0,"spec":"s"},' ++ '"trigger-a-1":{"armedAt":5,"spec":"canon"}}}}'+ await fs.writeFile(path.join(dir, 'trigger-arms.json'), hostileFile, 'utf-8')+ const reloaded = new TriggerArmStore(dir)+ await reloaded.load()+ expect(reloaded.armedRecord('project-1', 'trigger-a-1')).toEqual({ armedAt: 5, spec: 'canon' })+ expect(reloaded.armedRecord('project-1', 'bad id')).toBeUndefined()+ expect(reloaded.armedRecord('project-1', 'trigger-ok-1')).toBeUndefined()+ expect(reloaded.armedRecord('__proto__', 'trigger-a-1')).toBeUndefined()+ expect(({} as Record<string, unknown>)['trigger-a-1']).toBeUndefined()+ })++ it('prunes dead projects and dead nodes', async () => {+ await store.arm('project-1', 'trigger-a-1', spec())+ await store.arm('project-1', 'trigger-b-1', spec())+ await store.arm('project-2', 'trigger-c-1', spec())++ await store.pruneProjects(['project-1'])+ expect(store.armedRecord('project-2', 'trigger-c-1')).toBeUndefined()+ expect(store.armedRecord('project-1', 'trigger-a-1')).toBeDefined()++ await store.pruneNodes('project-1', ['trigger-a-1'])+ expect(store.armedRecord('project-1', 'trigger-b-1')).toBeUndefined()+ expect(store.armedRecord('project-1', 'trigger-a-1')).toBeDefined()+ })++ it('writes the file with owner-only permissions', async () => {+ await store.arm('project-1', 'trigger-a-1', spec())+ const stat = await fs.stat(path.join(dir, 'trigger-arms.json'))+ if (process.platform !== 'win32') expect(stat.mode & 0o777).toBe(0o600)+ })+})diff --git a/src/core/trigger-arm-store.ts b/src/core/trigger-arm-store.tsnew file mode 100644index 000000000..227529498--- /dev/null+++ b/src/core/trigger-arm-store.ts@@ -0,0 +1,191 @@+/**+ * MACHINE-LOCAL execution authorization for trigger nodes (issue #493) — the other half of the+ * trust model stated in @shared/trigger.+ *+ * A trigger's DEFINITION rides the git-shared `.nodeterm/project.json`; this store holds the one+ * thing that may never travel with it: this machine's consent for that definition to fire. The+ * precedent is `IndexEntryV3.localExec` / `capabilityAck` — nothing in a shared document may cause+ * execution on its own — but the record lives in its own userData file rather than the workspace+ * index because only core ever asks it (the scheduler at fire time, the arm/disarm IPC later),+ * and threading one more field through every index write/reconcile path is the duplication that+ * file warns about.+ *+ * The arm record BINDS TO CONTENT, not just to the node id: it stores `canonicalTriggerSpec` of+ * the spec that was on screen when the user armed it, and `isArmed` answers true only while the+ * node's CURRENT spec canonicalizes to the same string. Without that, "arm once" plus a later+ * `git pull` that rewrites the payload would run the new content under the old consent — the+ * exact laundering the machine-local split exists to prevent. A drifted spec reads as DISARMED+ * (`armedRecord` still returns the stale record so the UI can say "changed since armed" instead+ * of pretending nothing happened).+ *+ * Internal state is held in `Map`s and only converted to plain objects at the serialization+ * boundary: project/node ids reach `arm()` over IPC eventually, and a `__proto__` key assigned+ * into a plain object is prototype pollution — a Map key is just a key.+ */++import { promises as fs } from 'node:fs'+import path from 'node:path'+import { isSafeNodeId } from '../shared/safe-id'+import { canonicalTriggerSpec, sanitizeTriggerSpec, type TriggerSpec } from '../shared/trigger'+import { writeFileAtomic } from './fs-atomic'++const FILE_NAME = 'trigger-arms.json'++/** Canonical spec strings are bounded by the spec caps; anything past this is not one of ours. */+const SPEC_STRING_MAX = 32_768++export interface TriggerArmRecord {+ armedAt: number+ /** `canonicalTriggerSpec` of the spec the user consented to — the arm's content binding. */+ spec: string+}++interface TriggerArmFileV1 {+ version: 1+ projects: Record<string, Record<string, TriggerArmRecord>>+}++function validRecord(value: unknown): value is TriggerArmRecord {+ if (!value || typeof value !== 'object') return false+ const r = value as TriggerArmRecord+ return (+ Number.isSafeInteger(r.armedAt) &&+ r.armedAt > 0 &&+ typeof r.spec === 'string' &&+ r.spec.length > 0 &&+ r.spec.length <= SPEC_STRING_MAX+ )+}++/** `__proto__` & co pass `isSafeNodeId`'s charset, but assigning one onto the plain object+ * `toFile()` serializes into would SET ITS PROTOTYPE instead of writing the key — so they are+ * refused at every entry point into the maps, not handled at the exit. */+const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])++/** Both key alphabets: project ids are machine-minted (uuid / `project-1` / derived), node ids are+ * tmux names — `isSafeNodeId` covers both and bounds them. */+const validKey = (key: string): boolean => isSafeNodeId(key) && !DANGEROUS_KEYS.has(key)++export class TriggerArmStore {+ private arms = new Map<string, Map<string, TriggerArmRecord>>()+ private writeQueue: Promise<void> = Promise.resolve()++ constructor(private readonly userDataDir: string) {}++ private get filePath(): string {+ return path.join(this.userDataDir, FILE_NAME)+ }++ /** Tolerant: a missing, corrupt or foreign-shaped file is an EMPTY store (every trigger+ * disarmed), never a throw — fail-closed is the safe direction for an execution consent. */+ async load(): Promise<void> {+ this.arms = new Map()+ let parsed: unknown+ try {+ parsed = JSON.parse(await fs.readFile(this.filePath, 'utf-8'))+ } catch {+ return+ }+ if (!parsed || typeof parsed !== 'object') return+ const file = parsed as TriggerArmFileV1+ if (file.version !== 1 || !file.projects || typeof file.projects !== 'object') return+ for (const [projectId, nodes] of Object.entries(file.projects)) {+ if (!validKey(projectId) || !nodes || typeof nodes !== 'object') continue+ const perNode = new Map<string, TriggerArmRecord>()+ for (const [nodeId, record] of Object.entries(nodes)) {+ if (!validKey(nodeId) || !validRecord(record)) continue+ perNode.set(nodeId, { armedAt: record.armedAt, spec: record.spec })+ }+ if (perNode.size) this.arms.set(projectId, perNode)+ }+ }++ /** The raw record (armed for SOME spec), or undefined. Lets the UI distinguish "never armed"+ * from "armed, but the spec changed since" — `isArmed` treats both as not armed. */+ armedRecord(projectId: string, nodeId: string): TriggerArmRecord | undefined {+ return this.arms.get(projectId)?.get(nodeId)+ }++ /**+ * THE fire-time gate: armed here, for exactly this content. `current` is re-sanitized at this+ * interpolation-adjacent site (the caller's copy may have arrived over IPC or a stale in-memory+ * node — same rule as `permissionModeFlag`); a spec the schema refuses can never read as armed.+ */+ isArmed(projectId: string, nodeId: string, current: TriggerSpec): boolean {+ const record = this.arms.get(projectId)?.get(nodeId)+ if (!record) return false+ const safe = sanitizeTriggerSpec(current)+ if (!safe) return false+ return record.spec === canonicalTriggerSpec(safe)+ }++ /**+ * Record this machine's consent for `spec` on (projectId, nodeId). The spec is re-validated+ * here — the call will arrive over IPC — and an invalid spec or key records NOTHING and+ * returns false: consent for a value the schema refuses is not a thing that can exist.+ */+ async arm(projectId: string, nodeId: string, spec: TriggerSpec): Promise<boolean> {+ if (!validKey(projectId) || !validKey(nodeId)) return false+ const safe = sanitizeTriggerSpec(spec)+ if (!safe) return false+ const perNode = this.arms.get(projectId) ?? new Map<string, TriggerArmRecord>()+ perNode.set(nodeId, { armedAt: Date.now(), spec: canonicalTriggerSpec(safe) })+ this.arms.set(projectId, perNode)+ await this.persist()+ return true+ }++ async disarm(projectId: string, nodeId: string): Promise<void> {+ const perNode = this.arms.get(projectId)+ if (!perNode?.delete(nodeId)) return+ if (!perNode.size) this.arms.delete(projectId)+ await this.persist()+ }++ /** Drop arm records for projects that no longer exist (the index is forever, a canvas churns).+ * Callers pass the live project id set; unknown-project records are consent for nothing. */+ async pruneProjects(liveProjectIds: Iterable<string>): Promise<void> {+ const live = new Set(liveProjectIds)+ let changed = false+ for (const projectId of [...this.arms.keys()]) {+ if (live.has(projectId)) continue+ this.arms.delete(projectId)+ changed = true+ }+ if (changed) await this.persist()+ }++ /** Drop arm records for nodes no longer on the project's canvas. */+ async pruneNodes(projectId: string, liveNodeIds: Iterable<string>): Promise<void> {+ const perNode = this.arms.get(projectId)+ if (!perNode) return+ const live = new Set(liveNodeIds)+ let changed = false+ for (const nodeId of [...perNode.keys()]) {+ if (live.has(nodeId)) continue+ perNode.delete(nodeId)+ changed = true+ }+ if (!changed) return+ if (!perNode.size) this.arms.delete(projectId)+ await this.persist()+ }++ private toFile(): TriggerArmFileV1 {+ const projects: Record<string, Record<string, TriggerArmRecord>> = {}+ for (const [projectId, perNode] of this.arms)+ projects[projectId] = Object.fromEntries(perNode)+ return { version: 1, projects }+ }++ private persist(): Promise<void> {+ const snapshot = JSON.stringify(this.toFile())+ const run = this.writeQueue.then(async () => {+ await fs.mkdir(this.userDataDir, { recursive: true })+ await writeFileAtomic(this.filePath, snapshot, { mode: 0o600 })+ })+ // A failed write must reach the caller, but must not wedge the queue for every later write.+ this.writeQueue = run.catch(() => {})+ return run+ }+}diff --git a/src/core/workspace-files.trigger.test.ts b/src/core/workspace-files.trigger.test.tsnew file mode 100644index 000000000..5dc561660--- /dev/null+++ b/src/core/workspace-files.trigger.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from 'vitest'+import type { CanvasNodeState, Project } from '../shared/types'+import type { TriggerSpec } from '../shared/trigger'+import { fileToProject, projectToFile, sanitizeNodeTriggers } from './workspace-files'++const spec = (): TriggerSpec => ({+ schedule: { kind: 'cron', expr: '0 9 * * 1-5' },+ payload: 'npm run report',+ target: 'term-tgt-1',+ note: 'daily report'+})++const triggerNode = (extra?: Partial<CanvasNodeState>): CanvasNodeState => ({+ id: 'trigger-a-1',+ kind: 'trigger',+ position: { x: 10, y: 20 },+ size: { width: 300, height: 170 },+ title: 'Daily report',+ color: '#888',+ group: null,+ trigger: spec(),+ ...extra+})++const project = (nodes: CanvasNodeState[]): Project => ({+ id: 'project-1',+ name: 'Test',+ color: '#fff',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes+})++describe('sanitizeNodeTriggers', () => {+ it('keeps a valid spec on a trigger node and normalizes it', () => {+ const smuggled = { ...triggerNode(), trigger: { ...spec(), armed: true } as never }+ const [out] = sanitizeNodeTriggers([smuggled])+ expect(out.trigger).toEqual(spec())+ expect(Object.keys(out.trigger!)).not.toContain('armed')+ })++ it('drops a malformed spec — the node survives, inert', () => {+ const [out] = sanitizeNodeTriggers([+ triggerNode({ trigger: { schedule: { kind: 'weekly' } } as never })+ ])+ expect(out.id).toBe('trigger-a-1')+ expect(out.trigger).toBeUndefined()+ })++ it('drops a trigger spec sitting on a non-trigger node', () => {+ const [out] = sanitizeNodeTriggers([triggerNode({ kind: 'terminal' })])+ expect(out.trigger).toBeUndefined()+ })++ it('leaves nodes without a spec untouched (identity preserved)', () => {+ const plain = triggerNode({ trigger: undefined })+ delete (plain as { trigger?: unknown }).trigger+ const [out] = sanitizeNodeTriggers([plain])+ expect(out).toBe(plain)+ })+})++describe('project file boundary', () => {+ it('round-trips a valid trigger node through projectToFile → fileToProject', () => {+ const file = projectToFile(project([triggerNode()]), 1, '2026-08-29T00:00:00Z')+ expect(file.nodes[0].trigger).toEqual(spec())+ const back = fileToProject(file, { id: 'project-1' })+ expect(back.nodes[0].kind).toBe('trigger')+ expect(back.nodes[0].trigger).toEqual(spec())+ })++ it('a hostile file cannot deliver a malformed or misplaced spec', () => {+ const file = projectToFile(project([triggerNode()]), 1, '2026-08-29T00:00:00Z')+ const hostile = {+ ...file,+ nodes: [+ { ...file.nodes[0], trigger: { ...spec(), payload: 'x'.repeat(20_000) } },+ { ...triggerNode({ id: 'term-b-1', kind: 'terminal' }) }+ ]+ }+ const back = fileToProject(hostile, { id: 'project-1' })+ expect(back.nodes[0].trigger).toBeUndefined()+ expect(back.nodes[1].trigger).toBeUndefined()+ })++ it('never writes a malformed spec into the shared file', () => {+ const bad = triggerNode({ trigger: { schedule: null } as never })+ const file = projectToFile(project([bad]), 1, '2026-08-29T00:00:00Z')+ expect(file.nodes[0].trigger).toBeUndefined()+ })++ it('the shared file carries no arm state in any shape', () => {+ // The machine-local arm store is the ONLY carrier of consent; the file's serialized bytes+ // must never contain an armed-looking field, whatever a future refactor threads through.+ const file = projectToFile(project([triggerNode()]), 1, '2026-08-29T00:00:00Z')+ const raw = JSON.stringify(file)+ expect(raw).not.toMatch(/armed/i)+ expect(raw).not.toMatch(/localTriggerArm/)+ })+})diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex 4cee1655b..277507e28 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -11,6 +11,7 @@ import type { BridgeLink, CanvasNodeState, NavStop, Project, ProjectKanban, Viewimport { projectCapabilityFields, readProjectCapabilities } from '../shared/project-capabilities'import { loadedAgentBrowserPartition } from '../shared/browser-partition'import { sanitizeProjectIcon, type ProjectIcon } from '../shared/project-icon'+import { sanitizeTriggerSpec } from '../shared/trigger'/*** Drop a browser node's persisted `partition` unless it is exactly the jar THIS project (its@@ -29,6 +30,28 @@ function sanitizeBrowserPartitions(nodes: CanvasNodeState[], projectId: string):})}+/**+ * The trigger twin of `sanitizeBrowserPartitions`, applied on every path a node array crosses the+ * shared-file boundary (read AND write): a `trigger` spec is git-shared CONTENT (the team shares+ * the schedule), but the file is hostile input, so only a spec that passes the strict shape rules+ * survives — a malformed shape, an oversized payload, a smuggled extra key, or a spec sitting on a+ * non-trigger node all degrade to an INERT node with no spec, never a crash and never a+ * half-honored value. Note what this deliberately does NOT decide: whether the trigger may FIRE on+ * this machine — that is the machine-local arm store's question (`core/trigger-arm-store.ts`), and+ * a freshly loaded file can never answer it. See @shared/trigger for the trust model.+ */+export function sanitizeNodeTriggers(nodes: CanvasNodeState[]): CanvasNodeState[] {+ return nodes.map((n) => {+ if (n.trigger === undefined) return n+ if (n.kind === 'trigger') {+ const safe = sanitizeTriggerSpec(n.trigger)+ if (safe) return { ...n, trigger: safe }+ }+ const { trigger: _dropped, ...rest } = n+ return rest+ })+}+export const PROJECT_DIR = '.nodeterm'export const PROJECT_FILE = 'project.json'@@ -225,7 +248,12 @@ export function projectToFile(// The project file is a SHARED document (git, or the remote host). Exec-enabling node fields// (`shell`, `ssh.extraArgs`) never leave this machine in it — they ride the machine-local index// entry instead (`localNodeExec` / `IndexEntryV3.localExec`). See @shared/node-exec.- const nodes = stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)+ // Trigger specs are additionally normalized on the way OUT too, so a malformed spec that+ // reached the live nodes some other way (a peer mutation, a hand edit) is never written into+ // the shared file as if it were ours.+ const nodes = sanitizeNodeTriggers(+ stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)+ )const icon = sanitizeProjectIcon(p.icon)return {version: 1,@@ -306,9 +334,11 @@ export function fileToProject(// `partition` survives only when it is exactly the one THIS project (base.id, machine-local)// would mint — a foreign/cloned/unsafe one drops to un-owned default session. See// loadedAgentBrowserPartition; without it a cloned project.json forges another project's jar.- nodes: sanitizeBrowserPartitions(- applyLocalNodeExec(base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes, base.localExec),- base.id+ nodes: sanitizeNodeTriggers(+ sanitizeBrowserPartitions(+ applyLocalNodeExec(base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes, base.localExec),+ base.id+ )),...(f.bridges ? { bridges: f.bridges } : {}),...(f.ropes ? { ropes: f.ropes } : {}),diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex d8f310346..defa9ce9b 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -10,7 +10,7 @@ import {} from '../shared/types'import {PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, resolveNodes, sameProjectContent,- serializeProjectFile, splitWorkspace, validKanban,+ sanitizeNodeTriggers, serializeProjectFile, splitWorkspace, validKanban,type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3} from './workspace-files'import { readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'@@ -262,9 +262,11 @@ export class WorkspaceStore {for (const e of index.entries) {if (e.project) {// Inline projects are stored verbatim in the index (no fileToProject pass), so apply the- // same kanban shape guard here — a v1/hand-edited board would otherwise crash the render.+ // same kanban shape guard here — a v1/hand-edited board would otherwise crash the render —+ // and the same trigger shape rule (workspace.json is hand-editable input too).const { kanban, ...rest } = e.project- built.push({ entry: e, project: validKanban(kanban) ? e.project : rest })+ const base = validKanban(kanban) ? e.project : rest+ built.push({ entry: e, project: { ...base, nodes: sanitizeNodeTriggers(base.nodes) } })} else if (e.cwd) {if (sideline) await sweepStaleTmp(projectFilePath(e.cwd))const read = await this.readProjectFile(e.cwd, sideline)diff --git a/src/renderer/lib/nodeSizing.ts b/src/renderer/lib/nodeSizing.tsindex c9451d7bb..ba26b8abd 100644--- a/src/renderer/lib/nodeSizing.ts+++ b/src/renderer/lib/nodeSizing.ts@@ -21,7 +21,8 @@ export const NODE_MIN_SIZES: Record<NodeKind, { width: number; height: number }>browser: { width: 360, height: 240 },subagent: { width: 180, height: 84 },loop: { width: 180, height: 84 },- dino: { width: 400, height: 160 }+ dino: { width: 400, height: 160 },+ trigger: { width: 240, height: 120 }}export interface Rect {diff --git a/src/renderer/state/workspace.trigger.test.ts b/src/renderer/state/workspace.trigger.test.tsnew file mode 100644index 000000000..f9bd86800--- /dev/null+++ b/src/renderer/state/workspace.trigger.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'+import type { CanvasNodeState } from '@shared/types'+import type { TriggerSpec } from '@shared/trigger'+import { flowToNodeStates, nodeStatesToFlow } from './workspace'++const spec = (): TriggerSpec => ({+ schedule: { kind: 'interval', everyMinutes: 30 },+ payload: 'npm test',+ target: 'term-tgt-1'+})++const state = (): CanvasNodeState => ({+ id: 'trigger-a-1',+ kind: 'trigger',+ position: { x: 5, y: 6 },+ size: { width: 300, height: 170 },+ title: 'Every 30m',+ color: '#888',+ group: null,+ trigger: spec()+})++describe('trigger node serialization', () => {+ it('nodeStatesToFlow carries the spec into node data', () => {+ const [flow] = nodeStatesToFlow([state()])+ expect(flow.type).toBe('trigger')+ expect(flow.data.trigger).toEqual(spec())+ })++ it('round-trips through flowToNodeStates without loss', () => {+ const [back] = flowToNodeStates(nodeStatesToFlow([state()]))+ expect(back.kind).toBe('trigger')+ expect(back.trigger).toEqual(spec())+ expect(back.id).toBe('trigger-a-1')+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex d74256221..b999f795d 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -47,6 +47,7 @@ export const WORKTREE_GROUP_SIZE = { width: 760, height: 540 }const EDITOR_SIZE = { width: 660, height: 460 }const DIFF_SIZE = { width: 860, height: 500 }const DINO_SIZE = { width: 600, height: 200 }+const TRIGGER_SIZE = { width: 300, height: 170 }const VIDEO_SIZE = { width: 640, height: 420 }const WEB_SIZE = { width: 720, height: 520 }const BROWSER_SIZE = { width: 800, height: 560 }@@ -164,6 +165,12 @@ export interface NodeData {* SSH-project editor still routes to the remote fs after reopen.*/sshFs?: boolean+ /**+ * trigger-only: the schedule + payload + target of a trigger node (issue #493). Persisted as+ * git-shared content and sanitized on every load path; whether it may FIRE on this machine is+ * the machine-local arm store's question, never this field's. See @shared/trigger.+ */+ trigger?: import('@shared/trigger').TriggerSpec[key: string]: unknown}@@ -1696,7 +1703,8 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {ssh: n.ssh,sshRemoteTmux: n.sshRemoteTmux,sshFs: n.sshFs,- worktree: n.worktree+ worktree: n.worktree,+ trigger: n.trigger}}})@@ -1722,7 +1730,9 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {? WEB_SIZE: kind === 'dino'? DINO_SIZE- : TERMINAL_SIZE+ : kind === 'trigger'+ ? TRIGGER_SIZE+ : TERMINAL_SIZEreturn nodes.map((n) => {const kind: NodeKind = (n.type as NodeKind) ?? 'terminal'@@ -1767,6 +1777,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {sshRemoteTmux: n.data.sshRemoteTmux,sshFs: n.data.sshFs,worktree: n.data.worktree,+ trigger: n.data.trigger,premaxRect: n.data.premaxRect}})diff --git a/src/shared/trigger.test.ts b/src/shared/trigger.test.tsnew file mode 100644index 000000000..68a9bd3b2--- /dev/null+++ b/src/shared/trigger.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest'+import {+ TRIGGER_INTERVAL_MAX_MINUTES,+ TRIGGER_NOTE_MAX,+ TRIGGER_PAYLOAD_MAX,+ canonicalTriggerSpec,+ sanitizeTriggerSpec,+ type TriggerSpec+} from './trigger'++const valid = (): TriggerSpec => ({+ schedule: { kind: 'cron', expr: '0 9 * * 1-5' },+ payload: 'npm run report',+ target: 'term-abc123-1'+})++describe('sanitizeTriggerSpec', () => {+ it('accepts a valid cron spec and rebuilds it with only the known fields', () => {+ const out = sanitizeTriggerSpec({ ...valid(), armed: true, extra: { deep: 1 } })+ expect(out).toEqual(valid())+ // The rebuild is the smuggling defense: an `armed` (or any unknown) key from a hostile file+ // must not survive a load/save round trip.+ expect(Object.keys(out!)).toEqual(['schedule', 'payload', 'target'])+ expect(Object.keys(out!.schedule)).toEqual(['kind', 'expr'])+ })++ it('accepts interval and once schedules', () => {+ expect(+ sanitizeTriggerSpec({ ...valid(), schedule: { kind: 'interval', everyMinutes: 30 } })+ ).toEqual({ ...valid(), schedule: { kind: 'interval', everyMinutes: 30 } })+ expect(+ sanitizeTriggerSpec({ ...valid(), schedule: { kind: 'once', at: '2026-09-01T09:00:00Z' } })+ ).toEqual({ ...valid(), schedule: { kind: 'once', at: '2026-09-01T09:00:00Z' } })+ })++ it('keeps a valid note and drops an invalid one without refusing the spec', () => {+ expect(sanitizeTriggerSpec({ ...valid(), note: 'daily report' })).toEqual({+ ...valid(),+ note: 'daily report'+ })+ expect(sanitizeTriggerSpec({ ...valid(), note: 42 })).toEqual(valid())+ expect(sanitizeTriggerSpec({ ...valid(), note: 'x'.repeat(TRIGGER_NOTE_MAX + 1) })).toEqual(+ valid()+ )+ })++ it('refuses non-objects and missing parts', () => {+ expect(sanitizeTriggerSpec(undefined)).toBeUndefined()+ expect(sanitizeTriggerSpec(null)).toBeUndefined()+ expect(sanitizeTriggerSpec('cron')).toBeUndefined()+ expect(sanitizeTriggerSpec({})).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), schedule: undefined })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), payload: undefined })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), target: undefined })).toBeUndefined()+ })++ it('refuses malformed schedules', () => {+ const withSchedule = (schedule: unknown) => sanitizeTriggerSpec({ ...valid(), schedule })+ expect(withSchedule({ kind: 'cron', expr: '' })).toBeUndefined()+ expect(withSchedule({ kind: 'cron', expr: 42 })).toBeUndefined()+ expect(withSchedule({ kind: 'cron', expr: 'x'.repeat(257) })).toBeUndefined()+ expect(withSchedule({ kind: 'cron', expr: '0 9 * * *\u001b[2J' })).toBeUndefined()+ expect(withSchedule({ kind: 'interval', everyMinutes: 0 })).toBeUndefined()+ expect(withSchedule({ kind: 'interval', everyMinutes: 1.5 })).toBeUndefined()+ expect(withSchedule({ kind: 'interval', everyMinutes: -5 })).toBeUndefined()+ expect(+ withSchedule({ kind: 'interval', everyMinutes: TRIGGER_INTERVAL_MAX_MINUTES + 1 })+ ).toBeUndefined()+ expect(withSchedule({ kind: 'once', at: 'not-a-date' })).toBeUndefined()+ expect(withSchedule({ kind: 'once', at: '' })).toBeUndefined()+ expect(withSchedule({ kind: 'constructor' })).toBeUndefined()+ expect(withSchedule({ kind: 'weekly' })).toBeUndefined()+ })++ it('refuses payloads that are empty, oversized, or carry control bytes', () => {+ expect(sanitizeTriggerSpec({ ...valid(), payload: '' })).toBeUndefined()+ expect(+ sanitizeTriggerSpec({ ...valid(), payload: 'x'.repeat(TRIGGER_PAYLOAD_MAX + 1) })+ ).toBeUndefined()+ // Raw ESC — the bracketed-paste-escape injection class. Refused whole, never stripped.+ expect(sanitizeTriggerSpec({ ...valid(), payload: 'echo hi\u001b[201~rm -rf /' })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), payload: 'a\u0000b' })).toBeUndefined()+ // Multi-line (\n, \t, \r) is legitimate — the paste path frames it.+ expect(sanitizeTriggerSpec({ ...valid(), payload: 'line1\n\tline2\r\n' })).toBeDefined()+ })++ it('refuses targets that are not safe node ids', () => {+ expect(sanitizeTriggerSpec({ ...valid(), target: '' })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), target: 'a; rm -rf /' })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), target: '..' })).toBeUndefined()+ expect(sanitizeTriggerSpec({ ...valid(), target: 'x'.repeat(200) })).toBeUndefined()+ })+})++describe('canonicalTriggerSpec', () => {+ it('is independent of input key order', () => {+ const a = sanitizeTriggerSpec({+ target: 'term-a-1',+ payload: 'p',+ schedule: { expr: '* * * * *', kind: 'cron' }+ })!+ const b = sanitizeTriggerSpec({+ schedule: { kind: 'cron', expr: '* * * * *' },+ payload: 'p',+ target: 'term-a-1'+ })!+ expect(canonicalTriggerSpec(a)).toBe(canonicalTriggerSpec(b))+ })++ it('changes when any bound field changes', () => {+ const base = canonicalTriggerSpec(valid())+ expect(canonicalTriggerSpec({ ...valid(), payload: 'npm run report2' })).not.toBe(base)+ expect(canonicalTriggerSpec({ ...valid(), target: 'term-abc123-2' })).not.toBe(base)+ expect(+ canonicalTriggerSpec({ ...valid(), schedule: { kind: 'cron', expr: '0 8 * * 1-5' } })+ ).not.toBe(base)+ })+})diff --git a/src/shared/trigger.ts b/src/shared/trigger.tsnew file mode 100644index 000000000..446b2cf9e--- /dev/null+++ b/src/shared/trigger.ts@@ -0,0 +1,142 @@+/**+ * The persisted shape + validation rules of a `trigger` node — a canvas-owned schedule that fires+ * a payload into a connected terminal/agent node (issue #493).+ *+ * TRUST MODEL, stated once because every rule below follows from it: the spec lives on the node in+ * `.nodeterm/project.json`, which is HOSTILE input — git-shared, hand-editable, auto-adopted by+ * "Open folder…", and for an SSH project it lives on the remote host (see @shared/node-exec for+ * the precedent). A trigger definition alone must therefore NEVER cause execution. Firing+ * additionally requires a MACHINE-LOCAL arm record (`core/trigger-arm-store.ts`) that binds this+ * machine's consent to the exact spec content on screen when the user armed it+ * (`canonicalTriggerSpec`). A spec that arrives — or silently changes — via git pull is visible+ * but inert until someone on this machine arms it (again).+ *+ * Two consequences for the shape rules here:+ * - `sanitizeTriggerSpec` REBUILDS the object from known fields only, so a file cannot smuggle+ * extra keys (an `armed: true`, a prototype-polluting key) through a load/save round trip.+ * - Anything malformed degrades to `undefined` = an inert node with no spec — never a crash,+ * never a "nearest match" repair that silently changes what would run (the same rule as+ * `permissionModeFlag`: an unrecognized value yields the safe nothing).+ */++import { isSafeNodeId } from './safe-id'++/** When the trigger fires. `cron` grammar is validated by the scheduler (the one parser is the+ * authority); here only shape/charset/size are enforced, so an expression the parser refuses+ * renders as "invalid schedule" instead of half-running. */+export type TriggerSchedule =+ | { kind: 'cron'; expr: string }+ | { kind: 'interval'; everyMinutes: number }+ | { kind: 'once'; at: string }++export interface TriggerSpec {+ schedule: TriggerSchedule+ /**+ * Delivered into the target's pane via the `sendText` paste path when the trigger fires (multi-+ * line is fine — `paste-buffer -p` frames it). Content-validated here AND re-sanitized at the+ * delivery site: schema acceptance is not an execution license.+ */+ payload: string+ /** Node id of the terminal/agent node the payload is delivered to. */+ target: string+ /** Optional human note shown on the card. */+ note?: string+}++/** Same cap as BOARD_LOG_TEXT_MAX — far beyond any real prompt, small enough to bound. */+export const TRIGGER_PAYLOAD_MAX = 16_384+export const TRIGGER_CRON_MAX = 256+export const TRIGGER_NOTE_MAX = 500+export const TRIGGER_ONCE_AT_MAX = 64+export const TRIGGER_INTERVAL_MIN_MINUTES = 1+/** One year. An interval is minutes-granular like cron; anything longer is a `once`. */+export const TRIGGER_INTERVAL_MAX_MINUTES = 366 * 24 * 60++/** Printable ASCII only — a cron expression is ASCII by definition, and this keeps control+ * sequences out of a string that gets rendered and logged. */+const CRON_CHARSET = /^[\x20-\x7e]+$/++/**+ * C0 control characters except \t \n \r, plus DEL. A payload is something the user typed to run+ * in a pane; a raw ESC/C0 byte in it is either an accident or a terminal-injection attempt+ * (bracketed-paste escapes), so the whole spec is refused rather than silently rewritten.+ * The delivery path strips again at the interpolation site — this is the schema's half.+ */+const PAYLOAD_FORBIDDEN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/++function sanitizeSchedule(value: unknown): TriggerSchedule | undefined {+ if (!value || typeof value !== 'object') return undefined+ const s = value as { kind?: unknown; expr?: unknown; everyMinutes?: unknown; at?: unknown }+ if (s.kind === 'cron') {+ if (typeof s.expr !== 'string') return undefined+ const expr = s.expr.trim()+ if (!expr || expr.length > TRIGGER_CRON_MAX || !CRON_CHARSET.test(expr)) return undefined+ return { kind: 'cron', expr }+ }+ if (s.kind === 'interval') {+ const m = s.everyMinutes+ if (typeof m !== 'number' || !Number.isInteger(m)) return undefined+ if (m < TRIGGER_INTERVAL_MIN_MINUTES || m > TRIGGER_INTERVAL_MAX_MINUTES) return undefined+ return { kind: 'interval', everyMinutes: m }+ }+ if (s.kind === 'once') {+ if (typeof s.at !== 'string' || !s.at || s.at.length > TRIGGER_ONCE_AT_MAX) return undefined+ if (!Number.isFinite(Date.parse(s.at))) return undefined+ return { kind: 'once', at: s.at }+ }+ return undefined+}++/**+ * Strict shape rule for a trigger spec read from ANY untrusted carrier (the project file, the+ * ssh cache, a wire frame). Returns a REBUILT object holding only the known fields, or+ * `undefined` when any required part fails — the caller drops the spec and the node is inert.+ * An invalid optional `note` is dropped alone (it never executes anything).+ */+export function sanitizeTriggerSpec(value: unknown): TriggerSpec | undefined {+ if (!value || typeof value !== 'object') return undefined+ const t = value as { schedule?: unknown; payload?: unknown; target?: unknown; note?: unknown }+ const schedule = sanitizeSchedule(t.schedule)+ if (!schedule) return undefined+ if (typeof t.payload !== 'string' || !t.payload || t.payload.length > TRIGGER_PAYLOAD_MAX)+ return undefined+ if (PAYLOAD_FORBIDDEN.test(t.payload)) return undefined+ if (typeof t.target !== 'string' || !isSafeNodeId(t.target)) return undefined+ const note =+ typeof t.note === 'string' && t.note.length > 0 && t.note.length <= TRIGGER_NOTE_MAX+ ? t.note+ : undefined+ return {+ schedule,+ payload: t.payload,+ target: t.target,+ ...(note !== undefined ? { note } : {})+ }+}++/**+ * Deterministic serialization of a spec, used as the ARM BINDING: the machine-local arm store+ * records this string at arm time, and the scheduler fires only while the node's CURRENT spec+ * canonicalizes to the same string. That is what turns "arm once" into consent for one exact+ * payload/schedule/target — a git pull that edits any of them lands the trigger back in the+ * disarmed state instead of running the new content under the old consent.+ *+ * Determinism comes from construction (fixed key order, no reliance on input key order), so it+ * must only ever be fed a spec that went through `sanitizeTriggerSpec` — enforce that at the+ * call site rather than re-validating here.+ */+export function canonicalTriggerSpec(spec: TriggerSpec): string {+ const s = spec.schedule+ const schedule =+ s.kind === 'cron'+ ? { kind: s.kind, expr: s.expr }+ : s.kind === 'interval'+ ? { kind: s.kind, everyMinutes: s.everyMinutes }+ : { kind: s.kind, at: s.at }+ return JSON.stringify({+ schedule,+ payload: spec.payload,+ target: spec.target,+ ...(spec.note !== undefined ? { note: spec.note } : {})+ })+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 54821c517..4ccd6b1b0 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -270,7 +270,9 @@ export interface RecycledInfo {}// 'subagent' and 'loop' are render-only (ephemeral hook-driven viz) and never persisted.-export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'video' | 'web' | 'browser' | 'subagent' | 'loop' | 'dino'+// 'trigger' is a first-class PERSISTED kind (issue #493) — the canvas-owned schedule node; its+// spec rides `CanvasNodeState.trigger` and is sanitized on every load path (@shared/trigger).+export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'video' | 'web' | 'browser' | 'subagent' | 'loop' | 'dino' | 'trigger'/** Persisted state of a single canvas node (terminal, sticky note, group frame, or editor). *//**@@ -390,6 +392,14 @@ export interface CanvasNodeState {commitOid?: string/** group-only: when bound, the git worktree this group works in. */worktree?: GroupWorktree+ /**+ * trigger-only: the schedule + payload + target this node represents (issue #493). Git-shared+ * CONTENT — deliberately, the team shares the definition — which is exactly why it is treated+ * as hostile on every load path (`sanitizeNodeTriggers` in core/workspace-files) and why the+ * definition alone never fires: execution additionally requires this machine's arm record+ * (`core/trigger-arm-store.ts`), bound to the spec's exact content. See @shared/trigger.+ */+ trigger?: import('./trigger').TriggerSpec/*** Set while the node is maximized to fill the viewport (issue #399): the rect to give back on* the toggle's second click — the node's ROOT-space (absolute canvas) position plus its size.