@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/board.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
1
2
  import { GUIDANCE_VARIANT_LIMITS, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_HASH_HEX_LENGTH, parseGuidanceVariantV1, parseGuidanceExperiment, parseGuidanceStoredRecord, validateGuidanceVariantV1, type GuidanceVariantV1, type GuidanceExperimentRecord, type GuidanceStoredRecord, type GuidanceWriteFence } from "./guidance-variants.ts";
2
3
  import { ExecutionLinkError, EXECUTION_LINK_LIMITS, executionLinkActor, executionLinkInteger, executionLinkId, executionLinkReferences, executionReferenceDigest, parseExecutionLinkInput, parseExecutionLinkRecord, type ExecutionLinkInput, type ExecutionLinkRecord, type ExecutionLinkFence } from "./execution-links.ts";
3
4
  import { executionReferenceKey, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
@@ -10,6 +11,7 @@ import { parseComparisonPlan, comparisonPlanHash, evaluatorIdentityHash, parseEx
10
11
  import type { InvocationRow } from "./invocations.ts";
11
12
  import { HOST_CODE_SYMBOLS, parseTaskCodeSymbols, type TaskCodeSymbols } from "./task-code-symbols.ts";
12
13
  import { createHash } from "node:crypto";
14
+ import { types } from "node:util";
13
15
  import { planFingerprint } from "./plan-conformance.ts";
14
16
  import type { PlannerReason } from "./routing.ts";
15
17
  import type { ReviewerPoolReason } from "./reviewer-pool.ts";
@@ -18,15 +20,46 @@ import type { Database } from "./db-schema.ts";
18
20
  import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts";
19
21
  import { controlWriteSpan } from "./control-write-trace.ts";
20
22
  import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
23
+ import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState } from "./roadmap.ts";
21
24
  import { HUB, USER, type PeerId } from "./envelope.ts";
25
+ import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts";
26
+ import type { ReviewFinding } from "./review-findings.ts";
22
27
  import type { SweepRecord } from "./task-sweep.ts";
23
28
  import type { SpecAcceptance, SdlcReceipt } from "./sdlc.ts";
24
29
  import { parseReviewFindings, type ReviewFindingSet } from "./review-findings.ts";
30
+ import { storedSecurityPass, type SecurityPassRecord } from "./security-pass.ts";
25
31
  import { parseDeliverableRecords, type DeliverableRecord } from "./deliverables.ts";
26
32
  import type { CostPlan, ReviewCost } from "./cost-governance.ts";
27
33
  import type { SpecRef, SpecTaskReport } from "./specs-task.ts";
28
34
  export type { SpecAck, SpecRef, SpecTaskReport } from "./specs-task.ts";
29
35
  import { campaignHash, parseResearchCampaign, parseResearchHandoff, type ResearchCampaignContract, type ResearchCampaignStatus, type ResearchUnit, type ResearchHandoffV1, type ResearchHandoffRecord } from "./research-campaign.ts";
36
+ import { parseSurveyFindings, parseSurveyVetDecisions, surveyArray, surveyObject, surveyPath, surveyText, surveyFindingId, surveyPass, type SurveyFinding, type SurveyVetDecision, SURVEY_FOCUS, SURVEY_LIMITS, type SurveyFocus } from "./advisor-survey.ts";
37
+ import { parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
38
+
39
+ export interface StoredSurvey { id: number; task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true }
40
+ export interface StoredSurveyFinding { finding: SurveyFinding; foundBy: string; foundAt: number; decision?: SurveyVetDecision; decisionBy?: string; decisionAt?: number }
41
+ export interface SurveyPreparedCard { id: string; key: string; title: string; detail: string; class: "plan" | "triage"; refs?: TaskRefs; signals?: string[]; reopens?: number; reopenReason?: string }
42
+ export interface SurveyApplyInput { findings: SurveyFinding[]; decisions: SurveyVetDecision[]; by: string; at: number; cards?: SurveyPreparedCard[]; rejections?: ConsideredEntry[]; reconsiderations?: ConsideredEntry[]; withheld?: true }
43
+ export interface SurveyWriteFence { boardRevision: number; taskCreated: number; taskFlowRevision: number; owner: string }
44
+ export interface StoredRejectedFinding { id: number; entry: ConsideredEntry; reconsideredBy: number[] }
45
+ const SURVEY_STORE_LIMIT = 1000, SURVEY_STORE_BYTES = 64 * 1024;
46
+ const surveyStorageFailure = (): never => { throw new Error("survey storage invalid; stop the hub and restore a trusted hub.db backup before retrying"); };
47
+ const surveyInputFailure = (): never => { throw new Error("invalid survey storage input or changed binding"); };
48
+ const surveyInteger = (value: unknown, min = 1): number => typeof value === "number" && Number.isSafeInteger(value) && value >= min ? value : surveyInputFailure();
49
+ const surveyHash = (body: string) => createHash("sha256").update(body).digest("hex");
50
+ function surveyCreateInput(input: unknown): Omit<StoredSurvey, "id"> {
51
+ const row = surveyObject(input, ["task", "taskCreated", "repo", "ref", "focus", "by", "at", "withheld"]);
52
+ if (typeof row.ref !== "string" || !/^[a-f0-9]{40}$/.test(row.ref) || row.withheld !== undefined && row.withheld !== true) return surveyInputFailure();
53
+ return { task: surveyInteger(row.task), taskCreated: surveyInteger(row.taskCreated, 0), repo: surveyText(row.repo, 1024), ref: row.ref,
54
+ ...(row.focus === undefined ? {} : { focus: (typeof row.focus === "string" && (SURVEY_FOCUS as readonly string[]).includes(row.focus) ? row.focus as SurveyFocus : surveyInputFailure()) }), by: surveyText(row.by, 128), at: surveyInteger(row.at, 0), ...(row.withheld === true ? { withheld: true } : {}) };
55
+ }
56
+ function surveyStoredFinding(input: unknown): StoredSurveyFinding {
57
+ const row = surveyObject(input, ["finding", "foundBy", "foundAt", "decision", "decisionBy", "decisionAt"]), finding = parseSurveyFindings([row.finding])[0]!;
58
+ const decision = row.decision === undefined ? undefined : parseSurveyVetDecisions([row.decision])[0]!;
59
+ if (decision && decision.id !== finding.id || !decision && (row.decisionBy !== undefined || row.decisionAt !== undefined)) return surveyInputFailure();
60
+ return { finding, foundBy: surveyText(row.foundBy, 128), foundAt: surveyInteger(row.foundAt, 0),
61
+ ...(decision ? { decision, decisionBy: surveyText(row.decisionBy, 128), decisionAt: surveyInteger(row.decisionAt, 0) } : {}) };
62
+ }
30
63
 
31
64
  const GUIDANCE_VARIANT_SELECT = `SELECT CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=${GUIDANCE_HASH_HEX_LENGTH} THEN id END AS id,CASE WHEN typeof(body)='text' AND length(CAST(body AS BLOB))<=? THEN body END AS body,
32
65
  CASE WHEN typeof(body_sha256)='text' AND length(CAST(body_sha256 AS BLOB))<=${GUIDANCE_HASH_HEX_LENGTH} THEN body_sha256 END AS body_sha256,
@@ -160,6 +193,9 @@ const experimentPage = (after: number, limit: number): void => {
160
193
 
161
194
  export const CLASSES = ["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"] as const;
162
195
  export type TaskClass = (typeof CLASSES)[number];
196
+ /** #1403 A4: one security audit as stored. `units` is the ledger; it changes only through `Board.auditReport`. */
197
+ export interface StoredAudit { id: number; task: number; taskCreated: number; ref: string; since?: string; profile: AuditProfile; scoped: boolean; at: number; by: string; units: AuditUnit[] }
198
+ const EVIDENCE_HISTORY_WINDOW = 1024;
163
199
  export type TaskState = "backlog" | "proposed" | "in_progress" | "in_review" | "approved" | "changes_requested" | "cancelled";
164
200
 
165
201
  export const isClosedTaskState = (state: string): boolean => state === "approved" || state === "cancelled";
@@ -206,11 +242,17 @@ export interface TaskRefs {
206
242
  export const PLAN_KEYS = ["paths", "symbols", "signatures", "insertion_points"] as const;
207
243
  export const DOCUMENT_PLAN_KEYS = ["paths", "sections", "sources", "claims"] as const;
208
244
  export const ALL_PLAN_KEYS = [...PLAN_KEYS, "sections", "sources", "claims", "proof", "risks"] as const;
209
- export type TaskPlan = Partial<Record<(typeof ALL_PLAN_KEYS)[number], string[]>> & CostPlan;
245
+ export interface ColdPlanIntent {
246
+ base?: string;
247
+ out_of_scope?: string[];
248
+ stop_if?: string[];
249
+ steps?: { description: string; verify?: string }[];
250
+ }
251
+ export type TaskPlan = Partial<Record<(typeof ALL_PLAN_KEYS)[number], string[]>> & CostPlan & ColdPlanIntent;
210
252
  /** Task outcomes older than this are pruned: demotion (issue #36) reads one week, seven half-lives. */
211
253
  export const OUTCOMES_KEPT_MS = 7 * 24 * 3_600_000;
212
254
 
213
- export const TASK_MOVE_REASONS = ["manual", "budget", "offline", "idle", "rejections", "declined", "inference_failed", "delivery_failed"] as const;
255
+ export const TASK_MOVE_REASONS = ["manual", "budget", "offline", "idle", "rejections", "declined", "inference_failed", "delivery_failed", "step_limit"] as const;
214
256
  export type TaskMoveReason = (typeof TASK_MOVE_REASONS)[number];
215
257
  export type InvocationHistory = Pick<InvocationRow, "id" | "caller" | "target" | "capability" | "digest" | "class" | "approval" | "argsSha256" | "outcome">;
216
258
 
@@ -242,6 +284,8 @@ export interface HistoryEntry {
242
284
  reason?: TaskMoveReason;
243
285
  /** Persisted task-idle ladder; never counted as fresh task activity (#186). */
244
286
  sweep?: SweepRecord;
287
+ /** #1454: on a `wait recorded` entry, the bounded wait: when it ends and the owner it was recorded for. The reason is the entry's note. */
288
+ wait?: { until: number; owner: PeerId };
245
289
  /** The PII screen did not clear this entry's note (#198): only the console reads it. */
246
290
  withheld?: true;
247
291
  /** Public, head-bound design-spec status; acknowledgement text is screened before this is written. */
@@ -276,6 +320,8 @@ export interface HistoryEntry {
276
320
  deliverables?: DeliverableRecord[];
277
321
  /** #507b: the recorded acceptance criteria (S8 checklist ids) a verdict's unmet items named; derived by the hub from the checklist, never free text. */
278
322
  unmetCriteria?: string[];
323
+ /** #1403 A2: the security pass an approving verdict recorded (units covered and not covered, bound to the reviewed head). Enabled lifecycle only. */
324
+ securityPass?: SecurityPassRecord;
279
325
  /** Host-authored plan content revision, separate from backlog planningRevision. */
280
326
  planRevision?: { revision: number; fingerprint: string };
281
327
  planObservation?: { repo: string; pr: number; head: string; revision: number; fingerprint: string };
@@ -288,14 +334,15 @@ export interface HistoryEntry {
288
334
  queueReviewHeld?: true;
289
335
  /** Opaque artifact identity captured by the host at the queue-held role write. */
290
336
  queueReviewBinding?: string;
291
- reviewerFailure?: { peer: string; head?: string; cause: "start_failed" | "quota" | "no_verdict" };
337
+ reviewerQuotaWait?: { created: number; binding: string; since: number; deadline: number; resetAt: number };
338
+ reviewerFailure?: { peer: string; head?: string; cause: "start_failed" | "quota" | "no_verdict"; reason?: "review time cap" };
292
339
  resolvedReviewComments?: string[];
293
340
  planning?: { revision: number; fields: (keyof PlanningFields)[]; previous: PlanningFields; pull?: true; split?: { children: { id: number; revision: number; history: number }[] } };
294
341
  }
295
342
  /** #901: one person verdict on a plan claim, with the model label the person says produced the claim. All closed or bounded; nothing here is claim text. */
296
343
  export const CLAIM_VERDICTS = ["supported", "unsupported", "unclear"] as const;
297
344
  /** `modelVerdict` is what the model's own fact check said of the claim, as the person enters it: with it the scorecard can say whether person and model agree; without it agreement is unknown. */
298
- export interface ClaimVerdict { slot: number; verdict: (typeof CLAIM_VERDICTS)[number]; model?: string; modelVerdict?: (typeof CLAIM_VERDICTS)[number]; /** `claimListId` of the plan's claims when the verdict was entered: the list it evaluated, as a hash. Set by the hub, never by the person. */ list?: string }
345
+ export interface ClaimVerdict { slot: number; verdict: (typeof CLAIM_VERDICTS)[number]; model?: string; modelVerdict?: (typeof CLAIM_VERDICTS)[number]; /** Person-only disposition, valid only for this exact synthesis manifest. */ synthesis?: { manifestSha256: string; disposition: "resolved" | "qualified" }; /** `claimListId` of the plan's claims when the verdict was entered: the list it evaluated, as a hash. Set by the hub, never by the person. */ list?: string }
299
346
  /** A short opaque identity of an ordered claim list (a sha-256 prefix of its canonical form): equal lists, in order, give equal ids; it reveals nothing of the claims. Absent list: the empty list's id. */
300
347
  export function claimListId(claims: readonly string[] | undefined): string {
301
348
  return createHash("sha256").update(planFingerprint({ claims: [...(claims ?? [])] })).digest("hex").slice(0, 16);
@@ -310,28 +357,45 @@ export function taskClaimIdentity(task: Pick<Task, "id" | "created" | "plan">, s
310
357
  }
311
358
  /** A claim slot is a position in the plan's claim list (at most 50, as the scorecard's own bound); a model label is a bounded token, never prose. */
312
359
  export function parseClaimVerdict(value: unknown, slots: number): ClaimVerdict {
313
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("claim verdict must be an object");
360
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
361
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length
362
+ || Object.values(Object.getOwnPropertyDescriptors(value)).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) throw new Error("claim verdict must be an object");
314
363
  const v = value as Record<string, unknown>;
315
- if (Object.keys(v).some(key => !["slot", "verdict", "model", "modelVerdict"].includes(key))) throw new Error("claim verdict carries only slot, verdict, model and modelVerdict");
364
+ if (Object.keys(v).some(key => !["slot", "verdict", "model", "modelVerdict", "synthesis"].includes(key))) throw new Error("claim verdict carries only slot, verdict, model, modelVerdict and synthesis");
316
365
  if (!Number.isSafeInteger(v.slot) || (v.slot as number) < 1 || (v.slot as number) > Math.min(50, slots)) throw new Error(`claim slot must name one of the task's ${slots} declared claim${slots === 1 ? "" : "s"}`);
317
366
  if (typeof v.verdict !== "string" || !(CLAIM_VERDICTS as readonly string[]).includes(v.verdict)) throw new Error(`claim verdict must be one of ${CLAIM_VERDICTS.join(", ")}`);
318
367
  if (v.model !== undefined && (typeof v.model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,63}$/.test(v.model))) throw new Error("model label must be a short identifier (letters, digits and . _ : / @ + -)");
319
368
  if (v.modelVerdict !== undefined && (typeof v.modelVerdict !== "string" || !(CLAIM_VERDICTS as readonly string[]).includes(v.modelVerdict))) throw new Error(`model verdict must be one of ${CLAIM_VERDICTS.join(", ")}`);
320
- return { slot: v.slot as number, verdict: v.verdict as ClaimVerdict["verdict"], ...(v.model === undefined ? {} : { model: v.model }), ...(v.modelVerdict === undefined ? {} : { modelVerdict: v.modelVerdict as ClaimVerdict["verdict"] }) };
369
+ let synthesis: ClaimVerdict["synthesis"];
370
+ if (v.synthesis !== undefined) {
371
+ const item = v.synthesis;
372
+ if (!item || typeof item !== "object" || Array.isArray(item) || types.isProxy(item)
373
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(item)) || Object.getOwnPropertySymbols(item).length
374
+ || Object.values(Object.getOwnPropertyDescriptors(item)).some(field => !Object.hasOwn(field, "value") || !field.enumerable)
375
+ || Object.keys(item).some(key => key !== "manifestSha256" && key !== "disposition")) throw new Error("synthesis disposition requires only manifestSha256 and disposition");
376
+ const row = item as Record<string, unknown>;
377
+ if (typeof row.manifestSha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.manifestSha256) || row.disposition !== "resolved" && row.disposition !== "qualified") throw new Error("synthesis disposition needs a manifest SHA-256 and resolved or qualified");
378
+ synthesis = { manifestSha256: row.manifestSha256, disposition: row.disposition };
379
+ }
380
+ return { slot: v.slot as number, verdict: v.verdict as ClaimVerdict["verdict"], ...(v.model === undefined ? {} : { model: v.model }), ...(v.modelVerdict === undefined ? {} : { modelVerdict: v.modelVerdict as ClaimVerdict["verdict"] }), ...(synthesis ? { synthesis } : {}) };
321
381
  }
