@staix/agent-hub 0.37.0 → 0.39.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 (164) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/guidance-probes.md +365 -0
  15. package/docs/design/task-board.md +151 -5
  16. package/docs/dogfood.md +22 -7
  17. package/docs/events.md +3 -3
  18. package/docs/memory.md +5 -5
  19. package/docs/operations.md +189 -32
  20. package/docs/profiles.md +101 -9
  21. package/docs/quickstart.md +38 -4
  22. package/docs/research.md +6 -3
  23. package/docs/roles.md +52 -0
  24. package/docs/sdlc.md +187 -1
  25. package/docs/security.md +56 -13
  26. package/docs/text-projection.md +1 -0
  27. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  29. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  30. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  31. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  32. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  33. package/docs/verified.json +48 -25
  34. package/package.json +3 -3
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +1989 -474
  37. package/plugins/agent-hub/server.js +2056 -512
  38. package/src/adapters/acp-model-policy.ts +1 -1
  39. package/src/adapters/acp-session-model.ts +35 -0
  40. package/src/adapters/acp.ts +14 -0
  41. package/src/adapters/agy/definition.ts +1 -1
  42. package/src/adapters/agy/hooks.ts +7 -0
  43. package/src/adapters/claude-channel.ts +3 -2
  44. package/src/adapters/claude-implementer.ts +8 -0
  45. package/src/adapters/claude-print-child.ts +26 -2
  46. package/src/adapters/claude-print.ts +4 -0
  47. package/src/adapters/codex-appserver.ts +90 -16
  48. package/src/adapters/codex-review-isolation.ts +2 -0
  49. package/src/adapters/compat.ts +4 -4
  50. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  51. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  52. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  53. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  55. package/src/adapters/definitions/native-quota.ts +122 -0
  56. package/src/adapters/definitions/native-recovery.ts +3 -0
  57. package/src/adapters/definitions/qwen.ts +1 -1
  58. package/src/adapters/kimi-review.ts +23 -0
  59. package/src/adapters/kimi-wire-usage.ts +39 -16
  60. package/src/adapters/local-probe.ts +65 -6
  61. package/src/adapters/local-worker.ts +6 -3
  62. package/src/adapters/pi-state-model.ts +12 -0
  63. package/src/adapters/pi.ts +22 -0
  64. package/src/adapters/print-result-model.ts +24 -0
  65. package/src/adapters/registry-types.ts +10 -1
  66. package/src/adapters/registry.ts +19 -2
  67. package/src/adapters/reviewer-print.ts +130 -15
  68. package/src/adapters/role-eligibility.ts +99 -0
  69. package/src/adapters/same-directory.ts +16 -0
  70. package/src/cli/agy-mcp.ts +18 -7
  71. package/src/cli/console-state.ts +3 -1
  72. package/src/cli/free-text.ts +20 -0
  73. package/src/cli/handoff-args.ts +1 -1
  74. package/src/cli/help.ts +61 -6
  75. package/src/cli/identity.ts +10 -4
  76. package/src/cli/init-prompt.ts +31 -2
  77. package/src/cli/init-roles.ts +156 -0
  78. package/src/cli/init-settings.ts +24 -2
  79. package/src/cli/init.ts +141 -17
  80. package/src/cli/main.ts +216 -56
  81. package/src/cli/model.ts +1 -1
  82. package/src/cli/output.ts +64 -5
  83. package/src/cli/preview.ts +1 -1
  84. package/src/cli/recovery-launch.ts +114 -0
  85. package/src/cli/recovery-package.ts +14 -7
  86. package/src/cli/recovery-version-preflight.ts +104 -0
  87. package/src/cli/role-doctor.ts +39 -0
  88. package/src/cli/sdlc-output.ts +66 -1
  89. package/src/cli/study-output.ts +54 -0
  90. package/src/cli/study.ts +14 -1
  91. package/src/cli/terminal-recovery.ts +14 -0
  92. package/src/cli/upgrade-presentation.ts +4 -0
  93. package/src/cli/upgrade-restore-state.ts +12 -3
  94. package/src/cli/upgrade-runtime.ts +41 -3
  95. package/src/cli/upgrade.ts +8 -4
  96. package/src/hub/advisor-survey.ts +139 -0
  97. package/src/hub/audit-source.ts +66 -0
  98. package/src/hub/board.ts +479 -14
  99. package/src/hub/budget.ts +54 -4
  100. package/src/hub/bus.ts +2 -2
  101. package/src/hub/conductor.ts +14 -8
  102. package/src/hub/config-apply.ts +2 -1
  103. package/src/hub/config-edit-host.ts +77 -5
  104. package/src/hub/considered-findings.ts +47 -0
  105. package/src/hub/control-client.ts +1 -1
  106. package/src/hub/daemon.ts +373 -66
  107. package/src/hub/deliverable-files.ts +17 -1
  108. package/src/hub/dogfood-profile.ts +3 -2
  109. package/src/hub/envelope.ts +6 -1
  110. package/src/hub/events.ts +23 -2
  111. package/src/hub/folder-trigger.ts +11 -4
  112. package/src/hub/guidance-probe-store.ts +345 -14
  113. package/src/hub/guidance-probes.ts +338 -4
  114. package/src/hub/hub-tools.ts +88 -16
  115. package/src/hub/kimi-usage.ts +34 -2
  116. package/src/hub/lifecycle-schema.ts +3 -3
  117. package/src/hub/manager.ts +24 -1
  118. package/src/hub/memory-profile.ts +9 -1
  119. package/src/hub/memory-sync-state.ts +1 -0
  120. package/src/hub/model-overrides.ts +2 -1
  121. package/src/hub/no-writes.ts +2 -0
  122. package/src/hub/operational-authority.ts +8 -2
  123. package/src/hub/operational-view.ts +5 -1
  124. package/src/hub/peers.ts +2 -0
  125. package/src/hub/person-command.ts +25 -0
  126. package/src/hub/plan-conformance.ts +20 -2
  127. package/src/hub/quota-account.ts +34 -0
  128. package/src/hub/recovery-policy.ts +18 -4
  129. package/src/hub/research-evidence.ts +51 -3
  130. package/src/hub/research.ts +77 -13
  131. package/src/hub/restart.ts +14 -0
  132. package/src/hub/review-budget.ts +88 -0
  133. package/src/hub/review-findings.ts +93 -12
  134. package/src/hub/reviewer-pool-config.ts +6 -2
  135. package/src/hub/reviewer-pool.ts +39 -6
  136. package/src/hub/routing.ts +7 -3
  137. package/src/hub/sdlc-merge.ts +1 -1
  138. package/src/hub/sdlc-queue.ts +14 -4
  139. package/src/hub/sdlc-release.ts +1 -1
  140. package/src/hub/sdlc.ts +10 -6
  141. package/src/hub/security-audit.ts +178 -0
  142. package/src/hub/security-pass.ts +115 -0
  143. package/src/hub/settings.ts +11 -5
  144. package/src/hub/source-read.ts +80 -2
  145. package/src/hub/sources.ts +57 -9
  146. package/src/hub/startup-event-seeds.ts +5 -3
  147. package/src/hub/startup-timing.ts +1 -0
  148. package/src/hub/supervision.ts +3 -2
  149. package/src/hub/synthesis-readiness.ts +279 -0
  150. package/src/hub/tasks.ts +1131 -72
  151. package/src/hub/text-projection.ts +11 -1
  152. package/src/local/probe-types.ts +2 -0
  153. package/src/local/probe-workspace.ts +191 -2
  154. package/src/memory/capture.ts +2 -1
  155. package/src/ui/guidance-panel.ts +34 -2
  156. package/src/ui/guidance-view.ts +33 -0
  157. package/src/ui/index.html +3 -0
  158. package/src/ui/office-model.ts +11 -3
  159. package/src/ui/office-space.ts +50 -30
  160. package/src/ui/plugin.ts +31 -14
  161. package/templates/AGENTS.block.md +14 -14
  162. package/templates/profiles/general.json +1 -1
  163. package/templates/profiles/research.json +1 -1
  164. package/templates/profiles/writing.json +1 -1
package/src/hub/tasks.ts CHANGED
@@ -3,8 +3,9 @@ import { pathCandidates } from "@staix/agent-mem";
3
3
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
4
4
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
5
5
  import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, guidanceProbeCanonical, guidanceProbeManifestKey,
6
- parseGuidanceProbeRegistration, probeHash, probeSha256, probeInteger, probeSessionGeneration,
6
+ parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration,
7
7
  type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
8
+ type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState,
8
9
  type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
9
10
  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
11
  import { buildEntryDiagnostic } from "./build-entry.ts";
@@ -14,7 +15,8 @@ import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts
14
15
  import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
15
16
  import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
16
17
  import type { JournalDelivery } from "./delivery-journal.ts";
17
- import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt } from "./research-evidence.ts";
18
+ import { checkSynthesis, inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisCurrentClaim, type SynthesisArtifactSnapshot, type SynthesisReadiness } from "./synthesis-readiness.ts";
19
+ import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts";
18
20
  import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
19
21
  import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
20
22
  import type { ReviewMaterialBatch } from "./review-material.ts";
@@ -22,6 +24,8 @@ import { isReviewObserverExcluded } from "./memory-policy.ts";
22
24
  import { renderFindingAnchor } from "./review-brief.ts";
23
25
  import { reviewCommentFields, reviewCommentNumber, reviewCommentId, reviewCommentIds, reviewCommentHead, reviewCommentBody, reviewCommentAuthor, privateReviewAnchor, reviewThreadProjection, renderReviewComment, REVIEW_PACKAGE_BYTES, REVIEW_COMMENT_LIMIT,
24
26
  type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentMutation, type ReviewCommentCounts, type ReviewCommentView } from "./review-comments.ts";
27
+ import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts";
28
+ import type { SourceMeta } from "./sources.ts";
25
29
  import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts";
26
30
  import { approvalBinding, approvalText } from "./task-approval.ts";
27
31
  import type { InvocationRow } from "./invocations.ts";
@@ -39,11 +43,20 @@ import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampa
39
43
  import type { ResearchCampaignRecord, ResearchUnitBinding, PreparedResearchUnit, HandoffOutboundRow } from "./board.ts";
40
44
  import { HANDOFF_EVENTS, HANDOFF_KEY, HandoffRefusal, handoffRequestDigest, duplicateIssueTasks, duplicateRefusalText, followBackLine, handoffEventFor, parseHandoff, type HandoffEvent } from "./handoff.ts";
41
45
  import { taskShellBindingValid, type TaskShellBinding } from "./task-shell-command.ts";
46
+ import type { ReviewBudgetSnapshot, ReviewGate, ReviewUnknownQuota } from "./review-budget.ts";
42
47
  import { buildTaskCodeSymbols, publicTaskCodeSymbols, taskCodeSymbolsDisjoint, HOST_CODE_SYMBOLS } from "./task-code-symbols.ts";
43
48
  import { normalizePlanSymbol, symbolsOverlap } from "./symbol-normalizer.ts";
44
49
  import { publicTestIntegrity, readTestIntegrity, testIntegrityBlockers, type TestIntegrity } from "./test-integrity.ts";
45
50
  import { evalAdvice, evalGapBlockers, evalRequiredChecks, readEvalFor } from "./eval-gate.ts";
46
- import { completePlanInventory, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
51
+ import { parseSecurityPass, securityPassBlockers, securityPassView, securityRequestLine, SECURITY_CHECKLIST, type SecurityPassRecord, type SecurityPassView } from "./security-pass.ts";
52
+ import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditFinding, type AuditProfile, type AuditSummary, type CarryLookup, type PublicAuditFinding } from "./security-audit.ts";
53
+ import type { AuditSource } from "./audit-source.ts";
54
+ import { SURVEY_FOCUS, SURVEY_LIMITS, parseSurveyFindings, parseSurveyVetDecisions, publicSurveyFinding, surveyBrief, surveyFindingKey, surveyObject, surveyPath, surveyInputAt, surveyInputProblem,
55
+ type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
56
+ import { consideredFindingMatch, parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
57
+ import type { StoredSurvey, SurveyPreparedCard } from "./board.ts";
58
+ import { matchConfigPath } from "./eval-gate.ts";
59
+ import { completePlanInventory, planDrift, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
47
60
  import { RELEASE_TRAIN_HISTORY_LIMIT, releaseTrainData, releaseTrainReadiness, releaseMetrics } from "./sdlc-release.ts";
48
61
  import { cleanCostPlan, costMetrics, CostScopeError, type CostPlan, type ReviewCost } from "./cost-governance.ts";
49
62
  import { qualifiedTitleRepos, siblingTitleRefs, specRefs } from "./spec-read.ts";
@@ -62,7 +75,7 @@ import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue
62
75
  import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
63
76
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
64
77
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
65
- import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
78
+ import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
66
79
  import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
67
80
  import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
68
81
  import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
@@ -85,7 +98,7 @@ const learnVerdict = (card: Pick<Task, "state" | "history">): "accepted" | "reje
85
98
  return closed.note?.startsWith(LEARN_ACCEPTED) ? "accepted" : closed.note?.startsWith(LEARN_REJECTED) ? "rejected" : undefined;
86
99
  };
87
100
  import { approvedDeliverables, latestDeliverables, parseDeliverableClaims, publicDeliverables, type DeliverableRecord, type DeliverableStatus } from "./deliverables.ts";
88
- import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, type DeliverablePorts } from "./deliverable-files.ts";
101
+ import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, readGuardedDeliverable, guardedDeliverableCurrent, type GuardedDeliverableRead, type DeliverablePorts } from "./deliverable-files.ts";
89
102
  import { isAbsolute, relative, resolve } from "node:path";
90
103
  import type { Briefs, NativeItem } from "../memory/brief.ts";
91
104
  import type { MemoryClient } from "../memory/client.ts";
@@ -120,6 +133,9 @@ function requireLocalTaskPeer(peer: unknown): void {
120
133
  }
121
134
 
122
135
  export type TaskAssignmentRole = "owner" | "reviewer" | "planner";
136
+ export type EvidenceReadOrigins = { state: "known"; group: string; groups: number } | { state: "unknown" };
137
+ export type EvidenceReadResult = EvidenceReceipt & ({ status: "private" | "stale" | "unavailable" | "withdrawn" }
138
+ | { status: "resolved"; link: EvidenceLinkV1; excerpt: string; excerptSha256: string; locator: EvidenceLinkV1["locator"]; origins: EvidenceReadOrigins });
123
139
 
124
140
  /** What `hub_remember` carries (#802: one shape for `remember` and `rememberOutcome`). */
125
141
  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 }
