@staix/agent-hub 0.38.0 → 0.40.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 (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
package/src/hub/tasks.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import { requireConductor } from "./conductor.ts";
2
+ import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind } from "./roadmap.ts";
3
+ import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
4
+ import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
5
+ import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
2
6
  import { pathCandidates } from "@staix/agent-mem";
3
7
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
4
8
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
@@ -15,7 +19,8 @@ import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts
15
19
  import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
16
20
  import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
17
21
  import type { JournalDelivery } from "./delivery-journal.ts";
18
- import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt } from "./research-evidence.ts";
22
+ import { checkSynthesis, inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisCurrentClaim, type SynthesisArtifactSnapshot, type SynthesisReadiness } from "./synthesis-readiness.ts";
23
+ import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts";
19
24
  import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
20
25
  import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
21
26
  import type { ReviewMaterialBatch } from "./review-material.ts";
@@ -23,6 +28,8 @@ import { isReviewObserverExcluded } from "./memory-policy.ts";
23
28
  import { renderFindingAnchor } from "./review-brief.ts";
24
29
  import { reviewCommentFields, reviewCommentNumber, reviewCommentId, reviewCommentIds, reviewCommentHead, reviewCommentBody, reviewCommentAuthor, privateReviewAnchor, reviewThreadProjection, renderReviewComment, REVIEW_PACKAGE_BYTES, REVIEW_COMMENT_LIMIT,
25
30
  type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentMutation, type ReviewCommentCounts, type ReviewCommentView } from "./review-comments.ts";
31
+ import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts";
32
+ import type { SourceMeta } from "./sources.ts";
26
33
  import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts";
27
34
  import { approvalBinding, approvalText } from "./task-approval.ts";
28
35
  import type { InvocationRow } from "./invocations.ts";
@@ -40,11 +47,20 @@ import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampa
40
47
  import type { ResearchCampaignRecord, ResearchUnitBinding, PreparedResearchUnit, HandoffOutboundRow } from "./board.ts";
41
48
  import { HANDOFF_EVENTS, HANDOFF_KEY, HandoffRefusal, handoffRequestDigest, duplicateIssueTasks, duplicateRefusalText, followBackLine, handoffEventFor, parseHandoff, type HandoffEvent } from "./handoff.ts";
42
49
  import { taskShellBindingValid, type TaskShellBinding } from "./task-shell-command.ts";
50
+ import type { ReviewBudgetSnapshot, ReviewGate, ReviewUnknownQuota } from "./review-budget.ts";
43
51
  import { buildTaskCodeSymbols, publicTaskCodeSymbols, taskCodeSymbolsDisjoint, HOST_CODE_SYMBOLS } from "./task-code-symbols.ts";
44
52
  import { normalizePlanSymbol, symbolsOverlap } from "./symbol-normalizer.ts";
45
53
  import { publicTestIntegrity, readTestIntegrity, testIntegrityBlockers, type TestIntegrity } from "./test-integrity.ts";
46
54
  import { evalAdvice, evalGapBlockers, evalRequiredChecks, readEvalFor } from "./eval-gate.ts";
47
- import { completePlanInventory, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
55
+ import { parseSecurityPass, securityPassBlockers, securityPassView, securityRequestLine, SECURITY_CHECKLIST, type SecurityPassRecord, type SecurityPassView } from "./security-pass.ts";
56
+ 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";
57
+ import type { AuditSource } from "./audit-source.ts";
58
+ import { SURVEY_FOCUS, SURVEY_LIMITS, parseSurveyFindings, parseSurveyVetDecisions, publicSurveyFinding, surveyBrief, surveyFindingKey, surveyObject, surveyPath, surveyInputAt, surveyInputProblem,
59
+ type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
60
+ import { consideredFindingMatch, parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
61
+ import type { StoredSurvey, SurveyPreparedCard } from "./board.ts";
62
+ import { matchConfigPath } from "./eval-gate.ts";
63
+ import { completePlanInventory, planDrift, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
48
64
  import { RELEASE_TRAIN_HISTORY_LIMIT, releaseTrainData, releaseTrainReadiness, releaseMetrics } from "./sdlc-release.ts";
49
65
  import { cleanCostPlan, costMetrics, CostScopeError, type CostPlan, type ReviewCost } from "./cost-governance.ts";
50
66
  import { qualifiedTitleRepos, siblingTitleRefs, specRefs } from "./spec-read.ts";
@@ -57,13 +73,13 @@ import type { InstancesConfig } from "./instances.ts";
57
73
  import { composeRememberText } from "./memory-fail.ts";
58
74
  import { VERSION } from "../version.ts";
59
75
  import { NoWriteTurns } from "./no-writes.ts";
60
- import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
76
+ import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
61
77
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
62
78
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
63
79
  import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
64
80
  import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
65
81
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
66
- import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
82
+ import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
67
83
  import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
68
84
  import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
69
85
  import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
@@ -86,7 +102,7 @@ const learnVerdict = (card: Pick<Task, "state" | "history">): "accepted" | "reje
86
102
  return closed.note?.startsWith(LEARN_ACCEPTED) ? "accepted" : closed.note?.startsWith(LEARN_REJECTED) ? "rejected" : undefined;
87
103
  };
88
104
  import { approvedDeliverables, latestDeliverables, parseDeliverableClaims, publicDeliverables, type DeliverableRecord, type DeliverableStatus } from "./deliverables.ts";
89
- import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, type DeliverablePorts } from "./deliverable-files.ts";
105
+ import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, readGuardedDeliverable, guardedDeliverableCurrent, type GuardedDeliverableRead, type DeliverablePorts } from "./deliverable-files.ts";
90
106
  import { isAbsolute, relative, resolve } from "node:path";
91
107
  import type { Briefs, NativeItem } from "../memory/brief.ts";
92
108
  import type { MemoryClient } from "../memory/client.ts";
@@ -108,7 +124,7 @@ import { DEFAULT_SPECS_CONFIG, type SpecsConfig } from "./specs-config.ts";
108
124
  import type { SpecsCheckReport, SpecsCoverReport } from "./specs.ts";
109
125
  import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
110
126
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
111
- import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
127
+ import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
112
128
  import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
113
129
  import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
114
130
 
@@ -121,6 +137,9 @@ function requireLocalTaskPeer(peer: unknown): void {
121
137
  }
122
138
 
123
139
  export type TaskAssignmentRole = "owner" | "reviewer" | "planner";
140
+ export type EvidenceReadOrigins = { state: "known"; group: string; groups: number } | { state: "unknown" };
141
+ export type EvidenceReadResult = EvidenceReceipt & ({ status: "private" | "stale" | "unavailable" | "withdrawn" }
142
+ | { status: "resolved"; link: EvidenceLinkV1; excerpt: string; excerptSha256: string; locator: EvidenceLinkV1["locator"]; origins: EvidenceReadOrigins });
124
143
 
125
144
  /** What `hub_remember` carries (#802: one shape for `remember` and `rememberOutcome`). */
126
145
  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 }
