@staix/agent-hub 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +21 -4
  3. package/docs/agent-notes/README.md +60 -0
  4. package/docs/agent-notes/adapters.md +5 -2
  5. package/docs/agent-notes/bus.md +1 -0
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/models.md +4 -3
  8. package/docs/agent-notes/tasks.md +8 -1
  9. package/docs/agent-notes/tests.md +1 -0
  10. package/docs/design/adapters.md +72 -0
  11. package/docs/design/agent-hub-architecture.md +1 -1
  12. package/docs/design/bus.md +8 -0
  13. package/docs/design/execution-reference.md +171 -11
  14. package/docs/design/guidance-experiments.md +438 -0
  15. package/docs/design/model-routes.md +628 -0
  16. package/docs/design/supervision.md +121 -0
  17. package/docs/design/task-board.md +111 -0
  18. package/docs/dogfood.md +15 -4
  19. package/docs/operations.md +291 -22
  20. package/docs/profiles.md +2 -2
  21. package/docs/quickstart.md +106 -1
  22. package/docs/research.md +4 -2
  23. package/docs/sdlc.md +108 -4
  24. package/docs/security.md +67 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
  26. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  27. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  28. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  29. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  30. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  31. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  32. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  33. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  34. package/docs/verified.json +27 -27
  35. package/package.json +1 -1
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +1201 -368
  38. package/plugins/agent-hub/server.js +1682 -431
  39. package/src/adapters/claude-channel.ts +7 -4
  40. package/src/adapters/compat.ts +10 -10
  41. package/src/adapters/local-worker.ts +1 -1
  42. package/src/adapters/qwen-dual.ts +324 -44
  43. package/src/cli/guidance.ts +67 -0
  44. package/src/cli/help.ts +10 -3
  45. package/src/cli/identity.ts +10 -3
  46. package/src/cli/init-prompt.ts +15 -2
  47. package/src/cli/init-required-checks.ts +122 -0
  48. package/src/cli/init-settings.ts +10 -4
  49. package/src/cli/init.ts +39 -3
  50. package/src/cli/lineage.ts +78 -0
  51. package/src/cli/main.ts +111 -10
  52. package/src/cli/setup-research.ts +10 -0
  53. package/src/hub/autonomy-defaults.ts +20 -9
  54. package/src/hub/board.ts +346 -4
  55. package/src/hub/build-entry.ts +11 -0
  56. package/src/hub/bus.ts +12 -0
  57. package/src/hub/ci-watch.ts +4 -4
  58. package/src/hub/config-apply.ts +2 -1
  59. package/src/hub/config-trust.ts +1 -0
  60. package/src/hub/control-client.ts +1 -1
  61. package/src/hub/daemon.ts +342 -20
  62. package/src/hub/delivery-hints.ts +4 -2
  63. package/src/hub/delivery-journal.ts +50 -2
  64. package/src/hub/delivery-public.ts +51 -0
  65. package/src/hub/dogfood-profile.ts +8 -4
  66. package/src/hub/execution-lineage-owner.ts +272 -0
  67. package/src/hub/execution-lineage.ts +52 -8
  68. package/src/hub/execution-links.ts +85 -0
  69. package/src/hub/guidance-variants.ts +398 -0
  70. package/src/hub/handoff.ts +1 -0
  71. package/src/hub/hub-tools.ts +43 -2
  72. package/src/hub/manager.ts +44 -2
  73. package/src/hub/memory-policy.ts +2 -2
  74. package/src/hub/peers.ts +1 -1
  75. package/src/hub/planning.ts +1 -1
  76. package/src/hub/progress.ts +24 -7
  77. package/src/hub/restart.ts +13 -0
  78. package/src/hub/roles.ts +26 -0
  79. package/src/hub/routing.ts +4 -1
  80. package/src/hub/sdlc-merge.ts +39 -1
  81. package/src/hub/sdlc-release.ts +1 -1
  82. package/src/hub/sdlc.ts +62 -11
  83. package/src/hub/settings.ts +2 -0
  84. package/src/hub/supervision-proposals.ts +405 -0
  85. package/src/hub/supervision-rules.ts +388 -0
  86. package/src/hub/supervision.ts +2 -0
  87. package/src/hub/task-approval.ts +2 -2
  88. package/src/hub/task-repository.ts +5 -0
  89. package/src/hub/tasks.ts +603 -50
  90. package/src/memory/capture.ts +2 -2
  91. package/src/models/relay.ts +9 -2
  92. package/src/models/route/config.ts +27 -0
  93. package/src/models/route/decision.ts +87 -15
  94. package/src/models/route/relay-selector.ts +8 -7
  95. package/src/models/route/runtime.ts +22 -16
  96. package/src/models/route/stage-diagnostics.ts +22 -0
  97. package/src/models/route/stage-evidence.ts +55 -0
  98. package/src/models/route/stage-fallback.ts +58 -0
  99. package/src/models/route/stage-input.ts +155 -0
  100. package/src/models/route/stage.ts +5 -147
  101. package/src/ui/guidance-panel.ts +156 -0
  102. package/src/ui/guidance-view.ts +43 -0
  103. package/src/ui/lineage-view.ts +34 -0
  104. package/src/ui/plugin.ts +71 -7
package/src/hub/tasks.ts CHANGED
@@ -1,3 +1,11 @@
1
+ import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts";
2
+ import { buildEntryDiagnostic } from "./build-entry.ts";
3
+ import { taskShowAllowed } from "./conductor.ts";
4
+ import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
5
+ import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts";
6
+ import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
7
+ import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
8
+ import type { JournalDelivery } from "./delivery-journal.ts";
1
9
  import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt } from "./research-evidence.ts";
2
10
  import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
3
11
  import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
@@ -43,13 +51,13 @@ import { NoWriteTurns } from "./no-writes.ts";
43
51
  import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
44
52
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
45
53
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
46
- import { guardedMerge, mergeModeFor, mergeView, type MergeView } from "./sdlc-merge.ts";
54
+ import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
47
55
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
48
56
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
49
57
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
50
58
  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";
59
+ import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
60
+ import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
53
61
  import { isDenied } from "../local/deny.ts";
54
62
  import { foldSegment, isHubWritePath } from "./permission-mode.ts";
55
63
  import { correctionInput, resolveVisibleMemory } from "./memory-candidates.ts";
@@ -74,11 +82,11 @@ import { isAbsolute, relative, resolve } from "node:path";
74
82
  import type { Briefs, NativeItem } from "../memory/brief.ts";
