@staix/agent-hub 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
@@ -16,7 +16,7 @@ export interface AcpModelAdvertisement {
16
16
  readonly available: readonly string[];
17
17
  readonly wire: Readonly<Record<string, string>>;
18
18
  }
19
- const ACP_MODEL_OPTIONS_MAX = 256;
19
+ export const ACP_MODEL_OPTIONS_MAX = 256;
20
20
  /** Person ids retain the native-word grammar; only an exact receipt-owned wire codec may wrap one. */
21
21
  export function acpLogicalModelId(policy: AcpModelPolicy, wire: unknown): string | undefined {
22
22
  if (policy.idCodec === "qwen-openai") {
@@ -0,0 +1,35 @@
1
+ import { safeModelLabel } from "../omniroute/usage.ts";
2
+ import { ACP_MODEL_OPTIONS_MAX, acpLogicalModelId, type AcpModelPolicy } from "./acp-model-policy.ts";
3
+
4
+ /**
5
+ * #1402 T3: the model id an ACP agent says its session is on, whatever the override policy. Read-only and shape-checked: the three places ACP agents put it are `models.currentModelId` (`session/new`,
6
+ * `session/load`), the `model` select of `configOptions` (`currentValue`) and a model-update payload. A receipt policy that owns an id codec (Qwen's `id(openai)` wire ids) strips it exactly as the
7
+ * override path does; otherwise the id is the wire id through `safeModelLabel`. A value `safeModelLabel` refuses, the placeholder `unknown`, or an absent field names no model, so nothing is guessed.
8
+ */
9
+ function label(value: unknown, policy: AcpModelPolicy | undefined): string | undefined {
10
+ const id = policy?.idCodec ? acpLogicalModelId(policy, value) : safeModelLabel(value);
11
+ const safe = safeModelLabel(id);
12
+ return safe !== undefined && safe.toLowerCase() !== "unknown" ? safe : undefined;
13
+ }
14
+ const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
15
+ /** The model in a `session/new` or `session/load` result (or a `configOptions`-only holder). */
16
+ export function sessionModelId(session: unknown, policy?: AcpModelPolicy): string | undefined {
17
+ const holder = record(session);
18
+ if (!holder) return undefined;
19
+ const fromModels = label(record(holder.models)?.currentModelId, policy);
20
+ if (fromModels !== undefined) return fromModels;
21
+ return configModelId(holder.configOptions, policy);
22
+ }
23
+ function configModelId(options: unknown, policy: AcpModelPolicy | undefined): string | undefined {
24
+ if (!Array.isArray(options) || options.length > ACP_MODEL_OPTIONS_MAX) return undefined;
25
+ const models = options.filter(option => record(option)?.id === "model");
26
+ if (models.length !== 1) return undefined;
27
+ const option = record(models[0])!;
28
+ return option.type === "select" ? label(option.currentValue, policy) : undefined;
29
+ }
30
+ /** The model in a model-update notification: `current_model_update` and the Qwen notice carry `currentModelId`, `config_option_update` carries the options. */
31
+ export function updatedModelId(update: unknown, policy?: AcpModelPolicy): string | undefined {
32
+ const value = record(update);
33
+ if (!value) return undefined;
34
+ return value.configOptions !== undefined ? configModelId(value.configOptions, policy) : label(value.currentModelId, policy);
35
+ }
@@ -16,6 +16,8 @@ import type { StartForm, ModelOverrideSelection } from "./registry-types.ts";
16
16
  import { assessVersion, readTrust } from "./compat.ts";
17
17
  import { acpLogicalModelId, acpModelAdvertisement, type AcpModelAdvertisement, type AcpModelPolicy } from "./acp-model-policy.ts";
18
18
  import { isNativeModelToken } from "./model-token.ts";
19
+ import { sessionModelId, updatedModelId } from "./acp-session-model.ts";
20
+ import type { ModelObservation } from "../hub/events.ts";
19
21
  import type { CapabilityManifest } from "../hub/capabilities.ts";
20
22
  import { acpManifest } from "./native-capabilities.ts";
21
23
 
@@ -254,6 +256,9 @@ export class AcpPeer extends BasePeer {
254
256
  private modelBaseline: string | undefined;
255
257
  private modelSelected: string | undefined;
256
258
  private modelObservation: object = {};
259
+ /** #1402: the model id the session reports now, kept whatever the override policy; `turnModel` is its value when the turn's prompt was sent. Neither is ever invented. */
260
+ private sessionModel: string | undefined;
261
+ private turnModel: string | undefined;
257
262
  private modelBinding: { proc: ChildProcessWithoutNullStreams; session: string; proof: AcpOwnedGroup } | undefined;
258
263
  private modelTurn: { turn: number; selection: ModelOverrideSelection; target: string; sent: boolean; acknowledged: boolean } | undefined;
259
264
  private kimiAgent = false;
@@ -421,6 +426,7 @@ export class AcpPeer extends BasePeer {
421
426
  throw new Error("Configured ACP did not provide a valid native session identity");
422
427
  }
423
428
  this.sessionId = session.sessionId;
429
+ this.sessionModel = sessionModelId(session, this.modelPolicy); this.turnModel = undefined;
424
430
  const modelPolicy = this.modelPolicy;
425
431
  if (modelPolicy && this.modelAdmitted()) {
426
432
  const advertisement = acpModelAdvertisement(modelPolicy, session);
@@ -504,6 +510,11 @@ export class AcpPeer extends BasePeer {
504
510
  acceptsModelOverride(model: string): boolean {
505
511
  return this.modelOverrideState.available && isNativeModelToken(model) && this.modelAdvertisement!.available.includes(model);
506
512
  }
513
+ /** #1402: the model the session was on when the turn that just ended started, read once at its `turn_end` (`session`: the agent's own current model id, not a per-response one). Absent records nothing. */
514
+ observedModel(): ModelObservation | undefined {
515
+ const model = this.turnModel; this.turnModel = undefined;
516
+ return model ? { model, evidence: "session" } : undefined;
517
+ }
507
518
  private observeModelId(model: unknown): void {
508
519
  this.modelObservation = {};
509
520
  const logical = this.modelPolicy && acpLogicalModelId(this.modelPolicy, model);
@@ -698,6 +709,7 @@ export class AcpPeer extends BasePeer {
698
709
  if (this.modelTurn?.turn === turn) this.modelTurn.sent = true;
699
710
  }
700
711
  const fixedPreamble = this.turnRecordPrompt(this.primed ? "" : this.opts.preamble ?? "");
712
+ this.turnModel = this.sessionModel; // the session's model at the turn start
701
713
  // session/prompt answers only when the turn ends, so deliver resolves now and failures come back through onFailed.
702
714
  const prompt = this.request("session/prompt", { sessionId: this.sessionId, prompt: [{ type: "text", text: fixedPreamble ? `${fixedPreamble}\n\n${renderDigest(envs, this.primed)}` : renderDigest(envs, this.primed) }] });
703
715
  const reported = () => { if (this.cancelWait?.turn === turn) this.cancelWait.reported = true; };
@@ -881,6 +893,7 @@ export class AcpPeer extends BasePeer {
881
893
  }
882
894
  if (this.state === "busy" && !this.cancelWait) { this.lastSignAt = Date.now(); this.touch(); }
883
895
 
896
+ if (msg.method === "qwen/notify/session/model-update" && msg.params?.v === 1 && msg.params.sessionId === this.sessionId) this.sessionModel = updatedModelId(msg.params, this.modelPolicy) ?? this.sessionModel;
884
897
  if (this.modelPolicy && msg.method === "qwen/notify/session/model-update") {
885
898
  if (this.modelPolicy.modelUpdate === "qwen/notify/session/model-update" && msg.params?.v === 1 && msg.params.sessionId === this.sessionId) this.observeModelId(msg.params.currentModelId);
886
899
  return; // A setter/control notification is never prompt admission.
@@ -899,6 +912,7 @@ export class AcpPeer extends BasePeer {
899
912
  }
900
913
  if (msg.params?.sessionId && msg.params.sessionId !== this.sessionId) return;
901
914
  const u = msg.params?.update;
915
+ if (u?.sessionUpdate === "current_model_update" || u?.sessionUpdate === "config_option_update") this.sessionModel = updatedModelId(u, this.modelPolicy) ?? this.sessionModel;
902
916
  // Occupancy is the session's, not the turn's: 2.1.1's source text emits usage_update after the prompt
903
917
  // resolves, when the peer may already be idle (read from the source, not observed live; #285). So a
904
918
  // context-used update is accepted while idle too, but then it must name the current session; in a turn the
@@ -16,7 +16,7 @@ function agyLaunch(ctx: LaunchContext): LaunchPlan {
16
16
  export const AGY_DEFINITION: AdapterDefinition = {
17
17
  api: 1,
18
18
  kind: "agy",
19
- projection: { roleRank: 7, helpRank: 4, plannerEligible: false },
19
+ projection: { roleRank: 7, helpRank: 4, plannerEligible: false, conductorEligible: false, reviewerEligible: false },
20
20
  displayName: "Antigravity",
21
21
  family: "agy",
22
22
  transport: "ws-pull",
@@ -52,7 +52,7 @@ export const AGY_DEFINITION: AdapterDefinition = {
52
52
  recoveryRefusal: () => "Antigravity session continuity and resume are unavailable until native behavior is verified",
53
53
  },
54
54
  turnEnd: "native-hook",
55
- cli: { command: "agy", entry: { lifecycleAdmission: true, execute: runAgyEntry }, usage: [["ahub agy [--print-command | --dry-run] [args...]", "optional Antigravity CLI 1.4.x TUI (1.4.2 verified) in this terminal (roster.agy, default off): pull-only via hub_inbox, implementer/verifier only; native permissions unmanaged, no hub sandbox"]], authority: "person", startWords: () => ["agy"] },
55
+ cli: { command: "agy", entry: { lifecycleAdmission: true, execute: runAgyEntry }, usage: [["ahub agy [--print-command | --dry-run] [args...]", "optional Antigravity CLI 1.4.x TUI (1.4.2 verified) in this terminal (roster.agy, default off): pull-only via hub_inbox, implementer/verifier only; native permissions unmanaged, no hub sandbox", "start optional Antigravity CLI in this terminal"]], authority: "person", startWords: () => ["agy"] },
56
56
  display: DISPLAY,
57
57
  routing: { allowedRoles: ["implementer", "verifier"] },
58
58
  reviewer: { defaultPool: false, declaration: "automatic", unavailable: "agy is an implementer peer (#485)" },
@@ -2,12 +2,18 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, join, relative } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
+ import { safeModelLabel } from "../../omniroute/usage.ts";
5
6
  import type { NativeFactsInput, NativeFactsPort, NativeFactsReadOptions, NativeFactsTranscript } from "../registry-types.ts";
6
7
 
7
8
  const EVENTS = ["SessionStart", "PreInvocation", "PostInvocation", "PreToolUse", "PostToolUse", "Stop"] as const;
8
9
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
10
  const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
10
11
 
12
+ /** #1402: Antigravity names the session's model in every hook payload (`modelName`, verified for 1.4.3 to 1.5.3). A value `safeModelLabel` refuses or the placeholder `unknown` names none; an alias is kept as reported. */
13
+ function agyModel(value: unknown): string | undefined {
14
+ const model = safeModelLabel(value);
15
+ return model !== undefined && model.toLowerCase() !== "unknown" ? model : undefined;
16
+ }
11
17
  /** The pinned 1.4.2 envelope has no event name: the managed command supplies it separately. */
12
18
  export function decodeAgyHook(event: string, value: unknown): NativeFactsInput | undefined {
13
19
  if (!(EVENTS as readonly string[]).includes(event) || !record(value) || typeof value.conversationId !== "string" || !UUID.test(value.conversationId)
@@ -54,6 +60,7 @@ export function decodeAgyHook(event: string, value: unknown): NativeFactsInput |
54
60
  workspacePaths: value.workspacePaths as string[], tool, input,
55
61
  ...(Number.isSafeInteger(value.stepIdx) && (value.stepIdx as number) >= 0 ? { toolUseId: `${value.conversationId}:${value.stepIdx}` } : {}),
56
62
  ...(Number.isSafeInteger(value.invocationNum) && (value.invocationNum as number) >= 0 ? { invocation: value.invocationNum as number } : {}),
63
+ ...(agyModel(value.modelName) ? { model: agyModel(value.modelName)! } : {}),
57
64
  ...(event === "Stop" ? { fullyIdle: value.fullyIdle as boolean, terminationReason: typeof value.terminationReason === "string" ? value.terminationReason : "" } : {}) };
58
65
  }
59
66
 
@@ -433,7 +433,7 @@ function toolListFor(lifecycle: Awaited<ReturnType<typeof activeLifecycle>>) {
433
433
  ]
434
434
  : []),
435
435
  ]),
436
- ...profileTaskTools(profile, lifecycle?.stages, lifecycle?.criteria).filter(tool => (lifecycle !== undefined || tool.name !== "hub_sdlc_record") && (!deliveryOnly || tool.name !== "hub_delivery_retry")),
436
+ ...profileTaskTools(profile, lifecycle?.stages, lifecycle?.criteria, lifecycle?.audit, lifecycle?.survey, lifecycle?.wait).filter(tool => (lifecycle !== undefined || tool.name !== "hub_sdlc_record") && (!deliveryOnly || tool.name !== "hub_delivery_retry")),
437
437
  ...projectConductorTools(lifecycle?.startPeers),
438
438
  ], lifecycle?.readOnly).filter(tool => !permissionTool || IMPLEMENTER_HUB_TOOL_NAMES.includes(tool.name)),
439
439
  };
@@ -17,6 +17,7 @@ import { ClaudeTaskSessions } from "./claude-task-sessions.ts";
17
17
  import { formatClaudeFailure, type ClaudeFailureTrace } from "../hub/claude-failure-stage.ts";
18
18
  import type { PermissionMode } from "../hub/permission-mode.ts";
19
19
  import type { ReviewerPrintUsage } from "./reviewer-print.ts";
20
+ import { resultModel } from "./print-result-model.ts";
20
21
 
21
22
  const provenVersions = new WeakMap<() => boolean, string>();
22
23
  function provenVersion(binding: () => boolean): string | undefined { return provenVersions.get(binding); }
@@ -99,6 +100,12 @@ export async function proveClaudeImplementer(peer: string, command: readonly str
99
100
 
100
101
  /** One owned print child at a time. Idle holds no native process; task continuity is ids-only on disk. */
101
102
  export class ClaudeImplementerPeer extends BasePeer {
103
+ /** #1402: the model the last `result` row's modelUsage named; read once at the turn end. */
104
+ private servedModel: string | undefined;
105
+ observedModel(): import("../hub/events.ts").ModelObservation | undefined {
106
+ const model = this.servedModel; this.servedModel = undefined;
107
+ return model ? { model, evidence: "served" } : undefined;
108
+ }
102
109
  readonly hubNative = true;
103
110
  readonly hubOwned: boolean = true;
104
111
  private generation = 0;
@@ -273,6 +280,7 @@ export class ClaudeImplementerPeer extends BasePeer {
273
280
  if (row?.type !== "result" || result) return;
274
281
  result = true; failed = row.is_error === true || row.subtype !== "success";
275
282
  if (row.usage) this.options.onUsage?.(row.usage, group.task);
283
+ { const model = resultModel(row); if (model) this.servedModel = model; }
276
284
  } });
277
285
  this.owned = child;
278
286
  let code: number | null;
@@ -29,7 +29,10 @@ export interface OwnedPrintChildOptions {
29
29
  onLimit?: () => void;
30
30
  maxFrameBytes?: number;
31
31
  maxOutputBytes?: number;
32
+ /** Opt-in host diagnostic only; raw text is never a frame, activity signal or public log. */
33
+ captureStderr?: true;
32
34
  }
35
+ export type OwnedStderrReceipt = { status: "complete"; text: string } | { status: "unknown" };
33
36
 
34
37
  /** Shared owned print transport, independent of reviewer or implementer lifecycle and MCP authority. */
35
38
  export class OwnedPrintChild {
@@ -38,6 +41,17 @@ export class OwnedPrintChild {
38
41
  readonly done: Promise<number | null>;
39
42
  private stopping: Promise<void> | undefined;
40
43
  private limited = false;
44
+ private stderrChunks: Buffer[] = [];
45
+ private stderrBytes = 0;
46
+ private stderrEnded = false;
47
+ private stderrUnknown = false;
48
+ private settled = false;
49
+ /** Only the current owned child's complete bounded stream after confirmed group settlement is usable. */
50
+ stderrAfterSettlement(): OwnedStderrReceipt {
51
+ if (!this.options.captureStderr || !this.settled || !this.stderrEnded || this.stderrUnknown || this.options.current?.() === false) return { status: "unknown" };
52
+ try { return { status: "complete", text: new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(this.stderrChunks)) }; }
53
+ catch { return { status: "unknown" }; }
54
+ }
41
55
 
42
56
  constructor(private readonly options: OwnedPrintChildOptions) {
43
57
  const [command, ...prefix] = options.command;
@@ -45,7 +59,7 @@ export class OwnedPrintChild {
45
59
  const child = this.process = spawn(command, [...prefix, ...options.args], {
46
60
  cwd: options.cwd, detached: true,
47
61
  env: peerChildEnv(options.peer, options.envMode === "replace" ? options.env : { ...process.env, ...options.env }),
48
- stdio: ["pipe", "pipe", "ignore"],
62
+ stdio: ["pipe", "pipe", options.captureStderr ? "pipe" : "ignore"],
49
63
  });
50
64
  // ponytail: 256 KiB per NDJSON frame and 4 MiB stdout by default; raise only with native receipts.
51
65
  const frameLimit = options.maxFrameBytes ?? 256 * 1024, outputLimit = options.maxOutputBytes ?? 4 * 1024 * 1024;
@@ -53,6 +67,16 @@ export class OwnedPrintChild {
53
67
  let inputFailed = false;
54
68
  const current = () => !this.limited && options.current?.() !== false;
55
69
  const limit = () => { if (!this.limited) { this.limited = true; options.onLimit?.(); } };
70
+ if (options.captureStderr) {
71
+ child.stderr!.on("data", (chunk: Buffer) => {
72
+ if (this.stderrUnknown) return;
73
+ this.stderrBytes += chunk.length;
74
+ if (options.current?.() === false || this.stderrBytes > 64 * 1024) { this.stderrUnknown = true; this.stderrChunks = []; return; }
75
+ this.stderrChunks.push(Buffer.from(chunk));
76
+ });
77
+ child.stderr!.once("end", () => { this.stderrEnded = true; });
78
+ child.stderr!.once("error", () => { this.stderrUnknown = true; this.stderrChunks = []; });
79
+ }
56
80
  this.done = new Promise((resolve, reject) => {
57
81
  child.once("error", error => { options.onError?.(error); reject(error); });
58
82
  child.stdin!.on("error", () => { inputFailed = true; /* exit, rather than a prompt write, settles the owned child */ });
@@ -84,7 +108,7 @@ export class OwnedPrintChild {
84
108
  });
85
109
  child.once("exit", code => {
86
110
  options.onLeaderExit?.();
87
- void this.stop().then(() => resolve(code), error => reject(new PrintChildCleanupError((error as Error).message)));
111
+ void this.stop().then(() => { this.settled = true; resolve(code); }, error => reject(new PrintChildCleanupError((error as Error).message)));
88
112
  });
89
113
  });
90
114
  }
@@ -2,6 +2,8 @@ import { childEnv } from "../hub/child-process.ts";
2
2
  import { hubGitSync } from "../hub/git.ts";
3
3
  import { changedPathGroups } from "../hub/review-brief.ts";
4
4
  import { type Envelope } from "../hub/envelope.ts";
5
+ import { resultModel } from "./print-result-model.ts";
6
+ import { claudeReviewerQuota } from "./definitions/native-quota.ts";
5
7
  import { ReviewerPrintPeer, type ReviewerBackend, type ReviewerPrintOptions } from "./reviewer-print.ts";
6
8
 
7
9
  export interface ClaudePrintUsage { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }
@@ -75,6 +77,7 @@ export function reviewDiff(cwd: string, commit: unknown, policy: { privatePath(p
75
77
 
76
78
  export const claudeReviewerBackend: ReviewerBackend = {
77
79
  id: "claude",
80
+ failure: claudeReviewerQuota,
78
81
  prepare: async context => ({ command: context.command ?? ["claude"],
79
82
  args: claudePrintArgs(context.sessionId, context.mcpConfig, context.systemPrompt, context.privatePaths),
80
83
  isolation: { backend: "claude", version: "existing-223-contract", binary: (context.command ?? ["claude"])[0]!, profile: "strict-mcp-read-grep-glob",
@@ -83,6 +86,7 @@ export const claudeReviewerBackend: ReviewerBackend = {
83
86
  const row = event as { type?: string; usage?: ClaudePrintUsage } | null;
84
87
  return row?.type === "result" ? row.usage : undefined;
85
88
  },
89
+ model: event => (event as { type?: string } | null)?.type === "result" ? resultModel(event) : undefined,
86
90
  };
87
91
 
88
92
  /** Compatibility wrapper for the released Claude transport and its existing tests. */
@@ -1,3 +1,5 @@
1
+ import { codexAccountUsage, codexQuotaWindowInput } from "./definitions/native-quota.ts";
2
+ import type { QuotaAccountUsage } from "../hub/quota-account.ts";
1
3
  import type { ModelOverrideSelection } from "./registry-types.ts";
2
4
  import { isNativeModelToken } from "./model-token.ts";
3
5
  import { spawn, type ChildProcess } from "node:child_process";
@@ -6,6 +8,7 @@ import { renderDigest, replyAudience, replyParent, type Envelope, type PeerId }
6
8
  import type { PermissionMode } from "../hub/permission-mode.ts";
7
9
  import type { DeliveryFailureCause } from "../hub/delivery-failure.ts";
8
10
  import { BasePeer, type FrontendProxyPort } from "../hub/peers.ts";
11
+ import type { ModelObservation } from "../hub/events.ts";
9
12
  import { codexContext, type ContextReading } from "../hub/context-window.ts";
10
13
  import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
11
14
  import type { ContextReader } from "./registry-types.ts";
@@ -13,6 +16,9 @@ import type { CapabilityManifest } from "../hub/capabilities.ts";
13
16
  import { codexSkillsManifest, NATIVE_PINS } from "./native-capabilities.ts";
14
17
  import { ACTION_BUDGET_OPTION, type ActionGateVerdict, type PermissionRequest } from "./acp.ts";
15
18
 
19
+ // ponytail: paused quota reads use a fixed 60s cadence; a validated operational cadence setting is the upgrade path if tuning is needed.
20
+ const PAUSED_USAGE_POLL_MS = 60_000;
21
+
16
22
  const UNIDENTIFIED_CANCELLATION_NOTICE = "Codex cancelled turn has no verified native id; reattach the native session before further hub delivery";
17
23
  const PLANNER_SANDBOX_REFUSAL = "Codex planner thread requires a confirmed read-only sandbox";
18
24
 
@@ -50,8 +56,10 @@ export interface CodexOptions {
50
56
  extraArgs?: string[];
51
57
  /** Appended to the standing instruction of the first delivery (role contract). */
52
58
  preamble?: string;
53
- /** Raw `rateLimits` snapshots from app-server, and `hard = true` when a turn was refused for quota. */
54
- onUsage?: (rateLimits: unknown, hard: boolean) => void;
59
+ /** Window-only native fields plus allowlisted account diagnostics; hard means a turn was refused for quota. */
60
+ onUsage?: (rateLimits: unknown, hard: boolean, accountUsage?: QuotaAccountUsage) => void;
61
+ /** Host-only observation of the canonical account pause. It grants no resume authority. */
62
+ usagePause?: { current(): boolean; subscribe(changed: () => void): () => void };
55
63
  /** Tokens the thread used since the previous update (see `tokenTotal` for how they are counted). */
56
64
  onTokens?: (added: number) => void;
57
65
  /**
@@ -119,6 +127,9 @@ export class CodexPeer extends BasePeer {
119
127
  private readonly nativeApprovalPolicies = new Map<string, unknown>();
120
128
  private readonly overriddenApprovals = new Set<string>();
121
129
  private readonly nativeModels = new Map<string, { sequence: number; model?: string }>();
130
+ /** #1402: the model each thread reported (`thread/start`, `thread/resume`) or was started with (an accepted `turn/start`), and the model Codex rerouted the running turn to. Never invented. */
131
+ private readonly threadModels = new Map<string, string>();
132
+ private reroutedModel: string | undefined;
122
133
  private modelStartSequence = 0;
123
134
  private readonly restoringApprovals = new Map<string | number, string>();
124
135
  private proc: ChildProcess | undefined;
@@ -151,7 +162,11 @@ export class CodexPeer extends BasePeer {
151
162
  private unboundAccepted = false;
152
163
  private nextId = -1;
153
164
  private readonly pending = new Map<number, { resolve: (result?: any) => void; reject: (e: Error, failureCause?: DeliveryFailureCause) => void; deliveryId?: string; kind?: "deliver" | "steer"; modelStart?: ModelStartOrder; expectedTurnId?: string; afterTurn?: () => void; invalidate?: (reason: string, failureCause?: DeliveryFailureCause) => void }>();
154
- private usageTimer: ReturnType<typeof setInterval> | undefined;
165
+ private usageTimer: ReturnType<typeof setTimeout> | undefined;
166
+ private usageUnsubscribe: (() => void) | undefined;
167
+ private usageEpoch = 0;
168
+ private usageStopped = false;
169
+ private readonly usageRequests = new Map<number, ReturnType<typeof setTimeout>>();
155
170
  private injected: Envelope | undefined; // the hub envelope that started the current turn, if any
156
171
  private answering: Envelope[] = []; // everything delivered or steered into the current turn: who its answer is for
157
172
  private lastAnswer = "";
@@ -203,7 +218,8 @@ export class CodexPeer extends BasePeer {
203
218
  }
204
219
 
205
220
  async start(): Promise<void> {
206
- this.nativeModels.clear(); this.modelStartSequence = 0;
221
+ this.usageStopped = false;
222
+ this.nativeModels.clear(); this.threadModels.clear(); this.reroutedModel = undefined; this.modelStartSequence = 0;
207
223
  const upstream = this.opts.upstreamUrl ?? (await this.spawnAppServer());
208
224
  try {
209
225
  this.server = Bun.serve<Link>({
@@ -249,6 +265,8 @@ export class CodexPeer extends BasePeer {
249
265
  }
250
266
 
251
267
  async stop(): Promise<void> {
268
+ this.usageStopped = true;
269
+ this.stopUsagePolling();
252
270
  this.abortActionWaits();
253
271
  this.server?.stop(true);
254
272
  this.claimedTui?.tui.close(1001, "hub shutting down");
@@ -539,7 +557,7 @@ export class CodexPeer extends BasePeer {
539
557
  link.up.close();
540
558
  if (this.claimedTui === link) this.claimedTui = undefined;
541
559
  if (this.link !== link) return;
542
- clearInterval(this.usageTimer);
560
+ this.stopUsagePolling();
543
561
  this.link = undefined;
544
562
  this.restoringApprovals.clear();
545
563
  this.threadId = "";
@@ -634,11 +652,30 @@ export class CodexPeer extends BasePeer {
634
652
  if ((this.nativeModels.get(start.thread)?.sequence ?? 0) >= start.sequence) return undefined;
635
653
  const actual = model ?? (inherit ? this.nativeModelHint(start.thread) : undefined);
636
654
  this.nativeModels.set(start.thread, { sequence: start.sequence, ...(actual === undefined ? {} : { model: actual }) });
655
+ this.rememberThreadModel(start.thread, actual);
637
656
  // ponytail: keep at most 128 thread receipts; older defaults are unknown until native model readback is added.
638
657
  if (this.nativeModels.size > 128) this.nativeModels.delete(this.nativeModels.keys().next().value!);
639
658
  return actual === undefined ? {} : { model: actual };
640
659
  }
641
660
 
661
+ private rememberThreadModel(thread: string, model: unknown): void {
662
+ if (typeof model !== "string" || !model) return;
663
+ this.threadModels.delete(thread); this.threadModels.set(thread, model);
664
+ if (this.threadModels.size > 128) this.threadModels.delete(this.threadModels.keys().next().value!);
665
+ }
666
+
667
+ /**
668
+ * #1402: what the native surface reported for the turn that just ended, read once at its `turn_end`. A `model/rerouted` notification names the model Codex served for the turn (`served`);
669
+ * otherwise the thread's reported or accepted model (`session`). Codex's `thread/start`, `thread/resume` and `turn/start` replies carry no per-response model, so nothing here is `served` unless
670
+ * Codex said so; an absent field records nothing. Verified against the app-server schema of codex-cli 0.167.2.
671
+ */
672
+ observedModel(): ModelObservation | undefined {
673
+ const served = this.reroutedModel; this.reroutedModel = undefined;
674
+ if (served) return { model: served, evidence: "served" };
675
+ const session = this.threadModels.get(this.threadId);
676
+ return session ? { model: session, evidence: "session" } : undefined;
677
+ }
678
+
642
679
  private retireRejectedModelSelection(link: Link): void {
643
680
  const candidate = link.rejectedModelSelection;
644
681
  if (!candidate || link !== this.link || candidate.epoch !== this.contextEpoch || candidate.thread !== this.threadId ||
@@ -751,6 +788,7 @@ export class CodexPeer extends BasePeer {
751
788
  const thread = msg.result.thread.id;
752
789
  if (!this.overriddenApprovals.has(thread) && msg.result.approvalPolicy != null) this.nativeApprovalPolicies.set(thread, msg.result.approvalPolicy);
753
790
  this.adopt(link, msg.result.thread.id, tracked === "thread/start");
791
+ this.rememberThreadModel(msg.result.thread.id, msg.result.model);
754
792
  }
755
793
  }
756
794
  else if (msg.method) this.onNotification(link, msg.method, msg.params ?? {});
@@ -861,10 +899,7 @@ export class CodexPeer extends BasePeer {
861
899
  this.opts.log?.(`[${this.id}] thread ${threadId}`);
862
900
  this.opts.onThread?.(threadId, fresh);
863
901
  this.setState("idle");
864
- this.readUsage();
865
- clearInterval(this.usageTimer);
866
- this.usageTimer = setInterval(() => this.readUsage(), this.opts.usagePollMs ?? 600_000);
867
- this.usageTimer.unref?.();
902
+ this.startUsagePolling(link);
868
903
  }
869
904
 
870
905
  /**
@@ -901,19 +936,55 @@ export class CodexPeer extends BasePeer {
901
936
  });
902
937
  }
903
938
 
904
- /** account/rateLimits/read through the TUI's connection, with a hub id so the answer never reaches the TUI. */
939
+ private stopUsagePolling(): void {
940
+ this.usageEpoch++;
941
+ clearTimeout(this.usageTimer); this.usageTimer = undefined;
942
+ const unsubscribe = this.usageUnsubscribe; this.usageUnsubscribe = undefined;
943
+ try { unsubscribe?.(); } catch { /* observational subscription only */ }
944
+ for (const [id, timer] of this.usageRequests) { clearTimeout(timer); this.pending.delete(id); }
945
+ this.usageRequests.clear();
946
+ }
947
+
948
+ private startUsagePolling(link: Link): void {
949
+ this.stopUsagePolling();
950
+ if (!this.opts.onUsage || this.usageStopped) return;
951
+ const epoch = this.usageEpoch;
952
+ const current = () => !this.usageStopped && this.usageEpoch === epoch && this.link === link && link.up.readyState === WebSocket.OPEN;
953
+ const schedule = () => {
954
+ if (!current()) return;
955
+ clearTimeout(this.usageTimer); this.usageTimer = undefined;
956
+ let paused: boolean;
957
+ try { paused = this.opts.usagePause?.current() === true; } catch { return; }
958
+ this.usageTimer = setTimeout(() => {
959
+ if (!current()) return;
960
+ this.readUsage(); schedule();
961
+ }, paused ? PAUSED_USAGE_POLL_MS : this.opts.usagePollMs ?? 600_000);
962
+ this.usageTimer.unref?.();
963
+ };
964
+ try { this.usageUnsubscribe = this.opts.usagePause?.subscribe(schedule); } catch { return; }
965
+ this.readUsage(); schedule();
966
+ }
967
+
968
+ /** account/rateLimits/read through the TUI's connection; late replies never escape or update a replacement input. */
905
969
  private readUsage(): void {
906
- const link = this.link;
907
- if (!this.opts.onUsage || !link || link.up.readyState !== WebSocket.OPEN) return;
970
+ const link = this.link, epoch = this.usageEpoch;
971
+ if (this.usageStopped || !this.opts.onUsage || !link || link.up.readyState !== WebSocket.OPEN) return;
908
972
  const id = this.nextId--;
909
- this.pending.set(id, { resolve: (result) => this.opts.onUsage?.(result?.rateLimits, false), reject: () => {} });
910
- link.up.send(JSON.stringify({ method: "account/rateLimits/read", id }));
911
- setTimeout(() => this.pending.delete(id), 30_000).unref?.(); // an unanswered poll must not pile up until detach
973
+ const finish = () => { clearTimeout(this.usageRequests.get(id)); this.usageRequests.delete(id); };
974
+ const timer = setTimeout(() => { this.pending.delete(id); this.usageRequests.delete(id); }, 30_000);
975
+ timer.unref?.(); this.usageRequests.set(id, timer);
976
+ this.pending.set(id, { resolve: result => {
977
+ finish();
978
+ if (!this.usageStopped && this.link === link && this.usageEpoch === epoch)
979
+ this.opts.onUsage?.(codexQuotaWindowInput(result?.rateLimits), false, codexAccountUsage(result));
980
+ }, reject: finish });
981
+ try { link.up.send(JSON.stringify({ method: "account/rateLimits/read", id })); }
982
+ catch { finish(); this.pending.delete(id); }
912
983
  }
913
984
 
914
985
  private onNotification(link: Link, method: string, params: any): void {
915
986
  // Account-level notifications carry no threadId.
916
- if (link === this.link && method === "account/rateLimits/updated") return void this.opts.onUsage?.(params.rateLimits, false);
987
+ if (link === this.link && method === "account/rateLimits/updated") return void this.opts.onUsage?.(codexQuotaWindowInput(params.rateLimits), false);
917
988
  if (link === this.link && method === "error" && params.error?.codexErrorInfo === "usageLimitExceeded") {
918
989
  this.opts.onUsage?.({ rateLimitReachedType: "usageLimitExceeded" }, true);
919
990
  }
@@ -927,6 +998,8 @@ export class CodexPeer extends BasePeer {
927
998
  return;
928
999
  }
929
1000
  if (this.unidentifiedCancellation) return; // native traffic is still forwarded to its TUI; hub attribution is fenced
1001
+ // #1402: a reroute is the model of the turn it names, so it passes both fences above (a retired turn or a fenced cancellation never becomes a later turn's served model).
1002
+ if (method === "model/rerouted") { if (typeof params.toModel === "string" && params.toModel) this.reroutedModel = params.toModel; return; }
930
1003
  const unknownTurn = () => [...this.activeTurns].some(id => id.startsWith("unknown:"));
931
1004
  if (method === "thread/tokenUsage/updated") {
932
1005
  const reader = this.opts.contextReader;
@@ -946,6 +1019,7 @@ export class CodexPeer extends BasePeer {
946
1019
  return;
947
1020
  }
948
1021
  if (method === "turn/started") {
1022
+ this.reroutedModel = undefined; // a reroute whose turn end was never read cannot carry into another turn
949
1023
  link.rejectedModelSelection = undefined;
950
1024
  // The notification has no request id. Conservatively protect every outstanding capture on
951
1025
  // this bound thread rather than retiring a possibly accepted selection on a later RPC error.
@@ -1,4 +1,5 @@
1
1
  import { isNativeModelToken } from "./model-token.ts";
2
+ import { codexReviewerQuota } from "./definitions/native-quota.ts";
2
3
  import { DENY_NAMES, DENY_SEGMENTS } from "@staix/agent-mem/platform";
3
4
  import { assessVersion, COMPAT } from "./compat.ts";
4
5
  import { createHash } from "node:crypto";
@@ -8,7 +9,7 @@ import { createRequire } from "node:module";
8
9
  import { homedir, tmpdir } from "node:os";
9
10
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
10
11
  import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
11
- import { realPath } from "../hub/project.ts";
12
+ import { hubHome, realPath } from "../hub/project.ts";
12
13
  import type { ReviewerBackend, ReviewerCauseClass, ReviewerLaunch, ReviewerPrepareContext } from "./reviewer-print.ts";
13
14
 
14
15
  const TOOLS = ["hub_review", "hub_task_show"];
@@ -48,6 +49,58 @@ export function codexCoreDenyGlobs(names: readonly string[] = DENY_NAMES, segmen
48
49
  }
49
50
 
50
51
  const inside = (file: string, root: string) => { const part = relative(root, file); return part === "" || part !== ".." && !part.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) && !isAbsolute(part); };
52
+ /**
53
+ * #1493: the proof's public canary lives in a fresh fixture root. A deny entry that contains the directory the root is made in puts the canary under
54
+ * a denied tree, the proof's own read fails, and the leg reads as `sandbox_proof` with nothing naming the entry. This asks the same question the
55
+ * sandbox will: does any deny pattern match a directory on the chain from `/` to the candidate base (a match denies everything below it)?
56
+ * `*` stays inside one path segment, `**` crosses segments, `?` is one non-separator character, and a closed `[...]` class is kept.
57
+ */
58
+ function globRegExp(pattern: string): RegExp {
59
+ let source = "";
60
+ for (let i = 0; i < pattern.length; i++) {
61
+ const char = pattern[i]!;
62
+ if (char === "*") { if (pattern[i + 1] === "*") { source += ".*"; i++; } else source += "[^/]*"; }
63
+ else if (char === "?") source += "[^/]";
64
+ else if (char === "[" && pattern.indexOf("]", i + 2) > 0) { const close = pattern.indexOf("]", i + 2); source += pattern.slice(i, close + 1); i = close; }
65
+ else source += char.replace(/[\\^$.|+(){}\[\]]/g, "\\$&");
66
+ }
67
+ return new RegExp(`^${source}$`);
68
+ }
69
+ export function denyCoversDirectory(patterns: readonly string[], directory: string): boolean {
70
+ const chain: string[] = [];
71
+ for (let current = directory; ; current = dirname(current)) { chain.push(current); if (dirname(current) === current) break; }
72
+ return patterns.some(pattern => { let matcher: RegExp; try { matcher = globRegExp(pattern); } catch { return true; } return chain.some(part => matcher.test(part)); });
73
+ }
74
+ /** A fixture base no deny pattern covers: the system temp directory, else the hub's own per-user directory, else a refusal that names no entry. */
75
+ class FixtureRootError extends Error { constructor() { super("fixture root denied"); } }
76
+ function fixtureBase(patterns: readonly string[]): string {
77
+ const temp = realPath(tmpdir());
78
+ if (!denyCoversDirectory(patterns, temp)) return temp;
79
+ const own = join(hubHome(), "reviewer-proof");
80
+ mkdirSync(own, { recursive: true, mode: 0o700 });
81
+ const canonical = realPath(own);
82
+ if (denyCoversDirectory(patterns, canonical)) throw new FixtureRootError();
83
+ return canonical;
84
+ }
85
+ /** The expanded deny patterns for `ctx.privatePaths`, exactly as the proof's filesystem policy names them (with and without a resolved form). */
86
+ function privatePathPatterns(entries: readonly string[], cwd: string): string[] {
87
+ const out = new Set<string>();
88
+ for (const entry of entries) {
89
+ if (typeof entry !== "string" || !entry || Buffer.byteLength(entry) > 4096 || /\p{Cc}/u.test(entry)) throw new Error("invalid private path policy");
90
+ // Native Seatbelt supports *, ?, and closed character classes, not brace alternatives.
91
+ if (/[{}]/.test(entry)) throw new Error("unverified private path pattern");
92
+ const homePath = entry === "~" || entry.startsWith("~/");
93
+ const absolute = homePath ? resolve(homedir(), entry.slice(2)) : isAbsolute(entry) ? entry : resolve(cwd, entry);
94
+ out.add(absolute);
95
+ if (!/[?*\[\]]/.test(absolute) && existsSync(absolute)) out.add(realPath(absolute));
96
+ if (!isAbsolute(entry) && !homePath && entry !== "." && entry !== "..") {
97
+ out.add(join(cwd, "**", entry));
98
+ // ctx combines PII path patterns and local substring denies: broadening is safer than omission.
99
+ if (!/[?*\[\]]/.test(entry)) out.add(join(cwd, "**", `*${entry.replace(/^\.\//, "").replace(/\/$/, "")}*`));
100
+ }
101
+ }
102
+ return [...out];
103
+ }
51
104
  const object = (value: unknown): Record<string, unknown> => {
52
105
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid metadata");
53
106
  return value as Record<string, unknown>;
@@ -242,7 +295,11 @@ async function prepare(ctx: ReviewerPrepareContext): Promise<ReviewerLaunch | {
242
295
  if (observedTransport.type !== "stdio" || observedTransport.command !== hub.command || JSON.stringify(observedTransport.args ?? []) !== JSON.stringify(hub.args) || Object.keys(observedEnv).length !== Object.keys(intendedEnv).length || Object.entries(intendedEnv).some(([key, value]) => observedEnv[key] !== value)) throw new Error("hub transport changed");
243
296
  // A real native sandbox probes a fresh private fixture: the model never sees these files.
244
297
  leg = "sandbox_proof";
245
- root = realPath(mkdtempSync(join(tmpdir(), "ahub-codex-review-isolation-")));
298
+ const privatePatterns = privatePathPatterns(ctx.privatePaths, cwd);
299
+ // The credential roots are checked again, strictly, below; a root that cannot be resolved here is left to that check and its own cause class.
300
+ const credentialPatterns: string[] = [];
301
+ try { for (const { path, label } of hostCredentialRoots(env, cwd)) credentialPatterns.push(path, canonicalLabelled(path, label)); } catch { /* reported by denyCredentialRoots below */ }
302
+ root = realPath(mkdtempSync(join(fixtureBase([...privatePatterns, ...codexCoreDenyGlobs(), ...credentialPatterns]), "ahub-codex-review-isolation-")));
246
303
  const privateFile = join(root, "private.env"), publicFile = join(root, "public.txt"), writeFile = join(root, "write-proof");
247
304
  const coreName = join(root, ".env"), coreStateDir = join(root, ".agenthub", "state"), coreState = join(coreStateDir, "private.txt");
248
305
  const fixtureHome = join(root, "host-home"), hostConfig = join(fixtureHome, ".config", "gh", "hosts.yml"), hostKube = join(fixtureHome, ".kube", "config"), hostDocker = join(fixtureHome, ".docker", "config.json"), hostAlias = join(root, "host-alias.yml");
@@ -259,21 +316,7 @@ async function prepare(ctx: ReviewerPrepareContext): Promise<ReviewerLaunch | {
259
316
  for (const glob of codexCoreDenyGlobs()) filesystem[glob] = "deny";
260
317
  denyCredentialRoots(filesystem, [...hostCredentialRoots(env, cwd), ...hostCredentialRoots({ HOME: fixtureHome }, cwd)], cwd);
261
318
  leg = "sandbox_proof";
262
- for (const entry of ctx.privatePaths) {
263
- if (typeof entry !== "string" || !entry || Buffer.byteLength(entry) > 4096 || /\p{Cc}/u.test(entry)) throw new Error("invalid private path policy");
264
- // Native Seatbelt supports *, ?, and closed character classes, not brace alternatives.
265
- if (/[{}]/.test(entry)) throw new Error("unverified private path pattern");
266
- const homePath = entry === "~" || entry.startsWith("~/");
267
- const absolute = homePath ? resolve(homedir(), entry.slice(2)) : isAbsolute(entry) ? entry : resolve(cwd, entry);
268
- const patterns = new Set([absolute]);
269
- if (!/[?*\[\]]/.test(absolute) && existsSync(absolute)) patterns.add(realPath(absolute));
270
- if (!isAbsolute(entry) && !homePath && entry !== "." && entry !== "..") {
271
- patterns.add(join(cwd, "**", entry));
272
- // ctx combines PII path patterns and local substring denies: broadening is safer than omission.
273
- if (!/[?*\[\]]/.test(entry)) patterns.add(join(cwd, "**", `*${entry.replace(/^\.\//, "").replace(/\/$/, "")}*`));
274
- }
275
- for (const pattern of patterns) { filesystem[pattern] = "deny"; filesystem[`${pattern.replace(/\/$/, "")}/**`] = "deny"; }
276
- }
319
+ for (const pattern of privatePatterns) { filesystem[pattern] = "deny"; filesystem[`${pattern.replace(/\/$/, "")}/**`] = "deny"; }
277
320
  const profile = { filesystem, network: { enabled: false } }, permissions = ["-c", `permissions=${toml({ "ahub-review": profile })}`, "-c", 'default_permissions="ahub-review"'];
278
321
  // ponytail: drain the pinned catalog without retaining it, capped at 4 MiB; replace with quiet config validation when the native CLI provides it.
279
322
  await run(["debug", "models", "--bundled", ...policy, ...permissions], false, 4 * 1024 * 1024);
@@ -293,6 +336,8 @@ async function prepare(ctx: ReviewerPrepareContext): Promise<ReviewerLaunch | {
293
336
  if (root) { try { rmSync(root, { recursive: true, force: true }); } catch { /* unavailable remains refused */ } }
294
337
  // Name only the path class of an unusable credential root so a stale ~/.docker link is fixable; never a path or contents.
295
338
  if (error instanceof VersionRefusal) return { unavailable: error.message, causeClass: "version" };
339
+ // #1493: no directory the proof could use for its fixture is outside every deny pattern. The entry is never echoed; the person narrows it or moves TMPDIR.
340
+ if (error instanceof FixtureRootError) return { unavailable: "Codex reviewer isolation receipt unavailable (a local.deny or pii.paths entry contains the system temp directory and the hub directory; move TMPDIR or narrow the entry)", causeClass: "fixture_root_denied" };
296
341
  if (error instanceof CredentialRootError) {
297
342
  const why = { dangling: "a dangling link", unreadable: "an unreadable path", unsupported: "unsupported syntax or overlapping the checkout" }[error.kind];
298
343
  return { unavailable: `Codex reviewer isolation receipt unavailable (credential root ${error.label} is ${why}; remove or repair it)`, causeClass: "credential_root", detail: `${error.label}: ${why}` };
@@ -304,6 +349,7 @@ async function prepare(ctx: ReviewerPrepareContext): Promise<ReviewerLaunch | {
304
349
 
305
350
  export const codexReviewerBackend: ReviewerBackend = {
306
351
  id: "codex", prepare,
352
+ failure: codexReviewerQuota,
307
353
  toolTrace(event) {
308
354
  const row = event as { type?: string; item?: { type?: string; server?: string; tool?: string; error?: { message?: unknown } | string; result?: { isError?: boolean; content?: { type?: string; text?: unknown }[] } } };
309
355
  const item = row?.item;