@kenkaiiii/ggcoder 5.57.2 → 5.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,9 +12,9 @@
12
12
  <a href="https://github.com/KenKaiii"><img src="https://img.shields.io/badge/GitHub-181717?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"></a>
13
13
  </p>
14
14
 
15
- A coding agent that ships only what the model needs to work — a tiny system prompt, one carefully-chosen MCP, and a focused tool set. Switch between Anthropic, OpenAI, GLM, Moonshot, MiniMax, Xiaomi, DeepSeek, and OpenRouter mid-conversation. Run it on its own, or let [`@kenkaiiii/gg-boss`](../gg-boss/README.md) drive a fleet of `ggcoder` workers across many projects from a single chat.
15
+ A coding agent that ships only what the model needs to work — a tiny system prompt, one carefully-chosen MCP, and a focused tool set. Switch between Anthropic, OpenAI, GLM, Moonshot, MiniMax, Xiaomi, DeepSeek, and OpenRouter mid-conversation. Run it in the terminal, or use the same engine in the [GG Coder desktop app](../../README.md).
16
16
 
17
- Built on [`@kenkaiiii/gg-ai`](../gg-ai/README.md) and [`@kenkaiiii/gg-agent`](../gg-agent/README.md). Part of the [GG Framework](../../README.md) monorepo.
17
+ Built on [`@kenkaiiii/gg-ai`](../gg-ai/README.md), [`@kenkaiiii/gg-agent`](../gg-agent/README.md), and `@kenkaiiii/gg-core`. Part of the [GG Framework](../../README.md) monorepo.
18
18
 
19
19
  ---
20
20
 
@@ -27,7 +27,7 @@ ggcoder login # Pick provider, authenticate
27
27
  ggcoder # Start coding
