@staix/agent-hub 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
package/src/hub/tasks.ts CHANGED
@@ -1,3 +1,19 @@
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";
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";
10
+ import { buildEntryDiagnostic } from "./build-entry.ts";
11
+ import { taskShowAllowed } from "./conductor.ts";
12
+ import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
13
+ import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts";
14
+ import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
15
+ import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
16
+ import type { JournalDelivery } from "./delivery-journal.ts";
1
17
  import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt } from "./research-evidence.ts";
2
18
  import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
3
19
  import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
@@ -43,13 +59,13 @@ import { NoWriteTurns } from "./no-writes.ts";
43
59
  import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
44
60
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
45
61
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
46
- import { guardedMerge, mergeModeFor, mergeView, type MergeView } from "./sdlc-merge.ts";
62
+ import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
47
63
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
48
64
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
49
65
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
50
- import { readReleaseReadiness } from "./sdlc-release.ts";
51
- import { loadRoleCatalog, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
52
- import { matchesPolicy, policyRealPath, insideRoot } from "./path-policy.ts";
66
+ import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
67
+ import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
68
+ import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
53
69
  import { isDenied } from "../local/deny.ts";
54
70
  import { foldSegment, isHubWritePath } from "./permission-mode.ts";
55
71
  import { correctionInput, resolveVisibleMemory } from "./memory-candidates.ts";
@@ -74,11 +90,11 @@ import { isAbsolute, relative, resolve } from "node:path";
74
90
  import type { Briefs, NativeItem } from "../memory/brief.ts";
75
91
  import type { MemoryClient } from "../memory/client.ts";
76
92
  import { candidateTargetRevision, type CandidateInput, type CandidateStore, extractNodes, looksSecret, PROMOTED_KINDS, taskKey, type GoalView, type Kind, type MemoryStore, type NoteInput, type Scope, type Tier } from "@staix/agent-mem";
77
- import { parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
93
+ import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
78
94
  import type { Bus } from "./bus.ts";
79
95
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
80
96
  import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
81
- import { assign, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
97
+ import { assign, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
82
98
  import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts";
83
99
  import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts";
84
100
  import { realPath } from "./project.ts";
@@ -93,7 +109,7 @@ import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
93
109
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
94
110
  import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
95
111
  import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
96
- import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState } from "./sdlc.ts";
112
+ import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
97
113
 
98
114
  /** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
99
115
  const PERSON_RUN_SPLIT = "a person-run card is the person's to split: its children would be unmarked cards an agent could take (the person's own split marks every child person-run)";
@@ -108,6 +124,9 @@ export type TaskAssignmentRole = "owner" | "reviewer" | "planner";
108
124
  /** What `hub_remember` carries (#802: one shape for `remember` and `rememberOutcome`). */
109
125
  export interface RememberInput { text?: string; title?: string; kind?: string; task?: unknown; horizon?: unknown; scope?: unknown; approach?: unknown; symptom?: unknown; cause?: unknown; evidence?: unknown; retry_when?: unknown }
110
126
 
127
+ interface SpecGateRead { task: Task; edit?: SpecEdit; carry?: object; }
128
+ interface SpecCarryProof { by: PeerId; task: number; scope: string; commit: SpecAcceptanceCommit; current: () => boolean; }
129
+
111
130
  interface PreparedSpecInspection {
112
131
  report?: SpecTaskReport;
113
132
  policyKey: string;
@@ -120,6 +139,15 @@ interface PreparedSpecInspection {
120
139
  export interface ReleaseWindow { at: number; host: boolean; quota: boolean; idle: boolean; reasons: string[]; current?: () => boolean; close?: () => Promise<void>; }
121
140
 
122
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
+ };
123
151
  adapterCatalog?: ProjectAdapterCatalog;
124
152
  /** Host-bound evidence only; absent/expired observations never admit a release cut. */
125
153
  releaseWindow?: () => Promise<ReleaseWindow>;
@@ -141,6 +169,8 @@ export interface TasksDeps {
141
169
  ownerIsolation?: () => Readonly<Record<string, boolean>>;
142
170
  cwd: string;
143
171
  project: string;
172
+ /** Startup-bound namespace/key and an already-open exact-id journal read; never query-controlled. */
173
+ executionLineage?: { projectKey: string; cursorKey: string; readDelivery?(id: string): JournalDelivery | undefined };
144
174
  profile?: ProfileName;
145
175
  profileData?: ProjectProfile;
146
176
  piiPaths?: string[];
@@ -173,7 +203,8 @@ export interface TasksDeps {
173
203
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
174
204
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
175
205
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
176
- 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 };
177
208
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
178
209
  ciWatch?: { deadlineMs?: number; pollMs?: number };
179
210
  /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
@@ -496,7 +527,17 @@ function hasReviewAnchorInput(raw: unknown): boolean {
496
527
  } catch { return true; }
497
528
  }
498
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
+ }
499
537
  export class Tasks {
538
+ private guidanceProbeStopping = false;
539
+ private guidanceProbeAdmissions = 0;
540
+ private readonly guidanceProbeActive = new Map<string, GuidanceProbeRuntime>();
500
541
  private readonly findingPlacements = new WeakMap<ReviewReadiness, { binding: string; placements: Map<string, ReviewAnchorStatus>; placementOnly: boolean }>();
501
542
  private findingPlacementBinding(task: Task): string {
502
543
  return JSON.stringify([task.id, task.created, this.reviewHead(task), task.refs.paths, task.plan, this.reviewFindingSets(task)]);
@@ -746,7 +787,7 @@ export class Tasks {
746
787
  constructor(private readonly d: TasksDeps) {
747
788
  this.ciWatchers = new CiWatchers({
748
789
  ...d.ciWatch,
749
- poll: watch => pollCi(watch, watch.head, d.sdlc?.config().requiredChecks ?? [], d.sdlc?.gh ?? sdlcGh),
790
+ poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh),
750
791
  current: watch => this.ciWatchCurrent(watch),
751
792
  finish: (watch, outcome) => this.ciCompleted(watch, outcome),
752
793
  });
@@ -1732,9 +1773,10 @@ export class Tasks {
1732
1773
 
1733
1774
  private weights(cls: TaskClass, task?: Task, projectedHealth?: ReturnType<Tasks["health"]>) {
1734
1775
  const now = Date.now();
1776
+ const entryDiagnostic = task ? this.entryDiagnostic(task) : undefined;
1735
1777
  const quota = this.d.quota?.();
1736
1778
  const health = projectedHealth ?? this.health(), clock = health.now ?? now;
1737
- return { ...health, ...(task && this.hasPersonReservation(task) && task.reserved ? { queueReservedHold: task.reserved } : {}), planners: this.plannerHolders(), ...(task ? { reviewPool: this.reviewPoolOptions(task), ...(task.planner ? { keptPlanner: task.planner } : {}) } : {}), now: clock, demoted: this.demoted(cls, clock), reviews: this.reviewRecord(cls), ...(quota ? { quota } : {}), ...(this.d.review?.adaptive ? { adaptive: { min: this.d.review.min_reviews } } : {}) };
1779
+ return { ...health, ...(entryDiagnostic ? { entryDiagnostic } : {}), ...(task && this.hasPersonReservation(task) && task.reserved ? { queueReservedHold: task.reserved } : {}), planners: this.plannerHolders(), ...(task ? { reviewPool: this.reviewPoolOptions(task), ...(task.planner ? { keptPlanner: task.planner } : {}) } : {}), now: clock, demoted: this.demoted(cls, clock), reviews: this.reviewRecord(cls), ...(quota ? { quota } : {}), ...(this.d.review?.adaptive ? { adaptive: { min: this.d.review.min_reviews } } : {}) };
1738
1780
  }
1739
1781
 
1740
1782
  /**
@@ -4328,13 +4370,14 @@ export class Tasks {
4328
4370
  task = current; // Reviewer-only and quiet bookkeeping updates do not supersede ownership authority.
4329
4371
  if (gap) {
4330
4372
  this.requestIndependentPlanReview(current);
4331
- this.releaseNotice(`task ${this.publicTitle(current)}: ${gap}; planner: call hub_planner_groom then hub_plan_review`);
4373
+ const entry = mode === "enforce" ? this.entryDiagnostic(current, gap) ?? `${gap}; planner: hub_plan_review` : `${gap}; planner: call hub_planner_groom then hub_plan_review`;
4374
+ this.releaseNotice(`task ${this.publicTitle(current)}: ${entry}`);
4332
4375
  if (mode === "enforce") {
4333
4376
  if (opts.claim && opts.namedOwner === by) stagedClaimGap = gap;
4334
4377
  else {
4335
- if (opts.refuseNamed && opts.namedOwner) throw new (opts.refuseNamed === "pre" ? PreEffectToolRefusal : Error)(`cannot assign task #${current.id} to ${opts.namedOwner}: ${gap}; planner: call hub_planner_groom then hub_plan_review`); // #601, before the stall write
4336
- this.reportStall(current, { kind: "no-eligible-peer", code: "policy" });
4337
- return current;
4378
+ if (opts.refuseNamed && opts.namedOwner) throw new (opts.refuseNamed === "pre" ? PreEffectToolRefusal : Error)(`cannot assign task #${current.id} to ${opts.namedOwner}: ${entry}`); // #601, before hold bookkeeping
4379
+ this.holdReady(current, "build entry", entry);
4380
+ return this.d.board.get(current.id) ?? current;
4338
4381
  }
4339
4382
  }
4340
4383
  }
@@ -4840,10 +4883,19 @@ export class Tasks {
4840
4883
  } catch { return undefined; }
4841
4884
  }
4842
4885
 
4843
- /** Why a proposal's named owner (a self-claim included) did not get it, from the stall its proposal recorded (#601); undefined when it did. */
4886
+ /** Guidance is separate from candidate choice: offers retain their existing plan-only gate. */
4887
+ private entryDiagnostic(task: Task, planGap?: string): string | undefined {
4888
+ if (this.d.sdlc?.config().mode !== "enforce" || !this.isBuildTask(task) || this.isPii(task)) return undefined;
4889
+ return buildEntryDiagnostic(task, planGap);
4890
+ }
4891
+
4892
+ /** Proposal entry guidance first; otherwise explain an unassigned named owner from its recorded peer stall (#601). */
4844
4893
  namedOwnerNote(task: Task, named: PeerId | undefined, by: PeerId): string | undefined {
4845
4894
  requireLocalTaskPeer(by);
4846
- if (!named || task.owner || task.state !== "proposed") return undefined;
4895
+ if (task.state !== "proposed") return undefined;
4896
+ const entry = this.entryDiagnostic(task);
4897
+ if (entry) return `task #${task.id}: SDLC build entry blocked: ${entry}`;
4898
+ if (!named || task.owner) return undefined;
4847
4899
  const stall = this.d.board.stalls().find(row => row.task === task.id);
4848
4900
  if (!stall) return undefined;
4849
4901
  const code = stall.cause.refusals?.find(row => row.peer === named)?.code ?? (stall.cause.peer === named ? stall.cause.code : undefined);
@@ -4866,6 +4918,613 @@ export class Tasks {
4866
4918
  // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
4867
4919
  for (const peer of this.taskPlanner(task).filter(peer => this.d.bus.isRostered(peer))) this.releaseNotice(`task #${task.id}: stall notice unavailable`, () => this.d.tell?.(peer, noteLine(HUB, "finding", text)));
4868
4920
  }
4921
+ /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
4922
+ private lineageMetadata(text: string): boolean {
4923
+ try {
4924
+ if (!this.nameable(text) || looksSecret(text)) return false;
4925
+ const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []];
4926
+ if (!policy.length) return true;
4927
+ let parsed: unknown;
4928
+ try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof
4929
+ const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : [];
4930
+ // ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained
4931
+ // public metadata can prove it without filesystem discovery on this read path.
4932
+ return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy));
4933
+ } catch { return false; }
4934
+ }
4935
+
4936
+ private lineageVisible(by: PeerId, task: Task): boolean {
4937
+ try {
4938
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.reviewTaskPrivate(task)) return false;
4939
+ if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false;
4940
+ if (this.repositories.cachedScope(task.refs)?.key !== this.repositories.project.key) return false;
4941
+ return by === USER || this.d.bus.isRostered(by) && taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by));
4942
+ } catch { return false; }
4943
+ }
4944
+
4945
+ private lineagePorts(by: PeerId): ExecutionLineageOwnerPorts | undefined {
4946
+ const binding = this.d.executionLineage;
4947
+ if (!binding) return undefined;
4948
+ // Agent-wide roles do not grant diagnostic authority over a hidden or staged source.
4949
+ const diagnostics = by === USER;
4950
+ // ponytail: raw50 event pages cannot prove current field privacy after policy narrowing.
4951
+ // Refuse by policy alone until a privacy-aware page source supplies a complete public projection.
4952
+ let eventProjectionSupported = false;
4953
+ try { eventProjectionSupported = !this.d.piiPaths?.length && !this.d.deny?.length && !this.d.routing().signals.pii_patterns.length; } catch { /* unknown current policy cannot admit event projection */ }
4954
+ return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey,
4955
+ scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported,
4956
+ task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text),
4957
+ links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created),
4958
+ delivery: binding.readDelivery,
4959
+ attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit),
4960
+ receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) };
4961
+ }
4962
+
4963
+ /** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */
4964
+ executionLineage(by: PeerId, input: unknown): LineageResult {
4965
+ if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" };
4966
+ try {
4967
+ const check = this.requestCheck(by);
4968
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
4969
+ const ports = this.lineagePorts(by);
4970
+ if (!ports) return { state: "unavailable" };
4971
+ let query;
4972
+ try { query = parseOwnerLineageQuery(input); }
4973
+ catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; }
4974
+ const snapshot = executionOwnerSnapshot(ports, query);
4975
+ check();
4976
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
4977
+ if (snapshot.task) {
4978
+ const current = this.d.board.get(snapshot.task.id);
4979
+ if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" };
4980
+ }
4981
+ return readExecutionLineage(snapshot.source, snapshot.query);
4982
+ } catch { return { state: "unavailable" }; }
4983
+ }
4984
+
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 {
5269
+ if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
5270
+ throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
5271
+ const request = this.requestCheck(by, () => this.studyHold());
5272
+ const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
5273
+ const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined;
5274
+ const check = () => {
5275
+ request();
5276
+ if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by))
5277
+ throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
5278
+ if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
5279
+ || peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered))
5280
+ throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
5281
+ };
5282
+ check(); return check;
5283
+ }
5284
+ private guidanceTask(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, write: boolean): Task {
5285
+ const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId));
5286
+ if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying");
5287
+ if (task.created !== selector.taskCreated || !this.lineageVisible(by, task) || this.reviewObserverTurn(by, task.id))
5288
+ throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying");
5289
+ if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review"
5290
+ || !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by))))
5291
+ throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying");
5292
+ return task;
5293
+ }
5294
+ private guidanceProject(): string {
5295
+ const key = this.d.executionLineage?.projectKey;
5296
+ if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying");
5297
+ return key;
5298
+ }
5299
+ private guidanceRole(task: Task) {
5300
+ let role;
5301
+ try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); }
5302
+ catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); }
5303
+ if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant");
5304
+ return role;
5305
+ }
5306
+ private guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean {
5307
+ const { evidenceRefs, ...text } = record.variant;
5308
+ // Opaque evidence addresses never become filesystem/producer lookup instructions.
5309
+ return this.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.lineageMetadata(JSON.stringify(reference)));
5310
+ }
5311
+ /** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */
5312
+ private guidanceStorage<T>(operation: "read" | "write", action: () => T): T {
5313
+ try { return action(); }
5314
+ catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); }
5315
+ }
5316
+ private guidanceFence(by: PeerId, task: Task): GuidanceWriteFence {
5317
+ return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
5318
+ owner: task.owner, state: task.state, roleId: task.role };
5319
+ }
5320
+ private guidanceFieldAllowed(text: string): boolean {
5321
+ try { return this.nameable(text) && !looksSecret(text) && this.lineageMetadata(JSON.stringify(text)); }
5322
+ catch { return false; }
5323
+ }
5324
+ private guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; }
5325
+ private guidanceExperimentFor(projectKey: string, task: Task, selector: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id"> & { experimentId?: string }): string | undefined {
5326
+ return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined);
5327
+ }
5328
+ private guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; }
5329
+ private guidanceReadFence(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, task: Task, check: () => void): Task {
5330
+ check(); const current = this.guidanceTask(by, selector, false);
5331
+ if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role])
5332
+ !== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed");
5333
+ return current;
5334
+ }
5335
+ private guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] {
5336
+ const ports = this.lineagePorts(by), projectKey = this.guidanceProject();
5337
+ return records.map(record => record.variant.evidenceRefs.map(reference => {
5338
+ let known = false;
5339
+ if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) {
5340
+ const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } });
5341
+ known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference));
5342
+ }
5343
+ return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const };
5344
+ }));
5345
+ }
5346
+ private guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord {
5347
+ return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId),
5348
+ status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record),
5349
+ rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence };
5350
+ }
5351
+ private guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt {
5352
+ const value = saved.record.variant;
5353
+ return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already };
5354
+ }
5355
+ /** Immutable declarations only. Neither creation nor readback changes effective role guidance. */
5356
+ async guidanceVariantCreate(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
5357
+ const check = this.guidanceRequest(by);
5358
+ let variant: Readonly<GuidanceVariantV1>;
5359
+ try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); }
5360
+ return this.studyWrite(async () => {
5361
+ const context = () => {
5362
+ check();
5363
+ const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task);
5364
+ if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying");
5365
+ const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId));
5366
+ const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId));
5367
+ try {
5368
+ validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
5369
+ experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline,
5370
+ currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) });
5371
+ } catch (error) {
5372
+ if (error instanceof GuidanceVariantError) throw new PreEffectToolRefusal("guidance variant or frozen baseline is invalid or changed; reload the task and use a new experiment for a changed baseline");
5373
+ throw new Error("guidance validation is unavailable; inspect the task experiment before retrying");
5374
+ }
5375
+ return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) };
5376
+ };
5377
+ const before = context();
5378
+ if (this.screenOn() && (await this.screenCall(JSON.stringify(variant))).label !== "clear")
5379
+ throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available");
5380
+ const current = context();
5381
+ if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying");
5382
+ check();
5383
+ const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task)));
5384
+ return this.guidanceReceipt(saved);
5385
+ });
5386
+ }
5387
+ async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
5388
+ const check = this.guidanceRequest(by);
5389
+ let selector: GuidanceSelector | GuidanceIdSelector;
5390
+ try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } }
5391
+ catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); }
5392
+ return this.studyWrite(async () => {
5393
+ check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject();
5394
+ if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing");
5395
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5396
+ const record = experimentId === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId)).find(item => item.variant.id === selector.id);
5397
+ if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing");
5398
+ check();
5399
+ const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task)));
5400
+ return this.guidanceReceipt(saved);
5401
+ });
5402
+ }
5403
+ private guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean {
5404
+ try {
5405
+ if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false;
5406
+ const value = record.variant, role = this.guidanceRole(task);
5407
+ return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer
5408
+ && value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true);
5409
+ } catch { return false; }
5410
+ }
5411
+ /** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */
5412
+ guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult {
5413
+ try {
5414
+ const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input);
5415
+ check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject();
5416
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5417
+ if (experimentId === undefined) return { state: "unavailable" };
5418
+ const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId);
5419
+ const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records;
5420
+ if (!selected.length) return { state: "unavailable" };
5421
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check);
5422
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
5423
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId);
5424
+ const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh;
5425
+ if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" };
5426
+ const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) };
5427
+ check();
5428
+ return result;
5429
+ } catch { return { state: "unavailable" }; }
5430
+ }
5431
+ /** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */
5432
+ guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult {
5433
+ try {
5434
+ const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input);
5435
+ const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5436
+ if (experimentId === undefined) return { state: "unavailable" };
5437
+ const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id);
5438
+ if (!record) return { state: "unavailable" };
5439
+ const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check);
5440
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
5441
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id);
5442
+ if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" };
5443
+ const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!),
5444
+ sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() });
5445
+ check(); return result;
5446
+ } catch { return { state: "unavailable" }; }
5447
+ }
5448
+ /** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */
5449
+ guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult {
5450
+ try {
5451
+ const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject();
5452
+ const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" };
5453
+ const context = { ...this.guidanceCurrent(task), projectKey, actor: by };
5454
+ const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : "";
5455
+ if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" };
5456
+ const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS);
5457
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check);
5458
+ const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after);
5459
+ if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" };
5460
+ const records: GuidancePublicRecord[] = [];
5461
+ for (const [index, record] of selected.entries()) {
5462
+ const candidate = this.guidanceProjection(by, current, record, evidence[index]!);
5463
+ const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) };
5464
+ if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break;
5465
+ records.push(candidate);
5466
+ }
5467
+ const truncated = records.length < page.length;
5468
+ if (truncated && !records.length) return { state: "unavailable" };
5469
+ const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated,
5470
+ ...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) });
5471
+ check(); return result;
5472
+ } catch { return { state: "unavailable" }; }
5473
+ }
5474
+
5475
+ /** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */
5476
+ guidanceVariantApplicable(by: PeerId, input: unknown): boolean {
5477
+ try {
5478
+ const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected);
5479
+ return read.state === "available" && read.record.applicable;
5480
+ } catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ }
5481
+ try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; }
5482
+ const read = this.guidanceVariantRead(by, input);
5483
+ return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable;
5484
+ }
5485
+
5486
+ /** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */
5487
+ async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> {
5488
+ if (!executionLinkActor(by) || by === HUB || by === "admin") throw new PreEffectToolRefusal("execution links require a current local task actor; ask the person or the task owner to record the declaration");
5489
+ const check = this.requestCheck(by, () => this.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined);
5490
+ let proposed: ExecutionLinkInput;
5491
+ try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); }
5492
+ return this.studyWrite(async () => {
5493
+ const context = () => {
5494
+ check();
5495
+ const ports = this.lineagePorts(by);
5496
+ if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying");
5497
+ let task: Task;
5498
+ try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); }
5499
+ const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined;
5500
+ if (by !== USER && (!role || !this.d.roles?.[by]?.includes(role) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("execution links require the task's current owner or reviewer role; ask that peer or the person to record the declaration");
5501
+ if (!this.lineageVisible(by, task)) throw new PreEffectToolRefusal("execution links require a public task outside private or review input; refresh the current task policy before retrying");
5502
+ if (task.created !== proposed.taskCreated || task.history.length !== proposed.flowRevision) throw new PreEffectToolRefusal("execution link task identity or revision changed; refresh ahub task show before retrying");
5503
+ const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created);
5504
+ const scope = { id: task.id, created: task.created };
5505
+ const origin = executionOwnerSnapshot(ports, { root: from, task: scope });
5506
+ if (origin.source.health !== "ready" || !origin.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(from))) throw new PreEffectToolRefusal("execution link origin is not recorded in this task; select an existing public task-scoped reference");
5507
+ if (proposed.reference.tool === "ahub") {
5508
+ const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope });
5509
+ if (target.source.health !== "ready" || !target.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(proposed.reference))) throw new PreEffectToolRefusal("local execution target is not recorded in this task; select a verified task-scoped reference");
5510
+ }
5511
+ const metadata = JSON.stringify([from, proposed.reference]);
5512
+ if (!this.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying");
5513
+ return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) };
5514
+ };
5515
+ const before = context();
5516
+ if (this.screenOn()) {
5517
+ const result = await this.screenCall(before.metadata);
5518
+ if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available");
5519
+ }
5520
+ check();
5521
+ const current = context();
5522
+ if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying");
5523
+ const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() });
5524
+ return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already };
5525
+ });
5526
+ }
5527
+
4869
5528
  /** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */
