@aragon-agent/cli 0.6.63 → 0.6.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +44 -20
  3. package/dist/agent/controller.d.ts +66 -14
  4. package/dist/agent/controller.js +291 -81
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +44 -3
  7. package/dist/agent/team-notices.d.ts +57 -7
  8. package/dist/agent/team-notices.js +93 -10
  9. package/dist/app/App.js +199 -77
  10. package/dist/cli.js +4 -1
  11. package/dist/config/cli-commands.d.ts +1 -1
  12. package/dist/config/cli-commands.js +11 -0
  13. package/dist/exec/index.js +2 -0
  14. package/dist/exec/runner.js +10 -1
  15. package/dist/gene/commit-prepare.js +27 -1
  16. package/dist/gene/curator/curator.d.ts +15 -0
  17. package/dist/gene/curator/curator.js +26 -2
  18. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  19. package/dist/gene/curator/scripted-lane.js +101 -0
  20. package/dist/gene/curator/task-context.d.ts +21 -0
  21. package/dist/gene/curator/task-context.js +33 -0
  22. package/dist/gene/curator/task-runner.d.ts +10 -1
  23. package/dist/gene/curator/task-runner.js +39 -4
  24. package/dist/gene/curator/tool-support.js +11 -4
  25. package/dist/gene/curator/toolkit.d.ts +13 -0
  26. package/dist/gene/curator/toolkit.js +23 -1
  27. package/dist/gene/curator/tools-verify.js +2 -2
  28. package/dist/gene/curator/tools-write.js +6 -1
  29. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  30. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  31. package/dist/gene/curator/validate/knowledge.js +74 -11
  32. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  33. package/dist/gene/curator/validate/prompts.js +2 -2
  34. package/dist/gene/learn/draft-guard.d.ts +17 -0
  35. package/dist/gene/learn/draft-guard.js +113 -0
  36. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  37. package/dist/gene/learn/learn-prompt.js +27 -2
  38. package/dist/gene/learn/learner.js +20 -2
  39. package/dist/gene/queue.d.ts +16 -0
  40. package/dist/gene/queue.js +44 -1
  41. package/dist/governance/store/run-store.d.ts +20 -0
  42. package/dist/governance/store/run-store.js +54 -8
  43. package/dist/host/index.d.ts +1 -0
  44. package/dist/host/index.js +1 -0
  45. package/dist/host/interaction.d.ts +8 -17
  46. package/dist/host/interaction.js +50 -72
  47. package/dist/host/team-wake-driver.d.ts +90 -0
  48. package/dist/host/team-wake-driver.js +114 -0
  49. package/dist/logging/install.d.ts +32 -1
  50. package/dist/logging/install.js +15 -0
  51. package/dist/team/console-tools.d.ts +12 -0
  52. package/dist/team/console-tools.js +20 -3
  53. package/dist/team/console-view.js +11 -1
  54. package/dist/team/notices.d.ts +81 -4
  55. package/dist/team/notices.js +187 -22
  56. package/dist/team/prompt.js +1 -1
  57. package/dist/team/runtime.d.ts +67 -24
  58. package/dist/team/runtime.js +250 -31
  59. package/dist/team/stall-watch.d.ts +54 -0
  60. package/dist/team/stall-watch.js +119 -0
  61. package/dist/team/task-tool.js +2 -2
  62. package/dist/team/wake.d.ts +176 -0
  63. package/dist/team/wake.js +444 -0
  64. package/package.json +81 -81
@@ -20,6 +20,14 @@
20
20
  * into the queue. `TeamNoticeQueue.push` is idempotent by id, so a re-queue can
21
21
  * only delay a notice, never duplicate it.
22
22
  *
23
+ * THE RECEIPT IS PER STEER (team-lead-wake-signals I-WK6). Core only echoes a
24
+ * `steering_accepted` for a steer that carried an id (`accept-steering.ts:14`), and
25
+ * the old code steered without one: a notices-only batch never produced a receipt,
26
+ * so the ledger could only be emptied by `requeueUndelivered()` - which re-queued a
27
+ * notice that HAD been delivered, and delivered it again. Now every steer carries a
28
+ * `notice:` id and the ledger is keyed by it, so a receipt releases exactly the
29
+ * notices it carried and nothing else.
30
+ *
23
31
  * WHY NOT ABSTRACTED TOGETHER WITH THE JOB RELAY (spec 5.3.2). The job relay's
24
32
  * channel 1 must never inject while a tool batch is open (its I-5), because a job
25
33
  * notice is a courtesy. A settle report is not a courtesy: the lead was told "you
@@ -27,41 +35,83 @@
27
35
  * One shared class would have to be parameterised into two different policies and
28
36
  * would end up being two classes anyway, one of them hidden.
29
37
  */