@@ -139,6 +158,14 @@ interface PreparedSpecInspection {
139
158
 
140
159
  export interface ReleaseWindow { at: number; host: boolean; quota: boolean; idle: boolean; reasons: string[]; current?: () => boolean; close?: () => Promise<void>; }
141
160
 
161
+ /** #1403 A4: the audit as a caller reads it. `withheld` counts open important findings whose text the view leaves out. */
162
+ export interface AuditView extends AuditSummary {
163
+ units: { unit: string; state: string; prior?: { audit: number; head: string }; reason?: string }[];
164
+ items: PublicAuditFinding[];
165
+ withheld?: number;
166
+ /** Findings in this report that were already verified or rejected, so the hub left them as decided. */
167
+ notUpdated?: string[];
168
+ }
142
169
  export interface TasksDeps {
143
170
  /** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */
144
171
  guidanceProbes?: {
@@ -202,10 +229,18 @@ export interface TasksDeps {
202
229
  specsConfig?: () => SpecsConfig;
203
230
  /** Explicit, read-only inspection remains available when task notices are disabled. */
204
231
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
232
+ /** R3 (#1481): spec ids with their status, for the unplaced list. Absent or throwing is "unavailable", never "no specs". */
233
+ specsList?: () => { specs: { id: string; title: string; status: string | null }[]; errors: number; truncated: boolean };
234
+ /** R3 (#1481): the model for triage. Absent, off or failing is no suggestion; it carries no authority and links nothing. */
235
+ roadmapModel?: (system: string, user: string, allowed: () => boolean) => Promise<string | undefined>;
236
+ /** R3 (#1481): host-only `gh` runner for the roadmap's read-only issue and milestone reads (tests); production uses `sdlc.gh`. */
237
+ roadmapGh?: SdlcGh;
205
238
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
206
239
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
207
240
  /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
208
241
  sdlc?: { config: () => SdlcConfig; gh?: SdlcGh; reportPolicy?: (head: string, repo: string) => ReleaseReportPolicy | undefined };
242
+ /** #1403 A4: read-only git for the security audit (the checkout's head and changed paths); absent means the audit commands are unavailable. */
243
+ auditSource?: AuditSource;
209
244
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
210
245
  ciWatch?: { deadlineMs?: number; pollMs?: number };
211
246
  /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
@@ -217,6 +252,8 @@ export interface TasksDeps {
217
252
  candidateScreen?: MemoryScreen;
218
253
  /** Authenticated live turn context, not a model-supplied flag. */
219
254
  privateTurn?: (peer: PeerId) => boolean;
255
+ /** Host-only observer provenance, separate from task/turn authority. Sample before any operation await. */
256
+ observerExcludedTurn?: (peer: PeerId) => boolean;
220
257
  /** #223 R4: the hub's reading of a verdict's context (`fresh` only for a reviewer session started for this review). */
221
258
  reviewContext?: (by: PeerId, task: number) => "fresh" | "continuing" | undefined;
222
259
  /** Current-turn input carries review material or anchored findings; it expires on the next ordinary input. */
@@ -265,6 +302,12 @@ export interface TasksDeps {
265
302
  /** 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. */
266
303
  reviewMaterials?: (task: Task, requests: readonly { path: string; side?: "base" | "head" }[]) => Promise<ReviewMaterialBatch>;
267
304
  studySource?: (id: string) => { id: string; sha256: string; private: boolean } | undefined;
305
+ /** Host-owned screened snapshot read, never a public source-read excerpt reconstructed as a projection. */
306
+ /** Opaque host-only current raw/projection/converter token, never client evidence. */
307
+ evidenceSourceSnapshotKey?: (link: EvidenceLinkV1) => string | undefined;
308
+ evidenceSourceRead?: (by: PeerId, link: EvidenceLinkV1, current: () => boolean, mode?: { privacyReadOnly: true }) => Promise<EvidenceSourceRead>;
309
+ /** Fresh registered metadata for bounded, ephemeral origin grouping; no converter or model call. */
310
+ evidenceSourceMeta?: (id: string) => SourceMeta | undefined;
268
311
  /** Host-only fixture clock; never read from model input or project configuration. */
269
312
  studyNow?: () => number;
270
313
  /** Host-only reader for this project's check-runner receipts; record inputs never supply a receipt. */
@@ -272,7 +315,8 @@ export interface TasksDeps {
272
315
  /** Fresh trusted machine-local runner registrations. A source-trust failure refuses new receipts. */
273
316
  researchRunners?: () => unknown;
274
317
  /** Reviewer choice from recorded review outcomes (issue #35); off unless the project config turns it on. */
275
- review?: { adaptive: boolean; min_reviews: number; pool?: readonly string[]; rerotate?: boolean; same_family?: "fallback" | "never" };
318
+ review?: { adaptive: boolean; min_reviews: number; pool?: readonly string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number };
319
+ reviewBudget?: () => Pick<ReviewBudgetSnapshot, "paused" | "manualPaused">;
276
320
  /** Peers whose recent deliveries all failed, with the reason (issue #89); routing skips them. */
277
321
  capabilities?: () => Record<PeerId, PeerCapabilities>;
278
322
  /** #1115: the hub makes, commits and clears the task worktree of a hub-sandboxed peer. Absent: such a peer keeps the #1081 refusal. */
@@ -363,6 +407,7 @@ QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or
363
407
  QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff.
364
408
  QUIET_EVENTS.add("claim verdict"); // #901: a person's bookkeeping on a plan claim moves nothing, so it must not turn a running check into "check finished late".
365
409
  QUIET_EVENTS.add("invocation");
410
+ QUIET_EVENTS.add("wait recorded"); // #1454: a recorded wait moves nothing; it only suspends the idle-owner ladder, so it must not turn a running check into "check finished late".
366
411
  QUIET_EVENTS.add("shell branch bound"); // #880: the hub's host-observed branch binding (#845) is bookkeeping; it neither moves nor settles the task.
367
412
  /** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */
368
413
  const latestPendingDeliverables = (task: Task): DeliverableRecord[] | undefined => {
@@ -442,8 +487,8 @@ function acceptRefs(input: unknown): TaskRefs | undefined {
442
487
  return { repo: text(raw.repo)! };
443
488
  }
444
489
 
445
- /** The same for a plan (issue #31): only its four lists, each of short strings. */
446
- function cleanPlan(input: unknown, profile: ProfileSelection = "dev"): TaskPlan {
490
+ /** Normalize plan intent at the boundary; lifecycle-off ignores the additive cold-plan fields. */
491
+ function cleanPlan(input: unknown, profile: ProfileSelection = "dev", lifecycle = false): TaskPlan {
447
492
  const r = fields(input);
448
493
  const evidence: Pick<TaskPlan, "proof" | "risks"> = {};
449
494
  for (const key of ["proof", "risks"] as const) {
@@ -453,13 +498,42 @@ function cleanPlan(input: unknown, profile: ProfileSelection = "dev"): TaskPlan
453
498
  const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean);
454
499
  if (items.length) evidence[key] = items;
455
500
  }
501
+ const intent: import("./board.ts").ColdPlanIntent = {};
502
+ if (lifecycle) {
503
+ if (r.base !== undefined) {
504
+ if (typeof r.base !== "string" || !/^[a-f0-9]{40}$/.test(r.base)) throw new PreEffectToolRefusal("plan.base: expected a full lowercase commit SHA");
505
+ intent.base = r.base;
506
+ }
507
+ for (const key of ["out_of_scope", "stop_if"] as const) {
508
+ const value = r[key];
509
+ if (value === undefined) continue;
510
+ 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`);
511
+ const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean);
512
+ if (items.length) intent[key] = [...new Set(key === "out_of_scope" ? items.map(normPath) : items)];
513
+ }
514
+ if (r.steps !== undefined) {
515
+ if (!Array.isArray(r.steps) || r.steps.length > 32) throw new PreEffectToolRefusal("plan.steps: expected at most 32 steps");
516
+ intent.steps = r.steps.map(raw => {
517
+ const row = fields(raw);
518
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(row).some(key => key !== "description" && key !== "verify")
519
+ || typeof row.description !== "string" || !row.description.trim() || row.description.length > 512
520
+ || 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");
521
+ return { description: row.description.replace(/\s+/g, " ").trim(), ...(typeof row.verify === "string" ? { verify: row.verify.replace(/\s+/g, " ").trim() } : {}) };
522
+ });
523
+ }
524
+ }
456
525
  let scope: CostPlan;
457
526
  try { scope = cleanCostPlan(r); } catch (error) { throw new PreEffectToolRefusal(error instanceof CostScopeError ? error.message : "invalid review or CI cost scope"); }
458
- 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 };
527
+ 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 };
459
528
  }
460
529
 
461
530
  /** A plan as one line for other owners; the whole plan is on the board. */
462
- const planText = (plan: TaskPlan = {}) => ALL_PLAN_KEYS.filter((k) => plan[k]?.length).map((k) => `${k.replace("_", " ")}: ${plan[k]!.join("; ")}`).join(" | ");
531
+ const planText = (plan: TaskPlan = {}) => [
532
+ ...ALL_PLAN_KEYS.filter((k) => plan[k]?.length).map((k) => `${k.replace("_", " ")}: ${plan[k]!.join("; ")}`),
533
+ ...(plan.base ? [`base: ${plan.base}`] : []),
534
+ ...(["out_of_scope", "stop_if"] as const).filter(key => plan[key]?.length).map(key => `${key}: ${plan[key]!.join("; ")}`),
535
+ ...(plan.steps?.length ? [`steps: ${plan.steps.map(step => `${step.description}${step.verify ? `; verify: ${step.verify}` : ""}`).join("; ")}`] : []),
536
+ ].join(" | ");
463
537
  /** What the PII screen reads of a task (#198): the text the patterns are checked against. */
464
538
  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");
465
539
  /** Re-screens of one task whose verdict was unknown, per hub run (#198). */
@@ -836,7 +910,7 @@ export class Tasks {
836
910
 
837
911
  private signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing = this.d.routing()) {
838
912
  const signals = detectSignals(task, routing, this.d.cwd);
839
- const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)];
913
+ const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.out_of_scope ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)];
840
914
  if (paths.some(path => matchesPolicy(this.d.cwd, path, this.d.piiPaths ?? [], true))) {
841
915
  if (!signals.includes("pii")) signals.push("pii");
842
916
  signals.push("pii_path");
@@ -857,6 +931,9 @@ export class Tasks {
857
931
  const check = () => { const reason = authority?.() ?? fence?.(); if (reason) throw new PreEffectToolRefusal(reason); };
858
932
  check(); return check;
859
933
  }
934
+ private observerExcluded(by: PeerId): boolean {
935
+ try { return this.d.observerExcludedTurn?.(by) === true; } catch { return true; }
936
+ }
860
937
 
861
938
  private async screenCall(text: string): Promise<PiiVerdict> {
862
939
  return (await this.d.piiScreen?.(text).catch(() => undefined)) ?? { label: "unknown", miss: "failed", ms: 0 };
@@ -954,6 +1031,44 @@ export class Tasks {
954
1031
  return recorded;
955
1032
  }
956
1033
 
1034
+ /**
1035
+ * #1454: record a bounded wait on an in_progress task, so the idle-owner ladder is suspended until `until` and restarts from it.
1036
+ * Owner, its planner or the person only. The reason is public text: one the privacy screen would withhold is refused on an
1037
+ * ordinary task (the wait is shown in every board view), and kept withheld on a PII task. Every refusal is pre-effect and
1038
+ * names its cause and the next step. Done, decline, return and reassignment end a wait by moving the task (`taskWait`).
1039
+ */
1040
+ async wait(by: PeerId, input: { id: unknown; until: unknown; reason: unknown }): Promise<Task> {
1041
+ requireLocalTaskPeer(by);
1042
+ const refuse = (text: string): never => { throw new PreEffectToolRefusal(text); };
1043
+ if (!this.sweepConfig.enabled) refuse("a wait suspends the idle sweep and task_sweep is off, so there is nothing to suspend; just keep working, or ask the person to turn on task_sweep.enabled");
1044
+ const now = this.d.now?.() ?? Date.now();
1045
+ const until = typeof input.until === "number" ? input.until
1046
+ : typeof input.until === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(input.until.trim()) ? Date.parse(input.until.trim()) : NaN;
1047
+ if (!Number.isSafeInteger(until)) refuse("until must be an absolute time with a zone, for example 2026-11-18T09:00:00+09:00 (or milliseconds since the epoch); resend with that");
1048
+ if (until <= now) refuse(`until ${new Date(until).toISOString()} is not in the future (now ${new Date(now).toISOString()}); name a later time, or drop the wait and keep working`);
1049
+ if (until > now + TASK_WAIT_MAX_MS) refuse(`until ${new Date(until).toISOString()} is more than 14 days ahead (latest ${new Date(now + TASK_WAIT_MAX_MS).toISOString()}); name an earlier time and record the wait again when it passes`);
1050
+ const reason = typeof input.reason === "string" ? input.reason.trim() : "";
1051
+ if (!reason) refuse("reason must be a short public sentence naming what the task waits for; resend with it");
1052
+ if ([...reason].length > TASK_WAIT_REASON_MAX || /[\u0000-\u001f\u007f]/.test(reason)) refuse(`reason must be one line of at most ${TASK_WAIT_REASON_MAX} characters; shorten it and resend`);
1053
+ const validate = (): Task => {
1054
+ const task = this.need(input.id, false, true);
1055
+ if (task.state !== "in_progress") refuse(`task #${task.id} is ${task.state}: a wait applies only to in_progress work; ${task.state === "proposed" ? "accept the task first with hub_task_accept" : "it needs no wait"}`);
1056
+ if (by !== USER && task.owner !== by && !(this.d.roles?.[by]?.includes("planner") && this.taskPlanner(task).includes(by)))
1057
+ refuse(`task #${task.id}: only its owner (${task.owner ?? "none"}), its planner or the console user can record a wait; ask the owner, or hub_send the planner`);
1058
+ if (by !== USER && this.d.privateTurn?.(by) && !this.isPii(task)) refuse("a wait on ordinary work is unavailable during a private turn; record it from a public turn");
1059
+ return task;
1060
+ };
1061
+ const before = validate(), revision = before.history.length;
1062
+ const pii = this.isPii(before);
1063
+ const withheld = looksSecret(reason) || this.aboutPrivatePath("", reason, before) || await this.withholds("note", reason, before);
1064
+ if (withheld && !pii) refuse("the reason would be withheld by the privacy screen and a wait is shown in every board view; restate it without names, paths or personal details");
1065
+ const task = validate();
1066
+ if (task.history.length !== revision) refuse(`task #${task.id}: it changed while the reason was screened; read it with hub_task_show and record the wait again`);
1067
+ const next = this.d.board.update(task.id, by, "wait recorded", {}, reason, { wait: { until, owner: task.owner! }, ...(pii || withheld ? { withheld: true as const } : {}) }, revision);
1068
+ this.d.notify(`task ${this.publicTitle(next)}: wait recorded by ${by} until ${new Date(until).toISOString()}`);
1069
+ return next;
1070
+ }
1071
+
957
1072
  /** A validated snapshot takes effect on the next sweep, never halfway through one. */
958
1073
  configureSweep(config: TaskSweepConfig): void {
959
1074
  this.sweepConfig = taskSweepConfig(config);
@@ -963,7 +1078,8 @@ export class Tasks {
963
1078
  }
964
1079
  }
965
1080
 
966
- private ownerAcceptance(task: Task, first = false): { index: number; at: number } | undefined {
1081
+ /** Host-only acceptance binding, shared by owner-turn evidence and bounded native continuations. */
1082
+ ownerAcceptance(task: Task, first = false): { index: number; at: number } | undefined {
967
1083
  if (!task.owner) return undefined;
968
1084
  const boundary = task.history.findLastIndex(entry => OWNERSHIP_EVENTS.has(entry.event) || entry.owner !== undefined && entry.owner !== task.owner);
969
1085
  const accepted = (entry: Task["history"][number], index: number) => index > boundary && entry.event === "accepted" && (entry.by === task.owner || entry.by === USER);
@@ -1200,7 +1316,8 @@ export class Tasks {
1200
1316
  .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Review finding key: ")) ?? []));
1201
1317
  const created: number[] = [];
1202
1318
  // No await separates the durable dedupe read from creation; concurrent verdicts see the first proposal.
1203
- for (const item of items.filter(item => item.disposition !== "false_positive")) {
1319
+ // #1436: a positional id (N1, F5, nit-1) is review-local, so it never counts toward a cross-task recurrence; a semantic id does.
1320
+ for (const item of items.filter(item => item.disposition !== "false_positive" && !positionalFindingId(item.id))) {
1204
1321
  const same = (finding: ReviewFinding) => finding.id === item.id && finding.pass === item.pass;
1205
1322
  const holders = rows.filter(row => {
1206
1323
  if (this.isPii(row)) return false;
@@ -1225,6 +1342,37 @@ export class Tasks {
1225
1342
  for (const id of created) this.releaseNotice(`task #${id}: recurring review finding amendment proposed in the backlog`);
1226
1343
  }
1227
1344
 
1345
+ /**
1346
+ * #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
1347
+ * (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
1348
+ * 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).
1349
+ */
1350
+ private proposeFindingFollowUps(task: Task, by: PeerId, withheld: boolean): void {
1351
+ if (withheld || this.isPii(task) || this.d.privateTurn?.(by)) return;
1352
+ const { validation, preExisting } = findingFollowUps(this.reviewFindingSets(task));
1353
+ if (!validation.length && !preExisting.length) return;
1354
+ const visible = (item: ReviewFinding) => !task.history.some(entry => entry.withheld && entry.reviewFindings?.items.some(value => value.id === item.id)) && this.findingTextAllowed(task, [item]);
1355
+ const keys = new Set(this.d.board.list().filter(row => (row.class === "plan" || row.class === "triage") && row.history[0]?.by === HUB)
1356
+ .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Finding follow-up key: ")) ?? []));
1357
+ const created: number[] = [];
1358
+ // No await separates the durable dedupe read from creation; a repeated approval sees the first card.
1359
+ for (const [kind, items] of [["validation", validation], ["pre-existing", preExisting]] as const) for (const item of items.filter(visible)) {
1360
+ const key = `Finding follow-up key: ${task.id}:${item.pass}:${item.id}:${kind}`;
1361
+ if (keys.has(key)) continue;
1362
+ const ref = `${item.pass}:${item.id}`;
1363
+ 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`;
1364
+ const detail = kind === "validation"
1365
+ ? `${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}.`
1366
+ : `${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}.`;
1367
+ const draft = { title, detail, refs: {} };
1368
+ const signals = this.signalsFor(draft);
1369
+ if (this.isPii({ signals }) || !this.candidateTextAllowed(`${title}\n${detail}`)) continue;
1370
+ const proposal = this.d.board.propose(HUB, { ...draft, class: kind === "validation" ? "triage" : "plan", backlog: true, signals });
1371
+ this.incomingBacklog.add(proposal.id); keys.add(key); created.push(proposal.id);
1372
+ }
1373
+ for (const id of created) this.releaseNotice(`task #${id}: finding follow-up proposed in the backlog`);
1374
+ }
1375
+
1228
1376
  private publicClaimBindings(task: Task): ReturnType<typeof taskClaimIdentity>[] | undefined {
1229
1377
  const claims = task.plan?.claims;
1230
1378
  if (task.profile !== "research" || task.signals.includes("pii") || task.signals.includes("pii_path")
@@ -1276,17 +1424,20 @@ export class Tasks {
1276
1424
  ...(h.deliverables?.length ? { deliverables: publicDeliverables(h.deliverables, this.nameable) } : {}),
1277
1425
  ...(h.reviewBlocked ? { reviewBlocked: true } : {}),
1278
1426
  ...(h.queueReviewHeld ? { queueReviewHeld: true } : {}),
1279
- ...(h.reviewerFailure ? { reviewerFailure: { peer: screenHistoryText(h.reviewerFailure.peer, "reviewer"), cause: h.reviewerFailure.cause, ...(h.reviewerFailure.head ? { head: screenHistoryText(h.reviewerFailure.head, "review head") } : {}) } } : {}),
1427
+ ...(h.reviewerQuotaWait ? { reviewerQuotaWait: { since: h.reviewerQuotaWait.since, deadline: h.reviewerQuotaWait.deadline, resetAt: h.reviewerQuotaWait.resetAt } } : {}),
1428
+ ...(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") } : {}) } } : {}),
1280
1429
  ...(h.planning ? { planning: { revision: h.planning.revision, fields: h.planning.fields, ...(h.planning.split ? { children: h.planning.split.children.map(child => child.id) } : {}) } } : {}),
1281
1430
  ...(h.reason && TASK_MOVE_REASONS.includes(h.reason) ? { reason: h.reason } : {}),
1282
1431
  ...(h.sweep ? { sweep: { kind: h.sweep.kind, activity: h.sweep.activity, step: h.sweep.step, at: h.sweep.at } } : {}),
1432
+ ...(h.wait ? { wait: { until: h.wait.until, owner: h.wait.owner } } : {}),
1283
1433
  ...(h === currentSpecEntry && currentSpecReport ? { specReport: currentSpecReport } : {}),
1284
1434
  }));
1285
1435
  const sets = this.reviewFindingSets(task), current = findingsForHead(sets, this.findingHead(task));
1286
1436
  const symbolRepository = codeSymbols && this.codeSymbolsRepository(task);
1287
1437
  const publicSymbols = codeSymbols && symbolRepository ? publicTaskCodeSymbols(codeSymbols, this.reviewHead(task), symbolRepository.key, this.publicMetadataText) : undefined;
1288
1438
  const handedOff = this.d.board.handoffOrigin(task.id); // #604: where another project's handoff came from; two ids, never text
1289
- return { ...rest, ...(claimBindings ? { claims: claimBindings } : {}), ...(currentSpecReport ? { specReport: currentSpecReport } : {}), ...(approvalBinding(task) ? { approval: approvalBinding(task) } : {}), ...(handedOff ? { handoffOrigin: { projectId: handedOff.projectId, peer: handedOff.peer, ...(handedOff.originTask === null ? {} : { task: handedOff.originTask }) } } : {}), ...(publicSymbols ? { codeSymbols: publicSymbols } : {}), ...(current.length ? { findings: findingTally(current) } : {}), ...(cancelled ? { cancelled: { ...cancelled, reason: screenHistoryText(cancelled.reason, "cancellation", cancelled.withheld), ...(cancelled.supersededBy ? { supersededBy: screenHistoryText(cancelled.supersededBy, "supersession", cancelled.withheld) } : {}) } } : {}), ...(external && this.nameable(external.url) ? { external } : {}), actualDates: actualTaskDates(task), ...(((this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.sdlc?.config().workflow === "gsd-lite") ? { lifecycle: sdlcStatus(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc, undefined, this.workflowView(task), undefined, sets, task.refs.commit) } : {}), title, detail, history: publicHistory };
1439
+ const wait = taskWait(task), waitEntry = wait ? history.findLast(h => h.wait) : undefined;
1440
+ return { ...rest, ...(wait && waitEntry ? { wait: { until: wait.until, by: wait.by, at: wait.at, passed: wait.until <= (this.d.now?.() ?? Date.now()), ...(waitEntry.note ? { reason: screenHistoryText(waitEntry.note, "wait reason", waitEntry.withheld) } : {}) } } : {}), ...(claimBindings ? { claims: claimBindings } : {}), ...(currentSpecReport ? { specReport: currentSpecReport } : {}), ...(approvalBinding(task) ? { approval: approvalBinding(task) } : {}), ...(handedOff ? { handoffOrigin: { projectId: handedOff.projectId, peer: handedOff.peer, ...(handedOff.originTask === null ? {} : { task: handedOff.originTask }) } } : {}), ...(publicSymbols ? { codeSymbols: publicSymbols } : {}), ...(current.length ? { findings: findingTally(current) } : {}), ...(cancelled ? { cancelled: { ...cancelled, reason: screenHistoryText(cancelled.reason, "cancellation", cancelled.withheld), ...(cancelled.supersededBy ? { supersededBy: screenHistoryText(cancelled.supersededBy, "supersession", cancelled.withheld) } : {}) } } : {}), ...(external && this.nameable(external.url) ? { external } : {}), actualDates: actualTaskDates(task), ...(((this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.sdlc?.config().workflow === "gsd-lite") ? { lifecycle: sdlcStatus(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc, undefined, this.workflowView(task), undefined, sets, task.refs.commit) } : {}), title, detail, history: publicHistory };
1290
1441
  }
1291
1442
 
1292
1443
  /** Console results expose direct approval and delivery holds, not just the chosen peer ids. */
@@ -1304,6 +1455,8 @@ export class Tasks {
1304
1455
  const held = task.owner ? peerEntry(this.d.held?.(), task.owner) : undefined;
1305
1456
  const holdText = held ? `${task.owner}'s queue is held (${held}); it receives the task once the hold is resolved` : undefined;
1306
1457
  const request = task.history.findLast(entry => ["done", "reviewer changed", "reviewer unavailable"].includes(entry.event));
1458
+ const quotaWait = this.activeReviewerQuotaWait(task);
1459
+ if (quotaWait) return `${base}; waiting for reviewer quota reset until ${new Date(quotaWait.deadline).toISOString()}`;
1307
1460
  const poolBlocked = task.state === "in_review" && task.reviewer === USER && request?.reviewBlocked ? "blocked: no reviewer can run" : undefined;
1308
1461
  const specText = this.specReportText(task, by) || undefined;
1309
1462
  return [base, noReview, poolBlocked, holdText, specText].filter(Boolean).join("; ");
@@ -1696,8 +1849,11 @@ export class Tasks {
1696
1849
  private reviewPoolOptions(task: Task) {
1697
1850
  const head = this.reviewHead(task);
1698
1851
  const round = task.state === "in_review" ? task.history.slice(task.history.findLastIndex(entry => entry.event === "done") + 1) : [];
1699
- const failed = [...new Set(round.flatMap(entry => entry.reviewerFailure?.head === head && entry.reviewerFailure ? [entry.reviewerFailure.peer] : []))];
1700
- 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 } : {}) };
1852
+ const failed = [...new Set(round.flatMap(entry => entry.reviewerFailure?.head === head && entry.reviewerFailure && entry.reviewerFailure.cause !== "quota" ? [entry.reviewerFailure.peer] : []))];
1853
+ const gate = this.d.review?.gate;
1854
+ 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?.() };
1855
+ const wait = this.priorReviewerQuotaWait(task), now = this.d.now?.() ?? Date.now();
1856
+ 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 } : {}) };
1701
1857
  }
1702
1858
 
1703
1859
  private manuallyNamedReviewer(task: Task): boolean {
@@ -1726,7 +1882,12 @@ export class Tasks {
1726
1882
  const queueReviewHeld = task !== undefined && !this.isPii(task) && assignment?.reviewer === USER && assignment.reviewBlocked === true
1727
1883
  && assignment.refusals?.some(row => row.role === "reviewer" && isQueuePressureCode(row.code));
1728
1884
  const queueReviewBinding = task ? this.queueReviewBinding(task) : undefined;
1729
- return { ...(family ? { reviewerFamily: family } : {}), ...(reason ? { reviewerReason: reason } : {}), ...(assignment?.reviewBlocked ? { reviewBlocked: true } : {}), ...(queueReviewHeld ? { queueReviewHeld: true as const, ...(queueReviewBinding !== undefined ? { queueReviewBinding } : {}) } : {}) };
1885
+ const quota = choice?.quotaWait;
1886
+ const now = this.d.now?.() ?? Date.now(), prior = task ? this.priorReviewerQuotaWait(task) : undefined;
1887
+ const reviewerQuotaWait = quota && task && !this.isPii(task) && task.state === "in_review"
1888
+ ? { created: task.created, binding: this.queueReviewBinding(task), since: prior?.since ?? now,
1889
+ deadline: prior?.deadline ?? Math.floor(now + this.sweepConfig.review_min * 60_000), resetAt: quota.resetsAt } : undefined;
1890
+ return { ...(reviewerQuotaWait ? { reviewerQuotaWait } : {}), ...(family ? { reviewerFamily: family } : {}), ...(reason ? { reviewerReason: reason } : {}), ...(assignment?.reviewBlocked ? { reviewBlocked: true } : {}), ...(queueReviewHeld ? { queueReviewHeld: true as const, ...(queueReviewBinding !== undefined ? { queueReviewBinding } : {}) } : {}) };
1730
1891
  }
1731
1892
 
1732
1893
  /**
@@ -2817,7 +2978,7 @@ export class Tasks {
2817
2978
  const authored = task.history.findLast(entry => entry.event !== "plan reviewed" && entry.planRevision !== undefined)
2818
2979
  ?? task.history.findLast(entry => entry.event !== "plan reviewed" && (entry.planning?.fields as readonly string[] | undefined)?.includes("plan"));
2819
2980
  if (authored && authored !== task.history[0]) return authored.by;
2820
- return ALL_PLAN_KEYS.some(key => !!task.plan?.[key]?.length) ? authored?.by ?? task.history[0]?.by ?? null : null;
2981
+ 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;
2821
2982
  }
2822
2983
 
2823
2984
  private planReviewAuthority(by: PeerId, task: Task): { planAuthor: PeerId | null; selfReview?: true } {
@@ -3027,6 +3188,20 @@ export class Tasks {
3027
3188
  }
3028
3189
  return parts.length ? `no peer can take the planner pull: ${parts.join("; ")}` : "no peer has eligible planner WIP capacity";
3029
3190
  }
3191
+ /**
3192
+ * #1430: the owner refusals routing itself recorded, named the way the reserved branch already names its peer: peer id and
3193
+ * reason only, never task text (#531), so the text is safe for a PII task. Undefined when routing recorded none.
3194
+ */
3195
+ private ownerRefusals(assignment: Assignment): string | undefined {
3196
+ const refused = (assignment.refusals ?? []).filter(row => row.role === "owner");
3197
+ return refused.length ? `routing refusals: ${refused.map(row => `${row.peer}: ${row.reason}`).join("; ")}` : undefined;
3198
+ }
3199
+ /** Keep routing refusals even when other peers also have known WIP or delivery pressure. */
3200
+ private pullRefusal(task: Task, assignment: Assignment): string {
3201
+ const known = this.plannerRefusal(task);
3202
+ const routing = this.ownerRefusals(assignment);
3203
+ return routing ? `${known}; ${routing}` : known;
3204
+ }
3030
3205
  private plannerAssignment(task: Task, reservedOnly = false, routing: Routing = this.d.routing(), queueOverride?: "owner", projectedHealth?: ReturnType<Tasks["health"]>): Assignment {
3031
3206
  const states = this.states();
3032
3207
  const full = this.plannerFull(task);
@@ -3072,8 +3247,13 @@ export class Tasks {
3072
3247
  if (task.reserved && this.excluded(task).includes(task.reserved)) throw new PreEffectToolRefusal(this.plannerRefusal(task));
3073
3248
  const assignment = this.plannerAssignment(task, !!task.reserved, this.d.routing(), queueAssignment ? "owner" : undefined);
3074
3249
  if (!assignment.owner) {
3075
- 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);
3076
- throw new PreEffectToolRefusal(`${this.hasPersonReservation(task) ? "a person's reservation is retained; " : ""}${refusal}`);
3250
+ // #1430: an unreserved card names what routing refused instead of dropping it, and every pull refusal names the route out.
3251
+ const personReserved = this.hasPersonReservation(task);
3252
+ const nextStep = personReserved ? "ask the person to change the reservation" : "reserve a peer with hub_backlog_plan fields.reserved, then pull again";
3253
+ const refusal = task.reserved
3254
+ ? `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)}`
3255
+ : this.pullRefusal(task, assignment);
3256
+ throw new PreEffectToolRefusal(`${personReserved ? "a person's reservation is retained; " : ""}${refusal}; ${nextStep}`);
3077
3257
  }
3078
3258
  this.studyDispatchCheck(task, assignment.owner);
3079
3259
  return { task, owner: assignment.owner, assignment };
@@ -3221,6 +3401,297 @@ export class Tasks {
3221
3401
  }
3222
3402
  return notified.size;
3223
3403
  }
3404
+ private roadmapReadAuthority(by: PeerId): void {
3405
+ requireLocalTaskPeer(by);
3406
+ if (this.d.privateTurn?.(by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("roadmap is unavailable during private or review-observer input; use ahub roadmap list after that turn");
3407
+ }
3408
+
3409
+ private roadmapWriteAuthority(by: PeerId): () => void {
3410
+ const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap writes are held by recovery, shutdown or storage; retry ahub roadmap list after recovery" : undefined);
3411
+ const current = () => {
3412
+ check(); this.roadmapReadAuthority(by);
3413
+ if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by)))
3414
+ throw new PreEffectToolRefusal("roadmap writes require a configured planner or the unique conductor; ask the person to run ahub roadmap");
3415
+ };
3416
+ current(); return current;
3417
+ }
3418
+
3419
+ private roadmapParsed<T>(read: () => T): T {
3420
+ try { return read(); }
3421
+ catch (error) { throw new PreEffectToolRefusal(`${error instanceof Error ? error.message : "invalid roadmap input"}; check ahub roadmap show and correct the fields`); }
3422
+ }
3423
+
3424
+ private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone {
3425
+ const row = this.d.board.milestone(this.roadmapParsed(() => milestoneId(id)));
3426
+ if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3427
+ if (["done", "dropped"].includes(row.state) && state !== row.state) throw new PreEffectToolRefusal("a settled milestone is final; create new work with ahub roadmap new");
3428
+ return row;
3429
+ }
3430
+
3431
+ private roadmapStateAuthority(by: PeerId, state: MilestoneState | undefined): void {
3432
+ if (state !== undefined && !(MILESTONE_STATES as readonly string[]).includes(state)) throw new PreEffectToolRefusal("invalid milestone state; use proposed, planned, active, done or dropped with ahub roadmap state");
3433
+ if (by !== USER && (state === "done" || state === "dropped")) throw new PreEffectToolRefusal("done and dropped require the person; ask them to run ahub roadmap state");
3434
+ }
3435
+
3436
+ private roadmapTextCurrent(fields: MilestonePatch): string {
3437
+ const text = [fields.title, fields.outcome].filter((value): value is string => value !== undefined).join("\n");
3438
+ if (text && !this.publicMetadataText(text))
3439
+ throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3440
+ return text;
3441
+ }
3442
+
3443
+ private async roadmapScreen(fields: MilestonePatch): Promise<void> {
3444
+ const text = this.roadmapTextCurrent(fields);
3445
+ if (text && this.screenOn() && (await this.screenCall(text)).label !== "clear")
3446
+ throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3447
+ this.roadmapTextCurrent(fields);
3448
+ }
3449
+
3450
+ private roadmapResult(by: PeerId, id: number): MilestoneView {
3451
+ try { return this.milestoneShow(by, id); }
3452
+ catch { throw new Error("roadmap operation finished but public readback is unavailable; inspect ahub roadmap show before retrying"); }
3453
+ }
3454
+
3455
+ async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> {
3456
+ const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestoneInput(raw));
3457
+ this.roadmapStateAuthority(by, fields.state);
3458
+ await this.roadmapScreen(fields); current(); this.roadmapStateAuthority(by, fields.state); this.roadmapTextCurrent(fields);
3459
+ const row = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
3460
+ return this.roadmapResult(by, row.id);
3461
+ }
3462
+
3463
+ async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> {
3464
+ const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestonePatch(raw));
3465
+ this.roadmapParsed(() => milestoneRevision(revision)); this.roadmapStateAuthority(by, fields.state);
3466
+ const validate = () => {
3467
+ current(); this.roadmapStateAuthority(by, fields.state);
3468
+ const row = this.roadmapCurrent(id);
3469
+ if (row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before editing");
3470
+ return row;
3471
+ };
3472
+ validate(); await this.roadmapScreen(fields); const row = validate(); this.roadmapTextCurrent(fields);
3473
+ if (Object.entries(fields).every(([key, value]) => row[key as keyof Milestone] === value)) return this.milestoneShow(by, id);
3474
+ this.d.board.updateMilestone(id, fields, revision, { by, at: this.d.now?.() ?? Date.now(), event: "edited", fields: Object.keys(fields) });
3475
+ return this.roadmapResult(by, id);
3476
+ }
3477
+
3478
+ milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3479
+ this.roadmapWriteAuthority(by);
3480
+ const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3481
+ if (!this.publicMetadataText(ref)) throw new PreEffectToolRefusal("roadmap reference is private; use a public reference with ahub roadmap link");
3482
+ if (kind === "task" && !this.d.board.get(Number(ref)) || kind === "release" && !this.d.board.release(Number(ref)))
3483
+ throw new PreEffectToolRefusal("roadmap target does not exist; inspect ahub board or ahub release list before linking");
3484
+ this.d.board.linkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3485
+ return this.roadmapResult(by, id);
3486
+ }
3487
+
3488
+ milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3489
+ this.roadmapWriteAuthority(by);
3490
+ const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3491
+ this.d.board.unlinkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3492
+ return this.roadmapResult(by, id);
3493
+ }
3494
+
3495
+ milestoneOrder(by: PeerId, id: number, order: number): MilestoneView {
3496
+ this.roadmapWriteAuthority(by);
3497
+ const row = this.roadmapCurrent(id), fields = this.roadmapParsed(() => parseMilestonePatch({ order }));
3498
+ if (row.order !== order) this.d.board.updateMilestone(id, fields, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "ordered", fields: ["order"] });
3499
+ return this.roadmapResult(by, id);
3500
+ }
3501
+
3502
+ milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView {
3503
+ this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
3504
+ this.roadmapParsed(() => parseMilestonePatch({ state }));
3505
+ const row = this.roadmapCurrent(id, state);
3506
+ if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"] });
3507
+ return this.roadmapResult(by, id);
3508
+ }
3509
+
3510
+ private roadmapSnapshot(by: PeerId): RoadmapSnapshot {
3511
+ let freshness: SpecsCheckReport["freshness"] | undefined;
3512
+ try { const report = this.d.specsRead?.("check", []); if (report && "freshness" in report && !report.truncated && report.errors === 0)
3513
+ freshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); } catch { /* unavailable evidence stays unknown */ }
3514
+ return { milestones: this.d.board.milestones(), links: this.d.board.milestoneLinks(), tasks: this.d.board.list(), releases: this.d.board.releases(), freshness,
3515
+ issueOf: task => { try { const source = this.planIssueIdentity(task); return source ? `${source.repo.toLowerCase()}#${source.issue}` : undefined; } catch { return undefined; } },
3516
+ privateTask: task => this.isPii(task) || task.signals.includes("pii") || task.state === "backlog" && by !== USER && !this.isConfiguredPlanner(by),
3517
+ publicText: text => this.publicMetadataText(text),
3518
+ };
3519
+ }
3520
+
3521
+ milestoneList(by: PeerId): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] {
3522
+ this.roadmapReadAuthority(by);
3523
+ const views = withTree(milestoneViews(this.roadmapSnapshot(by)));
3524
+ this.roadmapReadAuthority(by); return views;
3525
+ }
3526
+
3527
+ milestoneShow(by: PeerId, id: number): MilestoneView {
3528
+ this.roadmapParsed(() => milestoneId(id));
3529
+ const row = this.milestoneList(by).find(row => row.id === id);
3530
+ if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3531
+ return row;
3532
+ }
3533
+
3534
+ // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
3535
+
3536
+ /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
3537
+ private roadmapRepo(raw: unknown): string | undefined {
3538
+ if (raw === undefined) return undefined;
3539
+ return this.roadmapParsed(() => githubRepo(raw));
3540
+ }
3541
+
3542
+ private roadmapGh(run?: SdlcGh): SdlcGh {
3543
+ return run ?? this.d.roadmapGh ?? this.d.sdlc?.gh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound));
3544
+ }
3545
+
3546
+ /** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */
3547
+ async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> {
3548
+ this.roadmapReadAuthority(by);
3549
+ const repo = this.roadmapRepo(input.repo);
3550
+ let issues: Awaited<ReturnType<typeof readGitHubIssuePages>> | undefined;
3551
+ try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.roadmapGh(run)); } catch { issues = undefined; }
3552
+ this.roadmapReadAuthority(by);
3553
+ let specs: { id: string; title: string; status: string | null }[] | undefined;
3554
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; }
3555
+ const snapshot = this.roadmapSnapshot(by);
3556
+ const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText });
3557
+ return { ...result, repo: issues?.repo ?? repo ?? null };
3558
+ }
3559
+
3560
+ /** Pending and settled suggestions as a caller may read them: public text only. */
3561
+ milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] {
3562
+ this.roadmapReadAuthority(by);
3563
+ return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row));
3564
+ }
3565
+
3566
+ private suggestionPublic(row: MilestoneSuggestion): boolean {
3567
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
3568
+ if (!this.publicMetadataText(text)) return false;
3569
+ if (row.kind !== "task") return true;
3570
+ const task = this.d.board.get(Number(row.ref));
3571
+ return task !== undefined && !this.isPii(task) && !task.signals.includes("pii");
3572
+ }
3573
+
3574
+ /**
3575
+ * Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown
3576
+ * (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`.
3577
+ */
3578
+ async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> {
3579
+ const current = this.roadmapWriteAuthority(by);
3580
+ const unplaced = await this.roadmapUnplaced(by, input, run);
3581
+ current();
3582
+ const snapshot = this.roadmapSnapshot(by), views = milestoneViews(snapshot);
3583
+ const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`));
3584
+ const items: TriageItem[] = [
3585
+ ...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })),
3586
+ ...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })),
3587
+ ...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })),
3588
+ ].filter(item => !pending.has(`${item.kind}:${item.ref}`));
3589
+ const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]");
3590
+ const batch = items.slice(0, TRIAGE_BATCH);
3591
+ const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable });
3592
+ if (!batch.length) return done([], 0, null);
3593
+ if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage");
3594
+ const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome })));
3595
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
3596
+ current();
3597
+ if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later");
3598
+ const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now();
3599
+ for (const row of parsed.suggestions) {
3600
+ // Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target.
3601
+ if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; }
3602
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
3603
+ if (!this.publicMetadataText(text)) continue;
3604
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
3605
+ current();
3606
+ // A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table.
3607
+ const made = this.d.board.addSuggestion(row, "hub", at);
3608
+ if (made) saved.push(made);
3609
+ }
3610
+ return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
3611
+ }
3612
+
3613
+ /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
3614
+ async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
3615
+ const current = this.roadmapWriteAuthority(by);
3616
+ const id = this.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id);
3617
+ if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
3618
+ if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
3619
+ if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject");
3620
+ let target = row.milestone ?? this.d.board.suggestionCreated(id);
3621
+ if (target === undefined) {
3622
+ const proposal = row.proposal;
3623
+ if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject");
3624
+ const fields = this.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome }));
3625
+ await this.roadmapScreen(fields); current();
3626
+ const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
3627
+ this.d.board.setSuggestionCreated(id, made.id); target = made.id;
3628
+ }
3629
+ const milestone = this.roadmapCurrent(target);
3630
+ const ref = this.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref));
3631
+ if (row.kind === "task" && !this.d.board.get(Number(ref))) throw new PreEffectToolRefusal("roadmap target does not exist; reject the suggestion with ahub roadmap reject");
3632
+ current();
3633
+ this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now());
3634
+ const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now());
3635
+ return { suggestion: settled, milestone: this.roadmapResult(by, target) };
3636
+ }
3637
+
3638
+ roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion {
3639
+ this.roadmapWriteAuthority(by);
3640
+ const id = this.roadmapParsed(() => milestoneId(rawId));
3641
+ return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now());
3642
+ }
3643
+
3644
+ /**
3645
+ * One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`.
3646
+ * A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub.
3647
+ */
3648
+ async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{
3649
+ repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number;
3650
+ }> {
3651
+ const current = this.roadmapWriteAuthority(by);
3652
+ if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
3653
+ if (input.apply !== undefined && typeof input.apply !== "boolean") throw new PreEffectToolRefusal("roadmap import apply must be true or false; omit it for a dry run");
3654
+ const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo);
3655
+ const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
3656
+ const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh);
3657
+ current();
3658
+ const issuesOf = new Map<number, string[]>();
3659
+ for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]);
3660
+ const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = [];
3661
+ let created = 0, linked = 0, withheld = 0;
3662
+ for (const source of milestonePages.rows) {
3663
+ const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`;
3664
+ let fields: ReturnType<typeof parseMilestoneInput>;
3665
+ try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); }
3666
+ catch { withheld++; continue; }
3667
+ const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior);
3668
+ const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.publicMetadataText(ref));
3669
+ const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []);
3670
+ const newRefs = refs.filter(ref => !have.has(ref));
3671
+ const text = `${fields.title}\n${fields.outcome}`;
3672
+ if (!this.publicMetadataText(text)) { withheld++; continue; }
3673
+ const row = { number: source.number, title: sanitize(fields.title), milestone: existing?.id ?? null, action: existing ? "exists" as const : "create" as const, issues: refs, newLinks: newRefs.length };
3674
+ if (apply) {
3675
+ // The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen.
3676
+ if (!existing && this.screenOn() && (await this.screenCall(text)).label !== "clear") { withheld++; continue; }
3677
+ current();
3678
+ const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now());
3679
+ if (made.created) created++;
3680
+ row.milestone = made.milestone.id;
3681
+ for (const ref of newRefs) {
3682
+ const live = this.d.board.milestone(made.milestone.id)!;
3683
+ // A settled milestone is final: an import never reopens or relinks it.
3684
+ if (["done", "dropped"].includes(live.state)) break;
3685
+ const before = this.d.board.milestoneLinks(made.milestone.id).length;
3686
+ this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now());
3687
+ if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++;
3688
+ }
3689
+ }
3690
+ out.push(row);
3691
+ }
3692
+ return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld };
3693
+ }
3694
+
3224
3695
  releaseList(by: PeerId): Record<string, unknown>[] {
3225
3696
  this.planningAuthority(by);
3226
3697
  const scopes = new Map<number, { id: number; state: Task["state"]; deps: number[] }[]>();
@@ -3429,7 +3900,7 @@ export class Tasks {
3429
3900
  const direct = afterParts.length ? deps.filter(dep => !parent.deps?.includes(dep)) : deps;
3430
3901
  if (direct.length + afterParts.length > 64) throw new PreEffectToolRefusal("split child dependencies exceed the 64-edge cap");
3431
3902
  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 ?? [])); }
3432
- const refs = part.refs === undefined ? parent.refs : cleanRefs(part.refs), plan = cleanPlan(part.plan, storedProfile);
3903
+ const refs = part.refs === undefined ? parent.refs : cleanRefs(part.refs), plan = cleanPlan(part.plan, storedProfile, (this.d.sdlc?.config().mode ?? "off") !== "off");
3433
3904
  // #1161: a part's plan sources are registered ids, as at propose and accept (#1144); refused before any screen or board write.
3434
3905
  this.validatePlanSources(plan);
3435
3906
  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 } : {}) } : {}) };
@@ -3696,8 +4167,8 @@ export class Tasks {
3696
4167
  if (["shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("settled release is final");
3697
4168
  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");
3698
4169
  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");
3699
- 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");
3700
- 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");
4170
+ 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");
4171
+ if (input.state === "frozen" && (release.train || (this.d.sdlc?.config().mode ?? "off") !== "off")) throw new PreEffectToolRefusal("use the resource-admitted release cut operation");
3701
4172
  if (input.state === "shipped" && release.train) {
3702
4173
  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");
3703
4174
  const readiness = releaseTrainReadiness(release, this.d.board.list());
@@ -3711,9 +4182,9 @@ export class Tasks {
3711
4182
  return updated; // a failed readback may follow a durable release write
3712
4183
  }
3713
4184
 
3714
- 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> {
4185
+ 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> {
3715
4186
  const requestCheck = this.requestCheck(by, fence);
3716
- const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev");
4187
+ const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
3717
4188
  this.validatePlanSources(plan);
3718
4189
  requireLocalTaskPeer(input.owner);
3719
4190
  external = external ? { ...external } : undefined;
@@ -3795,7 +4266,7 @@ export class Tasks {
3795
4266
  this.warmRepository({ refs: draft.refs, plan });
3796
4267
  const repositoryMismatch = !this.isPii({ signals }) && this.repositories.mismatch(draft.refs, plan);
3797
4268
  requestCheck();
3798
- 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 } : {}) });
4269
+ 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);
3799
4270
  if (repositoryMismatch) this.releaseNotice(`task #${task.id}: refs and plan name different repositories; check refs.repo before editing`);
3800
4271
  if (this.d.coordination) this.coordinationModes.set(task.id, this.d.coordination());
3801
4272
  created?.();
@@ -4330,11 +4801,13 @@ export class Tasks {
4330
4801
  const tagged = assignment.sameFamilyFallback ? `${note}; sameFamilyFallback=true` : note;
4331
4802
  const pool = assignment.reviewSelection, metadata = this.reviewMetadata(assignment);
4332
4803
  const walk = pool?.blocked ? pool.walk.slice(0, 16).map(row => {
4333
- const reason = this.nameable(row.reason) ? Array.from(sanitize(row.reason).replace(/\s+/g, " ")).slice(0, 80).join("") : "[withheld]";
4804
+ const reason = this.nameable(row.reason) ? Array.from(sanitize(row.reason).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]";
4334
4805
  return `${row.id || row.kind}: ${reason}`;
4335
4806
  }).join("; ") + (pool.walk.length > 16 ? `; +${pool.walk.length - 16} walk entries` : "") : "";
4336
- const recorded = pool ? `${tagged}; reviewerFamily=${metadata.reviewerFamily ?? "none"}; reviewerReason=${metadata.reviewerReason ?? pool.blocked}${pool.blocked ? `; pool=${pool.blocked}; walk: ${walk}` : ""}` : tagged;
4337
- return assignment.plannerFallback ? `${recorded}; reviewer=planner (fallback)` : recorded;
4807
+ const admission = pool?.admissionRule ? this.nameable(pool.admissionRule) ? Array.from(sanitize(pool.admissionRule).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]" : undefined;
4808
+ const recorded = pool ? `${tagged}; reviewerFamily=${metadata.reviewerFamily ?? "none"}; reviewerReason=${metadata.reviewerReason ?? pool.blocked}${pool.blocked ? `; pool=${pool.blocked}; walk: ${walk}` : ""}${admission ? `; reviewerQuotaRule=${admission}` : ""}` : tagged;
4809
+ const quota = pool?.quotaWait ? `; quota wait: ${pool.quotaWait.candidates.map(row => `${row.id} ${row.state}, reset ${new Date(row.resetsAt).toISOString()}`).join("; ")}` : "";
4810
+ return assignment.plannerFallback ? `${recorded}; reviewer=planner (fallback)${quota}` : recorded + quota;
4338
4811
  }
4339
4812
 
4340
4813
  /** A later move to another owner means the caller's assignment was superseded, so its success tail is not authoritative. */
@@ -4504,6 +4977,7 @@ export class Tasks {
4504
4977
  try { claimed = this.d.board.update(next.id, by, "accepted", { state: "in_progress" }); }
4505
4978
  catch (error) { undoWorktree?.(); throw error; }
4506
4979
  this.captureOwnerAcceptance(claimed);
4980
+ claimed = await this.prepareAcceptedWorktree(claimed, by, opts.current ?? this.requestCheck(by));
4507
4981
  this.releaseNotice(`task ${this.publicTitle(claimed)} claimed by ${by}`);
4508
4982
  return claimed;
4509
4983
  }
@@ -4737,6 +5211,7 @@ export class Tasks {
4737
5211
  this.scheduleQueuePressureRecheck();
4738
5212
  }
4739
5213
  private queueReviewWritten(task: Task): void {
5214
+ this.reviewQuotaTaskChanged(task);
4740
5215
  if (task.state === "in_review" && task.reviewer === USER && task.history.at(-1)?.queueReviewHeld) this.markQueuePressureCandidate();
4741
5216
  }
4742
5217
  private queuePressureAdmitted(): boolean {
@@ -4919,6 +5394,269 @@ export class Tasks {
4919
5394
  // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
4920
5395
  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)));
