Repository navigation
fix(subagent): surface a failed delegation's real cause, and make a transient failure resumable - #320
Merged
Merged
Conversation
… chat line
The loop already recorded a failed run's real failure detail on
session.ResultPayload.Error, and every delegation path then dropped it:
handleChildEvent returned only text+stop, so drainChildObserved/driveChild
never saw it, and the StopError render used the child's last assistant TEXT as
the error body. The model-facing "error" was therefore the child's last chat
line ("Now let me check the tests.") — or, when the child had said nothing, the
opaque "subagent failed without producing a summary". A stalled or 5xx'd child
looked like a child that had simply stopped talking.
Thread the cause out (handleChildEvent -> drainChildObserved -> driveChild,
last drive wins; drainChild keeps its 2-value signature — its five callers do
not want it) and compose the StopError body at ONE chokepoint,
subagentErrorBody: the cause LEADS (the actionable half), the child's last text
follows as clamped "Last activity before the failure" context. Both
renderSubagentResult/renderWritableSubagentResult and the Parallel
branch-failure arm go through it, so there is no second policy. The empty-cause
rows preserve the pre-fix shape, so non-loop StopError terminals do not
regress. salvageEmptyStop is untouched — isEmptyTerminalStop excludes StopError,
so a crashed child is still never re-driven.
Observability: new session.SubagentPayload.Cause, set on EvSubagentEnd ONLY and
clamped at both emit sites to maxSubagentCausePreview (400 runes) — bigger than
a text preview because a truncated provider error is unactionable, still
bounded. It is harness/provider metadata, never child-authored output, so
gauntlet #7 holds on the same footing as Stop/Usage. It rides Subagent.cause
(proto field 14) -> toProtoSubagent -> client.SubagentMsg -> the mecatui fleet
lane. ParallelPayload deliberately gains no field: a branch failure already
reaches the model through the Parallel ToolResult text, which failReason feeds.
mecatui: the inline Subagent card needs no new slot (the server-composed error
body already carries the cause and the card renders it in its result slot); the
ctrl+a fleet FOCUS pane gains a "failed: <clamped, single-line cause>" line,
which is the only channel there — a roster row otherwise shows just
stop:error, and a background child's failure never reaches an inline card at all.
llmresilience: the RECOVERABLE stream lifecycle was fully observable (breaker,
retry-exhaustion, idle stall at Info; per-attempt-timeout and
retry-with-backoff at Debug) while the two paths that actually END a turn logged
at NO level — a permanent non-retryable establishment error and a mid-stream
error chunk. Both now emit one Info line with a clamped err. The mid-stream line
lives in logMidStreamError, called from BOTH restSeq variants so disabling
StreamIdleTimeout cannot re-open the blind spot, and it is logged BEFORE the
yield: an ordinary consumer breaks its range loop on the error, which makes
yield return false, so a log after the yield-false return is unreachable on the
very path that matters. Per Config.Diagnostics' own contract this is an ADAPTER
seam, not the loop's run-scoped sink, so ADR 0020's three-line loop budget is
untouched. The Debug retry lines were NOT promoted (retries are routine); they
were made reachable instead by a new mecatui --log-level (debug|info|warn|error,
default info) threaded through one logLevels mapping to all three sinks, with an
unknown value rejected loudly rather than fail-softed.
Tests: the subagentErrorBody oracle (all four rows + clamping + whitespace
floor); an adversarial uncooperative-mock regression asserting MODEL-FACING that
the parent's RECORDED tool result leads with the provider cause and never
presents the child's chat line as the failure reason, plus the no-child-text
variant; the subagent.end clamp/end-only/clean-terminal guards; a durable-log
acceptance that recovers the cause from a re-opened jsonlstore .events.jsonl
alone; the Parallel branch equivalents (incl. that the cause survives the
judge join's firstLine truncation); mapper + client-relay + TUI focus-pane
render guards; and two llmresilience tests over both restSeq variants with a
clean-stream negative. Every guard was mutation-checked by deleting the
production line and watching it fail.
Closes #319
Co-Authored-By: Claude Opus 5 <[email protected]>
…o resume it session.Session.Recover (issue #51) existed, was exported, and did exactly the right thing — it was simply never wired into the child paths. resolveResumeSession hard-refused StateFailed, justified by "a failed child carries no accumulated-user-context cost", and the team supervisor encoded the same policy as `if stop != StopError { Reopen() }` + nonResumable. Issue #318 falsified the premise: two read-write children (direct-write, ADR 0041) died on the terminal 180s stream-idle stall after 58 and 52 turns and ~5M/~3.5M cumulative input tokens, with mutations ALREADY APPLIED to the real tree. Both transcripts were fully paired, both parents attempted resume:, both were refused. And the taxonomy inverted the penalty — an operator-configured timeout_ms cancels the run ctx and was already resumable via Interrupt, while a network stall becomes StopError and was permanent. resolveResumeSession now recovers StateFailed with the same error wrapping as the Reopen/Interrupt arms; everything downstream (tighten-only limits, fresh fork, Rehome, in-flight guard, resume-start persist) is untouched and no domain code changed. A non-terminal state (a snapshot still recorded `running`) is still a model-addressable tool error. The team supervisor dispatches on the session's STATE, not the run's stop reason. That distinction is load-bearing and was NOT in the plan: a StopError run does not imply a failed session — terminate() Fail()s it, but terminateComplete() (a text-bearing turn carrying a terminal error stop chunk) Stop()s it into StateCompleted, which the old code left un-reopened. Only the failed shape changes behaviour; every other state, deliberately including a CANCELLED member (whose Reopen failure is what deschedules it), keeps its exact prior disposition. nonResumable now means only "the recovery transition itself failed" and stays a set-only latch, so a recovered LEAD reaches synthesise and the team keeps its deliverable. stopped / StopReasonError are unchanged: a failed round still deschedules the member and releases its tasks, so the lead still reads an honest "stopped before finishing". warnUnexpectedReopen became warnUnexpectedRecovery (both seams report through it, so the line names the outcome, not one verb). Discoverability (mandatory, ADR 0070): a StopError result now carries subagentErrorResumeHint after the agentId trailer, and the resume arg's schema description says a failed subagent can be resumed. The hint deliberately lives in renderSubagentResult, NOT in the Parallel-shared subagentErrorBody: a parallel-<callID>-<n> branch id fails validateResume's prefix gate, so advertising resume there would instruct the model to take an action that cannot succeed. It is placed AFTER the trailer so "the agentId above" is literally accurate on the StopError layout, where the trailer comes last. resumeStalenessNote's "file changes ... are GONE" is true only for a read-only child, whose worktree was torn down. A writable child never forks, so on resume its edits are still in the real tree; it now gets resumeWritableNote instead. Shipping the fix at the one layer that matters, so this is in scope rather than polish. Tests: the failed-resume refusal test inverted into TestSubagentResumeFailedRecovers plus a tighten-only-limits sibling; TestSubagentResumeFailedRepairsOrphanedToolCall is the load-bearing adversarial case (a failed turn that orphaned a tool call replays satisfying session.ValidateToolPairing, with the FAILURE close-out wording and never the cancellation wording); TestSubagentFailedResultAdvertisesResume asserts the hint through the real render path with the agentId ordering, and TestParallelBranchFailureDoesNotAdvertiseResume is its negative; TestParentResumesFailedSubagentByTrailerID is the model-facing e2e; the two resume-note tests pin the writable/read-only split; TestSynthesisRunsAfterLeadRunFailed covers BOTH StopError shapes (empty turn -> StateFailed -> Recover; text-bearing -> StateCompleted -> Reopen) with a state-recording store proving which seam each case exercises — the first draft passed with the Recover arm neutered, which is why the state assertion exists. The forker fail-fast test swaps its failed seed for a still-running one (the state that is still refused). Every guard mutation-checked by deleting the production line and watching it fail. NOT delivered from #318's acceptance list: "a team member that hits one transient stall still participates in later rounds". planRound only schedules a member with drained messages or a claimable task, so an unbenched failed member would keep its in-progress claim, be neither rescheduled nor released, and report DispositionDone — hiding the failure from the lead. Genuine rescheduling needs task-release + bounded-retry + disposition honesty; recorded as an explicit non-goal in ADR 0077. Closes #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…d-resume change Review-panel follow-up on fd018f1 (#319) and 3aefa8e (#318). Four correctness fixes, five doc/ergonomic ones, and the test gaps the QA axis found by coverage profile and by mutating the new emits. CORRECTNESS The third EvSubagentEnd emit site broke the very contract the field documents. driveBackground's endOnError (a fork / session-build failure BEFORE the child drove) emitted Stop: StopError with Cause unset, so a client reading the doc as "stop==error implies a cause" got stop=error/cause="" on the BACKGROUND path — the one path where the event is the ONLY channel, because the model already holds the started-result and no inline card is ever produced. It now clamps errResult.Content in, and the field doc + AGENTS.md say THREE sites instead of two. errResult.Content is harness-composed text ("Subagent: workspace isolation failed: …"), so the gauntlet-#7 footing is identical to the drive-failure cause. The ACP projection dropped the cause, so two projections of one event disagreed: a mecatui user saw why a delegation failed and an ACP client (an editor — a developer-facing surface) saw a failed card with no reason. projectSubagent now appends it, collapsed to one line like the TUI focus pane, already server-clamped. subagentErrorBody clamped `final` but passed `cause` through unbounded into the parent's PERSISTED conversation, which the parent re-pays for on every subsequent turn — the same argument maxSubagentCausePreview's own doc-comment makes for the event stream, only stronger. The one place that composes the body is now the one place that bounds it: both halves clamped, cause at the larger 400-rune budget. The resume hint was stamped unconditionally, but validateResume's FIRST precondition is a wired store. A SubagentTool built without WithSubagentStore — a supported construction for an engine-module consumer, and what several tests in the previous commit used — told the model "resume it with the agentId above" and then refused the call with "not supported in this deployment". That is exactly the defect the hint's own doc-comment cites as the reason it stays out of the Parallel path, on a different precondition. It is now gated on t.store != nil (finishForegroundRun un-blanks its receiver for it), with TestStorelessSubagentFailureDoesNotAdvertiseResume as the negative beside the existing Parallel one. TESTS TestSynthesisFallbackWhenLeadStopped was deleted in the previous commit and its replacement no longer reaches synthesise's nonResumable guard — verified at count 0 by coverage profile. That guard matters MORE after #318, not less, because the diff narrowed nonResumable to mean only "the recovery transition itself failed", making it the one thing still keeping a dead session out of the deliverable path. TestSynthesisSkippedWhenLeadCannotReturnToIdle covers the reachable shape (a lead cancelled MID-round ends StateCancelled; Reopen is completed-only, so it fails and the latch fires). Note the oracle: Report=="" alone is VACUOUS here — bypassing the gate drives a cancelled session that yields no text, so Report stays empty either way. The assertion with teeth is that no phantom synthesis round is counted (Rounds), and both named mutations were verified to fail on it. The BACKGROUND child's Cause emit had no value assertion at all, though the background path is the field's whole justification; mutating it to Cause:"" left the suite green. TestBackgroundSubagentFailureCarriesCause asserts the event AND that the SubagentStatus-collected body leads with the cause rather than the child's chat line, and TestBackgroundPreRunFailureEmitsCause covers the endOnError site above (internal, since that emit needs a sink threaded straight into ExecuteWithParent). Also added: the writable (mode:"read-write") failed-delegation render — #318's motivating scenario, where the cause, the partial-edits note and the resume hint collide and the agentId-before-hint ordering is load-bearing but incidental (the trailer-prefix branch cannot match the StopError layout, so the note takes the defensive else); the TEAM side of Recover replaying a history that actually CONTAINS a tool_use/tool_result pair through ValidateToolPairing (the "a pair is present" precondition is asserted, because the validator passes trivially on a pair-free history — and the honest limit is recorded: a member round cannot produce an ORPHAN, since the loop never reaches RecordAssistant on the stream error path and WithMemberStore is save-only, so there is no seam to seed); --log-level actually reaching the sinks (a tiny newLogSinks seam so all three of them — the port.Diagnostics, the perf logger, the ambient-slog handler — are built from the one logLevels mapping and each is provably level-honouring, plus the baseline handler's own Enabled predicate); and the deliberate breadth of the mid-stream log line on a user cancel, pinned rather than left without an opinion. SMALLER event.go's new field cross-referenced RunResult.Error, which does not exist in the engine module (the only RunResult is e2e/harness, not importable) — a dead godoc reference on a brand-new public field. subagentErrorBody's floor no longer hard-codes caller #1's noun: the Parallel path renders it under a "=== branch-N [FAILED] ===" header, where "subagent failed without producing a summary" read wrong. Its parameters are reordered to (cause, final), the order they render, because both are strings and adjacent and a positional swap compiles into precisely the bug #319 fixed. The CHANGELOG's "must adjust" now names the one honest lever (there is no knob; resume requires a wired store, so a consumer that must forbid resuming a failed child does not wire one — which disables resume: wholesale). mecademo prints cause= when set, so the field is discoverable from the runnable example a library consumer copies. NOT changed, reviewed as correct-as-is: the mid-struct field placement, Cause vs Error naming, and the 4-/5-value returns (no value type extracted — the trip-wire is a 6th value or a second real consumer). The Closes #318 trailer decision is still open, so this commit uses Refs. Every new guard was mutation-checked by editing the production line and watching it fail: the nonResumable gate and the reopenErr latch, both background Cause emits, the background render's cause, the resume hint (dropped, and un-gated), the writable partial-note arm, the cause clamp, a positional argument swap, the ACP append, and each of the four --log-level sinks. LAYOUT (the blocker) The focus pane's new failure line could overflow the ctrl+a overlay card and mangle its border. renderSubagentFocus was not width-aware and centerCard/lipgloss.Place cannot shrink content, so the widest line directly sets the card width — and " failed: " plus a 160-rune clamp is ~170 columns. An ordinary gateway error ("upstream connect error or disconnect/reset before headers. reset reason: connection termination", ~95 chars) is already enough to push the card past an 80- or 100-col terminal, i.e. the operator's ONLY view of a background child's failure was also the thing that garbled the screen. Every peer bound in these overlays is 16-40 runes; 160 was 4x the widest. width is now threaded renderAgentsOverlay -> renderSubagentTab -> renderSubagentFocus and the cause goes through the same cardTextWidth + indentWrap pair the /skills and /agents inventory panels use, so it wraps inside the card budget and ansi.Wrap breaks even a space-free error string. The rune clamp stays, now honestly described as the HEIGHT bound. The old guard could not catch this: it asserted the bound on subagentFailureLine in ISOLATION and explicitly accepted maxSubagentCauseWidth + the prefix, a width wider than the viewport it gets drawn into. It is replaced by a per-wrapped-line width check plus TestSubagentFocusPaneWithLongCauseFitsViewport, which drives the whole pane through View() at 80/100/120 and runs the repo's existing assertFitsViewport — the helper whose own doc-comment warned about exactly this failure mode. TWO CONTRADICTORY NEXT ACTIONS, AND ONE FALSE ASSERTION These two are one problem seen from both ends, so they are fixed together. A failed mode:"read-write" child received "its edits may be PARTIAL, undo with git checkout" AND "resume it to continue where it left off" as independent imperatives. A model can follow both — discard the edits, then resume a child that resumeWritableNote greets with "the file edits you already made are STILL IN PLACE", which the discard just falsified. The writable arm now carries ONE combined decision (writableSubagentFailedNote: resume on top of them, or discard them, "Do not do both") and suppresses the generic hint; subagentResumeHint is the single gate, with two honest silent cases (no store, or the writable arm). A store-less writable failure keeps the plain review-or-undo note and offers no resume at all. And the note itself could assert something false in the other direction. `writable` comes only from the CURRENT call's mode, and validateMode deliberately lets mode COMPOSE with resume — "the read-only investigator stalled, resume it with write access so it can apply the fix" is a legal and natural parent move. That child was then told its edits were STILL IN PLACE when its git worktree had been torn down. A read-only child has no Edit/Write but DOES have Bash in that worktree, so it may genuinely have applied edits; and this inversion is WORSE than the "GONE" wording it replaced, because a child that trusts absent edits builds on nothing. The note is now selected by prepareChildSession's editsSurvived — writable AND the resumed snapshot's persisted Workspace equals the real parent root, captured before buildChildSession's Rehome overwrites it, so no new persisted field is needed — and anything else falls back to the conservative staleness note. --log-level is now labelled "embedded server only:" and states plainly that it has no effect with --server or when reusing a running mecated (a client-only run writes no log of its own), plus the honest note that a debug floor also admits third-party debug logging into that file. docs/tui.md's row and prose match. A mecated counterpart is deliberately NOT added here. The unbounded-cause finding was independently confirmed on the UX and Standards axes as well (three agreeing) and was already fixed above; the concrete risk they name is a gateway HTML error page written into the parent's PERSISTED transcript, burying the resume hint under it. Not acted on, as reviewed: UX N1-N7 and the Standards NOTEs (informational, incl. the deliberate decision not to extract a childOutcome struct before a 6th return value). The --log-level help text is a string with no capturable seam, so it carries no unit test; it was verified by reading `mecatui --help`. New mutations run for this addendum, all observed to fail: the un-wrapped 170-col failure line and a dropped width both overflow assertFitsViewport at 100 cols (with exactly the predicted 111-col card); the resume note keyed on `writable` again tells a torn-down worktree's child its edits survived; the generic hint un-suppressed on the writable arm; the writable failed arm reverted to the plain partial note; and the combined resume-or-discard decision emitted where no store is wired. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…nching it Closes the last acceptance bullet of #318 — "a team member that hits one transient stall still participates in later rounds" — which ADR 0077 shipped the recovery half of and explicitly deferred. Recovering a failed member's session rescued the LEAD's synthesis turn, but `stopped` still descheduled the member, so one 180s stream-idle stall permanently removed it from the run. ADR 0077 named the three things needed. All three land here. BOUNDED RETRY. runTurn no longer benches a member whose round ended StopError when the recovery seam SUCCEEDED and the member is still under its cap: it stays schedulable. The cap is WithMemberErrorRetries (default 1 — one retry survives a network hiccup while capping the wasted spend of a permanently-failing member; 0 restores the pre-amendment bench-on-first-error behaviour byte-for-byte). Never retried: a failed RECOVERY (nonResumable — undrivable), a CANCELLED member (a kill is not a transient failure; D5's disposition must hold), or a turn-budget-exhausted one. TERMINATION comes from memberRT.errorRounds being MONOTONIC — counted on every StopError round, never reset. A member that always fails runs exactly cap+1 rounds and is then benched with its ORIGINAL disposition (stopped + StopReasonError + ReleaseTasks + finishChildRun, all unchanged), so the round loop reaches quiescence far short of WithMaxRounds. TestSupervisorPermanentlyFailingMemberTerminates pins that against an always-failing provider with the round cap set well above cap+1, so a retry that failed to bound itself would run to the cap instead of the asserted 2 rounds. TASK RELEASE. A retried member releases its in-progress claim (the existing team.ReleaseTasks) and returns to team.MemberIdle, following the idle-between-rounds cancel path's shape. Without it the work is stranded: InProgressFor short-circuits planRound's auto-claim, so neither the member nor a peer could pick the task up. planRound also FORCE-SCHEDULES a retried member for exactly one turn (memberRT.retryPending, cleared on schedule). "Not stopped" is not sufficient to be rescheduled — planRound plans only a member with a drained message or a claimed task, and the commonest stall shape is a member dying on its first long exploration turn, before any task exists — so without the one-shot the retry would be a silent no-op in precisely the case #318 reported. That turn carries retryTurnNote: harness metadata (previous turn failed mid-flight, continue from your own transcript above, your claim was released), rendered TRUSTED like the roster, quoting nothing from the failed turn. Without it the member sees a fresh prompt over a transcript that stops mid-thought and cannot tell a crash from its own decision to stop. DISPOSITION HONESTY, both directions. MemberDisposition gains NO value — it is a closed enum mirrored on the proto wire, and "done" is still the honest terminal. Instead agent.MemberOutcome gains an additive count ErrorRounds, mirrored on session.TeamMemberDisposition and proto TeamMemberDisposition.error_rounds (field 4), so team.end carries it: a retried-then-finished member is otherwise byte-identical on the wire to one that never failed. mecatui renders such a lane "done (retried)". And the LEAD is told through the EXISTING trusted status section — writeTeamStatus, renamed from writeStoppedMemberStatus — which now names retried members and their failed-round counts alongside the stopped ones. A silently-retried member is a coordination lie in the opposite direction from the one the stopped line closes, since the lead re-plans and reports on what it believes members did. Supervisor-authored, count only, so the gauntlet-#7 footing is identical. TESTS. A new engine/agent/teamretry_test.go covers the headline case (fails round 0, recovered, retried, and CONTRIBUTES a finding in a later round — run at both retry tiers off the same script so the disabled tier's empty ledger is what gives the enabled tier teeth), the cap swept over 0/1/2, the task release asserted directly on the team aggregate plus a peer's ClaimNext, the never-retried exclusions, and the termination proof. Every new guard was mutation-checked: disabling the retry, unbounding it, dropping the release, dropping the force-schedule, suppressing the note, dropping the count at each of the three projection hops, dropping the TUI label, and widening the gate past its StopError/nonResumable exclusions all fail the suite. Three existing tests changed because the behaviour they pinned changed. The two synthesis tests now pin WithMemberErrorRetries(0) so they keep testing the SYNTHESIS rescue rather than spending their scripted synthesis turn on a retried working round; TestSupervisorMemberDispositionError does the same and now doubles as the retry-disabled-tier guard; TestTeamEndCarriesMemberDispositions scripts two errored rounds so it exercises the DEFAULT tier end-to-end through the Team tool. ADR 0077's Consequences bullet stating this was not delivered is left verbatim and corrected by an adjacent "Amendment (2026-07-29)" section — the bullet described an open item in the same decision, not a decision to reverse, so closing it in place beats fragmenting one decision across two frozen records. Closes #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…the --log-level flag Second review-panel round on fd018f1 (#319) / 3aefa8e (#318) / 60c4346, plus a scope correction that REMOVES surface rather than adding it. THREE MODEL-FACING MESSAGES, one class of defect Each is the same defect the two blocking findings of the last round were: a harness message asserting something the next turn contradicts. subagentErrorResumeHint promised "continue where it left off", but resumeStalenessNote greets the resumed child with "file changes … from your earlier run are GONE" — its worktree was torn down and the resume gets a fresh fork. A parent reading only "where it left off" can re-delegate a follow-up that assumes half-written files survived. The hint now states what carries over and what does not: conversation preserved, WORKSPACE not (it ran in a throwaway checkout). The claim is about the FAILED child's dead worktree, so it holds BOTH ways — a read-only resume (fresh fork) or an upgrade to mode:"read-write" (the real parent tree, still not the dead worktree). The oracle is the PAIRING with resumeStalenessNote rather than one string, so the two cannot drift apart into a contradiction the model has to arbitrate. The per-call TIME-BUDGET terminal was the LAST failure path with no next action. A timed-out child lands StateCancelled, which resolveResumeSession has always recovered, so after #318 taught the model that every other bad terminal is recoverable the silence read as "this delegation is dead" rather than as honesty. It gains one through a new subagentTimeoutNote(writable, resumable) gate mirroring subagentResumeHint's four cells, used by BOTH call sites (foreground finishForegroundRun, background driveBackground). The wording is its OWN rather than a StopError reuse for two reasons: the child ran out of CLOCK, not competence (so "if the failure looks transient" would misdescribe it), and the fix has a nameable knob — a larger `timeout_ms`. The writable arm gets the single combined resume-or-discard decision for the identical reason writableSubagentFailedNote exists (two independent imperatives let a model discard the edits and THEN resume a child told they are "STILL IN PLACE"); a store-less deployment keeps today's rendering, since validateResume's first precondition is a wired store and advertising a refused action is the same defect. recoveredDigestPrefix and the StopNoProgress note duplicated "treat as partial; resume it with the agentId above to continue" BYTE-FOR-BYTE, rendered one after the other. The repo's rule is that the stop reason is stated in exactly ONE place; the next action is worse to duplicate — a model reading one imperative twice, in two framings, cannot tell it from two. The prefix keeps provenance + partial-ness only. It still reads coherently standalone on the note-less empty-StopEndTurn path (the documented requirement): that terminal is a BENIGN clean end and owes no next action, and the agentId trailer is on the result regardless, so resuming stays available where it is not advertised. OPERATOR CORRELATION Both llmresilience Info lines now carry "model". Without it an operator on a busy mecated learns that *a* turn died, not whose. That is the finest correlation reachable and the honest limit: the wrapper is a provider DECORATOR handed only (ctx, port.LLMRequest) and holds no session/run identity — the loop binds .With("session", …) inside Engine.RunContent, below the provider port — so a session id would mean widening port.LLMRequest, which must stay provider-neutral. Not done. The mid-stream site had no request in scope, so the model threads Stream -> establish -> pullToCommit -> restSeq -> logMidStreamError as a plain string; BOTH restSeq variants carry it, so disabling the idle watchdog cannot leave that path uncorrelated. REMOVING --log-level (added in fd018f1, taken back out here) Decided on merit, not on the fact that it was already built. It was never needed for Info-level TERMINAL lines added in the same commit answer that at the DEFAULT floor on every binary with no flag. The Debug retry lines it existed to reach answer a DIFFERENT question — a slow or retrying provider — which is a properly-scoped change of its own if it is ever wanted. Against that it was permanent operator surface at every composition root (help text, docs, tests, support) and carried a real privacy footgun: a debug floor also admits any third-party dependency's debug output into mecatui's plaintext 0700 log file. The disclosure clause the review round asked for was mitigating a hazard the flag itself introduced, which is evidence against the flag rather than a fix for it. The repo's stated preference settles it — the cheapest abstraction is the one you don't write yet. So cmd/mecatui/{config.go,diaglog.go,diaglog_test.go,main.go} return to their pre-fd018f1f content (verified by diff that the flag was their ONLY change across this branch), every sink is hardcoded at its Info/port.LevelInfo floor again, and docs/tui.md loses the flag row and prose. A mecated counterpart was deliberately NOT added; the standards reviewer's headline on that NOTE was that the flag is scope creep past effect: `git diff origin/main` contains no log-level flag anywhere, and neither --help does. docs/tui.md instead gains a short knob-free note that the two terminal stream paths log at info, so the #319 diagnosis needs nothing but that file, and IMPLEMENTATION-NOTES records the DECISION in place of the removed mechanics — that the Debug retry lines stay Debug and there is deliberately no operator severity knob, with the reasoning above — so a future reader hits the answer instead of re-deriving it. That paragraph names no flag: the reusable part is the reasoning, not the reverted code. SMALLER subagentErrorBody clamped `final` with maxTeamPreview, so the one place that composes the StopError body read as borrowing the team tool's constant; it now uses a subagent-named maxSubagentFinalPreview (200 by DESIGN, not by dependence — either bound can move without dragging the other). driveChild's doc-comment gains the trip-wire the reviewers asked be RECORDED rather than acted on: a SIXTH value on the child-outcome return chain is the point to extract a childOutcome struct, not before, mirroring the same named trip-wire the three delegation-event families carry. NOT changed, as reviewed: no childOutcome type extracted (two reviewers, independently); Cause-vs-Error naming and the mid-struct field placement; the deliberate exclusion of the resume hint from the Parallel path. TESTS, each mutation-checked by editing the production line, ASSERTING the patch applied (an unmatched edit leaves a green test masquerading as a guard) and watching it fail: the hint reverted to "continue where it left off"; the timeout note dropped at the foreground site and, separately, at the background one; the writable+resumable arm collapsed to the plain partial note; the store-less gate widened to advertise a refused resume; the digest prefix's duplicated clause restored; the `final` clamp removed; and the model arg blanked on each of the two llmresilience lines (the mid-stream one failing in both restSeq subtests). Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…its tolerance TestRunMemoryBudgetSingleHugeValue failed under a loaded parallel `-race` suite and passed in isolation and on a re-run. It asserted `elapsed <= 2*time.Second`, so the obvious read is "the tolerance is too tight". Reproducing it under 13x CPU oversubscription showed the tolerance was the SYMPTOM, and that simply widening it would have left a guard that no longer guarded. WHAT IT ACTUALLY VERIFIES. Run has THREE bounds that can end `[range(1e9)]`, and the invariant is that the heap WATCHDOG is the one that does — because the output cap can only catch a single giant value AFTER the memory has already been allocated, which is the whole CWE-770/400 point. Each alternative surfaces a distinct, nameable error, so the honest oracle is the error's IDENTITY: memory-budget (wanted), "timed out" (wrapping context.DeadlineExceeded), or "output exceeded". No timing needed. WHY IT WAS FLAKY, both layers. (1) The wall-clock assertion was a LATENCY BUDGET, not the invariant. Deleted. The error-identity assertions prove which limiter fired with nothing load-sensitive in them, and the deadline negative is now the typed errors.Is(context.DeadlineExceeded) rather than a substring — only that branch wraps the ctx error. (2) The deeper one, and the reason widening 2s to 5s would not have been enough: measured under load, the run reached DefaultTimeout and reported "timed out" — the watchdog genuinely had not tripped. Its trip point sat at ~5% of the work (8 MiB of a ~160 MiB materialization), so under starvation the other 95% could finish first. With a longer deadline the same shape reappears one bound further out as an "output exceeded" overrun, because Run returns on the output cap BEFORE its post-loop overBudget check — so a late-tripping watchdog is reported as an output-cap overrun, which is precisely the distinction this test exists to pin. THE FIX moves the trip point to under 1% of the materialization (budget 1 MiB), which leaves the sampler the other 99% to observe it. That STRENGTHENS the guard rather than weakening it — a smaller budget makes the watchdog strictly harder to satisfy by accident, and the budget was always a test-only knob (withTinyBudget). The filter is bounded to `[range(1e6)]` and the deadline made explicit and generous (60s); those two go together, since a bounded N caps a REGRESSED watchdog's blast radius at ~160 MiB of transient allocation, and that is what makes a long deadline safe. Under `[range(1e9)]` the 5s deadline WAS the only backstop, so it could not be relaxed without risking an OOM — that coupling is why the original had to race its own timeout. 1e6 is still ~160x the budget, so the memory-amplifier premise is intact. The "output exceeded" arm is now asserted against explicitly, so a late trip fails with the reason named instead of being silently accepted. The false-trip sibling deliberately KEEPS its 8 MiB budget: that guard is strictest at the budget closest to a real filter's footprint, whereas its neighbour lowered its own to make a genuine trip easier to observe. VERIFIED, not assumed. 30/30 clean at 1 MiB under 13x CPU oversubscription where 8 MiB flaked (2-3 in 20, as both a deadline and an output-cap overrun), then 25 more clean runs of the committed form under the same load. Mutation-checked both directions with the patch application asserted: raising the effective threshold 1024x (the watchdog never trips) and dropping the cancel() after over.Store(true) (it trips but too late) each fail with "the OUTPUT CAP stopped it", in ~8s, without OOM or hang. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…p the duplicates
Closes the review panel's findings on the failure-terminal / failed-resume work.
SHIP-BLOCKER. writableSubagentFailedNote and writableSubagentTimeoutNote both said
"resume it with the agentId … to finish on top of them" and named `mode` ZERO times.
`writable` comes only from the CURRENT call (validateMode) — run() never infers it
from the loaded session — so the obvious follow-up, Subagent{resume: id, prompt:
"finish it"}, comes back as the READ-ONLY explorer: no Edit/Write, a fresh worktree
fork off committed HEAD (the partial edits are not even visible to it), and
resumeStalenessNote telling the child its changes are GONE. The operator's real tree
keeps the half-finished work while the model believes the job closed — on the most
expensive failure path in the tool. Both notes now name mode:"read-write" as part of
the resume clause.
The `resume` SCHEMA stated the same falsehood unconditionally ("EXCEPT with
mode:'read-write', which continues directly in your real workspace, where the edits it
already made are still in place") — the exact inverse editsSurvived exists to prevent,
and it is what a model reads BEFORE delegating. It now conditions on the EARLIER run
and states the read-only default as mode-independent.
FENCE DISCIPLINE (one pass, three sites). Neither half of subagentErrorBody's input is
harness-authored: `cause` is the provider/transport error VERBATIM (the anthropic
adapter returns the upstream error.message unquoted, so real newlines survive) and
`final` is child-authored prose — and both land in the parent's persisted conversation
immediately beside the harness's own imperatives (the agentId trailer the model resumes
by, the resume hint). Both now go through NeutraliseFraming in that ONE composer, and
framingHeader gained the headers this result emits plus retryTurnNote's "NOTE FROM THE
HARNESS:" (whose own doc says to extend it for any new model-visible header).
writeTeamStatus likewise neutralises the member NAMES it splices into the TRUSTED,
unfenced "Team status:" region — they come from the parent model's Team call args and
validateTeamArgs bounds only non-empty/unique/role. CWE-1427 / OWASP LLM01.
ACCURACY. MemberOutcome.ErrorRounds claimed "a member benched for cancellation or
budget has 0"; the counter is a MONOTONIC lifetime count (that monotonicity is the
retry cap's termination proof), so a member that failed round 1, was retried, and was
cancelled in round 2 reports Reason "cancelled" with ErrorRounds 1. Restated
independently of the terminal on both the outcome and its wire mirror.
REUSE (the axis's own list). subagentResumeHint's `writable` parameter was a dead
branch — every writable=true input returned "" and the only such call site was the
writable renderer, which now passes the literal "". handleChildEvent is back to three
values: drainChildObserved reads the cause off ev.Result beside Usage, which keeps a
second transposable text/cause pair off the trip-wire chain and drops the `_` at the
supervisor call site. maxSubagentFinalPreview is gone in favour of maxTeamPreview —
digestChildActivity one function away already bounds the same content class with it.
The per-call time-budget terminal, built verbatim at two sites, is now one
timeoutResult method (the sites' own comments worried about exactly this drift). The
whitespace collapse of SubagentPayload.Cause moved into the emit chokepoint
(subagentCausePayload) so its three line-oriented consumers just render; the TUI keeps
its own idempotent oneLine because it is a gRPC client and must not depend on the
peer's version for a display bound — and it now uses the package helper instead of
shadowing it.
ARCHITECTURE. "resume is supported in this deployment" was an unnamed predicate read
inline at five sites and owned at a sixth; it is now t.resumeSupported(), so the
never-advertise-a-resume-validateResume-will-refuse contract has one home.
TESTS. Every change above has an oracle that was mutation-verified to fail on the
production line, and three pre-existing gaps are closed:
- subagentGenericResumeHintFragment had gone STALE inside this branch ("continue where
it left off" was removed from the hint), so the suppression check could never fire.
It is re-pointed at the live wording AND paired with a POSITIVE CONTROL that fails
loudly if the wording moves again.
- setTeamEnd's `ln.errorRounds = d.ErrorRounds` had no oracle at all: deleting it left
the suite green while the overlay rendered a bare "done" for a retried member.
- the retry gate's !budgetExhausted conjunct, the retry path's
SetMemberState(MemberIdle), WithMemberErrorRetries(-1), a background StopError's
resume hint, and mecademo's cause= branch were all untested; the cancelled-member
oracle's headline assertion was unfalsifiable and now asserts the team AGGREGATE
state and the provider call count.
Refs #319 #318
Co-Authored-By: Claude Opus 5 <[email protected]>
…or cancel a failure Two accuracy holes in the same file the #319 diagnosis widened. An OPEN circuit breaker rejects the request before the provider is ever called, which ends the turn terminally — and it logged at NO level. That is the third instance of the exact defect #319 is about, whose acceptance is that no terminal stream failure ends a turn without at least one Info-level diagnostic: an operator reading the log saw the turn die with nothing in it, on the one path where there is not even a provider interaction to correlate against. It now emits the Info line with the same `model` correlation its siblings carry. logMidStreamError fired for context.Canceled too, so an operator's own ctrl+c (or a client disconnect) — the single most common way a turn ends early — was reported as "llm stream failed mid-stream", sending them hunting a provider problem that never existed. Same class as the "denied by user" message that was never a user's decision. A cancellation is now logged AS a cancellation, without the err= arg that made it read as a diagnosable fault; a genuine provider fault keeps the failure wording and its err=. Consistency: the other two terminal paths (establishment exhausted, idle stall) now carry `model` as well, and the exhaustion line carries the last attempt's err — an operator who has learned to grep by model was getting two of the four ways a turn dies. The mid-stream cancellation test is rewritten to pin the accurate wording rather than the old breadth, with a provider-fault control in the same test so it cannot pass on a build that labelled every terminal a cancellation. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…r retry to operators SHIP-BLOCKER. engine/CHANGELOG.md's `### Changed` entry asserted the opposite of what ships: "MemberOutcome.Stopped/Reason are unchanged (a failed round still deschedules the member)". True at the recovery commit, FALSE after the bounded retry — a retried member finishes Stopped == false / DispositionDone / Reason == "". COMPATIBILITY.md tells consumers `Changed` == breaking, so the section they grep for upgrade risk misinformed them and the [Unreleased] block contradicted its own `### Added` entry. Corrected and cross-referenced. The retry entry's lever was also over-claimed twice. WithMemberErrorRetries(0) restores the SCHEDULING half only — the session is still RECOVERED rather than latched nonResumable, so a failed lead runs its synthesis turn either way. And it is a LIBRARY option: a mecated/mecatui/mecak8s operator cannot reach it, so naming it as "the lever" told the wrong audience. Both scoped, and "pre-amendment" replaced with release-relative phrasing throughout (a consumer cannot pin an un-released state). THE MISSING OPERATOR DISCLOSURE. The retry is on by default and spends real tokens, and nothing an operator reads mentioned it. There is deliberately NO per-member flag: the repo's line is that team-wide RESOURCE ceilings get operator flags while per-member BEHAVIOURAL bounds stay engine-only defaults, and the precedent is the sibling WithMemberTurnBudget (default 200 turns/member), which is likewise unwired at every composition root — verified: no MemberTurnBudget reference exists outside engine/, and the only team option composition wires is WithTeamToolTokenBudget(cfg.MaxTeamTokens). So the fix is disclosure, not surface: docs/usage/mecated.md's delegation note and the CHANGELOG entry now state the behaviour, name the exposure exactly, and point at the ceilings that DO bind an operator (--max-team-tokens team-wide, --max-run-tokens per member drive) plus the built-in round cap and per-member turn budget. The magnitude is stated precisely in all three places, because "cap+1" alone reads as unbounded: the counter is per-member and NEVER reset, so at the default cap of 1 the exposure is ONE extra scheduled round per member over the whole team run — not one per failure — i.e. a permanently-failing member runs 2 rounds instead of 1. ADR 0077 was amended IN PLACE after acceptance — the only `## Amendment` in 77 ADRs, against a template that says the supersede pointer is the only post-acceptance edit. It has never landed on main, so freezing plausibly attaches at merge. The amendment is folded into Decision + Consequences (as "The team member's bounded retry", with the open bullet it closed replaced by the costs it actually carries, including the no-flag decision and what that choice costs) and the section deleted, so main receives ONE coherent frozen record instead of one that contradicts then corrects itself. Every in-code and doc reference to "the amendment" is updated to cite the ADR. Also recorded in that Decision, since all three ship model-facing wording no record covered: the per-call time-budget terminal's next-action family, why both writable notes name mode:"read-write", and the framing-neutralisation of the failure body. docs/architecture/subagents-and-teams.md was a HALF-APPLIED edit — corrected at one place while still asserting at another that `failed` is "not resumable (a deliberate subagent-policy fence)" and describing the resume note unconditionally. docs/lint cannot catch a false claim; both passages now describe the shipped behaviour, including why the edits-survived note keys on the EARLIER run. docs/tui.md named all four terminal log paths (it claimed two) and now says outright that no flag, env, or config key lowers the floor to `debug` — otherwise a reader goes looking for the switch that the --log-level removal took away. One in-code doc-comment reference is corrected with them: subagentErrorResumeHint cited the raw `t.store != nil` expression the resumeSupported() extraction replaced. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
… not a fresh checkout The resumed child's harness note is a function of TWO independent axes — WHERE it runs (THIS call's mode) and WHAT the earlier run left behind (editsSurvived) — and two notes covered three reachable cells. The missing cell is the dangerous one: a previously READ-ONLY child resumed with mode:"read-write" got resumeStalenessNote, "you are running in a FRESH workspace checkout … file changes are GONE", while prepareChildSession had passed forker=nil and handed it Edit/Write on the operator's REAL repository. A child that believes it is in a scratch checkout may rewrite or delete files to "start clean", and those deletions land in the working tree. The panel-2 fix actively routes traffic into that cell: both writable notes now tell the parent to resume AND pass mode:"read-write". resumePosture.note() enumerates the space in one place with three arms and no fall-through, and the new resumeWritableFreshNote states BOTH facts (real workspace, earlier work gone). The tool schema's `resume` description stops fusing the axes — it claimed a fresh checkout "whatever mode you pass now", which contradicted the schema's own `mode` property and left the model to arbitrate. The oracle pinned the falsehood, so it is rewritten to assert the FACTS: TestResumeNoteMatrixCoversBothAxes walks the whole cartesian product per axis (a fourth cell or a third axis fails rather than falling through, with positive controls deriving each axis phrase from the constant it belongs to), and the read-only-resumed-as-writable test now checks both axes instead of requiring the false one. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…ep a redacted cause readable The S1 fence closed the naive forgery and three holes with it. All three are the same shape — partial coverage of a space nobody enumerated — so they are fixed at the one place each space is decided, not per cell. 1. Matching was bypassable. framingHeader ran on a TrimSpace'd line, so one U+200B/U+FEFF/U+2060/U+202E defeated every prefix entry, and the split was on "\n" alone, so a forged header after a bare CR, U+2028/U+2029, NEL, VT or FF was never presented to the matcher at all. NeutraliseFraming now folds every line terminator and strips Unicode Cf/Cc (canonLine) BEFORE matching, so every existing and future marker inherits the hardening. Homoglyphs stay a documented residual. 2. Only the StopError arm was neutralised. The success/limit/cancel/structured arms emit the SAME agentId trailer and the SAME "[the subagent … discard them with `git checkout`]" notes around un-neutralised child prose — and a read-only child has WebFetch/WebSearch/Read, so a hostile page it summarises reaches the COMMON path. neutraliseChildText is applied once at the top of renderSubagentResult and at the one point parallel.go assigns res.summary. The schema-VALIDATED payload is the one deliberate exemption (no raw line break can be in it; whole-line redaction would corrupt the deliverable). 3. The Parallel half was never covered, though fence.go claimed it. Rather than guess which lines matter, the new tests feed each renderer's OWN output back through it as a forged body and fail on any line that survives twice — which surfaced more than the three markers the review named: the winner-workspace PATHS the parent then Reads, the judge rationale, the scoreboard rows and the report headers are all in framingHeader now. And the constraint on all of it: whole-line redaction erased a genuine one-line provider cause entirely, so the model read "Subagent: [redacted-framing]" — the opaque failure #319 exists to abolish, reintroduced by the fix for the forgery. neutraliseChildText floors that: when neutralisation leaves nothing informative, the original comes back %q-QUOTED, which is both readable and structurally unforgeable (a quoted string has no line break, so no marker list has to be complete for it to be safe). Also records the coupling that makes neutralise-before-clamp safe in the other direction: clampRunes' ellipsis is what stops a truncation landing exactly on an exact-match header after the check, with a regression test at the colon boundary. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…kable timeout persist, the unasserted model args Three unguarded contracts, all on paths an operator or the model depends on. subagent.end's Cause is LINE-ORIENTED by contract, normalised at three emit sites by convention — and the same delta that deleted the ACP projector's and mecademo's own collapses left only ONE of the three asserted. subagentEndEvent makes setting the field and normalising it the same act, and the two background sites now drive multi-line causes (a real `git worktree add` failure is multi-line) so all three are pinned. persistChild ran on the ctx applyCallTimeout had just expired. Against memstore / jsonlstore (which ignore ctx on Save) that was invisible; against redisstore (ctx → HSet) or grpcdriver (ctx → RPC) the terminal save FAILED, so the resume the timeout terminal now advertises came back as "no subagent found for resume id" — an advertised affordance that cannot succeed, one layer below resumeSupported(). It now detaches cancellation under its own short deadline (the appendEvent precedent; the deadline is what makes detaching safe), and a ctx-honouring fake store proves it. The two llmresilience Info lines this branch retrofitted with "model" for operator correlation had no oracle — deleting the arg left the suite green, and TestResilienceLogsExhaustion could not even express the assertion because it passed an empty LLMRequest. Both now assert it, plus the exhaustion line's `err` (the only clue to WHY establishment never succeeded). The "FOURTH terminal path" comments under-counted: there are five, and the fifth is the idle stall — the shape operators actually report. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…ims to provide
The subagent failure line's collapse exists ONLY for a version-skewed peer — the
current server already normalises the field — and its comment says so: the TUI is a
gRPC client and must not depend on the peer's version for a display bound. The same
edit that wrote that rationale down swapped strings.Fields for the package oneLine
helper, which splits on {\n, \r, \t} only, so against an older mecated runs of
spaces, NBSP and U+2028/U+2029 stopped collapsing. Against a current peer the two
are indistinguishable, which is why nothing caught it; the new test uses the
whitespace kinds only IsSpace covers.
Refs #319
Co-Authored-By: Claude Opus 5 <[email protected]>
…not make The fold left the reversed claim standing in the two highest-authority copies: ADR 0077's Decision section and the doc-comment on runTurn that cites the ADR as its authority. Both said `stopped` "is unchanged — a member whose round errored is still descheduled and still reports StopReasonError", 14 lines above the production `if` that reverses it for any member under the retry cap. Both now scope the claim to the BENCHED end state and point at the retry block. Also: - "Every failure terminal now names a next action" was sweeping: StopStructuredOutput still names none, deliberately (a resume would need the same output_schema passed again). The claim is scoped and the reason stated. For a DIRECT-WRITE child that terminal at least stops wearing the benign clean-finish note — a child that never delivered a valid payload did not finish cleanly. - The operator disclosure narrowed the member retry to "a transient provider error"; runTurn keys on stop == StopError alone and has no transient/permanent classifier at that seam, so a permanent 400 is retried too and re-fails. An operator budgeting worst-case spend from that paragraph under-counted the case that always costs the extra round. - "No per-member flag" implied a global one might exist: there is no flag or config key in any binary, so it now says that and names --max-team-tokens as the brake. --max-run-tokens was described as per-drive; it lives on the member's session and resetToIdle preserves Usage, so it is a CUMULATIVE per-member ceiling and binds tighter than described. - docs/tui.md counted "ALL FOUR" Info-level terminal paths; there are five, and the missing one is the mid-stream idle stall — the "thinking, then nothing" shape operators actually report. The resume-note and neutralisation records are updated to the three-cell matrix and the every-arm scope this branch now implements, and maxTeamPreview's doc-comment names its two model-facing subagent consumers (tuning it for a team-event reason also moves the clamp on the body that lands in the parent's persisted conversation). Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…scope the writable-resume caution
StopStructuredOutput was the last delegation terminal that named a cause and no
action: the model read "did not produce output matching the requested schema:
<validation error>" plus the agentId and nothing about what to do, while every
neighbour (StopError, the limit stops, StopNoProgress, the time-budget stop, even
the no-summary floor) names one. The reason recorded for leaving it bare — that a
resume "would need the same output_schema passed again" — was not an obstacle:
validateResume rejects only agent/model, buildSubagentRunOptions builds the submit
tool from args.OutputSchema unconditionally, and the schema is the parent's own
argument. The genuine caveat is weaker and different, so the resume is offered
SECOND, behind fixing the schema or the instruction, and says so.
structuredOutputNote gates on the same `resumable` signal subagentResumeHint and
subagentTimeoutNote use, so a store-less deployment still gets a next action (the
fix-and-re-delegate half needs no affordance) without advertising a resume
validateResume would refuse. Both notes open with "[the subagent " so a forged
copy is already redactable.
resumeWritableFreshNote loses two things it should not have said, both of the
class this branch keeps closing — it is a TRUSTED harness instruction to a child
holding Edit/Write on the operator's real tree:
- "do not delete or rewrite files to start clean" is broader than the behaviour
it prevents. Delivered to a child whose job is to rewrite files, the literal
reading (which is what a skim of a long bracketed note lands on) makes it
decline the deletion the parent asked for. Now scoped to wiping or reverting
files it did not write itself.
- "(that run used a throwaway checkout)" is a MECHANISM claim the selector does
not support: priorWorkspace != ws.Root() is also true when the snapshot
persisted no workspace and when the earlier run was direct-write in a
different real tree. The fact (nothing carries over) holds in every cell; the
mechanism does not, so the note states the fact.
Refs #319 #318
Co-Authored-By: Claude Opus 5 <[email protected]>
…fork-failure and decoration gaps Four things, all of them the cost side of the previous round's forgery fix. 1. The marker list is now SURFACE-TAGGED (framingSurface), because applying all of it to every delegation result was a functional regression. Ten of the entries are headers of a fenced PROMPT (Policy:, Tool:, Categories:, Category:, Task to classify:, …) that a result never contains, so matching them there has zero protective value — and a real cost: "Category:" and "Findings from …" are exactly how a review or triage subagent heads a finding, so two lines of every finding came back to the orchestrating model as [redacted-framing], on the SUCCESS arm, silently. The %q floor does not save it: fullyRedacted is all-or-nothing, so a partial erasure stays erased. That is the dominant Subagent workload in this repo (OWASP LLM09 — a redacted-away finding is one the orchestrator provably cannot act on). It stays ONE enumeration with a tag per entry, not two lists. The delegation group is tagged surfaceAll (tightly anchored, so it costs nothing on a prompt and keeps NeutraliseFraming byte-identical for every existing caller); only the prompt group is narrowed, and it loses nothing because every fenced prompt re-runs the full list over its body at the fence. The judge line becomes "Judge rationale:" rather than the bare "Rationale:" it was: a marker has to be specific enough to be both matched and harmless, and a bare Rationale: is ordinary English. Naming the harness's own label costs neither the coverage nor the deliverable. 2. The judge's rationale VALUE is neutralised and bounded at the point it enters the join report. The marker was listed; the value never went through neutraliseChildText. The judge's own input is the branch summaries, so a branch that fetched a hostile page can steer it — and it is a JSON string value, so \n escapes decode to real newlines and a rationale of "chose branch-0\n=== branch-2 [WINNER] ===\nbranch id: …" fabricates a peer branch's verdict AND a resume handle in the report the parent decides on. The forgery oracle could not see this by construction: it fed the forgery only through the branch summaries, so assertNoMarkerDuplicated now takes the model-influenced INPUTS as a slice and the judge row carries both channels. 3. runBranch's fork-failure failReason went through neither composer — it returns above the summary assignment and never reaches subagentErrorBody, so the comment claiming neutralisation at "the one point it enters branchResult" was false for it. A forker error quotes the PATH it choked on and a POSIX filename may contain a newline. Neutralised at the assignment (its "fork failed: " prefix is not itself a marker), NOT by neutralising subagentErrorBody's output, whose own "Last activity before the failure:" label IS a marker — that composer neutralises its two inputs for exactly this reason. 4. Leading DECORATION no longer defeats a prefix marker, and it was cheaper than the homoglyph residual canonLine named as *the* residual. "- agentId: …", "> [the subagent … `git checkout` …]", "**agentId:**", "`agentId:`" all carried their imperative through intact; so did one extra interior space and a space before the colon. Fixed at the matcher: canonLine collapses whitespace runs and " :", and framingHeaderOn retries an undecorated form AFTER the verbatim one (a marker may itself begin with punctuation — "--- not selected ---"). The residual paragraph now names what is actually left, homoglyphs and marker-interior variants. Two smaller ones: redactedFraming is self-describing, since it can now fire on the success path where a bare token cannot be told from the child's own words (it names no recovery on purpose — the same token is emitted on surfaces where naming InspectSubagent would be false); and the %q floor no longer hands back the UntrustedFence delimiter it inherited a substitution for. The tags are pinned by TestFramingSurfaceTagsArePinned, deliberately as an explicit list: the self-forgery oracles derive their cases from what the matcher MATCHES, so a deleted entry deletes its own case and they pass vacuously. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
The delta that hardened the engine matcher against Unicode Cf (zero-width, BOM, bidi override/isolate) did not carry the lesson to the client-side display bound changed in the same round. strings.Fields collapses everything unicode.IsSpace considers whitespace, which is not the same set: U+200B, U+FEFF and U+202E are Cf, so the collapse leaves them in place, and sanitizeTerminal stripped C0/C1/ESC/DEL but not Cf. A provider cause or child summary carrying an RTL override therefore reorders the rendered failure line — on the pane whose whole job is telling the operator what went wrong (CWE-1007). Display-only: no capability is gained either way, which is why this is one predicate and not a policy. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
…agnostic ledger ADR 0077 recorded StopStructuredOutput as the one terminal deliberately naming no next action, justified by "a resume would need the same output_schema passed again". That justification is wrong — resume composes with output_schema — and a future reader would take it as settled, so both the claim and the behaviour it excused are corrected here. The fence section also records the two mistakes the first cut of the forgery fix made (one flat marker list applied to every surface; an oracle that enumerated the renderers' body channels but not their model-influenced parameters), because those are the reusable half. llmresilience carried two code comments that contradicted each other about the pre-#319 state: one said exhausted attempts and the idle stall "logged at NO level", the other said the recoverable half including the breaker "was fully observable". Both are wrong, and the truth is checkable against the merge base: already Info-logged were exhaustion, the idle stall and the breaker's own state TRANSITIONS (plus the retry at Debug); silent were exactly three — the breaker REJECTION, the non-retryable establishment error and the mid-stream error. All three now log. The ledger is stated once, at logMidStreamError, and the two other sites point at it instead of paraphrasing it differently. Refs #319 #318 Co-Authored-By: Claude Opus 5 <[email protected]>
Four follow-ups from rebasing onto the delegation-observability-convergence merge (main's #327): - Subagent.cause moves to proto field 17 (14–16 are ADR 0079's inner_kind/text/detail) — regenerated harness.pb.go via task generate. - The ADR-0079 structural sentinel allow-list gains Cause with its gauntlet-#7 justification (engine/agent/delegation_observability_test.go). - The focus pane's bounded-previews honesty note is width-wrapped like the failure line (indentWrap over cardTextWidth) — unwrapped it set the card to 96 cols and overflowed an 80-col viewport, caught by TestSubagentFocusPaneWithLongCauseFitsViewport. - docs/adr/0077-resume-a-failed-subagent.md cited the direct-write ADR as 0041; on main that number is output-economy and the direct-write record is ADR 0077 — two links retargeted (matlatl strict). Co-Authored-By: Claude Code <[email protected]>
JAORMX
force-pushed
the
fix/subagent-failure-cause-and-resume
branch
from
August 1, 2026 11:11
fef3e85 to
d45d470
Compare
…turn Panel-review round 5 (the fix-verification audit) independently surfaced the one #319 shape still showing the child's last text AS the failure: a turn that ends on a terminal stop CHUNK (Anthropic max_tokens / refusal, mapped to StopError with NO Go error) AFTER the child streamed visible text routes through finishTurnNoTools → terminateComplete, which emitted an EMPTY ResultPayload.Error. subagentErrorBody then fell through to rendering the truncated/refused text as the error body — the exact #319 presentation on the terminateComplete path (the empty-turn shape already took terminate with a cause; OpenAI's incomplete/failed return a Go error and were never affected). terminateComplete gains an internal errMsg parameter and the loop synthesises the cause via stopTerminalCause (StopError-only, harness-authored, honouring the SubagentPayload.Cause 'empty on every other terminal' contract). The synthesised reason names the terminal stop and flags the text as TRUNCATED or refused; the partial text is demoted to labelled 'Last activity' context. Also corrects the IMPLEMENTATION-NOTES Subagent.cause field reference (14 → 17; 14–16 are ADR 0079's previews), caught by the Standards axis. Red-then-green: TestSubagentTruncatedTurnStillSurfacesAReason. Co-Authored-By: Claude Code <[email protected]>
This was referenced Aug 1, 2026
The ADR-0079 follow-up (b2c3c62) applied neutraliseChildText to EVERY delegation-result arm, which is correct (CWE-1427/LLM01) but regressed the two delegation scenarios on the perf gate: background_subagents 1505→1605 allocs/op, team_fanout 2467→2576. The cost was not the security work — it was running two Replacer passes + a Split + a Join + per-line canonLine/ToLower on every clean child result, where there is provably nothing to redact. Add an allocation-free candidate gate (lineMayBeHeader) plus a whole-string fast path: when the body has no fence, no fold-worthy line break / Cf/Cc code point, and no marker-candidate line, return it verbatim — the common case costs a few scans, not the full normalisation. The slow path is byte-for-byte unchanged and still runs for any line the gate cannot rule out. Correctness is the whole game on a security boundary, so the gate is conservative and the guards are non-vacuous (both mutation-tested): - TestLineMayBeHeaderNeverDropsAMarker — every marker (mixed-case, decorated, lower-cased) is admitted; ordinary prose is rejected. - TestNeutraliseFastPathIsByteIdentical — differential vs the reference slow path across clean/marker/perturbed/exotic-terminator/invisible inputs. - The pre-existing invisible-char and ordered-list oracles caught two real gate bugs (a leading Cf/Cc and a digit-led ordered-list line must reach the slow path) before this shipped. Result: team_fanout 2430 allocs/op (under main's 2467), background_subagents ~1548 (vs main 1508 — residual is diffuse pre-existing branch code, not the neutraliser, which no longer appears in the profile). Co-Authored-By: Claude Code <[email protected]>
…lint budget gocyclo flagged lineMayBeHeader at 21 (>20). Extract the conservative-admit checks (decoration / whitespace / invisible-char / digit-led) into lineNeedsFullScan, and switch IndexAny to ContainsAny per staticcheck S1003. No behaviour change — the security oracles and the perf win are unchanged. Co-Authored-By: Claude Code <[email protected]>
8349d0b made persistChild unconditionally cancel-detached (WithoutCancel + WithTimeout) so a Redis/remote-driver save survives the expired ctx on the timeout/cancel terminals. Correct, but it allocates two context objects on EVERY save — including the common persist on a still-live ctx, which is what the background_subagents perf scenario hammers (1505→1588 allocs/op, the remaining perf-gate regression after the neutraliser fix). Detach only when ctx.Err() != nil — i.e. exactly the terminals the change was FOR (timeout_ms fired / parent cancelled). A live-ctx persist takes the plain Save with zero allocation. The ctx-honouring-store test (TestTimedOutSubagentIsPersistedDespiteTheExpiredContext) still proves the detach fires on the expired ctx, and the scenario drops back to ~1506 allocs/op (at/under main's 1508 baseline). Co-Authored-By: Claude Code <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #319. Closes #318.
Diagnosed from two production failures in
mecatui: amode:"read-write"subagent onz-ai/glm-5.2died after ~15 minutes and ~5M tokens, and the model-facing error wasSubagent: Now let me check the ListPluginsRow structure…— the child's last chat line, not an error. Both parents then triedresume:and were refused, stranding partial edits already applied to the real tree.#319 — the failure cause was dropped four times
Engine.terminatecorrectly puts the cause onsession.ResultPayload.Error. ThenhandleChildEventnever read it;renderSubagentResultrendered the child'slastTextas the error;SubagentPayloadhad no cause field, sosubagent.endand the TUI card could only showstop:error; and child runs are never relayed, so nothing reached the durable log.parallel.go'sfailReasonhad the identical bug.Separately,
llmresiliencelogged its recoverable lifecycle at Info (retry-exhaustion, idle stall, breaker) while the paths that end a turn terminally logged at no level at all. That asymmetry is why the failing session's log went silent — and it let us eliminate stall/exhaustion/breaker as causes after the fact.Fixed by threading the cause into one composer,
SubagentPayload.Cause(proto field 14 → mapper → ACP projector → mecatui card), and Info diagnostics on all five terminal stream paths withmodelcorrelation.#318 — a transient failure bricked the child permanently
resolveResumeSessionhard-refusedStateFailed, justified by "a failed child carries no accumulated-user-context cost". The evidence falsified that: 50+ turns plus mutations already applied to the real tree.session.Session.Recover()already existed, already did the rightcloseOutInterruptedTurnrepair, and its own doc-comment named this exact scenario — it just wasn't wired to children.The sharpest detail: a per-call
timeout_msexpiry cancels the run ctx →StateCancelled→ already resumable, while a stream stall doesn't cancel it and becameStateFailed→ permanently dead. A network hiccup was punished harder than an operator-configured timeout.Fixed at both sites. The team supervisor keys on
m.sess.State, notstop— a text-bearing turn with a terminalStopErrorchunk goes throughterminateCompleteintoStateCompleted, so keying onstopwould have calledRecover()on a completed session and marked a drivable member non-resumable.ErrorRoundsdelivers the last acceptance bullet (a member surviving one transient stall) via bounded retry + task release + a one-shot force-schedule. That last piece is load-bearing:planRoundonly schedules a member with a drained message or claimable task, so a member that stalls on its round-0 exploration turn would have been "schedulable" and never scheduled — the fix would have been vacuous for the reported case.Recorded in ADR 0077.
Reviewed in four rounds
The recurring defect was prose, not logic: nine instances of "the text says something the code doesn't do." Three were introduced by fixes for the previous three, because each fix patched one cell of a state space nobody had enumerated. Two of them were dangerous rather than merely wrong:
mode:"read-write"silently got a read-only explorer in a fresh fork while the operator's tree kept the half-finished edits, and the note told it to "finish on top of them";mode:"read-write"was told it was in a "FRESH workspace checkout" while holding Edit/Write on the real repository — so it might delete files to "start clean".Round 3 stopped patching cells and enumerated the spaces instead:
resumePosture.note()switchframingHeadermarkersEvSubagentEndemit sitesmodelThe self-forgery oracle feeds each renderer's own output back through the composer, so a new marker with no
framingHeaderentry fails a test automatically — it found 9 markers the reviewers never named.Round 4 then caught the cost of that hardening: neutralisation applied prompt-surface markers to delegation results, silently erasing
Category:/Rationale:lines from structured child deliverables on the success arm. Fixed by tagging each marker with the surface it protects — one enumeration, not two lists.Also in scope
--log-levelflag was built and then removed: it was premised on the Debug retry lines being the only route to a diagnosis, but the Info terminals answer A failed subagent's actual cause is dropped four times — the error shown is the child's last chat line #319 at the default floor on every binary. Reasoning kept inIMPLEMENTATION-NOTES, code dropped; the net diff is flag-free.--max-team-tokens) while per-member behavioural bounds stay engine-only defaults (the precedent isWithMemberTurnBudget, likewise unwired at a default of 200 turns).mcp/jqflake was root-caused, not tolerance-widened: under load the watchdog genuinely wasn't tripping, so the guard had stopped guarding. The oracle is now typed error identity with no wall-clock assertion; 55 clean runs under 13× CPU oversubscription.Verification
task lint0 issues both modules ·task testexit 0 (root + engine-race+GOWORK=offstandalone) ·task api:checkok ·task docs169 docs / 0 broken ·mecademofull offline session ·task generatecontent-idempotent.Every new guard was mutation-checked. Mutations were required to be behavioural and compiling, and each had to fail the specific assertion it guards — a mutation that reddens the package via a different test proves nothing. That discipline exists because a guard on this branch went vacuous inside the diff (it asserted a string the diff had deleted) and survived a pass reported as mutation-verified.
🤖 Generated with Claude Code
Update — rebased onto main, round-5 audit
Rebased onto
main(which had independently landed ADR 0079 bounded previews —Text/Detail/InnerKindonSubagent/Parallel, proto fields 14/15/16). The branch'scausefield therefore moved from proto field 14 to field 17; the reconciliation commit (d45d4703) also:Causeto the ADR-0079 structural sentinel's allow-list with its gauntlet-ACP: accept client-provided streaming-HTTP MCP servers #7 justification,0077-*on main, not0041-*).A fifth review pass ran two independent fix-verification audits (one per issue) adversarially against the acceptance criteria. All #318 bullets hold and all four #319 drop points are closed. The audit independently surfaced one genuine remaining #319 shape, now fixed (
05489546):StopErrorturn still showed the child's last text as the error. A turn ending on a terminal stop chunk (Anthropicmax_tokens/refusal, mapped toStopErrorwith no Go error) after streaming text routes throughterminateComplete, which emitted an emptyResultPayload.Error— sosubagentErrorBodyrendered the truncated text as the failure. The empty-turn shape already tookterminate(with a cause); OpenAI'sincomplete/failedreturn a Go error and were never affected.terminateCompletenow synthesises the cause (stopTerminalCause,StopError-only, harness-authored, honouring the "empty on every other terminal" contract). Red-then-green:TestSubagentTruncatedTurnStillSurfacesAReason.The Standards axis separately caught a stale
Subagent.causefield reference inIMPLEMENTATION-NOTES(14 → 17), fixed in the same commit.Two further audit items are new scope beyond #318/#319, filed as follow-ups rather than growing this PR:
StopErrorcause is dropped (TeamPayloadhas noCausefield); the third delegation family A failed subagent's actual cause is dropped four times — the error shown is the child's last chat line #319 left out of scope.Update 2 — perf gate green
The rebase surfaced a perf-gate regression (
background_subagentsandteam_fanoutallocs/op at 1.07×, threshold 1.02). Bisected to two branch commits on the hot delegation path, both fixed without changing behaviour:c65078ec—b2c3c62cappliedneutraliseChildTextto every delegation-result arm (correct, CWE-1427/LLM01) but paid two Replacer passes + Split + Join + per-line normalisation on every clean result. Added an allocation-free candidate gate (lineMayBeHeader) + whole-string fast path. The security oracles caught two real gate bugs before it shipped (a leading Cf/Cc and a digit-led ordered-list line must reach the slow path); both new guards are mutation-tested.team_fanoutnow under baseline.0bb39516—8349d0b7made the child persist unconditionally cancel-detached (2 ctx allocs/save) so a Redis/remote save survives the expired ctx on the timeout/cancel terminals. Now detaches only whenctx.Err() != nil— the exact terminals it was for — so a live-ctx persist is allocation-free.background_subagentsback to baseline.All 13 CI checks green (including the previously-failing Perf gate and Test-race).