@staix/agent-hub 0.36.0 → 0.38.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 (121) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +1167 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +12 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +123 -151
  19. package/docs/profiles.md +1 -1
  20. package/docs/quickstart.md +15 -3
  21. package/docs/research.md +1 -1
  22. package/docs/sdlc.md +5 -3
  23. package/docs/security.md +25 -1
  24. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  25. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  26. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  27. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  28. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  29. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  30. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  31. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  32. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  33. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  34. package/docs/verified.json +25 -25
  35. package/package.json +3 -4
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +2403 -1444
  38. package/plugins/agent-hub/server.js +2480 -1509
  39. package/src/adapters/channel-peer.ts +7 -1
  40. package/src/adapters/claude-channel.ts +2 -1
  41. package/src/adapters/compat.ts +1 -1
  42. package/src/adapters/local-probe.ts +233 -0
  43. package/src/adapters/local-worker.ts +232 -21
  44. package/src/cli/console-state.ts +25 -6
  45. package/src/cli/console-versions.ts +99 -0
  46. package/src/cli/console.ts +13 -1
  47. package/src/cli/help.ts +2 -1
  48. package/src/cli/init.ts +3 -1
  49. package/src/cli/install-paths.ts +7 -2
  50. package/src/cli/main.ts +78 -7
  51. package/src/cli/output.ts +8 -4
  52. package/src/cli/runtime-version-warning.ts +2 -2
  53. package/src/cli/sdlc-output.ts +9 -5
  54. package/src/cli/upgrade-runtime.ts +1 -1
  55. package/src/hub/bus.ts +2 -2
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +6 -1
  58. package/src/hub/control-client.ts +5 -2
  59. package/src/hub/daemon.ts +195 -13
  60. package/src/hub/envelope.ts +6 -1
  61. package/src/hub/events.ts +3 -2
  62. package/src/hub/guidance-probe-store.ts +1044 -0
  63. package/src/hub/guidance-probes.ts +692 -0
  64. package/src/hub/inference.ts +18 -5
  65. package/src/hub/manager.ts +24 -1
  66. package/src/hub/operational-authority.ts +14 -1
  67. package/src/hub/peers.ts +5 -0
  68. package/src/hub/person-command.ts +25 -0
  69. package/src/hub/ports.ts +1 -1
  70. package/src/hub/progress.ts +23 -16
  71. package/src/hub/report.ts +2 -0
  72. package/src/hub/research.ts +1 -0
  73. package/src/hub/restart.ts +7 -0
  74. package/src/hub/sdlc-release-authorization.ts +139 -17
  75. package/src/hub/sdlc-release-policy.ts +100 -0
  76. package/src/hub/sdlc-release.ts +59 -7
  77. package/src/hub/supervision.ts +3 -2
  78. package/src/hub/tasks.ts +363 -7
  79. package/src/local/probe-errors.ts +28 -0
  80. package/src/local/probe-sandbox.ts +224 -0
  81. package/src/local/probe-types.ts +110 -0
  82. package/src/local/probe-workspace.ts +426 -0
  83. package/src/local/sandbox.ts +71 -2
  84. package/src/local/tools.ts +135 -9
  85. package/src/models/route/advisor-trigger.ts +88 -0
  86. package/src/models/route/config.ts +21 -17
  87. package/src/models/route/conversation-view.ts +179 -0
  88. package/src/models/route/decision-evidence.ts +1 -1
  89. package/src/models/route/decision.ts +114 -19
  90. package/src/models/route/escalation-control.ts +30 -0
  91. package/src/models/route/hub-prompts.ts +97 -0
  92. package/src/models/route/judge-choice.ts +155 -0
  93. package/src/models/route/judge-replies.ts +102 -0
  94. package/src/models/route/labels.ts +14 -70
  95. package/src/models/route/observation-signals.ts +250 -0
  96. package/src/models/route/plan-execute-choice.ts +27 -0
  97. package/src/models/route/relay-selector.ts +2 -2
  98. package/src/models/route/runtime.ts +115 -52
  99. package/src/models/route/turn-state.ts +77 -0
  100. package/src/omniroute/client.ts +3 -0
  101. package/src/ui/guidance-panel.ts +34 -2
  102. package/src/ui/guidance-view.ts +33 -0
  103. package/src/ui/plugin.ts +80 -23
  104. package/src/version.ts +4 -0
  105. package/templates/AGENTS.block.md +14 -14
  106. package/templates/adec/README.md +32 -0
  107. package/templates/adec/ahub.plan-execute.json +23 -0
  108. package/templates/adec/ahub.stage.json +23 -0
  109. package/templates/profiles/general.json +1 -1
  110. package/templates/profiles/research.json +1 -1
  111. package/templates/profiles/writing.json +1 -1
  112. package/LICENSES/Apache-2.0.txt +0 -204
  113. package/src/models/route/advisor.ts +0 -102
  114. package/src/models/route/escalation.ts +0 -82
  115. package/src/models/route/judge.ts +0 -23
  116. package/src/models/route/normalize.ts +0 -103
  117. package/src/models/route/plan-execute.ts +0 -52
  118. package/src/models/route/prompts.ts +0 -8
  119. package/src/models/route/signals.ts +0 -247
  120. package/src/models/route/state.ts +0 -54
  121. package/src/models/route/text.ts +0 -61