322
382
  /** The ids a stored verdict may carry (#507b): bounded criterion identifiers in the S8 checklist's own format, at most its 32, each once. */
323
383
  function criterionIdList(value: unknown): string[] {
324
384
  if (!Array.isArray(value) || value.length > 32 || value.some(id => typeof id !== "string" || !/^[A-Za-z][A-Za-z0-9-]{0,47}$/.test(id)) || new Set(value).size !== value.length) throw new Error("unmet criteria: expected up to 32 distinct criterion ids");
325
385
  return [...value] as string[];
326
386
  }
327
- export type ReviewerHistory = Pick<HistoryEntry, "reviewerFamily" | "reviewerReason" | "reviewBlocked" | "queueReviewHeld" | "queueReviewBinding" | "reviewerFailure">;
387
+ export type ReviewerHistory = Pick<HistoryEntry, "reviewerFamily" | "reviewerReason" | "reviewBlocked" | "queueReviewHeld" | "queueReviewBinding" | "reviewerFailure" | "reviewerQuotaWait">;
328
388
  function reviewerHistory(extra: ReviewerHistory): ReviewerHistory {
329
389
  const id = (value: unknown) => typeof value === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(value);
330
390
  if (extra.reviewerFamily !== undefined && !id(extra.reviewerFamily) || extra.reviewerReason !== undefined && !["rotation", "implementer skip", "unavailable skip", "same-family fallback"].includes(extra.reviewerReason) || extra.reviewBlocked !== undefined && extra.reviewBlocked !== true || extra.queueReviewHeld !== undefined && extra.queueReviewHeld !== true) throw new Error("invalid reviewer metadata");
331
391
  if (extra.queueReviewHeld && (typeof extra.queueReviewBinding !== "string" || !/^[0-9a-f]{64}$/.test(extra.queueReviewBinding)) || extra.queueReviewBinding !== undefined && extra.queueReviewHeld !== true) throw new Error("invalid queue-held review binding");
392
+ const wait = extra.reviewerQuotaWait;
393
+ if (wait && (!Number.isSafeInteger(wait.created) || wait.created < 0 || !/^[a-f0-9]{64}$/.test(wait.binding)
394
+ || !Number.isSafeInteger(wait.resetAt) || wait.resetAt <= 0 || !Number.isSafeInteger(wait.since) || !Number.isSafeInteger(wait.deadline) || wait.since < 0 || wait.deadline < wait.since)) throw new Error("invalid reviewer quota wait");
332
395
  const failure = extra.reviewerFailure;
396
+ if (failure?.reason !== undefined && (failure.reason !== "review time cap" || failure.cause !== "no_verdict")) throw new Error("invalid reviewer timeout metadata");
333
397
  if (failure && (!id(failure.peer) || !["start_failed", "quota", "no_verdict"].includes(failure.cause) || failure.head !== undefined && (typeof failure.head !== "string" || !failure.head.trim() || failure.head.length > 300 || Buffer.byteLength(failure.head) > 1200 || /\p{Cc}/u.test(failure.head)))) throw new Error("invalid reviewer failure metadata");
334
- return { ...(extra.reviewerFamily ? { reviewerFamily: extra.reviewerFamily } : {}), ...(extra.reviewerReason ? { reviewerReason: extra.reviewerReason } : {}), ...(extra.reviewBlocked ? { reviewBlocked: true } : {}), ...(extra.queueReviewHeld ? { queueReviewHeld: true, ...(extra.queueReviewBinding !== undefined ? { queueReviewBinding: extra.queueReviewBinding } : {}) } : {}), ...(failure ? { reviewerFailure: { peer: failure.peer, cause: failure.cause, ...(failure.head ? { head: failure.head } : {}) } } : {}) };
398
+ return { ...(wait ? { reviewerQuotaWait: { created: wait.created, binding: wait.binding, since: wait.since, deadline: wait.deadline, resetAt: wait.resetAt } } : {}), ...(extra.reviewerFamily ? { reviewerFamily: extra.reviewerFamily } : {}), ...(extra.reviewerReason ? { reviewerReason: extra.reviewerReason } : {}), ...(extra.reviewBlocked ? { reviewBlocked: true } : {}), ...(extra.queueReviewHeld ? { queueReviewHeld: true, ...(extra.queueReviewBinding !== undefined ? { queueReviewBinding: extra.queueReviewBinding } : {}) } : {}), ...(failure ? { reviewerFailure: { peer: failure.peer, cause: failure.cause, ...(failure.reason ? { reason: failure.reason } : {}), ...(failure.head ? { head: failure.head } : {}) } } : {}) };
335
399
  }
