@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
package/src/cli/main.ts CHANGED
@@ -46,6 +46,7 @@ import { autonomyHomeStatus, usedClaudeHomes } from "./autonomy-homes.ts";
46
46
  import { shellQuote } from "./shell-quote.ts";
47
47
  import { discoverClaudeHomes } from "./claude-homes.ts";
48
48
  import { setupClaudeHomes } from "./setup-homes.ts";
49
+ import { setupResearchDefault } from "./setup-research.ts";
49
50
  import { registerAconPlugin } from "./acon-register.ts";
50
51
  import { petView, readPet, renderPet } from "./pet.ts";
51
52
  import { PET_WINDOW_RETIRED_NOTICE, petPalette } from "../pet/config.ts";
@@ -70,11 +71,14 @@ import { loadConfig } from "../hub/daemon.ts";
70
71
  import { factsHook } from "./facts-hook.ts";
71
72
  import { hubHome, projectContext, projectRoot, realPath } from "../hub/project.ts";
72
73
  import { Registry, type Project } from "../hub/registry.ts";
74
+ import { datasetInputFor, exportResearchDataset, projectFamilyOf } from "../hub/research-dataset.ts";
75
+ import { readEvidence } from "../hub/research-record.ts";
73
76
  import { inspectProject, startProject, stopProject, runProjectDaemon } from "../hub/lifecycle.ts";
74
77
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
75
78
  import { openManager, startManager, stopManager } from "../hub/manager.ts";
76
79
  import { OmniRoute } from "../omniroute/client.ts";
77
- import { autonomyInheritanceChange, init, initSettingRows, planInit } from "./init.ts";
80
+ import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit } from "./init.ts";
81
+ import { discoverInitChecks, withInitChecks } from "./init-required-checks.ts";
78
82
  import { INIT_USAGE, parseInitSettings } from "./init-settings.ts";
79
83
  import { promptGate, runInitPrompt, settingLines, shadowOffered, type InitAnswers } from "./init-prompt.ts";
80
84
  import { loadPacks } from "../hub/packs.ts";
@@ -114,7 +118,7 @@ import { renderTidyPreview, renderTidyResult, renderWorktrees } from "./worktree
114
118
  import { formatMemoryStaleAnchors } from "../hub/memory-stale-anchors.ts";
115
119
  import { AGENT_MEM_VERSION, assertAgentMemVersion, selectedMemoryProfile } from "../hub/memory-profile.ts";
116
120
  import { checkMemoryProfiles, formatMemoryProfileCheck } from "../hub/memory-profile-check.ts";
117
- import { addonReport, appendRecords, formatAddons, formatResearch, LABELS, labelTarget, RESEARCH_SCHEMA, projectKey, readStores, researchReport, taskRecords, toCsv, type Label, type TaskRecord } from "../hub/research.ts";
121
+ import { addonReport, appendRecords, closedAtOf, formatAddons, formatResearch, LABELS, labelTarget, RESEARCH_SCHEMA, projectKey, readStores, researchReport, taskRecords, toCsv, type Label, type TaskRecord } from "../hub/research.ts";
118
122
  import { summarize, summarizeByTask } from "../hub/report.ts";
119
123
  import { readDogfood } from "../hub/dogfood-read.ts";
120
124
  import { dogfoodSince, formatDogfood } from "../hub/dogfood.ts";