4921
5396
  }
5397
+ private synthesisTask(by: PeerId, id: unknown): Task {
5398
+ requireLocalTaskPeer(by);
5399
+ if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task");
5400
+ const task = this.studyParent(this.studyNumber(id, "taskId"));
5401
+ if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by)))
5402
+ throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show");
5403
+ return task;
5404
+ }
5405
+
5406
+ private synthesisPrivate(task: Task, by: PeerId): boolean {
5407
+ try { return !!this.d.privateTurn?.(by) || this.isPii(task) || !this.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); }
5408
+ catch { return true; }
5409
+ }
5410
+
5411
+ private synthesisPolicy(task: Task): string {
5412
+ let root: string | undefined;
5413
+ try { root = this.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ }
5414
+ return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]);
5415
+ }
5416
+
5417
+ private synthesisRows(links: readonly EvidenceLinkV1[]) {
5418
+ return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const }));
5419
+ }
5420
+
5421
+ private synthesisInventories(task: Task) {
5422
+ const claims = task.plan?.claims;
5423
+ if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list");
5424
+ return claims.map((_claim, index) => {
5425
+ const identity = taskClaimIdentity(task, index + 1);
5426
+ try {
5427
+ const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128);
5428
+ let contradictionHistory: ReturnType<Board["evidenceContradictionHistory"]> = { ids: [], sources: [], members: [], complete: false };
5429
+ 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. */ }
5430
+ if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false;
5431
+ return { ...identity, inventory, contradictionHistory };
5432
+ }
5433
+ catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; }
5434
+ });
5435
+ }
5436
+
5437
+ private synthesisSources(links: readonly Pick<EvidenceLinkV1, "sourceId">[]): { private: boolean; key: string; bytes: number } {
5438
+ const meta: unknown[] = [], seen = new Set<string>(); let bytes = 0;
5439
+ for (const link of links) {
5440
+ if (seen.has(link.sourceId)) continue; seen.add(link.sourceId);
5441
+ const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })();
5442
+ if (source?.private || source && !this.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 };
5443
+ meta.push([link.sourceId, source]);
5444
+ if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes;
5445
+ }
5446
+ return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes };
5447
+ }
5448
+
5449
+ /** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */
5450
+ async synthesisEvidence(by: PeerId, input: unknown) {
5451
+ const fields = this.studyFields(input, ["taskId"]), check = this.requestCheck(by, () => this.studyHold());
5452
+ return this.studyWrite(async () => {
5453
+ check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId);
5454
+ if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const };
5455
+ const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]);
5456
+ if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const };
5457
+ const delivered = latestDeliverables(task.history) ?? [];
5458
+ const artifacts = delivered.filter(record => !record.private && record.path && !this.experimentOutputPrivate(task, record.path))
5459
+ .map(({ id, sha256, format }) => ({ id, sha256, format }));
5460
+ check();
5461
+ if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" };
5462
+ return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const,
5463
+ deliverables: artifacts, claims: claims.map(claim => {
5464
+ const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory);
5465
+ return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete,
5466
+ ...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) };
5467
+ }) };
5468
+ });
5469
+ }
5470
+
5471
+ /** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */
5472
+ async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
5473
+ return this.synthesisInspect(by, input);
5474
+ }
5475
+
5476
+ private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
5477
+ 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 }>;
5478
+ 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 }> {
5479
+ const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest);
5480
+ if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry");
5481
+ const check = this.requestCheck(by, () => this.studyHold());
5482
+ return this.studyWrite(async () => {
5483
+ check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id;
5484
+ if (this.synthesisPrivate(task, by)) return { taskId, status: "private" };
5485
+ const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links);
5486
+ const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))];
5487
+ const sources = this.synthesisSources(privacyLinks);
5488
+ if (sources.private) return { taskId, status: "private" };
5489
+ const activeLinks = allLinks.filter(link => link.status !== "withdrawn");
5490
+ if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" };
5491
+ const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task);
5492
+ // ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later.
5493
+ const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]);
5494
+ const current = () => {
5495
+ try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by)
5496
+ && this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy
5497
+ && JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; }
5498
+ catch { return false; }
5499
+ };
5500
+ const changed = () => {
5501
+ check(); const now = this.synthesisTask(by, taskId);
5502
+ if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const };
5503
+ return { taskId, status: "stale" as const, cause: "context_changed" };
5504
+ };
5505
+ try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; }
5506
+ const sourceKeys = new Map<string, string | undefined>();
5507
+ for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) {
5508
+ let key: string | undefined;
5509
+ 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 */ }
5510
+ sourceKeys.set(link.sourceId, key);
5511
+ }
5512
+ if (!current()) return changed();
5513
+ const reads: { path: string; read: GuardedDeliverableRead }[] = [];
5514
+ const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise<SynthesisArtifactSnapshot | "private"> => {
5515
+ const record = delivered.find(record => record.id === reference.id);
5516
+ if (!record) return { id: reference.id, state: "missing" };
5517
+ if (record.private || !record.path || this.experimentOutputPrivate(task, record.path)) return "private";
5518
+ try {
5519
+ const read = await readGuardedDeliverable(record.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit);
5520
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data);
5521
+ if (!this.publicMetadataText(text)) return "private";
5522
+ reads.push({ path: record.path, read });
5523
+ return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text };
5524
+ } catch { return { id: record.id, state: "unknown" }; }
5525
+ };
5526
+ const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" };
5527
+ if (!current()) return changed();
5528
+ const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" };
5529
+ if (!current()) return changed();
5530
+ const observed: SynthesisCurrentClaim[] = [];
5531
+ for (const claim of before) {
5532
+ const resolutions: NonNullable<NonNullable<SynthesisCurrent["claims"]>[number]["resolutions"]>[number][] = [];
5533
+ for (const link of claim.inventory.links) {
5534
+ if (!current()) return changed();
5535
+ const withdrawn = link.status === "withdrawn";
5536
+ if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; }
5537
+ if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; }
5538
+ let resolution: EvidenceSourceRead["resolution"];
5539
+ try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; }
5540
+ catch { resolution = { status: "unavailable", cause: "source_unavailable" }; }
5541
+ if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" };
5542
+ if (!current()) return changed();
5543
+ resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" });
5544
+ }
5545
+ const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim;
5546
+ const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined;
5547
+ const synthesis = entry?.synthesis;
5548
+ observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision,
5549
+ inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) },
5550
+ contradictionHistory: claim.contradictionHistory,
5551
+ resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } });
5552
+ }
5553
+ const finalCurrent = () => {
5554
+ try {
5555
+ if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false;
5556
+ const fencedSources = new Set<string>();
5557
+ for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) {
5558
+ fencedSources.add(link.sourceId);
5559
+ if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false;
5560
+ }
5561
+ if (reads.some(value => !guardedDeliverableCurrent(value.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false;
5562
+ return this.synthesisSources(privacyLinks).key === sources.key && current();
5563
+ } catch { return false; }
5564
+ };
5565
+ if (!finalCurrent()) return changed();
5566
+ const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed };
5567
+ const report = checkSynthesis(manifest, snapshot);
5568
+ return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report;
5569
+ });
5570
+ }
5571
+
5572
+ /** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */
5573
+ async evidenceRead(by: PeerId, input: unknown): Promise<EvidenceReadResult> {
5574
+ const refuse = () => new PreEffectToolRefusal("evidence read unavailable; use a current evidence id on a research task visible through hub_task_show");
5575
+ try { requireLocalTaskPeer(by); } catch { throw refuse(); }
5576
+ if (this.d.profile !== "research") throw refuse();
5577
+ const check = this.requestCheck(by, () => this.studyHold());
5578
+ let id: string, revision: number | undefined;
5579
+ try {
5580
+ const fields = this.studyFields(input, ["id", "revision"]);
5581
+ if (Object.values(Object.getOwnPropertyDescriptors(input)).some(field => !field.enumerable)
5582
+ || typeof fields.id !== "string" || !/^ev:[a-f0-9]{32}$/.test(fields.id)
5583
+ || fields.revision !== undefined && (typeof fields.revision !== "number" || !Number.isSafeInteger(fields.revision) || fields.revision < 1)) throw refuse();
5584
+ id = fields.id; revision = fields.revision as number | undefined;
5585
+ } catch { throw refuse(); }
5586
+ return this.studyWrite(async () => {
5587
+ check(); const link = this.d.board.evidenceLink(this.d.project, id, revision);
5588
+ if (!link) throw refuse();
5589
+ const receipt = { id: link.id, revision: link.revision, taskId: link.taskId };
5590
+ const stub = (status: "private" | "stale" | "unavailable" | "withdrawn"): EvidenceReadResult => ({ ...receipt, status });
5591
+ const context = () => {
5592
+ check(); let task: Task;
5593
+ try { task = this.studyParent(link.taskId); } catch { throw refuse(); }
5594
+ if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by))) throw refuse();
5595
+ let status: "private" | "stale" | "unavailable" | undefined;
5596
+ try {
5597
+ if (this.d.privateTurn?.(by) || task.signals.includes("pii") || task.signals.includes("pii_path") || this.isPii(task)
5598
+ || this.publicMetadataText(evidenceLinkCanonical(link)) !== true) status = "private";
5599
+ } catch { status = "private"; }
5600
+ if (!status) {
5601
+ try { const identity = taskClaimIdentity(task, Number(link.claimId.split(":").at(-1))); if (identity.claimId !== link.claimId || identity.claimRevision !== link.claimRevision) status = "stale"; }
5602
+ catch { status = "stale"; }
5603
+ }
5604
+ const source = this.studySource(link.sourceId);
5605
+ if (source?.private) status = "private";
5606
+ else if (!status && !source) status = "unavailable";
5607
+ else if (!status && source?.sha256 !== link.rawSha256) status = "stale";
5608
+ return { task, status, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.plan?.claims, source]) };
5609
+ };
5610
+ const before = context(); if (before.status) return stub(before.status);
5611
+ if (link.status === "withdrawn") return stub("withdrawn");
5612
+ if (!this.d.evidenceSourceRead) return stub("unavailable");
5613
+ const current = () => { try { const next = context(); return !next.status && next.key === before.key; } catch { return false; } };
5614
+ // A returned passage can be quoted by any later tool or final answer in this input.
5615
+ // Reuse the host review-input exclusion before crossing the async read boundary.
5616
+ try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return stub("unavailable"); }
5617
+ let read: EvidenceSourceRead;
5618
+ try { read = await this.d.evidenceSourceRead(by, link, current); }
5619
+ catch { check(); const after = context(); return stub(after.status ?? "unavailable"); }
5620
+ check(); const after = context();
5621
+ if (after.status) return stub(after.status);
5622
+ if (after.key !== before.key) return stub("stale");
5623
+ const resolution = read.resolution;
5624
+ if (resolution.status !== "resolved") return stub(resolution.status === "stale" ? "stale" : resolution.cause === "private" ? "private" : "unavailable");
5625
+ const result: EvidenceReadResult = { ...receipt, status: "resolved", link, excerpt: resolution.excerpt, excerptSha256: resolution.excerptSha256, locator: resolution.locator, origins: this.evidenceOrigins(link) };
5626
+ try { if (this.publicMetadataText(JSON.stringify(result)) !== true) return stub("private"); } catch { return stub("private"); }
5627
+ if (!current()) { const final = context(); return stub(final.status ?? "stale"); }
5628
+ return result;
5629
+ });
5630
+ }
5631
+
5632
+ private evidenceOrigins(link: EvidenceLinkV1): EvidenceReadOrigins {
5633
+ const unknown: EvidenceReadOrigins = { state: "unknown" };
5634
+ if (!this.d.evidenceSourceMeta) return unknown;
5635
+ // #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;
5636
+ // 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.
5637
+ let inventory: ReturnType<Board["latestEvidenceLinks"]>;
5638
+ try { inventory = this.d.board.latestEvidenceLinks(this.d.project, link.taskId, link.claimId, link.claimRevision, 128); }
5639
+ catch (error) { if (error instanceof Error && error.message.startsWith("evidence inventory changed")) return unknown; throw error; }
5640
+ if (!inventory.complete || !inventory.links.some(row => row.id === link.id && row.revision === link.revision)) return unknown;
5641
+ try {
5642
+ const groups: Set<string>[] = [], member: { id: string; keys: readonly string[] }[] = [];
5643
+ for (const row of inventory.links.filter(row => row.status !== "withdrawn")) {
5644
+ const meta = this.d.evidenceSourceMeta(row.sourceId);
5645
+ if (!meta || meta.id !== row.sourceId || meta.private || meta.sha256 !== row.rawSha256 || this.publicMetadataText(JSON.stringify(meta)) !== true) return unknown;
5646
+ const keys = evidenceOriginKeys(meta); if (!keys?.length) return unknown;
5647
+ member.push({ id: row.id, keys });
5648
+ const matches = groups.filter(group => keys.some(key => group.has(key)));
5649
+ const merged = new Set([...keys, ...matches.flatMap(group => [...group])]);
5650
+ for (const group of matches) groups.splice(groups.indexOf(group), 1);
5651
+ groups.push(merged);
5652
+ }
5653
+ const selected = member.find(row => row.id === link.id), group = selected && groups.find(group => selected.keys.some(key => group.has(key)));
5654
+ if (!group) return unknown;
5655
+ // Connected registered origins express provenance grouping only, never independent corroboration or source quality.
5656
+ return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length };
5657
+ } catch { return unknown; }
5658
+ }
5659
+
4922
5660
  /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
