@staix/agent-hub 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/guidance-probes.md +365 -0
  15. package/docs/design/task-board.md +151 -5
  16. package/docs/dogfood.md +22 -7
  17. package/docs/events.md +3 -3
  18. package/docs/memory.md +5 -5
  19. package/docs/operations.md +189 -32
  20. package/docs/profiles.md +101 -9
  21. package/docs/quickstart.md +38 -4
  22. package/docs/research.md +6 -3
  23. package/docs/roles.md +52 -0
  24. package/docs/sdlc.md +187 -1
  25. package/docs/security.md +56 -13
  26. package/docs/text-projection.md +1 -0
  27. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  29. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  30. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  31. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  32. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  33. package/docs/verified.json +48 -25
  34. package/package.json +3 -3
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +1989 -474
  37. package/plugins/agent-hub/server.js +2056 -512
  38. package/src/adapters/acp-model-policy.ts +1 -1
  39. package/src/adapters/acp-session-model.ts +35 -0
  40. package/src/adapters/acp.ts +14 -0
  41. package/src/adapters/agy/definition.ts +1 -1
  42. package/src/adapters/agy/hooks.ts +7 -0
  43. package/src/adapters/claude-channel.ts +3 -2
  44. package/src/adapters/claude-implementer.ts +8 -0
  45. package/src/adapters/claude-print-child.ts +26 -2
  46. package/src/adapters/claude-print.ts +4 -0
  47. package/src/adapters/codex-appserver.ts +90 -16
  48. package/src/adapters/codex-review-isolation.ts +2 -0
  49. package/src/adapters/compat.ts +4 -4
  50. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  51. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  52. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  53. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  55. package/src/adapters/definitions/native-quota.ts +122 -0
  56. package/src/adapters/definitions/native-recovery.ts +3 -0
  57. package/src/adapters/definitions/qwen.ts +1 -1
  58. package/src/adapters/kimi-review.ts +23 -0
  59. package/src/adapters/kimi-wire-usage.ts +39 -16
  60. package/src/adapters/local-probe.ts +65 -6
  61. package/src/adapters/local-worker.ts +6 -3
  62. package/src/adapters/pi-state-model.ts +12 -0
  63. package/src/adapters/pi.ts +22 -0
  64. package/src/adapters/print-result-model.ts +24 -0
  65. package/src/adapters/registry-types.ts +10 -1
  66. package/src/adapters/registry.ts +19 -2
  67. package/src/adapters/reviewer-print.ts +130 -15
  68. package/src/adapters/role-eligibility.ts +99 -0
  69. package/src/adapters/same-directory.ts +16 -0
  70. package/src/cli/agy-mcp.ts +18 -7
  71. package/src/cli/console-state.ts +3 -1
  72. package/src/cli/free-text.ts +20 -0
  73. package/src/cli/handoff-args.ts +1 -1
  74. package/src/cli/help.ts +61 -6
  75. package/src/cli/identity.ts +10 -4
  76. package/src/cli/init-prompt.ts +31 -2
  77. package/src/cli/init-roles.ts +156 -0
  78. package/src/cli/init-settings.ts +24 -2
  79. package/src/cli/init.ts +141 -17
  80. package/src/cli/main.ts +216 -56
  81. package/src/cli/model.ts +1 -1
  82. package/src/cli/output.ts +64 -5
  83. package/src/cli/preview.ts +1 -1
  84. package/src/cli/recovery-launch.ts +114 -0
  85. package/src/cli/recovery-package.ts +14 -7
  86. package/src/cli/recovery-version-preflight.ts +104 -0
  87. package/src/cli/role-doctor.ts +39 -0
  88. package/src/cli/sdlc-output.ts +66 -1
  89. package/src/cli/study-output.ts +54 -0
  90. package/src/cli/study.ts +14 -1
  91. package/src/cli/terminal-recovery.ts +14 -0
  92. package/src/cli/upgrade-presentation.ts +4 -0
  93. package/src/cli/upgrade-restore-state.ts +12 -3
  94. package/src/cli/upgrade-runtime.ts +41 -3
  95. package/src/cli/upgrade.ts +8 -4
  96. package/src/hub/advisor-survey.ts +139 -0
  97. package/src/hub/audit-source.ts +66 -0
  98. package/src/hub/board.ts +479 -14
  99. package/src/hub/budget.ts +54 -4
  100. package/src/hub/bus.ts +2 -2
  101. package/src/hub/conductor.ts +14 -8
  102. package/src/hub/config-apply.ts +2 -1
  103. package/src/hub/config-edit-host.ts +77 -5
  104. package/src/hub/considered-findings.ts +47 -0
  105. package/src/hub/control-client.ts +1 -1
  106. package/src/hub/daemon.ts +373 -66
  107. package/src/hub/deliverable-files.ts +17 -1
  108. package/src/hub/dogfood-profile.ts +3 -2
  109. package/src/hub/envelope.ts +6 -1
  110. package/src/hub/events.ts +23 -2
  111. package/src/hub/folder-trigger.ts +11 -4
  112. package/src/hub/guidance-probe-store.ts +345 -14
  113. package/src/hub/guidance-probes.ts +338 -4
  114. package/src/hub/hub-tools.ts +88 -16
  115. package/src/hub/kimi-usage.ts +34 -2
  116. package/src/hub/lifecycle-schema.ts +3 -3
  117. package/src/hub/manager.ts +24 -1
  118. package/src/hub/memory-profile.ts +9 -1
  119. package/src/hub/memory-sync-state.ts +1 -0
  120. package/src/hub/model-overrides.ts +2 -1
  121. package/src/hub/no-writes.ts +2 -0
  122. package/src/hub/operational-authority.ts +8 -2
  123. package/src/hub/operational-view.ts +5 -1
  124. package/src/hub/peers.ts +2 -0
  125. package/src/hub/person-command.ts +25 -0
  126. package/src/hub/plan-conformance.ts +20 -2
  127. package/src/hub/quota-account.ts +34 -0
  128. package/src/hub/recovery-policy.ts +18 -4
  129. package/src/hub/research-evidence.ts +51 -3
  130. package/src/hub/research.ts +77 -13
  131. package/src/hub/restart.ts +14 -0
  132. package/src/hub/review-budget.ts +88 -0
  133. package/src/hub/review-findings.ts +93 -12
  134. package/src/hub/reviewer-pool-config.ts +6 -2
  135. package/src/hub/reviewer-pool.ts +39 -6
  136. package/src/hub/routing.ts +7 -3
  137. package/src/hub/sdlc-merge.ts +1 -1
  138. package/src/hub/sdlc-queue.ts +14 -4
  139. package/src/hub/sdlc-release.ts +1 -1
  140. package/src/hub/sdlc.ts +10 -6
  141. package/src/hub/security-audit.ts +178 -0
  142. package/src/hub/security-pass.ts +115 -0
  143. package/src/hub/settings.ts +11 -5
  144. package/src/hub/source-read.ts +80 -2
  145. package/src/hub/sources.ts +57 -9
  146. package/src/hub/startup-event-seeds.ts +5 -3
  147. package/src/hub/startup-timing.ts +1 -0
  148. package/src/hub/supervision.ts +3 -2
  149. package/src/hub/synthesis-readiness.ts +279 -0
  150. package/src/hub/tasks.ts +1131 -72
  151. package/src/hub/text-projection.ts +11 -1
  152. package/src/local/probe-types.ts +2 -0
  153. package/src/local/probe-workspace.ts +191 -2
  154. package/src/memory/capture.ts +2 -1
  155. package/src/ui/guidance-panel.ts +34 -2
  156. package/src/ui/guidance-view.ts +33 -0
  157. package/src/ui/index.html +3 -0
  158. package/src/ui/office-model.ts +11 -3
  159. package/src/ui/office-space.ts +50 -30
  160. package/src/ui/plugin.ts +31 -14
  161. package/templates/AGENTS.block.md +14 -14
  162. package/templates/profiles/general.json +1 -1
  163. package/templates/profiles/research.json +1 -1
  164. package/templates/profiles/writing.json +1 -1
package/src/cli/main.ts CHANGED
@@ -14,8 +14,8 @@ import { assessVersion, COMPAT, configuredCommands } from "../adapters/compat.ts
14
14
  import { claudePeer as defaultChannelPeer } from "../hub/claude-state.ts";
