@staix/agent-hub 0.34.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +53 -7
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/addons/claude-mem.md +4 -4
  5. package/docs/addons/open-code-review.md +1 -1
  6. package/docs/agent-notes/README.md +66 -0
  7. package/docs/agent-notes/adapters.md +14 -7
  8. package/docs/agent-notes/budget.md +1 -1
  9. package/docs/agent-notes/bus.md +2 -1
  10. package/docs/agent-notes/daemon.md +9 -7
  11. package/docs/agent-notes/local-worker.md +1 -1
  12. package/docs/agent-notes/models.md +5 -2
  13. package/docs/agent-notes/tasks.md +9 -2
  14. package/docs/agent-notes/tests.md +6 -0
  15. package/docs/design/adapters.md +182 -2
  16. package/docs/design/agent-hub-architecture.md +64 -2
  17. package/docs/design/agent-hub.md +6 -0
  18. package/docs/design/bus.md +26 -0
  19. package/docs/design/execution-reference.md +306 -0
  20. package/docs/design/guidance-experiments.md +438 -0
  21. package/docs/design/model-routes.md +628 -0
  22. package/docs/design/supervision.md +121 -0
  23. package/docs/design/task-board.md +121 -0
  24. package/docs/dogfood.md +45 -13
  25. package/docs/events.md +38 -20
  26. package/docs/memory.md +21 -7
  27. package/docs/operations.md +824 -40
  28. package/docs/profiles.md +2 -2
  29. package/docs/quickstart.md +117 -4
  30. package/docs/research.md +73 -13
  31. package/docs/roles.md +1 -1
  32. package/docs/sdlc.md +117 -11
  33. package/docs/security.md +153 -15
  34. package/docs/smoke.md +14 -0
  35. package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
  36. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  37. package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
  38. package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
  39. package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
  40. package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
  41. package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
  42. package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
  43. package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
  44. package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
  45. package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
  46. package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
  47. package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
  48. package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
  49. package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
  50. package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
  51. package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
  52. package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
  53. package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
  54. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
  55. package/docs/verification/2026-11-09-0.35.0.md +129 -0
  56. package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
  57. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  58. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  59. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  60. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  61. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  62. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  63. package/docs/verification/claude-permission-transport-native.py +10 -3
  64. package/docs/verification/claude-shell-wrapper-native.py +8 -8
  65. package/docs/verified.json +245 -15
  66. package/package.json +3 -3
  67. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  68. package/plugins/agent-hub/kimi-hook.js +21230 -0
  69. package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
  70. package/plugins/agent-hub/server.js +4359 -1071
  71. package/scripts/check-docs.mjs +12 -1
  72. package/src/adapters/acp-model-policy.ts +56 -0
  73. package/src/adapters/acp.ts +175 -5
  74. package/src/adapters/agy/entry.ts +8 -5
  75. package/src/adapters/agy/hooks.ts +65 -15
  76. package/src/adapters/channel-peer.ts +33 -1
  77. package/src/adapters/claude-channel.ts +7 -4
  78. package/src/adapters/claude-implementer.ts +16 -3
  79. package/src/adapters/codex-appserver.ts +118 -8
  80. package/src/adapters/codex-review-isolation.ts +3 -1
  81. package/src/adapters/compat.ts +18 -13
  82. package/src/adapters/definitions/builtin-metadata.ts +8 -1
  83. package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
  84. package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
  85. package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
  86. package/src/adapters/definitions/reviewer-variants.ts +3 -1
  87. package/src/adapters/kimi-review-policy-worker.js +2 -0
  88. package/src/adapters/kimi-review-policy-worker.ts +85 -0
  89. package/src/adapters/kimi-review-policy.ts +68 -0
  90. package/src/adapters/kimi-review.ts +41 -41
  91. package/src/adapters/kimi-tui-facts.ts +153 -0
  92. package/src/adapters/kimi-wire-usage.ts +33 -8
  93. package/src/adapters/local-worker.ts +60 -21
  94. package/src/adapters/model-token.ts +3 -0
  95. package/src/adapters/pi.ts +27 -5
  96. package/src/adapters/qwen-dual.ts +324 -44
  97. package/src/adapters/registry-types.ts +34 -3
  98. package/src/adapters/registry.ts +1 -0
  99. package/src/adapters/reviewer-policy-watch.ts +86 -0
  100. package/src/adapters/reviewer-print.ts +80 -18
  101. package/src/cli/agents.ts +1 -1
  102. package/src/cli/facts-hook.ts +4 -2
  103. package/src/cli/guidance.ts +67 -0
  104. package/src/cli/help.ts +13 -5
  105. package/src/cli/identity.ts +13 -3
  106. package/src/cli/init-prompt.ts +15 -2
  107. package/src/cli/init-required-checks.ts +122 -0
  108. package/src/cli/init-settings.ts +10 -4
  109. package/src/cli/init.ts +39 -3
  110. package/src/cli/kimi-facts-hook.ts +11 -0
  111. package/src/cli/kimi-plugin.ts +157 -0
  112. package/src/cli/lineage.ts +78 -0
  113. package/src/cli/main.ts +159 -19
  114. package/src/cli/model.ts +52 -0
  115. package/src/cli/output.ts +23 -1
  116. package/src/cli/reset.ts +1 -1
  117. package/src/cli/setup-research.ts +10 -0
  118. package/src/cli/status-lines.ts +8 -4
  119. package/src/hub/autonomy-defaults.ts +20 -9
  120. package/src/hub/board.ts +346 -4
  121. package/src/hub/budget.ts +1 -1
  122. package/src/hub/build-entry.ts +11 -0
  123. package/src/hub/bus.ts +52 -2
  124. package/src/hub/ci-watch.ts +4 -4
  125. package/src/hub/code-facts.ts +10 -3
  126. package/src/hub/completions.ts +3 -1
  127. package/src/hub/config-apply.ts +3 -1
  128. package/src/hub/config-trust.ts +1 -0
  129. package/src/hub/control-client.ts +1 -1
  130. package/src/hub/daemon.ts +1387 -121
  131. package/src/hub/deliverable-files.ts +38 -5
  132. package/src/hub/delivery-hints.ts +4 -2
  133. package/src/hub/delivery-journal.ts +50 -2
  134. package/src/hub/delivery-public.ts +51 -0
  135. package/src/hub/dogfood-profile.ts +9 -5
  136. package/src/hub/envelope.ts +1 -1
  137. package/src/hub/events.ts +28 -18
  138. package/src/hub/execution-lineage-owner.ts +272 -0
  139. package/src/hub/execution-lineage.ts +164 -0
  140. package/src/hub/execution-links.ts +85 -0
  141. package/src/hub/execution-reference.ts +36 -0
  142. package/src/hub/guidance-variants.ts +398 -0
  143. package/src/hub/handoff.ts +1 -0
  144. package/src/hub/hub-tools.ts +62 -2
  145. package/src/hub/instances.ts +4 -3
  146. package/src/hub/kimi-events.ts +46 -0
  147. package/src/hub/kimi-usage.ts +132 -29
  148. package/src/hub/lifecycle.ts +31 -15
  149. package/src/hub/limits.ts +13 -4
  150. package/src/hub/manager.ts +58 -3
  151. package/src/hub/memory-policy.ts +4 -3
  152. package/src/hub/memory-sync-attestation.ts +54 -0
  153. package/src/hub/memory-sync-state.ts +20 -5
  154. package/src/hub/model-overrides.ts +115 -0
  155. package/src/hub/native-hook-launch.ts +12 -3
  156. package/src/hub/operational-view.ts +2 -2
  157. package/src/hub/peers.ts +28 -1
  158. package/src/hub/permission-mode.ts +1 -1
  159. package/src/hub/person-figures.ts +88 -0
  160. package/src/hub/planning.ts +1 -1
  161. package/src/hub/progress.ts +24 -7
  162. package/src/hub/report.ts +38 -4
  163. package/src/hub/research-dataset.ts +158 -0
  164. package/src/hub/research-memory.ts +68 -0
  165. package/src/hub/research-quality.ts +118 -0
  166. package/src/hub/research-record.ts +279 -0
  167. package/src/hub/research.ts +126 -27
  168. package/src/hub/restart.ts +27 -0
  169. package/src/hub/roles.ts +26 -0
  170. package/src/hub/routing.ts +4 -1
  171. package/src/hub/sdlc-merge.ts +39 -1
  172. package/src/hub/sdlc-release.ts +1 -1
  173. package/src/hub/sdlc.ts +62 -11
  174. package/src/hub/settings.ts +5 -0
  175. package/src/hub/startup-event-seeds.ts +51 -0
  176. package/src/hub/startup-readiness.ts +65 -0
  177. package/src/hub/startup-timing.ts +38 -0
  178. package/src/hub/supervision-proposals.ts +405 -0
  179. package/src/hub/supervision-rules.ts +388 -0
  180. package/src/hub/supervision.ts +2 -0
  181. package/src/hub/task-approval.ts +2 -2
  182. package/src/hub/task-repository.ts +5 -0
  183. package/src/hub/tasks.ts +632 -59
  184. package/src/hub/ui.ts +9 -5
  185. package/src/hub/visual-assets.ts +50 -0
  186. package/src/hub/visual.ts +257 -0
  187. package/src/memory/brief.ts +169 -14
  188. package/src/memory/capture.ts +4 -3
  189. package/src/memory/recall.ts +46 -5
  190. package/src/memory/record-provenance.ts +82 -0
  191. package/src/memory/records.ts +116 -0
  192. package/src/models/relay.ts +9 -2
  193. package/src/models/route/adec.ts +190 -0
  194. package/src/models/route/config.ts +64 -3
  195. package/src/models/route/decision-evidence.ts +83 -0
  196. package/src/models/route/decision.ts +215 -0
  197. package/src/models/route/relay-selector.ts +8 -7
  198. package/src/models/route/runtime.ts +35 -22
  199. package/src/models/route/stage-diagnostics.ts +22 -0
  200. package/src/models/route/stage-evidence.ts +55 -0
  201. package/src/models/route/stage-fallback.ts +58 -0
  202. package/src/models/route/stage-input.ts +155 -0
  203. package/src/models/route/stage.ts +5 -147
  204. package/src/ui/guidance-panel.ts +156 -0
  205. package/src/ui/guidance-view.ts +43 -0
  206. package/src/ui/index.html +134 -6
  207. package/src/ui/lineage-view.ts +34 -0
  208. package/src/ui/plugin.ts +136 -11
  209. package/templates/AGENTS.block.md +1 -1
  210. package/templates/config.json +1 -1
  211. package/templates/profiles/general.json +1 -1
  212. package/templates/profiles/research.json +1 -1
  213. package/templates/profiles/writing.json +1 -1
package/src/hub/daemon.ts CHANGED
@@ -1,3 +1,12 @@
1
+ import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
2
+ import { publicDeliveryBodies } from "./delivery-public.ts";
3
+ import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
4
+ import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
5
+ import { VisualStore, validateVisualInput, validateVisualPayload, VISUAL_ID_PATTERN, type VisualRecord, type VisualSummary } from "./visual.ts";
6
+ import { resolveVisualAssets } from "./visual-assets.ts";
7
+ import type { DeliverablePorts } from "./deliverable-files.ts";
8
+ import { readStartupEventSeeds } from "./startup-event-seeds.ts";
9
+ import { StartupTimings } from "./startup-timing.ts";
1
10
  import { repoGitArgs, repoGitEnv } from "./snapshots.ts";
2
11
  import { createReviewMaterialReader, type ReviewReadRequest, type ReviewMaterialBatch } from "./review-material.ts";
3
12
  import { readSdlcPr } from "./sdlc.ts";
@@ -35,7 +44,7 @@ import type { DocEvidence } from "./sdlc-release.ts";
35
44
  import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
36
45
  import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
37
46
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
38
- import { NativeHookLaunches } from "./native-hook-launch.ts";
47
+ import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
39
48
  import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
40
49
  import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunReceipt } from "./check-runner.ts";
41
50
  import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
@@ -56,7 +65,7 @@ import { listenWithoutPortCollision } from "./listen.ts";
56
65
  import { needs, type NeedsInput } from "../ui/needs.ts";
57
66
  import { loadPetConfig, PET_WINDOW_RETIRED_NOTICE, stripLegacyPetWindow } from "../pet/config.ts";
58
67
  import { projectionConfig, TextProjections, type ProjectionConfig } from "./text-projection.ts";
59
- import { policyPaths, matchesPolicy } from "./path-policy.ts";
68
+ import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
60
69
  import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
61
70
  import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
62
71
  import { profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "./profiles.ts";
@@ -75,6 +84,7 @@ import { RecoveryDeferredHubError } from "./deferred-hub.ts";
75
84
  import { databaseBusySite, isDatabaseBusy, RecoveryDatabaseBusy } from "./recovery-error.ts";
76
85
  import { ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, QUOTA_HANDOFF_PLATFORMS, NATIVE_CONFIG_BLOCKS, nativeConfigurationDefaults, mergeNativeConfiguration, retainNativeRouting, DAEMON_PORTS, definitionOf, createProjectAdapterCatalog, isFixedBuiltinDefinition } from "../adapters/registry.ts";
77
86
  import { isSupportedPeer as registrySupportedPeer, definitionOf as builtinDefinitionOf, KNOWN_PEERS as BASE_KNOWN_PEERS, SUPPORTED_PEERS as BASE_SUPPORTED_PEERS, STARTABLE_PEERS as BASE_STARTABLE_PEERS } from "../adapters/registry.ts";
87
+ import type { NativeFactsTranscript } from "../adapters/registry-types.ts";
78
88
  import type { ReviewScope } from "./review-scope.ts";
79
89
  import { checkJcodeInstanceHomes, instanceDefinitionOf, effectiveInstanceRoles, isPlannerOnly, instancePeerIds, validateInstances, type InstancesConfig } from "./instances.ts";
80
90
  import { INSTANCE_CONFIG_FILES, readInstanceConfig, withoutInertInstancePolicy, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
@@ -105,7 +115,7 @@ import { QuestionDesk } from "./question-desk.ts";
105
115
  import type { ScannedFile } from "./schedules.ts";
106
116
  import { corpusConfig } from "./corpus-config.ts";
107
117
  import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked, stripUntrusted } from "./config-trust.ts";
108
- import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateEffectiveConfig, validateOperationalConfig, validatePetConfig } from "./config-apply.ts";
118
+ import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig, validateOperationalConfig, validatePetConfig } from "./config-apply.ts";
109
119
  import { resolveSettledRoles } from "./settled-roles.ts";
110
120
  import { CONFIG_SOURCE_FILES, configFingerprint, configSourceTexts, parseConfigSources, type ConfigSourceTexts, type ConfigSources } from "./config-reload.ts";
111
121
  import { issueConductorRecoveryAuthority, authorizeConductorRecovery, assertConductorRecovery, RecoveryAuthorityError, type ConductorRecoveryBinding } from "./recovery-authority.ts";
@@ -116,9 +126,10 @@ import { planFingerprint, registeredProjects, type UpgradePlan } from "../cli/up
116
126
  import { conductorRecoveryBinding } from "../cli/conductor-recovery.ts";
117
127
  import { createConfigEditor } from "./config-edit-host.ts";
118
128
  import { readEditable } from "./config-edit.ts";
119
- import { eventLog, readEvents, type RoleIdentity } from "./events.ts";
129
+ import { eventLog, readEvents, type HubEvent, type RoleIdentity } from "./events.ts";
120
130
  import { SpecTaskInspector } from "./specs-task.ts";
121
- import { KimiUsage, kimiSeedRows } from "./kimi-usage.ts";
131
+ import { KimiUsage, kimiSeedRows, type KimiRowAttribution, type KimiUsageScheduler } from "./kimi-usage.ts";
132
+ import { KimiEventWriter } from "./kimi-events.ts";
122
133
  import { TokenWindow } from "./token-window.ts";
123
134
  import { budgetNotes, type BudgetPeerNote } from "./budget-notes.ts";
124
135
  import { kimiRowTotal } from "../adapters/kimi-wire-usage.ts";
@@ -133,6 +144,8 @@ import { startModelRelay, type ModelRelay } from "../models/relay.ts";
133
144
  import { ensureMlx, type MlxOptions } from "../models/mlx.ts";
134
145
  import { PiToolReceipts, packPiShellResult } from "../pi/tool-receipts.ts";
135
146
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
147
+ import { ModelOverrides, ModelOverrideLatches, type RuntimeModelStatus, type ModelSource } from "./model-overrides.ts";
148
+ import { isNativeModelToken } from "../adapters/model-token.ts";
136
149
  import { processSignature, processLiveness } from "../pi/process-signature.ts";
137
150
  import { PiSessionBookmarkMismatch, PiSessionUnresumable, recordPiReplacement, validatePiSession } from "../pi/session.ts";
138
151
  import { profile, proxyEnv, sandboxAvailable, type SandboxNetwork } from "../local/sandbox.ts";
@@ -156,7 +169,7 @@ import { Capture } from "../memory/capture.ts";
156
169
  import { DEFAULT_OMNIROUTE, OmniRoute, type OmniRouteConfig } from "../omniroute/client.ts";
157
170
  import { CorpusIndex } from "./corpus.ts";
158
171
  import { corpusEvidence } from "./corpus-evidence.ts";
159
- import { Briefs, type BriefTask } from "../memory/brief.ts";
172
+ import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../memory/brief.ts";
160
173
  import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
161
174
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
162
175
  import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
@@ -169,11 +182,13 @@ import { canonicalPath, realPath, hubHome } from "./project.ts";
169
182
  import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
170
183
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
171
184
  import type { BusEvent, PublishResult } from "./bus.ts";
