@staix/agent-hub 0.38.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +17 -7
- package/docs/adding-an-ai-tool.md +6 -4
- package/docs/agent-notes/README.md +16 -0
- package/docs/agent-notes/adapters.md +4 -2
- package/docs/agent-notes/budget.md +8 -0
- package/docs/agent-notes/daemon.md +15 -8
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +55 -0
- package/docs/agent-notes/tasks.md +15 -4
- package/docs/agent-notes/tests.md +3 -2
- package/docs/design/adapters.md +51 -0
- package/docs/design/agent-hub-architecture.md +29 -1
- package/docs/design/task-board.md +151 -5
- package/docs/dogfood.md +20 -6
- package/docs/events.md +3 -3
- package/docs/memory.md +5 -5
- package/docs/operations.md +177 -28
- package/docs/profiles.md +100 -8
- package/docs/quickstart.md +32 -4
- package/docs/research.md +6 -3
- package/docs/roles.md +52 -0
- package/docs/sdlc.md +187 -1
- package/docs/security.md +50 -11
- package/docs/text-projection.md +1 -0
- package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
- package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
- package/docs/verification/2026-11-14-0.39.0.md +51 -0
- package/docs/verified.json +48 -25
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1953 -460
- package/plugins/agent-hub/server.js +2019 -498
- package/src/adapters/acp-model-policy.ts +1 -1
- package/src/adapters/acp-session-model.ts +35 -0
- package/src/adapters/acp.ts +14 -0
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +7 -0
- package/src/adapters/claude-channel.ts +1 -1
- package/src/adapters/claude-implementer.ts +8 -0
- package/src/adapters/claude-print-child.ts +26 -2
- package/src/adapters/claude-print.ts +4 -0
- package/src/adapters/codex-appserver.ts +90 -16
- package/src/adapters/codex-review-isolation.ts +2 -0
- package/src/adapters/compat.ts +4 -4
- package/src/adapters/conformance/fakes/acp-server.ts +11 -2
- package/src/adapters/conformance/fakes/app-server.ts +5 -1
- package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
- package/src/adapters/definitions/builtin-metadata.ts +6 -6
- package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
- package/src/adapters/definitions/native-quota.ts +122 -0
- package/src/adapters/definitions/native-recovery.ts +3 -0
- package/src/adapters/definitions/qwen.ts +1 -1
- package/src/adapters/kimi-review.ts +23 -0
- package/src/adapters/kimi-wire-usage.ts +39 -16
- package/src/adapters/local-worker.ts +6 -3
- package/src/adapters/pi-state-model.ts +12 -0
- package/src/adapters/pi.ts +22 -0
- package/src/adapters/print-result-model.ts +24 -0
- package/src/adapters/registry-types.ts +10 -1
- package/src/adapters/registry.ts +19 -2
- package/src/adapters/reviewer-print.ts +130 -15
- package/src/adapters/role-eligibility.ts +99 -0
- package/src/adapters/same-directory.ts +16 -0
- package/src/cli/agy-mcp.ts +18 -7
- package/src/cli/console-state.ts +3 -1
- package/src/cli/free-text.ts +20 -0
- package/src/cli/handoff-args.ts +1 -1
- package/src/cli/help.ts +61 -6
- package/src/cli/identity.ts +10 -4
- package/src/cli/init-prompt.ts +31 -2
- package/src/cli/init-roles.ts +156 -0
- package/src/cli/init-settings.ts +24 -2
- package/src/cli/init.ts +139 -17
- package/src/cli/main.ts +194 -49
- package/src/cli/model.ts +1 -1
- package/src/cli/output.ts +56 -1
- package/src/cli/preview.ts +1 -1
- package/src/cli/recovery-launch.ts +114 -0
- package/src/cli/recovery-package.ts +14 -7
- package/src/cli/recovery-version-preflight.ts +104 -0
- package/src/cli/role-doctor.ts +39 -0
- package/src/cli/sdlc-output.ts +66 -1
- package/src/cli/study-output.ts +54 -0
- package/src/cli/study.ts +14 -1
- package/src/cli/terminal-recovery.ts +14 -0
- package/src/cli/upgrade-presentation.ts +4 -0
- package/src/cli/upgrade-restore-state.ts +12 -3
- package/src/cli/upgrade-runtime.ts +40 -2
- package/src/cli/upgrade.ts +8 -4
- package/src/hub/advisor-survey.ts +139 -0
- package/src/hub/audit-source.ts +66 -0
- package/src/hub/board.ts +479 -14
- package/src/hub/budget.ts +54 -4
- package/src/hub/conductor.ts +14 -8
- package/src/hub/config-apply.ts +2 -1
- package/src/hub/config-edit-host.ts +77 -5
- package/src/hub/considered-findings.ts +47 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +343 -58
- package/src/hub/deliverable-files.ts +17 -1
- package/src/hub/dogfood-profile.ts +3 -2
- package/src/hub/events.ts +23 -2
- package/src/hub/folder-trigger.ts +11 -4
- package/src/hub/hub-tools.ts +88 -16
- package/src/hub/kimi-usage.ts +34 -2
- package/src/hub/lifecycle-schema.ts +3 -3
- package/src/hub/memory-profile.ts +9 -1
- package/src/hub/memory-sync-state.ts +1 -0
- package/src/hub/model-overrides.ts +2 -1
- package/src/hub/no-writes.ts +2 -0
- package/src/hub/operational-authority.ts +6 -1
- package/src/hub/operational-view.ts +5 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/plan-conformance.ts +20 -2
- package/src/hub/quota-account.ts +34 -0
- package/src/hub/recovery-policy.ts +18 -4
- package/src/hub/research-evidence.ts +51 -3
- package/src/hub/research.ts +77 -13
- package/src/hub/restart.ts +14 -0
- package/src/hub/review-budget.ts +88 -0
- package/src/hub/review-findings.ts +93 -12
- package/src/hub/reviewer-pool-config.ts +6 -2
- package/src/hub/reviewer-pool.ts +39 -6
- package/src/hub/routing.ts +7 -3
- package/src/hub/sdlc-merge.ts +1 -1
- package/src/hub/sdlc-queue.ts +14 -4
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +10 -6
- package/src/hub/security-audit.ts +178 -0
- package/src/hub/security-pass.ts +115 -0
- package/src/hub/settings.ts +11 -5
- package/src/hub/source-read.ts +80 -2
- package/src/hub/sources.ts +57 -9
- package/src/hub/startup-event-seeds.ts +5 -3
- package/src/hub/startup-timing.ts +1 -0
- package/src/hub/synthesis-readiness.ts +279 -0
- package/src/hub/tasks.ts +1083 -69
- package/src/hub/text-projection.ts +11 -1
- package/src/memory/capture.ts +2 -1
- package/src/ui/index.html +3 -0
- package/src/ui/office-model.ts +11 -3
- package/src/ui/office-space.ts +50 -30
- package/src/ui/plugin.ts +21 -11
package/src/hub/board.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { parseComparisonPlan, comparisonPlanHash, evaluatorIdentityHash, parseEx
|
|
|
10
10
|
import type { InvocationRow } from "./invocations.ts";
|
|
11
11
|
import { HOST_CODE_SYMBOLS, parseTaskCodeSymbols, type TaskCodeSymbols } from "./task-code-symbols.ts";
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
|
+
import { types } from "node:util";
|
|
13
14
|
import { planFingerprint } from "./plan-conformance.ts";
|
|
14
15
|
import type { PlannerReason } from "./routing.ts";
|
|
15
16
|
import type { ReviewerPoolReason } from "./reviewer-pool.ts";
|
|
@@ -19,14 +20,44 @@ import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts";
|
|
|
19
20
|
import { controlWriteSpan } from "./control-write-trace.ts";
|
|
20
21
|
import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
|
|
21
22
|
import { HUB, USER, type PeerId } from "./envelope.ts";
|
|
23
|
+
import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts";
|
|
24
|
+
import type { ReviewFinding } from "./review-findings.ts";
|
|
22
25
|
import type { SweepRecord } from "./task-sweep.ts";
|
|
23
26
|
import type { SpecAcceptance, SdlcReceipt } from "./sdlc.ts";
|
|
24
27
|
import { parseReviewFindings, type ReviewFindingSet } from "./review-findings.ts";
|
|
28
|
+
import { storedSecurityPass, type SecurityPassRecord } from "./security-pass.ts";
|
|
25
29
|
import { parseDeliverableRecords, type DeliverableRecord } from "./deliverables.ts";
|
|
26
30
|
import type { CostPlan, ReviewCost } from "./cost-governance.ts";
|
|
27
31
|
import type { SpecRef, SpecTaskReport } from "./specs-task.ts";
|
|
28
32
|
export type { SpecAck, SpecRef, SpecTaskReport } from "./specs-task.ts";
|
|
29
33
|
import { campaignHash, parseResearchCampaign, parseResearchHandoff, type ResearchCampaignContract, type ResearchCampaignStatus, type ResearchUnit, type ResearchHandoffV1, type ResearchHandoffRecord } from "./research-campaign.ts";
|
|
34
|
+
import { parseSurveyFindings, parseSurveyVetDecisions, surveyArray, surveyObject, surveyPath, surveyText, surveyFindingId, surveyPass, type SurveyFinding, type SurveyVetDecision, SURVEY_FOCUS, SURVEY_LIMITS, type SurveyFocus } from "./advisor-survey.ts";
|
|
35
|
+
import { parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
|
|
36
|
+
|
|
37
|
+
export interface StoredSurvey { id: number; task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true }
|
|
38
|
+
export interface StoredSurveyFinding { finding: SurveyFinding; foundBy: string; foundAt: number; decision?: SurveyVetDecision; decisionBy?: string; decisionAt?: number }
|
|
39
|
+
export interface SurveyPreparedCard { id: string; key: string; title: string; detail: string; class: "plan" | "triage"; refs?: TaskRefs; signals?: string[]; reopens?: number; reopenReason?: string }
|
|
40
|
+
export interface SurveyApplyInput { findings: SurveyFinding[]; decisions: SurveyVetDecision[]; by: string; at: number; cards?: SurveyPreparedCard[]; rejections?: ConsideredEntry[]; reconsiderations?: ConsideredEntry[]; withheld?: true }
|
|
41
|
+
export interface SurveyWriteFence { boardRevision: number; taskCreated: number; taskFlowRevision: number; owner: string }
|
|
42
|
+
export interface StoredRejectedFinding { id: number; entry: ConsideredEntry; reconsideredBy: number[] }
|
|
43
|
+
const SURVEY_STORE_LIMIT = 1000, SURVEY_STORE_BYTES = 64 * 1024;
|
|
44
|
+
const surveyStorageFailure = (): never => { throw new Error("survey storage invalid; stop the hub and restore a trusted hub.db backup before retrying"); };
|
|
45
|
+
const surveyInputFailure = (): never => { throw new Error("invalid survey storage input or changed binding"); };
|
|
46
|
+
const surveyInteger = (value: unknown, min = 1): number => typeof value === "number" && Number.isSafeInteger(value) && value >= min ? value : surveyInputFailure();
|
|
47
|
+
const surveyHash = (body: string) => createHash("sha256").update(body).digest("hex");
|
|
48
|
+
function surveyCreateInput(input: unknown): Omit<StoredSurvey, "id"> {
|
|
49
|
+
const row = surveyObject(input, ["task", "taskCreated", "repo", "ref", "focus", "by", "at", "withheld"]);
|
|
50
|
+
if (typeof row.ref !== "string" || !/^[a-f0-9]{40}$/.test(row.ref) || row.withheld !== undefined && row.withheld !== true) return surveyInputFailure();
|
|
51
|
+
return { task: surveyInteger(row.task), taskCreated: surveyInteger(row.taskCreated, 0), repo: surveyText(row.repo, 1024), ref: row.ref,
|
|
52
|
+
...(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 } : {}) };
|
|
53
|
+
}
|
|
54
|
+
function surveyStoredFinding(input: unknown): StoredSurveyFinding {
|
|
55
|
+
const row = surveyObject(input, ["finding", "foundBy", "foundAt", "decision", "decisionBy", "decisionAt"]), finding = parseSurveyFindings([row.finding])[0]!;
|
|
56
|
+
const decision = row.decision === undefined ? undefined : parseSurveyVetDecisions([row.decision])[0]!;
|
|
57
|
+
if (decision && decision.id !== finding.id || !decision && (row.decisionBy !== undefined || row.decisionAt !== undefined)) return surveyInputFailure();
|
|
58
|
+
return { finding, foundBy: surveyText(row.foundBy, 128), foundAt: surveyInteger(row.foundAt, 0),
|
|
59
|
+
...(decision ? { decision, decisionBy: surveyText(row.decisionBy, 128), decisionAt: surveyInteger(row.decisionAt, 0) } : {}) };
|
|
60
|
+
}
|
|
30
61
|
|
|
31
62
|
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
63
|
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 +191,9 @@ const experimentPage = (after: number, limit: number): void => {
|
|
|
160
191
|
|
|
161
192
|
export const CLASSES = ["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"] as const;
|
|
162
193
|
export type TaskClass = (typeof CLASSES)[number];
|
|
194
|
+
/** #1403 A4: one security audit as stored. `units` is the ledger; it changes only through `Board.auditReport`. */
|
|
195
|
+
export interface StoredAudit { id: number; task: number; taskCreated: number; ref: string; since?: string; profile: AuditProfile; scoped: boolean; at: number; by: string; units: AuditUnit[] }
|
|
196
|
+
const EVIDENCE_HISTORY_WINDOW = 1024;
|
|
163
197
|
export type TaskState = "backlog" | "proposed" | "in_progress" | "in_review" | "approved" | "changes_requested" | "cancelled";
|
|
164
198
|
|
|
165
199
|
export const isClosedTaskState = (state: string): boolean => state === "approved" || state === "cancelled";
|
|
@@ -206,7 +240,13 @@ export interface TaskRefs {
|
|
|
206
240
|
export const PLAN_KEYS = ["paths", "symbols", "signatures", "insertion_points"] as const;
|
|
207
241
|
export const DOCUMENT_PLAN_KEYS = ["paths", "sections", "sources", "claims"] as const;
|
|
208
242
|
export const ALL_PLAN_KEYS = [...PLAN_KEYS, "sections", "sources", "claims", "proof", "risks"] as const;
|
|
209
|
-
export
|
|
243
|
+
export interface ColdPlanIntent {
|
|
244
|
+
base?: string;
|
|
245
|
+
out_of_scope?: string[];
|
|
246
|
+
stop_if?: string[];
|
|
247
|
+
steps?: { description: string; verify?: string }[];
|
|
248
|
+
}
|
|
249
|
+
export type TaskPlan = Partial<Record<(typeof ALL_PLAN_KEYS)[number], string[]>> & CostPlan & ColdPlanIntent;
|
|
210
250
|
/** Task outcomes older than this are pruned: demotion (issue #36) reads one week, seven half-lives. */
|
|
211
251
|
export const OUTCOMES_KEPT_MS = 7 * 24 * 3_600_000;
|
|
212
252
|
|
|
@@ -276,6 +316,8 @@ export interface HistoryEntry {
|
|
|
276
316
|
deliverables?: DeliverableRecord[];
|
|
277
317
|
/** #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
318
|
unmetCriteria?: string[];
|
|
319
|
+
/** #1403 A2: the security pass an approving verdict recorded (units covered and not covered, bound to the reviewed head). Enabled lifecycle only. */
|
|
320
|
+
securityPass?: SecurityPassRecord;
|
|
279
321
|
/** Host-authored plan content revision, separate from backlog planningRevision. */
|
|
280
322
|
planRevision?: { revision: number; fingerprint: string };
|
|
281
323
|
planObservation?: { repo: string; pr: number; head: string; revision: number; fingerprint: string };
|
|
@@ -288,14 +330,15 @@ export interface HistoryEntry {
|
|
|
288
330
|
queueReviewHeld?: true;
|
|
289
331
|
/** Opaque artifact identity captured by the host at the queue-held role write. */
|
|
290
332
|
queueReviewBinding?: string;
|
|
291
|
-
|
|
333
|
+
reviewerQuotaWait?: { created: number; binding: string; since: number; deadline: number; resetAt: number };
|
|
334
|
+
reviewerFailure?: { peer: string; head?: string; cause: "start_failed" | "quota" | "no_verdict"; reason?: "review time cap" };
|
|
292
335
|
resolvedReviewComments?: string[];
|
|
293
336
|
planning?: { revision: number; fields: (keyof PlanningFields)[]; previous: PlanningFields; pull?: true; split?: { children: { id: number; revision: number; history: number }[] } };
|
|
294
337
|
}
|
|
295
338
|
/** #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
339
|
export const CLAIM_VERDICTS = ["supported", "unsupported", "unclear"] as const;
|
|
297
340
|
/** `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 }
|
|
341
|
+
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
342
|
/** 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
343
|
export function claimListId(claims: readonly string[] | undefined): string {
|
|
301
344
|
return createHash("sha256").update(planFingerprint({ claims: [...(claims ?? [])] })).digest("hex").slice(0, 16);
|
|
@@ -310,28 +353,45 @@ export function taskClaimIdentity(task: Pick<Task, "id" | "created" | "plan">, s
|
|
|
310
353
|
}
|
|
311
354
|
/** 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
355
|
export function parseClaimVerdict(value: unknown, slots: number): ClaimVerdict {
|
|
313
|
-
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
356
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
|
|
357
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length
|
|
358
|
+
|| Object.values(Object.getOwnPropertyDescriptors(value)).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) throw new Error("claim verdict must be an object");
|
|
314
359
|
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
|
|
360
|
+
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
361
|
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
362
|
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
363
|
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
364
|
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
|
-
|
|
365
|
+
let synthesis: ClaimVerdict["synthesis"];
|
|
366
|
+
if (v.synthesis !== undefined) {
|
|
367
|
+
const item = v.synthesis;
|
|
368
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || types.isProxy(item)
|
|
369
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(item)) || Object.getOwnPropertySymbols(item).length
|
|
370
|
+
|| Object.values(Object.getOwnPropertyDescriptors(item)).some(field => !Object.hasOwn(field, "value") || !field.enumerable)
|
|
371
|
+
|| Object.keys(item).some(key => key !== "manifestSha256" && key !== "disposition")) throw new Error("synthesis disposition requires only manifestSha256 and disposition");
|
|
372
|
+
const row = item as Record<string, unknown>;
|
|
373
|
+
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");
|
|
374
|
+
synthesis = { manifestSha256: row.manifestSha256, disposition: row.disposition };
|
|
375
|
+
}
|
|
376
|
+
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
377
|
}
|
|
322
378
|
/** 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
379
|
function criterionIdList(value: unknown): string[] {
|
|
324
380
|
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
381
|
return [...value] as string[];
|
|
326
382
|
}
|
|
327
|
-
export type ReviewerHistory = Pick<HistoryEntry, "reviewerFamily" | "reviewerReason" | "reviewBlocked" | "queueReviewHeld" | "queueReviewBinding" | "reviewerFailure">;
|
|
383
|
+
export type ReviewerHistory = Pick<HistoryEntry, "reviewerFamily" | "reviewerReason" | "reviewBlocked" | "queueReviewHeld" | "queueReviewBinding" | "reviewerFailure" | "reviewerQuotaWait">;
|
|
328
384
|
function reviewerHistory(extra: ReviewerHistory): ReviewerHistory {
|
|
329
385
|
const id = (value: unknown) => typeof value === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(value);
|
|
330
386
|
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
387
|
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");
|
|
388
|
+
const wait = extra.reviewerQuotaWait;
|
|
389
|
+
if (wait && (!Number.isSafeInteger(wait.created) || wait.created < 0 || !/^[a-f0-9]{64}$/.test(wait.binding)
|
|
390
|
+
|| !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
391
|
const failure = extra.reviewerFailure;
|
|
392
|
+
if (failure?.reason !== undefined && (failure.reason !== "review time cap" || failure.cause !== "no_verdict")) throw new Error("invalid reviewer timeout metadata");
|
|
333
393
|
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 } : {}) } } : {}) };
|
|
394
|
+
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
395
|
}
|
|
336
396
|
function specReportHistory(report: unknown, binding: unknown, event: string): Pick<HistoryEntry, "specReport" | "specRefBinding"> {
|
|
337
397
|
if (!report || typeof report !== "object" || Array.isArray(report) || !["done", "done (checking)"].includes(event)
|
|
@@ -612,6 +672,25 @@ export class Board {
|
|
|
612
672
|
UNIQUE(project_id,task_id,task_created,from_sha256,reference_sha256))`);
|
|
613
673
|
this.db.run("CREATE INDEX IF NOT EXISTS execution_reference_task_scope ON execution_reference_links(project_id,task_id,task_created,id)");
|
|
614
674
|
this.db.run("CREATE INDEX IF NOT EXISTS guidance_variant_task_id ON guidance_variants(project_id,task_id,task_created,id)");
|
|
675
|
+
// Private additive survey/considered state, never copied into task projections or an unconditional format floor.
|
|
676
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS advisor_surveys (
|
|
677
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL,
|
|
678
|
+
withheld INTEGER NOT NULL DEFAULT 0, UNIQUE(task_id,task_created))`);
|
|
679
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS advisor_survey_findings (
|
|
680
|
+
survey INTEGER NOT NULL, finding_id TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(survey,finding_id))`);
|
|
681
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS considered_findings (
|
|
682
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, repo TEXT NOT NULL, finding_id TEXT NOT NULL, pass TEXT NOT NULL, kind TEXT NOT NULL,
|
|
683
|
+
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)`);
|
|
684
|
+
this.db.run("CREATE INDEX IF NOT EXISTS considered_finding_identity ON considered_findings(repo,finding_id,pass,id)");
|
|
685
|
+
// #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.
|
|
686
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS security_audits (
|
|
687
|
+
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,
|
|
688
|
+
scoped INTEGER NOT NULL, at INTEGER NOT NULL, by_peer TEXT NOT NULL, units TEXT NOT NULL, UNIQUE(task_id,task_created))`);
|
|
689
|
+
this.db.run(`CREATE TABLE IF NOT EXISTS security_audit_findings (
|
|
690
|
+
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,
|
|
691
|
+
verified_by TEXT, rejected_by TEXT, settled_by TEXT, settled_as TEXT, PRIMARY KEY(audit,seq), UNIQUE(audit,finding_id))`);
|
|
692
|
+
// #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.
|
|
693
|
+
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
694
|
this.db.run(`CREATE TABLE IF NOT EXISTS review_comments (
|
|
616
695
|
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
696
|
PRIMARY KEY(task_id,task_created,id))`);
|
|
@@ -1062,9 +1141,61 @@ export class Board {
|
|
|
1062
1141
|
} catch { throw new Error("evidence storage invalid; stop the hub and restore a trusted hub.db backup; then restart and retry"); }
|
|
1063
1142
|
}
|
|
1064
1143
|
|
|
1065
|
-
|
|
1144
|
+
/** Bounded current inventory. A task-wide overflow cannot establish complete claim coverage. */
|
|
1145
|
+
latestEvidenceLinks(project: string, taskId: number, claimId: string, claimRevision: string, limit: number): { links: EvidenceLinkV1[]; complete: boolean } {
|
|
1146
|
+
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)
|
|
1147
|
+
|| !/^[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");
|
|
1148
|
+
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 ?")
|
|
1149
|
+
.all(project, taskId, limit + 1) as { id: string; revision: number }[];
|
|
1150
|
+
const links = rows.slice(0, limit).flatMap(row => {
|
|
1151
|
+
const link = this.evidenceLink(project, row.id, row.revision);
|
|
1152
|
+
if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh the task review before retrying");
|
|
1153
|
+
return link.claimId === claimId && link.claimRevision === claimRevision ? [link] : [];
|
|
1154
|
+
});
|
|
1155
|
+
// ponytail: the task-wide cap can make a smaller claim inventory unknown; a claim-indexed validated read is the upgrade path.
|
|
1156
|
+
return { links, complete: rows.length <= limit };
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
/** Verified immutable relation history, never a second judgment store. */
|
|
1160
|
+
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 } {
|
|
1161
|
+
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)
|
|
1162
|
+
|| !/^[a-f0-9]{16}$/.test(claimRevision) || links.length > 128 || new Set(links.map(link => link.id)).size !== links.length
|
|
1163
|
+
|| links.some(link => link.taskId !== taskId || link.claimId !== claimId || link.claimRevision !== claimRevision)) throw new Error("evidence history identity invalid; refresh the complete inventory");
|
|
1164
|
+
const unknown = { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false };
|
|
1165
|
+
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 ?")
|
|
1166
|
+
.all(project, taskId, 129) as { id: string; revision: number }[];
|
|
1167
|
+
if (taskRows.length > 128) return unknown;
|
|
1168
|
+
const latest = taskRows.map(row => {
|
|
1169
|
+
const link = this.evidenceLink(project, row.id, row.revision);
|
|
1170
|
+
if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh its history");
|
|
1171
|
+
return link;
|
|
1172
|
+
}).filter(link => link.claimId === claimId);
|
|
1173
|
+
const current = latest.filter(link => link.claimRevision === claimRevision);
|
|
1174
|
+
if (current.length !== links.length || current.some(link => !links.some(given => evidenceLinkCanonical(given) === evidenceLinkCanonical(link)))) throw new Error("evidence inventory changed; refresh its history");
|
|
1175
|
+
const revisions = latest.reduce((count, link) => count + link.revision, 0);
|
|
1176
|
+
// ponytail: above 1024 owned revisions, history is unknown. Upgrade to paged verified history commitments before widening this window.
|
|
1177
|
+
if (!Number.isSafeInteger(revisions) || revisions > EVIDENCE_HISTORY_WINDOW) return unknown;
|
|
1178
|
+
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 ?`)
|
|
1179
|
+
.all(project, taskId, ...latest.map(link => link.id), EVIDENCE_HISTORY_WINDOW + 1) as { id: string; revision: number }[] : [];
|
|
1180
|
+
if (rows.length > EVIDENCE_HISTORY_WINDOW) return unknown;
|
|
1181
|
+
const seen = new Map<string, number>(), contradicted = new Set<string>(), sources = new Set<string>(), canonical: string[] = [];
|
|
1182
|
+
for (const row of rows) {
|
|
1183
|
+
const last = latest.find(link => link.id === row.id), prior = this.evidenceLink(project, row.id, row.revision);
|
|
1184
|
+
if (!last || !prior || prior.taskId !== taskId || prior.claimId !== claimId || row.revision !== (seen.get(row.id) ?? 0) + 1 || row.revision > last.revision)
|
|
1185
|
+
throw new Error("evidence history is incomplete or changed; restore trusted evidence storage and retry");
|
|
1186
|
+
seen.set(row.id, row.revision); sources.add(prior.sourceId); canonical.push(evidenceLinkCanonical(prior));
|
|
1187
|
+
if (prior.relation === "contradicts") contradicted.add(row.id);
|
|
1188
|
+
if (row.revision === last.revision && evidenceLinkCanonical(prior) !== evidenceLinkCanonical(last)) throw new Error("evidence inventory changed; refresh its history before retrying");
|
|
1189
|
+
}
|
|
1190
|
+
if (latest.some(link => seen.get(link.id) !== link.revision)) throw new Error("evidence history is incomplete; restore trusted evidence storage and retry");
|
|
1191
|
+
const sha256 = createHash("sha256").update(JSON.stringify({ project, taskId, claimId, rows: canonical })).digest("hex");
|
|
1192
|
+
return { ids: [...contradicted].sort(), sources: [...sources].sort(), members: latest.map(link => link.id), binding: { revision: revisions, sha256 }, complete: true };
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
recordEvidenceLink(project: string, input: EvidenceLinkV1, fence: { taskFlowRevision: number; taskCreated: number; owner: PeerId; personWithdrawal?: true }): EvidenceLinkV1 {
|
|
1066
1196
|
const link = parseEvidenceLink(input), canonical = evidenceLinkCanonical(link);
|
|
1067
|
-
|
|
1197
|
+
const personWithdrawal = fence.personWithdrawal === true && link.recordedBy === USER && link.status === "withdrawn";
|
|
1198
|
+
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
1199
|
return this.atomic(() => {
|
|
1069
1200
|
const task = this.get(link.taskId);
|
|
1070
1201
|
if (!task || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision || task.owner !== fence.owner || task.state !== "in_progress" || task.profile !== "research"
|
|
@@ -1189,6 +1320,314 @@ export class Board {
|
|
|
1189
1320
|
return { record: next, already: false };
|
|
1190
1321
|
});
|
|
1191
1322
|
}
|
|
1323
|
+
/** Private survey metadata, linked to the existing task incarnation. */
|
|
1324
|
+
surveyCreate(input: { task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true }): number {
|
|
1325
|
+
const row = surveyCreateInput(input);
|
|
1326
|
+
const write = () => {
|
|
1327
|
+
const task = this.get(row.task);
|
|
1328
|
+
if (!task || task.created !== row.taskCreated || task.class !== "plan" || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure();
|
|
1329
|
+
const known = this.surveyOfTask(row.task, row.taskCreated);
|
|
1330
|
+
if (known) {
|
|
1331
|
+
const { id: _id, withheld: _private, ...prior } = known, { withheld: _nextPrivate, ...next } = row;
|
|
1332
|
+
if (JSON.stringify(prior) !== JSON.stringify(next)) return surveyInputFailure();
|
|
1333
|
+
if (row.withheld && !known.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(known.id));
|
|
1334
|
+
return known.id;
|
|
1335
|
+
}
|
|
1336
|
+
const body = JSON.stringify(row);
|
|
1337
|
+
const saved = this.taskWrite(() => this.db.query("INSERT INTO advisor_surveys(task_id,task_created,body,body_sha256,withheld) VALUES(?,?,?,?,?)")
|
|
1338
|
+
.run(row.task, row.taskCreated, body, surveyHash(body), row.withheld ? 1 : 0));
|
|
1339
|
+
return Number(saved.lastInsertRowid);
|
|
1340
|
+
};
|
|
1341
|
+
// The host-only proposal hook already owns the transaction and deferred notifications.
|
|
1342
|
+
return this.pendingChanges ? write() : this.atomic(write);
|
|
1343
|
+
}
|
|
1344
|
+
surveyOfTask(taskId: number, created: number): StoredSurvey | undefined {
|
|
1345
|
+
surveyInteger(taskId); surveyInteger(created, 0);
|
|
1346
|
+
const row = this.db.query("SELECT id FROM advisor_surveys WHERE task_id=? AND task_created=?").get(taskId, created) as { id: number } | null;
|
|
1347
|
+
return row ? this.survey(row.id) : undefined;
|
|
1348
|
+
}
|
|
1349
|
+
surveyOpen(repo: string): { id: number; task: number; taskCreated: number } | undefined {
|
|
1350
|
+
surveyText(repo, 1024);
|
|
1351
|
+
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 }[];
|
|
1352
|
+
if (rows.length > SURVEY_STORE_LIMIT) throw new Error("open survey inventory unavailable; reduce open surveys and retry");
|
|
1353
|
+
const found = rows.map(row => this.survey(row.id)!).filter(row => row.repo === repo);
|
|
1354
|
+
if (found.length > 1) throw new Error("multiple surveys are open; finish or cancel them before starting another");
|
|
1355
|
+
const row = found[0]; return row ? { id: row.id, task: row.task, taskCreated: row.taskCreated } : undefined;
|
|
1356
|
+
}
|
|
1357
|
+
survey(id: number): StoredSurvey | undefined {
|
|
1358
|
+
surveyInteger(id);
|
|
1359
|
+
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;
|
|
1360
|
+
if (!row) return;
|
|
1361
|
+
try {
|
|
1362
|
+
if (!row.body || surveyHash(row.body) !== row.body_sha256 || row.withheld !== 0 && row.withheld !== 1) return surveyStorageFailure();
|
|
1363
|
+
const value = surveyCreateInput(JSON.parse(row.body));
|
|
1364
|
+
if (value.task !== row.task_id || value.taskCreated !== row.task_created) return surveyStorageFailure();
|
|
1365
|
+
return { id: row.id, ...value, ...(row.withheld ? { withheld: true } : {}) };
|
|
1366
|
+
} catch { return surveyStorageFailure(); }
|
|
1367
|
+
}
|
|
1368
|
+
surveyFindings(id: number): StoredSurveyFinding[] {
|
|
1369
|
+
surveyInteger(id);
|
|
1370
|
+
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 }[];
|
|
1371
|
+
try {
|
|
1372
|
+
if (rows.length > 64) return surveyStorageFailure();
|
|
1373
|
+
return rows.map(row => {
|
|
1374
|
+
if (!row.body || surveyHash(row.body) !== row.body_sha256) return surveyStorageFailure();
|
|
1375
|
+
const value = surveyStoredFinding(JSON.parse(row.body));
|
|
1376
|
+
if (value.finding.id !== row.finding_id) return surveyStorageFailure();
|
|
1377
|
+
return value;
|
|
1378
|
+
});
|
|
1379
|
+
} catch { return surveyStorageFailure(); }
|
|
1380
|
+
}
|
|
1381
|
+
private consideredWrite(input: unknown, kind: "rejected" | "reconsidered", priorIDs: readonly number[] = []): number {
|
|
1382
|
+
const entry = parseConsideredEntry(input), task = this.get(entry.source.task);
|
|
1383
|
+
if (!task || task.created !== entry.source.created) return surveyInputFailure();
|
|
1384
|
+
const prior = surveyArray(priorIDs, SURVEY_STORE_LIMIT).map(value => surveyInteger(value)).sort((a, b) => a - b);
|
|
1385
|
+
if (new Set(prior).size !== prior.length || kind === "rejected" && prior.length || kind === "reconsidered" && !prior.length) return surveyInputFailure();
|
|
1386
|
+
for (const id of prior) {
|
|
1387
|
+
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;
|
|
1388
|
+
if (!found || found.kind !== "rejected" || found.repo !== entry.repo || found.finding_id !== entry.id || found.pass !== entry.pass) return surveyInputFailure();
|
|
1389
|
+
}
|
|
1390
|
+
const { withheld: _private, ...identity } = entry, body = JSON.stringify(entry), priorBody = JSON.stringify(prior);
|
|
1391
|
+
const replay = surveyHash(JSON.stringify({ kind, entry: identity, prior }));
|
|
1392
|
+
const known = this.db.query("SELECT id FROM considered_findings WHERE replay_key=?").get(replay) as { id: number } | null;
|
|
1393
|
+
if (known) {
|
|
1394
|
+
if (entry.withheld) this.taskWrite(() => this.db.query("UPDATE considered_findings SET withheld=1 WHERE id=? AND withheld=0").run(known.id));
|
|
1395
|
+
return known.id;
|
|
1396
|
+
}
|
|
1397
|
+
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(?,?,?,?,?,?,?,?,?)")
|
|
1398
|
+
.run(entry.repo, entry.id, entry.pass, kind, body, surveyHash(body), replay, priorBody, entry.withheld || entry.pass === "security" ? 1 : 0));
|
|
1399
|
+
return Number(saved.lastInsertRowid);
|
|
1400
|
+
}
|
|
1401
|
+
recordRejectedFinding(entry: ConsideredEntry): number { return this.atomic(() => this.consideredWrite(entry, "rejected")); }
|
|
1402
|
+
recordReconsideredFinding(entry: ConsideredEntry, priorIDs: readonly number[]): number { return this.atomic(() => this.consideredWrite(entry, "reconsidered", priorIDs)); }
|
|
1403
|
+
/** Closed proposals are history, not dedupe. Caller screens any new reference before the atomic apply. */
|
|
1404
|
+
surveyCardHistory(key: string): { active?: number; closed?: number } {
|
|
1405
|
+
surveyText(key, 512);
|
|
1406
|
+
// ponytail: at most 1000 matching host-created cards; overflow is unknown, not permission to duplicate. Page this proof if a key outgrows the window.
|
|
1407
|
+
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 ?")
|
|
1408
|
+
.all(key, HUB, SURVEY_STORE_LIMIT + 1) as { id: number; state: string }[];
|
|
1409
|
+
if (rows.length > SURVEY_STORE_LIMIT) return surveyStorageFailure();
|
|
1410
|
+
const active = rows.filter(row => !isClosedTaskState(row.state));
|
|
1411
|
+
if (active.length > 1) return surveyStorageFailure();
|
|
1412
|
+
const closed = rows.find(row => isClosedTaskState(row.state));
|
|
1413
|
+
return { ...(active[0] ? { active: surveyInteger(active[0].id) } : {}), ...(closed ? { closed: surveyInteger(closed.id) } : {}) };
|
|
1414
|
+
}
|
|
1415
|
+
rejectedFindingsFor(repo: string, pass: string, id: string, limit = 100): { rows: StoredRejectedFinding[]; complete: boolean } {
|
|
1416
|
+
return this.rejectedFindings(repo, limit, { pass: surveyPass(pass), id: surveyFindingId(id) });
|
|
1417
|
+
}
|
|
1418
|
+
rejectedFindings(repo: string, limit = 100, selector?: { pass: string; id: string }): { rows: StoredRejectedFinding[]; complete: boolean } {
|
|
1419
|
+
surveyText(repo, 1024); surveyInteger(limit); if (limit > SURVEY_STORE_LIMIT) return surveyInputFailure();
|
|
1420
|
+
const selected = selector === undefined ? undefined : surveyObject(selector, ["pass", "id"]);
|
|
1421
|
+
const args: (string | number)[] = [repo];
|
|
1422
|
+
if (selected) args.push(surveyFindingId(selected.id), surveyPass(selected.pass)); args.push(limit + 1);
|
|
1423
|
+
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,
|
|
1424
|
+
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,
|
|
1425
|
+
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,
|
|
1426
|
+
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 }[];
|
|
1427
|
+
if (rows.length > limit) return { rows: [], complete: false };
|
|
1428
|
+
try {
|
|
1429
|
+
const parsed = rows.map(row => {
|
|
1430
|
+
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();
|
|
1431
|
+
const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value));
|
|
1432
|
+
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();
|
|
1433
|
+
const { withheld: _private, ...identity } = entry;
|
|
1434
|
+
if (surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key || prior.some(id => id >= row.id)) return surveyStorageFailure();
|
|
1435
|
+
return { id: row.id, entry: { ...entry, ...(row.withheld ? { withheld: true as const } : {}) }, kind: row.kind, prior };
|
|
1436
|
+
});
|
|
1437
|
+
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();
|
|
1438
|
+
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 };
|
|
1439
|
+
} catch { return surveyStorageFailure(); }
|
|
1440
|
+
}
|
|
1441
|
+
surveyApply(id: number, input: SurveyApplyInput, fenceInput: SurveyWriteFence): { createdIDs: number[]; dedupedIDs: number[]; already: boolean } {
|
|
1442
|
+
surveyInteger(id);
|
|
1443
|
+
const given = surveyObject(input, ["findings", "decisions", "by", "at", "cards", "rejections", "reconsiderations", "withheld"]);
|
|
1444
|
+
const findings = parseSurveyFindings(given.findings), decisions = parseSurveyVetDecisions(given.decisions), by = surveyText(given.by, 128), at = surveyInteger(given.at, 0);
|
|
1445
|
+
if (given.withheld !== undefined && given.withheld !== true) return surveyInputFailure();
|
|
1446
|
+
const cards = surveyArray(given.cards ?? [], 64).map(value => {
|
|
1447
|
+
const row = surveyObject(value, ["id", "key", "title", "detail", "class", "refs", "signals", "reopens", "reopenReason"]), key = surveyText(row.key, 512), title = surveyText(row.title, 512);
|
|
1448
|
+
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();
|
|
1449
|
+
const rawRefs = row.refs === undefined ? undefined : surveyObject(row.refs, ["repo", "branch", "commit", "paths"]), refs: TaskRefs | undefined = rawRefs ? {} : undefined;
|
|
1450
|
+
if (rawRefs && refs) {
|
|
1451
|
+
for (const key of ["repo", "branch", "commit"] as const) if (rawRefs[key] !== undefined) refs[key] = surveyText(rawRefs[key], 1024);
|
|
1452
|
+
if (rawRefs.paths !== undefined) refs.paths = surveyArray(rawRefs.paths, 64).map(surveyPath);
|
|
1453
|
+
}
|
|
1454
|
+
const signals = row.signals === undefined ? undefined : surveyArray(row.signals, 64).map(value => surveyText(value, 128));
|
|
1455
|
+
if ((row.reopens === undefined) !== (row.reopenReason === undefined)) return surveyInputFailure();
|
|
1456
|
+
const reopening = row.reopens === undefined ? {} : { reopens: surveyInteger(row.reopens), reopenReason: surveyText(row.reopenReason) };
|
|
1457
|
+
return { id: surveyText(row.id, 96), key, title, detail: row.detail, class: row.class, ...(refs ? { refs } : {}), ...(signals ? { signals } : {}), ...reopening };
|
|
1458
|
+
});
|
|
1459
|
+
if (new Set(cards.map(card => card.id)).size !== cards.length || new Set(cards.map(card => card.key)).size !== cards.length) return surveyInputFailure();
|
|
1460
|
+
const rejections = surveyArray(given.rejections ?? [], 64).map(parseConsideredEntry), reconsiderations = surveyArray(given.reconsiderations ?? [], 64).map(parseConsideredEntry);
|
|
1461
|
+
const fence = surveyObject(fenceInput, ["boardRevision", "taskCreated", "taskFlowRevision", "owner"]);
|
|
1462
|
+
surveyInteger(fence.boardRevision, 0); surveyInteger(fence.taskCreated, 0); surveyInteger(fence.taskFlowRevision, 0); surveyText(fence.owner, 128);
|
|
1463
|
+
return this.atomic(() => {
|
|
1464
|
+
const revision = this.statusRevision(), survey = this.survey(id), task = survey && this.get(survey.task);
|
|
1465
|
+
if (!survey || !task || revision !== fence.boardRevision || task.created !== survey.taskCreated || task.created !== fence.taskCreated
|
|
1466
|
+
|| task.history.length !== fence.taskFlowRevision || task.class !== "plan" || task.state !== "in_progress" || task.owner !== fence.owner
|
|
1467
|
+
|| by !== task.owner && by !== USER || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure();
|
|
1468
|
+
const existing = this.surveyFindings(id), merged = new Map(existing.map(row => [row.finding.id, { ...row }]));
|
|
1469
|
+
for (const finding of findings) {
|
|
1470
|
+
const prior = merged.get(finding.id);
|
|
1471
|
+
if (prior && JSON.stringify(prior.finding) !== JSON.stringify(finding)) return surveyInputFailure();
|
|
1472
|
+
if (!prior) merged.set(finding.id, { finding, foundBy: by, foundAt: at });
|
|
1473
|
+
}
|
|
1474
|
+
if (merged.size > 64) return surveyInputFailure();
|
|
1475
|
+
parseSurveyFindings([...merged.values()].map(row => row.finding));
|
|
1476
|
+
const prepared = [...rejections, ...reconsiderations];
|
|
1477
|
+
for (const entry of prepared) {
|
|
1478
|
+
const finding = merged.get(entry.id)?.finding;
|
|
1479
|
+
if (!finding || entry.repo !== survey.repo || entry.pass !== finding.pass || entry.ref !== survey.ref || entry.source.kind !== "survey"
|
|
1480
|
+
|| entry.source.task !== task.id || entry.source.created !== task.created || JSON.stringify(entry.paths) !== JSON.stringify(finding.paths)) return surveyInputFailure();
|
|
1481
|
+
}
|
|
1482
|
+
for (const decision of decisions) {
|
|
1483
|
+
const row = merged.get(decision.id); if (!row) return surveyInputFailure();
|
|
1484
|
+
const prior = row.decision;
|
|
1485
|
+
if (prior && JSON.stringify(prior) === JSON.stringify(decision)) continue;
|
|
1486
|
+
if (prior && !(prior.verdict === "rejected" && decision.verdict === "vetted" && decision.reason)
|
|
1487
|
+
&& !(prior.verdict === "vetted" && decision.verdict === "vetted" && decision.reason && reconsiderations.some(entry => entry.id === decision.id && entry.reason === decision.reason))) return surveyInputFailure();
|
|
1488
|
+
const ledger = decision.verdict === "rejected" ? rejections : prior?.verdict === "rejected" ? reconsiderations : [];
|
|
1489
|
+
if ((decision.verdict === "rejected" || prior?.verdict === "rejected") && !ledger.some(entry => entry.id === decision.id && entry.reason === decision.reason)) return surveyInputFailure();
|
|
1490
|
+
row.decision = decision;
|
|
1491
|
+
row.decisionBy = by; row.decisionAt = at;
|
|
1492
|
+
}
|
|
1493
|
+
parseSurveyVetDecisions([...merged.values()].flatMap(row => row.decision ? [row.decision] : []));
|
|
1494
|
+
for (const entry of rejections) if (!decisions.some(row => row.id === entry.id && row.verdict === "rejected" && row.reason === entry.reason)) return surveyInputFailure();
|
|
1495
|
+
for (const entry of reconsiderations) if (!decisions.some(row => row.id === entry.id && row.verdict === "vetted" && row.reason === entry.reason)) return surveyInputFailure();
|
|
1496
|
+
for (const entry of rejections) this.consideredWrite(entry, "rejected");
|
|
1497
|
+
for (const entry of reconsiderations) {
|
|
1498
|
+
const ledger = this.rejectedFindingsFor(survey.repo, entry.pass, entry.id, SURVEY_STORE_LIMIT); if (!ledger.complete) return surveyInputFailure();
|
|
1499
|
+
const prior = ledger.rows.filter(row => row.entry.id === entry.id && row.entry.pass === entry.pass).map(row => row.id);
|
|
1500
|
+
this.consideredWrite(entry, "reconsidered", prior);
|
|
1501
|
+
}
|
|
1502
|
+
const createdIDs: number[] = [], dedupedIDs: number[] = [];
|
|
1503
|
+
for (const card of cards) {
|
|
1504
|
+
const row = merged.get(card.id);
|
|
1505
|
+
if (!row || row.decision?.verdict !== "vetted" || card.class !== (row.finding.confidence === "low" ? "triage" : "plan")) return surveyInputFailure();
|
|
1506
|
+
if (row.finding.pass === "security" && card.refs && Object.keys(card.refs).length) return surveyInputFailure();
|
|
1507
|
+
const history = this.surveyCardHistory(card.key);
|
|
1508
|
+
if (history.active) dedupedIDs.push(history.active);
|
|
1509
|
+
else {
|
|
1510
|
+
if (history.closed !== card.reopens || card.reopens !== undefined && !card.detail.includes(`Reopened from hub task ${card.reopens}: ${card.reopenReason}`)) return surveyInputFailure();
|
|
1511
|
+
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);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
for (const row of merged.values()) {
|
|
1515
|
+
const prior = existing.find(old => old.finding.id === row.finding.id), body = JSON.stringify(row);
|
|
1516
|
+
if (Buffer.byteLength(body) > SURVEY_STORE_BYTES) return surveyInputFailure();
|
|
1517
|
+
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)));
|
|
1518
|
+
}
|
|
1519
|
+
if (given.withheld && !survey.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(id));
|
|
1520
|
+
return { createdIDs, dedupedIDs, already: this.statusRevision() === revision };
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
hasSurveyState(): boolean {
|
|
1525
|
+
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;
|
|
1526
|
+
}
|
|
1527
|
+
/** Stream bounded validated private rows into recovery proof; output never includes finding or ledger text. */
|
|
1528
|
+
surveyIntegrity(): { surveys: number; findings: number; considered: number; digest: string } {
|
|
1529
|
+
try { return this.db.transaction(() => {
|
|
1530
|
+
const digest = createHash("sha256"); let surveys = 0, findings = 0, considered = 0;
|
|
1531
|
+
for (const key of this.db.query("SELECT id FROM advisor_surveys ORDER BY id").iterate() as Iterable<{ id: number }>) {
|
|
1532
|
+
const row = this.survey(key.id); if (!row) return surveyStorageFailure();
|
|
1533
|
+
const task = this.get(row.task); if (!task || task.created !== row.taskCreated) return surveyStorageFailure();
|
|
1534
|
+
digest.update(JSON.stringify({ survey: row })); surveys++;
|
|
1535
|
+
const candidates = this.surveyFindings(row.id);
|
|
1536
|
+
parseSurveyFindings(candidates.map(candidate => candidate.finding));
|
|
1537
|
+
parseSurveyVetDecisions(candidates.flatMap(candidate => candidate.decision ? [candidate.decision] : []));
|
|
1538
|
+
for (const candidate of candidates) { digest.update(JSON.stringify({ survey: row.id, candidate })); findings++; }
|
|
1539
|
+
}
|
|
1540
|
+
const count = this.db.query("SELECT COUNT(*) AS count FROM advisor_survey_findings").get() as { count: number };
|
|
1541
|
+
if (count.count !== findings) return surveyStorageFailure();
|
|
1542
|
+
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,
|
|
1543
|
+
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,
|
|
1544
|
+
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,
|
|
1545
|
+
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`;
|
|
1546
|
+
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 }>) {
|
|
1547
|
+
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();
|
|
1548
|
+
const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value));
|
|
1549
|
+
const { withheld: _private, ...identity } = entry, task = this.get(entry.source.task);
|
|
1550
|
+
if (!task || task.created !== entry.source.created || entry.repo !== row.repo || entry.id !== row.finding_id || entry.pass !== row.pass
|
|
1551
|
+
|| new Set(prior).size !== prior.length || prior.some(id => id >= row.id) || row.kind === "rejected" && prior.length || row.kind === "reconsidered" && !prior.length
|
|
1552
|
+
|| surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key) return surveyStorageFailure();
|
|
1553
|
+
for (const id of prior) {
|
|
1554
|
+
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);
|
|
1555
|
+
if (!parent) return surveyStorageFailure();
|
|
1556
|
+
}
|
|
1557
|
+
digest.update(JSON.stringify({ id: row.id, kind: row.kind, entry, prior, withheld: row.withheld })); considered++;
|
|
1558
|
+
}
|
|
1559
|
+
return { surveys, findings, considered, digest: digest.digest("hex") };
|
|
1560
|
+
})(); } catch { return surveyStorageFailure(); }
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/** #1403 A4: a new audit with its seeded ledger, in one transaction. Only `Tasks.auditStart` calls this. */
|
|
1564
|
+
auditCreate(row: { task: number; taskCreated: number; ref: string; since?: string; profile: string; scoped: boolean; by: string; at: number; units: readonly AuditUnit[] }): number {
|
|
1565
|
+
return this.atomic(() => {
|
|
1566
|
+
const result = this.db.query("INSERT INTO security_audits(task_id,task_created,ref,since,profile,scoped,at,by_peer,units) VALUES(?,?,?,?,?,?,?,?,?)")
|
|
1567
|
+
.run(row.task, row.taskCreated, row.ref, row.since ?? null, row.profile, row.scoped ? 1 : 0, row.at, row.by, JSON.stringify(row.units));
|
|
1568
|
+
return Number(result.lastInsertRowid);
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
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 {
|
|
1572
|
+
if (!row) return undefined;
|
|
1573
|
+
const units = JSON.parse(row.units) as AuditUnit[];
|
|
1574
|
+
if (!Array.isArray(units)) throw new Error("security audit storage is invalid");
|
|
1575
|
+
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 };
|
|
1576
|
+
}
|
|
1577
|
+
audit(id: number): StoredAudit | undefined {
|
|
1578
|
+
return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE id=?").get(id) as never);
|
|
1579
|
+
}
|
|
1580
|
+
auditOfTask(task: number, taskCreated: number): StoredAudit | undefined {
|
|
1581
|
+
return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE task_id=? AND task_created=?").get(task, taskCreated) as never);
|
|
1582
|
+
}
|
|
1583
|
+
/** 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). */
|
|
1584
|
+
audits(limit = 32, recorded = false): StoredAudit[] {
|
|
1585
|
+
const rows = this.db.query("SELECT * FROM security_audits ORDER BY id DESC LIMIT ?").all(limit) as never[];
|
|
1586
|
+
const all = rows.map(row => this.auditRow(row)!);
|
|
1587
|
+
return recorded ? all.filter(row => row.units.some(unit => unit.reportedBy)) : all;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* 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
|
|
1591
|
+
* 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
|
|
1592
|
+
* needs the finding verified, not rejected and not yet settled.
|
|
1593
|
+
*/
|
|
1594
|
+
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 {
|
|
1595
|
+
const skipped: string[] = [];
|
|
1596
|
+
try {
|
|
1597
|
+
this.atomic(() => {
|
|
1598
|
+
if (change.units) this.db.query("UPDATE security_audits SET units=? WHERE id=?").run(JSON.stringify(change.units), id);
|
|
1599
|
+
let seq = (this.db.query("SELECT COALESCE(MAX(seq),0) AS seq FROM security_audit_findings WHERE audit=?").get(id) as { seq: number }).seq;
|
|
1600
|
+
for (const item of change.findings) {
|
|
1601
|
+
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;
|
|
1602
|
+
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; }
|
|
1603
|
+
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;
|
|
1604
|
+
if (changed !== 1) skipped.push(item.finding.id);
|
|
1605
|
+
}
|
|
1606
|
+
for (const decision of change.decisions) {
|
|
1607
|
+
const column = decision.verdict === "verified" ? "verified_by" : "rejected_by";
|
|
1608
|
+
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;
|
|
1609
|
+
if (done !== 1) throw new Error("audit decision lost");
|
|
1610
|
+
}
|
|
1611
|
+
for (const settlement of change.settlements ?? []) {
|
|
1612
|
+
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;
|
|
1613
|
+
if (done !== 1) throw new Error("audit decision lost");
|
|
1614
|
+
}
|
|
1615
|
+
});
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
if (error instanceof Error && error.message === "audit decision lost") return undefined;
|
|
1618
|
+
throw error;
|
|
1619
|
+
}
|
|
1620
|
+
return skipped;
|
|
1621
|
+
}
|
|
1622
|
+
auditFindings(id: number): AuditFinding[] {
|
|
1623
|
+
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 }[];
|
|
1624
|
+
// A settled finding reads with its settled disposition, so every reader that already shows a `fixed` or `false_positive` finding treats it as one.
|
|
1625
|
+
return rows.map(row => {
|
|
1626
|
+
const settled = row.settled_by && (row.settled_as === "fixed" || row.settled_as === "false_positive") ? row.settled_as : undefined;
|
|
1627
|
+
const body = JSON.parse(row.body) as ReviewFinding;
|
|
1628
|
+
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 } : {}) };
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1192
1631
|
hasGuidanceVariants(): boolean {
|
|
1193
1632
|
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
1633
|
}
|
|
@@ -1297,6 +1736,22 @@ export class Board {
|
|
|
1297
1736
|
return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_evidence_links) AS present").get() as { present: number }).present === 1;
|
|
1298
1737
|
}
|
|
1299
1738
|
|
|
1739
|
+
/** Older evidence readers reject the new optional stored withdrawal field. Keep that downgrade fence conditional. */
|
|
1740
|
+
hasWithdrawnEvidenceState(): boolean {
|
|
1741
|
+
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;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/** Same #901 history record, with the host's completed observation fenced against intervening database writes. No source I/O in this transaction. */
|
|
1745
|
+
recordSynthesisClaimVerdict(id: number, claim: ClaimVerdict, fence: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task {
|
|
1746
|
+
return this.atomic(() => {
|
|
1747
|
+
const task = this.get(id);
|
|
1748
|
+
if (!task || this.statusRevision() !== fence.boardRevision || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision
|
|
1749
|
+
|| !claim.synthesis || claim.list !== fence.claimRevision || taskClaimIdentity(task, claim.slot).claimRevision !== fence.claimRevision)
|
|
1750
|
+
throw new Error("synthesis context changed before the claim verdict write; refresh the manifest and explicitly record the disposition again");
|
|
1751
|
+
return this.update(id, USER, "claim verdict", {}, undefined, { claim }, fence.taskFlowRevision);
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1300
1755
|
researchEvidenceIntegrity(): { links: number; revisions: number; digest: string } {
|
|
1301
1756
|
return this.db.transaction(() => {
|
|
1302
1757
|
const digest = createHash("sha256").update("agent-hub.research-evidence/v1\n");
|
|
@@ -1950,7 +2405,12 @@ export class Board {
|
|
|
1950
2405
|
})();
|
|
1951
2406
|
}
|
|
1952
2407
|
|
|
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 {
|
|
2408
|
+
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 {
|
|
2409
|
+
// Host-only synchronous DB bookkeeping. Never sourced from task input or called with I/O/screens.
|
|
2410
|
+
if (createdHook !== undefined) {
|
|
2411
|
+
if (typeof createdHook !== "function") throw new Error("invalid host proposal hook");
|
|
2412
|
+
return this.atomic(() => { const task = this.propose(by, t); createdHook(task); return task; });
|
|
2413
|
+
}
|
|
1954
2414
|
const now = Date.now(), planner = plannerValue(t.planner);
|
|
1955
2415
|
const chosen = Object.hasOwn(t, "planner") || t.plannerReason !== undefined ? plannerMetadata(planner, t.plannerReason) : {};
|
|
1956
2416
|
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 +2663,7 @@ export class Board {
|
|
|
2203
2663
|
|
|
2204
2664
|
/** The only way a task changes. Validates the move, records who did what, returns the new row. */
|
|
2205
2665
|
/** 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 {
|
|
2666
|
+
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" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
|
|
2207
2667
|
if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
|
|
2208
2668
|
const task = this.get(id);
|
|
2209
2669
|
if (!task) throw new Error(`no task #${id}`);
|
|
@@ -2269,13 +2729,18 @@ export class Board {
|
|
|
2269
2729
|
if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("finding metadata requires a saved review verdict");
|
|
2270
2730
|
const head = extra.reviewFindings.head;
|
|
2271
2731
|
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 }) };
|
|
2732
|
+
reviewFindings = { ...(head ? { head } : {}), items: parseReviewFindings(extra.reviewFindings.items, { person: by === "user", maxNits: 64, contract: "stored" }) };
|
|
2273
2733
|
}
|
|
2274
2734
|
let deliverables: DeliverableRecord[] | undefined;
|
|
2275
2735
|
if (extra.deliverables !== undefined) {
|
|
2276
2736
|
if (!["done", "done (checking)", "lifecycle", "approved"].includes(event)) throw new Error("deliverable records require a done, a lifecycle record or an approval");
|
|
2277
2737
|
deliverables = parseDeliverableRecords(extra.deliverables);
|
|
2278
2738
|
}
|
|
2739
|
+
let securityPass: SecurityPassRecord | undefined;
|
|
2740
|
+
if (extra.securityPass !== undefined) {
|
|
2741
|
+
if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("a security pass requires a saved review verdict");
|
|
2742
|
+
securityPass = storedSecurityPass(extra.securityPass);
|
|
2743
|
+
}
|
|
2279
2744
|
let unmetCriteria: string[] | undefined;
|
|
2280
2745
|
if (extra.unmetCriteria !== undefined) {
|
|
2281
2746
|
if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("unmet criteria require a saved review verdict");
|
|
@@ -2296,7 +2761,7 @@ export class Board {
|
|
|
2296
2761
|
&& priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
|
|
2297
2762
|
const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
|
|
2298
2763
|
? { ...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 } : {}) }];
|
|
2764
|
+
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 } : {}), ...(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
2765
|
this.taskWrite(() => {
|
|
2301
2766
|
if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
|
|
2302
2767
|
if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
|