@staix/agent-hub 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
package/src/hub/daemon.ts CHANGED
@@ -1,3 +1,4 @@
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
4
  import { GuidanceProbeError, probeSessionGeneration, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.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";
@@ -244,6 +247,7 @@ import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf
244
247
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
245
248
 
246
249
  import { START_AGENTS_DEFAULT, checkStartAgents } from "./start-agents.ts";
250
+ import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
247
251
  import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, terminalTemplate, type PeerStartConfig, type StartMode } from "./start-mode.ts";
248
252
  import { hasKimiHubMcp } from "../cli/kimi-mcp.ts";
249
253
  import type { TerminalOpener } from "./terminal-open.ts";
@@ -255,7 +259,8 @@ import { CaptureStore, configuredPolicy, recordsEnabled, looksSecret, DEFAULT_LE
255
259
  import { memoryProjectKey } from "@staix/agent-mem";
256
260
  import { AGENT_MEM_VERSION, MEMORY_SPLIT_INCOMPLETE, memoryProjectFor, openProfileMemory, openProfileCandidates, MemoryProfileBinding, type UnboundMemoryProfileReceipt } from "./memory-profile.ts";
257
261
  import { syncMemory, createIntentBriefSource, createStandalonePolicy } from "@staix/agent-mem";
258
- 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";
259
264
  import { MEMORY_READ_TOOLS, memoryRead, validateMemoryRead, sourceRead, validateSourceRead } from "./read-tools.ts";
260
265
  import { nativeRecall } from "../memory/recall.ts";
261
266
  import { promotionScreen, withoutPii, mentionsPrivatePath } from "./memory-policy.ts";
@@ -351,7 +356,7 @@ export interface HubConfig {
351
356
  /** Per-sender rate limits and repeat suppression for what agents send (issue #38). */
352
357
  limits: LimitsConfig;
353
358
  /** Reviewer choice from recorded review outcomes, once a reviewer has `min_reviews` of an implementer (issue #35). */
354
- 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 };
355
360
  /** After an unplanned stop, start Kimi, Pi and the local worker again with their recorded sessions (issue #37). */
356
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. */
357
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 };
@@ -422,7 +427,7 @@ export const DEFAULT_CONFIG: HubConfig = {
422
427
  terminal: { open: [] },
423
428
  start: { agents: [...START_AGENTS_DEFAULT] },
424
429
  limits: DEFAULT_LIMITS,
425
- 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 },
426
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 },
427
432
  capabilities: {},
428
433
  coordination: "advisory",
@@ -431,7 +436,7 @@ export const DEFAULT_CONFIG: HubConfig = {
431
436
  export { stateDirFor };
432
437
 
433
438
  /** Ids an external process may not claim: the console user and the adapters the daemon runs itself. */
434
- 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"]);
435
440
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
436
441
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
437
442
 
@@ -472,7 +477,19 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
472
477
  const roles: Record<string, string[]> = { ...DEFAULT_ROLES };
473
478
  const conductor = { ...DEFAULT_CONFIG.conductor };
474
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 };
475
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
+ }
476
493
  for (const name of CONFIG_FILES) {
477
494
  let file: Record<string, unknown>;
478
495
  if (layers && !layers.some(layer => layer.name === name)) continue;
@@ -482,11 +499,13 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
482
499
  if (!file.roles || typeof file.roles !== "object" || Array.isArray(file.roles)) throw new Error("roles must be an object of peer role lists");
483
500
  for (const [peer, assigned] of Object.entries(file.roles)) {
484
501
  conductorPeer({ [peer]: assigned });
485
- const definition = definitionOf(peer), ceiling = definition?.routing?.allowedRoles;
486
502
  const declared = assigned as string[];
487
- // #525 R1: planner needs a kind that can plan (projection.plannerEligible); such an entry is dropped with the ceiling notice, never thrown.
488
- roles[peer] = (ceiling ? declared.filter(role => ceiling.includes(role)) : declared).filter(role => role !== "planner" || !definition || definition.projection?.plannerEligible === true);
489
- 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);
490
509
  }
491
510
  }
492
511
  if (file.planner !== undefined) {
@@ -509,6 +528,7 @@ export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[]
509
528
  }
510
529
  }
511
530
  }
531
+ conductorPeer(declaredRoles);
512
532
  conductorPeer(roles);
513
533
  return { roles, conductor, ...(planner ? { planner } : {}), ...(notices.length ? { notices } : {}) };
514
534
  }
@@ -763,6 +783,12 @@ export interface DaemonOptions {
763
783
  /** Host-only bounds of the per-head CI watcher (#785 P1b); tests shorten them, never read from config or a tool. */
764
784
  ciWatch?: { deadlineMs?: number; pollMs?: number };
765
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;
766
792
  /** Host-only admission transport; never selected by project config or tools. */
767
793
  releaseHostAdmission?: (cwd: string) => Promise<ReleaseHostAdmission>;
768
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. */
@@ -920,8 +946,8 @@ export function resolutionRefusal(error: unknown): string {
920
946
  return RESOLUTION_CAUSES.find(([pattern]) => pattern.test(text))?.[1] ?? "resolution refused: inspect ahub queue show for the delivery's state";
921
947
  }
922
948
 
923
- /** 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". */
924
- 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 ?? "");
925
951
 
926
952
  let recoverySourcePackageDigest: string | null | undefined;