336
400
  function specReportHistory(report: unknown, binding: unknown, event: string): Pick<HistoryEntry, "specReport" | "specRefBinding"> {
337
401
  if (!report || typeof report !== "object" || Array.isArray(report) || !["done", "done (checking)"].includes(event)
@@ -563,6 +627,24 @@ export class Board {
563
627
  this.db.run("CREATE INDEX IF NOT EXISTS releases_planner_present ON releases(planner) WHERE planner IS NOT NULL");
564
628
  if (!(this.db.query("PRAGMA table_info(releases)").all() as { name: string }[]).some(row => row.name === "train")) this.db.run("ALTER TABLE releases ADD COLUMN train TEXT");
565
629
 
630
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestones (
631
+ id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, outcome TEXT NOT NULL,
632
+ state TEXT NOT NULL, horizon TEXT NOT NULL, milestone_order INTEGER NOT NULL,
633
+ target TEXT, parent INTEGER, revision INTEGER NOT NULL DEFAULT 0, history TEXT NOT NULL,
634
+ created INTEGER NOT NULL, updated INTEGER NOT NULL)`);
635
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_links (
636
+ milestone INTEGER NOT NULL, kind TEXT NOT NULL, ref TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL,
637
+ PRIMARY KEY(milestone,kind,ref))`);
638
+ // R3 (#1481): advisory model suggestions and the one-time GitHub milestone import marks. Additive, outside the roadmap integrity digest:
639
+ // a lost suggestion is triaged again, and an import mark only stops a repeat from creating a second milestone.
640
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_suggestions (
641
+ id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, ref TEXT NOT NULL, milestone INTEGER,
642
+ proposal TEXT, cite_milestone TEXT, cite_item TEXT NOT NULL, state TEXT NOT NULL, by TEXT NOT NULL,
643
+ created INTEGER NOT NULL, settled INTEGER, settled_by TEXT, created_milestone INTEGER)`);
644
+ this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_suggestions_pending ON milestone_suggestions(kind,ref) WHERE state='pending'");
645
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_imports (
646
+ repo TEXT NOT NULL, number INTEGER NOT NULL, milestone INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(repo,number))`);
647
+
566
648
  this.db.run(`CREATE TABLE IF NOT EXISTS research_campaigns (
567
649
  id TEXT NOT NULL, project TEXT NOT NULL, parent_task_id INTEGER NOT NULL, revision INTEGER NOT NULL,
568
650
  status TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, private INTEGER NOT NULL,
@@ -612,6 +694,25 @@ export class Board {
612
694
  UNIQUE(project_id,task_id,task_created,from_sha256,reference_sha256))`);
613
695
  this.db.run("CREATE INDEX IF NOT EXISTS execution_reference_task_scope ON execution_reference_links(project_id,task_id,task_created,id)");
614
696
  this.db.run("CREATE INDEX IF NOT EXISTS guidance_variant_task_id ON guidance_variants(project_id,task_id,task_created,id)");
697
+ // Private additive survey/considered state, never copied into task projections or an unconditional format floor.
698
+ this.db.run(`CREATE TABLE IF NOT EXISTS advisor_surveys (
699
+ id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL,
700
+ withheld INTEGER NOT NULL DEFAULT 0, UNIQUE(task_id,task_created))`);
701
+ this.db.run(`CREATE TABLE IF NOT EXISTS advisor_survey_findings (
702
+ survey INTEGER NOT NULL, finding_id TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(survey,finding_id))`);
703
+ this.db.run(`CREATE TABLE IF NOT EXISTS considered_findings (
704
+ id INTEGER PRIMARY KEY AUTOINCREMENT, repo TEXT NOT NULL, finding_id TEXT NOT NULL, pass TEXT NOT NULL, kind TEXT NOT NULL,
705
+ body TEXT NOT NULL, body_sha256 TEXT NOT NULL, replay_key TEXT NOT NULL UNIQUE, prior_ids TEXT NOT NULL, withheld INTEGER NOT NULL DEFAULT 0)`);
706
+ this.db.run("CREATE INDEX IF NOT EXISTS considered_finding_identity ON considered_findings(repo,finding_id,pass,id)");
707
+ // #1403 A4: the security audit coverage ledger. Private local state like the guidance tables: only Tasks writes it (through the methods below), and no column is copied into a Task, a history entry or a public view.
708
+ this.db.run(`CREATE TABLE IF NOT EXISTS security_audits (
709
+ id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL, ref TEXT NOT NULL, since TEXT, profile TEXT NOT NULL,
710
+ scoped INTEGER NOT NULL, at INTEGER NOT NULL, by_peer TEXT NOT NULL, units TEXT NOT NULL, UNIQUE(task_id,task_created))`);
711
+ this.db.run(`CREATE TABLE IF NOT EXISTS security_audit_findings (
712
+ audit INTEGER NOT NULL, seq INTEGER NOT NULL, finding_id TEXT NOT NULL, body TEXT NOT NULL, found_by TEXT NOT NULL, at INTEGER NOT NULL,
713
+ verified_by TEXT, rejected_by TEXT, settled_by TEXT, settled_as TEXT, PRIMARY KEY(audit,seq), UNIQUE(audit,finding_id))`);
714
+ // #1403 A4 follow-up: a verified finding is settled as fixed or false_positive. A database from before has the table without the two columns.
715
+ for (const column of ["settled_by", "settled_as"]) if (!(this.db.query("PRAGMA table_info(security_audit_findings)").all() as { name: string }[]).some(row => row.name === column)) this.db.run(`ALTER TABLE security_audit_findings ADD COLUMN ${column} TEXT`);
615
716
  this.db.run(`CREATE TABLE IF NOT EXISTS review_comments (
616
717
  task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,id TEXT NOT NULL,body TEXT NOT NULL,lifecycle TEXT NOT NULL,revision INTEGER NOT NULL,
617
718
  PRIMARY KEY(task_id,task_created,id))`);
@@ -1062,9 +1163,61 @@ export class Board {
1062
1163
  } catch { throw new Error("evidence storage invalid; stop the hub and restore a trusted hub.db backup; then restart and retry"); }
1063
1164
  }
1064
1165
 