15
15
  import { effectiveInstanceRoles } from "../hub/instances.ts";
16
16
  import { resolveInstanceExecutionCwd } from "../hub/instance-execution.ts";
17
- import { readInstanceRoleConfig, readInstanceConfig, type InstanceRoleConfig } from "../hub/instance-config.ts";
18
- import { staleInstanceKey } from "../hub/roster.ts";
17
+ import { readInstanceRoleConfig, readInstanceConfig, readInstanceConfigLayers, type InstanceRoleConfig } from "../hub/instance-config.ts";
18
+ import { staleInstanceKey, rosterAllows } from "../hub/roster.ts";
19
19
  import { parseConfiguredAcpArguments, runConfiguredAcpEntry, requireActiveConfiguredAcp } from "./configured-acp-entry.ts";
20
20
  import type { NativeCliEntryContext } from "../adapters/definitions/native-cli-entry-types.ts";
21
21
  import { BUILTIN_CLI_ENTRIES, createProjectAdapterCatalog, definitionOf, DOCTOR_TOOL_PROBES, DOCTOR_MEMORY_CAPTURE_PEERS, DOCTOR_PLUGIN_PROBE, nativeDoctorCheck, nativeMemoryCaptureRow, type MemorySetupReading, nativeDoctorRecoveryIdentity, nativeDoctorOptionalProbes } from "../adapters/registry.ts";
@@ -23,17 +23,18 @@ import { parsePiFlags } from "../adapters/definitions/native-cli-pi.ts";
23
23
  import { supportsBoardReleaseFilter, supportsBoardColumnMetadata, readAllTasks } from "./board-read.ts";
24
24
  import { matchesPolicy } from "../hub/path-policy.ts";
25
25
  import { projectedDiff } from "../hub/projected-diff.ts";
26
- import { TextProjections } from "../hub/text-projection.ts";
27
- import { fetchSourceUrl, MAX_SOURCE_BYTES, publicSourceView, screenRegistration, SourceRegistry, validSourceId, type SourceMeta } from "../hub/sources.ts";
26
+ import { TextProjections, type ProjectedText } from "../hub/text-projection.ts";
27
+ import { fetchSourceUrl, MAX_SOURCE_BYTES, publicSourceView, screenRegistration, sourceProjectionReceipt, SourceRegistry, validSourceId, type SourceMeta } from "../hub/sources.ts";
28
28
  import { renderSourceAdd, renderSourceList } from "./source-output.ts";
29
29
  import { renderScheduleChange, renderScheduleList, renderScheduleRun } from "./schedule-output.ts";
30
30
  import { renderIntake, renderIntakeChange } from "./intake-output.ts";
31
31
  import { renderLearnChange, renderLearnList } from "./learn-output.ts";
32
32
  import { renderCapabilities } from "./capabilities-output.ts";
33
+ import { parseSynthesisManifest, synthesisManifestHash } from "../hub/synthesis-readiness.ts";
33
34
  import { parseStudyArgs } from "./study.ts";
34
35
  import { parseBacklogReturn } from "./backlog-return-args.ts";
35
36
  import { parseResultsArgs } from "./results-args.ts";
36
- import { renderExperiments, renderStudyList, renderStudyReceipt, renderStudyShow } from "./study-output.ts";
37
+ import { renderStudyEvidence, renderSynthesisReadiness, renderExperiments, renderStudyList, renderStudyReceipt, renderStudyShow } from "./study-output.ts";
37
38
  import { renderHandoffReceipt, renderHandoffs } from "./handoff-output.ts";
38
39
  import { parseHandoffArgs } from "./handoff-args.ts";
39
40
  import { terminalText } from "./console-state.ts";
@@ -60,6 +61,7 @@ import { qwenSessionId } from "../hub/crash.ts";
60
61
  import { isPermissionMode } from "../hub/permission-mode.ts";
61
62
  import { parseSettingText, settingDef, settingText, undoableDef, type SettingRow } from "../hub/settings.ts";
62
63
  import { startModeOf } from "../hub/start-mode.ts";
64
+ import { rolesRow } from "./role-doctor.ts";
63
65
  import { currentRouting, OVERLAY_FILE, parseOverlay, parseRouting, routingText, type Routing, type RoutingOverlay } from "../hub/routing.ts";
64
66
  import { spawn, spawnSync } from "node:child_process";
65
67
  import { chmodSync, closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
@@ -77,9 +79,10 @@ import { inspectProject, startProject, stopProject, runProjectDaemon } from "../
77
79
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
78
80
  import { openManager, startManager, stopManager } from "../hub/manager.ts";
79
81
  import { OmniRoute } from "../omniroute/client.ts";
80
- import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit } from "./init.ts";
82
+ import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit, sharedConfigRow } from "./init.ts";
81
83
  import { discoverInitChecks, withInitChecks } from "./init-required-checks.ts";
82
84
  import { INIT_USAGE, parseInitSettings } from "./init-settings.ts";
85
+ import { installedPeers } from "./init-roles.ts";
83
86
  import { promptGate, runInitPrompt, settingLines, shadowOffered, type InitAnswers } from "./init-prompt.ts";
84
87
  import { loadPacks } from "../hub/packs.ts";
85
88
  import { launcherPreview } from "./preview.ts";
@@ -88,7 +91,7 @@ import { configureKimiMcp } from "./kimi-mcp.ts";
88
91
  import { nextStep, parseList, pluginState, type InstalledPlugin, type Marketplace } from "./setup.ts";
89
92
  import { CLASSES } from "../hub/board.ts";
90
93
  import { VERSION } from "../version.ts";
91
- import { freeText } from "./free-text.ts";
94
+ import { freeText, unknownOption, unknownOptionRefusal, withoutSeparator } from "./free-text.ts";
92
95
  import { createInterface } from "node:readline/promises";
93
96
  import { createInterface as lineReader } from "node:readline";
94
97
  import { activeOperation, assertLifecycleAvailable, operationIdPattern, readOperation, writeOperation, recoveryLock, recoveryRunner, signedRunner, stopSignedRunner, supportsAction } from "../hub/recovery-store.ts";
@@ -116,7 +119,7 @@ import { runSpecs, runSpecsStamp } from "./specs.ts";
116
119
  import { confirmTidy, planTidy, realTidyGit, rowsFromReply, type TidyGit } from "./worktree-tidy.ts";
117
120
  import { renderTidyPreview, renderTidyResult, renderWorktrees } from "./worktrees-output.ts";
118
121
  import { formatMemoryStaleAnchors } from "../hub/memory-stale-anchors.ts";
119
- import { AGENT_MEM_VERSION, assertAgentMemVersion, selectedMemoryProfile } from "../hub/memory-profile.ts";
122
+ import { AGENT_MEM_VERSION, assertAgentMemVersion, memoryIndexExists, selectedMemoryProfile } from "../hub/memory-profile.ts";
120
123
  import { checkMemoryProfiles, formatMemoryProfileCheck } from "../hub/memory-profile-check.ts";
121
124
  import { addonReport, appendRecords, closedAtOf, formatAddons, formatResearch, LABELS, labelTarget, RESEARCH_SCHEMA, projectKey, readStores, researchReport, taskRecords, toCsv, type Label, type TaskRecord } from "../hub/research.ts";
122
125
  import { summarize, summarizeByTask } from "../hub/report.ts";
@@ -131,10 +134,12 @@ import { recordCliAudit, recordDelegatedCliAudit } from "./identity-audit.ts";
131
134
  import { runConsole } from "./console.ts";
132
135
  import { installedVersions } from "./console-versions.ts";
133
136
  import { paint, permissionBoundary, resolveColor, wrap, type Span } from "./console-state.ts";
