Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ In TUI chat mode there is no completion gate — the session stays open across t
Two directors, selected by role:

- **ChatDirector** (interactive, `src/agent/director.ts`) — Extends `DefaultDirector` with task list tracking, workflow nudges, LSP auto-activation, and multi-turn chat semantics. It never terminates the session: operator declines are surfaced as replies and the reactor stays alive for the next message. Auto mode is toggled by CLI flags (`--auto` / `--no-auto`); there is currently no in-session key to toggle it (default on; constrained envelope — workspace writes and unconstrained shell auto-allow; installs, recursive rm, force/uncontained worktree changes, sensitive-path and opaque-wrapper shell still ask; contained non-force `git worktree add`/`remove`/`prune` and `list` auto-allow; shell file-mutation denied). It is not a separate edit/plan mode.
- **SubAgentDirector** (delegated work, `src/subagent/index.ts`) — Drives a dispatched worker until a turn arrives with no tool calls, then replies with the final assistant text and ends the run. A tool-less completion with **zero tool calls in the entire run** is returned as a **never-acted** salvage report (not a successful implement); explore/read-only workers that used tools then replied with findings remain normal completes. Hard stops also fire after 2 consecutive identical tool-call fingerprints (**no-progress**), on progressive re-read pressure (**thrash** — the same path re-read past a limit amid enough tool volume, tracked by `src/subagent/thrash.ts`), or after the leaf turn budget (**turn-budget**, default 30, overridable via `task(maxTurns)`, agent profile `maxTurns`, or `settings.subagentMaxTurns`, capped at 100), each returning a structured salvage report (reason, partial findings, blockers) so a thrashing child cannot burn tokens indefinitely. A fourth hard stop, **repetition**, is detected outside the director entirely: `runSubAgent`'s stream sink watches the streamed text of the in-flight cycle for degenerate token loops (`src/subagent/repetition.ts`) — whitespace-collapsed raw text, a smallest-period KMP check over the probe tail, default window >= 16 chars repeated >= 8 times, evaluated every 256 streamed chars — and on a hit aborts the run controller mid-cycle, returning a `repetition` salvage report that leads with the looped window and warns the parent against re-dispatching the identical brief. Because directors only see completed turns, this is the only stop that can catch a loop inside a single turn that never finishes. A one-shot **report-forced** signal fires a few turns before the cap while the leaf is still tooling — it is not a stop: the director injects a wrap-up nudge and lets the leaf finish on its own, so turn-budget stays reachable for a leaf still making progress. Operator/parent cancel after any progress likewise returns a **cancelled** salvage report (partial findings + tool activity) instead of a bare cancel string; cancel before progress still surfaces as cancelled-by-operator. Optional `task(tier=)` (`fast` | `standard` | `clever`) overrides profile inference, profile tier, and the parent provider for that spawn only, and fails closed when the tier is unconfigured. The parent `task` tool keeps a session-scoped brief-dispatch ledger (`src/subagent/brief-dispatch.ts`): fingerprints cover prompt + agent + intent + success_criteria + do_not (not maxTurns/description/tier). After thrash / no-progress / repetition / never-acted salvage, an identical re-dispatch is hard-blocked for the rest of the parent chat; change at least one fingerprint field to force a re-run. Turn-budget salvage still invites a higher maxTurns for a few same-brief retries without a successful complete, then flips the parent hint to stop and change approach (soft — further identical dispatches are still admitted). A successful complete resets the same-brief retry budget.
- **SubAgentDirector** (delegated work, `src/subagent/index.ts`) — Drives a dispatched worker until a turn arrives with no tool calls, then replies with the final assistant text and ends the run. A tool-less completion with **zero tool calls in the entire run** is returned as a **never-acted** salvage report (not a successful implement). When `task(intent="implement")` is set, a tool-using run that never wrote/edited/deleted a file is returned as **never-edited** instead of complete — so a pure-explore "plan" cannot look shipped to the parent (tracked via `thrashState.editedPaths` from `edit_file` / `write_file` / `delete_file`). Explore/read-only workers that used tools then replied with findings remain normal completes. Hard stops also fire after 2 consecutive identical tool-call fingerprints (**no-progress**), on progressive re-read pressure (**thrash** — the same path re-read past a limit amid enough tool volume, tracked by `src/subagent/thrash.ts`), or after the leaf turn budget (**turn-budget**, default 30, overridable via `task(maxTurns)`, agent profile `maxTurns`, or `settings.subagentMaxTurns`, capped at 100), each returning a structured salvage report (reason, partial findings, blockers) so a thrashing child cannot burn tokens indefinitely. A fourth hard stop, **repetition**, is detected outside the director entirely: `runSubAgent`'s stream sink watches the streamed text of the in-flight cycle for degenerate token loops (`src/subagent/repetition.ts`) — format chars (ZWSP, BOM, bidi marks, soft hyphen, …) stripped then whitespace-collapsed raw text, a smallest-period KMP check over the probe tail, default window >= 16 chars repeated >= 8 times, evaluated every 256 streamed chars — and on a hit aborts the run controller mid-cycle, returning a `repetition` salvage report that leads with the looped window and warns the parent against re-dispatching the identical brief. Because directors only see completed turns, this is the only stop that can catch a loop inside a single turn that never finishes. A one-shot **report-forced** signal fires a few turns before the cap while the leaf is still tooling — it is not a stop: the director injects a wrap-up nudge and lets the leaf finish on its own, so turn-budget stays reachable for a leaf still making progress. Operator/parent cancel after any progress likewise returns a **cancelled** salvage report (partial findings + tool activity) instead of a bare cancel string; cancel before progress still surfaces as cancelled-by-operator. Optional `task(tier=)` (`fast` | `standard` | `clever`) overrides profile inference, profile tier, and the parent provider for that spawn only, and fails closed when the tier is unconfigured. The parent `task` tool keeps a session-scoped brief-dispatch ledger (`src/subagent/brief-dispatch.ts`): fingerprints cover prompt + agent + intent + success_criteria + do_not (not maxTurns/description/tier). After thrash / no-progress / repetition / never-acted / never-edited salvage, an identical re-dispatch is hard-blocked for the rest of the parent chat; change at least one fingerprint field to force a re-run. Turn-budget salvage still invites a higher maxTurns for a few same-brief retries without a successful complete, then flips the parent hint to stop and change approach (soft — further identical dispatches are still admitted). A successful complete resets the same-brief retry budget.