75
83
  import type { MemoryClient } from "../memory/client.ts";
76
84
  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";
85
+ 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
86
  import type { Bus } from "./bus.ts";
79
87
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
80
88
  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";
89
+ 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
90
  import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts";
83
91
  import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts";
84
92
  import { realPath } from "./project.ts";
@@ -93,7 +101,7 @@ import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
93
101
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
94
102
  import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
95
103
  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";
104
+ 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
105
 
98
106
  /** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
99
107
  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 +116,9 @@ export type TaskAssignmentRole = "owner" | "reviewer" | "planner";
108
116
  /** What `hub_remember` carries (#802: one shape for `remember` and `rememberOutcome`). */
109
117
  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
118
 
119
+ interface SpecGateRead { task: Task; edit?: SpecEdit; carry?: object; }
120
+ interface SpecCarryProof { by: PeerId; task: number; scope: string; commit: SpecAcceptanceCommit; current: () => boolean; }
121
+
111
122
  interface PreparedSpecInspection {
112
123
  report?: SpecTaskReport;
113
124
  policyKey: string;
@@ -141,6 +152,8 @@ export interface TasksDeps {
141
152
  ownerIsolation?: () => Readonly<Record<string, boolean>>;
142
153
  cwd: string;
143
154
  project: string;
155
+ /** Startup-bound namespace/key and an already-open exact-id journal read; never query-controlled. */
156
+ executionLineage?: { projectKey: string; cursorKey: string; readDelivery?(id: string): JournalDelivery | undefined };
144
157
  profile?: ProfileName;
145
158
  profileData?: ProjectProfile;
146
159
  piiPaths?: string[];
@@ -746,7 +759,7 @@ export class Tasks {
746
759
  constructor(private readonly d: TasksDeps) {
747
760
  this.ciWatchers = new CiWatchers({
748
761
  ...d.ciWatch,
749
- poll: watch => pollCi(watch, watch.head, d.sdlc?.config().requiredChecks ?? [], d.sdlc?.gh ?? sdlcGh),
762
+ poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh),
750
763
  current: watch => this.ciWatchCurrent(watch),
751
764
  finish: (watch, outcome) => this.ciCompleted(watch, outcome),
752
765
  });
@@ -1732,9 +1745,10 @@ export class Tasks {
1732
1745
 
1733
1746
  private weights(cls: TaskClass, task?: Task, projectedHealth?: ReturnType<Tasks["health"]>) {
1734
1747
  const now = Date.now();
1748
+ const entryDiagnostic = task ? this.entryDiagnostic(task) : undefined;
1735
1749
  const quota = this.d.quota?.();
1736
1750
  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 } } : {}) };
1751
+ 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
1752
  }
1739
1753
 