927
953
  function capturedRecoverySourceDigest(): string | undefined {
@@ -983,7 +1009,9 @@ export async function startDaemon(opts: DaemonOptions) {
983
1009
  const loadedConfig = recoveryConfiguration ?? (opts.config ? { ...opts.config, adapter_modules: moduleDeclarations.length ? moduleDeclarations : undefined }
984
1010
  : loadConfig(opts.cwd, startupLayers, undefined, externalDefinitions));
985
1011
  reviewerPoolConfig(loadedConfig.review, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS);
986
- 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);
987
1015
  // Preserve embedding-owned policy references, but never publish reloads into shared defaults.
988
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;
989
1017
  const adapterCatalog = createProjectAdapterCatalog(loadedConfig.adapters, externalDefinitions);
@@ -1265,9 +1293,18 @@ export async function startDaemon(opts: DaemonOptions) {
1265
1293
  for (const note of lifecycleConfig.deprecations ?? []) log(note);
1266
1294
  const resolvedProfile = resolveProfile(config.profile, config.profile_overrides);
1267
1295
  let roleAssignments = { ...resolvedProfile.catalog_roles, ...catalogAssignments(config.catalog_roles) };
1268
- 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) => {
1269
1299
  if (entry.type === "permission") log(`permission event recording failed at ${entry.event} for ${entry.peer}`);
1270
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
+ };
1271
1308
  const compatibleRoles = (peer: string) => [...catalog.roles.values()].filter(role => role.base.some(base => config.roles[peer]?.includes(base))).map(role => role.id).sort();
1272
1309
  const configuredRoles = (peer: string) => selectedRoles(peer, config.roles, roleAssignments, catalog).map(role => role.id);
1273
1310
  const dataRoleContract = (peer: string, contract: string) => config.data?.readonly.length && definitionOf(peer)?.trust.hubSandboxed === true
@@ -1294,12 +1331,12 @@ export async function startDaemon(opts: DaemonOptions) {
1294
1331
  preparedSessionRoles.set(peer, selected.map(role => role.id));
1295
1332
  preparedSessionRoleIdentities.set(peer, selected.map(roleIdentity));
1296
1333
  if (selected.length) event({ type: "role", peer, actor: "config", stage: "prepared", roles: selected.map(roleIdentity) });
1297
- return dataRoleContract(peer, roleContract(peer, config.roles, selected, resolvedProfile));
1334
+ return dataRoleContract(peer, roleContract(peer, config.roles, selected, resolvedProfile, lifecycleConfig.mode !== "off"));
1298
1335
  } catch (error) {
1299
1336
  preparedSessionRoles.delete(peer);
1300
1337
  preparedSessionRoleIdentities.delete(peer);
1301
1338
  log(`catalog role assignment refused for ${peer}: ${(error as Error).message}`);
1302
- const fallback = dataRoleContract(peer, roleContract(peer, config.roles, [], resolvedProfile));
1339
+ const fallback = dataRoleContract(peer, roleContract(peer, config.roles, [], resolvedProfile, lifecycleConfig.mode !== "off"));
1303
1340
  preparedSessionRoles.set(peer, []);
1304
1341
  preparedSessionRoleIdentities.set(peer, []);
1305
1342
  return fallback;
@@ -2346,6 +2383,13 @@ export async function startDaemon(opts: DaemonOptions) {
2346
2383
  } catch {
2347
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");
2348
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
+ }
2349
2393
  startupCleanup.push(() => guidanceProbeStore.close());
2350
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
2351
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
@@ -2834,6 +2878,7 @@ export async function startDaemon(opts: DaemonOptions) {
2834
2878
  let runnerState = await checkRunner.available(runnerRefreshAbort.signal);
2835
2879
  const orphanChecks = (await checkRunner.sweep()).map(line => boundedSafe(line) ? sanitize(line) : "orphan check: details withheld by privacy policy");
2836
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");
2837
2882
  let runnerStateAt = runnerState.checkedAt ?? Date.now(), refreshingRunner: Promise<void> | undefined;
2838
2883
  const refreshRunner = (): Promise<void> => {
2839
2884
  if (stopping || runnerRefreshAbort.signal.aborted) return Promise.resolve();
@@ -2931,6 +2976,7 @@ export async function startDaemon(opts: DaemonOptions) {
2931
2976
  const projectSpecs = specInspectorAt(opts.cwd);
2932
2977
  let specsMissingBlockHintShown = false;
2933
2978
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
2979
+ startupTimings.mark("task_ports");
2934
2980
  const tasks: Tasks = new Tasks({
2935
2981
  guidanceProbes: { store: guidanceProbeStore, session: by => {
2936
2982
  const request = guidanceProbeRequestContext.getStore();
@@ -2973,6 +3019,7 @@ export async function startDaemon(opts: DaemonOptions) {
2973
3019
  reviewContext: (by, task) => !!definitionOf(by)?.reviewer && (bus.peers.get(by) as ReviewerPrintPeer | undefined)?.reviewing === task ? "fresh" : "continuing",
2974
3020
  reviewObserverInput,
2975
3021
  onReviewObserverInput: latchReviewObserverInput,
3022
+ observerExcludedTurn: peer => resolvedProfile.name === "research" && reviewObserverHeld(peer),
2976
3023
  // Proof belongs to the adapter generation actually started in the validated root. A role-only
2977
3024
  // reload cannot turn a canonical reviewer process into an isolated implementation owner.
2978
3025
  ownerIsolation: () => Object.fromEntries(extraIds.map(id => {
@@ -3039,6 +3086,7 @@ export async function startDaemon(opts: DaemonOptions) {
3039
3086
  return report;
3040
3087
  },
3041
3088
  specsRead: (action, paths) => projectSpecs.read(action, paths),
3089
+ auditSource: gitAuditSource(opts.cwd), // #1403 A4
3042
3090
  sdlc: {
3043
3091
  config: () => lifecycleConfig,
3044
3092
  gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
@@ -3117,6 +3165,18 @@ export async function startDaemon(opts: DaemonOptions) {
3117
3165
  }, sourceKnown: id => sourceRegistry.get(id) !== undefined,
3118
3166
  partsSchema: () => profileTaskTools(resolvedProfile, lifecycleConfig.stages, lifecycleConfig.mode !== "off").find(tool => tool.name === "hub_backlog_split")?.inputSchema.properties.parts },
3119
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
+ },
3120
3180
  experimentCheck: run => checkRunner.result(run),
3121
3181
  // The PII screen (issue #198): the model on this machine when MLX/Ollama is enabled, else the gateway on campus only.
3122
3182
  piiScreen: (text) => {
@@ -3126,7 +3186,10 @@ export async function startDaemon(opts: DaemonOptions) {
3126
3186
  },
3127
3187
  recordScreen: (record) => event({ type: "pii_screen", ...record }),
3128
3188
  quota: (): ReturnType<Budget["headroom"]> => projectBudgetHeadroom(budget.headroom(), accountMembers), // budget is built below; this runs at assignment time
3129
- 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
+ },
3130
3193
  sweep: taskSweepConfig(config.task_sweep),
3131
3194
  sweepHeld: () => stopping || recoveryActive(),
3132
3195
  submodules: () => factsRepo ? submodulePaths(factsRepo) : [], // #798 D1: read from .gitmodules, no git call
@@ -3159,6 +3222,7 @@ export async function startDaemon(opts: DaemonOptions) {
3159
3222
  failing: () => ({ ...bus.failingPeers(), ...Object.fromEntries(reviewerUnavailable) }),
3160
3223
  held: () => Object.fromEntries(bus.knownPeers().flatMap((peer) => { const hold = queueHold(peer); return hold ? [[peer, hold]] : []; })),
3161
3224
  });
3225
+ startupTimings.mark("task_board");
3162
3226
  /**
3163
3227
  * #1221 T2: the bounded proposal queue. The store is built even while the mode is off (its tables are additive and a
3164
3228
  * person may turn the mode on at the next reload), and nothing in it runs until an explicit decision arrives: reading
@@ -3295,6 +3359,7 @@ export async function startDaemon(opts: DaemonOptions) {
3295
3359
  return true;
3296
3360
  };
3297
3361
  tasks.recoverIntegrations();
3362
+ startupTimings.mark("task_recovery");
3298
3363
  // #1221 T2 AC6: a restart keeps the dedupe keys, the dispositions and an action outcome the hub never observed. A
3299
3364
  // pending proposal whose task moved or closed expires here, once, with nothing replayed.
3300
3365
  void supervisionProposals.recover().catch((error: Error) => log(`supervision reconcile failed: ${error.message}`));
@@ -3350,7 +3415,8 @@ export async function startDaemon(opts: DaemonOptions) {
3350
3415
  if (!observation) return;
3351
3416
  if (reviewObserverHeld(peer) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded)) { progress.clearPeer(peer); return; }
3352
3417
  const toolName = observation.name.replace(/^mcp__[^ ]+__/, "");
3353
- 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;
3354
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)
3355
3421
  try {
3356
3422
  const candidates = board.list().filter(task => task.owner === peer && ["in_progress", "changes_requested"].includes(task.state));
@@ -3476,8 +3542,20 @@ export async function startDaemon(opts: DaemonOptions) {
3476
3542
  // same peer cannot undo a settlement.
3477
3543
  const turnEnded = new Map<PeerId, number>();
3478
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>();
3479
3547
  startupTimings.mark("task_runtime");
3480
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
+ }
3481
3559
  try { opts.startupSeedObserved?.({ readPasses: startupSeeds.readPasses, readBytes: startupSeeds.readBytes }); } catch { /* Diagnostic observers cannot change replay or readiness. */ }
3482
3560
  const nativeStopsSeen = startupSeeds.nativeStopsSeen;
3483
3561
  startupTimings.mark("native_stop_seed");
@@ -3511,6 +3589,7 @@ export async function startDaemon(opts: DaemonOptions) {
3511
3589
  /** What quiescence was judged on, for the log when an integration waits on it. */
3512
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"}`;
3513
3591
  board.onChange = (t, h) => {
3592
+ tasks.reviewQuotaTaskChanged(t);
3514
3593
  if (!isClosedTaskState(t.state) && t.state !== "backlog") {
3515
3594
  if (t.owner) inboxPolling.reset(t.owner);
3516
3595
  if (t.reviewer) inboxPolling.reset(t.reviewer);
@@ -3870,11 +3949,13 @@ export async function startDaemon(opts: DaemonOptions) {
3870
3949
  if (budgetFeedSeen.get(hold.peer) !== key && supervision.budgetPaused(hold.peer, hold.resetsAt)) budgetFeedSeen.set(hold.peer, key);
3871
3950
  }
3872
3951
  };
3952
+ const unsettledReviewerQuota = new Map<string, { account: string; peer: string }>();
3873
3953
  const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
3874
3954
  definitionOf,
3875
3955
  pause: (peer) => bus.pause(peer),
3876
3956
  resume: (peer) => {
3877
3957
  if (!manualPaused.has(peer) && !conductorHolds.has(peer)) bus.resume(peer);
3958
+ queueMicrotask(() => tasks.refreshReviewerQuotaWaits());
3878
3959
  },
3879
3960
  requestCheckpoint: (peer) => requestCheckpoint(peer, "quota"),
3880
3961
  platformContext: async (peer) => {
@@ -3885,11 +3966,11 @@ export async function startDaemon(opts: DaemonOptions) {
3885
3966
  },
3886
3967
  attached: (peer) => bus.peers.has(peer),
3887
3968
  // Somebody other than the paused peer has to be there, or the handoff would only leave its tasks without an owner.
3888
- 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))),
3889
3970
  // A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
3890
3971
  // #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
3891
3972
  ledger: entry => event(entry),
3892
- 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() } : {}) }) },
3893
3974
  handoff: (peer, context, urgentOnly) => tasks.reassignForPause(peer, context, urgentOnly),
3894
3975
  resumed: (record) => {
3895
3976
  // Coalesce unread notices without forgetting the public moves they carried.
@@ -3920,6 +4001,7 @@ export async function startDaemon(opts: DaemonOptions) {
3920
4001
  const startupEvents = startupSeeds.events;
3921
4002
  budget.seedResets(startupEvents.flatMap(e => e.type === "quota_reset" ? [{ peer: e.peer, window: e.window, ...(e.resetsAt !== undefined ? { resetsAt: e.resetsAt } : {}) }] : []));
3922
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;
3923
4005
  const kimiEvents = new KimiEventWriter({ append: event, read: () => readEvents(join(opts.stateDir, "events.jsonl")) }, startupEvents);
3924
4006
  const kimiUsage = new KimiUsage({
3925
4007
  home: opts.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), ".kimi-code"),
@@ -3940,8 +4022,23 @@ export async function startDaemon(opts: DaemonOptions) {
3940
4022
  });
3941
4023
  startupCleanup.push(() => kimiUsage.stop());
3942
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
+ }
3943
4035
  startupTimings.mark("usage_seed");
3944
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
+ };
3945
4042
  const budgetPeerNotes = (): BudgetPeerNote[] => {
3946
4043
  const quota = budget.status();
3947
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);
@@ -4157,6 +4254,14 @@ export async function startDaemon(opts: DaemonOptions) {
4157
4254
  }
4158
4255
  return snapshotBudget;
4159
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
+ };
4160
4265
  const snapshotFailure = (what: string, error: unknown) => {
4161
4266
  if (error instanceof SnapshotBudgetExceeded) {
4162
4267
  if (!snapshotBudgetNoticed) log(`snapshot unavailable: ${error.message}`);
@@ -4774,7 +4879,7 @@ export async function startDaemon(opts: DaemonOptions) {
4774
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
4775
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.
4776
4881
  const register = (file: ScannedFile) => registerScanned(file, { registry: sourceRegistry, cwd: opts.cwd, piiPaths: config.pii?.paths ?? [], piiPatterns: () => activeRouting().signals.pii_patterns,
4777
- project: (extension, data) => projections.projectBytes(join(opts.cwd, `source${extension}`), data)?.text });
4882
+ project: (extension, data) => projections.projectBytes(join(opts.cwd, `source${extension}`), data) });
4778
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)) {
4779
4884
  if (run.outcome === "ran") log(`folder trigger ${run.id}: proposed ${run.tasks.map(id => `task #${id}`).join(", ")}`);
4780
4885
  else if (run.outcome === "failed" || run.outcome === "refused") log(`folder trigger ${run.id}: ${run.outcome}: ${sanitize(run.reason ?? "").slice(0, 160)}`);
@@ -4802,7 +4907,7 @@ export async function startDaemon(opts: DaemonOptions) {
4802
4907
  const SERVER_JS = join(import.meta.dir, "..", "..", "plugins", "agent-hub", "server.js");
4803
4908
  // What the hub's MCP server offers a native peer. Codex approves them in config, Kimi's requests for exactly these
4804
4909
  // names are answered by the hub; every call still passes daemon role/capability checks before its effects.
4805
- 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)];
4806
4911
  const HUB_TOOL_TITLES = new Set(HUB_TOOLS.map((name) => `mcp__agent-hub__${name}`));
4807
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 });
4808
4913
 
@@ -5095,7 +5200,7 @@ export async function startDaemon(opts: DaemonOptions) {
5095
5200
  const taskOp = async (...args: Parameters<typeof taskOpBody>): Promise<string> => {
5096
5201
  const [by, op, input] = args;
5097
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");
5098
- 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;
5099
5204
  const nativeTurn = turns.get(by);
5100
5205
  const effectful = ownerToolEffect(op, input);
5101
5206
  if (nativeTurn && effectful) nativeTurn.effectsPending = (nativeTurn.effectsPending ?? 0) + 1;
@@ -5117,13 +5222,13 @@ export async function startDaemon(opts: DaemonOptions) {
5117
5222
  const id = Number.isSafeInteger(proposed) && proposed! > 0 ? proposed : admittedId;
5118
5223
  auditConduct({ kind: "conduct", actor: by, action: op.slice(4), ...(id === undefined ? {} : { task: id }) });
5119
5224
  }
5120
- 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) : "";
5121
5226
  return hint ? `${text}\n\n${hint}` : text;
5122
5227
  } catch (error) {
5123
5228
  if (reviewTool && traceId !== undefined) reviewerToolObservers.get(by)?.(traceId, reviewTool, error instanceof Error ? error.message : "review tool refused");
5124
5229
  if (nativeTurn && effectful && !(error instanceof PreEffectToolRefusal) && turns.get(by) === nativeTurn) nativeTurn.taskEffect = true;
5125
5230
  // Keep proven pre-effect refusal identity/code for native receipts; only add body-free metadata.
5126
- 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) : "";
5127
5232
  if (hint && error instanceof Error) error.message += `\n\n${hint}`;
5128
5233
  throw error;
5129
5234
  } finally {
@@ -5157,6 +5262,15 @@ export async function startDaemon(opts: DaemonOptions) {
5157
5262
  && policyKey === JSON.stringify({ signals: activeRouting().signals, constraints: activeRouting().constraints, paths: config.pii?.paths ?? [], mlx: config.mlx, model: activeRouting().local.fixed_model });
5158
5263
  }
5159
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
+ }
5160
5274
  const answeringInvocation = (peer: PeerId): boolean => {
5161
5275
  if (invocations.answering(peer)) return true;
5162
5276
  if (!bus.hasInvocationTurn(peer)) return false;
@@ -5491,6 +5605,17 @@ export async function startDaemon(opts: DaemonOptions) {
5491
5605
  if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
5492
5606
  const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5493
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
+ }
5494
5619
  if (GUIDANCE_TOOL_NAMES.has(op)) {
5495
5620
  if (op === "hub_guidance_list" || op === "hub_guidance_show") return JSON.stringify(guidanceRead(by, op === "hub_guidance_list" ? "list" : "show", a, piiTurn));
5496
5621
  const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
@@ -5598,15 +5723,7 @@ export async function startDaemon(opts: DaemonOptions) {
5598
5723
  const campus = await onCampus().catch(() => false);
5599
5724
  return campus && eligible();
5600
5725
  },
5601
- screen: async (text, meta) => {
5602
- if (meta.origins.some(origin => origin.kind === "file" && matchesPolicy(opts.cwd, origin.origin, config.pii?.paths ?? []))) return false;
5603
- try { if (looksSecret(text) || activeRouting().signals.pii_patterns.some(pattern => new RegExp(pattern).test(text))) return false; }
5604
- catch { return false; }
5605
- if (!tasks.screenOn()) return true;
5606
- // Reuse the bounded host screen. Oversized/unknown is private, never an unscreened excerpt.
5607
- 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);
5608
- return verdict?.label === "clear";
5609
- },
5726
+ screen: screenSourceText,
5610
5727
  }));