Expand All @@ -130,7 +130,7 @@ The ChatDirector counts consecutive assistant turns that contain tool calls and

#### Sub-agent stall management

`SubAgentDirector` tracks `lastActivityAt`, updated on every real `inference.done` and `tool.done`. Directors are pure `decide(event, ...)` functions with no timer of their own and the reactor has no proactive "idle" event, so a genuinely silent leaf (e.g. parked on a long-running background command with nothing else to do) produces no event for the director to react to. `runSubAgent` (`src/subagent/index.ts`) arms an external interval, at `subAgentStallTimeoutMs`, that pings the same content-less continuation channel the compaction governor uses to re-enter an idle reactor (`requestContinuation`). The director only acts on a ping if the elapsed time since `lastActivityAt` has crossed the timeout — a ping delivered while a tool call is still executing simply queues until that cycle finishes, so "no pending harness-tracked work" falls out of when the check can run at all rather than needing separate bookkeeping. The first stall past the timeout gets one continuation nudge (asking the leaf to check on the background work or report status); a second **consecutive** stall (no activity since that nudge) escalates to the existing salvage path, returning a `stalled` `forcedStopReport` with the same structured shape (summary/findings/blockers) as `no-progress` / `turn-budget` / `thrash` / `never-acted`. Any real activity between pings resets the streak, so a leaf that is genuinely working through a slow single turn is never penalized.
`SubAgentDirector` tracks `lastActivityAt`, updated on every real `inference.done` and `tool.done`. Directors are pure `decide(event, ...)` functions with no timer of their own and the reactor has no proactive "idle" event, so a genuinely silent leaf (e.g. parked on a long-running background command with nothing else to do) produces no event for the director to react to. `runSubAgent` (`src/subagent/index.ts`) arms an external interval, at `subAgentStallTimeoutMs`, that pings the same content-less continuation channel the compaction governor uses to re-enter an idle reactor (`requestContinuation`). The director only acts on a ping if the elapsed time since `lastActivityAt` has crossed the timeout — a ping delivered while a tool call is still executing simply queues until that cycle finishes, so "no pending harness-tracked work" falls out of when the check can run at all rather than needing separate bookkeeping. The first stall past the timeout gets one continuation nudge (asking the leaf to check on the background work or report status); a second **consecutive** stall (no activity since that nudge) escalates to the existing salvage path, returning a `stalled` `forcedStopReport` with the same structured shape (summary/findings/blockers) as `no-progress` / `turn-budget` / `thrash` / `never-acted` / `never-edited`. Any real activity between pings resets the streak, so a leaf that is genuinely working through a slow single turn is never penalized.