28
28
  ```
29
29
 
30
- OAuth for Anthropic and OpenAI (log in once, auto-refresh, no key to leak). API keys for the rest. Up and running in seconds either way. Auth lives in `~/.gg/auth.json` and is shared with `gg-boss`.
30
+ OAuth for Anthropic and OpenAI (log in once, auto-refresh, no key to leak). API keys for the rest. Up and running in seconds either way. Auth lives in `~/.gg/auth.json` and is shared with the GG Coder desktop app.
31
31
 
32
32
  ---
33
33
 
@@ -84,24 +84,6 @@ The same conversation, the same tools, the same project context — only the mod
84
84
 
85
85
  ---
86
86
 
87
- ## 🤝 Pair it with gg-boss
88
-
89
- `ggcoder` is the unit of work. [`gg-boss`](../gg-boss/README.md) is the orchestrator that drives many of them at once.
90
-
91
- ```bash
92
- npm i -g @kenkaiiii/gg-boss
93
- ggboss link # pick which projects to drive
94
- ggboss # one chat, N parallel ggcoder workers
95
- ```
96
-
97
- Inside `gg-boss`, every project gets its own `ggcoder` `AgentSession` running in that project's directory. The boss dispatches work — `prompt_worker(project, "...")` — and each worker uses the **same** focused tool set (read, write, edit, bash, grep, find, ls, web fetch, sub-agents) you'd get running `ggcoder` solo. Workers reply with a tight `Changed / Skipped / Verified / Notes / Status` summary the boss reads, cross-checks, and routes off.
98
-
99
- Why this works: ggcoder's lean prompt and tight tool set keep each worker cheap and predictable, so the boss can run six or more in parallel without context blow-up. Anything you can do in a single `ggcoder` session — slash commands, skills, MCPs, custom commands, project `CLAUDE.md` rules — works inside the boss too.
100
-
101
- Run `ggcoder` directly when you're heads-down on one project. Switch to `ggboss` when you want a coordinator on top.
102
-
103
- ---
104
-
105
87
  ## ⌨️ Keybindings
106
88
 
107
89
  | Key | What it does |
@@ -142,6 +142,10 @@ export interface AgentSessionOptions {
142
142
  coderSlashCommands?: boolean;
143
143
  /** Enable loop-break, re-grounding, and Ideal review hooks. Defaults to true. */
144
144
  selfCorrectionHooks?: boolean;
145
+ /** Override the semantic-loop judge LLM call (tests). Receives the finished
146
+ * prompt, returns the model's raw reply. Default: one-shot `stream()` call
147
+ * on the session's ACTIVE model. */
148
+ semanticLoopJudge?: (prompt: string) => Promise<string>;
145
149
  /** Load project skills/agents and create local .gg directories. Defaults to true. */
146
150
  projectCustomization?: boolean;
147
151
  /** Register global + bundled subagents without loading project customization. */
@@ -223,6 +227,14 @@ export declare class AgentSession {
223
227
  /** 0 = none; 1 = first nudge sent; 2 = final stop-and-report injected. */
224
228
  private loopBreakInjected;
225
229
  private regroundingInjected;
230
+ /** Recent tool-call digests for the semantic loop judge — bounded ring. */
231
+ private hookRecentCalls;
232
+ /** LLM-judged loop detection state. `verdict` holds a LOOP verdict awaiting
233
+ * injection at the next steering poll; judge failures fail open (no
234
+ * injection) and still consume budget + cooldown. */
235
+ private semanticLoop;
236
+ /** Independent Ideal reviewer spawned once per run (score-gated). */
237
+ private independentReviewStarted;
226
238
  /**
227
239
  * The environment as the cached system prompt currently describes it.
228
240
  * Re-recorded on every prompt build, so a rebuild (e.g. `/add-dir`) needs no
@@ -471,6 +483,25 @@ export declare class AgentSession {
471
483
  * Mirrors the TUI's getSteeringMessages ordering.
472
484
  */
473
485
  private getHookSteeringMessages;
486
+ /** Fire the semantic loop judge when deterministic evidence is suspicious but
487
+ * the deterministic breaker stayed quiet — the syntactic blind spot where
488
+ * every retry differs slightly and the run still makes no progress.
489
+ * Fire-and-forget: the call runs while the next turn streams, and a finished
490
+ * verdict is consumed by the NEXT steering poll — never blocking a turn. */
491
+ private maybeStartSemanticLoopCheck;
492
+ /** One-shot judge call on the session's ACTIVE model — deliberately not a
493
+ * cheaper routing: judging a model's own failure patterns with a weaker
494
+ * model swaps false negatives for false positives. */
495
+ private callSemanticLoopJudge;
496
+ /** Independent fresh-context review of the finished work (Codex Guardian
497
+ * pattern). Spawns a READ-ONLY child on the ACTIVE model, waits bounded,
498
+ * and returns findings for the acting agent to address — or nothing when
499
+ * the review passes, is unavailable, or fails (in-thread review remains the
500
+ * fallback; the feature degrades, never blocks).
501
+ *
502
+ * Runs inside the pre-stop poll, so the candidate final answer is already
503
+ * held by arming and this wait cannot race a streamed answer. */
504
+ private runIndependentReview;
474
505
  /**
475
506
  * Turn-budget extension gate. The loop consults this instead of stopping
476
507
  * mid-task when it exhausts `maxTurns`. Grant ONLY on evidence of progress —
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session.d.ts","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,SAAS,EAEf,MAAM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,OAAO,CAAC,iBAAiB;IAMzB,mEAAmE;IACnE,kBAAkB,IAAI,MAAM,GAAG,SAAS;IAIlC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAc9B,OAAO,CAAC,cAAc;YAOR,gBAAgB;YAehB,mBAAmB;IA4IjC;;;;;;;;;OASG;YACW,qBAAqB;YAcrB,qBAAqB;YAIrB,cAAc;IAuB5B,OAAO,CAAC,yBAAyB;IAgDjC;;;;;OAKG;IACG,uBAAuB,CAC3B,QAAQ,EAAE,MAAM,EAChB,IAAI,GAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAA;KAAO,GAC1B,OAAO,CAAC,6BAA6B,CAAC;CA2B1C"}
@@ -1,5 +1,5 @@
1
1
  import { agentLoop, isAbortError, isUsageLimitError, } from "@kenkaiiii/gg-agent";
2
- import { ProviderError, } from "@kenkaiiii/gg-ai";
2
+ import { ProviderError, stream, } from "@kenkaiiii/gg-ai";
3
3
  import { EventBus } from "./event-bus.js";
4
4
  import { SlashCommandRegistry, createBuiltinCommands, } from "./slash-commands.js";
5
5
  import { PROMPT_COMMANDS, getPromptCommand } from "./prompt-commands.js";
@@ -22,7 +22,7 @@ import { buildSubAgentSystemPrompt, buildSystemPrompt, } from "../system-prompt.
22
22
  import { createTools, createWebSearchTool, } from "../tools/index.js";
23
23
  import { partitionToolsByTier } from "../tools/tool-tiers.js";
24
24
  import { buildProcessCompletionFollowUp } from "./process-gate.js";
25
- import { buildSubAgentCompletionFollowUp } from "./subagent-manager.js";
25
+ import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
26
26
  import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
27
27
  import { z } from "zod";
28
28
  import { MCPClientManager, getAllMcpServers } from "./mcp/index.js";
@@ -42,6 +42,8 @@ import { detectProjectStack } from "./language-detector.js";
42
42
  import { evaluateIdealReview, buildIdealReviewMessage, buildReviewCoverageEscalationMessage, buildReviewCoverageMessage, MAX_REVIEW_COVERAGE_INJECTIONS, withReviewCoverageRequirements, detectTestDrift, ReviewCoverageTracker, } from "./ideal-review.js";
43
43
  import { evaluateLoopBreak, buildLoopBreakMessage, CycleDetector, ToolCallProgressTracker, detectTextRepetition, } from "./loop-breaker.js";
44
44
  import { buildRegroundingMessage } from "./regrounding.js";
45
+ import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, MAX_SEMANTIC_LOOP_CALLS, parseSemanticLoopVerdict, shouldRunSemanticLoopCheck, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
46
+ import { buildIndependentReviewMessage, buildReviewerTask, INDEPENDENT_REVIEW_SCORE_THRESHOLD, parseReviewerFindings, REVIEWER_TOOLS, REVIEWER_WAIT_MS, } from "./ideal-review-subagent.js";
45
47
  import { buildEnvDeltaMessage } from "./env-delta.js";
46
48
  import { wrapSteeringText, buildNotificationSteeringText, STEERING_PREFIX } from "./steering.js";
47
49
  import { AgentNotificationQueue } from "./agent-notifications.js";
@@ -58,6 +60,14 @@ import path from "node:path";
58
60
  * progressing — refuse to extend its turn budget.
59
61
  */
60
62
  const TURN_EXTENSION_MAX_FAILURE_RATIO = 0.5;
63
+ /** Terminal subagent states — mirrors SubAgentManager's private isTerminal. */
64
+ function isTerminalSubAgentState(state) {
65
+ return (state === "completed" ||
66
+ state === "failed" ||
67
+ state === "interrupted" ||
68
+ state === "closed" ||
69
+ state === "reaped");
70
+ }
61
71
  // ── Tool-result policy ─────────────────────────────────────
62
72
  /** Resolve the per-result cap passed to the agent loop for the active transport. */
63
73
  export function resolveSessionToolResultCharLimit(model, provider, accountId) {
@@ -159,6 +169,14 @@ export class AgentSession {
159
169
  /** 0 = none; 1 = first nudge sent; 2 = final stop-and-report injected. */
160
170
  loopBreakInjected = 0;
161
171
  regroundingInjected = false;
172
+ /** Recent tool-call digests for the semantic loop judge — bounded ring. */
173
+ hookRecentCalls = [];
174
+ /** LLM-judged loop detection state. `verdict` holds a LOOP verdict awaiting
175
+ * injection at the next steering poll; judge failures fail open (no
176
+ * injection) and still consume budget + cooldown. */
177
+ semanticLoop = { checksUsed: 0, lastCheckTurn: 0, pending: false, verdict: null, injected: false };
178
+ /** Independent Ideal reviewer spawned once per run (score-gated). */
179
+ independentReviewStarted = false;
162
180
  /**
163
181
  * The environment as the cached system prompt currently describes it.
164
182
  * Re-recorded on every prompt build, so a rebuild (e.g. `/add-dir`) needs no
@@ -1005,6 +1023,15 @@ export class AgentSession {
1005
1023
  this.idealDriftProbe = null;
1006
1024
  this.loopBreakInjected = 0;
1007
1025
  this.regroundingInjected = false;
1026
+ this.hookRecentCalls = [];
1027
+ this.semanticLoop = {
1028
+ checksUsed: 0,
1029
+ lastCheckTurn: 0,
1030
+ pending: false,
1031
+ verdict: null,
1032
+ injected: false,
1033
+ };
1034
+ this.independentReviewStarted = false;
1008
1035
  this.runStartedAt = Date.now();
1009
1036
  this.processGateInjected = 0;
1010
1037
  this.verificationGate.beginRun();
@@ -1036,9 +1063,14 @@ export class AgentSession {
1036
1063
  typeof event.args?.command === "string" &&
1037
1064
  (isVerificationCommand(event.args.command) ||
1038
1065
  classifyVerificationCommand(event.args.command).accepted)) {
1039
- // A rejected check may rewrite files (--fix, build scripts, shell
1040
- // wrappers). Earlier in-flight checks cannot validate those changes.
1041
- this.verificationGate.requireFreshVerification(!classifyVerificationCommand(event.args.command).accepted);
1066
+ // A check that can rewrite files (--fix, build scripts, emitters)
1067
+ // invalidates earlier in-flight evidence AND marks the run as
1068
+ // touched. A check that is merely UNRECOGNIZED (`make test`, `deno
1069
+ // test`) rewrites nothing we can point to: bumping the revision for
1070
+ // it poisoned the gate on green output and re-armed the hook into
1071
+ // every later question turn.
1072
+ const classification = classifyVerificationCommand(event.args.command);
1073
+ this.verificationGate.requireFreshVerification(!classification.accepted && classification.mayMutate, event.args.command);
1042
1074
  await this.persistVerificationState();