172
- import { CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
185
+ import { CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
173
186
  import { effectiveClass, listedCapabilities, PublishRefusal, readShare, shareView, validatePublished, type CapabilityManifest } from "./capabilities.ts";
174
187
  import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
175
188
  import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicConductorTask, publicPeerBudget, taskShowAllowed, type ConductEvent } from "./conductor.ts";
176
189
  import { SupervisionFeed } from "./supervision.ts";
190
+ import { MAX_REFS, taskRevision, type SupervisionFacts, type SupervisionHistoryFact } from "./supervision-rules.ts";
191
+ import { ProposalStore, SupervisionProposals, type SupervisionProposal } from "./supervision-proposals.ts";
177
192
  import { drainCliAudits } from "../cli/identity-audit.ts";
178
193
  import { launcherPreview } from "../cli/preview.ts";
179
194
  import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
@@ -200,12 +215,14 @@ import { ControlClient, DAEMON_FEATURES, HANDOFF_CONNECT_MS, HANDOFF_LOOKUP_CONN
200
215
  import { negotiateProtocol, protocolWindow } from "./protocol-window.ts";
201
216
  import { attachEvent, originOf, type Origin } from "./provenance.ts";
202
217
  import { mintSessionId, sessionGate } from "./session-identity.ts";
203
- import { MAX_HOP, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId, type Priority } from "./envelope.ts";
218
+ import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId, type Priority } from "./envelope.ts";
204
219
  import { BasePeer, DEFAULT_WATCHDOG_MS, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
205
220
  import { ClaudeTodoSource, DoingTracker, readAiTitle, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
206
221
  import { MemoryClient } from "../memory/client.ts";
207
222
  import { VERSION } from "../version.ts";
208
223
  import { appendRecords, taskRecords } from "./research.ts";
224
+ import { readEvidence } from "./research-record.ts";
225
+ import { memoryFigures, onlyTaskMemory, UNKNOWN_MEMORY_FIGURES, type MemoryFigures } from "./research-memory.ts";
209
226
  import { parseResearchRunners, type RegisteredRunnerV1 } from "./research-runner.ts";
210
227
  import { benchReport, MIN_ATTEMPTS, readRuns, runSummary, type Measures, type RunSummary } from "./bench.ts";
211
228
  import { projectChain } from "@staix/agent-mem";
@@ -225,11 +242,11 @@ import { START_AGENTS_DEFAULT, checkStartAgents } from "./start-agents.ts";
225
242
  import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, terminalTemplate, type PeerStartConfig, type StartMode } from "./start-mode.ts";
226
243
  import { hasKimiHubMcp } from "../cli/kimi-mcp.ts";
227
244
  import type { TerminalOpener } from "./terminal-open.ts";
228
- import { grantablePath, instructionProtection, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
245
+ import { isHubWritePath, grantablePath, instructionProtection, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
229
246
  import { ContextWindows, DEFAULT_CONTEXT, readNativeContext, type ContextConfig } from "./context-window.ts";
230
247
  import { projectFileTool, scopedWriteBlocked } from "../cli/facts-hook.ts";
231
248
  import { detectTooling } from "./tooling.ts";
232
- import { looksSecret, DEFAULT_LEASE_MS, memoryHome, SUGGESTED, taskKey, type CandidateStore, type MemoryStore, type GoalView, type Suggested, type View as MemoryView } from "@staix/agent-mem";
249
+ import { CaptureStore, configuredPolicy, recordsEnabled, looksSecret, DEFAULT_LEASE_MS, memoryHome, SUGGESTED, taskKey, type CandidateStore, type MemoryStore, type GoalView, type Suggested, type View as MemoryView } from "@staix/agent-mem";
233
250
  import { memoryProjectKey } from "@staix/agent-mem";
234
251
  import { AGENT_MEM_VERSION, MEMORY_SPLIT_INCOMPLETE, memoryProjectFor, openProfileMemory, openProfileCandidates, MemoryProfileBinding, type UnboundMemoryProfileReceipt } from "./memory-profile.ts";
235
252
  import { syncMemory, createIntentBriefSource, createStandalonePolicy } from "@staix/agent-mem";
@@ -237,7 +254,8 @@ import { SourceRegistry } from "./sources.ts";
237
254
  import { MEMORY_READ_TOOLS, memoryRead, validateMemoryRead, sourceRead, validateSourceRead } from "./read-tools.ts";
238
255
  import { nativeRecall } from "../memory/recall.ts";
239
256
  import { promotionScreen, withoutPii, mentionsPrivatePath } from "./memory-policy.ts";
240
- import { classifyMemorySyncFailure, initialMemorySyncState, memorySyncDeclinedDetails, memorySyncFailureDetailHash, memorySyncView, memorySyncPlacementCounts, reduceMemorySync } from "./memory-sync-state.ts";
257
+ import { hostPlacementAttestation, memorySyncErrorText, writerRefusalOf, type WriterRefusal } from "./memory-sync-attestation.ts";
258
+ import { classifyMemorySyncFailure, initialMemorySyncState, memorySyncDeclinedDetails, memorySyncFailureDetailHash, memorySyncView, memorySyncNextStep, memorySyncPlacementCounts, reduceMemorySync } from "./memory-sync-state.ts";
241
259
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows } from "./memory-sync-policy.ts";
242
260
  import { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig } from "./specs-config.ts";
243
261
 
@@ -285,6 +303,8 @@ export interface HubConfig {
285
303
  specs: SpecsConfig;
286
304
  catalog_roles?: Record<string, string[]>;
287
305
  conductor: { feed: "own" | "all" | "off"; approval_wait_s: number };
306
+ /** #1221 T2: what the supervision queue may do. `off` evaluates nothing, `shadow` stores bounded proposals with no inbox row or notice, `advisory` may also show a pending one in the console inbox. Machine-local and off by default. */
307
+ supervision: { mode: "off" | "shadow" | "advisory" };
288
308
  budget: BudgetConfig;
289
309
  context: ContextConfig;
290
310
  inference: InferenceConfig;
@@ -307,6 +327,8 @@ export interface HubConfig {
307
327
  checks: { timeout_s: number; runner?: "container" | "remote"; remote?: RemoteRunnerConfig; [cls: string]: string | number | RemoteRunnerConfig | undefined };
308
328
  /** A git tree at each turn boundary for `ahub turns` and `ahub undo`, the last `keep` per peer (issue #33). */
309
329
  snapshots: { enabled: boolean; keep: number };
330
+ /** Unbound visuals expire; task-bound records retain the task lifetime. */
331
+ visuals: { retention_days: number };
310
332
  /** #1057: the worktree shelf. `quiet_days` shelves a worktree idle that long (0 = never); `alert_over` is the settled count that raises one inbox alert (0 = never). */
311
333
  worktrees: { quiet_days: number; alert_over: number };
312
334
  /** #1053: `ttl_s` expires an unanswered question (default 86400); `wait_ms` overrides an adapter definition's `questionWaitMs` per kind. */
@@ -363,6 +385,7 @@ export const DEFAULT_CONFIG: HubConfig = {
363
385
  roster: {},
364
386
  roles: DEFAULT_ROLES,
365
387
  conductor: { feed: "own", approval_wait_s: 30 },
388
+ supervision: { mode: "off" },
366
389
  budget: DEFAULT_BUDGET,
367
390
  context: DEFAULT_CONTEXT,
368
391
  model_relay: { cooldown_failures: MODEL_COOLDOWN_FAILURES_SETTING.defaultValue, cooldown_s: MODEL_COOLDOWN_SETTING.defaultValue, cooldown_cap_s: MODEL_COOLDOWN_CAP_SETTING.defaultValue, terminal_history_limit: MODEL_TERMINAL_HISTORY_SETTING.defaultValue },
@@ -385,6 +408,7 @@ export const DEFAULT_CONFIG: HubConfig = {
385
408
  snapshots: { enabled: false, keep: 20 },
386
409
  worktrees: { quiet_days: 7, alert_over: 10 },
387
410
  questions: { ttl_s: 86_400, wait_ms: {} },
411
+ visuals: { retention_days: 30 },
388
412
  research: { enabled: false },
389
413
  bench: { enabled: false },
390
414
  peers: {},
@@ -400,14 +424,14 @@ export const DEFAULT_CONFIG: HubConfig = {
400
424
  export { stateDirFor };
401
425
 
402
426
  /** Ids an external process may not claim: the console user and the adapters the daemon runs itself. */
403
- const READ_ONLY_HUB_TOOLS = new Set(["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"]);
427
+ 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"]);
404
428
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
405
429
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
406
430
 
407
431
  /** The shared project config, then the machine's own file, which overrides it block by block (issue #17). */
408
432
  const CONFIG_FILES = INSTANCE_CONFIG_FILES;
409
433
  export interface ConfigLayer { name: typeof CONFIG_FILES[number]; raw: Record<string, any> }
410
- const CONFIG_BLOCKS = ["action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
434
+ const CONFIG_BLOCKS = ["action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "visuals", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
411
435
 
412
436
  /** Older targets parse raw keys before placement/trust checks, so even an empty or refused declaration needs the floor. */
413
437
  function rawResearchRunnersPresent(cwd: string): boolean {
@@ -424,6 +448,18 @@ function rawResearchRunnersPresent(cwd: string): boolean {
424
448
  return present;
425
449
  }
426
450
 
451
+ /** Raw declaration presence is the floor: defaults in the in-memory config are not an opt-in. */
452
+ function rawVisualsPresent(cwd: string): boolean {
453
+ const texts = configSourceTexts(cwd);
454
+ for (const name of CONFIG_FILES) {
455
+ if (texts[name] === null) continue;
456
+ const raw: unknown = JSON.parse(texts[name]!);
457
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid configuration");
458
+ if (Object.hasOwn(raw, "visuals")) return true;
459
+ }
460
+ return false;
461
+ }
462
+
427
463
  /** Connection-time policy refresh reads role/feed fields only, never launches or machine-local configuration. */
428
464
  export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[], scope: Pick<ReturnType<typeof readInstanceConfig>, "instances" | "catalog"> = readInstanceConfig(cwd, layers)): { roles: Record<string, string[]>; conductor: HubConfig["conductor"]; planner?: string | string[]; notices?: string[] } {
429
465
  const roles: Record<string, string[]> = { ...DEFAULT_ROLES };
@@ -650,6 +686,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
650
686
  snapshots: { ...DEFAULT_CONFIG.snapshots, enabled: true, ...file.snapshots },
651
687
  worktrees: { quiet_days: wholeDays(file.worktrees?.quiet_days, DEFAULT_CONFIG.worktrees.quiet_days), alert_over: wholeDays(file.worktrees?.alert_over, DEFAULT_CONFIG.worktrees.alert_over) },
652
688
  questions: questionsConfig(file.questions),
689
+ visuals: { retention_days: typeof file.visuals?.retention_days === "number" && Number.isSafeInteger(file.visuals.retention_days) && file.visuals.retention_days >= 1 && file.visuals.retention_days <= 3650 ? file.visuals.retention_days : DEFAULT_CONFIG.visuals.retention_days },
653
690
  research: { enabled: file.research?.enabled === true, ...(file.research?.runners !== undefined ? { runners: parseResearchRunners(file.research.runners) } : {}) }, // opt-in: anything but true is off
654
691
  bench: { enabled: file.bench?.enabled === true }, // opt-in: a run resets this project's work tree
655
692
  peers: { ...instanceModes, ...peerStartConfig(file.peers, instances, adapterCatalog) },
@@ -686,6 +723,10 @@ function mlxPinProblem(routing: Routing, project: boolean): string | undefined {
686
723
  }
687
724
 
688
725
  export interface DaemonOptions {
726
+ /** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
727
+ effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
728
+ /** Host-only numeric startup reader observation; never read from config or control input. Observer failure changes no replay state. */
729
+ startupSeedObserved?: (observation: { readPasses: number; readBytes: number }) => void;
689
730
  /** Host-only test/embedding port; never read from project configuration or a tool. */
690
731
  memoryClient?: MemoryClient;
691
732
  /** Host-only remote-default evidence seam; never read from config or control messages. */
@@ -710,6 +751,8 @@ export interface DaemonOptions {
710
751
  releaseHostAdmission?: (cwd: string) => Promise<ReleaseHostAdmission>;
711
752
  /** 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. */
712
753
  kimiHome?: string;
754
+ /** Host-only delayed-drain scheduler; tests fire it explicitly. Production leaves it unset and uses unreferenced timers. */
755
+ kimiUsageScheduler?: KimiUsageScheduler;
713
756
  /** Host-only replay-window test ceiling (1..512); never read from project config or a tool. */
714
757
  toolWriteReplayMaxEntries?: number;
715
758
  /** Host-only evidence seam; never supplied by project config or control messages. */
@@ -863,13 +906,16 @@ function capturedRecoverySourceDigest(): string | undefined {
863
906
  }
864
907
 
865
908
  export async function startDaemon(opts: DaemonOptions) {
909
+ const startupTimings = new StartupTimings();
866
910
  // Refuse unknown formats before logs, session cleanup, module factories or any writable store is opened.
867
911
  assertHubDbCompatible(join(opts.stateDir, "hub.db"));
912
+ startupTimings.mark("schema");
868
913
  if (opts.toolWriteReplayMaxEntries !== undefined && (!Number.isSafeInteger(opts.toolWriteReplayMaxEntries) || opts.toolWriteReplayMaxEntries < 1 || opts.toolWriteReplayMaxEntries > 512)) throw new Error("invalid host tool write replay capacity");
869
914
  const resolveExecutionCwd = (peer: string, currentDeclarations: InstancesConfig | undefined, currentRoles: readonly string[], catalog: ReturnType<typeof createProjectAdapterCatalog>): string =>
870
915
  resolveInstanceExecutionCwd(opts.cwd, peer, currentDeclarations, currentRoles, catalog, undefined, undefined, opts.instanceExecutionGit);
871
916
  const projectId = opts.projectId ?? randomUUID();
872
917
  const sourcePackageDigest = capturedRecoverySourceDigest();
918
+ startupTimings.mark("source");
873
919
  const instanceId = opts.instanceId ?? randomUUID();
874
920
  const startupCleanup: (() => void | Promise<void>)[] = [];
875
921
  let ready = false;
@@ -1121,6 +1167,7 @@ export async function startDaemon(opts: DaemonOptions) {
1121
1167
  let publicLine:string|undefined,view:ReturnType<typeof operationalView>|undefined;
1122
1168
  for(const [sock,current] of operationalLogSubscribers)try {current();if(sock.getBufferedAmount()>64*1024)throw new Error("slow log consumer");view??=publicOperationalView();publicLine??=view.line(text);sock.send(JSON.stringify({t:"operational_log",line:publicLine,complete:view.complete,...(!view.complete?{incompleteReason:view.incompleteReason}:{})}));}catch{operationalLogSubscribers.delete(sock);try{sock.close(4403,"operational log authority ended");}catch{/* The subscription is already gone. */}}
1123
1169
  };
1170
+ startupTimings.mark("configuration");
1124
1171
  let runningRoutingDefault = recoveryDefaultRouting;
1125
1172
  if (runningRoutingDefault === undefined) try { runningRoutingDefault = recoveryRoutingFallback(); } catch { /* unknown defaults refuse conductor recovery */ }
1126
1173
  let runningRouting = recoveryRouting ?? currentRouting(opts.cwd, log);
@@ -1242,12 +1289,42 @@ export async function startDaemon(opts: DaemonOptions) {
1242
1289
  // first writes once its peers have stopped and their turns ended.
1243
1290
  const researchGraceMs = opts.researchGraceMs ?? 10_000;
1244
1291
  const researchPending = new Map<number, { since: number; timer: ReturnType<typeof setTimeout> }>();
1292
+ /**
1293
+ * #1279: the counter figures of one task, read from agent-mem's sidecar at the moment the record is written (the sidecar, the store and the memory project are bound further down, and exist by
1294
+ * then). Undefined when memory or the sidecar is off, so the record's counters stay unknown; a task that is private reports none, whatever the sidecar holds.
1295
+ */
1296
+ const memoryFiguresFor = (taskId: number): MemoryFigures => {
1297
+ const row = board.get(taskId);
1298
+ if (!candidates || !memoryStore || !row || tasks.isPii(row)) return { ...UNKNOWN_MEMORY_FIGURES };
1299
+ try {
1300
+ const store = memoryStore, project = memoryProject;
1301
+ const planContext = { cwd: opts.cwd, project, repo: memoryRepo, deny: config.local.deny };
1302
+ const briefTask = { id: row.id, created: row.created, title: "", refs: { paths: row.refs.paths ?? [] }, plan: { paths: row.plan?.paths ?? [], symbols: row.plan?.symbols ?? [] } };
1303
+ // The store has no read by id (`get` and `list` each rebuild the whole live view), so it is listed at most once per record, and only when the task has a rendered counter at all: a task with
1304
+ // none never touches it. Only the rendered entries are screened, not the store. A hidden or unreadable entry is simply absent, and the figures then call their fail counts unknown.
1305
+ let listed: Map<string, ReturnType<MemoryStore["list"]>[number]> | undefined;
1306
+ const view = (id: string) => {
1307
+ listed ??= new Map(store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true }).map(v => [v.id, v]));
1308
+ const found = listed.get(id);
1309
+ return found ? screenMemory([found])[0] : undefined;
1310
+ };
1311
+ return memoryFigures({
1312
+ counters: candidates.counters(project),
1313
+ taskKey: taskKey(project, row),
1314
+ view,
1315
+ matchingPlan: fails => matchingPlanFails(briefTask, fails, planContext),
1316
+ });
1317
+ } catch { return { ...UNKNOWN_MEMORY_FIGURES }; }
1318
+ };
1245
1319
  const writeResearch = (taskId: number) => {
1246
1320
  const pending = researchPending.get(taskId);
1247
1321
  if (pending) clearTimeout(pending.timer);
1248
1322
  researchPending.delete(taskId);
1249
1323
  try {
1250
- appendRecords(projectId, taskRecords(readEvents(join(opts.stateDir, "events.jsonl")), projectId, { version: VERSION, source: "live" }).filter((r) => r.task === taskId));
1324
+ // #1277: the board and journal are read through a read-only handle, so the record carries its v2 blocks; the family lookup is the project's own (instances resolve there).
1325
+ // Scoped to the one task: the live writer runs on the daemon thread and must not parse every task's history and the whole journal for one record (a backfill reads them all).
1326
+ const evidence = { ...readEvidence(opts.stateDir, projectId, taskId), familyOf: (peer: string) => adapterCatalog.familyOf(peer, declarations), memory: onlyTaskMemory(taskId, memoryFiguresFor) };
1327
+ appendRecords(projectId, taskRecords(readEvents(join(opts.stateDir, "events.jsonl")), projectId, { version: VERSION, source: "live" }, evidence).filter((r) => r.task === taskId));
1251
1328
  } catch (error) {
1252
1329
  if (!researchLogged) log(`research record not written: ${(error as Error).message}`);
1253
1330
  researchLogged = true;
@@ -1298,7 +1375,13 @@ export async function startDaemon(opts: DaemonOptions) {
1298
1375
  sock.data.closed = true;
1299
1376
  for (const request of sock.data.invocationRequests?.values() ?? []) request.abort();
1300
1377
  sock.data.invocationRequests?.clear();
1301
- nativeHookLaunches.endOwner(sock);
1378
+ for (const { peer } of nativeHookLaunches.endOwner(sock)) {
1379
+ const run = runs.get(peer);
1380
+ if (!run) continue;
1381
+ if (budget.record(peer)) completionStore.dropRun(run.runTurn);
1382
+ else completionDone(peer, run, "interrupted");
1383
+ runs.close(peer);
1384
+ }
1302
1385
  if (sock.data.session && sock.data.peer) sessionIds.delete(sock.data.peer);
1303
1386
  consoles.delete(sock);
1304
1387
  operationalLogSubscribers.delete(sock);
@@ -1321,8 +1404,9 @@ export async function startDaemon(opts: DaemonOptions) {
1321
1404
  }), opts.controlPort === 0 ? [opts.codexAppPort, opts.codexProxyPort] : []);
1322
1405
  // Written once this run owns the port, before any connection can attach a peer: a daemon that fails to bind (another
1323
1406
  // is running) never marks a run boundary in the live one's events.
1324
- event({ type: "hub_start", instance: instanceId });
1407
+ event({ type: "hub_start", instance: instanceId, personAttribution: true });
1325
1408
  startupCleanup.push(() => server.stop(true));
1409
+ startupTimings.mark("control");
1326
1410
 
1327
1411
 
1328
1412
  const recoveryOperation = process.env.AGENTHUB_RECOVERY_OPERATION;
@@ -1374,12 +1458,14 @@ export async function startDaemon(opts: DaemonOptions) {
1374
1458
  const { terminalHistoryLimit, ...busReaders } = busOperationalReaders(() => config);
1375
1459
  const adapterTiming = adapterOperationalReaders(() => config);
1376
1460
  const modelTiming = modelOperationalReaders(() => config);
1461
+ startupTimings.mark("recovery");
1377
1462
  const journal = new DeliveryJournal({ file: join(opts.stateDir, "hub.db"), projectRoot: opts.cwd, projectId, instanceId, operationId: recoveryOperation, terminalHistoryLimit });
1378
1463
  // What the crash left in flight, per recipient: opening the journal just marked these needs_review.
1379
1464
  const lost = new Map<PeerId, JournalDelivery[]>();
1380
1465
  if (crashed) for (const d of journal.list()) if (d.state === "needs_review" && d.reason === "daemon stopped during delivery" && d.updatedAt >= startedAt) { lost.set(d.peer, [...(lost.get(d.peer) ?? []), d]); crashLostIds.add(d.id); }
1381
1466
  // Capabilities (issue #39): enforced here and in taskOp, never by role text alone. Unlisted peers keep everything.
1382
1467
  // A listed peer whose value is not a list gets nothing: whoever listed it meant to narrow it.
1468
+ startupTimings.mark("journal");
1383
1469
  const may = (peer: PeerId, cap: "propose" | "assign" | "remember" | "memory_correct" | "memory_read" | "important" | "spec_read" | "check_run" | "invoke"): boolean => {
1384
1470
  if (peer === USER || peer === HUB || !Object.hasOwn(config.capabilities, peer)) return true;
1385
1471
  const list = config.capabilities[peer];
@@ -1409,7 +1495,8 @@ export async function startDaemon(opts: DaemonOptions) {
1409
1495
  */
1410
1496
  const silence = (env: Envelope, to: PeerId): string | undefined => {
1411
1497
  if (reviewOnlyPeer(to) && env.to?.includes(to) && !reviewOnlyItem(to, env)) return `${to} is a review-only instance: it receives review requests only (send a review through the task board)`;
1412
- if (!turnFree() || env.from === USER || env.from === HUB || env.from === DIGEST || env.priority === "fyi" || env.kind !== "chat" || to === USER) return undefined;
1498
+ // Deferred hub notices are released before Tasks exists; keep Tasks-independent exclusions first.
1499
+ if (env.from === USER || env.from === HUB || env.from === DIGEST || env.priority === "fyi" || env.kind !== "chat" || to === USER || !turnFree()) return undefined;
1413
1500
  const cohort = tasks.silenced(env.from, to);
1414
1501
  if (!cohort) return undefined;
1415
1502
  const ids = [...cohort.members.keys()].sort((a, b) => a - b).map((id) => `#${id}`).join(", ");
@@ -1769,12 +1856,15 @@ export async function startDaemon(opts: DaemonOptions) {
1769
1856
  }, delayMs);
1770
1857
  recoveryLeaseTimer.unref?.();
1771
1858
  };
1859
+ startupTimings.mark("bus");
1772
1860
  const chain = projectChain(opts.cwd);
1773
1861
  const recalled = new Set<PeerId>(); // once per peer per hub run, however often the peer's session restarts
1774
1862
  // #258: the hub's own store, machine-wide in ~/.agenthub/memory. Entries are filed under the project's memory key (its
1775
1863
  // normalized origin remote, the same on every machine; without one, its path). Fail-open: without it the hub works as before.
1776
1864
  // Daemon start never depends on the memory home: an unresolvable home falls back to the raw key.
1777
1865
  const memoryProjectRaw = memoryProjectKey(opts.cwd);
1866
+ const executionLineageProjectKey = `ahub-${createHash("sha256").update(memoryProjectRaw).digest("hex")}`;
1867
+ const executionLineageCursorKey = randomBytes(32).toString("hex");
1778
1868
  const memoryProject = (() => { try { return memoryProjectFor(opts.cwd); } catch { return memoryProjectRaw; } })();
1779
1869
  let memoryStore: MemoryStore | undefined;
1780
1870
  let memoryBinding: MemoryProfileBinding | undefined;
@@ -1862,7 +1952,10 @@ export async function startDaemon(opts: DaemonOptions) {
1862
1952
  publicText: text => !looksSecret(text) && withoutPii([{ title: "", text }], activeRouting(), opts.cwd, config.pii?.paths ?? []).length === 1,
1863
1953
  capture: () => ({ memoryDir: captureBinding!.home }), log,
1864
1954
  });
1955
+ // ponytail: generated-note proofs are bounded to this daemon lifetime; after restart, unknown notes remain untouched.
1956
+ const generatedRecordNotes = new GeneratedNoteRegistry();
1865
1957
  const memoryTelemetry = candidates && memoryStore ? new MemoryTelemetry(candidates, memoryStore, memoryProject, screenMemory, checkMemory) : undefined;
1958
+ startupTimings.mark("memory");
1866
1959
  const staleness = () => createStalenessProbe({ cwd: opts.cwd, privatePaths: config.pii?.paths ?? [], deny: config.local.deny });
1867
1960
  const memoryLine = (v: MemoryView) => `mem:${v.id.slice(0, 8)} ${v.kind} ${v.tier}: ${`${v.title ? `${v.title}: ` : ""}${v.text}`.replace(/\s+/g, " ").slice(0, 160)}`;
1868
1961
  /** A task's own nodes: what its title names (an issue, a path), its refs and plan paths, plan symbols, and the task itself. */
@@ -2033,18 +2126,23 @@ export async function startDaemon(opts: DaemonOptions) {
2033
2126
  /** Machine sync, when a person set a remote; one log line per failure, never a blocked turn. Stopping aborts and awaits it. */
2034
2127
  function syncNow(): Promise<void> {
2035
2128
  if (!memoryStore || syncRun || stopping) return syncRun ?? Promise.resolve();
2036
- const recordFailure = (cause: ReturnType<typeof classifyMemorySyncFailure> & { declinedIdsFingerprint?: string; declinedIdsKnown?: false; failureDetailHash?: string; placementActive?: false }, errorText?: string) => {
2037
- if (quietSyncError(errorText)) {
2129
+ let attestation: ReturnType<typeof hostPlacementAttestation> | undefined;
2130
+ const recordFailure = (cause: ReturnType<typeof classifyMemorySyncFailure> & { declinedIdsFingerprint?: string; declinedIdsKnown?: false; failureDetailHash?: string; placementActive?: false; writerCategory?: string; writerCauseClass?: string }, errorText?: string) => {
2131
+ if (cause.cause !== "writer" && quietSyncError(errorText)) {
2038
2132
  const state = errorText?.startsWith("stopped") ? "stopped" : "not-configured";
2039
2133
  memorySyncState = reduceMemorySync(memorySyncState, { type: "quiet", at: Date.now(), state }).state;
2040
2134
  return;
2041
2135
  }
2042
2136
  const reduced = reduceMemorySync(memorySyncState, { type: "failure", at: Date.now(), ...cause });
2043
2137
  memorySyncState = reduced.state;
2044
- if (reduced.logFailure && !quietSyncError(errorText)) log(`hub memory sync failed: ${cause.cause}${cause.cause === "declined" ? ` (${cause.declinedCount ?? 0} declined)` : ""}`);
2138
+ if (reduced.logFailure) log(`hub memory sync failed: ${cause.cause}${cause.cause === "declined" ? ` (${cause.declinedCount ?? 0} declined)` : cause.cause === "writer" ? ` (${cause.writerCategory ?? "unknown"}, ${cause.writerCauseClass ?? "unavailable"}); next: ${memorySyncNextStep("writer")}` : ""}`);
2045
2139
  };
2140
+ /** #1173: a refused writer attestation is its own closed cause with its category and next step, never a silent skip or a generic unknown. */
2141
+ const writerFailure = (refusal: WriterRefusal) => ({ cause: "writer" as const, writerCategory: refusal.category, writerCauseClass: refusal.causeClass });
2046
2142
  const recordUnexpectedFailure = (error: unknown) => {
2047
- const errorText = typeof error === "string" ? error : error instanceof Error ? error.message : undefined;
2143
+ const refusal = attestation?.refusal() ?? writerRefusalOf(error);
2144
+ if (refusal) { recordFailure(writerFailure(refusal), undefined); return; }
2145
+ const errorText = memorySyncErrorText(error);
2048
2146
  if (quietSyncError(errorText)) {
2049
2147
  recordFailure(classifyMemorySyncFailure(error), errorText);
2050
2148
  return;
@@ -2056,11 +2154,16 @@ export async function startDaemon(opts: DaemonOptions) {
2056
2154
  checkMemory();
2057
2155
  const policy = currentMemorySyncPolicy();
2058
2156
  const policyVersion = memorySyncPolicyVersion();
2157
+ // Fresh per pass: agent-mem re-measures every writer install on each check; the legacy transport ignores it.
2158
+ attestation = hostPlacementAttestation(memoryStore!.profile.home);
2059
2159
  const r = await (opts.memorySync ?? syncMemory)(memoryStore!, {
2060
2160
  signal: syncStop.signal,
2161
+ placementAttestation: attestation.attest,
2061
2162
  screen: row => policy.screen(row, true).ok,
2062
2163
  policyVersion: () => memorySyncPolicyVersion(),
2063
2164
  });
2165
+ const refused = attestation.refusal();
2166
+ if (refused) { recordFailure(writerFailure(refused)); return; }
2064
2167
  if (memorySyncPolicyVersion() !== policyVersion) {
2065
2168
  recordFailure({ cause: "binding" }, "binding changed");
2066
2169
  return;
@@ -2108,7 +2211,14 @@ export async function startDaemon(opts: DaemonOptions) {
2108
2211
  own = memoryStore ? nativeRecall([...goals, ...recallMemoryLines(screenMemory(memoryStore.list({ project: memoryProject, tier: "long", limit: Number.MAX_SAFE_INTEGER }).filter((v) => v.kind !== "finding")), 30, staleness())], config.memory.enabled ? Math.floor(config.memory.inject_tokens / 2) : config.memory.inject_tokens, (line) => sanitize(line.replace(/\s+/g, " "))) : undefined;
2109
2212
  }
2110
2213
  catch (e) { log(`hub memory recall failed: ${(e as Error).message}`); }
2111
- const theirs = config.memory.enabled ? await recallFor(peer, memory, chain, own ? Math.ceil(config.memory.inject_tokens / 2) : config.memory.inject_tokens) : undefined;
2214
+ const recordRecallTask: BriefTask = { owner: peer, title: "", refs: {} };
2215
+ const recordRecallAllowed = () => !reviewOnlyPeer(peer) && !contextPii(peer) && !reviewObserverInput(peer) && recordReadAllowed(undefined, recordReadCwd(recordRecallTask));
2216
+ const recordRecallTokens = own ? Math.ceil(config.memory.inject_tokens / 2) : config.memory.inject_tokens;
2217
+ const theirs = config.memory.enabled ? await recallFor(peer, memory, chain, recordRecallTokens, {
2218
+ allowed: recordRecallAllowed, policyVersion: () => recordReadVersion(recordRecallTask),
2219
+ project: original => projectRecordRecall(peer, original, recordRecallTokens),
2220
+ observe: counts => { if (recordRecallAllowed()) log(`records recall before=${counts.beforeBytes} after=${counts.afterBytes}`); },
2221
+ }) : undefined;
2112
2222
  const block = [own, theirs].filter(Boolean).join("\n\n");
2113
2223
  if (!block || recalled.has(peer)) return; // nothing yet (worker down, no memory): the peer's next session tries again
2114
2224
  recalled.add(peer);
@@ -2162,7 +2272,26 @@ export async function startDaemon(opts: DaemonOptions) {
2162
2272
  try { notify(`conductor ${action.actor}: ${action.action}${action.task === undefined ? "" : ` #${action.task}`}${action.peer ? ` ${action.peer}` : ""}`); } catch { /* never throw after a task/hold write */ }
2163
2273
  };
2164
2274
  const inboxPolling = new InboxPolling();
2275
+ startupTimings.mark("model_runtime");
2165
2276
  const board = new Board(join(opts.stateDir, "hub.db"));
2277
+ try {
2278
+ const retainedExecutionReferences = board.executionReferencesIntegrity(), expected = restored?.integrity?.executionReferences;
2279
+ if (restored?.integrity && (expected ? expected.count !== retainedExecutionReferences.count || expected.digest !== retainedExecutionReferences.digest : retainedExecutionReferences.count !== 0)) throw new Error("changed recovery binding");
2280
+ } catch {
2281
+ board.close(); throw new Error("execution reference state or recovery binding is unavailable; restore trusted project state and choose a compatible recovery target before retrying");
2282
+ }
2283
+ try {
2284
+ const retainedGuidance = board.guidanceVariantsIntegrity(), expected = restored?.integrity?.guidanceVariants;
2285
+ if (restored?.integrity && (expected ? expected.experiments !== retainedGuidance.experiments || expected.variants !== retainedGuidance.variants
2286
+ || expected.digest !== retainedGuidance.digest : retainedGuidance.experiments !== 0 || retainedGuidance.variants !== 0)) throw new Error("changed recovery binding");
2287
+ } catch {
2288
+ board.close(); throw new Error("guidance variant state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2289
+ }
2290
+ const visuals = new VisualStore(join(opts.stateDir, "hub.db"));
2291
+ startupCleanup.push(() => visuals.close());
2292
+ // Held recovery must compare the source's exact rows before any retention mutation.
2293
+ if (!recoveryActive() && !bus.isRecoveryHeld) visuals.prune(config.visuals.retention_days, Date.now(), task => !!board.get(task));
2294
+ startupTimings.mark("board");
2166
2295
  const reviewInputHeld = (peer: PeerId, envs: readonly Envelope[]): boolean => {
2167
2296
  if (envs.some(isReviewObserverExcluded)) return true;
2168
2297
  const taskIds = envs.flatMap(env => {
@@ -2239,6 +2368,10 @@ export async function startDaemon(opts: DaemonOptions) {
2239
2368
  }
2240
2369
  };
2241
2370
  const reviewObserverInput = (peer: PeerId): boolean => {
2371
+ // ponytail: read-only held views mint no input receipt; conservatively exclude
2372
+ // retained readable held review rows until explicit disposition, even if unread.
2373
+ // Upgrade with host-verified read provenance, never a transport ACK.
2374
+ if (bus.hasHeldReviewScope(peer)) return true;
2242
2375
  resetReviewObserverSessionIfChanged(peer);
2243
2376
  const pending = pendingReviewObserverInputs.get(peer);
2244
2377
  return (pending ? pending.held || pending.previous?.held === true : currentReviewObserverInputs.get(peer)?.held === true) || reviewObserverDurableHeld(peer);
@@ -2397,6 +2530,12 @@ export async function startDaemon(opts: DaemonOptions) {
2397
2530
  const reviewSymbols = new Map<string, CodeFactResult<CodeSymbol[]>>();
2398
2531
  const memorySymbols = new Map<string, MemorySymbolNodes>();
2399
2532
  startupCleanup.push(() => board.close());
2533
+ const modelOverrides = new ModelOverrides(join(opts.stateDir, "hub.db"));
2534
+ const modelLatches = new ModelOverrideLatches(modelOverrides);
2535
+ const modelManagedOwners = new WeakSet<PeerAdapter>();
2536
+ const modelAcpOwners = new WeakMap<PeerAdapter, AcpPeer>();
2537
+ const modelLaunchModels = new WeakMap<PeerAdapter, string>();
2538
+ startupCleanup.push(() => modelOverrides.close());
2400
2539
  startupCleanup.push(() => codeFacts.close());
2401
2540
  const supervision = new SupervisionFeed({
2402
2541
  conductor: () => conductorPeer(config.roles) ?? undefined,
@@ -2830,6 +2969,7 @@ export async function startDaemon(opts: DaemonOptions) {
2830
2969
  ...(config.memory.enabled ? { memory } : {}),
2831
2970
  candidates, candidateScreen: screenMemory, privateTurn: peer => !!turns.get(peer)?.private || contextPii(peer),
2832
2971
  memoryCheck: checkMemory,
2972
+ executionLineage: { projectKey: executionLineageProjectKey, cursorKey: executionLineageCursorKey, readDelivery: id => journal.get(id) },
2833
2973
  briefs: new Briefs(config.memory.enabled ? memory : undefined, chain.at(-1)!, () => config.memory.brief_items,
2834
2974
  memoryStore ? taskMemoryItems : undefined,
2835
2975
  (peer, task, counts) => event({ type: "memory_brief", source: "amem", peer, task, ...counts }),
@@ -2838,6 +2978,9 @@ export async function startDaemon(opts: DaemonOptions) {
2838
2978
  {
2839
2979
  allowed: corpusBriefAllowed, policyVersion: corpusPolicyVersion,
2840
2980
  read: task => publicCorpus([task.title, ...task.refs.paths ?? [], ...task.plan?.paths ?? [], ...task.plan?.symbols ?? []].join(" "), () => corpusBriefAllowed(task)).map(item => ({ id: item.id, kind: "note", line: `${item.id}: ${item.text.replace(/\s+/g, " ")}` })),
2981
+ }, {
2982
+ allowed: recordReadAllowed, policyVersion: recordReadVersion, read: readRecordSnapshot,
2983
+ observe: (_peer, task, counts) => { const row = task === undefined ? undefined : board.get(task); if (row && recordReadAllowed(row)) log(`records brief before=${counts.beforeBytes} after=${counts.afterBytes} replaced=${counts.replacedNotes} records=${counts.records}`); },
2841
2984
  }),
2842
2985
  ...(memoryStore ? { planFails: (task: import("./board.ts").Task) => {
2843
2986
  const read = () => {
@@ -2851,7 +2994,7 @@ export async function startDaemon(opts: DaemonOptions) {
2851
2994
  };
2852
2995
  return controlWriteTelemetry ? controlWriteTelemetry.observe("memory", controlWritePrivacyGuard(true, true, undefined, task.id), read) : read();
2853
2996
  } } : {}),
2854
- ...(memoryStore ? { store: { store: memoryStore, project: memoryProject, repo: memoryRepo, deny: config.local.deny, onNote: (id: string) => void suggestEdges(id) } } : {}),
2997
+ ...(memoryStore ? { store: { store: memoryStore, project: memoryProject, repo: memoryRepo, deny: config.local.deny, onGeneratedNote: (proof: GeneratedNoteProof) => generatedRecordNotes.record(proof), onNote: (id: string) => void suggestEdges(id) } } : {}),
2855
2998
  notify,
2856
2999
  recordOverlap: (task, owner, others) => event({ type: "overlap", task, owner, others }),
2857
3000
  checkEnded: owner => settleCheck(owner), // #1054: a run waited on its owner's completion check
@@ -2931,6 +3074,115 @@ export async function startDaemon(opts: DaemonOptions) {
2931
3074
  failing: () => ({ ...bus.failingPeers(), ...Object.fromEntries(reviewerUnavailable) }),
2932
3075
  held: () => Object.fromEntries(bus.knownPeers().flatMap((peer) => { const hold = queueHold(peer); return hold ? [[peer, hold]] : []; })),
2933
3076
  });
3077
+ /**
3078
+ * #1221 T2: the bounded proposal queue. The store is built even while the mode is off (its tables are additive and a
3079
+ * person may turn the mode on at the next reload), and nothing in it runs until an explicit decision arrives: reading
3080
+ * the board is the only thing this side does on its own.
3081
+ */
3082
+ const proposalStore = new ProposalStore(join(opts.stateDir, "hub.db"));
3083
+ startupCleanup.push(() => proposalStore.close());
3084
+ const supervisionProposals = new SupervisionProposals(proposalStore, {
3085
+ facts: (task) => proposalFacts(task),
3086
+ isPrivate: (task) => { const row = board.get(task); return !row || tasks.isPii(row); },
3087
+ // The native generation this reading was made under: the owner's session, or `hub` when no agent owns the task.
3088
+ generation: (task) => {
3089
+ const owner = board.get(task)?.owner;
3090
+ return !owner || owner === USER || owner === HUB ? "hub" : `${owner}@${bus.peers.get(owner)?.sessionGeneration ?? "unknown"}`;
3091
+ },
3092
+ // Present roles only, and no new one: the task's owner and reviewer, the configured planner, the conductor, the person.
3093
+ mayDecide: (actor, task) => {
3094
+ const row = board.get(task);
3095
+ if (!row) return false;
3096
+ if (actor === USER || actor === conductorPeer(config.roles) || plannerPeers().includes(actor)) return true;
3097
+ return row.owner === actor || row.reviewer === actor;
3098
+ },
3099
+ // The action's own authority, which a decision does not carry: `escalate` is the conductor's move and the person's,
3100
+ // while the hub's owner notice for a recheck or an integration request runs for whoever may decide.
3101
+ mayRun: (actor, proposal) =>
3102
+ proposal.action !== "escalate" || actor === USER || actor === conductorPeer(config.roles),
3103
+ // A needs_review delivery holds the owner's advice too; unavailable hold evidence is held, never a pass.
3104
+ held: (task) => {
3105
+ const owner = board.get(task)?.owner;
3106
+ if (!owner || owner === USER || owner === HUB) return false;
3107
+ const hints = bus.heldDeliveryHints(owner);
3108
+ return hints === undefined || hints.count > 0;
3109
+ },
3110
+ run: (proposal, actor) => runSupervisionProposal(proposal, actor),
3111
+ now: () => Date.now(),
3112
+ });
3113
+ /** The bounded fact set one proposal reads: the task, its declared overlap partners, and its own measurement. */
3114
+ async function proposalFacts(task: number): Promise<SupervisionFacts> {
3115
+ const row = board.get(task);
3116
+ if (!row) return { tasks: [] };
3117
+ const partners = tasks.overlapTasks(row).filter((id) => id !== row.id).slice(0, MAX_REFS);
3118
+ const read = [row, ...partners.map((id) => board.get(id)).filter((candidate): candidate is typeof row => !!candidate)];
3119
+ const facts: SupervisionFacts = {
3120
+ tasks: read.map((candidate) => ({ id: candidate.id, state: candidate.state, history: candidate.history as SupervisionHistoryFact[] })),
3121
+ overlaps: partners.map((other) => ({ task: row.id, other })),
3122
+ };
3123
+ const side = facts.tasks[0]!;
3124
+ const window = side.history.slice(taskRevision(side).from);
3125
+ // Hashing is only owed when this revision recorded a check pass over delivered ids; otherwise the rule says so itself.
3126
+ if (!tasks.isPii(row) && window.some((entry) => entry.event === "check passed") && window.some((entry) => (entry.deliverables?.length ?? 0) > 0)) {
3127
+ const status = await tasks.deliverableStatus(row);
3128
+ if (status) {
3129
+ facts.deliverables = [{
3130
+ task: row.id, checked: status.files.every((file) => file.state !== "unknown"),
3131
+ changed: status.files.filter((file) => file.state === "changed").map((file) => file.id),
3132
+ missing: status.files.filter((file) => file.state === "missing").map((file) => file.id),
3133
+ }];
3134
+ }
3135
+ }
3136
+ return facts;
3137
+ }
3138
+ /**
3139
+ * The existing action a proposal names, through that action's own authority. `escalate` is the conductor's move (the
3140
+ * person may always escalate, exactly as the console does); the other two are the hub's own owner notice, whose own
3141
+ * authority is the delivery path: the check re-run and the integration stay the owner's actions, and their results
3142
+ * land on the board as their own records.
3143
+ */
3144
+ async function runSupervisionProposal(proposal: SupervisionProposal, actor: string): Promise<{ outcome: "ran" | "refused" | "unknown"; detail?: string }> {
3145
+ if (proposal.action === "escalate") {
3146
+ try {
3147
+ if (actor === USER) await tasks.escalate(USER, proposal.task, "a supervision proposal the person accepted", "manual", true);
3148
+ else await conductor.execute(actor, "hub_task_escalate", { id: proposal.task });
3149
+ } catch (error) {
3150
+ // An action's own pre-effect refusal is a certain outcome: nothing ran. Anything else may have had an effect, and
3151
+ // the queue records it `unknown` instead of pretending either way.
3152
+ if (error instanceof PreEffectToolRefusal) return { outcome: "refused", detail: error.message.slice(0, 200) };
3153
+ throw error;
3154
+ }
3155
+ return { outcome: "ran", detail: "escalate" };
3156
+ }
3157
+ const partner = proposal.refs.find((ref) => ref.startsWith("task:"));
3158
+ const other = proposal.action === "request_integration" && partner ? Number(partner.slice("task:".length)) : undefined;
3159
+ const stale = proposal.refs.filter((ref) => ref.startsWith("deliverable:")).join(", ");
3160
+ const body = proposal.action === "recheck"
3161
+ ? `Task #${proposal.task}: supervision recheck. The files delivered before the recorded check pass changed since then${stale ? ` (${stale})` : ""}. Run the check again and re-file hub_task_done with its result.`
3162
+ : `Task #${proposal.task}: supervision integration. #${proposal.task} and #${other ?? "?"} declared overlapping work, both owners accepted, and no integration is recorded since. Land the integration, or record why the overlap does not need one.`;
3163
+ const told = tasks.supervisionNotice(proposal.task, other, body);
3164
+ return told.sent.length ? { outcome: "ran", detail: `notice to ${told.sent.join(", ")}` } : { outcome: "refused", detail: told.refused ?? "no owner to tell" };
3165
+ }
3166
+ /** `off` evaluates nothing; `shadow` stores bounded proposals with no console row or notice; `advisory` may show one. */
3167
+ const supervisionMode = () => config.supervision?.mode ?? "off";
3168
+ /** What a tool result and the inbox show: codes and ids only, never a title, a note or a path. */
3169
+ const proposalView = (proposal: SupervisionProposal) => ({
3170
+ id: proposal.id, task: proposal.task, rule: proposal.rule, version: proposal.version, revision: proposal.revision, trigger: proposal.trigger,
3171
+ refs: proposal.refs, limits: { records: proposal.records, truncated: proposal.truncated }, action: proposal.action, reason: proposal.reason,
3172
+ state: proposal.state, created: proposal.createdAt, ...(proposal.actor ? { actor: proposal.actor } : {}),
3173
+ ...(proposal.disposedAt === undefined ? {} : { decided: proposal.disposedAt }), ...(proposal.receipt ? { receipt: proposal.receipt } : {}),
3174
+ });
3175
+ const proposeObserved = (task: number): void => {
3176
+ if (supervisionMode() === "off" || stopping || recoveryActive()) return;
3177
+ const row = board.get(task);
3178
+ // A declared pair's reading is bound to its lower task id, so a change on the higher-id side is only read by
3179
+ // re-reading each partner: without that, a pair proposal would be created or invalidated from one side alone.
3180
+ for (const id of new Set([task, ...(row ? tasks.overlapTasks(row) : [])])) {
3181
+ const candidate = board.get(id);
3182
+ if (!candidate || candidate.state === "backlog" || tasks.isPii(candidate)) continue;
3183
+ void supervisionProposals.observe(id).catch((error: Error) => log(`supervision observe for #${id} failed: ${error.message}`));
3184
+ }
3185
+ };
2934
3186
  relevantNotice = (peer, env) => {
2935
3187
  if (env.from === HUB && env.refs?.boundedCheck) {
2936
3188
  const run = env.refs.boundedCheck, binding = checkBindings.get(run);
@@ -2958,6 +3210,9 @@ export async function startDaemon(opts: DaemonOptions) {
2958
3210
  return true;
2959
3211
  };
2960
3212
  tasks.recoverIntegrations();
3213
+ // #1221 T2 AC6: a restart keeps the dedupe keys, the dispositions and an action outcome the hub never observed. A
3214
+ // pending proposal whose task moved or closed expires here, once, with nothing replayed.
3215
+ void supervisionProposals.recover().catch((error: Error) => log(`supervision reconcile failed: ${error.message}`));
2961
3216
  /** Peers told, at their first attach, what the cohorts lost in the restart held for them (issue #107). */
2962
3217
  const replayed = new Set<PeerId>();
2963
3218
  // Turn-free facts (issue #108): what the others changed in an owner's files, at its tool calls. Scopes are read from
@@ -3009,6 +3264,8 @@ export async function startDaemon(opts: DaemonOptions) {
3009
3264
  const observeProgress = (peer: PeerId, observation: ToolObservation | undefined, taskId?: string): void => {
3010
3265
  if (!observation) return;
3011
3266
  if (reviewObserverHeld(peer) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded)) { progress.clearPeer(peer); return; }
3267
+ const toolName = observation.name.replace(/^mcp__[^ ]+__/, "");
3268
+ if (GUIDANCE_TOOL_NAMES.has(toolName)) return;
3012
3269
  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)
3013
3270
  try {
3014
3271
  const candidates = board.list().filter(task => task.owner === peer && ["in_progress", "changes_requested"].includes(task.state));
@@ -3134,14 +3391,29 @@ export async function startDaemon(opts: DaemonOptions) {
3134
3391
  // same peer cannot undo a settlement.
3135
3392
  const turnEnded = new Map<PeerId, number>();
3136
3393
  const nativeCompletedAt = new Map<PeerId, number>();
3137
- const nativeStopsSeen = new Set(readEvents(join(opts.stateDir, "events.jsonl")).flatMap(event => event.type === "native_turn_end" && event.id ? [event.id] : []));
3394
+ startupTimings.mark("task_runtime");
3395
+ const startupSeeds = readStartupEventSeeds(join(opts.stateDir, "events.jsonl"));
3396
+ try { opts.startupSeedObserved?.({ readPasses: startupSeeds.readPasses, readBytes: startupSeeds.readBytes }); } catch { /* Diagnostic observers cannot change replay or readiness. */ }
3397
+ const nativeStopsSeen = startupSeeds.nativeStopsSeen;
3398
+ startupTimings.mark("native_stop_seed");
3138
3399
  const activeAt = new Map<PeerId, number>();
3139
3400
  interface NativeTurnStart { at: number; baseline?: string; generation: string; session: string; launch: string }
3140
3401
  const nativeTurnStart = new Map<PeerId, NativeTurnStart>();
3141
3402
  const stopUnconfirmedNoticed = new WeakSet<NativeTurnStart>();
3142
3403
  const nativeStopWaits = new Map<PeerId, { start: NativeTurnStart; wait: ReturnType<typeof waitForClaudeCompletion> }>();
3143
- /** Every Claude hook call's own start-up and the hub's time for it, summed per turn (issue #108): reported at Stop. */
3404
+ /** Every Claude or managed native hook call's own start-up and the hub's time for it, summed per turn (issue #108): reported at Stop. */
3144
3405
  const hookStats = new Map<PeerId, { n: number; startupMs: number; hubMs: number; maxStartupMs: number }>();
3406
+ const tallyHook = (peer: PeerId, callStarted: number, startedMs: unknown) => {
3407
+ const st = hookStats.get(peer) ?? { n: 0, startupMs: 0, hubMs: 0, maxStartupMs: 0 };
3408
+ const startup = typeof startedMs === "number" && Number.isFinite(startedMs) ? Math.max(0, startedMs) : 0;
3409
+ hookStats.set(peer, { n: st.n + 1, startupMs: st.startupMs + startup, hubMs: st.hubMs + (performance.now() - callStarted), maxStartupMs: Math.max(st.maxStartupMs, startup) });
3410
+ };
3411
+ const emitHookStats = (peer: PeerId) => {
3412
+ const st = hookStats.get(peer);
3413
+ if (!st) return;
3414
+ event({ type: "hook_stats", peer, n: st.n, startupMs: Math.round(st.startupMs), hubMs: Math.round(st.hubMs), maxStartupMs: Math.round(st.maxStartupMs) });
3415
+ hookStats.delete(peer);
3416
+ };
3145
3417
  /**
3146
3418
  * Between native turns now: Claude stopped after its last tool call began (its channel going offline says nothing
3147
3419
  * about its session, whose hooks may still run); any other peer's adapter is not in a turn. The adapter's own state,
@@ -3168,7 +3440,8 @@ export async function startDaemon(opts: DaemonOptions) {
3168
3440
  }
3169
3441
  if ((h.event === "proposed" || h.event === "backlog pulled" || h.event === "catalog role changed") && (t.role ? catalog.roles.has(t.role) : h.event === "catalog role changed")) event({ type: "role", task: t.id, actor: h.by, stage: "assigned", roles: t.role ? [roleIdentity(catalog.roles.get(t.role)!)] : [] });
3170
3442
  event({ type: "task", id: t.id, event: h.event, by: h.by, state: t.state, owner: t.owner, reviewer: t.reviewer, class: t.class, ...(t.profile ? { profile: t.profile, profileClass: t.profileClass } : {}), ...(t.role ? { role: t.role, ...(catalog.roles.has(t.role) ? { roleIdentity: roleIdentity(catalog.roles.get(t.role)!) } : {}) } : {}), pii: tasks.isPii(t), ...(t.planningRevision ? { release: t.release ?? null, priority: t.priority ?? null, plannedStart: t.plannedStart ?? null, due: t.due ?? null } : {}), ...(h.reason ? { reason: h.reason } : {}) });
3171
- if (config.research.enabled && t.state === "approved" && (h.event === "approved" || h.event === "done")) recordResearch(t.id);
3443
+ // #1277 AC6: a cancelled task is a terminal task too, and the guarded merge writes its receipt after the approval, so its result completes the record's merge block.
3444
+ if (config.research.enabled && ((t.state === "approved" && (h.event === "approved" || h.event === "done" || h.event === "merged outside the hub" || h.event === "merge result")) || (t.state === "cancelled" && h.event === "cancelled"))) recordResearch(t.id);
3172
3445
  if (memoryStore && (t.state === "in_progress" || h.event === "done") && !tasks.isPii(t)) renewLeases(t);
3173
3446
  if ((h.event === "proposed" || h.event === "backlog pulled") && projections.enabled && turnLog) {
3174
3447
  const created = taskProposalAt(t);
@@ -3178,6 +3451,8 @@ export async function startDaemon(opts: DaemonOptions) {
3178
3451
  }
3179
3452
  }
3180
3453
  supervision.taskChanged(t, h);
3454
+ // #1221 T2: the rules read only after the board has the record; a mode that is off costs one string comparison.
3455
+ proposeObserved(t.id);
3181
3456
  // Models can self-claim after their turn begins; preserve that ownership even if they finish before settlement.
3182
3457
  const turn = t.owner ? turns.get(t.owner) : undefined;
3183
3458
  if (turn) turnTasks.set(turn.id, [...new Set([...(turnTasks.get(turn.id) ?? []), t.id])]);
@@ -3193,6 +3468,161 @@ export async function startDaemon(opts: DaemonOptions) {
3193
3468
  };
3194
3469
  const activityRings: Record<string, ActivityRing> = Object.fromEntries(SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.capabilities?.watch).map(peer => [peer, new ActivityRing()]));
3195
3470
  const contextPii = (peer: PeerId) => !!turns.get(peer)?.private || board.peerTaskSignals(peer).some(task => !isClosedTaskState(task.state) && tasks.isPii(task));
3471
+ const recordOwners = new WeakMap<PeerAdapter, { cwd: string; session(): string | undefined }>();
3472
+ const recordInputs = new Map<PeerId, { owner: PeerAdapter | undefined; originals: readonly Envelope[]; tainted?: true }>();
3473
+ const recordFrames = new Map<PeerId, { owner: PeerAdapter; turn: NonNullable<ReturnType<typeof turns.get>>; capture: RecordCapture }>();
3474
+ function recordPolicy(cwd: string): { enabled: boolean; version: string } | undefined {
3475
+ try {
3476
+ if (opts.effectiveRecordPolicy) {
3477
+ const policy = opts.effectiveRecordPolicy(cwd);
3478
+ return policy && typeof policy.enabled === "boolean" && typeof policy.version === "string" && policy.version ? { enabled: policy.enabled, version: policy.version } : undefined;
3479
+ }
3480
+ const binding = captureBinding;
3481
+ if (!binding || memoryProblem) return;
3482
+ binding.assertCurrent();
3483
+ const enabled = recordsEnabled(binding.home, cwd);
3484
+ // This revision binds only the public flag; fresh configuredPolicy screens below bind current privacy policy.
3485
+ return { enabled, version: enabled ? "records:true" : "records:false" };
3486
+ }
3487
+ catch { return; }
3488
+ }
3489
+ function recordPublic(text: string): boolean { return !looksSecret(text) && boundedSafe(text) && tasks.publicMetadataText(text); }
3490
+ function recordPathDenied(path: string, cwd = opts.cwd): boolean { return isDenied(path, config.local.deny) || matchesPolicy(cwd, path, config.pii?.paths ?? [], true) || matchesPolicy(opts.cwd, resolve(cwd, path), config.pii?.paths ?? [], true); }
3491
+ function recordInputAllowed(peer: PeerId, envs: readonly Envelope[]): boolean {
3492
+ try { return !!envs.length && !reviewInputHeld(peer, envs) && !reviewObserverInput(peer) && !envs.some(env => env.private || isReviewObserverExcluded(env) || isInvocationKind(env) || remoteEnvelope(env) || env.to?.some(id => id.includes("@"))); }
3493
+ catch { return false; }
3494
+ }
3495
+ function recordOwnerEligible(owner: PeerAdapter): boolean {
3496
+ const recordPeerId = owner.id, input = recordInputs.get(recordPeerId), proxy = frontendProxyState(recordPeerId, owner);
3497
+ if (proxy.present && (!proxy.port || proxy.port.attached)) return false;
3498
+ return config.memory.enabled && !stopping && !recoveryActive() && !bus.isRecoveryHeld && recordOwners.has(owner) && bus.peers.get(recordPeerId) === owner
3499
+ && membershipAllowed(recordPeerId) && owner.state === "busy" && !reviewOnlyPeer(recordPeerId) && !definitionOf(recordPeerId)?.reviewer && !contextPii(recordPeerId)
3500
+ && !!input && !input.tainted && input.owner === owner && recordInputAllowed(recordPeerId, input.originals);
3501
+ }
3502
+ function noteRecordSteered(peer: PeerId, originals: readonly Envelope[]): void {
3503
+ const input = recordInputs.get(peer), owner = bus.peers.get(peer);
3504
+ if (!input) { recordInputs.set(peer, { owner, originals: [], tainted: true }); return; }
3505
+ if (!input.tainted && (!owner || input.owner !== owner || !recordInputAllowed(peer, originals))) input.tainted = true;
3506
+ }
3507
+ function closeRecordFrame(peer: PeerId): void { recordFrames.get(peer)?.capture.close(); recordFrames.delete(peer); }
3508
+ function bindRecordOwner(owner: PeerAdapter, cwd: string, session: () => string | undefined): void {
3509
+ recordOwners.set(owner, { cwd, session });
3510
+ owner.recordInstruction = () => {
3511
+ if (!recordOwnerEligible(owner)) return;
3512
+ const turn = turns.get(owner.id), bound = recordOwners.get(owner), prior = recordFrames.get(owner.id);
3513
+ if (!turn || !bound) return;
3514
+ if (prior?.owner === owner && prior.turn === turn) return prior.capture.instruction();
3515
+ closeRecordFrame(owner.id);
3516
+ const session = bound.session();
3517
+ if (!session) return;
3518
+ const effective = recordPolicy(cwd);
3519
+ if (!effective?.enabled || !captureBinding || memoryProblem) return;
3520
+ const binding = captureBinding, profile = memorySyncPolicyVersion(), revision = configRevision, generation = owner.sessionGeneration;
3521
+ const current = () => {
3522
+ if (!recordOwnerEligible(owner) || turns.get(owner.id) !== turn || bound.session() !== session || owner.sessionGeneration !== generation || configRevision !== revision || captureBinding !== binding || memoryProblem) return false;
3523
+ const policy = recordPolicy(cwd);
3524
+ if (policy?.enabled !== true || policy.version !== effective.version || memorySyncPolicyVersion() !== profile) return false;
3525
+ try { binding.assertCurrent(); return memoryProjectFor(opts.cwd) === memoryProject; } catch { return false; }
3526
+ };
3527
+ const policy: RecordCapturePolicy = { records: true, current, project: memoryProject, cwd, peer: owner.id, turn: turn.id, session, at: new Date(turn.start).toISOString(), memoryDir: binding.home,
3528
+ publicText: text => { try { return current() && configuredPolicy(binding.home, cwd).screenStandalone(text) && recordPublic(text) && current(); } catch { return false; } },
3529
+ denyPath: path => recordPathDenied(path, cwd) };
3530
+ const capture = new RecordCapture({ eligible: () => recordOwnerEligible(owner) && turns.get(owner.id) === turn, policy: () => current() ? policy : undefined,
3531
+ observe: counts => { if (current()) log(`records capture accepted=${counts.accepted} dropped=${counts.dropped} bytes=${counts.bytes}`); } });
3532
+ recordFrames.set(owner.id, { owner, turn, capture });
3533
+ return capture.instruction();
3534
+ };
3535
+ }
3536
+ function recordReadCwd(task?: Pick<BriefTask, "owner">): string {
3537
+ const owner = task?.owner ? bus.peers.get(task.owner) : undefined;
3538
+ return owner ? recordOwners.get(owner)?.cwd ?? opts.cwd : opts.cwd;
3539
+ }
3540
+ function recordReadAllowed(task?: BriefTask, cwd = recordReadCwd(task)): boolean {
3541
+ try { return config.memory.enabled && !stopping && !recoveryActive() && !bus.isRecoveryHeld && !memoryProblem && !!captureBinding
3542
+ && (task ? corpusBriefAllowed(task) : true) && recordPolicy(cwd)?.enabled === true; } catch { return false; }
3543
+ }
3544
+ function recordReadVersion(task?: BriefTask): string { const cwd = recordReadCwd(task); return JSON.stringify([memorySyncPolicyVersion(), cwd, recordPolicy(cwd)]); }
3545
+ function readRecordSnapshot(task?: BriefTask, peer?: PeerId): import("../memory/brief.ts").RecordBriefSnapshot | undefined {
3546
+ const selectedPeer = task?.owner ?? peer;
3547
+ if (selectedPeer && (reviewOnlyPeer(selectedPeer) || contextPii(selectedPeer) || reviewObserverInput(selectedPeer))) return;
3548
+ const context = task ?? (peer ? { owner: peer, title: "", refs: {} } : undefined), cwd = recordReadCwd(context), owner = selectedPeer ? bus.peers.get(selectedPeer) : undefined;
3549
+ if (!recordReadAllowed(task, cwd)) return;
3550
+ const version = recordReadVersion(context), binding = captureBinding!;
3551
+ let store: CaptureStore | undefined;
3552
+ try {
3553
+ binding.assertCurrent(); if (memoryProjectFor(opts.cwd) !== memoryProject) return;
3554
+ const policy = configuredPolicy(binding.home, cwd);
3555
+ store = new CaptureStore({ memoryDir: binding.home, project: memoryProject, cwd, readOnly: true });
3556
+ const snapshot = store.readBriefRecords(32);
3557
+ if (!recordReadAllowed(task, cwd) || recordReadVersion(context) !== version) return;
3558
+ const paths = task ? [...task.refs.paths ?? [], ...task.plan?.paths ?? []] : undefined;
3559
+ const publicRow = (row: (typeof snapshot.rows)[number], currentPolicy: ReturnType<typeof configuredPolicy>) => row.event === "Record" && !row.subagent && Array.isArray(row.paths)
3560
+ && currentPolicy.screenStandalone(row) && currentPolicy.screenStandalone(row.excerpt) && currentPolicy.screenStandalone(row.paths) && recordPublic(JSON.stringify(row))
3561
+ && sanitize(row.excerpt) === row.excerpt && row.paths.every(anchor => typeof anchor === "string" && !recordPathDenied(anchor.split("#")[0]!, cwd));
3562
+ const rows = snapshot.rows.filter(row => publicRow(row, policy)
3563
+ && (!paths || row.paths.length === 0 || row.paths.some(anchor => paths.some(path => anchor === path || anchor.split("#")[0] === path))));
3564
+ const current = (text?: string) => {
3565
+ try {
3566
+ if (selectedPeer && (bus.peers.get(selectedPeer) !== owner || reviewOnlyPeer(selectedPeer) || contextPii(selectedPeer) || reviewObserverInput(selectedPeer))) return false;
3567
+ if (captureBinding !== binding || recordReadCwd(context) !== cwd || !recordReadAllowed(task, cwd) || recordReadVersion(context) !== version) return false;
3568
+ binding.assertCurrent(); if (memoryProjectFor(opts.cwd) !== memoryProject) return false;
3569
+ const fresh = configuredPolicy(binding.home, cwd);
3570
+ return rows.every(row => publicRow(row, fresh)) && (text === undefined || typeof text === "string" && fresh.screenStandalone(text) && recordPublic(text));
3571
+ } catch { return false; }
3572
+ };
3573
+ if (!current()) return;
3574
+ return { rows, replaceable: generatedRecordNotes.matching([...new Set(rows.flatMap(row => row.paths))], 32), partial: snapshot.partial, current };
3575
+ } catch { return; } finally { try { store?.close(); } catch { /* Read preference never changes the old brief. */ } }
3576
+ }
3577
+ function projectRecordRecall(peer: PeerId, original: string, tokens: number): import("../memory/recall.ts").RecordRecallProjection | undefined {
3578
+ const header = "# [amem] recent curated context\n\n### Curated short-term notes\n";
3579
+ if (typeof original !== "string" || original.length > 64 * 1024 || Buffer.byteLength(original) > 64 * 1024 || !original.startsWith(header) || original.includes("\r") || !Number.isSafeInteger(tokens) || tokens < 1) return;
3580
+ const owner = bus.peers.get(peer), context: BriefTask = { owner: peer, title: "", refs: {} };
3581
+ const allowed = () => bus.peers.get(peer) === owner && !reviewOnlyPeer(peer) && !contextPii(peer) && !reviewObserverInput(peer) && recordReadAllowed(undefined, recordReadCwd(context));
3582
+ if (!allowed()) return;
3583
+ const version = recordReadVersion(context), current = () => allowed() && recordReadVersion(context) === version;
3584
+ if (!current()) return;
3585
+ const body = original.slice(header.length).split("\n"), items: NativeItem[] = [], ids = new Set<string>(), protectedIds = new Set<string>();
3586
+ const row = /^(mem:[a-f0-9]{32}) (decision|finding|contract|fail): /;
3587
+ for (const line of body) {
3588
+ const match = row.exec(line);
3589
+ if (!match) { if (line.startsWith("mem:")) return; continue; }
3590
+ const id = match[1]!;
3591
+ if (ids.has(id) || items.length >= 32) return;
3592
+ ids.add(id); items.push({ id, kind: match[2]!, line });
3593
+ if (!generatedRecordNotes.get(id)) protectedIds.add(id);
3594
+ }
3595
+ const snapshot = readRecordSnapshot(undefined, peer);
3596
+ let projectedText = original;
3597
+ const projectionCurrent = () => current() && (snapshot?.current === undefined || snapshot.current(original) === true && snapshot.current(projectedText) === true);
3598
+ if (!snapshot || !projectionCurrent()) return;
3599
+ const staticBytes = Buffer.byteLength(original) - Buffer.byteLength(items.map(item => item.line).join("\n"));
3600
+ const preferred = preferRecordItems(items, snapshot, 32, protectedIds, Math.max(0, tokens * 3 - staticBytes));
3601
+ if (!projectionCurrent()) return;
3602
+ const output: string[] = []; let index = 0;
3603
+ for (const line of body) {
3604
+ const match = row.exec(line);
3605
+ if (!match) { output.push(line); continue; }
3606
+ if (preferred.items.some(item => item.id === match[1])) {
3607
+ while (index < preferred.items.length && !ids.has(preferred.items[index]!.id)) output.push(preferred.items[index++]!.line);
3608
+ if (preferred.items[index]?.id !== match[1]) return;
3609
+ output.push(line); index++;
3610
+ } else {
3611
+ while (index < preferred.items.length && !ids.has(preferred.items[index]!.id)) output.push(preferred.items[index++]!.line);
3612
+ }
3613
+ }
3614
+ while (index < preferred.items.length) { const item = preferred.items[index++]!; if (ids.has(item.id)) return; output.push(item.line); }
3615
+ const after = header + output.join("\n"); projectedText = after;
3616
+ if (!projectionCurrent() || Buffer.byteLength(after) > Math.max(Buffer.byteLength(original), tokens * 3)) return;
3617
+ return { before: original, after, records: preferred.records, current: projectionCurrent };
3618
+ }
3619
+ bus.onFinalAnswer = (peer, raw, input) => {
3620
+ const frame = recordFrames.get(peer);
3621
+ if (!frame || !recordOwnerEligible(frame.owner) || turns.get(peer) !== frame.turn || !recordInputAllowed(peer, input.out) || !recordInputAllowed(peer, input.originals)) return;
3622
+ frame.capture.finish(raw);
3623
+ };
3624
+ bus.onFinalAnswerBytes = (peer, counts) => { const owner = bus.peers.get(peer); if (owner && recordOwnerEligible(owner)) log(`records forwarded before=${counts.before} after=${counts.after}`); };
3625
+
3196
3626
  // Hoisted for the Tasks ports above; only the returned guard reads fully initialized daemon state.
3197
3627
  function controlWritePrivacyGuard(admittedAtReceive: boolean, inputPublicAtReceive: boolean, peer?: PeerId, taskId?: number) {
3198
3628
  return () => {
@@ -3400,28 +3830,32 @@ export async function startDaemon(opts: DaemonOptions) {
3400
3830
  notify: (line) => { notify(line); feedBudgetPauses(); },
3401
3831
  }, accountMembers, accountOf));
3402
3832
  budget.setRecoveryHold(recoveryActive());
3403
- // ponytail: a third full read of events.jsonl at startup (after nativeStopsSeen and claudeNativeUsageSeen). Measured at about 70 ms on the real
3404
- // 46 MB, 238k-line log, so it is not folded into one pass across startup. Ceiling: the log is never rotated, so the cost grows with it; when a
3405
- // read passes a few hundred ms, make one `readEvents` pass feed all three sets (or keep the resets in hub.db, the #683 U2 roll-up).
3406
- const startupEvents = readEvents(join(opts.stateDir, "events.jsonl"));
3833
+ // Share the single streaming startup pass; quota, Kimi and token-window replay keep their existing predicates.
3834
+ startupTimings.mark("budget");
3835
+ const startupEvents = startupSeeds.events;
3407
3836
  budget.seedResets(startupEvents.flatMap(e => e.type === "quota_reset" ? [{ peer: e.peer, window: e.window, ...(e.resetsAt !== undefined ? { resetsAt: e.resetsAt } : {}) }] : []));
3408
3837
  // #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.
3838
+ const kimiEvents = new KimiEventWriter({ append: event, read: () => readEvents(join(opts.stateDir, "events.jsonl")) }, startupEvents);
3409
3839
  const kimiUsage = new KimiUsage({
3410
3840
  home: opts.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), ".kimi-code"),
3411
3841
  now: () => Date.now(),
3412
3842
  ceiling: () => config.budget.kimi_tokens_5h,
3413
3843
  session: peer => contextSession(peer),
3414
- record: (peer, row, counted) => {
3415
- addTokens(peer, counted);
3416
- event({ type: "usage", peer, source: "kimi_wire", id: row.id, measuredAt: new Date(row.at).toISOString(), inputTokens: row.inputOther, outputTokens: row.output,
3417
- cacheReadTokens: row.inputCacheRead, cacheWriteTokens: row.inputCacheCreation, totalTokens: kimiRowTotal(row),
3418
- ...taskAttribution(peer), ...(row.model ? { servedModel: row.model } : {}) });
3844
+ schedule: opts.kimiUsageScheduler ?? ((delay, run) => {
3845
+ const timer = setTimeout(run, delay); timer.unref?.();
3846
+ return () => clearTimeout(timer);
3847
+ }),
3848
+ record: (peer, row, counted, attributed) => {
3849
+ kimiEvents.write(peer, row, counted, attributed);
3850
+ applyKimiTokens(peer, counted, attributed);
3419
3851
  },
3420
3852
  report: (peer, window) => budget.report(peer, [{ id: "tokens", kind: "count", used: window.used, resetsAt: window.resetsAt, source: `hub count, kimi wire log, of kimi_tokens_5h ${window.ceiling}` }]),
3421
3853
  forget: peer => budget.forget(peer, "tokens", "count"),
3422
3854
  notice: line => notify(line),
3423
3855
  });
3856
+ startupCleanup.push(() => kimiUsage.stop());
3424
3857
  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))));
3858
+ startupTimings.mark("usage_seed");
3425
3859
  /** 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. */
3426
3860
  const budgetPeerNotes = (): BudgetPeerNote[] => {
3427
3861
  const quota = budget.status();
@@ -3429,15 +3863,16 @@ export async function startDaemon(opts: DaemonOptions) {
3429
3863
  return budgetNotes({ peers, windows: peer => quota[accountOf(peer)]?.windows.length ?? 0, definition: peer => definitionOf(peer), softTokens: () => kimiUsage.status(),
3430
3864
  hubTokens5h: peer => hubTokenWindows.get(peer)?.sum(Date.now()) });
3431
3865
  };
3432
- /** A peer whose definition keeps host-owned soft token accounting (Kimi): its rows are read at a turn start (the floor), a turn end and a usage_update. */
3866
+ /** A peer whose definition keeps host-owned soft token accounting (Kimi): its rows are read at a turn start (the floor), a turn end, a usage_update and a bounded delayed drain. */
3433
3867
  const softTokenPeer = (peer: PeerId): boolean => !!definitionOf(peer)?.budget?.resetSoftTokensOnResume;
3434
- const collectKimiUsage = (peer: PeerId): void => { if (!softTokenPeer(peer)) return; try { kimiUsage.collect(peer); } catch (error) { log(`kimi usage: ${(error as Error).name}`); } };
3868
+ const collectKimiUsage = (peer: PeerId, terminal = false): void => { if (!softTokenPeer(peer)) return; try { kimiUsage.collect(peer, false, terminal); } catch (error) { log(`kimi usage: ${(error as Error).name}`); } };
3435
3869
  startupCleanup.push(() => budget.close());
3436
3870
  // #683 U2: events.jsonl folded into hub.db, a bounded pass at a time, so `usage` never rescans the log.
3437
3871
  const usageRollup = new UsageRollup(join(opts.stateDir, "hub.db"), join(opts.stateDir, "events.jsonl"));
3438
3872
  startupCleanup.push(() => usageRollup.close());
3439
3873
  const pollUsageRollup = () => { try { usageRollup.poll(); } catch (error) { log(`usage roll-up pass failed: ${(error as Error).message.slice(0, 120)}`); } };
3440
3874
  pollUsageRollup();
3875
+ startupTimings.mark("usage_rollup");
3441
3876
  // Turns and their tokens for telemetry (issue #40). Turn ids carry the hub run, so they stay unique across restarts.
3442
3877
  const runId = Date.now().toString(36);
3443
3878
  let turnSeq = 0;
@@ -3447,11 +3882,14 @@ export async function startDaemon(opts: DaemonOptions) {
3447
3882
  const task = result.task === undefined ? undefined : board.get(result.task);
3448
3883
  return { ...result, ...(task && tasks.isPii(task) ? { pii: true as const } : {}) };
3449
3884
  };
3450
- const supervisionTurns = new Map<PeerId, { id: string; at: number; tokens?: number; session?: string }>();
3885
+ const supervisionTurns = new Map<PeerId, { id: string; at: number; tokens?: number; session?: string; nativeTurn?: string }>();
3451
3886
  /** #1054: who started the turn a delivery begins. The person's message (console, `ahub say`, an acon send: from `user`, never the hub's own `answer` envelope) opens a run; ids only. */
3452
3887
  const pendingPersonDelivery = new Map<PeerId, { envelope: string; private: boolean }>();
3888
+ /** A native turn whose transcript, not its hook payload, proved a person origin. Native prompt text is never available here, so the result stays private. */
3889
+ const pendingNativePerson = new Set<PeerId>();
3453
3890
  bus.onDeliver = (peer, originals) => {
3454
3891
  if (peer.includes("@")) return;
3892
+ recordInputs.set(peer, { owner: bus.peers.get(peer), originals: [...originals] });
3455
3893
  resetReviewObserverSessionIfChanged(peer);
3456
3894
  if (!presenceOnlyDelivery(originals)) {
3457
3895
  const pendingBefore = pendingReviewObserverInputs.get(peer), previous = pendingBefore ?? currentReviewObserverInputs.get(peer), reviewInputScoped = reviewInputHeld(peer, originals), turnId = turns.get(peer)?.id;
@@ -3579,7 +4017,7 @@ export async function startDaemon(opts: DaemonOptions) {
3579
4017
  supervisionTurns.set(peer, { id: turn?.id ?? `supervision-${randomUUID()}`, at: turn?.start ?? Date.now(), ...(turn?.tokens ? { tokens: turn.tokens } : {}), ...(contextSession(peer) ? { session: contextSession(peer) } : {}) });
3580
4018
  };
3581
4019
  bus.onPulled = (peer, originals) => { notePulledReviewInput(peer, originals); };
3582
- bus.onSteering = (peer, originals) => { noteSteeredReviewInput(peer, originals); };
4020
+ bus.onSteering = (peer, originals) => { try { noteSteeredReviewInput(peer, originals); } finally { noteRecordSteered(peer, originals); } };
3583
4021
  bus.onDeliveryFailed = peer => {
3584
4022
  pendingDeliveryTask.delete(peer); pendingPersonDelivery.delete(peer); deliveredAwaitingTurn.delete(peer); supervisionTurns.delete(peer);
3585
4023
  const pending = pendingReviewObserverInputs.get(peer);
@@ -4014,9 +4452,20 @@ export async function startDaemon(opts: DaemonOptions) {
4014
4452
  const noQuotaPeer = (peer: PeerId): boolean => !!definitionOf(peer)?.budget?.noQuotaReason;
4015
4453
  const hubTokenWindow = (peer: PeerId): TokenWindow => hubTokenWindows.get(peer) ?? hubTokenWindows.set(peer, new TokenWindow(5 * 3_600_000)).get(peer)!;
4016
4454
  // Replayed through `seed`, which skips rows older than 5 h before inserting any: a long-lived project's whole log costs one pass, not one search per row.
4455
+ startupTimings.mark("token_runtime");
4017
4456
  const seedNow = Date.now(), seedRows = new Map<PeerId, { at: number; n: number }[]>();
4018
4457
  for (const e of startupEvents) if (e.type === "tokens" && noQuotaPeer(e.peer)) (seedRows.get(e.peer) ?? seedRows.set(e.peer, []).get(e.peer)!).push({ at: Date.parse(e.at), n: e.n });
4019
4458
  for (const [peer, rows] of seedRows) hubTokenWindow(peer).seed(rows, seedNow);
4459
+ const applyKimiTokens = (peer: PeerId, n: number, attributed: KimiRowAttribution): void => {
4460
+ if (n > 0 && noQuotaPeer(peer)) hubTokenWindow(peer).add(Date.now(), Math.round(n));
4461
+ const supervisionTurn = supervisionTurns.get(peer);
4462
+ if (supervisionTurn && Number.isFinite(n) && n >= 0 && (supervisionTurn.nativeTurn ?? supervisionTurn.id) === attributed.turn) supervisionTurn.tokens = (supervisionTurn.tokens ?? 0) + n;
4463
+ if (n > 0) {
4464
+ const turn = turns.get(peer);
4465
+ if (turn && turn.id === attributed.turn) turn.tokens += n;
4466
+ }
4467
+ };
4468
+ startupTimings.mark("token_seed");
4020
4469
  const addTokens = (peer: PeerId, n: number, task?: number): number => {
4021
4470
  if (n > 0 && noQuotaPeer(peer)) hubTokenWindow(peer).add(Date.now(), Math.round(n));
4022
4471
  const supervisionTurn = supervisionTurns.get(peer);
@@ -4035,11 +4484,21 @@ export async function startDaemon(opts: DaemonOptions) {
4035
4484
  const claudeContextSeen = new Map<string, string>();
4036
4485
  const contextTailSeen = new Map<PeerId, string>();
4037
4486
  const retainedCliAudits = new Set<string>();
4487
+ /**
4488
+ * The period of the sweep that drains the CLI audit outbox (the interval below runs `drainCliAuditsNow` on it). A row is attributed to the peer's task only when it is at most this many
4489
+ * periods old at the drain: an ordinary row is drained within one period, so fifteen leaves room for a slow sweep, while a row left by a stalled hub or an unreadable outbox is not matched to
4490
+ * whatever task is open when it is finally read. The bound is derived from the period, so the two cannot drift apart.
4491
+ */
4492
+ const CLI_AUDIT_SWEEP_MS = 1000;
4493
+ const CLI_AUDIT_FRESH_MS = 15 * CLI_AUDIT_SWEEP_MS;
4038
4494
  function drainCliAuditsNow(): void {
4039
4495
  for (const audit of drainCliAudits(opts.stateDir)) {
4040
4496
  const delegated = audit.outcome === "delegated";
4041
4497
  const refused = audit.outcome !== "run" && !delegated;
4042
- if (!event({ type: "agent_cli", peer: audit.peer, command: audit.command, refused, ...(delegated ? { delegated: true } : {}) })) {
4498
+ // #1278: the audit row is written when the command runs and read here on a later sweep, so the peer's open tasks now may not be the ones then. A row older than the drain's own
4499
+ // freshness bound is `unattributed` (what is known), never matched to whatever is open at drain time; a fresh one uses the rule `turn_end` uses.
4500
+ const fresh = Date.now() - audit.at <= CLI_AUDIT_FRESH_MS && Date.now() >= audit.at;
4501
+ if (!event({ type: "agent_cli", peer: audit.peer, command: audit.command, refused, ...(delegated ? { delegated: true } : {}), ...(fresh ? taskAttribution(audit.peer) : { attribution: "unattributed" as const }) })) {
4043
4502
  throw new Error("CLI audit event was not retained");
4044
4503
  }
4045
4504
  retainedCliAudits.add(audit.id); // Only after the event append succeeded.
@@ -4135,7 +4594,7 @@ export async function startDaemon(opts: DaemonOptions) {
4135
4594
  const reading = bound ? readNativeContext(definitionOf(claudePeer), c.context, bound, c.at) : undefined;
4136
4595
  if (reading) contexts.report(claudePeer, reading, bound);
4137
4596
  } catch { /* absent or unreadable native telemetry is unknown */ }
4138
- }, 1000),
4597
+ }, CLI_AUDIT_SWEEP_MS),
4139
4598
  setInterval(() => budget.tick(), 30_000),
4140
4599
  setInterval(pollUsageRollup, 10_000),
4141
4600
  // #481 S7: band tiers are evaluated every five minutes, and only when the board changed since the last evaluation (the status
@@ -4159,6 +4618,10 @@ export async function startDaemon(opts: DaemonOptions) {
4159
4618
  void tasks.runSecurityScan().catch(error => log(`sdlc security scan failed: ${sanitize((error as Error).message).slice(0, 160)}`));
4160
4619
  }, opts.securityScanEveryMs ?? 3_600_000),
4161
4620
  setInterval(() => {
4621
+ if (!stopping && !recoveryActive() && !bus.isRecoveryHeld) {
4622
+ try { visuals.prune(config.visuals.retention_days, Date.now(), task => !!board.get(task)); }
4623
+ catch { /* retention retries on the existing maintenance tick */ }
4624
+ }
4162
4625
  if (!ready || !memoryBinding) return;
4163
4626
  const before = memoryProblem;
4164
4627
  memoryBinding.status(memoryStore);
@@ -4546,7 +5009,7 @@ export async function startDaemon(opts: DaemonOptions) {
4546
5009
  const conductedMutations = new Set(["hub_task_propose", "hub_task_accept", "hub_task_decline", "hub_task_done", "hub_review", "hub_checkpoint", "hub_remember"]);
4547
5010
  const taskOp = async (...args: Parameters<typeof taskOpBody>): Promise<string> => {
4548
5011
  const [by, op, input] = args;
4549
- if (readOnlyPeer(by) && !READ_ONLY_HUB_TOOLS.has(op)) throw new PreEffectToolRefusal("read-only instance cannot mutate hub state");
5012
+ if (readOnlyPeer(by) && !READ_ONLY_HUB_TOOLS.has(op)) throw op === "hub_visual" ? visualOperational("role") : new PreEffectToolRefusal("read-only instance cannot mutate hub state");
4550
5013
  const sourceCurrent = op === "hub_source_read" ? sourceReadCurrent(by, args[3] ?? false, args[4] ?? false) : undefined;
4551
5014
  const nativeTurn = turns.get(by);
4552
5015
  const effectful = ownerToolEffect(op, input);
@@ -4569,13 +5032,13 @@ export async function startDaemon(opts: DaemonOptions) {
4569
5032
  const id = Number.isSafeInteger(proposed) && proposed! > 0 ? proposed : admittedId;
4570
5033
  auditConduct({ kind: "conduct", actor: by, action: op.slice(4), ...(id === undefined ? {} : { task: id }) });
4571
5034
  }
4572
- const hint = args[3] && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" ? ownHeldHint(by) : "";
5035
+ 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) : "";
4573
5036
  return hint ? `${text}\n\n${hint}` : text;
4574
5037
  } catch (error) {
4575
5038
  if (reviewTool && traceId !== undefined) reviewerToolObservers.get(by)?.(traceId, reviewTool, error instanceof Error ? error.message : "review tool refused");
4576
5039
  if (nativeTurn && effectful && !(error instanceof PreEffectToolRefusal) && turns.get(by) === nativeTurn) nativeTurn.taskEffect = true;
4577
5040
  // Keep proven pre-effect refusal identity/code for native receipts; only add body-free metadata.
4578
- const hint = args[3] && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" ? ownHeldHint(by) : "";
5041
+ 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) : "";
4579
5042
  if (hint && error instanceof Error) error.message += `\n\n${hint}`;
4580
5043
  throw error;
4581
5044
  } finally {
@@ -4741,9 +5204,227 @@ export async function startDaemon(opts: DaemonOptions) {
4741
5204
  catch (error) { finishInvocation(row, "refused", { reason: "the hub could not queue the request; nothing ran" }); throw new PreEffectToolRefusal(error instanceof Error ? error.message : "the request could not be queued"); }
4742
5205
  return JSON.stringify({ invocation: row.id, state: "queued", note: "the result arrives later as one message from the hub, addressed to you only; do not wait for it in this turn" });
4743
5206
  }
5207
+ const visualUnavailable = () => new PreEffectToolRefusal("visual unavailable under the current privacy or project policy; use a public visual in an ordinary context and retry");
5208
+ const visualOperational = (cause: "stopping" | "recovery" | "authority" | "role" | "membership" | "observer" | "storage" | "concurrency" | "screen" | "policy") => new PreEffectToolRefusal({
5209
+ stopping: "visual unavailable: hub is stopping; wait for the hub to restart and retry",
5210
+ recovery: "visual operation is held by controlled recovery; check ahub status, wait for recovery release and retry",
5211
+ authority: "visual request authority changed; reconnect your current peer session and retry",
5212
+ role: "visual publication requires remember capability and a writable peer role; ask the person to update the peer role or capability and retry",
5213
+ membership: "visual peer is off roster; ask the person to enable it and retry",
5214
+ observer: "visual publication is held by an open review observer scope; finish or settle the review and start an ordinary turn",
5215
+ storage: "visual delivery storage is unavailable; inspect ahub status and retry after storage recovers",
5216
+ concurrency: "visual generation, task or policy changed while checking; inspect current task/session and retry",
5217
+ screen: "visual privacy screen is unavailable or returned no clear verdict; shorten the visual if it exceeds the screen limit, or restore the configured screen, check ahub status and retry",
5218
+ policy: "visual file policy is unavailable; repair the project configuration and retry",
5219
+ }[cause]);
5220
+ type VisualFilePolicy = { pii: string[]; deny: string[] };
5221
+ let visualPolicyCache: { key: string; value: VisualFilePolicy } | undefined;
5222
+ // These two non-machine-local path policies use ordinary per-key local-over-shared precedence.
5223
+ // Reading a candidate cannot relax accepted runtime restrictions until they are actually adopted.
5224
+ const visualFilePolicy = (): VisualFilePolicy => {
5225
+ try {
5226
+ const texts = configSourceTexts(opts.cwd);
5227
+ const key = JSON.stringify([texts["config.json"], texts["config.local.json"], config.pii?.paths ?? [], config.local.deny]);
5228
+ if (visualPolicyCache?.key === key) return visualPolicyCache.value;
5229
+ let pii: string[] = [], deny: string[] = [];
5230
+ for (const name of CONFIG_FILES) {
5231
+ if (texts[name] === null) continue;
5232
+ const raw: unknown = JSON.parse(texts[name]!);
5233
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw visualOperational("policy");
5234
+ const input = raw as Record<string, unknown>;
5235
+ if (input.pii !== undefined) {
5236
+ const policies: Record<string, unknown> = { pii: input.pii };
5237
+ validateRawConfig(policies, declarations, adapterCatalog);
5238
+ const value = input.pii as Record<string, unknown>;
5239
+ if (Object.hasOwn(value, "paths")) pii = policyPaths(value.paths, "pii.paths");
5240
+ }
5241
+ if (input.local !== undefined) {
5242
+ if (!input.local || typeof input.local !== "object" || Array.isArray(input.local)) throw visualOperational("policy");
5243
+ const value = input.local as Record<string, unknown>;
5244
+ if (Object.hasOwn(value, "deny")) {
5245
+ const localPolicy: Record<string, unknown> = { deny: value.deny }, policies: Record<string, unknown> = {};
5246
+ policies.local = localPolicy;
5247
+ validateRawConfig(policies, declarations, adapterCatalog);
5248
+ deny = value.deny as string[];
5249
+ }
5250
+ }
5251
+ }
5252
+ const value = { pii: [...new Set([...(config.pii?.paths ?? []), ...pii])], deny: [...new Set([...config.local.deny, ...deny])] };
5253
+ visualPolicyCache = { key, value }; return value;
5254
+ } catch { throw visualOperational("policy"); }
5255
+ };
5256
+ const visualSafeText = (text: string, policy: VisualFilePolicy): boolean => boundedSafe(text) && tasks.publicMetadataText(text)
5257
+ && !mentionsPrivatePath(text, [], [...policy.pii, ...policy.deny], opts.cwd);
5258
+ const visualPathPublic = (path: string, policy: VisualFilePolicy): boolean => {
5259
+ try {
5260
+ const root = realPath(opts.cwd), typed = resolve(root, path);
5261
+ const publicName = (value: string) => {
5262
+ const name = relative(root, value);
5263
+ return insideRoot(name) && !isHubWritePath(name) && !isDenied(name, policy.deny) && !isDenied(value, policy.deny)
5264
+ && !matchesPolicy(root, name, policy.pii, true) && visualSafeText(name, policy);
5265
+ };
5266
+ return publicName(typed) && publicName(policyRealPath(typed));
5267
+ } catch { return false; }
5268
+ };
5269
+ const visualTaskPublic = (task?: number, captured?: VisualFilePolicy): boolean => {
5270
+ try {
5271
+ const policy = captured ?? visualFilePolicy();
5272
+ if (task === undefined) return true;
5273
+ const current = board.get(task);
5274
+ return !!current && !tasks.isPii(current) && [...(current.refs.paths ?? []), ...(current.plan?.paths ?? [])].every(path =>
5275
+ visualPathPublic(path, policy));
5276
+ } catch { return false; }
5277
+ };
5278
+ const visualPorts = (policy = visualFilePolicy()): DeliverablePorts => ({ cwd: opts.cwd, deny: policy.deny, private: path =>
5279
+ !visualPathPublic(path, policy) });
5280
+ const visualPublic = (record: VisualRecord | VisualSummary, policy?: VisualFilePolicy): boolean => {
5281
+ try {
5282
+ return !stopping && (record.task !== undefined || record.created >= Date.now() - config.visuals.retention_days * 86_400_000) && !turns.get(record.from)?.private && !contextPii(record.from) && visualTaskPublic(record.task, policy)
5283
+ && visualSafeText(record.title, policy ?? visualFilePolicy()) && visualSafeText(record.from, policy ?? visualFilePolicy());
5284
+ } catch { return false; }
5285
+ };
5286
+ const visualRecord = (id: unknown, captured?: VisualFilePolicy): VisualRecord | undefined => {
5287
+ if (typeof id !== "string" || !new RegExp(VISUAL_ID_PATTERN).test(id)) return undefined;
5288
+ try {
5289
+ const policy = captured ?? visualFilePolicy(), record = visuals.get(id);
5290
+ if (!record || !visualPublic(record, policy)) return undefined;
5291
+ validateVisualPayload(record.payload, text => visualSafeText(text, policy));
5292
+ const ports = visualPorts(policy);
5293
+ for (const file of record.files) {
5294
+ if (ports.private(file.path)) return undefined;
5295
+ }
5296
+ return record;
5297
+ } catch { return undefined; }
5298
+ };
5299
+ const visualView = (record: VisualRecord) => ({ id: record.id, ...(record.task === undefined ? {} : { task: record.task }), from: record.from,
5300
+ kind: record.kind, title: record.title, payload: record.payload, created: record.created });
5301
+ const visualList = (task?: number): VisualSummary[] => {
5302
+ try { const policy = visualFilePolicy(); return visuals.list({ ...(task === undefined ? {} : { task }), limit: 20 },
5303
+ (record, paths) => visualPublic(record, policy) && paths.every(path => visualPathPublic(path, policy))); }
5304
+ catch { return []; }
5305
+ };
5306
+ async function visualTool(by: PeerId, op: string, a: Record<string, unknown>, piiTurn: boolean): Promise<string> {
5307
+ if (!a || typeof a !== "object" || Array.isArray(a)) throw new PreEffectToolRefusal("visual arguments must be an object; retry with the documented fields");
5308
+ const authority = childToolAuthority.getStore();
5309
+ const actor = (publishing: boolean) => {
5310
+ if (stopping) throw visualOperational("stopping");
5311
+ let current = false;
5312
+ try { current = !authority || authority.by === by && authority.current(); } catch { /* stale authority */ }
5313
+ if (!current) throw visualOperational("authority");
5314
+ if (piiTurn || turns.get(by)?.private || contextPii(by)) throw visualUnavailable();
5315
+ if (!membershipAllowed(by)) throw visualOperational("membership");
5316
+ if (!publishing) return;
5317
+ if (recoveryActive() || bus.isRecoveryHeld) throw visualOperational("recovery");
5318
+ if (readOnlyPeer(by) || !may(by, "remember")) throw visualOperational("role");
5319
+ if (reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded)) throw visualOperational("observer");
5320
+ if (!bus.deliveryJournalAvailable()) throw visualOperational("storage");
5321
+ };
5322
+ actor(op !== "hub_visual_show");
5323
+ if (op === "hub_visual_show") {
5324
+ if (Object.keys(a).some(key => key !== "id")) throw new PreEffectToolRefusal("visual show takes only id; retry with a visual id");
5325
+ const record = visualRecord(a.id, visualFilePolicy());
5326
+ if (!record) throw visualUnavailable();
5327
+ return JSON.stringify(visualView(record));
5328
+ }
5329
+ if (Object.keys(a).some(key => !["payload", "task", "to"].includes(key))) throw new PreEffectToolRefusal("visual has an unsupported field; use payload, task and to only");
5330
+ if (a.task !== undefined && (!Number.isSafeInteger(a.task) || Number(a.task) < 1)) throw new PreEffectToolRefusal("visual task must be a positive integer; retry with a task id");
5331
+ const task = a.task as number | undefined, before = task === undefined ? undefined : board.get(task);
5332
+ if (task !== undefined && !before) throw new PreEffectToolRefusal("visual task is unavailable; choose an existing public task and retry");
5333
+ const generation = connectionGeneration(by), turn = turns.get(by);
5334
+ const policyVersion = (filePolicy: VisualFilePolicy) => JSON.stringify({ revision: configRevision, filePolicy, pii: config.pii, deny: config.local.deny, signals: activeRouting().signals, constraints: activeRouting().constraints, mlx: config.mlx, model: activeRouting().local.fixed_model });
5335
+ const initialPolicy = visualFilePolicy(), policy = policyVersion(initialPolicy);
5336
+ const current = (): VisualFilePolicy => {
5337
+ actor(true);
5338
+ const filePolicy = visualFilePolicy();
5339
+ if (policyVersion(filePolicy) !== policy || connectionGeneration(by) !== generation || turns.get(by) !== turn)
5340
+ throw visualOperational("concurrency");
5341
+ if (task !== undefined) {
5342
+ const now = board.get(task);
5343
+ if (!before || !now || now.created !== before.created || now.updated !== before.updated || now.history.length !== before.history.length)
5344
+ throw visualOperational("concurrency");
5345
+ }
5346
+ if (!visualTaskPublic(task, filePolicy)) throw visualUnavailable();
5347
+ return filePolicy;
5348
+ };
5349
+ current();
5350
+ const recipients = typeof a.to === "string" && a.to.length ? [a.to] : a.to;
5351
+ if (a.to !== undefined && (!Array.isArray(recipients) || recipients.some(id => typeof id !== "string" || !id.length)))
5352
+ throw new PreEffectToolRefusal("visual to must be a peer id or array of peer ids; retry with local recipients");
5353
+ const to = a.to === undefined ? [USER] : Array.isArray(recipients) && recipients.length ? [...new Set(recipients as string[])] : bus.knownPeers().filter(id => !parseRemotePeerId(id));
5354
+ if (to.some(id => id !== USER && (!bus.knownPeers().includes(id) || parseRemotePeerId(id)))) throw new PreEffectToolRefusal("visual recipient unavailable; choose a known local peer or user and retry");
5355
+ const id = randomUUID(), priority = a.to === undefined ? "fyi" : "status";
5356
+ const early = newEnvelope(by, `[visual ${id}]`, { priority, to, refs: { visual: id, ...(task === undefined ? {} : { task: String(task) }) } });
5357
+ const preflight = (stub: Envelope, dry: boolean) => {
5358
+ try { bus.checkRemotePublication(stub); } catch { throw new PreEffectToolRefusal("visual delivery unavailable; choose local recipients and retry"); }
5359
+ const offRoster = bus.offRosterRecipients(stub).filter(peer => peer !== USER);
5360
+ const audience = new Set(stub.to?.filter(peer => peer !== by && peer !== USER));
5361
+ if (offRoster.length && offRoster.length === audience.size) throw new PreEffectToolRefusal("visual recipients are off roster; choose an available local peer and retry");
5362
+ const hushed = bus.hushed(stub);
5363
+ if (hushed.length && hushed.length === bus.audience(stub).length) throw new PreEffectToolRefusal("visual delivery is held by the current silence policy; wait for the hold to clear");
5364
+ const effective = offRoster.length ? { ...stub, to: stub.to!.filter(peer => !offRoster.includes(peer)) } : stub;
5365
+ const refused = dry
5366
+ ? (by === USER || by === HUB || by === DIGEST || stub.priority === "fyi" ? undefined : limiter.peek(by, effective.to, effective.priority, effective.body))
5367
+ : admit(effective);
5368
+ if (refused) throw new PreEffectToolRefusal("visual delivery is rate limited; wait before retrying");
5369
+ };
5370
+ // No screen, image read, or consuming admission has occurred at this point.
5371
+ preflight(early, true);
5372
+ const input = validateVisualInput(a.payload, text => visualSafeText(text, initialPolicy));
5373
+ if (tasks.screenOn()) {
5374
+ const screen = opts.piiScreen ?? ((value: string) => screenPii(value, { ...(config.mlx.enabled === false ? {} : { device: () => ensureMlx(config.mlx) }), onCampus, omni, fixedModel: () => activeRouting().local.fixed_model }));
5375
+ const verdict = await screen(JSON.stringify(input)).catch(() => undefined);
5376
+ current();
5377
+ if (verdict?.label === "pii") throw visualUnavailable();
5378
+ if (verdict?.label !== "clear") throw visualOperational("screen");
5379
+ }
5380
+ const beforeRead = current(), resolved = await resolveVisualAssets(input, id, visualPorts(beforeRead));
5381
+ const finalPolicy = current();
5382
+ const payload = validateVisualPayload(resolved.payload, text => visualSafeText(text, finalPolicy));
5383
+ const title = "title" in payload ? payload.title ?? "" : "caption" in payload ? payload.caption ?? "" : "";
5384
+ const record: VisualRecord = { id, ...(task === undefined ? {} : { task }), from: by, kind: payload.kind, title, payload, files: resolved.files, created: Date.now() };
5385
+ if (!visualPublic(record, finalPolicy) || resolved.files.some(file => !visualPathPublic(file.path, finalPolicy))) throw visualUnavailable();
5386
+ const stub = newEnvelope(by, `[visual ${id}] ${payload.kind}: ${sanitize(title)}`, { priority, to, refs: { visual: id, ...(task === undefined ? {} : { task: String(task) }) } });
5387
+ preflight(stub, false); // Recheck after every await; consume shared admission exactly once.
5388
+ if (!recoveryActive() && !bus.isRecoveryHeld) visuals.prune(config.visuals.retention_days, Date.now(), task => !!board.get(task));
5389
+ visuals.insert(record);
5390
+ try {
5391
+ event({ type: "visual", id, kind: payload.kind, bytes: Buffer.byteLength(JSON.stringify(payload)), files: resolved.files.length, ...(task === undefined ? {} : { task }) });
5392
+ bus.publish(stub);
5393
+ } catch { throw new Error(`visual ${id} was stored but its stub delivery failed; inspect the visual before posting again`); }
5394
+ return `visual ${id}`;
5395
+ }
5396
+ function executionLineageRead(by: PeerId, input: unknown, piiTurn = false): Record<string, unknown> {
5397
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewObserverHeld(by) || reviewObserverInput(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5398
+ return { ok: true, lineage: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" } : tasks.executionLineage(by, input) };
5399
+ }
5400
+ function guidanceRead(by: PeerId, op: "list" | "show", input: unknown, piiTurn = false): Record<string, unknown> {
5401
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewObserverHeld(by) || reviewObserverInput(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5402
+ return { ok: true, guidance: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" }
5403
+ : op === "list" ? tasks.guidanceVariantList(by, input) : tasks.guidanceVariantDiff(by, input) };
5404
+ }
4744
5405
  async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
5406
+ if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
4745
5407
  const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
4746
5408
  if (reviewTurn || op === "hub_review" && reviewCaptureExcluded(op, JSON.stringify(a))) progress.clearPeer(by);
5409
+ if (GUIDANCE_TOOL_NAMES.has(op)) {
5410
+ if (op === "hub_guidance_list" || op === "hub_guidance_show") return JSON.stringify(guidanceRead(by, op === "hub_guidance_list" ? "list" : "show", a, piiTurn));
5411
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
5412
+ if (excluded) throw new PreEffectToolRefusal("guidance writes are unavailable in private or review input; retry in a public current-owner context");
5413
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance writes; wait for release and inspect the task before retrying");
5414
+ if (op === "hub_guidance_create") {
5415
+ let variant; try { variant = parseGuidanceCreateInput(a); } catch { throw new PreEffectToolRefusal("guidance create accepts only a complete bounded V1 variant; remove unknown wrapper fields before retrying"); }
5416
+ return JSON.stringify({ ok: true, receipt: await tasks.guidanceVariantCreate(by, variant) });
5417
+ }
5418
+ let selector; try { selector = parseGuidanceIdQuery(a, true); } catch { throw new PreEffectToolRefusal("guidance withdrawal needs task epoch, current flow and variant id only; refresh the selected task before retrying"); }
5419
+ return JSON.stringify({ ok: true, receipt: await tasks.guidanceVariantWithdraw(by, selector) });
5420
+ }
5421
+ if (LINEAGE_TOOL_NAMES.has(op)) {
5422
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
5423
+ if (op === "hub_lineage_show") return JSON.stringify(executionLineageRead(by, a, piiTurn));
5424
+ if (excluded) throw new PreEffectToolRefusal("execution reference linking is unavailable in a private or review-observer context; retry only in a public task context");
5425
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding execution reference links; wait for release and retry");
5426
+ return JSON.stringify({ ok: true, link: await tasks.linkExecutionReference(by, a) });
5427
+ }
4747
5428
  if (op === "hub_ask") {
4748
5429
  // #1053: a structured question for the person. Refused before any row for a read-only instance, a PII turn's own words are marked private by the desk's `isPrivate`.
4749
5430
  if (by === USER) throw new PreEffectToolRefusal("hub_ask is for the agents of this project; the person answers with the console (ahub status shows open questions)");
@@ -4756,6 +5437,24 @@ export async function startDaemon(opts: DaemonOptions) {
4756
5437
  if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "title")) return JSON.stringify({ ok: false, reason: "invalid", error: "hub_set_title accepts only title; provide a public name of 1-80 normalized characters" });
4757
5438
  return JSON.stringify(await setSessionTitle(by, a.title, true, piiTurn));
4758
5439
  }
5440
+ if (op === "hub_supervision_list" || op === "hub_supervision_accept" || op === "hub_supervision_dismiss") {
5441
+ // #1221 T2: the queue carries public board facts only, so a private turn neither reads nor decides one.
5442
+ if (piiTurn || turns.get(by)?.private || contextPii(by)) throw new PreEffectToolRefusal("supervision proposals are unavailable during a private or PII turn");
5443
+ if (op === "hub_supervision_list") {
5444
+ if (a && (typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "task") || a.task !== undefined && (!Number.isSafeInteger(a.task) || a.task < 1)))
5445
+ throw new PreEffectToolRefusal("hub_supervision_list takes only an optional task id");
5446
+ const rows = await supervisionProposals.read(by, a?.task);
5447
+ // `refused` is the queue's own count of readings a bound refused instead of storing: a full queue is visible here.
5448
+ return JSON.stringify({ mode: supervisionMode(), proposals: rows.map(proposalView), refused: supervisionProposals.refusedReadings(),
5449
+ ...(rows.length ? {} : { note: supervisionMode() === "off" ? "supervision is off; a person turns it on with `ahub settings set supervision.mode advisory`" : "no supervision proposal is pending on your tasks" }) });
5450
+ }
5451
+ if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "id") || typeof a.id !== "string")
5452
+ throw new PreEffectToolRefusal(`${op} takes only a proposal id`);
5453
+ if (stopping || recoveryActive()) throw new PreEffectToolRefusal("recovery or shutdown is holding supervision decisions");
5454
+ const decision = await supervisionProposals.decide(by, a.id, op === "hub_supervision_accept" ? "accept" : "dismiss");
5455
+ if (!decision.ok) throw new PreEffectToolRefusal(decision.error);
5456
+ return JSON.stringify({ ok: true, proposal: proposalView(decision.proposal), ...(decision.receipt ? { receipt: decision.receipt } : {}) });
5457
+ }
4759
5458
  if (inProcess && (op === "hub_task_propose" || op === "hub_review") && a && typeof a === "object" && Object.hasOwn(a, "request_id")) throw new PreEffectToolRefusal("request_id replay keys require the control-protocol task transport");
4760
5459
  if (BOUNDED_TASK_TOOLS.has(op)) {
4761
5460
  const keys = op === "hub_task_spec" ? ["id"] : op === "hub_check_start" ? ["id", "check", "files"] : ["run"];
@@ -5085,6 +5784,9 @@ export async function startDaemon(opts: DaemonOptions) {
5085
5784
  const completion = t.history.findLast(h => h.by === by && (h.event === "done" || h.event === "done (checking)"));
5086
5785
  if (!piiTurn && !reviewTurn && !tasks.isPii(t) && completion && !completion.withheld && typeof a.summary === "string" && completion.note?.startsWith(a.summary)) {
5087
5786
  citeMemory(by, a.summary, `summary:${t.id}:${t.history.indexOf(completion)}`, [newEnvelope(by, "", { refs: { task: String(t.id) } })]);
5787
+ // #1279: the reasons of a spec acknowledgement are hub-screened text too, and one key per task keeps a repeat idempotent.
5788
+ const reasons = Array.isArray(a.spec_ack) ? a.spec_ack.flatMap((row: unknown) => typeof (row as { reason?: unknown })?.reason === "string" ? [(row as { reason: string }).reason] : []).join("\n") : "";
5789
+ if (reasons) citeMemory(by, reasons, `spec_ack:${t.id}:${t.history.indexOf(completion)}`, [newEnvelope(by, "", { refs: { task: String(t.id) } })]);
5088
5790
  }
5089
5791
  // A silent cohort (issue #107): the member that integrates is asked to check its work first; no done yet.
5090
5792
  const last = t.history.at(-1);
@@ -5096,12 +5798,26 @@ export async function startDaemon(opts: DaemonOptions) {
5096
5798
  return [result, specReport, extra].filter(Boolean).join("\n");
5097
5799
  }
5098
5800
  case "hub_sdlc_record":
5099
- await tasks.specStageGate(by, a.id, a.receipt); // #481 S1: a live spec edit-time check before a build stage
5100
5801
  return line(await tasks.recordSdlc(by, a.id, a.receipt));
5101
- case "hub_review":
5102
- return line(await tasks.review(by, a.id, a.verdict, a.note, a.unmet, a.head, a.coverage, a.findings));
5103
- case "hub_remember":
5104
- return tasks.remember(by, a);
5802
+ case "hub_review": {
5803
+ const reviewed = await tasks.review(by, a.id, a.verdict, a.note, a.unmet, a.head, a.coverage, a.findings);
5804
+ // #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.
5805
+ const verdict = reviewed.history.findLast(h => h.by === by && (h.event === "approved" || h.event === "changes_requested"));
5806
+ if (!piiTurn && !reviewTurn && !tasks.isPii(reviewed) && verdict && !verdict.withheld && typeof a.note === "string" && a.note && verdict.note?.startsWith(a.note)) {
5807
+ citeMemory(by, a.note, `review:${reviewed.id}:${reviewed.history.indexOf(verdict)}`, [newEnvelope(by, "", { refs: { task: String(reviewed.id) } })]);
5808
+ }
5809
+ return line(reviewed);
5810
+ }
5811
+ case "hub_remember": {
5812
+ const { message: saved, outcome } = await tasks.rememberOutcome(by, a);
5813
+ // #1279: a saved note that names another entry cites it. `tasks.remember` already refused a PII task, a private path and a secret, so only a note it saved gets here.
5814
+ // #802: the structured outcome decides, never the reply wording. Only `not_saved` skips the citation: a candidate note held for a person's review was cited under the old wording test too, and stays so.
5815
+ if (!piiTurn && !reviewTurn && typeof a.text === "string" && a.text && outcome !== "not_saved") {
5816
+ const task = a.task !== undefined && Number.isSafeInteger(Number(a.task)) ? Number(a.task) : undefined;
5817
+ citeMemory(by, a.text, `remember:${task ?? "none"}:${createHash("sha256").update(a.text).digest("hex").slice(0, 16)}`, task !== undefined ? [newEnvelope(by, "", { refs: { task: String(task) } })] : []);
5818
+ }
5819
+ return saved;
5820
+ }
5105
5821
  case "hub_checkpoint": {
5106
5822
  const summary = String(a.summary ?? "").trim();
5107
5823
  if (!summary) throw new Error("summary is required");
@@ -5509,6 +6225,24 @@ export async function startDaemon(opts: DaemonOptions) {
5509
6225
  // Question text lives in hub.db and the envelope to the asking peer only: never a log line, an event, a notice or memory capture.
5510
6226
  const questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
5511
6227
  startupCleanup.push(() => questionStore.close());
6228
+ const questionAttributions = new Map<string, TaskAttribution>();
6229
+ /**
6230
+ * The attribution of a question event. It is resolved ONLY when the question opens (`asked`, or `unavailable`, which has no set), by the rule `turn_end` uses, and cached by set. Every later event
6231
+ * of a set repeats the cached answer. A set with no cached answer (the hub restarted while the question was open, which `QuestionDesk.repair` leaves answerable, or the bounded map evicted it)
6232
+ * is `unattributed`: re-resolving it would put the person's answer, with its full latency, on whatever task the peer works on NOW, which is the read-time attribution this exists to prevent.
6233
+ */
6234
+ const withQuestionAttribution = (e: Extract<HubEvent, { type: "question" }>): HubEvent => {
6235
+ let attribution = questionAttributions.get(e.set);
6236
+ if (!attribution) {
6237
+ if (e.event === "asked" || e.event === "unavailable") {
6238
+ attribution = taskAttribution(e.peer);
6239
+ if (e.set !== "-") { questionAttributions.set(e.set, attribution); if (questionAttributions.size > 512) questionAttributions.delete(questionAttributions.keys().next().value!); }
6240
+ } else attribution = { attribution: "unattributed" };
6241
+ }
6242
+ // A closed question's entry is released; a pending one keeps it for its answer.
6243
+ if (e.event === "answered" || e.event === "superseded" || e.event === "cancelled" || e.event === "expired") questionAttributions.delete(e.set);
6244
+ return { ...e, ...attribution };
6245
+ };
5512
6246
  const questionDesk = new QuestionDesk({
5513
6247
  store: questionStore, now: () => Date.now(),
5514
6248
  waitMs: peer => config.questions.wait_ms[definitionOf(peer)?.kind ?? peer] ?? definitionOf(peer)?.questionWaitMs ?? 45_000,
@@ -5519,7 +6253,10 @@ export async function startDaemon(opts: DaemonOptions) {
5519
6253
  isPrivate: (peer, task, piiTurn) => piiTurn === true || contextPii(peer) || (task !== undefined && (() => { const row = board.get(task); return !row || tasks.isPii(row); })()),
5520
6254
  held: () => stopping || recoveryActive() || bus.isRecoveryHeld,
5521
6255
  publish: env => { bus.publish(env); },
5522
- event: e => { event(e); if (e.type === "question" && e.event !== "asked" && e.event !== "pending" && e.event !== "unavailable") queueMicrotask(() => settleCheck(e.peer)); }, // #1054: a closed question may be the last thing a run waited on
6256
+ // #1278: a question is attributed once, when it is asked, by the rule `turn_end` uses (the task of the delivery the peer is working on, else its single open task, else unattributed), and
6257
+ // every later event of the same set carries that same answer: the person answers minutes later, when the peer's open tasks may have changed. The task a question names for itself is the
6258
+ // peer's claim and is not used. An `unavailable` question has no set and is attributed on the spot.
6259
+ event: e => { event(e.type === "question" ? withQuestionAttribution(e) : e); if (e.type === "question" && e.event !== "asked" && e.event !== "pending" && e.event !== "unavailable") queueMicrotask(() => settleCheck(e.peer)); }, // #1054: a closed question may be the last thing a run waited on
5523
6260
  peerKnown: peer => bus.peers.has(peer) || (bus.knownPeers().includes(peer) && membershipAllowed(peer)),
5524
6261
  });
5525
6262
  // #1053: expiry (`questions.ttl_s`), a changed native session, an envelope a refused publish still owes, and old settled rows. Pushed here, after the desk exists, like the other late timers.
@@ -5531,6 +6268,8 @@ export async function startDaemon(opts: DaemonOptions) {
5531
6268
  startupCleanup.push(() => completionStore.close());
5532
6269
  const runs = new RunTracker();
5533
6270
  const checkOwners = new Map<PeerId, number>();
6271
+ const nativeBackgroundWaits = new Map<PeerId, ReturnType<typeof setTimeout>>();
6272
+ const nativeBackgroundBackoff = new Map<PeerId, number>();
5534
6273
  /**
5535
6274
  * A delivery handed to the peer whose turn has not started yet: the bus has already taken it out of its queue and the peer is still idle, so neither the queue nor the busy state
5536
6275
  * shows the continuation in that window. Cleared at the turn start or a failed delivery. ponytail: bounded to 10 s, so a delivery that never starts a turn (an adapter that
@@ -5541,8 +6280,8 @@ export async function startDaemon(opts: DaemonOptions) {
5541
6280
  /** A turn of the open run ended in a failure the adapter reported: a closed fact, never its text. */
5542
6281
  const runFailed = (peer: PeerId): void => { try { runs.note(peer, { failed: true }); } catch { /* advisory */ } };
5543
6282
  const settles = (peer: PeerId): boolean => {
5544
- // A pull-only attach (Kimi's TUI) has no hub turn machinery and no signal; the definition declares `settle` for its headless form, which attaches as a hub peer.
5545
- return !!definitionOf(peer)?.settle && !peer.includes("@") && bus.peers.get(peer)?.pullOnly !== true;
6283
+ // A pull-only native TUI earns a signal only through its launcher-bound native facts. An unattached pull-only peer still creates no run.
6284
+ return !!definitionOf(peer)?.settle && !peer.includes("@") && (bus.peers.get(peer)?.pullOnly !== true || nativeHookLaunches.current(peer) !== undefined);
5546
6285
  };
5547
6286
  /** Deliveries queued for the peer that will start another turn: all of them but the hub's own `presence` preface (a `fyi` never reaches the queue). */
5548
6287
  // The bus drains its queue into a dispatching journal row before the idle state reaches this tap, so the in-memory queue alone would read empty while a continuation is already on its
@@ -5562,10 +6301,37 @@ export async function startDaemon(opts: DaemonOptions) {
5562
6301
  const checksOwnedBy = (peer: PeerId): number => (checkOwners.get(peer) ?? 0) + tasks.checksOwnedBy(peer);
5563
6302
  // The peer's OWN adapter state, not the displayed one (a pause shows a busy peer as paused, and its work goes on): an owned child or a continuation the adapter still runs keeps it busy.
5564
6303
  const ownedChildrenOf = (peer: PeerId): number => (bus.peers.get(peer)?.state === "busy" ? 1 : 0);
6304
+ /**
6305
+ * #1278: the task a run's completion belongs to, resolved when the run opens (its first turn) by the rule `turn_end` uses and read when it settles, by which time the peer's open tasks have
6306
+ * moved on. In memory only: a run that a restart settles `interrupted` has lost it and reads `unattributed`, which is what is known.
6307
+ */
6308
+ const runAttributions = new Map<string, TaskAttribution>();
6309
+ const nativeBackgroundOf = (peer: PeerId): number | null | undefined => {
6310
+ const launch = nativeHookLaunches.current(peer), port = definitionOf(peer)?.hooks?.factsHook;
6311
+ if (!launch?.session || !launch.transcript || !port) return undefined;
6312
+ return port.read(launch.session, launch.transcript).background ?? null;
6313
+ };
6314
+ const completeNativeTurn = (peer: PeerId, launch: NativeHookLaunch, completion: NonNullable<NativeFactsTranscript["completion"]>): boolean => {
6315
+ const owner = bus.peers.get(peer);
6316
+ if (!launch.active || !isWsPeer(owner) || owner.state === "offline" || owner.sessionGeneration !== launch.generation || nativeHookLaunches.current(peer) !== launch) return false;
6317
+ launch.completed = completion.id; launch.active = false;
6318
+ turnEnded.set(peer, Date.now()); nativeCompletedAt.set(peer, Date.now()); tasks.cohorts.turnEnded(peer);
6319
+ event({ type: "native_turn_end", peer, id: completion.id }); owner.nativeStopped(launch.session!);
6320
+ const run = runs.get(peer);
6321
+ if (completion.reason === "cancelled") {
6322
+ if (run) { completionStore.dropRun(run.runTurn); runs.quietStop(peer); }
6323
+ } else {
6324
+ if (completion.reason === "failed") runFailed(peer);
6325
+ try { if (run) { runs.signalled(peer); settleCheck(peer); } } catch { log(`completion settle for ${peer} failed`); }
6326
+ }
6327
+ return true;
6328
+ };
5565
6329
  const completionDone = (peer: PeerId, run: Run, outcome: "done" | "failed" | "limit" | "interrupted"): void => {
5566
6330
  const made = completionStore.settle({ peer, runTurn: run.runTurn, lastTurn: run.lastTurn, startedAt: run.startedAt, ...(run.promptEnvelope ? { promptEnvelope: run.promptEnvelope } : {}), ...(run.replyEnvelope ? { replyEnvelope: run.replyEnvelope } : {}), private: run.private }, outcome, Date.now(), `cmp-${randomUUID().replaceAll("-", "").slice(0, 12)}`);
5567
6331
  if (!made) return;
5568
- event({ type: "completion", id: made.id, peer, outcome, ms: made.settledAt - made.startedAt });
6332
+ const attribution = runAttributions.get(run.runTurn) ?? { attribution: "unattributed" as const };
6333
+ runAttributions.delete(run.runTurn);
6334
+ event({ type: "completion", id: made.id, peer, outcome, ms: made.settledAt - made.startedAt, ...attribution });
5569
6335
  };
5570
6336
  /**
5571
6337
  * The one settle check. It runs at every point the pending-work facts can change: a turn end, a queue change, a permission or question closing, a check ending. A run settles
@@ -5573,10 +6339,29 @@ export async function startDaemon(opts: DaemonOptions) {
5573
6339
  */
5574
6340
  const settleCheck = (peer: PeerId): void => {
5575
6341
  try {
6342
+ const launch = nativeHookLaunches.current(peer), port = definitionOf(peer)?.hooks?.factsHook;
6343
+ if (launch?.active && launch.session && launch.transcript && port) {
6344
+ const completion = port.read(launch.session, launch.transcript).completion;
6345
+ if (completion && completion.index > (launch.baseline ?? -1) && completion.id !== launch.completed) completeNativeTurn(peer, launch, completion);
6346
+ }
5576
6347
  const run = runs.get(peer);
5577
6348
  if (!run || stopping) return;
5578
- const state = settleVerdict({ signal: run.signalled, queuedContinuations: queuedContinuations(peer), openPermissions: openPermissionsOf(peer), openQuestions: questionStore.openCount(peer), ownedChildren: ownedChildrenOf(peer), runningChecks: checksOwnedBy(peer), heldDeliveries: heldDeliveries(peer) });
5579
- if (state !== "settled") return;
6349
+ const nativeBackground = nativeBackgroundOf(peer);
6350
+ const state = settleVerdict({ signal: run.signalled, queuedContinuations: queuedContinuations(peer), openPermissions: openPermissionsOf(peer), openQuestions: questionStore.openCount(peer), ownedChildren: ownedChildrenOf(peer), runningChecks: checksOwnedBy(peer), heldDeliveries: heldDeliveries(peer), nativeBackground });
6351
+ if (state !== "settled") {
6352
+ // Native task notifications are optional observations. Re-read the inventory and final turn until both are settled or the run/launch ends.
6353
+ // ponytail: a quiet peer backs off from 250 ms to 1 s while each read may scan a 16 MiB index and an 8 MiB wire tail. Upgrade: incremental offsets.
6354
+ if ((launch?.active || nativeBackground === null || (nativeBackground ?? 0) > 0) && !nativeBackgroundWaits.has(peer)) {
6355
+ const delay = nativeBackgroundBackoff.get(peer) ?? 250;
6356
+ const timer = setTimeout(() => { nativeBackgroundWaits.delete(peer); settleCheck(peer); }, delay);
6357
+ nativeBackgroundBackoff.set(peer, Math.min(1000, delay * 2));
6358
+ nativeBackgroundWaits.set(peer, timer); timer.unref?.();
6359
+ }
6360
+ return;
6361
+ }
6362
+ const waiting = nativeBackgroundWaits.get(peer);
6363
+ if (waiting) { clearTimeout(waiting); nativeBackgroundWaits.delete(peer); }
6364
+ nativeBackgroundBackoff.delete(peer);
5580
6365
  // Persist FIRST and drop the in-memory run only after the store call returned: a write that throws (SQLite busy or locked) leaves the run open, so a later settle check retries it, and
5581
6366
  // the open-run row never outlives a run the daemon no longer tracks (a false `interrupted` after a restart, and a peer index that silently refuses the next run).
5582
6367
  // A budget pause stays a budget need (ahub budget): the run ends without a completion rather than reading as a result.
@@ -5886,7 +6671,11 @@ export async function startDaemon(opts: DaemonOptions) {
5886
6671
  join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "projects", opts.cwd.replace(/[^a-zA-Z0-9]/g, "-"), `${sessionId}.jsonl`), path => pathEvidence(path, lstatSync));
5887
6672
  // Optional native usage: only the instance-fenced explicit Claude session is read.
5888
6673
  // IDs persist in telemetry, so a restart/resume never counts the same native message twice.
5889
- const claudeNativeUsageSeen = new Set(readEvents(join(opts.stateDir, "events.jsonl")).filter(e => e.type === "usage" && e.source === "claude_transcript").map(e => (e as { id: string }).id));
6674
+ startupTimings.mark("services");
6675
+ const claudeNativeUsageSeen = startupSeeds.claudeNativeUsageSeen;
6676
+ startupTimings.mark("transcript_usage_seed");
6677
+ const agyNativeUsageSeen = new Set(startupEvents.filter(e => e.type === "usage" && e.source === "agy_transcript").map(e => (e as { id: string }).id));
6678
+ const agyTurnContext = new WeakMap<object, { hubTurnId?: string; baseline: number; attribution: TaskAttribution }>();
5890
6679
  const collectClaudeUsage = () => { for (const peer of channelPeers) {
5891
6680
  const session = claudeSession(peer);
5892
6681
  if (!session.sessionId || !session.transcriptPath) continue;
@@ -5922,6 +6711,151 @@ export async function startDaemon(opts: DaemonOptions) {
5922
6711
  // the newest `older` of them while they are empty, so an upgrade from such a hub verifies the board it was handed; a
5923
6712
  // filled one stays in the row and never matches.
5924
6713
  const ADDED_COLUMNS = [["deps", "[]"], ["plan", "{}"]] as const;
6714
+ // Person-owned runtime choices are separate from reload-bound configuration and native serving evidence.
6715
+ const modelBoundaries = new Map<string, { owner: PeerAdapter; token: object; turn?: object; nativeStarted?: true }>();
6716
+ const modelUnsupported = (peer: string): RuntimeModelStatus["unsupported"] | undefined => {
6717
+ const definition = definitionOf(peer), owner = bus.peers.get(peer);
6718
+ if (definition && isFixedBuiltinDefinition(definition) && definition.transport === "acp") {
6719
+ const state = owner ? modelAcpOwners.get(owner)?.modelOverrideState : undefined;
6720
+ if (!definition.modelOverride?.acp || !state?.available) return {
6721
+ reasonCode: "acp_setter_unavailable", kind: definition.kind, ...(state?.version ? { version: state.version } : {}),
6722
+ reason: `unsupported live: ${definition.kind} ${state?.version ?? "unknown"} lacks a setter receipt or compat admission`,
6723
+ nextStep: `restart this peer with ahub restart ${peer}`,
6724
+ };
6725
+ }
6726
+ if (!definition || !isFixedBuiltinDefinition(definition) || !definition.modelOverride) return {
6727
+ reasonCode: "unverified_setter", ...(definition ? { kind: definition.kind } : {}),
6728
+ reason: `unsupported live: ${definition?.kind ?? "retained peer"} (version unverified) has no verified model setter`, nextStep: `restart this peer with ahub restart ${peer}`,
6729
+ };
6730
+ if (owner && !modelManagedOwners.has(owner)) return { reasonCode: "unmanaged_attachment", kind: definition.kind, reason: "unsupported live: this attachment has no verified live model setter", nextStep: `change the native setting or restart this peer with ahub restart ${peer}` };
6731
+ return undefined;
6732
+ };
6733
+ const modelTokenAvailable = (peer: string, model: string): boolean => {
6734
+ if (!definitionOf(peer)?.modelOverride?.acp) return true;
6735
+ const owner = bus.peers.get(peer);
6736
+ return !!owner && modelAcpOwners.get(owner)?.acceptsModelOverride(model) === true;
6737
+ };
6738
+ const modelFallback = (peer: string): { model?: string; source: Exclude<ModelSource, "override"> } => {
6739
+ const declared = declarations[peer]?.model;
6740
+ if (isNativeModelToken(declared)) return { model: declared, source: "instance" };
6741
+ const owner = bus.peers.get(peer), model = owner ? modelLaunchModels.get(owner) : undefined;
6742
+ if (model !== undefined) return { model, source: "launch" };
6743
+ const baseline = owner ? modelAcpOwners.get(owner)?.modelOverrideState.baseline : undefined;
6744
+ return { ...(baseline ? { model: baseline } : {}), source: "native default" };
6745
+ };
6746
+ const registerModelOwner = (owner: PeerAdapter): void => {
6747
+ const definition = definitionOf(owner.id);
6748
+ if (!definition || !isFixedBuiltinDefinition(definition) || !definition.modelOverride) return;
6749
+ if (definition.modelOverride.acp && !modelAcpOwners.get(owner)?.modelOverrideState.available) return;
6750
+ modelManagedOwners.add(owner);
6751
+ try {
6752
+ const launch = owner.recoveryMetadata?.()?.launch;
6753
+ const model = launch && typeof launch === "object" && !Array.isArray(launch) ? (launch as Record<string, unknown>).model : undefined;
6754
+ if (isNativeModelToken(model)) modelLaunchModels.set(owner, model);
6755
+ } catch { /* No explicit launch evidence: leave native default unknown. Never read this hook on a poll. */ }
6756
+ };
6757
+ const runtimeModelRow = (peer: string) => modelLatches.status(peer, bus.peers.get(peer), modelFallback(peer), modelUnsupported(peer));
6758
+ const MODEL_DISPLAY_ROWS_MAX = 512;
6759
+ const runtimeModelRows = (): RuntimeModelStatus[] | undefined => {
6760
+ const ids = new Set<string>();
6761
+ const add = (id: string) => { if (PEER_ID.test(id)) ids.add(id); return ids.size <= MODEL_DISPLAY_ROWS_MAX; };
6762
+ // Stop at the first overflow: existing legacy attachments are not admission-bounded by this display ceiling.
6763
+ for (const id of SUPPORTED_PEERS) if (!add(id)) return undefined;
6764
+ for (const id of configuredIds) if (!add(id)) return undefined;
6765
+ for (const id of extraIds) if (!add(id)) return undefined;
6766
+ for (const peer of restored?.peers ?? []) if (peer.externalInstance && !add(peer.id)) return undefined;
6767
+ for (const id of externalInstanceIds) if (!add(id)) return undefined;
6768
+ for (const id of externalRefusedRows.keys()) if (!add(id)) return undefined;
6769
+ for (const id of bus.peers.keys()) if (!add(id)) return undefined;
6770
+ for (const row of modelOverrides.list()) if (!add(row.peer)) return undefined;
6771
+ return [...ids].sort().map(runtimeModelRow);
6772
+ };
6773
+ const runtimeModelProjection = () => {
6774
+ try { const rows = runtimeModelRows(); if (rows) return { runtimeModels: rows }; }
6775
+ catch { /* Model metadata failure is not whole-daemon status failure. The explicit list keeps its refusal. */ }
6776
+ return { runtimeModels: [] as RuntimeModelStatus[], runtimeModelsUnavailable: true as const };
6777
+ };
6778
+ const modelSelection = (peer: string) => {
6779
+ const owner = bus.peers.get(peer);
6780
+ if (!owner || modelUnsupported(peer)) throw new Error("model selection has no current supported owner; inspect ahub status and restart the peer before retrying");
6781
+ let boundary = modelBoundaries.get(peer);
6782
+ if (!boundary || boundary.owner !== owner) {
6783
+ if (boundary) modelLatches.forget(peer);
6784
+ boundary = { owner, token: {}, ...(turns.get(peer) ? { turn: turns.get(peer) } : {}) };
6785
+ modelBoundaries.set(peer, boundary);
6786
+ }
6787
+ const captured = boundary;
6788
+ const selection = modelLatches.capture(peer, owner, captured.token, () => !stopping && bus.peers.get(peer) === owner
6789
+ && modelBoundaries.get(peer) === captured && (!captured.turn || turns.get(peer) === captured.turn));
6790
+ return { model: selection.model, applied: (nativeModel?: string) => { selection.applied(nativeModel); if (!stopping) writeStatus(); }, rejected: () => {
6791
+ if (stopping || bus.peers.get(peer) !== owner || modelBoundaries.get(peer) !== captured || captured.nativeStarted
6792
+ || captured.turn && turns.get(peer) !== captured.turn) return;
6793
+ if (modelLatches.end(peer, captured.token, true)) { modelBoundaries.delete(peer); writeStatus(); }
6794
+ } };
6795
+ };
6796
+ const acpModelSelection = (peer: string) => {
6797
+ if (modelUnsupported(peer)) {
6798
+ if (modelOverrides.get(peer)) throw new Error("retained model override has no current receipt-verified ACP setter; clear it with ahub model clear or restart a supported peer before retrying");
6799
+ return undefined; // An unavailable optional setter must not break ordinary no-override ACP work.
6800
+ }
6801
+ return modelSelection(peer);
6802
+ };
6803
+ type ModelGrant = { source: "cli" | "dashboard"; scope: object | string; current: () => boolean; expiresAt?: number };
6804
+ type ModelPreview = { peer: string; action: "set" | "clear"; model?: string; expiresAt: number; scope: object | string; source: "cli" | "dashboard";
6805
+ revision: string; runtime: string; config: number; owner: PeerAdapter | undefined; generation: string | undefined; afterTurn: string | undefined };
6806
+ const modelPreviews = new Map<string, ModelPreview>();
6807
+ const MODEL_CONFIRM_MS = 60_000, MODEL_PREVIEWS_MAX = 64;
6808
+ const modelFailure = (error: string) => ({ ok: false as const, error });
6809
+ function modelCommand(input: Record<string, unknown>, grant: ModelGrant): Record<string, unknown> {
6810
+ if (!grant.current()) return modelFailure("model changes are person-only and this authority expired; run ahub model in a person's terminal or reopen ahub ui --settings");
6811
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) return modelFailure("recovery or shutdown is holding model overrides; inspect ahub status and retry after release");
6812
+ if (input.op === "list") {
6813
+ const rows = runtimeModelRows();
6814
+ return rows ? { ok: true, models: rows } : modelFailure("model list exceeds its display bound; close unused peer sessions and restart if needed, or clear unused overrides with ahub model clear, then list again");
6815
+ }
6816
+ let preview: ModelPreview;
6817
+ if (input.op === "confirm") {
6818
+ const token = typeof input.token === "string" ? input.token : "", retained = modelPreviews.get(token);
6819
+ if (!retained || retained.scope !== grant.scope || retained.source !== grant.source || retained.expiresAt <= Date.now()) return modelFailure("model confirmation expired or belongs to another session; preview the model change again");
6820
+ modelPreviews.delete(token); preview = retained;
6821
+ if (preview.config !== configRevision || preview.revision !== modelOverrides.revision(preview.peer) || preview.owner !== bus.peers.get(preview.peer)
6822
+ || preview.runtime !== JSON.stringify(runtimeModelRow(preview.peer)) || preview.generation !== connectionGeneration(preview.peer)
6823
+ || preview.afterTurn !== turns.get(preview.peer)?.id) return modelFailure("peer, configuration or model choice changed after preview; refresh and preview the change again");
6824
+ } else {
6825
+ const action = input.op === "preview" ? input.action : input.op, peer = input.peer;
6826
+ if ((action !== "set" && action !== "clear") || typeof peer !== "string" || !PEER_ID.test(peer)) return modelFailure("invalid model request; use model set <peer> <model> or model clear <peer>");
6827
+ if (!definitionOf(peer) && !(action === "clear" && modelOverrides.get(peer))) return modelFailure("model peer is unknown; run ahub model list and choose a current or retained peer");
6828
+ if (action === "set" && !isNativeModelToken(input.model)) return modelFailure("invalid native model token; use 1 to 128 ASCII letters, digits or ._:/@+- with an initial letter or digit");
6829
+ const unsupported = modelUnsupported(peer);
6830
+ if (action === "set" && unsupported) return modelFailure(`${unsupported.reason}; ${unsupported.nextStep}`);
6831
+ if (action === "set" && !modelTokenAvailable(peer, input.model as string)) return modelFailure("requested model is not advertised by this receipt-verified ACP session; inspect native model choices and retry");
6832
+ const expiresAt = Math.min(Date.now() + MODEL_CONFIRM_MS, grant.expiresAt ?? Infinity);
6833
+ preview = { peer, action, ...(action === "set" ? { model: input.model as string } : {}), expiresAt, scope: grant.scope, source: grant.source,
6834
+ revision: modelOverrides.revision(peer), runtime: JSON.stringify(runtimeModelRow(peer)), config: configRevision, owner: bus.peers.get(peer), generation: connectionGeneration(peer), afterTurn: turns.get(peer)?.id };
6835
+ if (input.op === "preview") {
6836
+ for (const [token, old] of modelPreviews) if (old.expiresAt <= Date.now()) modelPreviews.delete(token);
6837
+ if (modelPreviews.size >= MODEL_PREVIEWS_MAX) return modelFailure("too many model previews remain open; wait a minute and preview again");
6838
+ const token = randomUUID(); modelPreviews.set(token, preview);
6839
+ return { ok: true, model: runtimeModelRow(peer), confirmation: { token, expiresAt, peer, action, previousModel: modelOverrides.get(peer)?.model ?? null,
6840
+ nextModel: preview.model ?? null, appliesFrom: "next_turn", ...(preview.afterTurn ? { afterTurn: preview.afterTurn } : {}) } };
6841
+ }
6842
+ if (grant.source !== "cli") return modelFailure("dashboard model changes require preview and confirmation; preview the change again");
6843
+ }
6844
+ if (!grant.current()) return modelFailure("model authority expired before the write; reopen the person settings session and preview again");
6845
+ const unsupported = modelUnsupported(preview.peer);
6846
+ if (preview.action === "set" && unsupported) return modelFailure(`${unsupported.reason}; ${unsupported.nextStep}`);
6847
+ if (preview.action === "set" && !modelTokenAvailable(preview.peer, preview.model!)) return modelFailure("requested model is not advertised by this receipt-verified ACP session; inspect native model choices and retry");
6848
+ const previousModel = modelOverrides.get(preview.peer)?.model ?? null;
6849
+ if (preview.action === "set") modelOverrides.set(preview.peer, preview.model!); else modelOverrides.clear(preview.peer);
6850
+ const audited = event({ type: "model_change", peer: preview.peer, previousModel, model: preview.model ?? null, by: "person", source: grant.source,
6851
+ appliesFrom: "next_turn", ...(preview.afterTurn ? { afterTurn: preview.afterTurn } : {}) });
6852
+ writeStatus();
6853
+ if (!audited) return { ok: false, saved: true, error: "model override was saved but its model_change audit could not be appended; run ahub model list before retrying and repair events.jsonl" };
6854
+ return { ok: true, model: runtimeModelRow(preview.peer), appliesFrom: "next_turn", ...(preview.afterTurn ? { afterTurn: preview.afterTurn } : {}) };
6855
+ }
6856
+ const modelCommandSafe = (input: Record<string, unknown>, grant: ModelGrant): Record<string, unknown> => {
6857
+ 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"); }
6858
+ };
5925
6859
  const integrity = (older = 0) => {
5926
6860
  const queues = Object.fromEntries(Object.keys(bus.snapshot(false).queues).sort().map((id) => [id, bus.queueIds(id)]));
5927
6861
  const boardState = board.list().sort((a, b) => a.id - b.id).map((t) => {
@@ -5936,8 +6870,14 @@ export async function startDaemon(opts: DaemonOptions) {
5936
6870
  const researchComparisons = board.researchComparisonIntegrity();
5937
6871
  const researchRunners = board.runnerReceiptIntegrity();
5938
6872
  const researchEvidence = board.researchEvidenceIntegrity();
6873
+ const guidanceVariants = board.guidanceVariantsIntegrity();
6874
+ const executionReferences = board.executionReferencesIntegrity();
5939
6875
  const reviewComments = board.reviewCommentsIntegrity();
5940
- return { queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(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 } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
6876
+ const modelState = modelOverrides.integrity();
6877
+ const visualIntegrity = visuals.integrity();
6878
+ if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
6879
+ throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
6880
+ 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 } : {}), ...(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])) } : {}) };
5941
6881
  };
5942
6882
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
5943
6883
  const integrityAs = (expected: unknown) => {
@@ -6022,6 +6962,7 @@ export async function startDaemon(opts: DaemonOptions) {
6022
6962
  const deliveryFailures = bus.failedDeliveryCounts();
6023
6963
  const view = {
6024
6964
  ...(deliveryFailures ? { deliveryFailures } : {}),
6965
+ ...runtimeModelProjection(),
6025
6966
  ...(queueBackpressure ? { queueBackpressure } : {}),
6026
6967
  ...(crashLines.length ? { crash: crashLines } : {}),
6027
6968
  projectId,
@@ -6068,7 +7009,7 @@ export async function startDaemon(opts: DaemonOptions) {
6068
7009
  ...(dashboard ? { uiOrigin: dashboard.origin } : {}),
6069
7010
  codexProxyPort: opts.codexProxyPort,
6070
7011
  peers: Object.fromEntries(
6071
- peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
7012
+ peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
6072
7013
  ),
6073
7014
  taskWip: tasks.wipBreakdown(peerIds),
6074
7015
  boardReadCapabilities: { releaseFilter: true, columnMetadata: true },
@@ -6460,6 +7401,7 @@ export async function startDaemon(opts: DaemonOptions) {
6460
7401
  uiEvents.push({ seq: ++uiSequence, event: e });
6461
7402
  if (uiEvents.length > 200) uiEvents.shift();
6462
7403
  if (e.t === "state") {
7404
+ if (e.state === "offline") { modelBoundaries.delete(e.peer); modelLatches.forget(e.peer); }
6463
7405
  roomCommands.changed();
6464
7406
  log(`state ${e.peer} -> ${e.state}`);
6465
7407
  event({ type: "state", peer: e.peer, state: e.state });
@@ -6483,7 +7425,7 @@ export async function startDaemon(opts: DaemonOptions) {
6483
7425
  const delivery = pendingDeliveryTask.get(e.peer);
6484
7426
  pendingDeliveryTask.delete(e.peer);
6485
7427
  const attribution = taskAttribution(e.peer, delivery);
6486
- const id = `${e.peer}#${runId}.${++turnSeq}`;
7428
+ const id = `${e.peer}#${runId}.${++turnSeq}`, startedAt = Date.now();
6487
7429
  // A turn of a peer with a PII task open is not snapshotted: what it writes would stay in git's object store until
6488
7430
  // gc. It is still recorded, without trees, so an overlapping turn's undo knows its changes are unknown.
6489
7431
  const pii = holdsPii(e.peer);
@@ -6499,7 +7441,11 @@ export async function startDaemon(opts: DaemonOptions) {
6499
7441
  writeScope = ownerWriteRoot(e.peer) === opts.cwd ? canonicalWriteScope(start.repo, start.budget) : true;
6500
7442
  } catch (error) { snapshotFailure(`the write scope of ${id}`, error); }
6501
7443
  const preparedRoles = preparedSessionRoleIdentities.get(e.peer)?.map(role => ({ ...role })) ?? null;
6502
- turns.set(e.peer, { id, capture, start: Date.now(), tokens: 0, writeTasks, branches, writeScope, deliveryTask: delivery, attribution, preparedRoles, ...(start ? { tree: start.tree, head: start.head, commit: start.commit, reflog: start.reflog, snapshotMs: start.ms } : {}), ...(pii ? { private: true } : {}) });
7444
+ turns.set(e.peer, { id, capture, start: startedAt, tokens: 0, writeTasks, branches, writeScope, deliveryTask: delivery, attribution, preparedRoles, ...(start ? { tree: start.tree, head: start.head, commit: start.commit, reflog: start.reflog, snapshotMs: start.ms } : {}), ...(pii ? { private: true } : {}) });
7445
+ const modelBoundary = modelBoundaries.get(e.peer);
7446
+ if (modelBoundary && modelBoundary.owner === bus.peers.get(e.peer)) modelBoundary.turn = turns.get(e.peer);
7447
+ const supervised = supervisionTurns.get(e.peer);
7448
+ if (supervised?.id.startsWith("supervision-")) supervised.nativeTurn = id;
6503
7449
  const pendingReviewInput = pendingReviewObserverInputs.get(e.peer);
6504
7450
  if (pendingReviewInput) {
6505
7451
  pendingReviewInput.turnId = id; delete pendingReviewInput.awaitingTurn;
@@ -6520,16 +7466,23 @@ export async function startDaemon(opts: DaemonOptions) {
6520
7466
  try {
6521
7467
  deliveredAwaitingTurn.delete(e.peer);
6522
7468
  if (settles(e.peer)) {
6523
- const person = pendingPersonDelivery.get(e.peer);
7469
+ const person = pendingPersonDelivery.get(e.peer), nativePerson = pendingNativePerson.delete(e.peer);
6524
7470
  pendingPersonDelivery.delete(e.peer);
6525
- const run = runs.turnStarted({ peer: e.peer, turn: id, at: Date.now(), personOriginated: person !== undefined, ...(person ? { promptEnvelope: person.envelope } : {}), private: person?.private === true || pii || holdsPii(e.peer) });
6526
- if (run) { if (run.runTurn === id) completionStore.openRun(run); else completionStore.touchRun(run); }
7471
+ const run = runs.turnStarted({ peer: e.peer, turn: id, at: Date.now(), personOriginated: person !== undefined || nativePerson, ...(person ? { promptEnvelope: person.envelope } : {}), private: nativePerson || person?.private === true || pii || holdsPii(e.peer) });
7472
+ if (run) {
7473
+ if (run.runTurn === id) { completionStore.openRun(run); runAttributions.set(id, attribution); } else completionStore.touchRun(run);
7474
+ // A run that never settles in this process would keep its entry; the table only ever holds the open runs, one per settling peer.
7475
+ if (runAttributions.size > 256) runAttributions.delete(runAttributions.keys().next().value!);
7476
+ }
6527
7477
  }
6528
7478
  } catch { log(`completion run start for ${e.peer} failed; no completion for this turn`); }
6529
- if (softTokenPeer(e.peer)) try { kimiUsage.turnStarted(e.peer); } catch { /* counting never costs a turn */ }
7479
+ if (softTokenPeer(e.peer)) try { kimiUsage.turnStarted(e.peer, { id, startedAt, attribution }); } catch { /* counting never costs a turn */ }
6530
7480
  } else if (!busy && open) {
6531
7481
  collectKimiUsage(e.peer); // before the turn closes: its rows count toward the turn's tokens
7482
+ if (softTokenPeer(e.peer)) try { kimiUsage.turnEnded(e.peer, open.id, Date.now()); } catch { /* counting never costs a turn */ }
7483
+ closeRecordFrame(e.peer); recordInputs.delete(e.peer);
6532
7484
  turns.delete(e.peer);
7485
+ modelBoundaries.delete(e.peer); modelLatches.end(e.peer);
6533
7486
  let afterTurn: (() => void) | undefined;
6534
7487
  let files: number | undefined;
6535
7488
  let writeProgress: boolean | undefined;
@@ -6605,9 +7558,10 @@ export async function startDaemon(opts: DaemonOptions) {
6605
7558
  // After the turn_end event: a notice delivered at once starts the peer's next turn, which must come after it.
6606
7559
  if (changed.length) afterTurn = () => detectConflicts(e.peer, open.id, open.start, changed);
6607
7560
  }
6608
- // A lost Claude channel/watchdog is not native completion; only its real Stop closes a counted turn.
6609
- if (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 } : {}) });
6610
- if (definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
7561
+ // 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.
7562
+ const nativeFactsTurn = nativeHookLaunches.current(e.peer) !== undefined && bus.peers.get(e.peer)?.pullOnly === true;
7563
+ 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 } : {}) });
7564
+ if (!nativeFactsTurn && definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
6611
7565
  if ((bus.peers.get(e.peer)?.state ?? e.state) === "idle") queueMicrotask(() => finishSupervisionTurn(e.peer));
6612
7566
  turnEnded.set(e.peer, Date.now());
6613
7567
  tasks.cohorts.turnEnded(e.peer);
@@ -6622,7 +7576,7 @@ export async function startDaemon(opts: DaemonOptions) {
6622
7576
  try { tasks.recordOwnerTurn(e.peer, open.writeTasks, changed, !!open.taskEffect || !!open.effectsPending); } catch { /* advisory cannot fail native completion */ }
6623
7577
  }
6624
7578
  }
6625
- if (e.state === "offline" && softTokenPeer(e.peer)) { collectKimiUsage(e.peer); kimiUsage.drop(e.peer); }
7579
+ if (e.state === "offline" && softTokenPeer(e.peer)) { collectKimiUsage(e.peer, true); kimiUsage.drop(e.peer); }
6626
7580
  // #636: a class-budget allowance belongs to the owner that earned it. A stopped, crashed or removed owner that later resumes the same native
6627
7581
  // session id starts from zero (a replaced adapter's own `offline` is muted, so a new owner also revokes where it is created).
6628
7582
  if (e.state === "offline") actionBudgets.revoke(e.peer);
@@ -6753,6 +7707,9 @@ export async function startDaemon(opts: DaemonOptions) {
6753
7707
  const timeoutMs = opts.permissionTimeoutMs ?? approvalTimeoutS * 1000;
6754
7708
  const createdAt = Date.now();
6755
7709
  const expiresAt = createdAt + timeoutMs;
7710
+ // #1278: the task this request belongs to, resolved once when it opens by the rule `turn_end` and `tokens` use. The settle event reuses it, because the turn can have ended by then and the
7711
+ // peer's open tasks changed. Ids and a closed rule name only; unattributed stays unattributed.
7712
+ const requestAttribution = taskAttribution(req.peer);
6756
7713
  const publicTool = typeof req.tool === "string" && /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/.test(req.tool) && !/\s/.test(req.tool) ? req.tool : undefined;
6757
7714
  log(`permission ${id} requested by ${req.peer} (${title.length} chars, shown on the console; cancelled after ${timeoutMs / 1000}s)`);
6758
7715
  // The tool name is for the desktop notice only: the console push keeps its shape.
@@ -6781,7 +7738,7 @@ export async function startDaemon(opts: DaemonOptions) {
6781
7738
  if (outcome === "expired") { try { notify(`permission ${id} from ${req.peer} was not answered within ${Math.round(timeoutMs / 1000)}s and was cancelled`); } catch { /* registry withdrawal already completed */ } }
6782
7739
  const latencyMs = Math.max(0, Date.now() - createdAt);
6783
7740
  const optionKind = option?.kind === "allow_once" || option?.kind === "allow_always" || option?.kind === "reject_once" || option?.kind === "reject_always" ? option.kind : undefined;
6784
- try { event({ type: "permission", id, peer: req.peer, event: outcome, latencyMs, ...(surface ? { surface } : {}), ...(optionKind ? { option: optionKind } : {}) }); } catch { try { log(`permission event recording failed at settlement for ${req.peer}`); } catch { /* settlement remains authoritative */ } }
7741
+ try { event({ type: "permission", id, peer: req.peer, event: outcome, latencyMs, ...(surface ? { surface } : {}), ...(optionKind ? { option: optionKind } : {}), ...requestAttribution }); } catch { try { log(`permission event recording failed at settlement for ${req.peer}`); } catch { /* settlement remains authoritative */ } }
6785
7742
  try { notify(`permission ${id} from ${req.peer} ${outcome} option ${optionKind ?? "none"} by ${surface ?? "hub"} (${latencyMs}ms)`); } catch { /* no reporting failure strands the caller */ }
6786
7743
  for (const c of consoles) if (c.data.tail) { try { c.send(JSON.stringify({ t: "permission_closed", id, peer: req.peer, outcome: outcome === "expired" ? "cancelled" : outcome, ...(outcome === "expired" ? { reason: "expired" } : {}), latencyMs })); } catch { /* another surface can still observe the closure */ } }
6787
7744
  resolve({ outcome, ...(option ? { optionId: option.optionId, ...(surface ? { approvalId: id } : {}) } : {}) });
@@ -6793,7 +7750,7 @@ export async function startDaemon(opts: DaemonOptions) {
6793
7750
  timer = setTimeout(() => done(undefined, undefined, "expired"), timeoutMs);
6794
7751
  signal?.addEventListener("abort", aborted, { once: true });
6795
7752
  if (signal?.aborted) { aborted(); return; }
6796
- try { event({ type: "permission", id, peer: req.peer, event: "requested" }); } catch { /* optional observer */ }
7753
+ try { event({ type: "permission", id, peer: req.peer, event: "requested", ...requestAttribution }); } catch { /* optional observer */ }
6797
7754
  for (const c of consoles) if (c.data.tail) { try { c.send(push); } catch { /* next tail gets the registered request */ } }
6798
7755
  if (config.approvals.notify) { try { desktop("agent-hub", `${req.peer} asks for approval${req.tool ? `: ${req.tool}` : ""} (ahub tail)`); } catch { /* optional desktop */ } }
6799
7756
  });
@@ -7205,6 +8162,8 @@ export async function startDaemon(opts: DaemonOptions) {
7205
8162
  if (instance?.jcode_home) { const refusal = jcodeHomeRefusal(peer, instance.jcode_home); if (refusal) return { ok: false, error: refusal }; }
7206
8163
  startCurrent?.();
7207
8164
  const jcode: JcodePeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["owned-acp"]({ peer, command: config.jcode_cmd, home: instance?.jcode_home ?? config.jcode_home,
8165
+ getModelOverride: () => acpModelSelection(peer),
8166
+ ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride?.acp ? { modelPolicy: adapter.modelOverride.acp } : {}),
7208
8167
  providerProfile: (args.providerProfile ?? instance?.provider_profile ?? config.jcode_provider_profile) || undefined,
7209
8168
  ...(instance?.provider ? { provider: instance.provider } : {}),
7210
8169
  ...(args.model ?? instance?.model ? { launchModel: (args.model ?? instance?.model)! } : {}), ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}), cwd: executionCwd, watchdogMs: config.watchdog_ms,
@@ -7225,9 +8184,10 @@ export async function startDaemon(opts: DaemonOptions) {
7225
8184
  event({ type: "usage", peer, source: "jcode_acp", id: `jcode:${runId}:${peer}:${++codexUsageSeq}`, inputTokens: usage.inputTokens, outputTokens: usage.outputTokens,
7226
8185
  ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}), ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}), ...taskAttribution(peer) });
7227
8186
  } }) }) as JcodePeer;
8187
+ if (isFixedBuiltinDefinition(adapter)) modelAcpOwners.set(jcode, jcode);
7228
8188
  jcodeLaunches.set(peer, jcode);
7229
8189
  recoveryTaskPreface(peer); await ensurePreface(peer); startCurrent?.();
7230
- try { startCurrent?.(); await jcode.start(); startCurrent?.(); await reconcileNativeStart(peer, jcode, startCurrent); }
8190
+ try { startCurrent?.(); await jcode.start(); startCurrent?.(); registerModelOwner(jcode); bindRecordOwner(jcode, executionCwd, () => jcode.nativeSession); await reconcileNativeStart(peer, jcode, startCurrent); }
7231
8191
  catch { await jcode.stop().catch(() => {}); if (jcodeLaunches.get(peer) === jcode) jcodeLaunches.delete(peer); throw new Error("Jcode startup not verified; check native version, provider profile, MCP store and owned daemon (details withheld)"); }
7232
8192
  return { ok: true, policy: "unmanaged" };
7233
8193
  }
@@ -7240,6 +8200,8 @@ export async function startDaemon(opts: DaemonOptions) {
7240
8200
  isPrivateTurn: () => !!turns.get(peer)?.private || contextPii(peer),
7241
8201
  actionGate: acpActionGate(peer),
7242
8202
  cmd, kind: adapter.kind,
8203
+ getModelOverride: () => acpModelSelection(peer),
8204
+ ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride?.acp ? { modelPolicy: adapter.modelOverride.acp } : {}),
7243
8205
  toolCeilingMs: adapterTiming.acpToolCeilingMs(), activityBatchMs: adapterTiming.acpActivityBatchMs(),
7244
8206
  permissionMode: permissionMode(peer),
7245
8207
  ...(args.model ? { launchModel: args.model } : {}),
@@ -7275,10 +8237,12 @@ export async function startDaemon(opts: DaemonOptions) {
7275
8237
  mcpServers: [{ name: "agent-hub", command: "bun", args: ["run", SERVER_JS], env: Object.entries(toolEnv(peer, true)).map(([name, value]) => ({ name, value })) }],
7276
8238
  preamble: sessionRoleContract(peer),
7277
8239
  }) }) as AcpPeer;
8240
+ if (isFixedBuiltinDefinition(adapter)) modelAcpOwners.set(kimi, kimi);
7278
8241
  recoveryTaskPreface(peer);
7279
8242
  await ensurePreface(peer); startCurrent?.();
7280
8243
  try {
7281
- startCurrent?.(); await kimi.start(); startCurrent?.();
8244
+ startCurrent?.(); await kimi.start(); startCurrent?.(); registerModelOwner(kimi);
8245
+ bindRecordOwner(kimi, executionCwd, () => kimi.nativeSession);
7282
8246
  await reconcileNativeStart(peer, kimi, startCurrent);
7283
8247
  } catch (error) { await kimi.stop().catch(stop => log(`kimi stop after a failed start: ${(stop as Error).message}`)); throw error; }
7284
8248
  return { ok: true };
@@ -7296,6 +8260,8 @@ export async function startDaemon(opts: DaemonOptions) {
7296
8260
  const externalLaunchId = externalBinding ? randomUUID() : undefined;
7297
8261
  if (externalLaunchId) for (const server of mcpServers) server.env.push({ name: "AGENTHUB_LAUNCH_ID", value: externalLaunchId });
7298
8262
  const acpOptions: AcpOptions = {
8263
+ getModelOverride: () => acpModelSelection(peer),
8264
+ ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride?.acp ? { modelPolicy: adapter.modelOverride.acp } : {}),
7299
8265
  toolCeilingMs: adapterTiming.acpToolCeilingMs(), activityBatchMs: adapterTiming.acpActivityBatchMs(),
7300
8266
  onActivity: item => activityRings[peer]?.append(item),
7301
8267
  isPrivateTurn: () => !!turns.get(peer)?.private || contextPii(peer),
@@ -7328,6 +8294,7 @@ export async function startDaemon(opts: DaemonOptions) {
7328
8294
  if (externalBinding && externalLaunchId) externalLaunches.set(peer, { owner, options: acpOptions, launchId: externalLaunchId, binding: externalBinding, workspace: externalWorkspace! });
7329
8295
  assertNativeProofPorts(adapter, owner);
7330
8296
  if (!isAcpPeer(owner) || owner.id !== peer || owner.deliveryOnly !== true || owner.hubOwned !== true || owner.form !== "headless") throw new Error("ACP factory did not return its bound native transport");
8297
+ if (isFixedBuiltinDefinition(adapter)) modelAcpOwners.set(owner, owner);
7331
8298
  recoveryTaskPreface(peer); await ensurePreface(peer); startCurrent?.();
7332
8299
  try {
7333
8300
  if (externalBinding && (!membershipAllowed(peer) || externalWorkspaceIdentity(executionCwd) !== externalWorkspace || !sameExternalInstanceBinding(externalBinding, captureExternalBinding(peer, args.sessionId)))) throw new Error("external instance binding changed before native spawn");
@@ -7342,6 +8309,8 @@ export async function startDaemon(opts: DaemonOptions) {
7342
8309
  externalSessions.set(peer, receipt.sessionId);
7343
8310
  writeExternalInstanceRecord(opts.stateDir, externalBinding, receipt.sessionId);
7344
8311
  }
8312
+ registerModelOwner(owner);
8313
+ bindRecordOwner(owner, executionCwd, () => owner.nativeSession);
7345
8314
  await reconcileNativeStart(peer, owner, startCurrent);
7346
8315
  }
7347
8316
  catch (error) {
@@ -7359,6 +8328,11 @@ export async function startDaemon(opts: DaemonOptions) {
7359
8328
  actionBudgets.revoke(peer);
7360
8329
  startCurrent?.();
7361
8330
  const codex: CodexPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["codex-appserver"]({
8331
+ getModelOverride: () => modelSelection(peer),
8332
+ onNativeModelApplied: model => { if (!stopping && bus.peers.get(peer) === codex && isNativeModelToken(model)) {
8333
+ try { modelLatches.observeNative(peer, codex, model); } catch { modelLatches.forget(peer); }
8334
+ writeStatus();
8335
+ } },
7362
8336
  admitAttach: () => membershipAllowed(peer),
7363
8337
  permissionMode: permissionMode(peer),
7364
8338
  ...(declarations[peer] ? { threadSandbox: () => isPlannerOnly(config.roles[peer] ?? []) ? declarations[peer]?.worktree ? "unavailable" as const : "read-only" as const : undefined } : {}),
@@ -7375,6 +8349,8 @@ export async function startDaemon(opts: DaemonOptions) {
7375
8349
  // #215: before the thread's first turn_start, so the planner can tell which turns belong to which thread.
7376
8350
  onThread: (thread, fresh) => { lastCodexThreads.set(peer, thread); event({ type: "native_thread", peer, thread, fresh }); },
7377
8351
  onTurn: (native) => {
8352
+ const modelBoundary = modelBoundaries.get(peer);
8353
+ if (modelBoundary && modelBoundary.owner === codex) modelBoundary.nativeStarted = true;
7378
8354
  const open = turns.get(peer);
7379
8355
  if (open) turnLog?.native(open.id, native);
7380
8356
  if (factsOn()) factSession(peer, codex.thread); // a new thread is unverified before its first item
@@ -7426,10 +8402,12 @@ export async function startDaemon(opts: DaemonOptions) {
7426
8402
  watchdogMs: config.watchdog_ms,
7427
8403
  log,
7428
8404
  }) }) as CodexPeer;
8405
+ registerModelOwner(codex);
7429
8406
  recoveryTaskPreface(peer);
7430
8407
  await ensurePreface(peer); startCurrent?.();
7431
8408
  try {
7432
8409
  startCurrent?.(); await codex.start(); startCurrent?.();
8410
+ bindRecordOwner(codex, executionCwd, () => codex.nativeSession);
7433
8411
  await reconcileNativeStart(peer, codex, startCurrent);
7434
8412
  } catch (error) { await codex.stop().catch(stop => log(`codex stop after a failed start: ${(stop as Error).message}`)); throw error; }
7435
8413
  const proxy = frontendProxyState(peer, codex);
@@ -7522,6 +8500,7 @@ export async function startDaemon(opts: DaemonOptions) {
7522
8500
  const routing = activeRouting();
7523
8501
  startCurrent?.();
7524
8502
  const pi: PiPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["pi-rpc"]({
8503
+ getModelOverride: () => modelSelection(peer),
7525
8504
  cwd: executionCwd, stateDir: nativeRoot, ...(declarations[peer] ? { hubStateDir: opts.stateDir } : {}), cmd: config.pi.cmd, mode, backend,
7526
8505
  model: args.model,
7527
8506
  sessionId: args.sessionId, sessionFile: args.sessionFile,
@@ -7633,9 +8612,11 @@ export async function startDaemon(opts: DaemonOptions) {
7633
8612
  },
7634
8613
  watchdogMs: config.watchdog_ms, maxSteps: config.pi.max_steps, log,
7635
8614
  }) }) as PiPeer;
8615
+ registerModelOwner(pi);
7636
8616
  recoveryTaskPreface(peer);
7637
8617
  await ensurePreface(peer); startCurrent?.();
7638
8618
  executionOwners.set(peer, { owner: pi, cwd: executionCwd });
8619
+ if (pi.mode === "headless") bindRecordOwner(pi, executionCwd, () => pi.nativeSession);
7639
8620
  bus.add(pi);
7640
8621
  // The start's own error is the one reported; a stop that fails too is logged beside it (#115).
7641
8622
  try { startCurrent?.(); await pi.start(); } catch (error) {
@@ -7702,12 +8683,15 @@ export async function startDaemon(opts: DaemonOptions) {
7702
8683
  };
7703
8684
  startCurrent?.();
7704
8685
  const local: LocalPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["local-worker"]({
8686
+ getModelOverride: () => modelSelection(peer),
7705
8687
  cwd: executionCwd,
7706
8688
  omni,
7707
8689
  onUsage: record => event({ type: "usage", peer, source: "omniroute", id: record.id, ...record.usage, ...taskAttribution(peer, record.task), requestedModel: record.requestedModel, ...(record.servedModel ? { servedModel: record.servedModel } : {}), ...(record.provider ? { provider: record.provider } : {}), measuredAt: record.at }),
7708
8690
  admitBudget: async (envs, unit) => tasks.admitExecutionEnvelopes(envs, peer, unit),
7709
8691
  ...(route ? { route } : {}),
7710
8692
  hubRoutes: () => activeRouting().hub_routes ?? {},
8693
+ routeEvidencePublic: boundedSafe,
8694
+ routeDecisionContext: () => ({ pii: contextPii(peer), private: turns.get(peer)?.private === true, excluded: reviewObserverHeld(peer) }),
7711
8695
  staySwitch: () => activeRouting(),
7712
8696
  onRoute: record => event({ type: "route", peer, ...record }),
7713
8697
  onAdvisor: record => event({ type: "advisor", peer, ...record }),
@@ -7741,11 +8725,13 @@ export async function startDaemon(opts: DaemonOptions) {
7741
8725
  maxSteps: config.local.max_steps,
7742
8726
  log,
7743
8727
  }) }) as LocalPeer;
8728
+ registerModelOwner(local);
7744
8729
  localObserverSessionIds.set(local, () => local.observerSessionId);
7745
8730
  ownedReviewInputReleasePeers.add(local);
7746
8731
  recoveryTaskPreface(peer);
7747
8732
  await ensurePreface(peer); startCurrent?.();
7748
8733
  executionOwners.set(peer, { owner: local, cwd: executionCwd });
8734
+ bindRecordOwner(local, executionCwd, () => local.observerSessionId);
7749
8735
  bus.add(local);
7750
8736
  startCurrent?.(); await local.start();
7751
8737
  return { ok: true, model: route ? `${route} (fallback ${routing.local.fixed_model})` : (args.model ?? routing.local.fixed_model) };
@@ -7764,6 +8750,7 @@ export async function startDaemon(opts: DaemonOptions) {
7764
8750
  if (selected !== "ask" && selected !== "ask-when-needed") return { ok: false, error: "Claude implementer refuses never-ask" };
7765
8751
  startCurrent?.();
7766
8752
  const implementer = adapter.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: selected, mcpServers: [], daemon: DAEMON_PORTS["claude-implementer"]({
8753
+ getModelOverride: () => modelSelection(peer),
7767
8754
  cwd: executionCwd, stateDir: opts.stateDir, projectRoot: opts.cwd, instanceId, server: SERVER_JS,
7768
8755
  factsHook: join(import.meta.dir, "..", "cli", "facts-hook.ts"), systemPrompt: sessionRoleContract(peer), mode: selected, watchdogMs: config.watchdog_ms, ...(declarations[peer]?.model ? { model: declarations[peer].model } : {}),
7769
8756
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, implementer, context, envs),
@@ -7818,7 +8805,7 @@ export async function startDaemon(opts: DaemonOptions) {
7818
8805
  if (!currentRoot()) throw new Error("Claude implementer startup admission changed");
7819
8806
  recoveryTaskPreface(peer); await ensurePreface(peer); startCurrent?.();
7820
8807
  if (!currentRoot()) throw new Error("Claude implementer startup admission changed");
7821
- executionOwners.set(peer, { owner: implementer, cwd: executionCwd }); bus.add(implementer);
8808
+ registerModelOwner(implementer); executionOwners.set(peer, { owner: implementer, cwd: executionCwd }); bus.add(implementer);
7822
8809
  return { ok: true };
7823
8810
  } catch (error) { await implementer.stop().catch(() => {}); throw error; }
7824
8811
  }
@@ -7831,6 +8818,7 @@ export async function startDaemon(opts: DaemonOptions) {
7831
8818
  const reviewPolicies = new Map<string, string>();
7832
8819
  startCurrent?.();
7833
8820
  const reviewer = adapter.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["reviewer-print"]({
8821
+ ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride && !adapter.modelOverride.acp ? { getModelOverride: () => modelSelection(peer) } : {}),
7834
8822
  backend, cwd: executionCwd,
7835
8823
  mcpConfig: JSON.stringify({ mcpServers: { "agent-hub": { command: process.execPath, args: ["run", SERVER_JS], env: toolEnv(peer, true) } } }),
7836
8824
  systemPrompt: sessionRoleContract(peer),
@@ -7897,7 +8885,7 @@ export async function startDaemon(opts: DaemonOptions) {
7897
8885
  return { ok: false, error: reason };
7898
8886
  }
7899
8887
  reviewerUnavailable.delete(peer);
7900
- executionOwners.set(peer, { owner: reviewer, cwd: executionCwd });
8888
+ registerModelOwner(reviewer); executionOwners.set(peer, { owner: reviewer, cwd: executionCwd });
7901
8889
  reviewerToolObservers.set(peer, (task, tool, refusal) => {
7902
8890
  try { if (bus.peers.get(peer) === reviewer) reviewer.recordToolTrace(task, { tool, ...(refusal === undefined ? {} : { refusal }) }); }
7903
8891
  catch { /* Diagnostics never change a host tool's result or authority. */ }
@@ -8012,7 +9000,7 @@ export async function startDaemon(opts: DaemonOptions) {
8012
9000
  function queueView(row: ReturnType<Bus["queueShow"]>, detail = false, publicOnly = false) {
8013
9001
  if (!row) return undefined;
8014
9002
  const originals = row.originals;
8015
- const privateDelivery = originals.some((env) => env.private || publicOnly && env.refs?.task && (()=>{const task=board.get(Number(env.refs!.task));return !task || tasks.isPii(task);})());
9003
+
8016
9004
  return {
8017
9005
  id: row.id, peer: row.peer, state: row.state, revision: row.revision,
8018
9006
  ...(row.failureCause ? { failureCause: row.failureCause } : {}),
@@ -8022,12 +9010,40 @@ export async function startDaemon(opts: DaemonOptions) {
8022
9010
  createdAt: row.createdAt, updatedAt: row.updatedAt,
8023
9011
  envelopeIds: originals.map((env) => env.id),
8024
9012
  important: originals.some((env) => env.priority === "important"),
8025
- ...(detail ? { messages: originals.map((env) => ({ id: env.id, from: env.from, priority: env.priority, kind: env.kind,
8026
- body: privateDelivery ? "[private: inspect the associated task with ahub task show]" : publicOnly && !tasks.publicMetadataText(env.body) ? "[withheld]" : sanitize(env.body),
8027
- })) } : {}),
9013
+ ...(detail ? { messages: publicDeliveryBodies(originals, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
8028
9014
  };
8029
9015
  }
8030
9016
 
9017
+ /** Separate from pull: failure here must never discard an already committed normal handout. */
9018
+ function inboxHeldRead(c: Client, current: () => boolean) {
9019
+ try {
9020
+ const peer = c.peer;
9021
+ if (!peer || !current() || contextPii(peer)) throw new Error("held inbox authority unavailable");
9022
+ const policy = config, configVersion = configRevision, boardVersion = board.statusRevision();
9023
+ const held = bus.heldInbox(peer);
9024
+ const launch = c.toolsOwner ? currentImplementerTools(c) : undefined;
9025
+ const rows = held.rows.map(row => {
9026
+ if (!current() || reviewOnlyPeer(peer) && row.originals.some(env => !reviewOnlyItem(peer, env))) throw new Error("held inbox scope unavailable");
9027
+ if (c.toolsOwner && (!launch || row.originals.some(env => (env.refs?.task === undefined ? implementerChatTask(peer) : Number(env.refs.task)) !== launch.task))) throw new Error("held inbox belongs to another task session");
9028
+ return { id: row.id, revision: row.revision, state: row.state, messages: publicDeliveryBodies(row.originals, {
9029
+ publicOnly: true, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); },
9030
+ publicMetadataText: text => tasks.publicMetadataText(text),
9031
+ }) };
9032
+ });
9033
+ // Screening may consult host ports. Revalidate the exact caller and current privacy before exposure.
9034
+ if (!current() || contextPii(peer) || config !== policy || configRevision !== configVersion || board.statusRevision() !== boardVersion) throw new Error("held inbox changed during projection");
9035
+ for (const row of held.rows) {
9036
+ if (reviewInputHeld(peer, row.originals)) {
9037
+ const owner = bus.peers.get(peer), active = ownedObserverInputs.get(peer);
9038
+ if (active && active.owner === owner) active.supersededByReviewInput = true;
9039
+ noteSteeredReviewInput(peer, row.originals); // RAM observation only: no ACK or durable handoff.
9040
+ }
9041
+ }
9042
+ if (!current() || contextPii(peer)) throw new Error("held inbox authority changed");
9043
+ return { count: held.count, rows, truncated: held.truncated, ...(held.unavailable ? { unavailable: true } : {}) };
9044
+ } catch { return { unavailable: true, next: "Held bodies were not read; inspect ahub queue list for this peer, then retry hub_inbox after authority or storage recovers." }; }
9045
+ }
9046
+
8031
9047
  let operationalViewCache: { board: number; config: number; routing: ReturnType<typeof activeRouting>; privacy: string; view: ReturnType<typeof operationalView> } | undefined;
8032
9048
  function publicOperationalView() {
8033
9049
  const revision=board.statusRevision(),routing=activeRouting(),privacy=JSON.stringify([config.pii?.paths??[],config.local.deny]);
@@ -8056,6 +9072,14 @@ export async function startDaemon(opts: DaemonOptions) {
8056
9072
  if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).slice(0, 128).filter(([key]) => /^[A-Za-z][A-Za-z0-9_]*$/.test(key)).map(([key, item]) => [key, publicReadValue(item, depth + 1)]));
8057
9073
  return null;
8058
9074
  }
9075
+ function sdlcSettingsView() {
9076
+ let file: ReturnType<typeof loadSdlc> | undefined;
9077
+ try { file = loadSdlc(opts.cwd, VERSION); } catch { /* unreadable file stays unknown */ }
9078
+ return {
9079
+ "sdlc.mode": { value: lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9080
+ "sdlc.required_checks": { value: lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9081
+ };
9082
+ }
8059
9083
  function publicSettingsView() {
8060
9084
  const view = settingsView();
8061
9085
  const rows = view.rows.flatMap(row => {
@@ -8080,7 +9104,7 @@ export async function startDaemon(opts: DaemonOptions) {
8080
9104
  ...(row.min !== undefined ? { min: row.min } : {}), ...(row.max !== undefined ? { max: row.max } : {}),
8081
9105
  ...(row.locked ? { locked: "read-only" } : {}), ...(opaque ? { withheld: true } : {}) }];
8082
9106
  });
8083
- return { rows, roster: rosterView().map(row => ({ peer: row.peer, on: row.on, startMode: row.startMode, state: row.state, queued: row.queued, tasks: row.tasks })), public: true, withheld: ["file", "source", "notes", "undo", "configEdit"] };
9107
+ return { rows, sdlc: Object.fromEntries(Object.entries(sdlcSettingsView()).map(([key, value]) => [key, publicReadValue(value)])), roster: rosterView().map(row => ({ peer: row.peer, on: row.on, startMode: row.startMode, state: row.state, queued: row.queued, tasks: row.tasks })), public: true, withheld: ["file", "source", "notes", "undo", "configEdit"] };
8084
9108
  }
8085
9109
  function publicReleaseShow(input: Record<string, any>) {
8086
9110
  const release = input.id !== undefined ? Number.isSafeInteger(input.id) && input.id > 0 ? board.release(input.id) : undefined
@@ -8260,6 +9284,20 @@ export async function startDaemon(opts: DaemonOptions) {
8260
9284
  const start = input?.view === "memory" && query && query.codeNeighbours === true && typeof query.node === "string" && query.node.startsWith("symbol:") && Buffer.byteLength(query.node) <= 512 ? query.node : undefined;
8261
9285
  const code = start ? await memoryCode([start]).catch(() => unavailableMemoryCodeOverlay()) : undefined;
8262
9286
  const snapshot = uiSnapshot(after, input, session);
9287
+ if (input?.visual !== undefined) {
9288
+ const record = visualRecord(input.visual);
9289
+ return { ...snapshot, visual: record ? visualView(record) : null };
9290
+ }
9291
+ if (input?.visualTask !== undefined) {
9292
+ const task = input.visualTask;
9293
+ return { ...snapshot, visuals: Number.isSafeInteger(task) && Number(task) > 0 ? visualList(Number(task)) : [] };
9294
+ }
9295
+ if (input?.visualAsset !== undefined) {
9296
+ const match = typeof input.visualAsset === "string" ? /^([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}):(before|after)$/.exec(input.visualAsset) : null;
9297
+ const record = match ? visualRecord(match[1]) : undefined;
9298
+ const file = record?.files.find(file => file.asset === input.visualAsset);
9299
+ return { ...snapshot, visualAsset: record && file ? { id: record.id, ...(record.task === undefined ? {} : { task: record.task }), from: record.from, created: record.created, file } : null };
9300
+ }
8263
9301
  if (code && "memory" in snapshot && snapshot.memory && typeof snapshot.memory === "object") {
8264
9302
  const published = currentMemoryCode(code), tier = query?.tier === "goals" ? "goals" : query?.tier === "short" ? "short" : "long";
8265
9303
  const search = typeof query?.q === "string" ? query.q.toLowerCase() : undefined;
@@ -8343,11 +9381,13 @@ export async function startDaemon(opts: DaemonOptions) {
8343
9381
  projectId,
8344
9382
  instanceId,
8345
9383
  attention: attentionStatus.attentionInput,
9384
+ ...runtimeModelProjection(),
8346
9385
  rooms: attentionStatus.rooms,
8347
9386
  pet,
8348
9387
  status: { peers: peerView, pendingRestart: allPendingRestart(), retainedConfig, taskWip: attentionStatus.taskWip, roleInfo: attentionStatus.roleInfo, ownerIsolation: attentionStatus.ownerIsolation, ownerIsolationNotes: attentionStatus.ownerIsolationNotes },
8349
9388
  boardCapabilities: { backlog: true },
8350
9389
  planningCapabilities: { enabled: true, wipPull: true, split: true },
9390
+ visuals: visualList(),
8351
9391
  // #1144: source metadata only, including private records; never expose origins or stored text.
8352
9392
  sources: sourceRegistry.list().map(({ id, kind, bytes, sha256, added_at }) => ({ id, kind, bytes, hashPrefix: sha256.slice(0, 12), added_at })),
8353
9393
  releases: tasks.releaseList(USER),
@@ -8360,6 +9400,10 @@ export async function startDaemon(opts: DaemonOptions) {
8360
9400
  ...(attentionStatus.taskWip[id] ? { wip: attentionStatus.taskWip[id]!.wip, wipLimit: attentionStatus.taskWip[id]!.wipLimit, wipBreakdown: { active: attentionStatus.taskWip[id]!.active, reviewWait: attentionStatus.taskWip[id]!.reviewWait, reserved: attentionStatus.taskWip[id]!.reserved } } : { wip: tasks.wip(id), wipLimit: tasks.wipLimit(id) }),
8361
9401
  activeTasks: boardTasks.filter(task => task.owner === id && ["in_progress", "changes_requested"].includes(task.state)).map(task => task.id),
8362
9402
  })),
9403
+ // #1221 T2 AC5: the advisory row set for the console's existing inbox. Codes and ids only, never a title or a note;
9404
+ // a private task's proposal is not in the list at all, and `off` or `shadow` adds no field, so an older page and a
9405
+ // console that never opted in see exactly what they saw before.
9406
+ ...(supervisionMode() === "advisory" ? { supervision: { mode: "advisory" as const, proposals: supervisionProposals.awaiting(USER).map(proposalView) } } : {}),
8363
9407
  tasks: boardTasks.map((task) => {
8364
9408
  const view = tasks.publicView(task);
8365
9409
  // Refs and history can themselves quote private text. The dashboard needs neither.
@@ -9169,6 +10213,16 @@ export async function startDaemon(opts: DaemonOptions) {
9169
10213
  if (!option || (definitionOf(req.peer)?.trust.hubSandboxed === true && option.kind !== "reject_once")) return bad;
9170
10214
  return pending.done(option.optionId, "dashboard") ? { ok: true } : { ok: false, error: "permission expired or already answered" };
9171
10215
  }
10216
+ case "supervision": {
10217
+ // #1221 T2 AC5: an advisory inbox row decides one proposal as the person, through the same fence the hub tool
10218
+ // uses (`decide`); the console supplies the verb and the id, never an actor, a task or an action.
10219
+ if (typeof a.id !== "string" || (a.verb !== "accept" && a.verb !== "dismiss")) return bad;
10220
+ if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding supervision decisions" };
10221
+ const decision = await supervisionProposals.decide(USER, a.id, a.verb);
10222
+ return decision.ok
10223
+ ? { ok: true, proposal: proposalView(decision.proposal), ...(decision.receipt ? { receipt: decision.receipt } : {}) }
10224
+ : { ok: false, error: decision.error };
10225
+ }
9172
10226
  case "send": {
9173
10227
  if (!text("body", 8000)) return bad;
9174
10228
  if (a.to !== undefined && (!Array.isArray(a.to) || a.to.length > 32 || a.to.some((id) => typeof id !== "string" || !PEER_ID.test(id) || !bus.knownPeers().includes(id) && membershipAllowed(id)))) return bad;
@@ -9222,6 +10276,14 @@ export async function startDaemon(opts: DaemonOptions) {
9222
10276
  }
9223
10277
  case "setting":
9224
10278
  return settingsSet(a.key, a.value, authority, a.confirm, a.now, a.reason);
10279
+ case "model_preview":
10280
+ case "model_confirm": {
10281
+ const current = () => session?.settings === true && session.liveTest !== true && typeof session.authorityId === "string"
10282
+ && typeof session.settingsUntil === "number" && session.settingsUntil > Date.now();
10283
+ if (!current()) return modelFailure("model changes require a current person settings session; reopen ahub ui --settings and preview again");
10284
+ return modelCommandSafe(a.action === "model_preview" ? { op: "preview", action: a.modelAction, peer: a.peer, model: a.model } : { op: "confirm", token: a.token },
10285
+ { source: "dashboard", scope: session!.authorityId!, expiresAt: session!.settingsUntil, current });
10286
+ }
9225
10287
  case "setting_undo":
9226
10288
  return settingsUndo(authority, a.confirm, a.now, a.reason, a.key, a.undoDigest);
9227
10289
  case "setting_preview":
@@ -9306,6 +10368,21 @@ export async function startDaemon(opts: DaemonOptions) {
9306
10368
  ? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
9307
10369
  };
9308
10370
  const incompatibleRecoveryTarget = () => {
10371
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_variants")) {
10372
+ try { if (board.hasGuidanceVariants()) return "target lacks guidance_variants; retained immutable variants require a supporting daemon; choose a target advertising guidance_variants"; }
10373
+ catch { return "guidance variant compatibility is unknown; inspect retained storage or choose a supporting target"; }
10374
+ }
10375
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("execution_lineage")) {
10376
+ try { if (board.hasExecutionReferences()) return "target lacks execution_lineage; retained declared references require a supporting daemon; choose a target advertising execution_lineage"; }
10377
+ catch { return "execution reference compatibility is unknown; inspect the retained store or choose a supporting target"; }
10378
+ }
10379
+ if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("model_overrides")) && modelOverrides.hasRecords()) return "target lacks model_overrides; retained runtime model choices require a supporting daemon; clear them with ahub model clear or choose a supporting target";
10380
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("visuals")) {
10381
+ try {
10382
+ if (visuals.hasRecords()) return "target lacks visuals; retained visual records require a supporting daemon; choose a target with visuals";
10383
+ if (rawVisualsPresent(opts.cwd)) return "target lacks visuals; explicit visuals configuration requires a supporting daemon; choose a target with visuals or remove the explicit configuration";
10384
+ } catch { return "visuals compatibility is unknown; the store or configuration could not be read; inspect them or choose a target with visuals"; }
10385
+ }
9309
10386
  if (config.specs.enabled && config.specs.review === "require" && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("design_specs"))) return "target lacks design_specs; specs.enabled is on and specs.review is require; use a supporting release or explicitly change specs.enabled/specs.review";
9310
10387
  if (board.hasConductorManualState() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("conductor_recovery"))) return "target lacks conductor_recovery; open conductor manual-assignment intent cannot be preserved";
9311
10388
  if (allExternalInstanceIds().length && (!Array.isArray(msg.targetFeatures) || !["external_adapter_instances", "external_adapter_modules", "peer_instances"].every(feature => msg.targetFeatures.includes(feature)))) return "target lacks external_adapter_instances or its module/instance prerequisites";
@@ -9915,9 +10992,9 @@ export async function startDaemon(opts: DaemonOptions) {
9915
10992
  }
9916
10993
  const committedSourceProof = c.role === "tools" && msg.t === "recovery_authority" && msg.op === "verify" && recoveryCommitted
9917
10994
  && msg.binding?.operationId === recoveryOperationId && msg.binding?.sourceInstanceId === instanceId;
9918
- if (stopping && !committedSourceProof && msg.t !== "status" && msg.t !== "kill" && !(c.role === "console" && msg.t === "native_hook_launch" && msg.op === "end")) return void reply({ ok: false, error: "hub is stopping" });
10995
+ if (stopping && !committedSourceProof && msg.t !== "status" && msg.t !== "kill" && !(c.role === "console" && msg.t === "native_hook_launch" && msg.op === "end")) return void reply({ ok: false, error: msg.t === "task" && (msg.op === "hub_visual" || msg.op === "hub_visual_show") ? visualOperational("stopping").message : "hub is stopping" });
9919
10996
  if (c.role === "peer" && c.detachedByPerson) return void reply({ t: msg.t, ok: false, error: "detached by the person; stop using this peer connection and tell the person; inspect ahub status before opening a fresh session" });
9920
- if (c.role !== "console" && c.peer && !membershipAllowed(c.peer)) return void reply({ ok: false, error: `${c.peer} is off roster` });
10997
+ if (c.role !== "console" && c.peer && !membershipAllowed(c.peer)) return void reply({ ok: false, error: msg.t === "task" && (msg.op === "hub_visual" || msg.op === "hub_visual_show") ? visualOperational("membership").message : `${c.peer} is off roster` });
9921
10998
  if (c.role === "peer" && c.peer) {
9922
10999
  const currentPeer = bus.peers.get(c.peer);
9923
11000
  if (c.standbyId && currentPeer?.ownsSocket?.(sock) !== true) return void reply({ t: msg.t, ok: false, error: "peer is standing by; a person must request takeover" });
@@ -10118,19 +11195,21 @@ export async function startDaemon(opts: DaemonOptions) {
10118
11195
  return void reply({ ok: true });
10119
11196
  }
10120
11197
  case "inbox": {
11198
+ if (msg.peer !== undefined && msg.peer !== c.peer) return void reply({ ok: false, error: "hub_inbox reads only your authenticated peer; omit peer and ask the person to inspect another peer's queue" });
10121
11199
  if (stopping || recoveryActive()) return void reply({ ok: false, error: "the hub is not serving inbox reads now (recovery or shutdown); run ahub status, then call hub_inbox again after it recovers" });
10122
11200
  if (c.toolsOwner) {
10123
11201
  const peer = c.peer!, current = captureImplementerTools(c), launch = currentImplementerTools(c);
11202
+ const heldRead = () => inboxHeldRead(c, current);
10124
11203
  try {
10125
11204
  // Inspect the still-pending batch before pull commits/removes it: private work never reaches this native child.
10126
11205
  const pending = bus.pendingEnvelopes(peer);
10127
11206
  if (!current() || pending.some(env => { const task = env.refs?.task === undefined ? undefined : board.get(Number(env.refs.task)); return env.private || contextPii(peer) || !!task && tasks.isPii(task); })) return void reply({ ok: false, error: "private inbox delivery refused" });
10128
11207
  if (!launch || pending.some(env => (env.refs?.task === undefined ? implementerChatTask(peer) : Number(env.refs.task)) !== launch.task)) return void reply({ ok: false, error: "inbox delivery belongs to another task session" });
10129
11208
  const envs = bus.pull(peer, { allowNeedsReviewHold: true });
10130
- if (!envs) return void reply({ ok: false, error: queueHold(peer) ?? "delivery held", held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10131
- return void reply({ ok: true, envs, held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
11209
+ if (!envs) return void reply({ ok: false, error: queueHold(peer) ?? "delivery held", held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
11210
+ return void reply({ ok: true, envs, held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10132
11211
  } catch (error) {
10133
- if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
11212
+ if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10134
11213
  return void reply({ ok: false, error: "delivery journal unavailable" });
10135
11214
  }
10136
11215
  }
@@ -10138,6 +11217,8 @@ export async function startDaemon(opts: DaemonOptions) {
10138
11217
  // Pull and push share holds and journal settlement; work read here is completed, never pushed again.
10139
11218
  const peer = c.peer ? bus.peers.get(c.peer) : undefined;
10140
11219
  if (c.role !== "peer" || !isWsPeer(peer) || !peer.owns(sock)) return void reply({ ok: false, error: "not attached to the hub yet; retry hub_inbox in a moment" });
11220
+ const current = () => sock.data === c && sock.readyState === WebSocket.OPEN && c.role === "peer" && c.peer === peer.id && membershipAllowed(peer.id) && bus.peers.get(peer.id) === peer && peer.owns(sock) && !stopping && !recoveryActive();
11221
+ const heldRead = () => inboxHeldRead(c, current);
10141
11222
  try {
10142
11223
  const envs = bus.pull(peer.id, { allowNeedsReviewHold: true });
10143
11224
  if (!envs) {
@@ -10149,7 +11230,7 @@ export async function startDaemon(opts: DaemonOptions) {
10149
11230
  ?? (bus.isRecoveryHeld ? "recovery is holding deliveries" : undefined)
10150
11231
  ?? (bus.stateOf(peer.id) === "paused" ? pauseReason(peer.id) : undefined);
10151
11232
  const error = blockingCause ?? (accepted ? "an accepted delivery is awaiting your explicit confirmation" : "delivery held");
10152
- return void reply({ ok: false, error, held, waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
11233
+ return void reply({ ok: false, error, held, heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
10153
11234
  }
10154
11235
  peer.lastInboxAt = Date.now();
10155
11236
  let polling: ReturnType<InboxPolling["read"]>;
@@ -10160,9 +11241,9 @@ export async function startDaemon(opts: DaemonOptions) {
10160
11241
  } catch { polling = undefined; } // The pull already completed: advice must never discard its envelopes.
10161
11242
  writeStatus();
10162
11243
  if (envs.length) log(`${peer.id} read ${envs.length} queued message(s) through hub_inbox`);
10163
- return void reply({ ok: true, envs, held: inboxHeldMetadata(peer.id, true), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id), ...(polling ? { pollingAdvice: { count: polling.count, minutes: polling.minutes } } : {}) });
11244
+ return void reply({ ok: true, envs, held: inboxHeldMetadata(peer.id, true), heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id), ...(polling ? { pollingAdvice: { count: polling.count, minutes: polling.minutes } } : {}) });
10164
11245
  } catch (error) {
10165
- if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer.id, true), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
11246
+ if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer.id, true), heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
10166
11247
  return void reply({ ok: false, error: "delivery journal unavailable" });
10167
11248
  }
10168
11249
  }
@@ -10288,7 +11369,7 @@ export async function startDaemon(opts: DaemonOptions) {
10288
11369
  }
10289
11370
  if (!sourcePackageDigest || plan.sourceDigest !== sourcePackageDigest && (plan.kind !== "upgrade" || plan.sourceDigest !== raw.targetDigest)) throw new RecoveryAuthorityError();
10290
11371
  current();
10291
- if (!event({ type: "agent_cli", peer: c.peer!, command: raw.kind, refused: false })) throw new RecoveryAuthorityError();
11372
+ if (!event({ type: "agent_cli", peer: c.peer!, command: raw.kind, refused: false, ...taskAttribution(c.peer!) })) throw new RecoveryAuthorityError();
10292
11373
  current();
10293
11374
  issueConductorRecoveryAuthority(opts.stateDir, expected, fresh);
10294
11375
  } else {
@@ -10376,13 +11457,24 @@ export async function startDaemon(opts: DaemonOptions) {
10376
11457
  }
10377
11458
  case "native_hook_launch": {
10378
11459
  if (c.role !== "console" || typeof msg.peer !== "string" || !definitionOf(msg.peer)?.hooks?.factsHook) return void reply({ ok: false, error: "managed native launch requires the person and a supported hook adapter" });
10379
- if (msg.op === "end") return void reply({ ok: nativeHookLaunches.end(msg.peer, msg.launchId) });
11460
+ if (msg.op === "end") {
11461
+ const launch = nativeHookLaunches.get(msg.peer, msg.launchId);
11462
+ if (!launch) return void reply({ ok: false });
11463
+ const run = runs.get(msg.peer);
11464
+ if (run) {
11465
+ if (budget.record(msg.peer)) completionStore.dropRun(run.runTurn);
11466
+ else completionDone(msg.peer, run, "interrupted");
11467
+ runs.close(msg.peer);
11468
+ }
11469
+ return void reply({ ok: nativeHookLaunches.end(msg.peer, msg.launchId) });
11470
+ }
10380
11471
  if (recoveryActive() || stopping) return void reply({ ok: false, error: "recovery or shutdown is holding native launches" });
10381
11472
  if (!membershipAllowed(msg.peer)) return void reply({ ok: false, error: "peer is off roster" });
10382
11473
  if (msg.op !== "begin") return void reply({ ok: false, error: "unknown native launch operation" });
11474
+ if (msg.nativeHome !== undefined && (typeof msg.nativeHome !== "string" || !isAbsolute(msg.nativeHome) || msg.nativeHome.length > 4096 || /[\u0000-\u001f\u007f]/.test(msg.nativeHome))) return void reply({ ok: false, error: "native home must be an absolute control-free path" });
10383
11475
  const owner = bus.peers.get(msg.peer);
10384
11476
  if (owner && owner.state !== "offline") return void reply({ ok: false, error: "native peer is already attached; end it in its terminal first" });
10385
- try { return void reply({ ok: true, launchId: nativeHookLaunches.begin(msg.peer, sock).id, instanceId }); }
11477
+ try { return void reply({ ok: true, launchId: nativeHookLaunches.begin(msg.peer, sock, typeof msg.nativeHome === "string" ? msg.nativeHome : undefined).id, instanceId }); }
10386
11478
  catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
10387
11479
  }
10388
11480
  case "native_facts": {
@@ -10391,49 +11483,151 @@ export async function startDaemon(opts: DaemonOptions) {
10391
11483
  const launch = nativeHookLaunches.get(peer, msg.nativeLaunchId);
10392
11484
  const native = typeof msg.event === "string" ? port.decode(msg.event, msg.payload) : undefined;
10393
11485
  if (!launch || !native || !native.workspacePaths.every(root => { try { return realPath(root) === realPath(opts.cwd); } catch { return false; } })) return void reply({ ok: false });
11486
+ if (launch.home && native.transcriptPath !== join(launch.home, "session_index.jsonl")) return void reply({ ok: false });
10394
11487
  if (launch.session && launch.session !== native.sessionId) return void reply({ ok: false });
10395
11488
  launch.session = native.sessionId;
10396
11489
  const owner = bus.peers.get(peer);
10397
11490
  if (!isWsPeer(owner) || owner.state === "offline" && !owner.claiming) return void reply({ ok: false });
10398
11491
  if (launch.generation && launch.generation !== owner.sessionGeneration) return void reply({ ok: false });
10399
11492
  launch.generation = owner.sessionGeneration;
11493
+ launch.transcript = native.transcriptPath;
11494
+ const callStarted = performance.now();
11495
+ const tally = () => tallyHook(peer, callStarted, msg.startedMs);
10400
11496
  const current = () => !stopping && nativeHookLaunches.get(peer, msg.nativeLaunchId) === launch && bus.peers.get(peer) === owner && owner.sessionGeneration === launch.generation && owner.state !== "offline";
10401
11497
  // Preserve the start baseline at observation, even if native output is flushed before recall allows attach.
10402
- const readback = port.read(native.sessionId, native.transcriptPath);
11498
+ // Skip transcript I/O on PostToolUse, PostInvocation, Stop, and active-turn PreToolUse with no pending fact offers (#1280).
11499
+ const needsBaseline = (native.event === "PreInvocation" || native.event === "PreToolUse") && (!launch.active || native.event === "PreInvocation" && native.invocation === 0)
11500
+ || native.event === "TurnStarted" || native.event === "Stop" || native.event === "StopFailure" || native.event === "Interrupt";
11501
+ const needsAck = factsOn() && (native.event === "SessionStart" || native.event === "PreInvocation" || native.event === "PreToolUse" && factsFor(peer).pending(peer).length > 0);
11502
+ const since = launch.transcriptPath === native.transcriptPath && launch.transcriptOffset !== undefined ? { sinceOffset: launch.transcriptOffset } : {};
11503
+ const readback: ReturnType<typeof port.read> = needsBaseline
11504
+ ? port.read(native.sessionId, native.transcriptPath, since)
11505
+ : needsAck
11506
+ ? port.read(native.sessionId, native.transcriptPath, { completion: false, ...since })
11507
+ : { factIds: [] };
11508
+ // ponytail: an unacknowledged fact row followed by >4 MiB of output before the next readback hits the 4 MiB lookback cap in readAgyTranscript.
11509
+ const acknowledge = (read: ReturnType<typeof port.read>, turnCtx?: { hubTurnId?: string; baseline: number; attribution: TaskAttribution }) => {
11510
+ for (const u of read.usage ?? []) {
11511
+ if (agyNativeUsageSeen.has(u.id)) continue;
11512
+ agyNativeUsageSeen.add(u.id);
11513
+ const producedByTurn = !!turnCtx && u.index > turnCtx.baseline;
11514
+ const attr: TaskAttribution = producedByTurn ? turnCtx.attribution : { attribution: "unattributed" };
11515
+ if (u.totalTokens > 0) {
11516
+ if (noQuotaPeer(peer)) hubTokenWindow(peer).add(Date.now(), Math.round(u.totalTokens));
11517
+ const supervisionTurn = supervisionTurns.get(peer);
11518
+ if (producedByTurn && supervisionTurn && turnCtx.hubTurnId && supervisionTurn.id === turnCtx.hubTurnId) {
11519
+ supervisionTurn.tokens = (supervisionTurn.tokens ?? 0) + u.totalTokens;
11520
+ }
11521
+ event({ type: "tokens", peer, n: u.totalTokens, ...attr });
11522
+ const openTurn = turns.get(peer);
11523
+ if (producedByTurn && openTurn && turnCtx.hubTurnId && openTurn.id === turnCtx.hubTurnId) {
11524
+ openTurn.tokens += u.totalTokens;
11525
+ }
11526
+ }
11527
+ event({ type: "usage", peer, source: "agy_transcript", id: u.id, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens, totalTokens: u.totalTokens, ...attr, ...(u.at ? { measuredAt: u.at } : {}) });
11528
+ }
11529
+ if (factsOn()) {
11530
+ factSession(peer, native.sessionId);
11531
+ for (const id of read.factIds) acked(peer, id, "native-hook");
11532
+ }
11533
+ if (read.size !== undefined && read.scannedFrom !== undefined) {
11534
+ const prev = launch.transcriptPath === native.transcriptPath ? (launch.transcriptOffset ?? 0) : 0;
11535
+ if (read.scannedFrom <= prev) {
11536
+ launch.transcriptPath = native.transcriptPath;
11537
+ launch.transcriptOffset = read.size;
11538
+ }
11539
+ }
11540
+ };
10403
11541
  const apply = () => {
10404
11542
  if (!current()) return void reply({ ok: false });
10405
- if (factsOn()) { factSession(peer, native.sessionId); for (const id of readback.factIds) acked(peer, id, "native-hook"); }
10406
- if (native.event === "PreInvocation" || native.event === "PreToolUse") {
10407
- if (!launch.active || native.event === "PreInvocation" && native.invocation === 0) { launch.active = true; launch.turn = crypto.randomUUID(); launch.baseline = readback.completion?.index ?? -1; }
11543
+ if (native.event === "TurnStarted") {
11544
+ const started = readback.started;
11545
+ if (!started) return void reply({ ok: false });
11546
+ if (launch.active && launch.turn === started.id) return void reply({ ok: true });
11547
+ if (readback.completion && readback.completion.index >= started.index) return void reply({ ok: true });
11548
+ launch.active = true; launch.turn = started.id; launch.baseline = started.index - 1;
11549
+ pendingNativePerson.delete(peer);
11550
+ if (started.origin === "user") pendingNativePerson.add(peer);
10408
11551
  activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
10409
11552
  }
10410
- if (native.event === "Stop") {
10411
- if (!launch.active || !native.fullyIdle || native.terminationReason !== "NO_TOOL_CALL") return void reply({ ok: false });
10412
- // Native output can be flushed after its Stop command returns. Acknowledge observation, then wait for
10413
- // a fresh completion row while the same launcher/session/socket generation still owns the turn.
10414
- const turn = launch.turn, baseline = launch.baseline ?? -1;
11553
+ owner.bindNativeSession(native.sessionId);
11554
+ const startsTurn = (native.event === "PreInvocation" || native.event === "PreToolUse") && (!launch.active || native.event === "PreInvocation" && native.invocation === 0);
11555
+ if (native.event === "PreInvocation" || native.event === "PreToolUse") {
11556
+ if (startsTurn) {
11557
+ // Credit any leftover rows read at turn start to the preceding turn that produced them, never the new turn.
11558
+ acknowledge(readback, agyTurnContext.get(launch));
11559
+ launch.active = true; launch.turn = crypto.randomUUID(); launch.baseline = readback.completion?.index ?? -1;
11560
+ activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
11561
+ agyTurnContext.set(launch, { hubTurnId: turns.get(peer)?.id, baseline: launch.baseline, attribution: taskAttribution(peer) });
11562
+ } else {
11563
+ activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
11564
+ const activeCtx = { hubTurnId: turns.get(peer)?.id ?? agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: taskAttribution(peer) };
11565
+ agyTurnContext.set(launch, activeCtx);
11566
+ acknowledge(readback, activeCtx);
11567
+ }
11568
+ } else if (native.event !== "Stop") {
11569
+ const activeCtx = launch.active ? { hubTurnId: turns.get(peer)?.id ?? agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: taskAttribution(peer) } : agyTurnContext.get(launch);
11570
+ if (launch.active && activeCtx) agyTurnContext.set(launch, activeCtx);
11571
+ acknowledge(readback, activeCtx);
11572
+ }
11573
+ const stopCtx = { hubTurnId: turns.get(peer)?.id ?? agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: taskAttribution(peer) };
11574
+ agyTurnContext.set(launch, stopCtx);
11575
+ if (native.event === "Stop" && native.terminationReason !== undefined) {
11576
+ if (!launch.active || native.fullyIdle !== true) return void reply({ ok: false });
11577
+ const terminalReason = ({ USER_CANCELED: "user_canceled", ERROR: "error", MAX_INVOCATIONS: "max_invocations", MAX_FORCED_INVOCATIONS: "max_forced_invocations", MAX_TOKEN_BUDGET_EXCEEDED: "max_token_budget_exceeded", TERMINAL_STEP_TYPE: "terminal_step_type", TERMINAL_CUSTOM_HOOK: "terminal_custom_hook" } as const)[native.terminationReason];
11578
+ if (terminalReason) {
11579
+ acknowledge(port.read(native.sessionId, native.transcriptPath, { completion: false, ...since }), stopCtx);
11580
+ launch.active = false; turnEnded.set(peer, Date.now()); tasks.cohorts.turnEnded(peer);
11581
+ tally(); emitHookStats(peer);
11582
+ event({ type: "native_turn_end", peer, reason: terminalReason }); owner.nativeStopped(native.sessionId);
11583
+ // #1054: pull-only agy opens no run (`settles(peer)` is false); if a future native-hook peer does, settle an open run by its closed reason.
11584
+ try {
11585
+ const run = runs.get(peer);
11586
+ if (run) {
11587
+ if (terminalReason === "user_canceled") { completionDone(peer, run, "interrupted"); runs.close(peer); }
11588
+ else { runs.note(peer, terminalReason === "error" || terminalReason === "terminal_step_type" || terminalReason === "terminal_custom_hook" ? { failed: true } : { limit: true }); runs.signalled(peer); settleCheck(peer); }
11589
+ }
11590
+ } catch { log(`completion settle for ${peer} failed`); }
11591
+ return void reply({ ok: true });
11592
+ }
11593
+ if (native.terminationReason !== "NO_TOOL_CALL") return void reply({ ok: false });
11594
+ tally();
11595
+ }
11596
+ if (native.event === "Stop" || native.event === "StopFailure" || native.event === "Interrupt") {
11597
+ if (!launch.active || native.event === "Stop" && native.terminationReason !== undefined && native.fullyIdle !== true) return void reply({ ok: false });
11598
+ // A hook is only the candidate. The final native turn and prompt rows, correlated by id and reason, are the completion evidence.
11599
+ const turn = launch.turn, baseline = launch.baseline ?? -1, expected = native.event === "StopFailure" ? "failed" : native.event === "Interrupt" ? "cancelled" : "completed";
10415
11600
  reply({ ok: true, pending: true });
10416
11601
  void (async () => {
10417
11602
  const deadline = Date.now() + 2000;
10418
11603
  let delay = 5;
10419
- // ponytail: an unverified Stop may re-read up to 4 MiB per poll within this 2 s wait.
10420
- // Upgrade: cache unchanged transcript evidence within the wait.
11604
+ let lastStat: { size: number; mtimeMs: number } | undefined;
10421
11605
  while (current() && launch.active && launch.turn === turn) {
10422
- const completion = port.read(native.sessionId, native.transcriptPath).completion;
10423
- if (completion && completion.index > baseline && completion.id !== launch.completed) {
10424
- launch.completed = completion.id; launch.active = false;
10425
- turnEnded.set(peer, Date.now()); nativeCompletedAt.set(peer, Date.now()); tasks.cohorts.turnEnded(peer);
10426
- event({ type: "native_turn_end", peer, id: completion.id }); owner.nativeStopped(native.sessionId);
10427
- try { if (runs.get(peer)) { runs.signalled(peer); settleCheck(peer); } } catch { log(`completion settle for ${peer} failed`); } // #1054: the verified native Stop
11606
+ const pollSince = launch.transcriptPath === native.transcriptPath && launch.transcriptOffset !== undefined ? { sinceOffset: launch.transcriptOffset } : {};
11607
+ const polled = port.read(native.sessionId, native.transcriptPath, { ...(lastStat ? { unchanged: lastStat } : {}), ...pollSince });
11608
+ if (polled.size !== undefined && polled.mtimeMs !== undefined) lastStat = { size: polled.size, mtimeMs: polled.mtimeMs };
11609
+ acknowledge(polled, stopCtx);
11610
+ const completion = polled.completion;
11611
+ if (completion && completion.index > baseline && completion.id !== launch.completed && (completion.reason ?? "completed") === expected) {
11612
+ completeNativeTurn(peer, launch, completion);
11613
+ emitHookStats(peer);
10428
11614
  return;
10429
11615
  }
10430
- if (Date.now() >= deadline) { notify(`${peer}: native completion could not be verified; it stays busy until a verified turn end or detach`); return; }
11616
+ if (Date.now() >= deadline) { settleCheck(peer); emitHookStats(peer); notify(`${peer}: native completion could not be verified; it stays busy until a verified turn end or detach`); return; }
10431
11617
  await Bun.sleep(delay); delay = Math.min(50, delay * 2);
10432
11618
  }
10433
11619
  })().catch(() => log("managed native completion unavailable"));
10434
11620
  return;
10435
11621
  }
10436
- const offered = factsOn() && (native.event === "PreInvocation" || native.event === "SessionStart") ? offerFor(peer, native.toolUseId ?? `${native.sessionId}:invocation`) : undefined;
11622
+ if (native.event === "TaskStarted") activeAt.set(peer, Date.now());
11623
+ if (native.event === "TaskStarted" || native.event === "Notification") { nativeBackgroundBackoff.delete(peer); settleCheck(peer); }
11624
+ queueMicrotask(tally);
11625
+ const offeredFacts = factsOn() && (native.event === "PreInvocation" || native.event === "SessionStart") ? offerFor(peer, native.toolUseId ?? `${native.sessionId}:invocation`) : undefined;
11626
+ // #1280 P2: agy is pull-only, so a model boundary is the one place the hub can tell it mail waits. Counts only, never a body or sender.
11627
+ const modelBoundary = native.event === "PreInvocation" || native.event === "SessionStart";
11628
+ const waiting = bus.queued(peer), important = bus.queuedImportant(peer);
11629
+ const inboxHint = modelBoundary && waiting ? `[agent-hub: ${waiting} message(s) waiting${important ? ` (${important} important)` : ""}; call hub_inbox]` : undefined;
11630
+ const offered = offeredFacts || inboxHint ? { ...(offeredFacts ?? {}), text: [offeredFacts?.text, inboxHint].filter(Boolean).join("\n") } : undefined;
10437
11631
  // The decoded native read (agy view_file or read_file, as `Read`) is a peer fact: its target is observed before it runs and the
10438
11632
  // view moves after it. Nothing is offered here: agy's hook encodes an offer only on SessionStart/PreInvocation.
10439
11633
  if (factsOn() && native.event === "PreToolUse") factsFor(peer).preTool(peer, native.toolUseId, native.tool, native.input);
@@ -10460,11 +11654,7 @@ export async function startDaemon(opts: DaemonOptions) {
10460
11654
  const toolUseId = typeof msg.toolUseId === "string" && msg.toolUseId ? msg.toolUseId.slice(0, 128) : undefined;
10461
11655
  const sessionId = typeof msg.sessionId === "string" && msg.sessionId ? msg.sessionId.slice(0, 128) : undefined;
10462
11656
  const callStarted = performance.now();
10463
- const tally = (peer: PeerId) => {
10464
- const st = hookStats.get(peer) ?? { n: 0, startupMs: 0, hubMs: 0, maxStartupMs: 0 };
10465
- const startup = typeof msg.startedMs === "number" && Number.isFinite(msg.startedMs) ? Math.max(0, msg.startedMs) : 0;
10466
- hookStats.set(peer, { n: st.n + 1, startupMs: st.startupMs + startup, hubMs: st.hubMs + (performance.now() - callStarted), maxStartupMs: Math.max(st.maxStartupMs, startup) });
10467
- };
11657
+ const tally = (peer: PeerId) => tallyHook(peer, callStarted, msg.startedMs);
10468
11658
  try {
10469
11659
  const peer = c.peer;
10470
11660
  if (definitionOf(peer)?.start.daemonPort === "claude-implementer") {
@@ -10539,10 +11729,7 @@ export async function startDaemon(opts: DaemonOptions) {
10539
11729
  event({ type: "native_turn_end", peer, id });
10540
11730
  try { if (runs.get(peer)) { runs.signalled(peer); settleCheck(peer); } } catch { log(`completion settle for ${peer} failed`); } // #1054: the verified native Stop
10541
11731
  }
10542
- turnEnded.set(peer, Date.now()); tasks.cohorts.turnEnded(peer); tally(peer);
10543
- const st = hookStats.get(peer)!;
10544
- event({ type: "hook_stats", peer, n: st.n, startupMs: Math.round(st.startupMs), hubMs: Math.round(st.hubMs), maxStartupMs: Math.round(st.maxStartupMs) });
10545
- hookStats.delete(peer);
11732
+ turnEnded.set(peer, Date.now()); tasks.cohorts.turnEnded(peer); tally(peer); emitHookStats(peer);
10546
11733
  if (id && nativePeer) nativePeer.nativeStopped(sessionId!);
10547
11734
  if (factsOn()) { factSession(peer, sessionId); readbacks(peer, claudeTranscript(sessionId, msg.transcriptPath, peer)); }
10548
11735
  };
@@ -10680,6 +11867,35 @@ export async function startDaemon(opts: DaemonOptions) {
10680
11867
  }
10681
11868
  return;
10682
11869
  }
11870
+ if (msg.op === "adopt-merge") {
11871
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer ? c.peer : undefined;
11872
+ if (!asker) return void reply({ ok: false, error: "only the person or the current configured conductor may adopt a merge; ask the person to run ahub sdlc adopt-merge" });
11873
+ let actorCurrent: () => void;
11874
+ const externalOwner = c.externalOwner;
11875
+ try {
11876
+ const sessionCurrent = c.role === "console" ? () => {
11877
+ if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed");
11878
+ } : operationalCurrent(sock);
11879
+ actorCurrent = () => {
11880
+ sessionCurrent();
11881
+ if (externalOwner && !currentExternalTools(c, true)) throw new Error("actor execution root changed");
11882
+ sessionCurrent(); // A fresh execution-root probe can service callbacks before it returns.
11883
+ if (c.peer !== (asker === USER ? undefined : asker) || c.externalOwner !== externalOwner) throw new Error("actor session changed");
11884
+ };
11885
+ actorCurrent();
11886
+ }
11887
+ catch { return void reply({ ok: false, error: "current person or configured conductor session unavailable; reconnect the conductor or ask the person to run ahub sdlc adopt-merge" }); }
11888
+ const fence = () => {
11889
+ try { actorCurrent(); } catch { return "person or conductor session changed; reconnect and retry ahub sdlc adopt-merge"; }
11890
+ return recoveryActive() || stopping || c.peer && turns.get(c.peer)?.private ? "recovery, shutdown or a private turn holds adoption; retry ahub sdlc adopt-merge after it ends" : undefined;
11891
+ };
11892
+ taskOpsInFlight++;
11893
+ void tasks.adoptMerge(asker, msg.id, msg.pr, fence).then(
11894
+ result => reply({ ok: true, ...result }),
11895
+ (error: Error) => reply({ ok: false, error: sanitize(error.message) }),
11896
+ ).finally(() => { taskOpsInFlight--; });
11897
+ return;
11898
+ }
10683
11899
  if (msg.op === "merge") {
10684
11900
  // #786 T1: the person or the one configured conductor asks for a guarded merge. Every request gets a reply, a refusal included.
10685
11901
  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;
@@ -10937,7 +12153,7 @@ export async function startDaemon(opts: DaemonOptions) {
10937
12153
  case "ui_snapshot":
10938
12154
  if (c.role !== "console") return void reply({ ok: false, error: "ui_snapshot is a console command" });
10939
12155
  if (!Number.isSafeInteger(msg.after ?? 0) || (msg.after ?? 0) < 0) return void reply({ ok: false, error: "invalid cursor" });
10940
- void uiMemorySnapshot(msg.after ?? 0, msg.memory !== undefined || msg.reviewRefresh === true || dashboardView(msg.view) ? { ...(msg.memory !== undefined ? { memory: msg.memory } : {}), ...(msg.reviewRefresh === true && msg.reviewTask !== undefined ? { reviewTask: msg.reviewTask, reviewRefresh: true } : {}), ...(dashboardView(msg.view) ? { view: msg.view } : {}) } : undefined).then(value => reply(value), () => reply({ ok: false, error: "memory view unavailable" }));
12156
+ void uiMemorySnapshot(msg.after ?? 0, msg.memory !== undefined || msg.reviewRefresh === true || dashboardView(msg.view) || msg.visual !== undefined || msg.visualTask !== undefined || msg.visualAsset !== undefined ? { ...(msg.visual !== undefined ? { visual: msg.visual } : {}), ...(msg.visualTask !== undefined ? { visualTask: msg.visualTask } : {}), ...(msg.visualAsset !== undefined ? { visualAsset: msg.visualAsset } : {}), ...(msg.memory !== undefined ? { memory: msg.memory } : {}), ...(msg.reviewRefresh === true && msg.reviewTask !== undefined ? { reviewTask: msg.reviewTask, reviewRefresh: true } : {}), ...(dashboardView(msg.view) ? { view: msg.view } : {}) } : undefined).then(value => reply(value), () => reply({ ok: false, error: "memory view unavailable" }));
10941
12157
  return;
10942
12158
  case "ui_action":
10943
12159
  if (c.role !== "console") return void reply({ ok: false, error: "ui_action is a console command" });
@@ -10956,12 +12172,55 @@ export async function startDaemon(opts: DaemonOptions) {
10956
12172
  if (c.role !== "console") return void reply({ ok: false, error: "autonomy is a person-only command; run ahub autonomy in a person's terminal" });
10957
12173
  void autonomyCommand(msg.action, msg.environment, msg.confirmed, msg.confirmation).then(reply, () => reply({ ok: false, error: "project autonomy could not be changed" }));
10958
12174
  return;
12175
+ case "guidance_list":
12176
+ case "guidance_show":
12177
+ case "guidance_create":
12178
+ case "guidance_withdraw": {
12179
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12180
+ if (!actor) return void reply({ ok: false, error: "guidance is unavailable for this caller; use an authorized current project session" });
12181
+ const { t: _t, rid: _rid, ...input } = msg;
12182
+ const ownedCurrent = c.toolsOwner ? captureImplementerTools(c) : undefined;
12183
+ const current = () => {
12184
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || role === "tools" && c.peer !== actor || stopping)
12185
+ throw new PreEffectToolRefusal("guidance caller changed; reconnect in the current project session");
12186
+ if (c.externalOwner && !currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("guidance runtime owner changed; reconnect before retrying");
12187
+ };
12188
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
12189
+ if (msg.t === "guidance_list" || msg.t === "guidance_show") return void reply(guidanceRead(actor, msg.t === "guidance_list" ? "list" : "show", input));
12190
+ const op = msg.t === "guidance_create" ? "hub_guidance_create" : "hub_guidance_withdraw";
12191
+ void childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => taskOp(actor, op, input)).then(
12192
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }); } },
12193
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }));
12194
+ return;
12195
+ }
12196
+ case "lineage_show":
12197
+ case "lineage_link": {
12198
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12199
+ if (!actor) return void reply({ ok: false, error: "execution lineage is unavailable for this caller; use an authorized project session" });
12200
+ const { t: _t, rid: _rid, ...input } = msg;
12201
+ const ownedCurrent = c.toolsOwner ? captureImplementerTools(c) : undefined;
12202
+ const current = () => {
12203
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || (role === "tools" && c.peer !== actor) || stopping) throw new PreEffectToolRefusal("execution lineage caller changed; reconnect and retry");
12204
+ if (c.externalOwner && !currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("execution lineage owner changed; reconnect in the current project session");
12205
+ };
12206
+ const op = msg.t === "lineage_show" ? "hub_lineage_show" : "hub_lineage_link";
12207
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
12208
+ // A pure read is checked and serialized in this stack, without a new policy-change await.
12209
+ if (op === "hub_lineage_show") return void reply(executionLineageRead(actor, input));
12210
+ void childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => taskOp(actor, op, input)).then(
12211
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "execution lineage caller changed; reconnect and retry" }); } },
12212
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "execution lineage unavailable; inspect the project task and retry" }));
12213
+ return;
12214
+ }
12215
+ case "model":
12216
+ if (c.role !== "console") return void reply(modelFailure("model overrides are person-only; run ahub model in a person's terminal"));
12217
+ return void reply(modelCommandSafe(msg, { source: "cli", scope: c, current: () => c.authed === true && !c.closed && c.role === "console" && sock.readyState === WebSocket.OPEN }));
10959
12218
  case "settings_get":
10960
12219
  if (c.role !== "console") {
10961
12220
  try { const current = publicReadCurrent(sock); current(); const view = publicSettingsView(); current(); return void reply({ ok: true, ...view }); }
10962
12221
  catch { return void reply({ ok: false, error: "public settings read unavailable for this caller" }); }
10963
12222
  }
10964
- return void reply({ ok: true, ...settingsView(), roster: rosterView(), configEdit: (() => { const view = configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
12223
+ return void reply({ ok: true, ...settingsView(), sdlc: sdlcSettingsView(), roster: rosterView(), configEdit: (() => { const view = configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
10965
12224
  case "settings_reload":
10966
12225
  if (c.role !== "console") return void reply({ ok: false, error: "settings are a person command" });
10967
12226
  return void reloadConfig("terminal", undefined, msg.confirm).then(reply, () => reply({ ok: false, error: "configuration reload could not be confirmed; inspect hub.log" }));
@@ -11058,7 +12317,7 @@ export async function startDaemon(opts: DaemonOptions) {
11058
12317
  // #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.
11059
12318
  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" });
11060
12319
  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" });
11061
- if (recoveryActive() && recoveryPhase !== "preparing" && String(msg.op) !== "hub_checkpoint") return void reply({ t: "task", ok: false, error: "recovery is holding mutations" });
12320
+ 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" });
11062
12321
  if (c.role === "tools" && c.peer && Object.hasOwn(CONDUCTOR_TASK_OPS, String(msg.op))) {
11063
12322
  // #933: a console task op the conductor may run: admitted (role recheck and one audit row) before Tasks sees it; Tasks asks `operational` again.
11064
12323
  let current: () => void;
@@ -11322,6 +12581,7 @@ export async function startDaemon(opts: DaemonOptions) {
11322
12581
  }
11323
12582
  async function stopOnce(): Promise<void> {
11324
12583
  stopping = true;
12584
+ kimiUsage.stop();
11325
12585
  controlWriteTelemetry?.stop();
11326
12586
  const roomsStopped = roomCommands.stop().catch(() => { log("room shutdown failed; inspect ahub room status after restart"); });
11327
12587
  tasks.stopQueuePressureRechecks();
@@ -11385,9 +12645,12 @@ export async function startDaemon(opts: DaemonOptions) {
11385
12645
  executionBudget.close();
11386
12646
  syncStop.abort(); // a sync in flight kills its git step and ends before the store closes
11387
12647
  await syncRun?.catch(() => undefined);
12648
+ for (const peer of recordFrames.keys()) closeRecordFrame(peer); recordInputs.clear(); generatedRecordNotes.clear();
11388
12649
  memory.close();
11389
12650
  candidates?.close();
11390
12651
  memoryStore?.close();
12652
+ modelPreviews.clear(); modelOverrides.close();
12653
+ visuals.close();
11391
12654
  board.close();
11392
12655
  turnLog?.close();
11393
12656
  server.stop(true);
@@ -11429,6 +12692,7 @@ export async function startDaemon(opts: DaemonOptions) {
11429
12692
  // #1054: a run a restart cut short settles `interrupted`, once. Every process of the earlier run is gone by now, and the unique run turn makes repeated restarts yield one completion.
11430
12693
  reconstructRuns();
11431
12694
  ready = true;
12695
+ startupTimings.mark("ready");
11432
12696
  controlWriteTelemetry?.start();
11433
12697
  void handoffCatchUp();
11434
12698
  // #733: the periodic catch-up and the descriptor watch. Unref'd, cleared with the other intervals at stop; each pass is guarded by `stopping` and never overlaps another.
@@ -11479,6 +12743,8 @@ export async function startDaemon(opts: DaemonOptions) {
11479
12743
  // #843 AC3: at hub start, after the roster and the control socket exist; never awaited, so a slow probe delays no start.
11480
12744
  void sweepAgentDrift();
11481
12745
  // #515b: the loopback ports of the two egress proxies, for a host-only test that connects to the proxy this daemon actually started. Ports only: no list, no authority.
12746
+ startupTimings.mark("post_ready");
12747
+ log(startupTimings.finish());
11482
12748
  return { bus, token, port: server.port as number, egressPorts: () => ({ bash: egress?.port, web: webEgress?.port }), bandEvaluations: () => bandEvaluations, sdlcFileReads: () => sdlcFileReads, stop, stopped: new Promise<void>((r) => (onStop = r)) };
11483
12749
  } finally {
11484
12750
  if (!ready) for (const cleanup of startupCleanup.reverse()) { try { await cleanup(); } catch { /* preserve startup error */ } }