30
- import { type TeamNoticeQueue } from '../team/notices.js';
38
+ import { type TeamNotice, type TeamNoticeQueue } from '../team/notices.js';
31
39
  export interface TeamNoticeRelayDeps {
32
40
  queue: TeamNoticeQueue;
33
- /** `enqueueSteering(text, false)` - the receipt-less path. */
34
- steer: (text: string) => void;
41
+ /**
42
+ * `enqueueSteering(text, false, undefined, true)` - the RECEIPT-carrying path for
43
+ * notices. Returns the id Core will echo in `steering_accepted`.
44
+ */
45
+ steer: (text: string) => string;
46
+ /**
47
+ * Take one steer back out of Core's own steering queue (`Agent.removeQueuedSteering`).
48
+ * `true` means it was still waiting there and is now gone.
49
+ *
50
+ * Core's queue SURVIVES a run, and `acceptSteering` returns early on an aborted
51
+ * signal, so a steer can be "sent, not accepted, still queued" when the run ends
52
+ * (RV-P1-1). Re-queueing such a notice without withdrawing it would let the next
53
+ * turn steer a second copy and Core accept both.
54
+ */
55
+ withdraw: (receiptId: string) => boolean;
35
56
  /** `activeToolCalls === 0 && isRunning() && !abortRequested` (push channel). */
36
57
  isAtSafeSteerPoint: () => boolean;
37
58
  /**
38
- * `activeToolCalls === 0 && !abortRequested` - the FILL channel's precondition.
59
+ * The FILL channel's precondition: no tool batch open, and nothing being aborted
60
+ * RIGHT NOW (`activeToolCalls === 0 && (!abortRequested || !isRunning())`).
39
61
  *
40
62
  * NOT `isAtSafeSteerPoint()`, for the reason `job-notices.ts` records at length:
41
63
  * the fill runs immediately before `agent.prompt()`, where `isRunning()` is
42
64
  * FALSE by contract, so the push predicate would make this channel dead.
65
+ *
66
+ * `abortRequested` alone is the wrong half (RV-P1-5): it is set by `stopEngine()`
67
+ * and cleared only at the next `agent_start`, which is AFTER this check. A session
68
+ * whose last turn was interrupted would then refuse the fill for the very next
69
+ * turn - the wake turn included - and the report would miss it.
43
70
  */
44
71
  canSteerBeforeTurn: () => boolean;
45
72
  }