4923
5661
  private lineageMetadata(text: string): boolean {
4924
5662
  try {
@@ -5575,7 +6313,7 @@ export class Tasks {
5575
6313
  try { requireLocalTaskPeer(by); }
5576
6314
  catch { throw new PreEffectToolRefusal("remote peers cannot record local evidence; ask the current local research task owner to record it"); }
5577
6315
  const requestCheck = this.requestCheck(by, () => this.studyHold());
5578
- let proposed: EvidenceRecordInput;
6316
+ let proposed: ReturnType<typeof parseEvidenceRecord>;
5579
6317
  try { proposed = parseEvidenceRecord(input); }
5580
6318
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid evidence record; check the bounded evidence fields before retrying"); }
5581
6319
  return this.studyWrite(async () => {
@@ -5584,7 +6322,10 @@ export class Tasks {
5584
6322
  let task: Task;
5585
6323
  try { task = this.studyParent(proposed.taskId); }
5586
6324
  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"); }
5587
- 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");
6325
+ const personWithdrawal = by === USER && proposed.status === "withdrawn";
6326
+ if (task.profile === "research" && (task.owner === by || personWithdrawal) && isClosedTaskState(task.state))
6327
+ 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");
6328
+ 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");
5588
6329
  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");
5589
6330
  let identity;
5590
6331
  try { identity = taskClaimIdentity(task, Number(proposed.claimId.split(":").at(-1))); }
@@ -5624,7 +6365,7 @@ export class Tasks {
5624
6365
  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");
5625
6366
  requirePublicMetadata();
5626
6367
  requireRevision();
5627
- const saved = this.d.board.recordEvidenceLink(this.d.project, link, { taskFlowRevision: current.task.history.length, taskCreated: current.task.created, owner: by });
6368
+ 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 } : {}) });
5628
6369
  return { id: saved.id, revision: saved.revision, taskId: saved.taskId };
5629
6370
  });
5630
6371
  }
@@ -5635,14 +6376,72 @@ export class Tasks {
5635
6376
  * 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).
5636
6377
  */