134
- 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";
135
- import { renderHelp, configuredAcpHelp } from "./help.ts";
137
+ import { queueResolveArgsValid } from "../hub/person-command.ts";
138
+ import { outputWidth, renderRuntimeModels, renderRoster, renderRoles, rolesView,renderStatus, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
139
+ import { renderHelp, configuredAcpHelp, guidanceProbeUsage, listsSubcommand, subcommandUsage } from "./help.ts";
136
140
  import { renderBacklogResult, renderGroom, renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow, renderTaskCancel, renderTaskShow } from "./task-output.ts";
137
- import { renderAuthorization, renderSdlcCosts, renderSdlcExplain, renderSdlcMerge, renderSdlcMetrics, renderSdlcQueue, renderSdlcRelease, renderSdlcStatus } from "./sdlc-output.ts";
141
+ import { SURVEY_FOCUS } from "../hub/advisor-survey.ts";
142
+ import { renderAuthorization, renderSdlcCosts, renderSdlcExplain, renderSdlcMerge, renderSdlcMetrics, renderSdlcQueue, renderSdlcRelease, renderSdlcStatus, renderSdlcAudit, renderSdlcConfiguration, renderSdlcSurvey } from "./sdlc-output.ts";
138
143
  import { renderTailEvent } from "./tail-render.ts";
139
144
  import { archiveProblem, archiveState, damagedState, failureText, MANIFEST, planReset, resetLines, resetRuntime, startState, type ResetPlan } from "./reset.ts";
140
145
 
@@ -223,10 +228,11 @@ try {
223
228
  } else nativeSelection = instanceLaunchArguments(given, rest, declaredInstances);
224
229
  } catch (error) { fail(startupDiagnostic(error)); }
225
230
  const selectedInstance = nativeSelection.instance;
226
- // `ahub <command> -h` alone asks for that command's help instead of running it. Elsewhere `-h` may be message text
227
- // (`ahub say try ls -h`), and claude and codex pass their arguments on to the agent.
231
+ // `ahub <command> -h` alone asks for that command's help instead of running it, and so does `ahub <command> <sub> -h` when the help lists that subcommand (#1433: `ahub task propose --help` once
232
+ // filed a task titled --help). Elsewhere `-h` may be message text (`ahub say try ls -h`), and claude and codex pass their arguments on to the agent.
228
233
  const asksHelp = (a: string | undefined) => a === "--help" || a === "-h";
229
- const cmd = asksHelp(given) || (definitionOf(given)?.start.passthrough !== true && nativeSelection.args.length === 1 && asksHelp(nativeSelection.args[0])) ? "help" : given;
234
+ const subcommandHelp = !!given && nativeSelection.args.length === 2 && asksHelp(nativeSelection.args[1]) && listsSubcommand(given, nativeSelection.args[0]!);
235
+ const cmd = asksHelp(given) || (definitionOf(given)?.start.passthrough !== true && ((nativeSelection.args.length === 1 && asksHelp(nativeSelection.args[0])) || subcommandHelp)) ? "help" : given;
230
236
  const args = cmd === "help" && given !== "help" && !asksHelp(given) ? [given] : nativeSelection.args;
231
237
 
232
238
  /** Resolve a named peer only against this project's current trusted declarations. */