5611
5728
  }
5612
5729
  if (MEMORY_READ_TOOLS.has(op)) {
@@ -5798,6 +5915,8 @@ export async function startDaemon(opts: DaemonOptions) {
5798
5915
  return JSON.stringify(await tasks.experimentRecord(by, a));
5799
5916
  case "hub_evidence_record":
5800
5917
  return JSON.stringify(await tasks.evidenceRecord(by, a));
5918
+ case "hub_evidence_read":
5919
+ return JSON.stringify(await tasks.evidenceRead(by, a));
5801
5920
  case "hub_study_handoff":
5802
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");
5803
5922
  return JSON.stringify(await tasks.studyHandoff(by, a.handoff));
@@ -5821,6 +5940,10 @@ export async function startDaemon(opts: DaemonOptions) {
5821
5940
  return JSON.stringify({ handoffs: handoffListView(), synced: false, syncing: true, pending });
5822
5941
  }
5823
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));
5824
5947
  case "study_draft":
5825
5948
  return JSON.stringify(await tasks.studyDraft(by, a));
5826
5949
  case "study_revise":
@@ -5885,7 +6008,7 @@ export async function startDaemon(opts: DaemonOptions) {
5885
6008
  case "hub_sdlc_record":
5886
6009
  return line(await tasks.recordSdlc(by, a.id, a.receipt));
5887
6010
  case "hub_review": {
5888
- 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);
5889
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.
5890
6013
  const verdict = reviewed.history.findLast(h => h.by === by && (h.event === "approved" || h.event === "changes_requested"));
5891
6014
  if (!piiTurn && !reviewTurn && !tasks.isPii(reviewed) && verdict && !verdict.withheld && typeof a.note === "string" && a.note && verdict.note?.startsWith(a.note)) {
@@ -5975,8 +6098,11 @@ export async function startDaemon(opts: DaemonOptions) {
5975
6098
  switch (op) {
5976
6099
  case "release_new":
5977
6100
  return JSON.stringify(await tasks.newRelease(by, { name: a.name, goal: a.goal, order: a.order }));
5978
- case "claim_verdict": // #901: a person's verdict on one declared claim; the reply names the slot and the verdict only, never a claim
5979
- 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
+ }
5980
6106
  case "github_import":
5981
6107
  return JSON.stringify(await tasks.importGitHub(by, { repo: a.repo, label: a.label, milestone: a.milestone }));
5982
6108
  case "release_show": {
@@ -6825,13 +6951,26 @@ export async function startDaemon(opts: DaemonOptions) {
6825
6951
  const owner = bus.peers.get(peer);
6826
6952
  return !!owner && modelAcpOwners.get(owner)?.acceptsModelOverride(model) === true;
6827
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
+ };
6828
6964
  const modelFallback = (peer: string): { model?: string; source: Exclude<ModelSource, "override"> } => {
6829
6965
  const declared = declarations[peer]?.model;
6830
6966
  if (isNativeModelToken(declared)) return { model: declared, source: "instance" };
6831
6967
  const owner = bus.peers.get(peer), model = owner ? modelLaunchModels.get(owner) : undefined;
6832
6968
  if (model !== undefined) return { model, source: "launch" };
6833
6969
  const baseline = owner ? modelAcpOwners.get(owner)?.modelOverrideState.baseline : undefined;
6834
- 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" };
6835
6974
  };
6836
6975
  const registerModelOwner = (owner: PeerAdapter): void => {
6837
6976
  const definition = definitionOf(owner.id);
@@ -6946,6 +7085,8 @@ export async function startDaemon(opts: DaemonOptions) {
6946
7085
  const modelCommandSafe = (input: Record<string, unknown>, grant: ModelGrant): Record<string, unknown> => {
6947
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"); }
6948
7087
  };
7088
+ const reviewerQuotaIntegrity = () => ({ ...reviewerAccountingIntegrity(reviewerJournalRows, reviewerJournalComplete),
7089
+ waits: board.list().filter(task => task.history.some(row => row.reviewerQuotaWait !== undefined)).length });
6949
7090
  const integrity = (older = 0) => {
6950
7091
  const queues = Object.fromEntries(Object.keys(bus.snapshot(false).queues).sort().map((id) => [id, bus.queueIds(id)]));
6951
7092
  const boardState = board.list().sort((a, b) => a.id - b.id).map((t) => {
@@ -6960,6 +7101,8 @@ export async function startDaemon(opts: DaemonOptions) {
6960
7101
  const researchComparisons = board.researchComparisonIntegrity();
6961
7102
  const researchRunners = board.runnerReceiptIntegrity();
6962
7103
  const researchEvidence = board.researchEvidenceIntegrity();
7104
+ const reviewerQuota = reviewerQuotaIntegrity();
7105
+ const advisorSurveys = board.surveyIntegrity();
6963
7106
  const guidanceVariants = board.guidanceVariantsIntegrity();
6964
7107
  const guidanceProbes = guidanceProbeStore.integrity();
6965
7108
  const executionReferences = board.executionReferencesIntegrity();
@@ -6968,7 +7111,7 @@ export async function startDaemon(opts: DaemonOptions) {
6968
7111
  const visualIntegrity = visuals.integrity();
6969
7112
  if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
6970
7113
  throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
6971
- 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])) } : {}) };
6972
7115
  };
6973
7116
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
6974
7117
  const integrityAs = (expected: unknown) => {
@@ -7075,6 +7218,8 @@ export async function startDaemon(opts: DaemonOptions) {
7075
7218
  lifecycleStages: [...lifecycleConfig.stages],
7076
7219
  // ponytail: off keeps the #257 phase schema until RETIRED_WORKFLOW_FROM, when the alias and this flag go together.
7077
7220
  ...(lifecycleConfig.mode !== "off" ? { lifecycleCriteria: true } : {}),
7221
+ ...(lifecycleConfig.mode !== "off" && lifecycleConfig.security !== undefined ? { lifecycleAudit: true } : {}),
7222
+ ...(lifecycleConfig.mode !== "off" ? { lifecycleSurvey: true } : {}),
7078
7223
  // Every supported peer's membership, for launchers that run outside the console role (#484).
7079
7224
  roster: [...KNOWN_PEERS, ...OPTIONAL_PEERS].map(peer => ({ peer, on: onRoster(peer) })),
7080
7225
  protocol: PROTOCOL_MIN, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL,
@@ -7111,6 +7256,8 @@ export async function startDaemon(opts: DaemonOptions) {
7111
7256
  actionPolicyInfo: Object.fromEntries(peerIds.map(id => { const e = actionEnforcement(id); return [id, actionBudgets.status(id, e.enforced, e.reason)]; })),
7112
7257
  roleInfo: Object.fromEntries(peerIds.map(id => [id, { flowRoles: config.roles[id] ?? [], catalogRoles: roleState(id), ...roleVisibility(id), ...(config.roles[id]?.includes("planner") ? { planner: plannerSource } : {}) }])),
7113
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" },
7114
7261
  ...(pendingPermissionDefaults.size ? { permissionDefaults: [...pendingPermissionDefaults].map(([peer, source]) => ({ peer, mode: "never-ask", source })) } : {}),
7115
7262
  ...(modelRelay ? { models: modelRelay.status() } : {}),
7116
7263
  isolatedChecks: { pending: checkPending.size, orphans: orphanChecks, unknownReceipts: checkRunner.unknownReceipts ?? [], maintenanceUnavailable: checkRunner.maintenanceUnavailable === true },
@@ -7235,7 +7382,7 @@ export async function startDaemon(opts: DaemonOptions) {
7235
7382
  writeStatus();
7236
7383
  } finally { reportingQueues = false; }
7237
7384
  if (ready) {
7238
- tasks.scheduleQueuePressureRecheck();
7385
+ tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
7239
7386
  const policy = queuePolicy();
7240
7387
  if ((policy.max_queued > 0 || policy.max_oldest_s > 0) && !queuePressureStatusQueued) {
7241
7388
  queuePressureStatusQueued = true;
@@ -7501,11 +7648,11 @@ export async function startDaemon(opts: DaemonOptions) {
7501
7648
  uiEvents.push({ seq: ++uiSequence, event: e });
7502
7649
  if (uiEvents.length > 200) uiEvents.shift();
7503
7650
  if (e.t === "state") {
7504
- 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); }
7505
7652
  roomCommands.changed();
7506
7653
  log(`state ${e.peer} -> ${e.state}`);
7507
7654
  event({ type: "state", peer: e.peer, state: e.state });
7508
- if (ready) tasks.scheduleQueuePressureRecheck();
7655
+ if (ready) { tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits(); }
7509
7656
  if (e.peer.includes("@")) { if (!stopping) writeStatus(); return; }
7510
7657
  // #248: the add-ons it works with, once per attach (names and versions only).
7511
7658
  // A result is written unless a later attachment began meanwhile: a peer that detached before its probe settled
@@ -7660,7 +7807,7 @@ export async function startDaemon(opts: DaemonOptions) {
7660
7807
  }
7661
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.
7662
7809
  const nativeFactsTurn = nativeHookLaunches.current(e.peer) !== undefined && bus.peers.get(e.peer)?.pullOnly === true;
7663
- 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)) });
7664
7811
  if (!nativeFactsTurn && definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
7665
7812
  if ((bus.peers.get(e.peer)?.state ?? e.state) === "idle") queueMicrotask(() => finishSupervisionTurn(e.peer));
7666
7813
  turnEnded.set(e.peer, Date.now());
@@ -8024,10 +8171,11 @@ export async function startDaemon(opts: DaemonOptions) {
8024
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. */
8025
8172
  const startHeldByRecovery = (peer: unknown): string => {
8026
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.` : "";
8027
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`;
8028
8176
  const owner = bus.peers.get(peer);
8029
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`;
8030
- 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}`;
8031
8179
  };
8032
8180
 
8033
8181
  async function stopPeer(peer: unknown, rosterRemoval = false, operational?: {actor:string;current:()=>void}): Promise<Record<string, unknown>> {
@@ -8496,7 +8644,8 @@ export async function startDaemon(opts: DaemonOptions) {
8496
8644
  ...HUB_TOOLS.map((name) => [`tools.${name}.approval_mode`, '"approve"']),
8497
8645
  ].flatMap(([k, v]) => ["-c", `mcp_servers.agent-hub.${k}=${v}`]),
8498
8646
  preamble: sessionRoleContract(peer),
8499
- 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) },
8500
8649
  usagePollMs: config.budget.poll_min * 60_000,
8501
8650
  cwd: executionCwd,
8502
8651
  watchdogMs: config.watchdog_ms,
@@ -8606,7 +8755,7 @@ export async function startDaemon(opts: DaemonOptions) {
8606
8755
  sessionId: args.sessionId, sessionFile: args.sessionFile,
8607
8756
  admitBudget: async (envs, unit) => unit === "model_calls" ? [] : tasks.admitExecutionEnvelopes(envs, peer, unit),
8608
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 })) },
8609
- 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 }))],
8610
8759
  executeTool: async (name, raw, callId, sessionId, signal, context) => {
8611
8760
  const reviewToolTurn = reviewObserverHeld(peer) || pi.budgetEnvelopes.some(isReviewObserverExcluded) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded);