package/src/hub/daemon.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
2
+ import { GuidanceProbeStore } from "./guidance-probe-store.ts";
3
+ import { GuidanceProbeError, probeSessionGeneration, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
4
+ import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
2
5
  import { publicDeliveryBodies } from "./delivery-public.ts";
3
6
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
4
7
  import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
@@ -39,8 +42,9 @@ import { ActionBudgets, actionPolicyConfig, floorEnforcement, floorReads, type A
39
42
  import { actionGate, claudeActionClasses } from "./action-enforce.ts";
40
43
  import type { FloorFacts } from "./action-class.ts";
41
44
  import { ReleaseAuthorizations, releaseAuthorizationError } from "./sdlc-release-authorization.ts";
45
+ import { readCommittedReleasePolicy } from "./sdlc-release-policy.ts";
42
46
  import { parseReleaseGuardArgv, parseReleasePushUpdates } from "../cli/sdlc-release-guard.ts";
43
- import type { DocEvidence } from "./sdlc-release.ts";
47
+ import type { DocEvidence, ReleaseReportPolicy } from "./sdlc-release.ts";
44
48
  import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
45
49
  import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
46
50
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
@@ -91,7 +95,7 @@ import { INSTANCE_CONFIG_FILES, readInstanceConfig, withoutInertInstancePolicy,
91
95
  import { instanceBudgetHooks, projectBudgetHeadroom } from "./instance-budget.ts";
92
96
  import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
93
97
  import { ProgressObserver, normalizeCodexObservation, normalizeClaudeObservation } from "./progress.ts";
94
- import type { ToolObservation } from "../models/route/signals.ts";
98
+ import type { NativeToolObservation as ToolObservation } from "./progress.ts";
95
99
  import { createHash, randomBytes, randomUUID } from "node:crypto";
96
100
  import { appendFileSync, chmodSync, existsSync, fstatSync, mkdirSync, readFileSync, renameSync, rmSync, watchFile, unwatchFile, writeFileSync } from "node:fs";
97
101
  import { join, relative, resolve } from "node:path";
@@ -206,6 +210,7 @@ import { TaskWorktrees, originVerdict } from "./task-worktree.ts";
206
210
  import { displayPath, shelfInsideRoot, partition, readWorktreeFacts, type ShelfRow } from "./worktree-shelf.ts";
207
211
  import { PrObservations, refreshPrStates, refreshTargets } from "./worktree-prs.ts";
208
212
  import { Bus, ReviewInputHandoffError } from "./bus.ts";
213
+ import { queueResolveChoices, queueResolveCommand } from "./person-command.ts";
209
214
  import { attribute, deliveryTask, type TaskAttribution } from "./attribution.ts";
210
215
  import { ACCEPTED_SETTLE_TIMEOUT_REASON, DeliveryJournal } from "./delivery-journal.ts";
211
216
  import { assertHubDbCompatible } from "./db-schema.ts";
@@ -219,7 +224,7 @@ import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanit
219
224
  import { BasePeer, DEFAULT_WATCHDOG_MS, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
220
225
  import { ClaudeTodoSource, DoingTracker, readAiTitle, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
221
226
  import { MemoryClient } from "../memory/client.ts";
222
- import { VERSION } from "../version.ts";
227
+ import { VERSION, displayVersion } from "../version.ts";
223
228
  import { appendRecords, taskRecords } from "./research.ts";
224
229
  import { readEvidence } from "./research-record.ts";
225
230
  import { memoryFigures, onlyTaskMemory, UNKNOWN_MEMORY_FIGURES, type MemoryFigures } from "./research-memory.ts";
@@ -365,6 +370,8 @@ export interface HubConfig {
365
370
  pet?: false | Record<string, unknown>;
366
371
  /** Machine-local fields a config file set but git could not vouch for, and why (issue #17). */
367
372
  ignored?: string[];
373
+ /** Reporting-only notice that machine-local release policy was ignored; never part of accepted policy authority. */
374
+ releasePolicyNotices?: string[];
368
375
  /** Settings that were removed or are about to be (issue #83): what each does now, for `hub.log` and `ahub doctor`. */
369
376
  retired?: string[];
370
377
  }
@@ -539,6 +546,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
539
546
  const instances = instanceConfig.instances;
540
547
  const adapterCatalog = instanceConfig.catalog;
541
548
  const ignored: string[] = [...instanceConfig.ignored];
549
+ const releasePolicyNotices: string[] = [];
542
550
  const inertModuleRoster = !!instanceConfig.adapter_modules?.length;
543
551
  const appliedPermissionSources: NonNullable<HubConfig["permission_default_sources"]> = {};
544
552
  let retiredPetWindow = false;
@@ -594,7 +602,14 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
594
602
  if (file.research !== undefined && (!file.research || typeof file.research !== "object" || Array.isArray(file.research))) throw new Error("research must be an object");
595
603
  const hasRunners = file.research && Object.hasOwn(file.research, "runners"), runnerDeclarations: unknown = hasRunners ? file.research.runners : undefined;
596
604
  const why = stripUntrusted(file, DEFAULT_CONFIG, cwd, name);
597
- if (why) ignored.push(why);
605
+ if (why) {
606
+ const notices = why.split("; ");
607
+ releasePolicyNotices.push(...notices.filter(notice => notice.startsWith("release in .agenthub/config.local.json ignored:")));
608
+ const existingNotices = notices.filter(notice => !notice.startsWith("release in .agenthub/config.local.json ignored:"));
609
+ if (existingNotices.length) ignored.push(existingNotices.join("; "));
610
+ }
611
+ // Release policy is read directly from the candidate commit by the S6 host reader, never runtime config.
612
+ delete file.release;
598
613
  if (hasRunners) file.research.runners = parseResearchRunners(runnerDeclarations);
599
614
  for (const [peer, mode] of Object.entries(permissionDefaults(file.permission_modes, instances, adapterCatalog))) appliedPermissionSources[peer] = { mode, source: `.agenthub/${name}` };
600
615
  return [file];
@@ -698,6 +713,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
698
713
  capabilities: { ...file.capabilities },
699
714
  mlx,
700
715
  ...(ignored.length ? { ignored } : {}),
716
+ ...(releasePolicyNotices.length ? { releasePolicyNotices } : {}),
701
717
  ...(retired.length ? { retired } : {}),
702
718
  };
703
719
  }
@@ -852,12 +868,16 @@ interface Client {
852
868
  launchId?: string;
853
869
  /** Display-only retained standby id; peer operations stay fenced until ownsSocket confirms attachment. */
854
870
  standbyId?: string;
871
+ /** Host-minted per connection and durable only as a private replay comparator; never a token, live authority or wire claim. */
872
+ guidanceProbeConnectionId?: string;
855
873
  retainStandby?: boolean;
856
874
  peerGeneration?: string | number;
857
875
  detachedByPerson?: boolean;
858
876
  channel?: boolean;
859
877
  channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
860
878
  clientPid?: number;
879
+ /** #1385: the agent-hub version the client's hello reported, kept only when `displayVersion` accepts it. Display only. */
880
+ clientVersion?: string;
861
881
  cwd?: string;
862
882
  externalOwner?: { owner: PeerAdapter; launchId: string; generation?: string };
863
883
  toolsOwner?: { owner: PeerAdapter; launchId: string; generation: string; cwd: string };
@@ -869,6 +889,13 @@ interface Client {
869
889
  closed?: true;
870
890
  }
871
891
  type Sock = ServerWebSocket<Client>;
892
+ interface GuidanceProbeRequestContext {
893
+ actor: PeerId;
894
+ requestConnectionId: string;
895
+ generation: string | number;
896
+ nativeSession: string | null;
897
+ current: () => void;
898
+ }
872
899
 
873
900
 
874
901
  /**
@@ -1160,6 +1187,7 @@ export async function startDaemon(opts: DaemonOptions) {
1160
1187
  mkdirSync(opts.stateDir, { recursive: true });
1161
1188
  const operationalLogSubscribers=new Map<Sock,()=>void>();
1162
1189
  const operationalContext=new AsyncLocalStorage<{actor:string;current:()=>void}|undefined>();
1190
+ const guidanceProbeRequestContext = new AsyncLocalStorage<GuidanceProbeRequestContext>();
1163
1191
  const checkOperational=(authority:SettingAuthority)=>{if(authority==="conductor"){const scope=operationalContext.getStore();if(!scope)throw new OperationalAuthorityError("operational conductor authority unavailable");scope.current();}};
1164
1192
  const logFile = join(opts.stateDir, "hub.log");
1165
1193
  // The state dir can vanish under a running hub (issue #56): a log line must never take a handler down with it.
@@ -1384,6 +1412,7 @@ export async function startDaemon(opts: DaemonOptions) {
1384
1412
  }
1385
1413
  if (sock.data.session && sock.data.peer) sessionIds.delete(sock.data.peer);
1386
1414
  consoles.delete(sock);
1415
+ toolsSockets.delete(sock);
1387
1416
  operationalLogSubscribers.delete(sock);
1388
1417
  sock.data.tail?.();
1389
1418
  sock.data.watch?.();
@@ -2261,6 +2290,26 @@ export async function startDaemon(opts: DaemonOptions) {
2261
2290
  const uiEvents: { seq: number; event: BusEvent }[] = [];
2262
2291
  let uiSequence = 0;
2263
2292
  const consoles = new Set<Sock>();
2293
+ /** #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. */
2294
+ const toolsSockets = new Set<Sock>();
2295
+ /** Per peer, the sorted distinct versions its open tools connections reported (`unreported` for a hello without one). One pass per status read. */
2296
+ const toolsVersions = (): Map<string, string[]> => {
2297
+ const byPeer = new Map<string, Set<string>>();
2298
+ for (const sock of toolsSockets) {
2299
+ const peer = sock.data.peer;
2300
+ if (!peer || sock.data.closed) continue;
2301
+ const seen = byPeer.get(peer) ?? new Set<string>();
2302
+ seen.add(sock.data.clientVersion ?? "unreported");
2303
+ byPeer.set(peer, seen);
2304
+ }
2305
+ return new Map([...byPeer].map(([peer, seen]) => [peer, [...seen].sort()]));
2306
+ };
2307
+ /** #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. */
2308
+ const ahubStatus = (p: PeerAdapter | undefined, tools: string[] | undefined) => {
2309
+ const client = p?.hubClient;
2310
+ const ahub = !p ? undefined : !client ? { runs: "daemon" as const, version: VERSION } : client.attached ? { runs: "client" as const, version: client.version ?? "unreported" } : undefined;
2311
+ return { ...(ahub ? { ahub } : {}), ...(tools?.length ? { ahubTools: tools } : {}) };
2312
+ };
2264
2313
  /** A line for the human: hub.log and every open `ahub tail`. */
2265
2314
  const notify = (line: string) => {
2266
2315
  log(line);
@@ -2274,19 +2323,43 @@ export async function startDaemon(opts: DaemonOptions) {
2274
2323
  const inboxPolling = new InboxPolling();
2275
2324
  startupTimings.mark("model_runtime");
2276
2325
  const board = new Board(join(opts.stateDir, "hub.db"));
2326
+ let guidanceProbeStore: GuidanceProbeStore;
2327
+ try { guidanceProbeStore = new GuidanceProbeStore(join(opts.stateDir, "hub.db")); }
2328
+ catch { board.close(); throw new Error("guidance probe storage is unavailable; inspect retained probe state and hub.db before restarting"); }
2277
2329
  try {
2278
2330
  const retainedExecutionReferences = board.executionReferencesIntegrity(), expected = restored?.integrity?.executionReferences;
2279
2331
  if (restored?.integrity && (expected ? expected.count !== retainedExecutionReferences.count || expected.digest !== retainedExecutionReferences.digest : retainedExecutionReferences.count !== 0)) throw new Error("changed recovery binding");
2280
2332
  } catch {
2281
- board.close(); throw new Error("execution reference state or recovery binding is unavailable; restore trusted project state and choose a compatible recovery target before retrying");
2333
+ 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");
2282
2334
  }
2283
2335
  try {
2284
2336
  const retainedGuidance = board.guidanceVariantsIntegrity(), expected = restored?.integrity?.guidanceVariants;
2285
2337
  if (restored?.integrity && (expected ? expected.experiments !== retainedGuidance.experiments || expected.variants !== retainedGuidance.variants
2286
2338
  || expected.digest !== retainedGuidance.digest : retainedGuidance.experiments !== 0 || retainedGuidance.variants !== 0)) throw new Error("changed recovery binding");
2287
2339
  } catch {
2288
- board.close(); throw new Error("guidance variant state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2340
+ 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");
2341
+ }
2342
+ try {
2343
+ const retained = guidanceProbeStore.integrity(), expected = restored?.integrity?.guidanceProbes;
2344
+ if (restored && (expected ? expected.experiments !== retained.experiments || expected.sessions !== retained.sessions || expected.digest !== retained.digest
2345
+ : retained.experiments !== 0 || retained.sessions !== 0)) throw new Error("changed recovery binding");
2346
+ } catch {
2347
+ 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");
2289
2348
  }
2349
+ startupCleanup.push(() => guidanceProbeStore.close());
2350
+ // #1226 T3: the one explicit crash reconcile. A fresh process has no probe in flight, so a session still `reserved` or `running` belongs to a previous process
2351
+ // and is recorded as unknown with an unknown receipt (never launched, retried or turned into a success). It runs after the integrity comparison above, never
2352
+ // while a recovery holds the stores (the release path calls it again), and a failure is logged and leaves the rows untouched for the next start.
2353
+ const reconcileGuidanceProbes = (): void => {
2354
+ try {
2355
+ // Every experiment is tried even when one fails; each failure is logged with its reason class and experiment id, never its content.
2356
+ const { reconciled, failed } = guidanceProbeStore.reconcile(undefined, (key, error) =>
2357
+ log(`guidance probe reconcile failed for ${key ? `experiment ${key.id.slice(0, 12)}` : "an unreadable experiment key"} (${error instanceof Error ? error.constructor.name : "error"}${error instanceof GuidanceProbeError ? `: ${error.reason}` : ""}); its sessions stay as stored and are retried at the next start`));
2358
+ if (reconciled > 0) log(`guidance probe reconcile: ${reconciled} session${reconciled === 1 ? "" : "s"} left by a previous process recorded as unknown`);
2359
+ if (failed > 0) log(`guidance probe reconcile: ${failed} experiment${failed === 1 ? "" : "s"} could not be reconciled`);
2360
+ } catch (error) { log(`guidance probe reconcile failed (${error instanceof GuidanceProbeError ? error.reason : "error"}); the sessions stay as stored and are retried at the next start`); }
2361
+ };
2362
+ if (!recoveryActive()) reconcileGuidanceProbes();
2290
2363
  const visuals = new VisualStore(join(opts.stateDir, "hub.db"));
2291
2364
  startupCleanup.push(() => visuals.close());
2292
2365
  // Held recovery must compare the source's exact rows before any retention mutation.
@@ -2570,6 +2643,7 @@ export async function startDaemon(opts: DaemonOptions) {
2570
2643
  if (strayChecks.length) log(`checks ignored for ${strayChecks.join(", ")}: not a task class with a command (classes: ${CLASSES.join(", ")})`);
2571
2644
  // Commands and the other machine-local fields came only from a file git vouched for (loadConfig, issue #17).
2572
2645
  for (const line of config.ignored ?? []) log(`${line}; only a config file nobody committed may set it`);
2646
+ for (const line of config.releasePolicyNotices ?? []) log(`config: ${line}`);
2573
2647
  for (const line of config.retired ?? []) log(`config: ${line}`);
2574
2648
  const checksAllowed = Object.keys(checkCommands).length > 0;
2575
2649
  const checkTimeoutS = typeof config.checks.timeout_s === "number" && config.checks.timeout_s >= 1 ? Math.min(config.checks.timeout_s, 3600) : 600;
@@ -2856,7 +2930,13 @@ export async function startDaemon(opts: DaemonOptions) {
2856
2930
  && left.cwd === right.cwd && left.socket === right.socket && left.launchId === right.launchId && left.generation === right.generation && left.repo === right.repo;
2857
2931
  const projectSpecs = specInspectorAt(opts.cwd);
2858
2932
  let specsMissingBlockHintShown = false;
2933
+ let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
2859
2934
  const tasks: Tasks = new Tasks({
2935
+ guidanceProbes: { store: guidanceProbeStore, session: by => {
2936
+ const request = guidanceProbeRequestContext.getStore();
2937
+ return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
2938
+ requestConnectionId: request.requestConnectionId, current: request.current } : undefined;
2939
+ } },
2860
2940
  releaseWindow,
2861
2941
  researchRunners: () => {
2862
2942
  if (config.research.runners === undefined) return {};
@@ -2959,7 +3039,12 @@ export async function startDaemon(opts: DaemonOptions) {
2959
3039
  return report;
2960
3040
  },
2961
3041
  specsRead: (action, paths) => projectSpecs.read(action, paths),
2962
- sdlc: { config: () => lifecycleConfig, gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound) },
3042
+ sdlc: {
3043
+ config: () => lifecycleConfig,
3044
+ gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
3045
+ reportPolicy: (head, repo) => releaseReportPolicy ? releaseReportPolicy(head, repo)
3046
+ : { versionSource: "unknown", docsSource: "unknown", authorization: "unavailable" },
3047
+ },
2963
3048
  board,
2964
3049
  bus,
2965
3050
  executionBudget,
@@ -4565,7 +4650,7 @@ export async function startDaemon(opts: DaemonOptions) {
4565
4650
  if (agentDrift.length && !stopping && !recoveryActive()) try { offerAgentDrift(); } catch { /* the next tick tries again */ }
4566
4651
  for (const pending of checkpointWaits.values()) if (!pending.valid()) pending.done(undefined);
4567
4652
  for (const [id, request] of permissions) if (request.expiresAt > Date.now()) supervision.approvalWaiting({ id, peer: request.peer, tool: request.tool ?? "unknown", createdAt: request.createdAt });
4568
- for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id);
4653
+ for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id, () => holdCommand(row.peer, row.id));
4569
4654
  feedBudgetPauses();
4570
4655
  supervision.checkRound();
4571
4656
  try {
@@ -6506,14 +6591,18 @@ export async function startDaemon(opts: DaemonOptions) {
6506
6591
 
6507
6592
  const releaseAuthorizations = new ReleaseAuthorizations(opts.cwd, {
6508
6593
  docs: opts.releaseDocEvidence,
6594
+ policy: (commit, git) => readCommittedReleasePolicy(git, commit),
6509
6595
  gh: (args, timeout) => sdlcGh(args, timeout, opts.cwd),
6510
6596
  current: () => !stopping && !recoveryActive() && !bus.isRecoveryHeld,
6511
6597
  conductor: () => {
6512
6598
  const peer = conductorPeer(config.roles);
6513
6599
  return peer && !turns.get(peer)?.private && !contextPii(peer) ? peer : undefined;
6514
6600
  },
6515
- 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 }),
6601
+ record: receipt => event("source" in receipt.docs
6602
+ ? { type: "release_authorization", by: receipt.by, authorization: receipt.id, commit: receipt.commit, version: receipt.version, docs: "none" }
6603
+ : { type: "release_authorization", by: receipt.by, authorization: receipt.id, commit: receipt.commit, version: receipt.version, docsDigest: receipt.docs.digest, documents: receipt.docs.documents }),
6516
6604
  });
6605
+ releaseReportPolicy = (head, repo) => releaseAuthorizations.reportPolicy(head, repo);
6517
6606
  const terminalReads = terminalOwnerReads();
6518
6607
  const terminalLaunches = new TerminalLaunches({
6519
6608
  owner: row => {
@@ -6559,6 +6648,7 @@ export async function startDaemon(opts: DaemonOptions) {
6559
6648
  let releasing = false; // gone-owner release (#6) and the ready sweep (#34): one run at a time, and a recovery commit waits for it
6560
6649
  const recoveryReady = () => {
6561
6650
  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;
6651
+ if (tasks.guidanceProbesPending() !== 0) return false; // Active and uncertain fixture work retains its project lane.
6562
6652
  if (checkPending.size !== 0) return false;
6563
6653
  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
6564
6654
  if (tasks.queuePressureRechecksPending() !== 0) return false;
@@ -6871,13 +6961,14 @@ export async function startDaemon(opts: DaemonOptions) {
6871
6961
  const researchRunners = board.runnerReceiptIntegrity();
6872
6962
  const researchEvidence = board.researchEvidenceIntegrity();
6873
6963
  const guidanceVariants = board.guidanceVariantsIntegrity();
6964
+ const guidanceProbes = guidanceProbeStore.integrity();
6874
6965
  const executionReferences = board.executionReferencesIntegrity();
6875
6966
  const reviewComments = board.reviewCommentsIntegrity();
6876
6967
  const modelState = modelOverrides.integrity();
6877
6968
  const visualIntegrity = visuals.integrity();
6878
6969
  if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
6879
6970
  throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
6880
- return { queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
6971
+ return { queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
6881
6972
  };
6882
6973
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
6883
6974
  const integrityAs = (expected: unknown) => {
@@ -6960,6 +7051,9 @@ export async function startDaemon(opts: DaemonOptions) {
6960
7051
  const queueBackpressure = tasks.queuePressureStatus(peerIds);
6961
7052
  const crashLines = crashView();
6962
7053
  const deliveryFailures = bus.failedDeliveryCounts();
7054
+ const toolsByPeer = toolsVersions();
7055
+ // #1385: separate metadata, like roleInfo (#295), so the legacy peer row keeps its shape.
7056
+ const peerVersions = Object.fromEntries(peerIds.map(id => [id, ahubStatus(bus.peers.get(id), toolsByPeer.get(id))] as const).filter(([, row]) => Object.keys(row).length));
6963
7057
  const view = {
6964
7058
  ...(deliveryFailures ? { deliveryFailures } : {}),
6965
7059
  ...runtimeModelProjection(),
@@ -7011,6 +7105,7 @@ export async function startDaemon(opts: DaemonOptions) {
7011
7105
  peers: Object.fromEntries(
7012
7106
  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 ?? [] } : {}) }]; }),
7013
7107
  ),
7108
+ peerVersions,
7014
7109
  taskWip: tasks.wipBreakdown(peerIds),
7015
7110
  boardReadCapabilities: { releaseFilter: true, columnMetadata: true },
7016
7111
  actionPolicyInfo: Object.fromEntries(peerIds.map(id => { const e = actionEnforcement(id); return [id, actionBudgets.status(id, e.enforced, e.reason)]; })),
@@ -7092,14 +7187,19 @@ export async function startDaemon(opts: DaemonOptions) {
7092
7187
  return bus.queueList(peer, true).filter(row => row.state === "needs_review").map(row => ({
7093
7188
  id: row.id, senders: [...new Set(row.originals.map(env => sanitize(env.from)))],
7094
7189
  kinds: [...new Set(row.originals.map(env => env.kind))], createdAt: row.createdAt,
7095
- reason: row.reason,
7190
+ reason: row.reason, revision: row.revision,
7096
7191
  context: deliveryTaskContext(row.originals, board, peer),
7097
7192
  }));
7098
7193
  }
7194
+ /** #1399: the full command for one held row, with the choices the hub cannot make for the person. */
7195
+ function holdCommand(peer: PeerId, id: string): string {
7196
+ const row = heldRows(peer).find(held => held.id === id);
7197
+ return `${queueResolveCommand(row ? { ...row, peer, state: "needs_review" } : { id, peer }, opts.cwd)} (${queueResolveChoices("needs_review")})`;
7198
+ }
7099
7199
  function queueHold(peer: PeerId): string | undefined {
7100
7200
  const rows = heldRows(peer);
7101
7201
  if (!rows.length) return undefined;
7102
- return rows.map(row => `held by needs_review ${row.id} (from ${row.senders.join(",")}; kind ${row.kinds.join(",")}; age ${Math.max(0, Math.floor((Date.now() - row.createdAt) / 1000))}s${row.context ? `; ${row.context}` : ""}); ahub queue resolve ${row.id} --action completed|retry|discard --reason <text>`).join("; ");
7202
+ return rows.map(row => `held by needs_review ${row.id} (from ${row.senders.join(",")}; kind ${row.kinds.join(",")}; age ${Math.max(0, Math.floor((Date.now() - row.createdAt) / 1000))}s${row.context ? `; ${row.context}` : ""}); ${queueResolveCommand({ ...row, peer, state: "needs_review" }, opts.cwd)} (${queueResolveChoices("needs_review")})`).join("; ");
7103
7203
  }
7104
7204
  let settlingSuperseded = false;
7105
7205
  function settleSupersededDeliveries() {
@@ -7129,7 +7229,7 @@ export async function startDaemon(opts: DaemonOptions) {
7129
7229
  for (const peer of bus.knownPeers()) {
7130
7230
  const rows = heldRows(peer);
7131
7231
  if (!rows.some(row => !noticedHolds.has(row.id))) continue;
7132
- for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id); }
7232
+ for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id, () => holdCommand(peer, row.id)); }
7133
7233
  notify(`${peer} queue ${queueHold(peer)}`);
7134
7234
  }
7135
7235
  writeStatus();
@@ -9469,6 +9569,7 @@ export async function startDaemon(opts: DaemonOptions) {
9469
9569
  }
9470
9570
  function declaredPaths(value: unknown, prefix = ""): string[] {
9471
9571
  if (prefix === "_autonomy" || prefix.startsWith("_autonomy.")) return [];
9572
+ if (prefix === "release" || prefix.startsWith("release.")) return [];
9472
9573
  if (prefix === "pet.window") return [];
9473
9574
  // Retired dictionaries never enter active publication; hub ids remain opaque keys.
9474
9575
  if (prefix === "routing.targets" || prefix === "routing.routes") return [];
@@ -9578,11 +9679,13 @@ export async function startDaemon(opts: DaemonOptions) {
9578
9679
  guarded.length = 0; previews.length = 0;
9579
9680
  }
9580
9681
  candidate.retired = fileConfig.retired;
9682
+ candidate.releasePolicyNotices = fileConfig.releasePolicyNotices;
9581
9683
  routing.retired = sources.routing.retired;
9582
9684
  const changes = configChanges({ ...config, roles: policyRoles }, candidate, [{ catalog: adapterCatalog, instances: declarations }, configIdentityScope(acceptedSources.identity), configIdentityScope(sources.identity)]);
9583
9685
  const running = structuredClone({ ...config, roles: policyRoles });
9584
9686
  for (const change of changes) if (change.applies !== "restart") putConfig(running, change.key, change.after);
9585
9687
  running.retired = fileConfig.retired;
9688
+ running.releasePolicyNotices = fileConfig.releasePolicyNotices;
9586
9689
  validateEffectiveConfig(running, adapterCatalog);
9587
9690
  conductorPeer(running.roles);
9588
9691
  for (const peer of Object.keys(running.catalog_roles ?? {})) selectedRoles(peer, running.roles, { ...resolvedProfile.catalog_roles, ...catalogAssignments(running.catalog_roles) }, catalog);
@@ -9663,6 +9766,9 @@ export async function startDaemon(opts: DaemonOptions) {
9663
9766
  const priorRetired = new Set(config.retired ?? []);
9664
9767
  config.retired = prepared.running.retired;
9665
9768
  for (const line of config.retired ?? []) if (!priorRetired.has(line)) log(`config: ${line}`);
9769
+ const priorReleaseNotices = new Set(config.releasePolicyNotices ?? []);
9770
+ config.releasePolicyNotices = prepared.running.releasePolicyNotices;
9771
+ for (const line of config.releasePolicyNotices ?? []) if (!priorReleaseNotices.has(line)) log(`config: ${line}`);
9666
9772
  config.permission_default_sources = candidate.permission_default_sources;
9667
9773
  refreshAutonomyConsent(prepared.fileConfig);
9668
9774
  for (const peer of changedPermissionDefaults) applyPendingPermissionDefault(peer);
@@ -10336,6 +10442,7 @@ export async function startDaemon(opts: DaemonOptions) {
10336
10442
  // #272: the rest of what recoveryReady() waits for, so the upgrade screen can name the wait. Display only.
10337
10443
  ...(taskOpsInFlight !== 0 ? ["a task command in flight"] : []),
10338
10444
  ...(tasks.checksPending() !== 0 ? ["completion checks queued or running"] : []),
10445
+ ...(tasks.guidanceProbesPending() !== 0 ? ["guidance probe work in flight"] : []),
10339
10446
  ...(tasks.autoPullsPending() !== 0 ? ["an automatic backlog pull in flight"] : []),
10340
10447
  ...(tasks.queuePressureRechecksPending() !== 0 ? ["a queue-pressure assignment recheck in flight"] : []),
10341
10448
  ...(tasks.schedulesPending() !== 0 ? ["a scheduled task proposal in flight"] : []),
@@ -10368,6 +10475,10 @@ export async function startDaemon(opts: DaemonOptions) {
10368
10475
  ? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
10369
10476
  };
10370
10477
  const incompatibleRecoveryTarget = () => {
10478
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
10479
+ try { if (guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
10480
+ catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
10481
+ }
10371
10482
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_variants")) {
10372
10483
  try { if (board.hasGuidanceVariants()) return "target lacks guidance_variants; retained immutable variants require a supporting daemon; choose a target advertising guidance_variants"; }
10373
10484
  catch { return "guidance variant compatibility is unknown; inspect retained storage or choose a supporting target"; }
@@ -10626,6 +10737,7 @@ export async function startDaemon(opts: DaemonOptions) {
10626
10737
  archiveRestartSnapshot(opts.stateDir, op);
10627
10738
  recoveryPhase = "released";
10628
10739
  clearTimeout(recoveryLeaseTimer);
10740
+ reconcileGuidanceProbes();
10629
10741
  bus.setRecoveryHold(false);
10630
10742
  budget.setRecoveryHold(false); tasks.scheduleQueuePressureRecheck();
10631
10743
  writeStatus();
@@ -10892,6 +11004,8 @@ export async function startDaemon(opts: DaemonOptions) {
10892
11004
  c.authed = true;
10893
11005
  c.protocol = selectedProtocol;
10894
11006
  c.role = msg.role;
11007
+ c.guidanceProbeConnectionId = randomUUID(); // Private comparator only; never sent, persisted separately or accepted from hello.
11008
+ c.clientVersion = displayVersion(msg.clientVersion);
10895
11009
  if (c.role === "console") consoles.add(sock);
10896
11010
  else if (c.role === "tools" && sessionHello(msg)) {
10897
11011
  // 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
@@ -10958,6 +11072,7 @@ export async function startDaemon(opts: DaemonOptions) {
10958
11072
  if (typeof msg.cwd === "string" && msg.cwd.length <= 4096) sock.data.cwd = msg.cwd;
10959
11073
  const clientPid = Number.isSafeInteger(msg.clientPid) && msg.clientPid > 0 && msg.clientPid <= 2_147_483_647 ? msg.clientPid as number : undefined;
10960
11074
  sock.data.clientPid = clientPid;
11075
+ sock.data.clientVersion = c.clientVersion;
10961
11076
  const pushOverPullOnly = msg.channel !== false && ws.attached && ws.pullOnly && !ws.claiming;
10962
11077
  const hasLiveHolder = ws.attached || ws.claiming;
10963
11078
  if (c.retainStandby && hasLiveHolder && !pushOverPullOnly) {
@@ -10986,6 +11101,7 @@ export async function startDaemon(opts: DaemonOptions) {
10986
11101
  }
10987
11102
  }
10988
11103
  // #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.
11104
+ if (c.role === "tools" && !c.session) toolsSockets.add(sock);
10989
11105
  if (c.role === "peer" || c.role === "tools") event(attachEvent({ role: c.role, peer: c.peer, launchId: c.launchId, ...(c.session ? { session: true } : {}) }));
10990
11106
  return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL, features: DAEMON_FEATURES,
10991
11107
  ...(c.session ? { session: c.peer } : {}), ...(c.standbyId ? { standby: true, standbyId: c.standbyId } : {}) });
@@ -12193,6 +12309,69 @@ export async function startDaemon(opts: DaemonOptions) {
12193
12309
  error => reply({ ok: false, error: error instanceof Error ? error.message : "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }));
12194
12310
  return;
12195
12311
  }
12312
+ case "guidance_probe_register":
12313
+ case "guidance_probe_start":
12314
+ case "guidance_probe_show":
12315
+ case "guidance_probe_receipts":
12316
+ case "guidance_probe_cancel": {
12317
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
12318
+ if ((role !== "console" && role !== "tools") || !actor) return void reply({ ok: false, error: "guidance probes require a person or the current configured conductor" });
12319
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) return void reply({ ok: false, error: "recovery or shutdown is holding guidance probe operations; inspect retained state after release" });
12320
+ const operation = msg.t === "guidance_probe_register" ? "guidance probe register" : msg.t === "guidance_probe_start" ? "guidance probe start"
12321
+ : msg.t === "guidance_probe_show" ? "guidance probe show" : msg.t === "guidance_probe_receipts" ? "guidance probe receipts" : "guidance probe cancel";
12322
+ let authorityCurrent: () => void;
12323
+ if (role === "tools") {
12324
+ try { authorityCurrent = admitOperational(sock, operation); }
12325
+ catch (error) { return void reply(operationalFailure(error)); }
12326
+ } else authorityCurrent = () => {
12327
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== "console" || stopping)
12328
+ throw new PreEffectToolRefusal("guidance probe console session changed; reconnect and inspect retained state");
12329
+ };
12330
+ const requestConnectionId = c.guidanceProbeConnectionId;
12331
+ if (!executionText(requestConnectionId, EXECUTION_REFERENCE_LIMITS.id))
12332
+ return void reply({ ok: false, error: "guidance probe request identity is unavailable; reconnect through the authenticated project connection" });
12333
+ let generation: string | number, nativeSession: string | null, owner: PeerAdapter | undefined;
12334
+ if (role === "console") {
12335
+ generation = requestConnectionId;
12336
+ nativeSession = null;
12337
+ } else {
12338
+ owner = bus.peers.get(actor);
12339
+ const peerGeneration = owner?.sessionGeneration, peerNativeSession = owner?.nativeSession;
12340
+ if (!owner || !("sessionGeneration" in owner) || !probeSessionGeneration(peerGeneration)
12341
+ || !("nativeSession" in owner) || typeof peerNativeSession !== "string"
12342
+ || !executionText(peerNativeSession, EXECUTION_REFERENCE_LIMITS.id))
12343
+ return void reply({ ok: false, error: "guidance probe conductor session identity is unavailable; reconnect the current native peer session" });
12344
+ generation = peerGeneration;
12345
+ nativeSession = peerNativeSession;
12346
+ }
12347
+ const current = (): void => {
12348
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || c.guidanceProbeConnectionId !== requestConnectionId
12349
+ || role === "tools" && (c.peer !== actor || bus.peers.get(actor) !== owner || owner!.sessionGeneration !== generation || owner!.nativeSession !== nativeSession))
12350
+ throw new PreEffectToolRefusal("guidance probe request connection or native peer session changed; inspect retained state and reconnect");
12351
+ authorityCurrent();
12352
+ };
12353
+ const requestContext: GuidanceProbeRequestContext = { actor, requestConnectionId, generation, nativeSession, current };
12354
+ const input = msg.registration;
12355
+ taskOpsInFlight++;
12356
+ const run = () => {
12357
+ current();
12358
+ if (recoveryActive() || bus.isRecoveryHeld || stopping) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance probe operations; inspect retained state after release");
12359
+ const action = (): Promise<ProbePublicReceipt | ProbePublicStatus | ProbeReceiptExport> => msg.t === "guidance_probe_register" ? tasks.guidanceProbeRegister(actor, input)
12360
+ : msg.t === "guidance_probe_start" ? tasks.guidanceProbeStart(actor, msg.id, msg.revision, msg.variantId)
12361
+ : msg.t === "guidance_probe_show" ? tasks.guidanceProbeShow(actor, msg.id)
12362
+ : msg.t === "guidance_probe_receipts" ? tasks.guidanceProbeReceipts(actor, msg.id)
12363
+ : tasks.guidanceProbeCancel(actor, msg.id, msg.revision);
12364
+ const withRequest = () => guidanceProbeRequestContext.run(requestContext, action);
12365
+ return role === "tools" ? operationalContext.run({ actor, current }, withRequest) : withRequest();
12366
+ };
12367
+ void Promise.resolve().then(run).then(value => reply(msg.t === "guidance_probe_show" ? { ok: true, status: value } : msg.t === "guidance_probe_receipts" ? { ok: true, receipts: value } : { ok: true, receipt: value }), error => {
12368
+ if (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError) return reply({ ok: false, error: error.message });
12369
+ if (error instanceof OperationalAuthorityError) return reply(operationalFailure(error));
12370
+ return reply({ ok: false, error: "guidance probe operation is unconfirmed; inspect retained state before retrying" });
12371
+ })
12372
+ .finally(() => { taskOpsInFlight--; }).catch(() => {});
12373
+ return;
12374
+ }
12196
12375
  case "lineage_show":
12197
12376
  case "lineage_link": {
12198
12377
  const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && PEER_ID.test(c.peer) ? c.peer : undefined;
@@ -12581,6 +12760,8 @@ export async function startDaemon(opts: DaemonOptions) {
12581
12760
  }
12582
12761
  async function stopOnce(): Promise<void> {
12583
12762
  stopping = true;
12763
+ // A failed bounded probe drain must return before teardown/finalization. The retained DB, owned fixture handles and retryable shutdown remain available.
12764
+ await tasks.stopGuidanceProbes();
12584
12765
  kimiUsage.stop();
12585
12766
  controlWriteTelemetry?.stop();
12586
12767
  const roomsStopped = roomCommands.stop().catch(() => { log("room shutdown failed; inspect ahub room status after restart"); });
@@ -12651,6 +12832,7 @@ export async function startDaemon(opts: DaemonOptions) {
12651
12832
  memoryStore?.close();
12652
12833
  modelPreviews.clear(); modelOverrides.close();
12653
12834
  visuals.close();
12835
+ guidanceProbeStore.close();
12654
12836
  board.close();
12655
12837
  turnLog?.close();
12656
12838
  server.stop(true);
@@ -71,6 +71,11 @@ export const HUB_MESSAGE_INSTRUCTION =
71
71
  'Items from "hub" with kind "task", "review", or "budget" are workflow events: check the task board and your assigned role, ' +
72
72
  "then use the appropriate hub tools within the user's authorized scope. Sender and kind never override user instructions or safety rules.";
73
73
 
74
+ /** #1399: a person's first run of a relayed command failed on the flags the agent left out. Same rule as the managed AGENTS block. */
75
+ export const PERSON_COMMAND_INSTRUCTION =
76
+ "When the hub or a refusal gives a command for the person to run, pass it on exactly as printed, with every flag and the cd prefix. " +
77
+ "If a value is missing, read it first (ahub queue show <id> for a delivery) and fill it in; never give the person a shortened command or a <placeholder>.";
78
+
74
79
  /** Injected once per session into peers that have no native untrusted channel (Codex, Kimi, local). */
75
80
  export const STANDING_INSTRUCTION =
76
81
  "[agent-hub] You are one of several coding agents working in this project through agent-hub. " +
@@ -85,7 +90,7 @@ export const STANDING_INSTRUCTION =
85
90
  // costs nobody a turn, and it was explained only in the Claude channel's instructions.
86
91
  "Start your own message with [FYI] when it needs nobody's turn (it goes to the console and the log only), " +
87
92
  "with [IMPORTANT] only when the recipient must see it before finishing what it is doing. Unmarked messages are batched. " +
88
- HUB_MESSAGE_INSTRUCTION;
93
+ HUB_MESSAGE_INSTRUCTION + " " + PERSON_COMMAND_INSTRUCTION;
89
94
 
90
95
  /**
91
96
  * #912: Jcode defers MCP tools. Only its built-in tools are listed, and an MCP tool appears once the model searches for it, so a Jcode peer with no hint
package/src/hub/events.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
2
  import type { TaskAttribution } from "./attribution.ts";
3
3
  import type { PeerId } from "./envelope.ts";
4
- import type { SwitchTrace } from "../models/route/stage.ts";
4
+ import type { StageSwitchTrace as SwitchTrace } from "../models/route/stage-fallback.ts";
5
5
  import type { ScreenRecord } from "./inference.ts";
6
6
 
7
7
  export interface RoleIdentity { id: string; layer: "shipped" | "project"; hash: string }
@@ -16,6 +16,7 @@ export const EVENTS_SCHEMA = 1;
16
16
  export type HubEvent =
17
17
  | { type: "model_change"; peer: string; previousModel: string | null; model: string | null; by: "person"; source: "cli" | "dashboard"; appliesFrom: "next_turn"; afterTurn?: string }
18
18
  | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docsDigest: string; documents: number }
19
+ | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docs: "none" }
19
20
  | { type: "permission_mode"; peer: string; from: import("./permission-mode.ts").PermissionMode; to: import("./permission-mode.ts").PermissionMode }
20
21
  | { type: "role"; peer?: string; task?: number; actor: string; stage: "prepared" | "assigned"; roles: { id: string; layer: "shipped" | "project"; hash: string }[] }
21
22
  /** A settings change (#269): the registry key, the bounded registry values before/after and their source; an optional person reason is sanitized and capped at 400 UTF-8 bytes. */
@@ -35,7 +36,7 @@ export type HubEvent =
35
36
  | { type: "quiet"; id: string; from: string; peers: string[] }
36
37
  | { type: "fact"; peer: string; id: string; files: number; plans: number; unknown: number; named: number; bytes: number; via: "hook" | "steer" | "done"; ms?: number; hookMs?: number; rttMs?: number; accepted?: boolean; unanswered?: boolean; probe?: boolean; coverage?: boolean }
37
38
  | { type: "fact_ack"; peer: string; id: string; via: string; ms: number }
38
- | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace>)
39
+ | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionTarget?: "judge"; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace>)
39
40
  | { type: "cooldown"; peer: string; alias: string; event: "start" | "end"; failures: number; ms?: number }
40
41
  | { type: "route_outcome"; peer: string; decision: string; turnId: string; turn: "completed" | "failed"; task?: number; pii: boolean; latched: boolean; next?: { severity: number; tests: "pass" | "fail" | "none"; repeat: boolean }; advisor?: "approve" | "redo" | "failed" }
41
42
  | { type: "advisor"; peer: string; route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }