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): host-side scheduler in core, booted by both shells (#493 phase 2)
enes2e6112f8bcd9
diff --git a/CLAUDE.md b/CLAUDE.mdindex d55f2e114..c7194e277 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -137,8 +137,11 @@ group transforms (`groupSelectedNodes`, `ungroupNodes`, `duplicateNode`), and th`nodeStatesToFlow` / `flowToNodeStates` serializers. Node kinds (`NodeKind` in`src/shared/types.ts`): `terminal | sticky | group | editor | diff | video | web | browser |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`,+viz) and never persisted. `trigger` (issue #493, landing in phases — schema + the core+scheduler so far: `core/trigger-scheduler.ts`, booted by BOTH shells, sweep-service shape,+fire-time `TriggerArmStore.isArmed` re-ask, no catch-up for missed slots, cron matched by the+dependency-free `@shared/cron` with the vixie dom/dow OR rule; delivery + renderer still to come)+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 themachine-local, content-bound `core/trigger-arm-store.ts` (a spec that arrives or CHANGES via gitdiff --git a/src/core/trigger-scheduler.test.ts b/src/core/trigger-scheduler.test.tsnew file mode 100644index 000000000..0c1ae310b--- /dev/null+++ b/src/core/trigger-scheduler.test.ts@@ -0,0 +1,257 @@+import { describe, expect, it, vi } from 'vitest'+import type { CanvasNodeState } from '../shared/types'+import type { TriggerSpec } from '../shared/trigger'+import {+ computeNextFire,+ createTriggerScheduler,+ triggerRowsFromCanvases,+ type TriggerFireResult,+ type TriggerRow+} from './trigger-scheduler'++const MIN = 60_000+const T0 = new Date(2026, 8, 2, 12, 0).getTime()++const intervalSpec = (everyMinutes = 5): TriggerSpec => ({+ schedule: { kind: 'interval', everyMinutes },+ payload: 'npm test',+ target: 'term-tgt-1'+})++interface Harness {+ clock: { t: number }+ rows: TriggerRow[]+ armed: Set<string>+ fires: TriggerRow[]+ fire: ReturnType<typeof vi.fn>+ scheduler: ReturnType<typeof createTriggerScheduler>+}++function harness(fireImpl?: (row: TriggerRow) => Promise<TriggerFireResult>): Harness {+ const clock = { t: T0 }+ const rows: TriggerRow[] = []+ const armed = new Set<string>()+ const fires: TriggerRow[] = []+ const fire = vi.fn(+ fireImpl ??+ (async (row: TriggerRow) => {+ fires.push(row)+ return { ok: true }+ })+ )+ const scheduler = createTriggerScheduler({+ listTriggers: () => rows,+ isArmed: (p, n) => armed.has(`${p}/${n}`),+ fire,+ now: () => clock.t+ })+ return { clock, rows, armed, fires, fire, scheduler }+}++describe('triggerRowsFromCanvases', () => {+ it('collects valid trigger nodes and drops everything else', () => {+ const nodes: CanvasNodeState[] = [+ {+ id: 'trigger-a-1', kind: 'trigger', position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: '', color: '', group: null,+ trigger: intervalSpec()+ },+ {+ id: 'trigger-bad-1', kind: 'trigger', position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: '', color: '', group: null,+ trigger: { schedule: { kind: 'weekly' } } as never+ },+ {+ id: 'term-c-1', kind: 'terminal', position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: '', color: '', group: null+ }+ ]+ const out = triggerRowsFromCanvases([{ id: 'project-1', nodes }])+ expect(out).toHaveLength(1)+ expect(out[0]).toMatchObject({ projectId: 'project-1', nodeId: 'trigger-a-1' })+ })+})++describe('computeNextFire', () => {+ it('interval anchors to from, once honors only a future time', () => {+ expect(computeNextFire(intervalSpec(5), T0)).toBe(T0 + 5 * MIN)+ const future = new Date(T0 + 60 * MIN).toISOString()+ expect(+ computeNextFire({ ...intervalSpec(), schedule: { kind: 'once', at: future } }, T0)+ ).toBe(T0 + 60 * MIN)+ const past = new Date(T0 - MIN).toISOString()+ expect(+ computeNextFire({ ...intervalSpec(), schedule: { kind: 'once', at: past } }, T0)+ ).toBeNull()+ })++ it('an unparseable cron schedules nothing', () => {+ expect(+ computeNextFire({ ...intervalSpec(), schedule: { kind: 'cron', expr: 'not cron' } }, T0)+ ).toBeNull()+ })+})++describe('createTriggerScheduler', () => {+ it('fires an armed trigger when due — and asks the arm gate at FIRE time', async () => {+ const h = harness()+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce() // anchors: next = T0 + 5min+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 5 * MIN)++ h.clock.t = T0 + 5 * MIN+ await h.scheduler.sweepOnce() // due, but DISARMED → silent skip, schedule advances+ expect(h.fire).not.toHaveBeenCalled()+ expect(h.scheduler.runsFor('project-1', 'trigger-a-1')).toHaveLength(0)+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 10 * MIN)++ h.armed.add('project-1/trigger-a-1')+ h.clock.t = T0 + 10 * MIN+ await h.scheduler.sweepOnce()+ expect(h.fire).toHaveBeenCalledTimes(1)+ const runs = h.scheduler.runsFor('project-1', 'trigger-a-1')+ expect(runs).toHaveLength(1)+ expect(runs[0].outcome).toBe('fired')+ })++ it('no catch-up: sleeping through three intervals fires ONCE, re-anchored from now', async () => {+ const h = harness()+ h.armed.add('project-1/trigger-a-1')+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 17 * MIN // three slots (5, 10, 15) passed+ await h.scheduler.sweepOnce()+ expect(h.fire).toHaveBeenCalledTimes(1)+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 22 * MIN)+ })++ it('a spec edit re-anchors the schedule and is never due on the same sweep', async () => {+ const h = harness()+ h.armed.add('project-1/trigger-a-1')+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 5 * MIN+ h.rows[0] = { ...h.rows[0], spec: intervalSpec(30) } // edited right as the old slot came due+ await h.scheduler.sweepOnce()+ expect(h.fire).not.toHaveBeenCalled()+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 35 * MIN)+ })++ it('a spent `once` records a single honest miss — armed only — and never fires late', async () => {+ const h = harness()+ const past = new Date(T0 - 10 * MIN).toISOString()+ const spec: TriggerSpec = { ...intervalSpec(), schedule: { kind: 'once', at: past } }+ h.rows.push(+ { projectId: 'project-1', nodeId: 'trigger-armed-1', spec },+ { projectId: 'project-1', nodeId: 'trigger-clone-1', spec }+ )+ h.armed.add('project-1/trigger-armed-1')+ await h.scheduler.sweepOnce()+ await h.scheduler.sweepOnce()+ expect(h.fire).not.toHaveBeenCalled()+ const armedRuns = h.scheduler.runsFor('project-1', 'trigger-armed-1')+ expect(armedRuns).toHaveLength(1)+ expect(armedRuns[0].outcome).toBe('missed')+ // The disarmed clone (fresh from git) spams nothing.+ expect(h.scheduler.runsFor('project-1', 'trigger-clone-1')).toHaveLength(0)+ })++ it('a future `once` fires exactly once and is then spent', async () => {+ const h = harness()+ h.armed.add('project-1/trigger-a-1')+ const at = new Date(T0 + 10 * MIN).toISOString()+ h.rows.push({+ projectId: 'project-1', nodeId: 'trigger-a-1',+ spec: { ...intervalSpec(), schedule: { kind: 'once', at } }+ })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 11 * MIN+ await h.scheduler.sweepOnce()+ expect(h.fire).toHaveBeenCalledTimes(1)+ h.clock.t = T0 + 60 * MIN+ await h.scheduler.sweepOnce()+ expect(h.fire).toHaveBeenCalledTimes(1)+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBeNull()+ })++ it('a failed or throwing delivery records `failed` and the schedule keeps going', async () => {+ let call = 0+ const h = harness(async () => {+ call+++ if (call === 1) return { ok: false, detail: 'target not running' }+ throw new Error('boom')+ })+ h.armed.add('project-1/trigger-a-1')+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 5 * MIN+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 10 * MIN+ await h.scheduler.sweepOnce()+ const runs = h.scheduler.runsFor('project-1', 'trigger-a-1')+ expect(runs.map((r) => r.outcome)).toEqual(['failed', 'failed'])+ expect(runs[0].detail).toBe('target not running')+ expect(runs[1].detail).toBe('boom')+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 15 * MIN)+ })++ it('an in-flight delivery is not double-fired by an overlapping sweep', async () => {+ let release: (() => void) | undefined+ const h = harness(+ () =>+ new Promise<TriggerFireResult>((resolve) => {+ release = () => resolve({ ok: true })+ })+ )+ h.armed.add('project-1/trigger-a-1')+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 5 * MIN+ const slow = h.scheduler.sweepOnce() // enters fire, blocks+ await Promise.resolve()+ // The next slot comes due while the previous delivery is still in flight — the in-flight+ // guard must skip it rather than stack a second fire on the same trigger.+ h.clock.t = T0 + 10 * MIN+ await h.scheduler.sweepOnce()+ expect(h.fire).toHaveBeenCalledTimes(1)+ release!()+ await slow+ expect(h.scheduler.runsFor('project-1', 'trigger-a-1')).toHaveLength(1)+ })++ it('a deleted trigger drops its schedule state and run history', async () => {+ const h = harness()+ h.armed.add('project-1/trigger-a-1')+ h.rows.push({ projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) })+ await h.scheduler.sweepOnce()+ h.clock.t = T0 + 5 * MIN+ await h.scheduler.sweepOnce()+ expect(h.scheduler.runsFor('project-1', 'trigger-a-1')).toHaveLength(1)+ h.rows.length = 0+ await h.scheduler.sweepOnce()+ expect(h.scheduler.nextFireAt('project-1', 'trigger-a-1')).toBeNull()+ expect(h.scheduler.runsFor('project-1', 'trigger-a-1')).toHaveLength(0)+ })++ it('a listing failure changes no schedule state', async () => {+ const clock = { t: T0 }+ let throwNow = false+ const rows: TriggerRow[] = [+ { projectId: 'project-1', nodeId: 'trigger-a-1', spec: intervalSpec(5) }+ ]+ const scheduler = createTriggerScheduler({+ listTriggers: () => {+ if (throwNow) throw new Error('index unavailable')+ return rows+ },+ isArmed: () => true,+ fire: async () => ({ ok: true }),+ now: () => clock.t+ })+ await scheduler.sweepOnce()+ throwNow = true+ clock.t = T0 + 5 * MIN+ await scheduler.sweepOnce() // failure: neither fires nor forgets+ expect(scheduler.nextFireAt('project-1', 'trigger-a-1')).toBe(T0 + 5 * MIN)+ })+})diff --git a/src/core/trigger-scheduler.ts b/src/core/trigger-scheduler.tsnew file mode 100644index 000000000..338451011--- /dev/null+++ b/src/core/trigger-scheduler.ts@@ -0,0 +1,239 @@+/**+ * The host-side trigger scheduler (issue #493, phase 2) — the machinery that decides WHEN an+ * armed trigger node is due and asks the injected `fire` to deliver it. Runs in core, booted by+ * BOTH shells (desktop main and the Server Edition), with no renderer anywhere in the loop: a+ * headless SE with no browser tab open must still fire.+ *+ * Everything is injected (clock, trigger list, arm gate, delivery), in the sweep-service shape+ * `session-name-sweep.ts` established: `start()/stop()`, an unref'd interval, a short first pass+ * after boot, and a `sweepOnce()` the tests drive directly.+ *+ * The rules, each of which is a decision from the #493 design thread:+ * - **Host-alive v1.** Nothing here outlives the process; a fire that falls while the host is+ * down is not run later. `nextAt` is always computed from NOW — never from the missed slot —+ * so a host that slept through three intervals fires ONCE, not three times (no catch-up /+ * anacron semantics).+ * - **The arm gate is asked AT FIRE TIME**, per due trigger, never cached from plan time (the+ * same fire-time-re-ask rule Eco hibernation follows): `deps.isArmed` goes to the machine-local+ * `TriggerArmStore`, whose answer is bound to the spec's exact content. A disarmed (or+ * spec-drifted) trigger that comes due advances its schedule silently — being disarmed is a+ * state, not an event.+ * - **Specs are re-sanitized at this use site** (`triggerRowsFromCanvases` runs every row through+ * `sanitizeTriggerSpec`), whatever path the node object took to get here — the+ * `permissionModeFlag` rule. An invalid spec schedules nothing.+ * - **A `once` whose time already passed when first seen** (host was down, or the trigger just+ * arrived) records ONE honest `missed` run — if it is armed; a disarmed clone spams nothing —+ * and is done. It is never fired late.+ * - **An interval anchors to first sight**: next = now + everyMinutes. Deterministic enough for+ * v1 and honest about what an interval means on a host-alive scheduler; a wall-clock anchor is+ * what `cron` is for.+ * - **Exactly-once per due slot**: `nextAt` is advanced BEFORE the (async) fire is awaited, and+ * an in-flight key is skipped by later sweeps, so a slow delivery cannot double-fire.+ *+ * Run history is a per-trigger in-memory ring (RUNS_CAP) — machine-local by design (the shared+ * file must not churn per fire) and transient for now; phase 4's UI reads it via `runsFor` and+ * the `onRun` callback, and persistence can be added there if the card needs history across+ * restarts.+ */++import type { CanvasNodeState } from '../shared/types'+import { sanitizeTriggerSpec, type TriggerSpec } from '../shared/trigger'+import { nextCronFire, parseCron } from '../shared/cron'++export interface TriggerRow {+ projectId: string+ nodeId: string+ spec: TriggerSpec+}++/**+ * The trigger view of `WorkspaceStore.persistedCanvases()` — every valid trigger node across all+ * projects, spec re-sanitized at this use site. ONE definition consumed by both shells' wiring,+ * so the two cannot drift (the duplicated-gate lesson).+ */+export function triggerRowsFromCanvases(+ canvases: Array<{ id: string; nodes: CanvasNodeState[] }>+): TriggerRow[] {+ const rows: TriggerRow[] = []+ for (const canvas of canvases) {+ for (const n of canvas.nodes) {+ if (n.kind !== 'trigger' || n.trigger === undefined) continue+ const spec = sanitizeTriggerSpec(n.trigger)+ if (spec) rows.push({ projectId: canvas.id, nodeId: n.id, spec })+ }+ }+ return rows+}++export type TriggerRunOutcome = 'fired' | 'failed' | 'missed'++export interface TriggerRun {+ at: number+ outcome: TriggerRunOutcome+ detail?: string+}++export interface TriggerFireResult {+ ok: boolean+ detail?: string+}++export interface TriggerSchedulerDeps {+ /** Every persisted trigger node (see `triggerRowsFromCanvases`). */+ listTriggers: () => TriggerRow[]+ /** The machine-local, content-bound arm gate (`TriggerArmStore.isArmed`). */+ isArmed: (projectId: string, nodeId: string, spec: TriggerSpec) => boolean+ /** Deliver the payload (phase 3). Resolve `{ok:false}` — or throw — for a failed delivery. */+ fire: (row: TriggerRow) => Promise<TriggerFireResult>+ /** Observe every recorded run (UI feed later; optional). */+ onRun?: (projectId: string, nodeId: string, run: TriggerRun) => void+ now?: () => number+ intervalMs?: number+}++/** Sweep cadence. Schedules are minute-granular, so half-minute polling keeps worst-case firing+ * lag well under one schedule step while staying negligible (a pure in-memory pass). */+export const TRIGGER_SWEEP_MS = 30_000++/** Ring size of the per-trigger run history. */+export const TRIGGER_RUNS_CAP = 20++interface KeyState {+ canon: string+ /** Next due time (epoch ms); null = nothing scheduled (spent `once`, invalid cron). */+ nextAt: number | null+}++const keyOf = (projectId: string, nodeId: string): string => `${projectId}\n${nodeId}`++/** Next due time for a spec, from `fromMs`. Pure; `null` = never. */+export function computeNextFire(spec: TriggerSpec, fromMs: number): number | null {+ const s = spec.schedule+ if (s.kind === 'interval') return fromMs + s.everyMinutes * 60_000+ if (s.kind === 'once') {+ const at = Date.parse(s.at)+ return Number.isFinite(at) && at > fromMs ? at : null+ }+ const parsed = parseCron(s.expr)+ return parsed ? nextCronFire(parsed, fromMs) : null+}++export interface TriggerScheduler {+ start: () => void+ stop: () => void+ /** One pass over every trigger — what the interval runs, exposed for tests and shells. */+ sweepOnce: () => Promise<void>+ runsFor: (projectId: string, nodeId: string) => TriggerRun[]+ /** The computed next due time, or null — phase 4's card reads this for its countdown. */+ nextFireAt: (projectId: string, nodeId: string) => number | null+}++export function createTriggerScheduler(deps: TriggerSchedulerDeps): TriggerScheduler {+ const now = deps.now ?? Date.now+ const states = new Map<string, KeyState>()+ const runs = new Map<string, TriggerRun[]>()+ const inFlight = new Set<string>()+ let timer: ReturnType<typeof setInterval> | undefined+ let first: ReturnType<typeof setTimeout> | undefined++ const record = (projectId: string, nodeId: string, run: TriggerRun): void => {+ const key = keyOf(projectId, nodeId)+ const list = runs.get(key) ?? []+ list.push(run)+ if (list.length > TRIGGER_RUNS_CAP) list.splice(0, list.length - TRIGGER_RUNS_CAP)+ runs.set(key, list)+ deps.onRun?.(projectId, nodeId, run)+ }++ const sweepOnce = async (): Promise<void> => {+ let rows: TriggerRow[]+ try {+ rows = deps.listTriggers()+ } catch {+ return // a transient listing failure changes no schedule state+ }+ const t = now()+ const liveKeys = new Set<string>()+ const due: Array<{ row: TriggerRow; key: string }> = []++ for (const row of rows) {+ const key = keyOf(row.projectId, row.nodeId)+ liveKeys.add(key)+ const canon = JSON.stringify(row.spec)+ const st = states.get(key)+ if (!st || st.canon !== canon) {+ // New trigger, or its spec changed: (re)anchor the schedule from NOW — an edit is a+ // restart of the schedule, never a backfill of the old one's slots.+ const nextAt = computeNextFire(row.spec, t)+ states.set(key, { canon, nextAt })+ if (nextAt === null && row.spec.schedule.kind === 'once') {+ // The one-shot time passed while nobody was scheduling (host down, or the spec just+ // arrived). Honest `missed` — but only for a trigger this machine actually armed;+ // a disarmed clone from git must not spam records.+ if (deps.isArmed(row.projectId, row.nodeId, row.spec))+ record(row.projectId, row.nodeId, {+ at: t,+ outcome: 'missed',+ detail: 'scheduled time passed while the scheduler was not running'+ })+ }+ continue // never due on the sweep that (re)anchored it+ }+ if (st.nextAt !== null && t >= st.nextAt && !inFlight.has(key)) due.push({ row, key })+ }++ // Forget triggers that left the canvas (deleted node / project) — runs included.+ for (const key of [...states.keys()]) {+ if (liveKeys.has(key)) continue+ states.delete(key)+ runs.delete(key)+ }++ for (const { row, key } of due) {+ const st = states.get(key)+ if (!st) continue+ // Advance FIRST (exactly-once per slot, no catch-up), whatever happens below.+ st.nextAt = row.spec.schedule.kind === 'once' ? null : computeNextFire(row.spec, t)+ // Fire-time re-ask, never a plan-time verdict: the machine-local, content-bound arm gate.+ if (!deps.isArmed(row.projectId, row.nodeId, row.spec)) continue+ inFlight.add(key)+ try {+ const result = await deps.fire(row)+ record(row.projectId, row.nodeId, {+ at: now(),+ outcome: result.ok ? 'fired' : 'failed',+ ...(result.detail ? { detail: result.detail } : {})+ })+ } catch (e) {+ record(row.projectId, row.nodeId, {+ at: now(),+ outcome: 'failed',+ detail: e instanceof Error ? e.message : String(e)+ })+ } finally {+ inFlight.delete(key)+ }+ }+ }++ return {+ start: () => {+ if (timer) return+ timer = setInterval(() => void sweepOnce(), deps.intervalMs ?? TRIGGER_SWEEP_MS)+ timer.unref?.()+ // One pass shortly after boot: anchor every schedule (and surface passed `once`s) without+ // waiting a whole interval.+ first = setTimeout(() => void sweepOnce(), 5_000)+ first.unref?.()+ },+ stop: () => {+ if (timer) clearInterval(timer)+ if (first) clearTimeout(first)+ timer = undefined+ first = undefined+ },+ sweepOnce,+ runsFor: (projectId, nodeId) => [...(runs.get(keyOf(projectId, nodeId)) ?? [])],+ nextFireAt: (projectId, nodeId) => states.get(keyOf(projectId, nodeId))?.nextAt ?? null+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 299049fcd..0b4deb358 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,5 +1,7 @@import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'+import { TriggerArmStore } from '../core/trigger-arm-store'+import { createTriggerScheduler, triggerRowsFromCanvases } from '../core/trigger-scheduler'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'@@ -1762,6 +1764,19 @@ app.whenReady().then(async () => {// get it wrong, and getting it wrong is invisible — the wrong list silently skips an agent's// nodes with every test still green.})+ // Trigger nodes (issue #493, phase 2): the host-side scheduler. Same wiring as the Server+ // Edition's (src/server/index.ts) — the trigger list, the arm gate and the sweep all live in+ // core; this shell only supplies the seams. `fire` is a stub until the delivery phase lands,+ // and since nothing can ARM a trigger yet (no arm IPC/UI), a production trigger cannot reach+ // it — the stub exists so a due+armed trigger in a dev build records an honest failure+ // instead of pretending to run.+ const triggerArms = new TriggerArmStore(app.getPath('userData'))+ const triggerScheduler = createTriggerScheduler({+ listTriggers: () => triggerRowsFromCanvases(workspaceStore.persistedCanvases()),+ isArmed: (projectId, nodeId, spec) => triggerArms.isArmed(projectId, nodeId, spec),+ fire: async () => ({ ok: false, detail: 'delivery not wired yet (trigger phase 3)' })+ })+ void triggerArms.load().finally(() => triggerScheduler.start())// macOS Notch HUD (docs/notch-hud.md): walking agent mascots by the notch. darwin + setting only;// reads the same agent-status seams the mirror does. Live-toggled via settings below.//diff --git a/src/server/index.ts b/src/server/index.tsindex b83b224d7..14ba015f3 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1,6 +1,8 @@import fs from 'fs'import { readAgentSessionName } from '../core/agent-session-name'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'+import { TriggerArmStore } from '../core/trigger-arm-store'+import { createTriggerScheduler, triggerRowsFromCanvases } from '../core/trigger-scheduler'import path from 'path'import http from 'http'@@ -377,6 +379,17 @@ export async function startServer(// No `supports`: core's `supportsTitleRead` (TITLE_READ_CAPABLE) is the rule, and duplicating// it here is how the two shells drift — see the note in core/session-name-sweep.ts.})+ // Trigger nodes (issue #493, phase 2): the host-side scheduler — the reason it lives in core is+ // exactly this shell: a headless Server Edition with no browser tab open must still fire. Same+ // wiring as desktop main's; `fire` is a stub until the delivery phase, and with no arm IPC/UI+ // yet nothing can arm a trigger, so the stub is unreachable in production.+ const triggerArms = new TriggerArmStore(config.dataDir)+ const triggerScheduler = createTriggerScheduler({+ listTriggers: () => triggerRowsFromCanvases(workspaceStore.persistedCanvases()),+ isArmed: (projectId, nodeId, spec) => triggerArms.isArmed(projectId, nodeId, spec),+ fire: async () => ({ ok: false, detail: 'delivery not wired yet (trigger phase 3)' })+ })+ void triggerArms.load().finally(() => triggerScheduler.start())// Advertise launch settings to the mobile companion through the mirror (same provider the// desktop wires in src/main/index.ts). No SSH push exists server-side, so only the local// provider applies. The provider is consulted at every flush (heartbeat ≤60s), so a settingsdiff --git a/src/shared/cron.test.ts b/src/shared/cron.test.tsnew file mode 100644index 000000000..736fe1713--- /dev/null+++ b/src/shared/cron.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest'+import { nextCronFire, parseCron } from './cron'++// All expectations are built from LOCAL Date components, so they hold in any CI timezone.+const local = (+ y: number, mo: number, d: number, h = 0, mi = 0+): number => new Date(y, mo - 1, d, h, mi).getTime()++const next = (expr: string, fromMs: number): number | null => {+ const s = parseCron(expr)+ return s ? nextCronFire(s, fromMs) : null+}++describe('parseCron', () => {+ it('refuses malformed expressions', () => {+ expect(parseCron('')).toBeNull()+ expect(parseCron('* * * *')).toBeNull()+ expect(parseCron('* * * * * *')).toBeNull()+ expect(parseCron('60 * * * *')).toBeNull()+ expect(parseCron('* 24 * * *')).toBeNull()+ expect(parseCron('* * 0 * *')).toBeNull()+ expect(parseCron('* * 32 * *')).toBeNull()+ expect(parseCron('* * * 13 *')).toBeNull()+ expect(parseCron('* * * * 8')).toBeNull()+ expect(parseCron('*/0 * * * *')).toBeNull()+ expect(parseCron('5-2 * * * *')).toBeNull()+ expect(parseCron('a * * * *')).toBeNull()+ expect(parseCron('1;2 * * * *')).toBeNull()+ expect(parseCron('1//2 * * * *')).toBeNull()+ })++ it('accepts names, steps, ranges, lists, and dow 7 as Sunday', () => {+ expect(parseCron('0 9 * jan-mar mon,fri')).not.toBeNull()+ expect(parseCron('*/15 0-6/2 1,15 * *')).not.toBeNull()+ const sunday7 = parseCron('0 0 * * 7')!+ expect(sunday7.dow[0]).toBe(true)+ const sunday0 = parseCron('0 0 * * sun')!+ expect(sunday0.dow[0]).toBe(true)+ })+})++describe('nextCronFire', () => {+ it('finds the next minute strictly after `from`', () => {+ // 2026-09-02 is a Wednesday.+ const from = local(2026, 9, 2, 12, 0)+ expect(next('* * * * *', from)).toBe(local(2026, 9, 2, 12, 1))+ // A time exactly on a match is not returned — strictly after.+ expect(next('0 12 * * *', from)).toBe(local(2026, 9, 3, 12, 0))+ })++ it('handles hour/day/month skips', () => {+ const from = local(2026, 9, 2, 15, 30)+ expect(next('0 9 * * *', from)).toBe(local(2026, 9, 3, 9, 0))+ expect(next('30 8 1 * *', from)).toBe(local(2026, 10, 1, 8, 30))+ expect(next('0 0 * feb *', from)).toBe(local(2027, 2, 1, 0, 0))+ })++ it('applies steps and ranges', () => {+ const from = local(2026, 9, 2, 12, 7)+ expect(next('*/15 * * * *', from)).toBe(local(2026, 9, 2, 12, 15))+ expect(next('5/20 * * * *', from)).toBe(local(2026, 9, 2, 12, 25))+ expect(next('0 9-17 * * *', local(2026, 9, 2, 18, 0))).toBe(local(2026, 9, 3, 9, 0))+ })++ it('weekday schedules land on the right day', () => {+ // From Wednesday 2026-09-02: next Monday is 09-07.+ const from = local(2026, 9, 2, 12, 0)+ expect(next('0 9 * * mon', from)).toBe(local(2026, 9, 7, 9, 0))+ // Weekday range: Thursday 09-03 is next.+ expect(next('0 9 * * 1-5', from)).toBe(local(2026, 9, 3, 9, 0))+ })++ it('vixie OR rule: dom AND dow both restricted fire on EITHER', () => {+ // From Wednesday 2026-09-02. `0 9 15 * mon`: Monday 09-07 comes before the 15th.+ const from = local(2026, 9, 2, 12, 0)+ expect(next('0 9 15 * mon', from)).toBe(local(2026, 9, 7, 9, 0))+ // From Monday 09-07 09:00 (after fire): next is Monday 09-14... which precedes the 15th.+ expect(next('0 9 15 * mon', local(2026, 9, 7, 9, 0))).toBe(local(2026, 9, 14, 9, 0))+ // From 09-14 09:00: the 15th (a Tuesday) is next — the dom leg.+ expect(next('0 9 15 * mon', local(2026, 9, 14, 9, 0))).toBe(local(2026, 9, 15, 9, 0))+ // Only dom restricted: Mondays do NOT fire.+ expect(next('0 9 15 * *', from)).toBe(local(2026, 9, 15, 9, 0))+ })++ it('an impossible schedule returns null instead of scanning forever', () => {+ expect(next('0 0 30 2 *', local(2026, 9, 2, 12, 0))).toBeNull()+ })+})diff --git a/src/shared/cron.ts b/src/shared/cron.tsnew file mode 100644index 000000000..f305c7157--- /dev/null+++ b/src/shared/cron.ts@@ -0,0 +1,182 @@+/**+ * A small, dependency-free cron matcher for trigger nodes (issue #493) — the ONE parser both the+ * core scheduler (fire times) and the renderer (next-run display, phase 4) ask, so the two can+ * never disagree about when a schedule fires.+ *+ * Grammar: classic five fields (minute hour day-of-month month day-of-week), each a comma list of+ * `*`, `N`, `A-B`, with an optional `/step` on any part; month and day-of-week accept the usual+ * three-letter names (jan…dec, sun…sat) and dow `7` is Sunday (normalized to 0). No `@daily`+ * aliases, no seconds field, no wrapping ranges (`22-2` is refused) — a grammar this small is one+ * that can be tested exhaustively, and `parseCron` returning `null` is the SAFE outcome: an+ * unparseable expression schedules nothing (the trigger card will say "invalid schedule"), it+ * never half-runs. Same degrade rule as everything else fed from `.nodeterm/project.json`.+ *+ * Vixie-cron's day rule is honored: when BOTH day-of-month and day-of-week are restricted+ * (their raw field is not `*`), a day matches if EITHER matches — `0 9 15 * mon` fires on the+ * 15th AND on Mondays. This is the classic trap a naive AND implementation silently gets wrong.+ *+ * Times are LOCAL wall-clock, computed by scanning real timestamps and asking each for its local+ * fields — which is what makes DST behave sanely without a timezone library. Two documented+ * edges, both matching what classic cron daemons do: a wall time that does not exist on+ * spring-forward day is skipped, and a wall time that occurs twice on fall-back day can match+ * both instants (the scheduler fires the first it reaches).+ */++export interface CronSchedule {+ minute: boolean[]+ hour: boolean[]+ /** Index 1-31. */+ dom: boolean[]+ /** Index 1-12. */+ month: boolean[]+ /** Index 0-6, Sunday = 0 (an input 7 is normalized). */+ dow: boolean[]+ /** Raw field was not `*` — feeds the vixie OR rule above. */+ domRestricted: boolean+ dowRestricted: boolean+}++const MONTH_NAMES: Record<string, number> = {+ jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,+ jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12+}+const DOW_NAMES: Record<string, number> = {+ sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6+}++interface FieldRule {+ min: number+ max: number+ names?: Record<string, number>+ /** dow: 7 means Sunday. */+ normalize?: (n: number) => number+}++function parseValue(token: string, rule: FieldRule): number | null {+ const named = rule.names?.[token.toLowerCase()]+ if (named !== undefined) return named+ if (!/^\d+$/.test(token)) return null+ const n = Number(token)+ const v = rule.normalize ? rule.normalize(n) : n+ return v >= rule.min && v <= rule.max ? v : null+}++/** One comma-part: `*`, `N`, `A-B`, each optionally `/step`. Returns false on any refusal. */+function applyPart(part: string, rule: FieldRule, out: boolean[]): boolean {+ const [rangeRaw, stepRaw, extra] = part.split('/')+ if (extra !== undefined || rangeRaw === '') return false+ let step = 1+ if (stepRaw !== undefined) {+ if (!/^\d+$/.test(stepRaw)) return false+ step = Number(stepRaw)+ if (step < 1) return false+ }+ let lo: number+ let hi: number+ if (rangeRaw === '*') {+ lo = rule.min+ hi = rule.max+ } else if (rangeRaw.includes('-')) {+ const [a, b, more] = rangeRaw.split('-')+ if (more !== undefined) return false+ const va = parseValue(a, rule)+ const vb = parseValue(b, rule)+ if (va === null || vb === null || va > vb) return false+ lo = va+ hi = vb+ } else {+ const v = parseValue(rangeRaw, rule)+ if (v === null) return false+ // A bare value with a step (`5/15`) is vixie's "from 5 to max, every 15".+ if (stepRaw !== undefined) {+ lo = v+ hi = rule.max+ } else {+ out[v] = true+ return true+ }+ }+ for (let v = lo; v <= hi; v += step) out[v] = true+ return true+}++function parseField(field: string, rule: FieldRule, size: number): boolean[] | null {+ const out = new Array<boolean>(size).fill(false)+ for (const part of field.split(',')) {+ if (!applyPart(part, rule, out)) return null+ }+ return out+}++const DOW_RULE: FieldRule = { min: 0, max: 6, names: DOW_NAMES, normalize: (n) => (n === 7 ? 0 : n) }++/** Parse a five-field cron expression; `null` = refused (schedules nothing). */+export function parseCron(expr: string): CronSchedule | null {+ const fields = expr.trim().split(/\s+/)+ if (fields.length !== 5) return null+ const minute = parseField(fields[0], { min: 0, max: 59 }, 60)+ const hour = parseField(fields[1], { min: 0, max: 23 }, 24)+ const dom = parseField(fields[2], { min: 1, max: 31 }, 32)+ const month = parseField(fields[3], { min: 1, max: 12, names: MONTH_NAMES }, 13)+ const dow = parseField(fields[4], DOW_RULE, 7)+ if (!minute || !hour || !dom || !month || !dow) return null+ return {+ minute, hour, dom, month, dow,+ domRestricted: fields[2] !== '*',+ dowRestricted: fields[4] !== '*'+ }+}++function dayMatches(s: CronSchedule, d: Date): boolean {+ const domHit = s.dom[d.getDate()]+ const dowHit = s.dow[d.getDay()]+ if (s.domRestricted && s.dowRestricted) return domHit || dowHit+ if (s.domRestricted) return domHit+ if (s.dowRestricted) return dowHit+ return true+}++/** Default search horizon. `0 0 30 2 *` (Feb 30) never matches; a bound turns that into `null`+ * instead of an unbounded scan. 366 days covers every real yearly schedule. */+export const CRON_HORIZON_MS = 366 * 24 * 60 * 60 * 1000++/**+ * The first firing time STRICTLY AFTER `fromMs`, as epoch ms, or `null` when none exists within+ * the horizon. Scans day → hour → minute with skipping (a non-matching month jumps to the next+ * month's first day, a non-matching day to the next midnight, a non-matching hour to the next+ * hour), so the worst case is a few hundred steps, not half a million.+ */+export function nextCronFire(+ schedule: CronSchedule,+ fromMs: number,+ horizonMs: number = CRON_HORIZON_MS+): number | null {+ const t = new Date(fromMs)+ t.setSeconds(0, 0)+ t.setMinutes(t.getMinutes() + 1)+ const end = fromMs + horizonMs+ while (t.getTime() <= end) {+ if (!schedule.month[t.getMonth() + 1]) {+ t.setDate(1)+ t.setHours(0, 0, 0, 0)+ t.setMonth(t.getMonth() + 1)+ continue+ }+ if (!dayMatches(schedule, t)) {+ t.setHours(0, 0, 0, 0)+ t.setDate(t.getDate() + 1)+ continue+ }+ if (!schedule.hour[t.getHours()]) {+ t.setMinutes(0, 0, 0)+ t.setHours(t.getHours() + 1)+ continue+ }+ if (!schedule.minute[t.getMinutes()]) {+ t.setMinutes(t.getMinutes() + 1)+ continue+ }+ return t.getTime()+ }+ return null+}