Skip to content

handoff HO4: source agent (write turn, marker, cap, joined check) - #824

Merged
scuttletoby merged 5 commits into
mainfrom
fork/handoff-ho4-agent
Nov 22, 2026
Merged

scuttletoby merged 5 commits into
mainfrom
fork/handoff-ho4-agent

Conversation

@scuttletoby

@scuttletoby scuttletoby commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

What and why

Handoff source agent, the last part-2 source. When a handoff is due and the setting's source is agent, the old session gets one normal turn, the write turn: on its own thread, with its own model and no fresh context, so its cache is still warm. The text is the setting's instructions (or a default), plus "start with the marker line" and the 32 KB cap. The handoff then goes out with that reply as part 2.

Built on HO1–HO3 rather than beside them:

  • the same dispatch path and slot gate as the handoff
  • the same check before send (handoffDispatchDropped)
  • the command source's cap (HANDOFF_COMMAND_MAX_BYTES)
  • the same fallback when part 2 does not count: parts 1, 3 and 4 at the size backstop, nothing at idle
  • a timeout equal to the source's idle lead (HANDOFF_IDLE_LEAD_MS.agent, 4 min)

How the reply is judged (pure, handoffAgent.ts):

  • The write turn did not complete (stopped or failed), or another user message joined it: no handoff. The old session carries on and keeps that exchange, so nothing is lost. The same applies if the write turn does not end within the window.
  • No reply, a reply over the cap, a first line that is not [T3 handoff notes], or only the marker: the reply does not count, and the fallback above applies.
  • Otherwise part 2 is the reply without its marker. It sits between begin and end lines and is labelled as the old session's notes, not T3's state or rules.

The ids are fixed per source run (handoff-write:<thread>:<run>), so the same run never writes or hands off twice, including after a restart. The write run is not a turn end: no timer, and the pure decision skips it as last-run-handoff. It is also kept out of the part-3 transcript. Default stays off; no migration; no upstream file touched, so no seam lines.

Tests

apps/server/src/fork/handoff (11 files) plus the slot/start-path tests: 222 passed. Typecheck, vp fmt, vp lint and knip are clean.

Cases covered:

  • The write turn's shape: exact command; own thread, instructions text, no modelSelection/freshContext; the transcript leaves the write turn out.
  • Bad replies: marker missing (size and idle), over the cap, empty, only the marker.
  • No handoff: a joined, stopped or failed write turn. The next turn end starts over with new ids.
  • Wait and timeout: a write turn that ends later, including an end event that arrives before the read shows it, and one that never ends.
  • Slot waits: the write turn, then the handoff, each in its own place in the gate's line.
  • State question:
    • runs again: one write and one handoff per run, also with two triggers
    • stopped half-way: a stopped, failed or joined write turn → no handoff, old session usable (handoffBusyCheck)
    • restart: a finished write turn sends nothing and starts no new one
    • old/empty: an empty instructions uses the default

On the old code: 7 tests fail, and 2 files do not load (handoffAgent.ts is missing).

Red checks. Each guard was removed and the test that then fails was named:

Guard removed Fails
"no other message joined" check handoffAgent "a write turn that was stopped, failed or joined…" and service "a write turn where another message joined it…"
completed-status check handoffAgent "a write turn that was stopped, failed or joined…"
marker check "a reply with no marker line at the size trigger falls back" (+ pure test)
cap check "a reply with over the cap at the size trigger falls back" (+ pure test)
noHandoff → return "a write turn where another message joined it…"
write timeout "a write turn that never ends…"
write-turn-done counts as handed-off (handoffDispatchDropped) 26 tests
write command dropped when the thread moved on busy-check "after a write turn failed/interrupted/message…"
event skip for the write run "a write turn that ends later…"
transcript filter "no free agent slot: the write turn, then the handoff…"

Seen once under load: HO3's handoffCommand test "a program that cannot start…" got "its output could not be read" instead of "could not start". It passed 3 runs in a row on its own, and this PR does not touch that file; it looks like a timing race in that test.

Follow-up (not in this PR)

See "After the fix round" below: a completed write turn is now quiet; a failed one still alerts (upstream code).

Size

846 changed lines, over the 400 guide: about 280 source, 510 tests and 40 docs. The source is the write turn, the pure judge and the facts ids; most of the rest is the tests the brief asks for. Adding a default source also needed the existing harness and alert/busy-check tests to model a write turn.