1740
1754
  /**
@@ -4328,13 +4342,14 @@ export class Tasks {
4328
4342
  task = current; // Reviewer-only and quiet bookkeeping updates do not supersede ownership authority.
4329
4343
  if (gap) {
4330
4344
  this.requestIndependentPlanReview(current);
4331
- this.releaseNotice(`task ${this.publicTitle(current)}: ${gap}; planner: call hub_planner_groom then hub_plan_review`);
4345
+ const entry = mode === "enforce" ? this.entryDiagnostic(current, gap) ?? `${gap}; planner: hub_plan_review` : `${gap}; planner: call hub_planner_groom then hub_plan_review`;
4346
+ this.releaseNotice(`task ${this.publicTitle(current)}: ${entry}`);
4332
4347
  if (mode === "enforce") {
4333
4348
  if (opts.claim && opts.namedOwner === by) stagedClaimGap = gap;
4334
4349
  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;
4350
+ 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
4351
+ this.holdReady(current, "build entry", entry);
4352
+ return this.d.board.get(current.id) ?? current;
4338
4353
  }
4339
4354
  }
4340
4355
  }
@@ -4840,10 +4855,19 @@ export class Tasks {
4840
4855
  } catch { return undefined; }
4841
4856
  }
4842
4857
 
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. */
4858
+ /** Guidance is separate from candidate choice: offers retain their existing plan-only gate. */
4859
+ private entryDiagnostic(task: Task, planGap?: string): string | undefined {
4860
+ if (this.d.sdlc?.config().mode !== "enforce" || !this.isBuildTask(task) || this.isPii(task)) return undefined;
4861
+ return buildEntryDiagnostic(task, planGap);
4862
+ }
4863
+
4864
+ /** Proposal entry guidance first; otherwise explain an unassigned named owner from its recorded peer stall (#601). */
4844
4865
  namedOwnerNote(task: Task, named: PeerId | undefined, by: PeerId): string | undefined {
4845
4866
  requireLocalTaskPeer(by);
4846
- if (!named || task.owner || task.state !== "proposed") return undefined;
4867
+ if (task.state !== "proposed") return undefined;
4868
+ const entry = this.entryDiagnostic(task);
4869
+ if (entry) return `task #${task.id}: SDLC build entry blocked: ${entry}`;
4870
+ if (!named || task.owner) return undefined;
4847
4871
  const stall = this.d.board.stalls().find(row => row.task === task.id);
4848
4872
  if (!stall) return undefined;
4849
4873
  const code = stall.cause.refusals?.find(row => row.peer === named)?.code ?? (stall.cause.peer === named ? stall.cause.code : undefined);
@@ -4866,6 +4890,330 @@ export class Tasks {
4866
4890
  // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
4867
4891
  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
4892
  }
4893
+ /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
4894
+ private lineageMetadata(text: string): boolean {
4895
+ try {
4896
+ if (!this.nameable(text) || looksSecret(text)) return false;
4897
+ const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []];
4898
+ if (!policy.length) return true;
4899
+ let parsed: unknown;
4900
+ try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof
4901
+ const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : [];
4902
+ // ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained
4903
+ // public metadata can prove it without filesystem discovery on this read path.
4904
+ return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy));
4905
+ } catch { return false; }
4906
+ }
4907
+
4908
+ private lineageVisible(by: PeerId, task: Task): boolean {
4909
+ try {
4910
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.reviewTaskPrivate(task)) return false;
4911
+ if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false;
4912
+ if (this.repositories.cachedScope(task.refs)?.key !== this.repositories.project.key) return false;
4913
+ return by === USER || this.d.bus.isRostered(by) && taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by));
4914
+ } catch { return false; }
4915
+ }
4916
+
4917
+ private lineagePorts(by: PeerId): ExecutionLineageOwnerPorts | undefined {
4918
+ const binding = this.d.executionLineage;
4919
+ if (!binding) return undefined;
4920
+ // Agent-wide roles do not grant diagnostic authority over a hidden or staged source.
4921
+ const diagnostics = by === USER;
4922
+ // ponytail: raw50 event pages cannot prove current field privacy after policy narrowing.
4923
+ // Refuse by policy alone until a privacy-aware page source supplies a complete public projection.
4924
+ let eventProjectionSupported = false;
4925
+ 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 */ }
4926
+ return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey,
4927
+ scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported,
4928
+ task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text),
4929
+ links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created),
4930
+ delivery: binding.readDelivery,
4931
+ attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit),
4932
+ receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) };
4933
+ }
4934
+
4935
+ /** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */
4936
+ executionLineage(by: PeerId, input: unknown): LineageResult {
4937
+ if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" };
4938
+ try {
4939
+ const check = this.requestCheck(by);
4940
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
4941
+ const ports = this.lineagePorts(by);
4942
+ if (!ports) return { state: "unavailable" };
4943
+ let query;
4944
+ try { query = parseOwnerLineageQuery(input); }
4945
+ catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; }
4946
+ const snapshot = executionOwnerSnapshot(ports, query);
4947
+ check();
4948
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
4949
+ if (snapshot.task) {
4950
+ const current = this.d.board.get(snapshot.task.id);
4951
+ if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" };
4952
+ }
4953
+ return readExecutionLineage(snapshot.source, snapshot.query);
4954
+ } catch { return { state: "unavailable" }; }
4955
+ }
4956
+
4957
+ private guidanceRequest(by: PeerId): () => void {
4958
+ if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
4959
+ throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
4960
+ const request = this.requestCheck(by, () => this.studyHold());
4961
+ const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
4962
+ const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = delivery();
4963
+ const check = () => {
4964
+ request();
4965
+ if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by))
4966
+ throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
4967
+ if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
4968
+ || peer.sessionGeneration !== generation || peer.nativeSession !== session || delivery() !== delivered))
4969
+ throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
4970
+ };
4971
+ check(); return check;
4972
+ }
4973
+ private guidanceTask(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, write: boolean): Task {
4974
+ const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId));
4975
+ if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying");
4976
+ if (task.created !== selector.taskCreated || !this.lineageVisible(by, task) || this.reviewObserverTurn(by, task.id))
4977
+ throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying");
4978
+ if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review"
4979
+ || !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by))))
4980
+ throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying");
4981
+ return task;
4982
+ }
4983
+ private guidanceProject(): string {
4984
+ const key = this.d.executionLineage?.projectKey;
4985
+ if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying");
4986
+ return key;
4987
+ }
4988
+ private guidanceRole(task: Task) {
4989
+ let role;
4990
+ try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); }
4991
+ catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); }
4992
+ if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant");
4993
+ return role;
4994
+ }
4995
+ private guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean {
4996
+ const { evidenceRefs, ...text } = record.variant;
4997
+ // Opaque evidence addresses never become filesystem/producer lookup instructions.
4998
+ return this.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.lineageMetadata(JSON.stringify(reference)));
4999
+ }
5000
+ /** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */
5001
+ private guidanceStorage<T>(operation: "read" | "write", action: () => T): T {
5002
+ try { return action(); }
5003
+ catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); }
5004
+ }
5005
+ private guidanceFence(by: PeerId, task: Task): GuidanceWriteFence {
5006
+ return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
5007
+ owner: task.owner, state: task.state, roleId: task.role };
5008
+ }
5009
+ private guidanceFieldAllowed(text: string): boolean {
5010
+ try { return this.nameable(text) && !looksSecret(text) && this.lineageMetadata(JSON.stringify(text)); }
5011
+ catch { return false; }
5012
+ }
5013
+ private guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; }
5014
+ private guidanceExperimentFor(projectKey: string, task: Task, selector: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id"> & { experimentId?: string }): string | undefined {
5015
+ return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined);
5016
+ }
5017
+ private guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; }
5018
+ private guidanceReadFence(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, task: Task, check: () => void): Task {
5019
+ check(); const current = this.guidanceTask(by, selector, false);
5020
+ if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role])
5021
+ !== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed");
5022
+ return current;
5023
+ }
5024
+ private guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] {
5025
+ const ports = this.lineagePorts(by), projectKey = this.guidanceProject();
5026
+ return records.map(record => record.variant.evidenceRefs.map(reference => {
5027
+ let known = false;
5028
+ if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) {
5029
+ const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } });
5030
+ known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference));
5031
+ }
5032
+ return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const };
5033
+ }));
5034
+ }
5035
+ private guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord {
5036
+ return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId),
5037
+ status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record),
5038
+ rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence };
5039
+ }
5040
+ private guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt {
5041
+ const value = saved.record.variant;
5042
+ return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already };
5043
+ }
5044
+ /** Immutable declarations only. Neither creation nor readback changes effective role guidance. */
5045
+ async guidanceVariantCreate(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
5046
+ const check = this.guidanceRequest(by);
5047
+ let variant: Readonly<GuidanceVariantV1>;
5048
+ try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); }
5049
+ return this.studyWrite(async () => {
5050
+ const context = () => {
5051
+ check();
5052
+ const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task);
5053
+ if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying");
5054
+ const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId));
5055
+ const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId));
5056
+ try {
5057
+ validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
5058
+ experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline,
5059
+ currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) });
5060
+ } catch (error) {
5061
+ 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");
5062
+ throw new Error("guidance validation is unavailable; inspect the task experiment before retrying");
5063
+ }
5064
+ return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) };
5065
+ };
5066
+ const before = context();
5067
+ if (this.screenOn() && (await this.screenCall(JSON.stringify(variant))).label !== "clear")
5068
+ throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available");
5069
+ const current = context();
5070
+ if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying");
5071
+ check();
5072
+ const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task)));
5073
+ return this.guidanceReceipt(saved);
5074
+ });
5075
+ }
5076
+ async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
5077
+ const check = this.guidanceRequest(by);
5078
+ let selector: GuidanceSelector | GuidanceIdSelector;
5079
+ try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } }
5080
+ catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); }
5081
+ return this.studyWrite(async () => {
5082
+ check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject();
5083
+ if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing");
5084
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5085
+ 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);
5086
+ if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing");
5087
+ check();
5088
+ const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task)));
5089
+ return this.guidanceReceipt(saved);
5090
+ });
5091
+ }
5092
+ private guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean {
5093
+ try {
5094
+ if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false;
5095
+ const value = record.variant, role = this.guidanceRole(task);
5096
+ return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer
5097
+ && value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true);
5098
+ } catch { return false; }
5099
+ }
5100
+ /** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */
5101
+ guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult {
5102
+ try {
5103
+ const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input);
5104
+ check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject();
5105
+ const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5106
+ if (experimentId === undefined) return { state: "unavailable" };
5107
+ const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId);
5108
+ const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records;
5109
+ if (!selected.length) return { state: "unavailable" };
5110
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check);
5111
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
5112
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId);
5113
+ const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh;
5114
+ if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" };
5115
+ const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) };
5116
+ check();
5117
+ return result;
5118
+ } catch { return { state: "unavailable" }; }
5119
+ }
5120
+ /** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */
5121
+ guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult {
5122
+ try {
5123
+ const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input);
5124
+ const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector);
5125
+ if (experimentId === undefined) return { state: "unavailable" };
5126
+ const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id);
5127
+ if (!record) return { state: "unavailable" };
5128
+ const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check);
5129
+ if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
5130
+ const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id);
5131
+ if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" };
5132
+ const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!),
5133
+ sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() });
5134
+ check(); return result;
5135
+ } catch { return { state: "unavailable" }; }
5136
+ }
5137
+ /** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */
5138
+ guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult {
5139
+ try {
5140
+ const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject();
5141
+ const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" };
5142
+ const context = { ...this.guidanceCurrent(task), projectKey, actor: by };
5143
+ const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : "";
5144
+ if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" };
5145
+ const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS);
5146
+ const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check);
5147
+ const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after);
5148
+ if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" };
5149
+ const records: GuidancePublicRecord[] = [];
5150
+ for (const [index, record] of selected.entries()) {
5151
+ const candidate = this.guidanceProjection(by, current, record, evidence[index]!);
5152
+ const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) };
5153
+ if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break;
5154
+ records.push(candidate);
5155
+ }
5156
+ const truncated = records.length < page.length;
5157
+ if (truncated && !records.length) return { state: "unavailable" };
5158
+ const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated,
5159
+ ...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) });
5160
+ check(); return result;
5161
+ } catch { return { state: "unavailable" }; }
5162
+ }
5163
+
5164
+ /** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */
5165
+ guidanceVariantApplicable(by: PeerId, input: unknown): boolean {
5166
+ try {
5167
+ const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected);
5168
+ return read.state === "available" && read.record.applicable;
5169
+ } catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ }
5170
+ try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; }
5171
+ const read = this.guidanceVariantRead(by, input);
5172
+ return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable;
5173
+ }
5174
+
5175
+ /** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */
5176
+ async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> {
5177
+ 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");
5178
+ const check = this.requestCheck(by, () => this.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined);
5179
+ let proposed: ExecutionLinkInput;
5180
+ try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); }
5181
+ return this.studyWrite(async () => {
5182
+ const context = () => {
5183
+ check();
5184
+ const ports = this.lineagePorts(by);
5185
+ if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying");
5186
+ let task: Task;
5187
+ try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); }
5188
+ const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined;
5189
+ 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");
5190
+ 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");
5191
+ 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");
5192
+ const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created);
5193
+ const scope = { id: task.id, created: task.created };
5194
+ const origin = executionOwnerSnapshot(ports, { root: from, task: scope });
5195
+ 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");
5196
+ if (proposed.reference.tool === "ahub") {
5197
+ const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope });
5198
+ 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");
5199
+ }
5200
+ const metadata = JSON.stringify([from, proposed.reference]);
5201
+ if (!this.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying");
5202
+ return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) };
5203
+ };
5204
+ const before = context();
5205
+ if (this.screenOn()) {
5206
+ const result = await this.screenCall(before.metadata);
5207
+ if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available");
5208
+ }
5209
+ check();
5210
+ const current = context();
5211
+ if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying");
5212
+ const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() });
5213
+ return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already };
5214
+ });
5215
+ }
5216
+
4869
5217
  /** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */
4870
5218
  async evidenceRecord(by: PeerId, input: unknown): Promise<EvidenceReceipt> {
4871
5219
  try { requireLocalTaskPeer(by); }
@@ -5668,7 +6016,9 @@ export class Tasks {
5668
6016
  */
5669
6017
  async recordSdlc(by: PeerId, id: unknown, input: unknown): Promise<Task> {
5670
6018
  const requestCheck = this.requestCheck(by);
5671
- if (!input || typeof input !== "object" || Array.isArray(input) || !("deliverables" in input)) return this.recordLifecycle(by, id, input);
6019
+ const spec = await this.specStageGate(by, id, input);
6020
+ requestCheck();
6021
+ if (!input || typeof input !== "object" || Array.isArray(input) || !("deliverables" in input)) return this.recordLifecycle(by, id, input, undefined, spec?.carry);
5672
6022
  const { deliverables, ...receipt } = input as Record<string, unknown>;
5673
6023
  const task = this.need(id, false, true);
5674
6024
  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 +6027,12 @@ export class Tasks {
5677
6027
  requestCheck();
5678
6028
  const current = this.need(id, false, true);
5679
6029
  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);
6030
+ return this.recordLifecycle(by, id, receipt, records, spec?.carry);
5681
6031
  }
5682
6032
 
5683
- recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[]): Task {
6033
+ recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object): Task {
5684
6034
  requireLocalTaskPeer(by);
5685
- const task = this.need(id, false, true);
6035
+ const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
5686
6036
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
5687
6037
  const next = sdlcReceipt(input, task.sdlc, config, VERSION);
5688
6038
  const definition = stageDefinition(config, next.stage);
@@ -5714,7 +6064,7 @@ export class Tasks {
5714
6064
  if (next.reviewedHead !== undefined && (next.reviewedHead !== task.sdlc?.reviewedHead || (suppliedHead && artifactChanged))) this.mine(task, by, "reviewer", true);
5715
6065
  const departure = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture;
5716
6066
  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 } : {}) });
6067
+ return this.commitSpecCarry(by, specCarry, task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) });
5718
6068
  }
5719
6069
 
5720
6070
  /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */
