@staix/agent-hub 0.35.0 → 0.37.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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
package/src/hub/daemon.ts CHANGED
@@ -1,3 +1,8 @@
1
+ import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
2
+ import { GuidanceProbeStore } from "./guidance-probe-store.ts";
3
+ import { GuidanceProbeError, probeSessionGeneration } from "./guidance-probes.ts";
4
+ import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
5
+ import { publicDeliveryBodies } from "./delivery-public.ts";
1
6
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
2
7
  import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
3
8
  import { VisualStore, validateVisualInput, validateVisualPayload, VISUAL_ID_PATTERN, type VisualRecord, type VisualSummary } from "./visual.ts";
@@ -37,8 +42,9 @@ import { ActionBudgets, actionPolicyConfig, floorEnforcement, floorReads, type A
37
42
  import { actionGate, claudeActionClasses } from "./action-enforce.ts";
38
43
  import type { FloorFacts } from "./action-class.ts";
39
44
  import { ReleaseAuthorizations, releaseAuthorizationError } from "./sdlc-release-authorization.ts";
45
+ import { readCommittedReleasePolicy } from "./sdlc-release-policy.ts";
40
46
  import { parseReleaseGuardArgv, parseReleasePushUpdates } from "../cli/sdlc-release-guard.ts";
41
- import type { DocEvidence } from "./sdlc-release.ts";
47
+ import type { DocEvidence, ReleaseReportPolicy } from "./sdlc-release.ts";
42
48
  import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
43
49
  import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
44
50
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
@@ -89,7 +95,7 @@ import { INSTANCE_CONFIG_FILES, readInstanceConfig, withoutInertInstancePolicy,
89
95
  import { instanceBudgetHooks, projectBudgetHeadroom } from "./instance-budget.ts";
90
96
  import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
91
97
  import { ProgressObserver, normalizeCodexObservation, normalizeClaudeObservation } from "./progress.ts";
92
- import type { ToolObservation } from "../models/route/signals.ts";
98
+ import type { NativeToolObservation as ToolObservation } from "./progress.ts";
93
99
  import { createHash, randomBytes, randomUUID } from "node:crypto";
94
100
  import { appendFileSync, chmodSync, existsSync, fstatSync, mkdirSync, readFileSync, renameSync, rmSync, watchFile, unwatchFile, writeFileSync } from "node:fs";
95
101
  import { join, relative, resolve } from "node:path";
@@ -180,11 +186,13 @@ import { canonicalPath, realPath, hubHome } from "./project.ts";
180
186
  import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
181
187
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
182
188
  import type { BusEvent, PublishResult } from "./bus.ts";
183
- 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";
189
+ 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";
184
190
  import { effectiveClass, listedCapabilities, PublishRefusal, readShare, shareView, validatePublished, type CapabilityManifest } from "./capabilities.ts";
185
191
  import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
186
192
  import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicConductorTask, publicPeerBudget, taskShowAllowed, type ConductEvent } from "./conductor.ts";
187
193
  import { SupervisionFeed } from "./supervision.ts";
194
+ import { MAX_REFS, taskRevision, type SupervisionFacts, type SupervisionHistoryFact } from "./supervision-rules.ts";
195
+ import { ProposalStore, SupervisionProposals, type SupervisionProposal } from "./supervision-proposals.ts";
188
196
  import { drainCliAudits } from "../cli/identity-audit.ts";
189
197
  import { launcherPreview } from "../cli/preview.ts";
190
198
  import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
@@ -215,7 +223,7 @@ import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanit
215
223
  import { BasePeer, DEFAULT_WATCHDOG_MS, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
216
224
  import { ClaudeTodoSource, DoingTracker, readAiTitle, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
217
225
  import { MemoryClient } from "../memory/client.ts";
218
- import { VERSION } from "../version.ts";
226
+ import { VERSION, displayVersion } from "../version.ts";
219
227
  import { appendRecords, taskRecords } from "./research.ts";
220
228
  import { readEvidence } from "./research-record.ts";
221
229
  import { memoryFigures, onlyTaskMemory, UNKNOWN_MEMORY_FIGURES, type MemoryFigures } from "./research-memory.ts";
@@ -299,6 +307,8 @@ export interface HubConfig {
299
307
  specs: SpecsConfig;
300
308
  catalog_roles?: Record<string, string[]>;
301
309
  conductor: { feed: "own" | "all" | "off"; approval_wait_s: number };
310
+ /** #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. */
311
+ supervision: { mode: "off" | "shadow" | "advisory" };
302
312
  budget: BudgetConfig;
303
313
  context: ContextConfig;
304
314
  inference: InferenceConfig;
@@ -359,6 +369,8 @@ export interface HubConfig {
359
369
  pet?: false | Record<string, unknown>;
360
370
  /** Machine-local fields a config file set but git could not vouch for, and why (issue #17). */
361
371
  ignored?: string[];
372
+ /** Reporting-only notice that machine-local release policy was ignored; never part of accepted policy authority. */
373
+ releasePolicyNotices?: string[];
362
374
  /** Settings that were removed or are about to be (issue #83): what each does now, for `hub.log` and `ahub doctor`. */
363
375
  retired?: string[];
364
376
  }
@@ -379,6 +391,7 @@ export const DEFAULT_CONFIG: HubConfig = {
379
391
  roster: {},
380
392
  roles: DEFAULT_ROLES,
381
393
  conductor: { feed: "own", approval_wait_s: 30 },
394
+ supervision: { mode: "off" },
382
395
  budget: DEFAULT_BUDGET,
383
396
  context: DEFAULT_CONTEXT,
384
397
  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 },
@@ -417,7 +430,7 @@ export const DEFAULT_CONFIG: HubConfig = {
417
430
  export { stateDirFor };
418
431
 
419
432
  /** Ids an external process may not claim: the console user and the adapters the daemon runs itself. */
420
- const READ_ONLY_HUB_TOOLS = new Set(["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"]);
433
+ const READ_ONLY_HUB_TOOLS = new Set(["hub_guidance_list", "hub_guidance_show", "hub_lineage_show", "hub_visual_show", "hub_capabilities", "hub_inbox", "hub_send", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status", "hub_specs", "hub_supervision_list"]);
421
434
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
422
435
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
423
436
 
@@ -532,6 +545,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
532
545
  const instances = instanceConfig.instances;
533
546
  const adapterCatalog = instanceConfig.catalog;
534
547
  const ignored: string[] = [...instanceConfig.ignored];
548
+ const releasePolicyNotices: string[] = [];
535
549
  const inertModuleRoster = !!instanceConfig.adapter_modules?.length;
536
550
  const appliedPermissionSources: NonNullable<HubConfig["permission_default_sources"]> = {};
537
551
  let retiredPetWindow = false;
@@ -587,7 +601,14 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
587
601
  if (file.research !== undefined && (!file.research || typeof file.research !== "object" || Array.isArray(file.research))) throw new Error("research must be an object");
588
602
  const hasRunners = file.research && Object.hasOwn(file.research, "runners"), runnerDeclarations: unknown = hasRunners ? file.research.runners : undefined;
589
603
  const why = stripUntrusted(file, DEFAULT_CONFIG, cwd, name);
590
- if (why) ignored.push(why);
604
+ if (why) {
605
+ const notices = why.split("; ");
606
+ releasePolicyNotices.push(...notices.filter(notice => notice.startsWith("release in .agenthub/config.local.json ignored:")));
607
+ const existingNotices = notices.filter(notice => !notice.startsWith("release in .agenthub/config.local.json ignored:"));
608
+ if (existingNotices.length) ignored.push(existingNotices.join("; "));
609
+ }
610
+ // Release policy is read directly from the candidate commit by the S6 host reader, never runtime config.
611
+ delete file.release;
591
612
  if (hasRunners) file.research.runners = parseResearchRunners(runnerDeclarations);
592
613
  for (const [peer, mode] of Object.entries(permissionDefaults(file.permission_modes, instances, adapterCatalog))) appliedPermissionSources[peer] = { mode, source: `.agenthub/${name}` };
593
614
  return [file];
@@ -691,6 +712,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
691
712
  capabilities: { ...file.capabilities },
692
713
  mlx,
693
714
  ...(ignored.length ? { ignored } : {}),
715
+ ...(releasePolicyNotices.length ? { releasePolicyNotices } : {}),
694
716
  ...(retired.length ? { retired } : {}),
695
717
  };
696
718
  }
@@ -845,12 +867,16 @@ interface Client {
845
867
  launchId?: string;
846
868
  /** Display-only retained standby id; peer operations stay fenced until ownsSocket confirms attachment. */
847
869
  standbyId?: string;
870
+ /** Host-minted per connection and durable only as a private replay comparator; never a token, live authority or wire claim. */
871
+ guidanceProbeConnectionId?: string;
848
872
  retainStandby?: boolean;
849
873
  peerGeneration?: string | number;
850
874
  detachedByPerson?: boolean;
851
875
  channel?: boolean;
852
876
  channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
853
877
  clientPid?: number;
878
+ /** #1385: the agent-hub version the client's hello reported, kept only when `displayVersion` accepts it. Display only. */
879
+ clientVersion?: string;
854
880
  cwd?: string;
855
881
  externalOwner?: { owner: PeerAdapter; launchId: string; generation?: string };
856
882
  toolsOwner?: { owner: PeerAdapter; launchId: string; generation: string; cwd: string };
@@ -862,6 +888,13 @@ interface Client {
862
888
  closed?: true;
863
889
  }
864
890
  type Sock = ServerWebSocket<Client>;
891
+ interface GuidanceProbeRequestContext {
892
+ actor: PeerId;
893
+ requestConnectionId: string;
894
+ generation: string | number;
895
+ nativeSession: string | null;
896
+ current: () => void;
897
+ }
865
898
 
866
899
 
867
900
  /**
@@ -1153,6 +1186,7 @@ export async function startDaemon(opts: DaemonOptions) {
1153
1186
  mkdirSync(opts.stateDir, { recursive: true });
1154
1187
  const operationalLogSubscribers=new Map<Sock,()=>void>();
1155
1188
  const operationalContext=new AsyncLocalStorage<{actor:string;current:()=>void}|undefined>();
1189
+ const guidanceProbeRequestContext = new AsyncLocalStorage<GuidanceProbeRequestContext>();
1156
1190
  const checkOperational=(authority:SettingAuthority)=>{if(authority==="conductor"){const scope=operationalContext.getStore();if(!scope)throw new OperationalAuthorityError("operational conductor authority unavailable");scope.current();}};
1157
1191
  const logFile = join(opts.stateDir, "hub.log");
1158
1192
  // The state dir can vanish under a running hub (issue #56): a log line must never take a handler down with it.
@@ -1377,6 +1411,7 @@ export async function startDaemon(opts: DaemonOptions) {
1377
1411
  }
1378
1412
  if (sock.data.session && sock.data.peer) sessionIds.delete(sock.data.peer);
1379
1413
  consoles.delete(sock);
1414
+ toolsSockets.delete(sock);
1380
1415
  operationalLogSubscribers.delete(sock);
1381
1416
  sock.data.tail?.();
1382
1417
  sock.data.watch?.();
@@ -1488,7 +1523,8 @@ export async function startDaemon(opts: DaemonOptions) {
1488
1523
  */
1489
1524
  const silence = (env: Envelope, to: PeerId): string | undefined => {
1490
1525
  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)`;
1491
- if (!turnFree() || env.from === USER || env.from === HUB || env.from === DIGEST || env.priority === "fyi" || env.kind !== "chat" || to === USER) return undefined;
1526
+ // Deferred hub notices are released before Tasks exists; keep Tasks-independent exclusions first.
1527
+ if (env.from === USER || env.from === HUB || env.from === DIGEST || env.priority === "fyi" || env.kind !== "chat" || to === USER || !turnFree()) return undefined;
1492
1528
  const cohort = tasks.silenced(env.from, to);
1493
1529
  if (!cohort) return undefined;
1494
1530
  const ids = [...cohort.members.keys()].sort((a, b) => a - b).map((id) => `#${id}`).join(", ");
@@ -1855,6 +1891,8 @@ export async function startDaemon(opts: DaemonOptions) {
1855
1891
  // normalized origin remote, the same on every machine; without one, its path). Fail-open: without it the hub works as before.
1856
1892
  // Daemon start never depends on the memory home: an unresolvable home falls back to the raw key.
1857
1893
  const memoryProjectRaw = memoryProjectKey(opts.cwd);
1894
+ const executionLineageProjectKey = `ahub-${createHash("sha256").update(memoryProjectRaw).digest("hex")}`;
1895
+ const executionLineageCursorKey = randomBytes(32).toString("hex");
1858
1896
  const memoryProject = (() => { try { return memoryProjectFor(opts.cwd); } catch { return memoryProjectRaw; } })();
1859
1897
  let memoryStore: MemoryStore | undefined;
1860
1898
  let memoryBinding: MemoryProfileBinding | undefined;
@@ -2251,6 +2289,26 @@ export async function startDaemon(opts: DaemonOptions) {
2251
2289
  const uiEvents: { seq: number; event: BusEvent }[] = [];
2252
2290
  let uiSequence = 0;
2253
2291
  const consoles = new Set<Sock>();
2292
+ /** #1385: admitted `tools` connections (the MCP servers Codex, Kimi, agy and Jcode run), only so status can show the agent-hub version each one loaded. */
2293
+ const toolsSockets = new Set<Sock>();
2294
+ /** Per peer, the sorted distinct versions its open tools connections reported (`unreported` for a hello without one). One pass per status read. */
2295
+ const toolsVersions = (): Map<string, string[]> => {
2296
+ const byPeer = new Map<string, Set<string>>();
2297
+ for (const sock of toolsSockets) {
2298
+ const peer = sock.data.peer;
2299
+ if (!peer || sock.data.closed) continue;
2300
+ const seen = byPeer.get(peer) ?? new Set<string>();
2301
+ seen.add(sock.data.clientVersion ?? "unreported");
2302
+ byPeer.set(peer, seen);
2303
+ }
2304
+ return new Map([...byPeer].map(([peer, seen]) => [peer, [...seen].sort()]));
2305
+ };
2306
+ /** #1385: what agent-hub code a peer runs (status `peerVersions`): the daemon's own for an in-daemon adapter, else what its attached client reported. Absent while no client is attached. */
2307
+ const ahubStatus = (p: PeerAdapter | undefined, tools: string[] | undefined) => {
2308
+ const client = p?.hubClient;
2309
+ const ahub = !p ? undefined : !client ? { runs: "daemon" as const, version: VERSION } : client.attached ? { runs: "client" as const, version: client.version ?? "unreported" } : undefined;
2310
+ return { ...(ahub ? { ahub } : {}), ...(tools?.length ? { ahubTools: tools } : {}) };
2311
+ };
2254
2312
  /** A line for the human: hub.log and every open `ahub tail`. */
2255
2313
  const notify = (line: string) => {
2256
2314
  log(line);
@@ -2264,6 +2322,30 @@ export async function startDaemon(opts: DaemonOptions) {
2264
2322
  const inboxPolling = new InboxPolling();
2265
2323
  startupTimings.mark("model_runtime");
2266
2324
  const board = new Board(join(opts.stateDir, "hub.db"));
2325
+ let guidanceProbeStore: GuidanceProbeStore;
2326
+ try { guidanceProbeStore = new GuidanceProbeStore(join(opts.stateDir, "hub.db")); }
2327
+ catch { board.close(); throw new Error("guidance probe storage is unavailable; inspect retained probe state and hub.db before restarting"); }
2328
+ try {
2329
+ const retainedExecutionReferences = board.executionReferencesIntegrity(), expected = restored?.integrity?.executionReferences;
2330
+ if (restored?.integrity && (expected ? expected.count !== retainedExecutionReferences.count || expected.digest !== retainedExecutionReferences.digest : retainedExecutionReferences.count !== 0)) throw new Error("changed recovery binding");
2331
+ } catch {
2332
+ guidanceProbeStore.close(); 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");
2333
+ }
2334
+ try {
2335
+ const retainedGuidance = board.guidanceVariantsIntegrity(), expected = restored?.integrity?.guidanceVariants;
2336
+ if (restored?.integrity && (expected ? expected.experiments !== retainedGuidance.experiments || expected.variants !== retainedGuidance.variants
2337
+ || expected.digest !== retainedGuidance.digest : retainedGuidance.experiments !== 0 || retainedGuidance.variants !== 0)) throw new Error("changed recovery binding");
2338
+ } catch {
2339
+ guidanceProbeStore.close(); board.close(); throw new Error("guidance variant state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2340
+ }
2341
+ try {
2342
+ const retained = guidanceProbeStore.integrity(), expected = restored?.integrity?.guidanceProbes;
2343
+ if (restored && (expected ? expected.experiments !== retained.experiments || expected.sessions !== retained.sessions || expected.digest !== retained.digest
2344
+ : retained.experiments !== 0 || retained.sessions !== 0)) throw new Error("changed recovery binding");
2345
+ } catch {
2346
+ guidanceProbeStore.close(); board.close(); throw new Error("guidance probe state or recovery binding is unavailable; restore trusted project state and choose a compatible target before retrying");
2347
+ }
2348
+ startupCleanup.push(() => guidanceProbeStore.close());
2267
2349
  const visuals = new VisualStore(join(opts.stateDir, "hub.db"));
2268
2350
  startupCleanup.push(() => visuals.close());
2269
2351
  // Held recovery must compare the source's exact rows before any retention mutation.
@@ -2345,6 +2427,10 @@ export async function startDaemon(opts: DaemonOptions) {
2345
2427
  }
2346
2428
  };
2347
2429
  const reviewObserverInput = (peer: PeerId): boolean => {
2430
+ // ponytail: read-only held views mint no input receipt; conservatively exclude
2431
+ // retained readable held review rows until explicit disposition, even if unread.
2432
+ // Upgrade with host-verified read provenance, never a transport ACK.
2433
+ if (bus.hasHeldReviewScope(peer)) return true;
2348
2434
  resetReviewObserverSessionIfChanged(peer);
2349
2435
  const pending = pendingReviewObserverInputs.get(peer);
2350
2436
  return (pending ? pending.held || pending.previous?.held === true : currentReviewObserverInputs.get(peer)?.held === true) || reviewObserverDurableHeld(peer);
@@ -2543,6 +2629,7 @@ export async function startDaemon(opts: DaemonOptions) {
2543
2629
  if (strayChecks.length) log(`checks ignored for ${strayChecks.join(", ")}: not a task class with a command (classes: ${CLASSES.join(", ")})`);
2544
2630
  // Commands and the other machine-local fields came only from a file git vouched for (loadConfig, issue #17).
2545
2631
  for (const line of config.ignored ?? []) log(`${line}; only a config file nobody committed may set it`);
2632
+ for (const line of config.releasePolicyNotices ?? []) log(`config: ${line}`);
2546
2633
  for (const line of config.retired ?? []) log(`config: ${line}`);
2547
2634
  const checksAllowed = Object.keys(checkCommands).length > 0;
2548
2635
  const checkTimeoutS = typeof config.checks.timeout_s === "number" && config.checks.timeout_s >= 1 ? Math.min(config.checks.timeout_s, 3600) : 600;
@@ -2829,7 +2916,13 @@ export async function startDaemon(opts: DaemonOptions) {
2829
2916
  && left.cwd === right.cwd && left.socket === right.socket && left.launchId === right.launchId && left.generation === right.generation && left.repo === right.repo;
2830
2917
  const projectSpecs = specInspectorAt(opts.cwd);
2831
2918
  let specsMissingBlockHintShown = false;
2919
+ let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
2832
2920
  const tasks: Tasks = new Tasks({
2921
+ guidanceProbes: { store: guidanceProbeStore, session: by => {
2922
+ const request = guidanceProbeRequestContext.getStore();
2923
+ return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
2924
+ requestConnectionId: request.requestConnectionId, current: request.current } : undefined;
2925
+ } },
2833
2926
  releaseWindow,
2834
2927
  researchRunners: () => {
2835
2928
  if (config.research.runners === undefined) return {};
@@ -2932,7 +3025,12 @@ export async function startDaemon(opts: DaemonOptions) {
2932
3025
  return report;
2933
3026
  },
2934
3027
  specsRead: (action, paths) => projectSpecs.read(action, paths),
2935
- sdlc: { config: () => lifecycleConfig, gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound) },
3028
+ sdlc: {
3029
+ config: () => lifecycleConfig,
3030
+ gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
3031
+ reportPolicy: (head, repo) => releaseReportPolicy ? releaseReportPolicy(head, repo)
3032
+ : { versionSource: "unknown", docsSource: "unknown", authorization: "unavailable" },
3033
+ },
2936
3034
  board,
2937
3035
  bus,
2938
3036
  executionBudget,
@@ -2942,6 +3040,7 @@ export async function startDaemon(opts: DaemonOptions) {
2942
3040
  ...(config.memory.enabled ? { memory } : {}),
2943
3041
  candidates, candidateScreen: screenMemory, privateTurn: peer => !!turns.get(peer)?.private || contextPii(peer),
2944
3042
  memoryCheck: checkMemory,
3043
+ executionLineage: { projectKey: executionLineageProjectKey, cursorKey: executionLineageCursorKey, readDelivery: id => journal.get(id) },
2945
3044
  briefs: new Briefs(config.memory.enabled ? memory : undefined, chain.at(-1)!, () => config.memory.brief_items,
2946
3045
  memoryStore ? taskMemoryItems : undefined,
2947
3046
  (peer, task, counts) => event({ type: "memory_brief", source: "amem", peer, task, ...counts }),
@@ -3046,6 +3145,115 @@ export async function startDaemon(opts: DaemonOptions) {
3046
3145
  failing: () => ({ ...bus.failingPeers(), ...Object.fromEntries(reviewerUnavailable) }),
3047
3146
  held: () => Object.fromEntries(bus.knownPeers().flatMap((peer) => { const hold = queueHold(peer); return hold ? [[peer, hold]] : []; })),
3048
3147
  });
3148
+ /**
3149
+ * #1221 T2: the bounded proposal queue. The store is built even while the mode is off (its tables are additive and a
3150
+ * person may turn the mode on at the next reload), and nothing in it runs until an explicit decision arrives: reading
3151
+ * the board is the only thing this side does on its own.
3152
+ */
3153
+ const proposalStore = new ProposalStore(join(opts.stateDir, "hub.db"));
3154
+ startupCleanup.push(() => proposalStore.close());
3155
+ const supervisionProposals = new SupervisionProposals(proposalStore, {
3156
+ facts: (task) => proposalFacts(task),
3157
+ isPrivate: (task) => { const row = board.get(task); return !row || tasks.isPii(row); },
3158
+ // The native generation this reading was made under: the owner's session, or `hub` when no agent owns the task.
3159
+ generation: (task) => {
3160
+ const owner = board.get(task)?.owner;
3161
+ return !owner || owner === USER || owner === HUB ? "hub" : `${owner}@${bus.peers.get(owner)?.sessionGeneration ?? "unknown"}`;
3162
+ },
3163
+ // Present roles only, and no new one: the task's owner and reviewer, the configured planner, the conductor, the person.
3164
+ mayDecide: (actor, task) => {
3165
+ const row = board.get(task);
3166
+ if (!row) return false;
3167
+ if (actor === USER || actor === conductorPeer(config.roles) || plannerPeers().includes(actor)) return true;
3168
+ return row.owner === actor || row.reviewer === actor;
3169
+ },
3170
+ // The action's own authority, which a decision does not carry: `escalate` is the conductor's move and the person's,
3171
+ // while the hub's owner notice for a recheck or an integration request runs for whoever may decide.
3172
+ mayRun: (actor, proposal) =>
3173
+ proposal.action !== "escalate" || actor === USER || actor === conductorPeer(config.roles),
3174
+ // A needs_review delivery holds the owner's advice too; unavailable hold evidence is held, never a pass.
3175
+ held: (task) => {
3176
+ const owner = board.get(task)?.owner;
3177
+ if (!owner || owner === USER || owner === HUB) return false;
3178
+ const hints = bus.heldDeliveryHints(owner);
3179
+ return hints === undefined || hints.count > 0;
3180
+ },
3181
+ run: (proposal, actor) => runSupervisionProposal(proposal, actor),
3182
+ now: () => Date.now(),
3183
+ });
3184
+ /** The bounded fact set one proposal reads: the task, its declared overlap partners, and its own measurement. */
3185
+ async function proposalFacts(task: number): Promise<SupervisionFacts> {
3186
+ const row = board.get(task);
3187
+ if (!row) return { tasks: [] };
3188
+ const partners = tasks.overlapTasks(row).filter((id) => id !== row.id).slice(0, MAX_REFS);
3189
+ const read = [row, ...partners.map((id) => board.get(id)).filter((candidate): candidate is typeof row => !!candidate)];
3190
+ const facts: SupervisionFacts = {
3191
+ tasks: read.map((candidate) => ({ id: candidate.id, state: candidate.state, history: candidate.history as SupervisionHistoryFact[] })),
3192
+ overlaps: partners.map((other) => ({ task: row.id, other })),
3193
+ };
3194
+ const side = facts.tasks[0]!;
3195
+ const window = side.history.slice(taskRevision(side).from);
3196
+ // Hashing is only owed when this revision recorded a check pass over delivered ids; otherwise the rule says so itself.
3197
+ if (!tasks.isPii(row) && window.some((entry) => entry.event === "check passed") && window.some((entry) => (entry.deliverables?.length ?? 0) > 0)) {
3198
+ const status = await tasks.deliverableStatus(row);
3199
+ if (status) {
3200
+ facts.deliverables = [{
3201
+ task: row.id, checked: status.files.every((file) => file.state !== "unknown"),
3202
+ changed: status.files.filter((file) => file.state === "changed").map((file) => file.id),
3203
+ missing: status.files.filter((file) => file.state === "missing").map((file) => file.id),
3204
+ }];
3205
+ }
3206
+ }
3207
+ return facts;
3208
+ }
3209
+ /**
3210
+ * The existing action a proposal names, through that action's own authority. `escalate` is the conductor's move (the
3211
+ * person may always escalate, exactly as the console does); the other two are the hub's own owner notice, whose own
3212
+ * authority is the delivery path: the check re-run and the integration stay the owner's actions, and their results
3213
+ * land on the board as their own records.
3214
+ */
3215
+ async function runSupervisionProposal(proposal: SupervisionProposal, actor: string): Promise<{ outcome: "ran" | "refused" | "unknown"; detail?: string }> {
3216
+ if (proposal.action === "escalate") {
3217
+ try {
3218
+ if (actor === USER) await tasks.escalate(USER, proposal.task, "a supervision proposal the person accepted", "manual", true);
3219
+ else await conductor.execute(actor, "hub_task_escalate", { id: proposal.task });
3220
+ } catch (error) {
3221
+ // An action's own pre-effect refusal is a certain outcome: nothing ran. Anything else may have had an effect, and
3222
+ // the queue records it `unknown` instead of pretending either way.
3223
+ if (error instanceof PreEffectToolRefusal) return { outcome: "refused", detail: error.message.slice(0, 200) };
3224
+ throw error;
3225
+ }
3226
+ return { outcome: "ran", detail: "escalate" };
3227
+ }
3228
+ const partner = proposal.refs.find((ref) => ref.startsWith("task:"));
3229
+ const other = proposal.action === "request_integration" && partner ? Number(partner.slice("task:".length)) : undefined;
3230
+ const stale = proposal.refs.filter((ref) => ref.startsWith("deliverable:")).join(", ");
3231
+ const body = proposal.action === "recheck"
3232
+ ? `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.`
3233
+ : `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.`;
3234
+ const told = tasks.supervisionNotice(proposal.task, other, body);
3235
+ return told.sent.length ? { outcome: "ran", detail: `notice to ${told.sent.join(", ")}` } : { outcome: "refused", detail: told.refused ?? "no owner to tell" };
3236
+ }
3237
+ /** `off` evaluates nothing; `shadow` stores bounded proposals with no console row or notice; `advisory` may show one. */
3238
+ const supervisionMode = () => config.supervision?.mode ?? "off";
3239
+ /** What a tool result and the inbox show: codes and ids only, never a title, a note or a path. */
3240
+ const proposalView = (proposal: SupervisionProposal) => ({
3241
+ id: proposal.id, task: proposal.task, rule: proposal.rule, version: proposal.version, revision: proposal.revision, trigger: proposal.trigger,
3242
+ refs: proposal.refs, limits: { records: proposal.records, truncated: proposal.truncated }, action: proposal.action, reason: proposal.reason,
3243
+ state: proposal.state, created: proposal.createdAt, ...(proposal.actor ? { actor: proposal.actor } : {}),
3244
+ ...(proposal.disposedAt === undefined ? {} : { decided: proposal.disposedAt }), ...(proposal.receipt ? { receipt: proposal.receipt } : {}),
3245
+ });
3246
+ const proposeObserved = (task: number): void => {
3247
+ if (supervisionMode() === "off" || stopping || recoveryActive()) return;
3248
+ const row = board.get(task);
3249
+ // A declared pair's reading is bound to its lower task id, so a change on the higher-id side is only read by
3250
+ // re-reading each partner: without that, a pair proposal would be created or invalidated from one side alone.
3251
+ for (const id of new Set([task, ...(row ? tasks.overlapTasks(row) : [])])) {
3252
+ const candidate = board.get(id);
3253
+ if (!candidate || candidate.state === "backlog" || tasks.isPii(candidate)) continue;
3254
+ void supervisionProposals.observe(id).catch((error: Error) => log(`supervision observe for #${id} failed: ${error.message}`));
3255
+ }
3256
+ };
3049
3257
  relevantNotice = (peer, env) => {
3050
3258
  if (env.from === HUB && env.refs?.boundedCheck) {
3051
3259
  const run = env.refs.boundedCheck, binding = checkBindings.get(run);
@@ -3073,6 +3281,9 @@ export async function startDaemon(opts: DaemonOptions) {
3073
3281
  return true;
3074
3282
  };
3075
3283
  tasks.recoverIntegrations();
3284
+ // #1221 T2 AC6: a restart keeps the dedupe keys, the dispositions and an action outcome the hub never observed. A
3285
+ // pending proposal whose task moved or closed expires here, once, with nothing replayed.
3286
+ void supervisionProposals.recover().catch((error: Error) => log(`supervision reconcile failed: ${error.message}`));
3076
3287
  /** Peers told, at their first attach, what the cohorts lost in the restart held for them (issue #107). */
3077
3288
  const replayed = new Set<PeerId>();
3078
3289
  // Turn-free facts (issue #108): what the others changed in an owner's files, at its tool calls. Scopes are read from
@@ -3124,6 +3335,8 @@ export async function startDaemon(opts: DaemonOptions) {
3124
3335
  const observeProgress = (peer: PeerId, observation: ToolObservation | undefined, taskId?: string): void => {
3125
3336
  if (!observation) return;
3126
3337
  if (reviewObserverHeld(peer) || bus.lastDeliveredTo(peer).some(isReviewObserverExcluded)) { progress.clearPeer(peer); return; }
3338
+ const toolName = observation.name.replace(/^mcp__[^ ]+__/, "");
3339
+ if (GUIDANCE_TOOL_NAMES.has(toolName)) return;
3127
3340
  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)
3128
3341
  try {
3129
3342
  const candidates = board.list().filter(task => task.owner === peer && ["in_progress", "changes_requested"].includes(task.state));
@@ -3299,7 +3512,7 @@ export async function startDaemon(opts: DaemonOptions) {
3299
3512
  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)!)] : [] });
3300
3513
  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 } : {}) });
3301
3514
  // #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.
3302
- if (config.research.enabled && ((t.state === "approved" && (h.event === "approved" || h.event === "done" || h.event === "merge result")) || (t.state === "cancelled" && h.event === "cancelled"))) recordResearch(t.id);
3515
+ 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);
3303
3516
  if (memoryStore && (t.state === "in_progress" || h.event === "done") && !tasks.isPii(t)) renewLeases(t);
3304
3517
  if ((h.event === "proposed" || h.event === "backlog pulled") && projections.enabled && turnLog) {
3305
3518
  const created = taskProposalAt(t);
@@ -3309,6 +3522,8 @@ export async function startDaemon(opts: DaemonOptions) {
3309
3522
  }
3310
3523
  }
3311
3524
  supervision.taskChanged(t, h);
3525
+ // #1221 T2: the rules read only after the board has the record; a mode that is off costs one string comparison.
3526
+ proposeObserved(t.id);
3312
3527
  // Models can self-claim after their turn begins; preserve that ownership even if they finish before settlement.
3313
3528
  const turn = t.owner ? turns.get(t.owner) : undefined;
3314
3529
  if (turn) turnTasks.set(turn.id, [...new Set([...(turnTasks.get(turn.id) ?? []), t.id])]);
@@ -4888,13 +5103,13 @@ export async function startDaemon(opts: DaemonOptions) {
4888
5103
  const id = Number.isSafeInteger(proposed) && proposed! > 0 ? proposed : admittedId;
4889
5104
  auditConduct({ kind: "conduct", actor: by, action: op.slice(4), ...(id === undefined ? {} : { task: id }) });
4890
5105
  }
4891
- const hint = args[3] && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5106
+ const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
4892
5107
  return hint ? `${text}\n\n${hint}` : text;
4893
5108
  } catch (error) {
4894
5109
  if (reviewTool && traceId !== undefined) reviewerToolObservers.get(by)?.(traceId, reviewTool, error instanceof Error ? error.message : "review tool refused");
4895
5110
  if (nativeTurn && effectful && !(error instanceof PreEffectToolRefusal) && turns.get(by) === nativeTurn) nativeTurn.taskEffect = true;
4896
5111
  // Keep proven pre-effect refusal identity/code for native receipts; only add body-free metadata.
4897
- const hint = args[3] && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
5112
+ const hint = args[3] && !GUIDANCE_TOOL_NAMES.has(op) && op !== "hub_lineage_show" && op !== "hub_lineage_link" && op !== "hub_source_read" && op !== "hub_set_title" && op !== "hub_evidence_record" && op !== "hub_visual" && op !== "hub_visual_show" ? ownHeldHint(by) : "";
4898
5113
  if (hint && error instanceof Error) error.message += `\n\n${hint}`;
4899
5114
  throw error;
4900
5115
  } finally {
@@ -5249,10 +5464,38 @@ export async function startDaemon(opts: DaemonOptions) {
5249
5464
  } catch { throw new Error(`visual ${id} was stored but its stub delivery failed; inspect the visual before posting again`); }
5250
5465
  return `visual ${id}`;
5251
5466
  }
5467
+ function executionLineageRead(by: PeerId, input: unknown, piiTurn = false): Record<string, unknown> {
5468
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewObserverHeld(by) || reviewObserverInput(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5469
+ return { ok: true, lineage: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" } : tasks.executionLineage(by, input) };
5470
+ }
5471
+ function guidanceRead(by: PeerId, op: "list" | "show", input: unknown, piiTurn = false): Record<string, unknown> {
5472
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewObserverHeld(by) || reviewObserverInput(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5473
+ return { ok: true, guidance: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" }
5474
+ : op === "list" ? tasks.guidanceVariantList(by, input) : tasks.guidanceVariantDiff(by, input) };
5475
+ }
5252
5476
  async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
5253
5477
  if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
5254
5478
  const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5255
5479
  if (reviewTurn || op === "hub_review" && reviewCaptureExcluded(op, JSON.stringify(a))) progress.clearPeer(by);
5480
+ if (GUIDANCE_TOOL_NAMES.has(op)) {
5481
+ if (op === "hub_guidance_list" || op === "hub_guidance_show") return JSON.stringify(guidanceRead(by, op === "hub_guidance_list" ? "list" : "show", a, piiTurn));
5482
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
5483
+ if (excluded) throw new PreEffectToolRefusal("guidance writes are unavailable in private or review input; retry in a public current-owner context");
5484
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance writes; wait for release and inspect the task before retrying");
5485
+ if (op === "hub_guidance_create") {
5486
+ 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"); }
5487
+ return JSON.stringify({ ok: true, receipt: await tasks.guidanceVariantCreate(by, variant) });
5488
+ }
5489
+ 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"); }
5490
+ return JSON.stringify({ ok: true, receipt: await tasks.guidanceVariantWithdraw(by, selector) });
5491
+ }
5492
+ if (LINEAGE_TOOL_NAMES.has(op)) {
5493
+ const excluded = piiTurn || !!turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by);
5494
+ if (op === "hub_lineage_show") return JSON.stringify(executionLineageRead(by, a, piiTurn));
5495
+ if (excluded) throw new PreEffectToolRefusal("execution reference linking is unavailable in a private or review-observer context; retry only in a public task context");
5496
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding execution reference links; wait for release and retry");
5497
+ return JSON.stringify({ ok: true, link: await tasks.linkExecutionReference(by, a) });
5498
+ }
5256
5499
  if (op === "hub_ask") {
5257
5500
  // #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`.
5258
5501
  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)");
@@ -5265,6 +5508,24 @@ export async function startDaemon(opts: DaemonOptions) {
5265
5508
  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" });
5266
5509
  return JSON.stringify(await setSessionTitle(by, a.title, true, piiTurn));
5267
5510
  }
5511
+ if (op === "hub_supervision_list" || op === "hub_supervision_accept" || op === "hub_supervision_dismiss") {
5512
+ // #1221 T2: the queue carries public board facts only, so a private turn neither reads nor decides one.
5513
+ if (piiTurn || turns.get(by)?.private || contextPii(by)) throw new PreEffectToolRefusal("supervision proposals are unavailable during a private or PII turn");
5514
+ if (op === "hub_supervision_list") {
5515
+ 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)))
5516
+ throw new PreEffectToolRefusal("hub_supervision_list takes only an optional task id");
5517
+ const rows = await supervisionProposals.read(by, a?.task);
5518
+ // `refused` is the queue's own count of readings a bound refused instead of storing: a full queue is visible here.
5519
+ return JSON.stringify({ mode: supervisionMode(), proposals: rows.map(proposalView), refused: supervisionProposals.refusedReadings(),
5520
+ ...(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" }) });
5521
+ }
5522
+ if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "id") || typeof a.id !== "string")
5523
+ throw new PreEffectToolRefusal(`${op} takes only a proposal id`);
5524
+ if (stopping || recoveryActive()) throw new PreEffectToolRefusal("recovery or shutdown is holding supervision decisions");
5525
+ const decision = await supervisionProposals.decide(by, a.id, op === "hub_supervision_accept" ? "accept" : "dismiss");
5526
+ if (!decision.ok) throw new PreEffectToolRefusal(decision.error);
5527
+ return JSON.stringify({ ok: true, proposal: proposalView(decision.proposal), ...(decision.receipt ? { receipt: decision.receipt } : {}) });
5528
+ }
5268
5529
  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");
5269
5530
  if (BOUNDED_TASK_TOOLS.has(op)) {
5270
5531
  const keys = op === "hub_task_spec" ? ["id"] : op === "hub_check_start" ? ["id", "check", "files"] : ["run"];
@@ -5608,7 +5869,6 @@ export async function startDaemon(opts: DaemonOptions) {
5608
5869
  return [result, specReport, extra].filter(Boolean).join("\n");
5609
5870
  }
5610
5871
  case "hub_sdlc_record":
5611
- await tasks.specStageGate(by, a.id, a.receipt); // #481 S1: a live spec edit-time check before a build stage
5612
5872
  return line(await tasks.recordSdlc(by, a.id, a.receipt));
5613
5873
  case "hub_review": {
5614
5874
  const reviewed = await tasks.review(by, a.id, a.verdict, a.note, a.unmet, a.head, a.coverage, a.findings);
@@ -6317,14 +6577,18 @@ export async function startDaemon(opts: DaemonOptions) {
6317
6577
 
6318
6578
  const releaseAuthorizations = new ReleaseAuthorizations(opts.cwd, {
6319
6579
  docs: opts.releaseDocEvidence,
6580
+ policy: (commit, git) => readCommittedReleasePolicy(git, commit),
6320
6581
  gh: (args, timeout) => sdlcGh(args, timeout, opts.cwd),
6321
6582
  current: () => !stopping && !recoveryActive() && !bus.isRecoveryHeld,
6322
6583
  conductor: () => {
6323
6584
  const peer = conductorPeer(config.roles);
6324
6585
  return peer && !turns.get(peer)?.private && !contextPii(peer) ? peer : undefined;
6325
6586
  },
6326
- record: receipt => event({ type: "release_authorization", by: receipt.by, authorization: receipt.id, commit: receipt.commit, version: receipt.version, docsDigest: receipt.docs.digest, documents: receipt.docs.documents }),
6587
+ record: receipt => event("source" in receipt.docs
6588
+ ? { type: "release_authorization", by: receipt.by, authorization: receipt.id, commit: receipt.commit, version: receipt.version, docs: "none" }
6589
+ : { type: "release_authorization", by: receipt.by, authorization: receipt.id, commit: receipt.commit, version: receipt.version, docsDigest: receipt.docs.digest, documents: receipt.docs.documents }),
6327
6590
  });
6591
+ releaseReportPolicy = (head, repo) => releaseAuthorizations.reportPolicy(head, repo);
6328
6592
  const terminalReads = terminalOwnerReads();
6329
6593
  const terminalLaunches = new TerminalLaunches({
6330
6594
  owner: row => {
@@ -6370,6 +6634,7 @@ export async function startDaemon(opts: DaemonOptions) {
6370
6634
  let releasing = false; // gone-owner release (#6) and the ready sweep (#34): one run at a time, and a recovery commit waits for it
6371
6635
  const recoveryReady = () => {
6372
6636
  if (!recoveryActive() || releasing || taskOpsInFlight !== 0 || tasks.checksPending() !== 0 || piCallsInFlight() !== 0 || permissions.size !== 0 || starting.size !== 0 || requestedPeerStops.size !== 0 || rosterChanging !== undefined || !budget.recoverySettled || [...bus.peers.values()].filter(peer => !peer.id.includes("@")).some((peer) => peer.state === "busy" || ("recoveryReady" in peer && peer.recoveryReady !== true))) return false;
6637
+ if (tasks.guidanceProbesPending() !== 0) return false; // Active and uncertain fixture work retains its project lane.
6373
6638
  if (checkPending.size !== 0) return false;
6374
6639
  if (tasks.autoPullsPending() !== 0) return false; // #785 P1c: an automatic backlog pull mid-admission would write after the commit's digest; its own line keeps the line above exact for scripts/seeds.json
6375
6640
  if (tasks.queuePressureRechecksPending() !== 0) return false;
@@ -6681,12 +6946,15 @@ export async function startDaemon(opts: DaemonOptions) {
6681
6946
  const researchComparisons = board.researchComparisonIntegrity();
6682
6947
  const researchRunners = board.runnerReceiptIntegrity();
6683
6948
  const researchEvidence = board.researchEvidenceIntegrity();
6949
+ const guidanceVariants = board.guidanceVariantsIntegrity();
6950
+ const guidanceProbes = guidanceProbeStore.integrity();
6951
+ const executionReferences = board.executionReferencesIntegrity();
6684
6952
  const reviewComments = board.reviewCommentsIntegrity();
6685
6953
  const modelState = modelOverrides.integrity();
6686
6954
  const visualIntegrity = visuals.integrity();
6687
6955
  if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
6688
6956
  throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
6689
- 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 } : {}), ...(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])) } : {}) };
6957
+ return { queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
6690
6958
  };
6691
6959
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
6692
6960
  const integrityAs = (expected: unknown) => {
@@ -6769,6 +7037,9 @@ export async function startDaemon(opts: DaemonOptions) {
6769
7037
  const queueBackpressure = tasks.queuePressureStatus(peerIds);
6770
7038
  const crashLines = crashView();
6771
7039
  const deliveryFailures = bus.failedDeliveryCounts();
7040
+ const toolsByPeer = toolsVersions();
7041
+ // #1385: separate metadata, like roleInfo (#295), so the legacy peer row keeps its shape.
7042
+ const peerVersions = Object.fromEntries(peerIds.map(id => [id, ahubStatus(bus.peers.get(id), toolsByPeer.get(id))] as const).filter(([, row]) => Object.keys(row).length));
6772
7043
  const view = {
6773
7044
  ...(deliveryFailures ? { deliveryFailures } : {}),
6774
7045
  ...runtimeModelProjection(),
@@ -6820,6 +7091,7 @@ export async function startDaemon(opts: DaemonOptions) {
6820
7091
  peers: Object.fromEntries(
6821
7092
  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 ?? [] } : {}) }]; }),
6822
7093
  ),
7094
+ peerVersions,
6823
7095
  taskWip: tasks.wipBreakdown(peerIds),
6824
7096
  boardReadCapabilities: { releaseFilter: true, columnMetadata: true },
6825
7097
  actionPolicyInfo: Object.fromEntries(peerIds.map(id => { const e = actionEnforcement(id); return [id, actionBudgets.status(id, e.enforced, e.reason)]; })),
@@ -8809,7 +9081,7 @@ export async function startDaemon(opts: DaemonOptions) {
8809
9081
  function queueView(row: ReturnType<Bus["queueShow"]>, detail = false, publicOnly = false) {
8810
9082
  if (!row) return undefined;
8811
9083
  const originals = row.originals;
8812
- const privateDelivery = originals.some((env) => env.private || publicOnly && env.refs?.task && (()=>{const task=board.get(Number(env.refs!.task));return !task || tasks.isPii(task);})());
9084
+
8813
9085
  return {
8814
9086
  id: row.id, peer: row.peer, state: row.state, revision: row.revision,
8815
9087
  ...(row.failureCause ? { failureCause: row.failureCause } : {}),
@@ -8819,12 +9091,40 @@ export async function startDaemon(opts: DaemonOptions) {
8819
9091
  createdAt: row.createdAt, updatedAt: row.updatedAt,
8820
9092
  envelopeIds: originals.map((env) => env.id),
8821
9093
  important: originals.some((env) => env.priority === "important"),
8822
- ...(detail ? { messages: originals.map((env) => ({ id: env.id, from: env.from, priority: env.priority, kind: env.kind,
8823
- body: privateDelivery ? "[private: inspect the associated task with ahub task show]" : publicOnly && !tasks.publicMetadataText(env.body) ? "[withheld]" : sanitize(env.body),
8824
- })) } : {}),
9094
+ ...(detail ? { messages: publicDeliveryBodies(originals, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
8825
9095
  };
8826
9096
  }
8827
9097
 
9098
+ /** Separate from pull: failure here must never discard an already committed normal handout. */
9099
+ function inboxHeldRead(c: Client, current: () => boolean) {
9100
+ try {
9101
+ const peer = c.peer;
9102
+ if (!peer || !current() || contextPii(peer)) throw new Error("held inbox authority unavailable");
9103
+ const policy = config, configVersion = configRevision, boardVersion = board.statusRevision();
9104
+ const held = bus.heldInbox(peer);
9105
+ const launch = c.toolsOwner ? currentImplementerTools(c) : undefined;
9106
+ const rows = held.rows.map(row => {
9107
+ if (!current() || reviewOnlyPeer(peer) && row.originals.some(env => !reviewOnlyItem(peer, env))) throw new Error("held inbox scope unavailable");
9108
+ 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");
9109
+ return { id: row.id, revision: row.revision, state: row.state, messages: publicDeliveryBodies(row.originals, {
9110
+ publicOnly: true, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); },
9111
+ publicMetadataText: text => tasks.publicMetadataText(text),
9112
+ }) };
9113
+ });
9114
+ // Screening may consult host ports. Revalidate the exact caller and current privacy before exposure.
9115
+ if (!current() || contextPii(peer) || config !== policy || configRevision !== configVersion || board.statusRevision() !== boardVersion) throw new Error("held inbox changed during projection");
9116
+ for (const row of held.rows) {
9117
+ if (reviewInputHeld(peer, row.originals)) {
9118
+ const owner = bus.peers.get(peer), active = ownedObserverInputs.get(peer);
9119
+ if (active && active.owner === owner) active.supersededByReviewInput = true;
9120
+ noteSteeredReviewInput(peer, row.originals); // RAM observation only: no ACK or durable handoff.
9121
+ }
9122
+ }
9123
+ if (!current() || contextPii(peer)) throw new Error("held inbox authority changed");
9124
+ return { count: held.count, rows, truncated: held.truncated, ...(held.unavailable ? { unavailable: true } : {}) };
9125
+ } 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." }; }
9126
+ }
9127
+
8828
9128
  let operationalViewCache: { board: number; config: number; routing: ReturnType<typeof activeRouting>; privacy: string; view: ReturnType<typeof operationalView> } | undefined;
8829
9129
  function publicOperationalView() {
8830
9130
  const revision=board.statusRevision(),routing=activeRouting(),privacy=JSON.stringify([config.pii?.paths??[],config.local.deny]);
@@ -8853,6 +9153,14 @@ export async function startDaemon(opts: DaemonOptions) {
8853
9153
  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)]));
8854
9154
  return null;
8855
9155
  }
9156
+ function sdlcSettingsView() {
9157
+ let file: ReturnType<typeof loadSdlc> | undefined;
9158
+ try { file = loadSdlc(opts.cwd, VERSION); } catch { /* unreadable file stays unknown */ }
9159
+ return {
9160
+ "sdlc.mode": { value: lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9161
+ "sdlc.required_checks": { value: lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
9162
+ };
9163
+ }
8856
9164
  function publicSettingsView() {
8857
9165
  const view = settingsView();
8858
9166
  const rows = view.rows.flatMap(row => {
@@ -8877,7 +9185,7 @@ export async function startDaemon(opts: DaemonOptions) {
8877
9185
  ...(row.min !== undefined ? { min: row.min } : {}), ...(row.max !== undefined ? { max: row.max } : {}),
8878
9186
  ...(row.locked ? { locked: "read-only" } : {}), ...(opaque ? { withheld: true } : {}) }];
8879
9187
  });
8880
- 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"] };
9188
+ 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"] };
8881
9189
  }
8882
9190
  function publicReleaseShow(input: Record<string, any>) {
8883
9191
  const release = input.id !== undefined ? Number.isSafeInteger(input.id) && input.id > 0 ? board.release(input.id) : undefined
@@ -9173,6 +9481,10 @@ export async function startDaemon(opts: DaemonOptions) {
9173
9481
  ...(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) }),
9174
9482
  activeTasks: boardTasks.filter(task => task.owner === id && ["in_progress", "changes_requested"].includes(task.state)).map(task => task.id),
9175
9483
  })),
9484
+ // #1221 T2 AC5: the advisory row set for the console's existing inbox. Codes and ids only, never a title or a note;
9485
+ // 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
9486
+ // console that never opted in see exactly what they saw before.
9487
+ ...(supervisionMode() === "advisory" ? { supervision: { mode: "advisory" as const, proposals: supervisionProposals.awaiting(USER).map(proposalView) } } : {}),
9176
9488
  tasks: boardTasks.map((task) => {
9177
9489
  const view = tasks.publicView(task);
9178
9490
  // Refs and history can themselves quote private text. The dashboard needs neither.
@@ -9238,6 +9550,7 @@ export async function startDaemon(opts: DaemonOptions) {
9238
9550
  }
9239
9551
  function declaredPaths(value: unknown, prefix = ""): string[] {
9240
9552
  if (prefix === "_autonomy" || prefix.startsWith("_autonomy.")) return [];
9553
+ if (prefix === "release" || prefix.startsWith("release.")) return [];
9241
9554
  if (prefix === "pet.window") return [];
9242
9555
  // Retired dictionaries never enter active publication; hub ids remain opaque keys.
9243
9556
  if (prefix === "routing.targets" || prefix === "routing.routes") return [];
@@ -9347,11 +9660,13 @@ export async function startDaemon(opts: DaemonOptions) {
9347
9660
  guarded.length = 0; previews.length = 0;
9348
9661
  }
9349
9662
  candidate.retired = fileConfig.retired;
9663
+ candidate.releasePolicyNotices = fileConfig.releasePolicyNotices;
9350
9664
  routing.retired = sources.routing.retired;
9351
9665
  const changes = configChanges({ ...config, roles: policyRoles }, candidate, [{ catalog: adapterCatalog, instances: declarations }, configIdentityScope(acceptedSources.identity), configIdentityScope(sources.identity)]);
9352
9666
  const running = structuredClone({ ...config, roles: policyRoles });
9353
9667
  for (const change of changes) if (change.applies !== "restart") putConfig(running, change.key, change.after);
9354
9668
  running.retired = fileConfig.retired;
9669
+ running.releasePolicyNotices = fileConfig.releasePolicyNotices;
9355
9670
  validateEffectiveConfig(running, adapterCatalog);
9356
9671
  conductorPeer(running.roles);
9357
9672
  for (const peer of Object.keys(running.catalog_roles ?? {})) selectedRoles(peer, running.roles, { ...resolvedProfile.catalog_roles, ...catalogAssignments(running.catalog_roles) }, catalog);
@@ -9432,6 +9747,9 @@ export async function startDaemon(opts: DaemonOptions) {
9432
9747
  const priorRetired = new Set(config.retired ?? []);
9433
9748
  config.retired = prepared.running.retired;
9434
9749
  for (const line of config.retired ?? []) if (!priorRetired.has(line)) log(`config: ${line}`);
9750
+ const priorReleaseNotices = new Set(config.releasePolicyNotices ?? []);
9751
+ config.releasePolicyNotices = prepared.running.releasePolicyNotices;
9752
+ for (const line of config.releasePolicyNotices ?? []) if (!priorReleaseNotices.has(line)) log(`config: ${line}`);
9435
9753
  config.permission_default_sources = candidate.permission_default_sources;
9436
9754
  refreshAutonomyConsent(prepared.fileConfig);
9437
9755
  for (const peer of changedPermissionDefaults) applyPendingPermissionDefault(peer);
@@ -9982,6 +10300,16 @@ export async function startDaemon(opts: DaemonOptions) {
9982
10300
  if (!option || (definitionOf(req.peer)?.trust.hubSandboxed === true && option.kind !== "reject_once")) return bad;
9983
10301
  return pending.done(option.optionId, "dashboard") ? { ok: true } : { ok: false, error: "permission expired or already answered" };
9984
10302
  }
10303
+ case "supervision": {
10304
+ // #1221 T2 AC5: an advisory inbox row decides one proposal as the person, through the same fence the hub tool
10305
+ // uses (`decide`); the console supplies the verb and the id, never an actor, a task or an action.
10306
+ if (typeof a.id !== "string" || (a.verb !== "accept" && a.verb !== "dismiss")) return bad;
10307
+ if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding supervision decisions" };
10308
+ const decision = await supervisionProposals.decide(USER, a.id, a.verb);
10309
+ return decision.ok
10310
+ ? { ok: true, proposal: proposalView(decision.proposal), ...(decision.receipt ? { receipt: decision.receipt } : {}) }
10311
+ : { ok: false, error: decision.error };
10312
+ }
9985
10313
  case "send": {
9986
10314
  if (!text("body", 8000)) return bad;
9987
10315
  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;
@@ -10095,6 +10423,7 @@ export async function startDaemon(opts: DaemonOptions) {
10095
10423
  // #272: the rest of what recoveryReady() waits for, so the upgrade screen can name the wait. Display only.
10096
10424
  ...(taskOpsInFlight !== 0 ? ["a task command in flight"] : []),
10097
10425
  ...(tasks.checksPending() !== 0 ? ["completion checks queued or running"] : []),
10426
+ ...(tasks.guidanceProbesPending() !== 0 ? ["guidance probe work in flight"] : []),
10098
10427
  ...(tasks.autoPullsPending() !== 0 ? ["an automatic backlog pull in flight"] : []),
10099
10428
  ...(tasks.queuePressureRechecksPending() !== 0 ? ["a queue-pressure assignment recheck in flight"] : []),
10100
10429
  ...(tasks.schedulesPending() !== 0 ? ["a scheduled task proposal in flight"] : []),
@@ -10127,6 +10456,18 @@ export async function startDaemon(opts: DaemonOptions) {
10127
10456
  ? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
10128
10457
  };
10129
10458
  const incompatibleRecoveryTarget = () => {
10459
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
10460
+ try { if (guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
10461
+ catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
10462
+ }
10463
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_variants")) {
10464
+ try { if (board.hasGuidanceVariants()) return "target lacks guidance_variants; retained immutable variants require a supporting daemon; choose a target advertising guidance_variants"; }
10465
+ catch { return "guidance variant compatibility is unknown; inspect retained storage or choose a supporting target"; }
10466
+ }
10467
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("execution_lineage")) {
10468
+ try { if (board.hasExecutionReferences()) return "target lacks execution_lineage; retained declared references require a supporting daemon; choose a target advertising execution_lineage"; }
10469
+ catch { return "execution reference compatibility is unknown; inspect the retained store or choose a supporting target"; }
10470
+ }
10130
10471
  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";
10131
10472
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("visuals")) {
10132
10473
  try {
@@ -10643,6 +10984,8 @@ export async function startDaemon(opts: DaemonOptions) {
10643
10984
  c.authed = true;
10644
10985
  c.protocol = selectedProtocol;
10645
10986
  c.role = msg.role;
10987
+ c.guidanceProbeConnectionId = randomUUID(); // Private comparator only; never sent, persisted separately or accepted from hello.
10988
+ c.clientVersion = displayVersion(msg.clientVersion);
10646
10989
  if (c.role === "console") consoles.add(sock);
10647
10990
  else if (c.role === "tools" && sessionHello(msg)) {
10648
10991
  // agent-hub#1036: a connection that names a peer id but is not that peer's current session gets an id of its own instead of becoming the peer. It can send and read; it holds none of the
@@ -10709,6 +11052,7 @@ export async function startDaemon(opts: DaemonOptions) {
10709
11052
  if (typeof msg.cwd === "string" && msg.cwd.length <= 4096) sock.data.cwd = msg.cwd;
10710
11053
  const clientPid = Number.isSafeInteger(msg.clientPid) && msg.clientPid > 0 && msg.clientPid <= 2_147_483_647 ? msg.clientPid as number : undefined;
10711
11054
  sock.data.clientPid = clientPid;
11055
+ sock.data.clientVersion = c.clientVersion;
10712
11056
  const pushOverPullOnly = msg.channel !== false && ws.attached && ws.pullOnly && !ws.claiming;
10713
11057
  const hasLiveHolder = ws.attached || ws.claiming;
10714
11058
  if (c.retainStandby && hasLiveHolder && !pushOverPullOnly) {
@@ -10737,6 +11081,7 @@ export async function startDaemon(opts: DaemonOptions) {
10737
11081
  }
10738
11082
  }
10739
11083
  // #604 PR B: one attach event per admitted peer or tools hello, with the same fields an envelope's `origin` carries. A refused hello returned above and writes none.
11084
+ if (c.role === "tools" && !c.session) toolsSockets.add(sock);
10740
11085
  if (c.role === "peer" || c.role === "tools") event(attachEvent({ role: c.role, peer: c.peer, launchId: c.launchId, ...(c.session ? { session: true } : {}) }));
10741
11086
  return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL, features: DAEMON_FEATURES,
10742
11087
  ...(c.session ? { session: c.peer } : {}), ...(c.standbyId ? { standby: true, standbyId: c.standbyId } : {}) });
@@ -10946,19 +11291,21 @@ export async function startDaemon(opts: DaemonOptions) {
10946
11291
  return void reply({ ok: true });
10947
11292
  }
10948
11293
  case "inbox": {
11294
+ 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" });
10949
11295
  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" });
10950
11296
  if (c.toolsOwner) {
10951
11297
  const peer = c.peer!, current = captureImplementerTools(c), launch = currentImplementerTools(c);
11298
+ const heldRead = () => inboxHeldRead(c, current);
10952
11299
  try {
10953
11300
  // Inspect the still-pending batch before pull commits/removes it: private work never reaches this native child.
10954
11301
  const pending = bus.pendingEnvelopes(peer);
10955
11302
  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" });
10956
11303
  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" });
10957
11304
  const envs = bus.pull(peer, { allowNeedsReviewHold: true });
10958
- if (!envs) return void reply({ ok: false, error: queueHold(peer) ?? "delivery held", held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10959
- return void reply({ ok: true, envs, held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
11305
+ 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) });
11306
+ return void reply({ ok: true, envs, held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10960
11307
  } catch (error) {
10961
- if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer, true), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
11308
+ 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) });
10962
11309
  return void reply({ ok: false, error: "delivery journal unavailable" });
10963
11310
  }
10964
11311
  }
@@ -10966,6 +11313,8 @@ export async function startDaemon(opts: DaemonOptions) {
10966
11313
  // Pull and push share holds and journal settlement; work read here is completed, never pushed again.
10967
11314
  const peer = c.peer ? bus.peers.get(c.peer) : undefined;
10968
11315
  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" });
11316
+ 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();
11317
+ const heldRead = () => inboxHeldRead(c, current);
10969
11318
  try {
10970
11319
  const envs = bus.pull(peer.id, { allowNeedsReviewHold: true });
10971
11320
  if (!envs) {
@@ -10977,7 +11326,7 @@ export async function startDaemon(opts: DaemonOptions) {
10977
11326
  ?? (bus.isRecoveryHeld ? "recovery is holding deliveries" : undefined)
10978
11327
  ?? (bus.stateOf(peer.id) === "paused" ? pauseReason(peer.id) : undefined);
10979
11328
  const error = blockingCause ?? (accepted ? "an accepted delivery is awaiting your explicit confirmation" : "delivery held");
10980
- return void reply({ ok: false, error, held, waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
11329
+ return void reply({ ok: false, error, held, heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
10981
11330
  }
10982
11331
  peer.lastInboxAt = Date.now();
10983
11332
  let polling: ReturnType<InboxPolling["read"]>;
@@ -10988,9 +11337,9 @@ export async function startDaemon(opts: DaemonOptions) {
10988
11337
  } catch { polling = undefined; } // The pull already completed: advice must never discard its envelopes.
10989
11338
  writeStatus();
10990
11339
  if (envs.length) log(`${peer.id} read ${envs.length} queued message(s) through hub_inbox`);
10991
- 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 } } : {}) });
11340
+ 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 } } : {}) });
10992
11341
  } catch (error) {
10993
- 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) });
11342
+ 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) });
10994
11343
  return void reply({ ok: false, error: "delivery journal unavailable" });
10995
11344
  }
10996
11345
  }
@@ -11614,6 +11963,35 @@ export async function startDaemon(opts: DaemonOptions) {
11614
11963
  }
11615
11964
  return;
11616
11965
  }
11966
+ if (msg.op === "adopt-merge") {
11967
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer ? c.peer : undefined;
11968
+ 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" });
11969
+ let actorCurrent: () => void;
11970
+ const externalOwner = c.externalOwner;
11971
+ try {
11972
+ const sessionCurrent = c.role === "console" ? () => {
11973
+ if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed");
11974
+ } : operationalCurrent(sock);
11975
+ actorCurrent = () => {
11976
+ sessionCurrent();
11977
+ if (externalOwner && !currentExternalTools(c, true)) throw new Error("actor execution root changed");
11978
+ sessionCurrent(); // A fresh execution-root probe can service callbacks before it returns.
11979
+ if (c.peer !== (asker === USER ? undefined : asker) || c.externalOwner !== externalOwner) throw new Error("actor session changed");
11980
+ };
11981
+ actorCurrent();
11982
+ }
11983
+ 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" }); }
11984
+ const fence = () => {
11985
+ try { actorCurrent(); } catch { return "person or conductor session changed; reconnect and retry ahub sdlc adopt-merge"; }
11986
+ 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;
11987
+ };
11988
+ taskOpsInFlight++;
11989
+ void tasks.adoptMerge(asker, msg.id, msg.pr, fence).then(
11990
+ result => reply({ ok: true, ...result }),
11991
+ (error: Error) => reply({ ok: false, error: sanitize(error.message) }),
11992
+ ).finally(() => { taskOpsInFlight--; });
11993
+ return;
11994
+ }
11617
11995
  if (msg.op === "merge") {
11618
11996
  // #786 T1: the person or the one configured conductor asks for a guarded merge. Every request gets a reply, a refusal included.
11619
11997
  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;
@@ -11890,6 +12268,107 @@ export async function startDaemon(opts: DaemonOptions) {
11890
12268
  if (c.role !== "console") return void reply({ ok: false, error: "autonomy is a person-only command; run ahub autonomy in a person's terminal" });
11891
12269
  void autonomyCommand(msg.action, msg.environment, msg.confirmed, msg.confirmation).then(reply, () => reply({ ok: false, error: "project autonomy could not be changed" }));
11892
12270
  return;
12271
+ case "guidance_list":
12272
+ case "guidance_show":
12273
+ case "guidance_create":
12274
+ case "guidance_withdraw": {
12275
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12276
+ if (!actor) return void reply({ ok: false, error: "guidance is unavailable for this caller; use an authorized current project session" });
12277
+ const { t: _t, rid: _rid, ...input } = msg;
12278
+ const ownedCurrent = c.toolsOwner ? captureImplementerTools(c) : undefined;
12279
+ const current = () => {
12280
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || role === "tools" && c.peer !== actor || stopping)
12281
+ throw new PreEffectToolRefusal("guidance caller changed; reconnect in the current project session");
12282
+ if (c.externalOwner && !currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("guidance runtime owner changed; reconnect before retrying");
12283
+ };
12284
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
12285
+ if (msg.t === "guidance_list" || msg.t === "guidance_show") return void reply(guidanceRead(actor, msg.t === "guidance_list" ? "list" : "show", input));
12286
+ const op = msg.t === "guidance_create" ? "hub_guidance_create" : "hub_guidance_withdraw";
12287
+ void childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => taskOp(actor, op, input)).then(
12288
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }); } },
12289
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }));
12290
+ return;
12291
+ }
12292
+ case "guidance_probe_register":
12293
+ case "guidance_probe_start":
12294
+ case "guidance_probe_show":
12295
+ case "guidance_probe_cancel": {
12296
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12297
+ if ((role !== "console" && role !== "tools") || !actor) return void reply({ ok: false, error: "guidance probes require a person or the current configured conductor" });
12298
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) return void reply({ ok: false, error: "recovery or shutdown is holding guidance probe operations; inspect retained state after release" });
12299
+ const operation = msg.t === "guidance_probe_register" ? "guidance probe register" : msg.t === "guidance_probe_start" ? "guidance probe start"
12300
+ : msg.t === "guidance_probe_show" ? "guidance probe show" : "guidance probe cancel";
12301
+ let authorityCurrent: () => void;
12302
+ if (role === "tools") {
12303
+ try { authorityCurrent = admitOperational(sock, operation); }
12304
+ catch (error) { return void reply(operationalFailure(error)); }
12305
+ } else authorityCurrent = () => {
12306
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== "console" || stopping)
12307
+ throw new PreEffectToolRefusal("guidance probe console session changed; reconnect and inspect retained state");
12308
+ };
12309
+ const requestConnectionId = c.guidanceProbeConnectionId;
12310
+ if (!executionText(requestConnectionId, EXECUTION_REFERENCE_LIMITS.id))
12311
+ return void reply({ ok: false, error: "guidance probe request identity is unavailable; reconnect through the authenticated project connection" });
12312
+ let generation: string | number, nativeSession: string | null, owner: PeerAdapter | undefined;
12313
+ if (role === "console") {
12314
+ generation = requestConnectionId;
12315
+ nativeSession = null;
12316
+ } else {
12317
+ owner = bus.peers.get(actor);
12318
+ const peerGeneration = owner?.sessionGeneration, peerNativeSession = owner?.nativeSession;
12319
+ if (!owner || !("sessionGeneration" in owner) || !probeSessionGeneration(peerGeneration)
12320
+ || !("nativeSession" in owner) || typeof peerNativeSession !== "string"
12321
+ || !executionText(peerNativeSession, EXECUTION_REFERENCE_LIMITS.id))
12322
+ return void reply({ ok: false, error: "guidance probe conductor session identity is unavailable; reconnect the current native peer session" });
12323
+ generation = peerGeneration;
12324
+ nativeSession = peerNativeSession;
12325
+ }
12326
+ const current = (): void => {
12327
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || c.guidanceProbeConnectionId !== requestConnectionId
12328
+ || role === "tools" && (c.peer !== actor || bus.peers.get(actor) !== owner || owner!.sessionGeneration !== generation || owner!.nativeSession !== nativeSession))
12329
+ throw new PreEffectToolRefusal("guidance probe request connection or native peer session changed; inspect retained state and reconnect");
12330
+ authorityCurrent();
12331
+ };
12332
+ const requestContext: GuidanceProbeRequestContext = { actor, requestConnectionId, generation, nativeSession, current };
12333
+ const input = msg.registration;
12334
+ taskOpsInFlight++;
12335
+ const run = () => {
12336
+ current();
12337
+ if (recoveryActive() || bus.isRecoveryHeld || stopping) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance probe operations; inspect retained state after release");
12338
+ const action = () => msg.t === "guidance_probe_register" ? tasks.guidanceProbeRegister(actor, input)
12339
+ : msg.t === "guidance_probe_start" ? tasks.guidanceProbeStart(actor, msg.id, msg.revision, msg.variantId)
12340
+ : msg.t === "guidance_probe_show" ? tasks.guidanceProbeShow(actor, msg.id)
12341
+ : tasks.guidanceProbeCancel(actor, msg.id, msg.revision);
12342
+ const withRequest = () => guidanceProbeRequestContext.run(requestContext, action);
12343
+ return role === "tools" ? operationalContext.run({ actor, current }, withRequest) : withRequest();
12344
+ };
12345
+ void Promise.resolve().then(run).then(value => reply(msg.t === "guidance_probe_show" ? { ok: true, status: value } : { ok: true, receipt: value }), error => {
12346
+ if (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError) return reply({ ok: false, error: error.message });
12347
+ if (error instanceof OperationalAuthorityError) return reply(operationalFailure(error));
12348
+ return reply({ ok: false, error: "guidance probe operation is unconfirmed; inspect retained state before retrying" });
12349
+ })
12350
+ .finally(() => { taskOpsInFlight--; }).catch(() => {});
12351
+ return;
12352
+ }
12353
+ case "lineage_show":
12354
+ case "lineage_link": {
12355
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12356
+ if (!actor) return void reply({ ok: false, error: "execution lineage is unavailable for this caller; use an authorized project session" });
12357
+ const { t: _t, rid: _rid, ...input } = msg;
12358
+ const ownedCurrent = c.toolsOwner ? captureImplementerTools(c) : undefined;
12359
+ const current = () => {
12360
+ 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");
12361
+ if (c.externalOwner && !currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("execution lineage owner changed; reconnect in the current project session");
12362
+ };
12363
+ const op = msg.t === "lineage_show" ? "hub_lineage_show" : "hub_lineage_link";
12364
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
12365
+ // A pure read is checked and serialized in this stack, without a new policy-change await.
12366
+ if (op === "hub_lineage_show") return void reply(executionLineageRead(actor, input));
12367
+ void childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => taskOp(actor, op, input)).then(
12368
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "execution lineage caller changed; reconnect and retry" }); } },
12369
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "execution lineage unavailable; inspect the project task and retry" }));
12370
+ return;
12371
+ }
11893
12372
  case "model":