5637
6378
  recordClaimVerdict(by: PeerId, id: unknown, input: unknown): Task {
6379
+ return this.writeClaimVerdict(by, id, input);
6380
+ }
6381
+
6382
+ /** Refresh host bindings without changing the person's selected citation mappings or keeping a second manifest store. */
6383
+ private currentSynthesisManifest(manifest: SynthesisManifestV1, current: SynthesisCurrent): SynthesisManifestV1 | undefined {
6384
+ try {
6385
+ if (!current.deliverable?.sha256 || !current.bibliography?.sha256 || !current.claims) return;
6386
+ const currentClaims = current.claims;
6387
+ const ordered = [...manifest.claims.flatMap(ref => currentClaims.filter(claim => claim.claimId === ref.claimId)),
6388
+ ...currentClaims.filter(claim => !manifest.claims.some(ref => ref.claimId === claim.claimId))];
6389
+ const claims = ordered.map(claim => {
6390
+ if (!claim.inventory) throw new Error("incomplete inventory");
6391
+ const inventory = inventoryBinding(claim.inventory.links, claim.inventory.complete, claim.contradictionHistory);
6392
+ if (!inventory) throw new Error("incomplete inventory");
6393
+ const links = claim.inventory.links.map(row => "link" in row ? row.link : row);
6394
+ const evidence = (manifest.claims.find(row => row.claimId === claim.claimId)?.evidence ?? []).map(ref => {
6395
+ const latest = links.find(link => link.id === ref.id);
6396
+ if (!latest) throw new Error("selected link unavailable");
6397
+ return { ...ref, revision: latest.revision };
6398
+ });
6399
+ return { claimId: claim.claimId, claimRevision: claim.claimRevision, inventory, evidence };
6400
+ });
6401
+ return parseSynthesisManifest({ schemaVersion: 1, taskId: current.taskId, taskCreated: current.taskCreated,
6402
+ deliverable: { id: current.deliverable.id, sha256: current.deliverable.sha256 },
6403
+ bibliography: { id: current.bibliography.id, sha256: current.bibliography.sha256 }, claims });
6404
+ } catch { return; }
6405
+ }
6406
+
6407
+ /** Same console claim authority/store; the descriptor is transient and the write stays inside the final snapshot fence. */
6408
+ async recordSynthesisClaimVerdict(by: PeerId, id: unknown, input: unknown, manifest: unknown): Promise<Task> {
6409
+ if (by !== USER) throw new PreEffectToolRefusal("only the console user may record a claim verdict");
6410
+ const task = this.need(id), claim = parseClaimVerdict(input, task.plan?.claims?.length ?? 0), boardRevision = this.d.board.statusRevision();
6411
+ if (!claim.synthesis) throw new PreEffectToolRefusal("a synthesis verdict requires a manifest file and resolved or qualified disposition through ahub task claim");
6412
+ const result = await this.synthesisInspect(by, { taskId: task.id, manifest }, (supplied, current, report, valid) => {
6413
+ const refreshed = this.currentSynthesisManifest(supplied, current);
6414
+ if (!refreshed) throw new PreEffectToolRefusal("current synthesis manifest unavailable; refresh complete inventory, selected evidence and registered artifacts before recording a disposition");
6415
+ const hash = synthesisManifestHash(refreshed);
6416
+ if (!valid()) throw new PreEffectToolRefusal("synthesis context changed before the claim verdict write; refresh current public inputs and retry");
6417
+ if (claim.synthesis!.manifestSha256 !== hash || synthesisManifestHash(supplied) !== hash)
6418
+ throw new PreEffectToolRefusal(`synthesis manifest changed; current manifestSha256 ${hash}; refresh the manifest file and explicitly record the disposition again`);
6419
+ if (!("scope" in report) || report.binding !== "current" || report.claimCoverage !== "complete"
6420
+ || report.deliverable !== "unchanged" || report.bibliography !== "unchanged"
6421
+ || report.claims.some(row => row.claim !== "current" || row.inventory !== "current" || row.evidenceLink !== "present" || row.locator !== "resolved" || row.provenance !== "resolved"))
6422
+ throw new PreEffectToolRefusal("current synthesis provenance is unavailable or stale; resolve current source/locator and artifact statuses before recording a disposition");
6423
+ return this.writeClaimVerdict(by, task.id, claim, { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length,
6424
+ claimRevision: taskClaimIdentity(task, claim.slot).claimRevision });
6425
+ });
6426
+ if (!("history" in result)) {
6427
+ 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");
6428
+ throw new PreEffectToolRefusal("current synthesis is private, unavailable or changed; refresh public inputs before recording a disposition");
6429
+ }
6430
+ return result;
6431
+ }
6432
+
6433
+ private writeClaimVerdict(by: PeerId, id: unknown, input: unknown, verifiedSynthesis?: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task {
5638
6434
  if (by !== USER) throw new Error("only the console user may record a claim verdict");
5639
6435
  if (this.d.cancellationHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new Error("recovery or shutdown is holding task writes");
5640
6436
  const task = this.need(id);
5641
6437
  const claims = task.plan?.claims?.length ?? 0;
5642
6438
  if (!claims) throw new Error(`task #${task.id} declares no plan claims: add them to its plan first`);
5643
6439
  const claim = parseClaimVerdict(input, claims);
6440
+ if (claim.synthesis && !verifiedSynthesis) throw new PreEffectToolRefusal("a synthesis disposition needs current manifest validation; use ahub task claim with --manifest <manifest.json> and --disposition");
6441
+ if (claim.synthesis && (this.d.profile !== "research" || task.profile !== "research")) throw new Error("synthesis dispositions require a research task and profile");
5644
6442
  // 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.
5645
6443
  const identity = taskClaimIdentity(task, claim.slot);
6444
+ if (verifiedSynthesis) return this.d.board.recordSynthesisClaimVerdict(task.id, { ...claim, list: identity.claimRevision }, verifiedSynthesis);
5646
6445
  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
5647
6446
  }
5648
6447
 
@@ -5662,7 +6461,7 @@ export class Tasks {
5662
6461
  this.planningAuthority(by, task);
5663
6462
  const proposer = task.history.find(h => h.event === "proposed" || h.event === "backlogged")?.by;
5664
6463
  // #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.
5665
- 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");
6464
+ 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)` : ""}`);
5666
6465
  }
5667
6466
  return task;
5668
6467
  };
@@ -6425,7 +7224,7 @@ export class Tasks {
6425
7224
 
6426
7225
  /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */
6427
7226
  private deliveryLinks(config: SdlcConfig): DeliveryTask[] {
6428
- 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) } }));
7227
+ 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) } }));
6429
7228
  }
6430
7229
 