4870
5529
  async evidenceRecord(by: PeerId, input: unknown): Promise<EvidenceReceipt> {
4871
5530
  try { requireLocalTaskPeer(by); }
@@ -5668,7 +6327,9 @@ export class Tasks {
5668
6327
  */
5669
6328
  async recordSdlc(by: PeerId, id: unknown, input: unknown): Promise<Task> {
5670
6329
  const requestCheck = this.requestCheck(by);
5671
- if (!input || typeof input !== "object" || Array.isArray(input) || !("deliverables" in input)) return this.recordLifecycle(by, id, input);
6330
+ const spec = await this.specStageGate(by, id, input);
6331
+ requestCheck();
6332
+ if (!input || typeof input !== "object" || Array.isArray(input) || !("deliverables" in input)) return this.recordLifecycle(by, id, input, undefined, spec?.carry);
5672
6333
  const { deliverables, ...receipt } = input as Record<string, unknown>;
5673
6334
  const task = this.need(id, false, true);
5674
6335
  if (by !== USER && by !== task.owner && by !== task.reviewer) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence");
@@ -5677,12 +6338,12 @@ export class Tasks {
5677
6338
  requestCheck();
5678
6339
  const current = this.need(id, false, true);
5679
6340
  if (current.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed while its deliverables were hashed; record them again");
5680
- return this.recordLifecycle(by, id, receipt, records);
6341
+ return this.recordLifecycle(by, id, receipt, records, spec?.carry);
5681
6342
  }
5682
6343
 
5683
- recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[]): Task {
6344
+ recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object): Task {
5684
6345
  requireLocalTaskPeer(by);
5685
- const task = this.need(id, false, true);
6346
+ const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
5686
6347
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
5687
6348
  const next = sdlcReceipt(input, task.sdlc, config, VERSION);
5688
6349
  const definition = stageDefinition(config, next.stage);
@@ -5714,7 +6375,7 @@ export class Tasks {
5714
6375
  if (next.reviewedHead !== undefined && (next.reviewedHead !== task.sdlc?.reviewedHead || (suppliedHead && artifactChanged))) this.mine(task, by, "reviewer", true);
5715
6376
  const departure = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture;
5716
6377
  const invalidatesDeparture = !!departure && (artifactChanged || next.localHead !== task.sdlc?.localHead && next.localHead !== undefined && next.localHead !== departure.head || next.reviewedHead !== task.sdlc?.reviewedHead && next.reviewedHead !== undefined && next.reviewedHead !== departure.head);
5717
- return this.d.board.update(task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) });
6378
+ return this.commitSpecCarry(by, specCarry, task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) });
5718
6379
  }