@@ -5770,6 +6120,68 @@ export class Tasks {
5770
6120
  }
5771
6121
  return report;
5772
6122
  }
6123
+ /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
6124
+ async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
6125
+ const check = this.requestCheck(by, fence);
6126
+ const authority = () => {
6127
+ check();
6128
+ if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
6129
+ throw new PreEffectToolRefusal("only the person or the current configured conductor may adopt a merge; ask the person to run ahub sdlc adopt-merge");
6130
+ 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");
6131
+ if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError)
6132
+ throw new PreEffectToolRefusal("hub recovery, storage or task writes are held; clear the hold before retrying ahub sdlc adopt-merge");
6133
+ };
6134
+ authority();
6135
+ 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>");
6136
+ 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>");
6137
+ const task = this.d.board.get(id as number);
6138
+ if (!task) throw new PreEffectToolRefusal("merge adoption task does not exist; inspect ahub task list and choose the task to adopt");
6139
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), head = this.reviewHead(task);
6140
+ const identity = (row: Task) => JSON.stringify([row, this.isPii(row)]);
6141
+ const before = identity(task), policy = JSON.stringify(config);
6142
+ const current = () => {
6143
+ authority();
6144
+ const now = this.d.board.get(task.id);
6145
+ if (!now || identity(now) !== before || JSON.stringify(this.d.sdlc?.config() ?? sdlcConfig(undefined)) !== policy)
6146
+ throw new PreEffectToolRefusal("task, privacy or SDLC policy changed during merge adoption; reload the task and retry ahub sdlc adopt-merge");
6147
+ 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");
6148
+ return now;
6149
+ };
6150
+ current();
6151
+ 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`);
6152
+ 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`);
6153
+ 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`);
6154
+ 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");
6155
+ const scope = this.repositories.scope(task.refs), repo = task.sdlc?.repo ?? (scope.key.startsWith("repo:") ? scope.key.slice("repo:".length) : undefined);
6156
+ if (!repo || this.repositories.scope({ repo }).key !== scope.key || task.sdlc?.pr !== undefined && task.sdlc.pr !== pr)
6157
+ 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");
6158
+ const receipt = { ...task.sdlc, stage: lifecycleStage(config, "merge"), repo, pr: pr as number, head };
6159
+ const important = () => findingTally(findingsForHead(this.reviewFindingSets(current()), head)).openImportant > 0;
6160
+ if (important()) throw new PreEffectToolRefusal("open Important finding blocks merge adoption; resolve the finding and record its disposition before retrying ahub sdlc adopt-merge");
6161
+ const deadline = performance.now() + 20_000;
6162
+ const run: SdlcGh = async (args, timeout, cwd, cap) => {
6163
+ current();
6164
+ const remaining = deadline - performance.now();
6165
+ if (remaining <= 0) throw new PreEffectToolRefusal("merge evidence read timed out; restore GitHub access and retry ahub sdlc adopt-merge");
6166
+ const result = await (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? 10_000, remaining), cwd, cap);
6167
+ current();
6168
+ return result;
6169
+ };
6170
+ const evidence = await readAdoptMergeEvidence(receipt, run);
6171
+ const now = current();
6172
+ const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
6173
+ if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
6174
+ const capacity = this.capacityBefore(now);
6175
+ current(); // No await between the last authority/privacy/flow check and the sole approval write.
6176
+ const next = this.d.board.adoptMerge(now.id, by, receipt, head, now.history.length, HOST_MERGE_ADOPTION);
6177
+ this.cohorts.closed(next.id);
6178
+ this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id);
6179
+ this.writePlannerNotices(next, capacity, true);
6180
+ this.releaseNotice(`task #${next.id}: merged outside the hub; approved`);
6181
+ await this.releaseDependents(next);
6182
+ return { task: next.id, state: "approved" };
6183
+ }
6184
+
5773
6185
  private readonly mergesInFlight = new Set<number>();