46
73
  export declare class TeamNoticeRelay {
47
74
  private readonly deps;
48
- /** Notices steered but not yet proven delivered, keyed by their queue id. */
75
+ /** Notices steered but not yet proven delivered, keyed by the id their steer carried. */
49
76
  private readonly pendingSteered;
50
77
  constructor(deps: TeamNoticeRelayDeps);
51
78
  /** The push channel: called from the controller's one safe steer point. */
52
79
  tryPush(): boolean;
53
80
  /** The fill channel: just before the next turn starts. */
54
81
  flushForTurn(): boolean;
55
- /** A receipt proves the steering queue was drained, so nothing is stranded. */
56
- onSteeringAccepted(): void;
82
+ /**
83
+ * A receipt proves ONE steer was taken out of Core's queue and into history, so
84
+ * only the notices that steer carried are delivered. Returns their ids.
85
+ */
86
+ onSteeringAccepted(receiptIds: readonly string[]): string[];
57
87
  /**
58
88
  * Put undelivered notices back at `turn_start` and at the end of a run.
59
89
  *
60
90
  * THIS IS WHAT TURNS "swallowed by clearAllQueues()" INTO "delivered one turn
61
91
  * later" - the difference between a report the user gets and a report that
62
92
  * exists only in a file.
93
+ *
94
+ * WITHDRAW FIRST, THEN QUEUE. A receipt-less entry in the ledger is one of two
95
+ * things: Core's queue was wiped (`withdraw` answers false), or Core still holds
96
+ * the steer (`withdraw` answers true and removes it). Either way ours is the only
97
+ * copy afterwards, so queueing it cannot deliver it twice. "Already accepted" is
98
+ * not a third case: that receipt arrives first, synchronously, and the ledger is
99
+ * released before anything here can run.
63
100
  */
64
101
  requeueUndelivered(): void;
102
+ /**
103
+ * Everything the lead has not yet been PROVEN to have: the queue plus the ledger.
104
+ * The wake governor reads this - a notice that was steered but never receipted is
105
+ * still owed.
106
+ */
107
+ undelivered(): TeamNotice[];
108
+ /**
109
+ * Remove one notice from the queue AND the ledger without delivering it (the lead
110
+ * already has it in a tool result - `team_collect`). Returns whether it was held.
111
+ */
112
+ dropById(noticeId: string): boolean;
113
+ /** Forget everything held in the ledger (session reset). Does not touch the queue. */
114
+ reset(): void;
65
115
  /** How many notices are waiting. Used by the tests and the diagnostics path. */
66
116
  pending(): number;
67
117
  private steerQueued;
@@ -20,6 +20,14 @@
20
20
  * into the queue. `TeamNoticeQueue.push` is idempotent by id, so a re-queue can
21
21
  * only delay a notice, never duplicate it.
22
22
  *
23
+ * THE RECEIPT IS PER STEER (team-lead-wake-signals I-WK6). Core only echoes a
24
+ * `steering_accepted` for a steer that carried an id (`accept-steering.ts:14`), and
25
+ * the old code steered without one: a notices-only batch never produced a receipt,
26
+ * so the ledger could only be emptied by `requeueUndelivered()` - which re-queued a
27
+ * notice that HAD been delivered, and delivered it again. Now every steer carries a
28
+ * `notice:` id and the ledger is keyed by it, so a receipt releases exactly the
29
+ * notices it carried and nothing else.
30
+ *
23
31
  * WHY NOT ABSTRACTED TOGETHER WITH THE JOB RELAY (spec 5.3.2). The job relay's
24
32
  * channel 1 must never inject while a tool batch is open (its I-5), because a job
25
33
  * notice is a courtesy. A settle report is not a courtesy: the lead was told "you
@@ -30,7 +38,7 @@
30
38
  import { renderTeamNotices } from '../team/notices.js';
31
39
  export class TeamNoticeRelay {
32
40
  deps;
33
- /** Notices steered but not yet proven delivered, keyed by their queue id. */
41
+ /** Notices steered but not yet proven delivered, keyed by the id their steer carried. */
34
42
  pendingSteered = new Map();
35
43
  constructor(deps) {
36
44
  this.deps = deps;
@@ -47,9 +55,21 @@ export class TeamNoticeRelay {
47
55
  return false;
48
56
  return this.steerQueued();
49
57
  }
50
- /** A receipt proves the steering queue was drained, so nothing is stranded. */
51
- onSteeringAccepted() {
52
- this.pendingSteered.clear();
58
+ /**
59
+ * A receipt proves ONE steer was taken out of Core's queue and into history, so
60
+ * only the notices that steer carried are delivered. Returns their ids.
61
+ */
62
+ onSteeringAccepted(receiptIds) {
63
+ const delivered = [];
64
+ for (const receiptId of receiptIds) {
65
+ const carried = this.pendingSteered.get(receiptId);
66
+ if (carried === undefined)
67
+ continue;
68
+ this.pendingSteered.delete(receiptId);
69
+ for (const notice of carried)
70
+ delivered.push(notice.id);
71
+ }
72
+ return delivered;
53
73
  }
54
74
  /**
55
75
  * Put undelivered notices back at `turn_start` and at the end of a run.
@@ -57,14 +77,69 @@ export class TeamNoticeRelay {
57
77
  * THIS IS WHAT TURNS "swallowed by clearAllQueues()" INTO "delivered one turn
58
78
  * later" - the difference between a report the user gets and a report that
59
79
  * exists only in a file.
80
+ *
81
+ * WITHDRAW FIRST, THEN QUEUE. A receipt-less entry in the ledger is one of two
82
+ * things: Core's queue was wiped (`withdraw` answers false), or Core still holds
83
+ * the steer (`withdraw` answers true and removes it). Either way ours is the only
84
+ * copy afterwards, so queueing it cannot deliver it twice. "Already accepted" is
85
+ * not a third case: that receipt arrives first, synchronously, and the ledger is
86
+ * released before anything here can run.
60
87
  */
61
88
  requeueUndelivered() {
62
89
  if (this.pendingSteered.size === 0)
63
90
  return;
64
- const stranded = [...this.pendingSteered.values()];
91
+ const stranded = [...this.pendingSteered.entries()];
92
+ this.pendingSteered.clear();
93
+ for (const [receiptId, notices] of stranded) {
94
+ try {
95
+ this.deps.withdraw(receiptId);
96
+ }
97
+ catch {
98
+ // A failed withdraw must not cost the notice: the worst case is the old,
99
+ // duplicate-prone behaviour, which is still better than silence.
100
+ }
101
+ for (const notice of notices)
102
+ this.deps.queue.push(notice);
103
+ }
104
+ }
105
+ /**
106
+ * Everything the lead has not yet been PROVEN to have: the queue plus the ledger.
107
+ * The wake governor reads this - a notice that was steered but never receipted is
108
+ * still owed.
109
+ */
110
+ undelivered() {
111
+ const seen = new Set();
112
+ const out = [];
113
+ const all = [...this.deps.queue.peek(), ...[...this.pendingSteered.values()].flat()];
114
+ for (const notice of all) {
115
+ if (seen.has(notice.id))
116
+ continue;
117
+ seen.add(notice.id);
118
+ out.push(notice);
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * Remove one notice from the queue AND the ledger without delivering it (the lead
124
+ * already has it in a tool result - `team_collect`). Returns whether it was held.
125
+ */
126
+ dropById(noticeId) {
127
+ let dropped = this.deps.queue.dropById(noticeId);
128
+ for (const [receiptId, notices] of [...this.pendingSteered]) {
129
+ const kept = notices.filter((notice) => notice.id !== noticeId);
130
+ if (kept.length === notices.length)
131
+ continue;
132
+ dropped = true;
133
+ if (kept.length === 0)
134
+ this.pendingSteered.delete(receiptId);
135
+ else
136
+ this.pendingSteered.set(receiptId, kept);
137
+ }
138
+ return dropped;
139
+ }
140
+ /** Forget everything held in the ledger (session reset). Does not touch the queue. */
141
+ reset() {
65
142
  this.pendingSteered.clear();
66
- for (const notice of stranded)
67
- this.deps.queue.push(notice);
68
143
  }
69
144
  /** How many notices are waiting. Used by the tests and the diagnostics path. */
70
145
  pending() {
@@ -74,9 +149,17 @@ export class TeamNoticeRelay {
74
149
  const notices = this.deps.queue.drain();
75
150
  if (notices.length === 0)
76
151
  return false;
77
- for (const notice of notices)
78
- this.pendingSteered.set(notice.id, notice);
79
- this.deps.steer(renderTeamNotices(notices));
152
+ let receiptId;
153
+ try {
154
+ receiptId = this.deps.steer(renderTeamNotices(notices));
155
+ }
156
+ catch {
157
+ // Nothing was delivered: put them back so the next channel can try.
158
+ for (const notice of notices)
159
+ this.deps.queue.push(notice);
160
+ return false;
161
+ }
162
+ this.pendingSteered.set(receiptId, notices);
80
163
  return true;
81
164
  }
82
165
  }
package/dist/app/App.js CHANGED
@@ -14,7 +14,7 @@ import { Text, useApp, useInput, useStdout } from 'ink';
14
14
  import { advanceInterruptGesture, INTERRUPT_CONFIRM_MS, cancelInterruptConfirmation, } from '@aragon-agent/tui/input/interrupt-gesture';
15
15
  import { initialViewState, viewReducer, } from '@aragon-agent/tui/model/agent/reducer';
16
16
  import { ActionCoalescer, attachAgentChannel, attachCompactionChannel, attachContextUsageChannel, attachFastChannel, attachGovernanceChannel, attachProcChannel, attachTeamChannel, attachTodosChannel, attachToolOutputChannel, attachWaitChannel, makePatchSource, } from '../host/controller-feed.js';
17
- import { parseMaxTokensInput, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
17
+ import { parseMaxTokensInput, toRunResumePolicy, DEFAULT_TRANSCRIPT_RETAIN, DEFAULT_TRANSCRIPT_WINDOW, } from '@aragon-agent/tui/model/config/schema';
18
18
  import { updatePersistedConfig } from '../config/store.js';
19
19
  import { appendPrompt, loadPromptHistory } from '../config/prompt-history.js';
20
20
  import { bumpSubmitCount, getGovernanceIntroSeen, setGovernanceIntroSeen, setMouseNoticeVersion, setPromptKeyNoticeVersion, setScrollModeNoticeVersion, setVtInputNoticeVersion, } from '../config/ui-state.js';
@@ -58,7 +58,7 @@ import { ScrollViewport } from '@aragon-agent/tui/ui/layout/ScrollViewport';
58
58
  import { acceptanceChip, acceptanceRung, buildTodoRailLayout } from '@aragon-agent/tui/ui/layout/todo-layout';
59
59
  import { buildTeamPanelLayout } from '@aragon-agent/tui/ui/layout/team-panel';
60
60
  import { isLiveTeamCard, lastTeamEntry, rosterCounts } from '@aragon-agent/tui/ui/team-status';
61
- import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } from '@aragon-agent/tui/model/todo/follow-through';
61
+ import { advanceBudget, chargeResume, decideFollowThrough, emptyBudget, emptyResumeCounters, isTransientRunEnd, settleResumeCounters, } from '@aragon-agent/tui/model/todo/follow-through';
62
62
  // THE THIRD LAYER OF FORCED TEAM MODE (team-command-forced-dispatch §3.7): the
63
63
  // decision and its two strings live in a pure module, so `App` gains wiring and
64
64
  // no policy. Imported beside the todo decision it shares one timer with.
@@ -70,7 +70,7 @@ import { redTeamToastTtlMs, useRedTeamMode, } from './use-redteam-mode.js';
70
70
  import { RedTeamDisclaimerOverlay } from '@aragon-agent/tui/ui/overlays/RedTeamDisclaimerOverlay';
71
71
  import { teamStatusFromView } from '@aragon-agent/tui/model/team/team-mode';
72
72
  import { FORCED_NUDGE_GRACE_MS } from '@aragon-agent/tui/model/team/limits';
73
- import { planSettleContinuation } from '@aragon-agent/tui/model/team/settle-plan';
73
+ import { TeamWakeDriver } from '../host/team-wake-driver.js';
74
74
  import { formatDuration } from '@aragon-agent/tui/model/agent/usage';
75
75
  import { useTerminalSize } from '@aragon-agent/tui/ui/layout/useTerminalSize';
76
76
  import { useHeightStore } from '@aragon-agent/tui/ui/use-height-store';
@@ -546,7 +546,28 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
546
546
  */
547
547
  const updateToastPushed = useRef(false);
548
548
  const budgetRef = useRef(emptyBudget());
549
+ /**
550
+ * The two counters bounding a re-run of an engine-interrupted run
551
+ * (`team-idle-watchdog-dead-run` F3). A REF OF ITS OWN, NOT A FIELD OF
552
+ * `budgetRef`: that budget belongs to a PLAN LINEAGE and `advanceBudget` zeroes
553
+ * it the moment the plan is gone, whereas a stalled link has nothing to do with
554
+ * any plan - sharing it would hand the user a fresh allowance every time the
555
+ * model finished a todo list.
556
+ *
557
+ * `consecutive` is cleared by any run that ends without an error
558
+ * (`afterAgentEnd`); `total` ONLY by the user typing (`submitMessage`). It is
559
+ * deliberately NOT touched by `agent_start`: a recovery IS a new run, and
560
+ * clearing there would reset both counters on every recovery and make the bound
561
+ * unreachable.
562
+ */
563
+ const resumeRef = useRef(emptyResumeCounters());
549
564
  const followTimer = useRef(null);
565
+ /**
566
+ * The team wake driver (team-lead-wake-signals 4.10), mounted in an effect below. A
567
+ * ref because `cancelFollowThrough` - the one place every "the user did something"
568
+ * path already passes through - has to reach it without being re-created.
569
+ */
570
+ const teamWakeRef = useRef(null);
550
571
  /**
551
572
  * The forced-dispatch gate's three counters (team-command-forced-dispatch
552
573
  * §3.7). REFS, for the reason the follow-through block above records: every
@@ -739,79 +760,116 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
739
760
  *
740
761
  * ONE SLOT: `Esc`, `submitMessage`, the reset/restore port, the effect cleanup
741
762
  * and both follow-through arms (todo, then the gate) all cancel before arming.
763
+ *
764
+ * THE TEAM WAKE COUNTDOWN SITS IN THAT SAME SLOT (team-lead-wake-signals I-WK9), so
765
+ * cancelling it is the same act: the driver is told after the timer is cleared, and
766
+ * it only reacts when it actually holds a countdown (its own submit passes through
767
+ * `submitMessage` -> here and must find nothing to cancel).
742
768
  */
743
769
  const cancelFollowThrough = useCallback(() => {
744
770
  if (followTimer.current) {
745
771
  clearTimeout(followTimer.current);
746
772
  followTimer.current = null;
747
773
  }
774
+ teamWakeRef.current?.cancel();
748
775
  }, []);
749
776
  /**
750
- * Decide what, if anything, the settle of a dispatch earns (5.3.3).
751
- *
752
- * A PURE DECISION IN A PURE FILE (`planSettleContinuation`, in the tui package)
753
- * with an impure caller here: each host owns its timer, the truth table is
754
- * shared. That split is R9's mitigation - the desktop coordinator runs the same
755
- * function against its own timer.
777
+ * Re-run a run the ENGINE interrupted, after `graceMs`
778
+ * (`team-idle-watchdog-dead-run` F3). `decideFollowThrough` decided WHETHER; this
779
+ * is the host's half, and it deliberately reuses the one `followTimer` slot so
780
+ * "at most one armed continuation, ever" (I-3) stays true.
756
781
  *
757
- * DEFINED AFTER `cancelFollowThrough`, not before it: the callback closes over
758
- * it, and a `useCallback` whose deps array reads a `const` that is still in its
759
- * temporal dead zone throws during the very first render - which presents as a
760
- * blank tree, not as an error in the console.
782
+ * IT STARTS THE RUN WITH `controller.continue()`, NOT `submit()`. Nothing is
783
+ * appended to the history: the interrupted turn's input is already there and the
784
+ * half-written reply never was, so `continue()` just asks again. That is also why
785
+ * there is no card, no `userInitiated` bookkeeping and no prompt-history entry.
761
786
  *
762
- * `followThroughArmed` is PASSED IN rather than read here: the caller is the only
763
- * place that knows what the todo decision and the forced-dispatch gate did in
764
- * this very turn (I-9).
787
+ * A TEAM WAKE COUNTDOWN OUTRANKS IT. If the team already owes the lead a signal and
788
+ * its countdown is running, that wake starts a turn which redoes the interrupted
789
+ * work anyway (and delivers a real signal while doing it); arming here would cancel
790
+ * the wake (`cancelFollowThrough` -> `teamWakeRef.cancel()`) and spend an
791
+ * allowance to do the same thing worse. So this yields, silently, WITHOUT charging.
765
792
  */
766
- const armTeamSettle = useCallback((armed) => {
767
- // ABSENT MEANS "NO TEAM IN THIS HOST": a controller double without the team
768
- // surface simply never earns a continuation.
769
- const facts = controller.teamSettleFacts?.() ?? null;
770
- if (facts === null)
771
- return;
772
- // Same defence as the gate: a double without the team surface never reaches
773
- // this line, and one that has `teamSettleFacts` but no config still gets the
774
- // documented defaults rather than a crash inside an event handler.
775
- const teamConfig = controller.getTeamConfig?.() ?? {
776
- autoResume: 'auto',
777
- settleGraceMs: 3_000,
778
- detachDispatch: true,
779
- };
780
- const decision = planSettleContinuation({
781
- mode: teamConfig.autoResume,
782
- settled: facts.settled,
783
- settledInsideTurn: facts.settledInsideTurn,
784
- runEnd: { aborted: facts.aborted, errored: facts.errored },
785
- continuedThisDispatch: facts.continuedThisDispatch,
786
- userPending: controller.hasPendingUserMessages(),
787
- followThroughArmed: armed.followThroughArmed,
788
- graceMs: teamConfig.settleGraceMs,
789
- outcome: facts.outcome,
790
- });
791
- if (decision.kind === 'notice') {
792
- dispatch({ type: 'notice', level: decision.level, text: decision.text });
793
+ const armRunResume = (graceMs, notice) => {
794
+ if (teamWakeRef.current?.isCounting() === true) {
795
+ getLogger().debug('agent', 'run_resume_yield', { reason: 'team_wake_counting' });
793
796
  return;
794
797
  }
795
- if (decision.kind !== 'continue')
796
- return;
797
- dispatch({ type: 'notice', level: decision.level, text: decision.notice });
798
- cancelFollowThrough(); // I-9: at most one armed continuation, ever
798
+ dispatch({ type: 'notice', level: 'info', text: notice });
799
+ cancelFollowThrough(); // I-3: at most one armed continuation, ever
799
800
  followTimer.current = setTimeout(() => {
800
801
  followTimer.current = null;
801
- // The grace window is open to the user, so both facts are re-read at fire
802
- // time: they may have started a turn, or typed the very message the notice
803
- // was about.
804
- if (controller.isRunning() || controller.isCompactionBusy?.())
805
- return;
806
- if (controller.hasPendingUserMessages())
807
- return;
808
- // THE ID COMES FROM THE FACTS, never from `live()`: the dispatch has
809
- // already settled by the time this runs, so `live()` is null and the
810
- // continuation would never be charged (see `teamSettleFacts`).
811
- controller.markTeamContinued(facts.dispatchId);
812
- submitRef.current(decision.message, { userInitiated: false, todoPolicy: 'continue' });
813
- }, decision.graceMs);
814
- }, [controller, dispatch, cancelFollowThrough]);
802
+ void fireRunResume();
803
+ }, graceMs);
804
+ };
805
+ /**
806
+ * THE FIRE POINT. Every guard `drainCompactionQueue` applies to its own
807
+ * `controller.continue()` applies here, for the same reason: `Agent.continue()`
808
+ * THROWS while running, and the grace window is open to the user, who may have
809
+ * started typing at its very end. `submitMessage` -> `cancelFollowThrough()` already
810
+ * covers a message typed EARLIER in the window; what it cannot cover is a run that
811
+ * began in the same tick the timer fired, which `interactionPhase` does.
812
+ *
813
+ * ITS FAILURES ARE `warn`, NEVER `error`: the error level sets
814
+ * `endReasonRef.errored` (see the gate's note), and a failed START has no
815
+ * `agent_end` to clear it - the next, unrelated run would then be judged to have
816
+ * failed and recovered or reported for nothing.
817
+ */
818
+ const fireRunResume = async () => {
819
+ if (!mounted.current || switchingConversation.current
820
+ || controller.isCompactionBusy?.() || controller.isRunning()
821
+ || interactionPhase.current !== 'idle'
822
+ || controller.areModelSettingsBlocked?.() === true) {
823
+ getLogger().debug('agent', 'run_resume_skipped', { reason: 'host_busy' });
824
+ return;
825
+ }
826
+ const preflight = controller.preflight();
827
+ if (!preflight.ok) {
828
+ dispatch({ type: 'notice', level: 'warn', text: preflight.message ?? 'Configuration error.' });
829
+ return;
830
+ }
831
+ // CHARGED AT THE FIRE POINT, never at decision time: a recovery the user cancelled
832
+ // was never issued and must not spend their allowance.
833
+ resumeRef.current = chargeResume(resumeRef.current);
834
+ // COUNTS ONLY: no message body ever reaches this log.
835
+ getLogger().info('agent', 'run_resume', {
836
+ consecutive: resumeRef.current.consecutive,
837
+ total: resumeRef.current.total,
838
+ });
839
+ interactionPhase.current = 'starting';
840
+ try {
841
+ const outcome = await controller.continue();
842
+ if (outcome?.status === 'not-started' && outcome.reason !== 'cancelled') {
843
+ dispatch({
844
+ type: 'notice',
845
+ level: 'warn',
846
+ text: 'Could not retry the run automatically. Send any message to continue.',
847
+ });
848
+ }
849
+ }
850
+ catch (error) {
851
+ const reason = error instanceof Error ? error.message : String(error);
852
+ dispatch({
853
+ type: 'notice',
854
+ level: 'warn',
855
+ text: `Could not retry the run automatically (${reason}). Send any message to continue.`,
856
+ });
857
+ }
858
+ finally {
859
+ if (interactionPhase.current === 'starting')
860
+ interactionPhase.current = 'idle';
861
+ }
862
+ };
863
+ /**
864
+ * `armRunResume` as of the LATEST render, for the `afterAgentEnd` hook - the same
865
+ * reason `submitRef` exists just below: the subscription effect never re-runs, so a
866
+ * direct call would close over the mount render's binding forever. That binding
867
+ * would happen to be correct today because the function reads only refs and stable
868
+ * values, which is exactly the "happens to be correct" this file keeps having to
869
+ * unwind.
870
+ */
871
+ const armRunResumeRef = useRef(() => { });
872
+ armRunResumeRef.current = armRunResume;
815
873
  /**
816
874
  * `submitMessage` as of the LATEST render, for the grace timer.
817
875
  *
@@ -823,7 +881,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
823
881
  * (P1-1, P1-6). Assigned during render, the same discipline `stateRef` uses
824
882
  * twenty lines up.
825
883
  */
826
- const submitRef = useRef(() => { });
884
+ const submitRef = useRef(() => ({ accepted: false }));
827
885
  /**
828
886
  * THE SINGLE SETTLE PATH for a human request. Idempotent per entry, and it
829
887
  * clears the overlay as its last act.
@@ -948,6 +1006,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
948
1006
  const todos = controller.getTodoSnapshot();
949
1007
  budgetRef.current = advanceBudget(budgetRef.current, todos, autoContinuationRef.current);
950
1008
  autoContinuationRef.current = false;
1009
+ // A RUN THAT ENDED WITHOUT AN ERROR BREAKS THE CHAIN OF BACK-TO-BACK DEATHS
1010
+ // (F3). Read AFTER the engine's verdict was folded in at the top of this
1011
+ // hook and BEFORE `endReasonRef` is reset below, which is the only window in
1012
+ // which both facts are still true.
1013
+ resumeRef.current = settleResumeCounters(resumeRef.current, endReasonRef.current);
951
1014
  // --- Forced-dispatch gate (team-command-forced-dispatch §3.7). --------
952
1015
  //
953
1016
  // THE THIRD LAYER, AND THE ONLY MECHANICAL ONE: if a whole turn went by
@@ -993,11 +1056,24 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
993
1056
  runEnd: { ...endReasonRef.current },
994
1057
  budget: budgetRef.current,
995
1058
  interactive: true,
1059
+ // READ LIVE, like `followThrough` above: `/retry off` and `config set`
1060
+ // take effect on the very next death, not on relaunch.
1061
+ resume: {
1062
+ ...toRunResumePolicy(controller.getConfig().retry),
1063
+ consecutive: resumeRef.current.consecutive,
1064
+ total: resumeRef.current.total,
1065
+ // The engine's own verdict, for the WORDING only (`RunEndFacts` is a
1066
+ // structural subset of `AgentEndEvent`).
1067
+ cause: end,
1068
+ },
996
1069
  });
997
1070
  endReasonRef.current = { aborted: false, errored: false, transient: false };
998
1071
  if (decision.kind === 'notify') {
999
1072
  dispatch({ type: 'notice', level: decision.level, text: decision.text });
1000
1073
  }
1074
+ else if (decision.kind === 'resume') {
1075
+ armRunResumeRef.current(decision.graceMs, decision.notice);
1076
+ }
1001
1077
  else if (decision.kind === 'continue') {
1002
1078
  dispatch({ type: 'notice', level: 'info', text: decision.notice });
1003
1079
  // NO LIVE COUNTDOWN (D-10). The notice is written once and does not
@@ -1063,20 +1139,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1063
1139
  });
1064
1140
  }, FORCED_NUDGE_GRACE_MS);
1065
1141
  }
1066
- // --- The team's settle continuation (team-detached-dispatch 5.3.3) -----
1067
- //
1068
- // THE THIRD ARMER OF ONE TIMER, and the placement is the whole point: the
1069
- // forced-nudge branch above called `cancelFollowThrough()`, so a team
1070
- // decision written beside it would be silently cleared one line later. Here
1071
- // - after the nudge, before `onTurnEnd()` - nothing downstream cancels it.
1072
- //
1073
- // A dispatch that settled INSIDE this turn needs no new turn (its report
1074
- // already arrived as a steering message), and one that settled while the
1075
- // user was typing does not need one either (their turn carries it). Both
1076
- // are `planSettleContinuation`'s rules, not this block's.
1077
- armTeamSettle({
1078
- followThroughArmed: followTimer.current !== null || decision.kind === 'continue' || gated,
1079
- });
1142
+ // NO TEAM DECISION IS MADE HERE (team-lead-wake-signals). It used to be, once per
1143
+ // `agent_end`, and a dispatch that ends while the lead is idle never produces
1144
+ // one - so the team's report waited for the user to type. The controller's
1145
+ // governor now judges at every moment a signal could be collectable, and the
1146
+ // wake driver mounted below acts on its requests through this same timer slot.
1080
1147
  // A team-mode change asked for during the turn lands here, AFTER the gate above
1081
1148
  // read its basis (I-9). The posture lands next: a pending GOVERN entry that
1082
1149
  // arrives with it is reported by the same toast channel, not silently swallowed.
@@ -1136,6 +1203,51 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1136
1203
  controller.dispose();
1137
1204
  };
1138
1205
  }, [controller]);
1206
+ // --- The team wake driver (team-lead-wake-signals 4.10). ------------------
1207
+ //
1208
+ // THE TERMINAL'S HALF OF "THE TEAM NEEDS THE LEAD": the controller's governor decides
1209
+ // that a turn is owed; this starts it. The countdown lives in `followTimer` - the one
1210
+ // slot the todo follow-through and the forced nudge already share - so at most one
1211
+ // continuation is ever armed, and a wake that finds the slot taken answers `busy` and
1212
+ // is retried rather than stealing it or being dropped (I-WK9).
1213
+ useEffect(() => {
1214
+ const driver = new TeamWakeDriver({
1215
+ controller,
1216
+ timer: {
1217
+ set: (fn, ms) => {
1218
+ if (followTimer.current)
1219
+ clearTimeout(followTimer.current);
1220
+ followTimer.current = setTimeout(() => {
1221
+ followTimer.current = null;
1222
+ fn();
1223
+ }, ms);
1224
+ },
1225
+ clear: () => {
1226
+ if (followTimer.current)
1227
+ clearTimeout(followTimer.current);
1228
+ followTimer.current = null;
1229
+ },
1230
+ armed: () => followTimer.current !== null,
1231
+ },
1232
+ // The countdown is a transcript line (it does not tick - D-10), the cancellation a toast.
1233
+ announce: (level, text) => dispatch({ type: 'notice', level, text }),
1234
+ toast: (level, text) => dispatch({ type: 'pushToast', level, text }),
1235
+ // THROUGH `submitMessage`, so the wake gets the same card, phase bookkeeping and
1236
+ // `userInitiated: false` treatment as every other continuation. It is only ever
1237
+ // called with the lead idle (the driver re-checks in the same synchronous block),
1238
+ // so it can never take the "running -> queue as user steering" branch.
1239
+ submit: (text, invocation) => submitRef.current(text, { userInitiated: false, todoPolicy: 'continue', invocation })
1240
+ .accepted,
1241
+ cancelHint: () => 'Esc cancels',
1242
+ leadBusy: () => interactionPhase.current !== 'idle',
1243
+ });
1244
+ teamWakeRef.current = driver;
1245
+ const detach = driver.attach();
1246
+ return () => {
1247
+ detach();
1248
+ teamWakeRef.current = null;
1249
+ };
1250
+ }, [controller]);
1139
1251
  // --- Governance event stream (governance-mode 8.6 / 14.4). --------------
1140
1252
  //
1141
1253
  // ANOTHER CLI-LOCAL SUBSCRIPTION, for the reason the team one records: `GovernanceEvent`
@@ -2352,6 +2464,11 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
2352
2464
  // nudge continuation arrives here with `userInitiated: false`, so it cannot
2353
2465
  // refill its own budget.
2354
2466
  nudgesRef.current = 0;
2467
+ // THE ONE PLACE THE PER-PROMPT RECOVERY CEILING IS REFILLED (F3), for the same
2468
+ // reason as the nudge budget: only a human may hand an automatic mechanism
2469
+ // another allowance, and a recovery or a todo continuation arrives here with
2470
+ // `userInitiated: false` and so cannot refill its own.
2471
+ resumeRef.current = emptyResumeCounters();
2355
2472
  }
2356
2473
  // Mirrors where the reducer clears its own copies, in the same action
2357
2474
  // (C-11): a new turn's end reason must not inherit the previous one's.
@@ -3172,8 +3289,13 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
3172
3289
  // the pre-existing meaning of Esc here ("start nothing"), and a second rung
3173
3290
  // below it must not take that away.
3174
3291
  if (followTimer.current) {
3292
+ // A cancelled team wake says so itself ("Wake cancelled. The report goes with your
3293
+ // next message."); a second, generic toast would say the same thing twice.
3294
+ const wakeOwnsIt = teamWakeRef.current?.isCounting() === true;
3175
3295
  cancelFollowThrough();
3176
- dispatch({ type: 'pushToast', level: 'info', text: 'Auto-continue cancelled.' });
3296
+ if (!wakeOwnsIt) {
3297
+ dispatch({ type: 'pushToast', level: 'info', text: 'Auto-continue cancelled.' });
3298
+ }
3177
3299
  return;
3178
3300
  }
3179
3301
  // --- The team rung (team-detached-dispatch 5.6, I-DD11) -----------------