**Precedence**: stall detection sits **below** no-progress, thrash, and turn-budget — those are evaluated from real `inference.done` turns inside `evaluateSubAgentStop` and always take priority; the stall check only ever fires on a continuation ping that inference/tool-result handling did not already consume that cycle. Report-forced (the one-shot wrap-up nudge a few turns before the turn-budget cap) and stall nudging are independent one-shot signals that can both fire across a run — one is turn-count driven, the other wall-clock driven — but neither is a competing stop reason in the sense no-progress/thrash/turn-budget are.

Expand Down
2 changes: 1 addition & 1 deletion docs/PRODUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ Corbits Code can fan work out to short-lived **sub-agents** — child agents wit
- **Tasks** are checklist items owned by one agent via `manage_tasks`.
- **Sub-agents** are spawned with the `task` tool (wire name kept; meaning is "spawn a child agent," not "add a checklist item").

Dispatch uses a structured brief (context / goal / optional goals seed) and returns a structured report. The TUI Agents strip shows who is running; live tool progress updates the status bar without dumping the child transcript into the parent chat. Leaf workers hard-stop after 2 consecutive identical tool calls, when their inference-turn budget is exhausted (default 30; parent can pass `maxTurns` per dispatch; profiles and global settings can raise the default; cap 100), or when they finish without ever using tools (never-acted salvage — planning/prose only is not a successful implement). Each hard stop returns a salvage report so a runaway or idle child cannot quietly burn a large token budget or look done after prose alone. The parent tracks same-brief fingerprints for the session (`src/subagent/brief-dispatch.ts`): after thrash / no-progress / repetition / never-acted salvage, an identical re-dispatch is refused — change prompt, agent, intent, success_criteria, and/or do_not to unlock a new run (`maxTurns` or tier alone does not). Turn-budget salvage still allows a few same-brief retries with a higher `maxTurns`, then flips the parent hint to stop and change approach; a successful complete resets the same-brief retry budget.
Dispatch uses a structured brief (context / goal / optional goals seed) and returns a structured report. The TUI Agents strip shows who is running; live tool progress updates the status bar without dumping the child transcript into the parent chat. Leaf workers hard-stop after 2 consecutive identical tool calls, when their inference-turn budget is exhausted (default 30; parent can pass `maxTurns` per dispatch; profiles and global settings can raise the default; cap 100), when they finish without ever using tools (never-acted salvage — planning/prose only is not a successful implement), or when `intent=implement` finishes after tools but without any file write/edit/delete (never-edited salvage — a pure-explore plan is not a successful implement). Each hard stop returns a salvage report so a runaway or idle child cannot quietly burn a large token budget or look done after prose alone. The parent tracks same-brief fingerprints for the session (`src/subagent/brief-dispatch.ts`): after thrash / no-progress / repetition / never-acted / never-edited salvage, an identical re-dispatch is refused — change prompt, agent, intent, success_criteria, and/or do_not to unlock a new run (`maxTurns` or tier alone does not). Turn-budget salvage still allows a few same-brief retries with a higher `maxTurns`, then flips the parent hint to stop and change approach; a successful complete resets the same-brief retry budget.

## Roadmap (planned, not yet shipped)

