@staix/agent-hub 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
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";
@@ -132,10 +135,11 @@ 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
137
  import { queueResolveArgsValid } from "../hub/person-command.ts";
135
- 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";
136
- import { renderHelp, configuredAcpHelp } from "./help.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";
137
140
  import { renderBacklogResult, renderGroom, renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow, renderTaskCancel, renderTaskShow } from "./task-output.ts";
138
- 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";
139
143
  import { renderTailEvent } from "./tail-render.ts";
140
144
  import { archiveProblem, archiveState, damagedState, failureText, MANIFEST, planReset, resetLines, resetRuntime, startState, type ResetPlan } from "./reset.ts";
141
145
 
@@ -224,10 +228,11 @@ try {
224
228
  } else nativeSelection = instanceLaunchArguments(given, rest, declaredInstances);
225
229
  } catch (error) { fail(startupDiagnostic(error)); }
226
230
  const selectedInstance = nativeSelection.instance;
227
- // `ahub <command> -h` alone asks for that command's help instead of running it. Elsewhere `-h` may be message text
228
- // (`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.
229
233
  const asksHelp = (a: string | undefined) => a === "--help" || a === "-h";
230
- 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;
231
236
  const args = cmd === "help" && given !== "help" && !asksHelp(given) ? [given] : nativeSelection.args;
232
237
 
233
238
  /** Resolve a named peer only against this project's current trusted declarations. */
@@ -383,7 +388,7 @@ function showToolText(render: (data: any, columns?: number, now?: number) => Spa
383
388
  if (present.json) return console.log(text);
384
389
  printOutput(render(data, present.columns, Date.now()), present.color);
385
390
  }
386
- 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"];
387
392
  function sdlcOperands(): string[] { return SDLC_READ.includes(args[0] ?? "") ? outputArguments() : args; }
388
393
  function printOutput(lines: Span[][], color: boolean): void {
389
394
  for (const line of lines) console.log(paint(line, color));
@@ -575,6 +580,8 @@ async function taskOp(op: string, a: Record<string, unknown>, throwOnError = fal
575
580
  const hub = connection ?? await connect();
576
581
  try {
577
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");
578
585
  const res = await hub.request({ t: "task", op, args: a }, timeoutMs ?? (op === "github_import" ? 60_000 : 30_000));
579
586
  if (!res.ok) {
580
587
  if (throwOnError) throw new Error(res.error);
@@ -879,8 +886,29 @@ const LOCAL_OPERATION_ARGS: Record<string, () => void> = {
879
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); },
880
887
  };
881
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
+
882
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.
883
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"];
884
912
  const commands: Record<string, () => Promise<void> | void> = {
885
913
  upgrade: () => upgrade("upgrade"),
886
914
  restart: () => upgrade("restart"),
@@ -1148,7 +1176,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1148
1176
  let result: Awaited<ReturnType<typeof runInitPrompt>>;
1149
1177
  try {
1150
1178
  result = await runInitPrompt({ ask, print: line => console.log(terminalText(line)) },
1151
- { ...(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);
1152
1180
  } finally { rl.close(); }
1153
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; }
1154
1182
  requestedProfile = result.answers.profile; request = result.answers.request; asked = Object.keys(request.values).length > 0; shadow = result.answers.shadow; releaseGuard = result.answers.releaseGuard;
@@ -1255,7 +1283,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1255
1283
  parseGuidanceProbePublicReceipt, parseGuidanceProbePublicStatus, parseGuidanceProbeReceiptExport } = await import("../hub/guidance-probes.ts");
1256
1284
  const { guidanceProbeStatusLines } = await import("../ui/guidance-view.ts");
1257
1285
  let probeCommand;
1258
- try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail("invalid guidance probe command; use probe register, start, show, receipts or cancel with the documented bounded arguments"); }
1286
+ try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail(guidanceProbeUsage(args)); }
1259
1287
  if (probeCommand) {
1260
1288
  if (liveTest) return fail("live-test cannot perform guidance probe operations as the person; use a current person or configured conductor session");
1261
1289
  let registration: ReturnType<typeof parseGuidanceProbeRegistration> | undefined;
@@ -1575,7 +1603,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1575
1603
  const res = await hub.request({ t: "budget", ...(set ? { set } : {}) });
1576
1604
  hub.close();
1577
1605
  if (!res.ok) fail(res.error);
1578
- 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 };
1579
1607
  if (options.json) return console.log(JSON.stringify(data, null, 2));
1580
1608
  printOutput(renderBudget(data, options.columns, Date.now(), options.full), options.color);
1581
1609
  },