5774
6186
  /** #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
6187
  private mergeAuthority(by: PeerId): boolean {
@@ -6072,7 +6484,8 @@ export class Tasks {
6072
6484
  }
6073
6485
  private specText(task: Task, state: Exclude<SpecState, "current">, verb: "blocked" | "advice"): string {
6074
6486
  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";
6487
+ const diagnostic = verb === "blocked" && !this.isPii(task) && state === "missing" ? buildEntryDiagnostic(task) : undefined;
6488
+ 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
6489
  return `task #${task.id}: SDLC build entry ${verb}: ${why}`;
6077
6490
  }
6078
6491
 
@@ -6088,19 +6501,137 @@ export class Tasks {
6088
6501
  return this.d.board.update(task.id, USER, "spec accepted", { sdlc: next }, `issue #${next.issue}, body last edited ${spec.edit.lastEditedAt ?? "never"}`);
6089
6502
  }
6090
6503
 
6504
+ private readonly specCarries = new WeakMap<object, SpecCarryProof>();
6505
+ /** Opaque host proof only: a virtual receipt never changes the stored row or its flow. */
6506
+ private stagedSpec(by: PeerId, task: Task, token?: object, preEffect = true): Task {
6507
+ if (!token) return task;
6508
+ try {
6509
+ const proof = this.specCarries.get(token);
6510
+ if (!proof || proof.by !== by || proof.task !== task.id) throw new Error("unknown or consumed host spec carry proof");
6511
+ if (!proof.current() || task.sdlc?.repo !== proof.commit.acceptance.repo || task.sdlc.issue !== proof.commit.acceptance.issue
6512
+ || this.specAcceptanceScope(task.refs) !== proof.scope || !this.specAcceptancePublic(task)) throw new Error("task or source changed during staged spec admission");
6513
+ return { ...task, sdlc: { ...task.sdlc, acceptance: proof.commit.acceptance } };
6514
+ } catch (error) {
6515
+ const message = error instanceof Error ? error.message : "staged spec admission changed";
6516
+ throw new (preEffect ? PreEffectToolRefusal : Error)(`${message}; inspect the current task and held deliveries before repeating this action`);
6517
+ }
6518
+ }
6519
+ /** Called only at an admitted outer write; later failures keep ordinary post-effect error semantics. */
6520
+ private commitSpecCarry(caller: PeerId, token: object | undefined, ...args: Parameters<Board["update"]>): Task {
6521
+ if (!token) return this.d.board.update(...args);
6522
+ const [id, by, event, patch, note, extra, revision, codeSymbolsAuthority, adoptionAuthority] = args;
6523
+ const stored = this.need(id, false, false);
6524
+ 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");
6525
+ this.stagedSpec(caller, { ...stored, ...patch, refs: { ...stored.refs, ...patch.refs } }, token, false);
6526
+ const proof = this.specCarries.get(token)!;
6527
+ const next = this.d.board.updateWithSpecAcceptance(proof.commit, HOST_SPEC_ACCEPTANCE_CARRY,
6528
+ id, by, event, patch, note, extra, revision ?? stored.history.length, codeSymbolsAuthority, adoptionAuthority);
6529
+ this.specCarries.delete(token);
6530
+ return next;
6531
+ }
6532
+
6533
+ /** No cold repository probes or source task hydration participate in consent authority. */
6534
+ private specAcceptanceScope(refs: TaskRefs): string | undefined {
6535
+ return this.repositories.cachedScope(refs)?.key
6536
+ ?? (!refs.repo && !(refs.paths ?? []).some(isAbsolute) ? this.repositories.project.key : undefined);
6537
+ }
6538
+ private specAcceptancePublic(task: Pick<Task, "refs" | "signals">): boolean {
6539
+ try {
6540
+ const normalized = cleanRefs(task.refs);
6541
+ if (["repo", "branch", "commit"].some(key => task.refs[key as keyof TaskRefs] !== normalized[key as keyof TaskRefs])
6542
+ || JSON.stringify(task.refs.paths ?? []) !== JSON.stringify(normalized.paths ?? [])) return false;
6543
+ return !task.signals.includes("pii") && !task.signals.includes("pii_path")
6544
+ && this.publicMetadataText(JSON.stringify(task.refs)) === true
6545
+ && !(task.refs.paths ?? []).some(path => this.reviewPathPrivate(path));
6546
+ } catch { return false; }
6547
+ }
6548
+ /** Carry uses the existing owner/reviewer/stage-planner authority, without admitting a stage write. */
6549
+ private specAcceptanceActor(by: PeerId, task: Task, receipt = task.sdlc, stageInput?: Record<string, unknown>): boolean {
6550
+ if (by === USER) return true;
6551
+ if (!this.d.bus.isRostered(by)) return false;
6552
+ let role = by === task.owner ? ownerRoleOfClass(task.class) : undefined;
6553
+ if (stageInput) {
6554
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), definition = receipt && stageDefinition(config, receipt.stage);
6555
+ const planners = this.taskPlanner(task), planner = planners.includes(by);
6556
+ const plannerStage = Object.keys(stageInput).every(key => ["stage", "repo", "issue"].includes(key))
6557
+ && (definition?.actor === "planner" || definition?.actor === "owner/planner") && planner;
6558
+ if (by !== task.owner && by !== task.reviewer && !plannerStage) return false;
6559
+ if (config.mode === "enforce" && config.definitions) {
6560
+ const actor = definition?.actor;
6561
+ const acts = actor === "owner" ? by === task.owner : actor === "reviewer" ? by === task.reviewer
6562
+ : actor === "planner" ? planner : actor === "owner/planner" && (by === task.owner || planner);
6563
+ if (!acts) return false;
6564
+ }
6565
+ role ??= by === task.reviewer ? "reviewer" : "planner";
6566
+ }
6567
+ return !!role && (!this.d.roles || this.d.roles[by]?.includes(role) === true);
6568
+ }
6569
+ /** One strict host observation serves both the carry decision and the ordinary spec verdict. */
6570
+ private async readSpecAcceptance(by: PeerId, task: Task, receipt = task.sdlc, allowCarry = true, stageInput?: Record<string, unknown>): Promise<SpecGateRead> {
6571
+ const unchanged: SpecGateRead = { task };
6572
+ const accepted = receipt?.acceptance;
6573
+ if (accepted) return { ...unchanged, edit: !this.isPii(task) ? await readSpecEdit(accepted.repo, accepted.issue, this.d.sdlc?.gh) : undefined };
6574
+ if (!allowCarry || !receipt?.repo || !receipt.issue || receipt.repo !== task.sdlc?.repo || receipt.issue !== task.sdlc?.issue) return unchanged;
6575
+ const check = this.requestCheck(by), scope = this.specAcceptanceScope(task.refs);
6576
+ const policy = () => {
6577
+ const routing = this.d.routing();
6578
+ return JSON.stringify([this.d.roles, this.d.deny, this.d.piiPaths, routing.constraints, routing.signals.pii_patterns, this.d.sdlc?.config()]);
6579
+ };
6580
+ const actorPublic = () => !this.d.privateTurn?.(by) && this.specAcceptanceActor(by, task, receipt, stageInput);
6581
+ if (!scope || isClosedTaskState(task.state) || !actorPublic() || !this.specAcceptancePublic(task)
6582
+ || this.publicMetadataText(receipt.repo) !== true) return unchanged;
6583
+ const eligible = (source: SpecAcceptanceCandidate) => {
6584
+ const consent = storedSpecAcceptance(source.acceptance);
6585
+ return !source.withheld && source.id < task.id && localSupersedingTask(source.supersededBy) === task.id
6586
+ && this.specAcceptancePublic(source) && this.specAcceptanceScope(source.refs) === scope
6587
+ && typeof source.repo === "string" && source.repo.toLowerCase() === receipt.repo!.toLowerCase() && source.issue === receipt.issue
6588
+ && !!consent && consent.repo.toLowerCase() === receipt.repo!.toLowerCase() && consent.issue === receipt.issue;
6589
+ };
6590
+ const snapshot = (value: Task) => JSON.stringify([value.created, value.state, value.class, value.reviewer, value.planner, value.refs, value.signals]);
6591
+ const beforeTask = snapshot(task), sources = this.d.board.specAcceptanceCandidates(task.id), beforePolicy = policy();
6592
+ const planners = JSON.stringify(this.taskPlanner(task));
6593
+ if (!sources.complete || !sources.rows.some(eligible)) return unchanged;
6594
+ const edit = await readSpecEdit(receipt.repo, receipt.issue, this.d.sdlc?.gh);
6595
+ check();
6596
+ if (this.specMoved(task)) return unchanged;
6597
+ const currentTask = this.need(task.id, false, true);
6598
+ if (snapshot(currentTask) !== beforeTask || !actorPublic() || !this.specAcceptancePublic(currentTask) || policy() !== beforePolicy
6599
+ || JSON.stringify(this.taskPlanner(task)) !== planners || this.specAcceptanceScope(task.refs) !== scope) return unchanged;
6600
+ const current = this.d.board.specAcceptanceCandidates(task.id);
6601
+ if (!current.complete || JSON.stringify(current.rows) !== JSON.stringify(sources.rows)) return unchanged;
6602
+ for (const source of current.rows) {
6603
+ if (!eligible(source)) continue;
6604
+ const acceptance = carriedSpecAcceptance(storedSpecAcceptance(source.acceptance)!, { repo: receipt.repo, issue: receipt.issue }, edit);
6605
+ if (!acceptance) continue;
6606
+ Object.freeze(acceptance); // The virtual receipt must not expose mutable host-consent fields.
6607
+ const token = Object.freeze({});
6608
+ this.specCarries.set(token, { by, task: task.id, scope, commit: { source: source.id, cancellationRevision: source.cancellationRevision, acceptance }, current: () => {
6609
+ check();
6610
+ const now = this.need(task.id, false, true), latest = this.d.board.specAcceptanceCandidates(task.id);
6611
+ const donor = latest.rows.find(row => row.id === source.id);
6612
+ return now.history.length === task.history.length && now.owner === task.owner && JSON.stringify(now.sdlc) === JSON.stringify(task.sdlc)
6613
+ && snapshot(now) === beforeTask && actorPublic() && policy() === beforePolicy
6614
+ && JSON.stringify(this.taskPlanner(now)) === planners && latest.complete && JSON.stringify(latest.rows) === JSON.stringify(sources.rows)
6615
+ && !!donor && eligible(donor);
6616
+ } });
6617
+ return { task: { ...task, sdlc: { ...task.sdlc!, acceptance } }, edit, carry: token };
6618
+ }
6619
+ return { ...unchanged, edit };
6620
+ }
6621
+
6091
6622
  /** 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> {
6623
+ async specGate(by: PeerId, id: unknown, prospectiveRefs?: TaskRefs): Promise<SpecGateRead | undefined> {
6093
6624
  requireLocalTaskPeer(by);
6094
6625
  const task = this.need(id, false, true);
6095
6626
  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;
6627
+ const result = await this.readSpecAcceptance(by, task, task.sdlc, !prospectiveRefs || this.specAcceptanceScope(prospectiveRefs) === this.specAcceptanceScope(task.refs));
6098
6628
  if (this.specMoved(task)) return;
6099
- this.specVerdict(task, task.sdlc?.issue ? specState(task.sdlc, edit) : "missing");
6629
+ this.specVerdict(result.task, result.task.sdlc?.issue ? specState(result.task.sdlc, result.edit) : "missing");
6630
+ return result.carry ? result : undefined;
6100
6631
  }
6101
6632
 
6102
6633
  /** #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> {
6634
+ async specStageGate(by: PeerId, id: unknown, input: unknown): Promise<SpecGateRead | undefined> {
6104
6635
  requireLocalTaskPeer(by);
6105
6636
  const task = this.need(id, false, true), config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6106
6637
  if (config.mode === "off" || by === USER || !input || typeof input !== "object" || !("stage" in input)) return;
@@ -6110,10 +6641,11 @@ export class Tasks {
6110
6641
  try { next = sdlcReceipt(lifecycleInput, task.sdlc, config, VERSION); } catch { return; } // recordLifecycle reports an invalid receipt
6111
6642
  const definition = stageDefinition(config, next.stage);
6112
6643
  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;
6644
+ const result = await this.readSpecAcceptance(by, task, next, true, lifecycleInput);
6115
6645
  if (this.specMoved(task)) return;
6116
- this.specVerdict(task, next.issue ? specState(next, edit) : "missing");
6646
+ if (result.carry) next.acceptance = result.task.sdlc!.acceptance;
6647
+ this.specVerdict(result.task, next.issue ? specState(next, result.edit) : "missing");
6648
+ return result.carry ? result : undefined;
6117
6649
  }
6118
6650
 
6119
6651
  /**
@@ -6222,30 +6754,31 @@ export class Tasks {
6222
6754
  this.validatePlanSources(proposedPlan && Object.keys(proposedPlan).length ? proposedPlan : task.plan);
6223
6755
  this.acceptanceCapacity(task, 0, "check"); // #1080: an urgent task may still take unaccepted offers; `accept` does that, after its gates
6224
6756
  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;
6757
+ let draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task;
6226
6758
  this.warmRepository(draft);
6227
6759
  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);
6760
+ const spec = await this.specGate(by, id, draft.refs);
6761
+ if (spec?.carry) draft = metadata ? { ...spec.task, refs: { ...spec.task.refs, ...metadata } } : spec.task;
6762
+ await this.planEntryGate(by, draft, spec?.carry);
6230
6763
  requestCheck();
6231
6764
  const current = this.need(id, false, true);
6232
6765
  this.mine(current, by, "owner", true);
6233
6766
  if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during build admission");
6234
6767
  this.reviewedAdmissions.set(current.id, { flow: current.history.length, owner: current.owner });
6235
- try { return this.accept(by, id, plan, metadata); }
6768
+ try { return this.accept(by, id, plan, metadata, spec?.carry); }
6236
6769
  finally { this.reviewedAdmissions.delete(current.id); }
6237
6770
  }
6238
6771
 
6239
6772
  /** 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> {
6773
+ private async planEntryGate(by: PeerId, task: Task, specCarry?: object): Promise<void> {
6241
6774
  const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode;
6242
6775
  if (mode === "off" || !this.isBuildTask(task)) return;
6243
6776
  const gap = await this.planReviewGap(task);
6244
6777
  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);
6778
+ const current = this.stagedSpec(by, this.need(task.id, false, true), specCarry);
6246
6779
  this.mine(current, by, "owner", true);
6247
6780
  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);
6781
+ if (gap && mode === "enforce") throw new PreEffectToolRefusal(this.entryDiagnostic(current, gap) ?? gap);
6249
6782
  if (gap) this.releaseNotice(`task ${this.publicTitle(current)}: ${gap}`);
6250
6783
  }
6251
6784
 
@@ -6344,10 +6877,10 @@ export class Tasks {
6344
6877
  * With a plan, the owners of overlapping tasks get it as a ride-along line, and an overlap only the plan reveals is
6345
6878
  * announced like one found at assignment (issue #31).
6346
6879
  */