@@ -138,6 +154,14 @@ interface PreparedSpecInspection {
138
154
 
139
155
  export interface ReleaseWindow { at: number; host: boolean; quota: boolean; idle: boolean; reasons: string[]; current?: () => boolean; close?: () => Promise<void>; }
140
156
 
157
+ /** #1403 A4: the audit as a caller reads it. `withheld` counts open important findings whose text the view leaves out. */
158
+ export interface AuditView extends AuditSummary {
159
+ units: { unit: string; state: string; prior?: { audit: number; head: string }; reason?: string }[];
160
+ items: PublicAuditFinding[];
161
+ withheld?: number;
162
+ /** Findings in this report that were already verified or rejected, so the hub left them as decided. */
163
+ notUpdated?: string[];
164
+ }
141
165
  export interface TasksDeps {
142
166
  /** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */
143
167
  guidanceProbes?: {
@@ -205,6 +229,8 @@ export interface TasksDeps {
205
229
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
206
230
  /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
207
231
  sdlc?: { config: () => SdlcConfig; gh?: SdlcGh; reportPolicy?: (head: string, repo: string) => ReleaseReportPolicy | undefined };
232
+ /** #1403 A4: read-only git for the security audit (the checkout's head and changed paths); absent means the audit commands are unavailable. */
233
+ auditSource?: AuditSource;
208
234
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
209
235
  ciWatch?: { deadlineMs?: number; pollMs?: number };
210
236
  /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
@@ -216,6 +242,8 @@ export interface TasksDeps {
216
242
  candidateScreen?: MemoryScreen;
217
243
  /** Authenticated live turn context, not a model-supplied flag. */
218
244
  privateTurn?: (peer: PeerId) => boolean;
245
+ /** Host-only observer provenance, separate from task/turn authority. Sample before any operation await. */
246
+ observerExcludedTurn?: (peer: PeerId) => boolean;
219
247
  /** #223 R4: the hub's reading of a verdict's context (`fresh` only for a reviewer session started for this review). */
220
248
  reviewContext?: (by: PeerId, task: number) => "fresh" | "continuing" | undefined;
221
249
  /** Current-turn input carries review material or anchored findings; it expires on the next ordinary input. */
@@ -264,6 +292,12 @@ export interface TasksDeps {
264
292
  /** Host-scoped immutable-head/material batch; supports host-staged completion refs/sdlc, never client-staged Task objects. The shared reader owns file authorization and budgets. */
265
293
  reviewMaterials?: (task: Task, requests: readonly { path: string; side?: "base" | "head" }[]) => Promise<ReviewMaterialBatch>;
266
294
  studySource?: (id: string) => { id: string; sha256: string; private: boolean } | undefined;
295
+ /** Host-owned screened snapshot read, never a public source-read excerpt reconstructed as a projection. */
296
+ /** Opaque host-only current raw/projection/converter token, never client evidence. */
297
+ evidenceSourceSnapshotKey?: (link: EvidenceLinkV1) => string | undefined;
298
+ evidenceSourceRead?: (by: PeerId, link: EvidenceLinkV1, current: () => boolean, mode?: { privacyReadOnly: true }) => Promise<EvidenceSourceRead>;
299
+ /** Fresh registered metadata for bounded, ephemeral origin grouping; no converter or model call. */
300
+ evidenceSourceMeta?: (id: string) => SourceMeta | undefined;
267
301
  /** Host-only fixture clock; never read from model input or project configuration. */
268
302
  studyNow?: () => number;
269
303
  /** Host-only reader for this project's check-runner receipts; record inputs never supply a receipt. */
@@ -271,7 +305,8 @@ export interface TasksDeps {
271
305
  /** Fresh trusted machine-local runner registrations. A source-trust failure refuses new receipts. */
272
306
  researchRunners?: () => unknown;
273
307
  /** Reviewer choice from recorded review outcomes (issue #35); off unless the project config turns it on. */
274
- review?: { adaptive: boolean; min_reviews: number; pool?: readonly string[]; rerotate?: boolean; same_family?: "fallback" | "never" };
308
+ review?: { adaptive: boolean; min_reviews: number; pool?: readonly string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number };
309
+ reviewBudget?: () => Pick<ReviewBudgetSnapshot, "paused" | "manualPaused">;
275
310
  /** Peers whose recent deliveries all failed, with the reason (issue #89); routing skips them. */
276
311
  capabilities?: () => Record<PeerId, PeerCapabilities>;
277
312
  /** #1115: the hub makes, commits and clears the task worktree of a hub-sandboxed peer. Absent: such a peer keeps the #1081 refusal. */
@@ -441,8 +476,8 @@ function acceptRefs(input: unknown): TaskRefs | undefined {
441
476
  return { repo: text(raw.repo)! };
442
477
  }
443
478
 
444
- /** The same for a plan (issue #31): only its four lists, each of short strings. */
445
- function cleanPlan(input: unknown, profile: ProfileSelection = "dev"): TaskPlan {
479
+ /** Normalize plan intent at the boundary; lifecycle-off ignores the additive cold-plan fields. */
480
+ function cleanPlan(input: unknown, profile: ProfileSelection = "dev", lifecycle = false): TaskPlan {
446
481
  const r = fields(input);
447
482
  const evidence: Pick<TaskPlan, "proof" | "risks"> = {};
448
483
  for (const key of ["proof", "risks"] as const) {
@@ -452,13 +487,42 @@ function cleanPlan(input: unknown, profile: ProfileSelection = "dev"): TaskPlan
452
487
  const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean);
453
488
  if (items.length) evidence[key] = items;
454
489
  }
490
+ const intent: import("./board.ts").ColdPlanIntent = {};
491
+ if (lifecycle) {
492
+ if (r.base !== undefined) {
493
+ if (typeof r.base !== "string" || !/^[a-f0-9]{40}$/.test(r.base)) throw new PreEffectToolRefusal("plan.base: expected a full lowercase commit SHA");
494
+ intent.base = r.base;
495
+ }
496
+ for (const key of ["out_of_scope", "stop_if"] as const) {
497
+ const value = r[key];
498
+ if (value === undefined) continue;
499
+ if (!Array.isArray(value) || value.length > 32 || value.some(item => typeof item !== "string" || item.length > 512)) throw new PreEffectToolRefusal(`plan.${key}: expected at most 32 strings of at most 512 characters`);
500
+ const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean);
501
+ if (items.length) intent[key] = [...new Set(key === "out_of_scope" ? items.map(normPath) : items)];
502
+ }
503
+ if (r.steps !== undefined) {
504
+ if (!Array.isArray(r.steps) || r.steps.length > 32) throw new PreEffectToolRefusal("plan.steps: expected at most 32 steps");
505
+ intent.steps = r.steps.map(raw => {
506
+ const row = fields(raw);
507
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(row).some(key => key !== "description" && key !== "verify")
508
+ || typeof row.description !== "string" || !row.description.trim() || row.description.length > 512
509
+ || row.verify !== undefined && (typeof row.verify !== "string" || !row.verify.trim() || row.verify.length > 512)) throw new PreEffectToolRefusal("plan.steps: each step needs a bounded description and optional verify command and expected result");
510
+ return { description: row.description.replace(/\s+/g, " ").trim(), ...(typeof row.verify === "string" ? { verify: row.verify.replace(/\s+/g, " ").trim() } : {}) };
511
+ });
512
+ }
513
+ }
455
514
  let scope: CostPlan;
456
515
  try { scope = cleanCostPlan(r); } catch (error) { throw new PreEffectToolRefusal(error instanceof CostScopeError ? error.message : "invalid review or CI cost scope"); }
457
- return { ...Object.fromEntries((profileData(profile).plan_keys as (keyof TaskPlan)[]).map((k) => [k, k === "paths" ? [...new Set(textList(r[k]).map(normPath))] : textList(r[k])] as const).filter(([, v]) => v.length)), ...evidence, ...scope };
516
+ return { ...Object.fromEntries((profileData(profile).plan_keys as (keyof TaskPlan)[]).map((k) => [k, k === "paths" ? [...new Set(textList(r[k]).map(normPath))] : textList(r[k])] as const).filter(([, v]) => v.length)), ...evidence, ...scope, ...intent };
458
517
  }
459
518
 
460
519
  /** A plan as one line for other owners; the whole plan is on the board. */
461
- const planText = (plan: TaskPlan = {}) => ALL_PLAN_KEYS.filter((k) => plan[k]?.length).map((k) => `${k.replace("_", " ")}: ${plan[k]!.join("; ")}`).join(" | ");
520
+ const planText = (plan: TaskPlan = {}) => [
521
+ ...ALL_PLAN_KEYS.filter((k) => plan[k]?.length).map((k) => `${k.replace("_", " ")}: ${plan[k]!.join("; ")}`),
522
+ ...(plan.base ? [`base: ${plan.base}`] : []),
523
+ ...(["out_of_scope", "stop_if"] as const).filter(key => plan[key]?.length).map(key => `${key}: ${plan[key]!.join("; ")}`),
524
+ ...(plan.steps?.length ? [`steps: ${plan.steps.map(step => `${step.description}${step.verify ? `; verify: ${step.verify}` : ""}`).join("; ")}`] : []),
525
+ ].join(" | ");
462
526
  /** What the PII screen reads of a task (#198): the text the patterns are checked against. */
463
527
  const screenText = (t: { title: string; detail: string; plan?: TaskPlan; external?: Task["external"] }) => [t.title, t.detail, planText(t.plan), t.external?.repo, t.external?.url].filter(value => value !== undefined).join("\n");
464
528
  /** Re-screens of one task whose verdict was unknown, per hub run (#198). */
@@ -835,7 +899,7 @@ export class Tasks {
835
899
 
836
900
  private signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing = this.d.routing()) {
837
901
  const signals = detectSignals(task, routing, this.d.cwd);
838
- const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)];
902
+ const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.out_of_scope ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)];
839
903
  if (paths.some(path => matchesPolicy(this.d.cwd, path, this.d.piiPaths ?? [], true))) {
840
904
  if (!signals.includes("pii")) signals.push("pii");
841
905
  signals.push("pii_path");
@@ -856,6 +920,9 @@ export class Tasks {
856
920
  const check = () => { const reason = authority?.() ?? fence?.(); if (reason) throw new PreEffectToolRefusal(reason); };
857
921
  check(); return check;
858
922
  }
923
+ private observerExcluded(by: PeerId): boolean {
924
+ try { return this.d.observerExcludedTurn?.(by) === true; } catch { return true; }
925
+ }
859
926
 
860
927
  private async screenCall(text: string): Promise<PiiVerdict> {
861
928
  return (await this.d.piiScreen?.(text).catch(() => undefined)) ?? { label: "unknown", miss: "failed", ms: 0 };
@@ -1199,7 +1266,8 @@ export class Tasks {
1199
1266
  .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Review finding key: ")) ?? []));
1200
1267
  const created: number[] = [];
1201
1268
  // No await separates the durable dedupe read from creation; concurrent verdicts see the first proposal.
1202
- for (const item of items.filter(item => item.disposition !== "false_positive")) {
1269
+ // #1436: a positional id (N1, F5, nit-1) is review-local, so it never counts toward a cross-task recurrence; a semantic id does.
1270
+ for (const item of items.filter(item => item.disposition !== "false_positive" && !positionalFindingId(item.id))) {
1203
1271
  const same = (finding: ReviewFinding) => finding.id === item.id && finding.pass === item.pass;
1204
1272
  const holders = rows.filter(row => {
1205
1273
  if (this.isPii(row)) return false;
@@ -1224,6 +1292,37 @@ export class Tasks {
1224
1292
  for (const id of created) this.releaseNotice(`task #${id}: recurring review finding amendment proposed in the backlog`);
1225
1293
  }
1226
1294
 
1295
+ /**
1296
+ * #1403 A1, B4: on approval, one backlog card per open Important finding that did not block it. A `needs_validation` security finding gets one read-only `triage` card that names its blocker
1297
+ * (the missing fact); a `pre_existing` one gets one `plan` card. Marker-deduplicated like the recurring-finding cards and held to the same privacy gates. The card carries the task id, the
1298
+ * finding id and pass, and for a hypothesis its blocker: never the boundary fields or the path, which stay on the task's own review history (the repository is public, and the hub opens no issue).
1299
+ */
1300
+ private proposeFindingFollowUps(task: Task, by: PeerId, withheld: boolean): void {
1301
+ if (withheld || this.isPii(task) || this.d.privateTurn?.(by)) return;
1302
+ const { validation, preExisting } = findingFollowUps(this.reviewFindingSets(task));
1303
+ if (!validation.length && !preExisting.length) return;
1304
+ const visible = (item: ReviewFinding) => !task.history.some(entry => entry.withheld && entry.reviewFindings?.items.some(value => value.id === item.id)) && this.findingTextAllowed(task, [item]);
1305
+ const keys = new Set(this.d.board.list().filter(row => (row.class === "plan" || row.class === "triage") && row.history[0]?.by === HUB)
1306
+ .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Finding follow-up key: ")) ?? []));
1307
+ const created: number[] = [];
1308
+ // No await separates the durable dedupe read from creation; a repeated approval sees the first card.
1309
+ for (const [kind, items] of [["validation", validation], ["pre-existing", preExisting]] as const) for (const item of items.filter(visible)) {
1310
+ const key = `Finding follow-up key: ${task.id}:${item.pass}:${item.id}:${kind}`;
1311
+ if (keys.has(key)) continue;
1312
+ const ref = `${item.pass}:${item.id}`;
1313
+ const title = kind === "validation" ? `Validate security finding ${ref} from task #${task.id}: read-only triage` : `Pre-existing finding ${ref} from task #${task.id}: plan a fix`;
1314
+ const detail = kind === "validation"
1315
+ ? `${key}\nTask #${task.id} was approved with the important security finding ${ref} still a hypothesis. Blocker, the fact that settles it: ${item.blocker ?? "not recorded"}\nRead-only triage: settle that fact from source or a sandboxed check and report whether the finding is confirmed or false. Do not edit files, branches or the board, and open no issue: the person decides where a security finding is published. Details are in ahub task show ${task.id}.`
1316
+ : `${key}\nTask #${task.id} was approved with the important finding ${ref} marked pre_existing: that change did not introduce it, so it did not block the approval. Backlog card for the planner: decide whether and how to plan a fix. Details are in ahub task show ${task.id}.`;
1317
+ const draft = { title, detail, refs: {} };
1318
+ const signals = this.signalsFor(draft);
1319
+ if (this.isPii({ signals }) || !this.candidateTextAllowed(`${title}\n${detail}`)) continue;
1320
+ const proposal = this.d.board.propose(HUB, { ...draft, class: kind === "validation" ? "triage" : "plan", backlog: true, signals });
1321
+ this.incomingBacklog.add(proposal.id); keys.add(key); created.push(proposal.id);
1322
+ }
1323
+ for (const id of created) this.releaseNotice(`task #${id}: finding follow-up proposed in the backlog`);
1324
+ }
1325
+
1227
1326
  private publicClaimBindings(task: Task): ReturnType<typeof taskClaimIdentity>[] | undefined {
1228
1327
  const claims = task.plan?.claims;
1229
1328
  if (task.profile !== "research" || task.signals.includes("pii") || task.signals.includes("pii_path")
@@ -1275,7 +1374,8 @@ export class Tasks {
1275
1374
  ...(h.deliverables?.length ? { deliverables: publicDeliverables(h.deliverables, this.nameable) } : {}),
1276
1375
  ...(h.reviewBlocked ? { reviewBlocked: true } : {}),
1277
1376
  ...(h.queueReviewHeld ? { queueReviewHeld: true } : {}),
1278
- ...(h.reviewerFailure ? { reviewerFailure: { peer: screenHistoryText(h.reviewerFailure.peer, "reviewer"), cause: h.reviewerFailure.cause, ...(h.reviewerFailure.head ? { head: screenHistoryText(h.reviewerFailure.head, "review head") } : {}) } } : {}),
1377
+ ...(h.reviewerQuotaWait ? { reviewerQuotaWait: { since: h.reviewerQuotaWait.since, deadline: h.reviewerQuotaWait.deadline, resetAt: h.reviewerQuotaWait.resetAt } } : {}),
1378
+ ...(h.reviewerFailure ? { reviewerFailure: { peer: screenHistoryText(h.reviewerFailure.peer, "reviewer"), cause: h.reviewerFailure.cause, ...(h.reviewerFailure.reason === "review time cap" ? { reason: "review time cap" as const } : {}), ...(h.reviewerFailure.head ? { head: screenHistoryText(h.reviewerFailure.head, "review head") } : {}) } } : {}),
1279
1379
  ...(h.planning ? { planning: { revision: h.planning.revision, fields: h.planning.fields, ...(h.planning.split ? { children: h.planning.split.children.map(child => child.id) } : {}) } } : {}),
1280
1380
  ...(h.reason && TASK_MOVE_REASONS.includes(h.reason) ? { reason: h.reason } : {}),
1281
1381
  ...(h.sweep ? { sweep: { kind: h.sweep.kind, activity: h.sweep.activity, step: h.sweep.step, at: h.sweep.at } } : {}),
@@ -1303,6 +1403,8 @@ export class Tasks {
1303
1403
  const held = task.owner ? peerEntry(this.d.held?.(), task.owner) : undefined;
1304
1404
  const holdText = held ? `${task.owner}'s queue is held (${held}); it receives the task once the hold is resolved` : undefined;
1305
1405
  const request = task.history.findLast(entry => ["done", "reviewer changed", "reviewer unavailable"].includes(entry.event));
1406
+ const quotaWait = this.activeReviewerQuotaWait(task);
1407
+ if (quotaWait) return `${base}; waiting for reviewer quota reset until ${new Date(quotaWait.deadline).toISOString()}`;
1306
1408
  const poolBlocked = task.state === "in_review" && task.reviewer === USER && request?.reviewBlocked ? "blocked: no reviewer can run" : undefined;
1307
1409
  const specText = this.specReportText(task, by) || undefined;
1308
1410
  return [base, noReview, poolBlocked, holdText, specText].filter(Boolean).join("; ");
@@ -1695,8 +1797,11 @@ export class Tasks {
1695
1797
  private reviewPoolOptions(task: Task) {
1696
1798
  const head = this.reviewHead(task);
1697
1799
  const round = task.state === "in_review" ? task.history.slice(task.history.findLastIndex(entry => entry.event === "done") + 1) : [];
1698
- const failed = [...new Set(round.flatMap(entry => entry.reviewerFailure?.head === head && entry.reviewerFailure ? [entry.reviewerFailure.peer] : []))];
1699
- return { pool: this.d.review?.pool ?? DEFAULT_REVIEW_POOL, rerotate: this.d.review?.rerotate, failed, required: this.d.review?.pool !== undefined, ...(this.d.review?.same_family === "never" ? { sameFamily: "never" as const } : {}) };
1800
+ const failed = [...new Set(round.flatMap(entry => entry.reviewerFailure?.head === head && entry.reviewerFailure && entry.reviewerFailure.cause !== "quota" ? [entry.reviewerFailure.peer] : []))];
1801
+ const gate = this.d.review?.gate;
1802
+ const budget: ReviewBudgetSnapshot | undefined = gate === undefined ? undefined : { gate, unknownQuota: this.d.review?.unknown_quota, now: this.d.now?.() ?? Date.now(), readings: this.d.quota?.() ?? {}, paused: {}, ...this.d.reviewBudget?.() };
1803
+ const wait = this.priorReviewerQuotaWait(task), now = this.d.now?.() ?? Date.now();
1804
+ return { waitForReset: !wait || now < wait.deadline, pool: this.d.review?.pool ?? DEFAULT_REVIEW_POOL, rerotate: this.d.review?.rerotate, failed, required: this.d.review?.pool !== undefined, ...(budget ? { budget } : {}), ...(this.d.review?.same_family === "never" ? { sameFamily: "never" as const } : {}) };
1700
1805
  }
1701
1806
 
1702
1807
  private manuallyNamedReviewer(task: Task): boolean {
@@ -1725,7 +1830,12 @@ export class Tasks {
1725
1830
  const queueReviewHeld = task !== undefined && !this.isPii(task) && assignment?.reviewer === USER && assignment.reviewBlocked === true
1726
1831
  && assignment.refusals?.some(row => row.role === "reviewer" && isQueuePressureCode(row.code));
1727
1832
  const queueReviewBinding = task ? this.queueReviewBinding(task) : undefined;
1728
- return { ...(family ? { reviewerFamily: family } : {}), ...(reason ? { reviewerReason: reason } : {}), ...(assignment?.reviewBlocked ? { reviewBlocked: true } : {}), ...(queueReviewHeld ? { queueReviewHeld: true as const, ...(queueReviewBinding !== undefined ? { queueReviewBinding } : {}) } : {}) };
1833
+ const quota = choice?.quotaWait;
1834
+ const now = this.d.now?.() ?? Date.now(), prior = task ? this.priorReviewerQuotaWait(task) : undefined;
1835
+ const reviewerQuotaWait = quota && task && !this.isPii(task) && task.state === "in_review"
1836
+ ? { created: task.created, binding: this.queueReviewBinding(task), since: prior?.since ?? now,
1837
+ deadline: prior?.deadline ?? Math.floor(now + this.sweepConfig.review_min * 60_000), resetAt: quota.resetsAt } : undefined;
1838
+ return { ...(reviewerQuotaWait ? { reviewerQuotaWait } : {}), ...(family ? { reviewerFamily: family } : {}), ...(reason ? { reviewerReason: reason } : {}), ...(assignment?.reviewBlocked ? { reviewBlocked: true } : {}), ...(queueReviewHeld ? { queueReviewHeld: true as const, ...(queueReviewBinding !== undefined ? { queueReviewBinding } : {}) } : {}) };
1729
1839
  }
1730
1840
 
1731
1841
  /**
@@ -2816,7 +2926,7 @@ export class Tasks {
2816
2926
  const authored = task.history.findLast(entry => entry.event !== "plan reviewed" && entry.planRevision !== undefined)
2817
2927
  ?? task.history.findLast(entry => entry.event !== "plan reviewed" && (entry.planning?.fields as readonly string[] | undefined)?.includes("plan"));
2818
2928
  if (authored && authored !== task.history[0]) return authored.by;
2819
- return ALL_PLAN_KEYS.some(key => !!task.plan?.[key]?.length) ? authored?.by ?? task.history[0]?.by ?? null : null;
2929
+ return (ALL_PLAN_KEYS.some(key => !!task.plan?.[key]?.length) || !!task.plan?.base || !!task.plan?.out_of_scope?.length || !!task.plan?.stop_if?.length || !!task.plan?.steps?.length) ? authored?.by ?? task.history[0]?.by ?? null : null;
2820
2930
  }
2821
2931
 
2822
2932
  private planReviewAuthority(by: PeerId, task: Task): { planAuthor: PeerId | null; selfReview?: true } {
@@ -3019,13 +3129,27 @@ export class Tasks {
3019
3129
  if (excluded.includes(peer)) continue;
3020
3130
  const queue = this.d.bus.queueSummary(peer), wip = this.wip(peer, task.id), limit = this.wipLimit(peer);
3021
3131
  if (wip >= limit) parts.push(`${peer} WIP full (${wip}/${limit}); no eligible planner WIP capacity`);
3022
- else if (queue.heldBy) parts.push(`${peer} has a held queue (a delivery is held; resolve it with ahub queue list)`);
3132
+ else if (queue.heldBy) parts.push(`${peer} has a held queue (delivery ${queue.heldBy} is held; ahub queue show ${queue.heldBy} prints the full resolve command for the person)`);
3023
3133
  else if (queue.needsReview > 0) parts.push(`${peer} has ${queue.needsReview} delivery(ies) in needs_review`);
3024
3134
  const refusal = queueBackpressure(peer, pressure.queueBackpressure, peerEntry(pressure.queues, peer), pressure.now ?? NaN);
3025
3135
  if (refusal) parts.push(`${peer} ${refusal.reason}`);
3026
3136
  }
3027
3137
  return parts.length ? `no peer can take the planner pull: ${parts.join("; ")}` : "no peer has eligible planner WIP capacity";
3028
3138
  }
3139
+ /**
3140
+ * #1430: the owner refusals routing itself recorded, named the way the reserved branch already names its peer: peer id and
3141
+ * reason only, never task text (#531), so the text is safe for a PII task. Undefined when routing recorded none.
3142
+ */
3143
+ private ownerRefusals(assignment: Assignment): string | undefined {
3144
+ const refused = (assignment.refusals ?? []).filter(row => row.role === "owner");
3145
+ return refused.length ? `routing refusals: ${refused.map(row => `${row.peer}: ${row.reason}`).join("; ")}` : undefined;
3146
+ }
3147
+ /** Keep routing refusals even when other peers also have known WIP or delivery pressure. */
3148
+ private pullRefusal(task: Task, assignment: Assignment): string {
3149
+ const known = this.plannerRefusal(task);
3150
+ const routing = this.ownerRefusals(assignment);
3151
+ return routing ? `${known}; ${routing}` : known;
3152
+ }
3029
3153
  private plannerAssignment(task: Task, reservedOnly = false, routing: Routing = this.d.routing(), queueOverride?: "owner", projectedHealth?: ReturnType<Tasks["health"]>): Assignment {
3030
3154
  const states = this.states();
3031
3155
  const full = this.plannerFull(task);
@@ -3071,8 +3195,13 @@ export class Tasks {
3071
3195
  if (task.reserved && this.excluded(task).includes(task.reserved)) throw new PreEffectToolRefusal(this.plannerRefusal(task));
3072
3196
  const assignment = this.plannerAssignment(task, !!task.reserved, this.d.routing(), queueAssignment ? "owner" : undefined);
3073
3197
  if (!assignment.owner) {
3074
- const refusal = task.reserved ? `reserved peer ${task.reserved} cannot take the planner pull: ${assignment.refusals?.find(row => row.role === "owner" && row.peer === task.reserved)?.reason ?? "not eligible"}; ${this.plannerRefusal(task)}` : this.plannerRefusal(task);
3075
- throw new PreEffectToolRefusal(`${this.hasPersonReservation(task) ? "a person's reservation is retained; " : ""}${refusal}`);
3198
+ // #1430: an unreserved card names what routing refused instead of dropping it, and every pull refusal names the route out.
3199
+ const personReserved = this.hasPersonReservation(task);
3200
+ const nextStep = personReserved ? "ask the person to change the reservation" : "reserve a peer with hub_backlog_plan fields.reserved, then pull again";
3201
+ const refusal = task.reserved
3202
+ ? `reserved peer ${task.reserved} cannot take the planner pull: ${assignment.refusals?.find(row => row.role === "owner" && row.peer === task.reserved)?.reason ?? "not eligible"}; ${this.plannerRefusal(task)}`
3203
+ : this.pullRefusal(task, assignment);
3204
+ throw new PreEffectToolRefusal(`${personReserved ? "a person's reservation is retained; " : ""}${refusal}; ${nextStep}`);
3076
3205
  }
3077
3206
  this.studyDispatchCheck(task, assignment.owner);
3078
3207
  return { task, owner: assignment.owner, assignment };
@@ -3428,7 +3557,7 @@ export class Tasks {
3428
3557
  const direct = afterParts.length ? deps.filter(dep => !parent.deps?.includes(dep)) : deps;
3429
3558
  if (direct.length + afterParts.length > 64) throw new PreEffectToolRefusal("split child dependencies exceed the 64-edge cap");
3430
3559
  while (pending.length) { const dependency = pending.pop()!; if (dependency === id) throw new PreEffectToolRefusal("split dependency reaches its parent"); if (seen.has(dependency)) continue; seen.add(dependency); const task = this.d.board.get(dependency); if (!task) throw new PreEffectToolRefusal("split dependency is missing"); pending.push(...(task.deps ?? [])); }
3431
- const refs = part.refs === undefined ? parent.refs : cleanRefs(part.refs), plan = cleanPlan(part.plan, storedProfile);
3560
+ const refs = part.refs === undefined ? parent.refs : cleanRefs(part.refs), plan = cleanPlan(part.plan, storedProfile, (this.d.sdlc?.config().mode ?? "off") !== "off");
3432
3561
  // #1161: a part's plan sources are registered ids, as at propose and accept (#1144); refused before any screen or board write.
3433
3562
  this.validatePlanSources(plan);
3434
3563
  const draft = { title: part.title.replace(/\s+/g, " ").trim(), detail: part.detail as string | undefined ?? "", class: cls, refs, plan, deps, afterParts: afterParts as number[], ...(parent.role && cls === parent.class ? { role: parent.role } : {}), ...(parent.profile ? { profile: parent.profile, profileClass: given as string, ...(parent.profile === "dev" ? { customProfile: true as const } : {}) } : {}) };
@@ -3695,8 +3824,8 @@ export class Tasks {
3695
3824
  if (["shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("settled release is final");
3696
3825
  if (by !== USER && (release.state === "frozen" || input.state === "frozen" || input.state === "shipped" || input.state === "dropped")) throw new PreEffectToolRefusal("freeze, ship, drop and frozen changes require a person");
3697
3826
  if (input.state === "shipped" && this.d.board.list().some(task => task.release === release.id && !isClosedTaskState(task.state))) throw new PreEffectToolRefusal("every release task must be approved, cancelled, or moved out before ship");
3698
- if (input.state === "active" && (release.train || this.d.sdlc?.config().mode !== undefined && this.d.sdlc.config().mode !== "off" || this.d.board.releases().some(row => row.train && ["active", "frozen"].includes(row.state))) && this.d.board.releases().some(row => row.id !== release.id && ["active", "frozen"].includes(row.state))) throw new PreEffectToolRefusal("one open release train at a time");
3699
- if (input.state === "frozen" && (release.train || this.d.sdlc?.config().mode !== undefined && this.d.sdlc.config().mode !== "off")) throw new PreEffectToolRefusal("use the resource-admitted release cut operation");
3827
+ if (input.state === "active" && (release.train || (this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.board.releases().some(row => row.train && ["active", "frozen"].includes(row.state))) && this.d.board.releases().some(row => row.id !== release.id && ["active", "frozen"].includes(row.state))) throw new PreEffectToolRefusal("one open release train at a time");
3828
+ if (input.state === "frozen" && (release.train || (this.d.sdlc?.config().mode ?? "off") !== "off")) throw new PreEffectToolRefusal("use the resource-admitted release cut operation");
3700
3829
  if (input.state === "shipped" && release.train) {
3701
3830
  if (release.train.history.length >= RELEASE_TRAIN_HISTORY_LIMIT) throw new PreEffectToolRefusal("release train history full; ship needs one history slot, drop this train and create a replacement");
3702
3831
  const readiness = releaseTrainReadiness(release, this.d.board.list());
@@ -3710,9 +3839,9 @@ export class Tasks {
3710
3839
  return updated; // a failed readback may follow a durable release write
3711
3840
  }
3712
3841
 
3713
- async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined): Promise<Task> {
3842
+ async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise<Task> {
3714
3843
  const requestCheck = this.requestCheck(by, fence);
3715
- const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev");
3844
+ const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
3716
3845
  this.validatePlanSources(plan);
3717
3846
  requireLocalTaskPeer(input.owner);
3718
3847
  external = external ? { ...external } : undefined;
@@ -3794,7 +3923,7 @@ export class Tasks {
3794
3923
  this.warmRepository({ refs: draft.refs, plan });
3795
3924
  const repositoryMismatch = !this.isPii({ signals }) && this.repositories.mismatch(draft.refs, plan);
3796
3925
  requestCheck();
3797
- let task = this.d.board.propose(by, { ...draft, plan, ...(external ? { external } : {}), ...(deps.length ? { deps } : {}), ...(reserved ? { reserved } : {}), signals, ...(backlog ? { backlog: true } : {}), ...(input.draft === true ? { draft: true } : {}) });
3926
+ let task = this.d.board.propose(by, { ...draft, plan, ...(external ? { external } : {}), ...(deps.length ? { deps } : {}), ...(reserved ? { reserved } : {}), signals, ...(backlog ? { backlog: true } : {}), ...(input.draft === true ? { draft: true } : {}) }, hostCreatedHook);
3798
3927
  if (repositoryMismatch) this.releaseNotice(`task #${task.id}: refs and plan name different repositories; check refs.repo before editing`);
3799
3928
  if (this.d.coordination) this.coordinationModes.set(task.id, this.d.coordination());
3800
3929
  created?.();
@@ -4329,11 +4458,13 @@ export class Tasks {
4329
4458
  const tagged = assignment.sameFamilyFallback ? `${note}; sameFamilyFallback=true` : note;
4330
4459
  const pool = assignment.reviewSelection, metadata = this.reviewMetadata(assignment);
4331
4460
  const walk = pool?.blocked ? pool.walk.slice(0, 16).map(row => {
4332
- const reason = this.nameable(row.reason) ? Array.from(sanitize(row.reason).replace(/\s+/g, " ")).slice(0, 80).join("") : "[withheld]";
4461
+ const reason = this.nameable(row.reason) ? Array.from(sanitize(row.reason).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]";
4333
4462
  return `${row.id || row.kind}: ${reason}`;
4334
4463
  }).join("; ") + (pool.walk.length > 16 ? `; +${pool.walk.length - 16} walk entries` : "") : "";
4335
- const recorded = pool ? `${tagged}; reviewerFamily=${metadata.reviewerFamily ?? "none"}; reviewerReason=${metadata.reviewerReason ?? pool.blocked}${pool.blocked ? `; pool=${pool.blocked}; walk: ${walk}` : ""}` : tagged;
4336
- return assignment.plannerFallback ? `${recorded}; reviewer=planner (fallback)` : recorded;
4464
+ const admission = pool?.admissionRule ? this.nameable(pool.admissionRule) ? Array.from(sanitize(pool.admissionRule).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]" : undefined;
4465
+ const recorded = pool ? `${tagged}; reviewerFamily=${metadata.reviewerFamily ?? "none"}; reviewerReason=${metadata.reviewerReason ?? pool.blocked}${pool.blocked ? `; pool=${pool.blocked}; walk: ${walk}` : ""}${admission ? `; reviewerQuotaRule=${admission}` : ""}` : tagged;
4466
+ const quota = pool?.quotaWait ? `; quota wait: ${pool.quotaWait.candidates.map(row => `${row.id} ${row.state}, reset ${new Date(row.resetsAt).toISOString()}`).join("; ")}` : "";
4467
+ return assignment.plannerFallback ? `${recorded}; reviewer=planner (fallback)${quota}` : recorded + quota;
4337
4468
  }
4338
4469
 
4339
4470
  /** A later move to another owner means the caller's assignment was superseded, so its success tail is not authoritative. */
@@ -4736,6 +4867,7 @@ export class Tasks {
4736
4867
  this.scheduleQueuePressureRecheck();
4737
4868
  }
4738
4869
  private queueReviewWritten(task: Task): void {
4870
+ this.reviewQuotaTaskChanged(task);
4739
4871
  if (task.state === "in_review" && task.reviewer === USER && task.history.at(-1)?.queueReviewHeld) this.markQueuePressureCandidate();
4740
4872
  }
4741
4873
  private queuePressureAdmitted(): boolean {
@@ -4918,6 +5050,269 @@ export class Tasks {
4918
5050
  // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
4919
5051
  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)));
4920
5052
  }
5053
+ private synthesisTask(by: PeerId, id: unknown): Task {
5054
+ requireLocalTaskPeer(by);
5055
+ if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task");
5056
+ const task = this.studyParent(this.studyNumber(id, "taskId"));
5057
+ if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by)))
5058
+ throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show");
5059
+ return task;
5060
+ }
5061
+
5062
+ private synthesisPrivate(task: Task, by: PeerId): boolean {
5063
+ try { return !!this.d.privateTurn?.(by) || this.isPii(task) || !this.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); }
5064
+ catch { return true; }
5065
+ }
5066
+
5067
+ private synthesisPolicy(task: Task): string {
5068
+ let root: string | undefined;
5069
+ try { root = this.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ }
5070
+ return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]);
5071
+ }
5072
+
5073
+ private synthesisRows(links: readonly EvidenceLinkV1[]) {
5074
+ return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const }));
5075
+ }
5076
+
5077
+ private synthesisInventories(task: Task) {
5078
+ const claims = task.plan?.claims;
5079
+ if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list");
5080
+ return claims.map((_claim, index) => {
5081
+ const identity = taskClaimIdentity(task, index + 1);
5082
+ try {
5083
+ const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128);
5084
+ let contradictionHistory: ReturnType<Board["evidenceContradictionHistory"]> = { ids: [], sources: [], members: [], complete: false };
5085
+ if (inventory.complete) try { contradictionHistory = this.d.board.evidenceContradictionHistory(this.d.project, task.id, identity.claimId, identity.claimRevision, inventory.links); } catch { /* Unknown immutable history cannot erase a contradiction. */ }
5086
+ if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false;
5087
+ return { ...identity, inventory, contradictionHistory };
5088
+ }
5089
+ catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; }
5090
+ });
5091
+ }
5092
+
5093
+ private synthesisSources(links: readonly Pick<EvidenceLinkV1, "sourceId">[]): { private: boolean; key: string; bytes: number } {
5094
+ const meta: unknown[] = [], seen = new Set<string>(); let bytes = 0;
5095
+ for (const link of links) {
5096
+ if (seen.has(link.sourceId)) continue; seen.add(link.sourceId);
5097
+ const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })();
5098
+ if (source?.private || source && !this.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 };
5099
+ meta.push([link.sourceId, source]);
5100
+ if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes;
5101
+ }
5102
+ return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes };
5103
+ }
5104
+
5105
+ /** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */
5106
+ async synthesisEvidence(by: PeerId, input: unknown) {
5107
+ const fields = this.studyFields(input, ["taskId"]), check = this.requestCheck(by, () => this.studyHold());
5108
+ return this.studyWrite(async () => {
5109
+ check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId);
5110
+ if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const };
5111
+ const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]);
5112
+ if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const };
5113
+ const delivered = latestDeliverables(task.history) ?? [];
5114
+ const artifacts = delivered.filter(record => !record.private && record.path && !this.experimentOutputPrivate(task, record.path))
5115
+ .map(({ id, sha256, format }) => ({ id, sha256, format }));
5116
+ check();
5117
+ if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" };
5118
+ return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const,
5119
+ deliverables: artifacts, claims: claims.map(claim => {
5120
+ const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory);
5121
+ return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete,
5122
+ ...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) };
5123
+ }) };
5124
+ });
5125
+ }
5126
+
5127
+ /** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */
5128
+ async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
5129
+ return this.synthesisInspect(by, input);
5130
+ }
5131
+
5132
+ private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
5133
+ private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
5134
+ private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
5135
+ const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest);
5136
+ if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry");
5137
+ const check = this.requestCheck(by, () => this.studyHold());
5138
+ return this.studyWrite(async () => {
5139
+ check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id;
5140
+ if (this.synthesisPrivate(task, by)) return { taskId, status: "private" };
5141
+ const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links);
5142
+ const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))];
5143
+ const sources = this.synthesisSources(privacyLinks);
5144
+ if (sources.private) return { taskId, status: "private" };
5145
+ const activeLinks = allLinks.filter(link => link.status !== "withdrawn");
5146
+ if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" };
5147
+ const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task);
5148
+ // ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later.
5149
+ const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]);
5150
+ const current = () => {
5151
+ try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by)
5152
+ && this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy
5153
+ && JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; }
5154
+ catch { return false; }
5155
+ };
5156
+ const changed = () => {
5157
+ check(); const now = this.synthesisTask(by, taskId);
5158
+ if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const };
5159
+ return { taskId, status: "stale" as const, cause: "context_changed" };
5160
+ };
5161
+ try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; }
5162
+ const sourceKeys = new Map<string, string | undefined>();
5163
+ for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) {
5164
+ let key: string | undefined;
5165
+ try { const meta = this.d.evidenceSourceMeta?.(link.sourceId); key = meta && Number.isSafeInteger(meta.bytes) && meta.bytes >= 0 ? this.d.evidenceSourceSnapshotKey?.(link) : undefined; } catch { /* unavailable source cannot verify provenance */ }
5166
+ sourceKeys.set(link.sourceId, key);
5167
+ }
5168
+ if (!current()) return changed();
5169
+ const reads: { path: string; read: GuardedDeliverableRead }[] = [];
5170
+ const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise<SynthesisArtifactSnapshot | "private"> => {
5171
+ const record = delivered.find(record => record.id === reference.id);
5172
+ if (!record) return { id: reference.id, state: "missing" };
5173
+ if (record.private || !record.path || this.experimentOutputPrivate(task, record.path)) return "private";
5174
+ try {
5175
+ const read = await readGuardedDeliverable(record.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit);
5176
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data);
5177
+ if (!this.publicMetadataText(text)) return "private";
5178
+ reads.push({ path: record.path, read });
5179
+ return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text };
5180
+ } catch { return { id: record.id, state: "unknown" }; }
5181
+ };
5182
+ const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" };
5183
+ if (!current()) return changed();
5184
+ const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" };
5185
+ if (!current()) return changed();
5186
+ const observed: SynthesisCurrentClaim[] = [];
5187
+ for (const claim of before) {
5188
+ const resolutions: NonNullable<NonNullable<SynthesisCurrent["claims"]>[number]["resolutions"]>[number][] = [];
5189
+ for (const link of claim.inventory.links) {
5190
+ if (!current()) return changed();
5191
+ const withdrawn = link.status === "withdrawn";
5192
+ if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; }
5193
+ if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; }
5194
+ let resolution: EvidenceSourceRead["resolution"];
5195
+ try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; }
5196
+ catch { resolution = { status: "unavailable", cause: "source_unavailable" }; }
5197
+ if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" };
5198
+ if (!current()) return changed();
5199
+ resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" });
5200
+ }
5201
+ const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim;
5202
+ const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined;
5203
+ const synthesis = entry?.synthesis;
5204
+ observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision,
5205
+ inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) },
5206
+ contradictionHistory: claim.contradictionHistory,
5207
+ resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } });
5208
+ }
5209
+ const finalCurrent = () => {
5210
+ try {
5211
+ if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false;
5212
+ const fencedSources = new Set<string>();
5213
+ for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) {
5214
+ fencedSources.add(link.sourceId);
5215
+ if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false;
5216
+ }
5217
+ if (reads.some(value => !guardedDeliverableCurrent(value.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false;
5218
+ return this.synthesisSources(privacyLinks).key === sources.key && current();
5219
+ } catch { return false; }
5220
+ };
5221
+ if (!finalCurrent()) return changed();
5222
+ const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed };
5223
+ const report = checkSynthesis(manifest, snapshot);
5224
+ return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report;
5225
+ });
5226
+ }
5227
+
5228
+ /** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */
5229
+ async evidenceRead(by: PeerId, input: unknown): Promise<EvidenceReadResult> {
5230
+ const refuse = () => new PreEffectToolRefusal("evidence read unavailable; use a current evidence id on a research task visible through hub_task_show");
5231
+ try { requireLocalTaskPeer(by); } catch { throw refuse(); }
5232
+ if (this.d.profile !== "research") throw refuse();
5233
+ const check = this.requestCheck(by, () => this.studyHold());
5234
+ let id: string, revision: number | undefined;
5235
+ try {
5236
+ const fields = this.studyFields(input, ["id", "revision"]);
5237
+ if (Object.values(Object.getOwnPropertyDescriptors(input)).some(field => !field.enumerable)
5238
+ || typeof fields.id !== "string" || !/^ev:[a-f0-9]{32}$/.test(fields.id)
5239
+ || fields.revision !== undefined && (typeof fields.revision !== "number" || !Number.isSafeInteger(fields.revision) || fields.revision < 1)) throw refuse();
5240
+ id = fields.id; revision = fields.revision as number | undefined;
5241
+ } catch { throw refuse(); }
5242
+ return this.studyWrite(async () => {
5243
+ check(); const link = this.d.board.evidenceLink(this.d.project, id, revision);
5244
+ if (!link) throw refuse();
5245
+ const receipt = { id: link.id, revision: link.revision, taskId: link.taskId };
5246
+ const stub = (status: "private" | "stale" | "unavailable" | "withdrawn"): EvidenceReadResult => ({ ...receipt, status });
5247
+ const context = () => {
5248
+ check(); let task: Task;
5249
+ try { task = this.studyParent(link.taskId); } catch { throw refuse(); }
5250
+ if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by))) throw refuse();
5251
+ let status: "private" | "stale" | "unavailable" | undefined;
5252
+ try {
5253
+ if (this.d.privateTurn?.(by) || task.signals.includes("pii") || task.signals.includes("pii_path") || this.isPii(task)
5254
+ || this.publicMetadataText(evidenceLinkCanonical(link)) !== true) status = "private";
5255
+ } catch { status = "private"; }
5256
+ if (!status) {
5257
+ try { const identity = taskClaimIdentity(task, Number(link.claimId.split(":").at(-1))); if (identity.claimId !== link.claimId || identity.claimRevision !== link.claimRevision) status = "stale"; }
5258
+ catch { status = "stale"; }
5259
+ }
5260
+ const source = this.studySource(link.sourceId);
5261
+ if (source?.private) status = "private";
5262
+ else if (!status && !source) status = "unavailable";
5263
+ else if (!status && source?.sha256 !== link.rawSha256) status = "stale";
5264
+ return { task, status, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.plan?.claims, source]) };
5265
+ };
5266
+ const before = context(); if (before.status) return stub(before.status);
5267
+ if (link.status === "withdrawn") return stub("withdrawn");
5268
+ if (!this.d.evidenceSourceRead) return stub("unavailable");
5269
+ const current = () => { try { const next = context(); return !next.status && next.key === before.key; } catch { return false; } };
5270
+ // A returned passage can be quoted by any later tool or final answer in this input.
5271
+ // Reuse the host review-input exclusion before crossing the async read boundary.
5272
+ try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return stub("unavailable"); }
5273
+ let read: EvidenceSourceRead;
5274
+ try { read = await this.d.evidenceSourceRead(by, link, current); }
5275
+ catch { check(); const after = context(); return stub(after.status ?? "unavailable"); }
5276
+ check(); const after = context();
5277
+ if (after.status) return stub(after.status);
5278
+ if (after.key !== before.key) return stub("stale");
5279
+ const resolution = read.resolution;
5280
+ if (resolution.status !== "resolved") return stub(resolution.status === "stale" ? "stale" : resolution.cause === "private" ? "private" : "unavailable");
5281
+ const result: EvidenceReadResult = { ...receipt, status: "resolved", link, excerpt: resolution.excerpt, excerptSha256: resolution.excerptSha256, locator: resolution.locator, origins: this.evidenceOrigins(link) };
5282
+ try { if (this.publicMetadataText(JSON.stringify(result)) !== true) return stub("private"); } catch { return stub("private"); }
5283
+ if (!current()) { const final = context(); return stub(final.status ?? "stale"); }
5284
+ return result;
5285
+ });
5286
+ }
5287
+
5288
+ private evidenceOrigins(link: EvidenceLinkV1): EvidenceReadOrigins {
5289
+ const unknown: EvidenceReadOrigins = { state: "unknown" };
5290
+ if (!this.d.evidenceSourceMeta) return unknown;
5291
+ // #931 follow-up: an inventory that changed since the caller read it (a link revision gone between the list and its read) leaves the origins unknown beside the evidence that did resolve;
5292
+ // it never fails the whole read. Any other board error (storage invalid) is not this case and still throws, so a damaged hub.db is not hidden behind an advisory field.
5293
+ let inventory: ReturnType<Board["latestEvidenceLinks"]>;
5294
+ try { inventory = this.d.board.latestEvidenceLinks(this.d.project, link.taskId, link.claimId, link.claimRevision, 128); }
5295
+ catch (error) { if (error instanceof Error && error.message.startsWith("evidence inventory changed")) return unknown; throw error; }
5296
+ if (!inventory.complete || !inventory.links.some(row => row.id === link.id && row.revision === link.revision)) return unknown;
5297
+ try {
5298
+ const groups: Set<string>[] = [], member: { id: string; keys: readonly string[] }[] = [];
5299
+ for (const row of inventory.links.filter(row => row.status !== "withdrawn")) {
5300
+ const meta = this.d.evidenceSourceMeta(row.sourceId);
5301
+ if (!meta || meta.id !== row.sourceId || meta.private || meta.sha256 !== row.rawSha256 || this.publicMetadataText(JSON.stringify(meta)) !== true) return unknown;
5302
+ const keys = evidenceOriginKeys(meta); if (!keys?.length) return unknown;
5303
+ member.push({ id: row.id, keys });
5304
+ const matches = groups.filter(group => keys.some(key => group.has(key)));
5305
+ const merged = new Set([...keys, ...matches.flatMap(group => [...group])]);
5306
+ for (const group of matches) groups.splice(groups.indexOf(group), 1);
5307
+ groups.push(merged);
5308
+ }
5309
+ const selected = member.find(row => row.id === link.id), group = selected && groups.find(group => selected.keys.some(key => group.has(key)));
5310
+ if (!group) return unknown;
5311
+ // Connected registered origins express provenance grouping only, never independent corroboration or source quality.
5312
+ return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length };
5313
+ } catch { return unknown; }
5314
+ }
5315
+
4921
5316
  /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