@@ -1726,12 +1754,14 @@ const commands: Record<string, () => Promise<void> | void> = {
1726
1754
  } catch (error) { return fail(`cannot register ${isUrl ? "that URL" : target}: ${(error as Error).message}`); }
1727
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) });
1728
1756
  const extension = /\.[A-Za-z0-9]{1,16}$/.exec(isUrl ? new URL(origin).pathname : origin)?.[0] ?? "";
1757
+ let converted: ProjectedText | undefined;
1729
1758
  const verdict = screenRegistration({ bytes, kind, ...(absolute ? { path: absolute, typedPath: resolve(cwd, target) } : {}) }, {
1730
1759
  piiPaths: config.pii?.paths ?? [], piiPatterns: currentRouting(cwd).signals.pii_patterns, cwd, matchesPolicy,
1731
- 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; },
1732
1761
  });
1762
+ const projection = sourceProjectionReceipt(bytes, verdict.text, converted ? { extension: extension.toLowerCase(), value: converted } : undefined);
1733
1763
  let added;
1734
- 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 } : {}) }); }
1735
1765
  catch (error) { return fail(`cannot register ${isUrl ? "that URL" : target}: ${(error as Error).message}`); }
1736
1766
  const meta = registry.get(added.id);
1737
1767
  if (!meta) return fail(`the record for ${added.id} cannot be read after it was registered; inspect ${join(stateDir, "sources")}`);
@@ -1761,24 +1791,17 @@ const commands: Record<string, () => Promise<void> | void> = {
1761
1791
  const present = outputOptions(split.flags); // before any request: an invalid --color must refuse before a mutation is sent
1762
1792
  const parsed = parseStudyArgs(split.operands);
1763
1793
  if ("usage" in parsed) return fail(parsed.usage);
1764
- const contract = (file: string): unknown => {
1765
- // 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
1766
- // 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.
1767
- const cap = 64 * 1024;
1768
- let text: string;
1769
- try {
1770
- const fd = openSync(resolve(invokedFrom, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1771
- try {
1772
- if (!fstatSync(fd).isFile()) return fail("the contract file is not a regular file");
1773
- const bytes = Buffer.alloc(cap + 1); let got = 0;
1774
- while (got < bytes.length) { const n = readSync(fd, bytes, got, bytes.length - got, null); if (!n) break; got += n; }
1775
- if (got > cap) return fail("the contract file is over 64 KiB");
1776
- text = bytes.subarray(0, got).toString("utf8");
1777
- } finally { closeSync(fd); }
1778
- }
1779
- catch { return fail("cannot read the contract file"); }
1780
- try { return JSON.parse(text); } catch { return fail("the contract file is not valid JSON"); }
1781
- };
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
+ }
1782
1805
  if (parsed.op === "experiments") {
1783
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.
1784
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 }) };
@@ -1904,6 +1927,22 @@ const commands: Record<string, () => Promise<void> | void> = {
1904
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. */
1905
1928
  const human = (render: (data: any, columns?: number, now?: number) => Span[][], data: unknown) => printOutput(render(data, present!.columns, Date.now()), present!.color);
1906
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
+ }
1907
1946
  if (sub === "authorize-release") {
1908
1947
  if (args.length !== 2 || !validReleaseVersion(args[1])) fail("usage: ahub sdlc authorize-release <version>");
1909
1948
  const result = hubGitSync(["rev-parse", "--verify", "HEAD"], { cwd, env: hubGitEnv(process.env, { repositoryIsolation: true }), encoding: "utf8", timeout: 2000 });
@@ -1948,6 +1987,59 @@ const commands: Record<string, () => Promise<void> | void> = {
1948
1987
  finally { hub?.close(); }
1949
1988
  return;
1950
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
+ }
1951
2043
  if (sub === "queue" || sub === "release") {
1952
2044
  const repo = args[1], liveIssues = args.slice(2).map(Number);
1953
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...]");
@@ -2095,10 +2187,14 @@ const commands: Record<string, () => Promise<void> | void> = {
2095
2187
  }
2096
2188
  if (sub === "claim") {
2097
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.
2098
- const { one, rest: positional } = takeFlags(rest, ["--model", "--model-said"], []);
2099
- 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>]");
2100
- 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 } };
2101
- 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}` : ""}`);
2102
2198
  }
2103
2199
  if (sub === "escalate") return console.log(await taskOp("task_escalate", { id: rest[0] }));