@@ -126,7 +130,7 @@ import { agentShellCause, classifyPeerCommand, cliCommandLabel, detectCliIdentit
126
130
  import { recordCliAudit, recordDelegatedCliAudit } from "./identity-audit.ts";
127
131
  import { runConsole } from "./console.ts";
128
132
  import { paint, permissionBoundary, resolveColor, wrap, type Span } from "./console-state.ts";
129
- import { outputWidth, renderRoster, renderStatus, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
133
+ import { outputWidth, renderRuntimeModels, renderRoster, renderStatus, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
130
134
  import { renderHelp, configuredAcpHelp } from "./help.ts";
131
135
  import { renderBacklogResult, renderGroom, renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow, renderTaskCancel, renderTaskShow } from "./task-output.ts";
132
136
  import { renderAuthorization, renderSdlcCosts, renderSdlcExplain, renderSdlcMerge, renderSdlcMetrics, renderSdlcQueue, renderSdlcRelease, renderSdlcStatus } from "./sdlc-output.ts";
@@ -851,11 +855,14 @@ function benchRunArgs(rest: string[]) {
851
855
  }
852
856
  /** Another project is `ahub --project <dir> research`; anything unknown is refused rather than ignored. */
853
857
  function researchArgs(): void {
854
- const sub = args[0], flags = new Set(["--all", "--json", "--since", "--format"]), valued = new Set(["--since", "--format"]);
858
+ const sub = args[0], flags = new Set(["--all", "--json", "--since", "--format", "--dataset"]), valued = new Set(["--since", "--format", "--dataset"]);
855
859
  for (let i = sub === "export" || sub === "backfill" || sub === "addons" ? 1 : 0; i < args.length; i++) {
856
860
  if (!flags.has(args[i]!)) fail(`ahub research: unknown argument ${args[i]} (another project: ahub --project <dir> research)`);
857
861
  if (valued.has(args[i]!)) i++;
858
862
  }
863
+ if (args.includes("--dataset") && (sub !== "export" || args.includes("--format"))) fail("ahub research: --dataset belongs to export and replaces --format (usage: ahub research export --dataset <dir> [--since] [--all])");
864
+ const at = args.indexOf("--dataset");
865
+ if (at >= 0 && (args[at + 1] === undefined || args[at + 1]!.startsWith("--"))) fail("ahub research: --dataset takes a directory");
859
866
  }
860
867
  const SOURCE_USAGE = "usage: ahub source add <path|url> [--json] [--color=auto|always|never] | list [--json] [--color=auto|always|never]";
861
868
  /** #933: a local conductor form's argument check, run before the `admit` handshake so a usage error leaves no admitted row. */
@@ -1060,9 +1067,13 @@ const commands: Record<string, () => Promise<void> | void> = {
1060
1067
  recoveryLauncherCurrent?.();
1061
1068
  assertLifecycleAvailable(cwd);
1062
1069
  const root = join(import.meta.dir, "..", "..");
1063
- const setupFlags = takeFlags(args.filter(arg => arg !== "--yes"), ["--agents"], []);
1064
- if (setupFlags.rest.length) fail("usage: ahub setup [--yes] [--agents <a,b>]");
1070
+ if (args.includes("--research") && args.includes("--no-research")) fail("--research conflicts with --no-research; give one; nothing was written");
1071
+ const research = args.includes("--research") ? true : args.includes("--no-research") ? false : undefined;
1072
+ const setupFlags = takeFlags(args.filter(arg => !["--yes", "--research", "--no-research"].includes(arg)), ["--agents"], []);
1073
+ if (setupFlags.rest.length) fail("usage: ahub setup [--yes] [--agents <a,b>] [--research|--no-research]");
1074
+ if (research !== undefined && (liveTest || delegatedPeer || recoveryLauncherCurrent)) fail("the machine research default requires the person's own ahub setup; nothing was written");
1065
1075
  const registry = new Registry(), rl = process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
1076
+ let machineRoots = [cwd];
1066
1077
  let homesFailed = false, homesFailure: unknown;
1067
1078
  try {
1068
1079
  const found = recoveryLauncherCurrent || delegatedPeer ? await discoverClaudeHomes({ home: homedir(), env: process.env }) : await usedClaudeHomes(registry, homedir(), process.env);
@@ -1083,8 +1094,11 @@ const commands: Record<string, () => Promise<void> | void> = {
1083
1094
  ...(rl ? { ask: async (prompt: string) => { try { return await rl.question(prompt); } catch { return null; } } } : {}), print: line => console.log(terminalText(line)) });
1084
1095
  if (refused) fail(refused);
1085
1096
  }
1097
+ if (research !== undefined) machineRoots = [...registry.list().map(row => row.root), cwd];
1086
1098
  } finally { registry.close(); rl?.close(); }
1087
1099
  if (homesFailed) fail(startupDiagnostic(homesFailure));
1100
+ try { if (research !== undefined) assertLifecycleAvailable(cwd); const line = setupResearchDefault(hubHome(), machineRoots, research); if (line) console.log(terminalText(line)); }
1101
+ catch (error) { return fail((error as Error).message); }
1088
1102
  // #935: register the acon console plugin (acon reads it at its next start; no acon install is needed for this).
1089
1103
  const acon = registerAconPlugin(hubHome(), join(root, "src", "ui", "plugin.ts"));
1090
1104
  console.log("error" in acon ? `acon plugin not registered: ${acon.error}` : acon.changed ? `acon plugin registered: ${acon.path}` : `acon plugin up to date: ${acon.path}`);
@@ -1101,6 +1115,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1101
1115
  // A pack is a project file in .agenthub/roles/<name>.pack.json (#513a); init resolves the name and refuses an unknown one with the profiles and packs it knows.
1102
1116
  let requestedProfile = flags.one["--profile"];
1103
1117
  const newProject = !existsSync(join(cwd, ".agenthub/config.json"));
1118
+ const initMachine = newProject ? readAutonomyDefaults(hubHome(), [cwd]) : undefined;
1104
1119
  let request = settings.request, asked = Object.keys(request.values).length > 0;
1105
1120
  let shadow = args.includes("--shadow"), releaseGuard = args.includes("--release-guard");
1106
1121
  // #1065 T2: a person at a terminal on a new project, with no flag that sets anything and no --yes, is asked each setting (init-prompt.ts). Every other run, including a delegated peer, a live test and any run
@@ -1113,8 +1128,9 @@ const commands: Record<string, () => Promise<void> | void> = {
1113
1128
  const ask = (question: string): Promise<string | null> => Promise.race([rl.question(question).catch(() => null), interrupted]);
1114
1129
  const machine = readAutonomyDefaults(hubHome(), [cwd]);
1115
1130
  const preview = (answers: InitAnswers): string[] => {
1116
- const rows = initSettingRows(cwd, answers.profile, answers.shadow, answers.releaseGuard, answers.request);
1117
- const plan = planInit(cwd, answers.profile, answers.shadow, answers.releaseGuard, answers.request);
1131
+ const planned = withInitResearch(cwd, answers.request, initMachine?.researchEnabled);
1132
+ const rows = initSettingRows(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
1133
+ const plan = planInit(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
1118
1134
  // The same autonomy-inheritance row `--dry-run` shows, from the one helper: a new project inherits the trusted machine preset after the writes unless the answer was off.
1119
1135
  const inherit = autonomyInheritanceChange(cwd, machine.enabled, answers.request.autonomy);
1120
1136
  if (inherit) plan.push(inherit);
@@ -1123,11 +1139,13 @@ const commands: Record<string, () => Promise<void> | void> = {
1123
1139
  let result: Awaited<ReturnType<typeof runInitPrompt>>;
1124
1140
  try {
1125
1141
  result = await runInitPrompt({ ask, print: line => console.log(terminalText(line)) },
1126
- { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), packs: [...loadPacks(cwd).packs.keys()], shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
1142
+ { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), machineResearch: initResearchDefault(cwd, initMachine?.researchEnabled), packs: [...loadPacks(cwd).packs.keys()], discoverChecks: async () => (await discoverInitChecks(cwd)).names, shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
1127
1143
  } finally { rl.close(); }
1128
1144
  if (!result.ok) { console.error(`ahub init: ${result.reason === "refused" ? result.message : result.reason === "interrupted" ? `interrupted; ${result.message}` : result.message}`); process.exitCode = result.reason === "refused" ? 1 : 0; return; }
1129
1145
  requestedProfile = result.answers.profile; request = result.answers.request; asked = Object.keys(request.values).length > 0; shadow = result.answers.shadow; releaseGuard = result.answers.releaseGuard;
1130
1146
  }
1147
+ request = withInitResearch(cwd, request, initMachine?.researchEnabled);
1148
+ try { request = await withInitChecks(cwd, request); } catch (error) { return fail((error as Error).message); }
1131
1149
  // `--autonomy off` skips the machine inheritance on a new project; `inherit` is today's behaviour. Neither changes an existing project.
1132
1150
  const inheritAutonomy = newProject && request.autonomy !== "off";
1133
1151
  if (!newProject && request.autonomy !== undefined) console.error("note: --autonomy applies to a new project only; this project already exists, so its autonomy settings are unchanged");
@@ -1145,8 +1163,8 @@ const commands: Record<string, () => Promise<void> | void> = {
1145
1163
  }
1146
1164
  assertLifecycleAvailable(cwd);
1147
1165
  if (inheritAutonomy && delegatedPeer && readAutonomyDefaults(hubHome(), [cwd]).enabled) fail("machine autonomy inheritance is person-only; delegated live tests cannot apply it (ahub init --autonomy off skips it)");
1148
- let changed: string[];
1149
- try { changed = init(cwd, requestedProfile, shadow, releaseGuard, request); } catch (error) { return fail((error as Error).message); }
1166
+ let changed: string[], nextSteps: string[];
1167
+ try { nextSteps = initNextSteps(cwd, request); changed = init(cwd, requestedProfile, shadow, releaseGuard, request); } catch (error) { return fail((error as Error).message); }
1150
1168
  const project = registeredProject();
1151
1169
  console.log(changed.length ? changed.map((p) => `${existsSync(p) ? "wrote" : "removed"} ${p}`).join("\n") : "already up to date");
1152
1170
  if (newProject) {
@@ -1160,6 +1178,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1160
1178
  }
1161
1179
  const config = projectConfig(), examples = resolveProfile(config.profile, config.profile_overrides).example_checks;
1162
1180
  if (examples.length) console.log(terminalText("Example checks (advisory):\n" + examples.map(example => "- " + example).join("\n")));
1181
+ console.log(nextSteps.join("\n"));
1163
1182
  },
1164
1183
 
1165
1184
  // Internal: the detached daemon process started by ahub up or the manager.
@@ -1179,7 +1198,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1179
1198
  up: async () => {
1180
1199
  const unattended = unattendedEnv || args.includes("--unattended");
1181
1200
  if (unattended) console.error(UNATTENDED_WARNING);
1182
- const status = await startProject(registeredProject(), { unattended, liveTest, ...(recoveryLauncherCurrent ? { current: recoveryLauncherCurrent, env: { ...personEnv(process.env), AGENTHUB_RECOVERY_OPERATION: continuationId, AGENTHUB_PEER_ID: continuationPeer, AGENTHUB_RECOVERY_CONDUCTOR: continuationPeer, AGENTHUB_RECOVERY_CONTINUATION: continuationId } } : {}) });
1201
+ const status = await startProject(registeredProject(), { unattended, liveTest, starting: pid => console.error(`ahub: hub is still starting, pid ${pid}; waiting for readiness, run ahub status in another terminal to inspect progress`), ...(recoveryLauncherCurrent ? { current: recoveryLauncherCurrent, env: { ...personEnv(process.env), AGENTHUB_RECOVERY_OPERATION: continuationId, AGENTHUB_PEER_ID: continuationPeer, AGENTHUB_RECOVERY_CONDUCTOR: continuationPeer, AGENTHUB_RECOVERY_CONTINUATION: continuationId } } : {}) });
1183
1202
  console.log(`ahub up (ws://127.0.0.1:${status.controlPort}), state in ${stateDir}`);
1184
1203
  if (recoveryLauncherCurrent) { recoveryLauncherCurrent(); return; }
1185
1204
  // #608: the default agent set, only for a person's own `ahub up` (never an agent's, a live test's, or an upgrade or recovery relaunch, which set AGENTHUB_RECOVERY_OPERATION).
@@ -1220,6 +1239,91 @@ const commands: Record<string, () => Promise<void> | void> = {
1220
1239
  return entry.execute(context);
1221
1240
  }])),
1222
1241
 
1242
+ guidance: async () => {
1243
+ const { parseGuidanceCommand, validateGuidancePageReply, validateGuidanceDiffReply, validateGuidanceReceipt, renderGuidance, renderGuidanceReceipt } = await import("./guidance.ts");
1244
+ const { parseGuidanceVariantV1, GUIDANCE_RECORD_MAX_BYTES } = await import("../hub/guidance-variants.ts");
1245
+ let command; try { command = parseGuidanceCommand(args); } catch (error) { return fail((error as Error).message); }
1246
+ if (liveTest && (command.op === "create" || command.op === "withdraw")) return fail("live-test cannot write guidance declarations as the person; use the current task actor without --live-test");
1247
+ let variant: ReturnType<typeof parseGuidanceVariantV1> | undefined;
1248
+ if (command.op === "create") {
1249
+ try {
1250
+ const fd = openSync(resolve(invokedFrom, command.file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1251
+ try {
1252
+ if (!fstatSync(fd).isFile()) return fail("the guidance file must be a bounded regular JSON file");
1253
+ const bytes = Buffer.alloc(GUIDANCE_RECORD_MAX_BYTES + 1); let got = 0;
1254
+ while (got < bytes.length) { const read = readSync(fd, bytes, got, bytes.length - got, null); if (!read) break; got += read; }
1255
+ if (got > GUIDANCE_RECORD_MAX_BYTES) return fail("the guidance file exceeds the 32 KiB input bound");
1256
+ variant = parseGuidanceVariantV1(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, got))));
1257
+ } finally { closeSync(fd); }
1258
+ } catch { return fail("cannot read a valid bounded GuidanceVariantV1 file; check its shape, content id and protected role bytes"); }
1259
+ }
1260
+ const hub = await connect();
1261
+ try {
1262
+ if (!hub.features.includes("guidance_views")) return fail("running hub lacks guidance_views; upgrade and restart the hub and refresh the client plugin, then retry ahub guidance");
1263
+ const { op, json, ...fields } = command;
1264
+ const message = op === "create" ? { variant } : fields;
1265
+ const result = await hub.request({ t: `guidance_${op}`, ...message });
1266
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "guidance request is unconfirmed").replace(/[\r\n]+/g, " ").slice(0, 512)}; inspect ahub guidance list for the task before explicitly retrying a write`, result.refusalAudited === true, result.authorityRefused);
1267
+ const options = { json };
1268
+ if (command.op === "create" || command.op === "withdraw") {
1269
+ let receipt;
1270
+ try { receipt = validateGuidanceReceipt(result.receipt, command.op === "create" ? { id: variant!.id, taskId: variant!.taskId } : { id: command.id, taskId: command.taskId, status: "withdrawn" }); }
1271
+ catch (error) { return fail((error as Error).message); }
1272
+ if (options.json) console.log(JSON.stringify(receipt, null, 2)); else console.log(renderGuidanceReceipt(receipt).join("\n"));
1273
+ } else {
1274
+ let page;
1275
+ try { page = command.op === "list" ? validateGuidancePageReply(result.guidance, command) : validateGuidanceDiffReply(result.guidance, command); }
1276
+ catch { return fail("guidance reply is unavailable or malformed; refresh the task scope and upgrade the hub/client before retrying"); }
1277
+ if (options.json) console.log(JSON.stringify(page, null, 2)); else console.log(renderGuidance(page).join("\n"));
1278
+ }
1279
+ } finally { hub.close(); }
1280
+ },
1281
+
1282
+ lineage: async () => {
1283
+ const { parseLineageCommand, renderExecutionLineage, validateLineageReply, validateLineageLink } = await import("./lineage.ts");
1284
+ let command;
1285
+ try { command = parseLineageCommand(args); } catch (error) { return fail((error as Error).message); }
1286
+ if (liveTest && command.op === "link") return fail("live-test cannot register execution links; retry without --live-test as the task's authorized actor");
1287
+ const hub = await connect();
1288
+ try {
1289
+ if (!hub.features.includes("execution_lineage")) return fail("running hub lacks execution_lineage support; upgrade and restart the hub, then retry ahub lineage");
1290
+ const { op, json, ...message } = command;
1291
+ const result = await hub.request({ t: op === "show" ? "lineage_show" : "lineage_link", ...message });
1292
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "lineage request refused").replace(/[\r\n]+/g, " ").slice(0, 512)}; check task scope, current flow revision and source access before retrying ahub lineage`, result.refusalAudited === true, result.authorityRefused);
1293
+ const options = { json };
1294
+ if (op === "show") {
1295
+ let lineage;
1296
+ try { lineage = validateLineageReply(result.lineage); } catch (error) { return fail((error as Error).message); }
1297
+ if (options.json) console.log(JSON.stringify(lineage, null, 2));
1298
+ else console.log(renderExecutionLineage(lineage).join("\n"));
1299
+ } else {
1300
+ let link;
1301
+ try { link = validateLineageLink(result.link, command); } catch (error) { return fail((error as Error).message); }
1302
+ if (options.json) console.log(JSON.stringify(link, null, 2));
1303
+ else console.log(`Declared execution metadata link ${link.already ? "already registered" : "registered"} for task #${link.taskId}; this does not attest to producer execution.`);
1304
+ }
1305
+ } finally { hub.close(); }
1306
+ },
1307
+ model: async () => {
1308
+ const { parseModelCommand, projectModelStatus } = await import("./model.ts");
1309
+ let command;
1310
+ try { command = parseModelCommand(args); } catch (error) { return fail((error as Error).message); }
1311
+ const hub = await connect();
1312
+ try {
1313
+ if (!hub.features.includes("model_overrides")) return fail("running hub lacks model_overrides support; upgrade and restart the hub, then retry ahub model list");
1314
+ const { json, ...message } = command;
1315
+ const result = await hub.request({ t: "model", ...message });
1316
+ if (result.ok !== true) return fail(String(result.error ?? "model request refused; upgrade and restart the hub before retrying"), result.refusalAudited === true, result.authorityRefused);
1317
+ if (command.op !== "list" && result.appliesFrom !== "next_turn") return fail("model change is unconfirmed; inspect ahub model list before retrying");
1318
+ const values = command.op === "list" ? result.models : [result.model];
1319
+ if (!Array.isArray(values) || values.length > 512) return fail("model reply is not a supported bounded row list; upgrade and restart the hub, then retry ahub model list");
1320
+ const models = values.map(projectModelStatus);
1321
+ if (models.some(row => row === null)) return fail("model reply invalid; upgrade and restart the hub, then retry ahub model list");
1322
+ const options = { json };
1323
+ if (options.json) console.log(JSON.stringify({ models }, null, 2));
1324
+ else printOutput(renderRuntimeModels(models.filter((row): row is NonNullable<typeof row> => row !== null)), false);
1325
+ } finally { hub.close(); }
1326
+ },
1223
1327
  models: async () => {
1224
1328
  const action = outputArguments()[0] ?? "status";
1225
1329
  const options = ["status", "start", "setup"].includes(action) ? outputOptions() : undefined;
@@ -1837,6 +1941,21 @@ const commands: Record<string, () => Promise<void> | void> = {
1837
1941
  } finally { hub.close(); }
1838
1942
  return;
1839
1943
  }