Expand Down
6 changes: 5 additions & 1 deletion src/subagent/brief-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { parseSubAgentReport } from "./report.js";
import {
isDeadlineSubAgentReport,
isNeverActedSubAgentReport,
isNeverEditedSubAgentReport,
isNoProgressSubAgentReport,
isRepetitionSubAgentReport,
isThrashSubAgentReport,
Expand All @@ -27,7 +28,8 @@ export type HardBlockSalvage =
| "thrash"
| "no-progress"
| "repetition"
| "never-acted";
| "never-acted"
| "never-edited";

export type BriefSalvageKind =
| HardBlockSalvage
Expand Down Expand Up @@ -63,6 +65,7 @@ const HARD_BLOCK_SALVAGES = new Set<BriefSalvageKind>([
"no-progress",
"repetition",
"never-acted",
"never-edited",
]);

export function isHardBlockSalvage(kind: BriefSalvageKind): kind is HardBlockSalvage {
Expand All @@ -89,6 +92,7 @@ export function classifyBriefSalvage(report: string): BriefSalvageKind | null {
// Order: more specific salvage phrases first.
if (isThrashSubAgentReport(report)) return "thrash";
if (isRepetitionSubAgentReport(report)) return "repetition";
if (isNeverEditedSubAgentReport(report)) return "never-edited";
if (isNeverActedSubAgentReport(report)) return "never-acted";
if (isNoProgressSubAgentReport(report)) return "no-progress";
if (isTurnBudgetSubAgentReport(report)) return "turn-budget";
Expand Down
63 changes: 61 additions & 2 deletions src/subagent/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,60 @@ describe("sub-agent stop helpers", () => {
).toBe("never-acted");
});

test("evaluateSubAgentStop returns never-edited when requireEdit and tools never wrote files", () => {
const thrashState = {
totalToolCalls: 4,
readCounts: new Map([["src/a.ts", 2]]),
editedPaths: new Set<string>(),
};
expect(
evaluateSubAgentStop({
hasToolCalls: false,
everHadToolCalls: true,
turnsCompleted: 5,
maxTurns: 30,
consecutiveIdentical: 0,
repeatLimit: 2,
thrashState,
requireEdit: true,
}),
).toBe("never-edited");
});

test("evaluateSubAgentStop still completes implement when an edit path was recorded", () => {
const thrashState = {
totalToolCalls: 4,
readCounts: new Map([["src/a.ts", 1]]),
editedPaths: new Set(["src/a.ts"]),
};
expect(
evaluateSubAgentStop({
hasToolCalls: false,
everHadToolCalls: true,
turnsCompleted: 5,
maxTurns: 30,
consecutiveIdentical: 0,
repeatLimit: 2,
thrashState,
requireEdit: true,
}),
).toBe("complete");
});

test("evaluateSubAgentStop ignores requireEdit when the run never used tools (never-acted wins)", () => {
expect(
evaluateSubAgentStop({
hasToolCalls: false,
everHadToolCalls: false,
turnsCompleted: 1,
maxTurns: 10,
consecutiveIdentical: 0,
repeatLimit: 2,
requireEdit: true,
}),
).toBe("never-acted");
});

test("evaluateSubAgentStop prefers no-progress over turn-budget", () => {
expect(
evaluateSubAgentStop({
Expand Down Expand Up @@ -414,6 +468,10 @@ describe("sub-agent stop helpers", () => {
expect(neverParsed.blockers).toContain("unexecuted");
expect(neverActed.toLowerCase()).not.toContain("summarize what you found");

const neverEdited = forcedStopReport("never-edited", "I mapped the files; ready to code next");
expect(neverEdited).toContain("without writing any files");
expect(appendSubAgentParentHints(neverEdited)).toContain("edit-first");

const thrashReport = forcedStopReport("thrash", "Re-read a.ts after edit");
const thrashParsed = parseSubAgentReport(thrashReport);
expect(thrashParsed.summary).toContain("progressive thrash");
Expand Down Expand Up @@ -1658,8 +1716,8 @@ describe("brief re-dispatch ledger (CL-4343 / CL-5203)", () => {
expect(ledger.admit(other).ok).toBe(true);
});

test("hard-blocks no-progress, repetition, never-acted; not turn-budget", () => {
for (const salvage of ["no-progress", "repetition", "never-acted"] as const) {
test("hard-blocks no-progress, repetition, never-acted, never-edited; not turn-budget", () => {
for (const salvage of ["no-progress", "repetition", "never-acted", "never-edited"] as const) {
const ledger = createBriefDispatchLedger();
const fp = fingerprintTaskBrief({ prompt: `job ${salvage}` });
expect(ledger.admit(fp).ok).toBe(true);
Expand Down Expand Up @@ -1713,6 +1771,7 @@ describe("brief re-dispatch ledger (CL-4343 / CL-5203)", () => {
expect(classifyBriefSalvage(forcedStopReport("no-progress", "x"))).toBe("no-progress");
expect(classifyBriefSalvage(forcedStopReport("repetition", "x"))).toBe("repetition");
expect(classifyBriefSalvage(forcedStopReport("never-acted", "x"))).toBe("never-acted");
expect(classifyBriefSalvage(forcedStopReport("never-edited", "x"))).toBe("never-edited");
expect(classifyBriefSalvage(forcedStopReport("turn-budget", "x"))).toBe("turn-budget");
expect(classifyBriefSalvage("## Summary\nDone\n\n## Findings\nok\n\n## Blockers\nNone\n\n## Paths\n")).toBeNull();
});
Expand Down
1 change: 1 addition & 0 deletions src/subagent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export {
forcedStopReport,
isDeadlineSubAgentReport,
isNeverActedSubAgentReport,
isNeverEditedSubAgentReport,
isNoProgressSubAgentReport,
isRepetitionSubAgentReport,
isThrashSubAgentReport,
Expand Down
Loading
Loading