5719
6380
 
5720
6381
  /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */
@@ -5770,6 +6431,68 @@ export class Tasks {
5770
6431
  }
5771
6432
  return report;
5772
6433
  }
6434
+ /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
6435
+ async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
6436
+ const check = this.requestCheck(by, fence);
6437
+ const authority = () => {
6438
+ check();
6439
+ if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
6440
+ throw new PreEffectToolRefusal("only the person or the current configured conductor may adopt a merge; ask the person to run ahub sdlc adopt-merge");
6441
+ if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("merge adoption is unavailable in a private turn; finish that turn and retry ahub sdlc adopt-merge");
6442
+ if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError)
6443
+ throw new PreEffectToolRefusal("hub recovery, storage or task writes are held; clear the hold before retrying ahub sdlc adopt-merge");
6444
+ };
6445
+ authority();
6446
+ if (!Number.isSafeInteger(pr) || (pr as number) <= 0) throw new PreEffectToolRefusal("merge adoption needs a positive PR number; run ahub sdlc adopt-merge <task> --pr <n>");
6447
+ if (!Number.isSafeInteger(id) || (id as number) <= 0) throw new PreEffectToolRefusal("merge adoption needs a positive task id; run ahub sdlc adopt-merge <task> --pr <n>");
6448
+ const task = this.d.board.get(id as number);
6449
+ if (!task) throw new PreEffectToolRefusal("merge adoption task does not exist; inspect ahub task list and choose the task to adopt");
6450
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), head = this.reviewHead(task);
6451
+ const identity = (row: Task) => JSON.stringify([row, this.isPii(row)]);
6452
+ const before = identity(task), policy = JSON.stringify(config);
6453
+ const current = () => {
6454
+ authority();
6455
+ const now = this.d.board.get(task.id);
6456
+ if (!now || identity(now) !== before || JSON.stringify(this.d.sdlc?.config() ?? sdlcConfig(undefined)) !== policy)
6457
+ throw new PreEffectToolRefusal("task, privacy or SDLC policy changed during merge adoption; reload the task and retry ahub sdlc adopt-merge");
6458
+ if (this.isPii(now) || now.signals.includes("pii") || now.signals.includes("pii_path")) throw new PreEffectToolRefusal("a private task cannot send merge evidence to GitHub; keep its approval local through the person's review workflow");
6459
+ return now;
6460
+ };
6461
+ current();
6462
+ if (task.draft) throw new PreEffectToolRefusal(`task #${task.id} is a ${task.state} intake draft; approve the intake through ahub intake approve before retrying ahub sdlc adopt-merge`);
6463
+ if (task.state === "proposed" || task.state === "backlog") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state}; assign and accept it first, then retry ahub sdlc adopt-merge`);
6464
+ if (task.state === "approved" || task.state === "cancelled") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state} and already closed; inspect ahub task show ${task.id} and choose an active task instead`);
6465
+ if (!head || !/^[a-f0-9]{40}$/.test(head)) throw new PreEffectToolRefusal("the task has no recorded full head; record its full commit SHA before retrying ahub sdlc adopt-merge");
6466
+ const scope = this.repositories.scope(task.refs), repo = task.sdlc?.repo ?? (scope.key.startsWith("repo:") ? scope.key.slice("repo:".length) : undefined);
6467
+ if (!repo || this.repositories.scope({ repo }).key !== scope.key || task.sdlc?.pr !== undefined && task.sdlc.pr !== pr)
6468
+ throw new PreEffectToolRefusal("PR repository or number differs from the task's recorded artifact, or its repository is unknown; record its correct repository and PR before retrying ahub sdlc adopt-merge");
6469
+ const receipt = { ...task.sdlc, stage: lifecycleStage(config, "merge"), repo, pr: pr as number, head };
6470
+ const important = () => findingTally(findingsForHead(this.reviewFindingSets(current()), head)).openImportant > 0;
6471
+ if (important()) throw new PreEffectToolRefusal("open Important finding blocks merge adoption; resolve the finding and record its disposition before retrying ahub sdlc adopt-merge");
6472
+ const deadline = performance.now() + 20_000;
6473
+ const run: SdlcGh = async (args, timeout, cwd, cap) => {
6474
+ current();
6475
+ const remaining = deadline - performance.now();
6476
+ if (remaining <= 0) throw new PreEffectToolRefusal("merge evidence read timed out; restore GitHub access and retry ahub sdlc adopt-merge");
6477
+ const result = await (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? 10_000, remaining), cwd, cap);
6478
+ current();
6479
+ return result;
6480
+ };
6481
+ const evidence = await readAdoptMergeEvidence(receipt, run);
6482
+ const now = current();
6483
+ const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
6484
+ if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
6485
+ const capacity = this.capacityBefore(now);
6486
+ current(); // No await between the last authority/privacy/flow check and the sole approval write.
6487
+ const next = this.d.board.adoptMerge(now.id, by, receipt, head, now.history.length, HOST_MERGE_ADOPTION);
6488
+ this.cohorts.closed(next.id);
6489
+ this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id);
6490
+ this.writePlannerNotices(next, capacity, true);
6491
+ this.releaseNotice(`task #${next.id}: merged outside the hub; approved`);
6492
+ await this.releaseDependents(next);
6493
+ return { task: next.id, state: "approved" };
6494
+ }
6495
+
5773
6496
  private readonly mergesInFlight = new Set<number>();