General vs project

All general: a setting any T3 user can turn on. There are no project facts, paths or ids; the marker and default instructions are generic.

Upstream fit: a fork-only add-on in apps/server/src/fork/handoff. It uses upstream's normal message dispatch, run and turn-item projections and the slot gate, and touches no upstream file.

Handoff design row HO4

After the fix round (lenses A+B)

One fix round on both lens reviews. The tables above describe the first version; this section is current.

Major findings

Finding State How
A1 late update of the source run drops part 2 fixed Any loop that finds a write turn as the thread's latest run carries it on to its handoff (finishWrite), with the same fixed ids, so at most once. A late update during the write turn or during the slot wait after it, and a restart mid write turn, all still send.
A2 a steered message vanishes from later part 3 fixed Part 3 leaves out only the write turn's own prompt and its marked reply; a steered message and its answer stay.
A3 failed / timed-out write turn at the size backstop fixed Parts 1, 3 and 4 with the reason, as the command source does; at idle nothing. A person's Stop or a joined message is still no handoff.
B1 notes can fake the end line or T3's parts fixed Lines in the notes that could pass for the message's own (begin/end lines, [T3 handoff, Recent conversation:, the rules line) are quoted with > (neutraliseNotes, also for command).
B2 slow write turn at the size backstop fixed At the 4-minute timeout T3 stops the write turn (run.interrupt with its own reason, so it reads differently from a person's Stop) and waits up to one more minute. After a write turn T3 had to stop, the next size handoff skips the write turn and sends parts 1, 3 and 4 at once. A write turn that ignores the stop sends its handoff when it ends.
B3 the write turn's finish alerts fixed in part A completed write turn uses the handoff run's quiet mark (same rule and :loud suffix, through the existing seam lines; no new upstream line). A T3-stopped write turn is an interrupted run, which upstream does not alert for. Left: a failed write turn still alerts as "failed": that alert is in upstream's awareness code, which is not a fork seam.

Minor findings

Finding State
Old settings get write turns without opting in (A6, B4) fixed: a new source none is the default; a saved mode: handoff without a source keeps parts 1, 3 and 4. agent only when set.
Write-turn outcomes log nothing (A4) fixed: "handoff write turn did not count", "…spent, nothing sent: the thread moved on", "…did not stop; nothing sent yet".
Every event reads all runs during the write turn (A5) fixed: the wait reads only the write run (runIds).
Part 1 up to 4 minutes old (A7) fixed: the thread is read again after the write turn ends, before the send.
A reply that does not count at idle alerts (A8) fixed by the quiet mark above.
Only the last assistant message is used (B5) fixed: the last reply that starts with the marker, else the last reply.
A write turn that asks for approval (B6) in part: it is now stopped at the timeout. The approval request itself alerts like any request; rare, as the prompt says to use no tools.
Old-code failure count in this body (B7) noted: the table above undercounts; see the red checks below.

Red checks (each fix removed, the named test fails; put back after):

Fix removed Test that fails
loop carries a write turn on "a late update of the source run during the write turn / while the handoff waits for a slot"
steered exchange kept in part 3 "a message steered into a write turn stays in the next handoff's conversation"
fallback after a failed write turn "a failed write turn at the size trigger…"
notes quoting "notes that fake the end line or T3's parts stay inside part 2"
stop at the timeout "a write turn not ended in time…: T3 stops it…" (size and idle)
bound after a stop "after a write turn T3 stopped, the next due handoff at the size trigger"
write turn kept in hand after an ignored stop "a write turn that ignores T3's stop…"
quiet mark, JavaScript and SQL handoffShell "a write turn (the agent source) ending with no handoff is quiet too…"
loop started by a write turn's update after a restart "a restart mid write turn: its end sends the handoff once"
busy check lets the fallback through busy check "after a write turn failed / interrupted the check lets its handoff through"
last marked reply handoffAgent "…the last reply that starts with the marker"
none default contracts "a saved handoff without a source reads as none"; service "a handoff saved before the sources (no source)"

State questions in tests: restart mid write turn; restart after a write turn that ended long before (nothing sent, no new write turn); timeout then the next turn (bounded); a steered message then a second handoff.

The flaky HO3 test ("a program that cannot start…") failed once in this round. Cause: on Linux the program runs under timeout, which exits 127 at once for a missing program, sometimes before the process runner has written and closed the empty stdin. That write then fails (EPIPE), and the reason reads "its output could not be read" instead of "could not start" (35 of 200 in a direct Node run). The handoff is still a failure either way; only the reason text differs. Test-only fix: the "could not start" case now uses a spawn that fails (its project folder is gone), with no race; the 126/127 exit codes, which are how a missing program reads on Linux, stay covered. 8 runs in a row green. Left: the race itself is in the upstream process runner (apps/server/src/processRunner.ts, a seam file); fixing it (ignore a stdin EPIPE once the program has exited) needs a seam line, so it is a follow-up.

Size of this round: about 620 source lines, 690 test lines and 60 docs lines.

🤖 Generated with Claude Code

The old session gets one normal turn on its own thread with the
setting's instructions; its reply is part 2 of the handoff when the
turn completed, no other message joined it, the reply starts with the
marker line and is within the command source's 32 KB cap. A reply that
does not count falls back like the command source (size: parts 1, 3, 4;
idle: nothing). A stopped, failed, joined or timed-out write turn means
no handoff: the old session carries on. Fixed ids per source run, so a
run never writes or hands off twice; the write run is no turn end and
stays out of the transcript. Default stays off; no migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@scuttletoby

scuttletoby commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner Author

Lens A

Verdict: SAFE. Reviewed at head dbba7f5. No path sends a handoff twice, hands off mid-task or leaves the thread stuck. Every failure I found means a handoff that does not happen: the old session carries on with its full context. Major 1 drops part 2 without a word, and major 2 leaves a steered exchange out of later handoffs. Both should be fixed. The changed test files pass when run one by one: handoffAgent 4, HandoffService 63, handoffBusyCheck 15, handoffFacts 15, handoffAlert 15.

Blocking

None.

Major

  1. A late update of the source run drops the handoff without a word. apps/server/src/fork/handoff/HandoffService.ts:557-558 together with :280.
    • A late completed update of run R replaces the thread's fiber. The test at HandoffService.test.ts:776 gives a child's settlement or a re-emitted wake as examples. On an orchestrator thread with children this is likely within a write turn that can last up to 4 minutes.
    • During the write turn: the new loop for R sees the running write turn as the latest run. Its state maps to interrupted, so the takeover at :280 does not apply. The decision then gives skip("newer-run") and the loop returns. The write turn finishes, but :556 skips its end, so nothing sends the handoff.
    • After the write turn, while the handoff waits for a slot: the takeover at :280 sets runId to the write turn's own id. The decision then gives last-run-handoff and the loop returns.
    • Either way the write turn is spent and part 2 is never sent, and the log says nothing. At the size backstop this repeats at every turn end while the context keeps growing.
    • Fix: when the latest run is R's own write turn (parseHandoffWriteMessageId(latest) === runId), carry on with that write instead of skipping. That means waiting for it if it is still running, or judging and sending it if it has finished. Another option: a late update of a run older than the loop's current one does not replace the fiber.
    • A test should send a late update of R during the write turn and another during the slot wait after it.
  2. A user message that joined a write turn disappears from later handoffs' part 3. HandoffService.ts:138.
    • The transcript filter removes every write-turn run, including one where the person steered in a real message and the old session answered it.
    • The PR's rule is "the old session carries on and keeps that exchange". It does, but at the next handoff the new session's "Recent conversation" leaves that exchange out without saying so. Only t3_thread_read still shows it.
    • Fix: remove only the write turn's own user message and reply, or only write turns with no joined message. Keep the steered exchange.
  3. A failed or timed-out write turn at the size backstop: no fallback. HandoffService.ts:391, handoffAgent.ts:41.
    • Design 4.3 lists "timeout" and "bad reply" as source failures, and at the size backstop those still send parts 1, 3 and 4. Its state table says "interrupted, failed or steered: does not count, the old session carries on".
    • The PR reads every failed write turn as "no handoff". For a timeout that is forced, because the write run is still active and the busy check would drop the handoff anyway. For a failed write turn it is a choice.
    • At the backstop, a provider error, for example a nearly full context or an overloaded provider, means no handoff. It also means another write turn, and another failed run in the timeline, at every later turn end.
    • Suggest: at the size backstop, a failed write turn (not one stopped by a person or joined) falls back to parts 1, 3 and 4 as the command source does. Or the docs state plainly that the backstop does not fire then. This is a design call for the owner.

Minor

  1. Write-turn outcomes that drop part 2 log nothing: the loop returning after a late-update skip, and a handoff dropped after the write turn because the thread moved on. Only the generic "handoff dropped: the thread moved on" is logged. A warning such as "handoff write turn spent, nothing sent" would make major 1 visible in the logs.
  2. HandoffService.ts:197: while the write turn runs, every event of the thread (each streamed item) reads all of the thread's runs again. On long threads that can be many full reads for up to 4 minutes. Once the run is found, read it by runIds: [write.id].
  3. Old settings: source defaults to agent (packages/contracts/src/handoff.ts). A person who already has mode: handoff without a source used to get parts 1, 3 and 4 with "no handoff source is set up yet". After this PR they get write turns without changing anything. That is intended, but say it in the release note.
  4. Part 1 is built from the read taken before the write turn. Only attempts, subagents and turn items are read again, so the thread and runs facts can be up to 4 minutes old. The design says part 1 is "read at send time". The slot-wait path already reads again (again); the first send could do the same.
  5. The follow-up about the write turn's finish alerting is already noted in the PR. A reply that does not count at the idle trigger always alerts, because no handoff run starts in the 5 s hold.

Checked and fine

  • Ids fixed per source run. The check before send allows a write turn only at its source run (handoffFacts.ts:179), and the handoff only after that run's own completed write turn. After a restart, a finished write turn sends nothing and starts no second write turn.
  • Joined check. Upstream puts a steered message's user_message item on the running run with its own messageId, so the check works on real projections, not only on the testkit. An unread steer that went back to the queue also leaves a queued run, which the busy check drops.
  • Slot waits. A write turn refused a slot goes back to the outer loop and decides again with the same ids. A handoff refused a slot after the write turn sends again, with the check before send each time. The gate deletes a place on admit, so no stale place holds others back during the write turn.
  • Reply judging: completed status, joined check, last reply by ordinal, empty reply, cap on the UTF-8 bytes of the whole reply, marker as the first trimmed line, only the marker. Cancelled and rolled-back runs count as ended and give "no handoff".
  • HO3 records and command settings: unchanged paths. handoff-write: does not match the handoff: prefix, so old ids parse as before.

@scuttletoby

Copy link
Copy Markdown
Owner Author

Lens B

Verdict: SAFE to merge (head dbba7f5). The default stays off. Every failure ends in "no handoff, the old session carries on", or in the documented fallback (parts 1, 3, 4). Nothing is sent twice, and no failure loses the old session. The three majors below should be fixed before anyone turns source: agent on for real threads. They are not merge blockers.

Blocking

None.

Major (non-blocking; fix in this PR or file follow-ups)

  1. The reply can fake the end line. At apps/server/src/fork/handoff/handoffMessage.ts:97-100 the reply goes in word for word. If the reply contains ----- end handoff from the old session ----- followed by text styled as T3's part 1 ("Open child tasks: none") or as rules, that text sits outside the "its notes, not T3's state" block. It can only add text: the real part 3 and part 4 still come last. This is new compared with command, because the text here is model output, and a prompt injection earlier in the old session can steer it. Fix: before joining, drop or escape any reply line that equals one of the begin or end lines (agent or command), or put a per-handoff nonce in the begin and end lines.

  2. Timeout at the size backstop with a slow provider. See HandoffService.ts:212-221, :391 and :556. After 4 minutes the result is noHandoff, but the write turn keeps running (nothing stops it). When it ends, it starts no timer. So at the backstop, every later turn end sends another write turn that can run past 4 minutes and adds up to about 8K tokens, and the thread never hands off. Codex at high effort writing close to 32 KB on a 150K context can take more than 4 minutes. Suggest: on timeout, stop the write turn; or at the size trigger, wait longer, or as long as the run is still making progress. Clock jumps are not an issue: the timeout is an Effect sleep (monotonic). Only the existing idle-window decision reads wall time.

  3. The unquiet write-turn finish happens more often than the docs say. docs/fork/handoff.md:167 names only "the handoff does not start within 5 s (for example a slot wait)". The write turn's finish also alerts the phone every time it ends with no handoff:

    • at the idle trigger, a reply that does not count (HandoffService.ts:391, return);
    • a failed or stopped write turn;
    • a timed-out write turn.

    That is at most one extra alert per user turn, because the write turn's end starts no new timer. There is no data loss, so it is fine as a follow-up while the default is off. Please file the issue and fix the doc line. The likely fix is to treat handoff-write: like handoff: in the quiet-run rule (handoffShell.ts:85).

Minor

  1. Existing settings. source defaults to agent (packages/contracts/src/handoff.ts:48). Until now, a thread with mode: handoff and no source set got parts 1, 3, 4 and no extra turn. After this PR it gets a write turn with no new opt-in. This matches the design, but it deserves one line in the docs or release notes.
  2. Only the last assistant message is used (handoffAgent.ts:50-53). A model that writes the marker and the notes, then makes a tool call, then ends with "Done." fails the marker check. Using the last message that starts with the marker would be more robust.
  3. A write turn that asks for approval (a tool call) waits the full 4 minutes and then leaves that request pending in the old session. The request alerts like any other. "Use no tools unless you must" makes this rare.
  4. The PR body's "on the old code 7 tests fail" undercounts. With handoffAgent.ts present and the three changed source files reverted, I measured 23 failures: HandoffService 16, busyCheck 5, facts 2. That is more red than the body claims, so it does not weaken the PR.

Checked, no finding

  • Default off is really off. readThread returns null for off and compact (HandoffService.ts:99) before any write turn is built. handoffAlert's off cases stay green.
  • Fake ids. Write ids are made only by the server. MCP tools build their own message ids, so an agent cannot forge handoff-write:. The handoff after a write turn passes the check only when the latest run is that source run's own completed write turn (handoffFacts.ts:188-193).
  • Caps. The reply is checked against 32 KB before the join. Part 3 keeps its own budget, so the total has the same bound as command. A joined message, or a steered one, means noHandoff (handoffAgent.ts:44-48).
  • Slot gate while the turn is due. A write turn refused a slot decides again every 5 s, keeps its own place, and stops at cache expiry (cache-expired). After the write turn, the handoff waits in its own place, and the check before the send drops it if the thread moved on.
  • Non-Claude providers. The write turn has no modelSelection, so it runs on the thread's own instance. The judging is the same for every provider. The idle trigger is Claude-only (it needs the cache expiry); the size trigger works for any provider that reports a size. This is where the timeout risk in major 2 applies.
  • Restart. A finished or interrupted write turn sends nothing and starts no new turn. The old session keeps the exchange, and the next turn end starts over.
  • Size. 846 lines in one PR is fine. The pure judge, the ids and the service wiring depend on each other, and a split would merge dead code. Most of the lines are tests.

Tests run (own worktree, one file at a time)

  • PR head: handoffAgent 4/4, HandoffService 63/63, handoffAlert 15/15, handoffBusyCheck 15/15, handoffFacts 15/15.

  • Old code (HandoffService.ts, handoffFacts.ts and handoffMessage.ts reverted to the merge base): 23 fail, as listed in minor 7.

  • Guard checks:

    • Removed the transcript filter (HandoffService.ts:138): "no free agent slot: the write turn, then the handoff…" goes red (1 failure).
    • Removed the event skip for the write run (HandoffService.ts:556): "a write turn that ends later: its end wakes the wait…" goes red (1 failure).

    Both match the PR's table.

scuttletoby and others added 3 commits November 21, 2026 22:07
… quiet

- A late update of the source run, or a restart, no longer drops part 2:
  any loop that finds a write turn as the latest run carries it on to its
  handoff (fixed ids, so at most once).
- A message steered into a write turn stays in later handoffs' part 3; only
  the write turn's prompt and marked reply are left out.
- A failed or timed-out write turn at the size backstop sends parts 1, 3
  and 4 (idle: nothing), as the command source does.
- Notes lines that could pass for the message's own lines are quoted.
- T3 stops a write turn at its timeout (run.interrupt, its own reason);
  after one such stop the next size handoff uses the fallback at once.
- A completed write turn is marked quiet, as the handoff run is.
- New source `none` is the default, so a saved handoff setting keeps its
  old behaviour; `agent` only when set.
- The last reply that starts with the marker is used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A missing program under `timeout` can exit before the empty stdin is
written, so the reason sometimes read as an output error. The case now
uses a spawn that fails (its project folder is gone); exit codes 126 and
127 stay covered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@scuttletoby

Copy link
Copy Markdown
Owner Author

Lens round 2

Verdict: SAFE to merge at head d7785af. All six round-1 majors are fixed or, where the PR says so, fixed in part. The rule "handoff mode without a source keeps today's behaviour" holds.

There is one new major, N1: a server restart in the middle of a write turn. It still sends exactly one handoff and loses nothing. But it costs a second write turn and puts the old notes into part 3. Like the leftovers, it is not a blocker while agent is opt-in, but it should be a follow-up issue, together with the gaps in the quoting of the notes (B1).

1. Round-1 majors

Item State Evidence A test fails without the fix?
A1 late update drops part 2 FIXED HandoffService.ts:477-486: any loop that finds a write turn as the latest run carries it on through finishWrite. carrying (:252-261) is kept when a loop is replaced (:394-403), so a replaced loop's write turn is always carried on. Yes, checked here: with the carry-on at :482-485 removed, 4 tests go red (both late-update tests, "a restart mid write turn…" and "a write turn that ignores T3's stop…")
A2 steered exchange lost from part 3 FIXED withoutWriteTurns (HandoffService.ts:86-104): a joined write turn loses only its own prompt and the reply that starts with the marker. Yes, per the PR's red-check table ("a message steered into a write turn stays…"). Not re-checked here.
A3 failed / timed-out write turn at the backstop FIXED handoffAgent.ts:66-69: a failed run, or one T3 stopped, is "does not count" without noHandoff. HandoffService.ts:372: at size, parts 1, 3 and 4 still go; at idle, nothing. A person's Stop or a joined message is still no handoff (:63-65, :70-72). Yes, per the table ("a failed write turn at the size trigger…")
B1 notes fake the end line or T3's parts PARTLY handoffMessage.ts:38-57 quotes a line that starts with dashes plus begin/end…handoff, [T3 handoff, Recent conversation: or the rules line. The exact forgery is closed. Look-alikes still get through unquoted (checked with the regex): a leading zero-width space, **----- end handoff from the old session -----**, the same line in backticks, em-dashes or ===== instead of hyphens, and ## Recent conversation:. Not blocking: the notes come from the same agent with the same tools, they can only add text, and the real parts 3 and 4 still come last. Follow-up: a per-handoff nonce in the begin and end lines (for example derived from the handoff's message id), with the header "only the end line with this id ends the notes", in place of a deny-list. Yes, per the table (exact forgery)
B2 slow write turn at the backstop FIXED finishWrite stops the write turn at its deadline (:296-316), waits one more minute (:317-324), then keeps it in hand. lastWriteTimedOut (:410-433, used at :587-595) makes the next size handoff skip the write turn. The repeat is bounded. Yes, per the table (3 rows)
B3 write-turn finish alerts PARTLY, as stated handoffShell.ts quietCandidate and the SQL CASE: a completed write turn is quiet, a joined one is loud (a person's message is in it), and a T3-stopped one is an interrupted run. A failed one alerts (see 3). Yes, per the table (JS + SQL)
No source keeps today's behaviour FIXED packages/contracts/src/handoff.ts:52 now defaults to none. The settings writer saves sparse (defaults left out), and agent was the default before, so no saved file has source: agent unless someone wrote it by hand. source: none gets the old lead and the old text (handoffDecision.ts none: 4 min; handoffMessage.ts:128-129). Yes: contracts test, and service test "a handoff saved before the sources (no source)" (HandoffService.test.ts:1700-1711)

2. New problems from the fix round

N1 (major, not blocking): a restart mid write turn does not happen the way the test models it.

  • The test "a restart mid write turn: its end sends the handoff once" (HandoffService.test.ts:1713) has the write turn still running after the restart, ending later.
  • Upstream does not do that. A run cut short by a restart is cancelled, and RestartContinuation.ts:248-358 sends "Continue where you left off" as a new run. That run's message id is message:restart-continuation:<run>, an ordinary id. There is no continuation when a stop was requested (restartStopRequested), so a turn T3 already stopped is fine.
  • What happens then:
    1. The cancelled write run is judged "ended cancelled", which means no handoff (handoffAgent.ts:70-72).
    2. The continuation run goes on writing the notes as a normal turn.
    3. Its end is a normal turn end: handoffThreadFacts gives kind: "turn", so a second write turn starts for the continuation run, then the handoff.
  • Still exactly one handoff, nothing lost, and nothing stuck. But:
    • there is an extra write turn (tokens, up to 5 more minutes);
    • the continuation's reply (up to 32 KB of notes) is not filtered from part 3, so it can push the real conversation out of the 8K budget;
    • the continuation's finish alerts.
  • Fix: treat a run whose restartContinuationOfRunId is a write run as part of that write turn. Carry it on and judge its reply in finishWrite, and leave it out of part 3 like the write turn. The test should use a cancelled write run plus a continuation run.

T3's own stop vs a person's: sound.

  • The match is exact on the run_interrupt_request item's message (handoffAgent.ts:47-50).
  • An agent's stop through MCP always reads "Stopped by an agent: …" (OrchestratorMcpService.ts:281), so an agent cannot fake T3's reason.
  • The interrupt-request item has a fixed id per run, and only the first stop writes it (Orchestrator.ts:13174-13206):
    • A person's Stop before T3's stays a person's Stop: no handoff.
    • A person's Stop after T3's reads as T3's: at size, parts 1, 3 and 4 go. That is harmless.
  • Only a raw command with that exact reason text could fake it, and only the person can send one. T3's run.interrupt does not set holdQueue, so a person's queued message is not held.

Slot-wait and timeout loops: bounded and correct.

  • In finishWrite the wake is set before the read (:286-290), and the wait is the deadline, then deadline plus 1 min, then kept. The stop's command id is fixed per write turn, so a replaced loop sends it again only as the same command.
  • sendWithSlot (:226-249) has no bound of its own while no slot is free. It reads the thread every 5 s, and a thread that moves on or is switched off drops it. That is the same shape as HO1-3's retry loop, so it is fine.
  • Minor: carrying keeps the id of a kept write turn that never ends (tiny).
  • Minor: the deadline and carriesOn now compare stored wall-clock times with DateTime.now, no longer a monotonic sleep. A clock jump forward can stop a write turn early. That is rare and only means "does not count".

Double dispatch: never two; zero only in documented cases.

  • Why never two:
    • one loop per thread (FiberMap);
    • the write turn's command id has no :loud, so a second write turn for the same run cannot start;
    • the handoff's command id is the same on every path;
    • finishWrite returns when the latest run is already its handoff (:345-349).
  • Zero only when:
    • the thread moved on (logged now);
    • a restart came more than 4 minutes after the write turn ended (carriesOn; the next turn end decides);
    • a small race: a write run's update arrives while the old fiber is still leaving the FiberMap (onlyIfMissing, :794-801). At worst no handoff, and the next turn end decides. Minor.

State question.

  • Runs again: the judge is pure and the ids are fixed, so judging the same write turn again gives the same result. A write turn that ended within 4 minutes and is reported again is judged again. If its handoff was already sent, finishWrite sees that and returns.
  • Stops half-way: see N1 for a restart. A stop between the write turn's end and the send is carried on by any loop: within 4 minutes after a restart, and at any time without one.
  • Old or empty state: threads in handoff mode from before this PR read none (above). HO3 handoff: ids parse as before. Empty instructions uses the default.

3. The "Left" items

  • B3, a failed write turn alerts as "failed": fine to merge with a follow-up issue. It is rare (a provider error), and an alert for a provider failure is arguably useful. Fixing it needs an upstream line that the seams do not allow.
  • B6, a write turn that asks for approval: partly fixed. It is now stopped at the timeout, and the request alerts like any other. Fine.
  • B7: a note on the PR body only. Fine.
  • Neither is blocking while agent is opt-in. Please file the follow-ups: B3 failed-write alert, N1 restart continuation, B1 nonce, process-runner stdin EPIPE. I found no issues for them yet.

4. d7785af (handoffCommand.test.ts)

  • Fine as a test change. The spawn that fails (its project folder is gone) gives "could not start" with no race, and the 126/127 cases still cover the reason text.
  • What it hides: no test now runs a missing program end to end on Linux. In production such a program still reads as "could not start" or, sometimes, "its output could not be read". Both are failures, and only the reason text differs. It hides nothing in this PR's logic.
  • The root-cause fix belongs in the process-runner follow-up.

Tests run (own worktree, one file at a time, each after a capacity check)

  • At d7785af: HandoffService 75/75, handoffAgent 6/6, handoffBusyCheck 15/15, handoffFacts 16/16, handoffShell 10/10, handoffAlert 15/15, handoffDecision 33/33, handoffCommand 9/9, contracts handoff 18/18, forkRowReset.logic 6/6.
  • Red check: the A1 carry-on removed gives 4 failures in HandoffService (see the table). The file was put back afterwards.

@scuttletoby
scuttletoby merged commit 05a82df into main Nov 22, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant