@staix/agent-hub 0.36.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 (102) hide show
  1. package/CHANGELOG.md +17 -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 +802 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +11 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +112 -148
  19. package/docs/quickstart.md +9 -3
  20. package/docs/research.md +1 -1
  21. package/docs/sdlc.md +5 -3
  22. package/docs/security.md +21 -1
  23. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  24. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  25. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  26. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  27. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  29. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  30. package/docs/verified.json +24 -24
  31. package/package.json +3 -4
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +2373 -1436
  34. package/plugins/agent-hub/server.js +2445 -1497
  35. package/src/adapters/channel-peer.ts +7 -1
  36. package/src/adapters/compat.ts +1 -1
  37. package/src/adapters/local-probe.ts +174 -0
  38. package/src/adapters/local-worker.ts +232 -21
  39. package/src/cli/console-state.ts +25 -6
  40. package/src/cli/console-versions.ts +99 -0
  41. package/src/cli/console.ts +13 -1
  42. package/src/cli/help.ts +2 -1
  43. package/src/cli/install-paths.ts +7 -2
  44. package/src/cli/main.ts +60 -4
  45. package/src/cli/runtime-version-warning.ts +2 -2
  46. package/src/cli/sdlc-output.ts +9 -5
  47. package/src/hub/config-apply.ts +4 -2
  48. package/src/hub/config-trust.ts +6 -1
  49. package/src/hub/control-client.ts +5 -2
  50. package/src/hub/daemon.ts +169 -9
  51. package/src/hub/events.ts +3 -2
  52. package/src/hub/guidance-probe-store.ts +713 -0
  53. package/src/hub/guidance-probes.ts +358 -0
  54. package/src/hub/inference.ts +18 -5
  55. package/src/hub/operational-authority.ts +13 -1
  56. package/src/hub/peers.ts +5 -0
  57. package/src/hub/ports.ts +1 -1
  58. package/src/hub/progress.ts +23 -16
  59. package/src/hub/report.ts +2 -0
  60. package/src/hub/research.ts +1 -0
  61. package/src/hub/restart.ts +7 -0
  62. package/src/hub/sdlc-release-authorization.ts +139 -17
  63. package/src/hub/sdlc-release-policy.ts +100 -0
  64. package/src/hub/sdlc-release.ts +59 -7
  65. package/src/hub/tasks.ts +317 -6
  66. package/src/local/probe-errors.ts +28 -0
  67. package/src/local/probe-sandbox.ts +224 -0
  68. package/src/local/probe-types.ts +108 -0
  69. package/src/local/probe-workspace.ts +237 -0
  70. package/src/local/sandbox.ts +71 -2
  71. package/src/local/tools.ts +135 -9
  72. package/src/models/route/advisor-trigger.ts +88 -0
  73. package/src/models/route/config.ts +21 -17
  74. package/src/models/route/conversation-view.ts +179 -0
  75. package/src/models/route/decision-evidence.ts +1 -1
  76. package/src/models/route/decision.ts +114 -19
  77. package/src/models/route/escalation-control.ts +30 -0
  78. package/src/models/route/hub-prompts.ts +97 -0
  79. package/src/models/route/judge-choice.ts +155 -0
  80. package/src/models/route/judge-replies.ts +102 -0
  81. package/src/models/route/labels.ts +14 -70
  82. package/src/models/route/observation-signals.ts +250 -0
  83. package/src/models/route/plan-execute-choice.ts +27 -0
  84. package/src/models/route/relay-selector.ts +2 -2
  85. package/src/models/route/runtime.ts +115 -52
  86. package/src/models/route/turn-state.ts +77 -0
  87. package/src/omniroute/client.ts +3 -0
  88. package/src/ui/plugin.ts +70 -20
  89. package/src/version.ts +4 -0
  90. package/templates/adec/README.md +32 -0
  91. package/templates/adec/ahub.plan-execute.json +23 -0
  92. package/templates/adec/ahub.stage.json +23 -0
  93. package/LICENSES/Apache-2.0.txt +0 -204
  94. package/src/models/route/advisor.ts +0 -102
  95. package/src/models/route/escalation.ts +0 -82
  96. package/src/models/route/judge.ts +0 -23
  97. package/src/models/route/normalize.ts +0 -103
  98. package/src/models/route/plan-execute.ts +0 -52
  99. package/src/models/route/prompts.ts +0 -8
  100. package/src/models/route/signals.ts +0 -247
  101. package/src/models/route/state.ts +0 -54
  102. package/src/models/route/text.ts +0 -61
package/src/hub/tasks.ts CHANGED
@@ -1,3 +1,11 @@
1
+ import { requireConductor } from "./conductor.ts";
2
+ import { pathCandidates } from "@staix/agent-mem";
3
+ import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
4
+ import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
5
+ import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, guidanceProbeCanonical, guidanceProbeManifestKey,
6
+ parseGuidanceProbeRegistration, probeHash, probeSha256, probeInteger, probeSessionGeneration,
7
+ type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
8
+ type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
1
9
  import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts";
2
10
  import { buildEntryDiagnostic } from "./build-entry.ts";
3
11
  import { taskShowAllowed } from "./conductor.ts";
@@ -55,7 +63,7 @@ import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeE
55
63
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
56
64
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
57
65
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
58
- import { readReleaseReadiness } from "./sdlc-release.ts";
66
+ import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
59
67
  import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
60
68
  import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
61
69
  import { isDenied } from "../local/deny.ts";
@@ -131,6 +139,15 @@ interface PreparedSpecInspection {
131
139
  export interface ReleaseWindow { at: number; host: boolean; quota: boolean; idle: boolean; reasons: string[]; current?: () => boolean; close?: () => Promise<void>; }
132
140
 
133
141
  export interface TasksDeps {
142
+ /** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */
143
+ guidanceProbes?: {
144
+ store: GuidanceProbeStore;
145
+ fakePorts?: GuidanceProbeFakePorts;
146
+ prepareWorkerFrame?: ProbeWorkerFramePreparer;
147
+ prepareEditorFrame?: (state: ProbeStoredState, slot: ProbeSlot) => string | Promise<string>;
148
+ session?: (by: PeerId) => { generation: string | number; nativeSession: string | null; requestConnectionId: string; current: () => void } | undefined;
149
+ timer?: { set(callback: () => void, ms: number): unknown; clear(handle: unknown): void };
150
+ };
134
151
  adapterCatalog?: ProjectAdapterCatalog;
135
152
  /** Host-bound evidence only; absent/expired observations never admit a release cut. */
136
153
  releaseWindow?: () => Promise<ReleaseWindow>;
@@ -186,7 +203,8 @@ export interface TasksDeps {
186
203
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
187
204
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
188
205
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
189
- sdlc?: { config: () => SdlcConfig; gh?: SdlcGh };
206
+ /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
207
+ sdlc?: { config: () => SdlcConfig; gh?: SdlcGh; reportPolicy?: (head: string, repo: string) => ReleaseReportPolicy | undefined };
190
208
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
191
209
  ciWatch?: { deadlineMs?: number; pollMs?: number };
192
210
  /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
@@ -509,7 +527,17 @@ function hasReviewAnchorInput(raw: unknown): boolean {
509
527
  } catch { return true; }
510
528
  }
511
529
 
530
+ interface GuidanceProbeRuntime {
531
+ id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck;
532
+ requestedRevision: number; variantId?: string;
533
+ reservation?: ProbeReservation; promise?: Promise<ProbePublicReceipt>; stopPromise?: Promise<void>;
534
+ launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean;
535
+ watch?: { handle: unknown }; failure?: Error;
536
+ }
512
537
  export class Tasks {
538
+ private guidanceProbeStopping = false;
539
+ private guidanceProbeAdmissions = 0;
540
+ private readonly guidanceProbeActive = new Map<string, GuidanceProbeRuntime>();
513
541
  private readonly findingPlacements = new WeakMap<ReviewReadiness, { binding: string; placements: Map<string, ReviewAnchorStatus>; placementOnly: boolean }>();
514
542
  private findingPlacementBinding(task: Task): string {
515
543
  return JSON.stringify([task.id, task.created, this.reviewHead(task), task.refs.paths, task.plan, this.reviewFindingSets(task)]);
@@ -4954,18 +4982,301 @@ export class Tasks {
4954
4982
  } catch { return { state: "unavailable" }; }
4955
4983
  }
4956
4984
 
4957
- private guidanceRequest(by: PeerId): () => void {
4985
+ private guidanceProbeTimer(): NonNullable<NonNullable<TasksDeps["guidanceProbes"]>["timer"]> {
4986
+ return this.d.guidanceProbes?.timer ?? {
4987
+ set: (callback, ms) => { const timer = setTimeout(callback, ms); timer.unref?.(); return timer; },
4988
+ clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
4989
+ };
4990
+ }
4991
+ /** Owned in-process work only, not persisted held lanes or a quiescence assertion. */
4992
+ guidanceProbesPending = (): number => this.guidanceProbeAdmissions + this.guidanceProbeActive.size;
4993
+ async stopGuidanceProbes(): Promise<void> {
4994
+ this.guidanceProbeStopping = true;
4995
+ const active = [...this.guidanceProbeActive.values()];
4996
+ for (const entry of active) this.guidanceProbeAbort(entry, "observation", true);
4997
+ if (this.guidanceProbesPending() === 0) return;
4998
+ await this.guidanceProbeDrain(active);
4999
+ if (this.guidanceProbesPending() !== 0) throw new Error("guidance probe admission drain is unconfirmed; retain project storage and explicitly retry after owned callbacks settle");
5000
+ }
5001
+ private async guidanceProbeDrain(active: GuidanceProbeRuntime[]): Promise<void> {
5002
+ const settled = Promise.allSettled(active.flatMap(entry => [entry.promise, entry.stopPromise].filter((value): value is Promise<ProbePublicReceipt> | Promise<void> => value !== undefined)));
5003
+ let timeout: { handle: unknown } | undefined;
5004
+ try {
5005
+ await Promise.race([settled, new Promise<never>((_resolve, reject) => {
5006
+ timeout = { handle: this.guidanceProbeTimer().set(() => reject(new Error("guidance probe stop is unconfirmed after the owned drain bound; retain the held lane and explicitly drain after its fixture callbacks settle")), GUIDANCE_PROBE_STOP_TIMEOUT_MS) };
5007
+ })]);
5008
+ if (active.some(entry => this.guidanceProbeActive.get(entry.id) === entry)) throw new Error("guidance probe stop evidence is unknown; retain owned handles and explicitly retry the drain after matching fixture stop evidence");
5009
+ } finally { if (timeout !== undefined) this.guidanceProbeTimer().clear(timeout.handle); }
5010
+ }
5011
+ private guidanceProbeClearWatch(entry: GuidanceProbeRuntime): void {
5012
+ if (entry.watch !== undefined) { this.guidanceProbeTimer().clear(entry.watch.handle); entry.watch = undefined; }
5013
+ }
5014
+ private guidanceProbeRetire(entry: GuidanceProbeRuntime): void {
5015
+ if (this.guidanceProbeActive.get(entry.id) !== entry || !entry.launchSettled || entry.stopRequested && (!entry.stopSettled || !entry.stopKnown)) return;
5016
+ this.guidanceProbeClearWatch(entry); this.guidanceProbeActive.delete(entry.id);
5017
+ }
5018
+ private guidanceProbeAbort(entry: GuidanceProbeRuntime, reason: "elapsed" | "observation", explicitStop = false): void {
5019
+ if (this.guidanceProbeActive.get(entry.id) !== entry) return;
5020
+ this.guidanceProbeClearWatch(entry);
5021
+ if (entry.reservation) {
5022
+ try { this.d.guidanceProbes!.store.latchHold(entry.reservation, reason); }
5023
+ catch { entry.failure = new Error("guidance probe hold bookkeeping is unconfirmed; inspect retained state before any further work"); }
5024
+ }
5025
+ entry.controller.abort();
5026
+ if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; }
5027
+ if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return;
5028
+ const reservation = entry.reservation, ports = this.d.guidanceProbes!.fakePorts!;
5029
+ entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false;
5030
+ entry.stopPromise = (async () => {
5031
+ try {
5032
+ const result = await ports.stop({ reservation }, new AbortController().signal);
5033
+ entry.stopKnown = result?.stopped === "known_fixture" && guidanceProbeCanonical(result.reservation) === guidanceProbeCanonical(reservation);
5034
+ if (!entry.stopKnown) entry.failure = new Error("guidance probe stop evidence is unknown; inspect the owned reservation and explicitly drain without replaying it");
5035
+ } catch { entry.failure = new Error("guidance probe stop failed; retain owned handles and explicitly drain before closing project storage"); }
5036
+ finally { entry.stopSettled = true; this.guidanceProbeRetire(entry); }
5037
+ })();
5038
+ }
5039
+ private guidanceProbeWatch(entry: GuidanceProbeRuntime): void {
5040
+ if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
5041
+ try {
5042
+ entry.current();
5043
+ const state = this.d.guidanceProbes!.store.read({ projectKey: this.guidanceProject(), id: entry.id });
5044
+ if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable");
5045
+ const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt;
5046
+ if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; }
5047
+ const remaining = state.registration.manifest.limits.elapsedMs - elapsed;
5048
+ if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; }
5049
+ entry.watch = { handle: this.guidanceProbeTimer().set(() => {
5050
+ if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
5051
+ entry.watch = undefined; this.guidanceProbeWatch(entry);
5052
+ }, Math.min(GUIDANCE_PROBE_FENCE_INTERVAL_MS, remaining)) };
5053
+ } catch { this.guidanceProbeAbort(entry, "observation"); }
5054
+ }
5055
+ private guidanceProbeProjection(state: ProbeStoredState, already = false): ProbePublicStatus {
5056
+ const holds = state.admissionHold !== "none" || state.counters.usageUnknown;
5057
+ const authoring: ProbePublicStatus["authoring"] = state.sessions.some(item => item.child?.authoring === "uncontrolled") ? "uncontrolled"
5058
+ : state.sessions.some(item => item.child?.authoring === "admitted_fixture") ? "admitted_fixture" : "unknown";
5059
+ const launchedSessions = state.sessions.filter(item => item.coverage.launchExposed);
5060
+ const verifiedCoverage = launchedSessions.length > 0 && launchedSessions.every(item => item.coverage.coverageVerified)
5061
+ && state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified)
5062
+ && state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified);
5063
+ const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration"
5064
+ : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : "fixture";
5065
+ return { ...state.receipt, already, taskId: state.registration.manifest.task.id,
5066
+ experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence,
5067
+ counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring,
5068
+ comparable: state.receipt.state === "closed_fixture" && !holds && verifiedCoverage && authoring === "admitted_fixture" };
5069
+ }
5070
+ private guidanceProbeReceipt(state: ProbeStoredState, already = false): ProbePublicReceipt {
5071
+ const { counters: _counters, cancelRequested: _cancelRequested, notNeeded: _notNeeded, comparable: _comparable, authoring: _authoring, ...result } = this.guidanceProbeProjection(state, already);
5072
+ return result;
5073
+ }
5074
+ private guidanceProbeState(by: PeerId, id: string, check: () => void): ProbeStoredState {
5075
+ check();
5076
+ if (!probeSha256(id)) throw new PreEffectToolRefusal("guidance probe id is invalid; use the exact registered content id");
5077
+ if (!this.d.guidanceProbes) throw new PreEffectToolRefusal("guidance probe storage is unavailable; restart a supporting hub before retrying");
5078
+ const state = this.d.guidanceProbes.store.read({ projectKey: this.guidanceProject(), id });
5079
+ if (!state) throw new PreEffectToolRefusal("guidance probe is unavailable; inspect a registered declaration in this project");
5080
+ this.guidanceProbeTask(by, state.registration.manifest.task, false); check(); return state;
5081
+ }
5082
+ private guidanceProbeHost(by: PeerId, manifest: GuidanceProbeManifestV1, request: ReturnType<Tasks["guidanceProbeRequest"]>, history?: ProbeHostBinding): ProbeHostBinding {
5083
+ request.check();
5084
+ const projectKey = this.guidanceProject();
5085
+ if (projectKey !== manifest.projectKey) throw new PreEffectToolRefusal("guidance probe project changed; register within the current project namespace");
5086
+ const task = this.guidanceProbeTask(by, manifest.task, history === undefined);
5087
+ const binding = { projectKey, actor: by, task: { id: task.id, created: task.created, flowRevision: task.history.length },
5088
+ sessionGeneration: request.generation, nativeSession: request.nativeSession, requestConnectionId: request.requestConnectionId };
5089
+ // A narrowing cancellation carries its original baseline as history, never a new applicability grant.
5090
+ if (history) return { ...binding, role: history.role, baselineGuidance: history.baselineGuidance };
5091
+ const role = this.guidanceRole(task);
5092
+ return { ...binding, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, baselineGuidance: taskRoleText(role) };
5093
+ }
5094
+ private guidanceProbeSnapshotClear(state: ProbeStoredState["registration"]): boolean {
5095
+ return Object.entries(state.snapshots).every(([field, value]) => {
5096
+ const text = field === "dataPolicy" ? guidanceProbeCanonical(value) : value as string;
5097
+ return this.nameable(text) && !looksSecret(text);
5098
+ });
5099
+ }
5100
+ private guidanceProbeRenderedClear(text: string): boolean {
5101
+ if (!this.nameable(text) || looksSecret(text)) return false;
5102
+ const policy = [...this.d.deny ?? [], ...this.d.piiPaths ?? []];
5103
+ if ([...pathCandidates(text)].some(candidate => matchesPolicyLexically(this.d.cwd, candidate, policy))) return false;
5104
+ return !policy.some(entry => {
5105
+ const literal = entry.replace(/^\.\//, "").split(/[*?[\]{}]/)[0]!.replace(/\/+$/, "");
5106
+ return /[/\s]/.test(literal) && text.includes(literal);
5107
+ });
5108
+ }
5109
+ async guidanceProbeRegister(by: PeerId, value: unknown): Promise<ProbePublicReceipt> {
5110
+ const request = this.guidanceProbeRequest(by), registration = parseGuidanceProbeRegistration(value);
5111
+ if (!registration) throw new PreEffectToolRefusal("guidance probe declaration is invalid or oversized; use the closed V1 envelope without trimming its snapshots");
5112
+ const binding = this.guidanceProbeHost(by, registration.manifest, request);
5113
+ if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe inputs are private; register public task-local inputs in a current public session");
5114
+ this.guidanceProbeAdmissions++;
5115
+ let wrote = false;
5116
+ try {
5117
+ const saved = this.d.guidanceProbes!.store.register(registration, binding, () => {
5118
+ if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe input policy changed; inspect its current public scope before retrying");
5119
+ return this.guidanceProbeHost(by, registration.manifest, request);
5120
+ });
5121
+ wrote = !saved.already;
5122
+ const state = this.guidanceProbeState(by, saved.id, request.check);
5123
+ return this.guidanceProbeReceipt(state, saved.already);
5124
+ } catch (error) {
5125
+ if (!wrote && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
5126
+ throw new Error("guidance probe registration is unconfirmed; inspect retained state before explicitly retrying");
5127
+ }
5128
+ finally { this.guidanceProbeAdmissions--; }
5129
+ }
5130
+ async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
5131
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5132
+ request.check(); return this.guidanceProbeProjection(state);
5133
+ }
5134
+ async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
5135
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5136
+ const host = this.guidanceProbeHost(by, state.registration.manifest, request);
5137
+ if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId))
5138
+ throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id");
5139
+ const dependency = this.d.guidanceProbes!;
5140
+ // No production runner: refuse before original-child selection, G1 raw read, binding, reservation or timer.
5141
+ if (!dependency.fakePorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1; use fake-only fixtures, not a live launch");
5142
+ const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision);
5143
+ if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession
5144
+ || original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it");
5145
+ const slot = original ? state.registration.manifest.slots.find(item => item.id === original.slotId)
5146
+ : state.registration.manifest.slots.find(item => state.sessions.find(session => session.slotId === item.id)?.state === "planned");
5147
+ if (!slot) throw new PreEffectToolRefusal("guidance probe has no eligible slot; inspect its retained terminal or held state");
5148
+ if (original && original.variantId !== (variantId ?? null)) throw new PreEffectToolRefusal("guidance probe original selector differs; inspect its original G1 id without rebinding the start");
5149
+ const needsVariant = slot.role === "worker" && slot.arm !== "baseline";
5150
+ if (needsVariant !== (variantId !== undefined)) throw new PreEffectToolRefusal("guidance probe next worker needs its existing G1 id only; use --variant for the next non-baseline worker");
5151
+ const current = (): ProbeAdmissionRecheck => {
5152
+ const fresh = this.guidanceProbeHost(by, state.registration.manifest, request);
5153
+ if (!this.guidanceProbeSnapshotClear(state.registration)) throw new PreEffectToolRefusal("guidance probe input privacy changed; retain its declaration and use current public inputs");
5154
+ return { host: fresh, ...(variantId === undefined ? {} : { child: this.guidanceProbeVariantBinding(by, this.guidanceProbeTask(by, state.registration.manifest.task, true), variantId) }) };
5155
+ };
5156
+ const prepared = current();
5157
+ const active = this.guidanceProbeActive.get(id);
5158
+ if (active) {
5159
+ if (active.requestedRevision !== revision || active.variantId !== variantId)
5160
+ throw new PreEffectToolRefusal("another owned probe attempt is still settling; inspect its state before explicitly starting the next stage");
5161
+ const captured = active.current().host;
5162
+ if (captured.actor !== host.actor || captured.sessionGeneration !== host.sessionGeneration || captured.nativeSession !== host.nativeSession
5163
+ || captured.requestConnectionId !== host.requestConnectionId)
5164
+ throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it");
5165
+ // Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata.
5166
+ if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
5167
+ const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, current);
5168
+ if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work");
5169
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
5170
+ }
5171
+ const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, launched: false, launchSettled: false,
5172
+ stopRequested: false, stopSettled: false, stopKnown: false };
5173
+ this.guidanceProbeActive.set(id, entry);
5174
+ const ports: GuidanceProbeFakePorts = {
5175
+ launch: async (input, effects, signal) => {
5176
+ entry.reservation = input.reservation;
5177
+ this.guidanceProbeWatch(entry);
5178
+ if (signal.aborted) throw new Error("owned probe was aborted before launch");
5179
+ entry.launched = true;
5180
+ return dependency.fakePorts!.launch(input, effects, signal);
5181
+ },
5182
+ stop: (input, signal) => dependency.fakePorts!.stop(input, signal),
5183
+ };
5184
+ let reserved = false, returned = false;
5185
+ const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, revalidate: current, now: () => this.d.now?.() ?? Date.now(),
5186
+ prepareWorkerFrame: dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
5187
+ entry.promise = (async () => {
5188
+ try {
5189
+ const saved = await runner.start({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
5190
+ returned = true;
5191
+ if (saved.state === "unknown_held" && entry.launched) {
5192
+ this.guidanceProbeAbort(entry, "observation", true);
5193
+ if (!entry.stopPromise) throw new Error("owned probe stop was not recorded; retain the held lane and explicitly inspect its outcome");
5194
+ await entry.stopPromise;
5195
+ }
5196
+ request.check();
5197
+ if (entry.failure) throw entry.failure;
5198
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
5199
+ } catch (error) {
5200
+ this.guidanceProbeAbort(entry, "observation");
5201
+ if (!reserved && !returned && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
5202
+ throw new Error("guidance probe attempt outcome is unconfirmed; inspect its retained id without replaying work");
5203
+ } finally { entry.launchSettled = true; this.guidanceProbeClearWatch(entry); this.guidanceProbeRetire(entry); }
5204
+ })();
5205
+ return entry.promise;
5206
+ }
5207
+ async guidanceProbeCancel(by: PeerId, id: string, revision: number): Promise<ProbePublicReceipt> {
5208
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5209
+ if (!probeInteger(revision)) throw new PreEffectToolRefusal("guidance probe cancellation revision is invalid; inspect its current CAS revision");
5210
+ const current = () => this.guidanceProbeHost(by, state.registration.manifest, request, state.binding), host = current();
5211
+ try {
5212
+ const saved = this.d.guidanceProbes!.store.cancelIntent({ key: { projectKey: host.projectKey, id }, expectedRevision: revision, host }, current);
5213
+ const entry = this.guidanceProbeActive.get(id);
5214
+ if (entry) { this.guidanceProbeAbort(entry, "observation", true); await this.guidanceProbeDrain([entry]); }
5215
+ request.check();
5216
+ return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
5217
+ } catch { throw new Error("guidance probe cancellation is unconfirmed; inspect its retained intent and owned drain before retrying"); }
5218
+ }
5219
+ private guidanceProbeRequest(by: PeerId): { check: () => void; generation: number | string; nativeSession: string | null; requestConnectionId: string } {
5220
+ const request = this.guidanceRequest(by, "probe");
5221
+ if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("guidance probes require the person or current configured conductor; use an admitted operational session");
5222
+ const session = this.d.guidanceProbes?.session?.(by);
5223
+ if (!session || !probeSessionGeneration(session.generation) || !executionText(session.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
5224
+ || session.nativeSession !== null && !executionText(session.nativeSession, EXECUTION_REFERENCE_LIMITS.id))
5225
+ throw new PreEffectToolRefusal("guidance probe request session is unavailable; reconnect through a current authenticated project connection");
5226
+ const sessionCurrent = session.current;
5227
+ const current = () => {
5228
+ sessionCurrent(); request();
5229
+ if (this.guidanceProbeStopping) throw new PreEffectToolRefusal("guidance probe admission is stopping; inspect retained work after the owned drain");
5230
+ if (this.d.reviewOnly?.(by)) throw new PreEffectToolRefusal("guidance probes are unavailable in a review-only context; use a current public operational session");
5231
+ if (by !== USER) {
5232
+ try { requireConductor(by, this.d.roles); }
5233
+ catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; refresh the configured role before retrying"); }
5234
+ if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor is not currently rostered; restore current membership before retrying");
5235
+ }
5236
+ };
5237
+ current(); return { check: current, generation: session.generation, nativeSession: session.nativeSession, requestConnectionId: session.requestConnectionId };
5238
+ }
5239
+ private guidanceProbeTask(by: PeerId, selected: { id: number; created: number; flowRevision: number }, admission: boolean): Task {
5240
+ const task = this.guidanceTask(by, { taskId: selected.id, taskCreated: selected.created }, false);
5241
+ if (admission && (task.history.length !== selected.flowRevision || !["in_progress", "changes_requested"].includes(task.state)))
5242
+ throw new PreEffectToolRefusal(`guidance probe admission is stale or task state is ${task.state}; accept current work in in_progress or changes_requested and reload its revision`);
5243
+ return task;
5244
+ }
5245
+ /** Actual probe actor only; the source owner validates/hydrates G1, never an impersonated read or separate SQL parser. */
5246
+ private guidanceProbeVariantBinding(by: PeerId, task: Task, variantId: string): ProbeChildBinding {
5247
+ if (by !== USER) {
5248
+ try { requireConductor(by, this.d.roles); }
5249
+ catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; reconnect in a current operational session"); }
5250
+ if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor membership changed; restore current roster membership before retrying");
5251
+ }
5252
+ const current = this.guidanceProbeTask(by, { id: task.id, created: task.created, flowRevision: task.history.length }, true);
5253
+ if (!probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe variant selector is invalid; choose an existing current G1 content id");
5254
+ const project = this.guidanceProject(), role = this.guidanceRole(current);
5255
+ const experiment = this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(project, current.id, current.created, variantId));
5256
+ const record = experiment === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(project, current.id, current.created, experiment)).find(item => item.variant.id === variantId);
5257
+ if (!record || record.withdrawn || record.variant.flowRevision !== current.history.length || record.variant.baseline.roleId !== role.id
5258
+ || record.variant.baseline.layer !== role.layer || record.variant.baseline.sha256 !== role.hash)
5259
+ throw new PreEffectToolRefusal("guidance probe G1 is unavailable, withdrawn or stale; separately admit a current owner/person variant before retrying");
5260
+ const guidance = renderGuidanceVariantV1(record.variant);
5261
+ if (!this.guidanceProbeRenderedClear(guidance))
5262
+ throw new PreEffectToolRefusal("guidance probe handoff text is private; use a current public G1 before retrying");
5263
+ return { variantId, candidateSha256: record.variant.candidate.sha256, guidanceSha256: probeHash(guidance), guidance,
5264
+ task: { id: current.id, created: current.created, flowRevision: current.history.length },
5265
+ role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, authoring: "uncontrolled", sourceSessionId: null };
5266
+ }
5267
+
5268
+ private guidanceRequest(by: PeerId, mode: "guidance" | "probe" = "guidance"): () => void {
4958
5269
  if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
4959
5270
  throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
4960
5271
  const request = this.requestCheck(by, () => this.studyHold());
4961
5272
  const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
4962
- const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = delivery();
5273
+ const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined;
4963
5274
  const check = () => {
4964
5275
  request();
4965
5276
  if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by))
4966
5277
  throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
4967
5278
  if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
4968
- || peer.sessionGeneration !== generation || peer.nativeSession !== session || delivery() !== delivered))
5279
+ || peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered))
4969
5280
  throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
