@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
@@ -1,7 +1,7 @@
1
1
  import type { ModelOverrideSelection } from "./registry-types.ts";
2
2
  import { isNativeModelToken } from "./model-token.ts";
3
3
  import type { ChildProcess } from "node:child_process";
4
- import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver } from "./claude-print-child.ts";
4
+ import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver, type OwnedStderrReceipt } from "./claude-print-child.ts";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { HUB, frame, sanitize } from "../hub/envelope.ts";
7
7
  import { BasePeer } from "../hub/peers.ts";
@@ -9,9 +9,12 @@ import type { DeliveryFailureCause } from "../hub/delivery-failure.ts";
9
9
  import type { Envelope } from "../hub/envelope.ts";
10
10
  import type { ReviewerMcpSession, ReviewerToolName } from "./reviewer-mcp.ts";
11
11
  import { createReviewerPolicyWatch, type ReviewerPolicyProbe, type ReviewerPolicyWatch } from "./reviewer-policy-watch.ts";
12
+ import { DEFAULT_REVIEW_MAX_MINUTES, MAX_REVIEW_MINUTES } from "../hub/review-budget.ts";
13
+ import { nativeReviewerQuota, type NativeReviewerQuota } from "./definitions/native-quota.ts";
12
14
 
13
15
  /** #722: the closed list of legs a reviewer's per-review start can fail on. A class names a leg, never a path, content or token. */
14
- export const REVIEWER_CAUSE_CLASSES = ["version", "binary", "mcp_inventory", "plugins_hooks_apps", "sandbox_proof", "credential_root", "timeout", "unknown"] as const;
16
+ class ReviewerUsageCleanupError extends PrintChildCleanupError {}
17
+ export const REVIEWER_CAUSE_CLASSES = ["version", "binary", "mcp_inventory", "plugins_hooks_apps", "sandbox_proof", "credential_root", "fixture_root_denied", "timeout", "unknown"] as const;
15
18
  export type ReviewerCauseClass = typeof REVIEWER_CAUSE_CLASSES[number];