6431
7230
  /**
@@ -6476,6 +7275,431 @@ export class Tasks {
6476
7275
  }
6477
7276
  return report;
6478
7277
  }
7278
+
7279
+ /** #1403 A4: a summary of the newest audit for the release report: ref, profile, partial and unit counts, never a finding or a path. */
7280
+ auditLine(): AuditSummary | undefined {
7281
+ const audit = this.d.board.audits(1)[0];
7282
+ 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;
7283
+ }
7284
+
7285
+ private surveyToolInput<T>(command: "start" | "report", field: string, rule: string, read: () => T): T {
7286
+ try { return surveyInputAt(field, rule, read); } catch (error) {
7287
+ const problem = surveyInputProblem(error) ?? { field, rule };
7288
+ const next = command === "report" ? "fix that field and resend hub_survey_report; tool description lists shape"
7289
+ : "fix that field and resend ahub sdlc survey start; ahub help sdlc survey lists shape";
7290
+ throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; ${next}`);
7291
+ }
7292
+ }
7293
+ private surveyStarting = false;
7294
+ private surveyAdmit(by: PeerId, check: () => void): void {
7295
+ check();
7296
+ if ((this.d.sdlc?.config().mode ?? "off") === "off") throw new PreEffectToolRefusal("advisor surveys require lifecycle advise or enforce");
7297
+ 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");
7298
+ const held = this.studyHold(); if (held) throw new PreEffectToolRefusal(held);
7299
+ }
7300
+ private surveyTask(by: PeerId, id: unknown, write = false): { task: Task; survey: StoredSurvey } {
7301
+ const task = this.need(this.studyNumber(id, "survey task")), survey = this.d.board.surveyOfTask(task.id, task.created);
7302
+ 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");
7303
+ const owner = task.owner === by && this.d.bus.isRostered(by) && this.isConfiguredPlanner(by);
7304
+ const reviewer = task.reviewer === by && this.d.bus.isRostered(by) && !!this.d.roles?.[by]?.includes("reviewer");
7305
+ if (write ? !owner || task.state !== "in_progress" : by !== USER && !owner && !reviewer && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by)))
7306
+ throw new PreEffectToolRefusal("survey reporting requires its assigned in-progress planner; readback requires its owner, reviewer, person or current conductor");
7307
+ return { task, survey };
7308
+ }
7309
+ private surveyPrivate(task: Task, by?: PeerId): boolean {
7310
+ return this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path") || !!(by && this.d.privateTurn?.(by));
7311
+ }
7312
+ /** The existing task routing chooses one planner; no worker, scanner, issue or fix is launched. */
7313
+ async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> {
7314
+ const fields = this.surveyToolInput("start", "start", "must be a closed object with optional focus", () => surveyObject(input, ["focus"])), focus = fields.focus;
7315
+ 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"); });
7316
+ const check = this.requestCheck(by, fence), authority = () => {
7317
+ this.surveyAdmit(by, check);
7318
+ 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");
7319
+ };
7320
+ authority();
7321
+ if (this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey start is unavailable from observer material");
7322
+ if (this.surveyStarting) throw new PreEffectToolRefusal("a survey is already starting");
7323
+ const repo = this.repositories.scope({}).key, source = this.d.auditSource;
7324
+ if (!source) throw new PreEffectToolRefusal("survey source unavailable; start the hub from the project checkout");
7325
+ const ref = source.head();
7326
+ 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");
7327
+ if (this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("a survey is already open; finish or cancel it first");
7328
+ 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)}`;
7329
+ if (!this.publicMetadataText(brief)) throw new PreEffectToolRefusal("survey brief is not public");
7330
+ this.surveyStarting = true;
7331
+ try { return await this.studyWrite(async () => {
7332
+ 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"); };
7333
+ guard();
7334
+ let surveyID: number | undefined;
7335
+ const task = await this.propose(by, { title: `Advisor survey${focus ? ` (${focus})` : ""} at ${ref.slice(0, 12)}`, detail: brief, class: "plan" }, undefined, undefined,
7336
+ () => { guard(); return undefined; }, created => {
7337
+ if (this.surveyPrivate(created, by)) throw new PreEffectToolRefusal("survey brief privacy was not cleared");
7338
+ 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() });
7339
+ });
7340
+ return { task: task.id, survey: surveyID!, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) };
7341
+ }); } finally { this.surveyStarting = false; }
7342
+ }
7343
+ private consideredChanges(repo: string, ref?: string): (entryRef?: string) => string[] | undefined {
7344
+ // 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.
7345
+ const cache = new Map<string, string[] | undefined>(); let currentKnown: boolean | undefined;
7346
+ return entryRef => {
7347
+ if (!entryRef || !ref || entryRef === ref || repo !== this.repositories.scope({}).key) return undefined;
7348
+ if (cache.has(entryRef)) return cache.get(entryRef);
7349
+ let changed: string[] | undefined;
7350
+ try {
7351
+ currentKnown ??= this.d.auditSource?.resolve(ref) === ref;
7352
+ if (currentKnown && this.d.auditSource?.resolve(entryRef) === entryRef) changed = this.d.auditSource.changed(entryRef, ref);
7353
+ } catch { currentKnown ??= false; /* Per-call unknown evidence stays unknown; no cross-call freshness cache. */ }
7354
+ cache.set(entryRef, changed); return changed;
7355
+ };
7356
+ }
7357
+ /** Same semantic identity and affected literal paths only; unreadable change evidence never clears suppression. */
7358
+ 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 } {
7359
+ const neutral = { rejectedBefore: false, change: "none" as const, suppressed: false };
7360
+ if (positionalFindingId(finding.id) || (this.d.sdlc?.config().mode ?? "off") === "off" || this.surveyPrivate(task)) return neutral;
7361
+ const repo = this.repositories.scope(task.refs).key, ledger = this.d.board.rejectedFindingsFor(repo, finding.pass, finding.id, 1000);
7362
+ if (!ledger.complete) return { rejectedBefore: true, change: "unknown", suppressed: true };
7363
+ const matched = ledger.rows.filter(row => row.entry.id === finding.id && row.entry.pass === finding.pass);
7364
+ if (!matched.length) return neutral;
7365
+ if (repo !== this.repositories.scope({}).key) return { rejectedBefore: true, change: "unknown", suppressed: true };
7366
+ const currentRef = ref, paths = "paths" in finding ? finding.paths : finding.path ? (() => { try { return [surveyPath(finding.path)]; } catch { return []; } })() : [];
7367
+ const changes = readChanges ?? this.consideredChanges(repo, ref);
7368
+ let seen = false, unknown = false, unchanged = false;
7369
+ const overlaps = (a: string, b: string) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
7370
+ for (const row of matched) {
7371
+ seen = true;
7372
+ const changed = changes(row.entry.ref);
7373
+ 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 } }) });
7374
+ if (match.status === "unknown" || !paths.length) unknown = true;
7375
+ if (match.status === "applicable" && match.applicablePaths.some(path => paths.some(candidate => overlaps(path, candidate)))) unchanged = true;
7376
+ }
7377
+ return !seen ? neutral : { rejectedBefore: true, change: unknown ? "unknown" : unchanged ? "unchanged" : "changed", suppressed: unknown || unchanged };
7378
+ }
7379
+ private consideredPaths(path: string | undefined): string[] {
7380
+ if (!path) return [];
7381
+ try {
7382
+ let name = path.replace(/:[1-9][0-9]*(?::[1-9][0-9]*)?$/, "");
7383
+ if (isAbsolute(name)) name = relative(this.d.cwd, name);
7384
+ return [surveyPath(name)];
7385
+ } catch { return []; }
7386
+ }
7387
+ private consideredPublic(entry: ConsideredEntry): boolean {
7388
+ try {
7389
+ const source = this.d.board.get(entry.source.task);
7390
+ if (entry.withheld || entry.pass === "security" || !source || source.created !== entry.source.created || this.surveyPrivate(source)) return false;
7391
+ const { repo: _scope, ...data } = entry;
7392
+ 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");
7393
+ } catch { return false; }
7394
+ }
7395
+ /** Bounded public historical reasons; never expose internal scope keys, security text or paths. */
7396
+ 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 }[] } {
7397
+ const publicId = this.publicMetadataText(id) ? id : "withheld";
7398
+ const ledger = this.d.board.rejectedFindingsFor(repo, pass, id, 1000);
7399
+ if (!ledger.complete) return { complete: false, change: "unknown", items: [{ id: publicId, change: "unknown", withheld: true }] };
7400
+ const changes = readChanges ?? this.consideredChanges(repo, ref);
7401
+ const items = ledger.rows.slice(0, 16).map(row => {
7402
+ const entry = row.entry;
7403
+ const changed = changes(entry.ref);
7404
+ 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;
7405
+ const change = match?.status === "applicable" ? "unchanged" as const : match?.status === "changed" ? "changed" as const : "unknown" as const;
7406
+ return { id: publicId, change, ...(this.consideredPublic(entry) ? { reason: entry.reason } : { withheld: true as const }) };
7407
+ });
7408
+ 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";
7409
+ return { complete: ledger.rows.length <= 16, change, items };
7410
+ }
7411
+ consideredBrief(repo: string, ref?: string, scope?: readonly string[]): string {
7412
+ const ledger = this.d.board.rejectedFindings(repo, 1000);
7413
+ if (!ledger.complete) return "Previously rejected findings: history incomplete; change is unknown and rejection remains in effect.";
7414
+ const lines = ["Previously rejected findings (unknown change retains rejection; positional ids never match across tasks):"], seen = new Set<string>(), changes = this.consideredChanges(repo, ref);
7415
+ for (const row of ledger.rows) {
7416
+ const entry = row.entry, key = `${entry.pass}:${entry.id}`;
7417
+ 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;
7418
+ seen.add(key);
7419
+ const details = this.consideredDetails(repo, entry.id, entry.pass, ref, changes), detail = details.items[0];
7420
+ const reason = detail?.reason ? `: ${Array.from(detail.reason).slice(0, 160).join("")}${Array.from(detail.reason).length > 160 ? "..." : ""}` : " (details withheld)";
7421
+ const line = `${entry.pass}:${detail?.id ?? "withheld"}: rejected before; change ${details.change}${reason}`;
7422
+ 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; }
7423
+ lines.push(line);
7424
+ }
7425
+ if (lines.length === 1) lines.push("No matching recorded rejections.");
7426
+ return lines.join("\n");
7427
+ }
7428
+ /** Saved facts stay local. Private/sensitive facts retain a withheld identity stub without a cloud screen. */
7429
+ async recordConsideredFinding(task: Task, finding: ReviewFinding, reason: string | undefined, kind: "review" | "audit" | "survey", ref?: string): Promise<number | undefined> {
7430
+ if ((this.d.sdlc?.config().mode ?? "off") === "off") return;
7431
+ return this.studyWrite(async () => {
7432
+ const revision = this.d.board.statusRevision(), current = this.d.board.get(task.id);
7433
+ if (!current || current.created !== task.created || current.history.length !== task.history.length || this.studyHold()) return;
7434
+ const normalized = typeof reason === "string" ? reason.replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim() : "";
7435
+ const safeReason = normalized && Buffer.byteLength(normalized) <= 2048 ? normalized : "reason not recorded";
7436
+ const paths = this.consideredPaths(finding.path), privateFact = this.surveyPrivate(current) || !!task.history.at(-1)?.withheld;
7437
+ 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,
7438
+ ...(ref && /^[a-f0-9]{40}$/.test(ref) ? { ref } : {}), source: { task: task.id, created: task.created, kind }, ...(privateFact || finding.pass === "security" ? { withheld: true } : {}) });
7439
+ const { repo: _internalScope, ...publicEntry } = entry;
7440
+ if (!this.publicMetadataText(JSON.stringify(publicEntry))) entry = { ...entry, paths: [], reason: "reason not recorded", withheld: true };
7441
+ const now = this.d.board.get(task.id);
7442
+ if (!now || now.created !== task.created || now.history.length !== task.history.length || this.d.board.statusRevision() !== revision
7443
+ || (this.d.sdlc?.config().mode ?? "off") === "off" || this.studyHold() || this.repositories.scope(now.refs).key !== entry.repo) return;
7444
+ return this.d.board.recordRejectedFinding(entry);
7445
+ });
7446
+ }
7447
+ private recordConsideredAfter(task: Task, findings: readonly ReviewFinding[], kind: "review" | "audit", ref?: string): void {
7448
+ if ((this.d.sdlc?.config().mode ?? "off") === "off" || !findings.length) return;
7449
+ this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`, () => {
7450
+ void Promise.all(findings.map(finding => this.recordConsideredFinding(task, finding, kind === "audit" ? undefined : finding.rationale, kind, ref)))
7451
+ .then(ids => { if (ids.some(id => id === undefined)) this.releaseNotice(`task #${task.id}: considered rejection ledger admission changed; source decision remains saved`); })
7452
+ .catch(() => this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`));
7453
+ });
7454
+ }
7455
+ surveyShow(by: PeerId, id: unknown) {
7456
+ const check = this.requestCheck(by); this.surveyAdmit(by, check);
7457
+ const { task, survey } = this.surveyTask(by, id);
7458
+ if (this.surveyPrivate(task, by)) return { task: task.id, status: "private" as const };
7459
+ const revision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]);
7460
+ const full = by === USER || this.d.bus.isRostered(by) && (task.owner === by && this.isConfiguredPlanner(by) || task.reviewer === by && !!this.d.roles?.[by]?.includes("reviewer"));
7461
+ const stored = this.d.board.surveyFindings(survey.id), changes = this.consideredChanges(survey.repo, survey.ref);
7462
+ 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 };
7463
+ const items = stored.map(row => {
7464
+ const finding = full ? row.finding : publicSurveyFinding(row.finding), before = this.consideredBefore(task, row.finding, survey.ref, changes);
7465
+ const details = this.consideredDetails(survey.repo, row.finding.id, row.finding.pass, survey.ref, changes);
7466
+ return { ...finding, ...(row.decision ? { verdict: row.decision.verdict } : {}), ...before, rejected: details.items, rejectedComplete: details.complete };
7467
+ });
7468
+ this.surveyAdmit(by, check);
7469
+ const now = this.surveyTask(by, id);
7470
+ if (this.surveyPrivate(now.task, by)) return { task: task.id, status: "private" as const };
7471
+ 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");
7472
+ return { task: task.id, survey: survey.id, ref: survey.ref, ...(survey.focus ? { focus: survey.focus } : {}), status: "available" as const, items };
7473
+ }
7474
+ async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) {
7475
+ const fields = this.surveyToolInput("report", "report", "must be a closed object with id and findings, vet or show", () => surveyObject(input, ["id", "findings", "vet", "show"]));
7476
+ 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"); });
7477
+ this.surveyToolInput("report", "show", "must be true for read-only show and cannot include findings or vet decisions", () => {
7478
+ if (fields.show !== undefined && fields.show !== true || fields.show && (fields.findings !== undefined || fields.vet !== undefined)) throw new Error("invalid bounded survey data");
7479
+ });
7480
+ if (fields.show) { this.requestCheck(by, fence)(); return this.surveyShow(by, fields.id); }
7481
+ const findings = fields.findings === undefined ? [] : this.surveyToolInput("report", "findings", "must match the documented finding array", () => parseSurveyFindings(fields.findings));
7482
+ const decisions = fields.vet === undefined ? [] : this.surveyToolInput("report", "vet", "must match the documented vet array", () => parseSurveyVetDecisions(fields.vet));
7483
+ const check = this.requestCheck(by, fence), guard = () => { this.surveyAdmit(by, check); return this.surveyTask(by, fields.id, true); };
7484
+ const initial = guard();
7485
+ if (this.surveyPrivate(initial.task, by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey writes unavailable during private or observer work");
7486
+ 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");
7487
+ const observerExcluded = this.observerExcluded(by); // Capture before any awaited screen; never forward observer material.
7488
+ if (observerExcluded) throw new PreEffectToolRefusal("survey observer input is unavailable");
7489
+ return this.studyWrite(async () => {
7490
+ 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]);
7491
+ const current = () => {
7492
+ const now = guard();
7493
+ if (now.task.created !== task.created || now.task.history.length !== task.history.length || now.task.owner !== task.owner || this.surveyPrivate(now.task, by)
7494
+ || 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");
7495
+ };
7496
+ const existing = this.d.board.surveyFindings(survey.id), merged = new Map(existing.map(row => [row.finding.id, row.finding]));
7497
+ 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); }
7498
+ const text = JSON.stringify({ findings: this.surveyToolInput("report", "findings", "combined findings must remain within the documented bounds", () => parseSurveyFindings([...merged.values()])), decisions });
7499
+ if (!this.publicMetadataText(text)) throw new PreEffectToolRefusal("survey metadata was not cleared as public");
7500
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("survey metadata privacy screening was unavailable or refused");
7501
+ current();
7502
+ const changes = this.consideredChanges(survey.repo, survey.ref);
7503
+ const cards: SurveyPreparedCard[] = [], rejections: ConsideredEntry[] = [], reconsiderations: ConsideredEntry[] = [];
7504
+ const items: { id: string; rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean }[] = [];
7505
+ for (const decision of decisions) {
7506
+ 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");
7507
+ const before = this.consideredBefore(task, finding, survey.ref, changes); items.push({ id: finding.id, ...before });
7508
+ const entry = (reason: string): ConsideredEntry => ({ repo: survey.repo, id: finding.id, pass: finding.pass, paths: finding.paths, reason, ref: survey.ref,
7509
+ source: { task: task.id, created: task.created, kind: "survey" }, ...(finding.pass === "security" ? { withheld: true } : {}) });
7510
+ if (decision.verdict === "rejected") { rejections.push(entry(decision.reason!)); continue; }
7511
+ if (before.suppressed && !decision.reason) continue;
7512
+ if (before.rejectedBefore && decision.reason) reconsiderations.push(entry(decision.reason));
7513
+ const key = surveyFindingKey(survey.repo, finding.pass, finding.id), security = finding.pass === "security";
7514
+ const history = this.d.board.surveyCardHistory(key), reopens = history.active ? undefined : history.closed;
7515
+ current();
7516
+ const reopenReason = security ? "explicit current vet; security details remain in the authorized survey"
7517
+ : decision.reason ?? (before.change === "changed" ? "affected paths changed since the recorded rejection" : "explicit current vet; no applicable rejected finding remains");
7518
+ const reopening = reopens === undefined ? {} : { reopens, reopenReason };
7519
+ const draft = { title: security ? `Survey security finding ${finding.id}` : `Survey ${finding.confidence}: ${finding.id}`,
7520
+ 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}`}`,
7521
+ refs: security ? {} : { paths: finding.paths } };
7522
+ if (Buffer.byteLength(draft.detail) > SURVEY_LIMITS.cardBytes) throw new PreEffectToolRefusal("survey card exceeds its detail bound; shorten the finding or reconsideration reason");
7523
+ const signals = this.signalsFor(draft);
7524
+ 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");
7525
+ if (this.screenOn() && (await this.screenCall(JSON.stringify(draft))).label !== "clear") throw new PreEffectToolRefusal("survey card privacy screening was unavailable or refused");
7526
+ current(); cards.push({ id: finding.id, key, ...draft, class: finding.confidence === "low" ? "triage" : "plan", signals, ...reopening });
7527
+ }
7528
+ current();
7529
+ const result = this.d.board.surveyApply(survey.id, { findings, decisions, by, at: this.d.now?.() ?? Date.now(), cards, rejections, reconsiderations },
7530
+ { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, owner: task.owner! });
7531
+ for (const id of result.createdIDs) this.incomingBacklog.add(id);
7532
+ this.releaseNotice(`survey task ${task.id}: ${result.createdIDs.length} backlog candidates created`);
7533
+ return { task: task.id, survey: survey.id, status: "recorded" as const, ...result, items };
7534
+ });
7535
+ }
7536
+
7537
+ private auditCarry(head: string, source: AuditSource): CarryLookup {
7538
+ const audits = this.d.board.audits(32, true), changed = new Map<string, string[] | undefined>();
7539
+ const since = (base: string) => { if (!changed.has(base)) changed.set(base, source.changed(base, head)); return changed.get(base); };
7540
+ return (surface, companion) => {
7541
+ const id = unitId(surface, companion);
7542
+ for (const audit of audits) {
7543
+ const unit = audit.units.find(row => row.unit === id);
7544
+ // 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.
7545
+ if (!unit) continue;
7546
+ if (unit.state !== "covered") return undefined;
7547
+ const base = unit.prior?.head ?? audit.ref, origin = unit.prior?.audit ?? audit.id, paths = since(base);
7548
+ // Unknown never carries: an unreadable change list, or a changed path under the surface, plans the unit again.
7549
+ return paths && !paths.some(path => matchConfigPath(surface, path)) ? { audit: origin, head: base } : undefined;
7550
+ }
7551
+ return undefined;
7552
+ };
7553
+ }
7554
+
7555
+ /**
7556
+ * #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`
7557
+ * (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.
7558
+ */
7559
+ 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 }> {
7560
+ const check = this.requestCheck(by, fence);
7561
+ 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");
7562
+ 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");
7563
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
7564
+ if (config.mode === "off") throw new PreEffectToolRefusal("security audits need the lifecycle on: set sdlc.mode to advise or enforce in .agenthub/sdlc.toml");
7565
+ if (!config.security) throw new PreEffectToolRefusal("security audits need a [security] table in .agenthub/sdlc.toml (paths and companions)");
7566
+ const source = this.d.auditSource;
7567
+ 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");
7568
+ const profile = input.profile === undefined ? "standard" : input.profile;
7569
+ if (typeof profile !== "string" || !(AUDIT_PROFILES as readonly string[]).includes(profile)) throw new PreEffectToolRefusal(`profile is one of ${AUDIT_PROFILES.join(", ")}`);
7570
+ const head = source.head();
7571
+ if (!head) throw new PreEffectToolRefusal("the checkout's head commit could not be read; run the audit from a git checkout with a commit");
7572
+ let scoped: string[] | undefined;
7573
+ if (input.since !== undefined) {
7574
+ 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");
7575
+ const base = source.resolve(input.since.trim());
7576
+ if (!base) throw new PreEffectToolRefusal("--since does not name a commit in this checkout");
7577
+ scoped = source.changed(base, head);
7578
+ if (!scoped) throw new PreEffectToolRefusal("the paths changed since that ref could not be listed completely; narrow --since or run an unscoped audit");
7579
+ }
7580
+ 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");
7581
+ const units = seedLedger(config.security, profile as AuditProfile, { ...(scoped ? { scoped } : {}), carry: this.auditCarry(head, source) });
7582
+ if (!units.length) throw new PreEffectToolRefusal("no configured security surface has a changed path in that scope; nothing to audit");
7583
+ const partial = auditIsPartial(profile as AuditProfile, scoped !== undefined);
7584
+ const inline = units.filter(u => !u.prior).slice(0, 40), cut = units.filter(u => !u.prior).length - inline.length;
7585
+ 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)` : "")
7586
+ + "\n" + this.consideredBrief(this.repositories.scope({}).key, head, config.security.paths);
7587
+ check();
7588
+ const task = await this.propose(by, { title: `Security audit (${profile}${scoped ? ", scoped" : ""}) at ${head.slice(0, 12)}`, detail: brief, class: "review" }, undefined, undefined, fence);
7589
+ let audit: number;
7590
+ try {
7591
+ if (this.isPii(task)) throw new PreEffectToolRefusal("the audit brief matched a private-data pattern; rename the configured surface");
7592
+ 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 });
7593
+ } catch (error) {
7594
+ // The ledger is the audit: a task without one would be an empty promise, so it is cancelled rather than left to run.
7595
+ await this.cancel(task.id, by, { reason: "security audit ledger could not be created" }).catch(() => undefined);
7596
+ throw error;
7597
+ }
7598
+ 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 };
7599
+ }
7600
+
7601
+ private auditView(audit: NonNullable<ReturnType<Board["audit"]>>, full: boolean): AuditView {
7602
+ const findings = this.d.board.auditFindings(audit.id);
7603
+ const summary = auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, findings);
7604
+ 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 }) };
7605
+ }
7606
+
7607
+ /** `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. */
7608
+ auditShow(by: PeerId, id?: unknown): AuditView | undefined {
7609
+ 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");
7610
+ if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("the audit readback is unavailable in a private turn");
7611
+ 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;
7612
+ if (id !== undefined && !audit) throw new PreEffectToolRefusal("no such security audit");
7613
+ return audit ? this.auditView(audit, by === USER) : undefined;
7614
+ }
7615
+
7616
+ /**
7617
+ * #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
7618
+ * 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
7619
+ * auditor, a reviewer-role peer or the person, and never rides a message to anyone else.
7620
+ */
7621
+ async auditReport(by: PeerId, input: { id?: unknown; units?: unknown; findings?: unknown; verify?: unknown; settle?: unknown; show?: unknown }, fence?: () => string | undefined): Promise<AuditView> {
7622
+ const check = this.requestCheck(by, fence);
7623
+ const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
7624
+ if (config.mode === "off" || !config.security) throw new PreEffectToolRefusal("audit reports need the lifecycle on and a [security] table in .agenthub/sdlc.toml");
7625
+ 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");
7626
+ if (!Number.isSafeInteger(input.id) || (input.id as number) <= 0) throw new PreEffectToolRefusal("hub_audit_report needs the audit task id");
7627
+ const task = this.d.board.get(input.id as number), audit = task ? this.d.board.auditOfTask(task.id, task.created) : undefined;
7628
+ if (!task || !audit) throw new PreEffectToolRefusal("no security audit on that task");
7629
+ if (this.isPii(task)) throw new PreEffectToolRefusal("that task is private");
7630
+ const isOwner = by !== USER && task.owner === by && task.state === "in_progress";
7631
+ const reviewerRole = by !== USER && (this.d.roles?.[by] ?? []).includes("reviewer") && this.d.bus.isRostered(by);
7632
+ const writes = input.units !== undefined || input.findings !== undefined, verifies = input.verify !== undefined, settles = input.settle !== undefined;
7633
+ 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");
7634
+ if (writes && !isOwner) throw new PreEffectToolRefusal("only the assigned auditor reports units and findings, while the audit task is in progress");
7635
+ if (verifies && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer or the person verifies a finding");
7636
+ 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");
7637
+ if ((verifies || settles) && (task.state === "cancelled" || task.state === "backlog")) throw new PreEffectToolRefusal("the audit task is closed");
7638
+ if (!isOwner && !reviewerRole && by !== USER) throw new PreEffectToolRefusal("only the auditor, a reviewer-role peer or the person reads an audit report");
7639
+ const when = this.d.now?.() ?? Date.now();
7640
+ let units = audit.units, filed: { finding: ReviewFinding; foundBy: string; at: number }[] = [];
7641
+ const decisions: { finding: string; verdict: "verified" | "rejected" }[] = [];
7642
+ const settlements: { finding: string; disposition: "fixed" | "false_positive" }[] = [];
7643
+ if (input.units !== undefined) {
7644
+ try { units = applyUnitReports(audit.units, parseUnitReports(input.units, audit.units), by, when); }
7645
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid units"); }
7646
+ }
7647
+ if (input.findings !== undefined) {
7648
+ let parsed: ReviewFinding[];
7649
+ try { parsed = parseReviewFindings(input.findings, { person: false, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: "required" }); }
7650
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid findings"); }
7651
+ if (parsed.some(item => item.pass !== "security")) throw new PreEffectToolRefusal("an audit takes security findings only (pass: security)");
7652
+ if (parsed.some(item => item.anchor !== undefined)) throw new PreEffectToolRefusal("anchors belong to review verdicts; name the file in path");
7653
+ const text = JSON.stringify(parsed);
7654
+ 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");
7655
+ filed = parsed.map(finding => ({ finding, foundBy: by, at: when }));
7656
+ }
7657
+ if (input.verify !== undefined) {
7658
+ 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}");
7659
+ const stored = this.d.board.auditFindings(audit.id);
7660
+ for (const item of input.verify as unknown[]) {
7661
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
7662
+ 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}");
7663
+ const refusal = verificationRefusal(stored.find(row => row.finding.id === record.finding), by);
7664
+ if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
7665
+ decisions.push({ finding: record.finding, verdict: record.verdict });
7666
+ }
7667
+ if (new Set(decisions.map(d => d.finding)).size !== decisions.length) throw new PreEffectToolRefusal("a finding is decided once per call");
7668
+ }
7669
+ if (input.settle !== undefined) {
7670
+ 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}");
7671
+ const stored = this.d.board.auditFindings(audit.id);
7672
+ for (const item of input.settle as unknown[]) {
7673
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record<string, unknown> : undefined;
7674
+ 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}");
7675
+ const refusal = settlementRefusal(stored.find(row => row.finding.id === record.finding), by);
7676
+ if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`);
7677
+ settlements.push({ finding: record.finding, disposition: record.disposition as "fixed" | "false_positive" });
7678
+ }
7679
+ if (new Set(settlements.map(item => item.finding)).size !== settlements.length) throw new PreEffectToolRefusal("a finding is settled once per call");
7680
+ // 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.
7681
+ if (settlements.some(item => decisions.some(decision => decision.finding === item.finding))) throw new PreEffectToolRefusal("verify a finding and settle it in separate calls");
7682
+ }
7683
+ check();
7684
+ const now = this.d.board.audit(audit.id), nowTask = this.d.board.get(task.id);
7685
+ 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");
7686
+ // One transaction: a unit report, its findings, the verifications and the settlements land together or not at all.
7687
+ const skipped = this.d.board.auditApply(audit.id, { units: writes ? units : undefined, findings: filed, decisions, ...(settlements.length ? { settlements } : {}), by });
7688
+ if (skipped === undefined) throw new PreEffectToolRefusal("a finding was decided meanwhile; read the audit again and retry");
7689
+ try {
7690
+ const rejected = new Set(decisions.filter(row => row.verdict === "rejected").map(row => row.finding));
7691
+ const falsePositives = new Set(settlements.filter(row => row.disposition === "false_positive").map(row => row.finding));
7692
+ const savedAudit = this.d.board.audit(audit.id);
7693
+ if (savedAudit?.task === nowTask.id && savedAudit.taskCreated === nowTask.created) {
7694
+ const saved = this.d.board.auditFindings(audit.id).filter(row => rejected.has(row.finding.id) && row.rejectedBy === by
7695
+ || falsePositives.has(row.finding.id) && row.settledAs === "false_positive" && row.settledBy === by);
7696
+ this.recordConsideredAfter(nowTask, saved.map(row => row.finding), "audit", savedAudit.ref);
7697
+ }
7698
+ } catch { this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`); }
7699
+ const full = this.d.board.audit(audit.id)!;
7700
+ return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) };
7701
+ }
7702
+
6479
7703
  /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
6480
7704
  async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
6481
7705
  const check = this.requestCheck(by, fence);