4970
5281
  };
4971
5282
  check(); return check;
@@ -6331,7 +6642,7 @@ export class Tasks {
6331
6642
  } catch { /* an approval never fails because of the merge check */ }
6332
6643
  }
6333
6644
  async releaseReadiness(repo: string, liveIssues: number[]) {
6334
- const report = await readReleaseReadiness(this.d.cwd, repo, liveIssues, { gh: this.d.sdlc?.gh });
6645
+ const report = await readReleaseReadiness(this.d.cwd, repo, liveIssues, { gh: this.d.sdlc?.gh, reportPolicy: this.d.sdlc?.reportPolicy });
6335
6646
  if (report.documents) report.documents.documents = report.documents.documents.map(d => {
6336
6647
  if (d.path && (!this.nameable(d.path) || matchesPolicy(this.d.cwd, d.path, this.d.piiPaths ?? [], true))) { const { path: _privatePath, ...metadata } = d; return metadata; }
6337
6648
  return d;
@@ -0,0 +1,28 @@
1
+ /** Closed probe-only causes. They carry no physical path, model text, actor id or native diagnostic. */
2
+ export type ProbeToolRefusalCode = "outside_workspace" | "invalid_path" | "unadmitted_write" | "file_ceiling"
3
+ | "hardlinked_target" | "nonregular_target" | "authority_stopped" | "target_changed" | "tool_unavailable"
4
+ | "workspace_ceiling" | "confinement_unavailable" | "token_bound_unavailable" | "token_ceiling";
5
+ const reasons: Record<ProbeToolRefusalCode, string> = {
6
+ outside_workspace: "path is outside the admitted logical workspace; use a declared /workspace path",
7
+ invalid_path: "path is not an admitted relative name; use a declared /workspace file without traversal, dependency or internal-temp components",
8
+ unadmitted_write: "write target is not admitted; choose a target from the supplied logical /workspace/scratch or /workspace/output list",
9
+ file_ceiling: "file exceeds the 1 MiB file ceiling; reduce the file before requesting another admitted operation",
10
+ hardlinked_target: "hardlinked target is not a private probe file; ask the host for a fresh regular file",
11
+ nonregular_target: "target is not a regular probe file; choose a declared regular file",
12
+ authority_stopped: "probe authority is stopped or unavailable; stop this session and ask the host for a newly admitted session",
13
+ target_changed: "probe target or reservation changed; stop this operation and ask the host to inspect the admitted state",
14
+ tool_unavailable: "tool is unavailable in the confined probe; use only the admitted read, write and edit tools",
15
+ workspace_ceiling: "workspace reservation exceeds its admitted workspace ceiling (at most 64 MiB); reduce the declared data or ask the host for a new bounded session",
16
+ confinement_unavailable: "OS confinement or owned cleanup is unverified; stop this session and ask the host to inspect confinement and retained resources",
17
+ token_bound_unavailable: "trusted token upper-bound proof is unavailable; ask the host to prepare a frozen configuration before another model call",
18
+ token_ceiling: "model call exceeds the admitted token ceiling; reduce its declared input or ask the host for a new bounded session",
19
+ };
20
+ const unknownReason = "confined probe operation refused; stop this operation and ask the host to inspect the admitted state";
21
+ export class ProbeToolRefusal extends Error {
22
+ constructor(readonly code: ProbeToolRefusalCode) { super(Object.hasOwn(reasons, code) ? reasons[code] : unknownReason); }
23
+ }
24
+ /** Never classify from native/error prose or reuse an arbitrary Error.message. */
25
+ export function formatProbeToolRefusal(error: unknown): string {
26
+ const reason = error instanceof ProbeToolRefusal && Object.hasOwn(reasons, error.code) ? reasons[error.code] : unknownReason;
27
+ return `error: ${reason}`;
28
+ }