@staix/agent-hub 0.38.0 → 0.39.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 (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
@@ -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,8 +9,11 @@ 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. */
16
+ class ReviewerUsageCleanupError extends PrintChildCleanupError {}
14
17
  export const REVIEWER_CAUSE_CLASSES = ["version", "binary", "mcp_inventory", "plugins_hooks_apps", "sandbox_proof", "credential_root", "timeout", "unknown"] as const;
15
18
  export type ReviewerCauseClass = typeof REVIEWER_CAUSE_CLASSES[number];
16
19
  const REVIEWER_CAUSE_HINT: Record<ReviewerCauseClass, string> = {
@@ -41,6 +44,7 @@ class ReviewerPolicyCleanupError extends PrintChildCleanupError {
41
44
  }
42
45
 
43
46
  export interface ReviewerPrintUsage { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }
47
+ export interface ReviewerUsageIdentity { id: string; at: number; model?: string }
44
48
  export interface ReviewerIsolationReceipt {
45
49
  backend: string;
46
50
  version: string;
@@ -84,6 +88,8 @@ export interface ReviewerLaunch {
84
88
  watchCurrent?: true;
85
89
  /** Fixed host factory: periodic work is separate from the synchronous current() authority fence. */
86
90
  startPolicyWatch?: () => ReviewerPolicyProbe;
91
+ /** Runs only after owned teardown and before private-profile cleanup. Receives counts and opaque identity only. */
92
+ readUsage?(startedAt: number, receive: (usage: ReviewerPrintUsage, identity: ReviewerUsageIdentity) => void): boolean;
87
93
  }
88
94
  export interface ReviewerBackend {
89
95
  id: string;
@@ -91,7 +97,10 @@ export interface ReviewerBackend {
91
97
  nativePolicy?: true;
92
98
  prepare(context: ReviewerPrepareContext): Promise<ReviewerLaunch | { unavailable: string; causeClass?: ReviewerCauseClass; detail?: string }>;
93
99
  usage?(event: unknown): ReviewerPrintUsage | undefined;
94
- failure?(event: unknown): "quota" | undefined;
100
+ /** #1402: the model a result frame says was served, by the backend's own native shape; absent when the frame names none. */
101
+ model?(event: unknown): string | undefined;
102
+ failure?(event: unknown): NativeReviewerQuota | "quota" | undefined;
103
+ failureOnExit?(event: { exitCode: number | null; stderr: OwnedStderrReceipt }): NativeReviewerQuota | undefined;
95
104
  /** Structured native MCP events only, never model messages or tool arguments. */
96
105
  toolTrace?(event: unknown): ReviewerToolTrace | undefined;
97
106
  }
@@ -126,6 +135,8 @@ export interface ReviewerFailure {
126
135
  /** Only for `start_failed`: the leg that refused (#722). */
127
136
  causeClass?: ReviewerCauseClass;
128
137
  causeDetail?: string;
138
+ reason?: "review time cap";
139
+ quota?: readonly NativeReviewerQuota[];
129
140
  }
130
141
 
131
142
  export interface ReviewerReviewBinding { readonly head?: string; readonly flowRevision?: number }
@@ -138,10 +149,22 @@ export interface ReviewerPrintOptions {
138
149
  systemPrompt: string;
139
150
  privatePaths?: readonly string[];
140
151
  watchdogMs: number;
152
+ /** Sampled once for each actual child; activity never extends this wall-clock cap. */
153
+ maxMinutes?(): number;
154
+ /** Host-owned deterministic timer seam; never accepted from a review envelope. */
155
+ reviewTimer?: { set(run: () => void, ms: number): unknown; clear(handle: unknown): void };
141
156
  backend: ReviewerBackend;
142
157
  facts?(env: Envelope): string | undefined;
143
158
  verdictSince(task: number, since: number): boolean;
144
- onUsage?(usage: ReviewerPrintUsage, task: number): void;
159
+ onUsage?(usage: ReviewerPrintUsage, task: number, identity?: ReviewerUsageIdentity): void;
160
+ /** Host journal ACK before any usage-producing child is constructed; absent port refuses that launch. */
161
+ usageIntent?(attempt: string, task: number): boolean;
162
+ /** Proven native quota is account evidence, independent of whether this task later reroutes. */
163
+ onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean): boolean;
164
+ /** Only after this attempt's owned group and watch have settled. Never grants task authority. */
165
+ quotaSettled?(attempt: string): void;
166
+ /** ACK after owned settlement and usage read; failed ACK retains the private profile for recovery. */
167
+ usageSettled?(attempt: string, outcome: "complete" | "unknown", task: number): boolean;
145
168
  /** True confirms that the host re-offered the current review; void/false retains uncertainty. */
146
169
  onUnavailable?(failure: ReviewerFailure, current: () => boolean): boolean | void | Promise<boolean | void>;
147
170
  onNoVerdict?(diagnostic: ReviewerNoVerdict, current: () => boolean): void;
@@ -177,6 +200,12 @@ const reviewTask = (env: Envelope): number | undefined => {
177
200
  };
178
201
 
179
202
  export class ReviewerPrintPeer extends BasePeer {
203
+ /** #1402: the model the last result frame named; read once at the turn end. */
204
+ private servedModel: string | undefined;
205
+ observedModel(): import("../hub/events.ts").ModelObservation | undefined {
206
+ const model = this.servedModel; this.servedModel = undefined;
207
+ return model ? { model, evidence: "served" } : undefined;
208
+ }
180
209
  readonly hubNative = true;
181
210
  readonly hubOwned: boolean = true;
182
211
  private generation = 0;
@@ -235,7 +264,7 @@ export class ReviewerPrintPeer extends BasePeer {
235
264
  async start(): Promise<void> {
236
265
  // A retained child means a review's process group was never confirmed gone: no new review beside it.
237
266
  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();
267
+ if (this.policyWatch || this.childCleanup) throw new ReviewerPolicyCleanupError();
239
268
  if (this.preparation) throw new Error(`${this.id}: reviewer preparation is still running`);
240
269
  this.receipt = undefined;
241
270
  const generation = ++this.generation;
@@ -264,7 +293,8 @@ export class ReviewerPrintPeer extends BasePeer {
264
293
 
265
294
  protected override onWatchdog(): void { this.abortReview("review watchdog timeout", "timeout"); }
266
295
 
267
- private abortReview(reason: "review watchdog timeout" | "review output limit exceeded" | "review policy changed", failureCause?: DeliveryFailureCause): void {
296
+ private abortReview(reason: "review watchdog timeout" | "review output limit exceeded" | "review policy changed" | "review time cap", failureCause?: DeliveryFailureCause): void {
297
+ const cappedTask = this.reviewing;
268
298
  const generation = ++this.generation, batch = this.batch, preparation = this.preparation;
269
299
  this.reviewing = undefined;
270
300
  this.reviewMcpClose?.();
@@ -278,13 +308,13 @@ export class ReviewerPrintPeer extends BasePeer {
278
308
  if (generation !== this.generation) return;
279
309
  await this.kill();
280
310
  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);
311
+ 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
312
  if (generation === this.generation && this.state === "busy") { this.batch = undefined; super.onWatchdog(); }
283
313
  })().catch((error: Error) => this.opts.log?.(`[${this.id}] review cleanup failed, staying busy`));
284
314
  }
285
315
 
286
316
  async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
287
- if (this.state !== "idle") {
317
+ if (this.state !== "idle" || this.childCleanup) {
288
318
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
289
319
  throw new Error(`${this.id} is ${this.state}`);
290
320
  }
@@ -312,7 +342,7 @@ export class ReviewerPrintPeer extends BasePeer {
312
342
  if (task === undefined) continue; // a withdrawal or other notice: nothing to review
313
343
  if (env.private) { failure = { state: "needs_review", reason: "a private review is the person's, never a cloud reviewer's" }; break; }
314
344
  const since = Date.now();
315
- let result: { code: number | null; quota: boolean; trace: ReviewerTraceState };
345
+ let result: { code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState };
316
346
  try { result = await this.review(env, task, generation); }
317
347
  catch (error) {
318
348
  if (generation !== this.generation) return;
@@ -332,6 +362,7 @@ export class ReviewerPrintPeer extends BasePeer {
332
362
  continue;
333
363
  }
334
364
  if (error instanceof PrintChildCleanupError) {
365
+ if (error instanceof ReviewerUsageCleanupError) await this.reportFailures(batch.failures.filter(row => row.cause === "quota"), generation);
335
366
  // Unavailable until a stop confirms the group gone: no new review runs beside the survivors.
336
367
  this.opts.log?.(`[${this.id}] review of task #${task}: ${error.message}`);
337
368
  this.settle("needs_review", error instanceof ReviewerPolicyCleanupError ? error.message : `review process group still running: ${error.message}`);
@@ -357,9 +388,10 @@ export class ReviewerPrintPeer extends BasePeer {
357
388
  if (this.opts.onNoVerdict) this.opts.onNoVerdict(diagnostic, () => generation === this.generation);
358
389
  else this.opts.log?.(reviewerNoVerdictLine(this.id, diagnostic));
359
390
  } 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" });
391
+ const quotaMetadata = result.quotaReadings?.length ? { quota: result.quotaReadings } : {};
392
+ if (target) reroute.push({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata });
361
393
  if (result.quota) {
362
- reroute.push(...remainingFailures(batch, index + 1, "quota"));
394
+ reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => ({ ...failure, ...quotaMetadata })));
363
395
  batch.next = envs.length;
364
396
  break;
365
397
  }
@@ -422,7 +454,7 @@ export class ReviewerPrintPeer extends BasePeer {
422
454
  if (this.opts.admit?.(env) === false) throw new ReviewerAdmissionError(this.opts.bindingCurrent?.(task, binding) === false ? "stale_binding" : "policy_changed");
423
455
  }
424
456
 
425
- private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; trace: ReviewerTraceState }> {
457
+ private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
426
458
  const revision=Number(env.refs?.reviewRevision);
427
459
  const binding: ReviewerReviewBinding=Object.freeze({head:env.refs?.commit,flowRevision:Number.isSafeInteger(revision)&&revision>0?revision:undefined});
428
460
  this.assertAdmission(env, task, binding);
@@ -450,7 +482,18 @@ export class ReviewerPrintPeer extends BasePeer {
450
482
  };
451
483
  this.reviewMcpClose=closeMcp;
452
484
  let ownedChild: OwnedPrintChild | undefined, releasing: Promise<void> | undefined;
485
+ let deadline: { handle: unknown } | undefined;
486
+ const clearDeadline = () => {
487
+ if (!deadline) return;
488
+ if (this.opts.reviewTimer) this.opts.reviewTimer.clear(deadline.handle);
489
+ else clearTimeout(deadline.handle as ReturnType<typeof setTimeout>);
490
+ deadline = undefined;
491
+ };
453
492
  let inputReleased = false, childClosed = false, launchCleanupConfirmed = false;
493
+ let nativeStartedAt: number | undefined, usageRead = false;
494
+ const quotaAttempt = randomUUID().replaceAll("-", "");
495
+ let quotaSettlementSent = false;
496
+ let accountingAttempt: string | undefined, accountingOutcome: "complete" | "unknown" = "unknown";
454
497
  let inputFinished = false;
455
498
  const finishInput = () => {
456
499
  const closedWithoutChild = !ownedChild || ownedChild.process.pid === undefined;
@@ -460,23 +503,75 @@ export class ReviewerPrintPeer extends BasePeer {
460
503
  }
461
504
  };
462
505
  let policyOwner: ReviewPolicyOwner | undefined;
463
- const release = () => releasing ??= Promise.resolve().then(() => launch?.cleanup?.()).then(() => {});
506
+ const release = () => releasing ??= Promise.resolve().then(() => {
507
+ if (!quotaSettlementSent) {
508
+ quotaSettlementSent = true;
509
+ this.opts.quotaSettled?.(quotaAttempt);
510
+ }
511
+ if (accountingAttempt) {
512
+ if (!usageRead) {
513
+ usageRead = true;
514
+ if (ownedChild?.process.pid === undefined) accountingOutcome = "complete";
515
+ else if (nativeStartedAt !== undefined && launch?.readUsage) {
516
+ try { if (launch.readUsage(nativeStartedAt, (usage, identity) => this.opts.onUsage?.(usage, task, identity))) accountingOutcome = "complete"; }
517
+ catch { /* An unreadable or uncommitted count remains unknown. */ }
518
+ }
519
+ }
520
+ if (this.opts.usageSettled?.(accountingAttempt, accountingOutcome, task) !== true)
521
+ throw new ReviewerUsageCleanupError("reviewer accounting settlement was not acknowledged");
522
+ if (accountingOutcome === "unknown") throw new ReviewerUsageCleanupError("reviewer usage is incomplete; owned profile retained");
523
+ }
524
+ return launch?.cleanup?.();
525
+ }).then(() => {});
464
526
  try {
465
527
  launch = await this.prepare(sessionId, input, task, mcp?.config, selection?.model);
466
528
  if (generation !== this.generation) throw new ReviewerAdmissionError("stale_binding");
467
529
  this.assertAdmission(env, task, binding);
468
530
  if (launch.current?.() === false) throw new ReviewerUnavailableError("reviewer isolation changed before child spawn", "binary");
469
531
  this.receipt = launch.isolation;
532
+ const maxMinutes = this.opts.maxMinutes?.() ?? DEFAULT_REVIEW_MAX_MINUTES;
533
+ if (!Number.isFinite(maxMinutes) || maxMinutes <= 0 || maxMinutes > MAX_REVIEW_MINUTES) throw new ReviewerAdmissionError("policy_changed");
470
534
  let quota = false;
535
+ const quotaReadings = new Map<NativeReviewerQuota["id"], NativeReviewerQuota>();
536
+ const publishedQuota = new Set<string>();
537
+ const observeQuota = (reading: NativeReviewerQuota) => {
538
+ const key = JSON.stringify(reading);
539
+ if (publishedQuota.has(key)) return;
540
+ try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation) === true) publishedQuota.add(key); }
541
+ catch { /* Retain the proven quota in the batch even if its immediate account write could not commit. */ }
542
+ };
543
+ const rememberQuota = () => {
544
+ const batch = this.batch, target = batch?.targets[batch.next];
545
+ if (!batch || generation !== this.generation || target?.task !== task) return;
546
+ const failure: ReviewerFailure = { ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) };
547
+ const prior = batch.failures.findIndex(row => row.task === target.task && row.head === target.head && row.flowRevision === target.flowRevision && row.cause === "quota");
548
+ if (prior < 0) batch.failures.push(failure); else batch.failures[prior] = failure;
549
+ };
550
+ if (launch.readUsage) {
551
+ const attempt = randomUUID().replaceAll("-", "");
552
+ if (this.opts.usageIntent?.(attempt, task) !== true) throw new ReviewerAdmissionError("policy_changed");
553
+ accountingAttempt = attempt;
554
+ // The journal intent precedes spawn: the native agent-file already contains the review facts.
555
+ this.assertAdmission(env, task, binding);
556
+ }
471
557
  const child = new OwnedPrintChild({ peer: this.id, command: launch.command, args: launch.args,
472
558
  cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input,
559
+ ...(this.opts.backend.failureOnExit ? { captureStderr: true as const } : {}),
473
560
  current: () => generation === this.generation, stop: launch.stop,
474
561
  onInputReleased: () => { inputReleased = true; this.opts.inputReleased?.(inputContext, [env]); },
475
562
  onError: () => { if (this.child === child) this.child = undefined; },
476
563
  onSpawn: () => {
564
+ nativeStartedAt = Date.now();
477
565
  try { selection?.applied(); } catch { /* Native spawn remains authoritative. */ }
478
566
  this.runningBinding={task,binding};
479
567
  this.reviewing = task; this.reviewSeq++;
568
+ const reviewSequence = this.reviewSeq;
569
+ const expire = () => {
570
+ if (this.child === child && generation === this.generation && this.reviewing === task && this.reviewSeq === reviewSequence)
571
+ this.abortReview("review time cap", "timeout");
572
+ };
573
+ if (this.opts.reviewTimer) deadline = { handle: this.opts.reviewTimer.set(expire, maxMinutes * 60_000) };
574
+ else { const timer = setTimeout(expire, maxMinutes * 60_000); timer.unref?.(); deadline = { handle: timer }; }
480
575
  if (launch!.watchCurrent) {
481
576
  try {
482
577
  const sequence = this.reviewSeq, probe = launch!.startPolicyWatch!();
@@ -500,11 +595,20 @@ export class ReviewerPrintPeer extends BasePeer {
500
595
  } catch { /* Optional trace metadata never changes review execution. */ }
501
596
  const usage = this.opts.backend.usage?.(event);
502
597
  if (usage) this.opts.onUsage?.(usage, task);
503
- if (this.opts.backend.failure?.(event) === "quota") quota = true;
598
+ try { const model = this.opts.backend.model?.(event); if (model) this.servedModel = model; } catch { /* optional metadata never changes review execution */ }
599
+ try {
600
+ const failure = this.opts.backend.failure?.(event);
601
+ if (failure === "quota") { quota = true; rememberQuota(); } // Legacy synthetic backends carry no reset evidence.
602
+ else {
603
+ const reading = nativeReviewerQuota(failure);
604
+ if (reading) { quota = true; quotaReadings.set(reading.id, reading); observeQuota(reading); rememberQuota(); }
605
+ }
606
+ } catch { /* Malformed optional metadata cannot manufacture a quota pause. */ }
504
607
  },
505
608
  onActivity: () => this.touch(),
506
609
  onLimit: () => this.abortReview("review output limit exceeded"),
507
610
  onLeaderExit: () => {
611
+ clearDeadline();
508
612
  if (this.child === child) { this.reviewing = undefined; this.runningBinding=undefined; }
509
613
  void this.stopPolicyWatch(policyOwner).catch(() => {});
510
614
  },
@@ -514,10 +618,17 @@ export class ReviewerPrintPeer extends BasePeer {
514
618
  this.childCleanup = release;
515
619
  this.childCurrent = launch.watchCurrent ? launch.current : undefined;
516
620
  const code = await child.done;
621
+ if (generation === this.generation && this.child === child && this.opts.backend.failureOnExit) {
622
+ try {
623
+ const reading = nativeReviewerQuota(this.opts.backend.failureOnExit({ exitCode: code, stderr: child.stderrAfterSettlement() }));
624
+ if (reading) { quota = true; quotaReadings.set(reading.id, reading); observeQuota(reading); rememberQuota(); }
625
+ } catch { /* Unknown or incomplete exit diagnostics remain ordinary failure. */ }
626
+ }
517
627
  childClosed = true;
518
628
  if (this.child === child) this.child = undefined;
519
- return { code, quota, trace };
629
+ return { code, quota, trace, ...(quotaReadings.size ? { quotaReadings: [...quotaReadings.values()] } : {}) };
520
630
  } finally {
631
+ clearDeadline();
521
632
  if (this.activeTrace?.value === trace) this.activeTrace = undefined;
522
633
  closeMcp();
523
634
  // Joining the watcher precedes deletion of files it can still read, even when native cleanup failed.
@@ -528,7 +639,7 @@ export class ReviewerPrintPeer extends BasePeer {
528
639
  launchCleanupConfirmed = true;
529
640
  if (this.policyWatch === policyOwner) this.policyWatch = undefined;
530
641
  }
531
- } catch { this.opts.log?.(`[${this.id}] reviewer isolation cleanup incomplete`); }
642
+ } catch (error) { this.opts.log?.(`[${this.id}] reviewer isolation cleanup incomplete`); if (error instanceof ReviewerUsageCleanupError) throw error; }
532
643
  finishInput();
533
644
  }
534
645
  }
@@ -559,6 +670,10 @@ export class ReviewerPrintPeer extends BasePeer {
559
670
  try { await workerStopped; } catch (error) { workerError = error; }
560
671
  if (workerError) throw workerError;
561
672
  if (childError) throw childError;
673
+ if (!child && cleanup) {
674
+ await cleanup();
675
+ if (this.childCleanup === cleanup) this.childCleanup = undefined;
676
+ }
562
677
  if (child) {
563
678
  await cleanup?.();
564
679
  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;
@@ -1003,7 +1003,9 @@ export function cells(s: ConsoleState, row: any, selected: boolean, now: number,
1003
1003
  const paused = b?.paused ? `budget ${relative(b.paused.resetsAt, now)}` : row.paused && typeof row.paused === "object"
1004
1004
  ? `${row.paused.by ?? "paused"}${typeof row.paused.at === "number" ? ` ${duration(now - row.paused.at)}` : ""}`
1005
1005
  : row.paused === "manual" ? "user" : row.paused ? String(row.paused).split(":")[0] : "-";
1006
- return [id(row.planner ? `${row.id} (planner)` : row.id, row.state === "offline" ? undefined : "info"), span(`${row.rostered === false ? `${row.state} off roster` : row.state}${Array.isArray(row.standbySessions) && row.standbySessions.length ? ` +standby:${row.standbySessions.length}` : ""}`, stateTone(row.state)),
1006
+ // #1414: the conductor from the hub's settled flow roles, first so a narrow PEER column still shows it; an older hub without flowRoles keeps the planner-only label.
1007
+ const tags = [Array.isArray(row.flowRoles) && row.flowRoles.includes("conductor") && "conductor", row.planner && "planner"].filter(Boolean);
1008
+ return [id(tags.length ? `${row.id} (${tags.join(", ")})` : row.id, row.state === "offline" ? undefined : "info"), span(`${row.rostered === false ? `${row.state} off roster` : row.state}${Array.isArray(row.standbySessions) && row.standbySessions.length ? ` +standby:${row.standbySessions.length}` : ""}`, stateTone(row.state)),
1007
1009
  ...(showPermissionModes(s) ? [span(row.permissionMode && row.permissionMode !== "ask" ? row.permissionMode : "-", row.permissionMode === "never-ask" ? "attention" : undefined)] : []),
1008
1010
  span(row.pullOnly && definitionOf(row.id)?.attach?.pullOnlyForms?.includes("tui") ? "pull-only" : row.toolsOnly ? "tools-only" : row.attached === false ? "detached" : "attached", row.toolsOnly ? "attention" : undefined),
1009
1011
  ((hub) => span(hub.cell, hub.differs ? "attention" : hub.cell === "-" || hub.unknown ? "muted" : undefined))(peerHubVersion(row, s.versions?.daemon)),
@@ -6,3 +6,23 @@ export function freeText(words: string[], usage: string): string {
6
6
  if (flag) throw new Error(`the message would absorb the flag "${flag}"; put it after "--" to send it as text; usage: ${usage}`);
7
7
  return (end === -1 ? words : [...before, ...words.slice(end + 1)]).join(" ");
8
8
  }
9
+
10
+ /**
11
+ * #1433: the first word of a write command's free text that reads as an option the command does not know: it starts with `--`, or is `-h`. Words after a lone `--` are text, as in `freeText`.
12
+ * A command that takes its flags out first passes what is left.
13
+ */
14
+ export function unknownOption(words: readonly string[]): string | undefined {
15
+ const end = words.indexOf("--");
16
+ return (end === -1 ? words : words.slice(0, end)).find(word => word.startsWith("--") || word === "-h");
17
+ }
18
+
19
+ /** The text words with the lone `--` separator removed. */
20
+ export function withoutSeparator(words: readonly string[]): string[] {
21
+ const end = words.indexOf("--");
22
+ return end === -1 ? [...words] : [...words.slice(0, end), ...words.slice(end + 1)];
23
+ }
24
+
25
+ /** The refusal for an option-like word where a write command wanted text, said before anything is filed. */
26
+ export function unknownOptionRefusal(word: string, command: string, usage: string | undefined): string {
27
+ return `unknown option ${JSON.stringify(word)} for ${command}; nothing was filed. Put "--" before text that starts with dashes${usage ? `. Usage: ${usage}` : ""}`;
28
+ }
@@ -23,7 +23,7 @@ export function parseHandoffArgs(operands: readonly string[]): HandoffCliRequest
23
23
  const value = operands[++i];
24
24
  if (value === undefined || value.startsWith("--")) return { usage: HANDOFF_USAGE };
25
25
  if (arg === "--path") paths.push(value); else { if (Object.hasOwn(one, arg)) return { usage: HANDOFF_USAGE }; one[arg] = value; }
26
- } else if (arg.startsWith("--")) return { usage: HANDOFF_USAGE };
26
+ } else if (arg.startsWith("--") || arg === "-h") return { usage: `unknown option ${JSON.stringify(arg)}; nothing was filed\n${HANDOFF_USAGE}` };
27
27
  else rest.push(arg);
28
28
  }
29
29
  const project = one["--project"];