8612
8761
  if (MEMORY_READ_TOOLS.has(name)) validateMemoryRead(name, raw as Record<string, unknown>);
@@ -8811,6 +8960,8 @@ export async function startDaemon(opts: DaemonOptions) {
8811
8960
  profile: resolvedProfile,
8812
8961
  sdlcStages: lifecycleConfig.stages,
8813
8962
  sdlcCriteria: lifecycleConfig.mode !== "off",
8963
+ sdlcAudit: lifecycleConfig.mode !== "off" && lifecycleConfig.security !== undefined,
8964
+ sdlcSurvey: lifecycleConfig.mode !== "off",
8814
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),
8815
8966
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, local, context, envs),
8816
8967
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, local, context, envs),
@@ -8920,6 +9071,7 @@ export async function startDaemon(opts: DaemonOptions) {
8920
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"]({
8921
9072
  ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride && !adapter.modelOverride.acp ? { getModelOverride: () => modelSelection(peer) } : {}),
8922
9073
  backend, cwd: executionCwd,
9074
+ maxMinutes: () => config.review.max_minutes ?? DEFAULT_REVIEW_MAX_MINUTES,
8923
9075
  mcpConfig: JSON.stringify({ mcpServers: { "agent-hub": { command: process.execPath, args: ["run", SERVER_JS], env: toolEnv(peer, true) } } }),