11894
12373
  if (c.role !== "console") return void reply(modelFailure("model overrides are person-only; run ahub model in a person's terminal"));
11895
12374
  return void reply(modelCommandSafe(msg, { source: "cli", scope: c, current: () => c.authed === true && !c.closed && c.role === "console" && sock.readyState === WebSocket.OPEN }));
@@ -11898,7 +12377,7 @@ export async function startDaemon(opts: DaemonOptions) {
11898
12377
  try { const current = publicReadCurrent(sock); current(); const view = publicSettingsView(); current(); return void reply({ ok: true, ...view }); }
11899
12378
  catch { return void reply({ ok: false, error: "public settings read unavailable for this caller" }); }
11900
12379
  }
11901
- return void reply({ ok: true, ...settingsView(), roster: rosterView(), configEdit: (() => { const view = configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
12380
+ return void reply({ ok: true, ...settingsView(), sdlc: sdlcSettingsView(), roster: rosterView(), configEdit: (() => { const view = configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
11902
12381
  case "settings_reload":
11903
12382
  if (c.role !== "console") return void reply({ ok: false, error: "settings are a person command" });
11904
12383
  return void reloadConfig("terminal", undefined, msg.confirm).then(reply, () => reply({ ok: false, error: "configuration reload could not be confirmed; inspect hub.log" }));
@@ -12259,6 +12738,8 @@ export async function startDaemon(opts: DaemonOptions) {
12259
12738
  }
12260
12739
  async function stopOnce(): Promise<void> {
12261
12740
  stopping = true;
12741
+ // A failed bounded probe drain must return before teardown/finalization. The retained DB, owned fixture handles and retryable shutdown remain available.
12742
+ await tasks.stopGuidanceProbes();
12262
12743
  kimiUsage.stop();
12263
12744
  controlWriteTelemetry?.stop();
12264
12745
  const roomsStopped = roomCommands.stop().catch(() => { log("room shutdown failed; inspect ahub room status after restart"); });
@@ -12329,6 +12810,7 @@ export async function startDaemon(opts: DaemonOptions) {
12329
12810
  memoryStore?.close();
12330
12811
  modelPreviews.clear(); modelOverrides.close();
12331
12812
  visuals.close();
12813
+ guidanceProbeStore.close();
12332
12814
  board.close();
12333
12815
  turnLog?.close();
12334
12816
  server.stop(true);