16
19
  const REVIEWER_CAUSE_HINT: Record<ReviewerCauseClass, string> = {
17
20
  version: "the CLI version is neither verified nor trusted; see ahub agents",
@@ -20,6 +23,7 @@ const REVIEWER_CAUSE_HINT: Record<ReviewerCauseClass, string> = {
20
23
  plugins_hooks_apps: "plugins, hooks or apps could not be proven disabled",
21
24
  sandbox_proof: "the native sandbox proof did not pass",
22
25
  credential_root: "a host credential root is unusable; remove or repair it",
26
+ fixture_root_denied: "a deny entry contains every directory the proof could use for its fixture; move TMPDIR or narrow the entry",
23
27
  timeout: "a proof command timed out",
24
28
  unknown: "unclassified; inspect hub.log",
25
29
  };
@@ -41,6 +45,7 @@ class ReviewerPolicyCleanupError extends PrintChildCleanupError {
41
45
  }
42
46
 
43
47
  export interface ReviewerPrintUsage { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }
48
+ export interface ReviewerUsageIdentity { id: string; at: number; model?: string }
44
49
  export interface ReviewerIsolationReceipt {
45
50
  backend: string;
46
51
  version: string;
@@ -84,6 +89,8 @@ export interface ReviewerLaunch {
84
89
  watchCurrent?: true;
85
90
  /** Fixed host factory: periodic work is separate from the synchronous current() authority fence. */
86
91
  startPolicyWatch?: () => ReviewerPolicyProbe;
92
+ /** Runs only after owned teardown and before private-profile cleanup. Receives counts and opaque identity only. */
93
+ readUsage?(startedAt: number, receive: (usage: ReviewerPrintUsage, identity: ReviewerUsageIdentity) => void): boolean;
87
94
  }
88
95
  export interface ReviewerBackend {
89
96
  id: string;
@@ -91,7 +98,10 @@ export interface ReviewerBackend {
91
98
  nativePolicy?: true;
92
99
  prepare(context: ReviewerPrepareContext): Promise<ReviewerLaunch | { unavailable: string; causeClass?: ReviewerCauseClass; detail?: string }>;
93
100
  usage?(event: unknown): ReviewerPrintUsage | undefined;
94
- failure?(event: unknown): "quota" | undefined;
101
+ /** #1402: the model a result frame says was served, by the backend's own native shape; absent when the frame names none. */
102
+ model?(event: unknown): string | undefined;
103
+ failure?(event: unknown): NativeReviewerQuota | "quota" | undefined;
104
+ failureOnExit?(event: { exitCode: number | null; stderr: OwnedStderrReceipt }): NativeReviewerQuota | undefined;
95
105
  /** Structured native MCP events only, never model messages or tool arguments. */
96
106
  toolTrace?(event: unknown): ReviewerToolTrace | undefined;
97
107
  }
@@ -126,6 +136,8 @@ export interface ReviewerFailure {
126
136
  /** Only for `start_failed`: the leg that refused (#722). */
127
137
  causeClass?: ReviewerCauseClass;
128
138
  causeDetail?: string;
139
+ reason?: "review time cap";
140
+ quota?: readonly NativeReviewerQuota[];
129
141
  }
130
142
 
131
143
  export interface ReviewerReviewBinding { readonly head?: string; readonly flowRevision?: number }
@@ -138,10 +150,22 @@ export interface ReviewerPrintOptions {
138
150
  systemPrompt: string;
139
151
  privatePaths?: readonly string[];
140
152
  watchdogMs: number;
153
+ /** Sampled once for each actual child; activity never extends this wall-clock cap. */
154
+ maxMinutes?(): number;
155
+ /** Host-owned deterministic timer seam; never accepted from a review envelope. */
156
+ reviewTimer?: { set(run: () => void, ms: number): unknown; clear(handle: unknown): void };
141
157
  backend: ReviewerBackend;
142
158
  facts?(env: Envelope): string | undefined;
143
159
  verdictSince(task: number, since: number): boolean;
144
- onUsage?(usage: ReviewerPrintUsage, task: number): void;
160
+ onUsage?(usage: ReviewerPrintUsage, task: number, identity?: ReviewerUsageIdentity): void;
161
+ /** Host journal ACK before any usage-producing child is constructed; absent port refuses that launch. */
162
+ usageIntent?(attempt: string, task: number): boolean;
163
+ /** Proven native quota is account evidence, independent of whether this task later reroutes. */
164
+ onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean): boolean;
165
+ /** Only after this attempt's owned group and watch have settled. Never grants task authority. */
166
+ quotaSettled?(attempt: string): void;
167
+ /** ACK after owned settlement and usage read; failed ACK retains the private profile for recovery. */
168
+ usageSettled?(attempt: string, outcome: "complete" | "unknown", task: number): boolean;
145
169
  /** True confirms that the host re-offered the current review; void/false retains uncertainty. */
146
170
  onUnavailable?(failure: ReviewerFailure, current: () => boolean): boolean | void | Promise<boolean | void>;
147
171
  onNoVerdict?(diagnostic: ReviewerNoVerdict, current: () => boolean): void;
@@ -177,6 +201,12 @@ const reviewTask = (env: Envelope): number | undefined => {
177
201
  };
178
202
 
179
203
  export class ReviewerPrintPeer extends BasePeer {
204
+ /** #1402: the model the last result frame named; read once at the turn end. */
205
+ private servedModel: string | undefined;
206
+ observedModel(): import("../hub/events.ts").ModelObservation | undefined {
207
+ const model = this.servedModel; this.servedModel = undefined;
208
+ return model ? { model, evidence: "served" } : undefined;
209
+ }
180
210
  readonly hubNative = true;
181
211
  readonly hubOwned: boolean = true;
182
212
  private generation = 0;
@@ -235,7 +265,7 @@ export class ReviewerPrintPeer extends BasePeer {
235
265
  async start(): Promise<void> {
236
266
  // A retained child means a review's process group was never confirmed gone: no new review beside it.
237
267
  if (this.child) throw new Error(`${this.id}: an earlier review's process group is still running; stop it first`);
238
- if (this.policyWatch) throw new ReviewerPolicyCleanupError();
268
+ if (this.policyWatch || this.childCleanup) throw new ReviewerPolicyCleanupError();
239
269
  if (this.preparation) throw new Error(`${this.id}: reviewer preparation is still running`);
240
270
  this.receipt = undefined;
241
271
  const generation = ++this.generation;
@@ -264,7 +294,8 @@ export class ReviewerPrintPeer extends BasePeer {
264
294
 
265
295
  protected override onWatchdog(): void { this.abortReview("review watchdog timeout", "timeout"); }
266
296
 
267
- private abortReview(reason: "review watchdog timeout" | "review output limit exceeded" | "review policy changed", failureCause?: DeliveryFailureCause): void {
297
+ private abortReview(reason: "review watchdog timeout" | "review output limit exceeded" | "review policy changed" | "review time cap", failureCause?: DeliveryFailureCause): void {
298
+ const cappedTask = this.reviewing;
268
299
  const generation = ++this.generation, batch = this.batch, preparation = this.preparation;
269
300
  this.reviewing = undefined;
270
301
  this.reviewMcpClose?.();
@@ -278,13 +309,13 @@ export class ReviewerPrintPeer extends BasePeer {
278
309
  if (generation !== this.generation) return;
279
310
  await this.kill();
280
311
  if (generation !== this.generation) return; // a person's stop owns the hold; never reroute it
281
- if (batch) await this.reportFailures([...batch.failures, ...remainingFailures(batch, batch.next, "no_verdict")], generation);
312
+ if (batch) await this.reportFailures([...batch.failures, ...remainingFailures(batch, batch.next, "no_verdict").map(failure => reason === "review time cap" && failure.task === cappedTask ? { ...failure, reason: "review time cap" as const } : failure)], generation);
282
313
  if (generation === this.generation && this.state === "busy") { this.batch = undefined; super.onWatchdog(); }
283
314
  })().catch((error: Error) => this.opts.log?.(`[${this.id}] review cleanup failed, staying busy`));
284
315
  }
285
316
 
286
317
  async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
287
- if (this.state !== "idle") {
318
+ if (this.state !== "idle" || this.childCleanup) {
288
319
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
289
320
  throw new Error(`${this.id} is ${this.state}`);
290
321
  }
@@ -312,7 +343,7 @@ export class ReviewerPrintPeer extends BasePeer {
312
343
  if (task === undefined) continue; // a withdrawal or other notice: nothing to review
313
344
  if (env.private) { failure = { state: "needs_review", reason: "a private review is the person's, never a cloud reviewer's" }; break; }
314
345
  const since = Date.now();
315
- let result: { code: number | null; quota: boolean; trace: ReviewerTraceState };
346
+ let result: { code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState };
316
347
  try { result = await this.review(env, task, generation); }
317
348
  catch (error) {
318
349
  if (generation !== this.generation) return;
@@ -332,6 +363,7 @@ export class ReviewerPrintPeer extends BasePeer {
332
363
  continue;
333
364
  }
334
365
  if (error instanceof PrintChildCleanupError) {
366
+ if (error instanceof ReviewerUsageCleanupError) await this.reportFailures(batch.failures.filter(row => row.cause === "quota"), generation);
335
367
  // Unavailable until a stop confirms the group gone: no new review runs beside the survivors.
336
368
  this.opts.log?.(`[${this.id}] review of task #${task}: ${error.message}`);
337
369
  this.settle("needs_review", error instanceof ReviewerPolicyCleanupError ? error.message : `review process group still running: ${error.message}`);
@@ -357,9 +389,10 @@ export class ReviewerPrintPeer extends BasePeer {
357
389
  if (this.opts.onNoVerdict) this.opts.onNoVerdict(diagnostic, () => generation === this.generation);
358
390
  else this.opts.log?.(reviewerNoVerdictLine(this.id, diagnostic));
359
391
  } catch { this.opts.log?.(reviewerNoVerdictLine(this.id, { task, exitCode: result.code, reviewCalled: false }, undefined, true)); }
360
- if (target) reroute.push({ ...target, cause: result.quota ? "quota" : "no_verdict" });
392
+ const quotaMetadata = result.quotaReadings?.length ? { quota: result.quotaReadings } : {};
393
+ if (target) reroute.push({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata });
361
394
  if (result.quota) {
362
- reroute.push(...remainingFailures(batch, index + 1, "quota"));
395
+ reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => ({ ...failure, ...quotaMetadata })));
363
396
  batch.next = envs.length;
364
397
  break;
365
398
  }
@@ -422,7 +455,7 @@ export class ReviewerPrintPeer extends BasePeer {
422
455
  if (this.opts.admit?.(env) === false) throw new ReviewerAdmissionError(this.opts.bindingCurrent?.(task, binding) === false ? "stale_binding" : "policy_changed");
423
456
  }
424
457
 
425
- private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; trace: ReviewerTraceState }> {
458
+ private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
426
459
  const revision=Number(env.refs?.reviewRevision);
427
460
  const binding: ReviewerReviewBinding=Object.freeze({head:env.refs?.commit,flowRevision:Number.isSafeInteger(revision)&&revision>0?revision:undefined});
428
461
  this.assertAdmission(env, task, binding);
@@ -450,7 +483,18 @@ export class ReviewerPrintPeer extends BasePeer {
450
483
  };
451
484
  this.reviewMcpClose=closeMcp;
452
485
  let ownedChild: OwnedPrintChild | undefined, releasing: Promise<void> | undefined;
486
+ let deadline: { handle: unknown } | undefined;
487
+ const clearDeadline = () => {
488
+ if (!deadline) return;
489
+ if (this.opts.reviewTimer) this.opts.reviewTimer.clear(deadline.handle);
490
+ else clearTimeout(deadline.handle as ReturnType<typeof setTimeout>);
491
+ deadline = undefined;
492
+ };
453
493
  let inputReleased = false, childClosed = false, launchCleanupConfirmed = false;
494
+ let nativeStartedAt: number | undefined, usageRead = false;
495
+ const quotaAttempt = randomUUID().replaceAll("-", "");
496
+ let quotaSettlementSent = false;
497
+ let accountingAttempt: string | undefined, accountingOutcome: "complete" | "unknown" = "unknown";
454
498
  let inputFinished = false;
455
499
  const finishInput = () => {
456
500
  const closedWithoutChild = !ownedChild || ownedChild.process.pid === undefined;
@@ -460,23 +504,75 @@ export class ReviewerPrintPeer extends BasePeer {
460
504
  }
461
505
  };
462
506
  let policyOwner: ReviewPolicyOwner | undefined;
463
- const release = () => releasing ??= Promise.resolve().then(() => launch?.cleanup?.()).then(() => {});
507
+ const release = () => releasing ??= Promise.resolve().then(() => {
508
+ if (!quotaSettlementSent) {
509
+ quotaSettlementSent = true;
510
+ this.opts.quotaSettled?.(quotaAttempt);
511
+ }
512
+ if (accountingAttempt) {
513
+ if (!usageRead) {
514
+ usageRead = true;
515
+ if (ownedChild?.process.pid === undefined) accountingOutcome = "complete";
516
+ else if (nativeStartedAt !== undefined && launch?.readUsage) {
517
+ try { if (launch.readUsage(nativeStartedAt, (usage, identity) => this.opts.onUsage?.(usage, task, identity))) accountingOutcome = "complete"; }
518
+ catch { /* An unreadable or uncommitted count remains unknown. */ }
519
+ }
520
+ }
521
+ if (this.opts.usageSettled?.(accountingAttempt, accountingOutcome, task) !== true)
522
+ throw new ReviewerUsageCleanupError("reviewer accounting settlement was not acknowledged");
523
+ if (accountingOutcome === "unknown") throw new ReviewerUsageCleanupError("reviewer usage is incomplete; owned profile retained");
524
+ }
525
+ return launch?.cleanup?.();
526
+ }).then(() => {});
464
527
  try {
465
528
  launch = await this.prepare(sessionId, input, task, mcp?.config, selection?.model);
466
529
  if (generation !== this.generation) throw new ReviewerAdmissionError("stale_binding");
467
530
  this.assertAdmission(env, task, binding);
468
531
  if (launch.current?.() === false) throw new ReviewerUnavailableError("reviewer isolation changed before child spawn", "binary");
469
532
  this.receipt = launch.isolation;
533
+ const maxMinutes = this.opts.maxMinutes?.() ?? DEFAULT_REVIEW_MAX_MINUTES;
534
+ if (!Number.isFinite(maxMinutes) || maxMinutes <= 0 || maxMinutes > MAX_REVIEW_MINUTES) throw new ReviewerAdmissionError("policy_changed");
470
535
  let quota = false;
536
+ const quotaReadings = new Map<NativeReviewerQuota["id"], NativeReviewerQuota>();
537
+ const publishedQuota = new Set<string>();
538
+ const observeQuota = (reading: NativeReviewerQuota) => {
539
+ const key = JSON.stringify(reading);
540
+ if (publishedQuota.has(key)) return;
541
+ try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation) === true) publishedQuota.add(key); }
542
+ catch { /* Retain the proven quota in the batch even if its immediate account write could not commit. */ }
543
+ };
544
+ const rememberQuota = () => {
545
+ const batch = this.batch, target = batch?.targets[batch.next];
546
+ if (!batch || generation !== this.generation || target?.task !== task) return;
547
+ const failure: ReviewerFailure = { ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) };
548
+ const prior = batch.failures.findIndex(row => row.task === target.task && row.head === target.head && row.flowRevision === target.flowRevision && row.cause === "quota");
549
+ if (prior < 0) batch.failures.push(failure); else batch.failures[prior] = failure;
550
+ };
551
+ if (launch.readUsage) {
552
+ const attempt = randomUUID().replaceAll("-", "");
553
+ if (this.opts.usageIntent?.(attempt, task) !== true) throw new ReviewerAdmissionError("policy_changed");
554
+ accountingAttempt = attempt;
555
+ // The journal intent precedes spawn: the native agent-file already contains the review facts.
556
+ this.assertAdmission(env, task, binding);
557
+ }
471
558
  const child = new OwnedPrintChild({ peer: this.id, command: launch.command, args: launch.args,
472
559
  cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input,
560
+ ...(this.opts.backend.failureOnExit ? { captureStderr: true as const } : {}),
473
561
  current: () => generation === this.generation, stop: launch.stop,
474
562
  onInputReleased: () => { inputReleased = true; this.opts.inputReleased?.(inputContext, [env]); },
475
563
  onError: () => { if (this.child === child) this.child = undefined; },
476
564
  onSpawn: () => {
565
+ nativeStartedAt = Date.now();
477
566
  try { selection?.applied(); } catch { /* Native spawn remains authoritative. */ }
478
567
  this.runningBinding={task,binding};
479
568
  this.reviewing = task; this.reviewSeq++;
569
+ const reviewSequence = this.reviewSeq;
570
+ const expire = () => {
571
+ if (this.child === child && generation === this.generation && this.reviewing === task && this.reviewSeq === reviewSequence)
572
+ this.abortReview("review time cap", "timeout");
573
+ };
574
+ if (this.opts.reviewTimer) deadline = { handle: this.opts.reviewTimer.set(expire, maxMinutes * 60_000) };
575
+ else { const timer = setTimeout(expire, maxMinutes * 60_000); timer.unref?.(); deadline = { handle: timer }; }
480
576
  if (launch!.watchCurrent) {
481
577
  try {
482
578
  const sequence = this.reviewSeq, probe = launch!.startPolicyWatch!();
@@ -500,11 +596,20 @@ export class ReviewerPrintPeer extends BasePeer {
500
596
  } catch { /* Optional trace metadata never changes review execution. */ }
501
597
  const usage = this.opts.backend.usage?.(event);
502
598
  if (usage) this.opts.onUsage?.(usage, task);
503
- if (this.opts.backend.failure?.(event) === "quota") quota = true;
599
+ try { const model = this.opts.backend.model?.(event); if (model) this.servedModel = model; } catch { /* optional metadata never changes review execution */ }
600
+ try {
601
+ const failure = this.opts.backend.failure?.(event);
602
+ if (failure === "quota") { quota = true; rememberQuota(); } // Legacy synthetic backends carry no reset evidence.
603
+ else {
604
+ const reading = nativeReviewerQuota(failure);
605
+ if (reading) { quota = true; quotaReadings.set(reading.id, reading); observeQuota(reading); rememberQuota(); }
606
+ }
607
+ } catch { /* Malformed optional metadata cannot manufacture a quota pause. */ }
504
608
  },
505
609
  onActivity: () => this.touch(),
506
610
  onLimit: () => this.abortReview("review output limit exceeded"),
507
611
  onLeaderExit: () => {
612
+ clearDeadline();
508
613
  if (this.child === child) { this.reviewing = undefined; this.runningBinding=undefined; }
509
614
  void this.stopPolicyWatch(policyOwner).catch(() => {});
510
615
  },
@@ -514,10 +619,17 @@ export class ReviewerPrintPeer extends BasePeer {
514
619
  this.childCleanup = release;
515
620
  this.childCurrent = launch.watchCurrent ? launch.current : undefined;
516
621
  const code = await child.done;
622
+ if (generation === this.generation && this.child === child && this.opts.backend.failureOnExit) {
623
+ try {
624
+ const reading = nativeReviewerQuota(this.opts.backend.failureOnExit({ exitCode: code, stderr: child.stderrAfterSettlement() }));
625
+ if (reading) { quota = true; quotaReadings.set(reading.id, reading); observeQuota(reading); rememberQuota(); }
626
+ } catch { /* Unknown or incomplete exit diagnostics remain ordinary failure. */ }
627
+ }
517
628
  childClosed = true;
518
629
  if (this.child === child) this.child = undefined;
519
- return { code, quota, trace };
630
+ return { code, quota, trace, ...(quotaReadings.size ? { quotaReadings: [...quotaReadings.values()] } : {}) };
520
631
  } finally {
632
+ clearDeadline();
521
633
  if (this.activeTrace?.value === trace) this.activeTrace = undefined;
522
634
  closeMcp();
523
635
  // Joining the watcher precedes deletion of files it can still read, even when native cleanup failed.
@@ -528,7 +640,7 @@ export class ReviewerPrintPeer extends BasePeer {
528
640
  launchCleanupConfirmed = true;
529
641
  if (this.policyWatch === policyOwner) this.policyWatch = undefined;
530
642
  }
531
- } catch { this.opts.log?.(`[${this.id}] reviewer isolation cleanup incomplete`); }
643
+ } catch (error) { this.opts.log?.(`[${this.id}] reviewer isolation cleanup incomplete`); if (error instanceof ReviewerUsageCleanupError) throw error; }
532
644
  finishInput();
533
645
  }
534
646
  }
@@ -559,6 +671,10 @@ export class ReviewerPrintPeer extends BasePeer {
559
671
  try { await workerStopped; } catch (error) { workerError = error; }
560
672
  if (workerError) throw workerError;
561
673
  if (childError) throw childError;
674
+ if (!child && cleanup) {
675
+ await cleanup();
676
+ if (this.childCleanup === cleanup) this.childCleanup = undefined;
677
+ }
562
678
  if (child) {
563
679
  await cleanup?.();
564
680
  owner?.closed();
@@ -0,0 +1,99 @@
1
+ import { SUPPORTED_PEERS, definitionOf, type ProjectAdapterCatalog } from "./registry.ts";
2
+ import type { StartMode } from "../hub/start-mode.ts";
3
+
4
+ /**
5
+ * #1408 R1, R2: who may hold a flow role, read from the adapter definition. Pure: no clock, no I/O. Init, the loader, doctor and the docs table all ask `roleEligibility`, so the answer
6
+ * and its reason cannot drift between them.
7
+ */
8
+ export type EligibleRole = "conductor" | "planner" | "reviewer";
9
+ export interface RoleEligibility { eligible: boolean; reason?: string; fix?: string }
10
+
11
+ type Definition = NonNullable<ReturnType<typeof definitionOf>>;
12
+ const lookup = (peer: string, catalog?: ProjectAdapterCatalog): Definition | undefined => (catalog?.definitionOf ?? definitionOf)(peer);
13
+
14
+ /**
15
+ * Whether `peer` may hold `role` when it starts in `startMode` (undefined: the kind's own default form). A kind with no definition is not refused here: its roles are the
16
+ * project's own and the ceiling that already applies to it stays the authority.
17
+ */
18
+ export function roleEligibility(peer: string, role: EligibleRole, startMode?: StartMode, catalog?: ProjectAdapterCatalog): RoleEligibility {
19
+ const definition = lookup(peer, catalog);
20
+ if (!definition) return { eligible: true };
21
+ const projection = definition.projection;
22
+ if (role === "planner") return projection?.plannerEligible === true ? { eligible: true } : { eligible: false, reason: `${peer} cannot plan (its kind is not planner-eligible)`, fix: "choose a planner-eligible peer, or move the planner role" };
23
+ if (role === "reviewer") return projection?.reviewerEligible === true ? { eligible: true } : { eligible: false, reason: `${peer} cannot receive hub_review`, fix: "choose another reviewer, or leave reviews to the person" };
24
+ if (projection?.conductorEligible !== true) {
25
+ return { eligible: false, reason: `${peer} cannot conduct: its kind has no interactive session that receives hub pushes and holds a writable tools connection`, fix: "move the conductor role to claude, codex, jcode or pi, or leave the project without a conductor (the person conducts from ahub console)" };
26
+ }
27
+ const mode = startMode ?? definition.start.defaultForm ?? (definition.start.forms.includes("tui") ? "tui" : "headless");
28
+ if (mode === "headless") {
29
+ return { eligible: false, reason: `${peer} starts headless, and the conductor role needs an interactive session to report to the person and ask for decisions`,
30
+ fix: definition.start.forms.includes("tui") ? `run ahub settings set peers.${peer}.start_mode tui, or move the conductor role` : "move the conductor role to an interactive peer" };
31
+ }
32
+ return { eligible: true };
33
+ }
34
+
35
+ /**
36
+ * The adapter ceiling alone, exactly as it was before #1408: roles outside `routing.allowedRoles` and a planner the kind cannot do are dropped. The at-most-one-conductor count runs on this
37
+ * result, so a conductor the kind never allowed (agy) does not count, while one the kind allows but eligibility drops (local) still does.
38
+ */
39
+ export function adapterCeiling(peer: string, declared: readonly string[], catalog?: ProjectAdapterCatalog): string[] {
40
+ const definition = lookup(peer, catalog), ceiling = definition?.routing?.allowedRoles;
41
+ return declared.filter(role => (!ceiling || ceiling.includes(role)) && (role !== "planner" || !definition || definition.projection?.plannerEligible === true));
42
+ }
43
+
44
+ /**
45
+ * The roles a peer keeps after the ceilings. `declared` is what the config named; `allowed` is the kind's `routing.allowedRoles` ceiling when it has one. A role outside the ceiling,
46
+ * a planner the kind cannot do, and a conductor `roleEligibility` refuses are dropped, each with one notice that names the reason and the fix. Nobody else gains a dropped role.
47
+ */
48
+ export function applyRoleCeiling(peer: string, declared: readonly string[], startMode: StartMode | undefined, catalog?: ProjectAdapterCatalog): { roles: string[]; notices: string[] } {
49
+ const definition = lookup(peer, catalog), ceiling = definition?.routing?.allowedRoles;
50
+ const notices: string[] = [];
51
+ const roles = declared.filter(role => {
52
+ if (ceiling && !ceiling.includes(role)) return false;
53
+ if (role === "planner" && definition && definition.projection?.plannerEligible !== true) return false;
54
+ if (role === "conductor") {
55
+ const verdict = roleEligibility(peer, "conductor", startMode, catalog);
56
+ if (!verdict.eligible) { notices.push(`roles.${peer}: conductor ignored: ${verdict.reason}; ${verdict.fix}`); return false; }
57
+ }
58
+ return true;
59
+ });
60
+ // The existing notice stays for ceiling and planner drops, so every released reader of it keeps working.
61
+ const conductorDropped = declared.includes("conductor") && !roles.includes("conductor") && notices.length > 0;
62
+ if (roles.length !== declared.length - (conductorDropped ? 1 : 0)) notices.unshift(`roles.${peer}: ignored roles outside the adapter ceiling`);
63
+ return { roles, notices };
64
+ }
65
+
66
+ /** One kind's row of the eligibility table: its start forms and what `roleEligibility` answers for it. */
67
+ export interface EligibilityRow {
68
+ peer: string;
69
+ /** The forms the kind can start in, in the definition's order. */
70
+ forms: readonly string[];
71
+ /** The forms in which the kind may conduct (none for a kind that cannot conduct at all). */
72
+ conductor: readonly string[];
73
+ planner: boolean;
74
+ reviewer: boolean;
75
+ }
76
+
77
+ /**
78
+ * #1408 R4: the eligibility table, one row per builtin kind, read only from `roleEligibility` so the docs table, init, the loader and doctor cannot disagree. Pure and ordered as the registry is.
79
+ * A conductor form is judged in that form (`roleEligibility(peer, "conductor", form)`), so a kind that can conduct only interactively lists only its interactive form.
80
+ */
81
+ export function eligibilityRows(): EligibilityRow[] {
82
+ return SUPPORTED_PEERS.map(peer => {
83
+ const forms = definitionOf(peer)?.start.forms ?? [];
84
+ return {
85
+ peer, forms: [...forms],
86
+ conductor: forms.filter(form => roleEligibility(peer, "conductor", form).eligible),
87
+ planner: roleEligibility(peer, "planner").eligible,
88
+ reviewer: roleEligibility(peer, "reviewer").eligible,
89
+ };
90
+ });
91
+ }
92
+
93
+ const mark = (yes: boolean) => yes ? "yes" : "no";
94
+ /** The Markdown table `docs/roles.md` carries, generated from `eligibilityRows`; `test/roles-doc.test.ts` compares the document with it. */
95
+ export function renderEligibilityTable(): string {
96
+ const header = "| Kind | Start forms | Conductor | Planner | Reviewer |\n| --- | --- | --- | --- | --- |";
97
+ const rows = eligibilityRows().map(row => `| ${row.peer} | ${row.forms.join(", ") || "none"} | ${row.conductor.length ? row.conductor.join(", ") : "no"} | ${mark(row.planner)} | ${mark(row.reviewer)} |`);
98
+ return [header, ...rows].join("\n");
99
+ }
@@ -0,0 +1,16 @@
1
+ import { realPath } from "../hub/project.ts";
2
+
3
+ /**
4
+ * #1423: whether a path a hub-written config names is this directory, also after the project moved (a rename that left the old path as a symlink). Compared by real path, never by text alone, and through
5
+ * `realPath` (project.ts), so a typed name is not rebuilt from its parts. A path that does not resolve (the old name is gone, not left as a link) is not the same directory: the caller then refuses
6
+ * with a next step. Never throws, never writes.
7
+ */
8
+ export function sameDirectory(named: unknown, directory: string): boolean {
9
+ if (typeof named !== "string" || !named || named.length > 4096 || /[\u0000-\u001f\u007f]/.test(named)) return false;
10
+ if (named === directory) return true;
11
+ try { return realPath(named) === realPath(directory); } catch { return false; }
12
+ }
13
+ /** A foreign value shown in a refusal: printable and short, or not shown at all (the field name is the clue then). */
14
+ export function shownValue(value: unknown): string | undefined {
15
+ return typeof value === "string" && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f]/.test(value) ? value : undefined;
16
+ }
@@ -6,6 +6,7 @@ import { isAbsolute, join, resolve } from "node:path";
6
6
  import { isDeepStrictEqual } from "node:util";
7
7
  import { hubGitSync } from "../hub/git.ts";
8
8
  import { realPath } from "../hub/project.ts";
9
+ import { sameDirectory, shownValue } from "../adapters/same-directory.ts";
9
10
 
10
11
  export interface AgyMcpOptions {
11
12
  projectRoot: string;
@@ -130,17 +131,20 @@ function parseManagedHookCommand(command: unknown, phase: typeof EVENTS[number],
130
131
  if (typeof command !== "string") return undefined;
131
132
  const prefix = `AGENTHUB_HOOK_EVENT='${phase}' AGENTHUB_INSTANCE_ID='`;
132
133
  const middle = `' AGENTHUB_LAUNCH_ID='`;
133
- const suffix = `' AGENTHUB_HOOK_PURPOSE='facts' AGENTHUB_PEER_ID=${shellQuote(peer)} AGENTHUB_STATE_DIR=${shellQuote(options.stateDir)} AGENTHUB_PROJECT_DIR=${shellQuote(resolve(options.projectRoot))} bun `;
134
+ // #1423: the state and project directories are compared by real path, so the hub's own hook from before a project move (old path left as a symlink) is still its own.
135
+ const suffix = new RegExp(`' AGENTHUB_HOOK_PURPOSE='facts' AGENTHUB_PEER_ID=${shellQuote(peer).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} AGENTHUB_STATE_DIR=('(?:[^']|'\\\\'')*') AGENTHUB_PROJECT_DIR=('(?:[^']|'\\\\'')*') bun `);
134
136
  if (!command.startsWith(prefix)) return undefined;
135
137
  const rest = command.slice(prefix.length);
136
138
  const launchSplit = rest.indexOf(middle);
137
139
  if (launchSplit < 1) return undefined;
138
140
  const instanceId = rest.slice(0, launchSplit);
139
141
  const afterInstance = rest.slice(launchSplit + middle.length);
140
- const pathSplit = afterInstance.indexOf(suffix);
141
- if (pathSplit < 1) return undefined;
142
+ const found = suffix.exec(afterInstance);
143
+ if (!found || found.index < 1) return undefined;
144
+ const pathSplit = found.index;
142
145
  const launchId = afterInstance.slice(0, pathSplit);
143
- const hookScript = shellUnquote(afterInstance.slice(pathSplit + suffix.length));
146
+ if (!sameDirectory(shellUnquote(found[1]!), options.stateDir) || !sameDirectory(shellUnquote(found[2]!), resolve(options.projectRoot))) return undefined;
147
+ const hookScript = shellUnquote(afterInstance.slice(pathSplit + found[0].length));
144
148
  if (!/^[A-Za-z0-9._:-]{1,128}$/.test(instanceId) || !/^[A-Za-z0-9._:-]{1,128}$/.test(launchId) || !hookScript || !isAbsolute(hookScript) || !hookScript.endsWith("/src/cli/facts-hook.ts")) return undefined;
145
149
  return { instanceId, launchId };
146
150
  }
@@ -214,9 +218,16 @@ function internalPlan(options: AgyMcpOptions): Plan {
214
218
  if (mcp) {
215
219
  if (Object.hasOwn(mcp, "mcpServers") && !object(mcp.mcpServers)) throw new Error(`${MCP_FILE} mcpServers must be an object`);
216
220
  const entry = mcp.mcpServers?.[PLUGIN_KEY];
217
- if (entry !== undefined && (!object(entry) || Object.keys(entry).sort().join(",") !== "args,command,env" || entry.command !== "bun" || !Array.isArray(entry.args) || entry.args.length !== 2 || entry.args[0] !== "run" || typeof entry.args[1] !== "string" || !isAbsolute(entry.args[1]) || !object(entry.env) || Object.keys(entry.env).sort().join(",") !== "AGENTHUB_PEER_ID,AGENTHUB_PROJECT_DIR,AGENTHUB_STATE_DIR" || entry.env.AGENTHUB_PEER_ID !== peer || entry.env.AGENTHUB_PROJECT_DIR !== root || entry.env.AGENTHUB_STATE_DIR !== options.stateDir)) {
218
- throw new Error(`${MCP_FILE} agent-hub is a foreign MCP entry; it was not changed`);
219
- }
221
+ // #1423: the project and state directories are compared by real path (a project directory renamed with the old path left as a symlink is still this project), and the refusal names the field.
222
+ const why = entry === undefined ? undefined
223
+ : !object(entry) ? "the entry is not an object"
224
+ : Object.keys(entry).sort().join(",") !== "args,command,env" || entry.command !== "bun" || !Array.isArray(entry.args) || entry.args.length !== 2 || entry.args[0] !== "run" || typeof entry.args[1] !== "string" || !isAbsolute(entry.args[1]) ? "command or args differ from the managed entry"
225
+ : !object(entry.env) || Object.keys(entry.env).sort().join(",") !== "AGENTHUB_PEER_ID,AGENTHUB_PROJECT_DIR,AGENTHUB_STATE_DIR" ? "env differs from the managed entry"
226
+ : entry.env.AGENTHUB_PEER_ID !== peer ? "AGENTHUB_PEER_ID names another peer"
227
+ : !sameDirectory(entry.env.AGENTHUB_PROJECT_DIR, root) ? `AGENTHUB_PROJECT_DIR ${shownValue(entry.env.AGENTHUB_PROJECT_DIR) ?? ""} is not this project (${root})`.replace(" ", " ")
228
+ : !sameDirectory(entry.env.AGENTHUB_STATE_DIR, options.stateDir) ? `AGENTHUB_STATE_DIR ${shownValue(entry.env.AGENTHUB_STATE_DIR) ?? ""} is not this hub's state directory (${options.stateDir})`.replace(" ", " ")
229
+ : undefined;
230
+ if (why !== undefined) throw new Error(`${MCP_FILE} agent-hub is a foreign MCP entry (${why}); it was not changed. If it is the hub's own entry from before the project moved, remove the agent-hub key from ${MCP_FILE} and run ahub agy again.`);
220
231
  }
221
232
  const hooks = current[HOOKS_FILE];
222
233
  const oldLaunch = hooks ? managedHookLaunch(hooks, options, peer) : undefined;
@@ -1,4 +1,4 @@
1
- import { QUESTION_SET } from "../hub/questions.ts";
1
+ import { parseAnswerInstruction, QUESTION_SET } from "../hub/questions.ts";
2
2
 
3
3
  /**
4
4
  * #1053 T4: `ahub answer <set> <question>=<option>[,<option>]... [--other <text>]...`. Pure: it turns argv into the `answers` list the hub validates
@@ -9,7 +9,7 @@ import { QUESTION_SET } from "../hub/questions.ts";
9
9
  */
10
10
 
11
11
  const ID = /^[A-Za-z0-9_.-]{1,64}$/;
12
- export interface ParsedAnswer { set: string; answers: { questionId: string; optionIds: string[]; other?: string }[] }
12
+ export interface ParsedAnswer { set: string; instruction?: string; answers: { questionId: string; optionIds: string[]; other?: string }[] }
13
13
  export type AnswerArgs = { ok: true; value: ParsedAnswer } | { ok: false; error: string };
14
14
  export const ANSWER_USAGE = "usage: ahub answer <set> <question>=<option>[,<option>] [--other <text>] (ahub answer lists the open questions)";
15
15
 
@@ -17,9 +17,17 @@ export function parseAnswerArgs(args: readonly string[]): AnswerArgs {
17
17
  const fail = (error: string): { ok: false; error: string } => ({ ok: false, error });
18
18
  const [set, ...rest] = args;
19
19
  if (!set || !QUESTION_SET.test(set)) return fail(`${ANSWER_USAGE}; the set looks like qs-0123456789ab`);
20
+ let instruction: string | undefined;
20
21
  const picks = new Map<string, string[]>(), others: string[] = [];
21
22
  for (let index = 0; index < rest.length; index++) {
22
23
  const word = rest[index]!;
24
+ if (word === "--instructed") {
25
+ if (instruction !== undefined) return fail("--instructed may appear once; correct it or use ahub console");
26
+ const parsed = parseAnswerInstruction(rest[++index]);
27
+ if (!parsed.ok) return fail(`${parsed.error}; supply --instructed with the person's quote, or use ahub console`);
28
+ instruction = parsed.value;
29
+ continue;
30
+ }
23
31
  if (word === "--other" || word.startsWith("--other=")) {
24
32
  const value = word === "--other" ? rest[++index] : word.slice("--other=".length);
25
33
  if (value === undefined || value === "") return fail("--other needs the text to give");
@@ -46,5 +54,5 @@ export function parseAnswerArgs(args: readonly string[]): AnswerArgs {
46
54
  if (other.has(target)) return fail(`question ${target} has two --other texts`);
47
55
  other.set(target, named ? text.slice(at + 1) : text);
48
56
  }
49
- return { ok: true, value: { set, answers: [...picks].map(([questionId, optionIds]) => ({ questionId, optionIds, ...(other.has(questionId) ? { other: other.get(questionId)! } : {}) })) } };
57
+ return { ok: true, value: { set, ...(instruction === undefined ? {} : { instruction }), answers: [...picks].map(([questionId, optionIds]) => ({ questionId, optionIds, ...(other.has(questionId) ? { other: other.get(questionId)! } : {}) })) } };
50
58
  }
@@ -18,7 +18,7 @@ export interface FlowStep { flow?: QuestionFlow; answers?: FlowAnswer[]; notice?
18
18
  export function questionRows(raw: unknown): QuestionView[] {
19
19
  if (!Array.isArray(raw)) return [];
20
20
  return raw.flatMap<QuestionView>(row => {
21
- if (!row || typeof row !== "object" || typeof row.set !== "string" || typeof row.peer !== "string" || !Array.isArray(row.questions) || !row.questions.length) return [];
21
+ if (!row || typeof row !== "object" || (row.state !== undefined && row.state !== "open") || typeof row.set !== "string" || typeof row.peer !== "string" || !Array.isArray(row.questions) || !row.questions.length) return [];
22
22
  return [{ set: row.set, peer: row.peer, created: Number.isSafeInteger(row.created) ? row.created : 0, ...(row.private === true ? { private: true } : {}), questions: row.questions as AskQuestion[] }];
23
23
  }).sort((a, b) => a.created - b.created || a.set.localeCompare(b.set));
24
24
  }