2104
2200
  if (sub === "assign") {
@@ -2145,8 +2241,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2145
2241
  const urgent = rest.includes("--urgent"), backlog = rest.includes("--backlog"), needsNetwork = rest.includes("--needs-network"), needsWorktree = rest.includes("--needs-worktree");
2146
2242
  const flags = takeFlags(rest.filter((a) => a !== "--urgent" && a !== "--backlog" && a !== "--needs-network" && a !== "--needs-worktree"), ["--owner", "--detail", "--class"], ["--path", "--after"]);
2147
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;
2148
- const cls = flags.one["--class"] ?? (positional ? flags.rest[0] : undefined);
2149
- 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(" ");
2150
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`);
2151
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 } : {}) }));
2152
2252
  },
@@ -2157,15 +2257,19 @@ const commands: Record<string, () => Promise<void> | void> = {
2157
2257
  if (args.length !== 2 || !/^\d+$/.test(args[1]!)) fail("usage: ahub review brief <task id>");
2158
2258
  return console.log(await taskOp("review_brief", { id: Number(args[1]) }));
2159
2259
  }
2160
- const { one, many, rest } = takeFlags(args, ["--head", "--findings"], ["--unmet"]);
2260
+ const { one, many, rest } = takeFlags(args, ["--head", "--findings", "--security-pass"], ["--unmet"]);
2161
2261
  const [id, verdict, ...note] = rest;
2162
- 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
+ }
2163
2267
  let findings: unknown;
2164
2268
  if (one["--findings"] !== undefined) {
2165
2269
  try { findings = JSON.parse(one["--findings"]); } catch { fail("--findings must be a JSON array"); }
2166
2270
  if (!Array.isArray(findings)) fail("--findings must be a JSON array");
2167
2271
  }
2168
- 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"] } : {}) }));
2169
2273
  },
2170
2274
 
2171
2275
  remember: async () => console.log(await taskOp("hub_remember", { text: freeText(args, "ahub remember <text>") })),
@@ -2500,7 +2604,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2500
2604
  if (sub === "list" && row.group !== group) console.log(`${group ? "\n" : ""}${group = row.group}`);
2501
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] : [])];
2502
2606
  console.log(` ${row.key.padEnd(width)} ${settingText(row.value).padEnd(valueWidth)} ${facts.join("; ")}`);
2503
- 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" : ""}`);
2504
2608
  }
2505
2609
  if (sub === "list" && view.pendingRestart?.length) console.log(`\npending restart: ${view.pendingRestart.map((entry: { key: string }) => entry.key).join(", ")}`);
2506
2610
  if (sub === "list" && view.undo) console.log(`\nahub settings undo puts back the last write (${view.undo})`);
@@ -2596,6 +2700,27 @@ const commands: Record<string, () => Promise<void> | void> = {
2596
2700
  process.stdout.write(short ? text : text + "\n");
2597
2701
  },
2598
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
+ },
2599
2724
  status: async () => {
2600
2725
  const options = outputOptions();
2601
2726
  if (args.includes("--all")) return printProjects(options);
@@ -2607,7 +2732,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2607
2732
  printOutput(renderStatus({ ...status, budget: quota.budget ?? {} }, options.columns, Date.now(), options.full), options.color);
2608
2733
  if (status.needs) { const pet = loadPetConfig(cwd); if (pet.enabled) console.log(renderPet(petView(status), false, pet.character)); }
2609
2734
  // #258: open long-term tasks and who holds them, as of this machine's last memory sync.
2610
- 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"))) {
2611
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 */ }
2612
2737
  }
2613
2738
  } finally { hub.close(); }
@@ -2709,6 +2834,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2709
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); }
2710
2835
  finally { hub.close(); }
2711
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
+ }
2712
2843
  try { console.log(await goalCommand(args, cwd, { link, person: caller.role === "console" })); } catch (e) { fail((e as Error).message); }
2713
2844
  },