1065
- recordEvidenceLink(project: string, input: EvidenceLinkV1, fence: { taskFlowRevision: number; taskCreated: number; owner: PeerId }): EvidenceLinkV1 {
1166
+ /** Bounded current inventory. A task-wide overflow cannot establish complete claim coverage. */
1167
+ latestEvidenceLinks(project: string, taskId: number, claimId: string, claimRevision: string, limit: number): { links: EvidenceLinkV1[]; complete: boolean } {
1168
+ if (!researchText(project) || !researchInteger(taskId) || typeof claimId !== "string" || !/^claim:[1-9][0-9]{0,15}:(?:0|[1-9][0-9]{0,15}):[1-9][0-9]?$/.test(claimId)
1169
+ || !/^[a-f0-9]{16}$/.test(claimRevision) || !researchInteger(limit) || limit > 128) throw new Error("evidence inventory identity is invalid; refresh the task claim binding before retrying");
1170
+ const rows = this.db.query("SELECT id,MAX(revision) AS revision FROM research_evidence_links WHERE project=? AND task_id=? GROUP BY id ORDER BY id LIMIT ?")
1171
+ .all(project, taskId, limit + 1) as { id: string; revision: number }[];
1172
+ const links = rows.slice(0, limit).flatMap(row => {
1173
+ const link = this.evidenceLink(project, row.id, row.revision);
1174
+ if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh the task review before retrying");
1175
+ return link.claimId === claimId && link.claimRevision === claimRevision ? [link] : [];
1176
+ });
1177
+ // ponytail: the task-wide cap can make a smaller claim inventory unknown; a claim-indexed validated read is the upgrade path.
1178
+ return { links, complete: rows.length <= limit };
1179
+ }
1180
+
1181
+ /** Verified immutable relation history, never a second judgment store. */
1182
+ evidenceContradictionHistory(project: string, taskId: number, claimId: string, claimRevision: string, links: readonly EvidenceLinkV1[]): { ids: string[]; sources: string[]; members: string[]; binding?: { revision: number; sha256: string }; complete: boolean } {
1183
+ if (!researchText(project) || !researchInteger(taskId) || !/^claim:[1-9][0-9]{0,15}:(?:0|[1-9][0-9]{0,15}):[1-9][0-9]?$/.test(claimId)
1184
+ || !/^[a-f0-9]{16}$/.test(claimRevision) || links.length > 128 || new Set(links.map(link => link.id)).size !== links.length
1185
+ || links.some(link => link.taskId !== taskId || link.claimId !== claimId || link.claimRevision !== claimRevision)) throw new Error("evidence history identity invalid; refresh the complete inventory");
1186
+ const unknown = { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false };
1187
+ const taskRows = this.db.query("SELECT id,MAX(revision) AS revision FROM research_evidence_links WHERE project=? AND task_id=? GROUP BY id ORDER BY id LIMIT ?")
1188
+ .all(project, taskId, 129) as { id: string; revision: number }[];
1189
+ if (taskRows.length > 128) return unknown;
1190
+ const latest = taskRows.map(row => {
1191
+ const link = this.evidenceLink(project, row.id, row.revision);
1192
+ if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh its history");
1193
+ return link;
1194
+ }).filter(link => link.claimId === claimId);
1195
+ const current = latest.filter(link => link.claimRevision === claimRevision);
1196
+ if (current.length !== links.length || current.some(link => !links.some(given => evidenceLinkCanonical(given) === evidenceLinkCanonical(link)))) throw new Error("evidence inventory changed; refresh its history");
1197
+ const revisions = latest.reduce((count, link) => count + link.revision, 0);
1198
+ // ponytail: above 1024 owned revisions, history is unknown. Upgrade to paged verified history commitments before widening this window.
1199
+ if (!Number.isSafeInteger(revisions) || revisions > EVIDENCE_HISTORY_WINDOW) return unknown;
1200
+ const rows = latest.length ? this.db.query(`SELECT id,revision FROM research_evidence_links WHERE project=? AND task_id=? AND id IN (${latest.map(() => "?").join(",")}) ORDER BY id,revision LIMIT ?`)
1201
+ .all(project, taskId, ...latest.map(link => link.id), EVIDENCE_HISTORY_WINDOW + 1) as { id: string; revision: number }[] : [];
1202
+ if (rows.length > EVIDENCE_HISTORY_WINDOW) return unknown;
1203
+ const seen = new Map<string, number>(), contradicted = new Set<string>(), sources = new Set<string>(), canonical: string[] = [];
1204
+ for (const row of rows) {
1205
+ const last = latest.find(link => link.id === row.id), prior = this.evidenceLink(project, row.id, row.revision);
1206
+ if (!last || !prior || prior.taskId !== taskId || prior.claimId !== claimId || row.revision !== (seen.get(row.id) ?? 0) + 1 || row.revision > last.revision)
1207
+ throw new Error("evidence history is incomplete or changed; restore trusted evidence storage and retry");
1208
+ seen.set(row.id, row.revision); sources.add(prior.sourceId); canonical.push(evidenceLinkCanonical(prior));
1209
+ if (prior.relation === "contradicts") contradicted.add(row.id);
1210
+ if (row.revision === last.revision && evidenceLinkCanonical(prior) !== evidenceLinkCanonical(last)) throw new Error("evidence inventory changed; refresh its history before retrying");
1211
+ }
1212
+ if (latest.some(link => seen.get(link.id) !== link.revision)) throw new Error("evidence history is incomplete; restore trusted evidence storage and retry");
1213
+ const sha256 = createHash("sha256").update(JSON.stringify({ project, taskId, claimId, rows: canonical })).digest("hex");
1214
+ return { ids: [...contradicted].sort(), sources: [...sources].sort(), members: latest.map(link => link.id), binding: { revision: revisions, sha256 }, complete: true };
1215
+ }
1216
+
1217
+ recordEvidenceLink(project: string, input: EvidenceLinkV1, fence: { taskFlowRevision: number; taskCreated: number; owner: PeerId; personWithdrawal?: true }): EvidenceLinkV1 {
1066
1218
  const link = parseEvidenceLink(input), canonical = evidenceLinkCanonical(link);
1067
- if (!researchText(project) || !researchInteger(fence.taskFlowRevision, 0) || !researchInteger(fence.taskCreated, 0) || fence.owner !== link.recordedBy) throw new Error("evidence write binding is invalid; refresh the task before retrying");
1219
+ const personWithdrawal = fence.personWithdrawal === true && link.recordedBy === USER && link.status === "withdrawn";
1220
+ if (!researchText(project) || !researchInteger(fence.taskFlowRevision, 0) || !researchInteger(fence.taskCreated, 0) || fence.owner !== link.recordedBy && !personWithdrawal) throw new Error("evidence write binding is invalid; refresh the task before retrying");
1068
1221
  return this.atomic(() => {
1069
1222
  const task = this.get(link.taskId);
1070
1223
  if (!task || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision || task.owner !== fence.owner || task.state !== "in_progress" || task.profile !== "research"
@@ -1189,6 +1342,314 @@ export class Board {
1189
1342
  return { record: next, already: false };
1190
1343
  });
1191
1344
  }
1345
+ /** Private survey metadata, linked to the existing task incarnation. */
1346
+ surveyCreate(input: { task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true }): number {
1347
+ const row = surveyCreateInput(input);
1348
+ const write = () => {
1349
+ const task = this.get(row.task);
1350
+ if (!task || task.created !== row.taskCreated || task.class !== "plan" || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure();
1351
+ const known = this.surveyOfTask(row.task, row.taskCreated);
1352
+ if (known) {
1353
+ const { id: _id, withheld: _private, ...prior } = known, { withheld: _nextPrivate, ...next } = row;
1354
+ if (JSON.stringify(prior) !== JSON.stringify(next)) return surveyInputFailure();
1355
+ if (row.withheld && !known.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(known.id));
1356
+ return known.id;
1357
+ }
1358
+ const body = JSON.stringify(row);
1359
+ const saved = this.taskWrite(() => this.db.query("INSERT INTO advisor_surveys(task_id,task_created,body,body_sha256,withheld) VALUES(?,?,?,?,?)")
1360
+ .run(row.task, row.taskCreated, body, surveyHash(body), row.withheld ? 1 : 0));
1361
+ return Number(saved.lastInsertRowid);
1362
+ };
1363
+ // The host-only proposal hook already owns the transaction and deferred notifications.
1364
+ return this.pendingChanges ? write() : this.atomic(write);
1365
+ }
1366
+ surveyOfTask(taskId: number, created: number): StoredSurvey | undefined {
1367
+ surveyInteger(taskId); surveyInteger(created, 0);
1368
+ const row = this.db.query("SELECT id FROM advisor_surveys WHERE task_id=? AND task_created=?").get(taskId, created) as { id: number } | null;
1369
+ return row ? this.survey(row.id) : undefined;
1370
+ }
1371
+ surveyOpen(repo: string): { id: number; task: number; taskCreated: number } | undefined {
1372
+ surveyText(repo, 1024);
1373
+ const rows = this.db.query("SELECT s.id FROM advisor_surveys s JOIN tasks t ON t.id=s.task_id AND t.created=s.task_created WHERE t.state NOT IN ('approved','cancelled') ORDER BY s.id DESC LIMIT 1001").all() as { id: number }[];
1374
+ if (rows.length > SURVEY_STORE_LIMIT) throw new Error("open survey inventory unavailable; reduce open surveys and retry");
1375
+ const found = rows.map(row => this.survey(row.id)!).filter(row => row.repo === repo);
1376
+ if (found.length > 1) throw new Error("multiple surveys are open; finish or cancel them before starting another");
1377
+ const row = found[0]; return row ? { id: row.id, task: row.task, taskCreated: row.taskCreated } : undefined;
1378
+ }
1379
+ survey(id: number): StoredSurvey | undefined {
1380
+ surveyInteger(id);
1381
+ const row = this.db.query(`SELECT id,task_id,task_created,CASE WHEN length(CAST(body AS BLOB))<=${SURVEY_STORE_BYTES} THEN body END AS body,CASE WHEN length(CAST(body_sha256 AS BLOB))=64 THEN body_sha256 END AS body_sha256,withheld FROM advisor_surveys WHERE id=?`).get(id) as { id: number; task_id: number; task_created: number; body: string | null; body_sha256: string; withheld: number } | null;
1382
+ if (!row) return;
1383
+ try {
1384
+ if (!row.body || surveyHash(row.body) !== row.body_sha256 || row.withheld !== 0 && row.withheld !== 1) return surveyStorageFailure();
1385
+ const value = surveyCreateInput(JSON.parse(row.body));
1386
+ if (value.task !== row.task_id || value.taskCreated !== row.task_created) return surveyStorageFailure();
1387
+ return { id: row.id, ...value, ...(row.withheld ? { withheld: true } : {}) };
1388
+ } catch { return surveyStorageFailure(); }
1389
+ }
1390
+ surveyFindings(id: number): StoredSurveyFinding[] {
1391
+ surveyInteger(id);
1392
+ const rows = this.db.query(`SELECT CASE WHEN length(CAST(finding_id AS BLOB))<=96 THEN finding_id END AS finding_id,CASE WHEN length(CAST(body AS BLOB))<=${SURVEY_STORE_BYTES} THEN body END AS body,CASE WHEN length(CAST(body_sha256 AS BLOB))=64 THEN body_sha256 END AS body_sha256 FROM advisor_survey_findings WHERE survey=? ORDER BY finding_id LIMIT 65`).all(id) as { finding_id: string; body: string | null; body_sha256: string }[];
1393
+ try {
1394
+ if (rows.length > 64) return surveyStorageFailure();
1395
+ return rows.map(row => {
1396
+ if (!row.body || surveyHash(row.body) !== row.body_sha256) return surveyStorageFailure();
1397
+ const value = surveyStoredFinding(JSON.parse(row.body));
1398
+ if (value.finding.id !== row.finding_id) return surveyStorageFailure();
1399
+ return value;
1400
+ });
1401
+ } catch { return surveyStorageFailure(); }
1402
+ }
1403
+ private consideredWrite(input: unknown, kind: "rejected" | "reconsidered", priorIDs: readonly number[] = []): number {
1404
+ const entry = parseConsideredEntry(input), task = this.get(entry.source.task);
1405
+ if (!task || task.created !== entry.source.created) return surveyInputFailure();
1406
+ const prior = surveyArray(priorIDs, SURVEY_STORE_LIMIT).map(value => surveyInteger(value)).sort((a, b) => a - b);
1407
+ if (new Set(prior).size !== prior.length || kind === "rejected" && prior.length || kind === "reconsidered" && !prior.length) return surveyInputFailure();
1408
+ for (const id of prior) {
1409
+ const found = this.db.query("SELECT repo,finding_id,pass,kind FROM considered_findings WHERE id=?").get(id) as { repo: string; finding_id: string; pass: string; kind: string } | null;
1410
+ if (!found || found.kind !== "rejected" || found.repo !== entry.repo || found.finding_id !== entry.id || found.pass !== entry.pass) return surveyInputFailure();
1411
+ }
1412
+ const { withheld: _private, ...identity } = entry, body = JSON.stringify(entry), priorBody = JSON.stringify(prior);
1413
+ const replay = surveyHash(JSON.stringify({ kind, entry: identity, prior }));
1414
+ const known = this.db.query("SELECT id FROM considered_findings WHERE replay_key=?").get(replay) as { id: number } | null;
1415
+ if (known) {
1416
+ if (entry.withheld) this.taskWrite(() => this.db.query("UPDATE considered_findings SET withheld=1 WHERE id=? AND withheld=0").run(known.id));
1417
+ return known.id;
1418
+ }
1419
+ const saved = this.taskWrite(() => this.db.query("INSERT INTO considered_findings(repo,finding_id,pass,kind,body,body_sha256,replay_key,prior_ids,withheld) VALUES(?,?,?,?,?,?,?,?,?)")
1420
+ .run(entry.repo, entry.id, entry.pass, kind, body, surveyHash(body), replay, priorBody, entry.withheld || entry.pass === "security" ? 1 : 0));
1421
+ return Number(saved.lastInsertRowid);
1422
+ }
1423
+ recordRejectedFinding(entry: ConsideredEntry): number { return this.atomic(() => this.consideredWrite(entry, "rejected")); }
1424
+ recordReconsideredFinding(entry: ConsideredEntry, priorIDs: readonly number[]): number { return this.atomic(() => this.consideredWrite(entry, "reconsidered", priorIDs)); }
1425
+ /** Closed proposals are history, not dedupe. Caller screens any new reference before the atomic apply. */
1426
+ surveyCardHistory(key: string): { active?: number; closed?: number } {
1427
+ surveyText(key, 512);
1428
+ // ponytail: at most 1000 matching host-created cards; overflow is unknown, not permission to duplicate. Page this proof if a key outgrows the window.
1429
+ const rows = this.db.query("SELECT id,state FROM tasks WHERE substr(detail,1,instr(detail||char(10),char(10))-1)=? AND class IN ('plan','triage') AND json_extract(history,'$[0].by')=? ORDER BY id DESC LIMIT ?")
1430
+ .all(key, HUB, SURVEY_STORE_LIMIT + 1) as { id: number; state: string }[];
1431
+ if (rows.length > SURVEY_STORE_LIMIT) return surveyStorageFailure();
1432
+ const active = rows.filter(row => !isClosedTaskState(row.state));
1433
+ if (active.length > 1) return surveyStorageFailure();
1434
+ const closed = rows.find(row => isClosedTaskState(row.state));
1435
+ return { ...(active[0] ? { active: surveyInteger(active[0].id) } : {}), ...(closed ? { closed: surveyInteger(closed.id) } : {}) };
1436
+ }
1437
+ rejectedFindingsFor(repo: string, pass: string, id: string, limit = 100): { rows: StoredRejectedFinding[]; complete: boolean } {
1438
+ return this.rejectedFindings(repo, limit, { pass: surveyPass(pass), id: surveyFindingId(id) });
1439
+ }
1440
+ rejectedFindings(repo: string, limit = 100, selector?: { pass: string; id: string }): { rows: StoredRejectedFinding[]; complete: boolean } {
1441
+ surveyText(repo, 1024); surveyInteger(limit); if (limit > SURVEY_STORE_LIMIT) return surveyInputFailure();
1442
+ const selected = selector === undefined ? undefined : surveyObject(selector, ["pass", "id"]);
1443
+ const args: (string | number)[] = [repo];
1444
+ if (selected) args.push(surveyFindingId(selected.id), surveyPass(selected.pass)); args.push(limit + 1);
1445
+ const rows = this.db.query(`SELECT id,CASE WHEN length(CAST(repo AS BLOB))<=1024 THEN repo END AS repo,CASE WHEN length(CAST(finding_id AS BLOB))<=96 THEN finding_id END AS finding_id,
1446
+ CASE WHEN length(CAST(pass AS BLOB))<=16 THEN pass END AS pass,CASE WHEN length(CAST(kind AS BLOB))<=16 THEN kind END AS kind,
1447
+ CASE WHEN length(CAST(body AS BLOB))<=${SURVEY_STORE_BYTES} THEN body END AS body,CASE WHEN length(CAST(body_sha256 AS BLOB))=64 THEN body_sha256 END AS body_sha256,
1448
+ CASE WHEN length(CAST(prior_ids AS BLOB))<=${SURVEY_STORE_BYTES} THEN prior_ids END AS prior_ids,CASE WHEN length(CAST(replay_key AS BLOB))=64 THEN replay_key END AS replay_key,withheld FROM considered_findings WHERE repo=?${selected ? " AND finding_id=? AND pass=?" : ""} ORDER BY id LIMIT ?`).all(...args) as { id: number; repo: string; finding_id: string; pass: string; kind: string; body: string | null; body_sha256: string; prior_ids: string; replay_key: string; withheld: number }[];
1449
+ if (rows.length > limit) return { rows: [], complete: false };
1450
+ try {
1451
+ const parsed = rows.map(row => {
1452
+ if (!row.body || surveyHash(row.body) !== row.body_sha256 || row.withheld !== 0 && row.withheld !== 1 || row.kind !== "rejected" && row.kind !== "reconsidered" || typeof row.prior_ids !== "string") return surveyStorageFailure();
1453
+ const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value));
1454
+ if (entry.repo !== row.repo || entry.id !== row.finding_id || entry.pass !== row.pass || new Set(prior).size !== prior.length || row.kind === "rejected" && prior.length || row.kind === "reconsidered" && !prior.length) return surveyStorageFailure();
1455
+ const { withheld: _private, ...identity } = entry;
1456
+ if (surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key || prior.some(id => id >= row.id)) return surveyStorageFailure();
1457
+ return { id: row.id, entry: { ...entry, ...(row.withheld ? { withheld: true as const } : {}) }, kind: row.kind, prior };
1458
+ });
1459
+ for (const row of parsed) for (const id of row.prior) if (!parsed.some(prior => prior.id === id && prior.kind === "rejected" && prior.entry.id === row.entry.id && prior.entry.pass === row.entry.pass)) return surveyStorageFailure();
1460
+ return { rows: parsed.filter(row => row.kind === "rejected").map(row => ({ id: row.id, entry: row.entry, reconsideredBy: parsed.filter(next => next.prior.includes(row.id)).map(next => next.id) })), complete: true };
1461
+ } catch { return surveyStorageFailure(); }
1462
+ }
1463
+ surveyApply(id: number, input: SurveyApplyInput, fenceInput: SurveyWriteFence): { createdIDs: number[]; dedupedIDs: number[]; already: boolean } {
1464
+ surveyInteger(id);
1465
+ const given = surveyObject(input, ["findings", "decisions", "by", "at", "cards", "rejections", "reconsiderations", "withheld"]);
1466
+ const findings = parseSurveyFindings(given.findings), decisions = parseSurveyVetDecisions(given.decisions), by = surveyText(given.by, 128), at = surveyInteger(given.at, 0);
1467
+ if (given.withheld !== undefined && given.withheld !== true) return surveyInputFailure();
1468
+ const cards = surveyArray(given.cards ?? [], 64).map(value => {
1469
+ const row = surveyObject(value, ["id", "key", "title", "detail", "class", "refs", "signals", "reopens", "reopenReason"]), key = surveyText(row.key, 512), title = surveyText(row.title, 512);
1470
+ if (typeof row.detail !== "string" || Buffer.byteLength(row.detail) > SURVEY_LIMITS.cardBytes || row.detail.split("\n", 1)[0] !== key || !key.startsWith("Survey finding key: ") || row.class !== "plan" && row.class !== "triage") return surveyInputFailure();
1471
+ const rawRefs = row.refs === undefined ? undefined : surveyObject(row.refs, ["repo", "branch", "commit", "paths"]), refs: TaskRefs | undefined = rawRefs ? {} : undefined;
1472
+ if (rawRefs && refs) {
1473
+ for (const key of ["repo", "branch", "commit"] as const) if (rawRefs[key] !== undefined) refs[key] = surveyText(rawRefs[key], 1024);
1474
+ if (rawRefs.paths !== undefined) refs.paths = surveyArray(rawRefs.paths, 64).map(surveyPath);
1475
+ }
1476
+ const signals = row.signals === undefined ? undefined : surveyArray(row.signals, 64).map(value => surveyText(value, 128));
1477
+ if ((row.reopens === undefined) !== (row.reopenReason === undefined)) return surveyInputFailure();
1478
+ const reopening = row.reopens === undefined ? {} : { reopens: surveyInteger(row.reopens), reopenReason: surveyText(row.reopenReason) };
1479
+ return { id: surveyText(row.id, 96), key, title, detail: row.detail, class: row.class, ...(refs ? { refs } : {}), ...(signals ? { signals } : {}), ...reopening };
1480
+ });
1481
+ if (new Set(cards.map(card => card.id)).size !== cards.length || new Set(cards.map(card => card.key)).size !== cards.length) return surveyInputFailure();
1482
+ const rejections = surveyArray(given.rejections ?? [], 64).map(parseConsideredEntry), reconsiderations = surveyArray(given.reconsiderations ?? [], 64).map(parseConsideredEntry);
1483
+ const fence = surveyObject(fenceInput, ["boardRevision", "taskCreated", "taskFlowRevision", "owner"]);
1484
+ surveyInteger(fence.boardRevision, 0); surveyInteger(fence.taskCreated, 0); surveyInteger(fence.taskFlowRevision, 0); surveyText(fence.owner, 128);
1485
+ return this.atomic(() => {
1486
+ const revision = this.statusRevision(), survey = this.survey(id), task = survey && this.get(survey.task);
1487
+ if (!survey || !task || revision !== fence.boardRevision || task.created !== survey.taskCreated || task.created !== fence.taskCreated
1488
+ || task.history.length !== fence.taskFlowRevision || task.class !== "plan" || task.state !== "in_progress" || task.owner !== fence.owner
1489
+ || by !== task.owner && by !== USER || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure();
1490
+ const existing = this.surveyFindings(id), merged = new Map(existing.map(row => [row.finding.id, { ...row }]));
1491
+ for (const finding of findings) {
1492
+ const prior = merged.get(finding.id);
1493
+ if (prior && JSON.stringify(prior.finding) !== JSON.stringify(finding)) return surveyInputFailure();
1494
+ if (!prior) merged.set(finding.id, { finding, foundBy: by, foundAt: at });
1495
+ }
1496
+ if (merged.size > 64) return surveyInputFailure();
1497
+ parseSurveyFindings([...merged.values()].map(row => row.finding));
1498
+ const prepared = [...rejections, ...reconsiderations];
1499
+ for (const entry of prepared) {
1500
+ const finding = merged.get(entry.id)?.finding;
1501
+ if (!finding || entry.repo !== survey.repo || entry.pass !== finding.pass || entry.ref !== survey.ref || entry.source.kind !== "survey"
1502
+ || entry.source.task !== task.id || entry.source.created !== task.created || JSON.stringify(entry.paths) !== JSON.stringify(finding.paths)) return surveyInputFailure();
1503
+ }
1504
+ for (const decision of decisions) {
1505
+ const row = merged.get(decision.id); if (!row) return surveyInputFailure();
1506
+ const prior = row.decision;
1507
+ if (prior && JSON.stringify(prior) === JSON.stringify(decision)) continue;
1508
+ if (prior && !(prior.verdict === "rejected" && decision.verdict === "vetted" && decision.reason)
1509
+ && !(prior.verdict === "vetted" && decision.verdict === "vetted" && decision.reason && reconsiderations.some(entry => entry.id === decision.id && entry.reason === decision.reason))) return surveyInputFailure();
1510
+ const ledger = decision.verdict === "rejected" ? rejections : prior?.verdict === "rejected" ? reconsiderations : [];
1511
+ if ((decision.verdict === "rejected" || prior?.verdict === "rejected") && !ledger.some(entry => entry.id === decision.id && entry.reason === decision.reason)) return surveyInputFailure();
1512
+ row.decision = decision;
1513
+ row.decisionBy = by; row.decisionAt = at;
1514
+ }
1515
+ parseSurveyVetDecisions([...merged.values()].flatMap(row => row.decision ? [row.decision] : []));
1516
+ for (const entry of rejections) if (!decisions.some(row => row.id === entry.id && row.verdict === "rejected" && row.reason === entry.reason)) return surveyInputFailure();
1517
+ for (const entry of reconsiderations) if (!decisions.some(row => row.id === entry.id && row.verdict === "vetted" && row.reason === entry.reason)) return surveyInputFailure();
1518
+ for (const entry of rejections) this.consideredWrite(entry, "rejected");
1519
+ for (const entry of reconsiderations) {
1520
+ const ledger = this.rejectedFindingsFor(survey.repo, entry.pass, entry.id, SURVEY_STORE_LIMIT); if (!ledger.complete) return surveyInputFailure();
1521
+ const prior = ledger.rows.filter(row => row.entry.id === entry.id && row.entry.pass === entry.pass).map(row => row.id);
1522
+ this.consideredWrite(entry, "reconsidered", prior);
1523
+ }
1524
+ const createdIDs: number[] = [], dedupedIDs: number[] = [];
1525
+ for (const card of cards) {
1526
+ const row = merged.get(card.id);
1527
+ if (!row || row.decision?.verdict !== "vetted" || card.class !== (row.finding.confidence === "low" ? "triage" : "plan")) return surveyInputFailure();
1528
+ if (row.finding.pass === "security" && card.refs && Object.keys(card.refs).length) return surveyInputFailure();
1529
+ const history = this.surveyCardHistory(card.key);
1530
+ if (history.active) dedupedIDs.push(history.active);
1531
+ else {
1532
+ if (history.closed !== card.reopens || card.reopens !== undefined && !card.detail.includes(`Reopened from hub task ${card.reopens}: ${card.reopenReason}`)) return surveyInputFailure();
1533
+ createdIDs.push(this.propose(HUB, { title: card.title, detail: card.detail, class: card.class, backlog: true, ...(card.refs ? { refs: card.refs } : {}), ...(card.signals ? { signals: card.signals } : {}) }).id);
1534
+ }
1535
+ }
1536
+ for (const row of merged.values()) {
1537
+ const prior = existing.find(old => old.finding.id === row.finding.id), body = JSON.stringify(row);
1538
+ if (Buffer.byteLength(body) > SURVEY_STORE_BYTES) return surveyInputFailure();
1539
+ if (!prior || JSON.stringify(prior) !== body) this.taskWrite(() => this.db.query("INSERT INTO advisor_survey_findings(survey,finding_id,body,body_sha256) VALUES(?,?,?,?) ON CONFLICT(survey,finding_id) DO UPDATE SET body=excluded.body,body_sha256=excluded.body_sha256").run(id, row.finding.id, body, surveyHash(body)));
1540
+ }
1541
+ if (given.withheld && !survey.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(id));
1542
+ return { createdIDs, dedupedIDs, already: this.statusRevision() === revision };
1543
+ });
1544
+ }
1545
+
1546
+ hasSurveyState(): boolean {
1547
+ return !!(this.db.query("SELECT EXISTS(SELECT 1 FROM advisor_surveys UNION ALL SELECT 1 FROM advisor_survey_findings UNION ALL SELECT 1 FROM considered_findings) AS present").get() as { present: number }).present;
1548
+ }
1549
+ /** Stream bounded validated private rows into recovery proof; output never includes finding or ledger text. */
1550
+ surveyIntegrity(): { surveys: number; findings: number; considered: number; digest: string } {
1551
+ try { return this.db.transaction(() => {
1552
+ const digest = createHash("sha256"); let surveys = 0, findings = 0, considered = 0;
1553
+ for (const key of this.db.query("SELECT id FROM advisor_surveys ORDER BY id").iterate() as Iterable<{ id: number }>) {
1554
+ const row = this.survey(key.id); if (!row) return surveyStorageFailure();
1555
+ const task = this.get(row.task); if (!task || task.created !== row.taskCreated) return surveyStorageFailure();
1556
+ digest.update(JSON.stringify({ survey: row })); surveys++;
1557
+ const candidates = this.surveyFindings(row.id);
1558
+ parseSurveyFindings(candidates.map(candidate => candidate.finding));
1559
+ parseSurveyVetDecisions(candidates.flatMap(candidate => candidate.decision ? [candidate.decision] : []));
1560
+ for (const candidate of candidates) { digest.update(JSON.stringify({ survey: row.id, candidate })); findings++; }
1561
+ }
1562
+ const count = this.db.query("SELECT COUNT(*) AS count FROM advisor_survey_findings").get() as { count: number };
1563
+ if (count.count !== findings) return surveyStorageFailure();
1564
+ const query = `SELECT id,CASE WHEN length(CAST(repo AS BLOB))<=1024 THEN repo END AS repo,CASE WHEN length(CAST(finding_id AS BLOB))<=96 THEN finding_id END AS finding_id,
1565
+ CASE WHEN length(CAST(pass AS BLOB))<=16 THEN pass END AS pass,CASE WHEN length(CAST(kind AS BLOB))<=16 THEN kind END AS kind,
1566
+ CASE WHEN length(CAST(body AS BLOB))<=${SURVEY_STORE_BYTES} THEN body END AS body,CASE WHEN length(CAST(body_sha256 AS BLOB))=64 THEN body_sha256 END AS body_sha256,
1567
+ CASE WHEN length(CAST(prior_ids AS BLOB))<=${SURVEY_STORE_BYTES} THEN prior_ids END AS prior_ids,CASE WHEN length(CAST(replay_key AS BLOB))=64 THEN replay_key END AS replay_key,withheld FROM considered_findings ORDER BY id`;
1568
+ for (const row of this.db.query(query).iterate() as Iterable<{ id: number; repo: string; finding_id: string; pass: string; kind: string; body: string | null; body_sha256: string; prior_ids: string | null; replay_key: string; withheld: number }>) {
1569
+ if (!row.body || surveyHash(row.body) !== row.body_sha256 || typeof row.prior_ids !== "string" || row.withheld !== 0 && row.withheld !== 1 || row.kind !== "rejected" && row.kind !== "reconsidered") return surveyStorageFailure();
1570
+ const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value));
1571
+ const { withheld: _private, ...identity } = entry, task = this.get(entry.source.task);
1572
+ if (!task || task.created !== entry.source.created || entry.repo !== row.repo || entry.id !== row.finding_id || entry.pass !== row.pass
1573
+ || new Set(prior).size !== prior.length || prior.some(id => id >= row.id) || row.kind === "rejected" && prior.length || row.kind === "reconsidered" && !prior.length
1574
+ || surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key) return surveyStorageFailure();
1575
+ for (const id of prior) {
1576
+ const parent = this.db.query("SELECT id FROM considered_findings WHERE id=? AND repo=? AND finding_id=? AND pass=? AND kind='rejected'").get(id, row.repo, row.finding_id, row.pass);
1577
+ if (!parent) return surveyStorageFailure();
1578
+ }
1579
+ digest.update(JSON.stringify({ id: row.id, kind: row.kind, entry, prior, withheld: row.withheld })); considered++;
1580
+ }
1581
+ return { surveys, findings, considered, digest: digest.digest("hex") };
1582
+ })(); } catch { return surveyStorageFailure(); }
1583
+ }
1584
+
1585
+ /** #1403 A4: a new audit with its seeded ledger, in one transaction. Only `Tasks.auditStart` calls this. */
1586
+ auditCreate(row: { task: number; taskCreated: number; ref: string; since?: string; profile: string; scoped: boolean; by: string; at: number; units: readonly AuditUnit[] }): number {
1587
+ return this.atomic(() => {
1588
+ const result = this.db.query("INSERT INTO security_audits(task_id,task_created,ref,since,profile,scoped,at,by_peer,units) VALUES(?,?,?,?,?,?,?,?,?)")
1589
+ .run(row.task, row.taskCreated, row.ref, row.since ?? null, row.profile, row.scoped ? 1 : 0, row.at, row.by, JSON.stringify(row.units));
1590
+ return Number(result.lastInsertRowid);
1591
+ });
1592
+ }
1593
+ private auditRow(row: { id: number; task_id: number; task_created: number; ref: string; since: string | null; profile: string; scoped: number; at: number; by_peer: string; units: string } | null): StoredAudit | undefined {
1594
+ if (!row) return undefined;
1595
+ const units = JSON.parse(row.units) as AuditUnit[];
1596
+ if (!Array.isArray(units)) throw new Error("security audit storage is invalid");
1597
+ return { id: row.id, task: row.task_id, taskCreated: row.task_created, ref: row.ref, ...(row.since ? { since: row.since } : {}), profile: row.profile as AuditProfile, scoped: row.scoped === 1, at: row.at, by: row.by_peer, units };
1598
+ }
1599
+ audit(id: number): StoredAudit | undefined {
1600
+ return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE id=?").get(id) as never);
1601
+ }
1602
+ auditOfTask(task: number, taskCreated: number): StoredAudit | undefined {
1603
+ return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE task_id=? AND task_created=?").get(task, taskCreated) as never);
1604
+ }
1605
+ /** Newest first. `recorded` keeps only audits whose ledger holds at least one unit the auditor reported (the baseline carry-over and the default scope read these). */
1606
+ audits(limit = 32, recorded = false): StoredAudit[] {
1607
+ const rows = this.db.query("SELECT * FROM security_audits ORDER BY id DESC LIMIT ?").all(limit) as never[];
1608
+ const all = rows.map(row => this.auditRow(row)!);
1609
+ return recorded ? all.filter(row => row.units.some(unit => unit.reportedBy)) : all;
1610
+ }
1611
+ /**
1612
+ * One report in one transaction: the ledger, the filed findings, the verifications and the settlements land together or not at all. A finding id already verified or rejected is left as decided and returned
1613
+ * in the skipped list (the caller says so); a verification or settlement whose guard fails (decided or settled meanwhile, or by its own finder) rolls everything back and returns undefined. A settlement
1614
+ * needs the finding verified, not rejected and not yet settled.
1615
+ */
1616
+ auditApply(id: number, change: { units?: readonly AuditUnit[]; findings: readonly { finding: ReviewFinding; foundBy: string; at: number }[]; decisions: readonly { finding: string; verdict: "verified" | "rejected" }[]; settlements?: readonly { finding: string; disposition: "fixed" | "false_positive" }[]; by: string }): string[] | undefined {
1617
+ const skipped: string[] = [];
1618
+ try {
1619
+ this.atomic(() => {
1620
+ if (change.units) this.db.query("UPDATE security_audits SET units=? WHERE id=?").run(JSON.stringify(change.units), id);
1621
+ let seq = (this.db.query("SELECT COALESCE(MAX(seq),0) AS seq FROM security_audit_findings WHERE audit=?").get(id) as { seq: number }).seq;
1622
+ for (const item of change.findings) {
1623
+ const existing = this.db.query("SELECT seq FROM security_audit_findings WHERE audit=? AND finding_id=?").get(id, item.finding.id) as { seq: number } | null;
1624
+ if (!existing) { this.db.query("INSERT INTO security_audit_findings(audit,seq,finding_id,body,found_by,at) VALUES(?,?,?,?,?,?)").run(id, ++seq, item.finding.id, JSON.stringify(item.finding), item.foundBy, item.at); continue; }
1625
+ const changed = this.db.query("UPDATE security_audit_findings SET body=?,found_by=?,at=? WHERE audit=? AND seq=? AND verified_by IS NULL AND rejected_by IS NULL").run(JSON.stringify(item.finding), item.foundBy, item.at, id, existing.seq).changes;
1626
+ if (changed !== 1) skipped.push(item.finding.id);
1627
+ }
1628
+ for (const decision of change.decisions) {
1629
+ const column = decision.verdict === "verified" ? "verified_by" : "rejected_by";
1630
+ const done = this.db.query(`UPDATE security_audit_findings SET ${column}=? WHERE audit=? AND finding_id=? AND verified_by IS NULL AND rejected_by IS NULL AND found_by<>?`).run(change.by, id, decision.finding, change.by).changes;
1631
+ if (done !== 1) throw new Error("audit decision lost");
1632
+ }
1633
+ for (const settlement of change.settlements ?? []) {
1634
+ const done = this.db.query("UPDATE security_audit_findings SET settled_by=?,settled_as=? WHERE audit=? AND finding_id=? AND verified_by IS NOT NULL AND rejected_by IS NULL AND settled_by IS NULL AND found_by<>?").run(change.by, settlement.disposition, id, settlement.finding, change.by).changes;
1635
+ if (done !== 1) throw new Error("audit decision lost");
1636
+ }
1637
+ });
1638
+ } catch (error) {
1639
+ if (error instanceof Error && error.message === "audit decision lost") return undefined;
1640
+ throw error;
1641
+ }
1642
+ return skipped;
1643
+ }
1644
+ auditFindings(id: number): AuditFinding[] {
1645
+ const rows = this.db.query("SELECT body,found_by,at,verified_by,rejected_by,settled_by,settled_as FROM security_audit_findings WHERE audit=? ORDER BY seq").all(id) as { body: string; found_by: string; at: number; verified_by: string | null; rejected_by: string | null; settled_by: string | null; settled_as: string | null }[];
1646
+ // A settled finding reads with its settled disposition, so every reader that already shows a `fixed` or `false_positive` finding treats it as one.
1647
+ return rows.map(row => {
1648
+ const settled = row.settled_by && (row.settled_as === "fixed" || row.settled_as === "false_positive") ? row.settled_as : undefined;
1649
+ const body = JSON.parse(row.body) as ReviewFinding;
1650
+ return { finding: settled ? { ...body, disposition: settled } : body, foundBy: row.found_by, at: row.at, ...(row.verified_by ? { verifiedBy: row.verified_by } : {}), ...(row.rejected_by ? { rejectedBy: row.rejected_by } : {}), ...(settled ? { settledBy: row.settled_by!, settledAs: settled } : {}) };
1651
+ });
1652
+ }
1192
1653
  hasGuidanceVariants(): boolean {
1193
1654
  return (this.db.query("SELECT EXISTS(SELECT 1 FROM guidance_experiments) OR EXISTS(SELECT 1 FROM guidance_variants) AS present").get() as { present: number }).present === 1;
1194
1655
  }
@@ -1297,6 +1758,22 @@ export class Board {
1297
1758
  return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_evidence_links) AS present").get() as { present: number }).present === 1;
1298
1759
  }