1944
+ if (sub === "adopt-merge") {
1945
+ const flags = takeFlags(args.slice(2), ["--pr"], []), pr = Number(flags.one["--pr"]);
1946
+ if (flags.rest.length || !Number.isSafeInteger(id) || id! <= 0 || !Number.isSafeInteger(pr) || pr <= 0) fail("usage: ahub sdlc adopt-merge <task> --pr <n>");
1947
+ const hub = await connect();
1948
+ try {
1949
+ const reply = await hub.request({ t: "sdlc", op: "adopt-merge", id, pr }, 60_000);
1950
+ if (!reply.ok) {
1951
+ const reason = typeof reply.error === "string" ? reply.error : "merge adoption failed without a reason; inspect the hub log and retry ahub sdlc adopt-merge";
1952
+ if (/unknown SDLC operation|does not know|SDLC readback is console only/.test(reason)) fail(`${reason}; the running hub does not support adopt-merge; upgrade agent-hub and run ahub restart before retrying ahub sdlc adopt-merge`);
1953
+ fail(reason);
1954
+ }
1955
+ console.log(`task #${id}: merged outside the hub; approved`);
1956
+ } finally { hub.close(); }
1957
+ return;
1958
+ }
1840
1959
  if (sub === "merge") {
1841
1960
  // #786 T1: the guarded merge of one approved task; a person or the configured conductor asks, the daemon re-reads every gate.
1842
1961
  // #899: the decision prints for a person; `--json` is the same view as a document. The presentation flags are read before the
@@ -2213,7 +2332,8 @@ const commands: Record<string, () => Promise<void> | void> = {
2213
2332
  if (!Object.hasOwn(allowed, sub) || flags.some((flag) => !allowed[sub]!.includes(flag)) || extra.length) fail(usage);
2214
2333
  if ((sub === "get" && (!key || text !== undefined)) || (sub === "set" && (!key || text === undefined)) || ((sub === "list" || sub === "undo" || sub === "reload") && key !== undefined)) fail(usage);
2215
2334
  const { scope: settingScope, error: settingScopeError } = localDeclarations();
2216
- const def = key === undefined ? undefined : settingDef(key, settingScope.instances, settingScope.catalog);
2335
+ const sdlcRead = sub === "get" && ["sdlc.mode", "sdlc.required_checks"].includes(key ?? "");
2336
+ const def = key === undefined || sdlcRead ? undefined : settingDef(key, settingScope.instances, settingScope.catalog);
2217
2337
  if (typeof def === "string") fail(settingScopeError && def.startsWith("unknown setting") ? `${key}: ${def}; the project config could not be read: ${settingScopeError}` : `${key}: ${def}`);
2218
2338
  if (flags.includes("--now") && (typeof def !== "object" || def.group !== "Roster")) fail(usage);
2219
2339
  const value = sub === "set" ? parseSettingText(def!, text!) : undefined;
@@ -2232,6 +2352,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2232
2352
  }
2233
2353
  return reply;
2234
2354
  };