6347
- accept(by: PeerId, id: unknown, plan?: unknown, refs?: unknown): Task {
6880
+ accept(by: PeerId, id: unknown, plan?: unknown, refs?: unknown, specCarry?: object): Task {
6348
6881
  requireLocalTaskPeer(by);
6349
6882
  const metadata = acceptRefs(refs);
6350
- const task = this.need(id, false, true);
6883
+ const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
6351
6884
  this.mine(task, by, "owner", true);
6352
6885
  this.ready(task, true);
6353
6886
  // #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 +6922,7 @@ export class Tasks {
6389
6922
  let next: Task;
6390
6923
  try {
6391
6924
  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
6925
+ 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
6926
  } catch (error) { undoWorktree?.(); throw error; }
6394
6927
  this.captureOwnerAcceptance(next);
6395
6928
  this.d.notify(`task ${this.publicTitle(next)} accepted by ${by}`);
@@ -6714,7 +7247,9 @@ export class Tasks {
6714
7247
  const refileHead: RefileHeadGuard | undefined = !submittedCommit && initial.sdlc?.repo && initial.sdlc.pr && this.hasReviewHistory(initial) && !this.isPii(initial)
6715
7248
  ? { recorded: this.ownerReviewHead(initial) } : undefined;
6716
7249
  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; };
7250
+ let specCarry: object | undefined;
7251
+ const write = (...args: Parameters<Board["update"]>) => { const result = this.commitSpecCarry(by, specCarry, ...args); specCarry = undefined; return result; };
7252
+ 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
7253
  if (initial.state === "approved") { await this.unmergedForReopen(initial, valid); valid(); }
6719
7254
  // #509a: a bad claim (a claimed hash, an outside or denied path, a missing file) is refused before any effect, with nothing recorded.
6720
7255
  const claims = deliverables === undefined ? undefined : this.deliverableClaims(deliverables, valid());
@@ -6726,18 +7261,18 @@ export class Tasks {
6726
7261
  task = valid();
6727
7262
  // #481 S1: done without a separate accept starts build work too: the same live spec check as accept, before any write.
6728
7263
  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);
7264
+ const admission = await this.specGate(by, task.id, { ...task.refs, ...cleanRefs(refs) });
7265
+ specCarry = admission?.carry;
7266
+ await this.planEntryGate(by, admission?.carry ? admission.task : task, specCarry);
6732
7267
  task = valid();
6733
7268
  }
6734
7269
  // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them.
6735
7270
  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);
