@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/hub/daemon.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { nativeReviewerQuota } from "../adapters/definitions/native-quota.ts";
1
2
  import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
2
3
  import { GuidanceProbeStore } from "./guidance-probe-store.ts";
3
- import { GuidanceProbeError, probeSessionGeneration } from "./guidance-probes.ts";
4
+ import { GuidanceProbeError, probeSessionGeneration, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
4
5
  import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
5
6
  import { publicDeliveryBodies } from "./delivery-public.ts";
6
7
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
@@ -71,6 +72,7 @@ import { loadPetConfig, PET_WINDOW_RETIRED_NOTICE, stripLegacyPetWindow } from "
71
72
  import { projectionConfig, TextProjections, type ProjectionConfig } from "./text-projection.ts";
72
73
  import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
73
74
  import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
75
+ import { gitAuditSource } from "./audit-source.ts";
74
76
  import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
75
77
  import { profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "./profiles.ts";
76
78
  import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
@@ -80,7 +82,7 @@ import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../ad
80
82
  import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
81
83
  import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
82
84
  import { jcodeMcpReady } from "../cli/jcode-mcp.ts";
83
- import { loadSdlc, readSpecEdit, sdlcGh } from "./sdlc.ts";
85
+ import { loadSdlc, readSpecEdit, sdlcGh, type SdlcConfig } from "./sdlc.ts";
84
86
  import { claudePeer as defaultChannelPeer, claudeStateFile, ownTerminalRow, pathEvidence, transcriptPersisted } from "./claude-state.ts";
85
87
  import { peerRosterConfig, rosterAllows, staleInstanceKey, type PeerRoster } from "./roster.ts";
86
88
  import { KNOWN_PEERS, OPTIONAL_PEERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS, isSupportedPeer, STARTABLE_PEERS, isStartablePeer } from "../adapters/registry.ts";
@@ -130,7 +132,7 @@ import { planFingerprint, registeredProjects, type UpgradePlan } from "../cli/up
130
132
  import { conductorRecoveryBinding } from "../cli/conductor-recovery.ts";
131
133
  import { createConfigEditor } from "./config-edit-host.ts";
132
134
  import { readEditable } from "./config-edit.ts";
133
- import { eventLog, readEvents, type HubEvent, type RoleIdentity } from "./events.ts";
135
+ import { eventLog, readEvents, turnModelFields, type HubEvent, type RoleIdentity } from "./events.ts";
134
136
  import { SpecTaskInspector } from "./specs-task.ts";
135
137
  import { KimiUsage, kimiSeedRows, type KimiRowAttribution, type KimiUsageScheduler } from "./kimi-usage.ts";
136
138
  import { KimiEventWriter } from "./kimi-events.ts";
@@ -168,6 +170,7 @@ import { isReviewerPrintPeer, reviewerNoVerdictLine, reviewerUnavailableReason,
168
170
  import type { OwnedInputContext } from "../adapters/claude-print-child.ts";
169
171
  import { createReviewerMcpSession, type ReviewerToolName } from "../adapters/reviewer-mcp.ts";
170
172
  import { reviewerPoolConfig } from "./reviewer-pool-config.ts";
173
+ import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewBudgetPolicyDescription, type ReviewGate, type ReviewUnknownQuota, reviewerAccountingIntegrity, reviewerAccountingRelevant } from "./review-budget.ts";
171
174
  import { reviewDiff } from "../adapters/claude-print.ts";
172
175
  import { Capture } from "../memory/capture.ts";
173
176
  import { DEFAULT_OMNIROUTE, OmniRoute, type OmniRouteConfig } from "../omniroute/client.ts";
@@ -210,6 +213,7 @@ import { TaskWorktrees, originVerdict } from "./task-worktree.ts";
210
213
  import { displayPath, shelfInsideRoot, partition, readWorktreeFacts, type ShelfRow } from "./worktree-shelf.ts";
211
214
  import { PrObservations, refreshPrStates, refreshTargets } from "./worktree-prs.ts";
212
215
  import { Bus, ReviewInputHandoffError } from "./bus.ts";
216
+ import { queueResolveChoices, queueResolveCommand } from "./person-command.ts";
213
217
  import { attribute, deliveryTask, type TaskAttribution } from "./attribution.ts";
214
218
  import { ACCEPTED_SETTLE_TIMEOUT_REASON, DeliveryJournal } from "./delivery-journal.ts";
215
219
  import { assertHubDbCompatible } from "./db-schema.ts";
@@ -243,6 +247,7 @@ import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf
243
247
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
244
248
 
245
249
  import { START_AGENTS_DEFAULT, checkStartAgents } from "./start-agents.ts";
250
+ import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
246
251
  import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, terminalTemplate, type PeerStartConfig, type StartMode } from "./start-mode.ts";
247
252
  import { hasKimiHubMcp } from "../cli/kimi-mcp.ts";
248
253
  import type { TerminalOpener } from "./terminal-open.ts";
@@ -254,7 +259,8 @@ import { CaptureStore, configuredPolicy, recordsEnabled, looksSecret, DEFAULT_LE
254
259
  import { memoryProjectKey } from "@staix/agent-mem";
255
260
  import { AGENT_MEM_VERSION, MEMORY_SPLIT_INCOMPLETE, memoryProjectFor, openProfileMemory, openProfileCandidates, MemoryProfileBinding, type UnboundMemoryProfileReceipt } from "./memory-profile.ts";
256
261
  import { syncMemory, createIntentBriefSource, createStandalonePolicy } from "@staix/agent-mem";
257
- import { SourceRegistry } from "./sources.ts";
262
+ import { SourceRegistry, SOURCE_UTF8_PROJECTION_VERSION, type SourceMeta } from "./sources.ts";
263
+ import { evidenceSnapshotKey, readEvidenceSource } from "./source-read.ts";
258
264
  import { MEMORY_READ_TOOLS, memoryRead, validateMemoryRead, sourceRead, validateSourceRead } from "./read-tools.ts";
259
265
  import { nativeRecall } from "../memory/recall.ts";
260
266
  import { promotionScreen, withoutPii, mentionsPrivatePath } from "./memory-policy.ts";
@@ -350,7 +356,7 @@ export interface HubConfig {
350
356
  /** Per-sender rate limits and repeat suppression for what agents send (issue #38). */
351
357
  limits: LimitsConfig;
352
358
  /** Reviewer choice from recorded review outcomes, once a reviewer has `min_reviews` of an implementer (issue #35). */
353
- review: { adaptive: boolean; min_reviews: number; pool?: string[]; rerotate?: boolean; same_family?: "fallback" | "never" };
359
+ review: { adaptive: boolean; min_reviews: number; pool?: string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number };
354
360
  /** After an unplanned stop, start Kimi, Pi and the local worker again with their recorded sessions (issue #37). */
355
361
  /** #489 H4: the five waits the upgrade coordinator reads from this project's config at the start of each wait; the daemon itself only validates and carries them. */
356
362
  recovery: { auto_resume_after_crash: boolean; reconnect_wait_s?: number; unmanaged_reconnect_wait_s?: number; control_timeout_s?: number; shutdown_wait_s?: number; terminal_idle_wait_s?: number };
@@ -421,7 +427,7 @@ export const DEFAULT_CONFIG: HubConfig = {
421
427
  terminal: { open: [] },
422
428
  start: { agents: [...START_AGENTS_DEFAULT] },
423
429
  limits: DEFAULT_LIMITS,
424
- review: { adaptive: false, min_reviews: 5 },
430
+ review: { adaptive: false, min_reviews: 5, gate: DEFAULT_REVIEW_GATE, unknown_quota: DEFAULT_REVIEW_UNKNOWN_QUOTA, max_minutes: DEFAULT_REVIEW_MAX_MINUTES },
425
431
  recovery: { auto_resume_after_crash: false, reconnect_wait_s: RECOVERY_RECONNECT_WAIT_SETTING.defaultValue, unmanaged_reconnect_wait_s: RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING.defaultValue, control_timeout_s: RECOVERY_CONTROL_TIMEOUT_SETTING.defaultValue, shutdown_wait_s: RECOVERY_SHUTDOWN_WAIT_SETTING.defaultValue, terminal_idle_wait_s: RECOVERY_TERMINAL_IDLE_WAIT_SETTING.defaultValue },
426
432
  capabilities: {},
427
433
  coordination: "advisory",
@@ -430,7 +436,7 @@ export const DEFAULT_CONFIG: HubConfig = {
430
436
  export { stateDirFor };
431
437
 
432
438
  /** Ids an external process may not claim: the console user and the adapters the daemon runs itself. */
433
- const READ_ONLY_HUB_TOOLS = new Set(["hub_guidance_list", "hub_guidance_show", "hub_lineage_show", "hub_visual_show", "hub_capabilities", "hub_inbox", "hub_send", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status", "hub_specs", "hub_supervision_list"]);
439
+ const READ_ONLY_HUB_TOOLS = new Set(["hub_guidance_list", "hub_guidance_show", "hub_lineage_show", "hub_visual_show", "hub_capabilities", "hub_inbox", "hub_send", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_evidence_read", "hub_status", "hub_specs", "hub_supervision_list"]);
434
440
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
435
441
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
436
442
 
@@ -471,7 +477,19 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
471
477
  const roles: Record<string, string[]> = { ...DEFAULT_ROLES };
472
478
  const conductor = { ...DEFAULT_CONFIG.conductor };
473
479
  const notices: string[] = [];
480
+ // #1063: what the layers declare after the adapter ceiling and before the #1408 eligibility drop. At most one conductor is checked on this map (as on main), so an eligible-ceiling kind that cannot conduct is refused, never ignored, and a conductor the ceiling never allowed does not count.
481
+ const declaredRoles: Record<string, string[]> = { ...DEFAULT_ROLES };
474
482
  let planner: string | string[] | undefined;
483
+ // #1408 R2: the conductor role needs an interactive session, so the loader reads each peer's effective start mode (config.local.json wins per peer) before it reads roles.
484
+ const startModes: Record<string, StartMode> = {};
485
+ for (const name of CONFIG_FILES) {
486
+ const raw = layers ? layers.find(layer => layer.name === name)?.raw : (() => { try { return JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")) as Record<string, unknown>; } catch { return undefined; } })();
487
+ const peers = raw?.peers;
488
+ if (peers && typeof peers === "object" && !Array.isArray(peers)) for (const [peer, block] of Object.entries(peers)) {
489
+ const mode = block && typeof block === "object" ? (block as { start_mode?: unknown }).start_mode : undefined;
490
+ if (mode === "tui" || mode === "headless") startModes[peer] = mode;
491
+ }
492
+ }
475
493
  for (const name of CONFIG_FILES) {
476
494
  let file: Record<string, unknown>;
477
495
  if (layers && !layers.some(layer => layer.name === name)) continue;
@@ -481,11 +499,13 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
481
499
  if (!file.roles || typeof file.roles !== "object" || Array.isArray(file.roles)) throw new Error("roles must be an object of peer role lists");
482
500
  for (const [peer, assigned] of Object.entries(file.roles)) {
483
501
  conductorPeer({ [peer]: assigned });
484
- const definition = definitionOf(peer), ceiling = definition?.routing?.allowedRoles;
485
502
  const declared = assigned as string[];
486
- // #525 R1: planner needs a kind that can plan (projection.plannerEligible); such an entry is dropped with the ceiling notice, never thrown.
487
- roles[peer] = (ceiling ? declared.filter(role => ceiling.includes(role)) : declared).filter(role => role !== "planner" || !definition || definition.projection?.plannerEligible === true);
488
- if (roles[peer]!.length !== declared.length) notices.push(`roles.${peer}: ignored roles outside the adapter ceiling`);
503
+ declaredRoles[peer] = adapterCeiling(peer, declared);
504
+ // #525 R1: planner needs a kind that can plan; #1408 R2: conductor needs an eligible kind in an interactive form. Such an entry is dropped with a notice, never thrown, and nobody else gains it.
505
+ // The builtin registry only, exactly as before: a project-configured ACP kind keeps the roles it is given (#525, #735).
506
+ const kept = applyRoleCeiling(peer, declared, startModes[peer]);
507
+ roles[peer] = kept.roles;
508
+ notices.push(...kept.notices);
489
509
  }
490
510
  }
491
511
  if (file.planner !== undefined) {
@@ -508,6 +528,7 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
508
528
  }
509
529
  }
510
530
  }
531
+ conductorPeer(declaredRoles);
511
532
  conductorPeer(roles);
512
533
  return { roles, conductor, ...(planner ? { planner } : {}), ...(notices.length ? { notices } : {}) };
513
534
  }
@@ -762,6 +783,12 @@ export interface DaemonOptions {
762
783
  /** Host-only bounds of the per-head CI watcher (#785 P1b); tests shorten them, never read from config or a tool. */
763
784
  ciWatch?: { deadlineMs?: number; pollMs?: number };
764
785
  checkoutBranch?: typeof mainCheckoutBranch;
786
+ /**
787
+ * Host-only fixture lifecycle config (#1411): the daemon runs this instead of reading `.agenthub/sdlc.toml`,
788
+ * and reports it as the file's value too, so a fixture at this checkout neither runs the repository's own
789
+ * mode nor shows a restart pending against a file it is ignoring. Never read from project config or control input.
790
+ */
791
+ sdlc?: SdlcConfig;
765
792
  /** Host-only admission transport; never selected by project config or tools. */
766
793
  releaseHostAdmission?: (cwd: string) => Promise<ReleaseHostAdmission>;
767
794
  /** Host-only (#285): Kimi's data home for its wire-log usage reader; default `KIMI_CODE_HOME`, else `~/.kimi-code`. Never read from config or tools. */
@@ -919,8 +946,8 @@ export function resolutionRefusal(error: unknown): string {
919
946
  return RESOLUTION_CAUSES.find(([pattern]) => pattern.test(text))?.[1] ?? "resolution refused: inspect ahub queue show for the delivery's state";
920
947
  }
921
948
 
922
- /** No remote set and a stop are not failures: agent-mem words the missing remote "no sync remote" (v1) or "no generation sync remote configured". */
923
- export const quietSyncError = (error: string | undefined): boolean => /^(no (generation )?sync remote|stopped)/.test(error ?? "");
949
+ /** No remote set and a stop are not failures: agent-mem words the missing remote "no sync remote" (v1), "no generation sync remote configured" or "no shard sync remote configured" (sharded homes). */
950
+ export const quietSyncError = (error: string | undefined): boolean => /^(no (generation |shard )?sync remote|stopped)/.test(error ?? "");
924
951
 
925
952
  let recoverySourcePackageDigest: string | null | undefined;
926
953
  function capturedRecoverySourceDigest(): string | undefined {
@@ -982,7 +1009,9 @@ export async function startDaemon(opts: DaemonOptions) {
982
1009
  const loadedConfig = recoveryConfiguration ?? (opts.config ? { ...opts.config, adapter_modules: moduleDeclarations.length ? moduleDeclarations : undefined }
983
1010
  : loadConfig(opts.cwd, startupLayers, undefined, externalDefinitions));
984
1011
  reviewerPoolConfig(loadedConfig.review, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS);
985
- const lifecycleConfig = loadSdlc(opts.cwd, VERSION);
1012
+ const lifecycleConfig = opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
1013
+ /** The file's lifecycle as the status and settings views report it; a supplied fixture config stands in for it. */
1014
+ const readSdlcFile = () => opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
986
1015
  // Preserve embedding-owned policy references, but never publish reloads into shared defaults.
987
1016
  const ownedConfig = Object.fromEntries(Object.entries(loadedConfig).map(([key, value]) => [key, !opts.config || value === (DEFAULT_CONFIG as unknown as Record<string, unknown>)[key] ? structuredClone(value) : value])) as unknown as HubConfig;
988
1017
  const adapterCatalog = createProjectAdapterCatalog(loadedConfig.adapters, externalDefinitions);
@@ -1264,9 +1293,18 @@ export async function startDaemon(opts: DaemonOptions) {
1264
1293
  for (const note of lifecycleConfig.deprecations ?? []) log(note);
1265
1294
  const resolvedProfile = resolveProfile(config.profile, config.profile_overrides);
1266
1295
  let roleAssignments = { ...resolvedProfile.catalog_roles, ...catalogAssignments(config.catalog_roles) };
1267
- const event = eventLog(join(opts.stateDir, "events.jsonl"), (entry) => {
1296
+ let reviewerJournalComplete = true;
1297
+ const reviewerJournalRows: unknown[] = [];
1298
+ const appendEvent = eventLog(join(opts.stateDir, "events.jsonl"), (entry) => {
1268
1299
  if (entry.type === "permission") log(`permission event recording failed at ${entry.event} for ${entry.peer}`);
1269
1300
  });
1301
+ const event: ReturnType<typeof eventLog> = entry => {
1302
+ const stamped = { ...entry, at: new Date().toISOString() };
1303
+ const committed = appendEvent(stamped);
1304
+ if (!committed) reviewerJournalComplete = false;
1305
+ else if (reviewerAccountingRelevant(entry)) reviewerJournalRows.push(stamped);
1306
+ return committed;
1307
+ };
1270
1308
  const compatibleRoles = (peer: string) => [...catalog.roles.values()].filter(role => role.base.some(base => config.roles[peer]?.includes(base))).map(role => role.id).sort();
1271
1309
  const configuredRoles = (peer: string) => selectedRoles(peer, config.roles, roleAssignments, catalog).map(role => role.id);
1272
1310
  const dataRoleContract = (peer: string, contract: string) => config.data?.readonly.length && definitionOf(peer)?.trust.hubSandboxed === true
@@ -1293,12 +1331,12 @@ export async function startDaemon(opts: DaemonOptions) {
1293
1331
  preparedSessionRoles.set(peer, selected.map(role => role.id));
1294
1332
  preparedSessionRoleIdentities.set(peer, selected.map(roleIdentity));
1295
1333
  if (selected.length) event({ type: "role", peer, actor: "config", stage: "prepared", roles: selected.map(roleIdentity) });
1296
- return dataRoleContract(peer, roleContract(peer, config.roles, selected, resolvedProfile));
1334
+ return dataRoleContract(peer, roleContract(peer, config.roles, selected, resolvedProfile, lifecycleConfig.mode !== "off"));
1297
1335
  } catch (error) {
1298
1336
  preparedSessionRoles.delete(peer);
1299
1337
  preparedSessionRoleIdentities.delete(peer);
1300
1338
  log(`catalog role assignment refused for ${peer}: ${(error as Error).message}`);
1301
- const fallback = dataRoleContract(peer, roleContract(peer, config.roles, [], resolvedProfile));
1339
+ const fallback = dataRoleContract(peer, roleContract(peer, config.roles, [], resolvedProfile, lifecycleConfig.mode !== "off"));
1302
1340
  preparedSessionRoles.set(peer, []);
1303
1341
  preparedSessionRoleIdentities.set(peer, []);
1304
1342
  return fallback;
@@ -2345,7 +2383,27 @@ export async function startDaemon(opts: DaemonOptions) {
2345
2383
  } catch {
2346
2384
  guidanceProbeStore.close(); board.close(); throw new Error("guidance probe state or recovery binding is unavailable; restore trusted project state and choose a compatible target before retrying");
2347
2385
  }
2386
+ try {
2387
+ const retained = board.surveyIntegrity(), expected = restored?.integrity?.advisorSurveys;
2388
+ if (restored && (expected ? expected.surveys !== retained.surveys || expected.findings !== retained.findings || expected.considered !== retained.considered || expected.digest !== retained.digest
2389
+ : retained.surveys !== 0 || retained.findings !== 0 || retained.considered !== 0)) throw new Error("changed recovery binding");
2390
+ } catch {
2391
+ guidanceProbeStore.close(); board.close(); throw new Error("advisor survey state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2392
+ }
2348
2393
  startupCleanup.push(() => guidanceProbeStore.close());
2394
+ // #1226 T3: the one explicit crash reconcile. A fresh process has no probe in flight, so a session still `reserved` or `running` belongs to a previous process
2395
+ // and is recorded as unknown with an unknown receipt (never launched, retried or turned into a success). It runs after the integrity comparison above, never
2396
+ // while a recovery holds the stores (the release path calls it again), and a failure is logged and leaves the rows untouched for the next start.
2397
+ const reconcileGuidanceProbes = (): void => {
2398
+ try {
2399
+ // Every experiment is tried even when one fails; each failure is logged with its reason class and experiment id, never its content.
2400
+ const { reconciled, failed } = guidanceProbeStore.reconcile(undefined, (key, error) =>
2401
+ log(`guidance probe reconcile failed for ${key ? `experiment ${key.id.slice(0, 12)}` : "an unreadable experiment key"} (${error instanceof Error ? error.constructor.name : "error"}${error instanceof GuidanceProbeError ? `: ${error.reason}` : ""}); its sessions stay as stored and are retried at the next start`));
2402
+ if (reconciled > 0) log(`guidance probe reconcile: ${reconciled} session${reconciled === 1 ? "" : "s"} left by a previous process recorded as unknown`);
2403
+ if (failed > 0) log(`guidance probe reconcile: ${failed} experiment${failed === 1 ? "" : "s"} could not be reconciled`);
2404
+ } catch (error) { log(`guidance probe reconcile failed (${error instanceof GuidanceProbeError ? error.reason : "error"}); the sessions stay as stored and are retried at the next start`); }
2405
+ };
2406
+ if (!recoveryActive()) reconcileGuidanceProbes();
2349
2407
  const visuals = new VisualStore(join(opts.stateDir, "hub.db"));
2350
2408
  startupCleanup.push(() => visuals.close());
2351
2409
  // Held recovery must compare the source's exact rows before any retention mutation.
@@ -2820,6 +2878,7 @@ export async function startDaemon(opts: DaemonOptions) {
2820
2878
  let runnerState = await checkRunner.available(runnerRefreshAbort.signal);
2821
2879
  const orphanChecks = (await checkRunner.sweep()).map(line => boundedSafe(line) ? sanitize(line) : "orphan check: details withheld by privacy policy");
2822
2880
  if (opts.boundedTools?.specAvailable || !opts.config && (config.pi.enabled || config.checks.runner === "container" || config.checks.runner === "remote")) await ensureSpec();
2881
+ startupTimings.mark("task_checks");
2823
2882
  let runnerStateAt = runnerState.checkedAt ?? Date.now(), refreshingRunner: Promise<void> | undefined;
2824
2883
  const refreshRunner = (): Promise<void> => {
2825
2884
  if (stopping || runnerRefreshAbort.signal.aborted) return Promise.resolve();
@@ -2917,6 +2976,7 @@ export async function startDaemon(opts: DaemonOptions) {
2917
2976
  const projectSpecs = specInspectorAt(opts.cwd);
2918
2977
  let specsMissingBlockHintShown = false;
2919
2978
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
2979
+ startupTimings.mark("task_ports");
2920
2980
  const tasks: Tasks = new Tasks({
2921
2981
  guidanceProbes: { store: guidanceProbeStore, session: by => {
2922
2982
  const request = guidanceProbeRequestContext.getStore();
@@ -2959,6 +3019,7 @@ export async function startDaemon(opts: DaemonOptions) {
2959
3019
  reviewContext: (by, task) => !!definitionOf(by)?.reviewer && (bus.peers.get(by) as ReviewerPrintPeer | undefined)?.reviewing === task ? "fresh" : "continuing",
2960
3020
  reviewObserverInput,
2961
3021
  onReviewObserverInput: latchReviewObserverInput,
3022
+ observerExcludedTurn: peer => resolvedProfile.name === "research" && reviewObserverHeld(peer),
2962
3023
  // Proof belongs to the adapter generation actually started in the validated root. A role-only
2963
3024
  // reload cannot turn a canonical reviewer process into an isolated implementation owner.
2964
3025
  ownerIsolation: () => Object.fromEntries(extraIds.map(id => {
@@ -3025,6 +3086,7 @@ export async function startDaemon(opts: DaemonOptions) {
3025
3086
  return report;
3026
3087
  },
3027
3088
  specsRead: (action, paths) => projectSpecs.read(action, paths),
3089
+ auditSource: gitAuditSource(opts.cwd), // #1403 A4
3028
3090
  sdlc: {
3029
3091
  config: () => lifecycleConfig,
3030
3092
  gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
@@ -3103,6 +3165,18 @@ export async function startDaemon(opts: DaemonOptions) {
3103
3165
  }, sourceKnown: id => sourceRegistry.get(id) !== undefined,
3104
3166
  partsSchema: () => profileTaskTools(resolvedProfile, lifecycleConfig.stages, lifecycleConfig.mode !== "off").find(tool => tool.name === "hub_backlog_split")?.inputSchema.properties.parts },
3105
3167
  studySource: id => sourceRegistry.get(id),
3168
+ evidenceSourceMeta: id => sourceRegistry.get(id),
3169
+ evidenceSourceSnapshotKey: link => evidenceSnapshotKey(sourceRegistry, link.sourceId, receipt => receipt.converter
3170
+ ? projections.fingerprint(join(opts.cwd, `source${receipt.converter.extension}`)) : SOURCE_UTF8_PROJECTION_VERSION),
3171
+ evidenceSourceRead: (by, link, current, mode) => {
3172
+ const hostCurrent = sourceReadCurrent(by, false, false);
3173
+ return readEvidenceSource(sourceRegistry, link, {
3174
+ valid: () => hostCurrent() && current(), canReadPrivate: async () => false,
3175
+ screen: screenSourceText, privacyReadOnly: mode?.privacyReadOnly,
3176
+ projectionVersion: receipt => receipt.converter
3177
+ ? projections.fingerprint(join(opts.cwd, `source${receipt.converter.extension}`)) : SOURCE_UTF8_PROJECTION_VERSION,
3178
+ });
3179
+ },
3106
3180
  experimentCheck: run => checkRunner.result(run),
3107
3181
  // The PII screen (issue #198): the model on this machine when MLX/Ollama is enabled, else the gateway on campus only.
3108
3182
  piiScreen: (text) => {
@@ -3112,7 +3186,10 @@ export async function startDaemon(opts: DaemonOptions) {
3112
3186
  },
3113
3187
  recordScreen: (record) => event({ type: "pii_screen", ...record }),
3114
3188
  quota: (): ReturnType<Budget["headroom"]> => projectBudgetHeadroom(budget.headroom(), accountMembers), // budget is built below; this runs at assignment time
3115
- review: config.review,
3189
+ get review() { return config.review; },
3190
+ reviewBudget: () => {
3191
+ return { paused: Object.fromEntries(SUPPORTED_PEERS.flatMap(peer => { const paused = budget.reviewerPause(peer); return paused ? [[peer, paused]] : []; })), manualPaused: [...manualPaused] };
3192
+ },
3116
3193
  sweep: taskSweepConfig(config.task_sweep),
3117
3194
  sweepHeld: () => stopping || recoveryActive(),
3118
3195
  submodules: () => factsRepo ? submodulePaths(factsRepo) : [], // #798 D1: read from .gitmodules, no git call
@@ -3145,6 +3222,7 @@ export async function startDaemon(opts: DaemonOptions) {
3145
3222
  failing: () => ({ ...bus.failingPeers(), ...Object.fromEntries(reviewerUnavailable) }),
3146
3223
  held: () => Object.fromEntries(bus.knownPeers().flatMap((peer) => { const hold = queueHold(peer); return hold ? [[peer, hold]] : []; })),
3147
3224
  });
3225
+ startupTimings.mark("task_board");
3148
3226
  /**
3149
3227
  * #1221 T2: the bounded proposal queue. The store is built even while the mode is off (its tables are additive and a
3150
3228
  * person may turn the mode on at the next reload), and nothing in it runs until an explicit decision arrives: reading
@@ -3281,6 +3359,7 @@ export async function startDaemon(opts: DaemonOptions) {
3281
3359
  return true;
3282
3360
  };
3283
3361
  tasks.recoverIntegrations();
3362
+ startupTimings.mark("task_recovery");
3284
3363
  // #1221 T2 AC6: a restart keeps the dedupe keys, the dispositions and an action outcome the hub never observed. A
3285
3364
  // pending proposal whose task moved or closed expires here, once, with nothing replayed.
3286
3365
  void supervisionProposals.recover().catch((error: Error) => log(`supervision reconcile failed: ${error.message}`));
@@ -3336,7 +3415,8 @@ export async function startDaemon(opts: DaemonOptions) {
3336
3415
  if (!observation) return;
3337
3416
  if (reviewObserverHeld(peer) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded)) { progress.clearPeer(peer); return; }
3338
3417
  const toolName = observation.name.replace(/^mcp__[^ ]+__/, "");
3339
- if (GUIDANCE_TOOL_NAMES.has(toolName)) return;
3418
+ if (toolName === "hub_survey_report") return;
3419
+ if (GUIDANCE_TOOL_NAMES.has(toolName) || toolName === "hub_audit_report") return;
3340
3420
  if (observation.name === "hub_set_title" || observation.name === "hub_ask") return; // #1053: a question and its answer are never progress evidence (they may reach an escalation model)
3341
3421
  try {
3342
3422
  const candidates = board.list().filter(task => task.owner === peer && ["in_progress", "changes_requested"].includes(task.state));
@@ -3462,8 +3542,20 @@ export async function startDaemon(opts: DaemonOptions) {
3462
3542
  // same peer cannot undo a settlement.
3463
3543
  const turnEnded = new Map<PeerId, number>();
3464
3544
  const nativeCompletedAt = new Map<PeerId, number>();
3545
+ /** #1402: the model the latest accepted native hook payload named, per peer (Antigravity's `modelName`); `session` evidence, read once at the turn end and dropped when the peer goes offline. */
3546
+ const hookModels = new Map<PeerId, string>();
3465
3547
  startupTimings.mark("task_runtime");
3466
3548
  const startupSeeds = readStartupEventSeeds(join(opts.stateDir, "events.jsonl"));
3549
+ reviewerJournalComplete &&= startupSeeds.complete;
3550
+ for (const row of startupSeeds.events) if (reviewerAccountingRelevant(row)) reviewerJournalRows.push(row);
3551
+ const startupReviewerAccounting = reviewerAccountingIntegrity(reviewerJournalRows, reviewerJournalComplete);
3552
+ reviewerJournalComplete &&= startupReviewerAccounting.complete;
3553
+ const expectedReviewerQuota = restored?.integrity?.reviewerQuota;
3554
+ if (restored?.integrity && (expectedReviewerQuota
3555
+ ? JSON.stringify(startupReviewerAccounting) !== JSON.stringify({ rows: expectedReviewerQuota.rows, completed: expectedReviewerQuota.completed, pending: expectedReviewerQuota.pending, unknown: expectedReviewerQuota.unknown, complete: expectedReviewerQuota.complete, digest: expectedReviewerQuota.digest })
3556
+ : startupReviewerAccounting.rows !== 0 || !startupReviewerAccounting.complete)) {
3557
+ throw new Error("reviewer accounting recovery binding changed; retain the journal and use a supporting recovery target");
3558
+ }
3467
3559
  try { opts.startupSeedObserved?.({ readPasses: startupSeeds.readPasses, readBytes: startupSeeds.readBytes }); } catch { /* Diagnostic observers cannot change replay or readiness. */ }
3468
3560
  const nativeStopsSeen = startupSeeds.nativeStopsSeen;
3469
3561
  startupTimings.mark("native_stop_seed");
@@ -3497,6 +3589,7 @@ export async function startDaemon(opts: DaemonOptions) {
3497
3589
  /** What quiescence was judged on, for the log when an integration waits on it. */
3498
3590
  const stopEvidence = (peer: PeerId) => `${peer}: turn end ${turnEnded.has(peer) ? new Date(turnEnded.get(peer)!).toISOString() : "none"}, last tool call ${activeAt.has(peer) ? new Date(activeAt.get(peer)!).toISOString() : "none"}, ${bus.peers.get(peer)?.state ?? "offline"}`;
3499
3591
  board.onChange = (t, h) => {
3592
+ tasks.reviewQuotaTaskChanged(t);
3500
3593
  if (!isClosedTaskState(t.state) && t.state !== "backlog") {
3501
3594
  if (t.owner) inboxPolling.reset(t.owner);
3502
3595
  if (t.reviewer) inboxPolling.reset(t.reviewer);
@@ -3856,11 +3949,13 @@ export async function startDaemon(opts: DaemonOptions) {
3856
3949
  if (budgetFeedSeen.get(hold.peer) !== key && supervision.budgetPaused(hold.peer, hold.resetsAt)) budgetFeedSeen.set(hold.peer, key);
3857
3950
  }
3858
3951
  };
3952
+ const unsettledReviewerQuota = new Map<string, { account: string; peer: string }>();
3859
3953
  const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
3860
3954
  definitionOf,
3861
3955
  pause: (peer) => bus.pause(peer),
3862
3956
  resume: (peer) => {
3863
3957
  if (!manualPaused.has(peer) && !conductorHolds.has(peer)) bus.resume(peer);
3958
+ queueMicrotask(() => tasks.refreshReviewerQuotaWaits());
3864
3959
  },
3865
3960
  requestCheckpoint: (peer) => requestCheckpoint(peer, "quota"),
3866
3961
  platformContext: async (peer) => {
@@ -3871,11 +3966,11 @@ export async function startDaemon(opts: DaemonOptions) {
3871
3966
  },
3872
3967
  attached: (peer) => bus.peers.has(peer),
3873
3968
  // Somebody other than the paused peer has to be there, or the handoff would only leave its tasks without an owner.
3874
- canHandOff: (peer) => [...bus.peers.keys()].some((id) => accountOf(id) !== accountOf(peer) && ["idle", "busy"].includes(bus.stateOf(id))),
3969
+ canHandOff: (peer) => ![...unsettledReviewerQuota.values()].some(row => row.account === accountOf(peer)) && [...bus.peers.keys()].some((id) => accountOf(id) !== accountOf(peer) && ["idle", "busy"].includes(bus.stateOf(id))),
3875
3970
  // A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
3876
3971
  // #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
3877
3972
  ledger: entry => event(entry),
3878
- reading: (peer, windows, hard, at) => event({ type: "quota", peer, windows: windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, ...(Math.abs(Date.now() - at) > 1000 ? { measuredAt: new Date(at).toISOString() } : {}) }),
3973
+ reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); return event({ type: "quota", peer, windows: windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, ...(Math.abs(Date.now() - at) > 1000 ? { measuredAt: new Date(at).toISOString() } : {}) }) },
3879
3974
  handoff: (peer, context, urgentOnly) => tasks.reassignForPause(peer, context, urgentOnly),
3880
3975
  resumed: (record) => {
3881
3976
  // Coalesce unread notices without forgetting the public moves they carried.
@@ -3906,6 +4001,7 @@ export async function startDaemon(opts: DaemonOptions) {
3906
4001
  const startupEvents = startupSeeds.events;
3907
4002
  budget.seedResets(startupEvents.flatMap(e => e.type === "quota_reset" ? [{ peer: e.peer, window: e.window, ...(e.resetsAt !== undefined ? { resetsAt: e.resetsAt } : {}) }] : []));
3908
4003
  // #285 phase 2: Kimi's consumption is the hub's own count of its session wire log (`src/adapters/kimi-wire-usage.ts`), not an ACP total.
4004
+ const softTokenAccount = (peer: string): boolean => definitionOf(accountOf(peer))?.budget?.resetSoftTokensOnResume === true;
3909
4005
  const kimiEvents = new KimiEventWriter({ append: event, read: () => readEvents(join(opts.stateDir, "events.jsonl")) }, startupEvents);
3910
4006
  const kimiUsage = new KimiUsage({
3911
4007
  home: opts.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), ".kimi-code"),
@@ -3926,8 +4022,23 @@ export async function startDaemon(opts: DaemonOptions) {
3926
4022
  });
3927
4023
  startupCleanup.push(() => kimiUsage.stop());
3928
4024
  kimiUsage.seed(kimiSeedRows(startupEvents, Math.max(0, ...startupEvents.flatMap(e => e.type === "budget_resume" && definitionOf(e.peer)?.budget?.resetSoftTokensOnResume ? [Date.parse(e.at)] : []).filter(Number.isFinite))));
4025
+ if (!reviewerJournalComplete) {
4026
+ // ponytail: a damaged journal cannot prove which owned attempts settled. Keep soft counts unknown;
4027
+ // recovery needs a verified settlement, not a guessed expiry from a host start/cap timestamp.
4028
+ for (const peer of SUPPORTED_PEERS.filter(softTokenAccount)) kimiUsage.reviewerReplayIncomplete(peer);
4029
+ }
4030
+ for (const row of startupEvents) if (row.type === "reviewer_accounting" && softTokenAccount(row.peer)) {
4031
+ if (/^[a-f0-9]{32}$/.test(row.attempt) && ["started", "complete", "unknown"].includes(row.outcome))
4032
+ kimiUsage.reviewerAccounting(row.peer, row.attempt, row.outcome);
4033
+ else kimiUsage.reviewerReplayIncomplete(row.peer);
4034
+ }
3929
4035
  startupTimings.mark("usage_seed");
3930
4036
  /** Why a peer shows no number (no quota, nothing read yet): one line each, from the definition and the counters, never from a log's text. */
4037
+ const reviewerBudgetView = () => {
4038
+ if (config.review.gate === undefined) return undefined; // Legacy embedded hosts do not inject reviewer quota admission.
4039
+ const policy = { gate: config.review.gate, unknownQuota: config.review.unknown_quota ?? DEFAULT_REVIEW_UNKNOWN_QUOTA };
4040
+ return { gate: policy.gate, unknown_quota: policy.unknownQuota, rule: reviewBudgetPolicyDescription(policy) };
4041
+ };
3931
4042
  const budgetPeerNotes = (): BudgetPeerNote[] => {
3932
4043
  const quota = budget.status();
3933
4044
  const peers = [...new Set([...bus.knownPeers().filter(peer => bus.peers.has(peer) && bus.stateOf(peer) !== "offline"), ...Object.keys(quota)])].filter(peer => peer !== USER && peer !== HUB);
@@ -4143,6 +4254,14 @@ export async function startDaemon(opts: DaemonOptions) {
4143
4254
  }
4144
4255
  return snapshotBudget;
4145
4256
  };
4257
+ /** #1402: the `turn_end` model fields for a peer, read through its adapter. An adapter that throws or reports nothing records neither field; a label `safeModelLabel` refuses is dropped whole. */
4258
+ const observedTurnModel = (peer: string) => {
4259
+ try {
4260
+ // The adapter's own observation first; a native-hook peer (Antigravity) has none, so the model its hook payloads named is the session's current model. Read once, like the adapter's.
4261
+ const hooked = hookModels.get(peer); hookModels.delete(peer);
4262
+ return turnModelFields(bus.peers.get(peer)?.observedModel?.() ?? (hooked ? { model: hooked, evidence: "session" } : undefined));
4263
+ } catch { return {}; }
4264
+ };
4146
4265
  const snapshotFailure = (what: string, error: unknown) => {
4147
4266
  if (error instanceof SnapshotBudgetExceeded) {
4148
4267
  if (!snapshotBudgetNoticed) log(`snapshot unavailable: ${error.message}`);
@@ -4636,7 +4755,7 @@ export async function startDaemon(opts: DaemonOptions) {
4636
4755
  if (agentDrift.length && !stopping && !recoveryActive()) try { offerAgentDrift(); } catch { /* the next tick tries again */ }
4637
4756
  for (const pending of checkpointWaits.values()) if (!pending.valid()) pending.done(undefined);
4638
4757
  for (const [id, request] of permissions) if (request.expiresAt > Date.now()) supervision.approvalWaiting({ id, peer: request.peer, tool: request.tool ?? "unknown", createdAt: request.createdAt });
4639
- for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id);
4758
+ for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id, () => holdCommand(row.peer, row.id));
4640
4759
  feedBudgetPauses();
4641
4760
  supervision.checkRound();
4642
4761
  try {
@@ -4760,7 +4879,7 @@ export async function startDaemon(opts: DaemonOptions) {
4760
4879
  // Registration is the same two steps `ahub source add` takes (`registerScanned`): one decision about privacy, then the registry. The scan kept no bytes, so the file
4761
4880
  // is read again there and refused if it no longer hashes to what the scan saw. A file under pii.paths or whose text matches a PII pattern is a private source.
4762
4881
  const register = (file: ScannedFile) => registerScanned(file, { registry: sourceRegistry, cwd: opts.cwd, piiPaths: config.pii?.paths ?? [], piiPatterns: () => activeRouting().signals.pii_patterns,
4763
- project: (extension, data) => projections.projectBytes(join(opts.cwd, `source${extension}`), data)?.text });
4882
+ project: (extension, data) => projections.projectBytes(join(opts.cwd, `source${extension}`), data) });
4764
4883
  for (const run of await tasks.runFolderTriggers(folderStore, config.folder_triggers, entry => scanFolder(entry, policy, (real, size, mtime) => folderStore.known(entry.id, real, size, mtime)), register, scheduleNow(), () => opts.schedulesHeld?.() === true)) {
4765
4884
  if (run.outcome === "ran") log(`folder trigger ${run.id}: proposed ${run.tasks.map(id => `task #${id}`).join(", ")}`);
4766
4885
  else if (run.outcome === "failed" || run.outcome === "refused") log(`folder trigger ${run.id}: ${run.outcome}: ${sanitize(run.reason ?? "").slice(0, 160)}`);
@@ -4788,7 +4907,7 @@ export async function startDaemon(opts: DaemonOptions) {
4788
4907
  const SERVER_JS = join(import.meta.dir, "..", "..", "plugins", "agent-hub", "server.js");
4789
4908
  // What the hub's MCP server offers a native peer. Codex approves them in config, Kimi's requests for exactly these
4790
4909
  // names are answered by the hub; every call still passes daemon role/capability checks before its effects.
4791
- const HUB_TOOLS = ["hub_send", ...[...TASK_TOOL_NAMES].filter(name => name !== "hub_set_title" && (name !== "hub_evidence_record" || resolvedProfile.name === "research")), ...CONDUCTOR_TOOLS.map((t) => t.name)];
4910
+ const HUB_TOOLS = ["hub_send", ...[...TASK_TOOL_NAMES].filter(name => name !== "hub_set_title" && (!["hub_evidence_record", "hub_evidence_read"].includes(name) || resolvedProfile.name === "research")), ...CONDUCTOR_TOOLS.map((t) => t.name)];
4792
4911
  const HUB_TOOL_TITLES = new Set(HUB_TOOLS.map((name) => `mcp__agent-hub__${name}`));
4793
4912
  const toolEnv = (peer: PeerId, deliveryOnly = false) => ({ ...(deliveryOnly ? { AGENTHUB_DELIVERY_ONLY: "true" } : {}), AGENTHUB_MODE: "tools", AGENTHUB_PEER_ID: peer, AGENTHUB_STATE_DIR: opts.stateDir, AGENTHUB_PROJECT_DIR: opts.cwd });
4794
4913
 
@@ -5081,7 +5200,7 @@ export async function startDaemon(opts: DaemonOptions) {
5081
5200
  const taskOp = async (...args: Parameters<typeof taskOpBody>): Promise<string> => {
5082
5201
  const [by, op, input] = args;
5083
5202
  if (readOnlyPeer(by) && !READ_ONLY_HUB_TOOLS.has(op)) throw op === "hub_visual" ? visualOperational("role") : new PreEffectToolRefusal("read-only instance cannot mutate hub state");
5084
- const sourceCurrent = op === "hub_source_read" ? sourceReadCurrent(by, args[3] ?? false, args[4] ?? false) : undefined;
5203
+ const sourceCurrent = op === "hub_source_read" || op === "hub_evidence_read" ? sourceReadCurrent(by, args[3] ?? false, args[4] ?? false) : undefined;
5085
5204
  const nativeTurn = turns.get(by);
5086
5205
  const effectful = ownerToolEffect(op, input);
5087
5206
  if (nativeTurn && effectful) nativeTurn.effectsPending = (nativeTurn.effectsPending ?? 0) + 1;
@@ -5103,13 +5222,13 @@ export async function startDaemon(opts: DaemonOptions) {
5103
5222
  const id = Number.isSafeInteger(proposed) && proposed! > 0 ? proposed : admittedId;
5104
5223
  auditConduct({ kind: "conduct", actor: by, action: op.slice(4), ...(id === undefined ? {} : { task: id }) });
5105
5224
  }
5106
- const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5225
+ const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_evidence_read" && op !== "hub_audit_report" && op !== "hub_survey_report" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5107
5226
  return hint ? `${text}\n\n${hint}` : text;
5108
5227
  } catch (error) {
5109
5228
  if (reviewTool && traceId !== undefined) reviewerToolObservers.get(by)?.(traceId, reviewTool, error instanceof Error ? error.message : "review tool refused");
5110
5229
  if (nativeTurn && effectful && !(error instanceof PreEffectToolRefusal) && turns.get(by) === nativeTurn) nativeTurn.taskEffect = true;
5111
5230
  // Keep proven pre-effect refusal identity/code for native receipts; only add body-free metadata.
5112
- const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5231
+ const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_evidence_read" && op !== "hub_audit_report" && op !== "hub_survey_report" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5113
5232
  if (hint && error instanceof Error) error.message += `\n\n${hint}`;
5114
5233
  throw error;
5115
5234
  } finally {
@@ -5143,6 +5262,15 @@ export async function startDaemon(opts: DaemonOptions) {
5143
5262
  && policyKey === JSON.stringify({ signals: activeRouting().signals, constraints: activeRouting().constraints, paths: config.pii?.paths ?? [], mlx: config.mlx, model: activeRouting().local.fixed_model });
5144
5263
  }
5145
5264
  const sourceRegistry = new SourceRegistry(opts.stateDir);
5265
+ async function screenSourceText(text: string, meta: SourceMeta): Promise<boolean> {
5266
+ if (meta.origins.some(origin => origin.kind === "file" && matchesPolicy(opts.cwd, origin.origin, config.pii?.paths ?? []))) return false;
5267
+ try { if (looksSecret(text) || activeRouting().signals.pii_patterns.some(pattern => new RegExp(pattern).test(text))) return false; }
5268
+ catch { return false; }
5269
+ if (!tasks.screenOn()) return true;
5270
+ // Reuse the bounded host screen. Oversized/unknown is private, never an unscreened excerpt.
5271
+ const verdict = await (opts.piiScreen ?? ((value: string) => screenPii(value, { ...(config.mlx.enabled === false ? {} : { device: () => ensureMlx(config.mlx) }), onCampus, omni, fixedModel: () => activeRouting().local.fixed_model })))(text).catch(() => undefined);
5272
+ return verdict?.label === "clear";
5273
+ }
5146
5274
  const answeringInvocation = (peer: PeerId): boolean => {
5147
5275
  if (invocations.answering(peer)) return true;
5148
5276
  if (!bus.hasInvocationTurn(peer)) return false;
@@ -5477,6 +5605,17 @@ export async function startDaemon(opts: DaemonOptions) {
5477
5605
  if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
5478
5606
  const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5479
5607
  if (reviewTurn || op === "hub_review" && reviewCaptureExcluded(op, JSON.stringify(a))) progress.clearPeer(by);
5608
+ if (op === "hub_survey_report") {
5609
+ if (piiTurn || turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by)) throw new PreEffectToolRefusal("survey reports are unavailable in private or review input; retry in a public current-owner context");
5610
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown holds survey writes; wait for release and retry");
5611
+ return JSON.stringify(await tasks.surveyReport(by, a, () => stopping || recoveryActive() || bus.isRecoveryHeld ? "survey write held by recovery or shutdown" : undefined));
5612
+ }
5613
+ if (op === "hub_audit_report") {
5614
+ // #1403 A4, A5: finding text of an open important security finding is the auditor's and a reviewer's to read, never a PII turn's, a review observer's or memory's.
5615
+ if (piiTurn || turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by)) throw new PreEffectToolRefusal("audit reports are unavailable in private or review input; retry in a public current-owner context");
5616
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding audit writes; wait for release and read the audit before retrying");
5617
+ return JSON.stringify(await tasks.auditReport(by, a));
5618
+ }
5480
5619
  if (GUIDANCE_TOOL_NAMES.has(op)) {
5481
5620
  if (op === "hub_guidance_list" || op === "hub_guidance_show") return JSON.stringify(guidanceRead(by, op === "hub_guidance_list" ? "list" : "show", a, piiTurn));
5482
5621
  const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
@@ -5584,15 +5723,7 @@ export async function startDaemon(opts: DaemonOptions) {
5584
5723
  const campus = await onCampus().catch(() => false);
5585
5724
  return campus && eligible();
5586
5725
  },
5587
- screen: async (text, meta) => {
5588
- if (meta.origins.some(origin => origin.kind === "file" && matchesPolicy(opts.cwd, origin.origin, config.pii?.paths ?? []))) return false;
5589
- try { if (looksSecret(text) || activeRouting().signals.pii_patterns.some(pattern => new RegExp(pattern).test(text))) return false; }
5590
- catch { return false; }
5591
- if (!tasks.screenOn()) return true;
5592
- // Reuse the bounded host screen. Oversized/unknown is private, never an unscreened excerpt.
5593
- const verdict = await (opts.piiScreen ?? ((value: string) => screenPii(value, { ...(config.mlx.enabled === false ? {} : { device: () => ensureMlx(config.mlx) }), onCampus, omni, fixedModel: () => activeRouting().local.fixed_model })))(text).catch(() => undefined);
5594
- return verdict?.label === "clear";
5595
- },
5726
+ screen: screenSourceText,
5596
5727
  }));
5597
5728
  }
5598
5729
  if (MEMORY_READ_TOOLS.has(op)) {
@@ -5784,6 +5915,8 @@ export async function startDaemon(opts: DaemonOptions) {
5784
5915
  return JSON.stringify(await tasks.experimentRecord(by, a));
5785
5916
  case "hub_evidence_record":
5786
5917
  return JSON.stringify(await tasks.evidenceRecord(by, a));
5918
+ case "hub_evidence_read":
5919
+ return JSON.stringify(await tasks.evidenceRead(by, a));
5787
5920
  case "hub_study_handoff":
5788
5921
  if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "handoff")) throw new PreEffectToolRefusal("study handoff takes only a handoff object");
5789
5922
  return JSON.stringify(await tasks.studyHandoff(by, a.handoff));
@@ -5807,6 +5940,10 @@ export async function startDaemon(opts: DaemonOptions) {
5807
5940
  return JSON.stringify({ handoffs: handoffListView(), synced: false, syncing: true, pending });
5808
5941
  }
5809
5942
  // #601: the person's own forms (a read is hub_study_show, which every connection may use). `by` is USER only on the console path; approval and close are never a tool.
5943
+ case "study_evidence":
5944
+ return JSON.stringify(await tasks.synthesisEvidence(by, a));
5945
+ case "study_check":
5946
+ return JSON.stringify(await tasks.synthesisCheck(by, a));
5810
5947
  case "study_draft":
5811
5948
  return JSON.stringify(await tasks.studyDraft(by, a));
5812
5949
  case "study_revise":
@@ -5871,7 +6008,7 @@ export async function startDaemon(opts: DaemonOptions) {
5871
6008
  case "hub_sdlc_record":
5872
6009
  return line(await tasks.recordSdlc(by, a.id, a.receipt));
5873
6010
  case "hub_review": {
5874
- const reviewed = await tasks.review(by, a.id, a.verdict, a.note, a.unmet, a.head, a.coverage, a.findings);
6011
+ const reviewed = await tasks.review(by, a.id, a.verdict, a.note, a.unmet, a.head, a.coverage, a.findings, a.security_pass);
5875
6012
  // #1279: a verdict note that names a brief entry is a citation. The same exclusions as a done summary apply (a PII or review-observer turn, withheld text), and the key binds it to this verdict.
5876
6013
  const verdict = reviewed.history.findLast(h => h.by === by && (h.event === "approved" || h.event === "changes_requested"));
5877
6014
  if (!piiTurn && !reviewTurn && !tasks.isPii(reviewed) && verdict && !verdict.withheld && typeof a.note === "string" && a.note && verdict.note?.startsWith(a.note)) {
@@ -5961,8 +6098,11 @@ export async function startDaemon(opts: DaemonOptions) {
5961
6098
  switch (op) {
5962
6099
  case "release_new":
5963
6100
  return JSON.stringify(await tasks.newRelease(by, { name: a.name, goal: a.goal, order: a.order }));
5964
- case "claim_verdict": // #901: a person's verdict on one declared claim; the reply names the slot and the verdict only, never a claim
5965
- return JSON.stringify((({ id, history }) => ({ task: id, recorded: history.at(-1)?.claim }))(tasks.recordClaimVerdict(by, a.id, { slot: a.slot, verdict: a.verdict, ...(a.model === undefined ? {} : { model: a.model }), ...(a.modelVerdict === undefined ? {} : { modelVerdict: a.modelVerdict }) })));
6101
+ case "claim_verdict": { // #901: same person-only record; a synthesis descriptor is validated transiently, never retained.
6102
+ const claim = { slot: a.slot, verdict: a.verdict, ...(a.model === undefined ? {} : { model: a.model }), ...(a.modelVerdict === undefined ? {} : { modelVerdict: a.modelVerdict }), ...(a.synthesis === undefined ? {} : { synthesis: a.synthesis }) };
6103
+ const task = a.synthesis === undefined ? tasks.recordClaimVerdict(by, a.id, claim) : await tasks.recordSynthesisClaimVerdict(by, a.id, claim, a.manifest);
6104
+ return JSON.stringify({ task: task.id, recorded: task.history.at(-1)?.claim });
6105
+ }
5966
6106
  case "github_import":
5967
6107
  return JSON.stringify(await tasks.importGitHub(by, { repo: a.repo, label: a.label, milestone: a.milestone }));
5968
6108
  case "release_show": {
@@ -6811,13 +6951,26 @@ export async function startDaemon(opts: DaemonOptions) {
6811
6951
  const owner = bus.peers.get(peer);
6812
6952
  return !!owner && modelAcpOwners.get(owner)?.acceptsModelOverride(model) === true;
6813
6953
  };
6954
+ /**
6955
+ * #1402 T5: the last model each peer's finished turn reported, for `ahub status` / `ahub model list` when nothing configured names one. Only a served or session grade counts (a configured one is already
6956
+ * the instance or launch model), and only a model the status projection can show (a native model token; a longer label would make the CLI drop the whole row). Dropped when the peer goes offline.
6957
+ */
6958
+ const observedModels = new Map<PeerId, { model: string; source: "observed (served)" | "observed (session)"; owner: PeerAdapter | undefined }>();
6959
+ const noteObservedModel = <T extends { model?: string; modelEvidence?: string }>(peer: PeerId, fields: T): T => {
6960
+ if (fields.model !== undefined && isNativeModelToken(fields.model) && (fields.modelEvidence === "served" || fields.modelEvidence === "session"))
6961
+ observedModels.set(peer, { model: fields.model, source: `observed (${fields.modelEvidence})`, owner: bus.peers.get(peer) });
6962
+ return fields;
6963
+ };
6814
6964
  const modelFallback = (peer: string): { model?: string; source: Exclude<ModelSource, "override"> } => {
6815
6965
  const declared = declarations[peer]?.model;
6816
6966
  if (isNativeModelToken(declared)) return { model: declared, source: "instance" };
6817
6967
  const owner = bus.peers.get(peer), model = owner ? modelLaunchModels.get(owner) : undefined;
6818
6968
  if (model !== undefined) return { model, source: "launch" };
6819
6969
  const baseline = owner ? modelAcpOwners.get(owner)?.modelOverrideState.baseline : undefined;
6820
- return { ...(baseline ? { model: baseline } : {}), source: "native default" };
6970
+ if (baseline) return { model: baseline, source: "native default" };
6971
+ const seen = observedModels.get(peer);
6972
+ if (seen && seen.owner === owner) return { model: seen.model, source: seen.source };
6973
+ return { source: "native default" };
6821
6974
  };
6822
6975
  const registerModelOwner = (owner: PeerAdapter): void => {
6823
6976
  const definition = definitionOf(owner.id);
@@ -6932,6 +7085,8 @@ export async function startDaemon(opts: DaemonOptions) {
6932
7085
  const modelCommandSafe = (input: Record<string, unknown>, grant: ModelGrant): Record<string, unknown> => {
6933
7086
  try { return modelCommand(input, grant); } catch { return modelFailure("model override state could not be read or written; inspect ahub status and hub.db before retrying"); }
6934
7087
  };
7088
+ const reviewerQuotaIntegrity = () => ({ ...reviewerAccountingIntegrity(reviewerJournalRows, reviewerJournalComplete),
7089
+ waits: board.list().filter(task => task.history.some(row => row.reviewerQuotaWait !== undefined)).length });
6935
7090
  const integrity = (older = 0) => {
6936
7091
  const queues = Object.fromEntries(Object.keys(bus.snapshot(false).queues).sort().map((id) => [id, bus.queueIds(id)]));
6937
7092
  const boardState = board.list().sort((a, b) => a.id - b.id).map((t) => {
@@ -6946,6 +7101,8 @@ export async function startDaemon(opts: DaemonOptions) {
6946
7101
  const researchComparisons = board.researchComparisonIntegrity();
6947
7102
  const researchRunners = board.runnerReceiptIntegrity();
6948
7103
  const researchEvidence = board.researchEvidenceIntegrity();
7104
+ const reviewerQuota = reviewerQuotaIntegrity();
7105
+ const advisorSurveys = board.surveyIntegrity();
6949
7106
  const guidanceVariants = board.guidanceVariantsIntegrity();
6950
7107
  const guidanceProbes = guidanceProbeStore.integrity();
6951
7108
  const executionReferences = board.executionReferencesIntegrity();
@@ -6954,7 +7111,7 @@ export async function startDaemon(opts: DaemonOptions) {
6954
7111
  const visualIntegrity = visuals.integrity();
6955
7112
  if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
6956
7113
  throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
6957
- return { queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
7114
+ return { ...(reviewerQuota.rows || !reviewerQuota.complete || reviewerQuota.waits ? { reviewerQuota } : {}), queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(advisorSurveys.surveys || advisorSurveys.findings || advisorSurveys.considered ? { advisorSurveys } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
6958
7115
  };
6959
7116
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
6960
7117
  const integrityAs = (expected: unknown) => {
@@ -7061,6 +7218,8 @@ export async function startDaemon(opts: DaemonOptions) {
7061
7218
  lifecycleStages: [...lifecycleConfig.stages],
7062
7219
  // ponytail: off keeps the #257 phase schema until RETIRED_WORKFLOW_FROM, when the alias and this flag go together.
7063
7220
  ...(lifecycleConfig.mode !== "off" ? { lifecycleCriteria: true } : {}),
7221
+ ...(lifecycleConfig.mode !== "off" && lifecycleConfig.security !== undefined ? { lifecycleAudit: true } : {}),
7222
+ ...(lifecycleConfig.mode !== "off" ? { lifecycleSurvey: true } : {}),
7064
7223
  // Every supported peer's membership, for launchers that run outside the console role (#484).
7065
7224
  roster: [...KNOWN_PEERS, ...OPTIONAL_PEERS].map(peer => ({ peer, on: onRoster(peer) })),
7066
7225
  protocol: PROTOCOL_MIN, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL,
@@ -7097,6 +7256,8 @@ export async function startDaemon(opts: DaemonOptions) {
7097
7256
  actionPolicyInfo: Object.fromEntries(peerIds.map(id => { const e = actionEnforcement(id); return [id, actionBudgets.status(id, e.enforced, e.reason)]; })),
7098
7257
  roleInfo: Object.fromEntries(peerIds.map(id => [id, { flowRoles: config.roles[id] ?? [], catalogRoles: roleState(id), ...roleVisibility(id), ...(config.roles[id]?.includes("planner") ? { planner: plannerSource } : {}) }])),
7099
7258
  planner: { peers: plannerPeers(), source: plannerSource },
7259
+ // #1411 T2: the review settings routing reads when no reviewer can run (assign() decides; `ahub roles` only reports them).
7260
+ reviewFallback: { required: config.review.pool !== undefined, sameFamily: config.review.same_family ?? "fallback" },
7100
7261
  ...(pendingPermissionDefaults.size ? { permissionDefaults: [...pendingPermissionDefaults].map(([peer, source]) => ({ peer, mode: "never-ask", source })) } : {}),
7101
7262
  ...(modelRelay ? { models: modelRelay.status() } : {}),
7102
7263
  isolatedChecks: { pending: checkPending.size, orphans: orphanChecks, unknownReceipts: checkRunner.unknownReceipts ?? [], maintenanceUnavailable: checkRunner.maintenanceUnavailable === true },
@@ -7173,14 +7334,19 @@ export async function startDaemon(opts: DaemonOptions) {
7173
7334
  return bus.queueList(peer, true).filter(row => row.state === "needs_review").map(row => ({
7174
7335
  id: row.id, senders: [...new Set(row.originals.map(env => sanitize(env.from)))],
7175
7336
  kinds: [...new Set(row.originals.map(env => env.kind))], createdAt: row.createdAt,
7176
- reason: row.reason,
7337
+ reason: row.reason, revision: row.revision,
7177
7338
  context: deliveryTaskContext(row.originals, board, peer),
7178
7339
  }));
7179
7340
  }
7341
+ /** #1399: the full command for one held row, with the choices the hub cannot make for the person. */
7342
+ function holdCommand(peer: PeerId, id: string): string {
7343
+ const row = heldRows(peer).find(held => held.id === id);
7344
+ return `${queueResolveCommand(row ? { ...row, peer, state: "needs_review" } : { id, peer }, opts.cwd)} (${queueResolveChoices("needs_review")})`;
7345
+ }
7180
7346
  function queueHold(peer: PeerId): string | undefined {
7181
7347
  const rows = heldRows(peer);
7182
7348
  if (!rows.length) return undefined;
7183
- return rows.map(row => `held by needs_review ${row.id} (from ${row.senders.join(",")}; kind ${row.kinds.join(",")}; age ${Math.max(0, Math.floor((Date.now() - row.createdAt) / 1000))}s${row.context ? `; ${row.context}` : ""}); ahub queue resolve ${row.id} --action completed|retry|discard --reason <text>`).join("; ");
7349
+ return rows.map(row => `held by needs_review ${row.id} (from ${row.senders.join(",")}; kind ${row.kinds.join(",")}; age ${Math.max(0, Math.floor((Date.now() - row.createdAt) / 1000))}s${row.context ? `; ${row.context}` : ""}); ${queueResolveCommand({ ...row, peer, state: "needs_review" }, opts.cwd)} (${queueResolveChoices("needs_review")})`).join("; ");
7184
7350
  }
7185
7351
  let settlingSuperseded = false;
7186
7352
  function settleSupersededDeliveries() {
@@ -7210,13 +7376,13 @@ export async function startDaemon(opts: DaemonOptions) {
7210
7376
  for (const peer of bus.knownPeers()) {
7211
7377
  const rows = heldRows(peer);
7212
7378
  if (!rows.some(row => !noticedHolds.has(row.id))) continue;
7213
- for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id); }
7379
+ for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id, () => holdCommand(peer, row.id)); }
7214
7380
  notify(`${peer} queue ${queueHold(peer)}`);
7215
7381
  }
7216
7382
  writeStatus();
7217
7383
  } finally { reportingQueues = false; }
7218
7384
  if (ready) {
7219
- tasks.scheduleQueuePressureRecheck();
7385
+ tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
7220
7386
  const policy = queuePolicy();
7221
7387
  if ((policy.max_queued > 0 || policy.max_oldest_s > 0) && !queuePressureStatusQueued) {
7222
7388
  queuePressureStatusQueued = true;
@@ -7482,11 +7648,11 @@ export async function startDaemon(opts: DaemonOptions) {
7482
7648
  uiEvents.push({ seq: ++uiSequence, event: e });
7483
7649
  if (uiEvents.length > 200) uiEvents.shift();
7484
7650
  if (e.t === "state") {
7485
- if (e.state === "offline") { modelBoundaries.delete(e.peer); modelLatches.forget(e.peer); }
7651
+ if (e.state === "offline") { modelBoundaries.delete(e.peer); modelLatches.forget(e.peer); hookModels.delete(e.peer); observedModels.delete(e.peer); }
7486
7652
  roomCommands.changed();
7487
7653
  log(`state ${e.peer} -> ${e.state}`);
7488
7654
  event({ type: "state", peer: e.peer, state: e.state });
7489
- if (ready) tasks.scheduleQueuePressureRecheck();
7655
+ if (ready) { tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits(); }
7490
7656
  if (e.peer.includes("@")) { if (!stopping) writeStatus(); return; }
7491
7657
  // #248: the add-ons it works with, once per attach (names and versions only).
7492
7658
  // A result is written unless a later attachment began meanwhile: a peer that detached before its probe settled
@@ -7641,7 +7807,7 @@ export async function startDaemon(opts: DaemonOptions) {
7641
7807
  }
7642
7808
  // A lost Claude channel/watchdog is not native completion; only its real Stop closes a counted turn. A launcher-bound pull-only native turn follows the same rule.
7643
7809
  const nativeFactsTurn = nativeHookLaunches.current(e.peer) !== undefined && bus.peers.get(e.peer)?.pullOnly === true;
7644
- if (nativeFactsTurn ? (nativeCompletedAt.get(e.peer) ?? -1) >= open.start : definitionOf(e.peer)?.turnEnd !== "native-hook" || (nativeCompletedAt.get(e.peer) ?? -1) >= open.start) event({ type: "turn_end", peer: e.peer, turn: open.id, ms: Date.now() - open.start, ...open.attribution, preparedRoles: open.preparedRoles, ...(open.tokens ? { tokens: open.tokens } : {}), ...(files !== undefined ? { files, snapshotMs } : {}) });
7810
+ if (nativeFactsTurn ? (nativeCompletedAt.get(e.peer) ?? -1) >= open.start : definitionOf(e.peer)?.turnEnd !== "native-hook" || (nativeCompletedAt.get(e.peer) ?? -1) >= open.start) event({ type: "turn_end", peer: e.peer, turn: open.id, ms: Date.now() - open.start, ...open.attribution, preparedRoles: open.preparedRoles, ...(open.tokens ? { tokens: open.tokens } : {}), ...(files !== undefined ? { files, snapshotMs } : {}), ...noteObservedModel(e.peer, observedTurnModel(e.peer)) });
7645
7811
  if (!nativeFactsTurn && definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
7646
7812
  if ((bus.peers.get(e.peer)?.state ?? e.state) === "idle") queueMicrotask(() => finishSupervisionTurn(e.peer));
7647
7813
  turnEnded.set(e.peer, Date.now());
@@ -8005,10 +8171,11 @@ export async function startDaemon(opts: DaemonOptions) {
8005
8171
  /** The refusal of a start request while recovery holds mutations (#1088): the old sentence first, then whether the peer already runs and the step that works. */
8006
8172
  const startHeldByRecovery = (peer: unknown): string => {
8007
8173
  const held = "recovery is holding mutations";
8174
+ const recoveryExit = recoveryOperationId ? ` If a restoration launch was refused, fix its cause and close that launch terminal; run ahub recovery status ${recoveryOperationId}, then ahub recovery resume ${recoveryOperationId} once its runner blocks or exits.` : "";
8008
8175
  if (typeof peer !== "string" || !PEER_ID.test(peer)) return `${held}; no peer was started. Wait for the recovery to finish (ahub recovery status shows where it is), then start the peer again`;
8009
8176
  const owner = bus.peers.get(peer);
8010
8177
  if (owner && owner.state !== "offline") return `${held}, and ${peer} is already running, so there is nothing to start. Wait for the recovery to finish (ahub recovery status shows where it is), then check ${peer} with ahub status. If the recovery names ${peer} as blocked, a person repairs it with ahub recovery reattach <operation-id> ${peer}, or ends the hold with ahub recovery resume or abort`;
8011
- return `${held}, so ${peer} was not started. Wait for the recovery to finish (ahub recovery status shows where it is), then start it with ${startCommand(peer)}`;
8178
+ return `${held}, so ${peer} was not started. Wait for the recovery to finish (ahub recovery status shows where it is), then start it with ${startCommand(peer)}${recoveryExit}`;
8012
8179
  };
8013
8180
 
8014
8181
  async function stopPeer(peer: unknown, rosterRemoval = false, operational?: {actor:string;current:()=>void}): Promise<Record<string, unknown>> {
@@ -8477,7 +8644,8 @@ export async function startDaemon(opts: DaemonOptions) {
8477
8644
  ...HUB_TOOLS.map((name) => [`tools.${name}.approval_mode`, '"approve"']),
8478
8645
  ].flatMap(([k, v]) => ["-c", `mcp_servers.agent-hub.${k}=${v}`]),
8479
8646
  preamble: sessionRoleContract(peer),
8480
- onUsage: (rateLimits, hard) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard); },
8647
+ onUsage: (rateLimits, hard, accountUsage) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard, Date.now(), accountUsage); },
8648
+ usagePause: { current: () => budget.record(peer) !== undefined, subscribe: changed => budget.watchPause(peer, changed) },
8481
8649
  usagePollMs: config.budget.poll_min * 60_000,
8482
8650
  cwd: executionCwd,
8483
8651
  watchdogMs: config.watchdog_ms,
@@ -8587,7 +8755,7 @@ export async function startDaemon(opts: DaemonOptions) {
8587
8755
  sessionId: args.sessionId, sessionFile: args.sessionFile,
8588
8756
  admitBudget: async (envs, unit) => unit === "model_calls" ? [] : tasks.admitExecutionEnvelopes(envs, peer, unit),
8589
8757
  relay: { url: modelRelay.url, token: modelRelay.token, models: modelRelay.models.map((id) => ({ id, contextWindow: id.startsWith("mlx/") ? Math.min(routing.pi.mlx_max_context_tokens, config.mlx.provider === "ollama" ? (config.mlx.contextWindow ?? 8192) : routing.pi.mlx_max_context_tokens) : routing.pi.dgx_max_context_tokens, maxTokens: id === "hub/auto" ? (config.mlx.enabled === false ? 8192 : Math.min(config.mlx.maxTokens ?? 2048, 8192)) : id.startsWith("mlx/") ? (config.mlx.maxTokens ?? 2048) : 8192 })) },
8590
- tools: [...TOOL_SCHEMAS.map((t) => t.function), ...sessionTitleTools([...profileTaskTools(resolvedProfile, lifecycleConfig.stages, lifecycleConfig.mode !== "off"), ...CONDUCTOR_TOOLS], adapter?.title === "hub").map((t) => ({ name: t.name, description: t.description, parameters: t.inputSchema }))],
8758
+ tools: [...TOOL_SCHEMAS.map((t) => t.function), ...sessionTitleTools([...profileTaskTools(resolvedProfile, lifecycleConfig.stages, lifecycleConfig.mode !== "off", lifecycleConfig.mode !== "off" && lifecycleConfig.security !== undefined, lifecycleConfig.mode !== "off"), ...CONDUCTOR_TOOLS], adapter?.title === "hub").map((t) => ({ name: t.name, description: t.description, parameters: t.inputSchema }))],
8591
8759
  executeTool: async (name, raw, callId, sessionId, signal, context) => {
8592
8760
  const reviewToolTurn = reviewObserverHeld(peer) || pi.budgetEnvelopes.some(isReviewObserverExcluded) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded);
8593
8761
  if (MEMORY_READ_TOOLS.has(name)) validateMemoryRead(name, raw as Record<string, unknown>);
@@ -8792,6 +8960,8 @@ export async function startDaemon(opts: DaemonOptions) {
8792
8960
  profile: resolvedProfile,
8793
8961
  sdlcStages: lifecycleConfig.stages,
8794
8962
  sdlcCriteria: lifecycleConfig.mode !== "off",
8963
+ sdlcAudit: lifecycleConfig.mode !== "off" && lifecycleConfig.security !== undefined,
8964
+ sdlcSurvey: lifecycleConfig.mode !== "off",
8795
8965
  taskTool: (name, a, turn) => name === "hub_ask" && turn.signal ? invocationRequestSignal.run({ signal: turn.signal, current: () => !turn.signal!.aborted }, () => taskOp(peer, name, a, true, turn.pii)) : taskOp(peer, name, a, true, turn.pii),
8796
8966
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, local, context, envs),
8797
8967
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, local, context, envs),
@@ -8901,6 +9071,7 @@ export async function startDaemon(opts: DaemonOptions) {
8901
9071
  const reviewer = adapter.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["reviewer-print"]({
8902
9072
  ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride && !adapter.modelOverride.acp ? { getModelOverride: () => modelSelection(peer) } : {}),
8903
9073
  backend, cwd: executionCwd,
9074
+ maxMinutes: () => config.review.max_minutes ?? DEFAULT_REVIEW_MAX_MINUTES,
8904
9075
  mcpConfig: JSON.stringify({ mcpServers: { "agent-hub": { command: process.execPath, args: ["run", SERVER_JS], env: toolEnv(peer, true) } } }),
8905
9076
  systemPrompt: sessionRoleContract(peer),
8906
9077
  watchdogMs: config.watchdog_ms,
@@ -8925,7 +9096,35 @@ export async function startDaemon(opts: DaemonOptions) {
8925
9096
  },
8926
9097
  facts: env => env.private ? undefined : reviewDiff(executionCwd, env.refs?.commit, { privatePath: path => isDenied(path, config.local.deny) || matchesPolicy(executionCwd, path, config.pii?.paths ?? [], true), nameable: tasks.nameable }),
8927
9098
  verdictSince: (task, since) => board.get(task)?.history.some(h => h.by === peer && h.at >= since && (h.event === "approved" || h.event === "changes_requested")) === true,
8928
- onUsage: usage => void addTokens(peer, (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0)),
9099
+ onQuota: (value, attempt, current) => {
9100
+ const reading = nativeReviewerQuota(value);
9101
+ if (!reading || !current() || bus.peers.get(peer) !== reviewer || !/^[a-f0-9]{32}$/.test(attempt)) return false;
9102
+ unsettledReviewerQuota.set(attempt, { account: accountOf(peer), peer });
9103
+ budget.report(peer, [reading], true);
9104
+ return budget.record(peer) !== undefined;
9105
+ },
9106
+ quotaSettled: attempt => {
9107
+ if (unsettledReviewerQuota.get(attempt)?.peer !== peer) return;
9108
+ unsettledReviewerQuota.delete(attempt);
9109
+ queueMicrotask(() => budget.tick()); // Existing Budget handoff, only after the owned attempt settled.
9110
+ },
9111
+ usageIntent: (attempt, task) => {
9112
+ if (!softTokenAccount(peer) || !event({ type: "reviewer_accounting", peer: accountOf(peer), attempt, outcome: "started" })) return false;
9113
+ kimiUsage.reviewerAccounting(peer, attempt, "started");
9114
+ return true;
9115
+ },
9116
+ usageSettled: (attempt, outcome) => {
9117
+ if (!softTokenAccount(peer) || !event({ type: "reviewer_accounting", peer: accountOf(peer), attempt, outcome })) return false;
9118
+ kimiUsage.reviewerAccounting(peer, attempt, outcome);
9119
+ return true;
9120
+ },
9121
+ onUsage: (usage, task, identity) => {
9122
+ if (identity && softTokenAccount(peer)) {
9123
+ kimiUsage.observeReviewer(peer, { id: identity.id, at: identity.at, ...(identity.model ? { model: identity.model } : {}),
9124
+ inputOther: usage.input_tokens ?? 0, inputCacheCreation: usage.cache_creation_input_tokens ?? 0,
9125
+ inputCacheRead: usage.cache_read_input_tokens ?? 0, output: usage.output_tokens ?? 0 }, { attribution: taskAttribution(peer, task) });
9126
+ } else addTokens(peer, (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0), task);
9127
+ },
8929
9128
  onNoVerdict: (diagnostic, current) => {
8930
9129
  const task = board.get(diagnostic.task);
8931
9130
  const observerHeld = reviewer.reviewObserverInputHeld();
@@ -8939,6 +9138,14 @@ export async function startDaemon(opts: DaemonOptions) {
8939
9138
  onUnavailable: (failure, current) => {
8940
9139
  const attached = () => current() && bus.peers.get(peer) === reviewer;
8941
9140
  if (!attached()) return false;
9141
+ if (failure.cause === "quota") {
9142
+ const readings = (failure.quota ?? []).map(nativeReviewerQuota).filter((row): row is NonNullable<typeof row> => row !== undefined);
9143
+ // ponytail: reviewer-only children have no attached native quota transport. Only an attached account sibling
9144
+ // or Budget's existing evaluate/expiry paths can end a pause; never infer an early reset here.
9145
+ if (readings.length && !budget.record(peer)) budget.report(peer, readings, true);
9146
+ // Canonical account handoff may already have moved this exact review while applying the hard pause.
9147
+ if (!tasks.reviewBindingCurrent(peer, failure.task, failure)) return true;
9148
+ }
8942
9149
  if (failure.cause === "start_failed") {
8943
9150
  // #722: the class (a closed list) is the only detail; never a path, native text or token.
8944
9151
  const reason = reviewerUnavailableReason(failure.causeClass ?? "unknown", failure.causeDetail);
@@ -9155,7 +9362,7 @@ export async function startDaemon(opts: DaemonOptions) {
9155
9362
  }
9156
9363
  function sdlcSettingsView() {
9157
9364
  let file: ReturnType<typeof loadSdlc> | undefined;
9158
- try { file = loadSdlc(opts.cwd, VERSION); } catch { /* unreadable file stays unknown */ }
9365
+ try { file = readSdlcFile(); } catch { /* unreadable file stays unknown */ }
9159
9366
  return {
9160
9367
  "sdlc.mode": { value: lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9161
9368
  "sdlc.required_checks": { value: lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
@@ -9207,7 +9414,7 @@ export async function startDaemon(opts: DaemonOptions) {
9207
9414
  rows: report.rows.map(row => row.private || privatePrs.has(row.pr) ? { private: true, ready: false, tasks: [], after: [], blockers: ["private lifecycle evidence unavailable"] }
9208
9415
  : mixed ? { pr: row.pr, tasks: row.tasks.filter(id => !privateIds.has(id)), ready: false, after: [], blockers: ["private dependency evidence unavailable"] }
9209
9416
  : { pr: row.pr, tasks: row.tasks, head: row.head, ready: row.ready, blockers: row.blockers, after: row.after,
9210
- ...(row.findings ? { findings: row.findings } : {}), ...(row.planConformance ? { planConformance: row.planConformance } : {}), ...(row.testIntegrity ? { testIntegrity: row.testIntegrity } : {}), ...(row.evalGate ? { evalGate: row.evalGate } : {}) }),
9417
+ ...(row.findings ? { findings: row.findings } : {}), ...(row.planConformance ? { planConformance: row.planConformance } : {}), ...(row.testIntegrity ? { testIntegrity: row.testIntegrity } : {}), ...(row.evalGate ? { evalGate: row.evalGate } : {}), ...(row.securityPass ? { securityPass: row.securityPass } : {}) }),
9211
9418
  order: mixed ? [] : report.order, ...(report.unordered ? { unordered: mixed ? [] : report.unordered } : {}), conflicts: mixed ? [] : report.conflicts });
9212
9419
  }
9213
9420
  /** A public read may use host GitHub authentication only for this project's current public scope. */
@@ -9764,7 +9971,7 @@ export async function startDaemon(opts: DaemonOptions) {
9764
9971
  desiredRouting = structuredClone(prepared.routing);
9765
9972
  acknowledgeConfiguration(sources, prepared.accepted);
9766
9973
  if (priorDesired !== JSON.stringify([desiredConfig, desiredRouting, acceptedSources.trustLayers])) configRevision++;
9767
- if (ready && changes.some(change => change.key === "tasks.queue_backpressure" || change.key.startsWith("tasks.queue_backpressure."))) tasks.scheduleQueuePressureRecheck();
9974
+ if (ready) { if (changes.some(change => change.key === "tasks.queue_backpressure" || change.key.startsWith("tasks.queue_backpressure."))) tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits(); }
9768
9975
  pendingRestart = configChanges({ ...config, roles: policyRoles }, candidate, [{ catalog: adapterCatalog, instances: declarations }, configIdentityScope(acceptedSources.identity), configIdentityScope(sources.identity)]).filter(change => change.applies === "restart").map(change => ({ key: change.key, reason: change.reason! }));
9769
9976
  pendingRestart.push(...routingChanges.filter(key => configApply(key).applies === "restart").map(key => ({ key, reason: configApply(key).reason! })));
9770
9977
  retainedConfig = retainedConfigAfterReload(sources, prepared.fileConfig, prepared.rejected, scope);
@@ -9853,6 +10060,11 @@ export async function startDaemon(opts: DaemonOptions) {
9853
10060
  else throw new Error(`${def.key} does not restore a boolean`);
9854
10061
  return next;
9855
10062
  }
10063
+ function conductorStartModeRefusal(def: SettingDef, value: SettingValue): string | undefined {
10064
+ const match = /^peers\.([^.]+)\.start_mode$/.exec(def.key);
10065
+ if (!match || value !== "headless") return undefined;
10066
+ return conductorPeer(config.roles) === match[1] ? `${match[1]} holds the conductor role, which needs an interactive session; move the role first (the roles block in .agenthub/config.json), then set the start mode` : undefined;
10067
+ }
9856
10068
  function rosterRemovalRefusal(peer: string, now: boolean): string | undefined {
9857
10069
  if (stopping || recoveryActive()) return "recovery or shutdown is holding roster changes";
9858
10070
  if (conductorPeer(config.roles) === peer) return `${peer} holds the conductor role; move the role before removing it`;
@@ -9978,6 +10190,9 @@ export async function startDaemon(opts: DaemonOptions) {
9978
10190
  const refusal = settingRefusal(def, value, authority);
9979
10191
  if (refusal) return { ok: false, error: refusal };
9980
10192
  const source = settingSource(authority);
10193
+ // #1408 R2: the conductor needs an interactive session, so its start mode cannot be set to headless while it holds the role. The refusal comes before any write, from the running policy.
10194
+ const modeRefusal = conductorStartModeRefusal(def, value);
10195
+ if (modeRefusal) return { ok: false, error: modeRefusal };
9981
10196
  if (def.group === "Roster") return changeRosterSetting(def, value, source, confirm, now === true, false, authority, reason);
9982
10197
  if (rosterChanging) return { ok: false, error: `roster change for ${rosterChanging} is in progress` };
9983
10198
  const peer = def.group === "Permissions" ? def.path.at(-1)! : undefined;
@@ -10248,6 +10463,11 @@ export async function startDaemon(opts: DaemonOptions) {
10248
10463
  try { return await reloadConfig(authority, key); } finally { structuralScopes.delete(key); }
10249
10464
  },
10250
10465
  event: entry => event(entry),
10466
+ conductor: () => {
10467
+ const peer = conductorPeer(config.roles);
10468
+ return peer && !turns.get(peer)?.private && !contextPii(peer) && !reviewObserverHeld(peer) ? peer : undefined;
10469
+ },
10470
+ recordSdlcInstruction: (by, paths) => event({ type: "sdlc_config_instruction", by, paths, instructionClaim: "person_direct_instruction" }),
10251
10471
  notify: text => notify(text),
10252
10472
  changed: () => writeStatus(),
10253
10473
  pending: () => pendingRestart,
@@ -10259,7 +10479,7 @@ export async function startDaemon(opts: DaemonOptions) {
10259
10479
  if (sdlcFileCache?.stamp !== stamp) {
10260
10480
  let value: { mode: string; requiredChecks: readonly string[] } | string;
10261
10481
  sdlcFileReads++;
10262
- try { const loaded = loadSdlc(opts.cwd, VERSION); value = { mode: loaded.mode, requiredChecks: loaded.requiredChecks }; } catch (error) { value = sanitize((error as Error).message).slice(0, 300); }
10482
+ try { const loaded = readSdlcFile(); value = { mode: loaded.mode, requiredChecks: loaded.requiredChecks }; } catch (error) { value = sanitize((error as Error).message).slice(0, 300); }
10263
10483
  sdlcFileCache = { stamp, value };
10264
10484
  }
10265
10485
  return sdlcFileCache.value;
@@ -10456,6 +10676,21 @@ export async function startDaemon(opts: DaemonOptions) {
10456
10676
  ? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
10457
10677
  };
10458
10678
  const incompatibleRecoveryTarget = () => {
10679
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("reviewer_quota")) {
10680
+ const proof = reviewerQuotaIntegrity();
10681
+ let explicit = config.review.gate !== undefined && config.review.gate !== DEFAULT_REVIEW_GATE || config.review.max_minutes !== undefined && config.review.max_minutes !== DEFAULT_REVIEW_MAX_MINUTES || config.review.unknown_quota !== undefined && config.review.unknown_quota !== DEFAULT_REVIEW_UNKNOWN_QUOTA;
10682
+ try {
10683
+ const texts = configSourceTexts(opts.cwd);
10684
+ explicit ||= CONFIG_FILES.some(name => {
10685
+ if (texts[name] === null) return false;
10686
+ const review = JSON.parse(texts[name]!).review;
10687
+ return review && typeof review === "object" && (Object.hasOwn(review, "gate") || Object.hasOwn(review, "max_minutes") || Object.hasOwn(review, "unknown_quota"));
10688
+ });
10689
+ } catch { return "reviewer quota compatibility is unknown; configuration could not be read"; }
10690
+ if (proof.rows || !proof.complete || proof.waits || explicit)
10691
+ return "target lacks reviewer_quota; retained accounting, wait deadlines or explicit reviewer quota policy require a supporting daemon";
10692
+ }
10693
+
10459
10694
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
10460
10695
  try { if (guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
10461
10696
  catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
@@ -10560,6 +10795,10 @@ export async function startDaemon(opts: DaemonOptions) {
10560
10795
  return "target lacks research_comparisons; persisted comparison plans, approvals or protocol context require a supporting daemon";
10561
10796
  if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_evidence")) && board.hasResearchEvidenceState())
10562
10797
  return "target lacks research_evidence; choose a daemon advertising research_evidence to preserve persisted links and revisions";
10798
+ if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_evidence_withdrawal")) && board.hasWithdrawnEvidenceState())
10799
+ return "target lacks research_evidence_withdrawal; choose a supporting daemon to preserve withdrawal revisions";
10800
+ if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("advisor_surveys")) && board.hasSurveyState())
10801
+ return "target lacks advisor_surveys; persisted survey candidates and considered-finding history require a supporting daemon";
10563
10802
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("project_autonomy")) {
10564
10803
  let needsAutonomy = autonomyConfirmed.size > 0;
10565
10804
  try {
@@ -10662,7 +10901,7 @@ export async function startDaemon(opts: DaemonOptions) {
10662
10901
  recoveryPhase = undefined;
10663
10902
  recoveryPeerSnapshot = undefined;
10664
10903
  clearTimeout(recoveryLeaseTimer);
10665
- budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10904
+ budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10666
10905
  writeStatus();
10667
10906
  return { t: "recovery", ok: true, aborted: true, recovery: recoveryView() };
10668
10907
  }
@@ -10702,7 +10941,7 @@ export async function startDaemon(opts: DaemonOptions) {
10702
10941
  }
10703
10942
  if (msg.op === "release") {
10704
10943
  if (recoveryPhase === "released") {
10705
- bus.setRecoveryHold(false); budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10944
+ bus.setRecoveryHold(false); budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10706
10945
  return { t: "recovery", ok: true, released: true, recovery: recoveryView() };
10707
10946
  }
10708
10947
  if (recoveryPhase !== "restored") return recoveryError("recovery is not restored");
@@ -10718,8 +10957,9 @@ export async function startDaemon(opts: DaemonOptions) {
10718
10957
  archiveRestartSnapshot(opts.stateDir, op);
10719
10958
  recoveryPhase = "released";
10720
10959
  clearTimeout(recoveryLeaseTimer);
10960
+ reconcileGuidanceProbes();
10721
10961
  bus.setRecoveryHold(false);
10722
- budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10962
+ budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10723
10963
  writeStatus();
10724
10964
  return { t: "recovery", ok: true, released: true, recovery: recoveryView() };
10725
10965
  }
@@ -11587,6 +11827,7 @@ export async function startDaemon(opts: DaemonOptions) {
11587
11827
  if (launch.generation && launch.generation !== owner.sessionGeneration) return void reply({ ok: false });
11588
11828
  launch.generation = owner.sessionGeneration;
11589
11829
  launch.transcript = native.transcriptPath;
11830
+ if (native.model) hookModels.set(peer, native.model);
11590
11831
  const callStarted = performance.now();
11591
11832
  const tally = () => tallyHook(peer, callStarted, msg.startedMs);
11592
11833
  const current = () => !stopping && nativeHookLaunches.get(peer, msg.nativeLaunchId) === launch && bus.peers.get(peer) === owner && owner.sessionGeneration === launch.generation && owner.state !== "offline";
@@ -11992,6 +12233,48 @@ export async function startDaemon(opts: DaemonOptions) {
11992
12233
  ).finally(() => { taskOpsInFlight--; });
11993
12234
  return;
11994
12235
  }
12236
+ if (msg.op === "survey-start" || msg.op === "survey-show") {
12237
+ if (Object.keys(msg).some(key => !["t", "rid", "op", "focus", "id"].includes(key))) return void reply({ ok: false, error: "survey accepts only its task id or focus; remove unknown fields" });
12238
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
12239
+ if (!asker) return void reply({ ok: false, error: "only the person or current configured conductor may start or show advisor surveys" });
12240
+ const externalOwner = c.externalOwner;
12241
+ const sessionCurrent = c.role === "console" ? () => { if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed"); } : operationalCurrent(sock);
12242
+ const fence = () => {
12243
+ try {
12244
+ sessionCurrent();
12245
+ if (externalOwner && !currentExternalTools(c, true)) return "survey execution root changed; reconnect and retry";
12246
+ sessionCurrent();
12247
+ if (c.peer !== (asker === USER ? undefined : asker) || c.externalOwner !== externalOwner || c.toolsOwner) return "survey actor changed; reconnect and retry";
12248
+ if (c.peer && (turns.get(c.peer)?.private || contextPii(c.peer))) return "survey unavailable during private input";
12249
+ return recoveryActive() || stopping ? "recovery or shutdown holds survey writes; retry after release" : undefined;
12250
+ } catch { return "survey person or conductor session changed; reconnect and retry"; }
12251
+ };
12252
+ const refusal = fence(); if (refusal) return void reply({ ok: false, error: refusal });
12253
+ if (msg.op === "survey-show") {
12254
+ try { return void reply({ ok: true, survey: tasks.surveyShow(asker, msg.id) }); }
12255
+ catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "survey read unavailable").slice(0, 300) }); }
12256
+ }
12257
+ taskOpsInFlight++;
12258
+ void tasks.surveyStart(asker, { focus: msg.focus }, fence).then(result => reply({ ok: true, ...result }),
12259
+ (error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) })).finally(() => { taskOpsInFlight--; });
12260
+ return;
12261
+ }
12262
+ if (msg.op === "audit-start" || msg.op === "audit-show") {
12263
+ // #1403 A4: the person or the one configured conductor starts and reads a security audit. Every request gets a reply, a refusal included.
12264
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
12265
+ if (!asker) return void reply({ ok: false, error: "only the console user or the configured conductor may use security audits; ask the person to run ahub sdlc audit" });
12266
+ if (msg.op === "audit-show") {
12267
+ try { return void reply({ ok: true, audit: tasks.auditShow(asker, msg.id) ?? null }); }
12268
+ catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "audit readback unavailable").slice(0, 300) }); }
12269
+ }
12270
+ if (recoveryActive() || stopping) return void reply({ ok: false, error: "recovery or shutdown is holding task writes; retry ahub sdlc audit start after it ends" });
12271
+ taskOpsInFlight++;
12272
+ void tasks.auditStart(asker, { profile: msg.profile, since: msg.since }, () => recoveryActive() || stopping ? "recovery or shutdown is holding task writes; retry ahub sdlc audit start after it ends" : undefined).then(
12273
+ result => reply({ ok: true, ...result }),
12274
+ (error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) }),
12275
+ ).finally(() => { taskOpsInFlight--; });
12276
+ return;
12277
+ }
11995
12278
  if (msg.op === "merge") {
11996
12279
  // #786 T1: the person or the one configured conductor asks for a guarded merge. Every request gets a reply, a refusal included.
11997
12280
  const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
@@ -12004,6 +12287,27 @@ export async function startDaemon(opts: DaemonOptions) {
12004
12287
  );
12005
12288
  return;
12006
12289
  }
12290
+ if (msg.op === "configure") {
12291
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
12292
+ if (!asker) return void reply({ ok: false, error: "only the console user or current configured conductor may configure SDLC" });
12293
+ if (Object.keys(msg).some(key => !["t", "rid", "op", "mode", "required_checks", "instructionClaim"].includes(key)))
12294
+ return void reply({ ok: false, error: "sdlc configure accepts only mode and required_checks; protected settings remain person-only" });
12295
+ const externalOwner = c.externalOwner;
12296
+ const session = c.role === "console" ? () => { if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed; reconnect before configuring SDLC"); } : operationalCurrent(sock);
12297
+ const current = () => {
12298
+ session();
12299
+ if (c.toolsOwner || c.externalOwner !== externalOwner || externalOwner && !currentExternalTools(c, true)) throw new Error("SDLC caller or execution root changed; reconnect before configuring");
12300
+ session();
12301
+ if (asker !== USER && (c.peer !== asker || conductorPeer(config.roles) !== asker || turns.get(asker)?.private || contextPii(asker) || reviewObserverHeld(asker) || reviewObserverInput(asker)))
12302
+ throw new Error("SDLC configuration unavailable for private, observer or changed conductor input");
12303
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new Error("recovery or shutdown holds SDLC configuration; retry after release");
12304
+ };
12305
+ try { current(); } catch { return void reply({ ok: false, error: "SDLC configuration authority unavailable; reconnect in a public current conductor session" }); }
12306
+ taskOpsInFlight++;
12307
+ void configEditor!.configureSdlc(asker, { ...(Object.hasOwn(msg, "mode") ? { mode: msg.mode } : {}), ...(Object.hasOwn(msg, "required_checks") ? { required_checks: msg.required_checks } : {}), instructionClaim: msg.instructionClaim }, current)
12308
+ .then(reply, () => reply({ ok: false, error: "SDLC configuration could not be completed; inspect the file and event log before retrying" })).finally(() => { taskOpsInFlight--; });
12309
+ return;
12310
+ }
12007
12311
  if (msg.op === "authorize-release") {
12008
12312
  const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
12009
12313
  if (!asker) return void reply({ ok: false, error: "only the console user or the configured conductor may authorize a release" });
@@ -12045,7 +12349,7 @@ export async function startDaemon(opts: DaemonOptions) {
12045
12349
  if (tasks.isPii(now)) return { id: now.id, title: tasks.publicTitle(now), private: true };
12046
12350
  if (task.history.length !== now.history.length || !statuses.has(task.id)) throw new Error("task changed");
12047
12351
  const status = statuses.get(task.id)!;
12048
- const safeStatus = Object.fromEntries(["mode", "stage", "blockers", "ready", "actor", "next", "spec", "playbook", "criteria", "definition", "entry", "exit", "planConformance", "testIntegrity", "evalGate", "findings"].filter(key => key in status).map(key => [key, publicReadValue(status[key as keyof typeof status])]));
12352
+ const safeStatus = Object.fromEntries(["mode", "stage", "blockers", "ready", "actor", "next", "spec", "playbook", "criteria", "definition", "entry", "exit", "planConformance", "testIntegrity", "evalGate", "securityPass", "findings"].filter(key => key in status).map(key => [key, publicReadValue(status[key as keyof typeof status])]));
12049
12353
  return { id: now.id, title: tasks.publicTitle(now), receipt: publicReadValue(tasks.publicView(now).sdlc), ...safeStatus };
12050
12354
  });
12051
12355
  current(); reply({ ok: true, public: true, mode: lifecycleConfig.mode, rows, truncated: selected.length > 100 });
@@ -12292,12 +12596,13 @@ export async function startDaemon(opts: DaemonOptions) {
12292
12596
  case "guidance_probe_register":
12293
12597
  case "guidance_probe_start":
12294
12598
  case "guidance_probe_show":
12599
+ case "guidance_probe_receipts":
12295
12600
  case "guidance_probe_cancel": {
12296
12601
  const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12297
12602
  if ((role !== "console" && role !== "tools") || !actor) return void reply({ ok: false, error: "guidance probes require a person or the current configured conductor" });
12298
12603
  if (stopping || recoveryActive() || bus.isRecoveryHeld) return void reply({ ok: false, error: "recovery or shutdown is holding guidance probe operations; inspect retained state after release" });
12299
12604
  const operation = msg.t === "guidance_probe_register" ? "guidance probe register" : msg.t === "guidance_probe_start" ? "guidance probe start"
12300
- : msg.t === "guidance_probe_show" ? "guidance probe show" : "guidance probe cancel";
12605
+ : msg.t === "guidance_probe_show" ? "guidance probe show" : msg.t === "guidance_probe_receipts" ? "guidance probe receipts" : "guidance probe cancel";
12301
12606
  let authorityCurrent: () => void;
12302
12607
  if (role === "tools") {
12303
12608
  try { authorityCurrent = admitOperational(sock, operation); }
@@ -12335,14 +12640,15 @@ export async function startDaemon(opts: DaemonOptions) {
12335
12640
  const run = () => {
12336
12641
  current();
12337
12642
  if (recoveryActive() || bus.isRecoveryHeld || stopping) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance probe operations; inspect retained state after release");
12338
- const action = () => msg.t === "guidance_probe_register" ? tasks.guidanceProbeRegister(actor, input)
12643
+ const action = (): Promise<ProbePublicReceipt | ProbePublicStatus | ProbeReceiptExport> => msg.t === "guidance_probe_register" ? tasks.guidanceProbeRegister(actor, input)
12339
12644
  : msg.t === "guidance_probe_start" ? tasks.guidanceProbeStart(actor, msg.id, msg.revision, msg.variantId)
12340
12645
  : msg.t === "guidance_probe_show" ? tasks.guidanceProbeShow(actor, msg.id)
12646
+ : msg.t === "guidance_probe_receipts" ? tasks.guidanceProbeReceipts(actor, msg.id)
12341
12647
  : tasks.guidanceProbeCancel(actor, msg.id, msg.revision);
12342
12648
  const withRequest = () => guidanceProbeRequestContext.run(requestContext, action);
12343
12649
  return role === "tools" ? operationalContext.run({ actor, current }, withRequest) : withRequest();
12344
12650
  };
12345
- void Promise.resolve().then(run).then(value => reply(msg.t === "guidance_probe_show" ? { ok: true, status: value } : { ok: true, receipt: value }), error => {
12651
+ void Promise.resolve().then(run).then(value => reply(msg.t === "guidance_probe_show" ? { ok: true, status: value } : msg.t === "guidance_probe_receipts" ? { ok: true, receipts: value } : { ok: true, receipt: value }), error => {
12346
12652
  if (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError) return reply({ ok: false, error: error.message });
12347
12653
  if (error instanceof OperationalAuthorityError) return reply(operationalFailure(error));
12348
12654
  return reply({ ok: false, error: "guidance probe operation is unconfirmed; inspect retained state before retrying" });
@@ -12472,6 +12778,7 @@ export async function startDaemon(opts: DaemonOptions) {
12472
12778
  catch { return void reply({ t: "task", ok: false, error: "public release read unavailable" }); }
12473
12779
  }
12474
12780
  // #601: ahub study is the person's. A tools connection (any agent) may use the hub_study_* tools, never these op names, whatever Tasks would answer.
12781
+ if ((msg.op === "study_evidence" || msg.op === "study_check") && c.role !== "console") return void reply({ t: "task", ok: false, error: "task inventory and synthesis checks are console commands; ask the person to run ahub study evidence --task or ahub study check; a single link is readable through hub_evidence_read" });
12475
12782
  if (String(msg.op).startsWith("study_") && c.role !== "console") return void reply({ t: "task", ok: false, error: "ahub study draft, revise, approve and close are console commands; agents use the hub_study_* tools" });
12476
12783
  if (c.toolsOwner && !IMPLEMENTER_HUB_TOOL_NAMES.includes(String(msg.op))) return void reply({ t: "task", ok: false, error: "tool is not available to this Claude implementer child" });
12477
12784
  if (recoveryActive() && recoveryPhase !== "preparing" && String(msg.op) !== "hub_checkpoint") return void reply({ t: "task", ok: false, error: msg.op === "hub_visual" || msg.op === "hub_visual_show" ? visualOperational("recovery").message : "recovery is holding mutations" });
@@ -12585,7 +12892,7 @@ export async function startDaemon(opts: DaemonOptions) {
12585
12892
  case "budget":
12586
12893
  if (c.role !== "console") {
12587
12894
  if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
12588
- return void reply({ t: "budget", ok: true, budget: publicPeerBudget(budget.status(), text => tasks.nameable(text)), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate });
12895
+ return void reply({ t: "budget", ok: true, budget: publicPeerBudget(budget.status(), text => tasks.nameable(text)), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
12589
12896
  }
12590
12897
  if (recoveryActive()) return void reply({ t: "budget", ok: false, error: "recovery is holding mutations" });
12591
12898
  if (msg.resume) {
@@ -12596,7 +12903,7 @@ export async function startDaemon(opts: DaemonOptions) {
12596
12903
  if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
12597
12904
  budget.report(String(msg.set.peer), [{ id: msg.set.window === "week" ? "week" : "5h", kind: "manual", used, ...(msg.set.resetsInMs ? { resetsAt: Date.now() + Number(msg.set.resetsInMs) } : {}), source: "ahub budget set" }]);
12598
12905
  }
12599
- return void reply({ t: "budget", ok: true, budget: budget.status(), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate });
12906
+ return void reply({ t: "budget", ok: true, budget: budget.status(), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
12600
12907
  case "usage": {
12601
12908
  // #683 U2: the console, the person and a configured planner read usage; every other agent is refused. Always answered (rid).
12602
12909
  const planner = c.role === "tools" && !!c.peer && !!config.roles[c.peer]?.includes("planner");
@@ -12859,7 +13166,7 @@ export async function startDaemon(opts: DaemonOptions) {
12859
13166
  { const every = opts.handoffCatchUpMs ?? 5 * 60_000, watch = opts.handoffWatchMs ?? 15_000;
12860
13167
  const periodic = setInterval(() => void handoffCatchUp(), every), descriptorWatch = setInterval(handoffWatch, watch);
12861
13168
  periodic.unref?.(); descriptorWatch.unref?.(); intervals.push(periodic, descriptorWatch); }
12862
- tasks.scheduleQueuePressureRecheck();
13169
+ tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
12863
13170
  for (const name of opts.configWatch === false ? [] : CONFIG_SOURCE_FILES) {
12864
13171
  const path = join(opts.cwd, ".agenthub", name);
12865
13172
  const listener = (current: import("node:fs").Stats, previous: import("node:fs").Stats) => {