4922
5317
  private lineageMetadata(text: string): boolean {
4923
5318
  try {
@@ -5129,7 +5524,50 @@ export class Tasks {
5129
5524
  }
5130
5525
  async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
5131
5526
  const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5132
- request.check(); return this.guidanceProbeProjection(state);
5527
+ request.check();
5528
+ const status = this.guidanceProbeProjection(state);
5529
+ // T3 (#1226): the sealed receipts can only make the verdict stricter, never grant one the older expression refused. The reasons and the denominator stay in
5530
+ // the store's private status; public show keeps just this flag. A store that cannot be read is not comparable.
5531
+ if (!status.comparable) return status;
5532
+ let sealedComparable = false;
5533
+ try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ }
5534
+ return sealedComparable ? status : { ...status, comparable: false };
5535
+ }
5536
+ /**
5537
+ * T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches,
5538
+ * reserves, writes and prunes nothing. It carries the status, the outcome denominator and the sealed receipts, each re-verified against its own digest by the
5539
+ * Store, so a tampered row refuses the whole read instead of being skipped. Output names are model-written, so each receipt passes the same screen as any
5540
+ * other public field; one that fails is replaced by its digest alone and the slot says `withheld`. A retained directory is a state, never a path.
5541
+ */
5542
+ async guidanceProbeReceipts(by: PeerId, id: string): Promise<ProbeReceiptExport> {
5543
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5544
+ request.check();
5545
+ const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id };
5546
+ const status = await this.guidanceProbeShow(by, id);
5547
+ let receipts: ProbeReceiptV1[], outcome: ReturnType<GuidanceProbeStore["outcome"]>, retention: Map<string, ProbeRetentionState>;
5548
+ try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); }
5549
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
5550
+ if (!outcome) throw new GuidanceProbeError("storage");
5551
+ request.check();
5552
+ const bySlot = new Map(receipts.map(item => [item.slotId, item]));
5553
+ const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => {
5554
+ const session = state.sessions[index]!, receipt = bySlot.get(slot.id);
5555
+ const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt);
5556
+ return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null,
5557
+ receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" };
5558
+ });
5559
+ // The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused.
5560
+ const comparable = status.comparable && outcome.comparability.comparable;
5561
+ const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots };
5562
+ // What leaves this process is what the consumer's parser will accept: a result that does not round-trip is a storage fault, never a partial answer.
5563
+ const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result)));
5564
+ if (!checked) throw new GuidanceProbeError("storage");
5565
+ return checked;
5566
+ }
5567
+ /** Every free-text name a receipt carries (output paths, exclusions, the served model) must pass the public-field screen; the digest alone is kept otherwise. */
5568
+ private guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean {
5569
+ const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)];
5570
+ return names.every(text => text === "" || this.guidanceFieldAllowed(text));
5133
5571
  }