5774
6497
  /** #786: who may ask for a guarded merge. The hub's own approval trigger acts as HUB; a peer must be the one configured conductor. */
5775
6498
  private mergeAuthority(by: PeerId): boolean {
@@ -5919,7 +6642,7 @@ export class Tasks {
5919
6642
  } catch { /* an approval never fails because of the merge check */ }
5920
6643
  }
5921
6644
  async releaseReadiness(repo: string, liveIssues: number[]) {
5922
- 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 });
5923
6646
  if (report.documents) report.documents.documents = report.documents.documents.map(d => {
5924
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; }
5925
6648
  return d;
@@ -6072,7 +6795,8 @@ export class Tasks {
6072
6795
  }
6073
6796
  private specText(task: Task, state: Exclude<SpecState, "current">, verb: "blocked" | "advice"): string {
6074
6797
  const issue = task.sdlc?.issue;
6075
- const why = issue ? SPEC_STATE_TEXT[state].replace("<task>", String(task.id)).replace("<n>", String(issue)) : "spec issue unknown: record repo and issue with hub_sdlc_record, then the person accepts it with ahub sdlc accept";
6798
+ const diagnostic = verb === "blocked" && !this.isPii(task) && state === "missing" ? buildEntryDiagnostic(task) : undefined;
6799
+ const why = diagnostic ?? (issue ? SPEC_STATE_TEXT[state].replace("<task>", String(task.id)).replace("<n>", String(issue)) : "spec issue unknown: record repo and issue with hub_sdlc_record, then the person accepts it with ahub sdlc accept");
6076
6800
  return `task #${task.id}: SDLC build entry ${verb}: ${why}`;
6077
6801
  }
6078
6802
 
@@ -6088,19 +6812,137 @@ export class Tasks {
6088
6812
  return this.d.board.update(task.id, USER, "spec accepted", { sdlc: next }, `issue #${next.issue}, body last edited ${spec.edit.lastEditedAt ?? "never"}`);
6089
6813
  }
6090
6814
 
6815
+ private readonly specCarries = new WeakMap<object, SpecCarryProof>();
6816
+ /** Opaque host proof only: a virtual receipt never changes the stored row or its flow. */
6817
+ private stagedSpec(by: PeerId, task: Task, token?: object, preEffect = true): Task {
6818
+ if (!token) return task;
6819
+ try {
6820
+ const proof = this.specCarries.get(token);
6821
+ if (!proof || proof.by !== by || proof.task !== task.id) throw new Error("unknown or consumed host spec carry proof");
6822
+ if (!proof.current() || task.sdlc?.repo !== proof.commit.acceptance.repo || task.sdlc.issue !== proof.commit.acceptance.issue
6823
+ || this.specAcceptanceScope(task.refs) !== proof.scope || !this.specAcceptancePublic(task)) throw new Error("task or source changed during staged spec admission");
6824
+ return { ...task, sdlc: { ...task.sdlc, acceptance: proof.commit.acceptance } };
6825
+ } catch (error) {
6826
+ const message = error instanceof Error ? error.message : "staged spec admission changed";
6827
+ throw new (preEffect ? PreEffectToolRefusal : Error)(`${message}; inspect the current task and held deliveries before repeating this action`);
6828
+ }
6829
+ }
6830
+ /** Called only at an admitted outer write; later failures keep ordinary post-effect error semantics. */
6831
+ private commitSpecCarry(caller: PeerId, token: object | undefined, ...args: Parameters<Board["update"]>): Task {
6832
+ if (!token) return this.d.board.update(...args);
6833
+ const [id, by, event, patch, note, extra, revision, codeSymbolsAuthority, adoptionAuthority] = args;
6834
+ const stored = this.need(id, false, false);
6835
+ if (by !== caller && !(by === HUB && ["integration requested", "integration unresolved", "integrated"].includes(event))) throw new Error("spec carry event actor differs from its admitted caller; inspect the current task and held deliveries before repeating this action");
6836
+ this.stagedSpec(caller, { ...stored, ...patch, refs: { ...stored.refs, ...patch.refs } }, token, false);
6837
+ const proof = this.specCarries.get(token)!;
6838
+ const next = this.d.board.updateWithSpecAcceptance(proof.commit, HOST_SPEC_ACCEPTANCE_CARRY,
6839
+ id, by, event, patch, note, extra, revision ?? stored.history.length, codeSymbolsAuthority, adoptionAuthority);
6840
+ this.specCarries.delete(token);
6841
+ return next;
6842
+ }
6843
+
6844
+ /** No cold repository probes or source task hydration participate in consent authority. */
6845
+ private specAcceptanceScope(refs: TaskRefs): string | undefined {
6846
+ return this.repositories.cachedScope(refs)?.key
6847
+ ?? (!refs.repo && !(refs.paths ?? []).some(isAbsolute) ? this.repositories.project.key : undefined);
6848
+ }
6849
+ private specAcceptancePublic(task: Pick<Task, "refs" | "signals">): boolean {
6850
+ try {
6851
+ const normalized = cleanRefs(task.refs);
6852
+ if (["repo", "branch", "commit"].some(key => task.refs[key as keyof TaskRefs] !== normalized[key as keyof TaskRefs])
6853
+ || JSON.stringify(task.refs.paths ?? []) !== JSON.stringify(normalized.paths ?? [])) return false;
6854
+ return !task.signals.includes("pii") && !task.signals.includes("pii_path")
6855
+ && this.publicMetadataText(JSON.stringify(task.refs)) === true
6856
+ && !(task.refs.paths ?? []).some(path => this.reviewPathPrivate(path));
6857
+ } catch { return false; }
6858
+ }
6859
+ /** Carry uses the existing owner/reviewer/stage-planner authority, without admitting a stage write. */
6860
+ private specAcceptanceActor(by: PeerId, task: Task, receipt = task.sdlc, stageInput?: Record<string, unknown>): boolean {
6861
+ if (by === USER) return true;
6862
+ if (!this.d.bus.isRostered(by)) return false;
6863
+ let role = by === task.owner ? ownerRoleOfClass(task.class) : undefined;
6864
+ if (stageInput) {
6865
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), definition = receipt && stageDefinition(config, receipt.stage);
6866
+ const planners = this.taskPlanner(task), planner = planners.includes(by);
6867
+ const plannerStage = Object.keys(stageInput).every(key => ["stage", "repo", "issue"].includes(key))
6868
+ && (definition?.actor === "planner" || definition?.actor === "owner/planner") && planner;
6869
+ if (by !== task.owner && by !== task.reviewer && !plannerStage) return false;
6870
+ if (config.mode === "enforce" && config.definitions) {
6871
+ const actor = definition?.actor;
6872
+ const acts = actor === "owner" ? by === task.owner : actor === "reviewer" ? by === task.reviewer
6873
+ : actor === "planner" ? planner : actor === "owner/planner" && (by === task.owner || planner);
6874
+ if (!acts) return false;
6875
+ }
6876
+ role ??= by === task.reviewer ? "reviewer" : "planner";
6877
+ }
6878
+ return !!role && (!this.d.roles || this.d.roles[by]?.includes(role) === true);
6879
+ }
6880
+ /** One strict host observation serves both the carry decision and the ordinary spec verdict. */
6881
+ private async readSpecAcceptance(by: PeerId, task: Task, receipt = task.sdlc, allowCarry = true, stageInput?: Record<string, unknown>): Promise<SpecGateRead> {
6882
+ const unchanged: SpecGateRead = { task };
6883
+ const accepted = receipt?.acceptance;
6884
+ if (accepted) return { ...unchanged, edit: !this.isPii(task) ? await readSpecEdit(accepted.repo, accepted.issue, this.d.sdlc?.gh) : undefined };
6885
+ if (!allowCarry || !receipt?.repo || !receipt.issue || receipt.repo !== task.sdlc?.repo || receipt.issue !== task.sdlc?.issue) return unchanged;
6886
+ const check = this.requestCheck(by), scope = this.specAcceptanceScope(task.refs);
6887
+ const policy = () => {
6888
+ const routing = this.d.routing();
6889
+ return JSON.stringify([this.d.roles, this.d.deny, this.d.piiPaths, routing.constraints, routing.signals.pii_patterns, this.d.sdlc?.config()]);
6890
+ };
6891
+ const actorPublic = () => !this.d.privateTurn?.(by) && this.specAcceptanceActor(by, task, receipt, stageInput);
6892
+ if (!scope || isClosedTaskState(task.state) || !actorPublic() || !this.specAcceptancePublic(task)
6893
+ || this.publicMetadataText(receipt.repo) !== true) return unchanged;
6894
+ const eligible = (source: SpecAcceptanceCandidate) => {
6895
+ const consent = storedSpecAcceptance(source.acceptance);
6896
+ return !source.withheld && source.id < task.id && localSupersedingTask(source.supersededBy) === task.id
6897
+ && this.specAcceptancePublic(source) && this.specAcceptanceScope(source.refs) === scope
6898
+ && typeof source.repo === "string" && source.repo.toLowerCase() === receipt.repo!.toLowerCase() && source.issue === receipt.issue
6899
+ && !!consent && consent.repo.toLowerCase() === receipt.repo!.toLowerCase() && consent.issue === receipt.issue;
6900
+ };
6901
+ const snapshot = (value: Task) => JSON.stringify([value.created, value.state, value.class, value.reviewer, value.planner, value.refs, value.signals]);
6902
+ const beforeTask = snapshot(task), sources = this.d.board.specAcceptanceCandidates(task.id), beforePolicy = policy();
6903
+ const planners = JSON.stringify(this.taskPlanner(task));
6904
+ if (!sources.complete || !sources.rows.some(eligible)) return unchanged;
6905
+ const edit = await readSpecEdit(receipt.repo, receipt.issue, this.d.sdlc?.gh);
6906
+ check();
6907
+ if (this.specMoved(task)) return unchanged;
6908
+ const currentTask = this.need(task.id, false, true);
6909
+ if (snapshot(currentTask) !== beforeTask || !actorPublic() || !this.specAcceptancePublic(currentTask) || policy() !== beforePolicy
6910
+ || JSON.stringify(this.taskPlanner(task)) !== planners || this.specAcceptanceScope(task.refs) !== scope) return unchanged;
6911
+ const current = this.d.board.specAcceptanceCandidates(task.id);
6912
+ if (!current.complete || JSON.stringify(current.rows) !== JSON.stringify(sources.rows)) return unchanged;
6913
+ for (const source of current.rows) {
6914
+ if (!eligible(source)) continue;
6915
+ const acceptance = carriedSpecAcceptance(storedSpecAcceptance(source.acceptance)!, { repo: receipt.repo, issue: receipt.issue }, edit);
6916
+ if (!acceptance) continue;
6917
+ Object.freeze(acceptance); // The virtual receipt must not expose mutable host-consent fields.
6918
+ const token = Object.freeze({});
6919
+ this.specCarries.set(token, { by, task: task.id, scope, commit: { source: source.id, cancellationRevision: source.cancellationRevision, acceptance }, current: () => {
6920
+ check();
6921
+ const now = this.need(task.id, false, true), latest = this.d.board.specAcceptanceCandidates(task.id);
6922
+ const donor = latest.rows.find(row => row.id === source.id);
6923
+ return now.history.length === task.history.length && now.owner === task.owner && JSON.stringify(now.sdlc) === JSON.stringify(task.sdlc)
6924
+ && snapshot(now) === beforeTask && actorPublic() && policy() === beforePolicy
6925
+ && JSON.stringify(this.taskPlanner(now)) === planners && latest.complete && JSON.stringify(latest.rows) === JSON.stringify(sources.rows)
6926
+ && !!donor && eligible(donor);
6927
+ } });
6928
+ return { task: { ...task, sdlc: { ...task.sdlc!, acceptance } }, edit, carry: token };
6929
+ }
6930
+ return { ...unchanged, edit };
6931
+ }
6932
+
6091
6933
  /** Build entry with a live readback of the spec's body edit time (#481 S1): enforce refuses, advise notifies, off does nothing. */