@@ -255,7 +261,7 @@ const projectConfig = () => {
255
261
  const stateDir = selected.stateDir;
256
262
  var operationalAuditReady=false, operationalRefusalRecorded=false;
257
263
  const caller = declaredInstances ? detectCliIdentity(process.env, declaredInstances) : unboundCaller;
258
- const commandLabel = cmd === "guidance" && args[0] === "probe" && ["register", "start", "show", "cancel"].includes(args[1] ?? "")
264
+ const commandLabel = cmd === "guidance" && args[0] === "probe" && ["register", "start", "show", "receipts", "cancel"].includes(args[1] ?? "")
259
265
  ? `guidance probe ${args[1]}` : cliCommandLabel(cmd, args, projectCatalog);
260
266
  let commandAccess = classifyPeerCommand(cmd, args, projectCatalog);
261
267
  const continuationPeer = process.env.AGENTHUB_RECOVERY_CONDUCTOR;
@@ -279,7 +285,7 @@ if (continuationPeer !== undefined) {
279
285
  const conductorPeer = !liveTest && caller.role === "tools" && (recoveryRunnerContinuation || ["restart", "upgrade", "recovery"].includes(cmd) && commandAccess === "conductor") ? caller.peer : undefined;
280
286
  // Agent-authored content keeps its peer. Operational starts/holds may borrow console authority for live verification.
281
287
  const guidanceProbeDelegationRefused = liveTest && caller.role === "tools" && cmd === "guidance"
282
- && args[0] === "probe" && ["register", "start", "show", "cancel"].includes(args[1] ?? "");
288
+ && args[0] === "probe" && ["register", "start", "show", "receipts", "cancel"].includes(args[1] ?? "");
283
289
  const delegationRefused = liveTest && caller.role === "tools" && commandAccess !== "allowed"
284
290
  && (liveTestRefusal(cmd, args) || guidanceProbeDelegationRefused);
285
291
  const delegatedPeer = liveTest && caller.role === "tools" && commandAccess !== "allowed" && !delegationRefused ? caller.peer : undefined;
@@ -382,7 +388,7 @@ function showToolText(render: (data: any, columns?: number, now?: number) => Spa
382
388
  if (present.json) return console.log(text);
383
389
  printOutput(render(data, present.columns, Date.now()), present.color);
384
390
  }
385
- const SDLC_READ = ["status", "explain", "queue", "release", "metrics", "costs", "authorize-release"];
391
+ const SDLC_READ = ["status", "explain", "queue", "release", "metrics", "costs", "authorize-release", "audit", "configure", "survey"];
386
392
  function sdlcOperands(): string[] { return SDLC_READ.includes(args[0] ?? "") ? outputArguments() : args; }
387
393
  function printOutput(lines: Span[][], color: boolean): void {
388
394
  for (const line of lines) console.log(paint(line, color));
@@ -574,6 +580,8 @@ async function taskOp(op: string, a: Record<string, unknown>, throwOnError = fal
574
580
  const hub = connection ?? await connect();
575
581
  try {
576
582
  if (op === "hub_task_cancel" && !hub.features.includes("task_cancel")) fail("this daemon does not support task cancellation; upgrade it first");
583
+ if ((op === "study_evidence" || op === "study_check" || op === "claim_verdict" && a.synthesis !== undefined) && !hub.features.includes("research_synthesis"))
584
+ fail("running hub lacks research_synthesis; upgrade and restart the hub before requesting synthesis evidence or recording a manifest-bound verdict");
577
585
  const res = await hub.request({ t: "task", op, args: a }, timeoutMs ?? (op === "github_import" ? 60_000 : 30_000));
578
586
  if (!res.ok) {
579
587
  if (throwOnError) throw new Error(res.error);
@@ -878,8 +886,29 @@ const LOCAL_OPERATION_ARGS: Record<string, () => void> = {
878
886
  "source add": () => { const operands = args.filter(arg => arg !== "--json" && arg !== "--full" && !arg.startsWith("--color=")); if (operands[0] !== "add" || operands.length !== 2 || !operands[1]) fail(SOURCE_USAGE); },
879
887
  };
880
888
 
889
+ const contract = (file: string, kind: "contract" | "manifest" = "contract"): unknown => {
890
+ // One descriptor decides everything: opened non-blocking and without following a final symlink (a FIFO would otherwise block the open), checked to be a regular file with fstat, and
891
+ // read for at most the cap plus one byte, so a file that grows or is replaced after the check, or a device that reports size zero, cannot exhaust memory or hang this process.
892
+ const cap = 64 * 1024;
893
+ let text: string;
894
+ try {
895
+ const fd = openSync(resolve(invokedFrom, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
896
+ try {
897
+ if (!fstatSync(fd).isFile()) return fail(`the ${kind} file is not a regular file`);
898
+ const bytes = Buffer.alloc(cap + 1); let got = 0;
899
+ while (got < bytes.length) { const n = readSync(fd, bytes, got, bytes.length - got, null); if (!n) break; got += n; }
900
+ if (got > cap) return fail(`the ${kind} file is over 64 KiB`);
901
+ text = bytes.subarray(0, got).toString("utf8");
902
+ } finally { closeSync(fd); }
903
+ }
904
+ catch { return fail(`cannot read the ${kind} file`); }
905
+ try { return JSON.parse(text); } catch { return fail(`the ${kind} file is not valid JSON`); }
906
+ };
907
+
881
908
  // Outside the command bodies: test/lifecycle-starting-1232.test.ts runs the `up` body as a plain function, where import.meta does not parse.
882
909
  const consoleInstalled = () => installedVersions(join(import.meta.dir, "..", ".."));
910
+ /** `ahub goal new` options: those that take a value, and all it knows. The words they leave are the title. */
911
+ const GOAL_NEW_VALUE_FLAGS = ["--milestone", "--depends"], GOAL_NEW_FLAGS = [...GOAL_NEW_VALUE_FLAGS, "--shared", "--json"];
883
912
  const commands: Record<string, () => Promise<void> | void> = {
884
913
  upgrade: () => upgrade("upgrade"),
885
914
  restart: () => upgrade("restart"),
@@ -1147,7 +1176,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1147
1176
  let result: Awaited<ReturnType<typeof runInitPrompt>>;
1148
1177
  try {
1149
1178
  result = await runInitPrompt({ ask, print: line => console.log(terminalText(line)) },
1150
- { ...(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);
1179
+ { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), machineResearch: initResearchDefault(cwd, initMachine?.researchEnabled), installedPeers: installedPeers(), packs: [...loadPacks(cwd).packs.keys()], discoverChecks: async () => (await discoverInitChecks(cwd)).names, shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
1151
1180
  } finally { rl.close(); }
1152
1181
  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; }
1153
1182
  requestedProfile = result.answers.profile; request = result.answers.request; asked = Object.keys(request.values).length > 0; shadow = result.answers.shadow; releaseGuard = result.answers.releaseGuard;
@@ -1251,9 +1280,10 @@ const commands: Record<string, () => Promise<void> | void> = {
1251
1280
  const { parseGuidanceCommand, validateGuidancePageReply, validateGuidanceDiffReply, validateGuidanceReceipt, renderGuidance, renderGuidanceReceipt } = await import("./guidance.ts");
1252
1281
  const { parseGuidanceVariantV1, GUIDANCE_RECORD_MAX_BYTES } = await import("../hub/guidance-variants.ts");
1253
1282
  const { parseGuidanceProbeSubcommand, parseGuidanceProbeRegistration, GUIDANCE_PROBE_REGISTRATION_BYTES,
1254
- parseGuidanceProbePublicReceipt, parseGuidanceProbePublicStatus } = await import("../hub/guidance-probes.ts");
1283
+ parseGuidanceProbePublicReceipt, parseGuidanceProbePublicStatus, parseGuidanceProbeReceiptExport } = await import("../hub/guidance-probes.ts");
1284
+ const { guidanceProbeStatusLines } = await import("../ui/guidance-view.ts");
1255
1285
  let probeCommand;
1256
- try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail("invalid guidance probe command; use probe register, start, show or cancel with the documented bounded arguments"); }
1286
+ try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail(guidanceProbeUsage(args)); }
1257
1287
  if (probeCommand) {
1258
1288
  if (liveTest) return fail("live-test cannot perform guidance probe operations as the person; use a current person or configured conductor session");
1259
1289
  let registration: ReturnType<typeof parseGuidanceProbeRegistration> | undefined;
@@ -1273,9 +1303,11 @@ const commands: Record<string, () => Promise<void> | void> = {
1273
1303
  const hub = await connect();
1274
1304
  try {
1275
1305
  if (!hub.features.includes("guidance_probes")) return fail("running hub lacks guidance_probes; upgrade and restart the hub, then retry ahub guidance");
1306
+ if (probeCommand.op === "receipts" && !hub.features.includes("guidance_probe_receipts")) return fail("running hub lacks guidance_probe_receipts; upgrade and restart the hub, then retry ahub guidance probe receipts");
1276
1307
  const request = probeCommand.op === "register" ? { t: "guidance_probe_register", registration: registration! }
1277
1308
  : probeCommand.op === "start" ? { t: "guidance_probe_start", id: probeCommand.id, revision: probeCommand.revision, ...(probeCommand.variantId ? { variantId: probeCommand.variantId } : {}) }
1278
1309
  : probeCommand.op === "cancel" ? { t: "guidance_probe_cancel", id: probeCommand.id, revision: probeCommand.revision }
1310
+ : probeCommand.op === "receipts" ? { t: "guidance_probe_receipts", id: probeCommand.id }
1279
1311
  : { t: "guidance_probe_show", id: probeCommand.id };
1280
1312
  const result = await hub.request(request);
1281
1313
  if (result.ok !== true) {
@@ -1283,7 +1315,12 @@ const commands: Record<string, () => Promise<void> | void> = {
1283
1315
  const nextStep = probeCommand.op === "register" ? "" : `; inspect ahub guidance probe show --id ${probeCommand.id} before any explicit retry`;
1284
1316
  return fail(`${detail}${nextStep}`);
1285
1317
  }
1286
- if (probeCommand.op === "show") {
1318
+ if (probeCommand.op === "receipts") {
1319
+ const exported = parseGuidanceProbeReceiptExport(result.receipts);
1320
+ if (!exported) return fail("guidance probe receipts are malformed or fail their digest check; inspect retained probe state before relying on them");
1321
+ if (args.includes("--json")) console.log(JSON.stringify(exported, null, 2));
1322
+ else for (const line of guidanceProbeStatusLines(exported)) console.log(terminalText(line));
1323
+ } else if (probeCommand.op === "show") {
1287
1324
  const status = parseGuidanceProbePublicStatus(result.status);
1288
1325
  if (!status) return fail("guidance probe status is malformed; refresh its id and current task context");
1289
1326
  if (args.includes("--json")) console.log(JSON.stringify(status, null, 2));
@@ -1471,11 +1508,11 @@ const commands: Record<string, () => Promise<void> | void> = {
1471
1508
  const shown = await hub.request({ t: "queue", op: "show", id });
1472
1509
  if (!shown.ok) fail(shown.error,shown.refusalAudited===true,shown.authorityRefused);
1473
1510
  if (options.json) return console.log(JSON.stringify(shown.delivery, null, 2));
1474
- return printOutput(renderQueueShow(shown.delivery, options.columns, Date.now()), options.color);
1511
+ return printOutput(renderQueueShow(shown.delivery, options.columns, Date.now(), cwd), options.color);
1475
1512
  }
1476
1513
  const { one, rest: extra } = takeFlags(flags, ["--action", "--reason", "--revision"], []);
1477
1514
  const rawRevision = one["--revision"], parsedRevision = rawRevision === undefined ? undefined : Number(rawRevision);
1478
- if (extra.length || !["completed", "retry", "discard"].includes(one["--action"] ?? "") || !one["--reason"]?.trim() || (rawRevision !== undefined && (!/^\d+$/.test(rawRevision) || !Number.isSafeInteger(parsedRevision)))) fail("usage: ahub queue resolve <id> --action completed|retry|discard --reason <text> [--revision N]");
1515
+ if (!queueResolveArgsValid(one["--action"], one["--reason"], rawRevision, extra)) fail("usage: ahub queue resolve <id> --action completed|retry|discard --reason <text> [--revision N]");
1479
1516
  let revision = parsedRevision;
1480
1517
  if (revision === undefined) {
1481
1518
  const shown = await hub.request({ t: "queue", op: "show", id });
@@ -1485,7 +1522,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1485
1522
  const result = await hub.request({ t: "queue", op: "resolve", id, revision, action: one["--action"], reason: one["--reason"] });
1486
1523
  if (!result.ok) fail(result.error,result.refusalAudited===true,result.authorityRefused);
1487
1524
  if (options.json) console.log(JSON.stringify(result.delivery, null, 2));
1488
- else printOutput(renderQueueShow(result.delivery, options.columns, Date.now()), options.color);
1525
+ else printOutput(renderQueueShow(result.delivery, options.columns, Date.now(), cwd), options.color);
1489
1526
  } finally { hub.close(); }
1490
1527
  },
1491
1528
 
@@ -1566,7 +1603,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1566
1603
  const res = await hub.request({ t: "budget", ...(set ? { set } : {}) });
1567
1604
  hub.close();
1568
1605
  if (!res.ok) fail(res.error);
1569
- const data = { budget: res.budget, ...(res.peers ? { peers: res.peers } : {}), gate: res.gate };
1606
+ const data = { budget: res.budget, ...(res.peers ? { peers: res.peers } : {}), ...(res.review ? { review: res.review } : {}), gate: res.gate };
1570
1607
  if (options.json) return console.log(JSON.stringify(data, null, 2));
1571
1608
  printOutput(renderBudget(data, options.columns, Date.now(), options.full), options.color);
1572
1609
  },
@@ -1717,12 +1754,14 @@ const commands: Record<string, () => Promise<void> | void> = {
1717
1754
  } catch (error) { return fail(`cannot register ${isUrl ? "that URL" : target}: ${(error as Error).message}`); }
1718
1755
  const projections = new TextProjections({ cwd, stateDir, config: config.text_projection ?? {}, deny: config.local.deny, readAllow: config.local.read_allow, log: line => console.error(line) });
1719
1756
  const extension = /\.[A-Za-z0-9]{1,16}$/.exec(isUrl ? new URL(origin).pathname : origin)?.[0] ?? "";
1757
+ let converted: ProjectedText | undefined;
1720
1758
  const verdict = screenRegistration({ bytes, kind, ...(absolute ? { path: absolute, typedPath: resolve(cwd, target) } : {}) }, {
1721
1759
  piiPaths: config.pii?.paths ?? [], piiPatterns: currentRouting(cwd).signals.pii_patterns, cwd, matchesPolicy,
1722
- project: data => extension ? projections.projectBytes(join(cwd, `source${extension.toLowerCase()}`), data)?.text : undefined,
1760
+ project: data => { converted = extension ? projections.projectBytes(join(cwd, `source${extension.toLowerCase()}`), data) : undefined; return converted?.text; },
1723
1761
  });
1762
+ const projection = sourceProjectionReceipt(bytes, verdict.text, converted ? { extension: extension.toLowerCase(), value: converted } : undefined);
1724
1763
  let added;
1725
- try { added = registry.add({ bytes, kind, origin, private: verdict.private, ...(verdict.text !== undefined ? { text: verdict.text } : {}) }); }
1764
+ try { added = registry.add({ bytes, kind, origin, private: verdict.private, ...(verdict.text !== undefined ? { text: verdict.text } : {}), ...(projection ? { projection } : {}) }); }
1726
1765
  catch (error) { return fail(`cannot register ${isUrl ? "that URL" : target}: ${(error as Error).message}`); }
1727
1766
  const meta = registry.get(added.id);
1728
1767
  if (!meta) return fail(`the record for ${added.id} cannot be read after it was registered; inspect ${join(stateDir, "sources")}`);
@@ -1752,24 +1791,17 @@ const commands: Record<string, () => Promise<void> | void> = {
1752
1791
  const present = outputOptions(split.flags); // before any request: an invalid --color must refuse before a mutation is sent
1753
1792
  const parsed = parseStudyArgs(split.operands);
1754
1793
  if ("usage" in parsed) return fail(parsed.usage);
1755
- const contract = (file: string): unknown => {
1756
- // One descriptor decides everything: opened non-blocking and without following a final symlink (a FIFO would otherwise block the open), checked to be a regular file with fstat, and
1757
- // read for at most the cap plus one byte, so a file that grows or is replaced after the check, or a device that reports size zero, cannot exhaust memory or hang this process.
1758
- const cap = 64 * 1024;
1759
- let text: string;
1760
- try {
1761
- const fd = openSync(resolve(invokedFrom, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1762
- try {
1763
- if (!fstatSync(fd).isFile()) return fail("the contract file is not a regular file");
1764
- const bytes = Buffer.alloc(cap + 1); let got = 0;
1765
- while (got < bytes.length) { const n = readSync(fd, bytes, got, bytes.length - got, null); if (!n) break; got += n; }
1766
- if (got > cap) return fail("the contract file is over 64 KiB");
1767
- text = bytes.subarray(0, got).toString("utf8");
1768
- } finally { closeSync(fd); }
1769
- }
1770
- catch { return fail("cannot read the contract file"); }
1771
- try { return JSON.parse(text); } catch { return fail("the contract file is not valid JSON"); }
1772
- };
1794
+
1795
+ if (parsed.op === "evidence") return showToolText(data => renderStudyEvidence(data, present.columns), await taskOp("hub_evidence_read", { id: parsed.id, ...(parsed.revision === undefined ? {} : { revision: parsed.revision }) }), present);
1796
+ if (parsed.op === "evidence_inventory") return showToolText(data => renderStudyEvidence(data, present.columns), await taskOp("study_evidence", { taskId: parsed.taskId }), present);
1797
+ if (parsed.op === "check") {
1798
+ const manifest = parseSynthesisManifest(contract(parsed.file, "manifest"));
1799
+ if (manifest.taskId !== parsed.taskId) return fail("synthesis manifest names another task; refresh its task binding and retry");
1800
+ const text = await taskOp("study_check", { taskId: parsed.taskId, manifest });
1801
+ showToolText(data => renderSynthesisReadiness(data, present.columns), text, present);
1802
+ if (JSON.parse(text).status !== "ready") process.exitCode = 1;
1803
+ return;
1804
+ }
1773
1805
  if (parsed.op === "experiments") {
1774
1806
  // A read of the records Tasks keeps (hub_experiment_show): it runs no command and reads no file, and the hub blanks a private record itself.
1775
1807
  const args = parsed.attempt ? { attemptId: parsed.attempt, ...(parsed.eventsAfter === undefined ? {} : { eventAfter: parsed.eventsAfter }) } : parsed.plan ? { planHash: parsed.plan, baselineAttemptId: parsed.baseline, variantAttemptId: parsed.variant } : { campaignId: parsed.campaign, ...(parsed.after === undefined ? {} : { after: parsed.after }) };
@@ -1895,6 +1927,22 @@ const commands: Record<string, () => Promise<void> | void> = {
1895
1927
  /** The human form (#814). Each site keeps its own `if (present.json) console.log(JSON.stringify(...))`, so the JSON branch stays visible to the guard test. */
1896
1928
  const human = (render: (data: any, columns?: number, now?: number) => Span[][], data: unknown) => printOutput(render(data, present!.columns, Date.now()), present!.color);
1897
1929
  const sub = args[0], id = args[1] === undefined ? undefined : Number(args[1]);
1930
+ if (sub === "configure") {
1931
+ const parsed = takeFlags(args.slice(1), ["--mode", "--required-checks"], []);
1932
+ if (parsed.rest.length || !Object.keys(parsed.one).length || ["--mode", "--required-checks"].some(flag => args.filter(arg => arg === flag).length > 1)
1933
+ || parsed.one["--mode"] !== undefined && !["off", "advise"].includes(parsed.one["--mode"]))
1934
+ fail("usage: ahub sdlc configure [--mode off|advise] [--required-checks check,lint]");
1935
+ const hub = await connect();
1936
+ try {
1937
+ const result = await hub.request({ t: "sdlc", op: "configure", instructionClaim: true,
1938
+ ...(parsed.one["--mode"] === undefined ? {} : { mode: parsed.one["--mode"] }),
1939
+ ...(parsed.one["--required-checks"] === undefined ? {} : { required_checks: parsed.one["--required-checks"] === "" ? [] : parsed.one["--required-checks"].split(",").map(name => name.trim()) }) });
1940
+ if (!result.ok) fail(/unknown SDLC operation|does not know/.test(String(result.error)) ? "running hub does not support instructed SDLC configuration; upgrade and restart it first" : result.error);
1941
+ const { rid: _transportId, ...receipt } = result;
1942
+ if (present!.json) console.log(JSON.stringify(receipt, null, 2)); else human(renderSdlcConfiguration, receipt);
1943
+ } finally { hub.close(); }
1944
+ return;
1945
+ }
1898
1946
  if (sub === "authorize-release") {
1899
1947
  if (args.length !== 2 || !validReleaseVersion(args[1])) fail("usage: ahub sdlc authorize-release <version>");
1900
1948
  const result = hubGitSync(["rev-parse", "--verify", "HEAD"], { cwd, env: hubGitEnv(process.env, { repositoryIsolation: true }), encoding: "utf8", timeout: 2000 });
@@ -1939,6 +1987,59 @@ const commands: Record<string, () => Promise<void> | void> = {
1939
1987
  finally { hub?.close(); }
1940
1988
  return;
1941
1989
  }
1990
+ if (sub === "survey") {
1991
+ const action = args[1];
1992
+ if (action === "start") {
1993
+ const flags = takeFlags(args.slice(2), ["--focus"], []);
1994
+ if (flags.rest.length || args.filter(arg => arg === "--focus").length > 1 || flags.one["--focus"] !== undefined && !(SURVEY_FOCUS as readonly string[]).includes(flags.one["--focus"])) fail("usage: ahub sdlc survey start [--focus bugs|tests|debt|deps|dx|docs]");
1995
+ const hub = await connect();
1996
+ try {
1997
+ const reply = await hub.request({ t: "sdlc", op: "survey-start", ...(flags.one["--focus"] === undefined ? {} : { focus: flags.one["--focus"] }) }, 60_000);
1998
+ if (!reply.ok) fail(/unknown SDLC operation|does not know/.test(String(reply.error)) ? "running hub does not support advisor surveys; upgrade and restart it first" : reply.error);
1999
+ const receipt = { task: reply.task, survey: reply.survey, ref: reply.ref, ...(reply.focus === undefined ? {} : { focus: reply.focus }) };
2000
+ if (present!.json) console.log(JSON.stringify(receipt, null, 2)); else human(renderSdlcSurvey, receipt);
2001
+ } finally { hub.close(); }
2002
+ return;
2003
+ }
2004
+ if (action === "show" && args.length === 3 && /^[1-9]\d*$/.test(args[2]!) && Number.isSafeInteger(Number(args[2]))) {
2005
+ const hub = await connect();
2006
+ try {
2007
+ const reply = await hub.request({ t: "sdlc", op: "survey-show", id: Number(args[2]) });
2008
+ if (!reply.ok) fail(reply.error);
2009
+ if (present!.json) console.log(JSON.stringify(reply.survey ?? null, null, 2)); else human(renderSdlcSurvey, reply.survey);
2010
+ } finally { hub.close(); }
2011
+ return;
2012
+ }
2013
+ fail("usage: ahub sdlc survey start [--focus bugs|tests|debt|deps|dx|docs] | ahub sdlc survey show <task>");
2014
+ }
2015
+ if (sub === "audit") {
2016
+ // #1403 A4: `audit start [--profile quick|standard] [--since <ref>]` files the read-only audit task and seeds its ledger; `audit show [<audit>]` reads the newest or the named one.
2017
+ const action = args[1];
2018
+ if (action === "start") {
2019
+ const flags = takeFlags(args.slice(2), ["--profile", "--since"], []);
2020
+ if (flags.rest.length || (flags.one["--profile"] !== undefined && !["quick", "standard"].includes(flags.one["--profile"]))) fail("usage: ahub sdlc audit start [--profile quick|standard] [--since <ref>]");
2021
+ const hub = await connect();
2022
+ try {
2023
+ const reply = await hub.request({ t: "sdlc", op: "audit-start", ...(flags.one["--profile"] !== undefined ? { profile: flags.one["--profile"] } : {}), ...(flags.one["--since"] !== undefined ? { since: flags.one["--since"] } : {}) }, 60_000);
2024
+ if (!reply.ok) fail(/unknown SDLC operation|does not know/.test(String(reply.error)) ? `${reply.error}; the running hub does not support security audits; upgrade agent-hub and run ahub restart before retrying` : reply.error);
2025
+ if (present!.json) console.log(JSON.stringify({ task: reply.task, audit: reply.audit, units: reply.units, planned: reply.planned, carried: reply.carried, partial: reply.partial, ref: reply.ref }, null, 2));
2026
+ else console.log(`task #${reply.task}: security audit ${reply.audit} started at ${String(reply.ref).slice(0, 12)}, ${reply.units} units (${reply.planned} planned, ${reply.carried} carried over)${reply.partial ? ", partial" : ""}`);
2027
+ } finally { hub.close(); }
2028
+ return;
2029
+ }
2030
+ if (action === "show") {
2031
+ const given = args[2] === undefined ? undefined : Number(args[2]);
2032
+ if (args.length > 3 || given !== undefined && (!Number.isSafeInteger(given) || given <= 0)) fail("usage: ahub sdlc audit show [<audit>]");
2033
+ const hub = await connect();
2034
+ try {
2035
+ const reply = await hub.request({ t: "sdlc", op: "audit-show", ...(given !== undefined ? { id: given } : {}) }, 30_000);
2036
+ if (!reply.ok) fail(reply.error);
2037
+ if (present!.json) console.log(JSON.stringify(reply.audit ?? null, null, 2)); else human(renderSdlcAudit, reply);
2038
+ } finally { hub.close(); }
2039
+ return;
2040
+ }
2041
+ fail("usage: ahub sdlc audit start [--profile quick|standard] [--since <ref>] | ahub sdlc audit show [<audit>]");
2042
+ }
1942
2043
  if (sub === "queue" || sub === "release") {
1943
2044
  const repo = args[1], liveIssues = args.slice(2).map(Number);
1944
2045
  if (!repo || args.length > 34 || (sub === "queue" && args.length !== 2) || liveIssues.some(id => !Number.isSafeInteger(id) || id <= 0)) fail("usage: ahub sdlc queue <owner/repository> | release <owner/repository> [live-issue...]");
@@ -2086,10 +2187,14 @@ const commands: Record<string, () => Promise<void> | void> = {
2086
2187
  }
2087
2188
  if (sub === "claim") {
2088
2189
  // #901: a person's verdict on one declared plan claim. The claim is named by its 1-based slot and its text is never typed, stored or printed here.
2089
- const { one, rest: positional } = takeFlags(rest, ["--model", "--model-said"], []);
2090
- if (positional.length !== 3 || !/^[1-9]\d*$/.test(positional[0]!) || !/^[1-9]\d*$/.test(positional[1]!) || !["supported", "unsupported", "unclear"].includes(positional[2]!)) fail("usage: ahub task claim <id> <slot> <supported|unsupported|unclear> [--model <label>] [--model-said <supported|unsupported|unclear>]");
2091
- const reply = JSON.parse(await taskOp("claim_verdict", { id: Number(positional[0]), slot: Number(positional[1]), verdict: positional[2], ...(one["--model"] === undefined ? {} : { model: one["--model"] }), ...(one["--model-said"] === undefined ? {} : { modelVerdict: one["--model-said"] }) })) as { task: number; recorded?: { slot: number; verdict: string; model?: string; modelVerdict?: string } };
2092
- return console.log(`task #${reply.task}: claim ${reply.recorded?.slot} recorded as ${reply.recorded?.verdict}${reply.recorded?.model ? ` (model ${reply.recorded.model}` : ""}${reply.recorded?.modelVerdict ? `${reply.recorded?.model ? ", " : " ("}model said ${reply.recorded.modelVerdict}` : ""}${reply.recorded?.model || reply.recorded?.modelVerdict ? ")" : ""}`);
2190
+ const { one, rest: positional } = takeFlags(rest, ["--model", "--model-said", "--manifest", "--disposition"], []);
2191
+ if (positional.length !== 3 || !/^[1-9]\d*$/.test(positional[0]!) || !/^[1-9]\d*$/.test(positional[1]!) || !["supported", "unsupported", "unclear"].includes(positional[2]!)
2192
+ || (one["--manifest"] === undefined) !== (one["--disposition"] === undefined)
2193
+ || one["--manifest"] !== undefined && !["resolved", "qualified"].includes(one["--disposition"]!)) fail("usage: ahub task claim <id> <slot> <supported|unsupported|unclear> [--model <label>] [--model-said <supported|unsupported|unclear>] [--manifest <manifest.json> --disposition <resolved|qualified>]");
2194
+ const manifest = one["--manifest"] === undefined ? undefined : parseSynthesisManifest(contract(one["--manifest"], "manifest"));
2195
+ if (manifest && manifest.taskId !== Number(positional[0])) return fail("synthesis manifest names another task; refresh its task binding and retry");
2196
+ const reply = JSON.parse(await taskOp("claim_verdict", { id: Number(positional[0]), slot: Number(positional[1]), verdict: positional[2], ...(one["--model"] === undefined ? {} : { model: one["--model"] }), ...(one["--model-said"] === undefined ? {} : { modelVerdict: one["--model-said"] }), ...(manifest === undefined ? {} : { manifest, synthesis: { manifestSha256: synthesisManifestHash(manifest), disposition: one["--disposition"] } }) })) as { task: number; recorded?: { slot: number; verdict: string; model?: string; modelVerdict?: string; synthesis?: { manifestSha256: string; disposition: string } } };
2197
+ return console.log(`task #${reply.task}: claim ${reply.recorded?.slot} recorded as ${reply.recorded?.verdict}${reply.recorded?.model ? ` (model ${reply.recorded.model}` : ""}${reply.recorded?.modelVerdict ? `${reply.recorded?.model ? ", " : " ("}model said ${reply.recorded.modelVerdict}` : ""}${reply.recorded?.model || reply.recorded?.modelVerdict ? ")" : ""}${reply.recorded?.synthesis ? `; synthesis ${reply.recorded.synthesis.disposition} @ ${reply.recorded.synthesis.manifestSha256}` : ""}`);
2093
2198
  }
2094
2199
  if (sub === "escalate") return console.log(await taskOp("task_escalate", { id: rest[0] }));
2095
2200
  if (sub === "assign") {
@@ -2136,8 +2241,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2136
2241
  const urgent = rest.includes("--urgent"), backlog = rest.includes("--backlog"), needsNetwork = rest.includes("--needs-network"), needsWorktree = rest.includes("--needs-worktree");
2137
2242
  const flags = takeFlags(rest.filter((a) => a !== "--urgent" && a !== "--backlog" && a !== "--needs-network" && a !== "--needs-worktree"), ["--owner", "--detail", "--class"], ["--path", "--after"]);
2138
2243
  const positional = !flags.one["--class"] && ((CLASSES as readonly string[]).includes(flags.rest[0] ?? "") || Object.hasOwn((() => { const config = projectConfig(); return resolveProfile(config.profile, config.profile_overrides); })().classes, flags.rest[0] ?? "")) && flags.rest.length > 1;
2139
- const cls = flags.one["--class"] ?? (positional ? flags.rest[0] : undefined);
2140
- const title = (positional ? flags.rest.slice(1) : flags.rest).join(" ");
2244
+ // #1433: a title word that is an option the command does not know, or -h, is refused before anything is filed. A lone `--` ends the options, so a title that starts with dashes can still be typed.
2245
+ const stray = unknownOption(flags.rest);
2246
+ if (stray) fail(unknownOptionRefusal(stray, "ahub task propose", subcommandUsage("task", "propose")));
2247
+ const textWords = withoutSeparator(flags.rest);
2248
+ const cls = flags.one["--class"] ?? (positional ? textWords[0] : undefined);
2249
+ const title = (positional ? textWords.slice(1) : textWords).join(" ");
2141
2250
  if (positional) console.error(`note: "${cls}" was taken as the class and left out of the title; use --class <c> when the title itself starts with that word`);
2142
2251
  console.log(await taskOp("hub_task_propose", { ...(cls ? { class: cls } : {}), title, owner: flags.one["--owner"], detail: flags.one["--detail"], ...(flags.many["--path"]?.length ? { refs: { paths: flags.many["--path"] } } : {}), ...(flags.many["--after"]?.length ? { after: flags.many["--after"].map(Number) } : {}), ...(urgent ? { urgent: true } : {}), ...(needsNetwork ? { needs_network: true } : {}), ...(needsWorktree ? { needs_worktree: true } : {}), ...(backlog ? { backlog: true } : {}) }));
2143
2252
  },
@@ -2148,15 +2257,19 @@ const commands: Record<string, () => Promise<void> | void> = {
2148
2257
  if (args.length !== 2 || !/^\d+$/.test(args[1]!)) fail("usage: ahub review brief <task id>");
2149
2258
  return console.log(await taskOp("review_brief", { id: Number(args[1]) }));
2150
2259
  }
2151
- const { one, many, rest } = takeFlags(args, ["--head", "--findings"], ["--unmet"]);
2260
+ const { one, many, rest } = takeFlags(args, ["--head", "--findings", "--security-pass"], ["--unmet"]);
2152
2261
  const [id, verdict, ...note] = rest;
2153
- if (!id || !verdict) fail("usage: ahub review <id> approved|changes_requested [note...] [--unmet <item>]... [--head <sha>] [--findings <json>] | ahub review brief <id>");
2262
+ if (!id || !verdict) fail("usage: ahub review <id> approved|changes_requested [note...] [--unmet <item>]... [--head <sha>] [--findings <json>] [--security-pass <json>] | ahub review brief <id>");
2263
+ let securityPass: unknown;
2264
+ if (one["--security-pass"] !== undefined) {
2265
+ try { securityPass = JSON.parse(one["--security-pass"]); } catch { fail("--security-pass must be a JSON object like {\"covered\":[\"unit\"],\"not_covered\":[]}"); }
2266
+ }
2154
2267
  let findings: unknown;
2155
2268
  if (one["--findings"] !== undefined) {
2156
2269
  try { findings = JSON.parse(one["--findings"]); } catch { fail("--findings must be a JSON array"); }
2157
2270
  if (!Array.isArray(findings)) fail("--findings must be a JSON array");
2158
2271
  }
2159
- console.log(await taskOp("hub_review", { id: Number(id), verdict, ...(one["--head"] ? { head: one["--head"] } : {}), note: note.join(" "), ...(findings === undefined ? {} : { findings }), ...(many["--unmet"]?.length ? { unmet: many["--unmet"] } : {}) }));
2272
+ console.log(await taskOp("hub_review", { id: Number(id), verdict, ...(one["--head"] ? { head: one["--head"] } : {}), note: note.join(" "), ...(findings === undefined ? {} : { findings }), ...(securityPass === undefined ? {} : { security_pass: securityPass }), ...(many["--unmet"]?.length ? { unmet: many["--unmet"] } : {}) }));
2160
2273
  },
2161
2274
 
2162
2275
  remember: async () => console.log(await taskOp("hub_remember", { text: freeText(args, "ahub remember <text>") })),
@@ -2491,7 +2604,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2491
2604
  if (sub === "list" && row.group !== group) console.log(`${group ? "\n" : ""}${group = row.group}`);
2492
2605
  const facts = [`from ${row.source}`, `file: ${settingText(row.fileValue === undefined ? row.pending ?? row.value : row.fileValue)}`, row.applies === "live" ? "applies at once" : row.applies === "next use" ? "applies at next use" : "pending restart", ...(row.restartReason ? [row.restartReason] : []), ...(row.note ? [row.note] : [])];
2493
2606
  console.log(` ${row.key.padEnd(width)} ${settingText(row.value).padEnd(valueWidth)} ${facts.join("; ")}`);
2494
- if (sub === "get") console.log(` ${row.label}; written to ${row.file}; takes ${row.type === "boolean" ? "true, false" : row.type === "integer" || row.type === "number" ? `a number from ${row.min ?? 0} to ${row.max ?? "the configured bound"}` : row.type === "peers" ? "a comma list of peer ids" : row.type === "roles" ? "up to two comma-separated catalog ids" : (row.values ?? []).join(", ")}${row.file === "this hub run" ? "" : ", or inherit to remove the machine-local value"}${row.risk === "raises" ? "; a dashboard needs a settings session (ahub ui --settings) to raise it" : ""}`);
2607
+ if (sub === "get") console.log(` ${row.label}; written to ${row.file}; takes ${row.type === "boolean" ? "true, false" : row.type === "number-or-off" ? `off or a number from ${row.min ?? 0} to ${row.max ?? "the configured bound"}` : row.type === "integer" || row.type === "number" ? `a number from ${row.min ?? 0} to ${row.max ?? "the configured bound"}` : row.type === "peers" ? "a comma list of peer ids" : row.type === "roles" ? "up to two comma-separated catalog ids" : (row.values ?? []).join(", ")}${row.file === "this hub run" ? "" : ", or inherit to remove the machine-local value"}${row.risk === "raises" ? "; a dashboard needs a settings session (ahub ui --settings) to raise it" : ""}`);
2495
2608
  }
2496
2609
  if (sub === "list" && view.pendingRestart?.length) console.log(`\npending restart: ${view.pendingRestart.map((entry: { key: string }) => entry.key).join(", ")}`);
2497
2610
  if (sub === "list" && view.undo) console.log(`\nahub settings undo puts back the last write (${view.undo})`);
@@ -2587,6 +2700,27 @@ const commands: Record<string, () => Promise<void> | void> = {
2587
2700
  process.stdout.write(short ? text : text + "\n");
2588
2701
  },
2589
2702
 
2703
+ // #1411 T2: the flow roles the running hub settled (defaults, overrides, ceilings), resolved from a worktree like every command.
2704
+ roles: async () => {
2705
+ const options = outputOptions();
2706
+ if (outputArguments().length) fail("usage: ahub roles [--json]");
2707
+ // A task worktree has no .agenthub of its own, and projectContext deliberately never joins it to the main checkout's hub (#604). This read changes nothing,
2708
+ // so a linked worktree with no hub of its own reads the main worktree's hub, under the same identity.
2709
+ let target = { root: cwd, stateDir };
2710
+ if (!existsSync(join(cwd, ".agenthub"))) {
2711
+ const common = hubGitSync(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8", timeout: 3000 });
2712
+ const main = common.status === 0 ? dirname(common.stdout.trim()) : undefined;
2713
+ if (main && realPath(main) !== cwd && existsSync(join(main, ".agenthub"))) target = projectContext(main);
2714
+ }
2715
+ const hub = target.root === cwd ? await connect() : await ControlClient.connect(target.stateDir, identity.role === "tools"
2716
+ ? { role: "tools", peer: identity.peer, projectRoot: target.root } : { role: "console", projectRoot: target.root }, 3000);
2717
+ try {
2718
+ const { status } = await hub.request({ t: "status" });
2719
+ const view = rolesView(status);
2720
+ if (options.json) return console.log(JSON.stringify(view, null, 2));
2721
+ printOutput(renderRoles(view, options.columns), options.color);
2722
+ } finally { hub.close(); }
2723
+ },
2590
2724
  status: async () => {
2591
2725
  const options = outputOptions();
2592
2726
  if (args.includes("--all")) return printProjects(options);
@@ -2598,7 +2732,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2598
2732
  printOutput(renderStatus({ ...status, budget: quota.budget ?? {} }, options.columns, Date.now(), options.full), options.color);
2599
2733
  if (status.needs) { const pet = loadPetConfig(cwd); if (pet.enabled) console.log(renderPet(petView(status), false, pet.character)); }
2600
2734
  // #258: open long-term tasks and who holds them, as of this machine's last memory sync.
2601
- if (status.memoryProfile ? status.memoryProfile.state === "ready" : existsSync(join(hubHome(), "memory", "index.db"))) {
2735
+ if (status.memoryProfile ? status.memoryProfile.state === "ready" : memoryIndexExists(join(hubHome(), "memory"))) {
2602
2736
  try { const lines = await goalCommand(["list"], cwd); if (!lines.startsWith("no open")) console.log(`\nlong-term tasks\n${lines}`); } catch { /* memory unreadable: status goes on */ }
2603
2737
  }
2604
2738
  } finally { hub.close(); }
@@ -2700,6 +2834,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2700
2834
  try { const r = await hub.request({ t: "goal_link", goal, task: Number(task) }); if (!r.ok) throw new Error(String(r.error)); return String(r.text); }
2701
2835
  finally { hub.close(); }
2702
2836
  };
2837
+ // #1433: `goal new` takes its title from the words the flags leave, so `--help` or a mistyped flag would become the goal's title: refuse it before anything is written.
2838
+ if (args[0] === "new") {
2839
+ const titleWords = args.slice(1).filter((word, index, all) => !GOAL_NEW_FLAGS.includes(word) && !GOAL_NEW_VALUE_FLAGS.includes(all[index - 1] ?? ""));
2840
+ const stray = unknownOption(titleWords);
2841
+ if (stray) return fail(unknownOptionRefusal(stray, "ahub goal new", subcommandUsage("goal", "new")));
2842
+ }
2703
2843
  try { console.log(await goalCommand(args, cwd, { link, person: caller.role === "console" })); } catch (e) { fail((e as Error).message); }
2704
2844
  },
2705
2845
  research: () => {
@@ -3095,6 +3235,26 @@ const commands: Record<string, () => Promise<void> | void> = {
3095
3235
 
3096
3236
  try {
3097
3237
  for (const check of runtimePruneHealth()) row(check.ok, check.name, check.detail);
3238
+ // #1399: a project initialised by an older ahub keeps that version's instruction block until init runs again; doctor says so with the command.
3239
+ try {
3240
+ const stale = planInit(cwd).some(change => change.path === join(cwd, "AGENTS.md"));
3241
+ row(stale ? undefined : true, "hub instructions", // a warning, never a failure: doctor's exit code stays what it was for a project that has not refreshed yet
3242
+ stale ? `the managed block in AGENTS.md differs from this ahub version; preview with: cd ${cwd} && ahub init --dry-run; apply with: cd ${cwd} && ahub init --yes (text outside the markers is kept), then commit AGENTS.md` : "AGENTS.md managed block matches this ahub version");
3243
+ } catch (error) { row(false, "hub instructions", `AGENTS.md could not be checked: ${error instanceof Error ? error.message : "unknown error"}; run ahub init --dry-run to see why`); }
3244
+ // #1411 T2: a warning, never a failure, like the row above.
3245
+ try { const shared = sharedConfigRow(cwd); if (shared) row(shared.ok, "shared config", shared.detail); }
3246
+ catch (error) { row(undefined, "shared config", `could not be checked: ${error instanceof Error ? error.message : "unknown error"}`); }
3247
+ // #1408 R2: who holds conductor, planner and reviewer as the loader settled them, and a conductor the loader ignored. A warning, never a failure, like the rows above.
3248
+ try {
3249
+ const settled = loadConfig(cwd), scope = readInstanceRoleConfig(cwd), layers = readInstanceConfigLayers(cwd);
3250
+ const declared: Record<string, string[]> = {}, modes: Record<string, "tui" | "headless"> = {};
3251
+ // The start mode the loader reads: the raw peers.<peer>.start_mode, a later layer winning, so doctor and the loader cannot disagree for an instance peer.
3252
+ for (const layer of layers) { const peers = layer.raw.peers; if (peers && typeof peers === "object" && !Array.isArray(peers)) for (const [peer, block] of Object.entries(peers as Record<string, unknown>)) { const mode = block && typeof block === "object" ? (block as { start_mode?: unknown }).start_mode : undefined; if (mode === "tui" || mode === "headless") modes[peer] = mode; } }
3253
+ for (const layer of layers) if (layer.raw.roles && typeof layer.raw.roles === "object" && !Array.isArray(layer.raw.roles)) for (const [peer, list] of Object.entries(layer.raw.roles as Record<string, unknown>)) if (Array.isArray(list)) declared[peer] = list.filter((role): role is string => typeof role === "string");
3254
+ const result = rolesRow({ roles: settled.roles, declared: Object.keys(declared).length ? declared : undefined, startMode: peer => modes[peer],
3255
+ rostered: peer => rosterAllows(settled.roster, peer, settled.pi.enabled, scope.instances, scope.catalog) });
3256
+ row(result.ok, "roles", result.detail);
3257
+ } catch (error) { row(undefined, "roles", `could not be checked: ${error instanceof Error ? error.message : "unknown error"}`); }
3098
3258
  const catalog = loadRoleCatalog(cwd);
3099
3259
  for (const error of catalog.errors) row(false, "catalog role", `${error.id}: ${error.reason}`);
3100
3260
  try {
package/src/cli/model.ts CHANGED
@@ -21,7 +21,7 @@ export function projectModelStatus(value: unknown): RuntimeModelStatus | null {
21
21
  if (descriptor && "value" in descriptor) row[key] = descriptor.value;
22
22
  }
23
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;
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)", "observed (served)", "observed (session)"].includes(row.source)) || typeof row.pendingNextTurn !== "boolean") return null;
25
25
  let unsupported: RuntimeModelStatus["unsupported"];
26
26
  if (row.unsupported !== undefined) {
27
27
  if (!row.unsupported || typeof row.unsupported !== "object" || Array.isArray(row.unsupported)) return null;