5134
5572
  async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
5135
5573
  const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
@@ -5180,6 +5618,7 @@ export class Tasks {
5180
5618
  return dependency.fakePorts!.launch(input, effects, signal);
5181
5619
  },
5182
5620
  stop: (input, signal) => dependency.fakePorts!.stop(input, signal),
5621
+ ...(dependency.fakePorts.discardRetained ? { discardRetained: record => dependency.fakePorts!.discardRetained!(record) } : {}),
5183
5622
  };
5184
5623
  let reserved = false, returned = false;
5185
5624
  const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, revalidate: current, now: () => this.d.now?.() ?? Date.now(),
@@ -5530,7 +5969,7 @@ export class Tasks {
5530
5969
  try { requireLocalTaskPeer(by); }
5531
5970
  catch { throw new PreEffectToolRefusal("remote peers cannot record local evidence; ask the current local research task owner to record it"); }
5532
5971
  const requestCheck = this.requestCheck(by, () => this.studyHold());
5533
- let proposed: EvidenceRecordInput;
5972
+ let proposed: ReturnType<typeof parseEvidenceRecord>;
5534
5973
  try { proposed = parseEvidenceRecord(input); }
5535
5974
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid evidence record; check the bounded evidence fields before retrying"); }
5536
5975
  return this.studyWrite(async () => {
@@ -5539,7 +5978,10 @@ export class Tasks {
5539
5978
  let task: Task;
5540
5979
  try { task = this.studyParent(proposed.taskId); }
5541
5980
  catch { throw new PreEffectToolRefusal("evidence task is unavailable or outside this project; refresh ahub task show and select an active research task in this project"); }
5542
- if (task.profile !== "research" || task.state !== "in_progress" || task.owner !== by) throw new PreEffectToolRefusal("evidence recording requires the current in-progress research task owner; accept an assigned research task before recording evidence");
5981
+ const personWithdrawal = by === USER && proposed.status === "withdrawn";
5982
+ if (task.profile === "research" && (task.owner === by || personWithdrawal) && isClosedTaskState(task.state))
5983
+ throw new PreEffectToolRefusal("a closed research task's evidence records are final; open a follow-up research task to correct evidence and create a new manifest binding");
5984
+ if (task.profile !== "research" || task.state !== "in_progress" || !task.owner || task.owner !== by && !personWithdrawal) throw new PreEffectToolRefusal("evidence recording requires the current in-progress research task owner; accept an assigned research task before recording evidence");
5543
5985
  if (this.d.privateTurn?.(by) || this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new PreEffectToolRefusal("private evidence recording is unavailable in T1; use a public research task outside a private turn");
5544
5986
  let identity;
5545
5987
  try { identity = taskClaimIdentity(task, Number(proposed.claimId.split(":").at(-1))); }
@@ -5579,7 +6021,7 @@ export class Tasks {
5579
6021
  if (current.key !== before.key) throw new PreEffectToolRefusal("evidence task, claim or source changed during admission; refresh hub_task_show or ahub task show --json and registered source metadata before retrying");
5580
6022
  requirePublicMetadata();
5581
6023
  requireRevision();
5582
- const saved = this.d.board.recordEvidenceLink(this.d.project, link, { taskFlowRevision: current.task.history.length, taskCreated: current.task.created, owner: by });
6024
+ const saved = this.d.board.recordEvidenceLink(this.d.project, link, { taskFlowRevision: current.task.history.length, taskCreated: current.task.created, owner: current.task.owner!, ...(by === USER ? { personWithdrawal: true as const } : {}) });
5583
6025
  return { id: saved.id, revision: saved.revision, taskId: saved.taskId };
5584
6026
  });
5585
6027
  }
@@ -5590,14 +6032,72 @@ export class Tasks {
5590
6032
  * its history entry stays a stub. The entry is not a transition and moves nothing; a later verdict for the same slot supersedes the earlier one (the scorecard reads the last).
5591
6033
  */
5592
6034
  recordClaimVerdict(by: PeerId, id: unknown, input: unknown): Task {
6035
+ return this.writeClaimVerdict(by, id, input);
6036
+ }
6037
+
6038
+ /** Refresh host bindings without changing the person's selected citation mappings or keeping a second manifest store. */
6039
+ private currentSynthesisManifest(manifest: SynthesisManifestV1, current: SynthesisCurrent): SynthesisManifestV1 | undefined {
6040
+ try {
6041
+ if (!current.deliverable?.sha256 || !current.bibliography?.sha256 || !current.claims) return;
6042
+ const currentClaims = current.claims;
6043
+ const ordered = [...manifest.claims.flatMap(ref => currentClaims.filter(claim => claim.claimId === ref.claimId)),
6044
+ ...currentClaims.filter(claim => !manifest.claims.some(ref => ref.claimId === claim.claimId))];
6045
+ const claims = ordered.map(claim => {
6046
+ if (!claim.inventory) throw new Error("incomplete inventory");
6047
+ const inventory = inventoryBinding(claim.inventory.links, claim.inventory.complete, claim.contradictionHistory);
6048
+ if (!inventory) throw new Error("incomplete inventory");
6049
+ const links = claim.inventory.links.map(row => "link" in row ? row.link : row);
6050
+ const evidence = (manifest.claims.find(row => row.claimId === claim.claimId)?.evidence ?? []).map(ref => {
6051
+ const latest = links.find(link => link.id === ref.id);
6052
+ if (!latest) throw new Error("selected link unavailable");
6053
+ return { ...ref, revision: latest.revision };
6054
+ });
6055
+ return { claimId: claim.claimId, claimRevision: claim.claimRevision, inventory, evidence };
6056
+ });
6057
+ return parseSynthesisManifest({ schemaVersion: 1, taskId: current.taskId, taskCreated: current.taskCreated,
6058
+ deliverable: { id: current.deliverable.id, sha256: current.deliverable.sha256 },
6059
+ bibliography: { id: current.bibliography.id, sha256: current.bibliography.sha256 }, claims });
6060
+ } catch { return; }
6061
+ }
6062
+
6063
+ /** Same console claim authority/store; the descriptor is transient and the write stays inside the final snapshot fence. */
6064
+ async recordSynthesisClaimVerdict(by: PeerId, id: unknown, input: unknown, manifest: unknown): Promise<Task> {
6065
+ if (by !== USER) throw new PreEffectToolRefusal("only the console user may record a claim verdict");
6066
+ const task = this.need(id), claim = parseClaimVerdict(input, task.plan?.claims?.length ?? 0), boardRevision = this.d.board.statusRevision();
6067
+ if (!claim.synthesis) throw new PreEffectToolRefusal("a synthesis verdict requires a manifest file and resolved or qualified disposition through ahub task claim");
6068
+ const result = await this.synthesisInspect(by, { taskId: task.id, manifest }, (supplied, current, report, valid) => {
6069
+ const refreshed = this.currentSynthesisManifest(supplied, current);
6070
+ if (!refreshed) throw new PreEffectToolRefusal("current synthesis manifest unavailable; refresh complete inventory, selected evidence and registered artifacts before recording a disposition");
6071
+ const hash = synthesisManifestHash(refreshed);
6072
+ if (!valid()) throw new PreEffectToolRefusal("synthesis context changed before the claim verdict write; refresh current public inputs and retry");
6073
+ if (claim.synthesis!.manifestSha256 !== hash || synthesisManifestHash(supplied) !== hash)
6074
+ throw new PreEffectToolRefusal(`synthesis manifest changed; current manifestSha256 ${hash}; refresh the manifest file and explicitly record the disposition again`);
6075
+ if (!("scope" in report) || report.binding !== "current" || report.claimCoverage !== "complete"
6076
+ || report.deliverable !== "unchanged" || report.bibliography !== "unchanged"
6077
+ || report.claims.some(row => row.claim !== "current" || row.inventory !== "current" || row.evidenceLink !== "present" || row.locator !== "resolved" || row.provenance !== "resolved"))
6078
+ throw new PreEffectToolRefusal("current synthesis provenance is unavailable or stale; resolve current source/locator and artifact statuses before recording a disposition");
6079
+ return this.writeClaimVerdict(by, task.id, claim, { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length,
6080
+ claimRevision: taskClaimIdentity(task, claim.slot).claimRevision });
6081
+ });
6082
+ if (!("history" in result)) {
6083
+ if ("cause" in result && result.cause === "source_input_limit") throw new PreEffectToolRefusal("synthesis source input exceeds the bounded check; split the task into smaller research tasks before recording a disposition");
6084
+ throw new PreEffectToolRefusal("current synthesis is private, unavailable or changed; refresh public inputs before recording a disposition");
6085
+ }
6086
+ return result;
6087
+ }
6088
+
6089
+ private writeClaimVerdict(by: PeerId, id: unknown, input: unknown, verifiedSynthesis?: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task {
5593
6090
  if (by !== USER) throw new Error("only the console user may record a claim verdict");
5594
6091
  if (this.d.cancellationHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new Error("recovery or shutdown is holding task writes");
5595
6092
  const task = this.need(id);
5596
6093
  const claims = task.plan?.claims?.length ?? 0;
5597
6094
  if (!claims) throw new Error(`task #${task.id} declares no plan claims: add them to its plan first`);
5598
6095
  const claim = parseClaimVerdict(input, claims);
6096
+ if (claim.synthesis && !verifiedSynthesis) throw new PreEffectToolRefusal("a synthesis disposition needs current manifest validation; use ahub task claim with --manifest <manifest.json> and --disposition");
6097
+ if (claim.synthesis && (this.d.profile !== "research" || task.profile !== "research")) throw new Error("synthesis dispositions require a research task and profile");
5599
6098
  // Bound to the claim list it evaluated: a hash of the plan's claims (never their text), so a later replacement or reorder of the list leaves this verdict naming no claim of the new list.
5600
6099
  const identity = taskClaimIdentity(task, claim.slot);
6100
+ if (verifiedSynthesis) return this.d.board.recordSynthesisClaimVerdict(task.id, { ...claim, list: identity.claimRevision }, verifiedSynthesis);
5601
6101
  return this.d.board.update(task.id, USER, "claim verdict", {}, undefined, { claim: { ...claim, list: identity.claimRevision } }); // no note: nothing a person typed beyond the closed fields is kept
5602
6102
  }
5603
6103
 
@@ -5617,7 +6117,7 @@ export class Tasks {
5617
6117
  this.planningAuthority(by, task);
5618
6118
  const proposer = task.history.find(h => h.event === "proposed" || h.event === "backlogged")?.by;
5619
6119
  // #812 AC5: back in proposed or backlog with no execution evidence (the `hub_backlog_return_untouched` test: no branch, commit, PR, local check, done, verdict or reopen), an accepted-then-declined task is cancellable; any such evidence keeps today's refusal.
5620
- if (proposer !== by || !["backlog", "proposed"].includes(task.state) || taskHasWorkEvidence(task)) throw new PreEffectToolRefusal("planner may cancel only its own historically unaccepted backlog or proposed work");
6120
+ if (proposer !== by || !["backlog", "proposed"].includes(task.state) || taskHasWorkEvidence(task)) throw new PreEffectToolRefusal(`planner may cancel only its own historically unaccepted backlog or proposed work${proposer === HUB ? `; task #${task.id} was created by the hub, so only the person can cancel it: ahub task cancel ${task.id} --reason <text> (a recurring-finding card that matched unrelated findings is a false recurrence)` : ""}`);
5621
6121
  }
5622
6122
  return task;
5623
6123
  };
@@ -6380,7 +6880,7 @@ export class Tasks {
6380
6880
 
6381
6881
  /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */
6382
6882
  private deliveryLinks(config: SdlcConfig): DeliveryTask[] {
6383
- return this.d.board.list().map(t => ({ id: t.id, after: t.deps ?? [], private: this.isPii(t), latestHead: this.reviewHead(t), approval: approvalBinding(t), receipt: t.sdlc, phase: this.isPii(t) ? undefined : this.workflowView(t), findings: this.isPii(t) ? undefined : this.reviewFindingSets(t), plan: config.mode === "off" || this.isPii(t) ? undefined : { paths: this.planPaths(t), revision: t.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0, fingerprint: planFingerprint(t.plan ?? {}), accepted: this.validPlanDepartures(t) } }));
6883
+ return this.d.board.list().map(t => ({ id: t.id, after: t.deps ?? [], private: this.isPii(t), latestHead: this.reviewHead(t), approval: approvalBinding(t), receipt: t.sdlc, phase: this.isPii(t) ? undefined : this.workflowView(t), findings: this.isPii(t) ? undefined : this.reviewFindingSets(t), ...(config.mode === "off" || !config.security || this.isPii(t) ? {} : { securityPass: t.history.findLast(entry => entry.securityPass && !entry.withheld && (entry.event === "approved" || entry.event === "changes_requested"))?.securityPass }), plan: config.mode === "off" || this.isPii(t) ? undefined : { paths: this.planPaths(t), out_of_scope: this.planPaths(t, "out_of_scope") ?? t.plan?.out_of_scope, revision: t.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0, fingerprint: planFingerprint(t.plan ?? {}), accepted: this.validPlanDepartures(t) } }));
6384
6884
  }
6385
6885
 
6386
6886
  /**
@@ -6431,6 +6931,431 @@ export class Tasks {
6431
6931
  }
6432
6932
  return report;
6433
6933
  }
6934
+
6935
+ /** #1403 A4: a summary of the newest audit for the release report: ref, profile, partial and unit counts, never a finding or a path. */
6936
+ auditLine(): AuditSummary | undefined {
6937
+ const audit = this.d.board.audits(1)[0];
6938
+ return audit ? auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, this.d.board.auditFindings(audit.id)) : undefined;
6939
+ }
6940
+
6941
+ private surveyToolInput<T>(command: "start" | "report", field: string, rule: string, read: () => T): T {
6942
+ try { return surveyInputAt(field, rule, read); } catch (error) {
6943
+ const problem = surveyInputProblem(error) ?? { field, rule };
6944
+ const next = command === "report" ? "fix that field and resend hub_survey_report; tool description lists shape"
6945
+ : "fix that field and resend ahub sdlc survey start; ahub help sdlc survey lists shape";
6946
+ throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; ${next}`);
6947
+ }
6948
+ }
6949
+ private surveyStarting = false;
6950
+ private surveyAdmit(by: PeerId, check: () => void): void {
6951
+ check();
6952
+ if ((this.d.sdlc?.config().mode ?? "off") === "off") throw new PreEffectToolRefusal("advisor surveys require lifecycle advise or enforce");
6953
+ if (this.d.privateTurn?.(by) || this.d.reviewOnly?.(by) || this.d.requestAuthority?.(by)) throw new PreEffectToolRefusal("advisor surveys are unavailable in private or child sessions");
6954
+ const held = this.studyHold(); if (held) throw new PreEffectToolRefusal(held);
6955
+ }
6956
+ private surveyTask(by: PeerId, id: unknown, write = false): { task: Task; survey: StoredSurvey } {
6957
+ const task = this.need(this.studyNumber(id, "survey task")), survey = this.d.board.surveyOfTask(task.id, task.created);
6958
+ if (!survey || survey.repo !== this.repositories.scope({}).key || this.repositories.scope(task.refs).key !== survey.repo) throw new PreEffectToolRefusal("survey is unavailable in this project");
6959
+ const owner = task.owner === by && this.d.bus.isRostered(by) && this.isConfiguredPlanner(by);
6960
+ const reviewer = task.reviewer === by && this.d.bus.isRostered(by) && !!this.d.roles?.[by]?.includes("reviewer");
6961
+ if (write ? !owner || task.state !== "in_progress" : by !== USER && !owner && !reviewer && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by)))
6962
+ throw new PreEffectToolRefusal("survey reporting requires its assigned in-progress planner; readback requires its owner, reviewer, person or current conductor");
6963
+ return { task, survey };
6964
+ }
6965
+ private surveyPrivate(task: Task, by?: PeerId): boolean {
6966
+ return this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path") || !!(by && this.d.privateTurn?.(by));
6967
+ }
6968
+ /** The existing task routing chooses one planner; no worker, scanner, issue or fix is launched. */
6969
+ async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> {
6970
+ const fields = this.surveyToolInput("start", "start", "must be a closed object with optional focus", () => surveyObject(input, ["focus"])), focus = fields.focus;
6971
+ if (focus !== undefined && (typeof focus !== "string" || !(SURVEY_FOCUS as readonly string[]).includes(focus))) this.surveyToolInput("start", "focus", "must be bugs, tests, debt, deps, dx or docs", () => { throw new Error("invalid bounded survey data"); });
6972
+ const check = this.requestCheck(by, fence), authority = () => {
6973
+ this.surveyAdmit(by, check);
6974
+ if (by !== USER && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or current unique conductor may start a survey");
6975
+ };
6976
+ authority();
6977
+ if (this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey start is unavailable from observer material");
6978
+ if (this.surveyStarting) throw new PreEffectToolRefusal("a survey is already starting");
6979
+ const repo = this.repositories.scope({}).key, source = this.d.auditSource;
6980
+ if (!source) throw new PreEffectToolRefusal("survey source unavailable; start the hub from the project checkout");
6981
+ const ref = source.head();
6982
+ if (!ref || !/^[a-f0-9]{40}$/.test(ref) || source.resolve(ref) !== ref) throw new PreEffectToolRefusal("survey commit unavailable; select a checkout with a readable commit");
6983
+ if (this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("a survey is already open; finish or cancel it first");
6984
+ const brief = `${surveyBrief({ ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) })}\nPinned source commit: ${ref}\nRead this exact commit, including during vetting. Findings are declarations, never host proof of independent source review.\nSubmit candidates with hub_survey_report {id: <this task>, findings: [...]}; explicit vet decisions use vet: [...].\n${this.consideredBrief(repo, ref)}`;
6985
+ if (!this.publicMetadataText(brief)) throw new PreEffectToolRefusal("survey brief is not public");
6986
+ this.surveyStarting = true;
6987
+ try { return await this.studyWrite(async () => {
6988
+ const guard = () => { authority(); if (this.d.auditSource !== source || this.repositories.scope({}).key !== repo || this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("survey source or open-survey admission changed"); };
6989
+ guard();
6990
+ let surveyID: number | undefined;
6991
+ const task = await this.propose(by, { title: `Advisor survey${focus ? ` (${focus})` : ""} at ${ref.slice(0, 12)}`, detail: brief, class: "plan" }, undefined, undefined,
6992
+ () => { guard(); return undefined; }, created => {
6993
+ if (this.surveyPrivate(created, by)) throw new PreEffectToolRefusal("survey brief privacy was not cleared");
6994
+ surveyID = this.d.board.surveyCreate({ task: created.id, taskCreated: created.created, repo, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }), by, at: this.d.now?.() ?? Date.now() });
6995
+ });
6996
+ return { task: task.id, survey: surveyID!, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) };
6997
+ }); } finally { this.surveyStarting = false; }
6998
+ }
6999
+ private consideredChanges(repo: string, ref?: string): (entryRef?: string) => string[] | undefined {
7000
+ // ponytail: distinct refs still use synchronous reads within the existing ledger window per key; batch through an async audit port if histories outgrow interactive readback.
7001
+ const cache = new Map<string, string[] | undefined>(); let currentKnown: boolean | undefined;
7002
+ return entryRef => {
7003
+ if (!entryRef || !ref || entryRef === ref || repo !== this.repositories.scope({}).key) return undefined;
7004
+ if (cache.has(entryRef)) return cache.get(entryRef);
7005
+ let changed: string[] | undefined;
7006
+ try {
7007
+ currentKnown ??= this.d.auditSource?.resolve(ref) === ref;
7008
+ if (currentKnown && this.d.auditSource?.resolve(entryRef) === entryRef) changed = this.d.auditSource.changed(entryRef, ref);
7009
+ } catch { currentKnown ??= false; /* Per-call unknown evidence stays unknown; no cross-call freshness cache. */ }
7010
+ cache.set(entryRef, changed); return changed;
7011
+ };
7012
+ }
7013
+ /** Same semantic identity and affected literal paths only; unreadable change evidence never clears suppression. */
7014
+ consideredBefore(task: Task, finding: Pick<ReviewFinding, "id" | "pass" | "path"> | SurveyFinding, ref?: string, readChanges?: (entryRef?: string) => string[] | undefined): { rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean } {
7015
+ const neutral = { rejectedBefore: false, change: "none" as const, suppressed: false };
7016
+ if (positionalFindingId(finding.id) || (this.d.sdlc?.config().mode ?? "off") === "off" || this.surveyPrivate(task)) return neutral;
7017
+ const repo = this.repositories.scope(task.refs).key, ledger = this.d.board.rejectedFindingsFor(repo, finding.pass, finding.id, 1000);
7018
+ if (!ledger.complete) return { rejectedBefore: true, change: "unknown", suppressed: true };
7019
+ const matched = ledger.rows.filter(row => row.entry.id === finding.id && row.entry.pass === finding.pass);
7020
+ if (!matched.length) return neutral;
7021
+ if (repo !== this.repositories.scope({}).key) return { rejectedBefore: true, change: "unknown", suppressed: true };
7022
+ const currentRef = ref, paths = "paths" in finding ? finding.paths : finding.path ? (() => { try { return [surveyPath(finding.path)]; } catch { return []; } })() : [];
7023
+ const changes = readChanges ?? this.consideredChanges(repo, ref);
7024
+ let seen = false, unknown = false, unchanged = false;
7025
+ const overlaps = (a: string, b: string) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
7026
+ for (const row of matched) {
7027
+ seen = true;
7028
+ const changed = changes(row.entry.ref);
7029
+ const match = consideredFindingMatch(row.entry, { repo, id: finding.id, pass: finding.pass, currentRef: currentRef ?? "", ...(changed === undefined ? {} : { diff: { repo, base: row.entry.ref!, head: currentRef!, complete: true, paths: changed } }) });
7030
+ if (match.status === "unknown" || !paths.length) unknown = true;
7031
+ if (match.status === "applicable" && match.applicablePaths.some(path => paths.some(candidate => overlaps(path, candidate)))) unchanged = true;
7032
+ }
7033
+ return !seen ? neutral : { rejectedBefore: true, change: unknown ? "unknown" : unchanged ? "unchanged" : "changed", suppressed: unknown || unchanged };
7034
+ }
7035
+ private consideredPaths(path: string | undefined): string[] {
7036
+ if (!path) return [];
7037
+ try {
7038
+ let name = path.replace(/:[1-9][0-9]*(?::[1-9][0-9]*)?$/, "");
7039
+ if (isAbsolute(name)) name = relative(this.d.cwd, name);
7040
+ return [surveyPath(name)];
7041
+ } catch { return []; }
7042
+ }
7043
+ private consideredPublic(entry: ConsideredEntry): boolean {
7044
+ try {
7045
+ const source = this.d.board.get(entry.source.task);
7046
+ if (entry.withheld || entry.pass === "security" || !source || source.created !== entry.source.created || this.surveyPrivate(source)) return false;
7047
+ const { repo: _scope, ...data } = entry;
7048
+ return this.publicMetadataText(JSON.stringify(data)) && !this.signalsFor({ title: entry.id, detail: entry.reason, refs: { paths: entry.paths } }).some(signal => signal === "pii" || signal === "pii_path");
7049
+ } catch { return false; }
7050
+ }
7051
+ /** Bounded public historical reasons; never expose internal scope keys, security text or paths. */
7052
+ consideredDetails(repo: string, id: string, pass: SurveyPass, ref?: string, readChanges?: (entryRef?: string) => string[] | undefined): { complete: boolean; change: "unchanged" | "changed" | "unknown"; items: { id: string; reason?: string; change: "unchanged" | "changed" | "unknown"; withheld?: true }[] } {
7053
+ const publicId = this.publicMetadataText(id) ? id : "withheld";
7054
+ const ledger = this.d.board.rejectedFindingsFor(repo, pass, id, 1000);
7055
+ if (!ledger.complete) return { complete: false, change: "unknown", items: [{ id: publicId, change: "unknown", withheld: true }] };
7056
+ const changes = readChanges ?? this.consideredChanges(repo, ref);
7057
+ const items = ledger.rows.slice(0, 16).map(row => {
7058
+ const entry = row.entry;
7059
+ const changed = changes(entry.ref);
7060
+ const match = repo === this.repositories.scope({}).key ? consideredFindingMatch(entry, { repo, id, pass, currentRef: ref ?? "", ...(changed === undefined ? {} : { diff: { repo, base: entry.ref!, head: ref!, complete: true, paths: changed } }) }) : undefined;
7061
+ const change = match?.status === "applicable" ? "unchanged" as const : match?.status === "changed" ? "changed" as const : "unknown" as const;
7062
+ return { id: publicId, change, ...(this.consideredPublic(entry) ? { reason: entry.reason } : { withheld: true as const }) };
7063
+ });
7064
+ const change = ledger.rows.length > 16 ? "unknown" : items.some(row => row.change === "unknown") ? "unknown" : items.some(row => row.change === "unchanged") ? "unchanged" : items.length ? "changed" : "unknown";
7065
+ return { complete: ledger.rows.length <= 16, change, items };
7066
+ }
7067
+ consideredBrief(repo: string, ref?: string, scope?: readonly string[]): string {
7068
+ const ledger = this.d.board.rejectedFindings(repo, 1000);
7069
+ if (!ledger.complete) return "Previously rejected findings: history incomplete; change is unknown and rejection remains in effect.";
7070
+ const lines = ["Previously rejected findings (unknown change retains rejection; positional ids never match across tasks):"], seen = new Set<string>(), changes = this.consideredChanges(repo, ref);
7071
+ for (const row of ledger.rows) {
7072
+ const entry = row.entry, key = `${entry.pass}:${entry.id}`;
7073
+ if (seen.has(key) || scope?.length && entry.paths.length && !entry.paths.some(path => scope.some(surface => matchConfigPath(surface, path) || path === surface || path.startsWith(surface + "/")))) continue;
7074
+ seen.add(key);
7075
+ const details = this.consideredDetails(repo, entry.id, entry.pass, ref, changes), detail = details.items[0];
7076
+ const reason = detail?.reason ? `: ${Array.from(detail.reason).slice(0, 160).join("")}${Array.from(detail.reason).length > 160 ? "..." : ""}` : " (details withheld)";
7077
+ const line = `${entry.pass}:${detail?.id ?? "withheld"}: rejected before; change ${details.change}${reason}`;
7078
+ if (seen.size > 32 || Buffer.byteLength([...lines, line].join("\n")) > 3072) { lines.push("Additional rejection history omitted; consult authorized readback. Unknown change retains rejection."); break; }
7079
+ lines.push(line);
7080
+ }
7081
+ if (lines.length === 1) lines.push("No matching recorded rejections.");
7082
+ return lines.join("\n");
7083
+ }
7084
+ /** Saved facts stay local. Private/sensitive facts retain a withheld identity stub without a cloud screen. */
7085
+ async recordConsideredFinding(task: Task, finding: ReviewFinding, reason: string | undefined, kind: "review" | "audit" | "survey", ref?: string): Promise<number | undefined> {
7086
+ if ((this.d.sdlc?.config().mode ?? "off") === "off") return;
7087
+ return this.studyWrite(async () => {
7088
+ const revision = this.d.board.statusRevision(), current = this.d.board.get(task.id);
7089
+ if (!current || current.created !== task.created || current.history.length !== task.history.length || this.studyHold()) return;
7090
+ const normalized = typeof reason === "string" ? reason.replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim() : "";
7091
+ const safeReason = normalized && Buffer.byteLength(normalized) <= 2048 ? normalized : "reason not recorded";
7092
+ const paths = this.consideredPaths(finding.path), privateFact = this.surveyPrivate(current) || !!task.history.at(-1)?.withheld;
7093
+ let entry = parseConsideredEntry({ repo: this.repositories.scope(task.refs).key, id: finding.id, pass: finding.pass, paths: privateFact ? [] : paths, reason: privateFact ? "reason not recorded" : safeReason,
7094
+ ...(ref && /^[a-f0-9]{40}$/.test(ref) ? { ref } : {}), source: { task: task.id, created: task.created, kind }, ...(privateFact || finding.pass === "security" ? { withheld: true } : {}) });
7095
+ const { repo: _internalScope, ...publicEntry } = entry;
7096
+ if (!this.publicMetadataText(JSON.stringify(publicEntry))) entry = { ...entry, paths: [], reason: "reason not recorded", withheld: true };
7097
+ const now = this.d.board.get(task.id);
7098
+ if (!now || now.created !== task.created || now.history.length !== task.history.length || this.d.board.statusRevision() !== revision
7099
+ || (this.d.sdlc?.config().mode ?? "off") === "off" || this.studyHold() || this.repositories.scope(now.refs).key !== entry.repo) return;
7100
+ return this.d.board.recordRejectedFinding(entry);
7101
+ });
7102
+ }
7103
+ private recordConsideredAfter(task: Task, findings: readonly ReviewFinding[], kind: "review" | "audit", ref?: string): void {
7104
+ if ((this.d.sdlc?.config().mode ?? "off") === "off" || !findings.length) return;
7105
+ this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`, () => {
7106
+ void Promise.all(findings.map(finding => this.recordConsideredFinding(task, finding, kind === "audit" ? undefined : finding.rationale, kind, ref)))
7107
+ .then(ids => { if (ids.some(id => id === undefined)) this.releaseNotice(`task #${task.id}: considered rejection ledger admission changed; source decision remains saved`); })
7108
+ .catch(() => this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`));
7109
+ });
7110
+ }
7111
+ surveyShow(by: PeerId, id: unknown) {
7112
+ const check = this.requestCheck(by); this.surveyAdmit(by, check);
7113
+ const { task, survey } = this.surveyTask(by, id);
7114
+ if (this.surveyPrivate(task, by)) return { task: task.id, status: "private" as const };
7115
+ const revision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]);
7116
+ const full = by === USER || this.d.bus.isRostered(by) && (task.owner === by && this.isConfiguredPlanner(by) || task.reviewer === by && !!this.d.roles?.[by]?.includes("reviewer"));
7117
+ const stored = this.d.board.surveyFindings(survey.id), changes = this.consideredChanges(survey.repo, survey.ref);
7118
+ if (stored.some(row => !this.publicMetadataText(JSON.stringify(row.finding)) || this.signalsFor({ title: row.finding.id, detail: JSON.stringify(row.finding), refs: { paths: row.finding.paths } }).some(signal => signal === "pii" || signal === "pii_path"))) return { task: task.id, status: "private" as const };
7119
+ const items = stored.map(row => {
7120
+ const finding = full ? row.finding : publicSurveyFinding(row.finding), before = this.consideredBefore(task, row.finding, survey.ref, changes);
7121
+ const details = this.consideredDetails(survey.repo, row.finding.id, row.finding.pass, survey.ref, changes);
7122
+ return { ...finding, ...(row.decision ? { verdict: row.decision.verdict } : {}), ...before, rejected: details.items, rejectedComplete: details.complete };
7123
+ });
7124
+ this.surveyAdmit(by, check);
7125
+ const now = this.surveyTask(by, id);
7126
+ if (this.surveyPrivate(now.task, by)) return { task: task.id, status: "private" as const };
7127
+ if (this.d.board.statusRevision() !== revision || now.task.history.length !== task.history.length || JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey changed during readback; reload before reading");
7128
+ return { task: task.id, survey: survey.id, ref: survey.ref, ...(survey.focus ? { focus: survey.focus } : {}), status: "available" as const, items };
7129
+ }
7130
+ async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) {
7131
+ const fields = this.surveyToolInput("report", "report", "must be a closed object with id and findings, vet or show", () => surveyObject(input, ["id", "findings", "vet", "show"]));
7132
+ this.surveyToolInput("report", "id", "must be a positive integer survey task id", () => { if (!Number.isSafeInteger(fields.id) || (fields.id as number) < 1) throw new Error("invalid bounded survey data"); });
7133
+ this.surveyToolInput("report", "show", "must be true for read-only show and cannot include findings or vet decisions", () => {
7134
+ if (fields.show !== undefined && fields.show !== true || fields.show && (fields.findings !== undefined || fields.vet !== undefined)) throw new Error("invalid bounded survey data");
7135
+ });
7136
+ if (fields.show) { this.requestCheck(by, fence)(); return this.surveyShow(by, fields.id); }
7137
+ const findings = fields.findings === undefined ? [] : this.surveyToolInput("report", "findings", "must match the documented finding array", () => parseSurveyFindings(fields.findings));
7138
+ const decisions = fields.vet === undefined ? [] : this.surveyToolInput("report", "vet", "must match the documented vet array", () => parseSurveyVetDecisions(fields.vet));
7139
+ const check = this.requestCheck(by, fence), guard = () => { this.surveyAdmit(by, check); return this.surveyTask(by, fields.id, true); };
7140
+ const initial = guard();
7141
+ if (this.surveyPrivate(initial.task, by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey writes unavailable during private or observer work");
7142
+ if (!findings.length && !decisions.length) throw new PreEffectToolRefusal("report: needs findings or explicit vet decisions; fix that field and resend hub_survey_report; tool description lists shape");
7143
+ const observerExcluded = this.observerExcluded(by); // Capture before any awaited screen; never forward observer material.
7144
+ if (observerExcluded) throw new PreEffectToolRefusal("survey observer input is unavailable");
7145
+ return this.studyWrite(async () => {
7146
+ const { task, survey } = guard(), boardRevision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]);
7147
+ const current = () => {
7148
+ const now = guard();
7149
+ if (now.task.created !== task.created || now.task.history.length !== task.history.length || now.task.owner !== task.owner || this.surveyPrivate(now.task, by)
7150
+ || this.d.board.statusRevision() !== boardRevision || JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey authority, privacy or policy changed; reload before reporting");
7151
+ };
7152
+ const existing = this.d.board.surveyFindings(survey.id), merged = new Map(existing.map(row => [row.finding.id, row.finding]));
7153
+ for (const finding of findings) { const prior = merged.get(finding.id); if (prior && JSON.stringify(prior) !== JSON.stringify(finding)) throw new PreEffectToolRefusal("findings[].id: survey candidate id already records different content; fix that field and resend hub_survey_report; tool description lists shape"); merged.set(finding.id, finding); }
7154
+ const text = JSON.stringify({ findings: this.surveyToolInput("report", "findings", "combined findings must remain within the documented bounds", () => parseSurveyFindings([...merged.values()])), decisions });
7155
+ if (!this.publicMetadataText(text)) throw new PreEffectToolRefusal("survey metadata was not cleared as public");
7156
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("survey metadata privacy screening was unavailable or refused");
7157
+ current();
7158
+ const changes = this.consideredChanges(survey.repo, survey.ref);
7159
+ const cards: SurveyPreparedCard[] = [], rejections: ConsideredEntry[] = [], reconsiderations: ConsideredEntry[] = [];
7160
+ const items: { id: string; rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean }[] = [];
7161
+ for (const decision of decisions) {
7162
+ const finding = merged.get(decision.id); if (!finding) throw new PreEffectToolRefusal("vet[].id: vet decision names an unknown survey candidate; fix that field and resend hub_survey_report; tool description lists shape");
7163
+ const before = this.consideredBefore(task, finding, survey.ref, changes); items.push({ id: finding.id, ...before });
7164
+ const entry = (reason: string): ConsideredEntry => ({ repo: survey.repo, id: finding.id, pass: finding.pass, paths: finding.paths, reason, ref: survey.ref,
7165
+ source: { task: task.id, created: task.created, kind: "survey" }, ...(finding.pass === "security" ? { withheld: true } : {}) });
7166
+ if (decision.verdict === "rejected") { rejections.push(entry(decision.reason!)); continue; }
7167
+ if (before.suppressed && !decision.reason) continue;
7168
+ if (before.rejectedBefore && decision.reason) reconsiderations.push(entry(decision.reason));
7169
+ const key = surveyFindingKey(survey.repo, finding.pass, finding.id), security = finding.pass === "security";
7170
+ const history = this.d.board.surveyCardHistory(key), reopens = history.active ? undefined : history.closed;
7171
+ current();
7172
+ const reopenReason = security ? "explicit current vet; security details remain in the authorized survey"
7173
+ : decision.reason ?? (before.change === "changed" ? "affected paths changed since the recorded rejection" : "explicit current vet; no applicable rejected finding remains");
7174
+ const reopening = reopens === undefined ? {} : { reopens, reopenReason };
7175
+ const draft = { title: security ? `Survey security finding ${finding.id}` : `Survey ${finding.confidence}: ${finding.id}`,
7176
+ detail: `${key}\nSource survey task ${task.id} at ${survey.ref}.\n${finding.confidence === "low" ? "Read-only investigation. Do not edit files or execute a fix." : "Prepare a backlog plan. Do not execute a fix."}${security ? "\nSecurity details withheld; read the source survey with authorized task access." : `\nEvidence: ${finding.evidence}\nImpact: ${finding.impact}\nEffort: ${finding.effort}\nRisk: ${finding.risk}\nFix sketch: ${finding.fix_sketch}`}${reopens === undefined ? "" : `\nReopened from hub task ${reopens}: ${reopenReason}`}`,
7177
+ refs: security ? {} : { paths: finding.paths } };
7178
+ if (Buffer.byteLength(draft.detail) > SURVEY_LIMITS.cardBytes) throw new PreEffectToolRefusal("survey card exceeds its detail bound; shorten the finding or reconsideration reason");
7179
+ const signals = this.signalsFor(draft);
7180
+ if (this.isPii({ signals }) || signals.includes("pii") || signals.includes("pii_path") || !this.publicMetadataText(JSON.stringify(draft))) throw new PreEffectToolRefusal("survey candidate card is not public");
7181
+ if (this.screenOn() && (await this.screenCall(JSON.stringify(draft))).label !== "clear") throw new PreEffectToolRefusal("survey card privacy screening was unavailable or refused");
7182
+ current(); cards.push({ id: finding.id, key, ...draft, class: finding.confidence === "low" ? "triage" : "plan", signals, ...reopening });
7183
+ }
7184
+ current();
7185
+ const result = this.d.board.surveyApply(survey.id, { findings, decisions, by, at: this.d.now?.() ?? Date.now(), cards, rejections, reconsiderations },
7186
+ { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, owner: task.owner! });
7187
+ for (const id of result.createdIDs) this.incomingBacklog.add(id);
7188
+ this.releaseNotice(`survey task ${task.id}: ${result.createdIDs.length} backlog candidates created`);
7189
+ return { task: task.id, survey: survey.id, status: "recorded" as const, ...result, items };
7190
+ });
7191
+ }
7192
+
7193
+ private auditCarry(head: string, source: AuditSource): CarryLookup {
7194
+ const audits = this.d.board.audits(32, true), changed = new Map<string, string[] | undefined>();
7195
+ const since = (base: string) => { if (!changed.has(base)) changed.set(base, source.changed(base, head)); return changed.get(base); };
7196
+ return (surface, companion) => {
7197
+ const id = unitId(surface, companion);
7198
+ for (const audit of audits) {
7199
+ const unit = audit.units.find(row => row.unit === id);
7200
+ // The newest audit that lists the unit decides: a scoped audit that left it out says nothing, but a deferred, out-of-scope or still planned unit plans it again.
7201
+ if (!unit) continue;
7202
+ if (unit.state !== "covered") return undefined;
7203
+ const base = unit.prior?.head ?? audit.ref, origin = unit.prior?.audit ?? audit.id, paths = since(base);
7204
+ // Unknown never carries: an unreadable change list, or a changed path under the surface, plans the unit again.
7205
+ return paths && !paths.some(path => matchConfigPath(surface, path)) ? { audit: origin, head: base } : undefined;
7206
+ }
7207
+ return undefined;
7208
+ };
7209
+ }
7210
+
7211
+ /**
7212
+ * #1403 A4: `ahub sdlc audit start`. The person or the one configured conductor files one read-only `review` task whose brief lists the ledger, and the hub seeds the ledger in `hub.db`
7213
+ * (surface x companion, `planned`, or `covered (prior)` for a surface whose paths are unchanged since its last covered state). Nothing is written until every check has passed.
7214
+ */
7215
+ async auditStart(by: PeerId, input: { profile?: unknown; since?: unknown }, fence?: () => string | undefined): Promise<{ task: number; audit: number; units: number; planned: number; carried: number; partial: boolean; ref: string }> {
7216
+ const check = this.requestCheck(by, fence);
7217
+ if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or the current configured conductor may start a security audit; ask the person to run ahub sdlc audit start");
7218
+ if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("a security audit cannot start in a private turn; finish that turn and retry ahub sdlc audit start");
7219
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
7220
+ if (config.mode === "off") throw new PreEffectToolRefusal("security audits need the lifecycle on: set sdlc.mode to advise or enforce in .agenthub/sdlc.toml");
7221
+ if (!config.security) throw new PreEffectToolRefusal("security audits need a [security] table in .agenthub/sdlc.toml (paths and companions)");
7222
+ const source = this.d.auditSource;
7223
+ if (!source) throw new PreEffectToolRefusal("this hub has no git source to read for an audit; start the hub from a git checkout of the project and retry ahub sdlc audit start");
7224
+ const profile = input.profile === undefined ? "standard" : input.profile;
7225
+ if (typeof profile !== "string" || !(AUDIT_PROFILES as readonly string[]).includes(profile)) throw new PreEffectToolRefusal(`profile is one of ${AUDIT_PROFILES.join(", ")}`);
7226
+ const head = source.head();
7227
+ if (!head) throw new PreEffectToolRefusal("the checkout's head commit could not be read; run the audit from a git checkout with a commit");
7228
+ let scoped: string[] | undefined;
7229
+ if (input.since !== undefined) {
7230
+ if (typeof input.since !== "string" || !input.since.trim() || input.since.length > 200) throw new PreEffectToolRefusal("--since names a commit, tag or branch of this checkout");
7231
+ const base = source.resolve(input.since.trim());
7232
+ if (!base) throw new PreEffectToolRefusal("--since does not name a commit in this checkout");
7233
+ scoped = source.changed(base, head);
7234
+ if (!scoped) throw new PreEffectToolRefusal("the paths changed since that ref could not be listed completely; narrow --since or run an unscoped audit");
7235
+ }
7236
+ if (this.d.board.list().some(t => t.class === "review" && t.title.startsWith("Security audit (") && !isClosedTaskState(t.state) && t.state !== "approved" && this.d.board.auditOfTask(t.id, t.created))) throw new PreEffectToolRefusal("a security audit is already open; finish or cancel it first");
7237
+ const units = seedLedger(config.security, profile as AuditProfile, { ...(scoped ? { scoped } : {}), carry: this.auditCarry(head, source) });
7238
+ if (!units.length) throw new PreEffectToolRefusal("no configured security surface has a changed path in that scope; nothing to audit");
7239
+ const partial = auditIsPartial(profile as AuditProfile, scoped !== undefined);
7240
+ const inline = units.filter(u => !u.prior).slice(0, 40), cut = units.filter(u => !u.prior).length - inline.length;
7241
+ const brief = auditBrief([...inline, ...units.filter(u => u.prior)], { profile: profile as AuditProfile, partial, checklist: SECURITY_CHECKLIST, ref: head }) + (cut > 0 ? `\n(${cut} more units: hub_audit_report {id: <this task>, show: true} lists the ledger)` : "")
7242
+ + "\n" + this.consideredBrief(this.repositories.scope({}).key, head, config.security.paths);
7243
+ check();
7244
+ const task = await this.propose(by, { title: `Security audit (${profile}${scoped ? ", scoped" : ""}) at ${head.slice(0, 12)}`, detail: brief, class: "review" }, undefined, undefined, fence);
7245
+ let audit: number;
7246
+ try {
7247
+ if (this.isPii(task)) throw new PreEffectToolRefusal("the audit brief matched a private-data pattern; rename the configured surface");
7248
+ audit = this.d.board.auditCreate({ task: task.id, taskCreated: task.created, ref: head, ...(typeof input.since === "string" ? { since: input.since.trim() } : {}), profile, scoped: scoped !== undefined, by, at: this.d.now?.() ?? Date.now(), units });
7249
+ } catch (error) {
7250
+ // The ledger is the audit: a task without one would be an empty promise, so it is cancelled rather than left to run.
7251
+ await this.cancel(task.id, by, { reason: "security audit ledger could not be created" }).catch(() => undefined);
7252
+ throw error;
7253
+ }
7254
+ return { task: task.id, audit, units: units.length, planned: units.filter(u => !u.prior).length, carried: units.filter(u => u.prior).length, partial, ref: head };
7255
+ }
7256
+
7257
+ private auditView(audit: NonNullable<ReturnType<Board["audit"]>>, full: boolean): AuditView {
7258
+ const findings = this.d.board.auditFindings(audit.id);
7259
+ const summary = auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, findings);
7260
+ return { ...summary, units: audit.units.map(u => ({ unit: u.unit, state: u.state, ...(u.prior ? { prior: u.prior } : {}), ...(u.reason ? { reason: u.reason } : {}) })), items: findings.map(row => auditFindingView(row, full)), ...(full ? {} : { withheld: findings.filter(row => !!auditFindingView(row, false).withheld).length }) };
7261
+ }
7262
+
7263
+ /** `ahub sdlc audit show`: the newest audit, or the one named. The full view (open important boundary text included) is the person's alone; a conductor reads the public one. */
7264
+ auditShow(by: PeerId, id?: unknown): AuditView | undefined {
7265
+ if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("the audit readback is for the person or the configured conductor");
7266
+ if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("the audit readback is unavailable in a private turn");
7267
+ const audit = id === undefined ? this.d.board.audits(1)[0] : Number.isSafeInteger(id) && (id as number) > 0 ? this.d.board.audit(id as number) : undefined;
7268
+ if (id !== undefined && !audit) throw new PreEffectToolRefusal("no such security audit");
7269
+ return audit ? this.auditView(audit, by === USER) : undefined;
7270
+ }
7271
+
7272
+ /**
7273
+ * #1403 A4, A5: `hub_audit_report`. The assigned auditor (the audit task's owner) reports a state per unit and its findings; the hub alone writes the ledger. A reviewer-role peer that did
7274
+ * not file a `confirmed` important finding verifies or rejects it; until then it stays a `candidate`. Boundary text of an open important finding is read only through this tool by the
7275
+ * auditor, a reviewer-role peer or the person, and never rides a message to anyone else.
7276
+ */
7277
+ async auditReport(by: PeerId, input: { id?: unknown; units?: unknown; findings?: unknown; verify?: unknown; settle?: unknown; show?: unknown }, fence?: () => string | undefined): Promise<AuditView> {
7278
+ const check = this.requestCheck(by, fence);
7279
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
7280
+ if (config.mode === "off" || !config.security) throw new PreEffectToolRefusal("audit reports need the lifecycle on and a [security] table in .agenthub/sdlc.toml");
7281
+ if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("audit reports are unavailable in a private turn: their text must not leave this machine");
7282
+ if (!Number.isSafeInteger(input.id) || (input.id as number) <= 0) throw new PreEffectToolRefusal("hub_audit_report needs the audit task id");
7283
+ const task = this.d.board.get(input.id as number), audit = task ? this.d.board.auditOfTask(task.id, task.created) : undefined;
7284
+ if (!task || !audit) throw new PreEffectToolRefusal("no security audit on that task");
7285
+ if (this.isPii(task)) throw new PreEffectToolRefusal("that task is private");
7286
+ const isOwner = by !== USER && task.owner === by && task.state === "in_progress";
7287
+ const reviewerRole = by !== USER && (this.d.roles?.[by] ?? []).includes("reviewer") && this.d.bus.isRostered(by);
7288
+ const writes = input.units !== undefined || input.findings !== undefined, verifies = input.verify !== undefined, settles = input.settle !== undefined;
7289
+ if (!writes && !verifies && !settles && input.show !== true) throw new PreEffectToolRefusal("give units and findings (the auditor), verify or settle (a reviewer other than the finder, or the person) or show: true");
7290
+ if (writes && !isOwner) throw new PreEffectToolRefusal("only the assigned auditor reports units and findings, while the audit task is in progress");
7291
+ if (verifies && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer or the person verifies a finding");
7292
+ if (settles && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer other than the finder, or the person, settles a verified finding; ask a reviewer or the person to settle it");
7293
+ if ((verifies || settles) && (task.state === "cancelled" || task.state === "backlog")) throw new PreEffectToolRefusal("the audit task is closed");
7294
+ if (!isOwner && !reviewerRole && by !== USER) throw new PreEffectToolRefusal("only the auditor, a reviewer-role peer or the person reads an audit report");
7295
+ const when = this.d.now?.() ?? Date.now();
7296
+ let units = audit.units, filed: { finding: ReviewFinding; foundBy: string; at: number }[] = [];
7297
+ const decisions: { finding: string; verdict: "verified" | "rejected" }[] = [];
7298
+ const settlements: { finding: string; disposition: "fixed" | "false_positive" }[] = [];
7299
+ if (input.units !== undefined) {
7300
+ try { units = applyUnitReports(audit.units, parseUnitReports(input.units, audit.units), by, when); }
7301
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid units"); }
7302
+ }
7303
+ if (input.findings !== undefined) {
7304
+ let parsed: ReviewFinding[];
7305
+ try { parsed = parseReviewFindings(input.findings, { person: false, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: "required" }); }
7306
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid findings"); }
7307
+ if (parsed.some(item => item.pass !== "security")) throw new PreEffectToolRefusal("an audit takes security findings only (pass: security)");
7308
+ if (parsed.some(item => item.anchor !== undefined)) throw new PreEffectToolRefusal("anchors belong to review verdicts; name the file in path");
7309
+ const text = JSON.stringify(parsed);
7310
+ if (!this.nameable(text) || this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("finding text was not cleared for the audit ledger: it matches a private-data pattern or the PII screen did not clear it");
7311
+ filed = parsed.map(finding => ({ finding, foundBy: by, at: when }));
7312
+ }
7313
+ if (input.verify !== undefined) {
7314
+ if (!Array.isArray(input.verify) || !input.verify.length || input.verify.length > 32) throw new PreEffectToolRefusal("verify is a list of 1 to 32 {finding, verdict: verified|rejected}");
7315
+ const stored = this.d.board.auditFindings(audit.id);
7316
+ for (const item of input.verify as unknown[]) {
7317
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
7318
+ if (!record || Object.keys(record).some(key => key !== "finding" && key !== "verdict") || typeof record.finding !== "string" || (record.verdict !== "verified" && record.verdict !== "rejected")) throw new PreEffectToolRefusal("each verify entry is {finding: <id>, verdict: verified|rejected}");
7319
+ const refusal = verificationRefusal(stored.find(row => row.finding.id === record.finding), by);
7320
+ if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
7321
+ decisions.push({ finding: record.finding, verdict: record.verdict });
7322
+ }
7323
+ if (new Set(decisions.map(d => d.finding)).size !== decisions.length) throw new PreEffectToolRefusal("a finding is decided once per call");
7324
+ }
7325
+ if (input.settle !== undefined) {
7326
+ if (!Array.isArray(input.settle) || !input.settle.length || input.settle.length > 32) throw new PreEffectToolRefusal("settle is a list of 1 to 32 {finding, disposition: fixed|false_positive}");
7327
+ const stored = this.d.board.auditFindings(audit.id);
7328
+ for (const item of input.settle as unknown[]) {
7329
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
7330
+ if (!record || Object.keys(record).some(key => key !== "finding" && key !== "disposition") || typeof record.finding !== "string" || !(SETTLEMENTS as readonly unknown[]).includes(record.disposition)) throw new PreEffectToolRefusal("each settle entry is {finding: <id>, disposition: fixed|false_positive}");
7331
+ const refusal = settlementRefusal(stored.find(row => row.finding.id === record.finding), by);
7332
+ if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
7333
+ settlements.push({ finding: record.finding, disposition: record.disposition as "fixed" | "false_positive" });
7334
+ }
7335
+ if (new Set(settlements.map(item => item.finding)).size !== settlements.length) throw new PreEffectToolRefusal("a finding is settled once per call");
7336
+ // A finding verified in this same call is not settled in it: the verification is a separate reader's decision and its result is read before the settlement.
7337
+ if (settlements.some(item => decisions.some(decision => decision.finding === item.finding))) throw new PreEffectToolRefusal("verify a finding and settle it in separate calls");
7338
+ }
7339
+ check();
7340
+ const now = this.d.board.audit(audit.id), nowTask = this.d.board.get(task.id);
7341
+ if (!now || !nowTask || nowTask.owner !== task.owner || nowTask.state !== task.state || JSON.stringify(now.units) !== JSON.stringify(audit.units)) throw new PreEffectToolRefusal("the audit changed while the report was checked; read it again and retry");
7342
+ // One transaction: a unit report, its findings, the verifications and the settlements land together or not at all.
7343
+ const skipped = this.d.board.auditApply(audit.id, { units: writes ? units : undefined, findings: filed, decisions, ...(settlements.length ? { settlements } : {}), by });
7344
+ if (skipped === undefined) throw new PreEffectToolRefusal("a finding was decided meanwhile; read the audit again and retry");
7345
+ try {
7346
+ const rejected = new Set(decisions.filter(row => row.verdict === "rejected").map(row => row.finding));
7347
+ const falsePositives = new Set(settlements.filter(row => row.disposition === "false_positive").map(row => row.finding));
7348
+ const savedAudit = this.d.board.audit(audit.id);
7349
+ if (savedAudit?.task === nowTask.id && savedAudit.taskCreated === nowTask.created) {
7350
+ const saved = this.d.board.auditFindings(audit.id).filter(row => rejected.has(row.finding.id) && row.rejectedBy === by
7351
+ || falsePositives.has(row.finding.id) && row.settledAs === "false_positive" && row.settledBy === by);
7352
+ this.recordConsideredAfter(nowTask, saved.map(row => row.finding), "audit", savedAudit.ref);
7353
+ }
7354
+ } catch { this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`); }
7355
+ const full = this.d.board.audit(audit.id)!;
7356
+ return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) };
7357
+ }
7358
+
6434
7359
  /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
6435
7360
  async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
6436
7361
  const check = this.requestCheck(by, fence);
@@ -6653,6 +7578,8 @@ export class Tasks {
6653
7578
  const publicShipped = this.d.board.releases().filter(release => !rowsNow.some(task => task.release === release.id && this.isPii(task)));
6654
7579
  const metrics = publicShipped.some(release => release.state === "shipped") ? releaseMetrics(publicShipped, rowsNow.filter(task => !this.isPii(task))) : undefined;
6655
7580
  if (metrics) report.releaseMetrics = metrics;
7581
+ const audit = this.auditLine();
7582
+ if (audit) report.securityAudit = audit;
6656
7583
  const trains = this.d.board.releases().filter(release => release.train && ["active", "frozen"].includes(release.state));
6657
7584
  if (trains.length) {
6658
7585
  const planned = trains.map(release => {
@@ -6688,13 +7615,13 @@ export class Tasks {
6688
7615
  return JSON.stringify([task.refs, task.sdlc, task.plan, task.owner, task.reviewer, task.state, this.isPii(task), this.d.sdlc?.config()]);
6689
7616
  }
6690
7617
  private planReadIdentity(task: Task): string { return JSON.stringify([task.sdlc?.repo, task.sdlc?.pr, task.refs.repo, planFingerprint(task.plan ?? {})]); }
6691
- private planPaths(task: Task): string[] | undefined {
7618
+ private planPaths(task: Task, key: "paths" | "out_of_scope" = "paths"): string[] | undefined {
6692
7619
  if (!task.sdlc?.repo) return;
6693
7620
  // Resolve the artifact slug first: it may warm the canonical project's previously unnamed identity.
6694
7621
  const artifact = this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths });
6695
7622
  const scope = this.repositories.scope(task.refs);
6696
7623
  if (scope.key !== artifact.key) return;
6697
- return task.plan?.paths?.map(path => scope === this.repositories.project ? this.projectPath(path) : this.repositories.relativePath(scope, path));
7624
+ return task.plan?.[key]?.map(path => scope === this.repositories.project ? this.projectPath(path) : this.repositories.relativePath(scope, path));
6698
7625
  }
6699
7626
  private planScopeIdentity(task: Task): string {
6700
7627
  const paths = this.planPaths(task); // Warm verified aliases before capturing the scope identity.
@@ -6709,8 +7636,18 @@ export class Tasks {
6709
7636
  return latest > invalidated && task.history[latest]!.planDeparture!.generation === this.departureGeneration
6710
7637
  && task.history[latest]!.planDeparture!.scope === this.planScopeIdentity(task) ? [task.history[latest]!.planDeparture!] : [];
6711
7638
  }
7639
+ /**
7640
+ * #1403 A2: whether this PR needs a recorded security pass, from the same complete file inventory plan conformance reads. The record is the latest one on a verdict of this task, bound to the head it
7641
+ * reviewed; `proposed` is the pass on the verdict being written (not on the board yet). A PII task and an off lifecycle compute nothing.
7642
+ */
7643
+ private securityView(task: Task, evidence: PrEvidence | undefined, proposed?: SecurityPassRecord): SecurityPassView | undefined {
7644
+ const config = this.d.sdlc?.config();
7645
+ if (!config || config.mode === "off" || !config.security || this.isPii(task)) return undefined;
7646
+ const recorded = proposed ?? task.history.findLast(entry => entry.securityPass && !entry.withheld && (entry.event === "approved" || entry.event === "changes_requested"))?.securityPass;
7647
+ return securityPassView(config.security, evidence, recorded);
7648
+ }
6712
7649
  private planReport(task: Task, evidence?: PrEvidence) {
6713
- const rawReport = planConformance(this.isPii(task) ? undefined : this.planPaths(task), this.isPii(task) ? undefined : evidence);
7650
+ const rawReport = planConformance(this.isPii(task) ? undefined : this.planPaths(task), this.isPii(task) ? undefined : evidence, this.planPaths(task, "out_of_scope") ?? task.plan?.out_of_scope);
6714
7651
  const safe = [...rawReport.outside, ...rawReport.untouched].every(path => this.publicMetadataText(path));
6715
7652
  const report: PlanConformance = safe ? rawReport : { state: "unknown", head: rawReport.head, outside: [], untouched: [] };
6716
7653
  const fingerprint = planFingerprint(task.plan ?? {});
@@ -6786,7 +7723,7 @@ export class Tasks {
6786
7723
  if (this.planIdentity(current) !== this.planIdentity(task) || current.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed during lifecycle readback");
6787
7724
  this.capturePlanRead(current, evidence);
6788
7725
  return sdlcStatus(config, current.sdlc, evidence, this.workflowView(current), edit, this.isPii(current) ? [] : this.reviewFindingSets(current), current.refs.commit,
6789
- config.mode !== "off" ? this.planReport(this.d.board.get(current.id)!, evidence) : undefined, integrity, evalResult);
7726
+ config.mode !== "off" ? this.planReport(this.d.board.get(current.id)!, evidence) : undefined, integrity, evalResult, this.securityView(current, evidence));
6790
7727
  }
6791
7728
 
6792
7729
  /** #481 S1: only build work starts from an accepted spec. */
@@ -6982,7 +7919,7 @@ export class Tasks {
6982
7919
 
6983
7920
  /** The eval record the last approval-time lifecycle read produced for a task; consumed by the verdict that follows it. */
6984
7921
  private readonly evalRecords = new Map<number, string>();
6985
- private async lifecycleGate(task: Task, transition: "review" | "approval", reviewedHead?: string, findings?: readonly ReviewFindingSet[], refileHead?: RefileHeadGuard): Promise<PrEvidence | undefined> {
7922
+ private async lifecycleGate(task: Task, transition: "review" | "approval", reviewedHead?: string, findings?: readonly ReviewFindingSet[], refileHead?: RefileHeadGuard, securityPass?: SecurityPassRecord): Promise<PrEvidence | undefined> {
6986
7923
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6987
7924
  if (config.mode === "off") return;
6988
7925
  const receipt = task.sdlc && { ...task.sdlc, ...(reviewedHead ? { reviewedHead } : {}) };
@@ -7020,7 +7957,7 @@ export class Tasks {
7020
7957
  if (current.history.length !== task.history.length || current.owner !== task.owner || current.reviewer !== task.reviewer || current.state !== task.state || this.isPii(current) !== this.isPii(task)) return;
7021
7958
  this.capturePlanRead(current, evidence);
7022
7959
  const planReport = this.planReport(current, evidence);
7023
- const status = sdlcStatus(config, receipt, evidence, this.workflowView(current), undefined, this.isPii(current) ? [] : findings ?? this.reviewFindingSets(current), current.refs.commit, planReport, integrity, evalResult);
7960
+ const status = sdlcStatus(config, receipt, evidence, this.workflowView(current), undefined, this.isPii(current) ? [] : findings ?? this.reviewFindingSets(current), current.refs.commit, planReport, integrity, evalResult, this.securityView(current, evidence, transition === "approval" ? securityPass : undefined));
7024
7961
  // #481 S5: review entry keeps the eval gate's own blockers (its check, and in enforce its evidence gaps), like the premature-review rule does for the ordinary required checks.
7025
7962
  const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name));
7026
7963
  const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker);
@@ -7030,7 +7967,7 @@ export class Tasks {
7030
7967
  const gate = status.evalGate;
7031
7968
  if (transition === "approval" && gate?.state === "passed" && gate.passRate !== undefined && gate.suite !== undefined && !this.isPii(task)) this.evalRecords.set(task.id, `Eval gate: ${gate.check} passed at ${evidence!.head.slice(0, 12)}, pass rate ${gate.passRate}, suite ${gate.suite}`);
7032
7969
  else this.evalRecords.delete(task.id);
7033
- const advice = [...new Set([...blockers, ...planConformanceBlockers(planReport), ...testIntegrityBlockers(integrity), ...evalAdvice(status.evalGate)])];
7970
+ const advice = [...new Set([...blockers, ...planConformanceBlockers(planReport), ...testIntegrityBlockers(integrity), ...evalAdvice(status.evalGate), ...securityPassBlockers(status.securityPass)])];
7034
7971
  if (config.mode === "advise" && advice.length) this.d.notify(`task ${this.publicTitle(task)}: SDLC ${transition} advice: ${this.isPii(task) ? "private lifecycle evidence unknown" : advice.join("; ")}`);
7035
7972
  return evidence;
7036
7973
  }
@@ -7061,7 +7998,7 @@ export class Tasks {
7061
7998
  const task = this.need(id, false, true);
7062
7999
  this.mine(task, by, "owner", true);
7063
8000
  if (by !== USER && task.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_ACCEPT(task.id)); // #1176: before any spec or plan-review work is spent on it
7064
- const proposedPlan = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev");
8001
+ const proposedPlan = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
7065
8002
  this.validatePlanSources(proposedPlan && Object.keys(proposedPlan).length ? proposedPlan : task.plan);
7066
8003
  this.acceptanceCapacity(task, 0, "check"); // #1080: an urgent task may still take unaccepted offers; `accept` does that, after its gates
7067
8004
  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");
@@ -7198,7 +8135,7 @@ export class Tasks {
7198
8135
  if (by !== USER && task.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_ACCEPT(task.id));
7199
8136
  if (task.state !== "proposed" && task.state !== "changes_requested" && task.state !== "in_progress") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state}: cannot move to in_progress`);
7200
8137
  // Models send null or {} for an optional field they leave empty: neither replaces a plan.
7201
- const given = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev");
8138
+ const given = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
7202
8139
  // File-list intent still replaces the old lists; omitted budget keys retain the planner-reviewed scope.
7203
8140
  const cleaned = given && Object.keys(given).length ? { ...cleanCostPlan(task.plan ?? {}), ...given } : undefined;
7204
8141
  this.validatePlanSources(cleaned ?? task.plan);
@@ -7290,7 +8227,8 @@ export class Tasks {
7290
8227
  takeDoneNote = (id: number): string | undefined => {
7291
8228
  const note = this.doneNotes.get(id);
7292
8229
  this.doneNotes.delete(id);
7293
- return note;
8230
+ const task = this.d.board.get(id);
8231
+ return [note, task ? this.planDriftText(task, "done") : ""].filter(Boolean).join("\n") || undefined;
7294
8232
  };
7295
8233
  /** #572 AC3: what the owner's `hub_task_done` result adds while the project root checkout is on a task branch. */
7296
8234
  checkoutNote = (): string | undefined => { const warning = mainCheckoutWarning(this.d.cwd, this.publicMetadataText); return warning ? `Note: ${warning}.` : undefined; };
@@ -7535,10 +8473,11 @@ export class Tasks {
7535
8473
  }
7536
8474
 
7537
8475
  async done(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
8476
+ const observerExcluded = this.observerExcluded(by);
7538
8477
  const requestCheck = this.requestCheck(by);
7539
8478
  const initial = this.need(id, false, true);
7540
8479
  this.mine(initial, by, "owner", true);
7541
- const reviewObserverTurn = this.reviewObserverTurn(by, initial.id);
8480
+ const reviewObserverTurn = observerExcluded || this.reviewObserverTurn(by, initial.id);
7542
8481
  const resolvedReviewComments = this.reviewCommentResolve(by, initial, resolved);
7543
8482
  let refresh: CompletionRefresh | undefined;
7544
8483
  if (initial.state === "in_review" || initial.state === "approved") {
@@ -7565,7 +8504,7 @@ export class Tasks {
7565
8504
  // #509a: a bad claim (a claimed hash, an outside or denied path, a missing file) is refused before any effect, with nothing recorded.
7566
8505
  const claims = deliverables === undefined ? undefined : this.deliverableClaims(deliverables, valid());
7567
8506
  // The PII screen reads the summary of a done that passes these checks (issue #198); they run again after it.
7568
- const withheld = await this.withholds("summary", summary, valid());
8507
+ const withheld = observerExcluded || await this.withholds("summary", summary, valid());
7569
8508
  let task = valid();
7570
8509
  // The hub hashes the files itself, once, here: what the owner delivered is what this read, whatever the file becomes afterwards.
7571
8510
  const records = claims ? await this.hashClaims(claims, task, true) : undefined;
@@ -7641,7 +8580,7 @@ export class Tasks {
7641
8580
  const seen = { events: pending.history.length, owner: pending.owner };
7642
8581
  this.pendingChecks++;
7643
8582
  this.checkQueue = this.checkQueue
7644
- .then(() => this.finishChecked(pending.id, by, summary, command, seen, withheld, specInspection, resolvedReviewComments, reviewObserverTurn))
8583
+ .then(() => this.finishChecked(pending.id, by, summary, command, seen, withheld, specInspection, resolvedReviewComments, reviewObserverTurn, observerExcluded))
7645
8584
  .catch((e: Error) => {
7646
8585
  this.releaseNotice(`task #${pending.id}: its check result could not be recorded: ${e.message}`);
7647
8586
  this.releaseNotice(`task #${pending.id}: its owner retry notice could not be published`, () => {
@@ -7744,7 +8683,7 @@ export class Tasks {
7744
8683
  return { ...(key ? { checkKey: key } : {}), ...(match ? { missingKeys: Number(match[2]) } : {}) };
7745
8684
  }
7746
8685
 
7747
- private async finishChecked(id: number, by: PeerId, summary: string | undefined, command: string, seen: { events: number; owner: PeerId | null }, withheld: boolean, specInspection: PreparedSpecInspection, resolvedReviewComments?: string[], reviewObserverExcluded = false): Promise<void> {
8686
+ private async finishChecked(id: number, by: PeerId, summary: string | undefined, command: string, seen: { events: number; owner: PeerId | null }, withheld: boolean, specInspection: PreparedSpecInspection, resolvedReviewComments?: string[], reviewObserverExcluded = false, evidenceObserverExcluded = false): Promise<void> {
7748
8687
  const result = await this.d.runCheck!(command).catch((e: Error) => ({ code: null, timedOut: false, interrupted: false, tail: e.message }));
7749
8688
  const checkOwner = this.checking.get(id);
7750
8689
  this.checking.delete(id);
@@ -7781,7 +8720,7 @@ export class Tasks {
7781
8720
  if (task.owner) this.d.board.recordOutcome(task.owner, task.class, false);
7782
8721
  this.contradict(task);
7783
8722
  this.d.notify(`task ${this.publicTitle(task)}: its check failed (${outcome}); it stays with ${task.owner ?? by}`);
7784
- this.tell(task, `Task #${id}: its check failed.\n$ ${outcome}${result.tail ? `\n${result.tail}` : ""}\nFix it and call hub_task_done again.`, pii, "owner", this.reviewObserverTurn(by, id));
8723
+ this.tell(task, `Task #${id}: its check failed.\n$ ${outcome}${!evidenceObserverExcluded && result.tail ? `\n${result.tail}` : ""}\nFix it and call hub_task_done again.`, pii, "owner", this.reviewObserverTurn(by, id));
7785
8724
  }
7786
8725
 
7787
8726
  /** `gated`: the transition `done()` already gated with no await since, so it is not read back twice (#382). */
@@ -7796,7 +8735,8 @@ export class Tasks {
7796
8735
  let selection = this.poolReview(task, refs);
7797
8736
  let reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined), reviewEvidence: PrEvidence | undefined;
7798
8737
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off" && gated !== (reviewer ? "review" : "approval")) {
7799
- reviewEvidence = await this.lifecycleGate(task, reviewer ? "review" : "approval");
8738
+ // #1435: the head this done submits is the head the gate compares with the PR. `refs.commit` still holds the earlier head until the done is written, so an approval-path gate (no reviewer after an escalation) would refuse the very head its refusal names.
8739
+ reviewEvidence = await this.lifecycleGate(draft?.commit ? { ...task, refs: { ...task.refs, commit: draft.commit } } : task, reviewer ? "review" : "approval");
7800
8740
  requestCheck();
7801
8741
  task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, false, refresh), draft), link, refs);
7802
8742
  if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; }
@@ -7814,7 +8754,7 @@ export class Tasks {
7814
8754
  reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined);
7815
8755
  const reviewCost: ReviewCost | undefined = reviewer && task.plan && (task.plan.review || task.plan.ci)
7816
8756
  ? { ...cleanCostPlan(task.plan), ...(admission?.ready && admission.head ? { head: admission.head } : {}) } : undefined;
7817
- const routedSummary = selection?.reviewSelection?.blocked ? `${summary ?? ""}\nReview routing: ${this.assignmentNote("pool unavailable", selection)}`.trim() : summary;
8757
+ const routedSummary = selection?.reviewSelection && (selection.reviewSelection.blocked || selection.reviewSelection.admissionRule) ? `${summary ?? ""}\nReview routing: ${this.assignmentNote(selection.reviewSelection.blocked ? "pool unavailable" : "pool selected", selection)}`.trim() : summary;
7818
8758
  if (refresh?.state === "approved") {
7819
8759
  await this.unmergedForReopen(task, () => { requestCheck(); return this.completionCurrent(task.id, by, true, refresh); });
7820
8760
  task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, true, refresh), draft), link, refs);
@@ -7833,7 +8773,8 @@ export class Tasks {
7833
8773
  const noWrites = this.noWritesRecorded({ ...task, refs: storedRefs });
7834
8774
  const capacity = this.capacityBefore(task);
7835
8775
  reviewObserverExcluded ||= this.reviewObserverTurn(by, task.id);
7836
- const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...task.sdlc, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge") } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
8776
+ const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined;
8777
+ const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: quotaWaiting ? null : reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...task.sdlc, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge") } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, state: "in_review", refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
7837
8778
  this.queueReviewWritten(next);
7838
8779
  this.writePlannerNotices(next, capacity, next.state === "approved");
7839
8780
  this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); // a newer head or a move ends the old head's watcher (#785 P1b)
@@ -7847,9 +8788,10 @@ export class Tasks {
7847
8788
  this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}, no reviewer: approved`);
7848
8789
  await this.releaseDependents(next);
7849
8790
  }
8791
+ else if (quotaWaiting) this.releaseNotice(`task ${this.publicTitle(next)}: waiting for reviewer quota reset`);
7850
8792
  else if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}: review it in the ahub console (Tasks, select #${next.id}, press r) or with ahub review ${next.id} approved|changes_requested [note]`);
7851
8793
  else this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, "", admission));
7852
- if (reviewer && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next);
8794
+ if (reviewer && !quotaWaiting && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next);
7853
8795
  return next;
7854
8796
  }
7855
8797
 
@@ -7940,10 +8882,34 @@ export class Tasks {
7940
8882
  } catch { return []; } // Optional memory cannot refuse an assignment or review.
7941
8883
  }
7942
8884
 
8885
+ /** #1403 B1: no checkout-HEAD fallback, foreign repository read or admission effect. */
8886
+ private planDriftText(task: Task, stage: "accept" | "done"): string {
8887
+ if ((this.d.sdlc?.config().mode ?? "off") === "off" || !task.plan?.base || this.isPii(task) || task.owner && this.d.privateTurn?.(task.owner)) return "";
8888
+ let report: import("./plan-conformance.ts").PlanDrift = { state: "unknown", paths: [] };
8889
+ try {
8890
+ const source = this.d.auditSource, base = task.plan.base;
8891
+ if (source?.defaultTip && source.mergeBase && /^[a-f0-9]{40}$/.test(base)
8892
+ && this.repositories.scope(task.refs).key === this.repositories.project.key
8893
+ && (!task.sdlc?.repo || this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths }).key === this.repositories.project.key)
8894
+ && source.resolve(base) === base) {
8895
+ const tip = source.defaultTip(), head = stage === "done" ? this.reviewHead(task) : undefined;
8896
+ const endpoint = tip && /^[a-f0-9]{40}$/.test(tip) && source.resolve(tip) === tip
8897
+ ? stage === "accept" ? tip : head && /^[a-f0-9]{40}$/.test(head) && source.resolve(head) === head ? source.mergeBase(head, tip) : undefined
8898
+ : undefined;
8899
+ if (endpoint && /^[a-f0-9]{40}$/.test(endpoint) && source.resolve(endpoint) === endpoint && source.mergeBase(base, endpoint) === base) {
8900
+ report = planDrift(task.plan.paths?.map(path => this.projectPath(path)), source.changed(base, endpoint));
8901
+ if (source.defaultTip() !== tip) report = { state: "unknown", paths: [] };
8902
+ }
8903
+ }
8904
+ if (report.paths.some(path => !this.publicMetadataText(path))) report = { state: "unknown", paths: [] };
8905
+ } catch { /* Optional local Git evidence is unknown, never a failed task transition. */ }
8906
+ return `Plan drift at ${stage} (upstream advice only): drift: ${report.state}${report.paths.length ? ` (${report.paths.join("; ")})` : ""}`;
8907
+ }
8908
+
7943
8909
  /** Current plan advice for an accepted plan's tool result, which has no new assignment envelope. */
7944
8910
  planGuardText(task: Task): string {
7945
8911
  const items = this.planGuardItems(task);
7946
- return items.length ? ["Live fail notes for this plan (advice, not a block):", ...items.map(item => item.line)].join("\n") : "";
8912
+ return [this.planDriftText(task, "accept"), items.length ? ["Live fail notes for this plan (advice, not a block):", ...items.map(item => item.line)].join("\n") : ""].filter(Boolean).join("\n");
7947
8913
  }
7948
8914
 
7949
8915
  /** The one place a review request is written: the first reviewer and a replacement get the same text, refs and privacy. */
@@ -8045,6 +9011,9 @@ export class Tasks {
8045
9011
  const cachedPlanRead = this.planReads.get(task.id);
8046
9012
  const planRead = this.planReport(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined);
8047
9013
  const conformanceText = mode !== "off" ? this.screen(task, `Plan conformance: ${JSON.stringify(planRead)}`, "plan conformance", reviewer) + "\n" : "";
9014
+ // #1403 A2: from the same cached PR read as plan conformance. No cached read is `unknown`, never "not required", so a missing readback still points the reviewer at the checklist.
9015
+ const securityLine = mode !== "off" ? securityRequestLine(this.securityView(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined)) : undefined;
9016
+ const securityText = securityLine ? this.screen(task, securityLine, "security pass", reviewer) + "\n" : "";
8048
9017
  const profile = (task.profile ?? "dev") === (this.d.profile ?? "dev") ? profileData(this.d.profileData ?? task.profile ?? "dev") : profileData(task.profile);
8049
9018
  const target = plan ? `the plan (${plan})` : task.detail ? "the task detail above" : "the task title";
8050
9019
  const noCheckWording = profile.name === "research" || profile.name === "writing"
@@ -8114,7 +9083,7 @@ export class Tasks {
8114
9083
  const brief = this.briefText(task);
8115
9084
  // #572 AC3: advisory only, from git state never from task text, so it is safe for a PII task too.
8116
9085
  const checkout = mainCheckoutWarning(this.d.cwd, this.publicMetadataText);
8117
- const body = `Review task #${task.id} [${profileTaskLabel(task)}] ${task.title}\nDone by ${last?.by ?? task.owner}: ${summary}\n${where ? `Where: ${where}\n` : ""}${last?.noWrites ? "no writes recorded since acceptance\n" : ""}${spec}${why ? `${why}\n` : ""}${!plan && task.detail ? `Task detail:\n${task.detail}\n` : ""}${guidance ? guidance + "\n" : ""}${projection ? projection + "\n" : ""}${brief ? brief + "\n" : ""}${checkout ? `Note: ${checkout}.\n` : ""}${findings.length ? `Earlier findings (set a disposition for each):\n${findings.join("\n")}\n` : ""}${carriedText}${conformanceText}${rulingsBlock}${verified}${checklist}\nGive your verdict with hub_review {id: ${task.id}, verdict: "approved" | "changes_requested", note, unmet, findings: [{id, pass: "bugs" | "security" | "compliance", severity: "important" | "nit", path?, disposition: "open" | "fixed" | "false_positive"}]}. Reuse finding ids when updating their disposition; only the person may accept a finding with a rationale.`;
9086
+ const body = `Review task #${task.id} [${profileTaskLabel(task)}] ${task.title}\nDone by ${last?.by ?? task.owner}: ${summary}\n${where ? `Where: ${where}\n` : ""}${last?.noWrites ? "no writes recorded since acceptance\n" : ""}${spec}${why ? `${why}\n` : ""}${!plan && task.detail ? `Task detail:\n${task.detail}\n` : ""}${guidance ? guidance + "\n" : ""}${projection ? projection + "\n" : ""}${brief ? brief + "\n" : ""}${checkout ? `Note: ${checkout}.\n` : ""}${findings.length ? `Earlier findings (set a disposition for each):\n${findings.join("\n")}\n` : ""}${carriedText}${conformanceText}${securityText}${rulingsBlock}${verified}${checklist}\nGive your verdict with hub_review {id: ${task.id}, verdict: "approved" | "changes_requested", note, unmet, findings: [{id, pass: "bugs" | "security" | "compliance", severity: "important" | "nit", path?, disposition: "open" | "fixed" | "false_positive"}]}. Reuse finding ids when updating their disposition; only the person may accept a finding with a rationale.`;
8118
9087
  const comments = this.d.board.reviewCommentCounts(task.id, task.created);
8119
9088
  const quoteMaterial = task.history.some(entry => entry.reviewFindings?.items.some(item => item.anchor !== undefined))
8120
9089
  || comments.sent + comments.resolved + comments.dismissed > 0;
@@ -8180,7 +9149,84 @@ export class Tasks {
8180
9149
  }
8181
9150
 
8182
9151
  /** Daemon shutdown: no watcher outlives the hub. */
8183
- stopCiWatchers(): void { this.ciWatchers.stopAll(); this.heldReviews.clear(); }
9152
+ private readonly reviewerQuotaTimers = new Map<number, { key: string; timer: ReturnType<typeof setTimeout> }>();
9153
+ private readonly reviewerQuotaRunning = new Set<number>();
9154
+ private reviewerQuotaStopped = false;
9155
+ private priorReviewerQuotaWait(task: Task): NonNullable<ReviewerHistory["reviewerQuotaWait"]> | undefined {
9156
+ const binding = this.queueReviewBinding(task), firstReview = task.history.findIndex(row => row.event === "done");
9157
+ // Role routing before the first completion never starts a review deadline.
9158
+ return firstReview < 0 ? undefined : task.history.slice(firstReview).findLast(row => row.reviewerQuotaWait?.created === task.created && row.reviewerQuotaWait.binding === binding)?.reviewerQuotaWait;
9159
+ }
9160
+ private activeReviewerQuotaWait(task: Task): NonNullable<ReviewerHistory["reviewerQuotaWait"]> | undefined {
9161
+ const role = task.history[this.reviewRequestRevision(task) - 1];
9162
+ return task.state === "in_review" && task.reviewer === null && !this.isPii(task) && !this.manuallyNamedReviewer(task)
9163
+ && role?.reviewerQuotaWait?.created === task.created && role.reviewerQuotaWait.binding === this.queueReviewBinding(task)
9164
+ ? role.reviewerQuotaWait : undefined;
9165
+ }
9166
+ /** Host board-change hook: a changed head/incarnation/privacy/role cancels the old deadline immediately. */
9167
+ reviewQuotaTaskChanged(task: Task): void {
9168
+ const wait = this.activeReviewerQuotaWait(task), prior = this.reviewerQuotaTimers.get(task.id);
9169
+ const key = wait ? JSON.stringify([task.created, wait.binding, wait.since, wait.deadline, wait.resetAt, this.reviewRequestRevision(task)]) : undefined;
9170
+ if (prior?.key === key) return;
9171
+ if (prior) clearTimeout(prior.timer);
9172
+ this.reviewerQuotaTimers.delete(task.id);
9173
+ if (!wait || this.reviewerQuotaStopped || this.studyHold()) return;
9174
+ const now = this.d.now?.() ?? Date.now();
9175
+ const wake = wait.resetAt > now ? wait.resetAt : wait.resetAt + 60_000 > now ? wait.resetAt + 60_000 : wait.deadline;
9176
+ const timer = setTimeout(() => {
9177
+ if (this.reviewerQuotaTimers.get(task.id)?.key !== key) return;
9178
+ this.reviewerQuotaTimers.delete(task.id);
9179
+ void this.refreshReviewerQuotaWait(task.id).catch(() => {});
9180
+ }, Math.min(2_147_483_647, Math.max(0, Math.min(wait.deadline, wake) - now)));
9181
+ timer.unref?.(); this.reviewerQuotaTimers.set(task.id, { key: key!, timer });
9182
+ }
9183
+ /** Reading/reset signals and recovery release call this; no quota polling or native transport is added. */
9184
+ refreshReviewerQuotaWaits(): void {
9185
+ if (this.reviewerQuotaStopped || this.studyHold()) return;
9186
+ for (const task of this.d.board.list("in_review")) {
9187
+ this.reviewQuotaTaskChanged(task);
9188
+ if (this.activeReviewerQuotaWait(task)) void this.refreshReviewerQuotaWait(task.id).catch(() => {});
9189
+ }
9190
+ }
9191
+ private async refreshReviewerQuotaWait(id: number): Promise<void> {
9192
+ if (this.reviewerQuotaStopped || this.reviewerQuotaRunning.has(id) || this.studyHold()) return;
9193
+ this.reviewerQuotaRunning.add(id);
9194
+ try { await this.studyWrite(async () => {
9195
+ const before = this.d.board.get(id), wait = before && this.activeReviewerQuotaWait(before);
9196
+ if (!before || !wait) return;
9197
+ const revision = this.reviewRequestRevision(before), identity = JSON.stringify([before.created, wait.binding, wait.since, wait.deadline]);
9198
+ const valid = () => {
9199
+ const task = this.d.board.get(id), live = task && this.activeReviewerQuotaWait(task);
9200
+ return !this.reviewerQuotaStopped && !this.studyHold() && task && live && this.reviewRequestRevision(task) === revision
9201
+ && JSON.stringify([task.created, live.binding, live.since, live.deadline]) === identity ? task : undefined;
9202
+ };
9203
+ const choose = (task: Task) => assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}) });
9204
+ let selection = choose(before);
9205
+ if (selection.reviewSelection?.quotaWait) {
9206
+ if (selection.reviewSelection.quotaWait.resetsAt !== wait.resetAt) {
9207
+ const next = this.d.board.update(before.id, HUB, "reviewer changed", { reviewer: null }, this.assignmentNote("reviewer quota reset observation changed", selection), this.reviewMetadata(selection, before), before.history.length);
9208
+ this.queueReviewWritten(next);
9209
+ } else this.reviewQuotaTaskChanged(before);
9210
+ return;
9211
+ }
9212
+ let admission: ReviewReadiness | undefined, admissionFailed = false;
9213
+ // Ending an account wait is not permission to send native review input. A person fallback needs no native admission.
9214
+ if (selection.reviewer && selection.reviewer !== USER) {
9215
+ try { admission = await this.reviewRequestAdmission(before, undefined, true, before.owner ?? USER, undefined, () => !!valid()); }
9216
+ catch { admissionFailed = true; }
9217
+ }
9218
+ const task = valid(); if (!task) return;
9219
+ selection = choose(task);
9220
+ if (selection.reviewSelection?.quotaWait) { this.reviewQuotaTaskChanged(task); return; }
9221
+ // Failed readiness/authority never sends native facts, but cannot extend the original quota deadline.
9222
+ const reviewer = admissionFailed ? USER : selection.reviewer ?? USER;
9223
+ const next = this.d.board.update(task.id, HUB, "reviewer changed", { reviewer }, this.assignmentNote("reviewer quota wait ended", selection), this.reviewMetadata(selection, task), task.history.length);
9224
+ this.queueReviewWritten(next);
9225
+ if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)}: reviewer quota wait ended; the person must review`);
9226
+ else this.releaseNotice(`task ${this.publicTitle(next)}: review request unavailable after quota wait`, () => this.sendReview(next, reviewer, "", admission));
9227
+ }); } finally { this.reviewerQuotaRunning.delete(id); }
9228
+ }
9229
+ stopCiWatchers(): void { this.ciWatchers.stopAll(); this.heldReviews.clear(); this.reviewerQuotaStopped = true; for (const row of this.reviewerQuotaTimers.values()) clearTimeout(row.timer); this.reviewerQuotaTimers.clear(); }
8184
9230
 
8185
9231
  private reviewRequestRevision(task: Task): number {
8186
9232
  // Role changes fence older requests; bookkeeping appended after the request does not.
@@ -8196,7 +9242,7 @@ export class Tasks {
8196
9242
  }
8197
9243
 
8198
9244
  /** Host-only failure report, bound to the exact review request and its still-current child generation. */
8199
- async retryReviewer(id: number, failedPeer: PeerId, failure: { head?: string; flowRevision?: number; cause: "start_failed" | "quota" | "no_verdict" }, current: () => boolean, onReoffered?: () => void): Promise<Task> {
9245
+ async retryReviewer(id: number, failedPeer: PeerId, failure: { head?: string; flowRevision?: number; cause: "start_failed" | "quota" | "no_verdict"; reason?: "review time cap" }, current: () => boolean, onReoffered?: () => void): Promise<Task> {
8200
9246
  requireLocalTaskPeer(failedPeer);
8201
9247
  if (!failure || !["start_failed", "quota", "no_verdict"].includes(failure.cause) || !/^[a-z][a-z0-9-]{0,63}$/.test(failedPeer) || !Number.isSafeInteger(failure.flowRevision) || failure.flowRevision! < 1 || failure.head !== undefined && (typeof failure.head !== "string" || text(failure.head) !== failure.head || Buffer.byteLength(failure.head) > 1200 || /\p{Cc}/u.test(failure.head))) throw new PreEffectToolRefusal("invalid reviewer failure binding");
8202
9248
  const valid = () => {
@@ -8210,17 +9256,19 @@ export class Tasks {
8210
9256
  const options = this.reviewPoolOptions(task);
8211
9257
  // A person-selected reviewer never falls through to an agent the person did not select.
8212
9258
  const manual = this.manuallyNamedReviewer(task);
8213
- const selection = manual ? undefined : assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), reviewPool: { ...options, failed: [...options.failed, failedPeer] } });
9259
+ const selection = manual ? undefined : assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), reviewPool: { ...options, failed: failure.cause === "quota" ? options.failed : [...options.failed, failedPeer] } });
8214
9260
  if (!selection?.reviewSelection && failure.cause !== "no_verdict") throw new PreEffectToolRefusal("no declared reviewer pool can receive the fallback");
9261
+ const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined;
8215
9262
  const reviewer = selection?.reviewSelection ? selection.reviewer ?? USER : USER;
8216
9263
  valid();
8217
9264
  const note = manual ? "named reviewer recorded no verdict; the person must review"
8218
- : selection?.reviewSelection ? this.assignmentNote(`reviewer unavailable: ${failure.cause}`, selection) : "no declared reviewer pool can receive the fallback; the person must review";
8219
- const next = this.d.board.update(task.id, HUB, "reviewer unavailable", { reviewer }, note, { ...this.reviewMetadata(selection, task), ...(reviewer === USER ? { reviewBlocked: true } : {}), reviewerFailure: { peer: failedPeer, cause: failure.cause, ...(failure.head ? { head: failure.head } : {}) } }, task.history.length);
9265
+ : selection?.reviewSelection ? this.assignmentNote(`reviewer unavailable: ${failure.reason ?? failure.cause}`, selection) : "no declared reviewer pool can receive the fallback; the person must review";
9266
+ const next = this.d.board.update(task.id, HUB, "reviewer unavailable", { reviewer: quotaWaiting ? null : reviewer }, note, { ...this.reviewMetadata(selection, task), ...(reviewer === USER ? { reviewBlocked: true } : {}), reviewerFailure: { peer: failedPeer, cause: failure.cause, ...(failure.reason ? { reason: failure.reason } : {}), ...(failure.head ? { head: failure.head } : {}) } }, task.history.length);
8220
9267
  this.queueReviewWritten(next);
8221
9268
  this.releaseNotice(`task ${this.publicTitle(next)}: former review request withdrawal incomplete`, () => this.withdrawRoleRequest(task, next, "reviewer"));
8222
- let offered = false;
8223
- if (reviewer === USER) {
9269
+ let offered = quotaWaiting;
9270
+ if (quotaWaiting) { try { onReoffered?.(); } catch { /* The saved wait remains authoritative. */ } }
9271
+ else if (reviewer === USER) {
8224
9272
  const notice = `task ${this.publicTitle(next)}: blocked: the person must review`;
8225
9273
  this.releaseNotice(notice, () => { this.d.notify(notice); offered = true; });
8226
9274
  } else this.releaseNotice(`task ${this.publicTitle(next)}: fallback review request unavailable`, () => { offered = this.sendReview(next, reviewer, "", admission); });
@@ -8300,11 +9348,12 @@ export class Tasks {
8300
9348
  } catch { return prefix("Review brief unavailable: it could not be built."); }
8301
9349
  }
8302
9350
 
8303
- async review(by: PeerId, id: unknown, verdict: unknown, note?: string, unmet?: unknown, head?: unknown, coverage?: unknown, findings?: unknown): Promise<Task> {
9351
+ async review(by: PeerId, id: unknown, verdict: unknown, note?: string, unmet?: unknown, head?: unknown, coverage?: unknown, findings?: unknown, securityPass?: unknown): Promise<Task> {
8304
9352
  if (by !== USER && hasReviewAnchorInput(findings)) {
8305
9353
  try { this.d.onReviewObserverInput?.(by); }
8306
9354
  catch { throw new PreEffectToolRefusal("the anchored review input could not be privately scoped; retry after ordinary new input"); }
8307
9355
  }
9356
+ const evidenceObserverExcluded = this.observerExcluded(by);
8308
9357
  const requestCheck = this.requestCheck(by);
8309
9358
  if (typeof id !== "number" && !(typeof id === "string" && /^\s*\d+\s*$/.test(id))) this.need(id, false, true);
8310
9359
  const authority = by === USER ? undefined : this.d.reviewAuthority?.(by, Number(id));
@@ -8345,12 +9394,19 @@ export class Tasks {
8345
9394
  if (withdrawing) withdrawalRevision = initial.history.length;
8346
9395
  if (withdrawing) { await this.unmergedForReopen(initial, valid); valid(); }
8347
9396
  let parsed: ReviewFinding[];
8348
- try { parsed = parseReviewFindings(findings, { person: by === USER, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS }); }
9397
+ try { parsed = parseReviewFindings(findings, { person: by === USER, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: mode === "off" ? "off" : "required" }); }
8349
9398
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid structured findings"); }
9399
+ // #1403 A2: the field exists only under an enabled lifecycle (off neither advertises nor accepts it), and only on a verdict that can carry it. Validated before any board effect.
9400
+ let securityRecord: SecurityPassRecord | undefined;
9401
+ if (securityPass !== undefined) {
9402
+ if (mode === "off") throw new PreEffectToolRefusal("security_pass is not available: the lifecycle is off (set sdlc.mode to advise or enforce in .agenthub/sdlc.toml)");
9403
+ try { securityRecord = parseSecurityPass(securityPass); }
9404
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid security_pass"); }
9405
+ }
8350
9406
  const anchorPrivacy = new Map(parsed.flatMap(item => item.anchor ? [[item.anchor.path, this.reviewPathPrivate(item.anchor.path)] as const] : []));
8351
9407
  try { parsed = parsed.map(item => item.anchor && anchorPrivacy.get(item.anchor.path) ? { ...item, anchor: privateReviewAnchor(item.anchor) } : item); }
8352
9408
  catch { throw new PreEffectToolRefusal("private finding path needs an existing lineRange or structural selector; remove quoted selectors and retry"); }
8353
- const observerExcluded = reviewObserverTurn || parsed.some(item => item.anchor !== undefined);
9409
+ const observerExcluded = evidenceObserverExcluded || reviewObserverTurn || parsed.some(item => item.anchor !== undefined);
8354
9410
  // #852 AC3 (amended): a code-scope reviewer's changes_requested is always recorded, never refused. Without an open structured finding it is
8355
9411
  // evidence-only: it does not count toward rejections or escalation, the task returns to its owner as usual, and the conductor gets one ids-only
8356
9412
  // notice. The rule is structural (a finding with disposition open), never a reading of the unmet text.
@@ -8411,7 +9467,7 @@ export class Tasks {
8411
9467
  path: anchor.path, ...(anchor.side ? { side: anchor.side } : {}), ...(anchor.contentHash ? { contentHash: anchor.contentHash } : {}),
8412
9468
  ...(anchor.projection ? { projection: anchor.projection } : {}),
8413
9469
  } } : {}) }));
8414
- const withheld = await this.withholds("review note", parsed.length ? JSON.stringify({ note, findings: screenFindings }) : note, valid())
9470
+ const withheld = evidenceObserverExcluded || await this.withholds("review note", parsed.length ? JSON.stringify({ note, findings: screenFindings }) : note, valid())
8415
9471
  || parsed.length > 0 && !this.findingTextAllowed(initial, parsed);
8416
9472
  let task = valid();
8417
9473
  let reviewedHead: string | undefined;
@@ -8443,7 +9499,7 @@ export class Tasks {
8443
9499
  }
8444
9500
  if (verdict === "approved" && this.d.sdlc && this.d.sdlc.config().mode !== "off") {
8445
9501
  this.evalRecords.delete(task.id);
8446
- await this.lifecycleGate(task, "approval", reviewedHead, proposedSets(task)); task = valid();
9502
+ await this.lifecycleGate(task, "approval", reviewedHead, proposedSets(task), undefined, securityRecord && { ...securityRecord, head: reviewedHead ?? findingHead }); task = valid();
8447
9503
  const record = this.evalRecords.get(task.id); this.evalRecords.delete(task.id);
8448
9504
  if (record) note = `${note ?? ""}\n${record}`.trim();
8449
9505
  } else if (verdict === "approved" && this.d.sdlc?.config().mode === "off" && this.d.sdlc?.gh && task.sdlc?.repo && task.sdlc.pr
@@ -8474,11 +9530,12 @@ export class Tasks {
8474
9530
  // #507b: unmet items that start with a recorded criterion id name that criterion. The ids come from the checklist on the board as it is at this
8475
9531
  // write (the `task` just rechecked by valid()), never from the caller; a PII task carries none, its checklist being private.
8476
9532
  const unmetCriteria = pii ? [] : unmetCriteriaIds(items, checklistOf(task.sdlc));
8477
- const flag = { ...(findingHead ? { reviewedHead: findingHead } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(report ? { reviewFindings: report } : {}), ...(unmetCriteria.length ? { unmetCriteria } : {}), ...(boundDeliverables ? { deliverables: boundDeliverables } : {}), ...(reviewContext ? { reviewContext } : {}), ...(codeScope ? { reviewScope: "code" as const } : {}), ...(evidenceOnly ? { evidenceOnly: true as const } : {}), ...(reviewerFamily ? { reviewerFamily } : {}), ...(reviewerReason ? { reviewerReason } : {}) };
9533
+ const flag = { ...(findingHead ? { reviewedHead: findingHead } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(report ? { reviewFindings: report } : {}), ...(securityRecord && !pii ? { securityPass: { ...securityRecord, ...((reviewedHead ?? findingHead) ? { head: (reviewedHead ?? findingHead)! } : {}) } } : {}), ...(unmetCriteria.length ? { unmetCriteria } : {}), ...(boundDeliverables ? { deliverables: boundDeliverables } : {}), ...(reviewContext ? { reviewContext } : {}), ...(codeScope ? { reviewScope: "code" as const } : {}), ...(evidenceOnly ? { evidenceOnly: true as const } : {}), ...(reviewerFamily ? { reviewerFamily } : {}), ...(reviewerReason ? { reviewerReason } : {}) };
8478
9534
  if (verdict === "approved") {
8479
9535
  const capacity = this.capacityBefore(task);
8480
9536
  this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
8481
9537
  const next = this.d.board.update(task.id, by, "approved", { state: "approved", rejections: 0, ...(reviewedHead && task.sdlc ? { sdlc: { ...task.sdlc, reviewedHead, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), "merge") } } : {}) }, note, flag);
9538
+ this.recordConsideredAfter(next, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
8482
9539
  this.writePlannerNotices(next, capacity, next.state === "approved");
8483
9540
  if (next.owner) {
8484
9541
  this.d.board.recordOutcome(next.owner, next.class, true);
@@ -8496,11 +9553,13 @@ export class Tasks {
8496
9553
  this.autoMerge(next, this.mirrorVerdict(next, by, "approved", reviewedHead ?? next.sdlc?.reviewedHead, note, withheld || observerExcluded));
8497
9554
  // A proposal storage failure cannot roll back the saved verdict; another matching verdict retries it.
8498
9555
  this.releaseNotice(`task #${next.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(next, by, parsed, withheld));
9556
+ this.releaseNotice(`task #${next.id}: review saved but finding follow-up proposal unavailable`, () => this.proposeFindingFollowUps(next, by, withheld));
8499
9557
  this.releaseNotice(`task #${next.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(next, by, withheld));
8500
9558
  return next;
8501
9559
  }
8502
9560
  this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
8503
9561
  const rejected = this.d.board.update(task.id, by, "changes_requested", { state: "changes_requested", rejections: evidenceOnly ? task.rejections : task.rejections + 1 }, note, flag, task.history.length);
9562
+ this.recordConsideredAfter(rejected, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
8504
9563
  void this.mirrorVerdict(rejected, by, "changes_requested", reviewedHead ?? rejected.sdlc?.reviewedHead, note, withheld || observerExcluded);
8505
9564
  if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(rejected, by, parsed, withheld));
8506
9565
  if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(rejected, by, withheld));
@@ -8805,8 +9864,8 @@ export class Tasks {
8805
9864
  current?.();
8806
9865
  moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner, role: "owner" });
8807
9866
  } else if (task.reviewer === peer && !isClosedTaskState(task.state)) {
8808
- const a = assign(task, this.states(), routing, { exclude: [peer], candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
8809
- const reviewer = a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
9867
+ const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
9868
+ const reviewer = !a.reviewSelection?.quotaWait && a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
8810
9869
  if (roster && !reviewer) {
8811
9870
  this.releaseNotice(`task ${this.publicTitle(task)}: its reviewer ${peer} is off roster and nobody else can review; the reviewer stays ${peer}; use ahub review ${task.id}`);
8812
9871
  continue;
@@ -8819,7 +9878,7 @@ export class Tasks {
8819
9878
  if (next.state === "in_review" && reviewer && reviewer !== USER) {
8820
9879
  if (roster) this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, `(${peer} was reviewing this and is off roster.)`));
8821
9880
  else this.sendReview(next, reviewer, `(${peer} was reviewing this and is paused for quota.)`);
8822
- } else if (next.state === "in_review" && !reviewer) this.d.notify(`task ${this.publicTitle(next)}: its reviewer ${peer} is paused and nobody else can review; use ahub review ${next.id}`);
9881
+ } else if (next.state === "in_review" && !reviewer && !a.reviewSelection?.quotaWait) this.d.notify(`task ${this.publicTitle(next)}: its reviewer ${peer} is paused and nobody else can review; use ahub review ${next.id}`);
8823
9882
  }
8824
9883
  }
8825
9884
  return moved;