@@ -6698,6 +7922,8 @@ export class Tasks {
6698
7922
  const publicShipped = this.d.board.releases().filter(release => !rowsNow.some(task => task.release === release.id && this.isPii(task)));
6699
7923
  const metrics = publicShipped.some(release => release.state === "shipped") ? releaseMetrics(publicShipped, rowsNow.filter(task => !this.isPii(task))) : undefined;
6700
7924
  if (metrics) report.releaseMetrics = metrics;
7925
+ const audit = this.auditLine();
7926
+ if (audit) report.securityAudit = audit;
6701
7927
  const trains = this.d.board.releases().filter(release => release.train && ["active", "frozen"].includes(release.state));
6702
7928
  if (trains.length) {
6703
7929
  const planned = trains.map(release => {
@@ -6733,13 +7959,13 @@ export class Tasks {
6733
7959
  return JSON.stringify([task.refs, task.sdlc, task.plan, task.owner, task.reviewer, task.state, this.isPii(task), this.d.sdlc?.config()]);
6734
7960
  }
6735
7961
  private planReadIdentity(task: Task): string { return JSON.stringify([task.sdlc?.repo, task.sdlc?.pr, task.refs.repo, planFingerprint(task.plan ?? {})]); }
6736
- private planPaths(task: Task): string[] | undefined {
7962
+ private planPaths(task: Task, key: "paths" | "out_of_scope" = "paths"): string[] | undefined {
6737
7963
  if (!task.sdlc?.repo) return;
6738
7964
  // Resolve the artifact slug first: it may warm the canonical project's previously unnamed identity.
6739
7965
  const artifact = this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths });
6740
7966
  const scope = this.repositories.scope(task.refs);
6741
7967
  if (scope.key !== artifact.key) return;
6742
- return task.plan?.paths?.map(path => scope === this.repositories.project ? this.projectPath(path) : this.repositories.relativePath(scope, path));
7968
+ return task.plan?.[key]?.map(path => scope === this.repositories.project ? this.projectPath(path) : this.repositories.relativePath(scope, path));
6743
7969
  }
6744
7970
  private planScopeIdentity(task: Task): string {
6745
7971
  const paths = this.planPaths(task); // Warm verified aliases before capturing the scope identity.
@@ -6754,8 +7980,18 @@ export class Tasks {
6754
7980
  return latest > invalidated && task.history[latest]!.planDeparture!.generation === this.departureGeneration
6755
7981
  && task.history[latest]!.planDeparture!.scope === this.planScopeIdentity(task) ? [task.history[latest]!.planDeparture!] : [];
6756
7982
  }
7983
+ /**
7984
+ * #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
7985
+ * reviewed; `proposed` is the pass on the verdict being written (not on the board yet). A PII task and an off lifecycle compute nothing.
7986
+ */
7987
+ private securityView(task: Task, evidence: PrEvidence | undefined, proposed?: SecurityPassRecord): SecurityPassView | undefined {
7988
+ const config = this.d.sdlc?.config();
7989
+ if (!config || config.mode === "off" || !config.security || this.isPii(task)) return undefined;
7990
+ const recorded = proposed ?? task.history.findLast(entry => entry.securityPass && !entry.withheld && (entry.event === "approved" || entry.event === "changes_requested"))?.securityPass;
7991
+ return securityPassView(config.security, evidence, recorded);
7992
+ }
6757
7993
  private planReport(task: Task, evidence?: PrEvidence) {
6758
- const rawReport = planConformance(this.isPii(task) ? undefined : this.planPaths(task), this.isPii(task) ? undefined : evidence);
7994
+ 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);
6759
7995
  const safe = [...rawReport.outside, ...rawReport.untouched].every(path => this.publicMetadataText(path));
6760
7996
  const report: PlanConformance = safe ? rawReport : { state: "unknown", head: rawReport.head, outside: [], untouched: [] };
6761
7997
  const fingerprint = planFingerprint(task.plan ?? {});
@@ -6831,7 +8067,7 @@ export class Tasks {
6831
8067
  if (this.planIdentity(current) !== this.planIdentity(task) || current.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed during lifecycle readback");
6832
8068
  this.capturePlanRead(current, evidence);
6833
8069
  return sdlcStatus(config, current.sdlc, evidence, this.workflowView(current), edit, this.isPii(current) ? [] : this.reviewFindingSets(current), current.refs.commit,
6834
- config.mode !== "off" ? this.planReport(this.d.board.get(current.id)!, evidence) : undefined, integrity, evalResult);
8070
+ config.mode !== "off" ? this.planReport(this.d.board.get(current.id)!, evidence) : undefined, integrity, evalResult, this.securityView(current, evidence));
6835
8071
  }
6836
8072
 
6837
8073
  /** #481 S1: only build work starts from an accepted spec. */
@@ -7027,7 +8263,7 @@ export class Tasks {
7027
8263
 
7028
8264
  /** The eval record the last approval-time lifecycle read produced for a task; consumed by the verdict that follows it. */
7029
8265
  private readonly evalRecords = new Map<number, string>();
7030
- private async lifecycleGate(task: Task, transition: "review" | "approval", reviewedHead?: string, findings?: readonly ReviewFindingSet[], refileHead?: RefileHeadGuard): Promise<PrEvidence | undefined> {
8266
+ private async lifecycleGate(task: Task, transition: "review" | "approval", reviewedHead?: string, findings?: readonly ReviewFindingSet[], refileHead?: RefileHeadGuard, securityPass?: SecurityPassRecord): Promise<PrEvidence | undefined> {
7031
8267
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
7032
8268
  if (config.mode === "off") return;
7033
8269
  const receipt = task.sdlc && { ...task.sdlc, ...(reviewedHead ? { reviewedHead } : {}) };
@@ -7065,7 +8301,7 @@ export class Tasks {
7065
8301
  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;
7066
8302
  this.capturePlanRead(current, evidence);
7067
8303
  const planReport = this.planReport(current, evidence);
7068
- const status = sdlcStatus(config, receipt, evidence, this.workflowView(current), undefined, this.isPii(current) ? [] : findings ?? this.reviewFindingSets(current), current.refs.commit, planReport, integrity, evalResult);
8304
+ 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));
7069
8305
  // #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.
7070
8306
  const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name));
7071
8307
  const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker);
@@ -7075,7 +8311,7 @@ export class Tasks {
7075
8311
  const gate = status.evalGate;
7076
8312
  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}`);
7077
8313
  else this.evalRecords.delete(task.id);
7078
- const advice = [...new Set([...blockers, ...planConformanceBlockers(planReport), ...testIntegrityBlockers(integrity), ...evalAdvice(status.evalGate)])];
8314
+ const advice = [...new Set([...blockers, ...planConformanceBlockers(planReport), ...testIntegrityBlockers(integrity), ...evalAdvice(status.evalGate), ...securityPassBlockers(status.securityPass)])];
7079
8315
  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("; ")}`);
7080
8316
  return evidence;
7081
8317
  }
@@ -7106,13 +8342,13 @@ export class Tasks {
7106
8342
  const task = this.need(id, false, true);
7107
8343
  this.mine(task, by, "owner", true);
7108
8344
  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
7109
- const proposedPlan = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev");
8345
+ 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");
7110
8346
  this.validatePlanSources(proposedPlan && Object.keys(proposedPlan).length ? proposedPlan : task.plan);
7111
8347
  this.acceptanceCapacity(task, 0, "check"); // #1080: an urgent task may still take unaccepted offers; `accept` does that, after its gates
7112
8348
  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");
7113
8349
  let draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task;
7114
8350
  this.warmRepository(draft);
7115
- if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.accept(by, id, plan, metadata);
8351
+ if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata), by, requestCheck);
7116
8352
  const spec = await this.specGate(by, id, draft.refs);
7117
8353
  if (spec?.carry) draft = metadata ? { ...spec.task, refs: { ...spec.task.refs, ...metadata } } : spec.task;
7118
8354
  await this.planEntryGate(by, draft, spec?.carry);
@@ -7121,7 +8357,7 @@ export class Tasks {
7121
8357
  this.mine(current, by, "owner", true);
7122
8358
  if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during build admission");
7123
8359
  this.reviewedAdmissions.set(current.id, { flow: current.history.length, owner: current.owner });
7124
- try { return this.accept(by, id, plan, metadata, spec?.carry); }
8360
+ try { return await this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata, spec?.carry), by, requestCheck); }
7125
8361
  finally { this.reviewedAdmissions.delete(current.id); }
7126
8362
  }
7127
8363
 
@@ -7243,7 +8479,7 @@ export class Tasks {
7243
8479
  if (by !== USER && task.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_ACCEPT(task.id));
7244
8480
  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`);
7245
8481
  // Models send null or {} for an optional field they leave empty: neither replaces a plan.
7246
- const given = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev");
8482
+ 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");
7247
8483
  // File-list intent still replaces the old lists; omitted budget keys retain the planner-reviewed scope.
7248
8484
  const cleaned = given && Object.keys(given).length ? { ...cleanCostPlan(task.plan ?? {}), ...given } : undefined;
7249
8485
  this.validatePlanSources(cleaned ?? task.plan);
@@ -7335,7 +8571,8 @@ export class Tasks {
7335
8571
  takeDoneNote = (id: number): string | undefined => {
7336
8572
  const note = this.doneNotes.get(id);
7337
8573
  this.doneNotes.delete(id);
7338
- return note;
8574
+ const task = this.d.board.get(id);
8575
+ return [note, task ? this.planDriftText(task, "done") : ""].filter(Boolean).join("\n") || undefined;
7339
8576
  };
7340
8577
  /** #572 AC3: what the owner's `hub_task_done` result adds while the project root checkout is on a task branch. */
7341
8578
  checkoutNote = (): string | undefined => { const warning = mainCheckoutWarning(this.d.cwd, this.publicMetadataText); return warning ? `Note: ${warning}.` : undefined; };
@@ -7356,7 +8593,37 @@ export class Tasks {
7356
8593
  /** The hub-made worktree of the task's owner, for the accept answer: where to edit, and what the hub does at `hub_task_done`. */
7357
8594
  worktreeNote(task: Task, peer: PeerId): string | undefined {
7358
8595
  const found = this.d.taskWorktree?.describe(peer, task.id);
7359
- return found ? `Worktree: the hub made ${found.path} on branch ${found.branch} for this task. Edit files there only; do not run git. At hub_task_done the hub stages, commits and pushes it for you.` : undefined;
8596
+ return found ? [`Worktree: the hub made ${found.path} on branch ${found.branch} for this task. Edit files there only; do not run git. At hub_task_done the hub stages, commits and pushes it for you.`, this.dependencyNote(task, peer)].filter(Boolean).join("\n") : undefined;
8597
+ }
8598
+
8599
+ private dependencyNote(task: Task, peer: PeerId): string | undefined {
8600
+ const state = this.d.taskWorktree?.dependencyState?.(peer, task.id);
8601
+ return state ? `Task #${task.id} dependencies ${state.ready ? "prepared" : `not prepared: ${state.reason}`}. Full checks stay with CI and the remote runner.` : undefined;
8602
+ }
8603
+
8604
+ /** Only fixed readiness/cause text for this peer's current public work reaches its next prompt. */
8605
+ dependencyNotes(peer: PeerId): string | undefined {
8606
+ return this.d.board.list().filter(task => task.owner === peer && task.state === "in_progress" && !this.isPii(task))
8607
+ .map(task => this.dependencyNote(task, peer)).filter(Boolean).join("\n") || undefined;
8608
+ }
8609
+
8610
+ private async prepareAcceptedWorktree(task: Task, actor: PeerId, requestCheck: () => void): Promise<Task> {
8611
+ const port = this.d.taskWorktree;
8612
+ const peer = task.owner ?? actor;
8613
+ if (!port?.prepareDependencies || !port.preparesDependencies?.(peer) || !port.describe(peer, task.id)) return task;
8614
+ const acceptance = this.ownerAcceptance(task)?.index;
8615
+ const current = () => {
8616
+ try {
8617
+ requestCheck();
8618
+ const row = this.d.board.get(task.id);
8619
+ return !!row && row.created === task.created && row.owner === peer && row.state === "in_progress"
8620
+ && !this.isPii(row) && this.ownerAcceptance(row)?.index === acceptance;
8621
+ } catch { return false; }
8622
+ };
8623
+ await port.prepareDependencies({ peer, task: task.id, current });
8624
+ // Acceptance is already a board effect. Do not describe a lost request as pre-effect.
8625
+ if (!current()) throw new Error(`task #${task.id} changed owner, session or privacy during dependency preparation; read pending notices and call hub_task_list before continuing`);
8626
+ return this.d.board.get(task.id)!;
7360
8627
  }
7361
8628
 
7362
8629
  /**
@@ -7580,10 +8847,11 @@ export class Tasks {
7580
8847
  }
7581
8848
 
7582
8849
  async done(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise<Task> {
8850
+ const observerExcluded = this.observerExcluded(by);
7583
8851
  const requestCheck = this.requestCheck(by);
7584
8852
  const initial = this.need(id, false, true);
7585
8853
  this.mine(initial, by, "owner", true);
7586
- const reviewObserverTurn = this.reviewObserverTurn(by, initial.id);
8854
+ const reviewObserverTurn = observerExcluded || this.reviewObserverTurn(by, initial.id);
7587
8855
  const resolvedReviewComments = this.reviewCommentResolve(by, initial, resolved);
7588
8856
  let refresh: CompletionRefresh | undefined;
7589
8857
  if (initial.state === "in_review" || initial.state === "approved") {
@@ -7610,7 +8878,7 @@ export class Tasks {
7610
8878
  // #509a: a bad claim (a claimed hash, an outside or denied path, a missing file) is refused before any effect, with nothing recorded.
7611
8879
  const claims = deliverables === undefined ? undefined : this.deliverableClaims(deliverables, valid());
7612
8880
  // The PII screen reads the summary of a done that passes these checks (issue #198); they run again after it.
7613
- const withheld = await this.withholds("summary", summary, valid());
8881
+ const withheld = observerExcluded || await this.withholds("summary", summary, valid());
7614
8882
  let task = valid();
7615
8883
  // The hub hashes the files itself, once, here: what the owner delivered is what this read, whatever the file becomes afterwards.
7616
8884
  const records = claims ? await this.hashClaims(claims, task, true) : undefined;
@@ -7686,7 +8954,7 @@ export class Tasks {
7686
8954
  const seen = { events: pending.history.length, owner: pending.owner };
7687
8955
  this.pendingChecks++;
7688
8956
  this.checkQueue = this.checkQueue
7689
- .then(() => this.finishChecked(pending.id, by, summary, command, seen, withheld, specInspection, resolvedReviewComments, reviewObserverTurn))
8957
+ .then(() => this.finishChecked(pending.id, by, summary, command, seen, withheld, specInspection, resolvedReviewComments, reviewObserverTurn, observerExcluded))
7690
8958
  .catch((e: Error) => {
7691
8959
  this.releaseNotice(`task #${pending.id}: its check result could not be recorded: ${e.message}`);
7692
8960
  this.releaseNotice(`task #${pending.id}: its owner retry notice could not be published`, () => {
@@ -7789,7 +9057,7 @@ export class Tasks {
7789
9057
  return { ...(key ? { checkKey: key } : {}), ...(match ? { missingKeys: Number(match[2]) } : {}) };
7790
9058
  }
7791
9059
 
7792
- 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> {
9060
+ 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> {
7793
9061
  const result = await this.d.runCheck!(command).catch((e: Error) => ({ code: null, timedOut: false, interrupted: false, tail: e.message }));
7794
9062
  const checkOwner = this.checking.get(id);
7795
9063
  this.checking.delete(id);
@@ -7826,7 +9094,7 @@ export class Tasks {
7826
9094
  if (task.owner) this.d.board.recordOutcome(task.owner, task.class, false);
7827
9095
  this.contradict(task);
7828
9096
  this.d.notify(`task ${this.publicTitle(task)}: its check failed (${outcome}); it stays with ${task.owner ?? by}`);
7829
- 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));
9097
+ 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));
7830
9098
  }
7831
9099
 
7832
9100
  /** `gated`: the transition `done()` already gated with no await since, so it is not read back twice (#382). */
@@ -7841,7 +9109,8 @@ export class Tasks {
7841
9109
  let selection = this.poolReview(task, refs);
7842
9110
  let reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined), reviewEvidence: PrEvidence | undefined;
7843
9111
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off" && gated !== (reviewer ? "review" : "approval")) {
7844
- reviewEvidence = await this.lifecycleGate(task, reviewer ? "review" : "approval");
9112
+ // #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.
9113
+ reviewEvidence = await this.lifecycleGate(draft?.commit ? { ...task, refs: { ...task.refs, commit: draft.commit } } : task, reviewer ? "review" : "approval");
7845
9114
  requestCheck();
7846
9115
  task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, false, refresh), draft), link, refs);
7847
9116
  if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; }
@@ -7859,7 +9128,7 @@ export class Tasks {
7859
9128
  reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined);
7860
9129
  const reviewCost: ReviewCost | undefined = reviewer && task.plan && (task.plan.review || task.plan.ci)
7861
9130
  ? { ...cleanCostPlan(task.plan), ...(admission?.ready && admission.head ? { head: admission.head } : {}) } : undefined;
7862
- const routedSummary = selection?.reviewSelection?.blocked ? `${summary ?? ""}\nReview routing: ${this.assignmentNote("pool unavailable", selection)}`.trim() : summary;
9131
+ 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;
7863
9132
  if (refresh?.state === "approved") {
7864
9133
  await this.unmergedForReopen(task, () => { requestCheck(); return this.completionCurrent(task.id, by, true, refresh); });
7865
9134
  task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, true, refresh), draft), link, refs);
@@ -7878,7 +9147,8 @@ export class Tasks {
7878
9147
  const noWrites = this.noWritesRecorded({ ...task, refs: storedRefs });
7879
9148
  const capacity = this.capacityBefore(task);
7880
9149
  reviewObserverExcluded ||= this.reviewObserverTurn(by, task.id);
7881
- 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);
9150
+ const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined;
9151
+ 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);
7882
9152
  this.queueReviewWritten(next);
7883
9153
  this.writePlannerNotices(next, capacity, next.state === "approved");
7884
9154
  this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); // a newer head or a move ends the old head's watcher (#785 P1b)
@@ -7892,9 +9162,10 @@ export class Tasks {
7892
9162
  this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}, no reviewer: approved`);
7893
9163
  await this.releaseDependents(next);
7894
9164
  }
9165
+ else if (quotaWaiting) this.releaseNotice(`task ${this.publicTitle(next)}: waiting for reviewer quota reset`);
7895
9166
  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]`);
7896
9167
  else this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, "", admission));
7897
- if (reviewer && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next);
9168
+ if (reviewer && !quotaWaiting && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next);
7898
9169
  return next;
7899
9170
  }
7900
9171
 
@@ -7985,10 +9256,34 @@ export class Tasks {
7985
9256
  } catch { return []; } // Optional memory cannot refuse an assignment or review.
7986
9257
  }
7987
9258
 
9259
+ /** #1403 B1: no checkout-HEAD fallback, foreign repository read or admission effect. */
9260
+ private planDriftText(task: Task, stage: "accept" | "done"): string {
9261
+ if ((this.d.sdlc?.config().mode ?? "off") === "off" || !task.plan?.base || this.isPii(task) || task.owner && this.d.privateTurn?.(task.owner)) return "";
9262
+ let report: import("./plan-conformance.ts").PlanDrift = { state: "unknown", paths: [] };
9263
+ try {
9264
+ const source = this.d.auditSource, base = task.plan.base;
9265
+ if (source?.defaultTip && source.mergeBase && /^[a-f0-9]{40}$/.test(base)
9266
+ && this.repositories.scope(task.refs).key === this.repositories.project.key
9267
+ && (!task.sdlc?.repo || this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths }).key === this.repositories.project.key)
9268
+ && source.resolve(base) === base) {
9269
+ const tip = source.defaultTip(), head = stage === "done" ? this.reviewHead(task) : undefined;
9270
+ const endpoint = tip && /^[a-f0-9]{40}$/.test(tip) && source.resolve(tip) === tip
9271
+ ? stage === "accept" ? tip : head && /^[a-f0-9]{40}$/.test(head) && source.resolve(head) === head ? source.mergeBase(head, tip) : undefined
9272
+ : undefined;
9273
+ if (endpoint && /^[a-f0-9]{40}$/.test(endpoint) && source.resolve(endpoint) === endpoint && source.mergeBase(base, endpoint) === base) {
9274
+ report = planDrift(task.plan.paths?.map(path => this.projectPath(path)), source.changed(base, endpoint));
9275
+ if (source.defaultTip() !== tip) report = { state: "unknown", paths: [] };
9276
+ }
9277
+ }
9278
+ if (report.paths.some(path => !this.publicMetadataText(path))) report = { state: "unknown", paths: [] };
9279
+ } catch { /* Optional local Git evidence is unknown, never a failed task transition. */ }
9280
+ return `Plan drift at ${stage} (upstream advice only): drift: ${report.state}${report.paths.length ? ` (${report.paths.join("; ")})` : ""}`;
9281
+ }
9282
+
7988
9283
  /** Current plan advice for an accepted plan's tool result, which has no new assignment envelope. */
