@staix/agent-hub 0.34.1 → 0.36.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 (213) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +53 -7
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/addons/claude-mem.md +4 -4
  5. package/docs/addons/open-code-review.md +1 -1
  6. package/docs/agent-notes/README.md +66 -0
  7. package/docs/agent-notes/adapters.md +14 -7
  8. package/docs/agent-notes/budget.md +1 -1
  9. package/docs/agent-notes/bus.md +2 -1
  10. package/docs/agent-notes/daemon.md +9 -7
  11. package/docs/agent-notes/local-worker.md +1 -1
  12. package/docs/agent-notes/models.md +5 -2
  13. package/docs/agent-notes/tasks.md +9 -2
  14. package/docs/agent-notes/tests.md +6 -0
  15. package/docs/design/adapters.md +182 -2
  16. package/docs/design/agent-hub-architecture.md +64 -2
  17. package/docs/design/agent-hub.md +6 -0
  18. package/docs/design/bus.md +26 -0
  19. package/docs/design/execution-reference.md +306 -0
  20. package/docs/design/guidance-experiments.md +438 -0
  21. package/docs/design/model-routes.md +628 -0
  22. package/docs/design/supervision.md +121 -0
  23. package/docs/design/task-board.md +121 -0
  24. package/docs/dogfood.md +45 -13
  25. package/docs/events.md +38 -20
  26. package/docs/memory.md +21 -7
  27. package/docs/operations.md +824 -40
  28. package/docs/profiles.md +2 -2
  29. package/docs/quickstart.md +117 -4
  30. package/docs/research.md +73 -13
  31. package/docs/roles.md +1 -1
  32. package/docs/sdlc.md +117 -11
  33. package/docs/security.md +153 -15
  34. package/docs/smoke.md +14 -0
  35. package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
  36. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  37. package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
  38. package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
  39. package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
  40. package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
  41. package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
  42. package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
  43. package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
  44. package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
  45. package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
  46. package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
  47. package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
  48. package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
  49. package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
  50. package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
  51. package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
  52. package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
  53. package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
  54. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
  55. package/docs/verification/2026-11-09-0.35.0.md +129 -0
  56. package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
  57. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  58. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  59. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  60. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  61. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  62. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  63. package/docs/verification/claude-permission-transport-native.py +10 -3
  64. package/docs/verification/claude-shell-wrapper-native.py +8 -8
  65. package/docs/verified.json +245 -15
  66. package/package.json +3 -3
  67. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  68. package/plugins/agent-hub/kimi-hook.js +21230 -0
  69. package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
  70. package/plugins/agent-hub/server.js +4359 -1071
  71. package/scripts/check-docs.mjs +12 -1
  72. package/src/adapters/acp-model-policy.ts +56 -0
  73. package/src/adapters/acp.ts +175 -5
  74. package/src/adapters/agy/entry.ts +8 -5
  75. package/src/adapters/agy/hooks.ts +65 -15
  76. package/src/adapters/channel-peer.ts +33 -1
  77. package/src/adapters/claude-channel.ts +7 -4
  78. package/src/adapters/claude-implementer.ts +16 -3
  79. package/src/adapters/codex-appserver.ts +118 -8
  80. package/src/adapters/codex-review-isolation.ts +3 -1
  81. package/src/adapters/compat.ts +18 -13
  82. package/src/adapters/definitions/builtin-metadata.ts +8 -1
  83. package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
  84. package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
  85. package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
  86. package/src/adapters/definitions/reviewer-variants.ts +3 -1
  87. package/src/adapters/kimi-review-policy-worker.js +2 -0
  88. package/src/adapters/kimi-review-policy-worker.ts +85 -0
  89. package/src/adapters/kimi-review-policy.ts +68 -0
  90. package/src/adapters/kimi-review.ts +41 -41
  91. package/src/adapters/kimi-tui-facts.ts +153 -0
  92. package/src/adapters/kimi-wire-usage.ts +33 -8
  93. package/src/adapters/local-worker.ts +60 -21
  94. package/src/adapters/model-token.ts +3 -0
  95. package/src/adapters/pi.ts +27 -5
  96. package/src/adapters/qwen-dual.ts +324 -44
  97. package/src/adapters/registry-types.ts +34 -3
  98. package/src/adapters/registry.ts +1 -0
  99. package/src/adapters/reviewer-policy-watch.ts +86 -0
  100. package/src/adapters/reviewer-print.ts +80 -18
  101. package/src/cli/agents.ts +1 -1
  102. package/src/cli/facts-hook.ts +4 -2
  103. package/src/cli/guidance.ts +67 -0
  104. package/src/cli/help.ts +13 -5
  105. package/src/cli/identity.ts +13 -3
  106. package/src/cli/init-prompt.ts +15 -2
  107. package/src/cli/init-required-checks.ts +122 -0
  108. package/src/cli/init-settings.ts +10 -4
  109. package/src/cli/init.ts +39 -3
  110. package/src/cli/kimi-facts-hook.ts +11 -0
  111. package/src/cli/kimi-plugin.ts +157 -0
  112. package/src/cli/lineage.ts +78 -0
  113. package/src/cli/main.ts +159 -19
  114. package/src/cli/model.ts +52 -0
  115. package/src/cli/output.ts +23 -1
  116. package/src/cli/reset.ts +1 -1
  117. package/src/cli/setup-research.ts +10 -0
  118. package/src/cli/status-lines.ts +8 -4
  119. package/src/hub/autonomy-defaults.ts +20 -9
  120. package/src/hub/board.ts +346 -4
  121. package/src/hub/budget.ts +1 -1
  122. package/src/hub/build-entry.ts +11 -0
  123. package/src/hub/bus.ts +52 -2
  124. package/src/hub/ci-watch.ts +4 -4
  125. package/src/hub/code-facts.ts +10 -3
  126. package/src/hub/completions.ts +3 -1
  127. package/src/hub/config-apply.ts +3 -1
  128. package/src/hub/config-trust.ts +1 -0
  129. package/src/hub/control-client.ts +1 -1
  130. package/src/hub/daemon.ts +1387 -121
  131. package/src/hub/deliverable-files.ts +38 -5
  132. package/src/hub/delivery-hints.ts +4 -2
  133. package/src/hub/delivery-journal.ts +50 -2
  134. package/src/hub/delivery-public.ts +51 -0
  135. package/src/hub/dogfood-profile.ts +9 -5
  136. package/src/hub/envelope.ts +1 -1
  137. package/src/hub/events.ts +28 -18
  138. package/src/hub/execution-lineage-owner.ts +272 -0
  139. package/src/hub/execution-lineage.ts +164 -0
  140. package/src/hub/execution-links.ts +85 -0
  141. package/src/hub/execution-reference.ts +36 -0
  142. package/src/hub/guidance-variants.ts +398 -0
  143. package/src/hub/handoff.ts +1 -0
  144. package/src/hub/hub-tools.ts +62 -2
  145. package/src/hub/instances.ts +4 -3
  146. package/src/hub/kimi-events.ts +46 -0
  147. package/src/hub/kimi-usage.ts +132 -29
  148. package/src/hub/lifecycle.ts +31 -15
  149. package/src/hub/limits.ts +13 -4
  150. package/src/hub/manager.ts +58 -3
  151. package/src/hub/memory-policy.ts +4 -3
  152. package/src/hub/memory-sync-attestation.ts +54 -0
  153. package/src/hub/memory-sync-state.ts +20 -5
  154. package/src/hub/model-overrides.ts +115 -0
  155. package/src/hub/native-hook-launch.ts +12 -3
  156. package/src/hub/operational-view.ts +2 -2
  157. package/src/hub/peers.ts +28 -1
  158. package/src/hub/permission-mode.ts +1 -1
  159. package/src/hub/person-figures.ts +88 -0
  160. package/src/hub/planning.ts +1 -1
  161. package/src/hub/progress.ts +24 -7
  162. package/src/hub/report.ts +38 -4
  163. package/src/hub/research-dataset.ts +158 -0
  164. package/src/hub/research-memory.ts +68 -0
  165. package/src/hub/research-quality.ts +118 -0
  166. package/src/hub/research-record.ts +279 -0
  167. package/src/hub/research.ts +126 -27
  168. package/src/hub/restart.ts +27 -0
  169. package/src/hub/roles.ts +26 -0
  170. package/src/hub/routing.ts +4 -1
  171. package/src/hub/sdlc-merge.ts +39 -1
  172. package/src/hub/sdlc-release.ts +1 -1
  173. package/src/hub/sdlc.ts +62 -11
  174. package/src/hub/settings.ts +5 -0
  175. package/src/hub/startup-event-seeds.ts +51 -0
  176. package/src/hub/startup-readiness.ts +65 -0
  177. package/src/hub/startup-timing.ts +38 -0
  178. package/src/hub/supervision-proposals.ts +405 -0
  179. package/src/hub/supervision-rules.ts +388 -0
  180. package/src/hub/supervision.ts +2 -0
  181. package/src/hub/task-approval.ts +2 -2
  182. package/src/hub/task-repository.ts +5 -0
  183. package/src/hub/tasks.ts +632 -59
  184. package/src/hub/ui.ts +9 -5
  185. package/src/hub/visual-assets.ts +50 -0
  186. package/src/hub/visual.ts +257 -0
  187. package/src/memory/brief.ts +169 -14
  188. package/src/memory/capture.ts +4 -3
  189. package/src/memory/recall.ts +46 -5
  190. package/src/memory/record-provenance.ts +82 -0
  191. package/src/memory/records.ts +116 -0
  192. package/src/models/relay.ts +9 -2
  193. package/src/models/route/adec.ts +190 -0
  194. package/src/models/route/config.ts +64 -3
  195. package/src/models/route/decision-evidence.ts +83 -0
  196. package/src/models/route/decision.ts +215 -0
  197. package/src/models/route/relay-selector.ts +8 -7
  198. package/src/models/route/runtime.ts +35 -22
  199. package/src/models/route/stage-diagnostics.ts +22 -0
  200. package/src/models/route/stage-evidence.ts +55 -0
  201. package/src/models/route/stage-fallback.ts +58 -0
  202. package/src/models/route/stage-input.ts +155 -0
  203. package/src/models/route/stage.ts +5 -147
  204. package/src/ui/guidance-panel.ts +156 -0
  205. package/src/ui/guidance-view.ts +43 -0
  206. package/src/ui/index.html +134 -6
  207. package/src/ui/lineage-view.ts +34 -0
  208. package/src/ui/plugin.ts +136 -11
  209. package/templates/AGENTS.block.md +1 -1
  210. package/templates/config.json +1 -1
  211. package/templates/profiles/general.json +1 -1
  212. package/templates/profiles/research.json +1 -1
  213. package/templates/profiles/writing.json +1 -1
