Skip to content

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.

feat(control): --after-success waits for a station to REPORT success, not just end its turn

reviewc13a474efead
diff --git a/CLAUDE.md b/CLAUDE.md
index f7fd2f0f5..ccf4e8e75 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3646,6 +3646,60 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
build older than this one keeps `afterPr` in the file but ignores it, releasing the node on
`after` alone. **Kanban / mobile:** the card does not show QUEUED for any held launch (a
pre-existing gap, not new here); the phone never sees `pendingLaunch`.
+ **Success waits (`--after-success`) and `report-outcome`** (2026-09-29). `--after` releases a
+ node when every station's TURN ends; a turn ending is not the task succeeding (a station can give
+ up, answer its own question or produce something broken, and end its turn cleanly), and #521 only
+ catches a turn that ERRORED. So a station says how its task went —
+ `report-outcome --outcome succeeded|failed [--note <line>]` — and `open-terminal --cmd` /
+ `open-claude` / `open-agent --after-success <id,id> [--success-deadline <90m|12h|3d>]` waits for
+ a reported success. Grammar, the persisted shape and the pure evaluation are ONE module,
+ `@shared/station-outcome`, used by desktop main's shape gate, the Server Edition's parser AND
+ headless factory, and the renderer's launch loop, so the two shells cannot disagree about when a
+ dependent starts. Rules a refactor must not undo:
+ - **A success wait is `--after` plus the report.** Every `--after-success` id is FOLDED INTO
+ `pendingLaunch.after` (renderer: once, right after `prWaitPre`; server: before `resolveAfter`),
+ so the existing rules apply unchanged — the station must exist and report status, the wait rope
+ is drawn and deleting it is the escape (`dropAfterDep` now drops the success half too), the
+ `--run-now` / `--project` refusals, #521's errored-turn hold. The hold
+ (`pendingLaunch.afterSuccess = {deps, deadlineAt}`) adds only "and it reported success". It is
+ also the downgrade story: a build that ignores the field still waits for the turn.
+ - **One grammar; the ambiguous form is refused by name.** `--after a1:ok` (any `:` in `--after` —
+ node ids never contain one) is refused pointing at `--after-success`, not answered "no such
+ node"; an id in both flags is refused ("name each station once").
+ - **The matrix** (`evaluateSuccessDep`): `failed` BLOCKS (never fires; `list` BLOCKED BY FAILURE,
+ badge ⚠ BLOCKED, tooltip names the station and its note); `succeeded` is met once the station's
+ turn is over without an error; no report = waiting (no news is never success); a DELETED station
+ counts only if it reported success before it went — the one place this differs from `--after`,
+ where a deletion is satisfied, because closing a station is how an orchestrator abandons a failed
+ attempt. Only a canvas-control agent can run `report-outcome`, so waiting on anything else is
+ refused (`successDepRefusal`, checked where `--after` is checked). Deadline: the `--pr-deadline`
+ grammar and bounds (`parseWaitDeadlineArg`, one parser for both), EXPIRED badge, `list` EXPIRED,
+ ▶ / `run` start it (`planRunVerb` treats the hold like `--after`).
+ - **The report is core's, transient, and never read from a file.** `core/station-outcome-store.ts`
+ holds it in MAIN (desktop) / the server process: a renderer reload does not lose it; an app
+ restart does, like `lastTurnError`. The board-log line (`station-reported`, on the station's own
+ card, NEVER_COLLAPSE) is display only — `project.json` and the board log are git-shared, and a
+ success anyone can commit would release every dependent. `report-outcome` is verified-only
+ (`requiresVerified`) and a node reports only about ITSELF: `--node` naming another node is
+ refused (`report-outcome-not-self`), not ignored. The note is display text (`sanitizeOutcomeNote`:
+ `oneLine` + format chars stripped, 200 code points) and is never typed into a pane.
+ - **When a report ends — the "new task" rule.** A later report supersedes. A `send` / `reply` /
+ `write` / `run` that SUCCEEDS against a station withdraws its report (`clearOutcomesAfterControl`,
+ run by each shell's control handler AFTER the answer). Without it, "hand a station its next task,
+ then open a dependent `--after-success` it" released the dependent at once on the previous task's
+ success — early, the direction nothing undoes; withdrawing errs toward holding, which the deadline
+ and ▶ end. A new TURN does not clear it (a turn is not a task: a station may report mid-turn, and a
+ person typing "thanks" starts a turn, not a task), and neither does a person typing in the pane or
+ a board comment. Closing a station keeps its report (the deleted-station rule reads it).
+ - **Both shells**: desktop main answers the verb before the forward and clears after it; the Server
+ Edition answers it through the same `handleReportOutcome` (`onRecorded` re-runs `refreshArmed`),
+ honours `--after-success` in the headless factory (`successFacts`: the mirror's `done` plus the
+ fresh-spawn `awaitingFirstWorking` rule) and wraps its handler with the same clearing rule.
+ `station-outcome:list` is in `HOST_ONLY_CHANNELS` (unscoped: every project's notes); relay tabs
+ take the inert stub. Pinned at source level by `main/station-outcome-wiring.test.ts`. **Not
+ done:** a reported `failed` does not raise a station-failure notice to the opener (the opener
+ reads BLOCKED BY FAILURE in `list`) — a candidate trigger for `@shared/station-notice`; the kanban
+ card and the phone show no outcome (the phone never sees `pendingLaunch`).
**Headless start (`--run-now`, `run`, #925):** `open-*` with `--run-now` into a project that is
not on screen starts the new node's held launch at once instead of "when next viewed". A node
with nothing held (an `open-terminal` without `--cmd`) has nothing to start, and gets the plain
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ac6c85258..0329b2e05 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -747,10 +747,15 @@ retry anywhere, ask what the clock actually starts on and where its exhaustion b
in the git-shared `.nodeterm/project.json`, so `normalizePendingLaunch`
(`src/shared/pending-launch-shape.ts`) runs at both serializer seams: an `after` that is not a list
used to throw inside the canvas's dependency-signature selector. Its rule, and the rule for any new
-gate you add (the `--after-pr` pull request wait is the latest): a value it cannot read turns the
+gate you add (the `--after-success` wait is the latest): a value it cannot read turns the
hold `manualOnly` or never-satisfied, never "no gate" — dropping it would start the node early, and
a dependent that has launched cannot un-launch. A new gate field also goes in that module's `KNOWN`
-set, and `launchesToFire` must treat a missing context for it as closed.
+set, and `launchesToFire` must treat a missing context for it as closed. If both shells evaluate the
+gate (the Server Edition's headless factory releases its own held launches), put the evaluation in
+`src/shared` beside the shape, as `@shared/station-outcome` does, so the desktop and the server
+cannot disagree about when a dependent starts. And never let a gate read its "satisfied" from a
+file: a success a git commit can claim releases every dependent waiting on it — the station's
+report lives in a transient core store, and its board-log line is display only.
**Never move the user's view on a background agent's say-so.** Canvas-control requests route by
SOURCE, and React Flow holds only the ACTIVE project's nodes — so the dispatch used to travel to the
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 6e36305d0..d0adba495 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -1,3 +1,4 @@
+import { REPORT_OUTCOME_CONTROL_REFUSAL } from '../../shared/station-outcome'
import { sessionContextWindow } from '../model-window'
import { labelHeldForRevision } from './permission-decision'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
@@ -260,7 +261,11 @@ export const requiresVerified: ReadonlySet<string> = new Set([
// caller", and an unjudgeable caller must never be the one that files.
'report-issue',
// Starts a process the user is not watching (#925).
- 'run'
+ 'run',
+ // A station's own task outcome (@shared/station-outcome): a reported success RELEASES every
+ // dependent armed with `--after-success`, so the claim must come from the node it is about — and
+ // only a verified caller is provably that node.
+ 'report-outcome'
])
/**
@@ -286,6 +291,8 @@ export const REPORT_ISSUE_CONTROL_REFUSAL = 'Issue reporting refused.'
/** Same posture for `run` (#925): it starts a queued session the user is not watching, and the
* refusal says only that the run was refused. */
export const RUN_CONTROL_REFUSAL = 'Run refused.'
+/** Same posture for `report-outcome` (defined beside its grammar, @shared/station-outcome). */
+export { REPORT_OUTCOME_CONTROL_REFUSAL }
/** The verified-only refusal, worded for the verb that was refused. */
export function verifiedRefusalFor(verb: string): string {
@@ -295,6 +302,7 @@ export function verifiedRefusalFor(verb: string): string {
if (verb === 'sticky') return STICKY_CONTROL_REFUSAL
if (verb === 'open-project') return OPEN_PROJECT_CONTROL_REFUSAL
if (verb === 'run') return RUN_CONTROL_REFUSAL
+ if (verb === 'report-outcome') return REPORT_OUTCOME_CONTROL_REFUSAL
return MESSAGING_CONTROL_REFUSAL
}
diff --git a/src/core/agents/messaging-verified-only.test.ts b/src/core/agents/messaging-verified-only.test.ts
index a5ca6add4..845fafb39 100644
--- a/src/core/agents/messaging-verified-only.test.ts
+++ b/src/core/agents/messaging-verified-only.test.ts
@@ -168,11 +168,14 @@ describe('where the verbs sit in the routing tables', () => {
// New verb, so fail-closed from day one strands no legacy population either.
// `run` (#925) is here because it STARTS a process in a session the user is not watching —
// possibly in another project; new verb, so fail-closed from day one strands nobody.
+ // `report-outcome` is here because a reported success RELEASES every dependent armed with
+ // `--after-success`: only a verified caller is provably the station the report is about.
expect([...requiresVerified].sort()).toEqual([
'notify',
'open-project',
'reply',
'report-issue',
+ 'report-outcome',
'run',
'send',
'settings',
@@ -180,6 +183,11 @@ describe('where the verbs sit in the routing tables', () => {
])
})
+ it('the report-outcome refusal is its own flat sentence, not the messaging one', () => {
+ expect(verifiedRefusalFor('report-outcome')).toBe('Outcome report refused.')
+ expect(verifiedRefusalFor('report-outcome')).not.toBe(MESSAGING_CONTROL_REFUSAL)
+ })
+
it('the run refusal is its own flat sentence, not the messaging one (#925)', () => {
expect(verifiedRefusalFor('run')).toBe(RUN_CONTROL_REFUSAL)
expect(verifiedRefusalFor('run')).not.toBe(MESSAGING_CONTROL_REFUSAL)
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 0fde6136d..6434b8546 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -31,6 +31,12 @@ import {
} from '../shared/station-notice'
import { STATION_NOTICE_FROM } from '../shared/agents/agent-messaging'
import { PR_DEADLINE_DEFAULT_MS, PR_DEADLINE_MAX_MS, PR_WAIT_MAX, afterPrFlagRefusal } from '../shared/pr-wait'
+import {
+ OUTCOME_NOTE_MAX,
+ REPORT_OUTCOME_VERB,
+ SUCCESS_WAIT_MAX,
+ afterSuccessFlagRefusal
+} from '../shared/station-outcome'
import { ISSUE_BRANCH_SLUG_MAX, issueWorktreeBranch } from '../shared/issue-worktree'
import {
REQUEST_ID_MAX_LENGTH,
@@ -201,6 +207,61 @@ function afterPrDocLines(): string[] {
]
}
+/**
+ * `--after-success` and the verb that feeds it, `report-outcome` — both agent-facing bodies share
+ * these lines. Every limit is RENDERED from the module that enforces it (@shared/station-outcome,
+ * and the one deadline grammar in @shared/pr-wait), so the text cannot promise a bound the gate
+ * refuses. The "when a report ends" rule is the one core/station-outcome-store.ts implements;
+ * `canvas-control-core.test.ts` pins its clauses against both bodies.
+ */
+function afterSuccessDocLines(): string[] {
+ const hours = PR_DEADLINE_DEFAULT_MS / 3_600_000
+ const days = PR_DEADLINE_MAX_MS / 86_400_000
+ return [
+ 'Success waits (`--after-success`, on `open-terminal --cmd` / `open-claude` / `open-agent`):',
+ '- `--after-success <id,id>` holds the launch until every listed station has REPORTED SUCCESS with',
+ ` \`${REPORT_OUTCOME_VERB}\` and its turn is over. It is \`--after\` plus the report: a station whose turn merely`,
+ ' ENDED — it gave up, answered its own question, produced something broken — does not release it.',
+ ' Use it when the next station must only start on a GOOD result; use plain `--after` when it should look',
+ ' at whatever the upstream produced. Both can be on one open, with different stations. `list` marks',
+ ' such a node WAITING FOR SUCCESS (naming who it still needs), and every station\'s own row says',
+ ' REPORTED SUCCESS or REPORTED FAILURE with its note — read that instead of asking the stations.',
+ '- A station that reports `failed` BLOCKS the dependent: it never starts on that (`list` marks it BLOCKED BY',
+ ' FAILURE and names the station and its note). Retry or re-brief the station — it reports again — or start',
+ ' the dependent yourself with `run`. No report yet means waiting: "no news" is never a success.',
+ '- Only an agent session with canvas control can report, so only such a node may be named; a plain',
+ ' terminal is refused (wait on it with `--after`). A station that is CLOSED counts only if it reported',
+ ' success before it was closed; closed without one, it blocks.',
+ '- A report stands until that station reports again, or until YOU hand it new work through canvas',
+ ' control: a `send`, `reply`, `write` or `run` aimed at it withdraws its report. So to reuse a station,',
+ ' hand it the next task FIRST, then open the dependent — opened first, the dependent would start at',
+ ' once on the earlier success. A new turn does not withdraw a report, and neither does the user',
+ " typing in the station's pane.",
+ `- \`--success-deadline <90m|12h|3d>\` bounds the wait (default ${hours}h, at most ${days}d). Past it the node`,
+ ' never starts on its own: `list` marks it EXPIRED, and you start it with `run` (the user can press ▶).',
+ `- Name each station once, at most ${SUCCESS_WAIT_MAX}: an id in both \`--after\` and \`--after-success\` is refused, and so is`,
+ ' a suffix on `--after` (`--after a1:ok`) — write `--after-success a1`. `--run-now` and `--project` cannot',
+ ' be combined with it. Reports live in the running app: after an app restart no station has reported',
+ ' yet, so a dependent still waiting then needs its stations to report again (or `run`). The Server',
+ ' Edition accepts both the flag and the verb.'
+ ]
+}
+
+function reportOutcomeDocLines(): string[] {
+ return [
+ `- \`${REPORT_OUTCOME_VERB} --outcome succeeded|failed [--note "<one line>"]\` — say how YOUR task went.`,
+ ' REPORT WHEN EVERY TASK YOU ARE GIVEN ENDS, including one handed to you later in a message: nodes',
+ ' opened with `--after-success` on you start only on `succeeded`, and `failed` holds them. Be honest:',
+ ' `succeeded` means the task is done and checked the way your brief asked (tests pass, the file',
+ ' exists, the PR is open) — not merely that you stopped. You gave up, hit a blocker, need a human, or',
+ ' are unsure: that is `failed`, with the reason in `--note`. Report last, when nothing is left to do.',
+ ' You report only about yourself — `--node` naming another node is refused — and a later report',
+ ` replaces the earlier one. The note (one line, at most ${OUTCOME_NOTE_MAX} characters) is shown in \`list\`, on your`,
+ " card and on the waiting node; it is never typed into anyone's session. Reporting does not end your",
+ ' session or your turn, and it moves no kanban card.'
+ ]
+}
+
function settingsVerbDocLines(): string[] {
const keys = SETTINGS_VERB_KEY_LIST.map((key) => {
const { scope, type } = SETTINGS_VERB_KEYS[key]
@@ -362,6 +423,7 @@ export type ControlVerb =
| 'open-project'
| 'settings'
| 'report-issue'
+ | 'report-outcome'
export interface ControlCommand {
verb: ControlVerb
@@ -415,7 +477,11 @@ const VERBS: ControlVerb[] = [
// something (@core/github/report-issue-service). Off by default per project; there is no
// `--project` flag on purpose — reporting into somebody else's repository is not a capability
// an agent should be able to reach by naming an id.
- 'report-issue'
+ 'report-issue',
+ // A station reports its OWN task outcome (@shared/station-outcome); a dependent opened with
+ // `--after-success` waits for a reported success. Answered by the shell's control handler, never
+ // forwarded to a canvas. Verified-only (requiresVerified).
+ 'report-outcome'
]
/**
@@ -541,6 +607,13 @@ export function parseControlRequest(
// refuses the well-formed flag as unsupported (its open allowlist), since it keeps no PR watch.
const afterPrRefusal = afterPrFlagRefusal(v, args)
if (afterPrRefusal) return { error: afterPrRefusal }
+ // `--after-success`: the same shape gate desktop main runs before forwarding, including the one
+ // refusal of the ambiguous `--after <id>:ok` form (@shared/station-outcome).
+ const afterSuccessRefusal = afterSuccessFlagRefusal(v, args)
+ if (afterSuccessRefusal) return { error: afterSuccessRefusal }
+ if (v === 'report-outcome' && !args.outcome) {
+ return { error: 'report-outcome requires --outcome succeeded|failed' }
+ }
if ((v === 'group' || v === 'arrange') && !args.nodes) return { error: `${v} requires --nodes <id,id>` }
if (v === 'ungroup' && !args.group) return { error: 'ungroup requires --group <id>' }
if (v === 'move' && !args.nodes) return { error: 'move requires --nodes <id,id>' }
@@ -653,9 +726,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'Verbs:',
'- `list` — current nodes (id, kind, title). Start here when you need a node id.',
'- `help` — print the verb list. Answered by the shim itself, so it works even if the app is down.',
- '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]` — open N plain terminals. `--cmd` requires verified node identity.',
- '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]` — open N Claude sessions.',
- `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open`,
+ '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]` — open N plain terminals. `--cmd` requires verified node identity.',
+ '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]` — open N Claude sessions.',
+ `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open`,
' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',
' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',
' start until every listed station has finished a turn SUCCESSFULLY. It is',
@@ -721,6 +794,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' agent does not recognise fails inside the session, not at open time — name a model you know.',
...issueBindingDocLines(),
...afterPrDocLines(),
+ ...afterSuccessDocLines(),
+ ...reportOutcomeDocLines(),
'- `open-project --cwd </abs/path> [--name N] [--color C]` — register (or find) the project for a',
' local directory; the reply carries `{ projectId, name, cwd, created }`. Idempotent: the same',
' cwd always returns the same project, never a duplicate. Creating/adding asks the user to',
@@ -846,7 +921,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'independent — for every "and then", ask whether the next step READS the previous step\'s',
'output. If not, they are separate stations, open them all at once; if it does, open the',
'downstream one with `--after <upstream-id>` and it starts itself when the upstream goes',
- 'idle (do not poll for that yourself). Then break the task into 2-5 workstreams;',
+ 'idle (do not poll for that yourself) — or with `--after-success <upstream-id>` when it must',
+ 'start only on a SUCCESSFUL upstream, and tell every station you open to finish with',
+ '`report-outcome`. Then break the task into 2-5 workstreams;',
'per stream `open-worktree --branch <slug>` then `open-agent --agent claude --group <groupId>',
'--prompt "<concrete task>"` (each stream on its own branch, no tree conflicts). Members land',
'in grid slots inside the frame automatically; align the frames themselves with',
@@ -1174,9 +1251,9 @@ Verbs:
not seven. It clears itself the moment that station completes another turn.
- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so it
is also what to run when you are unsure whether the control endpoint is alive.
-- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]\` — open N plain terminals (default 1). \`--cmd\` requires verified node identity.
-- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N Claude sessions (default 1).
-- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N sessions of any agent CLI.
+- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]\` — open N plain terminals (default 1). \`--cmd\` requires verified node identity.
+- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N Claude sessions (default 1).
+- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]\` — open N sessions of any agent CLI.
\`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
hands its worktree path down as the cwd.
\`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once
@@ -1261,6 +1338,8 @@ Verbs:
open time, so name a model you know that CLI accepts rather than guessing.
${issueBindingDocLines().join('\n')}
${afterPrDocLines().join('\n')}
+${afterSuccessDocLines().join('\n')}
+${reportOutcomeDocLines().join('\n')}
- \`open-project --cwd </abs/path> [--name N] [--color C]\` — register (or find) the project for a
local directory; the reply carries \`{ projectId, name, cwd, created }\`. Idempotent: the same
cwd always returns the same project, never a duplicate — and \`--name\`/\`--color\` apply only
@@ -1469,7 +1548,10 @@ across Nodeterm sessions), be the orchestration chef — plan the kitchen, then
the wait is wasted — those steps are separate stations, open them all at once. If it does,
the dependency is real: open the downstream station with \`--after <upstream-id>\` and it
will start itself when the upstream goes idle. Do not fake this by polling in your own
- session; that is what \`--after\` exists to replace.
+ session; that is what \`--after\` exists to replace. When the downstream must only start on
+ a SUCCESSFUL upstream — its turn ending is not enough — use \`--after-success <upstream-id>\`,
+ and end every station's brief with "when you are done, run \`report-outcome --outcome
+ succeeded\` or \`--outcome failed --note <why>\`".
1. Split the task into the independent workstreams step 0 identified.
2. Per workstream, give it its own branch + kitchen station:
\`open-worktree --branch <slug>\` → note the returned \`groupId\`, then
diff --git a/src/core/station-outcome-store.test.ts b/src/core/station-outcome-store.test.ts
new file mode 100644
index 000000000..525e40b2b
--- /dev/null
+++ b/src/core/station-outcome-store.test.ts
@@ -0,0 +1,186 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ OUTCOME_CLEARING_VERBS,
+ STATION_OUTCOME_MAX_RECORDS,
+ StationOutcomeStore,
+ clearOutcomesAfterControl,
+ handleReportOutcome,
+ registerStationOutcomeIpc,
+ type ReportOutcomeDeps
+} from './station-outcome-store'
+import { REPORT_OUTCOME_CONTROL_REFUSAL } from '../shared/station-outcome'
+import { IPC } from '../shared/ipc'
+import type { BoardLogEntry } from '../shared/types'
+
+function deps(over: Partial<ReportOutcomeDeps> = {}): ReportOutcomeDeps & { log: BoardLogEntry[] } {
+ const log: BoardLogEntry[] = []
+ return {
+ store: new StationOutcomeStore(),
+ now: () => 1_000,
+ projectIdOfNode: () => 'p1',
+ appendBoardLog: async (_projectId, entry) => {
+ log.push(entry)
+ return true
+ },
+ newId: () => 'log-1',
+ log,
+ ...over
+ }
+}
+
+describe('handleReportOutcome', () => {
+ it('records the caller’s OWN outcome, logs it on its own card and tells it what that releases', async () => {
+ const d = deps()
+ const onRecorded = vi.fn()
+ d.onRecorded = onRecorded
+ const r = await handleReportOutcome(
+ { nodeId: 'st1', args: { outcome: 'succeeded', note: 'tests\npass' }, verified: true },
+ d
+ )
+ expect(r.ok).toBe(true)
+ expect(r.message).toContain('recorded: your task succeeded — "tests pass"')
+ expect(r.message).toContain('--after-success')
+ expect(r.message).toContain('A new turn does not change it')
+ expect(d.store.get('st1')).toEqual({ nodeId: 'st1', outcome: 'succeeded', note: 'tests pass', at: 1_000 })
+ expect(d.log).toEqual([
+ {
+ id: 'log-1',
+ ts: 1_000,
+ author: { name: 'nodeterm', color: '#8b8b8b' },
+ nodeId: 'st1',
+ kind: 'event',
+ event: { type: 'station-reported', from: 'st1', to: 'succeeded', title: 'tests pass' }
+ }
+ ])
+ expect(onRecorded).toHaveBeenCalledWith(d.store.get('st1'))
+ })
+
+ it('refuses an unverified caller and records nothing — a forgeable success is not evidence', async () => {
+ const d = deps()
+ const r = await handleReportOutcome({ nodeId: 'st1', args: { outcome: 'succeeded' }, verified: false }, d)
+ expect(r).toEqual({ ok: false, error: REPORT_OUTCOME_CONTROL_REFUSAL, message: REPORT_OUTCOME_CONTROL_REFUSAL })
+ expect(d.store.list()).toEqual([])
+ expect(d.log).toEqual([])
+ })
+
+ it('refuses a report about ANOTHER node and records nothing, for either node', async () => {
+ const d = deps()
+ const r = await handleReportOutcome(
+ { nodeId: 'orchestrator', args: { outcome: 'succeeded', node: 'st1' }, verified: true },
+ d
+ )
+ expect(r.ok).toBe(false)
+ expect(r.error).toMatch(/^report-outcome-not-self:/)
+ expect(d.store.get('st1')).toBeUndefined()
+ expect(d.store.get('orchestrator')).toBeUndefined()
+ expect(d.log).toEqual([])
+ })
+
+ it('a node that is in no saved project is still recorded — the wait reads the store, not the log', async () => {
+ const d = deps({ projectIdOfNode: () => undefined })
+ const r = await handleReportOutcome({ nodeId: 'st1', args: { outcome: 'failed' }, verified: true }, d)
+ expect(r.ok).toBe(true)
+ expect(d.store.get('st1')?.outcome).toBe('failed')
+ expect(d.log).toEqual([])
+ expect(r.result).toMatchObject({ boardLog: false })
+ })
+
+ it('a board log that cannot be written does not fail the report', async () => {
+ const d = deps({ appendBoardLog: async () => Promise.reject(new Error('disk full')) })
+ const r = await handleReportOutcome({ nodeId: 'st1', args: { outcome: 'failed' }, verified: true }, d)
+ expect(r.ok).toBe(true)
+ expect(d.store.get('st1')?.outcome).toBe('failed')
+ })
+
+ it('a later report supersedes the earlier one', async () => {
+ const d = deps()
+ await handleReportOutcome({ nodeId: 'st1', args: { outcome: 'failed' }, verified: true }, d)
+ await handleReportOutcome({ nodeId: 'st1', args: { outcome: 'succeeded' }, verified: true }, d)
+ expect(d.store.get('st1')?.outcome).toBe('succeeded')
+ expect(d.store.list()).toHaveLength(1)
+ })
+})
+
+describe('StationOutcomeStore', () => {
+ it('publishes the WHOLE list, newest first, on every change', () => {
+ const publish = vi.fn()
+ const s = new StationOutcomeStore(publish)
+ s.record({ nodeId: 'a', outcome: 'failed', at: 1 })
+ s.record({ nodeId: 'b', outcome: 'succeeded', at: 2 })
+ expect(publish).toHaveBeenLastCalledWith([
+ { nodeId: 'b', outcome: 'succeeded', at: 2 },
+ { nodeId: 'a', outcome: 'failed', at: 1 }
+ ])
+ expect(s.clear('a')).toBe(true)
+ expect(publish).toHaveBeenLastCalledWith([{ nodeId: 'b', outcome: 'succeeded', at: 2 }])
+ // Clearing nothing publishes nothing.
+ const calls = publish.mock.calls.length
+ expect(s.clear('zzz')).toBe(false)
+ expect(publish.mock.calls.length).toBe(calls)
+ })
+
+ it('is bounded, evicting the oldest first', () => {
+ const s = new StationOutcomeStore()
+ for (let i = 0; i < STATION_OUTCOME_MAX_RECORDS + 3; i++) {
+ s.record({ nodeId: `n${i}`, outcome: 'succeeded', at: i })
+ }
+ expect(s.list()).toHaveLength(STATION_OUTCOME_MAX_RECORDS)
+ expect(s.get('n0')).toBeUndefined()
+ expect(s.get('n2')).toBeUndefined()
+ expect(s.get('n3')).toBeDefined()
+ })
+
+ it('serves the read channel from the store the thunk returns', async () => {
+ const handlers = new Map<string, (...a: unknown[]) => unknown>()
+ const s = new StationOutcomeStore()
+ s.record({ nodeId: 'a', outcome: 'succeeded', at: 1 })
+ let current: StationOutcomeStore | null = null
+ registerStationOutcomeIpc({ handle: (ch, fn) => handlers.set(ch, fn) }, () => current)
+ expect(handlers.get(IPC.stationOutcomeList)?.()).toEqual([])
+ current = s
+ expect(handlers.get(IPC.stationOutcomeList)?.()).toEqual([{ nodeId: 'a', outcome: 'succeeded', at: 1 }])
+ })
+})
+
+describe('clearOutcomesAfterControl — new work handed through canvas control withdraws a report', () => {
+ const seeded = () => {
+ const s = new StationOutcomeStore()
+ s.record({ nodeId: 'st1', outcome: 'succeeded', at: 1 })
+ s.record({ nodeId: 'st2', outcome: 'succeeded', at: 2 })
+ return s
+ }
+
+ it.each(['send', 'reply', 'write', 'run'])('a successful %s aimed at a station clears its report', (verb) => {
+ const s = seeded()
+ clearOutcomesAfterControl(s, verb, { node: 'st1', text: 'next task' }, { ok: true }, 'orch')
+ expect(s.get('st1')).toBeUndefined()
+ expect(s.get('st2')).toBeDefined()
+ })
+
+ it('a refused or failed request handed nothing, so nothing is cleared', () => {
+ const s = seeded()
+ clearOutcomesAfterControl(s, 'send', { node: 'st1' }, { ok: false }, 'orch')
+ expect(s.get('st1')).toBeDefined()
+ })
+
+ it('notify types nothing into a pane, and other verbs hand no work', () => {
+ const s = seeded()
+ for (const verb of ['notify', 'rename', 'list', 'close', 'color', 'assign']) {
+ clearOutcomesAfterControl(s, verb, { node: 'st1' }, { ok: true }, 'orch')
+ }
+ expect(s.get('st1')).toBeDefined()
+ expect([...OUTCOME_CLEARING_VERBS].sort()).toEqual(['reply', 'run', 'send', 'write'])
+ })
+
+ it('a node writing into its OWN pane is not handed work by anyone', () => {
+ const s = seeded()
+ clearOutcomesAfterControl(s, 'write', { node: 'st1' }, { ok: true }, 'st1')
+ expect(s.get('st1')).toBeDefined()
+ })
+
+ it('reads a comma list, and ignores an id it would not vouch for', () => {
+ const s = seeded()
+ clearOutcomesAfterControl(s, 'send', { node: 'st1, st2, ../x' }, { ok: true }, 'orch')
+ expect(s.list()).toEqual([])
+ })
+})
diff --git a/src/core/station-outcome-store.ts b/src/core/station-outcome-store.ts
new file mode 100644
index 000000000..55d0ddcdf
--- /dev/null
+++ b/src/core/station-outcome-store.ts
@@ -0,0 +1,198 @@
+/**
+ * The core half of @shared/station-outcome: what each station last REPORTED about its task, and the
+ * `report-outcome` verb that records it. ONE module for both shells — desktop main and the Server
+ * Edition both answer the verb here and both register the read channel — so the two cannot come to
+ * accept different reports or keep them differently.
+ *
+ * TRANSIENT, like the agent state it sits beside and for the same reason `lastTurnError` is: after
+ * a restart no station has spoken in this run, and a success restored from disk would describe a
+ * task from another app run. Held in MAIN rather than the renderer so a renderer reload (⌘R, a
+ * Server Edition browser tab closing) does not lose it — the station-notice monitor learned that
+ * lesson with its DROPPED verdict.
+ *
+ * WHEN A REPORT ENDS (the "new task" rule):
+ * - the station reports again — the later report supersedes;
+ * - the station is handed new work THROUGH CANVAS CONTROL — a `send` / `reply` / `write` into its
+ * pane, or a `run` of its held launch (`OUTCOME_CLEARING_VERBS`). Those are the moments nodeterm
+ * itself sees new work arrive, and they are how an orchestrator reuses a station: without the
+ * withdrawal, "hand the station its next task, then open a dependent `--after-success` it" would
+ * release that dependent at once on the PREVIOUS task's success — early, the direction nothing
+ * can undo. Withdrawing errs toward holding, which the deadline and ▶ / `run` can always end;
+ * - NOT a new turn. A turn is not a task: a station may report mid-turn and keep summarising, and
+ * a person typing "thanks" into its pane starts a turn without starting a task. nodeterm cannot
+ * tell a new task from a follow-up by looking at a turn, so a turn changes nothing here; the
+ * skill tells every station to report at the end of every task, which supersedes the old one;
+ * - NOT the station being closed. A closed station's success still counts for the dependents it
+ * already had (`evaluateSuccessDep`): closing finished stations is ordinary tidying.
+ * The store is bounded, oldest evicted first, so a long session cannot grow it without limit.
+ */
+import type { BoardLogEntry } from '../shared/types'
+import { IPC } from '../shared/ipc'
+import { isSafeNodeId } from '../shared/safe-id'
+import {
+ REPORT_OUTCOME_CONTROL_REFUSAL,
+ parseReportOutcome,
+ type StationOutcome,
+ type StationOutcomeRecord
+} from '../shared/station-outcome'
+import type { CorePlatform } from './platform'
+
+/** How many stations' reports one process keeps. Far past any canvas; evicts the oldest first. */
+export const STATION_OUTCOME_MAX_RECORDS = 1000
+
+/** The author of the board-log line — the app, like every other trace it writes. */
+const OUTCOME_AUTHOR = { name: 'nodeterm', color: '#8b8b8b' } as const
+
+export class StationOutcomeStore {
+ // Insertion order IS recency: a record is deleted and re-set on every write, so the first key is
+ // always the oldest and eviction is one `keys().next()`.
+ private readonly byId = new Map<string, StationOutcomeRecord>()
+
+ /** `publish` gets the FULL list after every change (never a delta), like station notices. */
+ constructor(private readonly publish: (records: StationOutcomeRecord[]) => void = () => {}) {}
+
+ record(rec: StationOutcomeRecord): void {
+ this.byId.delete(rec.nodeId)
+ this.byId.set(rec.nodeId, rec)
+ while (this.byId.size > STATION_OUTCOME_MAX_RECORDS) {
+ const oldest = this.byId.keys().next().value
+ if (oldest === undefined) break
+ this.byId.delete(oldest)
+ }
+ this.publish(this.list())
+ }
+
+ /** Withdraw a station's report. `true` when there was one. */
+ clear(nodeId: string): boolean {
+ if (!this.byId.delete(nodeId)) return false
+ this.publish(this.list())
+ return true
+ }
+
+ get(nodeId: string): StationOutcomeRecord | undefined {
+ return this.byId.get(nodeId)
+ }
+
+ /** Every record, newest first. */
+ list(): StationOutcomeRecord[] {
+ return [...this.byId.values()].reverse()
+ }
+}
+
+/**
+ * Verbs that hand the node they name (`--node`) NEW WORK when they succeed, and so withdraw its
+ * outcome report — see the header's "new task" rule. `notify` is not one: it raises an OS
+ * notification and types nothing into the pane.
+ */
+export const OUTCOME_CLEARING_VERBS: ReadonlySet<string> = new Set(['send', 'reply', 'write', 'run'])
+
+/**
+ * Apply the "new task" rule to one finished control request. Run by each shell's control handler
+ * AFTER the verb answered, and only on success: a refused or undelivered message handed nothing.
+ * A caller naming ITSELF is not handed work by anyone (a station `write`-ing into its own pane is
+ * still doing its own task).
+ */
+export function clearOutcomesAfterControl(
+ store: Pick<StationOutcomeStore, 'clear'>,
+ verb: string,
+ args: Record<string, string | undefined>,
+ result: { ok: boolean },
+ callerNodeId: string
+): void {
+ if (!result.ok || !OUTCOME_CLEARING_VERBS.has(verb) || typeof args.node !== 'string') return
+ for (const id of args.node.split(',').map((s) => s.trim())) {
+ if (id && id !== callerNodeId && isSafeNodeId(id)) store.clear(id)
+ }
+}
+
+export interface ReportOutcomeDeps {
+ store: StationOutcomeStore
+ now(): number
+ /** The station's project, for the board-log line. `undefined` = not in a saved project yet: the
+ * report is still recorded (it is what the wait reads); only the durable line is skipped. */
+ projectIdOfNode(nodeId: string): string | undefined
+ appendBoardLog(projectId: string, entry: BoardLogEntry): Promise<boolean>
+ newId?(): string
+ /** After a record lands. The Server Edition re-evaluates its armed launches here; the desktop's
+ * renderer hears the store's push instead. */
+ onRecorded?(record: StationOutcomeRecord): void
+}
+
+export interface ReportOutcomeReply {
+ ok: boolean
+ message?: string
+ error?: string
+ result?: unknown
+}
+
+const RELEASE_TEXT: Record<StationOutcome, string> = {
+ succeeded:
+ 'Nodes opened with --after-success on you start once your turn ends (and their other waits are met).',
+ failed:
+ 'Nodes opened with --after-success on you stay held — they will not start on this. If the task is ' +
+ 'retried, report again when it ends.'
+}
+
+/**
+ * `report-outcome`, answered in the shell's control handler (main on the desktop, never forwarded to
+ * the renderer). The caller is the VERIFIED node the request came from — the hook server refuses an
+ * unverified one before any handler runs, and this is the belt — and it may report only about
+ * itself (`parseReportOutcome`).
+ */
+export async function handleReportOutcome(
+ req: { nodeId: string; args: Record<string, string>; verified: boolean },
+ deps: ReportOutcomeDeps
+): Promise<ReportOutcomeReply> {
+ const refuse = (error: string): ReportOutcomeReply => ({ ok: false, error, message: error })
+ if (!req.verified) return refuse(REPORT_OUTCOME_CONTROL_REFUSAL)
+ if (!isSafeNodeId(req.nodeId)) return refuse(REPORT_OUTCOME_CONTROL_REFUSAL)
+ const parsed = parseReportOutcome(req.args, req.nodeId)
+ if (!parsed.ok) return refuse(parsed.error)
+ const at = deps.now()
+ const record: StationOutcomeRecord = {
+ nodeId: req.nodeId,
+ outcome: parsed.outcome,
+ at,
+ ...(parsed.note ? { note: parsed.note } : {})
+ }
+ deps.store.record(record)
+ const projectId = deps.projectIdOfNode(req.nodeId)
+ let logged = false
+ if (projectId) {
+ const entry: BoardLogEntry = {
+ id: deps.newId?.() ?? `station-reported-${req.nodeId}-${at}`,
+ ts: at,
+ author: OUTCOME_AUTHOR,
+ nodeId: req.nodeId,
+ kind: 'event',
+ event: {
+ type: 'station-reported',
+ from: req.nodeId,
+ to: parsed.outcome,
+ ...(parsed.note ? { title: parsed.note } : {})
+ }
+ }
+ logged = await deps.appendBoardLog(projectId, entry).catch(() => false)
+ }
+ deps.onRecorded?.(record)
+ const message = [
+ `recorded: your task ${parsed.outcome}${parsed.note ? ` — "${parsed.note}"` : ''}.`,
+ RELEASE_TEXT[parsed.outcome],
+ 'It stands until you report again, or until you are handed new work through canvas control ' +
+ '(a send, reply, write or run aimed at you). A new turn does not change it.'
+ ].join(' ')
+ return {
+ ok: true,
+ message,
+ result: { nodeId: req.nodeId, outcome: parsed.outcome, at, boardLog: logged }
+ }
+}
+
+/** The read channel, registered by BOTH shells. `store` is a thunk for the same reason as the
+ * station-notice channels': a shell may build its store after the platform handlers. */
+export function registerStationOutcomeIpc(
+ platform: Pick<CorePlatform, 'handle'>,
+ store: () => StationOutcomeStore | null
+): void {
+ platform.handle(IPC.stationOutcomeList, () => store()?.list() ?? [])
+}
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index ba94005ab..98335a634 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -53,6 +53,7 @@ import {
offScreenDisposition,
controlVerbSetsForTests
} from '../shared/control-off-screen'
+import { OUTCOME_NOTE_MAX, REPORT_OUTCOME_VERB, SUCCESS_WAIT_MAX } from '../shared/station-outcome'
describe('parseControlRequest', () => {
it('accepts known verbs', () => {
@@ -1407,3 +1408,98 @@ describe('--after-pr: open a node that waits on a pull request', () => {
expect(flat).toContain('Write the number bare (`1008:merged`)')
})
})
+
+describe('--after-success + report-outcome: a dependent that waits for a reported SUCCESS', () => {
+ it('passes a well-formed wait through the shape gate on the open verbs', () => {
+ expect(parseControlRequest('open-claude', { 'after-success': 'a1,a2', 'success-deadline': '6h' })).toMatchObject({
+ verb: 'open-claude'
+ })
+ expect(parseControlRequest('open-terminal', { 'after-success': 'a1', cmd: 'make' })).toMatchObject({
+ verb: 'open-terminal'
+ })
+ expect(parseControlRequest('open-agent', { agent: 'codex', after: 'b1', 'after-success': 'a1' })).toMatchObject({
+ verb: 'open-agent'
+ })
+ })
+
+ it.each([
+ [{ after: 'a1:ok' }, /--after takes plain node ids/],
+ [{ after: 'a1', 'after-success': 'a1' }, /name each station once/],
+ [{ 'after-success': 'a1:ok' }, /--after-success takes plain node ids/],
+ [{ 'after-success': 'a1', 'run-now': '1' }, /--run-now cannot be combined with --after-success/],
+ [{ 'success-deadline': '2h' }, /only with --after-success/],
+ [{ 'after-success': 'a1', 'success-deadline': '30d' }, /--success-deadline must be/]
+ ])('refuses %j before the renderer sees it', (args, error) => {
+ const r = parseControlRequest('open-agent', { agent: 'claude', ...args })
+ expect((r as { error?: string }).error).toMatch(error)
+ })
+
+ it('refuses the flag on a verb that opens nothing, and on a terminal with nothing to run', () => {
+ expect((parseControlRequest('spawn-team', { team: '[]', 'after-success': 'a1' }) as { error: string }).error).toMatch(
+ /applies only to open-terminal/
+ )
+ expect((parseControlRequest('open-terminal', { 'after-success': 'a1' }) as { error: string }).error).toMatch(
+ /needs --cmd/
+ )
+ })
+
+ it('report-outcome is a registered verb that needs --outcome', () => {
+ expect(parseControlRequest('report-outcome', { outcome: 'succeeded' })).toEqual({
+ verb: 'report-outcome',
+ args: { outcome: 'succeeded' }
+ })
+ expect(parseControlRequest('report-outcome', {})).toEqual({
+ error: 'report-outcome requires --outcome succeeded|failed'
+ })
+ })
+
+ const bodies: Array<[string, string]> = [
+ ['skill body', buildCanvasSkillBody('/x/nodeterm.sh')],
+ ['instructions block', buildCanvasControlInstructions('/x/nodeterm.sh')]
+ ]
+
+ it.each(bodies)('%s lists the flag on all three open verbs', (_name, body) => {
+ const synopsis = /\[--after-success <id,id>\] \[--success-deadline <90m\|12h\|3d>\]/
+ for (const verb of ['open-terminal ', 'open-claude ', 'open-agent --agent ']) {
+ const line = body.split('\n').find((l) => l.includes(`\`${verb}`)) ?? ''
+ expect(line, verb).toMatch(synopsis)
+ }
+ })
+
+ it.each(bodies)('%s states what a success wait needs, what blocks it, and when a report ends', (_name, body) => {
+ const flat = body.replace(/\s+/g, ' ')
+ expect(flat).toContain('`--after-success <id,id>` holds the launch until every listed station has REPORTED SUCCESS')
+ expect(flat).toContain('It is `--after` plus the report')
+ expect(flat).toContain('A station that reports `failed` BLOCKS the dependent')
+ expect(flat).toContain('BLOCKED BY FAILURE')
+ expect(flat).toContain('WAITING FOR SUCCESS')
+ expect(flat).toContain('No report yet means waiting')
+ expect(flat).toContain('A station that is CLOSED counts only if it reported success before it was closed')
+ // The "new task" rule, as core implements it (OUTCOME_CLEARING_VERBS).
+ expect(flat).toContain('a `send`, `reply`, `write` or `run` aimed at it withdraws its report')
+ expect(flat).toContain('hand it the next task FIRST, then open the dependent')
+ expect(flat).toContain('A new turn does not withdraw a report')
+ // Limits rendered from the modules that enforce them.
+ expect(flat).toContain('`--success-deadline <90m|12h|3d>` bounds the wait (default 24h, at most 14d)')
+ expect(flat).toContain(`at most ${SUCCESS_WAIT_MAX}`)
+ expect(flat).toContain('a suffix on `--after` (`--after a1:ok`)')
+ expect(flat).toContain('The Server Edition accepts both the flag and the verb')
+ })
+
+ it.each(bodies)('%s teaches stations to report, honestly, about themselves only', (_name, body) => {
+ const flat = body.replace(/\s+/g, ' ')
+ expect(flat).toContain(`\`${REPORT_OUTCOME_VERB} --outcome succeeded|failed [--note "<one line>"]\``)
+ expect(flat).toContain('REPORT WHEN EVERY TASK YOU ARE GIVEN ENDS')
+ expect(flat).toContain('not merely that you stopped')
+ expect(flat).toContain('`--node` naming another node is refused')
+ expect(flat).toContain(`at most ${OUTCOME_NOTE_MAX} characters`)
+ expect(flat).toContain('never typed into anyone\'s session')
+ // And orchestrators are told to ask for it.
+ expect(flat).toMatch(/--after-success <upstream-id>/)
+ expect(flat).toMatch(/report-outcome/)
+ })
+
+ it('the verb is in the shim\'s derived verb list and reached only through the verified gate', () => {
+ expect(CONTROL_SHIM_SCRIPT).toContain('report-outcome')
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index dc060d42c..770cedcf2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -80,6 +80,13 @@ import {
type AgentMessagingDeps
} from '../core/agents/agent-messaging'
import { registerStationNoticeIpc, StationNoticeMonitor } from '../core/agents/station-notice'
+import {
+ StationOutcomeStore,
+ clearOutcomesAfterControl,
+ handleReportOutcome,
+ registerStationOutcomeIpc
+} from '../core/station-outcome-store'
+import { afterSuccessFlagRefusal } from '../shared/station-outcome'
import { stationRecipient } from '../shared/station-notice'
import type { RemoteLogExec } from '../core/board-log'
import type { PtyCreateOptions, TranscriptPresence } from '../shared/types'
@@ -1943,6 +1950,13 @@ app.whenReady().then(async () => {
// "queued" about a message that has since landed or lapsed.
messagingDeps.onQueuedResult = (req, outcome) => stationNotices.onQueuedResult(req, outcome)
registerStationNoticeIpc(corePlatform, () => stationNotices)
+ // Station task outcomes (`report-outcome`, src/core/station-outcome-store.ts): what each station
+ // said about its OWN task, read by the renderer's `--after-success` gate. Held here, in main, so a
+ // renderer reload does not lose it; pushed whole to the window on every change.
+ const stationOutcomes = new StationOutcomeStore((records) =>
+ sendToMain(IPC.stationOutcomeChanged, records)
+ )
+ registerStationOutcomeIpc(corePlatform, () => stationOutcomes)
ipcMain.handle(IPC.dialogSelectFolder, async () => {
const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })
@@ -3776,6 +3790,23 @@ app.whenReady().then(async () => {
// exists in the board's repository is the renderer's question (`resolvePrWaitFor`).
const afterPrRefusal = afterPrFlagRefusal(verb, args)
if (afterPrRefusal) return { ok: false, error: afterPrRefusal, message: afterPrRefusal }
+ // `--after-success` / `--success-deadline`, and the refused `--after <id>:ok` form: same
+ // placement, same reason. Whether a named station exists and can report is the renderer's.
+ const afterSuccessRefusal = afterSuccessFlagRefusal(verb, args)
+ if (afterSuccessRefusal) return { ok: false, error: afterSuccessRefusal, message: afterSuccessRefusal }
+ // A station's report about ITSELF: recorded in main's store, board-logged on its own card, and
+ // never forwarded — there is no canvas work in it, and the renderer hears the store's push.
+ if (verb === 'report-outcome') {
+ return handleReportOutcome(
+ { nodeId, args, verified },
+ {
+ store: stationOutcomes,
+ now: () => Date.now(),
+ projectIdOfNode,
+ appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)
+ }
+ )
+ }
// `browser` is answered in MAIN and never forwarded to the renderer's agent-control dispatch:
// the debugger handle and the CDP allowlist are main-side, and the renderer is the more
// attackable half. Every other verb still round-trips to the renderer below.
@@ -3884,6 +3915,9 @@ app.whenReady().then(async () => {
return { ok: false, error: OPEN_PROJECT_GRANT_CAP, message: OPEN_PROJECT_GRANT_CAP }
}
}
+ // New work handed to a station through canvas control withdraws its outcome report — the
+ // "new task" rule in src/core/station-outcome-store.ts. After the answer, and only on success.
+ clearOutcomesAfterControl(stationOutcomes, verb, args, result, nodeId)
return result
})
initMediaProtocol()
diff --git a/src/main/station-notice-wiring.test.ts b/src/main/station-notice-wiring.test.ts
index 097dcb213..6d6fc4e97 100644
--- a/src/main/station-notice-wiring.test.ts
+++ b/src/main/station-notice-wiring.test.ts
@@ -68,8 +68,8 @@ describe('every canvas-control open path records the opener beside its rope', ()
it('the off-canvas and cold-open writes stamp the node they rope', () => {
expect(canvas).toContain('node: flowToNodeStates([withOpenedBy(placed, sourceNodeId)])[0]')
// The cold open stamps the node as it is built, right where `--after` (and any `--after-pr`
- // hold, via withPrHold) is folded into its hold.
- expect(canvas).toMatch(/const node = withOpenedBy\(\s*(?:withPrHold\(\s*)?held && coldAfterIds\.length[\s\S]{0,400}?sourceNodeId\s*\)/)
+ // / `--after-success` hold, via withPrHold / withSuccessHold) is folded into its hold.
+ expect(canvas).toMatch(/const node = withOpenedBy\(\s*(?:withSuccessHold\(\s*)?(?:withPrHold\(\s*)?held && coldAfterIds\.length[\s\S]{0,500}?sourceNodeId\s*\)/)
})
it('the renderer mirrors the list and reports DROPPED on the app api', () => {
diff --git a/src/main/station-outcome-wiring.test.ts b/src/main/station-outcome-wiring.test.ts
new file mode 100644
index 000000000..f0caf9f9c
--- /dev/null
+++ b/src/main/station-outcome-wiring.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * SOURCE-LEVEL pins for `report-outcome` / `--after-success` wiring — the same remedy
+ * `hook-verified-parity.test.ts` uses for the same class of hole: every piece below is well-typed
+ * whether or not it is wired (an optional dep left out, a store never registered, a handler that
+ * forgets to clear), so a feature can be plumbed end to end, pass `npm run typecheck` and every
+ * unit test, and ship INERT on one shell. The behaviour itself is proven against real code in
+ * `shared/station-outcome.test.ts`, `core/station-outcome-store.test.ts`,
+ * `renderer/lib/pendingLaunch.test.ts` and `server/headless-node-factory.test.ts`.
+ */
+const read = (rel: string): string =>
+ readFileSync(new URL(rel, import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+const main = read('./index.ts')
+const serverControl = read('../server/canvas-control.ts')
+const serverIndex = read('../server/index.ts')
+const canvas = read('../renderer/canvas/Canvas.tsx')
+
+describe('desktop main', () => {
+ const handler = main.slice(main.indexOf('hookServer.setControlHandler('))
+
+ it('runs the --after-success shape gate before anything is forwarded', () => {
+ const gate = handler.indexOf('afterSuccessFlagRefusal(verb, args)')
+ expect(gate).toBeGreaterThan(-1)
+ expect(gate).toBeLessThan(handler.indexOf("'window unavailable'"))
+ })
+
+ it('answers report-outcome in MAIN, never forwarding it to the renderer', () => {
+ const at = handler.indexOf("if (verb === 'report-outcome') {")
+ expect(at).toBeGreaterThan(-1)
+ expect(at).toBeLessThan(handler.indexOf('controlForwarder.forward('))
+ const block = handler.slice(at, at + 600)
+ expect(block).toContain('handleReportOutcome(')
+ expect(block).toContain('store: stationOutcomes')
+ expect(block).toContain('{ nodeId, args, verified }')
+ })
+
+ it('withdraws a station\'s report after new work lands, on the answered result', () => {
+ const clear = handler.indexOf('clearOutcomesAfterControl(stationOutcomes, verb, args, result, nodeId)')
+ expect(clear).toBeGreaterThan(handler.indexOf('controlForwarder.forward('))
+ })
+
+ it('registers the read channel and pushes every change to the window', () => {
+ expect(main).toContain('registerStationOutcomeIpc(corePlatform, () => stationOutcomes)')
+ expect(main).toMatch(/new StationOutcomeStore\(\(records\) =>\s*sendToMain\(IPC\.stationOutcomeChanged, records\)/)
+ })
+})
+
+describe('Server Edition', () => {
+ it('routes report-outcome through the SAME core handler and re-evaluates its arms', () => {
+ const at = serverControl.indexOf('reportOutcome: (sourceNodeId, args, verified) =>')
+ expect(at).toBeGreaterThan(-1)
+ const block = serverControl.slice(at, at + 900)
+ expect(block).toContain('handleReportOutcome(')
+ expect(block).toContain('onRecorded: () => void factory.refreshArmed()')
+ })
+
+ it('hands the factory the outcome store, so --after-success is honoured headlessly', () => {
+ expect(serverControl).toContain('outcomeOf: (nodeId) => stationOutcomes.get(nodeId)')
+ })
+
+ it('wraps its control handler with the same "new work withdraws a report" rule', () => {
+ expect(serverControl).toContain(
+ 'clearOutcomesAfterControl(stationOutcomes, req.verb, req.args, reply, req.nodeId)'
+ )
+ })
+
+ it('registers the read channel whether or not canvas control comes up', () => {
+ expect(serverIndex).toContain(
+ 'registerStationOutcomeIpc(platform, () => canvasControl?.stationOutcomes ?? null)'
+ )
+ })
+})
+
+describe('the desktop renderer', () => {
+ it('mirrors core\'s store', () => {
+ expect(canvas).toContain('useEffect(() => installStationOutcomeWiring(window.nodeTerminal), [])')
+ })
+
+ it('folds --after-success into --after once, before any open path resolves --after', () => {
+ const fold = canvas.indexOf('args = { ...args, after: [...new Set([...plainAfter, ...successIdsPre])].join(\',\') }')
+ expect(fold).toBeGreaterThan(-1)
+ // Before every consumer of `args.after`: the live resolver, the cold resolver, the run-now belt.
+ expect(fold).toBeLessThan(canvas.indexOf('const resolveAfter = (): string[] | null | undefined => {'))
+ expect(fold).toBeLessThan(canvas.indexOf('const coldAfter = coldResolveAfter('))
+ expect(fold).toBeLessThan(canvas.indexOf('reply({ ok: false, error: RUN_NOW_AFTER_REFUSAL })'))
+ expect(fold).toBeLessThan(canvas.indexOf('routeControlSource(projects, activeId, sourceNodeId)'))
+ })
+
+ it('checks that a success station can REPORT, on the live and the cold path', () => {
+ expect(canvas).toMatch(/successIdsPre\.includes\(depId\) && !sourceIsControlCapable\(depAgent\)/)
+ expect(canvas).toMatch(/const coldCannotReport = successIdsPre\.find\(/)
+ })
+
+ it('attaches the hold on the live path (armAfter) and the cold path', () => {
+ const armAfter = canvas.slice(canvas.indexOf('const armAfter = ('), canvas.indexOf('const addGrouped = ('))
+ expect(armAfter).toContain('withSuccessHold(')
+ expect(armAfter).toContain('successHoldPre')
+ const cold = canvas.slice(
+ canvas.indexOf('if (canColdOpen(verb)) {'),
+ canvas.indexOf('if (answersOffCanvas(verb) || answersFromStoredNodes(verb)) {')
+ )
+ expect(cold).toMatch(/withSuccessHold\(/)
+ })
+
+ it('judges the gate with the outcome store, and re-runs off a PRIMITIVE signature', () => {
+ const effect = canvas.slice(canvas.indexOf('const ready = launchesToFire('), canvas.indexOf('}, [nodes, armedDepSig'))
+ expect(effect).toContain('{ outcomes: useStationOutcomes.getState().byId, now: Date.now() }')
+ const sig = canvas.slice(canvas.indexOf('const armedSuccessSig = useStationOutcomes((s) => {'))
+ expect(sig.slice(0, 900)).toContain('sig +=')
+ })
+
+ it('list reads the outcomes on both the live and the stored path', () => {
+ const hits = canvas.split('useStationOutcomes.getState().byId)').length - 1
+ expect(hits).toBeGreaterThanOrEqual(2)
+ })
+})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index c7b373595..c9becea18 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -869,6 +869,14 @@ const api: NodeTerminalApi = {
reportDropped: (nodeId, dropped) => {
void ipcRenderer.invoke(IPC.stationNoticeDropped, nodeId, dropped).catch(() => undefined)
}
+ },
+ stationOutcome: {
+ list: () => ipcRenderer.invoke(IPC.stationOutcomeList),
+ onChanged: (cb) => {
+ const handler = (_e: unknown, records: Parameters<typeof cb>[0]) => cb(records)
+ ipcRenderer.on(IPC.stationOutcomeChanged, handler)
+ return () => ipcRenderer.removeListener(IPC.stationOutcomeChanged, handler)
+ }
}
}
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 0c0e169f9..033e0a2f1 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -189,6 +189,7 @@ export function buildRelayApi(
// Station-failure notices are about THIS machine's stations and its own orchestrators; a relay
// tab's nodes live in the host's core, whose notices are the host's renderer's to draw.
stationNotice: stub.stationNotice,
+ stationOutcome: stub.stationOutcome,
// The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's
// core, whose mirror is seeded by the host's own renderer from its own localStorage. This
// machine's localStorage holds no identity for them, and `...local` would plant this machine's
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 99cf54b66..79a0978be 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -589,6 +589,11 @@ export function buildStubApi(): Omit<
list: async () => [],
onChanged: noopUnsub,
reportDropped: noop
+ },
+ // Same split: the Server Edition overrides it (`buildStationOutcomeApi`); a relay tab keeps this.
+ stationOutcome: {
+ list: async () => [],
+ onChanged: noopUnsub
}
} satisfies Omit<
NodeTerminalApi,
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 67c103e7c..46946072e 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -71,6 +71,7 @@ import type { PeerIdentity } from '../../shared/presence'
import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'
import { buildStubApi, unsupported } from './stubs'
import { sanitizeStationNotices } from '@shared/station-notice'
+import { sanitizeOutcomeRecords } from '@shared/station-outcome'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
import { encodePcmForWire } from './speech-encode'
import { type FrameTransport, WebSocketFrameTransport } from './frame-transport'
@@ -693,6 +694,24 @@ export function buildStationNoticeApi(client: RpcClient): Pick<NodeTerminalApi,
}
}
+/**
+ * The Server Edition's station task outcomes — REAL, for the same reason as station notices: the
+ * server's canvas-control runtime records `report-outcome` and honours `--after-success` headlessly,
+ * and a browser tab's QUEUED badge and `list` must say what the server knows. Kept out of
+ * `buildAgentApi`, which relay tabs share.
+ */
+export function buildStationOutcomeApi(client: RpcClient): Pick<NodeTerminalApi, 'stationOutcome'> {
+ return {
+ stationOutcome: {
+ list: () =>
+ (client.request(IPC.stationOutcomeList) as Promise<unknown>).then(sanitizeOutcomeRecords, () => []),
+ onChanged: (cb) =>
+ client.subscribe(IPC.stationOutcomeChanged, ((records: unknown) =>
+ cb(sanitizeOutcomeRecords(records))) as Listener)
+ }
+ }
+}
+
/**
* Build the top-level agent-event subscriptions (`onAgentStatus` / `onSubagentActivity`) over an
* RpcClient. These mirror the preload's `.on(channel, …)` → `client.subscribe(channel, …)` split:
@@ -1214,6 +1233,7 @@ export async function installWsBridge(): Promise<boolean> {
...buildFilesApi(client),
...buildAgentApi(client),
...buildStationNoticeApi(client),
+ ...buildStationOutcomeApi(client),
...buildCanvasApi(client),
...buildPresenceApi(client),
...buildSpeechApi(client),
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e98a12127..8f0838185 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -528,6 +528,7 @@ import {
launchesToFire,
queueControlLaunch,
withPrHold,
+ withSuccessHold,
withLaunchBrief,
launchBriefPresent,
LAUNCH_STALL_MS,
@@ -535,6 +536,17 @@ import {
} from '../lib/pendingLaunch'
import { prHoldReports, prWaitReplyLine, resolvePrWaitFor, startFreshReadAsks, type PrWaitArmResult } from '../lib/prWait'
import { RUN_NOW_AFTER_PR_REFUSAL } from '@shared/pr-wait'
+import {
+ afterSuccessFlagRefusal,
+ normalizeSuccessWaitHold,
+ parseAfterSuccessArg,
+ parseSuccessDeadlineArg,
+ outcomeOf,
+ successDepRefusal,
+ type SuccessWaitHold
+} from '@shared/station-outcome'
+import { useStationOutcomes } from '../state/stationOutcomes'
+import { installStationOutcomeWiring } from '../lib/stationOutcomeWiring'
import { lookupPullRequests, pullBoardFor, useGitHubIssues } from '../state/githubIssues'
import { usePullChase } from '../components/kanban/usePullAutoMove'
import {
@@ -2088,6 +2100,25 @@ export function Canvas() {
}
return sig
})
+ // ---- the success reports an armed node waits on (`--after-success`) ----
+ // A PRIMITIVE signature of each waited-on station's latest report, the same discipline as
+ // `armedDepSig`: the launch effect re-runs when one of THOSE stations reports, and nothing
+ // re-renders on another station's report. Their turn state is already in `armedDepSig` — every
+ // success station is in `after` too.
+ const armedSuccessSig = useStationOutcomes((s) => {
+ let sig = ''
+ for (const n of nodesRef.current) {
+ // Through the shape rule: a selector must never throw on a malformed hold.
+ const hold = normalizeSuccessWaitHold((n.data.pendingLaunch as PendingLaunch | undefined)?.afterSuccess)
+ if (!hold || hold.invalid) continue
+ for (const d of hold.deps) {
+ const r = outcomeOf(s.byId, d)
+ sig += `${d}:${r ? `${r.outcome}@${r.at}` : '-'},`
+ }
+ sig += '|'
+ }
+ return sig
+ })
// Keep the host's pull request status coming while any node here waits on a PR. It is the board's
// own refcounted host subscription and #1008's conditional heartbeat (free while nothing changes),
// not a poller; a `checks` wait also asks the host's bounded chase (30 s … 5 min, at most 12 reads
@@ -2207,7 +2238,9 @@ export function Canvas() {
setupDoneForGroup,
useLaunchDelivery.getState().byId,
// The `--after-pr` gate: this canvas's pull request status and the clock its deadlines are on.
- { board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() }
+ { board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() },
+ // The `--after-success` gate: every station's latest task report (core's store, mirrored).
+ { outcomes: useStationOutcomes.getState().byId, now: Date.now() }
).filter((f) => !launchInFlight.current.has(f.id))
// Anything we were reporting on that is no longer an armed node — delivered, run by hand with
// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has
@@ -2298,8 +2331,8 @@ export function Canvas() {
return deliverHeld()
})
}
- // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/armedPrSig/launchNudge are the triggers
- }, [nodes, armedDepSig, armedSetupSig, armedPrSig, launchNudge])
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/armedPrSig/armedSuccessSig/launchNudge are the triggers
+ }, [nodes, armedDepSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge])
// Selection state for ephemeral nodes (they live outside React Flow's managed nodes), owned by
// the agent-nodes store so the cards themselves can set it — see `selectable: false` below.
@@ -10215,6 +10248,8 @@ export function Canvas() {
// never a session's: the default agent-status store and the stations core reports on are both
// this machine's (lib/stationNoticeWiring).
useEffect(() => installStationNoticeWiring(window.nodeTerminal), [])
+ // Station task outcomes (`report-outcome`): core's store mirrored for the `--after-success` gate.
+ useEffect(() => installStationOutcomeWiring(window.nodeTerminal), [])
// Session board cards are derived LIVE from the canvas nodes; the board stores only assignments.
// Only while the board is OPEN: `nodes` gets a fresh identity on every drag frame, so a closed
@@ -11227,6 +11262,45 @@ export function Canvas() {
}
}
: {}
+ // `--after-success` (@shared/station-outcome): stations the new node(s) also need a REPORTED
+ // SUCCESS from. Main already ran the shape gate (and refused the `--after <id>:ok` form); this
+ // is the renderer's belt, never the only gate. The ids are then FOLDED INTO `after` — a success
+ // wait is `--after` plus the station's report — so every existing `--after` rule applies to
+ // them unchanged on every open path: the station must exist and report status, the dependency
+ // rope is drawn and its delete is the escape, `--run-now` / `--project` refuse. The one thing
+ // added is checked where `--after` is checked: the station must be able to REPORT.
+ const successGatePre = openVerb ? afterSuccessFlagRefusal(verb, args) : null
+ if (successGatePre) {
+ reply({ ok: false, error: successGatePre })
+ return
+ }
+ const successParsedPre =
+ openVerb && args['after-success'] !== undefined ? parseAfterSuccessArg(args['after-success']) : undefined
+ const successIdsPre = successParsedPre?.ok ? successParsedPre.ids : []
+ const successDeadlinePre = parseSuccessDeadlineArg(args['success-deadline'])
+ const successHoldPre: SuccessWaitHold | undefined =
+ successIdsPre.length && successDeadlinePre.ok
+ ? { deps: successIdsPre, deadlineAt: Date.now() + successDeadlinePre.ms }
+ : undefined
+ if (successIdsPre.length) {
+ const plainAfter = (args.after ?? '').split(',').map((d) => d.trim()).filter(Boolean)
+ args = { ...args, after: [...new Set([...plainAfter, ...successIdsPre])].join(',') }
+ }
+ const successReplyLines = successHoldPre
+ ? [
+ `waits for a reported success from: ${successHoldPre.deps.join(', ')} ` +
+ `(until ${new Date(successHoldPre.deadlineAt).toISOString()})`
+ ]
+ : []
+ const successReplyText = successReplyLines.map((l) => `\n${l}`).join('')
+ const successResult = successHoldPre
+ ? {
+ afterSuccess: {
+ deps: successHoldPre.deps,
+ deadline: new Date(successHoldPre.deadlineAt).toISOString()
+ }
+ }
+ : {}
// ── Agent messaging (`send`/`reply`) — handled BEFORE the source-routing machinery ──────
// These are STORE_ANSWERED_VERBS (lib/controlRouting): routing by source must never travel
@@ -11853,7 +11927,7 @@ export function Canvas() {
return
}
if (!needsLiveCanvas(verb)) {
- const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId)
+ const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId)
reply({
ok: true,
result: rows,
@@ -11922,6 +11996,14 @@ export function Canvas() {
return
}
const coldAfterIds = coldAfter.after ?? []
+ // `--after-success` stations (folded into `after`) must also be able to REPORT.
+ const coldCannotReport = successIdsPre.find(
+ (d) => !sourceIsControlCapable(storedAgentIdOf(coldNodes.find((n) => n.id === d), coldStatusAgent))
+ )
+ if (coldCannotReport) {
+ reply({ ok: false, error: successDepRefusal(verb, coldCannotReport) })
+ return
+ }
const coldCwd =
args.cwd || coldGroupCwd(coldNodes, coldGroup.groupId, !!owner.ssh) || coldSrc.cwd
// Same SSH rule as the live path: a node an agent opens has to run on the same host the
@@ -11974,6 +12056,7 @@ export function Canvas() {
...(coldIssueRef ? [`bound to GitHub issue ${formatIssueRef(coldIssueRef)}`] : []),
...(coldAfterIds.length ? [`armed to wait for: ${coldAfterIds.join(', ')}`] : []),
...prReplyLines,
+ ...successReplyLines,
// #925: `--run-now` starts it headless instead — except on an SSH project, whose
// nodes a headless start refuses (they start on view, over SSH).
runNowRequested(args) && !owner.ssh
@@ -11988,7 +12071,8 @@ export function Canvas() {
after: coldAfterIds,
projectId: owner.id,
...(coldIssueRef ? { issue: formatIssueRef(coldIssueRef) } : {}),
- ...prResult
+ ...prResult,
+ ...successResult
}
})
return
@@ -12038,14 +12122,17 @@ export function Canvas() {
// opener's name goes on the node now (lib/stationOpener). `--after-pr` rides the same
// held launch (withPrHold — the one attach every path uses).
const node = withOpenedBy(
- withPrHold(
- held && coldAfterIds.length
- ? {
- ...armed,
- data: { ...armed.data, pendingLaunch: { ...held, after: coldAfterIds } }
- }
- : armed,
- prHoldPre
+ withSuccessHold(
+ withPrHold(
+ held && coldAfterIds.length
+ ? {
+ ...armed,
+ data: { ...armed.data, pendingLaunch: { ...held, after: coldAfterIds } }
+ }
+ : armed,
+ prHoldPre
+ ),
+ successHoldPre
),
sourceNodeId
)
@@ -12144,7 +12231,8 @@ export function Canvas() {
(coldDepLinked.length ? ' (and linked to read them)' : '')
: '') +
(coldIssueRef ? `\nbound to GitHub issue ${formatIssueRef(coldIssueRef)}` : '') +
- prReplyText,
+ prReplyText +
+ successReplyText,
// Every node on this branch has no process behind it until that project is viewed,
// whether or not it holds a command — the same rule the `--project` branch states.
result: {
@@ -12155,6 +12243,7 @@ export function Canvas() {
after: coldAfterIds,
...(coldIssueRef ? { issue: formatIssueRef(coldIssueRef) } : {}),
...prResult,
+ ...successResult,
queued: true,
queuedIds: coldIds
} as Record<string, unknown>
@@ -12470,6 +12559,12 @@ export function Canvas() {
})
return null
}
+ // `--after-success` (folded into `after` above): the station must also be able to
+ // REPORT, or the wait could only ever end at its deadline.
+ if (successIdsPre.includes(depId) && !sourceIsControlCapable(depAgent)) {
+ reply({ ok: false, error: successDepRefusal(verb, depId) })
+ return null
+ }
}
return ids
}
@@ -12491,7 +12586,10 @@ export function Canvas() {
const awaitSetupGroup = setupHoldGroup(intoGroup)
// Always retain the command until the PTY-ready delivery loop acknowledges it.
// Node creation (even on screen) is not command delivery.
- return withPrHold(withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile), prHoldPre)
+ return withSuccessHold(
+ withPrHold(withLaunchBrief(queueControlLaunch(node, after, awaitSetupGroup), promptFile), prHoldPre),
+ successHoldPre
+ )
}
// Open `count` nodes INTO a group frame: grow the frame FIRST (extent:'parent' would
// clamp children landing outside it), then drop each node into the next grid slot
@@ -12542,7 +12640,7 @@ export function Canvas() {
id: n.id, kind: n.type, title: n.data.title as string,
pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined,
issueRef: n.data.issueRef
- })), st, useLaunchDelivery.getState().byId)
+ })), st, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId)
reply({ ok: true, result: list, message: controlListingText(list) })
return
}
@@ -12566,7 +12664,8 @@ export function Canvas() {
(termCwd ? `, cwd ${termCwd}` : '') +
(args.cmd ? `, running: ${args.cmd}` : ''),
...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),
- ...prReplyLines
+ ...prReplyLines,
+ ...successReplyLines
].join('\n'),
result: {
dryRun: true,
@@ -12574,7 +12673,8 @@ export function Canvas() {
group: intoGroupId ?? null,
cwd: termCwd ?? null,
after: after ?? [],
- ...prResult
+ ...prResult,
+ ...successResult
}
})
return
@@ -12607,8 +12707,9 @@ export function Canvas() {
`opened ${count} terminal(s): ${ids.join(', ')}` +
(queuedIds.length ? '\nqueued; awaiting launch delivery' : '') +
(after?.length ? `\nwaiting for ${after.join(', ')} before running` : '') +
- prReplyText,
- result: { ...openResult, ...prResult }
+ prReplyText +
+ successReplyText,
+ result: { ...openResult, ...prResult, ...successResult }
})
return
}
@@ -12695,6 +12796,7 @@ export function Canvas() {
...(issueRef ? [`bound to GitHub issue ${formatIssueRef(issueRef)}`] : []),
...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),
...prReplyLines,
+ ...successReplyLines,
'Each session would be connected + context-linked to you.'
].join('\n'),
result: {
@@ -12705,7 +12807,8 @@ export function Canvas() {
cwd: agentCwd ?? null,
after: after ?? [],
...(issueRef ? { issue: formatIssueRef(issueRef) } : {}),
- ...prResult
+ ...prResult,
+ ...successResult
}
})
return
@@ -12782,12 +12885,14 @@ export function Canvas() {
? `\nwaiting for ${after.join(', ')} before running` +
(depLinked.length ? ` (and linked to read them)` : '')
: '') +
- prReplyText,
+ prReplyText +
+ successReplyText,
result: {
...openResult,
linked: bridged,
...(issueRef ? { issue: formatIssueRef(issueRef) } : {}),
- ...prResult
+ ...prResult,
+ ...successResult
}
})
return
diff --git a/src/renderer/canvas/control-after-pr.source.test.ts b/src/renderer/canvas/control-after-pr.source.test.ts
index 7bef577a2..7728e8e37 100644
--- a/src/renderer/canvas/control-after-pr.source.test.ts
+++ b/src/renderer/canvas/control-after-pr.source.test.ts
@@ -105,7 +105,7 @@ describe('the launch loop judges the wait on the ACTIVE project’s pull request
})
it('re-runs when a waited-on pull request changes, off a PRIMITIVE signature', () => {
- expect(src).toMatch(/\}, \[nodes, armedDepSig, armedSetupSig, armedPrSig, launchNudge\]\)/)
+ expect(src).toMatch(/\}, \[nodes, armedDepSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge\]\)/)
const sig = slice('const armedPrSig = useGitHubIssues((s) => {', '})')
expect(sig).toContain('prHoldReports(')
expect(sig).toContain("sig +=")
@@ -133,7 +133,7 @@ describe('the node badge', () => {
})
it('reads EXPIRED and hands the PR wait to the tooltip', () => {
- expect(node).toMatch(/prExpired \? '⚠ EXPIRED'/)
- expect(node).toMatch(/launchTooltip\([^)]*prTooltip\)/)
+ expect(node).toMatch(/prExpired \|\| successExpired\s*\?\s*'⚠ EXPIRED'/)
+ expect(node).toMatch(/launchTooltip\([^)]*prTooltip, successTooltip\)/)
})
})
diff --git a/src/renderer/canvas/pending-launch-delivery.source.test.ts b/src/renderer/canvas/pending-launch-delivery.source.test.ts
index 27eb59104..988b2cf20 100644
--- a/src/renderer/canvas/pending-launch-delivery.source.test.ts
+++ b/src/renderer/canvas/pending-launch-delivery.source.test.ts
@@ -22,7 +22,7 @@ function launchEffect(): string {
const start = src.indexOf('const ready = launchesToFire(')
expect(start).toBeGreaterThan(-1)
const rest = src.slice(start)
- const end = rest.indexOf('armedSetupSig, armedPrSig, launchNudge])')
+ const end = rest.indexOf('armedSetupSig, armedPrSig, armedSuccessSig, launchNudge])')
expect(end).toBeGreaterThan(-1)
return rest.slice(0, end)
}
diff --git a/src/renderer/components/kanban/BoardLogPanel.tsx b/src/renderer/components/kanban/BoardLogPanel.tsx
index 46c7d7cbe..aac8b4959 100644
--- a/src/renderer/components/kanban/BoardLogPanel.tsx
+++ b/src/renderer/components/kanban/BoardLogPanel.tsx
@@ -96,6 +96,12 @@ export function eventBody(e: BoardLogEvent): string {
// Rendered from the closed reason table, never from anything the station wrote: `to` is a
// reason CODE, and an unknown one (a newer peer, a hand edit) reads as a plain "stopped".
return `told this agent that station ${stationName(e)} stopped: ${stationTrigger(e.to)?.label ?? 'it stopped'}`
+ case 'station-reported':
+ // `to` is the outcome CODE and `title` the station's note — from a shared file, so text only
+ // (React escapes it); an outcome this build does not know reads as a plain report.
+ return `recorded this session's report: ${
+ e.to === 'succeeded' ? 'its task succeeded' : e.to === 'failed' ? 'its task failed' : 'an outcome'
+ }${typeof e.title === 'string' && e.title ? ` — "${e.title}"` : ''}`
default:
// A newer peer may write event types this build doesn't know — show them neutrally.
return `updated this card`
diff --git a/src/renderer/components/kanban/board-log-panel.test.tsx b/src/renderer/components/kanban/board-log-panel.test.tsx
index aaca0c139..66b988175 100644
--- a/src/renderer/components/kanban/board-log-panel.test.tsx
+++ b/src/renderer/components/kanban/board-log-panel.test.tsx
@@ -58,4 +58,17 @@ describe('eventBody — the activity sentence', () => {
'told this agent that station st1 stopped: it stopped'
)
})
+
+ it('renders a station outcome report from the outcome code, the note as text only', () => {
+ expect(eventBody({ type: 'station-reported', from: 'st1', to: 'succeeded', title: 'tests pass' })).toBe(
+ 'recorded this session\'s report: its task succeeded — "tests pass"'
+ )
+ expect(eventBody({ type: 'station-reported', from: 'st1', to: 'failed' })).toBe(
+ 'recorded this session\'s report: its task failed'
+ )
+ // An outcome code this build does not know (a newer peer, a hand edit) reads as a plain report.
+ expect(eventBody({ type: 'station-reported', from: 'st1', to: 'rm -rf ~' })).toBe(
+ 'recorded this session\'s report: an outcome'
+ )
+ })
})
diff --git a/src/renderer/lib/boardLogCollapse.test.ts b/src/renderer/lib/boardLogCollapse.test.ts
index 87a2175f7..a83c2d9ef 100644
--- a/src/renderer/lib/boardLogCollapse.test.ts
+++ b/src/renderer/lib/boardLogCollapse.test.ts
@@ -60,7 +60,7 @@ describe('collapseFeed (render-time only — the log itself is never rewritten)'
// row names a DIFFERENT session, so a "×3" would hide exactly which sessions ran (or stopped) —
// the thing that panel exists to show.
it('never folds the audit types or the run history, however alike the rows are', () => {
- expect([...NEVER_COLLAPSE].sort()).toEqual(['agent-message', 'agent-read-cookies', 'run-ended', 'run-started', 'station-failed'])
+ expect([...NEVER_COLLAPSE].sort()).toEqual(['agent-message', 'agent-read-cookies', 'run-ended', 'run-started', 'station-failed', 'station-reported'])
for (const type of NEVER_COLLAPSE) {
const feed = [ev(3, type, AGENT), ev(2, type, AGENT), ev(1, type, AGENT)]
expect(shape(collapseFeed(feed))).toEqual([1, 1, 1])
diff --git a/src/renderer/lib/boardLogCollapse.ts b/src/renderer/lib/boardLogCollapse.ts
index 08ac3c4f0..1bbc8163e 100644
--- a/src/renderer/lib/boardLogCollapse.ts
+++ b/src/renderer/lib/boardLogCollapse.ts
@@ -28,7 +28,10 @@ export const NEVER_COLLAPSE: ReadonlySet<BoardLogEvent['type']> = new Set<BoardL
'run-started',
'run-ended',
// Each names a different station — a "×N" would hide exactly which stations stopped.
- 'station-failed'
+ 'station-failed',
+ // A report is superseded by the next one, so which came LAST is the fact a reader needs — a
+ // "×N" row would hide it.
+ 'station-reported'
])
export type FeedItem =
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index a2a1f6218..6dce40c2f 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -493,3 +493,62 @@ it('lists a PR wait on the row, and EXPIRED once its deadline has passed (--afte
expect(text).toContain('late [terminal] — EXPIRED (PR wait deadline passed; run it with `run`)')
expect(text).toContain('bad [terminal] — EXPIRED')
})
+
+it('lists every station’s own report, and where a success wait stands (--after-success)', () => {
+ const NOW = 10_000
+ const wait = (deps: string[], deadlineAt = NOW + 1) => ({
+ command: 'claude',
+ after: deps,
+ afterSuccess: { deps, deadlineAt }
+ })
+ const nodes = [
+ { id: 'build', title: 'Builder', agentId: 'claude' },
+ { id: 'lint', title: 'Linter', agentId: 'claude' },
+ { id: 'rev', title: 'Reviewer', pendingLaunch: wait(['build']) },
+ { id: 'rel', title: 'Release', pendingLaunch: wait(['lint']) },
+ { id: 'late', title: 'Late', pendingLaunch: wait(['build'], NOW) },
+ { id: 'go', title: 'Go', pendingLaunch: wait(['build', 'lint']) }
+ ]
+ const statuses = { build: { state: 'done' as const }, lint: { state: 'done' as const } }
+ const outcomes = {
+ lint: { nodeId: 'lint', outcome: 'failed' as const, note: 'eslint red', at: 1 }
+ }
+ const rows = storedNodeListing(nodes, statuses, {}, NOW, outcomes)
+ const byId = Object.fromEntries(rows.map((r) => [r.id, r]))
+ expect(byId.rev.launchState).toBe('waiting-success')
+ expect(byId.rel.launchState).toBe('blocked-failure')
+ expect(byId.late.launchState).toBe('success-expired')
+ expect(byId.go.launchState).toBe('blocked-failure')
+ expect(byId.lint.outcome).toBe('failed')
+ const text = controlListingText(rows)
+ expect(text).toContain('lint [terminal] Linter — REPORTED FAILURE ("eslint red")')
+ expect(text).toContain(
+ 'rev [terminal] Reviewer — WAITING FOR SUCCESS — needs success from: build "Builder" (no outcome reported yet)'
+ )
+ expect(text).toContain(
+ 'rel [terminal] Release — BLOCKED BY FAILURE (will not start on its own; run it with `run`) — needs success from: lint "Linter" (reported failure: "eslint red")'
+ )
+ expect(text).toContain('late [terminal] Late — EXPIRED (success wait deadline passed; run it with `run`)')
+
+ // The success arrives: the row stops waiting, and the station's own row says what it reported.
+ const after = storedNodeListing(nodes, statuses, {}, NOW, {
+ build: { nodeId: 'build', outcome: 'succeeded', at: 2 }
+ })
+ const r2 = Object.fromEntries(after.map((r) => [r.id, r]))
+ expect(r2.rev.launchState).toBe('queued')
+ expect(r2.rev.successWait).toBeUndefined()
+ expect(controlListingText(after)).toContain('build [terminal] Builder — REPORTED SUCCESS')
+})
+
+it('a hostile success hold in a stored project neither throws nor reads as met', () => {
+ const rows = storedNodeListing(
+ [
+ { id: 'x', pendingLaunch: { command: 'claude', after: [], afterSuccess: 'build' } },
+ { id: 'y', pendingLaunch: { command: 'claude', after: [], afterSuccess: { deps: [1], deadlineAt: 'soon' } } }
+ ],
+ {},
+ {},
+ 5
+ )
+ expect(rows.map((r) => r.launchState)).toEqual(['success-expired', 'success-expired'])
+})
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index e418207f0..8ed575505 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -16,8 +16,15 @@
import { canControlCanvas, type AgentId } from '@shared/agents/config'
import { formatIssueRef } from '@shared/github-issue-ref'
import { formatPrWaits, normalizePrWaitHold } from '@shared/pr-wait'
+import {
+ normalizeSuccessWaitHold,
+ outcomeOf,
+ successWaitStatus,
+ successWaitSummary,
+ type StationOutcomeRecord
+} from '@shared/station-outcome'
import { prHoldExpired } from './prWait'
-import { controlLaunchState, type LaunchDelivery, type StatusById } from './pendingLaunch'
+import { controlLaunchState, successDepFacts, type LaunchDelivery, type StatusById } from './pendingLaunch'
import { projectTravel } from './presenceTravel'
import {
projectCapabilityGrantedFor,
@@ -178,25 +185,50 @@ export function storedNodeListing(
nodes: readonly StoredNode[],
statuses: StatusById & Record<string, { dropped?: boolean } | undefined> = {},
deliveries: Record<string, LaunchDelivery | undefined> = {},
- now: number = Date.now()
+ now: number = Date.now(),
+ /** Every station's latest task report (`report-outcome`, core's store mirrored). */
+ outcomes: Readonly<Record<string, StationOutcomeRecord>> = {}
) {
+ const live = new Set(nodes.map((n) => n.id))
+ const titleOf = (id: string): string => {
+ const t = nodes.find((n) => n.id === id)?.title
+ return t ? `${id} "${t}"` : id
+ }
return nodes.map((n) => {
const status = statuses[n.id]
// `--after-pr`: the row names what the node waits on (the pull request STATUS is the canvas's
// to judge; `list` states the wait and whether its deadline has passed, which needs no board).
const prHold = normalizePrWaitHold((n.pendingLaunch as { afterPr?: unknown } | undefined)?.afterPr)
const prExpired = !!prHold && prHoldExpired(prHold, now)
- const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status, prExpired) ??
+ // `--after-success`: judged here in full — every fact it needs (the stations' reports, their
+ // turn state, whether they still exist) is already in hand, so the row can say WAITING FOR
+ // SUCCESS, BLOCKED BY FAILURE or EXPIRED and name the station and its note.
+ const successHold = normalizeSuccessWaitHold(
+ (n.pendingLaunch as { afterSuccess?: unknown } | undefined)?.afterSuccess
+ )
+ const successFacts = (d: string) =>
+ successDepFacts(d, statuses, live, outcomes)
+ const successState = successHold ? successWaitStatus(successHold, successFacts, now) : undefined
+ const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status, prExpired, successState) ??
(n.agentId && !status?.state ? 'unconfirmed' as const : undefined)
// A session started on an issue is told so on its OWN row, so `list` is enough for an agent to
// learn it is bound (and which card to move). Only a reference `formatIssueRef` vouches for.
const issue = formatIssueRef(n.issueRef)
+ // What this node said about its OWN task, if anything — so an orchestrator reads every
+ // station's verdict in the one call it already makes.
+ const reported = outcomeOf(outcomes, n.id)
+ const successWait =
+ successHold && !successHold.invalid && successState !== 'met'
+ ? successWaitSummary(successHold, successFacts, titleOf)
+ : undefined
return {
id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',
...(issue ? { issue } : {}),
...(status?.lastTurnError ? { lastTurnErrored: true } : {}),
...(launchState ? { launchState } : {}),
- ...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {})
+ ...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {}),
+ ...(successWait ? { successWait } : {}),
+ ...(reported ? { outcome: reported.outcome, ...(reported.note ? { outcomeNote: reported.note } : {}) } : {})
}
})
}
@@ -210,7 +242,10 @@ const launchLabels = {
dropped: 'DROPPED',
working: 'WORKING',
unconfirmed: 'AGENT STATUS UNCONFIRMED',
- expired: 'EXPIRED (PR wait deadline passed; run it with `run`)'
+ expired: 'EXPIRED (PR wait deadline passed; run it with `run`)',
+ 'success-expired': 'EXPIRED (success wait deadline passed; run it with `run`)',
+ 'waiting-success': 'WAITING FOR SUCCESS',
+ 'blocked-failure': 'BLOCKED BY FAILURE (will not start on its own; run it with `run`)'
} as const
export function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {
@@ -218,6 +253,8 @@ export function controlListingText(rows: ReturnType<typeof storedNodeListing>):
(n.issue ? ` — issue ${n.issue}` : '') +
(n.launchState ? ` — ${launchLabels[n.launchState]}` : '') +
(n.prWait ? ` — waits on ${n.prWait}` : '') +
+ (n.successWait ? ` — needs success from: ${n.successWait}` : '') +
+ (n.outcome ? ` — REPORTED ${n.outcome === 'succeeded' ? 'SUCCESS' : 'FAILURE'}${n.outcomeNote ? ` ("${n.outcomeNote}")` : ''}` : '') +
(n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')
).join('\n')
}
diff --git a/src/renderer/lib/edgeModel.test.ts b/src/renderer/lib/edgeModel.test.ts
index a15d79df4..d2c0ed3e1 100644
--- a/src/renderer/lib/edgeModel.test.ts
+++ b/src/renderer/lib/edgeModel.test.ts
@@ -57,6 +57,19 @@ describe('dropAfterDep — deleting a waiting rope means "stop waiting on that o
expect(dropAfterDep(p, 'a')).toEqual({ after: ['b'], command: 'claude "x"' })
})
+ it('deleting a success station\'s rope stops BOTH waits on it — no success half is left behind', () => {
+ const p = { after: ['a', 'b'], command: 'c', afterSuccess: { deps: ['a', 'b'], deadlineAt: 9 } }
+ expect(dropAfterDep(p, 'a')).toEqual({ after: ['b'], command: 'c', afterSuccess: { deps: ['b'], deadlineAt: 9 } })
+ // The last one takes the whole success hold with it: an empty wait could never be met.
+ expect(dropAfterDep({ after: ['a'], command: 'c', afterSuccess: { deps: ['a'], deadlineAt: 9 } }, 'a')).toEqual({
+ after: [],
+ command: 'c'
+ })
+ // A hostile hold is not repaired here and does not throw.
+ const bad = { after: ['a'], command: 'c', afterSuccess: 'a' } as never
+ expect(() => dropAfterDep(bad, 'a')).not.toThrow()
+ })
+
it('returns the SAME object when the dep is not listed (no spurious re-render)', () => {
const p = { after: ['a'], command: 'c' }
expect(dropAfterDep(p, 'zzz')).toBe(p)
diff --git a/src/renderer/lib/edgeModel.ts b/src/renderer/lib/edgeModel.ts
index 2ef3ad0e7..a6a7f7960 100644
--- a/src/renderer/lib/edgeModel.ts
+++ b/src/renderer/lib/edgeModel.ts
@@ -3,6 +3,7 @@
// "sequenced after (--after)" — and its LOOK is derived from the target's pendingLaunch, never
// stored: dashed while the target still waits on the rope's source, solid otherwise. Kept free of
// React/store imports so Canvas.tsx only wraps these in a memo.
+import { normalizeSuccessWaitHold } from '@shared/station-outcome'
import type { PendingLaunch } from '@shared/types'
/** Rope colour for a source with no agent (a browser popup, a plain terminal that opened nothing). */
@@ -39,8 +40,19 @@ export function ropeVisual(
* satisfied and fires the held command, which is exactly what removing the last wait should do.
*/
export function dropAfterDep(p: PendingLaunch, depId: string): PendingLaunch {
- if (!p.after.includes(depId)) return p
- return { ...p, after: p.after.filter((d) => d !== depId) }
+ const success = normalizeSuccessWaitHold(p.afterSuccess)
+ const inSuccess = !!success && !success.invalid && success.deps.includes(depId)
+ if (!p.after.includes(depId) && !inSuccess) return p
+ const next: PendingLaunch = { ...p, after: p.after.filter((d) => d !== depId) }
+ // A `--after-success` station rides the same rope, so deleting that rope stops BOTH waits on it —
+ // "stop waiting for it" cannot leave the success half behind with no edge left to say so. A hold
+ // that names nobody any more is dropped whole: an empty success wait could never be met.
+ if (inSuccess && success) {
+ const deps = success.deps.filter((d) => d !== depId)
+ if (deps.length) next.afterSuccess = { ...success, deps }
+ else delete next.afterSuccess
+ }
+ return next
}
/** Nodes whose eye is closed (`hideFanout`): every edge touching them is hidden from the canvas. */
diff --git a/src/renderer/lib/headlessRun.test.ts b/src/renderer/lib/headlessRun.test.ts
index 3d014c76e..adef34fa0 100644
--- a/src/renderer/lib/headlessRun.test.ts
+++ b/src/renderer/lib/headlessRun.test.ts
@@ -62,6 +62,10 @@ describe('planRunVerb', () => {
// Armed with --after-pr: it fires when the pull request is ready, not on mount.
const afterPr = { repository: 'o/r', waits: [{ number: 7, until: 'merged' as const }], deadlineAt: 1, armedAt: 0 }
expect(planRunVerb({ ...onScreen, pending: { ...pending, afterPr } })).toBe('refuse-not-mounted')
+ // Armed with --after-success: it fires when its stations report success — and a hand-edited
+ // file whose `after` lost them must not turn that into "starts when mounted".
+ const afterSuccess = { deps: ['dep-1'], deadlineAt: 1 }
+ expect(planRunVerb({ ...onScreen, pending: { ...pending, afterSuccess } })).toBe('refuse-not-mounted')
// The plain, never-attempted, dependency-free launch does start on mount.
expect(planRunVerb({ ...onScreen, pending })).toBe('wait-for-mount')
})
diff --git a/src/renderer/lib/headlessRun.ts b/src/renderer/lib/headlessRun.ts
index 29f4dbb83..032ba402b 100644
--- a/src/renderer/lib/headlessRun.ts
+++ b/src/renderer/lib/headlessRun.ts
@@ -33,8 +33,11 @@ export function planRunVerb(input: {
if (input.projectActive) {
if (input.hasWriter) return 'mounted'
// `after` is required by the type, but the launch comes out of hand-editable project JSON.
- // A pull request wait (`--after-pr`) is a dependency too: the mount does not fire it.
- const waitsOnDeps = (input.pending.after?.length ?? 0) > 0 || !!input.pending.afterPr
+ // A pull request wait (`--after-pr`) is a dependency too: the mount does not fire it. So is a
+ // success wait (`--after-success`), whose stations are normally in `after` as well — checked on
+ // its own because a hand-edited file need not keep the two in step.
+ const waitsOnDeps =
+ (input.pending.after?.length ?? 0) > 0 || !!input.pending.afterPr || !!input.pending.afterSuccess
return input.pending.manualOnly || waitsOnDeps ? 'refuse-not-mounted' : 'wait-for-mount'
}
return 'headless'
diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.ts
index adc5a7f3d..159a956ae 100644
--- a/src/renderer/lib/pendingLaunch.test.ts
+++ b/src/renderer/lib/pendingLaunch.test.ts
@@ -9,6 +9,8 @@ import {
unmetDeps,
LAUNCH_STALL_MS,
withPrHold,
+ withSuccessHold,
+ successDepFacts,
withLaunchBrief,
launchBriefPresent,
type ArmedNode,
@@ -432,6 +434,137 @@ describe('--after-pr: a PR wait is a third gate, ANDed with the deps and the set
})
})
+describe('--after-success: a success wait is a fourth gate — the turn ending is not enough', () => {
+ const NOW = 5_000_000
+ // As every open path builds it: the station is in `after` too (a success wait is `--after` plus
+ // the report).
+ const successNode = (deps: string[], deadlineAt = NOW + 60_000, after = deps): ArmedNode => ({
+ id: 'c',
+ data: { pendingLaunch: { after, command: 'echo c', afterSuccess: { deps, deadlineAt } } }
+ })
+ const live = new Set(['a', 'b', 'c'])
+ const done: StatusById = { a: { state: 'done' }, b: { state: 'done' } }
+ const rec = (nodeId: string, outcome: 'succeeded' | 'failed') => ({ nodeId, outcome, at: 1 })
+ const ctx = (...records: ReturnType<typeof rec>[]) => ({
+ outcomes: Object.fromEntries(records.map((r) => [r.nodeId, r])),
+ now: NOW
+ })
+ const fire = (node: ArmedNode, status: StatusById, c?: ReturnType<typeof ctx>, l = live) =>
+ launchesToFire([node], status, l, undefined, undefined, undefined, c)
+
+ it('a reported success, turn over: fires', () => {
+ expect(fire(successNode(['a']), done, ctx(rec('a', 'succeeded')))).toEqual([{ id: 'c', command: 'echo c' }])
+ })
+
+ it('a reported FAILURE blocks — the dependent never starts on it', () => {
+ expect(fire(successNode(['a']), done, ctx(rec('a', 'failed')))).toEqual([])
+ })
+
+ it('no report yet holds, even though the turn is over (the whole point: done is not success)', () => {
+ expect(fire(successNode(['a']), done, ctx())).toEqual([])
+ })
+
+ it('a reported success mid-turn waits for the turn to end', () => {
+ expect(fire(successNode(['a']), { a: { state: 'working' } }, ctx(rec('a', 'succeeded')))).toEqual([])
+ })
+
+ it('an errored last turn holds even after a success report (#521 stands)', () => {
+ expect(
+ fire(successNode(['a']), { a: { state: 'done', lastTurnError: { at: 1 } } }, ctx(rec('a', 'succeeded')))
+ ).toEqual([])
+ })
+
+ it('needs every station: one success is not enough', () => {
+ expect(fire(successNode(['a', 'b']), done, ctx(rec('a', 'succeeded')))).toEqual([])
+ expect(fire(successNode(['a', 'b']), done, ctx(rec('a', 'succeeded'), rec('b', 'succeeded')))).toEqual([
+ { id: 'c', command: 'echo c' }
+ ])
+ })
+
+ it('is ANDed with a plain --after on another station', () => {
+ const node = successNode(['a'], NOW + 60_000, ['a', 'b'])
+ expect(fire(node, { a: { state: 'done' }, b: { state: 'working' } }, ctx(rec('a', 'succeeded')))).toEqual([])
+ expect(fire(node, done, ctx(rec('a', 'succeeded')))).toEqual([{ id: 'c', command: 'echo c' }])
+ })
+
+ it('never fires past the deadline, whatever was reported', () => {
+ expect(fire(successNode(['a'], NOW), done, ctx(rec('a', 'succeeded')))).toEqual([])
+ })
+
+ it('a caller that passes no success context never releases a success hold', () => {
+ expect(fire(successNode(['a']), done, undefined)).toEqual([])
+ })
+
+ it('a CLOSED station releases only if it reported success before it went', () => {
+ const gone = new Set(['c'])
+ expect(fire(successNode(['a']), {}, ctx(rec('a', 'succeeded')), gone)).toEqual([{ id: 'c', command: 'echo c' }])
+ // For plain `--after` a deleted station is satisfied; for a success wait it is not — closing a
+ // station is exactly how an orchestrator abandons a failed attempt.
+ expect(fire(successNode(['a']), {}, ctx(), gone)).toEqual([])
+ expect(fire(successNode(['a']), {}, ctx(rec('a', 'failed')), gone)).toEqual([])
+ })
+
+ it('a hostile persisted hold never throws and never fires', () => {
+ for (const bad of ['a', ['a'], { deps: 'a', deadlineAt: NOW + 1 }, { deps: [42], deadlineAt: NOW + 1 }, 7]) {
+ const node = {
+ id: 'c',
+ data: { pendingLaunch: { after: ['a'], command: 'echo c', afterSuccess: bad } }
+ } as unknown as ArmedNode
+ expect(() => fire(node, done, ctx(rec('a', 'succeeded')))).not.toThrow()
+ expect(fire(node, done, ctx(rec('a', 'succeeded')))).toEqual([])
+ }
+ })
+
+ it('successDepFacts reads the --after rule for the turn and an OWN record only', () => {
+ expect(successDepFacts('a', done, live, {})).toEqual({ exists: true, turnDone: true })
+ expect(successDepFacts('constructor', {}, new Set(), {})).toEqual({ exists: false, turnDone: false })
+ })
+
+ it('the list row names the wait: waiting, blocked, expired — a delivery record still wins', () => {
+ expect(controlLaunchState(true, undefined, undefined, false, 'waiting')).toBe('waiting-success')
+ expect(controlLaunchState(true, undefined, undefined, false, 'blocked')).toBe('blocked-failure')
+ expect(controlLaunchState(true, undefined, undefined, false, 'expired')).toBe('success-expired')
+ expect(controlLaunchState(true, undefined, undefined, false, 'met')).toBe('queued')
+ expect(controlLaunchState(true, { kind: 'failed', attempts: 1, at: 0 }, undefined, false, 'blocked')).toBe('failed')
+ })
+
+ it('the tooltip says why it waits, why it is blocked, and that an expired wait needs ▶', () => {
+ const waiting = launchTooltip(undefined, 'Linter', 'claude', undefined, false, undefined, {
+ status: 'waiting',
+ summary: 'Builder (no outcome reported yet)',
+ deadline: '18:00'
+ })
+ expect(waiting).toBe(
+ 'Waiting for Linter to finish and for a reported success from Builder (no outcome reported yet), until 18:00, then runs:\nclaude'
+ )
+ const blocked = launchTooltip(undefined, '', 'claude', undefined, false, undefined, {
+ status: 'blocked',
+ summary: 'Builder (reported failure: "red")',
+ deadline: '18:00'
+ })
+ expect(blocked).toContain('Held on Builder (reported failure: "red")')
+ expect(blocked).toContain('▶')
+ const expired = launchTooltip(undefined, '', 'claude', undefined, false, undefined, {
+ status: 'expired',
+ summary: '',
+ deadline: '18:00'
+ })
+ expect(expired).toMatch(/passed its deadline \(18:00\)/)
+ expect(expired).toMatch(/will not start on its own/)
+ })
+})
+
+describe('withSuccessHold — the sibling of withPrHold', () => {
+ const hold = { deps: ['a'], deadlineAt: 9 }
+ it('adds the hold to a node that already holds its launch, and only then', () => {
+ const node = { id: 'n', data: { pendingLaunch: { after: ['a'], command: 'c' } } }
+ expect(withSuccessHold(node, hold).data.pendingLaunch).toEqual({ after: ['a'], command: 'c', afterSuccess: hold })
+ expect(withSuccessHold(node, undefined)).toBe(node)
+ const bare = { id: 'n', data: {} as { pendingLaunch?: PendingLaunch } }
+ expect(withSuccessHold(bare, hold)).toBe(bare)
+ })
+})
+
describe('withPrHold — one way every open path attaches a PR wait', () => {
const hold = { repository: 'o/r', waits: [{ number: 7, until: 'merged' as const }], deadlineAt: 9, armedAt: 0 }
it('adds the hold to a node that already holds its launch', () => {
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index 1e9cd6ce2..21bdc1862 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -6,6 +6,14 @@
import type { AgentState } from '@shared/agents/normalize'
import type { GitHubPullBoard } from '@shared/github-pull-status'
import type { PrWaitHold } from '@shared/pr-wait'
+import {
+ normalizeSuccessWaitHold,
+ outcomeOf,
+ successWaitSatisfied,
+ type StationOutcomeRecord,
+ type SuccessDepFacts,
+ type SuccessWaitHold
+} from '@shared/station-outcome'
import type { PendingLaunch } from '@shared/types'
import { prHoldSatisfied } from './prWait'
@@ -49,6 +57,47 @@ export interface PrGateContext {
now: number
}
+/** What `launchesToFire` needs to judge a `--after-success` wait: every station's latest task
+ * report in this app run (core's store, mirrored) and the clock deadlines are on. */
+export interface SuccessGateContext {
+ outcomes: Readonly<Record<string, StationOutcomeRecord>>
+ now: number
+}
+
+/**
+ * What the success wait knows about one station, from the same sources the `--after` gate reads:
+ * whether it is still on the canvas, whether its turn is over without an error (`depSatisfied`'s
+ * rule, so a success wait can never release where plain `--after` would still hold), and its report.
+ */
+export function successDepFacts(
+ depId: string,
+ status: StatusById,
+ live: ReadonlySet<string>,
+ outcomes: Readonly<Record<string, StationOutcomeRecord>>
+): SuccessDepFacts {
+ const exists = live.has(depId)
+ const reported = outcomeOf(outcomes, depId)
+ return {
+ exists,
+ turnDone: exists && depSatisfied(depId, status, live),
+ ...(reported ? { outcome: reported } : {})
+ }
+}
+
+/**
+ * Attach a `--after-success` wait to a node whose launch is already held — the sibling of
+ * `withPrHold`, applied by every open path that applies that one, so no path can arm a node that
+ * forgets a wait it was asked for.
+ */
+export function withSuccessHold<T extends { data: { pendingLaunch?: PendingLaunch } }>(
+ node: T,
+ hold: SuccessWaitHold | undefined
+): T {
+ const p = node.data.pendingLaunch
+ if (!hold || !p) return node
+ return { ...node, data: { ...node.data, pendingLaunch: { ...p, afterSuccess: hold } } }
+}
+
/** Control opens reply before the PTY exists. Keep their command durable until delivery lands,
* even with no dependencies (or dependencies that are already done). */
export function queueControlLaunch<T extends { data: { initialCommand?: string; pendingLaunch?: PendingLaunch } }>(
@@ -109,9 +158,30 @@ export function controlLaunchState(
delivery: LaunchDelivery | undefined,
status?: { dropped?: boolean; state?: AgentState },
/** The node's `--after-pr` wait has passed its deadline: it will not start on its own. */
- prExpired = false
-): 'queued' | 'stalled' | 'failed' | 'starting' | 'brief-missing' | 'dropped' | 'working' | 'expired' | undefined {
- if (pending) return delivery?.kind ?? (prExpired ? 'expired' : 'queued')
+ prExpired = false,
+ /** Where the node's `--after-success` wait stands, when it has one. */
+ success?: 'met' | 'waiting' | 'blocked' | 'expired'
+):
+ | 'queued'
+ | 'stalled'
+ | 'failed'
+ | 'starting'
+ | 'brief-missing'
+ | 'dropped'
+ | 'working'
+ | 'expired'
+ | 'success-expired'
+ | 'waiting-success'
+ | 'blocked-failure'
+ | undefined {
+ if (pending) {
+ if (delivery) return delivery.kind
+ if (prExpired) return 'expired'
+ if (success === 'expired') return 'success-expired'
+ if (success === 'blocked') return 'blocked-failure'
+ if (success === 'waiting') return 'waiting-success'
+ return 'queued'
+ }
if (status?.dropped) return 'dropped'
if (status?.state === 'working') return 'working'
return undefined
@@ -183,7 +253,8 @@ export function launchesToFire(
live: ReadonlySet<string>,
setupDone?: (groupId: string) => boolean,
deliveries?: Record<string, LaunchDelivery | undefined>,
- pr?: PrGateContext
+ pr?: PrGateContext,
+ success?: SuccessGateContext
): LaunchToFire[] {
const out: LaunchToFire[] = []
for (const n of nodes) {
@@ -199,6 +270,23 @@ export function launchesToFire(
// that did not say what the pull requests look like has told us nothing, and "no news" is
// exactly what must never release a launch (the same rule as an unknown agent state).
if (p.afterPr && !(pr && prHoldSatisfied(p.afterPr, pr.board, pr.now))) continue
+ // The FOURTH gate (`--after-success`): every named station reported SUCCESS and its turn is over.
+ // Closed without a context, for the same reason as the PR gate: no news is never a success.
+ // Re-read through the shape rule: live node data can arrive by a path that did not cross a
+ // serializer seam (a peer's canvas mutation), and a malformed hold must hold, never throw.
+ const successHold = normalizeSuccessWaitHold(p.afterSuccess)
+ if (
+ successHold &&
+ !(
+ success &&
+ successWaitSatisfied(
+ successHold,
+ (d) => successDepFacts(d, status, live, success.outcomes),
+ success.now
+ )
+ )
+ )
+ continue
if (p.after.every((d) => depSatisfied(d, status, live))) {
out.push({ id: n.id, command: p.command, ...(p.promptFile ? { briefFile: p.promptFile } : {}) })
}
@@ -276,7 +364,10 @@ export function launchTooltip(
relay = false,
/** The node's `--after-pr` wait: what is still unmet (`prHoldSummary`), whether it has passed
* its deadline, and that deadline as the caller formats it (a locale string is not pure). */
- pr?: { expired: boolean; summary: string; deadline: string }
+ pr?: { expired: boolean; summary: string; deadline: string },
+ /** The node's `--after-success` wait: where it stands (`successWaitStatus`), the unmet stations
+ * (`successWaitSummary`), and its deadline as the caller formats it. */
+ success?: { status: 'met' | 'waiting' | 'blocked' | 'expired'; summary: string; deadline: string }
): string {
if (delivery?.kind === 'starting') return 'Starting in the background — an agent asked for this session to run now.'
const runs = `Runs:\n${command}`
@@ -312,12 +403,34 @@ export function launchTooltip(
'its own.\n' +
`Press \u25b6 to run it now.\n${runs}`
)
+ if (success?.status === 'expired')
+ return (
+ `The wait for stations to report success passed its deadline (${success.deadline}), so this ` +
+ 'will not start on its own.\n' +
+ `Press \u25b6 to run it now.\n${runs}`
+ )
+ // A reported failure is the other wait that will not end on its own: named, with both ways out.
+ if (success?.status === 'blocked')
+ return (
+ `Held on ${success.summary}.\n` +
+ 'It does not start on a task that did not succeed. Retry that station — this starts when it ' +
+ `reports success — or press \u25b6 to run it now.\n${runs}`
+ )
if (delivery?.kind === 'stalled')
return (
'Ready to run, but this terminal has not started yet — the launch is still held and ' +
'fires as soon as it does.\n' +
`Press \u25b6 to try it now.\n${runs}`
)
+ if (success?.status === 'waiting') {
+ // `waitingOn` here is the caller's list of the OTHER stations (plain `--after`), if any.
+ const stations = waitingOn ? `${waitingOn} to finish and for ` : ''
+ const prs = pr?.summary ? `, and for ${pr.summary}` : ''
+ return (
+ `Waiting for ${stations}a reported success from ${success.summary}${prs}, until ` +
+ `${success.deadline}, then runs:\n${command}`
+ )
+ }
if (pr?.summary) {
const stations = waitingOn ? `${waitingOn} to finish and for ` : ''
return `Waiting for ${stations}${pr.summary}, until ${pr.deadline}, then runs:\n${command}`
diff --git a/src/renderer/lib/projectOpen.test.ts b/src/renderer/lib/projectOpen.test.ts
index 58ee51775..c5545870b 100644
--- a/src/renderer/lib/projectOpen.test.ts
+++ b/src/renderer/lib/projectOpen.test.ts
@@ -222,7 +222,7 @@ describe('armForColdOpen — the launch moves (never copies) into pendingLaunch
describe('projectTargetFlagRefusal — the v1 flag exclusion fires (review I-2)', () => {
const REFUSAL =
- 'project-target-flag-unsupported: --group/--after cannot be combined with --project'
+ 'project-target-flag-unsupported: --group/--after/--after-success cannot be combined with --project'
it('refuses --group, --after, and both — with the exact named reply', () => {
expect(projectTargetFlagRefusal({ group: 'g1' })).toBe(REFUSAL)
diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.ts
index 3144a149b..95d94ab8d 100644
--- a/src/renderer/lib/projectOpen.ts
+++ b/src/renderer/lib/projectOpen.ts
@@ -83,9 +83,15 @@ export function clearAttachConsentForTests(): void {
* is red-capable (review #363 I-2) — the dispatch only relays the answer; an empty-string value
* counts as "not passed" (the shim always sends a value for a bare flag).
*/
-export function projectTargetFlagRefusal(args: { group?: string; after?: string }): string | null {
- if (args.group || args.after) {
- return 'project-target-flag-unsupported: --group/--after cannot be combined with --project'
+export function projectTargetFlagRefusal(args: {
+ group?: string
+ after?: string
+ 'after-success'?: string
+}): string | null {
+ // `--after-success` names station ids exactly as `--after` does, so it is excluded for the same
+ // reason (and it is folded into `after` before this runs, so either field refuses it).
+ if (args.group || args.after || args['after-success']) {
+ return 'project-target-flag-unsupported: --group/--after/--after-success cannot be combined with --project'
}
return null
}
diff --git a/src/renderer/lib/stationOutcomeWiring.ts b/src/renderer/lib/stationOutcomeWiring.ts
new file mode 100644
index 000000000..6ee1e1bd5
--- /dev/null
+++ b/src/renderer/lib/stationOutcomeWiring.ts
@@ -0,0 +1,28 @@
+/**
+ * Mirror core's station task outcomes (src/core/station-outcome-store.ts) into `useStationOutcomes`:
+ * the initial pull (a push that fired before this renderer loaded is otherwise lost) and every later
+ * push. Nothing flows the other way — a report is made by the station through canvas control, never
+ * by this renderer.
+ *
+ * Installed once, on the app's own api (`window.nodeTerminal`): the stations core reports on are this
+ * machine's (or, in the Server Edition, the server's).
+ */
+import type { NodeTerminalApi } from '@shared/types'
+import { sanitizeOutcomeRecords } from '@shared/station-outcome'
+import { useStationOutcomes } from '../state/stationOutcomes'
+
+export function installStationOutcomeWiring(api: Pick<NodeTerminalApi, 'stationOutcome'>): () => void {
+ const set = (raw: unknown): void => useStationOutcomes.getState().setRecords(sanitizeOutcomeRecords(raw))
+ let live = true
+ void api.stationOutcome
+ .list()
+ .then((records) => {
+ if (live) set(records)
+ })
+ .catch(() => undefined)
+ const off = api.stationOutcome.onChanged((records) => set(records))
+ return () => {
+ live = false
+ off()
+ }
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 5a4d5b5f6..15cfc9bfd 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -222,7 +222,14 @@ import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../sta
import { codexApprovalCaps } from '../state/codexCli'
import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
import { useLaunchDelivery } from '../state/launchDelivery'
-import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'
+import { erroredDeps, launchTooltip, successDepFacts } from '../lib/pendingLaunch'
+import {
+ normalizeSuccessWaitHold,
+ successWaitExpired,
+ successWaitStatus,
+ successWaitSummary
+} from '@shared/station-outcome'
+import { useStationOutcomes } from '../state/stationOutcomes'
import { StationFailedChip } from '../components/StationFailedChip'
import { prHoldExpired, prHoldSummary } from '../lib/prWait'
import { pullBoardFor, useGitHubIssues } from '../state/githubIssues'
@@ -2044,9 +2051,17 @@ export function TerminalNode({
!observedLaunchDelivery &&
!(pendingLaunch?.after?.length) &&
!pendingLaunch?.awaitSetupGroup &&
- !pendingLaunch?.afterPr
+ !pendingLaunch?.afterPr &&
+ !pendingLaunch?.afterSuccess
+ // Through the shape rule, memoized on the raw value: a malformed hold (a peer's mutation, a
+ // hand-edited file) reads as an unreadable, expired hold rather than throwing during render.
+ const rawSuccessHold = pendingLaunch?.afterSuccess
+ const successHold = useMemo(() => normalizeSuccessWaitHold(rawSuccessHold), [rawSuccessHold])
+ // The stations a `--after-success` wait names are ALSO in `after`; the tooltip speaks of them in
+ // the success sentence, so the plain list leaves them out rather than naming them twice.
+ const successDepIds = successHold && !successHold.invalid ? successHold.deps : []
const pendingWaitingOn = [
- ...(pendingLaunch?.after ?? []).map(
+ ...(pendingLaunch?.after ?? []).filter((depId) => !successDepIds.includes(depId)).map(
(depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId
),
// The other thing a launch can be held on: this worktree's project setup script. Named, or the
@@ -2087,6 +2102,47 @@ export function TerminalNode({
deadline: prHold.invalid ? 'the project file holds an unreadable one' : new Date(prHold.deadlineAt).toLocaleString()
}
: undefined
+ // `--after-success`: where the wait stands, from the same facts the launch loop judges (the
+ // stations' reports, their turn state, whether they still exist). A PRIMITIVE signature per store,
+ // selected only for a node that has such a wait, so no other node re-renders on a report or a
+ // hook event.
+ const successOutcomeSig = useStationOutcomes((s) =>
+ successDepIds.map((d) => {
+ const r = Object.prototype.hasOwnProperty.call(s.byId, d) ? s.byId[d] : undefined
+ return r ? `${d}:${r.outcome}:${r.at}` : `${d}:-`
+ }).join('|')
+ )
+ const successStateSig = useAgentStatus((s) =>
+ successDepIds.map((d) => `${d}:${s.byId[d]?.state ?? '-'}:${s.byId[d]?.lastTurnError ? 'e' : ''}`).join('|')
+ )
+ const [, setSuccessClock] = useState(0)
+ useEffect(() => {
+ if (!successHold || successWaitExpired(successHold, Date.now())) return
+ const t = setTimeout(
+ () => setSuccessClock((v) => v + 1),
+ Math.min(successHold.deadlineAt - Date.now() + 50, 2 ** 31 - 1)
+ )
+ return () => clearTimeout(t)
+ }, [successHold])
+ const successTooltip = useMemo(() => {
+ if (!successHold) return undefined
+ const live = new Set(successDepIds.filter((d) => !!getNode(d)))
+ const facts = (d: string) =>
+ successDepFacts(d, useAgentStatus.getState().byId, live, useStationOutcomes.getState().byId)
+ const name = (d: string) => ((getNode(d) as CanvasNode | undefined)?.data.title as string) || d
+ return {
+ status: successWaitStatus(successHold, facts, Date.now()),
+ summary: successHold.invalid
+ ? 'a success wait that could not be read'
+ : successWaitSummary(successHold, facts, name),
+ deadline: successHold.invalid
+ ? 'the project file holds an unreadable one'
+ : new Date(successHold.deadlineAt).toLocaleString()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the two signatures are the triggers
+ }, [successHold, successOutcomeSig, successStateSig, getNode])
+ const successExpired = successTooltip?.status === 'expired'
+ const successBlocked = successTooltip?.status === 'blocked'
const pendingErroredOn = erroredDepIds
? erroredDepIds
.split(',')
@@ -5896,12 +5952,22 @@ export function TerminalNode({
{pendingLaunch && !firstOpenInFlight && (
<span
className={`term-node__status term-node__status--queued nodrag${
- (launchDelivery || prExpired) && !startingNow ? ' term-node__status--queued-warn' : ''
+ (launchDelivery || prExpired || successExpired || successBlocked) && !startingNow
+ ? ' term-node__status--queued-warn'
+ : ''
}`}
- title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip)}
+ title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip)}
>
<span className="term-node__status-dot" />
- {startingNow ? 'STARTING' : launchDelivery ? '⚠ QUEUED' : prExpired ? '⚠ EXPIRED' : 'QUEUED'}
+ {startingNow
+ ? 'STARTING'
+ : launchDelivery
+ ? '⚠ QUEUED'
+ : prExpired || successExpired
+ ? '⚠ EXPIRED'
+ : successBlocked
+ ? '⚠ BLOCKED'
+ : 'QUEUED'}
<button
className="term-node__queued-run"
disabled={session.source === 'relay' || startingNow}
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index 416237681..05e2e8eeb 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -99,17 +99,23 @@ describe('the QUEUED badge carries the delivery state (source pins)', () => {
// `pendingErroredOn` is the fourth argument since #521 — an errored upstream is idle, so
// without it the tooltip would promise a wait that never ends. The relay flag also
// keeps unsupported queued delivery from promising a working Run now action, and the last
- // argument names an `--after-pr` wait (and its deadline) beside the stations.
+ // arguments name an `--after-pr` wait and an `--after-success` wait (with their deadlines)
+ // beside the stations.
expect(src).toContain(
- "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip)"
+ "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip)"
)
})
it('a background start reads STARTING, without the warning, and disables ▶ (#925)', () => {
// Core is typing the launch into this pane; a ▶ click would splice a second copy into it.
expect(src).toContain("const startingNow = launchDelivery?.kind === 'starting'")
- expect(src).toContain("(launchDelivery || prExpired) && !startingNow ? ' term-node__status--queued-warn' : ''")
- expect(src).toContain("{startingNow ? 'STARTING' : launchDelivery ? '⚠ QUEUED' : prExpired ? '⚠ EXPIRED' : 'QUEUED'}")
+ expect(src).toMatch(
+ /\(launchDelivery \|\| prExpired \|\| successExpired \|\| successBlocked\) && !startingNow\s*\?\s*' term-node__status--queued-warn'/
+ )
+ // STARTING wins over every warning; a blocked success wait is a warning of its own.
+ expect(src).toMatch(
+ /\{startingNow\s*\?\s*'STARTING'\s*:\s*launchDelivery\s*\?\s*'⚠ QUEUED'\s*:\s*prExpired \|\| successExpired\s*\?\s*'⚠ EXPIRED'\s*:\s*successBlocked\s*\?\s*'⚠ BLOCKED'\s*:\s*'QUEUED'\}/
+ )
expect(src).toContain("disabled={session.source === 'relay' || startingNow}")
})
diff --git a/src/renderer/state/stationOutcomes.ts b/src/renderer/state/stationOutcomes.ts
new file mode 100644
index 000000000..b5f62a894
--- /dev/null
+++ b/src/renderer/state/stationOutcomes.ts
@@ -0,0 +1,29 @@
+/**
+ * What each station last reported about its TASK (`report-outcome`) — a MIRROR of core's store
+ * (src/core/station-outcome-store.ts), replaced whole on every push, never edited here. Core decides
+ * what a report is and when it ends; the renderer reads it for the `--after-success` gate, the
+ * QUEUED badge and `list`.
+ *
+ * Transient: core re-sends the list on request after a reload, and after an app restart there is
+ * nothing to send — no station has reported in this run.
+ */
+import { create } from 'zustand'
+import type { StationOutcomeRecord } from '@shared/station-outcome'
+export { outcomeOf } from '@shared/station-outcome'
+
+interface StationOutcomesStore {
+ byId: Record<string, StationOutcomeRecord>
+ setRecords(records: readonly StationOutcomeRecord[]): void
+}
+
+export const useStationOutcomes = create<StationOutcomesStore>((set) => ({
+ byId: Object.create(null) as Record<string, StationOutcomeRecord>,
+ setRecords: (records) => {
+ // No prototype: `__proto__` passes the node-id charset, and assigning it on a plain object
+ // would replace the object's prototype instead of adding a record.
+ const byId = Object.create(null) as Record<string, StationOutcomeRecord>
+ for (const r of records) byId[r.nodeId] = r
+ set({ byId })
+ }
+}))
+
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index a4f6690b7..67db51d95 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -1217,6 +1217,25 @@ describe('pendingLaunch at the serializer seams (a held launch is hostile input
expect(flow[0].data.pendingLaunch).toMatchObject({ after: [], manualOnly: true })
})
+ it('round-trips a success-held launch (--after-success)', () => {
+ const hold = {
+ after: ['b1'],
+ command: 'claude',
+ attempted: false,
+ afterSuccess: { deps: ['b1'], deadlineAt: 5 }
+ }
+ const flow = nodeStatesToFlow([state(hold)])
+ expect(flow[0].data.pendingLaunch).toEqual(hold)
+ expect(flowToNodeStates(flow)[0].pendingLaunch).toEqual(hold)
+ })
+
+ it('a malformed success wait loads as the invalid hold, on the way in and on the way out', () => {
+ const flow = nodeStatesToFlow([state({ after: ['b1'], command: 'c', afterSuccess: { deps: 'b1' } })])
+ expect((flow[0].data.pendingLaunch as { afterSuccess?: { invalid?: true } }).afterSuccess?.invalid).toBe(true)
+ const out = flowToNodeStates([live({ after: [], command: 'c', afterSuccess: ['b1'] })])
+ expect(out[0].pendingLaunch?.afterSuccess?.invalid).toBe(true)
+ })
+
it('a malformed PR wait loads as the invalid hold, on the way in and on the way out', () => {
const flow = nodeStatesToFlow([state({ after: [], command: 'c', afterPr: { waits: 'all' } })])
expect((flow[0].data.pendingLaunch as { afterPr?: { invalid?: true } }).afterPr?.invalid).toBe(true)
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index 6055cd813..ddced8243 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -12,6 +12,11 @@ import {
} from '../core/agents/agent-messaging'
import { paneOwnerProject } from '../core/agents/pane-ownership'
import { StationNoticeMonitor } from '../core/agents/station-notice'
+import {
+ StationOutcomeStore,
+ clearOutcomesAfterControl,
+ handleReportOutcome
+} from '../core/station-outcome-store'
import { stationRecipientFromOwner } from '../shared/station-notice'
import {
mirrorEntry,
@@ -88,6 +93,8 @@ export interface ServerCanvasControl {
onAgentEvent(event: NormalizedAgentEvent): void
/** Station-failure notices for the stations agents opened during THIS server run. */
stationNotices: StationNoticeMonitor
+ /** What each station reported about its own task in THIS server run (`report-outcome`). */
+ stationOutcomes: StationOutcomeStore
installSkillInto(configDir: string): void
stop(): void
}
@@ -176,6 +183,10 @@ export async function initServerCanvasControl(
installHooksIntoLocalAccounts(deps.settings().claudeAccounts ?? [], installSkillInto)
}
+ // Station task outcomes: built before the factory, which reads them for `--after-success`.
+ const stationOutcomes = new StationOutcomeStore((records) =>
+ platform().broadcast(IPC.stationOutcomeChanged, records)
+ )
const factory = new HeadlessNodeFactory({
workspaceStore: deps.workspaceStore,
ptyManager: deps.ptyManager,
@@ -191,6 +202,7 @@ export async function initServerCanvasControl(
deps.codexSharedIdentity ?? (() => codexIdentityCaps().then((caps) => caps.shared)),
stateOf: nodeState,
agentIdOf: (nodeId) => mirrorEntry(nodeId)?.agentId,
+ outcomeOf: (nodeId) => stationOutcomes.get(nodeId),
// NOT `workspaceExternalChange`. That channel means "somebody else wrote this file" and the
// renderer answers it with `decideExternalChange`, which compares the whole project shell —
// and `ropes` is part of it, so every headless spawn (one appended `ctrl-…` rope) read as a
@@ -266,6 +278,22 @@ export async function initServerCanvasControl(
color: (sourceNodeId, args) => factory.color(sourceNodeId, args),
sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),
run: (sourceNodeId, args, verified) => factory.run(sourceNodeId, args, verified),
+ // A station's report about ITSELF (core/station-outcome-store.ts, the same handler the desktop
+ // runs). A report can release an armed dependent, so the factory re-evaluates its arms.
+ reportOutcome: (sourceNodeId, args, verified) =>
+ handleReportOutcome(
+ { nodeId: sourceNodeId, args, verified },
+ {
+ store: stationOutcomes,
+ now: () => Date.now(),
+ projectIdOfNode: (id) => {
+ const ids = deps.workspaceStore.projectIdsForNode(id)
+ return ids.length === 1 ? ids[0] : undefined
+ },
+ appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry),
+ onRecorded: () => void factory.refreshArmed()
+ }
+ ),
settings: async (sourceNodeId, args) =>
serverSettingsControl(
{
@@ -286,14 +314,22 @@ export async function initServerCanvasControl(
// restart clears it, so an owner request or browser view is the only cold-spawn authority.
await factory.start()
+ const baseHandler = createServerEditionControlHandler(actions)
return {
- handler: createServerEditionControlHandler(actions),
+ // New work handed to a station (`send` / `reply` / `run` aimed at it) withdraws its outcome
+ // report — the "new task" rule in core/station-outcome-store.ts, applied after the answer.
+ handler: async (req) => {
+ const reply = await baseHandler(req)
+ clearOutcomesAfterControl(stationOutcomes, req.verb, req.args, reply, req.nodeId)
+ return reply
+ },
onAgentEvent: (event) => {
onMessagingAgentEvent(event, queue)
factory.onAgentEvent(event)
stationNotices.onAgentEvent(event)
},
stationNotices,
+ stationOutcomes,
installSkillInto,
stop: () => {
factory.stop()
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index d0d2b4531..2b03e31d9 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -184,9 +184,44 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
sticky: vi.fn(async () => ({ ok: true as const, result: { id: 'sticky-new' } })),
settings: vi.fn(async () => ({ ok: true as const, message: 'settings' })),
run: vi.fn(async () => ({ ok: true as const })),
+ reportOutcome: vi.fn(async () => ({ ok: true as const, message: 'recorded' })),
deliver: vi.fn(async () => ({ ok: true as const, message: 'queued' }))
})
+ it('routes report-outcome to its action, after the shared parse', async () => {
+ const a = actions()
+ const handler = createServerEditionControlHandler(a)
+ await handler({
+ verb: 'report-outcome',
+ nodeId: 'src',
+ args: { outcome: 'succeeded', note: 'done' },
+ verified: true
+ })
+ expect(a.reportOutcome).toHaveBeenCalledWith('src', { outcome: 'succeeded', note: 'done' }, true)
+ // The shared parser requires --outcome before the action is reached.
+ await expect(
+ handler({ verb: 'report-outcome', nodeId: 'src', args: {}, verified: true })
+ ).resolves.toEqual({ ok: false, error: 'report-outcome requires --outcome succeeded|failed' })
+ expect(a.reportOutcome).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses the --after <id>:ok form and a malformed --after-success before any action', async () => {
+ const a = actions()
+ const handler = createServerEditionControlHandler(a)
+ await expect(
+ handler({ verb: 'open-agent', nodeId: 'src', args: { agent: 'claude', after: 'a1:ok' }, verified: true })
+ ).resolves.toMatchObject({ ok: false, error: expect.stringContaining('--after-success') })
+ await expect(
+ handler({
+ verb: 'open-agent',
+ nodeId: 'src',
+ args: { agent: 'claude', 'after-success': 'a1', after: 'a1' },
+ verified: true
+ })
+ ).resolves.toMatchObject({ ok: false, error: expect.stringContaining('name each station once') })
+ expect(a.openAgent).not.toHaveBeenCalled()
+ })
+
it('routes run to the factory (#925)', async () => {
const a = actions()
const handler = createServerEditionControlHandler(a)
@@ -432,6 +467,7 @@ describe('the enabled Server Edition handler, behind the request ledger', () =>
sticky: vi.fn(),
settings: vi.fn(),
run: vi.fn(),
+ reportOutcome: vi.fn(),
deliver: vi.fn()
})
hookServer.setControlHandler(handler)
diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.ts
index 73d655ccf..a04fe2373 100644
--- a/src/server/control-unsupported.ts
+++ b/src/server/control-unsupported.ts
@@ -97,6 +97,9 @@ export interface ServerEditionControlActions {
settings(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
/** `run --node <id>` (#925): deliver a retained launch for the node's creator. */
run(sourceNodeId: string, args: Record<string, string>, verified: boolean): Promise<ServerControlReply>
+ /** `report-outcome` (@shared/station-outcome): a station's report about ITSELF — no creator check,
+ * because it touches no other node. */
+ reportOutcome(sourceNodeId: string, args: Record<string, string>, verified: boolean): Promise<ServerControlReply>
deliver(input: {
verb: 'send' | 'reply' | 'notify'
sourceNodeId: string
@@ -119,7 +122,8 @@ const SERVER_V1_VERBS: ReadonlySet<string> = new Set([
'notify',
'sticky',
'settings',
- 'run'
+ 'run',
+ 'report-outcome'
])
/** A permanent, verb-specific refusal used only while canvas control itself is enabled. */
@@ -186,6 +190,8 @@ export function createServerEditionControlHandler(actions: ServerEditionControlA
return actions.settings(nodeId, command.args)
case 'run':
return actions.run(nodeId, command.args, verified)
+ case 'report-outcome':
+ return actions.reportOutcome(nodeId, command.args, verified)
case 'send':
case 'reply':
case 'notify':
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index f9ca1aac8..1bb19b16c 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -10,6 +10,7 @@ import { WorkspaceStore } from '../core/workspace-store'
import type { AgentState } from '../shared/agents/normalize'
import { MAX_LAUNCH_LINE_BYTES } from '../shared/canonical-line'
import { RUN_NOW_AFTER_REFUSAL } from '../shared/control-verbs'
+import { RUN_NOW_AFTER_SUCCESS_REFUSAL, type StationOutcomeRecord } from '../shared/station-outcome'
import {
DEFAULT_SETTINGS,
type CanvasNodeState,
@@ -163,6 +164,7 @@ describe('HeadlessNodeFactory', () => {
let ownership: HeadlessNodeOwnership
let codexSharedIdentity: boolean
let codexApprovalValues: { approvalValues: string[] | null }
+ let outcomes: Record<string, StationOutcomeRecord>
const settings = (): Settings => ({
...DEFAULT_SETTINGS,
@@ -179,6 +181,7 @@ describe('HeadlessNodeFactory', () => {
store = new WorkspaceStore()
pty = new FakePty()
states = {}
+ outcomes = {}
published = []
removed = []
publishedProjects = []
@@ -235,6 +238,7 @@ describe('HeadlessNodeFactory', () => {
codexSharedIdentity: async () => codexSharedIdentity,
ownership,
stateOf: (id) => states[id],
+ outcomeOf: (id) => outcomes[id],
launchTiming: { quietMs: 0, capMs: 0 },
publishNode: (_projectId, node) => published.push(node),
publishRemoval: (_projectId, nodeId) => removed.push(nodeId),
@@ -1211,6 +1215,124 @@ describe('HeadlessNodeFactory', () => {
expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()
})
+ describe('--after-success: the dependent waits for a REPORTED success, not a turn ending', () => {
+ const report = (nodeId: string, outcome: 'succeeded' | 'failed', note?: string) => {
+ outcomes[nodeId] = { nodeId, outcome, at: Date.now(), ...(note ? { note } : {}) }
+ }
+ const openWaiting = async () => {
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'ship it', 'after-success': 'term-upstream' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ return (reply.result as { id: string }).id
+ }
+
+ it('holds on an idle station with no report, and releases once it reports success', async () => {
+ states['term-upstream'] = 'done'
+ const id = await openWaiting()
+ expect(pty.sends).toEqual([])
+ const held = (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)
+ expect(held?.pendingLaunch).toMatchObject({
+ after: ['term-upstream'],
+ afterSuccess: { deps: ['term-upstream'], deadlineAt: expect.any(Number) },
+ executor: 'server'
+ })
+ // The turn is over and nothing was reported: `--after` alone would fire here.
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ report('term-upstream', 'succeeded')
+ await factory.refreshArmed()
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'ship it'" }])
+ })
+
+ it('a reported failure blocks it for good', async () => {
+ states['term-upstream'] = 'done'
+ const id = await openWaiting()
+ report('term-upstream', 'failed', 'tests red')
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ const still = (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)
+ expect(still?.pendingLaunch?.afterSuccess).toBeDefined()
+ })
+
+ it('a reported success mid-turn waits for the turn to end', async () => {
+ states['term-upstream'] = 'working'
+ await openWaiting()
+ report('term-upstream', 'succeeded')
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ states['term-upstream'] = 'done'
+ await factory.refreshArmed()
+ expect(pty.sends).toHaveLength(1)
+ })
+
+ it('a station already reported successful and idle releases the open at once', async () => {
+ states['term-upstream'] = 'done'
+ report('term-upstream', 'succeeded')
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'go', 'after-success': 'term-upstream' },
+ true
+ )
+ expect(reply.result).toMatchObject({ deliveredIds: [expect.any(String)], afterSuccess: ['term-upstream'] })
+ expect(pty.sends).toHaveLength(1)
+ })
+
+ it('never fires past its deadline', async () => {
+ states['term-upstream'] = 'done'
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'x', 'after-success': 'term-upstream', 'success-deadline': '1m' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ const ws = await store.load({ sideline: false })
+ const node = ws.projects[0].nodes.find((n) => n.id === (reply.result as { id: string }).id)
+ node!.pendingLaunch!.afterSuccess!.deadlineAt = 1
+ await store.save(ws)
+ report('term-upstream', 'succeeded')
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ })
+
+ it('a hostile persisted hold never fires and never throws', async () => {
+ states['term-upstream'] = 'done'
+ const id = await openWaiting()
+ const ws = await store.load({ sideline: false })
+ const node = ws.projects[0].nodes.find((n) => n.id === id)
+ ;(node!.pendingLaunch as unknown as { afterSuccess: unknown }).afterSuccess = { deps: 'term-upstream' }
+ await store.save(ws)
+ report('term-upstream', 'succeeded')
+ await expect(factory.refreshArmed()).resolves.toBeUndefined()
+ expect(pty.sends).toEqual([])
+ })
+
+ it('refuses a station that could never report, and --run-now, before creating anything', async () => {
+ const ws = await store.load({ sideline: false })
+ ws.projects[0].nodes.push({ ...terminal('term-agy', 'Agy'), agentId: 'antigravity' })
+ await store.save(ws)
+ ownership.record('term-agy', { sourceNodeId: 'term-source', projectId: 'project-1' })
+ const before = (await store.load({ sideline: false })).projects[0].nodes.length
+ const r = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'x', 'after-success': 'term-agy' },
+ true
+ )
+ expect(r).toMatchObject({ ok: false, error: expect.stringContaining('cannot report an outcome') })
+ await expect(
+ factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'x', 'after-success': 'term-upstream', 'run-now': '1' },
+ true
+ )
+ ).resolves.toEqual({ ok: false, error: RUN_NOW_AFTER_SUCCESS_REFUSAL })
+ expect((await store.load({ sideline: false })).projects[0].nodes.length).toBe(before)
+ })
+ })
+
it('holds a fresh dependency through its boot done blip, then releases after working -> done', async () => {
const upstreamReply = await factory.openAgent(
'term-source',
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 56baa85b9..2b92a747f 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -37,6 +37,17 @@ import { assembleLaunchCommand } from '../shared/agents/launch'
import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
import { oneLine } from '../shared/one-line'
import { RUN_NOW_AFTER_REFUSAL, runNowRequested } from '../shared/control-verbs'
+import {
+ RUN_NOW_AFTER_SUCCESS_REFUSAL,
+ normalizeSuccessWaitHold,
+ parseAfterSuccessArg,
+ parseSuccessDeadlineArg,
+ successDepRefusal,
+ successWaitSatisfied,
+ type StationOutcomeRecord,
+ type SuccessDepFacts,
+ type SuccessWaitHold
+} from '../shared/station-outcome'
import { isRemoteSessionNode } from '../shared/worktree'
import { issueLaunchPrompt, resolveIssueArg, type IssueRef } from '../shared/github-issue-ref'
import { runEndedEvent, runStartedEvent } from '../shared/issue-runs'
@@ -110,6 +121,9 @@ export interface HeadlessNodeFactoryDeps {
/** Hook-mirror lookups. A stored agentId wins; these cover a plain terminal running an agent. */
stateOf(nodeId: string): AgentState | undefined
agentIdOf?(nodeId: string): string | undefined
+ /** A station's latest task report (`report-outcome`, core's store) — what `--after-success` waits
+ * on. Absent = no report is ever known, so a success wait never releases on its own. */
+ outcomeOf?(nodeId: string): StationOutcomeRecord | undefined
env?: Record<string, string | undefined>
now?: () => number
publishNode?: (projectId: string, node: CanvasNodeState) => void
@@ -712,6 +726,27 @@ export class HeadlessNodeFactory {
return target
}
+ private now(): number {
+ return this.deps.now?.() ?? Date.now()
+ }
+
+ /** What a success wait knows about one station, from the same facts this edition's `--after`
+ * reads (the mirror's `done`, the `awaitWorking` fresh-spawn rule), plus its report. */
+ private successFacts(
+ project: Project,
+ depId: string,
+ observed?: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>
+ ): SuccessDepFacts {
+ const exists = project.nodes.some((candidate) => candidate.id === depId)
+ const state = observed?.nodeId === depId ? observed.state : this.deps.stateOf(depId)
+ const reported = this.deps.outcomeOf?.(depId)
+ return {
+ exists,
+ turnDone: exists && !this.awaitingFirstWorking.has(depId) && state === 'done',
+ ...(reported ? { outcome: reported } : {})
+ }
+ }
+
private resolveAfter(
project: Project,
raw: string | undefined,
@@ -1238,13 +1273,46 @@ export class HeadlessNodeFactory {
// `run-now` (#925) is a no-op, since a server open already delivers immediately; only its
// pairing with `--after` is refused, just below.
verb === 'open-terminal'
- ? new Set(['count', 'cwd', 'cmd', 'after', 'project', 'run-now'])
- : new Set(['agent', 'count', 'cwd', 'prompt', 'after', 'project', 'model', 'issue', 'run-now'])
+ ? new Set(['count', 'cwd', 'cmd', 'after', 'after-success', 'success-deadline', 'project', 'run-now'])
+ : new Set([
+ 'agent',
+ 'count',
+ 'cwd',
+ 'prompt',
+ 'after',
+ 'after-success',
+ 'success-deadline',
+ 'project',
+ 'model',
+ 'issue',
+ 'run-now'
+ ])
)
if (flagError) return { ok: false, error: `${verb}: ${flagError}` }
// "Start now" and "start when X is done" contradict each other: refused in the desktop's
// words, before anything is created, rather than silently opening an armed node.
if (runNowRequested(args) && args.after) return { ok: false, error: RUN_NOW_AFTER_REFUSAL }
+ if (runNowRequested(args) && args['after-success'] !== undefined) {
+ return { ok: false, error: RUN_NOW_AFTER_SUCCESS_REFUSAL }
+ }
+ // `--after-success` (@shared/station-outcome): the shape was checked in `parseControlRequest`;
+ // re-parsed here with the same grammar. The ids are folded into `after` — a success wait is
+ // `--after` plus the station's report — so the existence, status-reporting and creator checks
+ // below apply to them unchanged; the hold adds the report.
+ const successParsed =
+ args['after-success'] !== undefined ? parseAfterSuccessArg(args['after-success']) : undefined
+ if (successParsed && !successParsed.ok) return { ok: false, error: `${verb}: ${successParsed.error}` }
+ const successIds = successParsed?.ok ? successParsed.ids : []
+ const successDeadline = parseSuccessDeadlineArg(args['success-deadline'])
+ if (!successDeadline.ok) return { ok: false, error: `${verb}: ${successDeadline.error}` }
+ const afterArg = successIds.length
+ ? [
+ ...new Set([
+ ...(args.after ?? '').split(',').map((id) => id.trim()).filter(Boolean),
+ ...successIds
+ ])
+ ].join(',')
+ : args.after
if (!verified) {
return {
ok: false,
@@ -1260,10 +1328,21 @@ export class HeadlessNodeFactory {
}
const target = this.resolveTarget(workspace, source, verb, args, verified)
if ('ok' in target) return target
- const after = this.resolveAfter(target, args.after, verb)
+ const after = this.resolveAfter(target, afterArg, verb)
if (!Array.isArray(after)) return after
const unownedAfter = this.unownedMutation(sourceNodeId, after)
if (unownedAfter) return this.ownershipRefusal(verb, sourceNodeId, unownedAfter)
+ // A success wait is only as good as the station's ability to REPORT: only an agent with canvas
+ // control has `report-outcome`, so waiting on anything else could only end at the deadline.
+ for (const depId of successIds) {
+ const dep = target.nodes.find((candidate) => candidate.id === depId)
+ if (!dep || !sourceCanControl(dep, this.deps.agentIdOf)) {
+ return { ok: false, error: successDepRefusal(verb, depId) }
+ }
+ }
+ const successHold: SuccessWaitHold | undefined = successIds.length
+ ? { deps: successIds, deadlineAt: this.now() + successDeadline.ms }
+ : undefined
// `--issue`: resolved against the project the node OPENS IN, before anything is written. The
// shape gate already ran in `parseControlRequest`; this re-parses with the same grammar.
let issueRef: IssueRef | undefined
@@ -1318,7 +1397,10 @@ export class HeadlessNodeFactory {
for (const [depId, state] of afterStates) {
if (state === 'working') this.awaitingFirstWorking.delete(depId)
}
- const mustWait = after.some((depId) => afterStates.get(depId) !== 'done')
+ const mustWait =
+ after.some((depId) => afterStates.get(depId) !== 'done') ||
+ (!!successHold &&
+ !successWaitSatisfied(successHold, (d) => this.successFacts(target, d), this.now()))
const awaitWorking = after.filter((depId) =>
afterStates.get(depId) !== 'done' &&
afterStates.get(depId) !== 'working' &&
@@ -1372,7 +1454,8 @@ export class HeadlessNodeFactory {
executor: 'server' as const,
attempted: !mustWait,
...(!mustWait ? { manualOnly: true } : {}),
- ...(awaitWorking.length ? { awaitWorking: [...awaitWorking] } : {})
+ ...(awaitWorking.length ? { awaitWorking: [...awaitWorking] } : {}),
+ ...(successHold ? { afterSuccess: successHold } : {})
}
: undefined
const node: CanvasNodeState = {
@@ -1485,7 +1568,7 @@ export class HeadlessNodeFactory {
.map((node) => ({ id: node.id, reason: reasons[node.id], retained: !!node.pendingLaunch })),
verb
),
- result: { ids, id: ids[0], after, ...launchResult, reasons }
+ result: { ids, id: ids[0], after, ...launchResult, reasons, ...(successHold ? { afterSuccess: successHold.deps } : {}) }
}
}
return {
@@ -1494,8 +1577,16 @@ export class HeadlessNodeFactory {
`opened ${count} ${verb === 'open-agent' ? `${agentId} session` : 'terminal'}(s): ` +
ids.join(', ') +
(queuedIds.length ? `; queued: ${queuedIds.join(', ')}` : '') +
- (deliveredIds.length ? '; launch delivered; agent startup is not confirmed' : ''),
- result: { ids, id: ids[0], after, ...launchResult, ...(issueRef ? { issue: `${issueRef.owner}/${issueRef.repo}#${issueRef.number}` } : {}) }
+ (deliveredIds.length ? '; launch delivered; agent startup is not confirmed' : '') +
+ (successHold ? `; waits for a reported success from: ${successHold.deps.join(', ')}` : ''),
+ result: {
+ ids,
+ id: ids[0],
+ after,
+ ...launchResult,
+ ...(issueRef ? { issue: `${issueRef.owner}/${issueRef.repo}#${issueRef.number}` } : {}),
+ ...(successHold ? { afterSuccess: successHold.deps } : {})
+ }
}
})
}
@@ -1620,6 +1711,18 @@ export class HeadlessNodeFactory {
: this.deps.stateOf(depId) === 'done'
})
if (!ready) continue
+ // `--after-success`: every named station also REPORTED success. The persisted hold is
+ // hand-editable input, so it is re-validated here — a malformed one never fires.
+ const successHold = normalizeSuccessWaitHold(pending.afterSuccess)
+ if (
+ successHold &&
+ !successWaitSatisfied(
+ successHold,
+ (d) => this.successFacts(project, d, observed),
+ this.now()
+ )
+ )
+ continue
// `sessionExists` is a probe, whereas `createHeadless` is attach-or-create. Never call
// the latter from boot/event reconciliation: a dead node stays dormant until its owner
// explicitly opens it or a user views it. A probe failure also stays dormant because an
diff --git a/src/server/index.ts b/src/server/index.ts
index 33fb221fc..75fdd47b1 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -52,6 +52,7 @@ import { hookServer } from '../core/agents/hook-server'
import { serverEditionControlHandler } from './control-unsupported'
import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'
import { registerStationNoticeIpc } from '../core/agents/station-notice'
+import { registerStationOutcomeIpc } from '../core/station-outcome-store'
import { refreshNodeTokens } from '../core/agents/node-token-service'
import { armServerNodeIdentity } from './node-identity-arm'
import { wireServerCodexSharedIdentity } from './codex-shared-identity'
@@ -493,6 +494,9 @@ export async function startServer(
// `list` answers "none" rather than an unknown channel. Only the canvas-control runtime has a
// creator ledger, so only it has stations to report.
registerStationNoticeIpc(platform, () => canvasControl?.stationNotices ?? null)
+ // Station task outcomes: registered for the same reason — a browser tab's `list` gets "none"
+ // rather than an unknown channel when canvas control is off.
+ registerStationOutcomeIpc(platform, () => canvasControl?.stationOutcomes ?? null)
const { contextTail, geminiContextTail, codexContextTail } = wireAgentStatus(platform, {
onEvent: (event) => canvasControl?.onAgentEvent(event)
})
diff --git a/src/shared/control-off-screen.ts b/src/shared/control-off-screen.ts
index 6e1392a7a..6670d7692 100644
--- a/src/shared/control-off-screen.ts
+++ b/src/shared/control-off-screen.ts
@@ -88,7 +88,10 @@ const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set([
// Talks to GitHub on behalf of the caller's OWN project. No node at either end and no dialog, so
// travelling the user's view would be pure interruption — and the point of the verb is that it
// works while nobody is watching.
- 'report-issue'
+ 'report-issue',
+ // A station's report about ITSELF, recorded in core by the shell's control handler and never
+ // forwarded to a canvas — and the station reporting is, by definition, often not on screen.
+ 'report-outcome'
])
/**
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 9c65d8fde..4e7dfce9f 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -54,7 +54,10 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
// cannot quietly open it.
IPC.agentBoardCommentDeliver,
IPC.stationNoticeDropped,
- IPC.stationNoticeList
+ IPC.stationNoticeList,
+ // Unscoped: every project's station outcomes and their notes. A relay guest bound to one project
+ // must not read another's, and a relay tab's launch loop is refused anyway (its stub is inert).
+ IPC.stationOutcomeList
])
/** What a refused peer is told. One wording, so the two shells answer identically. */
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index c550fb47d..aefc0de6d 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -243,6 +243,11 @@ export const IPC = {
stationNoticeDropped: 'station-notice:dropped',
/** core → every renderer: the FULL current notice list on each change, never a delta. */
stationNoticeChanged: 'station-notice:changed',
+ /** Station task outcomes (`report-outcome`, src/core/station-outcome-store.ts). invoke: every
+ * record this process holds (StationOutcomeRecord[]), for a renderer that booted after a push. */
+ stationOutcomeList: 'station-outcome:list',
+ /** core → every renderer: the FULL current record list on each change, never a delta. */
+ stationOutcomeChanged: 'station-outcome:changed',
/** Canvas sync: a client casts its local node mutations here; the core reflector
* (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the
* SAME channel to EVERY attached client — the sender included, whose copy is its ack (see
diff --git a/src/shared/pending-launch-shape.test.ts b/src/shared/pending-launch-shape.test.ts
index 7412c318b..b9c66a45d 100644
--- a/src/shared/pending-launch-shape.test.ts
+++ b/src/shared/pending-launch-shape.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { normalizePendingLaunch } from './pending-launch-shape'
import { INVALID_PR_WAIT_HOLD } from './pr-wait'
+import { INVALID_SUCCESS_WAIT_HOLD } from './station-outcome'
describe('normalizePendingLaunch — the held launch as a hostile project file carries it', () => {
it('absent, null and non-objects are no hold', () => {
@@ -37,6 +38,15 @@ describe('normalizePendingLaunch — the held launch as a hostile project file c
expect(out).toMatchObject({ after: ['a'], manualOnly: true })
})
+ it('a success wait round-trips, and a malformed one stays a hold that never fires by itself', () => {
+ const hold = { after: ['a'], command: 'x', afterSuccess: { deps: ['a'], deadlineAt: 9 } }
+ expect(normalizePendingLaunch(hold)).toEqual(hold)
+ const out = normalizePendingLaunch({ after: ['a'], command: 'x', afterSuccess: { deps: ['a'] } })
+ expect(out?.afterSuccess).toEqual(INVALID_SUCCESS_WAIT_HOLD)
+ // Absent stays absent: a node that never asked for a success wait gets none.
+ expect(normalizePendingLaunch({ after: [], command: 'x' })).not.toHaveProperty('afterSuccess')
+ })
+
it('a malformed PR wait stays a hold that never fires by itself', () => {
const out = normalizePendingLaunch({ after: [], command: 'x', afterPr: { repository: 5 } })
expect(out?.afterPr).toEqual(INVALID_PR_WAIT_HOLD)
diff --git a/src/shared/pending-launch-shape.ts b/src/shared/pending-launch-shape.ts
index 6717ef011..4774689a4 100644
--- a/src/shared/pending-launch-shape.ts
+++ b/src/shared/pending-launch-shape.ts
@@ -13,6 +13,7 @@
import type { PendingLaunch } from './types'
import { normalizePrWaitHold } from './pr-wait'
+import { normalizeSuccessWaitHold } from './station-outcome'
const KNOWN = new Set([
'after',
@@ -23,6 +24,7 @@ const KNOWN = new Set([
'awaitWorking',
'awaitSetupGroup',
'afterPr',
+ 'afterSuccess',
'promptFile'
])
@@ -61,6 +63,8 @@ export function normalizePendingLaunch(value: unknown): PendingLaunch | undefine
}
const afterPr = normalizePrWaitHold(v.afterPr)
if (afterPr) out.afterPr = afterPr
+ const afterSuccess = normalizeSuccessWaitHold(v.afterSuccess)
+ if (afterSuccess) out.afterSuccess = afterSuccess
if (manual) out.manualOnly = true
return out as unknown as PendingLaunch
}
diff --git a/src/shared/pr-wait.ts b/src/shared/pr-wait.ts
index 3a1c0775a..e7e27eca8 100644
--- a/src/shared/pr-wait.ts
+++ b/src/shared/pr-wait.ts
@@ -136,10 +136,15 @@ export function parseAfterPrArg(
const DURATION = /^([1-9][0-9]{0,4})([mhd])$/
const UNIT_MS: Record<string, number> = { m: 60_000, h: 3_600_000, d: 86_400_000 }
-/** `--pr-deadline <duration>` (`90m`, `12h`, `3d`), 1 minute to 14 days; absent = 24 h. Refused, not
- * clamped: a caller who asked for a month would otherwise be told nothing about getting two weeks. */
-export function parsePrDeadlineArg(
- raw: string | undefined
+/**
+ * A wait's deadline flag (`90m`, `12h`, `3d`), 1 minute to 14 days; absent = 24 h. Refused, not
+ * clamped: a caller who asked for a month would otherwise be told nothing about getting two weeks.
+ * ONE grammar for every held-launch deadline (`--pr-deadline`, `--success-deadline`), so the two
+ * flags cannot come to accept different spellings or bounds.
+ */
+export function parseWaitDeadlineArg(
+ raw: string | undefined,
+ flag: string
): { ok: true; ms: number } | { ok: false; error: string } {
if (raw === undefined) return { ok: true, ms: PR_DEADLINE_DEFAULT_MS }
const m = DURATION.exec(raw)
@@ -147,12 +152,19 @@ export function parsePrDeadlineArg(
if (!m || ms < PR_DEADLINE_MIN_MS || ms > PR_DEADLINE_MAX_MS) {
return {
ok: false,
- error: `--pr-deadline must be a duration like 90m, 12h or 3d, between 1m and 14d (got ${JSON.stringify(raw).slice(0, 40)})`
+ error: `${flag} must be a duration like 90m, 12h or 3d, between 1m and 14d (got ${JSON.stringify(raw).slice(0, 40)})`
}
}
return { ok: true, ms }
}
+/** `--pr-deadline <duration>`: see `parseWaitDeadlineArg`. */
+export function parsePrDeadlineArg(
+ raw: string | undefined
+): { ok: true; ms: number } | { ok: false; error: string } {
+ return parseWaitDeadlineArg(raw, '--pr-deadline')
+}
+
const OPEN_VERBS: ReadonlySet<string> = new Set(['open-terminal', 'open-claude', 'open-agent'])
/**
diff --git a/src/shared/station-outcome.test.ts b/src/shared/station-outcome.test.ts
new file mode 100644
index 000000000..d7d268eec
--- /dev/null
+++ b/src/shared/station-outcome.test.ts
@@ -0,0 +1,265 @@
+import { describe, it, expect } from 'vitest'
+import {
+ INVALID_SUCCESS_WAIT_HOLD,
+ OUTCOME_NOTE_MAX,
+ RUN_NOW_AFTER_SUCCESS_REFUSAL,
+ SUCCESS_WAIT_MAX,
+ afterSuccessFlagRefusal,
+ evaluateSuccessDep,
+ normalizeSuccessWaitHold,
+ outcomeOf,
+ parseAfterSuccessArg,
+ parseReportOutcome,
+ parseSuccessDeadlineArg,
+ sanitizeOutcomeNote,
+ sanitizeOutcomeRecords,
+ successWaitSatisfied,
+ successWaitStatus,
+ successWaitSummary,
+ type SuccessDepFacts,
+ type SuccessWaitHold
+} from './station-outcome'
+import { PR_DEADLINE_DEFAULT_MS, PR_DEADLINE_MAX_MS } from './pr-wait'
+
+describe('parseReportOutcome — a station reports only about itself', () => {
+ it('accepts succeeded and failed, with an optional note', () => {
+ expect(parseReportOutcome({ outcome: 'succeeded' }, 'n1')).toEqual({ ok: true, outcome: 'succeeded' })
+ expect(parseReportOutcome({ outcome: 'failed', note: 'tests red' }, 'n1')).toEqual({
+ ok: true,
+ outcome: 'failed',
+ note: 'tests red'
+ })
+ })
+
+ it('refuses a --node naming ANOTHER node, rather than ignoring it', () => {
+ const r = parseReportOutcome({ outcome: 'succeeded', node: 'n2' }, 'n1')
+ expect(r.ok).toBe(false)
+ expect(!r.ok && r.error).toMatch(/^report-outcome-not-self:/)
+ })
+
+ it('accepts --node when it names the caller itself', () => {
+ expect(parseReportOutcome({ outcome: 'failed', node: 'n1' }, 'n1')).toEqual({ ok: true, outcome: 'failed' })
+ })
+
+ it.each([undefined, '', 'ok', 'success', 'SUCCEEDED', 'done', 'constructor'])(
+ 'refuses outcome %j',
+ (outcome) => {
+ const r = parseReportOutcome({ outcome }, 'n1')
+ expect(r.ok).toBe(false)
+ expect(!r.ok && r.error).toContain('--outcome succeeded|failed')
+ }
+ )
+})
+
+describe('sanitizeOutcomeNote — display text, one line, capped', () => {
+ it('collapses every control character and line break to one space', () => {
+ expect(sanitizeOutcomeNote('tests\npass\r\n\tnow')).toBe('tests pass now')
+ expect(sanitizeOutcomeNote('a\u001b[31mred\u0000b')).toBe('a [31mred b')
+ })
+
+ it('removes bidi overrides and zero-width characters, which would make a note read backwards', () => {
+ expect(sanitizeOutcomeNote('ok‮gnp.exe​')).toBe('okgnp.exe')
+ })
+
+ it('caps at the limit in code points, never splitting a surrogate pair', () => {
+ const long = '😀'.repeat(OUTCOME_NOTE_MAX + 5)
+ const out = sanitizeOutcomeNote(long) as string
+ expect(Array.from(out)).toHaveLength(OUTCOME_NOTE_MAX)
+ expect(out.endsWith('…')).toBe(true)
+ expect(out).not.toMatch(/[\ud800-\udbff](?![\udc00-\udfff])/)
+ })
+
+ it('an empty or non-string note is no note', () => {
+ expect(sanitizeOutcomeNote(' \n\t ')).toBeUndefined()
+ expect(sanitizeOutcomeNote(42)).toBeUndefined()
+ expect(sanitizeOutcomeNote(undefined)).toBeUndefined()
+ })
+})
+
+describe('sanitizeOutcomeRecords — the IPC/bridge boundary', () => {
+ it('keeps well-formed records and drops everything else', () => {
+ const out = sanitizeOutcomeRecords([
+ { nodeId: 'a1', outcome: 'succeeded', at: 1 },
+ { nodeId: 'a2', outcome: 'failed', at: 2, note: 'x\ny' },
+ { nodeId: 'bad id', outcome: 'succeeded', at: 3 },
+ { nodeId: 'a3', outcome: 'maybe', at: 3 },
+ { nodeId: 'a4', outcome: 'failed', at: 'now' },
+ null,
+ 'a5'
+ ])
+ expect(out).toEqual([
+ { nodeId: 'a1', outcome: 'succeeded', at: 1 },
+ { nodeId: 'a2', outcome: 'failed', at: 2, note: 'x y' }
+ ])
+ expect(sanitizeOutcomeRecords({ nodeId: 'a1' })).toEqual([])
+ })
+})
+
+describe('outcomeOf — own properties only', () => {
+ it('never answers with something inherited', () => {
+ expect(outcomeOf({}, 'constructor')).toBeUndefined()
+ expect(outcomeOf({}, '__proto__')).toBeUndefined()
+ const rec = { nodeId: 'a1', outcome: 'succeeded' as const, at: 1 }
+ expect(outcomeOf({ a1: rec }, 'a1')).toBe(rec)
+ })
+})
+
+describe('parseAfterSuccessArg', () => {
+ it('takes plain ids, comma-separated, each once', () => {
+ expect(parseAfterSuccessArg('a1, a2,a1')).toEqual({ ok: true, ids: ['a1', 'a2'] })
+ })
+
+ it.each(['', ' , ', 'a1:ok', 'a b', '../x'])('refuses %j', (raw) => {
+ expect(parseAfterSuccessArg(raw).ok).toBe(false)
+ })
+
+ it('caps the number of stations', () => {
+ const ids = Array.from({ length: SUCCESS_WAIT_MAX + 1 }, (_, i) => `n${i}`).join(',')
+ expect(parseAfterSuccessArg(ids)).toEqual({
+ ok: false,
+ error: `--after-success names at most ${SUCCESS_WAIT_MAX} stations`
+ })
+ })
+})
+
+describe('afterSuccessFlagRefusal — one grammar, the ambiguous forms refused', () => {
+ it('passes a well-formed wait', () => {
+ expect(afterSuccessFlagRefusal('open-claude', { 'after-success': 'a1,a2' })).toBeNull()
+ expect(
+ afterSuccessFlagRefusal('open-agent', { agent: 'codex', 'after-success': 'a1', after: 'b1', 'success-deadline': '6h' })
+ ).toBeNull()
+ expect(afterSuccessFlagRefusal('open-terminal', { cmd: 'make', 'after-success': 'a1' })).toBeNull()
+ expect(afterSuccessFlagRefusal('close', { node: 'x' })).toBeNull()
+ })
+
+ it('refuses a suffix on --after and points at --after-success instead of "no such node"', () => {
+ const r = afterSuccessFlagRefusal('open-claude', { after: 'a1:ok' })
+ expect(r).toContain('--after takes plain node ids')
+ expect(r).toContain('--after-success')
+ })
+
+ it('refuses the same station in both --after and --after-success', () => {
+ expect(afterSuccessFlagRefusal('open-claude', { after: 'a1,b1', 'after-success': 'a1' })).toContain(
+ 'name each station once'
+ )
+ })
+
+ it('refuses it on a verb that has no launch to hold', () => {
+ expect(afterSuccessFlagRefusal('spawn-team', { 'after-success': 'a1' })).toContain(
+ 'applies only to open-terminal / open-claude / open-agent'
+ )
+ expect(afterSuccessFlagRefusal('open-terminal', { 'after-success': 'a1' })).toContain('needs --cmd')
+ })
+
+ it('refuses a deadline with nothing to bound, and a malformed one', () => {
+ expect(afterSuccessFlagRefusal('open-claude', { 'success-deadline': '2h' })).toContain(
+ '--success-deadline applies only with --after-success'
+ )
+ expect(afterSuccessFlagRefusal('open-claude', { 'after-success': 'a1', 'success-deadline': '30d' })).toContain(
+ '--success-deadline must be a duration'
+ )
+ })
+
+ it('refuses --run-now, which contradicts waiting', () => {
+ expect(afterSuccessFlagRefusal('open-claude', { 'after-success': 'a1', 'run-now': '1' })).toBe(
+ RUN_NOW_AFTER_SUCCESS_REFUSAL
+ )
+ })
+})
+
+describe('parseSuccessDeadlineArg — the same bounds as --pr-deadline', () => {
+ it('defaults to 24h and accepts up to 14d', () => {
+ expect(parseSuccessDeadlineArg(undefined)).toEqual({ ok: true, ms: PR_DEADLINE_DEFAULT_MS })
+ expect(parseSuccessDeadlineArg('14d')).toEqual({ ok: true, ms: PR_DEADLINE_MAX_MS })
+ expect(parseSuccessDeadlineArg('15d').ok).toBe(false)
+ })
+})
+
+describe('normalizeSuccessWaitHold — the persisted shape is hostile input', () => {
+ it('keeps a valid hold, drops an absent one', () => {
+ expect(normalizeSuccessWaitHold({ deps: ['a1', 'a2'], deadlineAt: 5 })).toEqual({ deps: ['a1', 'a2'], deadlineAt: 5 })
+ expect(normalizeSuccessWaitHold(undefined)).toBeUndefined()
+ expect(normalizeSuccessWaitHold(null)).toBeUndefined()
+ })
+
+ it.each([
+ ['a string', 'a1'],
+ ['an array', ['a1']],
+ ['deps not a list', { deps: 'a1', deadlineAt: 5 }],
+ ['empty deps', { deps: [], deadlineAt: 5 }],
+ ['a non-string dep', { deps: ['a1', 7], deadlineAt: 5 }],
+ ['an unsafe dep', { deps: ['a1; rm -rf ~'], deadlineAt: 5 }],
+ ['a duplicate dep', { deps: ['a1', 'a1'], deadlineAt: 5 }],
+ ['too many deps', { deps: Array.from({ length: SUCCESS_WAIT_MAX + 1 }, (_, i) => `n${i}`), deadlineAt: 5 }],
+ ['no deadline', { deps: ['a1'] }],
+ ['a string deadline', { deps: ['a1'], deadlineAt: '5' }],
+ ['a non-finite deadline', { deps: ['a1'], deadlineAt: Infinity }],
+ ['an invalid marker', { deps: ['a1'], deadlineAt: 5, invalid: false }]
+ ])('%s becomes the INVALID hold — present, never satisfied, never dropped', (_label, raw) => {
+ expect(normalizeSuccessWaitHold(raw)).toBe(INVALID_SUCCESS_WAIT_HOLD)
+ })
+
+ it('an invalid hold is never satisfied and reads as expired', () => {
+ const met = (): SuccessDepFacts => ({ exists: true, turnDone: true, outcome: { outcome: 'succeeded' } })
+ expect(successWaitSatisfied(INVALID_SUCCESS_WAIT_HOLD, met, 0)).toBe(false)
+ expect(successWaitStatus(INVALID_SUCCESS_WAIT_HOLD, met, 0)).toBe('expired')
+ })
+})
+
+describe('evaluateSuccessDep — the whole matrix', () => {
+ const at = (facts: SuccessDepFacts) => evaluateSuccessDep('a1', facts).state
+
+ it('a reported success, turn over: met', () => {
+ expect(at({ exists: true, turnDone: true, outcome: { outcome: 'succeeded' } })).toBe('met')
+ })
+
+ it('a reported success mid-turn: waiting for the turn to end', () => {
+ expect(at({ exists: true, turnDone: false, outcome: { outcome: 'succeeded' } })).toBe('waiting')
+ })
+
+ it('a reported failure BLOCKS, whatever the turn state', () => {
+ expect(at({ exists: true, turnDone: true, outcome: { outcome: 'failed' } })).toBe('blocked')
+ expect(at({ exists: true, turnDone: false, outcome: { outcome: 'failed' } })).toBe('blocked')
+ expect(evaluateSuccessDep('a1', { exists: true, turnDone: true, outcome: { outcome: 'failed', note: 'red' } }).detail)
+ .toBe('reported failure: "red"')
+ })
+
+ it('no report yet: waiting, even when the turn is over — a turn ending is not a success', () => {
+ expect(at({ exists: true, turnDone: true })).toBe('waiting')
+ expect(at({ exists: true, turnDone: false })).toBe('waiting')
+ })
+
+ it('a CLOSED station counts only with a success reported before it went', () => {
+ expect(at({ exists: false, turnDone: false, outcome: { outcome: 'succeeded' } })).toBe('met')
+ expect(at({ exists: false, turnDone: false })).toBe('blocked')
+ expect(at({ exists: false, turnDone: false, outcome: { outcome: 'failed' } })).toBe('blocked')
+ })
+})
+
+describe('successWaitSatisfied / successWaitStatus', () => {
+ const hold: SuccessWaitHold = { deps: ['a1', 'a2'], deadlineAt: 1_000 }
+ const facts = (m: Record<string, SuccessDepFacts>) => (id: string) => m[id]
+ const ok: SuccessDepFacts = { exists: true, turnDone: true, outcome: { outcome: 'succeeded' } }
+
+ it('needs EVERY station met', () => {
+ expect(successWaitSatisfied(hold, facts({ a1: ok, a2: ok }), 500)).toBe(true)
+ expect(successWaitSatisfied(hold, facts({ a1: ok, a2: { exists: true, turnDone: true } }), 500)).toBe(false)
+ expect(successWaitStatus(hold, facts({ a1: ok, a2: { exists: true, turnDone: true } }), 500)).toBe('waiting')
+ })
+
+ it('a failure anywhere blocks, and says so ahead of "waiting"', () => {
+ const f = facts({ a1: { exists: true, turnDone: false }, a2: { exists: true, turnDone: true, outcome: { outcome: 'failed' } } })
+ expect(successWaitSatisfied(hold, f, 500)).toBe(false)
+ expect(successWaitStatus(hold, f, 500)).toBe('blocked')
+ })
+
+ it('past the deadline nothing is satisfied, and expiry is what the status says', () => {
+ expect(successWaitSatisfied(hold, facts({ a1: ok, a2: ok }), 1_000)).toBe(false)
+ expect(successWaitStatus(hold, facts({ a1: ok, a2: ok }), 1_000)).toBe('expired')
+ })
+
+ it('the summary names only the unmet stations, by the reader-facing name', () => {
+ const f = facts({ a1: ok, a2: { exists: true, turnDone: true, outcome: { outcome: 'failed', note: 'no tests' } } })
+ expect(successWaitSummary(hold, f, (id) => `"${id.toUpperCase()}"`)).toBe('"A2" (reported failure: "no tests")')
+ })
+})
diff --git a/src/shared/station-outcome.ts b/src/shared/station-outcome.ts
new file mode 100644
index 000000000..5941860f2
--- /dev/null
+++ b/src/shared/station-outcome.ts
@@ -0,0 +1,378 @@
+// A station's TASK outcome, as the station itself reports it — and the wait that holds a dependent
+// until that outcome is a success (`--after-success`).
+//
+// WHY THIS EXISTS. `--after <ids>` releases a node when every station it waits on ends a TURN
+// (`done`). A turn ending is not the work succeeding: a station can finish its turn having given
+// up, having answered its own question, or having produced something broken. #521 already keeps an
+// ERRORED turn (an API/model failure) from releasing dependents, but an ordinary turn that failed
+// at the TASK is indistinguishable from one that succeeded — only the station knows. So the station
+// says so (`report-outcome --outcome succeeded|failed`), and a dependent opened with
+// `--after-success <ids>` waits for that word.
+//
+// This module owns everything the three places that need it must agree on — desktop main's shape
+// gate, the Server Edition's parser and headless factory, the renderer's control dispatch and
+// launch loop, and the load seam that sanitizes a hand-editable project file:
+// - the `report-outcome` grammar and the note's display rule,
+// - the `--after-success` / `--success-deadline` grammar and the refusals of the mixed forms,
+// - the persisted SHAPE of the hold (`pendingLaunch.afterSuccess`), validated at both seams,
+// - and the pure EVALUATION of a hold against observed facts, so the renderer's launch loop and
+// the Server Edition's `refreshArmed` cannot come to disagree about when a dependent starts.
+//
+// WHERE THE OUTCOME LIVES is deliberately not here: a core store per process
+// (`core/station-outcome-store.ts`), transient like the agent state it sits beside. It is never
+// read from a project file — `.nodeterm/project.json` is git-shared, and a success claimed in a
+// file anyone can commit would release every dependent waiting on it.
+
+import { oneLine } from './one-line'
+import { parseWaitDeadlineArg } from './pr-wait'
+import { runNowRequested } from './control-verbs'
+import { isSafeNodeId } from './safe-id'
+
+export type StationOutcome = 'succeeded' | 'failed'
+
+const OUTCOMES: ReadonlySet<string> = new Set<StationOutcome>(['succeeded', 'failed'])
+
+export function isStationOutcome(value: unknown): value is StationOutcome {
+ return typeof value === 'string' && OUTCOMES.has(value)
+}
+
+/** One station's latest report. `at` is the recording process's clock. */
+export interface StationOutcomeRecord {
+ nodeId: string
+ outcome: StationOutcome
+ /** Display text only: one line, capped, controls stripped (`sanitizeOutcomeNote`). Never typed
+ * into a pane, never read as a gate. */
+ note?: string
+ at: number
+}
+
+/** The verb a station runs about ITSELF. Named apart from `report-issue` on purpose: "report" alone
+ * sits one flag away from filing a public GitHub issue. */
+export const REPORT_OUTCOME_VERB = 'report-outcome'
+
+/** The verified-only refusal (hook-server's `verifiedRefusalFor`): one sentence, no diagnosis —
+ * an outcome nobody can attribute to the station it names is not evidence. */
+export const REPORT_OUTCOME_CONTROL_REFUSAL = 'Outcome report refused.'
+
+/** Longest note kept, in code points. Long enough for "tests pass, PR #12 opened"; short enough
+ * that `list` stays one readable line per node. */
+export const OUTCOME_NOTE_MAX = 200
+
+// Unicode FORMAT characters (bidi overrides and isolates, zero-width joiners and spaces, the BOM):
+// invisible, and the bidi ones can make a note read backwards in a tooltip or a terminal. `oneLine`
+// already removes every control character and line separator.
+const FORMAT_CHARS = /\p{Cf}+/gu
+
+/**
+ * The note as it may be shown: one line, no control or format characters, capped, or `undefined`
+ * when nothing visible is left. It reaches `list` output (read by agents), the QUEUED tooltip and the
+ * board log — never a pane — so this is a display rule, not an injection defence; `oneLine` is the
+ * rule every other one-line value in the app follows.
+ */
+export function sanitizeOutcomeNote(raw: unknown): string | undefined {
+ if (typeof raw !== 'string') return undefined
+ const flat = oneLine(raw.replace(FORMAT_CHARS, ''))
+ if (!flat) return undefined
+ const points = Array.from(flat)
+ return points.length > OUTCOME_NOTE_MAX ? `${points.slice(0, OUTCOME_NOTE_MAX - 1).join('')}…` : flat
+}
+
+/**
+ * `report-outcome --outcome succeeded|failed [--note <text>] [--node <your own id>]`.
+ *
+ * A node reports only about ITSELF: the caller is the verified node the request came from, and a
+ * `--node` naming anyone else is refused rather than ignored — an agent that tried to report for a
+ * station it opened must learn that it cannot, not believe that it did.
+ */
+export function parseReportOutcome(
+ args: Record<string, string | undefined>,
+ callerNodeId: string
+): { ok: true; outcome: StationOutcome; note?: string } | { ok: false; error: string } {
+ if (args.node !== undefined && args.node !== callerNodeId) {
+ return {
+ ok: false,
+ error:
+ 'report-outcome-not-self: a node reports only its OWN task outcome — drop --node, or pass ' +
+ 'your own node id. To learn how another station did, read `list`.'
+ }
+ }
+ const outcome = args.outcome
+ if (!isStationOutcome(outcome)) {
+ return {
+ ok: false,
+ error: `report-outcome requires --outcome succeeded|failed (got ${JSON.stringify(String(outcome ?? '')).slice(0, 40)})`
+ }
+ }
+ const note = sanitizeOutcomeNote(args.note)
+ return { ok: true, outcome, ...(note ? { note } : {}) }
+}
+
+/** One station's record out of a by-id map, read as an OWN property only — `__proto__` and
+ * `constructor` pass the node-id charset, and must never resolve to something inherited. */
+export function outcomeOf(
+ byId: Readonly<Record<string, StationOutcomeRecord>>,
+ nodeId: string
+): StationOutcomeRecord | undefined {
+ return Object.prototype.hasOwnProperty.call(byId, nodeId) ? byId[nodeId] : undefined
+}
+
+/** A list of records from IPC or the browser bridge, re-checked field by field. */
+export function sanitizeOutcomeRecords(raw: unknown): StationOutcomeRecord[] {
+ if (!Array.isArray(raw)) return []
+ const out: StationOutcomeRecord[] = []
+ for (const e of raw as unknown[]) {
+ if (!e || typeof e !== 'object') continue
+ const r = e as Record<string, unknown>
+ if (typeof r.nodeId !== 'string' || !isSafeNodeId(r.nodeId)) continue
+ if (!isStationOutcome(r.outcome)) continue
+ if (typeof r.at !== 'number' || !Number.isFinite(r.at)) continue
+ const note = sanitizeOutcomeNote(r.note)
+ out.push({ nodeId: r.nodeId, outcome: r.outcome, at: r.at, ...(note ? { note } : {}) })
+ }
+ return out
+}
+
+// ── The wait (`--after-success`) ────────────────────────────────────────────────────────────
+
+/**
+ * What an armed node persists in `pendingLaunch.afterSuccess`. Every id in `deps` is ALSO in
+ * `pendingLaunch.after`: a success wait is `--after` (the station's turn is over and did not error)
+ * PLUS the station's reported success. Keeping the ids in `after` is what lets the dependency rope,
+ * its dashed "waiting" look, the rope-delete escape and every `--after` rule apply unchanged — and
+ * it is the downgrade story: a build that does not know this field still waits for the turn.
+ */
+export interface SuccessWaitHold {
+ deps: string[]
+ /** Epoch ms. Past it the node never starts on its own (▶ and `run` still start it). */
+ deadlineAt: number
+ /** A hold read from a project file that did not survive validation. Never satisfied. */
+ invalid?: true
+}
+
+/** How many stations one open may wait on for success. */
+export const SUCCESS_WAIT_MAX = 16
+
+/** The shape a malformed persisted hold becomes: present (the node stays held), never satisfied,
+ * already past its deadline so the node reads EXPIRED and offers ▶. */
+export const INVALID_SUCCESS_WAIT_HOLD: SuccessWaitHold = Object.freeze({
+ deps: [],
+ deadlineAt: 0,
+ invalid: true
+}) as SuccessWaitHold
+
+/** "Start now" and "start once they succeed" contradict each other, exactly like `--after`. */
+export const RUN_NOW_AFTER_SUCCESS_REFUSAL =
+ 'run-now-after-success-unsupported: --run-now cannot be combined with --after-success'
+
+const OPEN_VERBS: ReadonlySet<string> = new Set(['open-terminal', 'open-claude', 'open-agent'])
+
+function splitIds(raw: string): string[] {
+ return raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+}
+
+/** `--after-success <id,id>`: plain node ids, each named once. Nothing is repaired. */
+export function parseAfterSuccessArg(raw: unknown): { ok: true; ids: string[] } | { ok: false; error: string } {
+ if (typeof raw !== 'string') return { ok: false, error: '--after-success requires <id,id>' }
+ const ids = splitIds(raw)
+ if (ids.length === 0) return { ok: false, error: '--after-success requires <id,id>' }
+ for (const id of ids) {
+ if (!isSafeNodeId(id)) {
+ return {
+ ok: false,
+ error: `--after-success takes plain node ids, comma-separated (got ${JSON.stringify(id).slice(0, 60)})`
+ }
+ }
+ }
+ const unique = [...new Set(ids)]
+ if (unique.length > SUCCESS_WAIT_MAX) {
+ return { ok: false, error: `--after-success names at most ${SUCCESS_WAIT_MAX} stations` }
+ }
+ return { ok: true, ids: unique }
+}
+
+/**
+ * The `--after-success` / `--success-deadline` SHAPE gate, and the one refusal of the ambiguous
+ * form. Desktop main runs it before forwarding (it does not run `parseControlRequest`), the Server
+ * Edition inside `parseControlRequest`. Whether a named station exists and can report is each
+ * shell's own question, answered against the project the node opens in.
+ *
+ * ONE grammar, and the other one is refused by name: a suffix on `--after` (`--after a1:ok`,
+ * `--after a1:success`) reads like it might mean a success wait, and silently treating it as an
+ * unknown node id would tell the caller "no such node" about a node it can see. Node ids never
+ * contain `:`, so any `:` in `--after` is this mistake.
+ */
+export function afterSuccessFlagRefusal(verb: string, args: Record<string, string | undefined>): string | null {
+ const after = args.after
+ if (typeof after === 'string' && after.includes(':')) {
+ return (
+ `${verb}: --after takes plain node ids (got ${JSON.stringify(after).slice(0, 60)}). ` +
+ 'To wait for a station to REPORT SUCCESS, use --after-success <id,id>.'
+ )
+ }
+ if (args['after-success'] === undefined) {
+ return args['success-deadline'] === undefined
+ ? null
+ : `${verb}: --success-deadline applies only with --after-success`
+ }
+ if (!OPEN_VERBS.has(verb)) {
+ return `${verb}: --after-success applies only to open-terminal / open-claude / open-agent`
+ }
+ if (verb === 'open-terminal' && !args.cmd) {
+ return 'open-terminal: --after-success needs --cmd (a terminal with no command has nothing to hold)'
+ }
+ const parsed = parseAfterSuccessArg(args['after-success'])
+ if (!parsed.ok) return `${verb}: ${parsed.error}`
+ const plain = new Set(typeof after === 'string' ? splitIds(after) : [])
+ const both = parsed.ids.filter((id) => plain.has(id))
+ if (both.length) {
+ return (
+ `${verb}: name each station once — ${both.join(', ')} is in both --after and --after-success. ` +
+ '--after-success already waits for its turn to end; drop it from --after.'
+ )
+ }
+ const deadline = parseSuccessDeadlineArg(args['success-deadline'])
+ if (!deadline.ok) return `${verb}: ${deadline.error}`
+ if (runNowRequested(args)) return RUN_NOW_AFTER_SUCCESS_REFUSAL
+ return null
+}
+
+/** `--success-deadline <90m|12h|3d>`: the same bounds and grammar as `--pr-deadline`. */
+export function parseSuccessDeadlineArg(
+ raw: string | undefined
+): { ok: true; ms: number } | { ok: false; error: string } {
+ return parseWaitDeadlineArg(raw, '--success-deadline')
+}
+
+/** The refusal for a `--after-success` station that could never report: only an agent session that
+ * runs canvas control has `report-outcome`, so waiting on anything else would hold until the
+ * deadline. Shared so both shells refuse in one sentence. */
+export function successDepRefusal(verb: string, depId: string): string {
+ return (
+ `${verb}: --after-success ${depId} cannot report an outcome — only an agent session with canvas ` +
+ 'control runs report-outcome. Use --after to wait for its turn to end instead.'
+ )
+}
+
+/**
+ * The persisted hold, validated at both serializer seams. Absent stays absent. Anything present but
+ * malformed becomes `INVALID_SUCCESS_WAIT_HOLD`, never `undefined`: dropping it would let the node
+ * start on its turn-end deps alone — early, the unsafe direction.
+ */
+export function normalizeSuccessWaitHold(value: unknown): SuccessWaitHold | undefined {
+ if (value === undefined || value === null) return undefined
+ if (typeof value !== 'object' || Array.isArray(value)) return INVALID_SUCCESS_WAIT_HOLD
+ const v = value as Record<string, unknown>
+ if (v.invalid !== undefined) return INVALID_SUCCESS_WAIT_HOLD
+ if (!Array.isArray(v.deps) || v.deps.length === 0 || v.deps.length > SUCCESS_WAIT_MAX) {
+ return INVALID_SUCCESS_WAIT_HOLD
+ }
+ const deps: string[] = []
+ for (const d of v.deps as unknown[]) {
+ if (typeof d !== 'string' || !isSafeNodeId(d) || deps.includes(d)) return INVALID_SUCCESS_WAIT_HOLD
+ deps.push(d)
+ }
+ if (typeof v.deadlineAt !== 'number' || !Number.isFinite(v.deadlineAt)) return INVALID_SUCCESS_WAIT_HOLD
+ return { deps, deadlineAt: v.deadlineAt }
+}
+
+/** An invalid hold (read from a corrupt or hostile file) is already past its deadline. */
+export function successWaitExpired(hold: SuccessWaitHold, now: number): boolean {
+ return !!hold.invalid || now >= hold.deadlineAt
+}
+
+// ── Evaluation ──────────────────────────────────────────────────────────────────────────────
+
+/** What the caller observed about ONE station a hold waits on. */
+export interface SuccessDepFacts {
+ /** The station is still on the canvas. */
+ exists: boolean
+ /** Its last turn is over and did not end on an error — `--after`'s own rule, whatever the shell
+ * counts as that (`depSatisfied` on the desktop, `stateOf === 'done'` on the Server Edition). */
+ turnDone: boolean
+ /** Its latest report in this app run, if any. */
+ outcome?: Pick<StationOutcomeRecord, 'outcome' | 'note'>
+}
+
+export type SuccessDepState = 'met' | 'waiting' | 'blocked'
+
+export interface SuccessDepReport {
+ id: string
+ state: SuccessDepState
+ /** Short, human: what is true about this station right now. Never a cause nobody observed. */
+ detail: string
+}
+
+/**
+ * One station's verdict.
+ *
+ * - `failed` BLOCKS: the dependent never fires on it, whatever else happens, until the station
+ * reports again (or is handed new work, which withdraws the report) — or the deadline passes and
+ * a human or an agent runs it on purpose.
+ * - `succeeded` is met once the station's turn is over, so a dependent that reads the station's
+ * work (get-linked-context) reads a finished transcript — the same idle edge `--after` uses.
+ * - no report yet: waiting. "No news" is never success; that is the whole point of the wait.
+ * - a DELETED station: met only if it reported success before it went (a closed station can never
+ * report again, and closing one is exactly how an orchestrator abandons a failed attempt — reading
+ * the deletion as success, which is `--after`'s rule, would release dependents on a failure).
+ * Closed without a success report ⇒ blocked, with the deadline and ▶ as the way out.
+ */
+export function evaluateSuccessDep(id: string, facts: SuccessDepFacts): SuccessDepReport {
+ const r = (state: SuccessDepState, detail: string): SuccessDepReport => ({ id, state, detail })
+ const reported = facts.outcome
+ if (reported?.outcome === 'failed') {
+ return r('blocked', `reported failure${reported.note ? `: "${reported.note}"` : ''}`)
+ }
+ if (reported?.outcome === 'succeeded') {
+ if (facts.exists && !facts.turnDone) return r('waiting', 'reported success; waiting for its turn to end')
+ return r('met', 'reported success')
+ }
+ return facts.exists ? r('waiting', 'no outcome reported yet') : r('blocked', 'closed without reporting success')
+}
+
+export function successWaitReports(
+ hold: SuccessWaitHold,
+ factsOf: (id: string) => SuccessDepFacts
+): SuccessDepReport[] {
+ return hold.deps.map((id) => evaluateSuccessDep(id, factsOf(id)))
+}
+
+/** EVERY station met, the hold readable, and the deadline not passed. */
+export function successWaitSatisfied(
+ hold: SuccessWaitHold,
+ factsOf: (id: string) => SuccessDepFacts,
+ now: number
+): boolean {
+ if (successWaitExpired(hold, now) || hold.deps.length === 0) return false
+ return successWaitReports(hold, factsOf).every((d) => d.state === 'met')
+}
+
+/** The one-word state `list`, the badge and the tooltip speak. Expiry first: past the deadline the
+ * node will not start on its own whatever its stations did, and the answer is `run` / ▶. */
+export type SuccessWaitStatus = 'met' | 'waiting' | 'blocked' | 'expired'
+
+export function successWaitStatus(
+ hold: SuccessWaitHold,
+ factsOf: (id: string) => SuccessDepFacts,
+ now: number
+): SuccessWaitStatus {
+ if (successWaitExpired(hold, now)) return 'expired'
+ const reports = successWaitReports(hold, factsOf)
+ if (reports.some((d) => d.state === 'blocked')) return 'blocked'
+ return reports.every((d) => d.state === 'met') ? 'met' : 'waiting'
+}
+
+/** "a1 (reported failure: "tests red"); a2 (no outcome reported yet)" — the unmet stations only.
+ * `name` turns an id into what a reader recognises (a node title), defaulting to the id. */
+export function successWaitSummary(
+ hold: SuccessWaitHold,
+ factsOf: (id: string) => SuccessDepFacts,
+ name: (id: string) => string = (id) => id
+): string {
+ return successWaitReports(hold, factsOf)
+ .filter((d) => d.state !== 'met')
+ .map((d) => `${name(d.id)} (${d.detail})`)
+ .join('; ')
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f8dfbdb9d..c4351d806 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -440,6 +440,14 @@ export interface PendingLaunch {
* A build older than this one does not know the field and releases the node on `after` alone.
*/
afterPr?: PrWaitHold
+ /**
+ * Also wait for these stations to REPORT SUCCESS (`--after-success`, see @shared/station-outcome):
+ * each id is in `after` too, so this adds "and it said it succeeded" to "its turn is over". ANDed
+ * with every other gate. Validated at both serializer seams (`normalizePendingLaunch`): a malformed
+ * value becomes a hold that never fires on its own. A build older than this one does not know the
+ * field and releases the node on the turn ending alone.
+ */
+ afterSuccess?: import('./station-outcome').SuccessWaitHold
/**
* The file `command` reads its prompt from (`"$(cat '<path>')"`): a `--prompt-file`, or a long
* `--prompt` spilled to a file (#706). A held launch may be delivered weeks after it was armed, so
@@ -822,6 +830,11 @@ export interface BoardLogEvent {
* `StationFailureReason`, @shared/station-notice), `title` = the station's title as the notice
* carried it (one line, capped). Never any station output. */
| 'station-failed'
+ /** A station reported its TASK outcome (`report-outcome`, @shared/station-outcome). Filed under
+ * the STATION's own card. `from` = the station's node id, `to` = the outcome (`succeeded` /
+ * `failed`), `title` = its note (one line, capped). Written by the app, never a gate: the
+ * outcome a `--after-success` wait reads lives in core's transient store, not in this file. */
+ | 'station-reported'
from?: string
to?: string
/** Column title for column-added/deleted; card title for card-created; outcome for agent-message;
@@ -4109,4 +4122,12 @@ export interface NodeTerminalApi {
onChanged(cb: (views: import('./station-notice').StationNoticeView[]) => void): () => void
reportDropped(nodeId: string, dropped: boolean): void
}
+ /** Station task outcomes (`report-outcome`, src/core/station-outcome-store.ts): what each station
+ * reported about its own task in this app run — what a `--after-success` wait reads. Desktop and
+ * Server Edition are real; a relay tab's stations belong to the host's core, so there it is inert
+ * (and its launch delivery is refused anyway). */
+ stationOutcome: {
+ list(): Promise<import('./station-outcome').StationOutcomeRecord[]>
+ onChanged(cb: (records: import('./station-outcome').StationOutcomeRecord[]) => void): () => void
+ }
}