1299
1760
 
1761
+ /** Older evidence readers reject the new optional stored withdrawal field. Keep that downgrade fence conditional. */
1762
+ hasWithdrawnEvidenceState(): boolean {
1763
+ return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_evidence_links WHERE json_extract(body,'$.status')='withdrawn') AS present").get() as { present: number }).present === 1;
1764
+ }
1765
+
1766
+ /** Same #901 history record, with the host's completed observation fenced against intervening database writes. No source I/O in this transaction. */
1767
+ recordSynthesisClaimVerdict(id: number, claim: ClaimVerdict, fence: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task {
1768
+ return this.atomic(() => {
1769
+ const task = this.get(id);
1770
+ if (!task || this.statusRevision() !== fence.boardRevision || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision
1771
+ || !claim.synthesis || claim.list !== fence.claimRevision || taskClaimIdentity(task, claim.slot).claimRevision !== fence.claimRevision)
1772
+ throw new Error("synthesis context changed before the claim verdict write; refresh the manifest and explicitly record the disposition again");
1773
+ return this.update(id, USER, "claim verdict", {}, undefined, { claim }, fence.taskFlowRevision);
1774
+ });
1775
+ }
1776
+
1300
1777
  researchEvidenceIntegrity(): { links: number; revisions: number; digest: string } {
1301
1778
  return this.db.transaction(() => {
1302
1779
  const digest = createHash("sha256").update("agent-hub.research-evidence/v1\n");
@@ -1950,7 +2427,12 @@ export class Board {
1950
2427
  })();
1951
2428
  }
1952
2429
 
1953
- propose(by: PeerId, t: { title: string; detail?: string; class: TaskClass; planner?: PeerId | null; plannerReason?: PlannerReason; profile?: import("./profiles.ts").ProfileName; profileClass?: string; customProfile?: true; role?: string; refs?: TaskRefs; plan?: TaskPlan; deps?: number[]; reserved?: PeerId; signals?: string[]; backlog?: boolean; draft?: boolean; external?: GitHubSource }): Task {
2430
+ propose(by: PeerId, t: { title: string; detail?: string; class: TaskClass; planner?: PeerId | null; plannerReason?: PlannerReason; profile?: import("./profiles.ts").ProfileName; profileClass?: string; customProfile?: true; role?: string; refs?: TaskRefs; plan?: TaskPlan; deps?: number[]; reserved?: PeerId; signals?: string[]; backlog?: boolean; draft?: boolean; external?: GitHubSource }, createdHook?: (task: Task) => void): Task {
2431
+ // Host-only synchronous DB bookkeeping. Never sourced from task input or called with I/O/screens.
2432
+ if (createdHook !== undefined) {
2433
+ if (typeof createdHook !== "function") throw new Error("invalid host proposal hook");
2434
+ return this.atomic(() => { const task = this.propose(by, t); createdHook(task); return task; });
2435
+ }
1954
2436
  const now = Date.now(), planner = plannerValue(t.planner);
1955
2437
  const chosen = Object.hasOwn(t, "planner") || t.plannerReason !== undefined ? plannerMetadata(planner, t.plannerReason) : {};
1956
2438
  const history: HistoryEntry[] = [{ at: now, by, ...chosen, event: t.backlog ? "backlogged" : "proposed", ...(this.trackPlanRevisions?.() && t.plan && Object.keys(t.plan).length ? { planRevision: { revision: 1, fingerprint: planFingerprint(t.plan) } } : {}) }];
@@ -2203,7 +2685,7 @@ export class Board {
2203
2685
 
2204
2686
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
2205
2687
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
2206
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2688
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2207
2689
  if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
2208
2690
  const task = this.get(id);
2209
2691
  if (!task) throw new Error(`no task #${id}`);
@@ -2269,13 +2751,18 @@ export class Board {
2269
2751
  if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("finding metadata requires a saved review verdict");
2270
2752
  const head = extra.reviewFindings.head;
2271
2753
  if (head !== undefined && !/^[a-f0-9]{40}$/.test(head)) throw new Error("finding metadata requires a full reviewed head");
2272
- reviewFindings = { ...(head ? { head } : {}), items: parseReviewFindings(extra.reviewFindings.items, { person: by === "user", maxNits: 64 }) };
2754
+ reviewFindings = { ...(head ? { head } : {}), items: parseReviewFindings(extra.reviewFindings.items, { person: by === "user", maxNits: 64, contract: "stored" }) };
2273
2755
  }
2274
2756
  let deliverables: DeliverableRecord[] | undefined;
2275
2757
  if (extra.deliverables !== undefined) {
2276
2758
  if (!["done", "done (checking)", "lifecycle", "approved"].includes(event)) throw new Error("deliverable records require a done, a lifecycle record or an approval");
2277
2759
  deliverables = parseDeliverableRecords(extra.deliverables);
2278
2760
  }
2761
+ let securityPass: SecurityPassRecord | undefined;
2762
+ if (extra.securityPass !== undefined) {
2763
+ if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("a security pass requires a saved review verdict");
2764
+ securityPass = storedSecurityPass(extra.securityPass);
2765
+ }
2279
2766
  let unmetCriteria: string[] | undefined;
2280
2767
  if (extra.unmetCriteria !== undefined) {
2281
2768
  if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("unmet criteria require a saved review verdict");
@@ -2296,7 +2783,7 @@ export class Board {
2296
2783
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2297
2784
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2298
2785
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
2299
- const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2786
+ const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2300
2787
  this.taskWrite(() => {
2301
2788
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2302
2789
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
@@ -2439,6 +2926,169 @@ export class Board {
2439
2926
  });
2440
2927
  }
2441
2928
 
2929
+ /** Raw roadmap storage. Every external writer is admitted by Tasks. */
2930
+ newMilestone(input: MilestoneInput, by: string, now = Date.now()): Milestone {
2931
+ const value = parseMilestoneInput(input), actor = milestoneActor(by), at = milestoneId(now);
2932
+ return this.db.transaction(() => {
2933
+ this.milestoneParent(undefined, value.parent);
2934
+ const history = milestoneHistory([{ at, by: actor, event: "created" }]);
2935
+ const inserted = this.db.query("INSERT INTO milestones(title,outcome,state,horizon,milestone_order,target,parent,history,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?)")
2936
+ .run(value.title, value.outcome, value.state, value.horizon, value.order, value.target, value.parent, JSON.stringify(history), at, at);
2937
+ return this.milestone(Number(inserted.lastInsertRowid))!;
2938
+ })();
2939
+ }
2940
+
2941
+ milestone(id: number): Milestone | undefined {
2942
+ milestoneId(id);
2943
+ const row = this.db.query("SELECT * FROM milestones WHERE id=?").get(id) as Record<string, unknown> | null;
2944
+ return row ? parseMilestone(row) : undefined;
2945
+ }
2946
+
2947
+ milestones(): Milestone[] {
2948
+ return (this.db.query("SELECT * FROM milestones ORDER BY milestone_order,id").all() as Record<string, unknown>[]).map(parseMilestone);
2949
+ }
2950
+
2951
+ milestoneLinks(id?: number): MilestoneLink[] {
2952
+ if (id !== undefined) milestoneId(id);
2953
+ const rows = (id === undefined
2954
+ ? this.db.query("SELECT * FROM milestone_links ORDER BY milestone,kind,ref").all()
2955
+ : this.db.query("SELECT * FROM milestone_links WHERE milestone=? ORDER BY kind,ref").all(id)) as Record<string, unknown>[];
2956
+ return rows.map(row => ({ milestone: milestoneId(row.milestone), kind: row.kind as MilestoneLinkKind,
2957
+ ref: milestoneLinkRef(row.kind as MilestoneLinkKind, row.ref), by: milestoneActor(row.by), at: milestoneId(row.at) }));
2958
+ }
2959
+
2960
+ hasMilestoneState(): boolean {
2961
+ const row = this.db.query("SELECT EXISTS(SELECT 1 FROM milestones) OR EXISTS(SELECT 1 FROM milestone_links) AS present").get() as { present: number };
2962
+ return row.present === 1;
2963
+ }
2964
+
2965
+ roadmapIntegrity(): { milestones: number; links: number; digest: string } {
2966
+ return this.db.transaction(() => {
2967
+ const milestones = this.milestones().sort((a, b) => a.id - b.id), links = this.milestoneLinks();
2968
+ return { milestones: milestones.length, links: links.length, digest: createHash("sha256").update(JSON.stringify({ milestones, links })).digest("hex") };
2969
+ })();
2970
+ }
2971
+
2972
+ /** Parent shape and compare-and-set are checked under the same write transaction. */
2973
+ updateMilestone(id: number, patch: MilestonePatch, revision: number, event: MilestoneHistoryEntry): Milestone {
2974
+ const fields = parseMilestonePatch(patch), entry = milestoneHistory([event])[0]!;
2975
+ return this.db.transaction(() => this.writeMilestone(id, fields, revision, entry))();
2976
+ }
2977
+
2978
+ linkMilestone(id: number, kind: MilestoneLinkKind, ref: string, by: string, revision: number, now = Date.now()): Milestone {
2979
+ const key = milestoneLinkRef(kind, ref), actor = milestoneActor(by), at = milestoneId(now);
2980
+ return this.db.transaction(() => {
2981
+ const before = this.currentMilestone(id, revision);
2982
+ if (this.db.query("SELECT 1 FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").get(id, kind, key)) return before;
2983
+ const updated = this.writeMilestone(id, {}, revision, { at, by: actor, event: "linked", kind });
2984
+ this.db.query("INSERT INTO milestone_links(milestone,kind,ref,by,at) VALUES(?,?,?,?,?)").run(id, kind, key, actor, at);
2985
+ return updated;
2986
+ })();
2987
+ }
2988
+
2989
+ unlinkMilestone(id: number, kind: MilestoneLinkKind, ref: string, by: string, revision: number, now = Date.now()): Milestone {
2990
+ const key = milestoneLinkRef(kind, ref), actor = milestoneActor(by), at = milestoneId(now);
2991
+ return this.db.transaction(() => {
2992
+ const before = this.currentMilestone(id, revision);
2993
+ if (!this.db.query("SELECT 1 FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").get(id, kind, key)) return before;
2994
+ const updated = this.writeMilestone(id, {}, revision, { at, by: actor, event: "unlinked", kind });
2995
+ this.db.query("DELETE FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").run(id, kind, key);
2996
+ return updated;
2997
+ })();
2998
+ }
2999
+
3000
+ /** R3: a pending model suggestion. One per item at a time; a repeat for the same item is ignored, never doubled. */
3001
+ addSuggestion(row: { kind: SuggestionItemKind; ref: string; milestone: number | null; proposal: { title: string; outcome: string } | null; citeMilestone: string | null; citeItem: string }, by: string, now = Date.now()): MilestoneSuggestion | undefined {
3002
+ const actor = milestoneActor(by), at = milestoneId(now);
3003
+ return this.db.transaction(() => {
3004
+ if (this.db.query("SELECT 1 FROM milestone_suggestions WHERE kind=? AND ref=? AND state='pending'").get(row.kind, row.ref)) return undefined;
3005
+ const inserted = this.db.query("INSERT INTO milestone_suggestions(kind,ref,milestone,proposal,cite_milestone,cite_item,state,by,created) VALUES(?,?,?,?,?,?,'pending',?,?)")
3006
+ .run(row.kind, row.ref, row.milestone, row.proposal ? JSON.stringify(row.proposal) : null, row.citeMilestone, row.citeItem, actor, at);
3007
+ // Settled rows are history, not storage: keep the newest 500.
3008
+ this.db.query("DELETE FROM milestone_suggestions WHERE state<>'pending' AND id NOT IN (SELECT id FROM milestone_suggestions WHERE state<>'pending' ORDER BY id DESC LIMIT 500)").run();
3009
+ return this.suggestion(Number(inserted.lastInsertRowid))!;
3010
+ })();
3011
+ }
3012
+
3013
+ suggestion(id: number): MilestoneSuggestion | undefined {
3014
+ milestoneId(id);
3015
+ const row = this.db.query("SELECT * FROM milestone_suggestions WHERE id=?").get(id) as Record<string, unknown> | null;
3016
+ return row ? parseSuggestion(row) : undefined;
3017
+ }
3018
+
3019
+ suggestions(state?: SuggestionState): MilestoneSuggestion[] {
3020
+ const rows = (state === undefined ? this.db.query("SELECT * FROM milestone_suggestions ORDER BY id").all() : this.db.query("SELECT * FROM milestone_suggestions WHERE state=? ORDER BY id").all(state)) as Record<string, unknown>[];
3021
+ return rows.map(parseSuggestion);
3022
+ }
3023
+
3024
+ /** Remember the milestone an accepted "new milestone" suggestion created, so a retry after a failed link never creates a second one. */
3025
+ suggestionCreated(id: number): number | undefined {
3026
+ const row = this.db.query("SELECT created_milestone AS made FROM milestone_suggestions WHERE id=?").get(milestoneId(id)) as { made: number | null } | null;
3027
+ return row?.made ?? undefined;
3028
+ }
3029
+
3030
+ setSuggestionCreated(id: number, milestone: number): void {
3031
+ this.db.query("UPDATE milestone_suggestions SET created_milestone=? WHERE id=? AND state='pending' AND created_milestone IS NULL").run(milestoneId(milestone), milestoneId(id));
3032
+ }
3033
+
3034
+ /** Compare-and-set from pending: a second settle of the same suggestion changes nothing. */
3035
+ settleSuggestion(id: number, state: "accepted" | "rejected" | "superseded", by: string, now = Date.now()): MilestoneSuggestion {
3036
+ const actor = milestoneActor(by), at = milestoneId(now);
3037
+ return this.db.transaction(() => {
3038
+ const result = this.db.query("UPDATE milestone_suggestions SET state=?,settled=?,settled_by=? WHERE id=? AND state='pending'").run(state, at, actor, milestoneId(id));
3039
+ const row = this.suggestion(id);
3040
+ if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
3041
+ if (result.changes !== 1 && row.state !== state) throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
3042
+ return row;
3043
+ })();
3044
+ }
3045
+
3046
+ importedMilestone(repo: string, number: number): number | undefined {
3047
+ const row = this.db.query("SELECT milestone FROM milestone_imports WHERE repo=? AND number=?").get(repo.toLowerCase(), milestoneId(number)) as { milestone: number } | null;
3048
+ return row?.milestone;
3049
+ }
3050
+
3051
+ /** One transaction: the milestone and its import mark exist together or not at all, so a repeat finds the mark. */
3052
+ importMilestone(repo: string, number: number, input: MilestoneInput, by: string, now = Date.now()): { milestone: Milestone; created: boolean } {
3053
+ const key = repo.toLowerCase();
3054
+ return this.db.transaction(() => {
3055
+ const prior = this.importedMilestone(key, number);
3056
+ const existing = prior === undefined ? undefined : this.milestone(prior);
3057
+ if (existing) return { milestone: existing, created: false };
3058
+ const milestone = this.newMilestone(input, by, now);
3059
+ this.db.query("INSERT OR REPLACE INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, milestoneId(number), milestone.id, milestoneId(now));
3060
+ return { milestone, created: true };
3061
+ })();
3062
+ }
3063
+
3064
+ private currentMilestone(id: number, revision: number): Milestone {
3065
+ milestoneRevision(revision);
3066
+ const row = this.milestone(id);
3067
+ if (!row || row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before retrying");
3068
+ return row;
3069
+ }
3070
+
3071
+ private milestoneParent(id: number | undefined, parent: number | null): void {
3072
+ if (parent === null) return;
3073
+ if (parent === id) throw new PreEffectToolRefusal("roadmap milestone cannot parent itself; choose another parent with ahub roadmap edit");
3074
+ const ancestor = this.milestone(parent);
3075
+ if (!ancestor || ancestor.parent !== null) throw new PreEffectToolRefusal("roadmap parent must exist at the top level; inspect ahub roadmap list");
3076
+ if (id !== undefined && this.db.query("SELECT 1 FROM milestones WHERE parent=? LIMIT 1").get(id)) throw new PreEffectToolRefusal("roadmap nesting is limited to one level; move child milestones first");
3077
+ }
3078
+
3079
+ private writeMilestone(id: number, patch: MilestonePatch, revision: number, event: MilestoneHistoryEntry): Milestone {
3080
+ const current = this.currentMilestone(id, revision), next = { ...current, ...patch };
3081
+ this.milestoneParent(id, next.parent);
3082
+ const settling = current.state !== next.state && (next.state === "done" || next.state === "dropped");
3083
+ if (current.history.length >= MILESTONE_HISTORY_LIMIT - 1 && !settling)
3084
+ throw new PreEffectToolRefusal(`roadmap history reserves its last slot for settlement; ask the person to run ahub roadmap state ${id} done or ahub roadmap state ${id} dropped`);
3085
+ const history = milestoneHistory([...current.history, event]);
3086
+ const result = this.db.query("UPDATE milestones SET title=?,outcome=?,state=?,horizon=?,milestone_order=?,target=?,parent=?,history=?,updated=?,revision=revision+1 WHERE id=? AND revision=?")
3087
+ .run(next.title, next.outcome, next.state, next.horizon, next.order, next.target, next.parent, JSON.stringify(history), event.at, id, revision);
3088
+ if (result.changes !== 1) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before retrying");
3089
+ return this.milestone(id)!;
3090
+ }
3091
+
2442
3092
  newRelease(name: string, goal: string, order: number, planner?: PeerId | null): Release {
2443
3093
  const now = Date.now(), selected = plannerValue(planner);
2444
3094
  const result = this.db.query("INSERT INTO releases(name,goal,release_order,created,updated,planner) VALUES(?,?,?,?,?,?)").run(name, goal, order, now, now, selected);
@@ -2569,6 +3219,18 @@ function parse(row: Record<string, unknown>): Task {
2569
3219
  return out as unknown as Task;
2570
3220
  }
2571
3221
 
3222
+ function parseMilestone(row: Record<string, unknown>): Milestone {
3223
+ return { ...parseMilestoneInput({ title: row.title, outcome: row.outcome, state: row.state, horizon: row.horizon, order: row.milestone_order, target: row.target, parent: row.parent }),
3224
+ id: milestoneId(row.id), revision: milestoneRevision(row.revision), history: milestoneHistory(JSON.parse(String(row.history))), created: milestoneId(row.created), updated: milestoneId(row.updated) };
3225
+ }
3226
+
3227
+ function parseSuggestion(row: Record<string, unknown>): MilestoneSuggestion {
3228
+ return { id: milestoneId(row.id), kind: row.kind as SuggestionItemKind, ref: String(row.ref), milestone: row.milestone == null ? null : milestoneId(row.milestone),
3229
+ proposal: row.proposal == null ? null : JSON.parse(String(row.proposal)) as { title: string; outcome: string }, citeMilestone: row.cite_milestone == null ? null : String(row.cite_milestone),
3230
+ citeItem: String(row.cite_item), state: row.state as SuggestionState, by: milestoneActor(row.by), created: milestoneId(row.created),
3231
+ settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
3232
+ }
3233
+
2572
3234
  function parseRelease(row: Record<string, unknown>): Release {
2573
3235
  return { ...(row.train == null ? {} : { train: JSON.parse(String(row.train)) }), planner: row.planner == null ? null : String(row.planner), id: Number(row.id), name: String(row.name), goal: String(row.goal), order: Number(row.release_order), state: row.state as ReleaseState,
2574
3236
  plannedStart: row.planned_start as number | null, cut: row.cut as number | null, ship: row.ship as number | null,