2714
2845
  research: () => {
@@ -3110,6 +3241,20 @@ const commands: Record<string, () => Promise<void> | void> = {
3110
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
3111
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");
3112
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"}`); }
3113
3258
  const catalog = loadRoleCatalog(cwd);
3114
3259
  for (const error of catalog.errors) row(false, "catalog role", `${error.id}: ${error.reason}`);
3115
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;
package/src/cli/output.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ReviewGate, ReviewUnknownQuota } from "../hub/review-budget.ts";
2
+ import { quotaAccountReading } from "../hub/quota-account.ts";
1
3
  import { projectModelStatus } from "./model.ts";
2
4
  import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
3
5
  import type { QueueBackpressureStatus } from "../hub/queue-backpressure.ts";
@@ -46,7 +48,7 @@ export interface StatusOutput {
46
48
  tasks?: Record<string, number>; personRun?: number[]; models?: { backends?: any[] }; permissionDefaults?: any[]; deliveryError?: string; reviewInputHealth?: { state?: string; cause?: string | null }; crash?: string[];
47
49
  }
48
50
  /** `peers`: one note per peer that shows no number, and why (no quota, nothing read yet); absent from an older hub. */
49
- export interface BudgetOutput { budget: Record<string, any>; gate?: number; peers?: { peer: string; kind?: string; note: string }[] }
51
+ export interface BudgetOutput { budget: Record<string, any>; gate?: number; review?: { gate: ReviewGate; unknown_quota: ReviewUnknownQuota; rule: string }; peers?: { peer: string; kind?: string; note: string }[] }
50
52
  export interface RosterRow { peer: string; on: boolean; startMode: string; state: string; queued: number; tasks: number }
51
53
  export function renderRuntimeModels(models: readonly RuntimeModelStatus[], columns?: number): Span[][] {
52
54
  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);
@@ -59,6 +61,41 @@ export function renderRuntimeModels(models: readonly RuntimeModelStatus[], colum
59
61
  export function renderRoster(data: RosterRow[], columns?: number): Span[][] {
60
62
  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);
61
63
  }
64
+ /** #1411 T2: who holds which flow role as the running hub settled them, from its status reply. */
65
+ export interface RolesView {
66
+ peers: { peer: string; roles: string[] }[];
67
+ planner: { peers: string[]; source: string } | null;
68
+ reviewFallback: { required: boolean; sameFamily: string } | null;
69
+ }
70
+ export function rolesView(status: any): RolesView {
71
+ const off = new Set((Array.isArray(status?.roster) ? status.roster : []).filter((row: any) => row?.on === false).map((row: any) => row.peer));
72
+ const info = status?.roleInfo && typeof status.roleInfo === "object" ? status.roleInfo : {};
73
+ const peers = Object.keys(info).filter(peer => !off.has(peer)).sort()
74
+ .map(peer => ({ peer, roles: Array.isArray(info[peer]?.flowRoles) ? info[peer].flowRoles.map(String) : [] }));
75
+ const planner = Array.isArray(status?.planner?.peers) ? { peers: status.planner.peers.map(String), source: String(status.planner.source ?? "unknown") } : null;
76
+ const fallback = status?.reviewFallback;
77
+ const reviewFallback = fallback && typeof fallback.required === "boolean" ? { required: fallback.required, sameFamily: String(fallback.sameFamily ?? "fallback") } : null;
78
+ return { peers, planner, reviewFallback };
79
+ }
80
+ /** Who reviews when no pool reviewer can run, as routing decides it (src/hub/routing.ts assign()); an older hub sends no settings, so unknown. */
81
+ function reviewFallbackLine(view: RolesView): string {
82
+ const fallback = view.reviewFallback;
83
+ if (!fallback || !view.planner) return "unknown: this hub does not report it; upgrade the running hub";
84
+ if (fallback.required && fallback.sameFamily !== "never") return "the person (review.pool is set)";
85
+ const planners = view.planner.peers.join(", ");
86
+ if (!planners) return "the person (no planner)";
87
+ return fallback.sameFamily === "never"
88
+ ? `a planner of another family than the task's owner (${planners}), else the person`
89
+ : `a planner other than the task's owner (${planners}), another family first, else the person`;
90
+ }
91
+ export function renderRoles(view: RolesView, columns?: number): Span[][] {
92
+ return [
93
+ ...rows(["PEER", "ROLES"], view.peers.map(row => [span(row.peer, peerTone(row.peer), true), span(row.roles.length ? row.roles.join(", ") : "-", row.roles.length ? undefined : "muted")]), columns),
94
+ [],
95
+ ...lines(`planner: ${view.planner ? `${view.planner.peers.join(", ") || "nobody"} (${view.planner.source})` : "unknown"}`, columns),
96
+ ...lines(`when no reviewer can run: ${reviewFallbackLine(view)}`, columns),
97
+ ];
98
+ }
62
99
  export function outputWidth(env: { isTTY: boolean; columns?: number; COLUMNS?: string }): number | undefined {
63
100
  if (env.isTTY) return Math.max(80, Number.isFinite(env.columns) ? env.columns! : 80);
64
101
  return env.COLUMNS && /^[1-9][0-9]*$/.test(env.COLUMNS) && Number.isSafeInteger(Number(env.COLUMNS)) ? Number(env.COLUMNS) : undefined;
@@ -463,6 +500,7 @@ export function renderBoard(tasks: any[], columns?: number, now = Date.now(), fu
463
500
  }
464
501
  export function renderBudget(data: BudgetOutput, columns?: number, now = Date.now(), _full = false): Span[][] {
465
502
  const out: Span[][] = [];
503
+ if (data.review) out.push(...detail("Reviewer admission", data.review.rule, columns));
466
504
  // KIND names what the number is (#285): the provider's own (native), tokens the hub counted against a ceiling (count), or a person's (manual).
467
505
  // A window without a kind, from an older hub, is classified by `windowKind`. A fresh window that does not gate says so in STATE.
468
506
  const windows = Object.entries(data.budget).flatMap(([peer, b]) => (b.windows ?? []).map((w: any) => [span(peer, peerTone(peer)), span(w.id), span(`${Math.round(w.used * 100)}%`, "number"), span(typeof w.resetsAt === "number" ? relative(w.resetsAt, now) : "-", "muted"), span(windowKind({ id: w.id, source: w.source ?? "", kind: w.kind }), "muted"), span(w.source ?? "unknown", "muted"), span(typeof w.at === "number" ? relative(w.at, now) : "unknown", "muted"), span(w.stale ? "stale" : w.superseded ? "info only" : "fresh", w.stale ? "attention" : undefined)]));
@@ -471,6 +509,23 @@ export function renderBudget(data: BudgetOutput, columns?: number, now = Date.no
471
509
  // A peer with no number says why, in its own line, so a peer without quota is not mistaken for one that has not reported.
472
510
  for (const note of data.peers ?? []) out.push(...detail(note.peer, note.note, columns, peerTone(note.peer)));
473
511
  for (const [peer, b] of Object.entries(data.budget)) if (b.paused) out.push(...detail(`paused ${peer}`, `${b.paused.reason ?? "budget"}${typeof b.paused.resetsAt === "number" ? `; resumes ${relative(b.paused.resetsAt, now)}` : ""}`, columns, "attention"));
512
+ for (const [peer, b] of Object.entries(data.budget)) {
513
+ const info = b.paused ? quotaAccountReading(b.accountUsage) : undefined;
514
+ if (!info) continue;
515
+ const parts: string[] = [];
516
+ if (info.resetCreditsAvailable !== undefined) {
517
+ const expiry = info.resetCreditsExpireAt !== undefined ? `expires ${new Date(info.resetCreditsExpireAt).toISOString().split("T")[0]}`
518
+ : info.resetCreditsExpiryKnown ? "no expiry" : "expiry unknown";
519
+ parts.push(`${plural(info.resetCreditsAvailable, "reset credit")} available${info.resetCreditsAvailable ? ` (${expiry})` : ""}`);
520
+ }
521
+ parts.push(info.ordinaryUsageAllowed === undefined ? "ordinary usage unknown" : info.ordinaryUsageAllowed ? "ordinary usage allowed" : "ordinary usage not allowed");
522
+ const flag = (value: boolean | undefined) => value === undefined ? "unknown" : value ? "yes" : "no";
523
+ parts.push(`credits available: ${flag(info.hasCredits)}`, `unlimited credits: ${flag(info.unlimited)}`);
524
+ if (info.stale) parts.push("stale snapshot");
525
+ else if (info.ordinaryUsageAllowed === false && (info.hasCredits === true || info.unlimited === true)) parts.push("turns would use paid credits");
526
+ out.push(...detail(peer, parts.join("; "), columns, "attention"));
527
+ }
528
+
474
529
  return out;
475
530
  }
476
531
  function boardColumnContext(tasks: any[], allTasks: any[] | null): any[] {
@@ -10,7 +10,7 @@ import { relayModelIds } from "../models/relay.ts";
10
10
  import { buildPiLaunch } from "../pi/launch.ts";
11
11
 
12
12
  /** Read-only builtin preview. Native redaction uses the same launch builders as actual startup. */
13
- export function launcherPreview(tool: "claude" | "codex" | "kimi" | "pi" | "qwen" | "jcode", raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
13
+ export function launcherPreview(tool: string, raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
14
14
  const config = loadConfig(cwd);
15
15
  const selected = instanceLaunchArguments(tool, requestedInstance ? ["--as", requestedInstance, ...raw] : raw, config.instances);
16
16
  const args = selected.args.filter(arg => !["--print-command", "--dry-run", "--json"].includes(arg));