8924
9076
  systemPrompt: sessionRoleContract(peer),
8925
9077
  watchdogMs: config.watchdog_ms,
@@ -8944,7 +9096,35 @@ export async function startDaemon(opts: DaemonOptions) {
8944
9096
  },
8945
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 }),
8946
9098
  verdictSince: (task, since) => board.get(task)?.history.some(h => h.by === peer && h.at >= since && (h.event === "approved" || h.event === "changes_requested")) === true,
8947
- 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
+ },
8948
9128
  onNoVerdict: (diagnostic, current) => {
8949
9129
  const task = board.get(diagnostic.task);
8950
9130
  const observerHeld = reviewer.reviewObserverInputHeld();
@@ -8958,6 +9138,14 @@ export async function startDaemon(opts: DaemonOptions) {
8958
9138
  onUnavailable: (failure, current) => {
8959
9139
  const attached = () => current() && bus.peers.get(peer) === reviewer;
8960
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
+ }
8961
9149
  if (failure.cause === "start_failed") {
8962
9150
  // #722: the class (a closed list) is the only detail; never a path, native text or token.
8963
9151
  const reason = reviewerUnavailableReason(failure.causeClass ?? "unknown", failure.causeDetail);
@@ -9174,7 +9362,7 @@ export async function startDaemon(opts: DaemonOptions) {
9174
9362
  }
9175
9363
  function sdlcSettingsView() {
9176
9364
  let file: ReturnType<typeof loadSdlc> | undefined;
9177
- try { file = loadSdlc(opts.cwd, VERSION); } catch { /* unreadable file stays unknown */ }
9365
+ try { file = readSdlcFile(); } catch { /* unreadable file stays unknown */ }
9178
9366
  return {
9179
9367
  "sdlc.mode": { value: lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9180
9368
  "sdlc.required_checks": { value: lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
@@ -9226,7 +9414,7 @@ export async function startDaemon(opts: DaemonOptions) {
9226
9414
  rows: report.rows.map(row => row.private || privatePrs.has(row.pr) ? { private: true, ready: false, tasks: [], after: [], blockers: ["private lifecycle evidence unavailable"] }
9227
9415
  : mixed ? { pr: row.pr, tasks: row.tasks.filter(id => !privateIds.has(id)), ready: false, after: [], blockers: ["private dependency evidence unavailable"] }
9228
9416
  : { pr: row.pr, tasks: row.tasks, head: row.head, ready: row.ready, blockers: row.blockers, after: row.after,
9229
- ...(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 } : {}) }),
9230
9418
  order: mixed ? [] : report.order, ...(report.unordered ? { unordered: mixed ? [] : report.unordered } : {}), conflicts: mixed ? [] : report.conflicts });
9231
9419
  }
9232
9420
  /** A public read may use host GitHub authentication only for this project's current public scope. */
@@ -9783,7 +9971,7 @@ export async function startDaemon(opts: DaemonOptions) {
9783
9971
  desiredRouting = structuredClone(prepared.routing);
9784
9972
  acknowledgeConfiguration(sources, prepared.accepted);
9785
9973
  if (priorDesired !== JSON.stringify([desiredConfig, desiredRouting, acceptedSources.trustLayers])) configRevision++;
9786
- 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(); }
9787
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! }));
9788
9976
  pendingRestart.push(...routingChanges.filter(key => configApply(key).applies === "restart").map(key => ({ key, reason: configApply(key).reason! })));
9789
9977
  retainedConfig = retainedConfigAfterReload(sources, prepared.fileConfig, prepared.rejected, scope);
@@ -9872,6 +10060,11 @@ export async function startDaemon(opts: DaemonOptions) {
9872
10060
  else throw new Error(`${def.key} does not restore a boolean`);
9873
10061
  return next;
9874
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
+ }
9875
10068
  function rosterRemovalRefusal(peer: string, now: boolean): string | undefined {
9876
10069
  if (stopping || recoveryActive()) return "recovery or shutdown is holding roster changes";
9877
10070
  if (conductorPeer(config.roles) === peer) return `${peer} holds the conductor role; move the role before removing it`;
@@ -9997,6 +10190,9 @@ export async function startDaemon(opts: DaemonOptions) {
9997
10190
  const refusal = settingRefusal(def, value, authority);
9998
10191
  if (refusal) return { ok: false, error: refusal };
9999
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 };
10000
10196
  if (def.group === "Roster") return changeRosterSetting(def, value, source, confirm, now === true, false, authority, reason);
10001
10197
  if (rosterChanging) return { ok: false, error: `roster change for ${rosterChanging} is in progress` };
10002
10198
  const peer = def.group === "Permissions" ? def.path.at(-1)! : undefined;
@@ -10267,6 +10463,11 @@ export async function startDaemon(opts: DaemonOptions) {
10267
10463
  try { return await reloadConfig(authority, key); } finally { structuralScopes.delete(key); }
10268
10464
  },
10269
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" }),
10270
10471
  notify: text => notify(text),
10271
10472
  changed: () => writeStatus(),
10272
10473
  pending: () => pendingRestart,
@@ -10278,7 +10479,7 @@ export async function startDaemon(opts: DaemonOptions) {
10278
10479
  if (sdlcFileCache?.stamp !== stamp) {
10279
10480
  let value: { mode: string; requiredChecks: readonly string[] } | string;
10280
10481
  sdlcFileReads++;
10281
- 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); }
10282
10483
  sdlcFileCache = { stamp, value };
10283
10484
  }
10284
10485
  return sdlcFileCache.value;
@@ -10475,6 +10676,21 @@ export async function startDaemon(opts: DaemonOptions) {
10475
10676
  ? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
10476
10677
  };
10477
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
+
10478
10694
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
10479
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"; }
10480
10696
  catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
@@ -10579,6 +10795,10 @@ export async function startDaemon(opts: DaemonOptions) {
10579
10795
  return "target lacks research_comparisons; persisted comparison plans, approvals or protocol context require a supporting daemon";
10580
10796
  if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_evidence")) && board.hasResearchEvidenceState())
10581
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";
10582
10802
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("project_autonomy")) {
10583
10803
  let needsAutonomy = autonomyConfirmed.size > 0;
10584
10804
  try {
@@ -10681,7 +10901,7 @@ export async function startDaemon(opts: DaemonOptions) {
10681
10901
  recoveryPhase = undefined;
10682
10902
  recoveryPeerSnapshot = undefined;
10683
10903
  clearTimeout(recoveryLeaseTimer);
10684
- budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10904
+ budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10685
10905
  writeStatus();
10686
10906
  return { t: "recovery", ok: true, aborted: true, recovery: recoveryView() };
10687
10907
  }
@@ -10721,7 +10941,7 @@ export async function startDaemon(opts: DaemonOptions) {
10721
10941
  }
10722
10942
  if (msg.op === "release") {
10723
10943
  if (recoveryPhase === "released") {
10724
- bus.setRecoveryHold(false); budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10944
+ bus.setRecoveryHold(false); budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10725
10945
  return { t: "recovery", ok: true, released: true, recovery: recoveryView() };
10726
10946
  }
10727
10947
  if (recoveryPhase !== "restored") return recoveryError("recovery is not restored");
@@ -10739,7 +10959,7 @@ export async function startDaemon(opts: DaemonOptions) {
10739
10959
  clearTimeout(recoveryLeaseTimer);
10740
10960
  reconcileGuidanceProbes();
10741
10961
  bus.setRecoveryHold(false);
10742
- budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10962
+ budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
10743
10963
  writeStatus();
10744
10964
  return { t: "recovery", ok: true, released: true, recovery: recoveryView() };
10745
10965
  }
@@ -11607,6 +11827,7 @@ export async function startDaemon(opts: DaemonOptions) {
11607
11827
  if (launch.generation && launch.generation !== owner.sessionGeneration) return void reply({ ok: false });
11608
11828
  launch.generation = owner.sessionGeneration;
11609
11829
  launch.transcript = native.transcriptPath;
11830
+ if (native.model) hookModels.set(peer, native.model);
11610
11831
  const callStarted = performance.now();
11611
11832
  const tally = () => tallyHook(peer, callStarted, msg.startedMs);
11612
11833
  const current = () => !stopping && nativeHookLaunches.get(peer, msg.nativeLaunchId) === launch && bus.peers.get(peer) === owner && owner.sessionGeneration === launch.generation && owner.state !== "offline";
@@ -12012,6 +12233,48 @@ export async function startDaemon(opts: DaemonOptions) {
12012
12233
  ).finally(() => { taskOpsInFlight--; });
12013
12234
  return;
12014
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
+ }
12015
12278
  if (msg.op === "merge") {
12016
12279
  // #786 T1: the person or the one configured conductor asks for a guarded merge. Every request gets a reply, a refusal included.
12017
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;
@@ -12024,6 +12287,27 @@ export async function startDaemon(opts: DaemonOptions) {
12024
12287
  );
12025
12288
  return;
12026
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
+ }
12027
12311
  if (msg.op === "authorize-release") {
12028
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;
12029
12313
  if (!asker) return void reply({ ok: false, error: "only the console user or the configured conductor may authorize a release" });
@@ -12065,7 +12349,7 @@ export async function startDaemon(opts: DaemonOptions) {
12065
12349
  if (tasks.isPii(now)) return { id: now.id, title: tasks.publicTitle(now), private: true };
12066
12350
  if (task.history.length !== now.history.length || !statuses.has(task.id)) throw new Error("task changed");
12067
12351
  const status = statuses.get(task.id)!;
12068
- 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])]));
12069
12353
  return { id: now.id, title: tasks.publicTitle(now), receipt: publicReadValue(tasks.publicView(now).sdlc), ...safeStatus };
12070
12354
  });