7271
+ const current = () => this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry);
6737
7272
  task = current();
6738
7273
  let reviewEvidence: PrEvidence | undefined;
6739
7274
  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;
7275
+ 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
7276
  task = current();
6742
7277
  if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") {
6743
7278
  const currentHead = await this.currentPrHeadForReview(task, current);
@@ -6765,11 +7300,11 @@ export class Tasks {
6765
7300
  const ig = cohort!.integration;
6766
7301
  if (ig?.task === task.id && ig.offer) this.d.ackFacts?.(task.owner!, ig.offer); // this call is the proof the request arrived
6767
7302
  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));
7303
+ if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
6769
7304
  if (r.action === "unresolved") {
6770
7305
  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);
7306
+ task = this.withLink(write(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
7307
+ } else if (r.integrated) task = this.withLink(write(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
6773
7308
  } else if (cohort?.held.size && !this.isPii(task)) {
6774
7309
  // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in
6775
7310
  // for it (issue #107, AC4).
@@ -6777,7 +7312,7 @@ export class Tasks {
6777
7312
  if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`);
6778
7313
  else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`);
6779
7314
  }
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
7315
+ 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
7316
  const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined;
6782
7317
  if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn);
6783
7318
  // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next.
@@ -6789,7 +7324,7 @@ export class Tasks {
6789
7324
  const storedRefs = { ...task.refs, ...checkedRefs };
6790
7325
  this.warmRepository({ ...task, refs: { ...task.refs, ...checkedRefs } });
6791
7326
  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);
7327
+ 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
7328
  if (refresh) { this.ciWatchers.cancel(pending.id); this.heldReviews.delete(pending.id); }
6794
7329
  this.releaseNotice(`task ${this.publicTitle(pending)} done by ${by}; its check is queued or running: ${command}`);
6795
7330
  const seen = { events: pending.history.length, owner: pending.owner };
@@ -7146,7 +7681,7 @@ export class Tasks {
7146
7681
  };
7147
7682
  const evidence: ReviewReadiness = this.isPii(task)
7148
7683
  ? { 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"] };
7684
+ : 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
7685
  const currentHead = refileHead && !evidence.head && task.sdlc ? await readSdlcPrHead(task.sdlc, read) : evidence.head;
7151
7686
  const current = guard();
7152
7687
  const admitted: ReviewReadiness = quietDrift ? { ready: false, blockers: ["review readiness unknown: task changed during readback"] } : evidence;
@@ -8228,6 +8763,24 @@ export class Tasks {
8228
8763
  }
8229
8764
  }
8230
8765
 
8766
+ /**
8767
+ * #1221 T2: one accepted supervision proposal's notice, to the owners of the tasks it names. A delivery through the
8768
+ * same owner path `tell` uses, never a board write: the task's own result stays in its history and a later review of
8769
+ * that result stays a separate record. The person is not told here (the console owns that), and a private task is
8770
+ * refused, so nothing about one leaves the machine.
8771
+ */
8772
+ supervisionNotice(task: number, other: number | undefined, body: string): { sent: PeerId[]; refused?: string } {
8773
+ const primary = this.d.board.get(task);
8774
+ if (!primary) return { sent: [], refused: `task #${task} is not on the board` };
8775
+ if (this.isPii(primary)) return { sent: [], refused: "a private task is never proposed on" };
8776
+ const partner = other === undefined ? undefined : this.d.board.get(other);
8777
+ if (other !== undefined && partner && this.isPii(partner)) return { sent: [], refused: "a private task is never proposed on" };
8778
+ const targets = [...new Set([primary.owner, partner?.owner].filter((peer): peer is PeerId => !!peer && peer !== USER && peer !== HUB))];
8779
+ if (!targets.length) return { sent: [], refused: "the task has no owner to tell" };
8780
+ for (const peer of targets) this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", priority: "important", refs: { task: String(task), taskRecipient: "owner" } }));
8781
+ return { sent: targets };
8782
+ }
8783
+
8231
8784
  private tell(task: Task, body: string, pii: boolean, audience: "owner" | "withdrawal" = "owner", reviewObserverExcluded = false): void {
8232
8785
  if (!task.owner || task.owner === USER) return;
8233
8786
  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 } : {}) }));