2355
+ if (sdlcRead) {
2356
+ const view = await request({ t: "settings_get" }), entry = view.sdlc?.[key!];
2357
+ if (!entry || !Object.hasOwn(entry, "value") || !Object.hasOwn(entry, "fileValue")) fail("running hub lacks SDLC settings reads; upgrade and restart it first");
2358
+ if (flags.includes("--json")) return console.log(JSON.stringify({ key, ...entry }, null, 2));
2359
+ return console.log(terminalText(`${key}: running ${JSON.stringify(entry.value)}; file ${JSON.stringify(entry.fileValue)}${entry.problem ? "; file unavailable" : ""}`));
2360
+ }
2235
2361
  if (sub === "reload") {
2236
2362
  let result = await request({ t: "settings_reload" });
2237
2363
  const confirmation = result.confirmation;
@@ -2526,17 +2652,31 @@ const commands: Record<string, () => Promise<void> | void> = {
2526
2652
  const [sub] = args;
2527
2653
  researchArgs();
2528
2654
  if (sub === "backfill") {
2529
- const project = researchProject();
2530
- const written = appendRecords(project.id, taskRecords(readEvents(join(stateDir, "events.jsonl")), project.id, { version: VERSION, source: "backfill" }));
2655
+ const project = researchProject(), familyOf = projectFamilyOf(cwd);
2656
+ const written = appendRecords(project.id, taskRecords(readEvents(join(stateDir, "events.jsonl")), project.id, { version: VERSION, source: "backfill" }, { ...readEvidence(stateDir, project.id), ...(familyOf ? { familyOf } : {}) }));
2531
2657
  return console.log(`${written} research record${written === 1 ? "" : "s"} written from this project's events`);
2532
2658
  }
2533
2659
  const all = args.includes("--all");
2534
- const records = readStores(all ? undefined : researchProject(false).id);
2535
2660
  const from = since();
2661
+ if (sub === "export" && args.includes("--dataset")) {
2662
+ // #1277: the dataset is read-only over the stores; a project that was never researched has no file and no directory. The target is refused inside any registered project.
2663
+ const registry = new Registry();
2664
+ let registered: Project[];
2665
+ try { registered = registry.list(); } finally { registry.close(); }
2666
+ const here = researchProject(false), chosen = all ? registered : [here];
2667
+ const inputs = chosen.flatMap(p => { const input = datasetInputFor(p); return input ? [input] : []; });
2668
+ if (!inputs.length) return fail(all ? "no registered project has research records" : "this project has no research records; turn research on and run ahub research backfill");
2669
+ try {
2670
+ const written = exportResearchDataset(args[args.indexOf("--dataset") + 1]!, inputs, { ...(from > 0 ? { since: from } : {}) }, [...registered, here]);
2671
+ for (const w of written) console.log(`${w.projectKeyHash}: ${w.counts.tasks} task${w.counts.tasks === 1 ? "" : "s"} (${w.counts.approved} approved, ${w.counts.cancelled} cancelled), ${w.counts.labels} label${w.counts.labels === 1 ? "" : "s"} -> ${w.dir}`);
2672
+ } catch (error) { return fail((error as Error).message); }
2673
+ return;
2674
+ }
2675
+ const records = readStores(all ? undefined : researchProject(false).id);
2536
2676
  if (sub === "export") {
2537
2677
  const format = args[args.indexOf("--format") + 1] ?? "jsonl";
2538
2678
  if (args.includes("--format") && !["jsonl", "csv"].includes(format)) fail("--format takes jsonl or csv");
2539
- const kept = records.filter((r) => r.kind === "label" || Date.parse(r.approvedAt) >= from);
2679
+ const kept = records.filter((r) => r.kind === "label" || Date.parse(closedAtOf(r) ?? "") >= from);
2540
2680
  return void process.stdout.write(args.includes("--format") && format === "csv" ? toCsv(kept) : kept.map((r) => JSON.stringify(r)).join("\n") + (kept.length ? "\n" : ""));
2541
2681
  }
2542
2682
  if (sub === "addons") {
@@ -2544,7 +2684,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2544
2684
  const rows = addonReport(records, from);
2545
2685
  return console.log(args.includes("--json") ? JSON.stringify(rows, null, 2) : formatAddons(rows).join("\n"));
2546
2686
  }
2547
- if (sub !== undefined && !sub.startsWith("--")) fail("usage: ahub research [--since 30d] [--all] [--json] | addons [--since] [--all] [--json] | export [--format jsonl|csv] [--since] [--all] | backfill");
2687
+ if (sub !== undefined && !sub.startsWith("--")) fail("usage: ahub research [--since 30d] [--all] [--json] | addons [--since] [--all] [--json] | export [--format jsonl|csv | --dataset <dir>] [--since] [--all] | backfill");
2548
2688
  const r = researchReport(records, from);
2549
2689
  console.log(args.includes("--json") ? JSON.stringify(r, null, 2) : formatResearch(r).join("\n"));
2550
2690
  },
@@ -3107,7 +3247,7 @@ async function runConductorCommand(): Promise<void> {
3107
3247
  }
3108
3248
  let op: string;
3109
3249
  let input: Record<string, unknown>;
3110
- if (cmd === "sdlc") return commands.sdlc!(); // #786: `sdlc merge` is the one conductor-class sdlc subcommand; the daemon checks the role.
3250
+ if (cmd === "sdlc") return commands.sdlc!(); // SDLC operational subcommands are role-checked by the daemon.
3111
3251
  if (cmd === "task") {
3112
3252
  op = args[0] === "assign" ? "hub_task_assign" : "hub_task_escalate";
3113
3253
  const { one, rest: positional } = takeFlags(args.slice(1), args[0] === "assign" ? ["--role"] : [], []);
@@ -0,0 +1,52 @@
1
+ import { isNativeModelToken } from "../adapters/model-token.ts";
2
+ import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
3
+
4
+ export const MODEL_USAGE = "usage: ahub model set <peer> <model> | clear <peer> | list [--json]";
5
+ const peerToken = (value: unknown): value is string => typeof value === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(value);
6
+ export function parseModelCommand(args: readonly string[]): { op: "list" | "set" | "clear"; peer?: string; model?: string; json: boolean } {
7
+ const [op, peer, model, ...extra] = args;
8
+ if (op === "list" && (args.length === 1 || args.length === 2 && peer === "--json")) return { op, json: peer === "--json" };
9
+ if (op === "clear" && args.length === 2 && peerToken(peer)) return { op, peer, json: false };
10
+ if (op === "set" && !extra.length && args.length === 3 && peerToken(peer) && isNativeModelToken(model)) return { op, peer, model, json: false };
11
+ throw new Error(MODEL_USAGE);
12
+ }
13
+
14
+ /** Closed metadata projection: an older or malformed reply never supplies display prose. */
15
+ export function projectModelStatus(value: unknown): RuntimeModelStatus | null {
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
17
+ const row: Record<string, unknown> = {};
18
+ try {
19
+ for (const key of ["peer", "effectiveModel", "desiredModel", "source", "pendingNextTurn", "unsupported"]) {
20
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
21
+ if (descriptor && "value" in descriptor) row[key] = descriptor.value;
22
+ }
23
+ } catch { return null; }
24
+ if (!peerToken(row.peer) || !(row.effectiveModel === null || isNativeModelToken(row.effectiveModel)) || !(row.desiredModel === null || isNativeModelToken(row.desiredModel)) || !(typeof row.source === "string" && ["override", "instance", "launch", "native default", "native thread default (was override)"].includes(row.source)) || typeof row.pendingNextTurn !== "boolean") return null;
25
+ let unsupported: RuntimeModelStatus["unsupported"];
26
+ if (row.unsupported !== undefined) {
27
+ if (!row.unsupported || typeof row.unsupported !== "object" || Array.isArray(row.unsupported)) return null;
28
+ let reasonCode: unknown, kind: unknown;
29
+ try {
30
+ const code = Object.getOwnPropertyDescriptor(row.unsupported, "reasonCode"), adapter = Object.getOwnPropertyDescriptor(row.unsupported, "kind");
31
+ reasonCode = code && "value" in code ? code.value : undefined;
32
+ kind = adapter && "value" in adapter ? adapter.value : undefined;
33
+ } catch { return null; }
34
+ if (kind !== undefined && !peerToken(kind)) return null;
35
+ if (reasonCode === "unverified_setter") unsupported = { reasonCode, ...(kind ? { kind } : {}), reason: `unsupported live: ${kind ?? "retained peer"} (version unverified) has no verified model setter`, nextStep: `restart this peer with ahub restart ${row.peer}` };
36
+ else if (reasonCode === "unmanaged_attachment") unsupported = { reasonCode, reason: "unsupported live: this attachment has no verified live model setter", nextStep: `change the native setting or restart this peer with ahub restart ${row.peer}` };
37
+ else if (reasonCode === "acp_setter_unavailable") {
38
+ if (!peerToken(kind)) return null;
39
+ let version: unknown;
40
+ try {
41
+ const descriptor = Object.getOwnPropertyDescriptor(row.unsupported, "version");
42
+ if (descriptor && !("value" in descriptor)) return null;
43
+ version = descriptor?.value;
44
+ } catch { return null; }
45
+ if (version !== undefined && !(isNativeModelToken(version) && /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(version))) return null;
46
+ unsupported = { reasonCode, kind, ...(typeof version === "string" ? { version } : {}), reason: `unsupported live: ${kind} ${version ?? "unknown"} lacks a setter receipt or compat admission`, nextStep: `restart this peer with ahub restart ${row.peer}` };
47
+ }
48
+ else return null;
49
+ }
50
+ return { peer: row.peer, effectiveModel: row.effectiveModel, desiredModel: row.desiredModel, source: row.source as RuntimeModelStatus["source"], pendingNextTurn: row.pendingNextTurn,
51
+ ...(unsupported ? { unsupported } : {}) };
52
+ }
package/src/cli/output.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { projectModelStatus } from "./model.ts";
2
+ import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
1
3
  import type { QueueBackpressureStatus } from "../hub/queue-backpressure.ts";
2
4
  import { definitionOf } from "../adapters/registry.ts";
3
5
  import { windowKind } from "../hub/window-kind.ts";
@@ -14,6 +16,8 @@ import type { SpecsStatus } from "../hub/specs-task.ts";
14
16
 
15
17
  export interface DoctorCheck { section: "Tools" | "Hub" | "Config" | "Models" | "Memory"; level: "ok" | "warn" | "fail" | "unknown"; name: string; detail: string }
16
18
  export interface StatusOutput {
19
+ runtimeModels?: RuntimeModelStatus[];
20
+ runtimeModelsUnavailable?: boolean;
17
21
  roomsUnavailable?: unknown;
18
22
  roomsOpening?: boolean;
19
23
  controlWriteTiming?: { active: number; slowRequests: number; blockedLoopSamples: number; droppedActive: number; droppedRecent: number; droppedLogs: number; droppedSpans?: number; droppedMetadata?: number; expiredRequests?: number };
@@ -33,7 +37,7 @@ export interface StatusOutput {
33
37
  pendingTaskOffers?: readonly { task: number; peer: string }[];
34
38
  isolatedChecks?: { pending?: number; orphans?: string[]; unknownReceipts?: readonly string[]; maintenanceUnavailable?: boolean };
35
39
  memoryRead?: { truncated: boolean; scanned: number; limit: number };
36
- memoryProfile?: { profile?: string; generation?: string; state?: string; agentMemVersion?: string; skippedRows?: number; error?: string; sync?: { state: "disabled" | "unavailable" | "notrun" | "not-configured" | "stopped" | "ok" | "failed" | "unknown"; at?: number; cause?: string; declinedCount?: number; declinedIdsKnown?: false; withheldCount?: number; exportedCount?: number; placementActive?: false; nextStep?: string } };
40
+ memoryProfile?: { profile?: string; generation?: string; state?: string; agentMemVersion?: string; skippedRows?: number; error?: string; sync?: { state: "disabled" | "unavailable" | "notrun" | "not-configured" | "stopped" | "ok" | "failed" | "unknown"; at?: number; cause?: string; declinedCount?: number; declinedIdsKnown?: false; withheldCount?: number; exportedCount?: number; placementActive?: false; writerCategory?: string; writerCauseClass?: string; nextStep?: string } };
37
41
  /** #784 AC3: `active`, `reviewWait` and `reserved` add up to `wip`; absent from an older hub. */
38
42
  taskWip?: Record<string, { wip: number; wipLimit: number; active?: number; reviewWait?: number; reserved?: number }>;
39
43
  pid?: number; controlPort?: number; cwd?: string; version?: string; peers: Record<string, any>; roleInfo?: Record<string, any>; actionPolicyInfo?: Record<string, { note: string; enforceable: boolean }>; budget?: Record<string, any>; planner?: { peers?: string[]; source?: string };
@@ -43,6 +47,14 @@ export interface StatusOutput {
43
47
  /** `peers`: one note per peer that shows no number, and why (no quota, nothing read yet); absent from an older hub. */
44
48
  export interface BudgetOutput { budget: Record<string, any>; gate?: number; peers?: { peer: string; kind?: string; note: string }[] }
45
49
  export interface RosterRow { peer: string; on: boolean; startMode: string; state: string; queued: number; tasks: number }
50
+ export function renderRuntimeModels(models: readonly RuntimeModelStatus[], columns?: number): Span[][] {
51
+ const out = rows(["PEER", "EFFECTIVE MODEL", "SOURCE", "STATE"], models.map(row => [span(row.peer, "info", true), span(row.effectiveModel ?? "not reported"), span(row.source), span(row.pendingNextTurn ? "pending next turn" : "current")]), columns);
52
+ for (const row of models) {
53
+ if (row.pendingNextTurn) out.push(...lines(`${row.peer}: next turn ${row.desiredModel ?? "native default"}; the active turn is unchanged.`, columns, "attention"));
54
+ if (row.unsupported) out.push(...lines(`${row.peer}: ${row.unsupported.reason}; ${row.unsupported.nextStep}`, columns, "attention"));
55
+ }
56
+ return out;
57
+ }
46
58
  export function renderRoster(data: RosterRow[], columns?: number): Span[][] {
47
59
  return rows(["PEER", "ROSTER", "START", "STATE", "Q", "TASKS"], data.map(row => [span(row.peer, "info", true), span(row.on ? "on" : "off", row.on ? "success" : "muted", true), span(row.startMode, undefined, true), span(row.state, stateTone(row.state), true), span(row.queued, undefined, true), span(row.tasks, undefined, true)]), columns);
48
60
  }
@@ -218,6 +230,8 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
218
230
  if (data.roleInfo) data = { ...data, peers: Object.fromEntries(Object.entries(data.peers).map(([peer, value]) => [peer, { ...value, ...data.roleInfo?.[peer] }])) };
219
231
  const out = lines(`agent-hub${data.version ? ` ${data.version}` : ""} pid ${data.pid ?? "unknown"} control 127.0.0.1:${data.controlPort ?? "unknown"}`, columns, "info");
220
232
  if (data.cwd) out.push(...lines(data.cwd, columns));
233
+ if (data.runtimeModelsUnavailable === true) out.push(...lines("Runtime models unavailable: could not read a bounded model catalog; run ahub model list for the cause. For a known peer, use ahub model set <peer> <model> or ahub model clear <peer>; repair storage or reduce the retained peer catalog as indicated before listing again.", columns, "attention"));
234
+ else if (Array.isArray(data.runtimeModels)) out.push(...renderRuntimeModels(data.runtimeModels.map(projectModelStatus).filter((row): row is RuntimeModelStatus => row !== null), columns));
221
235
  const timing = data.controlWriteTiming;
222
236
  if (full && timing && Object.values(timing).every(value => Number.isSafeInteger(value) && value >= 0)) {
223
237
  out.push(...lines(`control writes: active ${timing.active}, slow ${timing.slowRequests}, loop delays ${timing.blockedLoopSamples}, dropped ${timing.droppedActive + timing.droppedLogs + (timing.droppedSpans ?? 0) + (timing.droppedMetadata ?? 0)}, expired ${timing.expiredRequests ?? 0}; timings in hub.log`, columns, timing.slowRequests || timing.blockedLoopSamples ? "attention" : undefined));
@@ -290,6 +304,14 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
290
304
  let settling = false;
291
305
  const peerDetails = Object.entries(data.peers).map(([id, p]) => {
292
306
  const out: Span[][] = [];
307
+ // #1310: the current owner, when the hub reported one. Shown before the standby rows so the owner is never inferred from them. Every value is re-checked here: a pid is a positive integer, a time is
308
+ // finite, and a native session id is shown only when it is a short plain token; anything else is left out rather than cleaned up.
309
+ const owner = p.ownerAttachment;
310
+ if (owner && typeof owner === "object" && Number.isFinite(owner.attachedAt)) {
311
+ const pid = Number.isSafeInteger(owner.ownerPid) && owner.ownerPid > 0 ? `pid ${owner.ownerPid}` : "pid unknown";
312
+ const native = typeof owner.nativeSessionId === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(owner.nativeSessionId) ? `native session ${owner.nativeSessionId}` : "native session unverified";
313
+ out.push(...detail(`${id} owner`, `${pid}; attached ${relative(owner.attachedAt, now)}; ${native}`, columns, "muted"));
314
+ }
293
315
  for (const session of Array.isArray(p.standbySessions) ? p.standbySessions : []) {
294
316
  if (!session || typeof session.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(session.id)) continue;
295
317
  const pid = Number.isSafeInteger(session.pid) && session.pid > 0 ? String(session.pid) : "unknown";
package/src/cli/reset.ts CHANGED
@@ -149,7 +149,7 @@ export function resetRuntime(stateDir: string, project: Project): { settled: str
149
149
  const db = openHubDatabase(file);
150
150
  try {
151
151
  db.transaction(() => {
152
- for (const table of ["budget_pauses", "conductor_holds"]) {
152
+ for (const table of ["budget_pauses", "conductor_holds", "model_overrides"]) {
153
153
  if (db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) db.run(`DELETE FROM ${table}`);
154
154
  }
155
155
  })();
@@ -0,0 +1,10 @@
1
+ import { readAutonomyDefaults, writeMachineResearch } from "../hub/autonomy-defaults.ts";
2
+
3
+ /** Explicit person-only setup choice. Ordinary setup neither reads nor writes the research default. */
4
+ export function setupResearchDefault(home: string, roots: readonly string[], enabled: boolean | undefined): string | undefined {
5
+ if (enabled === undefined) return undefined;
6
+ const held = readAutonomyDefaults(home, roots);
7
+ try { writeMachineResearch(home, enabled, held.fingerprint, roots); }
8
+ catch { throw new Error("Research default was not saved: defaults.json is unsafe or changed; check its ownership, mode and schema, then rerun ahub setup --research or --no-research."); }
9
+ return `Research records for new projects: ${enabled ? "on" : "off"} (saved in this machine's defaults; ahub init inherits it). Upgrade every hub and CLI on this machine to 0.36 or later first: a version from before 0.36 treats the whole file as untrusted, so its machine autonomy preset falls back to off and its start-agent default to the shipped one.`;
10
+ }
@@ -1,11 +1,11 @@
1
1
  import { projectRoomUnavailable } from "../rooms/status.ts";
2
2
  import type { ContextView } from "../hub/context-window.ts";
3
- import { memorySyncNextStep, type MemorySyncCause } from "../hub/memory-sync-state.ts";
3
+ import { memorySyncNextStep, WRITER_CATEGORIES, WRITER_CAUSE_CLASSES, type MemorySyncCause } from "../hub/memory-sync-state.ts";
4
4
  // What `ahub status` prints for a peer and for a model backend, kept pure so it can be checked.
5
5
 
6
6
  export interface PeerRow { permissionMode?: string; context?: ContextView; state?: string; queued?: number; queuedImportant?: number; needsReview?: number; heldBy?: string; holdNote?: string; reviewObserverHoldNote?: string; liveAccepted?: string[]; oldestQueuedAt?: number; importantWaitingSince?: number; importantWaitingNote?: string; attached?: boolean; attachMode?: "channel" | "tools-only"; attachEvidence?: string; toolsOnly?: string; pullOnly?: boolean; lastInboxAt?: number | null; permissionNote?: string; reviewerUnavailable?: string; paused?: string; servedBy?: string; requestedModel?: string }
7
7
  export interface BackendRow { kind?: string; alias?: string; state?: string; active?: number; requestedModel?: string; actualModel?: string; provider?: string; coolingUntil?: string; failures?: number; failingUntil?: string }
8
- export interface MemorySyncRow { state?: string; at?: number; cause?: string; declinedCount?: number; declinedIdsKnown?: false; withheldCount?: number; exportedCount?: number; placementActive?: false; nextStep?: string }
8
+ export interface MemorySyncRow { state?: string; at?: number; cause?: string; declinedCount?: number; declinedIdsKnown?: false; withheldCount?: number; exportedCount?: number; placementActive?: false; writerCategory?: string; writerCauseClass?: string; nextStep?: string }
9
9
  export interface ReviewInputHealthRow { state?: string; cause?: string | null }
10
10
 
11
11
  /** Aliases are already namespaced ("dgx/coding"); only an alias that is not gets its kind in front of it. */
@@ -32,11 +32,15 @@ export function memorySyncLine(sync: MemorySyncRow, time = (at: number) => new D
32
32
  && Number.isSafeInteger(sync.exportedCount) && sync.exportedCount! >= 0)
33
33
  return `ok${stamp}; ${sync.withheldCount} row${sync.withheldCount === 1 ? "" : "s"} withheld locally; ${sync.exportedCount} exported`;
34
34
  if (state !== "failed") return `${state}${stamp}`;
35
- const causes = ["declined", "remote", "binding", "stopped", "transport", "unknown"];
35
+ const causes = ["declined", "remote", "binding", "stopped", "transport", "writer", "unknown"];
36
36
  const cause = (causes.includes(sync.cause ?? "") ? sync.cause : "unknown") as MemorySyncCause;
37
37
  if (cause === "declined" && sync.placementActive === false) {
38
38
  const declined = Number.isSafeInteger(sync.declinedCount) && sync.declinedCount! >= 0 ? String(sync.declinedCount) : "unknown";
39
- return "machine sync blocked: " + declined + " declined rows; per-row placement is not active on this store. Activation is person-only: preview with `amem migrate --sync-placement --dry-run` and declare every writer via --writer-root. The hub does not yet supply the fresh placementAttestation required for active-placement sync (#1173). Inspect with `ahub memory declined`.";
39
+ return "machine sync blocked: " + declined + " declined rows; per-row placement is not active on this store. Activation is person-only: preview with `amem migrate --sync-placement --dry-run` and declare every writer via --writer-root. Inspect with `ahub memory declined`.";
40
+ }
41
+ if (cause === "writer") {
42
+ const category = WRITER_CATEGORIES.includes(sync.writerCategory ?? "") ? sync.writerCategory : "unknown", causeClass = WRITER_CAUSE_CLASSES.includes(sync.writerCauseClass ?? "") ? sync.writerCauseClass : "unavailable";
43
+ return `failed (writer attestation refused: ${category}, ${causeClass})${stamp}; next: ${memorySyncNextStep("writer")}`;
40
44
  }
41
45
  const count = Number.isSafeInteger(sync.declinedCount) && sync.declinedCount! >= 0 ? `, ${sync.declinedCount} declined` : "";
42
46
  const ids = cause === "declined" && sync.declinedIdsKnown === false ? "; declined ID set unknown" : "";
@@ -6,7 +6,7 @@ import { insideRoot } from "./path-policy.ts";
6
6
  import { checkStartAgents } from "./start-agents.ts";
7
7
 
8
8
  /** `startAgents` is the machine default of `start.agents` (#608), present only when `ahub setup` chose one. */
9
- export interface AutonomyDefaultsRead { enabled: boolean; fingerprint: string; notice?: string; startAgents?: string[] }
9
+ export interface AutonomyDefaultsRead { enabled: boolean; fingerprint: string; notice?: string; startAgents?: string[]; researchEnabled?: boolean }
10
10
  const MAX_BYTES = 4096;
11
11
  const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
12
12
  const refusal = () => new Error("machine autonomy defaults are unsafe or changed; nothing was written");
@@ -32,12 +32,12 @@ function capture(home: string, roots: readonly string[]): { stat?: Stats; text?:
32
32
  return { stat: after, text, fingerprint: createHash("sha256").update(`${after.dev}:${after.ino}:${after.ctimeMs}:`).update(text).digest("hex") };
33
33
  } finally { closeSync(fd); }
34
34
  }
35
- interface DefaultsDocument { autonomy?: boolean; startAgents?: string[] }
36
- /** The file's content, or the refusal. `{schema:1}` alone and any key but schema, autonomy and start are refused. */
35
+ interface DefaultsDocument { autonomy?: boolean; startAgents?: string[]; researchEnabled?: boolean }
36
+ /** The file's content, or the refusal. `{schema:1}` alone and any key but schema, autonomy, start and research are refused. */
37
37
  function parseDefaults(text: string): DefaultsDocument {
38
38
  const raw: unknown = JSON.parse(text);
39
39
  const document = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : undefined;
40
- if (!document || Object.keys(document).some(key => !["schema", "autonomy", "start"].includes(key)) || document.schema !== 1) throw refusal();
40
+ if (!document || Object.keys(document).some(key => !["schema", "autonomy", "start", "research"].includes(key)) || document.schema !== 1) throw refusal();
41
41
  if (document.autonomy !== undefined && typeof document.autonomy !== "boolean") throw refusal();
42
42
  let startAgents: string[] | undefined;
43
43
  if (document.start !== undefined) {
@@ -45,8 +45,14 @@ function parseDefaults(text: string): DefaultsDocument {
45
45
  if (!start || typeof start !== "object" || Array.isArray(start) || Object.keys(start).some(key => key !== "agents")) throw refusal();
46
46
  try { startAgents = checkStartAgents((start as Record<string, unknown>).agents); } catch { throw refusal(); }
47
47
  }
48
- if (document.autonomy === undefined && startAgents === undefined) throw refusal();
49
- return { ...(document.autonomy === undefined ? {} : { autonomy: document.autonomy }), ...(startAgents ? { startAgents } : {}) };
48
+ let researchEnabled: boolean | undefined;
49
+ if (document.research !== undefined) {
50
+ const research = document.research;
51
+ if (!research || typeof research !== "object" || Array.isArray(research) || Object.keys(research).some(key => key !== "enabled") || typeof (research as Record<string, unknown>).enabled !== "boolean") throw refusal();
52
+ researchEnabled = (research as { enabled: boolean }).enabled;
53
+ }
54
+ if (document.autonomy === undefined && startAgents === undefined && researchEnabled === undefined) throw refusal();
55
+ return { ...(document.autonomy === undefined ? {} : { autonomy: document.autonomy }), ...(startAgents ? { startAgents } : {}), ...(researchEnabled === undefined ? {} : { researchEnabled }) };
50
56
  }
51
57
  /** Missing or untrusted machine files never change the shipped ask default. */
52
58
  export function readAutonomyDefaults(home: string, roots: readonly string[] = []): AutonomyDefaultsRead {
@@ -54,17 +60,22 @@ export function readAutonomyDefaults(home: string, roots: readonly string[] = []
54
60
  const held = capture(home, roots);
55
61
  if (held.text === undefined) return { enabled: false, fingerprint: held.fingerprint };
56
62
  const document = parseDefaults(held.text);
57
- return { enabled: document.autonomy === true, fingerprint: held.fingerprint, ...(document.startAgents ? { startAgents: document.startAgents } : {}) };
63
+ return { enabled: document.autonomy === true, fingerprint: held.fingerprint, ...(document.startAgents ? { startAgents: document.startAgents } : {}), ...(document.researchEnabled === undefined ? {} : { researchEnabled: document.researchEnabled }) };
58
64
  } catch { return { enabled: false, fingerprint: "untrusted", notice: "Machine autonomy defaults ignored: defaults.json must be an owner-only regular file with a valid schema, outside project roots." }; }
59
65
  }
60
66
  /** Person CLI only. Exact prior evidence is rechecked after confirmation and before replacement. The other half of the file (the start set) is kept. */
61
67
  export function writeAutonomyDefaults(home: string, enabled: boolean, expected: string, roots: readonly string[] = []): void {
62
- writeDefaults(home, expected, roots, kept => ({ schema: 1, autonomy: enabled, ...(kept.startAgents ? { start: { agents: kept.startAgents } } : {}) }));
68
+ writeDefaults(home, expected, roots, kept => ({ schema: 1, autonomy: enabled, ...(kept.startAgents ? { start: { agents: kept.startAgents } } : {}), ...(kept.researchEnabled === undefined ? {} : { research: { enabled: kept.researchEnabled } }) }));
63
69
  }
64
70
  /** Person CLI only (`ahub setup`): the machine default of `start.agents`. The autonomy half of the file is kept, and absent stays absent. */
65
71
  export function writeMachineStartAgents(home: string, agents: readonly string[], expected: string, roots: readonly string[] = []): void {
66
72
  const checked = checkStartAgents([...agents]);
67
- writeDefaults(home, expected, roots, kept => ({ schema: 1, ...(kept.autonomy === undefined ? {} : { autonomy: kept.autonomy }), start: { agents: checked } }));
73
+ writeDefaults(home, expected, roots, kept => ({ schema: 1, ...(kept.autonomy === undefined ? {} : { autonomy: kept.autonomy }), start: { agents: checked }, ...(kept.researchEnabled === undefined ? {} : { research: { enabled: kept.researchEnabled } }) }));
74
+ }
75
+ /** Person CLI only (`ahub setup --research|--no-research`); preserve autonomy and the chosen agent set. */
76
+ export function writeMachineResearch(home: string, enabled: boolean, expected: string, roots: readonly string[] = []): void {
77
+ if (typeof enabled !== "boolean") throw refusal();
78
+ writeDefaults(home, expected, roots, kept => ({ schema: 1, ...(kept.autonomy === undefined ? {} : { autonomy: kept.autonomy }), ...(kept.startAgents ? { start: { agents: kept.startAgents } } : {}), research: { enabled } }));
68
79
  }
69
80
  function writeDefaults(home: string, expected: string, roots: readonly string[], build: (kept: DefaultsDocument) => Record<string, unknown>): void {
70
81
  const before = capture(home, roots);