7989
9284
  planGuardText(task: Task): string {
7990
9285
  const items = this.planGuardItems(task);
7991
- return items.length ? ["Live fail notes for this plan (advice, not a block):", ...items.map(item => item.line)].join("\n") : "";
9286
+ 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");
7992
9287
  }
7993
9288
 
7994
9289
  /** The one place a review request is written: the first reviewer and a replacement get the same text, refs and privacy. */
@@ -8090,6 +9385,9 @@ export class Tasks {
8090
9385
  const cachedPlanRead = this.planReads.get(task.id);
8091
9386
  const planRead = this.planReport(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined);
8092
9387
  const conformanceText = mode !== "off" ? this.screen(task, `Plan conformance: ${JSON.stringify(planRead)}`, "plan conformance", reviewer) + "\n" : "";
9388
+ // #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.
9389
+ const securityLine = mode !== "off" ? securityRequestLine(this.securityView(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined)) : undefined;
9390
+ const securityText = securityLine ? this.screen(task, securityLine, "security pass", reviewer) + "\n" : "";
8093
9391
  const profile = (task.profile ?? "dev") === (this.d.profile ?? "dev") ? profileData(this.d.profileData ?? task.profile ?? "dev") : profileData(task.profile);
8094
9392
  const target = plan ? `the plan (${plan})` : task.detail ? "the task detail above" : "the task title";
8095
9393
  const noCheckWording = profile.name === "research" || profile.name === "writing"
@@ -8159,7 +9457,7 @@ export class Tasks {
8159
9457
  const brief = this.briefText(task);
8160
9458
  // #572 AC3: advisory only, from git state never from task text, so it is safe for a PII task too.
8161
9459
  const checkout = mainCheckoutWarning(this.d.cwd, this.publicMetadataText);
8162
- 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.`;
9460
+ 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.`;
8163
9461
  const comments = this.d.board.reviewCommentCounts(task.id, task.created);
8164
9462
  const quoteMaterial = task.history.some(entry => entry.reviewFindings?.items.some(item => item.anchor !== undefined))
8165
9463
  || comments.sent + comments.resolved + comments.dismissed > 0;
@@ -8225,7 +9523,84 @@ export class Tasks {
8225
9523
  }
8226
9524
 
8227
9525
  /** Daemon shutdown: no watcher outlives the hub. */
8228
- stopCiWatchers(): void { this.ciWatchers.stopAll(); this.heldReviews.clear(); }
9526
+ private readonly reviewerQuotaTimers = new Map<number, { key: string; timer: ReturnType<typeof setTimeout> }>();
9527
+ private readonly reviewerQuotaRunning = new Set<number>();
9528
+ private reviewerQuotaStopped = false;
9529
+ private priorReviewerQuotaWait(task: Task): NonNullable<ReviewerHistory["reviewerQuotaWait"]> | undefined {
9530
+ const binding = this.queueReviewBinding(task), firstReview = task.history.findIndex(row => row.event === "done");
9531
+ // Role routing before the first completion never starts a review deadline.
9532
+ return firstReview < 0 ? undefined : task.history.slice(firstReview).findLast(row => row.reviewerQuotaWait?.created === task.created && row.reviewerQuotaWait.binding === binding)?.reviewerQuotaWait;
9533
+ }
9534
+ private activeReviewerQuotaWait(task: Task): NonNullable<ReviewerHistory["reviewerQuotaWait"]> | undefined {
9535
+ const role = task.history[this.reviewRequestRevision(task) - 1];
9536
+ return task.state === "in_review" && task.reviewer === null && !this.isPii(task) && !this.manuallyNamedReviewer(task)
9537
+ && role?.reviewerQuotaWait?.created === task.created && role.reviewerQuotaWait.binding === this.queueReviewBinding(task)
9538
+ ? role.reviewerQuotaWait : undefined;
9539
+ }
9540
+ /** Host board-change hook: a changed head/incarnation/privacy/role cancels the old deadline immediately. */
9541
+ reviewQuotaTaskChanged(task: Task): void {
9542
+ const wait = this.activeReviewerQuotaWait(task), prior = this.reviewerQuotaTimers.get(task.id);
9543
+ const key = wait ? JSON.stringify([task.created, wait.binding, wait.since, wait.deadline, wait.resetAt, this.reviewRequestRevision(task)]) : undefined;
9544
+ if (prior?.key === key) return;
9545
+ if (prior) clearTimeout(prior.timer);
9546
+ this.reviewerQuotaTimers.delete(task.id);
9547
+ if (!wait || this.reviewerQuotaStopped || this.studyHold()) return;
9548
+ const now = this.d.now?.() ?? Date.now();
9549
+ const wake = wait.resetAt > now ? wait.resetAt : wait.resetAt + 60_000 > now ? wait.resetAt + 60_000 : wait.deadline;
9550
+ const timer = setTimeout(() => {
9551
+ if (this.reviewerQuotaTimers.get(task.id)?.key !== key) return;
9552
+ this.reviewerQuotaTimers.delete(task.id);
9553
+ void this.refreshReviewerQuotaWait(task.id).catch(() => {});
9554
+ }, Math.min(2_147_483_647, Math.max(0, Math.min(wait.deadline, wake) - now)));
9555
+ timer.unref?.(); this.reviewerQuotaTimers.set(task.id, { key: key!, timer });
9556
+ }
9557
+ /** Reading/reset signals and recovery release call this; no quota polling or native transport is added. */
9558
+ refreshReviewerQuotaWaits(): void {
9559
+ if (this.reviewerQuotaStopped || this.studyHold()) return;
9560
+ for (const task of this.d.board.list("in_review")) {
9561
+ this.reviewQuotaTaskChanged(task);
9562
+ if (this.activeReviewerQuotaWait(task)) void this.refreshReviewerQuotaWait(task.id).catch(() => {});
9563
+ }
9564
+ }
9565
+ private async refreshReviewerQuotaWait(id: number): Promise<void> {
9566
+ if (this.reviewerQuotaStopped || this.reviewerQuotaRunning.has(id) || this.studyHold()) return;
9567
+ this.reviewerQuotaRunning.add(id);
9568
+ try { await this.studyWrite(async () => {
9569
+ const before = this.d.board.get(id), wait = before && this.activeReviewerQuotaWait(before);
9570
+ if (!before || !wait) return;
9571
+ const revision = this.reviewRequestRevision(before), identity = JSON.stringify([before.created, wait.binding, wait.since, wait.deadline]);
9572
+ const valid = () => {
9573
+ const task = this.d.board.get(id), live = task && this.activeReviewerQuotaWait(task);
9574
+ return !this.reviewerQuotaStopped && !this.studyHold() && task && live && this.reviewRequestRevision(task) === revision
9575
+ && JSON.stringify([task.created, live.binding, live.since, live.deadline]) === identity ? task : undefined;
9576
+ };
9577
+ const choose = (task: Task) => assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}) });
9578
+ let selection = choose(before);
9579
+ if (selection.reviewSelection?.quotaWait) {
9580
+ if (selection.reviewSelection.quotaWait.resetsAt !== wait.resetAt) {
9581
+ 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);
9582
+ this.queueReviewWritten(next);
9583
+ } else this.reviewQuotaTaskChanged(before);
9584
+ return;
9585
+ }
9586
+ let admission: ReviewReadiness | undefined, admissionFailed = false;
9587
+ // Ending an account wait is not permission to send native review input. A person fallback needs no native admission.
9588
+ if (selection.reviewer && selection.reviewer !== USER) {
9589
+ try { admission = await this.reviewRequestAdmission(before, undefined, true, before.owner ?? USER, undefined, () => !!valid()); }
9590
+ catch { admissionFailed = true; }
9591
+ }
9592
+ const task = valid(); if (!task) return;
9593
+ selection = choose(task);
9594
+ if (selection.reviewSelection?.quotaWait) { this.reviewQuotaTaskChanged(task); return; }
9595
+ // Failed readiness/authority never sends native facts, but cannot extend the original quota deadline.
9596
+ const reviewer = admissionFailed ? USER : selection.reviewer ?? USER;
9597
+ 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);
9598
+ this.queueReviewWritten(next);
9599
+ if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)}: reviewer quota wait ended; the person must review`);
9600
+ else this.releaseNotice(`task ${this.publicTitle(next)}: review request unavailable after quota wait`, () => this.sendReview(next, reviewer, "", admission));
9601
+ }); } finally { this.reviewerQuotaRunning.delete(id); }
9602
+ }
9603
+ stopCiWatchers(): void { this.ciWatchers.stopAll(); this.heldReviews.clear(); this.reviewerQuotaStopped = true; for (const row of this.reviewerQuotaTimers.values()) clearTimeout(row.timer); this.reviewerQuotaTimers.clear(); }
8229
9604
 
8230
9605
  private reviewRequestRevision(task: Task): number {
8231
9606
  // Role changes fence older requests; bookkeeping appended after the request does not.
@@ -8241,7 +9616,7 @@ export class Tasks {
8241
9616
  }
8242
9617
 
8243
9618
  /** Host-only failure report, bound to the exact review request and its still-current child generation. */
8244
- async retryReviewer(id: number, failedPeer: PeerId, failure: { head?: string; flowRevision?: number; cause: "start_failed" | "quota" | "no_verdict" }, current: () => boolean, onReoffered?: () => void): Promise<Task> {
9619
+ 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> {
8245
9620
  requireLocalTaskPeer(failedPeer);
8246
9621
  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");
8247
9622
  const valid = () => {
@@ -8255,17 +9630,19 @@ export class Tasks {
8255
9630
  const options = this.reviewPoolOptions(task);
8256
9631
  // A person-selected reviewer never falls through to an agent the person did not select.
8257
9632
  const manual = this.manuallyNamedReviewer(task);
8258
- 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] } });
9633
+ 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] } });
8259
9634
  if (!selection?.reviewSelection && failure.cause !== "no_verdict") throw new PreEffectToolRefusal("no declared reviewer pool can receive the fallback");
9635
+ const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined;
8260
9636
  const reviewer = selection?.reviewSelection ? selection.reviewer ?? USER : USER;
8261
9637
  valid();
8262
9638
  const note = manual ? "named reviewer recorded no verdict; the person must review"
8263
- : selection?.reviewSelection ? this.assignmentNote(`reviewer unavailable: ${failure.cause}`, selection) : "no declared reviewer pool can receive the fallback; the person must review";
8264
- 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);
9639
+ : selection?.reviewSelection ? this.assignmentNote(`reviewer unavailable: ${failure.reason ?? failure.cause}`, selection) : "no declared reviewer pool can receive the fallback; the person must review";
9640
+ 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);
8265
9641
  this.queueReviewWritten(next);
8266
9642
  this.releaseNotice(`task ${this.publicTitle(next)}: former review request withdrawal incomplete`, () => this.withdrawRoleRequest(task, next, "reviewer"));
8267
- let offered = false;
8268
- if (reviewer === USER) {
9643
+ let offered = quotaWaiting;
9644
+ if (quotaWaiting) { try { onReoffered?.(); } catch { /* The saved wait remains authoritative. */ } }
9645
+ else if (reviewer === USER) {
8269
9646
  const notice = `task ${this.publicTitle(next)}: blocked: the person must review`;
8270
9647
  this.releaseNotice(notice, () => { this.d.notify(notice); offered = true; });
8271
9648
  } else this.releaseNotice(`task ${this.publicTitle(next)}: fallback review request unavailable`, () => { offered = this.sendReview(next, reviewer, "", admission); });
@@ -8345,11 +9722,12 @@ export class Tasks {
8345
9722
  } catch { return prefix("Review brief unavailable: it could not be built."); }
8346
9723
  }
8347
9724
 
8348
- async review(by: PeerId, id: unknown, verdict: unknown, note?: string, unmet?: unknown, head?: unknown, coverage?: unknown, findings?: unknown): Promise<Task> {
9725
+ async review(by: PeerId, id: unknown, verdict: unknown, note?: string, unmet?: unknown, head?: unknown, coverage?: unknown, findings?: unknown, securityPass?: unknown): Promise<Task> {
8349
9726
  if (by !== USER && hasReviewAnchorInput(findings)) {
8350
9727
  try { this.d.onReviewObserverInput?.(by); }
8351
9728
  catch { throw new PreEffectToolRefusal("the anchored review input could not be privately scoped; retry after ordinary new input"); }
8352
9729
  }
9730
+ const evidenceObserverExcluded = this.observerExcluded(by);
8353
9731
  const requestCheck = this.requestCheck(by);
8354
9732
  if (typeof id !== "number" && !(typeof id === "string" && /^\s*\d+\s*$/.test(id))) this.need(id, false, true);
8355
9733
  const authority = by === USER ? undefined : this.d.reviewAuthority?.(by, Number(id));
@@ -8390,12 +9768,19 @@ export class Tasks {
8390
9768
  if (withdrawing) withdrawalRevision = initial.history.length;
8391
9769
  if (withdrawing) { await this.unmergedForReopen(initial, valid); valid(); }
8392
9770
  let parsed: ReviewFinding[];
8393
- try { parsed = parseReviewFindings(findings, { person: by === USER, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS }); }
9771
+ try { parsed = parseReviewFindings(findings, { person: by === USER, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: mode === "off" ? "off" : "required" }); }
8394
9772
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid structured findings"); }
9773
+ // #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.
9774
+ let securityRecord: SecurityPassRecord | undefined;
9775
+ if (securityPass !== undefined) {
9776
+ 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)");
9777
+ try { securityRecord = parseSecurityPass(securityPass); }
9778
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid security_pass"); }
9779
+ }
8395
9780
  const anchorPrivacy = new Map(parsed.flatMap(item => item.anchor ? [[item.anchor.path, this.reviewPathPrivate(item.anchor.path)] as const] : []));
8396
9781
  try { parsed = parsed.map(item => item.anchor && anchorPrivacy.get(item.anchor.path) ? { ...item, anchor: privateReviewAnchor(item.anchor) } : item); }
8397
9782
  catch { throw new PreEffectToolRefusal("private finding path needs an existing lineRange or structural selector; remove quoted selectors and retry"); }
8398
- const observerExcluded = reviewObserverTurn || parsed.some(item => item.anchor !== undefined);
9783
+ const observerExcluded = evidenceObserverExcluded || reviewObserverTurn || parsed.some(item => item.anchor !== undefined);
8399
9784
  // #852 AC3 (amended): a code-scope reviewer's changes_requested is always recorded, never refused. Without an open structured finding it is
8400
9785
  // 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
8401
9786
  // notice. The rule is structural (a finding with disposition open), never a reading of the unmet text.
@@ -8456,7 +9841,7 @@ export class Tasks {
8456
9841
  path: anchor.path, ...(anchor.side ? { side: anchor.side } : {}), ...(anchor.contentHash ? { contentHash: anchor.contentHash } : {}),
8457
9842
  ...(anchor.projection ? { projection: anchor.projection } : {}),
8458
9843
  } } : {}) }));
8459
- const withheld = await this.withholds("review note", parsed.length ? JSON.stringify({ note, findings: screenFindings }) : note, valid())
9844
+ const withheld = evidenceObserverExcluded || await this.withholds("review note", parsed.length ? JSON.stringify({ note, findings: screenFindings }) : note, valid())
8460
9845
  || parsed.length > 0 && !this.findingTextAllowed(initial, parsed);
8461
9846
  let task = valid();
8462
9847
  let reviewedHead: string | undefined;
@@ -8488,7 +9873,7 @@ export class Tasks {
8488
9873
  }
8489
9874
  if (verdict === "approved" && this.d.sdlc && this.d.sdlc.config().mode !== "off") {
8490
9875
  this.evalRecords.delete(task.id);
8491
- await this.lifecycleGate(task, "approval", reviewedHead, proposedSets(task)); task = valid();
9876
+ await this.lifecycleGate(task, "approval", reviewedHead, proposedSets(task), undefined, securityRecord && { ...securityRecord, head: reviewedHead ?? findingHead }); task = valid();
8492
9877
  const record = this.evalRecords.get(task.id); this.evalRecords.delete(task.id);
8493
9878
  if (record) note = `${note ?? ""}\n${record}`.trim();
8494
9879
  } else if (verdict === "approved" && this.d.sdlc?.config().mode === "off" && this.d.sdlc?.gh && task.sdlc?.repo && task.sdlc.pr
@@ -8519,11 +9904,12 @@ export class Tasks {
8519
9904
  // #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
8520
9905
  // write (the `task` just rechecked by valid()), never from the caller; a PII task carries none, its checklist being private.
8521
9906
  const unmetCriteria = pii ? [] : unmetCriteriaIds(items, checklistOf(task.sdlc));
8522
- 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 } : {}) };
9907
+ 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 } : {}) };
8523
9908
  if (verdict === "approved") {
8524
9909
  const capacity = this.capacityBefore(task);
8525
9910
  this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
8526
9911
  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);
9912
+ this.recordConsideredAfter(next, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
8527
9913
  this.writePlannerNotices(next, capacity, next.state === "approved");
8528
9914
  if (next.owner) {
8529
9915
  this.d.board.recordOutcome(next.owner, next.class, true);
@@ -8541,11 +9927,13 @@ export class Tasks {
8541
9927
  this.autoMerge(next, this.mirrorVerdict(next, by, "approved", reviewedHead ?? next.sdlc?.reviewedHead, note, withheld || observerExcluded));
8542
9928
  // A proposal storage failure cannot roll back the saved verdict; another matching verdict retries it.
8543
9929
  this.releaseNotice(`task #${next.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(next, by, parsed, withheld));
9930
+ this.releaseNotice(`task #${next.id}: review saved but finding follow-up proposal unavailable`, () => this.proposeFindingFollowUps(next, by, withheld));
8544
9931
  this.releaseNotice(`task #${next.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(next, by, withheld));
8545
9932
  return next;
8546
9933
  }
8547
9934
  this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
8548
9935
  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);
9936
+ this.recordConsideredAfter(rejected, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
8549
9937
  void this.mirrorVerdict(rejected, by, "changes_requested", reviewedHead ?? rejected.sdlc?.reviewedHead, note, withheld || observerExcluded);
8550
9938
  if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(rejected, by, parsed, withheld));
8551
9939
  if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(rejected, by, withheld));
@@ -8850,8 +10238,8 @@ export class Tasks {
8850
10238
  current?.();
8851
10239
  moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner, role: "owner" });
8852
10240
  } else if (task.reviewer === peer && !isClosedTaskState(task.state)) {
8853
- const a = assign(task, this.states(), routing, { exclude: [peer], candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
8854
- const reviewer = a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
10241
+ const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
10242
+ const reviewer = !a.reviewSelection?.quotaWait && a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
8855
10243
  if (roster && !reviewer) {
8856
10244
  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}`);
8857
10245
  continue;
@@ -8864,7 +10252,7 @@ export class Tasks {
8864
10252
  if (next.state === "in_review" && reviewer && reviewer !== USER) {
8865
10253
  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.)`));
8866
10254
  else this.sendReview(next, reviewer, `(${peer} was reviewing this and is paused for quota.)`);
8867
- } 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}`);
10255
+ } 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}`);
8868
10256
  }
8869
10257
  }
8870
10258
  return moved;