1043
1075
  }
1044
1076
  break;
@@ -1058,6 +1090,19 @@ export class AgentSession {
1058
1090
  this.hookConsecutiveFailures = event.isError ? this.hookConsecutiveFailures + 1 : 0;
1059
1091
  this.hookRepeatedNoProgressCalls = this.hookProgressTracker.record(name, args, event.result, event.isError);
1060
1092
  this.hookCyclicPattern = this.hookCycleDetector.record(name, args, event.result, event.isError);
1093
+ // Semantic-loop judge input: a bounded digest of WHAT was attempted and
1094
+ // HOW it came out. Args/results are sliced AT RECORD TIME — a write with
1095
+ // a 50 KiB payload or a bash dump must never inflate the ring, and the
1096
+ // judge needs shapes, not payloads.
1097
+ this.hookRecentCalls.push({
1098
+ tool: name,
1099
+ args: args === undefined ? "" : JSON.stringify(args).slice(0, 300),
1100
+ ok: !event.isError,
1101
+ result: event.result.slice(0, 400),
1102
+ });
1103
+ if (this.hookRecentCalls.length > MAX_SEMANTIC_LOOP_CALLS) {
1104
+ this.hookRecentCalls.splice(0, this.hookRecentCalls.length - MAX_SEMANTIC_LOOP_CALLS);
1105
+ }
1061
1106
  if (name === "edit" && !event.isError) {
1062
1107
  const diff = event.details?.diff ?? event.result;
1063
1108
  const added = (diff.match(/^\+[^+]/gm) ?? []).length;
@@ -1084,19 +1129,23 @@ export class AgentSession {
1084
1129
  }
1085
1130
  if (args && call && name === "bash") {
1086
1131
  const command = typeof args.command === "string" ? args.command : "";
1087
- if (classifyVerificationCommand(command).accepted) {
1132
+ const classification = classifyVerificationCommand(command);
1133
+ if (classification.accepted) {
1088
1134
  if (args.run_in_background === true && !event.isError && args.persist !== true) {
1089
1135
  const id = /^ID:\s*(\S+)/m.exec(event.result)?.[1];
1136
+ // No parseable ID means the check cannot be tracked to a real exit
1137
+ // code — no evidence either way. Recording a FAILURE here made
1138
+ // every later green run of a different spelling look owed.
1090
1139
  if (id)
1091
1140
  this.backgroundVerification.set(id, { revision: call.revision, command });
1092
- else
1093
- this.verificationGate.recordFailedVerification(command, call.revision);
1094
- verificationChanged = true;
1141
+ }
1142
+ else if (args.persist === true) {
1143
+ // Persistent-shell checks are not bounded evidence (steering can
1144
+ // interleave): neither a pass nor a failure. A recorded failure
1145
+ // here blocked approval for sessions that prefer the shell.
1095
1146
  }
1096
1147
  else {
1097
- if (!event.isError &&
1098
- args.persist !== true &&
1099
- /^Exit code:\s*0(?:\s|$)/i.test(event.result.trim())) {
1148
+ if (!event.isError && /^Exit code:\s*0(?:\s|$)/i.test(event.result.trim())) {
1100
1149
  this.verificationGate.recordVerification(call.revision, command);
1101
1150
  }
1102
1151
  else {
@@ -1105,6 +1154,11 @@ export class AgentSession {
1105
1154
  verificationChanged = true;
1106
1155
  }
1107
1156
  }
1157
+ else if (classification.candidate) {
1158
+ // Green but untrusted: remember WHY so the demand can tell the
1159
+ // agent which command shape actually clears the gate.
1160
+ this.verificationGate.recordRejectedCheck(command, classification.reason);
1161
+ }
1108
1162
  }
1109
1163
  if (!event.isError && args && name === "task_output" && typeof args.id === "string") {
1110
1164
  const started = this.backgroundVerification.get(args.id);
@@ -1270,16 +1324,21 @@ export class AgentSession {
1270
1324
  return null;
1271
1325
  if (!this.settingsManager.get("idealReviewEnabled"))
1272
1326
  return null;
1327
+ // Deterministic stuck verdict, computed once and shared: the semantic
1328
+ // judge must not spend tokens on a burst the deterministic breaker is
1329
+ // about to correct itself.
1330
+ const deterministicDecision = evaluateLoopBreak({
1331
+ consecutiveFailures: this.hookConsecutiveFailures,
1332
+ repeatedNoProgressCalls: this.hookRepeatedNoProgressCalls,
1333
+ textRepetitionDetected: detectTextRepetition(this.hookText),
1334
+ ...(this.hookCyclicPattern ? { cyclicPattern: this.hookCyclicPattern } : {}),
1335
+ });
1336
+ this.maybeStartSemanticLoopCheck(deterministicDecision.shouldBreak);
1273
1337
  // Two-stage loop-breaker: stage 1 nudges; a FRESH detection after that
1274
1338
  // injects the harsher final stop-and-report prompt. Signals reset after
1275
1339
  // each injection so stage 2 only fires on new evidence.
1276
1340
  if (this.loopBreakInjected < 2) {
1277
- const decision = evaluateLoopBreak({
1278
- consecutiveFailures: this.hookConsecutiveFailures,
1279
- repeatedNoProgressCalls: this.hookRepeatedNoProgressCalls,
1280
- textRepetitionDetected: detectTextRepetition(this.hookText),
1281
- ...(this.hookCyclicPattern ? { cyclicPattern: this.hookCyclicPattern } : {}),
1282
- });
1341
+ const decision = deterministicDecision;
1283
1342
  if (decision.shouldBreak) {
1284
1343
  const stage = this.loopBreakInjected === 0 ? 1 : 2;
1285
1344
  this.loopBreakInjected = stage;
@@ -1288,6 +1347,9 @@ export class AgentSession {
1288
1347
  this.hookCyclicPattern = null;
1289
1348
  this.hookConsecutiveFailures = 0;
1290
1349
  this.hookRepeatedNoProgressCalls = 0;
1350
+ // The deterministic breaker owns this burst — a semantic verdict from
1351
+ // the same burst must not double-correct on the next poll.
1352
+ this.semanticLoop.verdict = null;
1291
1353
  // Clear the text buffer too — otherwise a stage-1 text-repetition
1292
1354
  // trigger still sees the same repeated tail on the next check and
1293
1355
  // escalates to stage 2 on stale evidence.
@@ -1300,6 +1362,22 @@ export class AgentSession {
1300
1362
  return [buildLoopBreakMessage(decision.reasons, stage === 2)];
1301
1363
  }
1302
1364
  }
1365
+ // Semantic loop-break: an LLM verdict (started by maybeStartSemanticLoopCheck
1366
+ // on a suspicious-but-syntactically-quiet burst) is consumed here, exactly
1367
+ // once, with the deterministic breaker getting priority above. Fail-open:
1368
+ // no verdict or no-loop verdict injects nothing.
1369
+ if (this.semanticLoop.verdict && !this.semanticLoop.injected) {
1370
+ const verdict = this.semanticLoop.verdict;
1371
+ this.semanticLoop.injected = true;
1372
+ this.semanticLoop.verdict = null;
1373
+ // The judged burst has been addressed; a fresh burst must re-accumulate.
1374
+ this.hookConsecutiveFailures = 0;
1375
+ log("INFO", "loop-break", "Injecting semantic loop-break steering", {
1376
+ reason: verdict.reason,
1377
+ });
1378
+ this.eventBus.emit("hook", { kind: "loop_break" });
1379
+ return [buildSemanticLoopMessage(verdict)];
1380
+ }
1303
1381
  if (!this.regroundingInjected && this.compactionOccurred) {
1304
1382
  this.regroundingInjected = true;
1305
1383
  this.eventBus.emit("hook", { kind: "regrounding" });
@@ -1307,6 +1385,159 @@ export class AgentSession {
1307
1385
  }
1308
1386
  return null;
1309
1387
  }
1388
+ /** Fire the semantic loop judge when deterministic evidence is suspicious but
1389
+ * the deterministic breaker stayed quiet — the syntactic blind spot where
1390
+ * every retry differs slightly and the run still makes no progress.
1391
+ * Fire-and-forget: the call runs while the next turn streams, and a finished
1392
+ * verdict is consumed by the NEXT steering poll — never blocking a turn. */
1393
+ maybeStartSemanticLoopCheck(deterministicBreak) {
1394
+ if (!shouldRunSemanticLoopCheck({
1395
+ consecutiveFailures: this.hookConsecutiveFailures,
1396
+ totalFailures: this.hookStats.toolFailures,
1397
+ turns: this.hookStats.turns,
1398
+ lastCheckTurn: this.semanticLoop.lastCheckTurn,
1399
+ checksUsed: this.semanticLoop.checksUsed,
1400
+ checkPending: this.semanticLoop.pending,
1401
+ deterministicBreak,
1402
+ })) {
1403
+ return;
1404
+ }
1405
+ // resetHookState replaces this object on every prompt. A late judge must
1406
+ // not publish a verdict or consume the next run's budget/cooldown.
1407
+ const runState = this.semanticLoop;
1408
+ runState.pending = true;
1409
+ log("INFO", "loop-break", "Starting semantic loop judge", {
1410
+ turn: String(this.hookStats.turns),
1411
+ consecutiveFailures: String(this.hookConsecutiveFailures),
1412
+ recentCalls: String(this.hookRecentCalls.length),
1413
+ });
1414
+ void (async () => {
1415
+ try {
1416
+ const prompt = buildSemanticLoopJudgePrompt(this.hookRecentCalls, this.originalRequest);
1417
+ const raw = await (this.opts.semanticLoopJudge?.(prompt) ??
1418
+ this.callSemanticLoopJudge(prompt));
1419
+ const verdict = parseSemanticLoopVerdict(raw);
1420
+ if (this.semanticLoop === runState && verdict?.loop)
1421
+ runState.verdict = verdict;
1422
+ }
1423
+ catch (error) {
1424
+ // Fail open: judge errors never stop a run. Budget and cooldown are
1425
+ // still consumed in `finally` so a flaky judge cannot retry-loop.
1426
+ log("WARN", "loop-break", "Semantic loop judge failed", {
1427
+ error: error instanceof Error ? error.message : String(error),
1428
+ });
1429
+ }
1430
+ finally {
1431
+ if (this.semanticLoop === runState) {
1432
+ runState.pending = false;
1433
+ runState.checksUsed += 1;
1434
+ runState.lastCheckTurn = this.hookStats.turns;
1435
+ }
1436
+ }
1437
+ })();
1438
+ }
1439
+ /** One-shot judge call on the session's ACTIVE model — deliberately not a
1440
+ * cheaper routing: judging a model's own failure patterns with a weaker
1441
+ * model swaps false negatives for false positives. */
1442
+ async callSemanticLoopJudge(prompt) {
1443
+ const creds = await this.authStorage.resolveCredentials(this.provider, {
1444
+ storageKeys: this.currentAuthStorageKeys(),
1445
+ });
1446
+ const result = stream({
1447
+ provider: this.provider,
1448
+ model: this.model,
1449
+ messages: [{ role: "user", content: prompt }],
1450
+ maxTokens: 500,
1451
+ apiKey: creds.accessToken,
1452
+ accountId: creds.accountId,
1453
+ projectId: creds.projectId,
1454
+ baseUrl: this.baseUrl ?? creds.baseUrl,
1455
+ signal: this.opts.signal,
1456
+ });
1457
+ const response = await withJudgeTimeout(result.response, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS);
1458
+ // Providers differ in reply shape: some return a bare string, others an
1459
+ // array of parts (glm-5.3 among them) — joining text parts covers both,
1460
+ // where the string-only branch silently dropped the whole verdict.
1461
+ const content = response.message.content;
1462
+ if (typeof content === "string")
1463
+ return content;
1464
+ return Array.isArray(content)
1465
+ ? content
1466
+ .filter((part) => part.type === "text")
1467
+ .map((part) => part.text)
1468
+ .join("\n")
1469
+ : "";
1470
+ }
1471
+ /** Independent fresh-context review of the finished work (Codex Guardian
1472
+ * pattern). Spawns a READ-ONLY child on the ACTIVE model, waits bounded,
1473
+ * and returns findings for the acting agent to address — or nothing when
1474
+ * the review passes, is unavailable, or fails (in-thread review remains the
1475
+ * fallback; the feature degrades, never blocks).
1476
+ *
1477
+ * Runs inside the pre-stop poll, so the candidate final answer is already
1478
+ * held by arming and this wait cannot race a streamed answer. */
1479
+ async runIndependentReview(decision) {
1480
+ if (!this.subAgentManager)
1481
+ return [];
1482
+ if (this.independentReviewStarted)
1483
+ return [];
1484
+ // An allow-listed session (a subagent worker itself) must not spawn
1485
+ // harness-owned grandchildren the tool policy never granted.
1486
+ if (this.opts.allowedTools && !this.opts.allowedTools.includes("spawn_agent"))
1487
+ return [];
1488
+ if (decision.score < INDEPENDENT_REVIEW_SCORE_THRESHOLD)
1489
+ return [];
1490
+ this.independentReviewStarted = true;
1491
+ const taskName = `ideal-reviewer-${Math.random().toString(36).slice(2, 8)}`;
1492
+ let agentId;
1493
+ try {
1494
+ const task = buildReviewerTask({
1495
+ originalRequest: this.originalRequest,
1496
+ changedFiles: [...this.hookFileEditCounts.keys()],
1497
+ stats: this.hookStats,
1498
+ triggerReasons: decision.reasons,
1499
+ });
1500
+ // Active model forced at spawn time — never routed to a fast/review model.
1501
+ const snapshot = await this.subAgentManager.spawn(taskName, task, undefined, {
1502
+ model: this.model,
1503
+ tools: REVIEWER_TOOLS,
1504
+ });
1505
+ agentId = snapshot.agent_id;
1506
+ const waited = await this.subAgentManager.wait([agentId], "all", REVIEWER_WAIT_MS);
1507
+ const agent = waited.agents[0];
1508
+ if (!agent || !isTerminalSubAgentState(agent.state)) {
1509
+ // Timeout: collect the straggler so the completion gate cannot fire on
1510
+ // it later, then fall back to the in-thread review.
1511
+ await this.subAgentManager.interrupt(agentId, true).catch(() => { });
1512
+ log("WARN", "ideal", "Independent reviewer timed out; falling back to in-thread review", {
1513
+ agentId,
1514
+ });
1515
+ return [];
1516
+ }
1517
+ const findings = parseReviewerFindings(agent.output ?? "");
1518
+ if (!findings) {
1519
+ log("WARN", "ideal", "Independent reviewer output unparseable; falling back", { agentId });
1520
+ return [];
1521
+ }
1522
+ if (findings.clean) {
1523
+ log("INFO", "ideal", "Independent reviewer verdict: clean", { agentId });
1524
+ return [];
1525
+ }
1526
+ log("INFO", "ideal", "Independent reviewer flagged findings", {
1527
+ agentId,
1528
+ count: String(findings.findings.length),
1529
+ });
1530
+ return [buildIndependentReviewMessage(findings.findings)];
1531
+ }
1532
+ catch (error) {
1533
+ if (agentId)
1534
+ await this.subAgentManager.interrupt(agentId, true).catch(() => { });
1535
+ log("WARN", "ideal", "Independent reviewer failed; falling back to in-thread review", {
1536
+ error: error instanceof Error ? error.message : String(error),
1537
+ });
1538
+ return [];
1539
+ }
1540
+ }
1310
1541
  /**
1311
1542
  * Turn-budget extension gate. The loop consults this instead of stopping
1312
1543
  * mid-task when it exhausts `maxTurns`. Grant ONLY on evidence of progress —
@@ -1424,7 +1655,7 @@ export class AgentSession {
1424
1655
  * Pre-stop Ideal review phase machine. Once review starts, completion is
1425
1656
  * blocked until harness-owned post-injection reads cover every changed file.
1426
1657
  */
1427
- getHookFollowUpMessages() {
1658
+ async getHookFollowUpMessages() {
1428
1659
  const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager);
1429
1660
  if (childCompletionFollowUp)
1430
1661
  return childCompletionFollowUp;
@@ -1515,6 +1746,10 @@ export class AgentSession {
1515
1746
  const driftedFiles = detectTestDrift(this.hookFileEditCounts.keys(), this.cwd).slice(0, 5);
1516
1747
  if (!decision.shouldReview && driftedFiles.length === 0)
1517
1748
  return null;
1749
+ // Independent reviewer first (async, bounded): its findings ride in the
1750
+ // SAME follow-up batch as the in-thread review + coverage requirements, so
1751
+ // addressing everything still costs one extra turn.
1752
+ const independentMessages = await this.runIndependentReview(decision);
1518
1753
  this.reviewCoverage.start(this.hookFileEditCounts.keys());
1519
1754
  this.idealReviewPhase = "reviewing";
1520
1755
  const coverage = this.reviewCoverage.evidence();
@@ -1538,6 +1773,7 @@ export class AgentSession {
1538
1773
  lspMissing: lspEvidence.missing,
1539
1774
  });
1540
1775
  return [
1776
+ ...independentMessages,
1541
1777
  this.withReviewLspEvidence(withReviewCoverageRequirements(buildIdealReviewMessage(decision.reasons, driftedFiles), coverage.missing), lspEvidence),
1542
1778
  ];
1543
1779
  }