@@ -1,3 +1,11 @@
1
+ /** One host-latched runtime choice; applied binds the captured revision and boundary, never a later value. */
2
+ export interface ModelOverrideSelection {
3
+ readonly model: string | undefined;
4
+ applied(nativeModel?: string): void;
5
+ /** Retire only this still-unacknowledged capture after a definitive native pre-start rejection. */
6
+ rejected?(): void;
7
+ }
8
+
1
9
  import type { ClaudeImplementerOptions } from "./claude-implementer.ts";
2
10
  import type { ReviewerBackend, ReviewerPrintOptions } from "./reviewer-print.ts";
3
11
  import type { SettingDef } from "../hub/settings.ts";
@@ -126,7 +134,7 @@ export interface ContextReader {
126
134
  export type { Capability, CapabilityManifest, SideEffect } from "../hub/capabilities.ts";
127
135
 
128
136
  export interface NativeFactsInput {
129
- event: "SessionStart" | "PreInvocation" | "PostInvocation" | "PreToolUse" | "PostToolUse" | "Stop";
137
+ event: "SessionStart" | "PreInvocation" | "PostInvocation" | "PreToolUse" | "PostToolUse" | "Stop" | "TurnStarted" | "StopFailure" | "Interrupt" | "SessionEnd" | "TaskStarted" | "Notification";
130
138
  phase: "session" | "start" | "pre" | "post" | "stop";
131
139
  sessionId: string;
132
140
  transcriptPath: string;
@@ -138,15 +146,36 @@ export interface NativeFactsInput {
138
146
  fullyIdle?: boolean;
139
147
  terminationReason?: string;
140
148
  }
149
+ export interface NativeFactsReadOptions {
150
+ completion?: boolean;
151
+ sinceOffset?: number;
152
+ unchanged?: { size: number; mtimeMs: number };
153
+ }
154
+ export interface NativeFactsUsage {
155
+ id: string;
156
+ index: number;
157
+ inputTokens: number;
158
+ outputTokens: number;
159
+ cacheReadTokens: number;
160
+ totalTokens: number;
161
+ at?: string;
162
+ }
141
163
  export interface NativeFactsTranscript {
142
- completion?: { id: string; index: number };
164
+ completion?: { id: string; index: number; reason?: "completed" | "failed" | "cancelled" };
165
+ started?: { id: string; index: number; origin: string };
166
+ background?: number;
143
167
  factIds: string[];
168
+ usage?: NativeFactsUsage[];
169
+ size?: number;
170
+ mtimeMs?: number;
171
+ scannedFrom?: number;
172
+ unchanged?: boolean;
144
173
  }
145
174
  /** Fixed native codec and bounded readback, never supplied by project configuration. */
146
175
  export interface NativeFactsPort {
147
176
  decode(event: string, input: unknown): NativeFactsInput | undefined;
148
177
  encode(event: string, text?: string): Record<string, unknown> | undefined;
149
- read(session: string, transcript: string): NativeFactsTranscript;
178
+ read(session: string, transcript: string, options?: NativeFactsReadOptions): NativeFactsTranscript;
150
179
  }
151
180
 
152
181
  /** Only the frozen native seams are extensible; a definition cannot add an arbitrary daemon callback. */
@@ -300,6 +329,8 @@ export interface AdapterDefinition {
300
329
  validateEffective?(raw: Record<string, unknown>, fail: (key: string, reason: string) => never): void;
301
330
  };
302
331
  capabilities?: { manifest?(peer: PeerAdapter): Promise<CapabilityManifest>; watch?: boolean };
332
+ /** Fixed factory support only; the host still checks the actual native surface and form. */
333
+ modelOverride?: { readonly boundary: "turn"; readonly acp?: import("./acp-model-policy.ts").AcpModelPolicy };
303
334
  /** Stable host projection order and planner eligibility, independent of default task roles. */
304
335
  projection?: { roleRank?: number; startRank?: number; helpRank?: number; plannerEligible?: boolean };
305
336
  cli: {
@@ -243,6 +243,7 @@ export function assertNativeCapabilityScope(definition: AdapterDefinition): void
243
243
  ["titlePersistence", definition.titlePersistence !== undefined],
244
244
  ["questionWaitMs", definition.questionWaitMs !== undefined],
245
245
  ["settle", definition.settle !== undefined],
246
+ ["modelOverride", definition.modelOverride !== undefined],
246
247
  ["start.acpCommand", declared(definition.start, "acpCommand")],
247
248
  ["attach.admission", declared(definition.attach, "admission")],
248
249
  ["budget.resetSoftTokensOnResume", declared(definition.budget, "resetSoftTokensOnResume")],
@@ -0,0 +1,86 @@
1
+ /** A fixed host producer's full policy check, never a verdict-authority cache. */
2
+ export interface ReviewerPolicyProbe {
3
+ /** Boot/protocol failures revoke even when a child exits before its first periodic poll. */
4
+ readonly failure?: Promise<void>;
5
+ check(): Promise<boolean>;
6
+ stop(): Promise<void>;
7
+ }
8
+ export interface ReviewerPolicyWatch {
9
+ /** The caller attaches ownership before any timer or notification can run. */
10
+ start(): void;
11
+ /** Only an explicit owner retry may repeat a failed join. */
12
+ stop(retry?: boolean): Promise<void>;
13
+ }
14
+ export interface ReviewerPolicyWatchClock {
15
+ now(): number;
16
+ schedule(delayMs: number, run: () => void): () => void;
17
+ }
18
+ const POLICY_POLL_MS = 100;
19
+
20
+ /** Serialized absolute cadence: an overdue check runs now, coalescing missed slots at its start. */
21
+ export function createReviewerPolicyWatch(probe: ReviewerPolicyProbe, changed: () => void,
22
+ clock: Partial<ReviewerPolicyWatchClock> = {}): ReviewerPolicyWatch {
23
+ const now = clock.now ?? (() => performance.now());
24
+ const schedule = clock.schedule ?? ((delayMs: number, run: () => void) => {
25
+ const timer = setTimeout(run, delayMs); timer.unref?.();
26
+ return () => clearTimeout(timer);
27
+ });
28
+ let started = false, stopped = false, due = 0;
29
+ let cancelTimer: (() => void) | undefined, flight: Promise<void> | undefined;
30
+ let stopping: Promise<void> | undefined, stopFailed = false;
31
+ const sample = () => {
32
+ const value = now();
33
+ if (!Number.isFinite(value)) throw new Error("review policy clock unavailable");
34
+ return value;
35
+ };
36
+ const stop = (retry = false): Promise<void> => {
37
+ stopped = true;
38
+ cancelTimer?.(); cancelTimer = undefined;
39
+ if (retry && stopFailed) { stopping = undefined; stopFailed = false; }
40
+ if (!stopping) {
41
+ const pending = flight;
42
+ // Termination must settle a blocked check before joining that check; the reverse order can deadlock.
43
+ stopping = Promise.resolve().then(() => probe.stop()).then(async () => { await pending; });
44
+ void stopping.catch(() => { stopFailed = true; });
45
+ }
46
+ return stopping;
47
+ };
48
+ const fail = () => {
49
+ if (stopped) return;
50
+ void stop().catch(() => {}); // The owner retains and observes the same failed join.
51
+ try { changed(); } catch { /* The probe is already stopping; a notification cannot rearm it. */ }
52
+ };
53
+ const arm = () => {
54
+ if (stopped) return;
55
+ try { cancelTimer = schedule(Math.max(0, due - sample()), tick); }
56
+ catch { fail(); }
57
+ };
58
+ const tick = () => {
59
+ cancelTimer = undefined;
60
+ if (stopped) return;
61
+ if (flight) { fail(); return; }
62
+ try {
63
+ const at = sample();
64
+ if (at > due) due += Math.floor((at - due) / POLICY_POLL_MS) * POLICY_POLL_MS;
65
+ } catch { fail(); return; }
66
+ const pending = (async () => {
67
+ let current = false;
68
+ try { current = await probe.check() === true; } catch { /* A failed check is policy drift. */ }
69
+ if (stopped) return;
70
+ if (!current) { fail(); return; }
71
+ due += POLICY_POLL_MS;
72
+ arm();
73
+ })();
74
+ flight = pending;
75
+ void pending.finally(() => { if (flight === pending) flight = undefined; }).catch(() => {});
76
+ };
77
+ return {
78
+ start: () => {
79
+ if (started || stopped) return;
80
+ started = true;
81
+ if (probe.failure) void probe.failure.then(fail, fail);
82
+ try { due = sample() + POLICY_POLL_MS; arm(); } catch { fail(); }
83
+ },
84
+ stop,
85
+ };
86
+ }
@@ -1,3 +1,5 @@
1
+ import type { ModelOverrideSelection } from "./registry-types.ts";
2
+ import { isNativeModelToken } from "./model-token.ts";
1
3
  import type { ChildProcess } from "node:child_process";
2
4
  import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver } from "./claude-print-child.ts";
3
5
  import { randomUUID } from "node:crypto";
@@ -6,6 +8,7 @@ import { BasePeer } from "../hub/peers.ts";
6
8
  import type { DeliveryFailureCause } from "../hub/delivery-failure.ts";
7
9
  import type { Envelope } from "../hub/envelope.ts";
8
10
  import type { ReviewerMcpSession, ReviewerToolName } from "./reviewer-mcp.ts";
11
+ import { createReviewerPolicyWatch, type ReviewerPolicyProbe, type ReviewerPolicyWatch } from "./reviewer-policy-watch.ts";
9
12
 
10
13
  /** #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. */
11
14
  export const REVIEWER_CAUSE_CLASSES = ["version", "binary", "mcp_inventory", "plugins_hooks_apps", "sandbox_proof", "credential_root", "timeout", "unknown"] as const;
@@ -33,6 +36,9 @@ class ReviewerAdmissionError extends Error {
33
36
  constructor(readonly reason: "stale_binding" | "policy_changed") { super("review admission changed"); }
34
37
  }
35
38
  class ReviewerInputAdmissionError extends Error {}
39
+ class ReviewerPolicyCleanupError extends PrintChildCleanupError {
40
+ constructor() { super("review policy worker cleanup unconfirmed; run ahub status and stop the peer before retrying"); }
41
+ }
36
42
 
37
43
  export interface ReviewerPrintUsage { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }
38
44
  export interface ReviewerIsolationReceipt {
@@ -60,6 +66,8 @@ export interface ReviewerPrepareContext {
60
66
  /** Host-framed public review evidence, never configuration-selected argv. */
61
67
  input?: string;
62
68
  task?: number;
69
+ /** Captured host runtime override, absent leaves the backend's native default unchanged. */
70
+ modelOverride?: string;
63
71
  }
64
72
  export interface ReviewerLaunch {
65
73
  command: readonly string[];
@@ -74,6 +82,8 @@ export interface ReviewerLaunch {
74
82
  stop?: (child: ChildProcess) => Promise<void>;
75
83
  /** Latch a change in native policy for the running review, not just at spawn. */
76
84
  watchCurrent?: true;
85
+ /** Fixed host factory: periodic work is separate from the synchronous current() authority fence. */
86
+ startPolicyWatch?: () => ReviewerPolicyProbe;
77
87
  }
78
88
  export interface ReviewerBackend {
79
89
  id: string;
@@ -120,6 +130,8 @@ export interface ReviewerFailure {
120
130
 
121
131
  export interface ReviewerReviewBinding { readonly head?: string; readonly flowRevision?: number }
122
132
  export interface ReviewerPrintOptions {
133
+ /** Host-only choice sampled once at the next turn/review boundary. */
134
+ getModelOverride?: () => ModelOverrideSelection;
123
135
  cwd: string;
124
136
  command?: readonly string[];
125
137
  mcpConfig: string;
@@ -149,6 +161,7 @@ export interface ReviewerPrintOptions {
149
161
 
150
162
  type ReviewTarget = Omit<ReviewerFailure, "cause">;
151
163
  interface ReviewBatch { targets: (ReviewTarget | undefined)[]; next: number; failures: ReviewerFailure[] }
164
+ interface ReviewPolicyOwner { readonly child: OwnedPrintChild; readonly watch: ReviewerPolicyWatch; readonly cleanup: () => Promise<void>; readonly closed: () => void }
152
165
  const reviewTarget = (env: Envelope): ReviewTarget | undefined => {
153
166
  const task = reviewTask(env);
154
167
  if (task === undefined || env.private) return undefined;
@@ -170,6 +183,7 @@ export class ReviewerPrintPeer extends BasePeer {
170
183
  private child: OwnedPrintChild | undefined;
171
184
  private childCleanup: (() => Promise<void>) | undefined;
172
185
  private childCurrent: (() => boolean) | undefined;
186
+ private policyWatch: ReviewPolicyOwner | undefined;
173
187
  private reviewMcpClose: (() => void) | undefined;
174
188
  private activeDeliveryId: string | undefined;
175
189
  private batch: ReviewBatch | undefined;
@@ -221,6 +235,7 @@ export class ReviewerPrintPeer extends BasePeer {
221
235
  async start(): Promise<void> {
222
236
  // A retained child means a review's process group was never confirmed gone: no new review beside it.
223
237
  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();
224
239
  if (this.preparation) throw new Error(`${this.id}: reviewer preparation is still running`);
225
240
  this.receipt = undefined;
226
241
  const generation = ++this.generation;
@@ -242,8 +257,8 @@ export class ReviewerPrintPeer extends BasePeer {
242
257
  this.preparation?.abort.abort();
243
258
  await this.preparation?.done.catch(() => {});
244
259
  this.settle("needs_review", reason ?? "review stopped before settlement");
245
- if (this.child) this.setState("busy"); // unavailable, not offline, until the group is confirmed gone
246
- await this.kill(); // throws when the child could not be stopped; its handle is kept and the peer stays busy
260
+ if (this.child || this.policyWatch) this.setState("busy"); // unavailable until both owned resources are confirmed gone
261
+ await this.kill(true); // An explicit stop may retry an earlier failed worker join.
247
262
  this.setState("offline");
248
263
  }
249
264
 
@@ -319,7 +334,7 @@ export class ReviewerPrintPeer extends BasePeer {
319
334
  if (error instanceof PrintChildCleanupError) {
320
335
  // Unavailable until a stop confirms the group gone: no new review runs beside the survivors.
321
336
  this.opts.log?.(`[${this.id}] review of task #${task}: ${error.message}`);
322
- this.settle("needs_review", `review process group still running: ${error.message}`);
337
+ this.settle("needs_review", error instanceof ReviewerPolicyCleanupError ? error.message : `review process group still running: ${error.message}`);
323
338
  return;
324
339
  }
325
340
  // Once an earlier review in this batch ran, the batch had effects: hold it for a person, never requeue it.
@@ -376,20 +391,21 @@ export class ReviewerPrintPeer extends BasePeer {
376
391
  return reoffered;
377
392
  }
378
393
 
379
- private prepare(sessionId: string, input?: string, task?: number, mcpConfig?: string): Promise<ReviewerLaunch> {
394
+ private prepare(sessionId: string, input?: string, task?: number, mcpConfig?: string, modelOverride?: string): Promise<ReviewerLaunch> {
380
395
  const abort = new AbortController();
381
396
  const done = (async () => {
382
397
  if (this.opts.backend.taskMcp && !this.opts.taskMcp) throw new Error("task-bound reviewer MCP is unavailable");
383
398
  const launch = await this.opts.backend.prepare({ peer: this.id, cwd: this.opts.cwd, sessionId,
384
399
  mcpConfig: this.opts.backend.taskMcp ? (mcpConfig ?? '{"mcpServers":{}}') : this.opts.mcpConfig,
385
400
  systemPrompt: this.opts.systemPrompt, privatePaths: this.opts.privatePaths ?? [], command: this.opts.command, signal: abort.signal,
386
- ...(input === undefined ? {} : { input }), ...(task === undefined ? {} : { task }) });
401
+ ...(input === undefined ? {} : { input }), ...(task === undefined ? {} : { task }), ...(modelOverride === undefined ? {} : { modelOverride }) });
387
402
  if ("unavailable" in launch) throw new ReviewerUnavailableError(launch.unavailable, launch.causeClass ?? "unknown", launch.detail);
388
403
  const proof = launch.isolation;
389
404
  const policy = this.opts.backend.nativePolicy
390
405
  ? proof?.enforcement === "native-policy" && proof.freshSession === true && proof.hubToolsOnly === true
391
406
  : proof?.strictMcp === true && proof.ephemeral === true;
392
- if (abort.signal.aborted || !proof || proof.backend !== this.opts.backend.id || proof.readOnly !== true || !policy || !proof.binary || !proof.version || !proof.profile || !proof.evidence.length || !launch.command.length) {
407
+ if (abort.signal.aborted || !proof || proof.backend !== this.opts.backend.id || proof.readOnly !== true || !policy || !proof.binary || !proof.version || !proof.profile || !proof.evidence.length || !launch.command.length
408
+ || launch.watchCurrent && (!launch.current || !launch.startPolicyWatch)) {
393
409
  await launch.cleanup?.();
394
410
  throw new ReviewerUnavailableError("reviewer isolation is unavailable or preparation was cancelled", "unknown");
395
411
  }
@@ -410,6 +426,8 @@ export class ReviewerPrintPeer extends BasePeer {
410
426
  const revision=Number(env.refs?.reviewRevision);
411
427
  const binding: ReviewerReviewBinding=Object.freeze({head:env.refs?.commit,flowRevision:Number.isSafeInteger(revision)&&revision>0?revision:undefined});
412
428
  this.assertAdmission(env, task, binding);
429
+ const selection = this.opts.getModelOverride?.();
430
+ if (selection?.model !== undefined && !isNativeModelToken(selection.model)) throw new ReviewerAdmissionError("policy_changed");
413
431
  let facts: string | undefined;
414
432
  try { facts = this.opts.facts?.(env); } catch (error) { this.opts.log?.(`[${this.id}] review facts for task #${task} failed: ${(error as Error).message}`); }
415
433
  const input = `${frame(env)}${facts ? `\n\n${facts}` : ""}`;
@@ -433,10 +451,18 @@ export class ReviewerPrintPeer extends BasePeer {
433
451
  this.reviewMcpClose=closeMcp;
434
452
  let ownedChild: OwnedPrintChild | undefined, releasing: Promise<void> | undefined;
435
453
  let inputReleased = false, childClosed = false, launchCleanupConfirmed = false;
436
- let policyTimer: ReturnType<typeof setInterval> | undefined;
454
+ let inputFinished = false;
455
+ const finishInput = () => {
456
+ const closedWithoutChild = !ownedChild || ownedChild.process.pid === undefined;
457
+ if (!inputFinished && mcpCloseConfirmed && launchCleanupConfirmed && (closedWithoutChild || inputReleased && childClosed)) {
458
+ inputFinished = true;
459
+ try { this.opts.inputFinished?.(inputContext, [env]); } catch { /* A cleanup receipt never changes the verdict. */ }
460
+ }
461
+ };
462
+ let policyOwner: ReviewPolicyOwner | undefined;
437
463
  const release = () => releasing ??= Promise.resolve().then(() => launch?.cleanup?.()).then(() => {});
438
464
  try {
439
- launch = await this.prepare(sessionId, input, task, mcp?.config);
465
+ launch = await this.prepare(sessionId, input, task, mcp?.config, selection?.model);
440
466
  if (generation !== this.generation) throw new ReviewerAdmissionError("stale_binding");
441
467
  this.assertAdmission(env, task, binding);
442
468
  if (launch.current?.() === false) throw new ReviewerUnavailableError("reviewer isolation changed before child spawn", "binary");
@@ -448,9 +474,24 @@ export class ReviewerPrintPeer extends BasePeer {
448
474
  onInputReleased: () => { inputReleased = true; this.opts.inputReleased?.(inputContext, [env]); },
449
475
  onError: () => { if (this.child === child) this.child = undefined; },
450
476
  onSpawn: () => {
477
+ try { selection?.applied(); } catch { /* Native spawn remains authoritative. */ }
451
478
  this.runningBinding={task,binding};
452
479
  this.reviewing = task; this.reviewSeq++;
453
- if (this.childCurrent) policyTimer = setInterval(() => { this.reviewToken(task); }, 100);
480
+ if (launch!.watchCurrent) {
481
+ try {
482
+ const sequence = this.reviewSeq, probe = launch!.startPolicyWatch!();
483
+ const watch = createReviewerPolicyWatch(probe, () => {
484
+ // Batch generation alone is insufficient: later reviews can reuse its task and generation.
485
+ if (this.policyWatch === policyOwner && this.child === child && generation === this.generation
486
+ && this.reviewing === task && this.reviewSeq === sequence) this.abortReview("review policy changed");
487
+ });
488
+ policyOwner = { child, watch, cleanup: release, closed: () => {
489
+ childClosed = true; launchCleanupConfirmed = true; finishInput();
490
+ } };
491
+ this.policyWatch = policyOwner;
492
+ watch.start();
493
+ } catch { this.abortReview("review policy changed"); }
494
+ }
454
495
  },
455
496
  onFrame: event => {
456
497
  try {
@@ -465,6 +506,7 @@ export class ReviewerPrintPeer extends BasePeer {
465
506
  onLimit: () => this.abortReview("review output limit exceeded"),
466
507
  onLeaderExit: () => {
467
508
  if (this.child === child) { this.reviewing = undefined; this.runningBinding=undefined; }
509
+ void this.stopPolicyWatch(policyOwner).catch(() => {});
468
510
  },
469
511
  });
470
512
  // Owned before any await, so a stop that lands before "spawn" still finds and kills it.
@@ -478,16 +520,16 @@ export class ReviewerPrintPeer extends BasePeer {
478
520
  } finally {
479
521
  if (this.activeTrace?.value === trace) this.activeTrace = undefined;
480
522
  closeMcp();
481
- if (policyTimer) clearInterval(policyTimer);
523
+ // Joining the watcher precedes deletion of files it can still read, even when native cleanup failed.
524
+ await this.stopPolicyWatch(policyOwner);
482
525
  try {
483
526
  if (!ownedChild || this.child !== ownedChild) {
484
527
  await release(); if (this.childCleanup === release) this.childCleanup = undefined;
485
528
  launchCleanupConfirmed = true;
529
+ if (this.policyWatch === policyOwner) this.policyWatch = undefined;
486
530
  }
487
531
  } catch { this.opts.log?.(`[${this.id}] reviewer isolation cleanup incomplete`); }
488
- const closedWithoutChild = !ownedChild || ownedChild.process.pid === undefined;
489
- if (mcpCloseConfirmed && launchCleanupConfirmed && (closedWithoutChild || inputReleased && childClosed))
490
- try { this.opts.inputFinished?.(inputContext, [env]); } catch { /* receipt cleanup never changes the review verdict */ }
532
+ finishInput();
491
533
  }
492
534
  }
493
535
 
@@ -498,13 +540,33 @@ export class ReviewerPrintPeer extends BasePeer {
498
540
  }
499
541
 
500
542
  /** Revokes the verdict authority at once, then stops the child; on failure the handle is kept and the error thrown. */
501
- private async kill(): Promise<void> {
543
+ private async stopPolicyWatch(owner: ReviewPolicyOwner | undefined, retry = false): Promise<void> {
544
+ if (!owner) return;
545
+ try { await owner.watch.stop(retry); }
546
+ catch { throw new ReviewerPolicyCleanupError(); }
547
+ // Retain the owner until native teardown and private cleanup also succeed, so a failed stop can be retried.
548
+ }
549
+
550
+ private async kill(retryWorker = false): Promise<void> {
502
551
  this.reviewing = undefined;
503
552
  this.runningBinding=undefined;
504
- const child = this.child;
505
- if (!child) return;
506
- await child.stop();
507
- if (this.child === child) { await this.childCleanup?.(); this.child = undefined; this.childCleanup = undefined; this.childCurrent = undefined; }
553
+ const owner = this.policyWatch, child = this.child ?? owner?.child;
554
+ const cleanup = this.childCleanup ?? owner?.cleanup;
555
+ const workerStopped = this.stopPolicyWatch(owner, retryWorker);
556
+ void workerStopped.catch(() => {}); // Native OAuth grace may outlast a failed join; observe it immediately.
557
+ let childError: unknown, workerError: unknown;
558
+ try { await child?.stop(); } catch (error) { childError = error; }
559
+ try { await workerStopped; } catch (error) { workerError = error; }
560
+ if (workerError) throw workerError;
561
+ if (childError) throw childError;
562
+ if (child) {
563
+ await cleanup?.();
564
+ owner?.closed();
565
+ if (this.child === child) this.child = undefined;
566
+ if (this.childCleanup === cleanup) this.childCleanup = undefined;
567
+ if (this.policyWatch === owner) this.policyWatch = undefined;
568
+ if (!this.child && !this.policyWatch) this.childCurrent = undefined;
569
+ }
508
570
  }
509
571
  }
510
572
 
package/src/cli/agents.ts CHANGED
@@ -6,7 +6,7 @@ import { withoutOrcaEnv } from "../hub/orca-env.ts";
6
6
  /** #691: what `ahub agents` and `ahub doctor` show for each gated native CLI. */
7
7
  export interface AgentVersionRow { id: CompatId; executable?: string; verdict: CompatVerdict; policy: string }
8
8
 
9
- const PROBE_ENV = { JCODE_NO_TELEMETRY: "1", JCODE_DISABLE_CLAUDE_MCP: "1" };
9
+ const PROBE_ENV = { JCODE_NO_TELEMETRY: "1", JCODE_DISABLE_CLAUDE_MCP: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1" };
10
10
 
11
11
  /** The one place that decides what is run for an id: the configured argv (including pi.cmd) plus the probe words. */
12
12
  function probeTarget(id: CompatId, commands: Partial<Record<CompatId, readonly string[]>>): { executable: string; args: string[] } | undefined {
@@ -64,10 +64,12 @@ export async function factsHook(stdin: string, stateDir: string, peer: string, t
64
64
  if (Buffer.byteLength(stdin, "utf8") > 1024 * 1024) return undefined;
65
65
  const port = definitionOf(peer)?.hooks?.factsHook;
66
66
  const payload: unknown = JSON.parse(stdin);
67
- if (!port?.decode(nativeEvent, payload)) return undefined;
67
+ const decoded = port?.decode(nativeEvent, payload);
68
+ if (!port || !decoded) return undefined;
69
+ const forwarded = payload && typeof payload === "object" && !Array.isArray(payload) ? { ...payload, agentHubTranscriptPath: decoded.transcriptPath } : payload;
68
70
  const hub = await ControlClient.connect(stateDir, { role: "tools", peer, ...(nativeHookIdentity(stateDir, peer).nativeLaunchId ? { launchId: nativeHookIdentity(stateDir, peer).nativeLaunchId } : {}) }, timeoutMs);
69
71
  try {
70
- const reply = await hub.request({ t: "native_facts", event: nativeEvent, payload, ...nativeHookIdentity(stateDir, peer) }, timeoutMs);
72
+ const reply = await hub.request({ t: "native_facts", event: nativeEvent, payload: forwarded, ...nativeHookIdentity(stateDir, peer), startedMs: performance.now() }, timeoutMs);
71
73
  const output = reply.ok ? port.encode(nativeEvent, typeof reply.text === "string" ? reply.text : undefined) : undefined;
72
74
  return output ? JSON.stringify(output) : undefined;
73
75
  } finally { hub.close(); }
@@ -0,0 +1,67 @@
1
+ import { executionText } from "../hub/execution-reference.ts";
2
+ import { GUIDANCE_HASH_HEX_LENGTH, GUIDANCE_CURSOR_MAX_BYTES, parseGuidanceWriteReceipt, type GuidanceDiffResult, type GuidancePageResult, type GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
3
+ import { guidanceLines, guidanceReceiptLines } from "../ui/guidance-view.ts";
4
+ import { terminalText } from "./console-state.ts";
5
+
6
+ export const GUIDANCE_USAGE = "usage: ahub guidance create --file FILE [--json] | list --task N --task-created MS [--cursor TOKEN] [--json] | show --task N --task-created MS --id HASH [--json] | withdraw --task N --task-created MS --revision R --id HASH [--json]";
7
+ type Create = { op: "create"; json: boolean; file: string };
8
+ type List = { op: "list"; json: boolean; taskId: number; taskCreated: number; cursor?: string };
9
+ type Show = { op: "show"; json: boolean; taskId: number; taskCreated: number; id: string };
10
+ type Withdraw = { op: "withdraw"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; id: string };
11
+ export type GuidanceCommand = Create | List | Show | Withdraw;
12
+ const invalid = (): never => { throw new Error(`invalid guidance arguments; ${GUIDANCE_USAGE}`); };
13
+ const integer = (raw: string | undefined, minimum: number): number => {
14
+ if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
15
+ const value = Number(raw);
16
+ return Number.isSafeInteger(value) && value >= minimum ? value : invalid();
17
+ };
18
+ const contentId = (raw: string | undefined): string =>
19
+ typeof raw === "string" && raw.length === GUIDANCE_HASH_HEX_LENGTH && /^[a-f0-9]+$/.test(raw) ? raw : invalid();
20
+ /** The explicit filename remains a selector; main owns its bounded read and the complete V1 parse. */
21
+ export function parseGuidanceCommand(args: readonly string[]): GuidanceCommand {
22
+ const [op, ...rest] = args;
23
+ if (op !== "create" && op !== "list" && op !== "show" && op !== "withdraw") return invalid();
24
+ const allowed = op === "create" ? ["--file"] : op === "list" ? ["--task", "--task-created", "--cursor"]
25
+ : op === "show" ? ["--task", "--task-created", "--id"] : ["--task", "--task-created", "--revision", "--id"];
26
+ const values = new Map<string, string>(); let json = false;
27
+ for (let index = 0; index < rest.length; index++) {
28
+ const flag = rest[index]!;
29
+ if (flag === "--json") { if (json) return invalid(); json = true; continue; }
30
+ if (!allowed.includes(flag) || values.has(flag)) return invalid();
31
+ const value = rest[++index];
32
+ if (typeof value !== "string" || value.length === 0 || value.startsWith("--") || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(value)) return invalid();
33
+ values.set(flag, value);
34
+ }
35
+ if (op === "create") {
36
+ const file = values.get("--file");
37
+ if (!file) return invalid();
38
+ return { op, json, file };
39
+ }
40
+ const taskId = integer(values.get("--task"), 1), taskCreated = integer(values.get("--task-created"), 0);
41
+ if (op === "list") {
42
+ if (!values.has("--cursor")) return { op, json, taskId, taskCreated };
43
+ const cursor = values.get("--cursor")!;
44
+ // V1 wire bound: authentication and task/actor binding belong to the source host.
45
+ if (!executionText(cursor, GUIDANCE_CURSOR_MAX_BYTES) || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
46
+ return { op, json, taskId, taskCreated, cursor };
47
+ }
48
+ const id = contentId(values.get("--id"));
49
+ return op === "show" ? { op, json, taskId, taskCreated, id }
50
+ : { op, json, taskId, taskCreated, flowRevision: integer(values.get("--revision"), 0), id };
51
+ }
52
+
53
+ export { parseGuidancePageResult as validateGuidancePageReply, parseGuidanceDiffResult as validateGuidanceDiffReply } from "../hub/guidance-variants.ts";
54
+ /** An unconfirmed write never authorizes an automatic retry or reinterprets a displayed experiment label as a selector. */
55
+ export function validateGuidanceReceipt(value: unknown, expected: { id?: string; taskId?: number; status?: "withdrawn" }): GuidanceWriteReceipt {
56
+ const unconfirmed = (): never => { throw new Error("guidance write reply is unconfirmed; inspect ahub guidance list for the task before retrying the write"); };
57
+ try {
58
+ const receipt = parseGuidanceWriteReceipt(value);
59
+ if (expected.id !== undefined && receipt.id !== expected.id || expected.taskId !== undefined && receipt.taskId !== expected.taskId
60
+ || expected.status !== undefined && receipt.status !== expected.status) return unconfirmed();
61
+ return receipt;
62
+ } catch { return unconfirmed(); }
63
+ }
64
+ /** The shared view contains public data only; terminal controls are stripped at this surface. */
65
+ const terminalLines = (lines: readonly string[]): string[] => lines.map(line => terminalText(line).replace(/[\r\n]+/g, " "));
66
+ export const renderGuidance = (result: GuidancePageResult | GuidanceDiffResult): string[] => terminalLines(guidanceLines(result));
67
+ export const renderGuidanceReceipt = (receipt: GuidanceWriteReceipt): string[] => terminalLines(guidanceReceiptLines(receipt));
package/src/cli/help.ts CHANGED
@@ -12,8 +12,8 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
12
12
  ["ahub --project <path|id> <command>", "select a repository or worktree explicitly"],
13
13
  ["ahub projects [--json] [--full] [--color=auto|always|never]", "list registered projects and live status"],
14
14
  ["ahub projects remove <id>", "forget a stopped registration (keeps project files)"],
15
- ["ahub setup [--yes] [--agents <a,b>]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
16
- ["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--coordination advisory|turn-free] [--memory|--no-memory] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent) and --autonomy off skips the autonomy inheritance, both in config.local.json; --sdlc sets sdlc.toml mode (off writes no file on a new project); --coordination, --memory, --snapshots and --pi set their keys in config.json. On an existing project only a flag you give changes anything, and --dry-run shows each change as old -> new (--dry-run --json adds a settings array); a value equal to the current one is a no-op, an invalid value is refused with the allowed ones and nothing is written. --specs/--no-specs and --spec-review set the design-specs keys (and the AGENTS.md specs block). A person at a terminal who runs ahub init on a new project with no flag that sets anything and no --yes is asked each setting in turn with its default in brackets (Enter keeps it, a wrong answer asks again, and a third wrong answer ends init with nothing written), sees the plan and answers y/N; N, Ctrl-C and Ctrl-D write nothing. A peer, a live test, a pipe and --dry-run are never asked, and --yes takes the defaults. Executables, secrets, models and permissions stay file edits"],
15
+ ["ahub setup [--yes] [--agents <a,b>] [--research|--no-research]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), save the research default only with explicit --research/--no-research (ordinary setup leaves it unchanged), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
16
+ ["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--required-checks <a,b,...>] [--coordination advisory|turn-free] [--memory|--no-memory] [--research|--no-research] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent), --research/--no-research sets research.enabled (new project default: the trusted setup choice, else off) and --autonomy off skips the autonomy inheritance, all in config.local.json; --sdlc sets sdlc.toml mode (off writes no file on a new project); advise/enforce discovers required checks from CI or literal workflow job names; --required-checks overrides discovery, and enforce without names refuses before writes; --coordination, --memory, --snapshots and --pi set their keys in config.json. On an existing project only a flag you give changes anything, and --dry-run shows each change as old -> new (--dry-run --json adds a settings array); a value equal to the current one is a no-op, an invalid value is refused with the allowed ones and nothing is written. --specs/--no-specs and --spec-review set the design-specs keys (and the AGENTS.md specs block). A person at a terminal who runs ahub init on a new project with no flag that sets anything and no --yes is asked each setting in turn with its default in brackets (Enter keeps it, a wrong answer asks again, and a third wrong answer ends init with nothing written), sees the plan and answers y/N; N, Ctrl-C and Ctrl-D write nothing. A peer, a live test, a pipe and --dry-run are never asked, and --yes takes the defaults. Success prints next steps to commit shared init changes, start with ahub up or ahub claude and, for advise/enforce, accept specs/departures and use guarded merge. Executables, secrets, models and permissions stay file edits"],
17
17
  ["ahub --live-test [--project <path|id>] <command> [args...]", "user-authorized operational console delegation; ordinary calls retain peer identity; person-authored content refuses"],
18
18
  ["ahub help [command]", "this help, or one command's entries; also --help and -h"],
19
19
  ["ahub version | --version", "print the installed version"],
@@ -27,6 +27,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
27
27
  ["ahub pet --palette <blue|teal|violet|ochre>", "retired floating-window option: run acon ui and open Mini"],
28
28
  ["ahub sdlc status [task] | explain <task> [--json] [--color=auto|always|never] | export <task> | record <task> <receipt-json>", "read head-bound lifecycle gates and the next actor/action; status and explain are open to any agent as a public view (private tasks stay stubs), export and record are person only; export stays JSON"],
29
29
  ["ahub sdlc queue <owner/repo> | release <owner/repo> [live-issue...] [--json] [--color=auto|always|never]", "read-only merge and release evidence; open to any agent as public readback of the checkout's repositories, never an authorization"],
30
+ ["ahub sdlc adopt-merge <task> --pr <n>", "record an already merged PR at the task's recorded head with green required checks and no open Important finding; approve and release dependents (person or current conductor)"],
30
31
  ["ahub sdlc merge <task> [--dry-run] [--json] [--color=auto|always|never]", "guarded squash merge of an approved task at its approved head after every gate is re-read; follows sdlc.toml auto_merge (off, dry-run, on); --dry-run only reports (person or conductor)"],
31
32
  ["ahub sdlc authorize-release <version> [--json] [--color=auto|always|never]", "approve this daemon checkout commit, version and fresh docs (person or unique configured conductor on the person's explicit release instruction naming the release in its own session; hub/task/review/file/peer relays never qualify; restart revokes)"],
32
33
  ["ahub sdlc release-guard -- <literal git push|gh release create|npm publish argv>", "read-only authorization preflight; init --release-guard installs the tag pre-push hook"],
@@ -79,7 +80,8 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
79
80
  ["ahub roster [--json] [--color=auto|always|never]", "every known peer, participation, start mode and retained work"],
80
81
  ["ahub roster add <peer> | remove <peer> [--yes] [--now]", "person or configured conductor: change live participation through settings; removal previews retained messages and task handoff; remove also deletes the roster key of an instance no longer declared"],
81
82
  ["ahub autonomy on [--all-projects] [--yes] | off [--all-projects] | status [--json]", "person only: apply the autonomy preset and machine default with one confirmation, optionally to every registered project; off removes fixed preset keys (manual edits included); status reports modes, floor enforcement and Claude homes; settings undo restores a live-hub project write"],
82
- ["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies"],
83
+ ["ahub model set <peer> <model> | clear <peer> | list [--json]", "person only: select a runtime model at the next turn, clear its override, or inspect effective models and pending changes; unsupported peers need a restart"],
84
+ ["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies; get sdlc.mode or sdlc.required_checks reads running and file values without adding writable keys"],
83
85
  ["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
84
86
  ["ahub settings edit <config.local.json|sdlc.toml> (set <path> <json> | remove <path>)... [--reason <text>] [--preview] [--yes] | backups [--json]", "human only: structural config (instances, review, snapshots, approvals, context.gate, research.runners, sdlc.toml mode and required_checks) validated by the hub's own loaders, previewed as a diff and written with a backup; a key that runs code or locates secrets needs its name typed, never --yes"],
85
87
  ["ahub pause|resume <peer>", "hold a peer's deliveries in its queue / release them"],
@@ -137,6 +139,12 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
137
139
  ["ahub budget execution configure <config.json> | disable <id> [--json] [--color=auto|always|never]", "opt-in limits on model calls, tool calls, time and tokens for pi and local"],
138
140
  ]],
139
141
  ["History and reports", [
142
+ ["ahub guidance create --file JSON [--json]", "record a bounded immutable advisory proposal through current task authority; no activation or probe"],
143
+ ["ahub guidance list --task N --task-created MS [--cursor TOKEN] [--json]", "bounded guidance metadata pages; withdrawn history and withheld fields remain explicit"],
144
+ ["ahub guidance show --task N --task-created MS --id HASH [--json]", "screened editable-section diff selected by existing variant id, never a displayed experiment label"],
145
+ ["ahub guidance withdraw --task N --task-created MS --revision R --id HASH [--json]", "one-way withdrawal using current task flow; retained history never becomes active guidance"],
146
+ ["ahub lineage show (--task N | --attempt ra-id | --root JSON [--task-scope N --task-created MS]) [--cursor TOKEN] [--nodes N --edges N --bytes N] [--json]", "bounded execution metadata and explicit evidence strengths; unavailable stays unknown, with no probes or replay"],
147
+ ["ahub lineage link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]", "register a declared metadata link through the task's current authority and revision; no producer attestation"],
140
148
  ["ahub turns [peer] [--limit N] [--json] [--color=auto|always|never]", "recent turns and the files each changed (a git work tree only)"],
141
149
  ["ahub undo <turn> [--yes] [--context]", "put back the files a turn changed; refuses files changed since. Without --yes it only lists them; --context also drops a Codex turn from its conversation"],
142
150
  ["ahub report [--since 7d|<iso>] [--by task] [--json] [--color=auto|always|never]", "turns, tokens, messages, overlaps and task events per period"],
@@ -145,9 +153,9 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
145
153
  ["ahub usage limits [--peer <id>] [--limit <n>] [--json] [--color=auto|always|never]", "current quota windows and the history of pauses, resumes and resets"],
146
154
  ["ahub usage total [--json] [--color=auto|always|never]", "lifetime development tokens since the first event, per peer and overall"],
147
155
  ["ahub export [--since 7d|<iso>]", "structured events (events.jsonl) as JSON lines; never message bodies; the configured conductor gets a bounded projection (last 1000 events)"],
148
- ["ahub research [--since 30d] [--all] [--json]", "success, first-pass, rework and check-failure rates, tokens and wall time per approved task, from the opt-in research records"],
156
+ ["ahub research [--since 30d] [--all] [--json]", "success, first-pass, rework and check-failure rates, tokens and wall time per approved task (cancelled tasks have records too and are not counted), from the opt-in research records"],
149
157
  ["ahub research addons [--since 30d] [--all] [--json]", "approved tasks with each add-on (claude-mem, ponytail, ripwire, ...) on against off, with intervals; association, not cause"],
150
- ["ahub research export [--format jsonl|csv] [--since 30d] [--all]", "the research records for outside analysis: ids, counts and tokens, never text"],
158
+ ["ahub research export [--format jsonl|csv | --dataset <dir>] [--since 30d] [--all]", "the research records for outside analysis: ids, counts and tokens, never text; --dataset writes per-project tasks.jsonl, manifest.json and quality.json (family names only, with each field's unknown count, quota gaps and token attribution share) to a directory in your home outside every project"],
151
159
  ["ahub research backfill", "build this project's research records once from events.jsonl (person or configured conductor)"],
152
160
  ["ahub bench run <suite.json> --arm <label> [--repeat N] [--tasks a,b] [--addon <name>=on|off]... [--memory off|claude-mem|native|both]", "run a benchmark suite against the peers attached here, in a project kept for benchmarks (it resets the work tree; person or configured conductor); --addon and --memory declare the arm's add-on and memory state and refuse a setup that differs"],
153
161
  ["ahub bench list|status [--json]", "benchmark runs on this machine / the one running now"],
@@ -15,6 +15,9 @@ export const LIVE_TEST_PERSON_REFUSAL = "live-test cannot write person-attribute
15
15
 
16
16
  /** Person verdicts and user-authored workflow content are never delegated. */
17
17
  export function liveTestRefusal(command: string, args: readonly string[], context: { repairedFresh?: boolean } = {}): boolean {
18
+ if (command === "lineage" && args[0] === "link") return true;
19
+ if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
20
+ if (command === "model") return true; // #1317: even listing runtime overrides is person-only, never live-test delegated.
18
21
  if (command === "sdlc" && (args[0] === "authorize-release" || args[0] === "plan-review" || args[0] === "release-assign" || args[0] === "merge" || args[0] === "train" && args[1] !== "report")) return true;
19
22
  if (args.some(arg => arg === "--as-user" || arg.startsWith("--as-user="))) return true;
20
23
  if (command === "pet" && (args.includes("--window") || args.includes("--palette"))) return false;
@@ -26,7 +29,7 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
26
29
  // #601: a campaign's draft, revise, approve and close are the person's verdicts; only `show` is a read. Without this an agent shell could run them as the person through `--live-test`.
27
30
  || (command === "study" && sub !== "show" && sub !== "experiments")
28
31
  || (command === "recovery" && (sub === "reattach" || sub === "dispose" && context.repairedFresh === true))
29
- || (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure"))
32
+ || (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure" || args[0] === "adopt-merge"))
30
33
  || (command === "bench" && args.find(arg => arg !== "--json") === "run") || command === "pet"
31
34
  // #691: trusting an untested agent CLI version is the person's consent, never a delegated live-test operation.
32
35
  || command === "autonomy" || command === "title"
@@ -143,6 +146,7 @@ const isPeerReadForm = (command: string, args: readonly string[]): boolean => {
143
146
  * The branches above them are the older authority rules and stay unchanged.
144
147
  */
145
148
  export function classifyPeerCommand(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): PeerCommandAccess {
149
+ if (command === "model") return "console";
146
150
  if (command === "recovery" && recoveryAction(args) === "reattach") return "console";
147
151
  const native = catalog?.definitionOf(command) ?? definitionOf(command);
148
152
  if (native?.cli.personOnlyFlags?.some(flag => args.includes(flag))) return "console";
@@ -152,9 +156,12 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
152
156
  if (conductorOperation(command,args)) return "conductor";
153
157
  if (command === "stop") return "console";
154
158
  if (command === "sdlc" && ["release-guard", "release-guard-hook"].includes(args[0] ?? "")) return "allowed";
155
- // #786, #1063: guarded merge and recording explicitly instructed release consent admit the person or unique configured conductor; the daemon checks the role.
156
- if (command === "sdlc" && ["merge", "authorize-release"].includes(args[0] ?? "")) return "conductor";
159
+ // #786, #1063, #1328: guarded merge, merge adoption and explicitly instructed release consent admit the person or unique configured conductor; the daemon checks the role.
160
+ if (command === "sdlc" && ["merge", "authorize-release", "adopt-merge"].includes(args[0] ?? "")) return "conductor";
157
161
  if (command === "role") return ["list", "show"].includes(args[0] ?? "") ? "allowed" : "console";
162
+ // The original tools identity reaches Tasks for read visibility or task-scoped link admission.
163
+ if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? "allowed" : "console";
164
+ if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? "allowed" : "console";
158
165
  if (command === "task") {
159
166
  // #933: cancel, label and role act on the caller's own task only; the daemon refuses another peer's task by role (Tasks.cancel, task_catalog_role, task_label_check).
160
167
  if (["propose", "show", "cancel", "label", "role"].includes(args[0] ?? "")) return "allowed";
@@ -194,6 +201,9 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
194
201
 
195
202
  /** No argument text is included: notices and refusal logs must not copy task text or credentials. */
196
203
  export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
204
+ if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? `lineage ${args[0]}` : "lineage";
205
+ if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? `guidance ${args[0]}` : "guidance";
206
+ if (command === "model") return ["list", "set", "clear"].includes(args[0] ?? "") ? `model ${args[0]}` : "model";
197
207
  if (command === "peer") return args[0] === "takeover" ? "peer takeover" : "peer";
198
208
  if (command === "backlog") return ["list", "add", "pull", "pull-ready", "split", "return", "plan", "pin", "undo"].includes(args[0] ?? "") ? `backlog ${args[0]}` : "backlog";
199
209
  if (command === "board" && args[0] === "import") return "board import";