6092
- async specGate(by: PeerId, id: unknown): Promise<void> {
6934
+ async specGate(by: PeerId, id: unknown, prospectiveRefs?: TaskRefs): Promise<SpecGateRead | undefined> {
6093
6935
  requireLocalTaskPeer(by);
6094
6936
  const task = this.need(id, false, true);
6095
6937
  if (!this.specGated(task) || task.owner !== by && by !== USER) return; // accept reports its own refusals
6096
- const accepted = task.sdlc?.acceptance;
6097
- const edit = accepted && !this.isPii(task) ? await readSpecEdit(accepted.repo, accepted.issue, this.d.sdlc?.gh) : undefined;
6938
+ const result = await this.readSpecAcceptance(by, task, task.sdlc, !prospectiveRefs || this.specAcceptanceScope(prospectiveRefs) === this.specAcceptanceScope(task.refs));
6098
6939
  if (this.specMoved(task)) return;
6099
- this.specVerdict(task, task.sdlc?.issue ? specState(task.sdlc, edit) : "missing");
6940
+ this.specVerdict(result.task, result.task.sdlc?.issue ? specState(result.task.sdlc, result.edit) : "missing");
6941
+ return result.carry ? result : undefined;
6100
6942
  }
6101
6943
 
6102
6944
  /** #481 S1: a build stage change by an agent re-reads the body edit time first, as accept does. */
6103
- async specStageGate(by: PeerId, id: unknown, input: unknown): Promise<void> {
6945
+ async specStageGate(by: PeerId, id: unknown, input: unknown): Promise<SpecGateRead | undefined> {
6104
6946
  requireLocalTaskPeer(by);
6105
6947
  const task = this.need(id, false, true), config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6106
6948
  if (config.mode === "off" || by === USER || !input || typeof input !== "object" || !("stage" in input)) return;
@@ -6110,10 +6952,11 @@ export class Tasks {
6110
6952
  try { next = sdlcReceipt(lifecycleInput, task.sdlc, config, VERSION); } catch { return; } // recordLifecycle reports an invalid receipt
6111
6953
  const definition = stageDefinition(config, next.stage);
6112
6954
  if (next.stage === task.sdlc?.stage || !definition || canonicalStage(definition.base) !== "build") return;
6113
- const accepted = next.acceptance;
6114
- const edit = accepted && !this.isPii(task) ? await readSpecEdit(accepted.repo, accepted.issue, this.d.sdlc?.gh) : undefined;
6955
+ const result = await this.readSpecAcceptance(by, task, next, true, lifecycleInput);
6115
6956
  if (this.specMoved(task)) return;
6116
- this.specVerdict(task, next.issue ? specState(next, edit) : "missing");
6957
+ if (result.carry) next.acceptance = result.task.sdlc!.acceptance;
6958
+ this.specVerdict(result.task, next.issue ? specState(next, result.edit) : "missing");
6959
+ return result.carry ? result : undefined;
6117
6960
  }
6118
6961
 
6119
6962
  /**
@@ -6222,30 +7065,31 @@ export class Tasks {
6222
7065
  this.validatePlanSources(proposedPlan && Object.keys(proposedPlan).length ? proposedPlan : task.plan);
6223
7066
  this.acceptanceCapacity(task, 0, "check"); // #1080: an urgent task may still take unaccepted offers; `accept` does that, after its gates
6224
7067
  if (metadata && !this.isPii(task) && (!this.nameable(metadata.repo!) || looksSecret(metadata.repo!) || this.aboutPrivatePath("", metadata.repo!, task))) throw new PreEffectToolRefusal("this repository metadata is private or sensitive and is not kept");
6225
- const draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task;
7068
+ let draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task;
6226
7069
  this.warmRepository(draft);
6227
7070
  if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.accept(by, id, plan, metadata);
6228
- await this.specGate(by, id);
6229
- await this.planEntryGate(by, draft);
7071
+ const spec = await this.specGate(by, id, draft.refs);
7072
+ if (spec?.carry) draft = metadata ? { ...spec.task, refs: { ...spec.task.refs, ...metadata } } : spec.task;
7073
+ await this.planEntryGate(by, draft, spec?.carry);
6230
7074
  requestCheck();
6231
7075
  const current = this.need(id, false, true);
6232
7076
  this.mine(current, by, "owner", true);
6233
7077
  if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during build admission");
6234
7078
  this.reviewedAdmissions.set(current.id, { flow: current.history.length, owner: current.owner });
6235
- try { return this.accept(by, id, plan, metadata); }
7079
+ try { return this.accept(by, id, plan, metadata, spec?.carry); }
6236
7080
  finally { this.reviewedAdmissions.delete(current.id); }
6237
7081
  }
6238
7082
 
6239
7083
  /** Spec and plan readbacks share the caller's original task snapshot until the final acceptance write. */
6240
- private async planEntryGate(by: PeerId, task: Task): Promise<void> {
7084
+ private async planEntryGate(by: PeerId, task: Task, specCarry?: object): Promise<void> {
6241
7085
  const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode;
6242
7086
  if (mode === "off" || !this.isBuildTask(task)) return;
6243
7087
  const gap = await this.planReviewGap(task);
6244
7088
  if (mode === "advise" && !task.sdlc?.planReview?.scope) this.releaseNotice(`task ${this.publicTitle(task)}: cost scope unspecified`);
6245
- const current = this.need(task.id, false, true);
7089
+ const current = this.stagedSpec(by, this.need(task.id, false, true), specCarry);
6246
7090
  this.mine(current, by, "owner", true);
6247
7091
  if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during plan readback");
6248
- if (gap && mode === "enforce") throw new PreEffectToolRefusal(gap);
7092
+ if (gap && mode === "enforce") throw new PreEffectToolRefusal(this.entryDiagnostic(current, gap) ?? gap);
6249
7093
  if (gap) this.releaseNotice(`task ${this.publicTitle(current)}: ${gap}`);
6250
7094
  }
6251
7095
 
@@ -6344,10 +7188,10 @@ export class Tasks {
6344
7188
  * With a plan, the owners of overlapping tasks get it as a ride-along line, and an overlap only the plan reveals is
6345
7189
  * announced like one found at assignment (issue #31).
6346
7190
  */
6347
- accept(by: PeerId, id: unknown, plan?: unknown, refs?: unknown): Task {
7191
+ accept(by: PeerId, id: unknown, plan?: unknown, refs?: unknown, specCarry?: object): Task {
6348
7192
  requireLocalTaskPeer(by);
6349
7193
  const metadata = acceptRefs(refs);
6350
- const task = this.need(id, false, true);
7194
+ const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
6351
7195
  this.mine(task, by, "owner", true);
6352
7196
  this.ready(task, true);
6353
7197
  // #1176: a person-run leg is never an agent's to accept, whatever offer or owner it carries from before it was marked.
@@ -6389,7 +7233,7 @@ export class Tasks {
6389
7233
  let next: Task;
6390
7234
  try {
6391
7235
  this.acceptanceCapacity(task, 0, "displace"); // #1080: every gate has passed; synchronous from here to the accept write
6392
- next = this.linkOnWrite(this.d.board.update(task.id, by, "accepted", { state: "in_progress", ...(cleaned ? { plan: cleaned } : {}), ...(metadata ? { refs: metadata } : {}) })); // #723: refs.repo may have just arrived
7236
+ next = this.linkOnWrite(this.commitSpecCarry(by, specCarry, task.id, by, "accepted", { state: "in_progress", ...(cleaned ? { plan: cleaned } : {}), ...(metadata ? { refs: metadata } : {}) })); // #723: refs.repo may have just arrived
6393
7237
  } catch (error) { undoWorktree?.(); throw error; }
6394
7238
  this.captureOwnerAcceptance(next);
6395
7239
  this.d.notify(`task ${this.publicTitle(next)} accepted by ${by}`);
@@ -6714,7 +7558,9 @@ export class Tasks {
6714
7558
  const refileHead: RefileHeadGuard | undefined = !submittedCommit && initial.sdlc?.repo && initial.sdlc.pr && this.hasReviewHistory(initial) && !this.isPii(initial)
6715
7559
  ? { recorded: this.ownerReviewHead(initial) } : undefined;
6716
7560
  const draft = refresh ?? (submittedCommit && /^[a-f0-9]{40}$/.test(submittedCommit) ? { commit: submittedCommit } : undefined);
6717
- const valid = () => { requestCheck(); const current = this.completionDraft(this.completionCurrent(id, by, true, refresh), draft); if (resolvedReviewComments !== undefined) this.reviewCommentResolve(by, current, resolvedReviewComments); return current; };
7561
+ let specCarry: object | undefined;
7562
+ const write = (...args: Parameters<Board["update"]>) => { const result = this.commitSpecCarry(by, specCarry, ...args); specCarry = undefined; return result; };
7563
+ const valid = () => { requestCheck(); const current = this.stagedSpec(by, this.completionDraft(this.completionCurrent(id, by, true, refresh), draft), specCarry); if (resolvedReviewComments !== undefined) this.reviewCommentResolve(by, current, resolvedReviewComments); return current; };
6718
7564
  if (initial.state === "approved") { await this.unmergedForReopen(initial, valid); valid(); }
6719
7565
  // #509a: a bad claim (a claimed hash, an outside or denied path, a missing file) is refused before any effect, with nothing recorded.
6720
7566
  const claims = deliverables === undefined ? undefined : this.deliverableClaims(deliverables, valid());
@@ -6726,18 +7572,18 @@ export class Tasks {
6726
7572
  task = valid();
6727
7573
  // #481 S1: done without a separate accept starts build work too: the same live spec check as accept, before any write.
6728
7574
  if (task.state === "proposed" || task.state === "changes_requested") {
6729
- const admission = task;
6730
- await this.specGate(by, task.id);
6731
- await this.planEntryGate(by, admission);
7575
+ const admission = await this.specGate(by, task.id, { ...task.refs, ...cleanRefs(refs) });
7576
+ specCarry = admission?.carry;
7577
+ await this.planEntryGate(by, admission?.carry ? admission.task : task, specCarry);
6732
7578
  task = valid();
6733
7579
  }
6734
7580
  // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them.
6735
7581
  const link = this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined;
6736
- const current = () => this.withLink(valid(), link, refs);
7582
+ const current = () => this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry);
6737
7583
  task = current();
6738
7584
  let reviewEvidence: PrEvidence | undefined;
6739
7585
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off") { reviewEvidence = await this.lifecycleGate(task, "review", undefined, undefined, refileHead); task = current(); }
6740
- const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => this.withLink(this.completionDraft(staged, draft), link, refs), !task.reviewer, refileHead) : undefined;
7586
+ const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => this.stagedSpec(by, this.withLink(this.completionDraft(staged, draft), link, refs), specCarry), !task.reviewer, refileHead) : undefined;
6741
7587
  task = current();
6742
7588
  if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") {
6743
7589
  const currentHead = await this.currentPrHeadForReview(task, current);
@@ -6765,11 +7611,11 @@ export class Tasks {
6765
7611
  const ig = cohort!.integration;
6766
7612
  if (ig?.task === task.id && ig.offer) this.d.ackFacts?.(task.owner!, ig.offer); // this call is the proof the request arrived
6767
7613
  const r = this.cohorts.completion(cohort!, task, { gen, tree: this.tree(cohort!), factsCurrent: this.d.factsCurrent?.(task.owner!) ?? true, handed: handedAt(task) });
6768
- if (r.action === "request") return this.d.board.update(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
7614
+ if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
6769
7615
  if (r.action === "unresolved") {
6770
7616
  this.d.notify(`task ${this.publicTitle(task)}: turn-free integration unresolved after ${MAX_REQUESTS} requests (${r.why}); its done is recorded, check the overlapping work by hand`);
6771
- task = this.withLink(this.d.board.update(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
6772
- } else if (r.integrated) task = this.withLink(this.d.board.update(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
7617
+ task = this.withLink(write(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
7618
+ } else if (r.integrated) task = this.withLink(write(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
6773
7619
  } else if (cohort?.held.size && !this.isPii(task)) {
6774
7620
  // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in
6775
7621
  // for it (issue #107, AC4).
@@ -6777,7 +7623,7 @@ export class Tasks {
6777
7623
  if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`);
6778
7624
  else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`);
6779
7625
  }
6780
- if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(this.d.board.update(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept
7626
+ if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(write(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept
6781
7627
  const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined;
6782
7628
  if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn);
6783
7629
  // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next.
@@ -6789,7 +7635,7 @@ export class Tasks {
6789
7635
  const storedRefs = { ...task.refs, ...checkedRefs };
6790
7636
  this.warmRepository({ ...task, refs: { ...task.refs, ...checkedRefs } });
6791
7637
  this.assertSpecInspection(specInspection, { ...task, refs: storedRefs }, by);
6792
- const pending = this.d.board.update(task.id, by, "done (checking)", { ...(refresh ? { state: "in_progress" as const } : {}), ...(refresh?.state === "approved" && !task.reviewer ? { reviewer: USER } : {}), codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), refs: checkedRefs, ...(task.sdlc ? { sdlc: task.sdlc } : {}) }, summary, { withheld: withheld || undefined, ...(records ? { deliverables: records } : {}), ...(specInspection.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
7638
+ const pending = write(task.id, by, "done (checking)", { ...(refresh ? { state: "in_progress" as const } : {}), ...(refresh?.state === "approved" && !task.reviewer ? { reviewer: USER } : {}), codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), refs: checkedRefs, ...(task.sdlc ? { sdlc: task.sdlc } : {}) }, summary, { withheld: withheld || undefined, ...(records ? { deliverables: records } : {}), ...(specInspection.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
6793
7639
  if (refresh) { this.ciWatchers.cancel(pending.id); this.heldReviews.delete(pending.id); }
6794
7640
  this.releaseNotice(`task ${this.publicTitle(pending)} done by ${by}; its check is queued or running: ${command}`);
6795
7641
  const seen = { events: pending.history.length, owner: pending.owner };
@@ -7146,7 +7992,7 @@ export class Tasks {
7146
7992
  };
7147
7993
  const evidence: ReviewReadiness = this.isPii(task)
7148
7994
  ? { ready: false, blockers: ["private review readiness unavailable"] }
7149
- : task.sdlc ? reviewReadinessFromEvidence(previous, expected, this.d.sdlc?.config().requiredChecks ?? []) ?? await readReviewReadiness(task.sdlc, expected, read, this.d.sdlc?.config().requiredChecks ?? []) : { ready: false, blockers: ["review PR identity missing"] };
7995
+ : task.sdlc ? reviewReadinessFromEvidence(previous, expected, this.d.sdlc ? requiredChecksFor(this.d.sdlc.config(), task.sdlc.repo) : [], task.sdlc.repo) ?? await readReviewReadiness(task.sdlc, expected, read, this.d.sdlc ? requiredChecksFor(this.d.sdlc.config(), task.sdlc.repo) : []) : { ready: false, blockers: ["review PR identity missing"] };
7150
7996
  const currentHead = refileHead && !evidence.head && task.sdlc ? await readSdlcPrHead(task.sdlc, read) : evidence.head;
7151
7997
  const current = guard();
7152
7998
  const admitted: ReviewReadiness = quietDrift ? { ready: false, blockers: ["review readiness unknown: task changed during readback"] } : evidence;
@@ -8228,6 +9074,24 @@ export class Tasks {
8228
9074
  }
8229
9075
  }
8230
9076
 
9077
+ /**
9078
+ * #1221 T2: one accepted supervision proposal's notice, to the owners of the tasks it names. A delivery through the
9079
+ * same owner path `tell` uses, never a board write: the task's own result stays in its history and a later review of
9080
+ * that result stays a separate record. The person is not told here (the console owns that), and a private task is
9081
+ * refused, so nothing about one leaves the machine.
9082
+ */
9083
+ supervisionNotice(task: number, other: number | undefined, body: string): { sent: PeerId[]; refused?: string } {
9084
+ const primary = this.d.board.get(task);
9085
+ if (!primary) return { sent: [], refused: `task #${task} is not on the board` };
9086
+ if (this.isPii(primary)) return { sent: [], refused: "a private task is never proposed on" };
9087
+ const partner = other === undefined ? undefined : this.d.board.get(other);
9088
+ if (other !== undefined && partner && this.isPii(partner)) return { sent: [], refused: "a private task is never proposed on" };
9089
+ const targets = [...new Set([primary.owner, partner?.owner].filter((peer): peer is PeerId => !!peer && peer !== USER && peer !== HUB))];
9090
+ if (!targets.length) return { sent: [], refused: "the task has no owner to tell" };
9091
+ for (const peer of targets) this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", priority: "important", refs: { task: String(task), taskRecipient: "owner" } }));
9092
+ return { sent: targets };
9093
+ }
9094
+
8231
9095
  private tell(task: Task, body: string, pii: boolean, audience: "owner" | "withdrawal" = "owner", reviewObserverExcluded = false): void {
8232
9096
  if (!task.owner || task.owner === USER) return;
8233
9097
  this.d.bus.publish(newEnvelope(HUB, body, { to: [task.owner], kind: reviewObserverExcluded ? "review" : "task", priority: "important", refs: { task: String(task.id), ...(reviewObserverExcluded ? { reviewPackage: `finding-${crypto.randomUUID()}` } : {}), ...(audience === "owner" ? { taskRecipient: "owner" as const } : {}) }, ...(pii ? { private: true } : {}) }));