12071
12355
  current(); reply({ ok: true, public: true, mode: lifecycleConfig.mode, rows, truncated: selected.length > 100 });
@@ -12494,6 +12778,7 @@ export async function startDaemon(opts: DaemonOptions) {
12494
12778
  catch { return void reply({ t: "task", ok: false, error: "public release read unavailable" }); }
12495
12779
  }
12496
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" });
12497
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" });
12498
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" });
12499
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" });
@@ -12607,7 +12892,7 @@ export async function startDaemon(opts: DaemonOptions) {
12607
12892
  case "budget":
12608
12893
  if (c.role !== "console") {
12609
12894
  if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
12610
- 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() });
12611
12896
  }
12612
12897
  if (recoveryActive()) return void reply({ t: "budget", ok: false, error: "recovery is holding mutations" });
12613
12898
  if (msg.resume) {
@@ -12618,7 +12903,7 @@ export async function startDaemon(opts: DaemonOptions) {
12618
12903
  if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
12619
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" }]);
12620
12905
  }
12621
- 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() });
12622
12907
  case "usage": {
12623
12908
  // #683 U2: the console, the person and a configured planner read usage; every other agent is refused. Always answered (rid).
12624
12909
  const planner = c.role === "tools" && !!c.peer && !!config.roles[c.peer]?.includes("planner");
@@ -12881,7 +13166,7 @@ export async function startDaemon(opts: DaemonOptions) {
12881
13166
  { const every = opts.handoffCatchUpMs ?? 5 * 60_000, watch = opts.handoffWatchMs ?? 15_000;
12882
13167
  const periodic = setInterval(() => void handoffCatchUp(), every), descriptorWatch = setInterval(handoffWatch, watch);
12883
13168
  periodic.unref?.(); descriptorWatch.unref?.(); intervals.push(periodic, descriptorWatch); }
12884
- tasks.scheduleQueuePressureRecheck();
13169
+ tasks.scheduleQueuePressureRecheck(); tasks.refreshReviewerQuotaWaits();
12885
13170
  for (const name of opts.configWatch === false ? [] : CONFIG_SOURCE_FILES) {
12886
13171
  const path = join(opts.cwd, ".agenthub", name);
12887
13172
  const listener = (current: import("node:fs").Stats, previous: import("node:fs").Stats) => {