import { instructedExecution, instructedHistory } from "./instructed-exact.ts"; import { PreEffectToolRefusal } from "./tool-refusal.ts"; 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"; import { ExecutionLinkError, EXECUTION_LINK_LIMITS, executionLinkActor, executionLinkInteger, executionLinkId, executionLinkReferences, executionReferenceDigest, parseExecutionLinkInput, parseExecutionLinkRecord, type ExecutionLinkInput, type ExecutionLinkRecord, type ExecutionLinkFence } from "./execution-links.ts"; import { executionReferenceKey, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts"; import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt, type AttemptReceiptV1 } from "./research-runner.ts"; import { canonicalJson } from "./packs.ts"; import { parseEvidenceLink, evidenceLinkCanonical, MAX_EVIDENCE_RECORD_BYTES, type EvidenceLinkV1 } from "./research-evidence.ts"; import { parseStoredReviewComment, reviewCommentIds, emptyReviewCommentCounts, REVIEW_COMMENT_LIMIT, type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentCounts, type ReviewCommentPackage, type ReviewCommentPackageView } from "./review-comments.ts"; import { parseComparisonPlan, comparisonPlanHash, evaluatorIdentityHash, parseExperimentProtocol, protocolHash, parseExperimentAttempt, parseExperimentEvent, parseExperimentHostEvidence, experimentStatus, projectExperimentWithObservations, declaredExperimentEvents, type ComparisonPlanV1, type ExperimentProtocolRecord, type ExperimentAttemptRecord, type ExperimentEventRecord, type ExperimentWriteFence, type DeclaredExperimentEventInput, type ExperimentHostEvidence, type ExperimentStatus } from "./research-experiments.ts"; import type { InvocationRow } from "./invocations.ts"; import { HOST_CODE_SYMBOLS, parseTaskCodeSymbols, type TaskCodeSymbols } from "./task-code-symbols.ts"; import { createHash } from "node:crypto"; import { types } from "node:util"; import { planFingerprint } from "./plan-conformance.ts"; import type { PlannerReason } from "./routing.ts"; import type { ReviewerPoolReason } from "./reviewer-pool.ts"; import type { GitHubSource } from "./github-import.ts"; import type { Database } from "./db-schema.ts"; import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts"; import { controlWriteSpan } from "./control-write-trace.ts"; import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts"; import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, githubRepo, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState, type DecomposePart, type DecomposeIntake, type DecompositionState, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts"; import { HUB, USER, type PeerId } from "./envelope.ts"; import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts"; import type { ReviewFinding } from "./review-findings.ts"; import type { SweepRecord } from "./task-sweep.ts"; import type { SpecAcceptance, SdlcReceipt } from "./sdlc.ts"; import { parseReviewFindings, type ReviewFindingSet } from "./review-findings.ts"; import { storedSecurityPass, type SecurityPassRecord } from "./security-pass.ts"; import { parseDeliverableRecords, type DeliverableRecord } from "./deliverables.ts"; import type { CostPlan, ReviewCost } from "./cost-governance.ts"; import type { SpecRef, SpecTaskReport } from "./specs-task.ts"; export type { SpecAck, SpecRef, SpecTaskReport } from "./specs-task.ts"; import { campaignHash, parseResearchCampaign, parseResearchHandoff, type ResearchCampaignContract, type ResearchCampaignStatus, type ResearchUnit, type ResearchHandoffV1, type ResearchHandoffRecord } from "./research-campaign.ts"; import { parseSurveyFindings, parseSurveyVetDecisions, surveyArray, surveyObject, surveyPath, surveyText, surveyFindingId, surveyPass, type SurveyFinding, type SurveyVetDecision, SURVEY_FOCUS, SURVEY_LIMITS, type SurveyFocus } from "./advisor-survey.ts"; import { parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts"; export interface StoredSurvey { id: number; task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true } export interface StoredSurveyFinding { finding: SurveyFinding; foundBy: string; foundAt: number; decision?: SurveyVetDecision; decisionBy?: string; decisionAt?: number } export interface SurveyPreparedCard { id: string; key: string; title: string; detail: string; class: "plan" | "triage"; refs?: TaskRefs; signals?: string[]; reopens?: number; reopenReason?: string } export interface SurveyApplyInput { findings: SurveyFinding[]; decisions: SurveyVetDecision[]; by: string; at: number; cards?: SurveyPreparedCard[]; rejections?: ConsideredEntry[]; reconsiderations?: ConsideredEntry[]; withheld?: true } export interface SurveyWriteFence { boardRevision: number; taskCreated: number; taskFlowRevision: number; owner: string } export interface StoredRejectedFinding { id: number; entry: ConsideredEntry; reconsideredBy: number[] } const SURVEY_STORE_LIMIT = 1000, SURVEY_STORE_BYTES = 64 * 1024; const surveyStorageFailure = (): never => { throw new Error("survey storage invalid; stop the hub and restore a trusted hub.db backup before retrying"); }; const surveyInputFailure = (): never => { throw new Error("invalid survey storage input or changed binding"); }; const surveyInteger = (value: unknown, min = 1): number => typeof value === "number" && Number.isSafeInteger(value) && value >= min ? value : surveyInputFailure(); const surveyHash = (body: string) => createHash("sha256").update(body).digest("hex"); function surveyCreateInput(input: unknown): Omit { const row = surveyObject(input, ["task", "taskCreated", "repo", "ref", "focus", "by", "at", "withheld"]); if (typeof row.ref !== "string" || !/^[a-f0-9]{40}$/.test(row.ref) || row.withheld !== undefined && row.withheld !== true) return surveyInputFailure(); return { task: surveyInteger(row.task), taskCreated: surveyInteger(row.taskCreated, 0), repo: surveyText(row.repo, 1024), ref: row.ref, ...(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 } : {}) }; } function surveyStoredFinding(input: unknown): StoredSurveyFinding { const row = surveyObject(input, ["finding", "foundBy", "foundAt", "decision", "decisionBy", "decisionAt"]), finding = parseSurveyFindings([row.finding])[0]!; const decision = row.decision === undefined ? undefined : parseSurveyVetDecisions([row.decision])[0]!; if (decision && decision.id !== finding.id || !decision && (row.decisionBy !== undefined || row.decisionAt !== undefined)) return surveyInputFailure(); return { finding, foundBy: surveyText(row.foundBy, 128), foundAt: surveyInteger(row.foundAt, 0), ...(decision ? { decision, decisionBy: surveyText(row.decisionBy, 128), decisionAt: surveyInteger(row.decisionAt, 0) } : {}) }; } 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, CASE WHEN typeof(body_sha256)='text' AND length(CAST(body_sha256 AS BLOB))<=${GUIDANCE_HASH_HEX_LENGTH} THEN body_sha256 END AS body_sha256, CASE WHEN typeof(created_by)='text' AND length(CAST(created_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN created_by END AS created_by,CASE WHEN typeof(created_at)='integer' THEN created_at END AS created_at, CASE WHEN withdrawn_by IS NULL OR typeof(withdrawn_by)='text' AND length(CAST(withdrawn_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN withdrawn_by END AS withdrawn_by,CASE WHEN withdrawn_at IS NULL OR typeof(withdrawn_at)='integer' THEN withdrawn_at END AS withdrawn_at, CASE WHEN withdrawn_at IS NULL OR typeof(withdrawn_at)='integer' THEN 1 ELSE 0 END AS valid_withdrawn_at, CASE WHEN withdrawn_by IS NULL OR typeof(withdrawn_by)='text' AND length(CAST(withdrawn_by AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN 1 ELSE 0 END AS valid_withdrawn_by`; /** Internal host capability; never accepted from a control or tool argument. */ export const HOST_MERGE_ADOPTION = Symbol("host merge adoption"); /** Internal publication capability, independent of the person-only acceptance API. */ export const HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry"); /** * Internal capability for R2 part 2 (#1480): the draft `roadmapDecomposePart` stages for an accepted part is held exactly like the * person's intake draft. A Symbol cannot arrive in a tool argument, so no caller can stage a hidden draft through it. */ export const HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft"); export interface SpecAcceptanceCommit { source: number; cancellationRevision: number; acceptance: SpecAcceptance; } export interface ResearchCampaignRecord { id: string; project: string; parentTaskId: number; revision: number; status: ResearchCampaignStatus; contract: ResearchCampaignContract; hash: string; private: boolean; createdBy: PeerId; createdAt: number; approvedBy?: PeerId; approvedAt?: number; closedBy?: PeerId; closedAt?: number; closedReason?: string; dispatchVersion?: 1; eligibleOwners?: string[]; } export interface ResearchUnitBinding { campaignId: string; revision: number; unitId: string; taskId: number; round: number; purpose: ResearchUnit["purpose"]; adopted: boolean; } export interface PreparedResearchUnit { unitId: string; create?: Parameters[1]; adopt?: { taskId: number; flowRevision: number }; reuse?: { taskId: number; flowRevision: number }; } interface ResearchCampaignRow { id: string; project: string; parent_task_id: number; revision: number; status: string; body: string | null; body_sha256: string; private: number; created_by: string; created_at: number; approved_by: string | null; approved_at: number | null; closed_by: string | null; closed_at: number | null; closed_reason: string | null; } interface ResearchHandoffRow { campaign_id: string; unit_id: string; seq: number; revision: number; task_id: number; body: string | null; by_peer: string; at: number; private: number } interface ResearchUnitRow { campaign_id: string; revision: number; unit_id: string; task_id: number; round: number; purpose: string; adopted: number } const RESEARCH_CAMPAIGN_SELECT = "SELECT id,project,parent_task_id,revision,status,CASE WHEN length(CAST(body AS BLOB)) <= 65536 THEN body END AS body,body_sha256,private,created_by,created_at,approved_by,approved_at,closed_by,closed_at,closed_reason FROM research_campaigns"; const researchFailure = (): Error => new Error("research campaign state is invalid, changed or corrupt"); const researchId = (value: unknown): value is string => typeof value === "string" && value.length === 15 && /^rc-[0-9a-f]{12}$/.test(value); const researchInteger = (value: unknown, minimum = 1): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= minimum; const researchText = (value: unknown, max = 512): value is string => typeof value === "string" && value.length > 0 && value.length <= max && Buffer.byteLength(value, "utf8") <= max && Buffer.from(value, "utf8").toString("utf8") === value; function checkedResearchCampaign(record: ResearchCampaignRecord): ResearchCampaignRecord { if (!researchId(record.id) || !researchText(record.project) || !researchInteger(record.parentTaskId) || !researchInteger(record.revision) || !["draft", "approved", "superseded", "closed"].includes(record.status) || typeof record.private !== "boolean" || !researchText(record.createdBy) || !researchInteger(record.createdAt, 0)) throw researchFailure(); const contract = parseResearchCampaign(record.contract), hash = campaignHash(contract); if (record.hash !== hash || (record.approvedBy === undefined) !== (record.approvedAt === undefined) || record.approvedBy !== undefined && (!researchText(record.approvedBy) || !researchInteger(record.approvedAt, 0)) || (record.closedBy === undefined) !== (record.closedAt === undefined) || (record.closedBy === undefined) !== (record.closedReason === undefined) || record.closedBy !== undefined && (!researchText(record.closedBy) || !researchInteger(record.closedAt, 0) || !researchText(record.closedReason, 4096)) || ["approved", "superseded"].includes(record.status) && record.approvedBy === undefined || record.status === "closed" && record.closedBy === undefined || record.status !== "closed" && record.closedBy !== undefined || record.status === "draft" && record.approvedBy !== undefined) throw researchFailure(); return { ...record, contract, hash }; } function researchCampaignFromRow(row: ResearchCampaignRow): ResearchCampaignRecord { try { if (typeof row.body !== "string" || ![0, 1].includes(row.private)) throw researchFailure(); return checkedResearchCampaign({ id: row.id, project: row.project, parentTaskId: row.parent_task_id, revision: row.revision, status: row.status as ResearchCampaignStatus, contract: JSON.parse(row.body) as ResearchCampaignContract, hash: row.body_sha256, private: row.private === 1, createdBy: row.created_by, createdAt: row.created_at, ...(row.approved_by !== null ? { approvedBy: row.approved_by } : {}), ...(row.approved_at !== null ? { approvedAt: row.approved_at } : {}), ...(row.closed_by !== null ? { closedBy: row.closed_by } : {}), ...(row.closed_at !== null ? { closedAt: row.closed_at } : {}), ...(row.closed_reason !== null ? { closedReason: row.closed_reason } : {}) }); } catch { throw researchFailure(); } } const EXECUTION_REFERENCE_SELECT = `SELECT CASE WHEN length(CAST(id AS BLOB))=64 THEN id END AS id, CASE WHEN length(CAST(project_id AS BLOB)) BETWEEN 1 AND 256 THEN project_id END AS project_id, task_id,task_created, CASE WHEN length(CAST(from_json AS BLOB))<=${EXECUTION_LINK_LIMITS.referenceBytes} THEN from_json END AS from_json, CASE WHEN length(CAST(from_sha256 AS BLOB))=64 THEN from_sha256 END AS from_sha256, CASE WHEN length(CAST(reference_json AS BLOB))<=${EXECUTION_LINK_LIMITS.referenceBytes} THEN reference_json END AS reference_json, CASE WHEN length(CAST(reference_sha256 AS BLOB))=64 THEN reference_sha256 END AS reference_sha256, CASE WHEN length(CAST(recorded_by AS BLOB)) BETWEEN 1 AND ${EXECUTION_LINK_LIMITS.actor} THEN recorded_by END AS recorded_by, recorded_at FROM execution_reference_links`; export interface ExperimentComparisonPlanRecord { hash: string; project: string; recordedForTaskId: number; plan: ComparisonPlanV1; by: PeerId; at: number; private: boolean; } export interface ExperimentProtocolApproval { protocolHash: string; evaluatorHash: string; approvedBy: PeerId; at: number } export type ExperimentProtocolContext = { state: "unknown" } | { state: "predeclared" } | { state: "post-hoc"; priorFinal: { attemptId: string; endSeq: number } }; interface ExperimentComparisonPlanRow { row_id?: number; hash: string; project: string; campaign_id: string; campaign_revision: number; task_id: number; body: string | null; by_peer: string; at: number; private: number } interface ExperimentProtocolApprovalRow { protocol_hash: string; evaluator_hash: string; approved_by: string; at: number } interface ExperimentProtocolContextRow { protocol_hash: string; prior_attempt_id: string | null; prior_end_seq: number | null; context_sha256: string } const EXPERIMENT_PLAN_SELECT = "SELECT rowid AS row_id,hash,project,campaign_id,campaign_revision,task_id,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,by_peer,at,private FROM research_plans"; interface ExperimentProtocolRow { hash: string; project: string; campaign_id: string; campaign_revision: number; task_id: number; body: string | null; by_peer: string; at: number; private: number } interface ExperimentAttemptRow { row_id?: number; attempt_id: string; project: string; campaign_id: string; campaign_revision: number; protocol_hash: string; task_id: number; idempotency_key: string; body: string | null; body_sha256: string; by_peer: string; at: number; private: number } interface ExperimentEventRow { attempt_id: string; project: string; seq: number; idempotency_key: string; kind: string; body: string | null; body_sha256: string; by_peer: string; at: number; private: number } export interface RunnerReceiptRecord { receipt: AttemptReceiptV1; signature: string; publicKey: string; keyHash: string; bodyHash: string; seq: number; by: PeerId; at: number; private: boolean; } interface RunnerReceiptRow { receipt_id: string; project: string; attempt_id: string; event_seq: number; body: string | null; body_sha256: string; by_peer: string; at: number; private: number } const RUNNER_RECEIPT_SELECT = "SELECT receipt_id,project,attempt_id,event_seq,CASE WHEN length(CAST(body AS BLOB))<=131072 THEN body END AS body,body_sha256,by_peer,at,private FROM research_runner_receipts"; interface ExperimentObservationRow { attempt_id: string; event_seq: number; body: string | null; body_sha256: string } const EXPERIMENT_PROTOCOL_SELECT = "SELECT hash,project,campaign_id,campaign_revision,task_id,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,by_peer,at,private FROM research_protocols"; const EXPERIMENT_ATTEMPT_SELECT = "SELECT rowid AS row_id,attempt_id,project,campaign_id,campaign_revision,protocol_hash,task_id,idempotency_key,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,body_sha256,by_peer,at,private FROM research_attempts"; const EXPERIMENT_EVENT_SELECT = "SELECT attempt_id,project,seq,idempotency_key,kind,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,body_sha256,by_peer,at,private FROM research_attempt_events"; const experimentFailure = (): Error => new Error("experiment state is invalid, changed or corrupt"); const experimentHash = (value: unknown): string => createHash("sha256").update(canonicalJson(value)).digest("hex"); const experimentHashValid = (value: unknown): value is string => typeof value === "string" && value.length === 64 && /^[0-9a-f]{64}$/.test(value); const experimentIdValid = (value: unknown): value is string => typeof value === "string" && /^ra-[0-9a-f]{12}$/.test(value); const experimentPage = (after: number, limit: number): void => { if (!researchInteger(after, 0) || !researchInteger(limit) || limit > 50) throw experimentFailure(); }; export const CLASSES = ["plan", "implement", "bulk_edit", "test", "review", "summarize", "triage"] as const; export type TaskClass = (typeof CLASSES)[number]; /** #1403 A4: one security audit as stored. `units` is the ledger; it changes only through `Board.auditReport`. */ export interface StoredAudit { id: number; task: number; taskCreated: number; ref: string; since?: string; profile: AuditProfile; scoped: boolean; at: number; by: string; units: AuditUnit[] } const EVIDENCE_HISTORY_WINDOW = 1024; export type TaskState = "backlog" | "proposed" | "in_progress" | "in_review" | "approved" | "changes_requested" | "cancelled"; export const isClosedTaskState = (state: string): boolean => state === "approved" || state === "cancelled"; export interface TaskOffer { envelopeId: string; owner: PeerId; assignmentFlowRevision: number; pullOnly?: boolean } export interface TaskCancellation { reason: string; supersededBy?: string; flowRevision: number; withheld?: true } /** Metadata only: source task text, plans and growing histories never enter a carry lookup. */ export interface SpecAcceptanceCandidate { id: number; created: number; state: "cancelled"; refs: TaskRefs; signals: string[]; supersededBy: string; cancellationRevision: number; withheld: boolean; repo: unknown; issue: unknown; acceptance: unknown; } // ponytail: one 32-source snapshot; larger sets need a bounded paginated lookup with a shared currentness proof. const SPEC_ACCEPTANCE_SOURCE_LIMIT = 32; const SPEC_ACCEPTANCE_FIELD_BYTES = 64 * 1024; const SPEC_ACCEPTANCE_TOTAL_BYTES = 256 * 1024; export const TASK_STALL_CODES = ["tests", "spec", "network", "worktree", "roster", "pull-only", "not-attached", "excluded", "owner-admission", "offline", "paused", "failing", "pii", "policy", "cancelled", "unavailable", "no-writes", "queue-count", "queue-age", "queue-age-unknown"] as const; export type TaskStallCode = (typeof TASK_STALL_CODES)[number]; export interface TaskStall { task: number; signature: string; replanRevision: number; cause: { kind: "reservation" | "no-eligible-peer" | "cancelled-dependency" | "no-writes"; peer?: string; dependency?: number; code: TaskStallCode; turns?: number; acceptance?: number; refusals?: { peer: string; code: TaskStallCode }[] }; at: number } const QUEUE_PRESSURE_STALL = "CASE WHEN length(CAST(payload AS BLOB)) <= 65536 THEN CASE WHEN json_valid(payload) THEN json_extract(payload,'$.cause.kind')='no-eligible-peer' AND json_extract(payload,'$.cause.code') IN ('queue-count','queue-age','queue-age-unknown') ELSE 0 END ELSE 0 END"; export interface QueuePressureStallPage { rows: TaskStall[]; afterTask: number; done: boolean } function parseStall(payload: string, task?: number): TaskStall | undefined { try { const value = JSON.parse(payload) as TaskStall, cause = value.cause; const peer = (id: unknown) => typeof id === "string" && /^[a-z][a-z0-9_-]{0,63}$/i.test(id); if (task !== undefined && value.task !== task || Object.keys(value).some(key => !["task", "signature", "replanRevision", "cause", "at"].includes(key)) || !Number.isSafeInteger(value.task) || value.task < 1 || !Number.isSafeInteger(value.replanRevision) || value.replanRevision < 0 || !Number.isFinite(value.at) || !cause || !["reservation", "no-eligible-peer", "cancelled-dependency", "no-writes"].includes(cause.kind) || !TASK_STALL_CODES.includes(cause.code) || cause.kind === "no-writes" && (cause.code !== "no-writes" || !peer(cause.peer) || !Number.isSafeInteger(cause.turns) || cause.turns! < 1 || !Number.isSafeInteger(cause.acceptance) || cause.acceptance! < 0) || cause.peer !== undefined && !peer(cause.peer) || cause.dependency !== undefined && (!Number.isSafeInteger(cause.dependency) || cause.dependency < 1) || cause.refusals !== undefined && (!Array.isArray(cause.refusals) || cause.refusals.length > 64 || cause.refusals.some(row => Object.keys(row).some(key => !["peer", "code"].includes(key)) || !peer(row.peer) || !TASK_STALL_CODES.includes(row.code))) || Object.keys(cause).some(key => !["kind", "peer", "dependency", "code", "refusals", ...(cause.kind === "no-writes" ? ["turns", "acceptance"] : [])].includes(key)) || value.signature !== JSON.stringify(cause)) return undefined; return value; } catch { return undefined; } } export interface TaskRefs { repo?: string; branch?: string; commit?: string; paths?: string[]; } /** What an owner says it will change, before it starts (issue #31). Each list holds short free-text items. */ export const PLAN_KEYS = ["paths", "symbols", "signatures", "insertion_points"] as const; export const DOCUMENT_PLAN_KEYS = ["paths", "sections", "sources", "claims"] as const; export const ALL_PLAN_KEYS = [...PLAN_KEYS, "sections", "sources", "claims", "proof", "risks"] as const; export interface ColdPlanIntent { base?: string; out_of_scope?: string[]; stop_if?: string[]; steps?: { description: string; verify?: string }[]; } export type TaskPlan = Partial> & CostPlan & ColdPlanIntent; /** Task outcomes older than this are pruned: demotion (issue #36) reads one week, seven half-lives. */ export const OUTCOMES_KEPT_MS = 7 * 24 * 3_600_000; export const TASK_MOVE_REASONS = ["manual", "budget", "offline", "idle", "rejections", "declined", "inference_failed", "delivery_failed", "step_limit"] as const; export type TaskMoveReason = (typeof TASK_MOVE_REASONS)[number]; export type InvocationHistory = Pick; export interface HistoryEntry { instructed?: true; instructedPeer?: string; instructionReceipt?: string; /** Host-owned invocation metadata only, never arguments or results. */ invocation?: InvocationHistory; at: number; by: PeerId; event: string; // proposed | assigned | accepted | declined | done | approved | changes_requested | escalated | reassigned note?: string; supersededBy?: string; /** The owner an event that set it left the task with (#67); absent in rows written before 0.11. */ owner?: PeerId | null; /** Host-selected planner at this transition; absent in legacy history. */ planner?: PeerId | null; plannerReason?: PlannerReason; /** Saved plan-review author/self-review evidence, retained if the current receipt changes. */ planAuthor?: PeerId | null; selfReview?: true; /** On a decline or an escalation: the owner it was declined for or taken from (#207); later reroutes leave it out. */ from?: PeerId; /** On a decline: the owner had no capacity right now (#531). Absent on older rows and on a plain refusal, which read as lasting. */ capacity?: true; /** Host-observed explicit conductor assignment/removal, retained independently of later role changes. */ conductorManual?: true; /** On a hand-over: the new owner's split profile then (#109); absent when it was unknown. */ profile?: string; /** Structured cause recorded at the operation source, never inferred from note text. */ reason?: TaskMoveReason; /** Persisted task-idle ladder; never counted as fresh task activity (#186). */ sweep?: SweepRecord; /** #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. */ wait?: { until: number; owner: PeerId }; /** The PII screen did not clear this entry's note (#198): only the console reads it. */ withheld?: true; /** Public, head-bound design-spec status; acknowledgement text is screened before this is written. */ specReport?: SpecTaskReport; /** Internal identity for incomplete reports without a full commit SHA; never projected publicly. */ specRefBinding?: string; /** Host evidence at done, never inferred from the owner's summary. */ noWrites?: true; /** Host-recorded expected cost and exact review head, never narrative. */ reviewCost?: ReviewCost; /** Full commit submitted for review; independent of cost planning. */ requestHead?: string; /** #901: on the hub's own `check passed` / `check failed`: the check key (task class or profile class alias) whose command ran. Set by the hub from its own selection, never from output or an owner's words. */ checkKey?: string; /** #901: on such an entry, the number of unresolved citation keys the example citation check printed (`citations: N declared keys, M missing`); absent when the check printed no such line. */ missingKeys?: number; /** #901: a person's verdict on one declared claim of a document plan. `slot` is the claim's 1-based position in the current plan; no claim text, no source and no path is stored. */ claim?: ClaimVerdict; /** #223 R4: on a verdict, whether the reviewer's context was new for it; set by the hub, never by the reviewer. */ reviewContext?: "fresh" | "continuing"; /** #852: a verdict by a `code`-scope reviewer says so; a `full` reviewer's verdict carries nothing, so existing rows are unchanged. */ reviewScope?: "code"; /** #852 AC3: a `code`-scope reviewer's changes_requested with no open finding. It is recorded, returns the task to its owner and counts toward nothing. */ evidenceOnly?: true; /** Structured review report bound to the reviewed artifact, stored in the existing history JSON. */ reviewFindings?: ReviewFindingSet; /** Immutable artifact head of this verdict, including when lifecycle gates are off. */ reviewedHead?: string; /** * #509a: the files a `done`, a lifecycle record or an approval bound, with the content hashes the hub computed. An approval carries the hashes * it was given at review time, so a later edit reads as "deliverable changed since review". Full paths live here; every view goes through * `publicDeliverables`. */ deliverables?: DeliverableRecord[]; /** #507b: the recorded acceptance criteria (S8 checklist ids) a verdict's unmet items named; derived by the hub from the checklist, never free text. */ unmetCriteria?: string[]; /** #1403 A2: the security pass an approving verdict recorded (units covered and not covered, bound to the reviewed head). Enabled lifecycle only. */ securityPass?: SecurityPassRecord; /** Host-authored plan content revision, separate from backlog planningRevision. */ planRevision?: { revision: number; fingerprint: string }; planObservation?: { repo: string; pr: number; head: string; revision: number; fingerprint: string }; planDepartureInvalidated?: true; planDeparture?: { generation: string; scope?: string; repo: string; pr: number; head: string; revision: number; fingerprint: string; paths: string[] }; reviewerFamily?: string; reviewerReason?: ReviewerPoolReason; reviewBlocked?: true; /** Host-only temporary automatic review hold caused by queue admission, never a reviewer failure. */ queueReviewHeld?: true; /** Opaque artifact identity captured by the host at the queue-held role write. */ queueReviewBinding?: string; reviewerQuotaWait?: { created: number; binding: string; since: number; deadline: number; resetAt: number }; reviewerFailure?: { peer: string; head?: string; cause: "start_failed" | "quota" | "no_verdict"; reason?: "review time cap" }; resolvedReviewComments?: string[]; planning?: { revision: number; fields: (keyof PlanningFields)[]; previous: PlanningFields; pull?: true; split?: { children: { id: number; revision: number; history: number }[] } }; } /** #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. */ export const CLAIM_VERDICTS = ["supported", "unsupported", "unclear"] as const; /** `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. */ 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 } /** 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. */ export function claimListId(claims: readonly string[] | undefined): string { return createHash("sha256").update(planFingerprint({ claims: [...(claims ?? [])] })).digest("hex").slice(0, 16); } /** #901's one claim identity boundary, shared by person verdicts and declared passage links. */ export function taskClaimIdentity(task: Pick, slot: number): { claimId: string; claimRevision: string; slot: number } { if (!Number.isSafeInteger(task.id) || task.id < 1 || !Number.isSafeInteger(task.created) || task.created < 0 || !Number.isSafeInteger(slot) || slot < 1 || slot > Math.min(50, task.plan?.claims?.length ?? 0)) throw new Error("claim slot is unavailable; refresh ahub task show and use a current declared claim slot"); // ponytail: revision binds the whole ordered list, so another claim's edit invalidates every link. // Upgrade to shared per-claim revision bindings at this #901 boundary, preserving exact-list restoration of existing verdicts. return { claimId: `claim:${task.id}:${task.created}:${slot}`, claimRevision: claimListId(task.plan?.claims), slot }; } /** 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. */ export function parseClaimVerdict(value: unknown, slots: number): ClaimVerdict { if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length || Object.values(Object.getOwnPropertyDescriptors(value)).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) throw new Error("claim verdict must be an object"); const v = value as Record; 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"); 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"}`); 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(", ")}`); 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 . _ : / @ + -)"); 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(", ")}`); let synthesis: ClaimVerdict["synthesis"]; if (v.synthesis !== undefined) { const item = v.synthesis; if (!item || typeof item !== "object" || Array.isArray(item) || types.isProxy(item) || ![Object.prototype, null].includes(Object.getPrototypeOf(item)) || Object.getOwnPropertySymbols(item).length || Object.values(Object.getOwnPropertyDescriptors(item)).some(field => !Object.hasOwn(field, "value") || !field.enumerable) || Object.keys(item).some(key => key !== "manifestSha256" && key !== "disposition")) throw new Error("synthesis disposition requires only manifestSha256 and disposition"); const row = item as Record; 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"); synthesis = { manifestSha256: row.manifestSha256, disposition: row.disposition }; } 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 } : {}) }; } /** The ids a stored verdict may carry (#507b): bounded criterion identifiers in the S8 checklist's own format, at most its 32, each once. */ function criterionIdList(value: unknown): string[] { 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"); return [...value] as string[]; } export type ReviewerHistory = Pick; function reviewerHistory(extra: ReviewerHistory): ReviewerHistory { const id = (value: unknown) => typeof value === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(value); 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"); 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"); const wait = extra.reviewerQuotaWait; if (wait && (!Number.isSafeInteger(wait.created) || wait.created < 0 || !/^[a-f0-9]{64}$/.test(wait.binding) || !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"); const failure = extra.reviewerFailure; if (failure?.reason !== undefined && (failure.reason !== "review time cap" || failure.cause !== "no_verdict")) throw new Error("invalid reviewer timeout metadata"); 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"); 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 } : {}) } } : {}) }; } function specReportHistory(report: unknown, binding: unknown, event: string): Pick { if (!report || typeof report !== "object" || Array.isArray(report) || !["done", "done (checking)"].includes(event) || typeof binding !== "string" || !/^[a-f0-9]{64}$/.test(binding)) throw new Error("invalid task spec report metadata"); const value = report as Record; if (Object.keys(value).some(key => !["head", "complete", "errors", "unchanged", "changed", "truncated", "reason"].includes(key)) || typeof value.head !== "string" || value.head !== "" && !/^[a-f0-9]{40}$/.test(value.head) || value.head === "" && value.complete !== false || typeof value.complete !== "boolean" || !Number.isSafeInteger(value.errors) || (value.errors as number) < 0 || (value.errors as number) > 1_000_000 || value.truncated !== undefined && value.truncated !== true || value.reason !== undefined && (typeof value.reason !== "string" || value.reason.length > 500 || /[\p{Cc}\p{Cf}]/u.test(value.reason)) || !Array.isArray(value.unchanged) || value.unchanged.length > 20 || !Array.isArray(value.changed) || value.changed.length > 20) throw new Error("invalid task spec report metadata"); const ref = (raw: unknown): SpecRef => { if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid task spec report metadata"); const row = raw as Record; if (Object.keys(row).some(key => !["id", "path", "title", "reason"].includes(key)) || typeof row.id !== "string" || !row.id.trim() || row.id.length > 160 || /[\p{Cc}\p{Cf}]/u.test(row.id) || typeof row.path !== "string" || !row.path.trim() || row.path.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.path) || typeof row.title !== "string" || !row.title.trim() || row.title.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.title) || row.reason !== undefined && (typeof row.reason !== "string" || row.reason.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.reason))) throw new Error("invalid task spec report metadata"); return { id: row.id, path: row.path, title: row.title, ...(typeof row.reason === "string" ? { reason: row.reason } : {}) }; }; const specReport: SpecTaskReport = { head: value.head, complete: value.complete, errors: value.errors as number, unchanged: value.unchanged.map(ref), changed: value.changed.map(ref), ...(value.truncated === true ? { truncated: true } : {}), ...(typeof value.reason === "string" ? { reason: value.reason } : {}) }; return { specReport, specRefBinding: binding }; } export interface PlannerBinding { planner: PeerId | null; plannerReason: PlannerReason } function plannerValue(value: unknown): PeerId | null { if (value == null) return null; if (typeof value !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(value)) throw new Error("invalid planner id"); return value; } function plannerMetadata(planner: unknown, reason?: PlannerReason): Pick { if (reason !== undefined && !["rotation", "named", "kept", "none"].includes(reason)) throw new Error("invalid planner reason"); return { planner: plannerValue(planner), ...(reason === undefined ? {} : { plannerReason: reason }) }; } /** #604: what this project handed to another project, and the last state that project reported (agent-hub#1030 design 4). */ export interface HandoffOutboundRow { remoteProject: string; remoteTask: number; originPeer: string; localTask: number | null; title: string; state: string; pr: number | null; head: string | null; updatedAt: number; /** #733: the target task's flow revision at the last event applied; null for a row from before sequences or from a target that sends none. */ seq: number | null } const OUTBOUND_COLUMNS = "remote_project, remote_task, origin_peer, local_task, title, last_state, pr, head, updated_at, seq"; const handoffOutboundFromRow = (row: Record): HandoffOutboundRow => ({ remoteProject: String(row.remote_project), remoteTask: Number(row.remote_task), originPeer: String(row.origin_peer), localTask: row.local_task === null ? null : Number(row.local_task), title: String(row.title), state: String(row.last_state), pr: row.pr === null ? null : Number(row.pr), head: row.head === null ? null : String(row.head), updatedAt: Number(row.updated_at), seq: row.seq === null || row.seq === undefined ? null : Number(row.seq) }); export interface Task extends PlanningFields { offer?: TaskOffer; cancelled?: TaskCancellation; external?: GitHubSource; planningRevision?: number; /** #334: an intake draft. Backlog work that is never offered or pulled until the person approves it; split children inherit it. */ draft?: true; id: number; title: string; detail: string; class: TaskClass; profile?: import("./profiles.ts").ProfileName; profileClass?: string; /** Catalog guidance id only, never an authority role (#295). */ role?: string; owner: PeerId | null; /** Null for legacy rows; only Tasks chooses or changes a planner. */ planner?: PeerId | null; reviewer: PeerId | null; state: TaskState; refs: TaskRefs; /** Absent only on tasks built outside the board (tests); the board always returns one, `{}` when none was given. */ plan?: TaskPlan; /** Artifact identities and bounded evidence, owned by Tasks (#257). */ sdlc?: SdlcReceipt; /** Host-derived observation for one head, never accepted from task tool arguments. */ codeSymbols?: TaskCodeSymbols; /** Tasks that must be approved before this one is offered; planning edits are limited to unstarted backlog. */ deps?: number[]; /** Who routing offers the task first once nothing is left to wait for (issue #207); null when nobody was named. */ reserved?: PeerId | null; /** #1176: only the person can run this leg. Present (true) only when set; no agent is ever offered it, and it counts toward no planner's WIP. */ needsPerson?: true; signals: string[]; /** consecutive changes_requested verdicts */ rejections: number; history: HistoryEntry[]; created: number; updated: number; } /** Structured execution evidence, including legacy rows whose owner was later cleared. */ export function taskHasStarted(task: Pick): boolean { if (task.history.some(entry => entry.event === "check run passed" || entry.event === "check run failed")) return true; return task.history.some(entry => ["accepted", "done", "done (checking)", "check passed", "check failed", "changes_requested", "approved", "reopened", "integration requested", "integrated"].includes(entry.event)); } /** S9 return eligibility never erases the historical acceptance used by cancellation and undo. */ export function taskHasWorkEvidence(task: Pick): boolean { return !!(task.refs.branch || task.refs.commit || task.sdlc?.localHead || task.sdlc?.localResult || task.sdlc?.reviewedHead || task.sdlc?.pr) || task.history.some(entry => entry.event === "done" || entry.event.startsWith("done (") || entry.event.startsWith("check ") || ["changes_requested", "approved", "reopened", "integration requested", "integration unresolved", "integrated"].includes(entry.event)); } /** A successful untouched return permits replanning, without changing historical start evidence. */ export function taskCanPlan(task: Pick): boolean { if (!taskHasStarted(task)) return true; const returned = task.history.findLastIndex(entry => entry.event === "backlog returned untouched"); const accepted = task.history.findLastIndex(entry => entry.event === "accepted"); return returned > accepted && !taskHasWorkEvidence(task); } /** First offer boundary; staged work has none until it is pulled. */ export function taskProposalAt(task: Pick): number | undefined { return task.history.find(entry => entry.event === "proposed" || entry.event === "backlog pulled")?.at; } /** Readiness carries out a pending pull; ownership or other later changes still fence undo. */ export function planningUndoEntry(task: Pick): HistoryEntry | undefined { return task.history.findLast(item => item.event !== "memory reference started" && (item.by !== HUB || item.event !== "ready")); } /** The moves the state machine allows. `accept` and `done` are transitions, not states: they carried no behaviour of their own. */ const MOVES: Record = { backlog: ["proposed", "cancelled"], proposed: ["in_progress", "backlog", "cancelled"], in_progress: ["in_review", "approved", "proposed", "cancelled"], // approved: class without a reviewer; proposed: owner declined or was taken off in_review: ["approved", "changes_requested", "cancelled"], changes_requested: ["in_progress", "proposed", "cancelled"], // proposed: declined redo waits for reassignment approved: [], cancelled: [], }; const JSON_COLS = ["refs", "plan", "deps", "signals", "history", "sdlc"] as const; // Separate storage keeps older SELECT * readers from exporting unscreened derived metadata. const TASK_SELECT = "SELECT tasks.*, (SELECT CASE WHEN length(CAST(payload AS BLOB)) <= 65536 THEN payload END FROM task_code_symbols WHERE task=tasks.id) AS code_symbols FROM tasks"; /** Task board in `.agenthub/state/hub.db`. It outlives the hub process: `ahub kill` leaves the file. */ export class Board { private readonly db: Database; private reviewObserverCacheStamp = ""; private readonly reviewObserverScopeCache = new Map(); private pendingChanges: { task: Task; entry: HistoryEntry }[] | undefined; /** Every recorded change, as it lands (telemetry, issue #40). */ onChange?: (task: Task, entry: HistoryEntry) => void; /** Host lifecycle policy, installed by Tasks; off projects keep their original history shape. */ trackPlanRevisions?: () => boolean; /** Fixed host-owned pure selection; no model, network or asynchronous work is admitted inside the insert. */ proposalPlanner?: (task: Task) => PlannerBinding; private changed(task: Task, entry: HistoryEntry): void { if (this.pendingChanges) { this.pendingChanges.push({ task, entry }); return; } try { this.onChange?.(task, entry); } catch { /* never throw after a board write */ } } /** Multi-row changes become observable only once their transaction commits. */ private atomic(write: () => T): T { if (this.pendingChanges) throw new Error("nested board transaction is not supported"); const changes: { task: Task; entry: HistoryEntry }[] = []; this.pendingChanges = changes; let result: T; try { result = this.db.transaction(write)(); } finally { this.pendingChanges = undefined; } for (const change of changes) this.changed(change.task, change.entry); return result; } /** Keep the generation and business write atomic without changing Bun's reported row count. */ private taskWrite(write: () => T): T { return controlWriteSpan("board-write", () => this.db.transaction(() => { const result = { ...write() }; if (result.changes) this.db.run("UPDATE board_status_revision SET revision=revision+1 WHERE id=1"); return result; })()); } statusRevision(): number { return (this.db.query("SELECT revision FROM board_status_revision WHERE id=1").get() as { revision: number }).revision; } constructor(path: string) { this.db = openHubDatabase(path, { create: true }); this.db.run("PRAGMA journal_mode = WAL"); this.db.run(`CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', class TEXT NOT NULL, owner TEXT, reviewer TEXT, state TEXT NOT NULL, refs TEXT NOT NULL DEFAULT '{}', signals TEXT NOT NULL DEFAULT '[]', rejections INTEGER NOT NULL DEFAULT 0, history TEXT NOT NULL DEFAULT '[]', created INTEGER NOT NULL, updated INTEGER NOT NULL)`); // Who did well or badly at which class, for demotion (issue #36). Only peers, classes and times: no task text. this.db.run("CREATE TABLE IF NOT EXISTS outcomes (peer TEXT NOT NULL, class TEXT NOT NULL, ok INTEGER NOT NULL, at INTEGER NOT NULL)"); this.db.run("CREATE INDEX IF NOT EXISTS outcomes_class_at ON outcomes (class, at)"); // How reviews turned out, per (implementer, reviewer, class) (issue #35): approved, contradicted later, caught, escalated. this.db.run("CREATE TABLE IF NOT EXISTS reviews (implementer TEXT NOT NULL, reviewer TEXT NOT NULL, class TEXT NOT NULL, kind TEXT NOT NULL, task INTEGER NOT NULL, at INTEGER NOT NULL)"); // ponytail: kept for good (a record is the whole history); prune by age if it ever grows large. this.db.run("CREATE INDEX IF NOT EXISTS reviews_class ON reviews (class)"); this.db.run("CREATE INDEX IF NOT EXISTS reviews_task ON reviews (task)"); // Boards from before issues #31 and #34 lack these columns; existing rows get the defaults. const have = new Set((this.db.query("PRAGMA table_info(tasks)").all() as { name: string }[]).map((c) => c.name)); for (const [col, empty] of [["plan", "{}"], ["deps", "[]"]] as const) { if (!have.has(col)) this.db.run(`ALTER TABLE tasks ADD COLUMN ${col} TEXT NOT NULL DEFAULT '${empty}'`); } // And from before issue #207: existing rows reserve nobody. for (const col of ["offer", "cancelled"]) if (!have.has(col)) this.db.run(`ALTER TABLE tasks ADD COLUMN ${col} TEXT`); this.db.run("CREATE TABLE IF NOT EXISTS task_stalls (task INTEGER PRIMARY KEY, payload TEXT NOT NULL)"); this.db.run(`CREATE INDEX IF NOT EXISTS task_stalls_queue_pressure ON task_stalls(task) WHERE ${QUEUE_PRESSURE_STALL}`); this.db.run("CREATE INDEX IF NOT EXISTS tasks_human_reviews ON tasks(id) WHERE state='in_review' AND reviewer='user'"); // #481 S7: one row per log-tier band breach episode already announced, so a restart never repeats the notice. this.db.run("CREATE TABLE IF NOT EXISTS band_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)"); this.db.run("CREATE TABLE IF NOT EXISTS roadmap_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)"); // #481 S7: one row per scheduled security scan. Counts only (no alert text); `total` is null when a named source could not be read completely. this.db.run("CREATE TABLE IF NOT EXISTS security_scans (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, repo TEXT NOT NULL, sources TEXT NOT NULL, counts TEXT NOT NULL, total INTEGER)"); // #843 AC3: one row per (agent id, installed version, planner) already queued, so a restart never repeats it. this.db.run("CREATE TABLE IF NOT EXISTS agent_drift_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)"); // #1057 D2: the person's park or pin of one worktree. Facts only: whether a worktree is settled is derived at read time and never stored here. this.db.run("CREATE TABLE IF NOT EXISTS worktree_override (path TEXT PRIMARY KEY, value TEXT NOT NULL CHECK(value IN ('settled','active')), at INTEGER NOT NULL)"); // Derived status-cache generation: only Board task/stall writes advance it, never journal writes. this.db.run("CREATE TABLE IF NOT EXISTS board_status_revision (id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL)"); this.db.run("INSERT OR IGNORE INTO board_status_revision VALUES (1,0)"); if (!have.has("planner")) this.db.run("ALTER TABLE tasks ADD COLUMN planner TEXT"); this.db.run("CREATE INDEX IF NOT EXISTS tasks_planner_present ON tasks(planner) WHERE planner IS NOT NULL"); if (!have.has("reserved")) this.db.run("ALTER TABLE tasks ADD COLUMN reserved TEXT"); if (!have.has("external_repo")) this.db.run("ALTER TABLE tasks ADD COLUMN external_repo TEXT"); if (!have.has("external_issue")) this.db.run("ALTER TABLE tasks ADD COLUMN external_issue INTEGER"); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS tasks_external_issue ON tasks(external_repo,external_issue) WHERE external_repo IS NOT NULL AND external_issue IS NOT NULL"); if (!have.has("sdlc")) this.db.run("ALTER TABLE tasks ADD COLUMN sdlc TEXT"); this.db.run("CREATE TABLE IF NOT EXISTS task_code_symbols (task INTEGER PRIMARY KEY, payload TEXT NOT NULL)"); this.db.run("DELETE FROM task_code_symbols WHERE task NOT IN (SELECT id FROM tasks) OR task IN (SELECT id FROM tasks WHERE json_valid(signals) AND EXISTS (SELECT 1 FROM json_each(signals) WHERE value IN ('pii','pii_path')))"); if (!have.has("task_role")) this.db.run("ALTER TABLE tasks ADD COLUMN task_role TEXT"); if (!have.has("project_profile")) this.db.run("ALTER TABLE tasks ADD COLUMN project_profile TEXT"); for (const col of ["rank", "priority", "release", "planned_start", "due"]) { if (!have.has(col)) this.db.run(`ALTER TABLE tasks ADD COLUMN "${col}" INTEGER`); } if (!have.has("pinned")) this.db.run("ALTER TABLE tasks ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0"); // #1176: additive, like `pinned`; an older hub ignores the column. if (!have.has("needs_person")) this.db.run("ALTER TABLE tasks ADD COLUMN needs_person INTEGER NOT NULL DEFAULT 0"); if (!have.has("draft")) this.db.run("ALTER TABLE tasks ADD COLUMN draft INTEGER NOT NULL DEFAULT 0"); if (!have.has("planning_revision")) this.db.run("ALTER TABLE tasks ADD COLUMN planning_revision INTEGER NOT NULL DEFAULT 0"); this.db.run(`CREATE TABLE IF NOT EXISTS releases ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, goal TEXT NOT NULL, release_order INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'planning', planned_start INTEGER, cut INTEGER, ship INTEGER, activated_at INTEGER, frozen_at INTEGER, shipped_at INTEGER, created INTEGER NOT NULL, updated INTEGER NOT NULL, revision INTEGER NOT NULL DEFAULT 0)`); if (!(this.db.query("PRAGMA table_info(releases)").all() as { name: string }[]).some(row => row.name === "planner")) this.db.run("ALTER TABLE releases ADD COLUMN planner TEXT"); this.db.run("CREATE INDEX IF NOT EXISTS releases_planner_present ON releases(planner) WHERE planner IS NOT NULL"); 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"); this.db.run(`CREATE TABLE IF NOT EXISTS milestones ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, outcome TEXT NOT NULL, state TEXT NOT NULL, horizon TEXT NOT NULL, milestone_order INTEGER NOT NULL, target TEXT, parent INTEGER, revision INTEGER NOT NULL DEFAULT 0, history TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL)`); this.db.run(`CREATE TABLE IF NOT EXISTS milestone_links ( milestone INTEGER NOT NULL, kind TEXT NOT NULL, ref TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(milestone,kind,ref))`); // R3 (#1481): advisory model suggestions and the one-time GitHub milestone import marks. Additive, outside the roadmap integrity digest: // a lost suggestion is triaged again, and an import mark only stops a repeat from creating a second milestone. this.db.run(`CREATE TABLE IF NOT EXISTS milestone_suggestions ( id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, ref TEXT NOT NULL, milestone INTEGER, proposal TEXT, cite_milestone TEXT, cite_item TEXT NOT NULL, state TEXT NOT NULL, by TEXT NOT NULL, created INTEGER NOT NULL, settled INTEGER, settled_by TEXT, created_milestone INTEGER)`); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_suggestions_pending ON milestone_suggestions(kind,ref) WHERE state='pending'"); this.db.run(`CREATE TABLE IF NOT EXISTS milestone_imports ( repo TEXT NOT NULL, number INTEGER NOT NULL, milestone INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(repo,number))`); // R2 (#1480): model-written decompositions, additive and outside the roadmap integrity digest like a suggestion: a lost // answer is asked for again, and one pending answer per milestone is the newest run. this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decompositions ( id INTEGER PRIMARY KEY AUTOINCREMENT, milestone INTEGER NOT NULL, parts TEXT NOT NULL, state TEXT NOT NULL, by TEXT NOT NULL, created INTEGER NOT NULL, settled INTEGER, settled_by TEXT)`); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_decompositions_pending ON milestone_decompositions(milestone) WHERE state='pending'"); // R2 part 2 (#1480): which parts of a pending answer are already held as intake drafts. Keyed by the answer and the part's // 1-based position, so accepting the same part twice finds this row instead of making a second draft. this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_accepts ( decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, task INTEGER NOT NULL, intake TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`); // R2 part 3 (#1480): the one issue a published part created, additive like the accept row. A lost row publishes the part // again; the issue's own marker names the draft it came from. this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_publishes ( decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, issue INTEGER NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`); this.db.run(`CREATE TABLE IF NOT EXISTS research_campaigns ( id TEXT NOT NULL, project TEXT NOT NULL, parent_task_id INTEGER NOT NULL, revision INTEGER NOT NULL, status TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, private INTEGER NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL, approved_by TEXT, approved_at INTEGER, closed_by TEXT, closed_at INTEGER, closed_reason TEXT, PRIMARY KEY(id,revision))`); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS research_campaigns_active_parent ON research_campaigns(project,parent_task_id) WHERE status='approved'"); this.db.run(`CREATE TABLE IF NOT EXISTS research_units ( campaign_id TEXT NOT NULL, revision INTEGER NOT NULL, unit_id TEXT NOT NULL, task_id INTEGER NOT NULL, round INTEGER NOT NULL, purpose TEXT NOT NULL, adopted INTEGER NOT NULL, PRIMARY KEY(campaign_id,revision,unit_id))`); this.db.run("CREATE INDEX IF NOT EXISTS research_units_task ON research_units(task_id)"); this.db.run(`CREATE TABLE IF NOT EXISTS research_dispatch ( campaign_id TEXT NOT NULL, revision INTEGER NOT NULL, version INTEGER NOT NULL, eligible_owners TEXT, PRIMARY KEY(campaign_id,revision))`); // #603: the owner whose queued offer a study hold made the bus discard, kept so approving the study offers the retained task again after a restart. this.db.run("CREATE TABLE IF NOT EXISTS research_dropped_offers (task_id INTEGER PRIMARY KEY, owner TEXT NOT NULL)"); // #604 (agent-hub#1030): cross-project handoff. `task_handoff_origin` is the TARGET's record of where a task came from (one row per task it created for another project); `task_handoff_outbound` // is the ORIGIN's record of what it handed to another project and the last state that project reported. Both are additive: a daemon without `task_handoff` never reads them, so a target // lacking the feature is refused at recovery while either holds a row. this.db.run("CREATE TABLE IF NOT EXISTS task_handoff_origin (task_id INTEGER PRIMARY KEY, project_id TEXT NOT NULL, peer TEXT NOT NULL, origin_task INTEGER, at INTEGER NOT NULL)"); // #731 (agent-hub#1203): the origin's idempotency key and a digest of what it asked for. A key is unique per origin project, so a replay can never file a second task. Rows from before keep NULL. for (const [column, type] of [["handoff_key", "TEXT"], ["request_digest", "TEXT"]] as const) if (!(this.db.query("PRAGMA table_info(task_handoff_origin)").all() as { name: string }[]).some(c => c.name === column)) this.db.run(`ALTER TABLE task_handoff_origin ADD COLUMN ${column} ${type}`); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS task_handoff_origin_key ON task_handoff_origin(project_id, handoff_key) WHERE handoff_key IS NOT NULL"); this.db.run(`CREATE TABLE IF NOT EXISTS task_handoff_outbound (remote_project TEXT NOT NULL, remote_task INTEGER NOT NULL, origin_peer TEXT NOT NULL, local_task INTEGER, title TEXT NOT NULL, last_state TEXT NOT NULL, pr INTEGER, head TEXT, updated_at INTEGER NOT NULL, PRIMARY KEY(remote_project, remote_task))`); // #733: the sequence of the last applied event, so an event that arrives late cannot move a row backwards. Rows from before keep NULL and accept any event. if (!(this.db.query("PRAGMA table_info(task_handoff_outbound)").all() as { name: string }[]).some(c => c.name === "seq")) this.db.run("ALTER TABLE task_handoff_outbound ADD COLUMN seq INTEGER"); this.db.run(`CREATE TABLE IF NOT EXISTS research_handoffs ( campaign_id TEXT NOT NULL, unit_id TEXT NOT NULL, seq INTEGER NOT NULL, revision INTEGER NOT NULL, task_id INTEGER NOT NULL, body TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL, PRIMARY KEY(campaign_id,unit_id,seq))`); this.db.run(`CREATE TABLE IF NOT EXISTS research_evidence_links ( project TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, task_id INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(project,id,revision))`); // Private snapshots stay outside Task and every SELECT * task reader. this.db.run(`CREATE TABLE IF NOT EXISTS guidance_experiments ( project_id TEXT NOT NULL,task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,experiment_id TEXT NOT NULL,baseline_json TEXT NOT NULL, PRIMARY KEY(project_id,task_id,task_created,experiment_id))`); this.db.run(`CREATE TABLE IF NOT EXISTS guidance_variants ( project_id TEXT NOT NULL,task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,experiment_id TEXT NOT NULL,id TEXT NOT NULL, body TEXT NOT NULL,body_sha256 TEXT NOT NULL,created_by TEXT NOT NULL,created_at INTEGER NOT NULL,withdrawn_by TEXT,withdrawn_at INTEGER, PRIMARY KEY(project_id,task_id,task_created,experiment_id,id))`); this.db.run(`CREATE TABLE IF NOT EXISTS execution_reference_links ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL, from_json TEXT NOT NULL, from_sha256 TEXT NOT NULL, reference_json TEXT NOT NULL, reference_sha256 TEXT NOT NULL, recorded_by TEXT NOT NULL, recorded_at INTEGER NOT NULL, UNIQUE(project_id,task_id,task_created,from_sha256,reference_sha256))`); this.db.run("CREATE INDEX IF NOT EXISTS execution_reference_task_scope ON execution_reference_links(project_id,task_id,task_created,id)"); this.db.run("CREATE INDEX IF NOT EXISTS guidance_variant_task_id ON guidance_variants(project_id,task_id,task_created,id)"); // Private additive survey/considered state, never copied into task projections or an unconditional format floor. this.db.run(`CREATE TABLE IF NOT EXISTS advisor_surveys ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, task_created INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, withheld INTEGER NOT NULL DEFAULT 0, UNIQUE(task_id,task_created))`); this.db.run(`CREATE TABLE IF NOT EXISTS advisor_survey_findings ( survey INTEGER NOT NULL, finding_id TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(survey,finding_id))`); this.db.run(`CREATE TABLE IF NOT EXISTS considered_findings ( id INTEGER PRIMARY KEY AUTOINCREMENT, repo TEXT NOT NULL, finding_id TEXT NOT NULL, pass TEXT NOT NULL, kind TEXT NOT NULL, 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)`); this.db.run("CREATE INDEX IF NOT EXISTS considered_finding_identity ON considered_findings(repo,finding_id,pass,id)"); // #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. this.db.run(`CREATE TABLE IF NOT EXISTS security_audits ( 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, scoped INTEGER NOT NULL, at INTEGER NOT NULL, by_peer TEXT NOT NULL, units TEXT NOT NULL, UNIQUE(task_id,task_created))`); this.db.run(`CREATE TABLE IF NOT EXISTS security_audit_findings ( 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, verified_by TEXT, rejected_by TEXT, settled_by TEXT, settled_as TEXT, PRIMARY KEY(audit,seq), UNIQUE(audit,finding_id))`); // #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. 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`); this.db.run(`CREATE TABLE IF NOT EXISTS review_comments ( 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, PRIMARY KEY(task_id,task_created,id))`); this.db.run("CREATE INDEX IF NOT EXISTS review_comments_sent ON review_comments(task_id,task_created,id) WHERE lifecycle='sent'"); this.db.run(`CREATE TABLE IF NOT EXISTS review_comment_packages ( id TEXT PRIMARY KEY,task_id INTEGER NOT NULL,task_created INTEGER NOT NULL,body TEXT NOT NULL)`); this.db.run("CREATE INDEX IF NOT EXISTS review_comment_packages_owner ON review_comment_packages(CASE WHEN json_valid(body)=1 THEN json_extract(body,'$.owner') END,task_id,task_created)"); this.db.run(`CREATE TABLE IF NOT EXISTS research_protocols ( hash TEXT PRIMARY KEY, project TEXT NOT NULL, campaign_id TEXT NOT NULL, campaign_revision INTEGER NOT NULL, task_id INTEGER NOT NULL, body TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL)`); this.db.run(`CREATE TABLE IF NOT EXISTS research_attempts ( attempt_id TEXT PRIMARY KEY, project TEXT NOT NULL, campaign_id TEXT NOT NULL, campaign_revision INTEGER NOT NULL, protocol_hash TEXT NOT NULL, task_id INTEGER NOT NULL, idempotency_key TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL, UNIQUE(project,idempotency_key))`); this.db.run("CREATE INDEX IF NOT EXISTS research_attempts_campaign ON research_attempts(project,campaign_id)"); this.db.run(`CREATE TABLE IF NOT EXISTS research_attempt_events ( attempt_id TEXT NOT NULL, project TEXT NOT NULL, seq INTEGER NOT NULL, idempotency_key TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL, PRIMARY KEY(attempt_id,seq), UNIQUE(project,idempotency_key))`); this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS research_attempt_one_end ON research_attempt_events(attempt_id) WHERE kind='end'"); this.db.run("CREATE INDEX IF NOT EXISTS research_attempt_private_event ON research_attempt_events(attempt_id) WHERE private=1"); this.db.run(`CREATE TABLE IF NOT EXISTS research_attempt_observations ( attempt_id TEXT NOT NULL, event_seq INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, PRIMARY KEY(attempt_id,event_seq))`); this.db.run(`CREATE TABLE IF NOT EXISTS research_runner_receipts ( receipt_id TEXT PRIMARY KEY, project TEXT NOT NULL, attempt_id TEXT NOT NULL, event_seq INTEGER NOT NULL, body TEXT NOT NULL, body_sha256 TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL, UNIQUE(attempt_id,event_seq))`); this.db.run(`CREATE TABLE IF NOT EXISTS research_plans ( hash TEXT PRIMARY KEY, project TEXT NOT NULL, campaign_id TEXT NOT NULL, campaign_revision INTEGER NOT NULL, task_id INTEGER NOT NULL, body TEXT NOT NULL, by_peer TEXT NOT NULL, at INTEGER NOT NULL, private INTEGER NOT NULL)`); this.db.run("CREATE INDEX IF NOT EXISTS research_plans_campaign ON research_plans(project,campaign_id)"); this.db.run(`CREATE TABLE IF NOT EXISTS research_protocol_approvals ( protocol_hash TEXT PRIMARY KEY, evaluator_hash TEXT NOT NULL, approved_by TEXT NOT NULL, at INTEGER NOT NULL)`); this.db.run(`CREATE TABLE IF NOT EXISTS research_protocol_context ( protocol_hash TEXT PRIMARY KEY, prior_attempt_id TEXT, prior_end_seq INTEGER, context_sha256 TEXT NOT NULL)`); } /** #604: a handoff row exists in either direction, so a recovery target must know `task_handoff`. */ hasHandoffState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM task_handoff_origin) OR EXISTS(SELECT 1 FROM task_handoff_outbound) AS present").get() as { present: number }).present === 1; } /** TARGET side: where one of this project's tasks came from. The origin peer is a record, never a roster peer or an actor. */ handoffOrigin(taskId: number): { projectId: string; peer: string; originTask: number | null; at: number } | undefined { const row = this.db.query("SELECT project_id, peer, origin_task, at FROM task_handoff_origin WHERE task_id=?").get(taskId) as { project_id: string; peer: string; origin_task: number | null; at: number } | null; return row ? { projectId: row.project_id, peer: row.peer, originTask: row.origin_task, at: row.at } : undefined; } setHandoffOrigin(taskId: number, origin: { projectId: string; peer: string; originTask?: number }): void { this.db.query("INSERT INTO task_handoff_origin(task_id, project_id, peer, origin_task, at) VALUES(?,?,?,?,?) ON CONFLICT(task_id) DO NOTHING").run(taskId, origin.projectId, origin.peer, origin.originTask ?? null, Date.now()); } /** * #731: the task a handoff key already made for this origin project, with the digest of the request that made it, or undefined. A read: a replayed key is answered from here. */ handoffOriginByKey(projectId: string, key: string): { taskId: number; digest: string | null } | undefined { const row = this.db.query("SELECT task_id, request_digest FROM task_handoff_origin WHERE project_id=? AND handoff_key=?").get(projectId, key) as { task_id: number; request_digest: string | null } | null; return row ? { taskId: row.task_id, digest: row.request_digest } : undefined; } /** * #731 (H9): the proposal and its origin row in ONE transaction, so a crash or a failure between them can never leave a task with no origin (which the origin could then never be told about), * and a replayed key answers with the task it already made instead of filing a second one. The unique index is the last guard: even two writers of one key cannot both commit. * Observers (`onChange`) run after the commit, as for every other multi-row write. */ proposeHandoff(by: PeerId, t: Parameters[1], origin: { projectId: string; peer: string; originTask?: number; key?: string; digest?: string }): { task: Task; replayed: boolean } { return this.atomic(() => { if (origin.key !== undefined) { const existing = this.handoffOriginByKey(origin.projectId, origin.key); if (existing) { const task = this.get(existing.taskId); if (task) return { task, replayed: true }; } } const task = this.propose(by, t); this.db.query("INSERT INTO task_handoff_origin(task_id, project_id, peer, origin_task, at, handoff_key, request_digest) VALUES(?,?,?,?,?,?,?)") .run(task.id, origin.projectId, origin.peer, origin.originTask ?? null, Date.now(), origin.key ?? null, origin.digest ?? null); return { task, replayed: false }; }); } /** * ORIGIN side: what this project handed to another one, newest first, for the person's list (`ahub board --handoffs`). Keyed by the target project and its task id, so a repeated event updates * one row. Capped for display only: the catch-up never reads this (`handoffOutboundOpen`), so a row the list does not show is still caught up (#733). */ handoffOutbound(): HandoffOutboundRow[] { return (this.db.query(`SELECT ${OUTBOUND_COLUMNS} FROM task_handoff_outbound ORDER BY updated_at DESC, remote_project, remote_task LIMIT 200`).all() as Record[]).map(handoffOutboundFromRow); } /** #733 (H5): every row the catch-up still asks about, no cap, oldest first so a long backlog is worked through in the same order every pass. The caller filters with `handoffCatchUpRow`. */ handoffOutboundOpen(): HandoffOutboundRow[] { return (this.db.query(`SELECT ${OUTBOUND_COLUMNS} FROM task_handoff_outbound WHERE last_state != 'cancelled' ORDER BY updated_at, remote_project, remote_task`).all() as Record[]).map(handoffOutboundFromRow); } handoffOutboundFor(remoteProject: string, remoteTask: number): HandoffOutboundRow | undefined { const row = this.db.query(`SELECT ${OUTBOUND_COLUMNS} FROM task_handoff_outbound WHERE remote_project=? AND remote_task=?`).get(remoteProject, remoteTask) as Record | null; return row ? handoffOutboundFromRow(row) : undefined; } /** * Record a state. With a `seq` the write applies only when it is newer than the stored one (#733 H4: events use a connection each and can arrive out of order), decided inside the one statement so * two events cannot both pass a check made before either wrote. Returns whether the row changed. An event with no `seq` (an older target, or the origin's own first write) behaves as before: * it applies, and keeps the highest `seq` already stored. */ recordHandoffOutbound(row: { remoteProject: string; remoteTask: number; originPeer: string; localTask?: number; title: string; state: string; pr?: number; head?: string; seq?: number }): { applied: boolean } { const result = this.db.query(`INSERT INTO task_handoff_outbound(remote_project, remote_task, origin_peer, local_task, title, last_state, pr, head, updated_at, seq) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(remote_project, remote_task) DO UPDATE SET last_state=excluded.last_state, pr=COALESCE(excluded.pr, pr), head=COALESCE(excluded.head, head), updated_at=excluded.updated_at, seq=COALESCE(MAX(excluded.seq, seq), excluded.seq, seq) WHERE excluded.seq IS NULL OR seq IS NULL OR excluded.seq > seq`) .run(row.remoteProject, row.remoteTask, row.originPeer, row.localTask ?? null, row.title, row.state, row.pr ?? null, row.head ?? null, Date.now(), row.seq ?? null); return { applied: result.changes > 0 }; } /** A digest over both tables, so a recovery that restores or loses a row is seen. */ handoffIntegrity(): { origins: number; outbound: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.handoff-integrity/v1\n"); let origins = 0, outbound = 0; for (const row of this.db.query("SELECT task_id, project_id, peer, origin_task, at, handoff_key, request_digest FROM task_handoff_origin ORDER BY task_id").iterate() as Iterable>) { // A row from before handoff keys has no key columns in its digest, so an upgrade does not change what a recovery compares (#731). if (row.handoff_key === null) { delete row.handoff_key; delete row.request_digest; } digest.update(JSON.stringify(row)).update("\n"); origins++; } for (const row of this.db.query(`SELECT ${OUTBOUND_COLUMNS} FROM task_handoff_outbound ORDER BY remote_project, remote_task`).iterate() as Iterable>) { if (row.seq === null) delete row.seq; // a row from before sequences keeps its digest (#733) digest.update(JSON.stringify(row)).update("\n"); outbound++; } return { origins, outbound, digest: digest.digest("hex") }; })(); } /** #601: the ids of a project's campaigns, oldest first, for `ahub study show` with no id. A read: no row is written. */ researchCampaignIds(project: string): string[] { if (!researchText(project)) throw researchFailure(); return (this.db.query("SELECT DISTINCT id FROM research_campaigns WHERE project=? ORDER BY id").all(project) as { id: string }[]).map(row => row.id); } /** * One page of a project's campaign ids, in id order: at most `limit` (never more than 50, the spec's readback bound) strictly after the cursor `after`. `next` is the last id of a full page that * has more behind it, to pass as the next `after`; absent when this is the last page. The query itself carries the bound, so a project with many drafts costs one page, not all of them. */ researchCampaignPage(project: string, after?: string, limit = 50): { ids: string[]; next?: string } { if (!researchText(project) || after !== undefined && !researchId(after) || !Number.isSafeInteger(limit) || limit < 1) throw researchFailure(); const size = Math.min(limit, 50); const rows = this.db.query("SELECT DISTINCT id FROM research_campaigns WHERE project=? AND id>? ORDER BY id LIMIT ?").all(project, after ?? "", size + 1) as { id: string }[]; const ids = rows.slice(0, size).map(row => row.id); return rows.length > size ? { ids, next: ids[ids.length - 1]! } : { ids }; } researchCampaign(id: string, revision?: number): ResearchCampaignRecord | undefined { if (!researchId(id) || revision !== undefined && !researchInteger(revision)) throw researchFailure(); const row = (revision === undefined ? this.db.query(`${RESEARCH_CAMPAIGN_SELECT} WHERE id=? ORDER BY revision DESC LIMIT 1`).get(id) : this.db.query(`${RESEARCH_CAMPAIGN_SELECT} WHERE id=? AND revision=?`).get(id, revision)) as ResearchCampaignRow | null; if (!row) return undefined; const campaign = researchCampaignFromRow(row); const dispatch = this.db.query("SELECT version,CASE WHEN length(CAST(eligible_owners AS BLOB))<=32768 OR eligible_owners IS NULL THEN eligible_owners ELSE '!' END AS eligible_owners FROM research_dispatch WHERE campaign_id=? AND revision=?") .get(id, campaign.revision) as { version: number; eligible_owners: string | null } | null; if (!dispatch) return campaign; if (dispatch.version !== 1 || campaign.approvedBy === undefined) throw researchFailure(); let owners: string[] | undefined; if (dispatch.eligible_owners !== null) { try { owners = JSON.parse(dispatch.eligible_owners) as string[]; } catch { throw researchFailure(); } if (!Array.isArray(owners) || owners.length < 1 || owners.length > 256 || owners.some(owner => !researchText(owner, 64) || !/^[a-z][a-z0-9_-]{0,63}$/.test(owner)) || new Set(owners).size !== owners.length) throw researchFailure(); } if (!!campaign.contract.budget?.hardCap.length !== !!owners?.length) throw researchFailure(); return { ...campaign, dispatchVersion: 1, ...(owners ? { eligibleOwners: owners } : {}) }; } private researchBindings(campaign: ResearchCampaignRecord): ResearchUnitBinding[] { const rows = this.db.query("SELECT campaign_id,revision,unit_id,task_id,round,purpose,adopted FROM research_units WHERE campaign_id=? AND revision=? ORDER BY unit_id LIMIT 33").all(campaign.id, campaign.revision) as ResearchUnitRow[]; const expected = new Map(campaign.contract.units.map(unit => [unit.id, unit])); if (rows.length > 32 || rows.length !== (campaign.approvedBy === undefined ? 0 : expected.size)) throw researchFailure(); const tasks = new Set(); return rows.map(row => { const unit = expected.get(row.unit_id); if (!unit || row.campaign_id !== campaign.id || row.revision !== campaign.revision || !researchInteger(row.task_id) || tasks.has(row.task_id) || row.round !== unit.round || row.purpose !== unit.purpose || ![0, 1].includes(row.adopted) || (row.adopted === 1) !== (unit.adoptTaskId !== undefined) || unit.adoptTaskId !== undefined && unit.adoptTaskId !== row.task_id) throw researchFailure(); tasks.add(row.task_id); return { campaignId: row.campaign_id, revision: row.revision, unitId: row.unit_id, taskId: row.task_id, round: row.round, purpose: unit.purpose, adopted: row.adopted === 1 }; }); } researchCampaignBindings(id: string, revision: number): ResearchUnitBinding[] { const campaign = this.researchCampaign(id, revision); return campaign ? this.researchBindings(campaign) : []; } /** Most recent persisted association, including a unit omitted from intervening revisions. */ researchLatestUnitBinding(campaignId: string, unitId: string): ResearchUnitBinding | undefined { if (!researchId(campaignId) || typeof unitId !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(unitId)) throw researchFailure(); const row = this.db.query("SELECT revision FROM research_units WHERE campaign_id=? AND unit_id=? ORDER BY revision DESC LIMIT 1") .get(campaignId, unitId) as { revision: number } | null; if (!row) return undefined; const campaign = this.researchCampaign(campaignId, row.revision); if (!campaign) throw researchFailure(); const binding = this.researchBindings(campaign).find(unit => unit.unitId === unitId); if (!binding) throw researchFailure(); return binding; } /** Lifetime unit association, including superseded/closed revisions; never reinterpret a task as another unit. */ researchTaskBinding(taskId: number): ResearchUnitBinding | undefined { if (!researchInteger(taskId)) throw researchFailure(); const row = this.db.query("SELECT campaign_id,revision FROM research_units WHERE task_id=? ORDER BY campaign_id,revision,unit_id LIMIT 1").get(taskId) as { campaign_id: string; revision: number } | null; if (!row) return undefined; const campaign = this.researchCampaign(row.campaign_id, row.revision); if (!campaign) throw researchFailure(); const binding = this.researchBindings(campaign).find(unit => unit.taskId === taskId); if (!binding) throw researchFailure(); return binding; } /** Resolve lifetime membership against the latest revision; an omitted unit or a draft never inherits old dispatch approval. */ researchDispatchBinding(taskId: number): { campaign: ResearchCampaignRecord; binding?: ResearchUnitBinding } | undefined { if (!researchInteger(taskId)) throw researchFailure(); const rows = this.db.query("SELECT DISTINCT campaign_id FROM research_units WHERE task_id=? ORDER BY campaign_id LIMIT 2").all(taskId) as { campaign_id: string }[]; if (!rows.length) return undefined; if (rows.length !== 1) throw researchFailure(); const campaign = this.researchCampaign(rows[0]!.campaign_id); if (!campaign) throw researchFailure(); const binding = this.researchBindings(campaign).find(unit => unit.taskId === taskId); return { campaign, ...(binding ? { binding } : {}) }; } private researchHandoffFromRow(row: ResearchHandoffRow): ResearchHandoffRecord { try { if (typeof row.body !== "string" || Buffer.byteLength(row.body, "utf8") > 65536 || !researchInteger(row.seq) || !researchInteger(row.at, 0) || !researchText(row.by_peer) || ![0, 1].includes(row.private)) throw researchFailure(); const handoff = parseResearchHandoff(JSON.parse(row.body)), campaign = this.researchCampaign(row.campaign_id, row.revision); const unit = campaign?.contract.units.find(value => value.id === row.unit_id); const binding = campaign && this.researchBindings(campaign).find(value => value.unitId === row.unit_id); if (!campaign || !unit || !binding || handoff.campaignId !== row.campaign_id || handoff.revision !== row.revision || handoff.unitId !== row.unit_id || handoff.taskId !== row.task_id || binding.taskId !== row.task_id || handoff.evidence.some(entry => !unit.sourceIds.includes(entry.sourceId)) || handoff.contradictions.some(entry => entry.sourceIds.some(source => !unit.sourceIds.includes(source)))) throw researchFailure(); return { handoff, seq: row.seq, by: row.by_peer, at: row.at, private: row.private === 1 || campaign.private }; } catch { throw researchFailure(); } } /** At most one latest handoff per unit; history remains append-only and older stable-unit evidence survives a revision. */ researchHandoffs(campaignId: string, revision?: number): ResearchHandoffRecord[] { const campaign = this.researchCampaign(campaignId, revision); if (!campaign) return []; const rows = this.db.query(`SELECT campaign_id,unit_id,seq,revision,task_id, CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,by_peer,at,private FROM research_handoffs AS h WHERE campaign_id=? AND revision<=? AND unit_id IN (${campaign.contract.units.map(() => "?").join(",")}) AND seq=(SELECT MAX(seq) FROM research_handoffs AS old WHERE old.campaign_id=h.campaign_id AND old.unit_id=h.unit_id AND old.revision<=?) ORDER BY unit_id LIMIT 33`) .all(campaignId, campaign.revision, ...campaign.contract.units.map(unit => unit.id), campaign.revision) as ResearchHandoffRow[]; if (rows.length > 32) throw researchFailure(); return rows.map(row => this.researchHandoffFromRow(row)).filter(row => campaign.contract.units.some(unit => unit.id === row.handoff.unitId)); } /** Caller authority/privacy screening belongs to Tasks; the transaction re-checks every persisted binding and ownership fact. */ recordResearchHandoff(input: ResearchHandoffV1, project: string, by: PeerId, at: number, expectedTaskFlow: number): ResearchHandoffRecord { const handoff = parseResearchHandoff(input); if (!researchText(project) || !researchText(by) || !researchInteger(at, 0) || !researchInteger(expectedTaskFlow, 0)) throw researchFailure(); return this.atomic(() => { const current = this.researchDispatchBinding(handoff.taskId), campaign = current?.campaign, binding = current?.binding; const task = this.get(handoff.taskId), unit = campaign?.contract.units.find(value => value.id === handoff.unitId); if (!campaign || campaign.id !== handoff.campaignId || campaign.revision !== handoff.revision || campaign.status !== "approved" || campaign.project !== project || !binding || binding.unitId !== handoff.unitId || !unit || !task || task.owner !== by || task.state !== "in_progress" || task.history.length !== expectedTaskFlow || handoff.evidence.some(entry => !unit.sourceIds.includes(entry.sourceId)) || handoff.contradictions.some(entry => entry.sourceIds.some(source => !unit.sourceIds.includes(source)))) throw researchFailure(); const last = this.db.query("SELECT MAX(seq) AS seq FROM research_handoffs WHERE campaign_id=? AND unit_id=?").get(campaign.id, unit.id) as { seq: number | null }; const seq = (last.seq ?? 0) + 1; if (!researchInteger(seq)) throw researchFailure(); const privateRecord = campaign.private || task.signals.some(signal => signal === "pii" || signal === "pii_path"); this.taskWrite(() => this.db.query("INSERT INTO research_handoffs(campaign_id,unit_id,seq,revision,task_id,body,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?)") .run(campaign.id, unit.id, seq, campaign.revision, task.id, JSON.stringify(handoff), by, at, privateRecord ? 1 : 0)); this.update(task.id, by, "study handoff", {}, `${campaign.id} revision ${campaign.revision}; evidence ${handoff.evidence.length}`, {}, expectedTaskFlow); return { handoff, seq, by, at, private: privateRecord }; }); } hasResearchDispatchState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_campaigns) OR EXISTS(SELECT 1 FROM research_units) OR EXISTS(SELECT 1 FROM research_dispatch) OR EXISTS(SELECT 1 FROM research_handoffs) AS present").get() as { present: number }).present === 1; } /** #603: a persisted study re-offer needs a target that knows `research_dropped_offers`; `research_dispatch` alone does not (the additive floor rule). */ hasResearchDroppedOffers(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_dropped_offers) AS present").get() as { present: number }).present === 1; } researchDispatchIntegrity(): { activations: number; handoffs: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.research-dispatch-integrity/v1\n"); let activations = 0, handoffs = 0; for (const row of this.db.query("SELECT campaign_id,revision,version,eligible_owners FROM research_dispatch ORDER BY campaign_id,revision").iterate() as Iterable<{ campaign_id: string; revision: number; version: number; eligible_owners: string | null }>) { const campaign = this.researchCampaign(row.campaign_id, row.revision); if (!campaign || campaign.dispatchVersion !== 1) throw researchFailure(); digest.update(JSON.stringify(row)).update("\n"); activations++; } for (const row of this.db.query("SELECT campaign_id,unit_id,seq,revision,task_id,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,by_peer,at,private FROM research_handoffs ORDER BY campaign_id,unit_id,seq").iterate() as Iterable) { const record = this.researchHandoffFromRow(row); digest.update(JSON.stringify(record)).update("\n"); handoffs++; } // Dropped-offer rows join the digest only when there are any, so a project without one keeps the digest it always had. for (const row of this.db.query("SELECT task_id,owner FROM research_dropped_offers ORDER BY task_id").iterate() as Iterable<{ task_id: number; owner: string }>) { this.droppedOfferRow(row); digest.update("dropped-offer\n").update(JSON.stringify(row)).update("\n"); } return { activations, handoffs, digest: digest.digest("hex") }; })(); } /** A row names a task bound to a research unit in some revision (the drop happens while a newer draft has no binding yet) and a peer id; anything else is corrupt state. */ private droppedOfferRow(row: { task_id: number; owner: string }): { taskId: number; owner: string } { if (!researchInteger(row.task_id) || !researchText(row.owner, 64) || !/^[a-z][a-z0-9_-]{0,63}$/.test(row.owner) || !this.db.query("SELECT 1 FROM research_units WHERE task_id=? LIMIT 1").get(row.task_id)) throw researchFailure(); return { taskId: row.task_id, owner: row.owner }; } /** #603: remember that a study hold discarded this owner's queued offer for the task. One row per task; a later drop replaces it. */ recordResearchDroppedOffer(taskId: number, owner: string): void { this.droppedOfferRow({ task_id: taskId, owner }); this.db.query("INSERT INTO research_dropped_offers(task_id,owner) VALUES(?,?) ON CONFLICT(task_id) DO UPDATE SET owner=excluded.owner").run(taskId, owner); } researchDroppedOffer(taskId: number): string | undefined { if (!researchInteger(taskId)) throw researchFailure(); const row = this.db.query("SELECT task_id,owner FROM research_dropped_offers WHERE task_id=?").get(taskId) as { task_id: number; owner: string } | null; return row ? this.droppedOfferRow(row).owner : undefined; } clearResearchDroppedOffer(taskId: number): void { if (!researchInteger(taskId)) throw researchFailure(); this.db.query("DELETE FROM research_dropped_offers WHERE task_id=?").run(taskId); } /** Bodies are append-only; a new revision cannot change its project's or parent's identity or lower privacy. */ saveResearchCampaignDraft(record: ResearchCampaignRecord, expectedLatest: number | undefined, expectedParentFlow: number): ResearchCampaignRecord { const checked = checkedResearchCampaign(record); if (checked.status !== "draft" || checked.approvedBy !== undefined || checked.closedBy !== undefined || expectedLatest !== undefined && !researchInteger(expectedLatest) || checked.revision !== (expectedLatest ?? 0) + 1 || !researchInteger(expectedParentFlow, 0)) throw researchFailure(); return this.atomic(() => { const parent = this.get(checked.parentTaskId), latest = this.researchCampaign(checked.id); if (!parent || parent.history.length !== expectedParentFlow || latest?.revision !== expectedLatest || latest && (latest.project !== checked.project || latest.parentTaskId !== checked.parentTaskId || latest.status === "closed")) throw researchFailure(); const stored = { ...checked, private: checked.private || latest?.private === true }; this.taskWrite(() => this.db.query("INSERT INTO research_campaigns(id,project,parent_task_id,revision,status,body,body_sha256,private,created_by,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)") .run(stored.id, stored.project, stored.parentTaskId, stored.revision, "draft", JSON.stringify(stored.contract), stored.hash, stored.private ? 1 : 0, stored.createdBy, stored.createdAt)); this.update(parent.id, stored.createdBy, latest ? "study revised" : "study drafted", {}, `${stored.id} revision ${stored.revision}`, {}, expectedParentFlow); return this.researchCampaign(stored.id, stored.revision)!; }); } /** An approved replay recreates nothing; only monotone privacy tightening may write, without task history or approval changes. */ activateCampaign(id: string, revision: number, project: string, by: PeerId, at: number, prepared: readonly PreparedResearchUnit[], expectedParentFlow: number, privateRecord = false, dispatch?: { eligibleOwners?: readonly string[] }): { campaign: ResearchCampaignRecord; bindings: ResearchUnitBinding[]; children: Task[] } { if (!researchText(project) || !researchText(by) || !researchInteger(at, 0) || typeof privateRecord !== "boolean") throw researchFailure(); return this.atomic(() => { const campaign = this.researchCampaign(id, revision); if (!campaign || campaign.project !== project) throw researchFailure(); if (campaign.status === "approved") { const bindings = this.researchBindings(campaign); if (privateRecord && !campaign.private) this.taskWrite(() => this.db.query("UPDATE research_campaigns SET private=1 WHERE id=? AND revision=? AND private=0").run(id, revision)); return { campaign: this.researchCampaign(id, revision)!, bindings, children: [] }; } const owners = dispatch?.eligibleOwners === undefined ? undefined : [...dispatch.eligibleOwners]; if (owners && (owners.length < 1 || owners.length > 256 || owners.some(owner => !researchText(owner, 64) || !/^[a-z][a-z0-9_-]{0,63}$/.test(owner)) || new Set(owners).size !== owners.length) || dispatch !== undefined && !!campaign.contract.budget?.hardCap.length !== !!owners?.length) throw researchFailure(); const parent = this.get(campaign.parentTaskId), latest = this.researchCampaign(id); const activeRow = this.db.query("SELECT revision FROM research_campaigns WHERE id=? AND status='approved' LIMIT 1").get(id) as { revision: number } | null; const active = activeRow ? this.researchCampaign(id, activeRow.revision) : undefined; if (campaign.status !== "draft" || latest?.revision !== revision || !researchInteger(expectedParentFlow, 0) || !parent || parent.history.length !== expectedParentFlow) throw researchFailure(); if (this.db.query("SELECT 1 FROM research_campaigns WHERE project=? AND parent_task_id=? AND status='approved' AND id<>? LIMIT 1").get(project, campaign.parentTaskId, id)) throw new Error("another research campaign is active for this parent"); if (this.researchBindings(campaign).length || prepared.length !== campaign.contract.units.length) throw researchFailure(); const inputs = new Map(), units = new Map(campaign.contract.units.map(unit => [unit.id, unit])); const mapped = new Map(), retained = new Map(), children: Task[] = []; const isPrivate = campaign.private || privateRecord; for (const entry of prepared) { const unit = units.get(entry.unitId); if (!unit || inputs.has(entry.unitId) || [entry.create, entry.adopt, entry.reuse].filter(value => value !== undefined).length !== 1) throw researchFailure(); inputs.set(entry.unitId, entry); const prior = this.researchLatestUnitBinding(id, unit.id); if (prior) { const previous = this.researchCampaign(id, prior.revision), previousUnit = previous?.contract.units.find(value => value.id === unit.id); if (!entry.reuse || entry.reuse.taskId !== prior.taskId || !researchInteger(entry.reuse.flowRevision, 0) || prior.revision >= revision || !previous || previous.project !== project || previous.parentTaskId !== campaign.parentTaskId || JSON.stringify(previousUnit) !== JSON.stringify(unit)) throw new Error("a bound research unit must retain its task and definition; changed work requires a fresh unit id"); const task = this.get(prior.taskId); if (!task || task.history.length !== entry.reuse.flowRevision || isPrivate && !task.signals.some(signal => signal === "pii" || signal === "pii_path")) throw researchFailure(); mapped.set(unit.id, task.id); retained.set(unit.id, task); } else if (entry.reuse) { throw researchFailure(); } else if (entry.adopt) { if (unit.adoptTaskId !== entry.adopt.taskId || !researchInteger(entry.adopt.flowRevision, 0)) throw researchFailure(); const task = this.get(entry.adopt.taskId); if (!task || task.history.length !== entry.adopt.flowRevision || task.draft || !task.history.some(history => history.event === "draft approved") || isPrivate && !task.signals.some(signal => signal === "pii" || signal === "pii_path")) throw researchFailure(); if (this.db.query("SELECT 1 FROM research_units WHERE task_id=? AND (campaign_id<>? OR unit_id<>?) LIMIT 1").get(task.id, id, unit.id)) throw new Error("intake task is already bound to another research unit"); mapped.set(unit.id, task.id); retained.set(unit.id, task); } else { const create = entry.create!; if (unit.adoptTaskId !== undefined || typeof create.title !== "string" || !create.title.trim() || create.title.length > 300 || !CLASSES.includes(create.class) || create.draft || isPrivate && !create.signals?.includes("pii")) throw researchFailure(); } } const pending = campaign.contract.units.filter(unit => !mapped.has(unit.id)); while (pending.length) { const next = pending.findIndex(unit => unit.dependsOn.every(dependency => mapped.has(dependency))); if (next < 0) throw researchFailure(); const unit = pending.splice(next, 1)[0]!, create = inputs.get(unit.id)!.create!; const deps = [...new Set([...(create.deps ?? []), ...unit.dependsOn.map(dependency => mapped.get(dependency)!)])]; if (deps.some(dependency => !researchInteger(dependency) || !this.get(dependency))) throw researchFailure(); const child = this.propose(by, { ...create, deps, backlog: true, draft: false }); mapped.set(unit.id, child.id); children.push(child); } for (const [unitId, task] of retained) if (units.get(unitId)!.dependsOn.some(dependency => !task.deps?.includes(mapped.get(dependency)!))) throw new Error("retained research task dependencies differ from the campaign"); for (const unit of campaign.contract.units) { const taskId = mapped.get(unit.id)!; if (this.db.query("SELECT 1 FROM research_units WHERE task_id=? AND (campaign_id<>? OR unit_id<>?) LIMIT 1").get(taskId, id, unit.id)) throw researchFailure(); this.taskWrite(() => this.db.query("INSERT INTO research_units(campaign_id,revision,unit_id,task_id,round,purpose,adopted) VALUES(?,?,?,?,?,?,?)") .run(id, revision, unit.id, taskId, unit.round, unit.purpose, unit.adoptTaskId !== undefined ? 1 : 0)); } this.taskWrite(() => this.db.query("UPDATE research_campaigns SET status='superseded',private=MAX(private,?) WHERE id=? AND project=? AND status='approved'").run(isPrivate ? 1 : 0, id, project)); this.taskWrite(() => this.db.query("UPDATE research_campaigns SET status='approved',approved_by=?,approved_at=?,private=? WHERE id=? AND revision=? AND status='draft'") .run(by, at, isPrivate ? 1 : 0, id, revision)); if (dispatch !== undefined) this.taskWrite(() => this.db.query("INSERT INTO research_dispatch(campaign_id,revision,version,eligible_owners) VALUES(?,?,1,?)") .run(id, revision, owners === undefined ? null : JSON.stringify(owners))); const nextUnits = new Set(campaign.contract.units.map(unit => unit.id)); const nextEdges = new Set(campaign.contract.units.flatMap(unit => unit.dependsOn.map(dependency => `${unit.id}:${dependency}`))); const omittedUnits = active?.contract.units.filter(unit => !nextUnits.has(unit.id)).length ?? 0; const omittedEdges = active?.contract.units.flatMap(unit => unit.dependsOn.map(dependency => `${unit.id}:${dependency}`)).filter(edge => !nextEdges.has(edge)).length ?? 0; this.update(parent.id, by, "study approved", {}, `${id} revision ${revision}; omitted units ${omittedUnits}, dependencies ${omittedEdges}`, {}, expectedParentFlow); const approved = this.researchCampaign(id, revision)!; return { campaign: approved, bindings: this.researchBindings(approved), children }; }); } closeCampaign(id: string, revision: number, project: string, by: PeerId, at: number, reason: string, expectedParentFlow: number, privateRecord = false): ResearchCampaignRecord { if (!researchText(project) || !researchText(by) || !researchInteger(at, 0) || !researchText(reason, 4096) || typeof privateRecord !== "boolean") throw researchFailure(); return this.atomic(() => { const campaign = this.researchCampaign(id, revision), latest = this.researchCampaign(id); if (!campaign || campaign.project !== project || latest?.revision !== revision) throw researchFailure(); if (campaign.status === "closed") { if (privateRecord && !campaign.private) this.taskWrite(() => this.db.query("UPDATE research_campaigns SET private=1 WHERE id=? AND revision=? AND private=0").run(id, revision)); return this.researchCampaign(id, revision)!; } const parent = this.get(campaign.parentTaskId); if (!researchInteger(expectedParentFlow, 0) || !parent || parent.history.length !== expectedParentFlow) throw researchFailure(); this.taskWrite(() => this.db.query("UPDATE research_campaigns SET status='closed',closed_by=?,closed_at=?,closed_reason=?,private=MAX(private,?) WHERE id=? AND project=? AND (revision=? OR status='approved')") .run(by, at, reason, campaign.private || privateRecord ? 1 : 0, id, project, revision)); this.update(parent.id, by, "study closed", {}, `${id} revision ${revision}`, {}, expectedParentFlow); return this.researchCampaign(id, revision)!; }); } /** Immutable declared link revisions. Caller/source/privacy admission belongs to Tasks. */ evidenceLink(project: string, id: string, revision?: number): EvidenceLinkV1 | undefined { if (!researchText(project) || !/^ev:[a-f0-9]{32}$/.test(id) || revision !== undefined && !researchInteger(revision)) throw new Error("invalid evidence identity; use the recorded evidence id and revision"); const row = this.db.query(`SELECT project,id,revision,task_id,CASE WHEN length(CAST(body AS BLOB))<=${MAX_EVIDENCE_RECORD_BYTES} THEN body END AS body,body_sha256 FROM research_evidence_links WHERE project=? AND id=?${revision === undefined ? "" : " AND revision=?"} ORDER BY revision DESC LIMIT 1`) .get(...(revision === undefined ? [project, id] : [project, id, revision])) as { project: string; id: string; revision: number; task_id: number; body: string | null; body_sha256: string } | null; if (!row) return undefined; try { if (typeof row.body !== "string") throw new Error("invalid body"); const link = parseEvidenceLink(JSON.parse(row.body)), canonical = evidenceLinkCanonical(link); if (link.id !== row.id || link.revision !== row.revision || link.taskId !== row.task_id || createHash("sha256").update(canonical).digest("hex") !== row.body_sha256) throw new Error("invalid binding"); return link; } catch { throw new Error("evidence storage invalid; stop the hub and restore a trusted hub.db backup; then restart and retry"); } } /** Bounded current inventory. A task-wide overflow cannot establish complete claim coverage. */ latestEvidenceLinks(project: string, taskId: number, claimId: string, claimRevision: string, limit: number): { links: EvidenceLinkV1[]; complete: boolean } { 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) || !/^[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"); 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 ?") .all(project, taskId, limit + 1) as { id: string; revision: number }[]; const links = rows.slice(0, limit).flatMap(row => { const link = this.evidenceLink(project, row.id, row.revision); if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh the task review before retrying"); return link.claimId === claimId && link.claimRevision === claimRevision ? [link] : []; }); // ponytail: the task-wide cap can make a smaller claim inventory unknown; a claim-indexed validated read is the upgrade path. return { links, complete: rows.length <= limit }; } /** Verified immutable relation history, never a second judgment store. */ 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 } { 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) || !/^[a-f0-9]{16}$/.test(claimRevision) || links.length > 128 || new Set(links.map(link => link.id)).size !== links.length || links.some(link => link.taskId !== taskId || link.claimId !== claimId || link.claimRevision !== claimRevision)) throw new Error("evidence history identity invalid; refresh the complete inventory"); const unknown = { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false }; 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 ?") .all(project, taskId, 129) as { id: string; revision: number }[]; if (taskRows.length > 128) return unknown; const latest = taskRows.map(row => { const link = this.evidenceLink(project, row.id, row.revision); if (!link || link.taskId !== taskId) throw new Error("evidence inventory changed; refresh its history"); return link; }).filter(link => link.claimId === claimId); const current = latest.filter(link => link.claimRevision === claimRevision); if (current.length !== links.length || current.some(link => !links.some(given => evidenceLinkCanonical(given) === evidenceLinkCanonical(link)))) throw new Error("evidence inventory changed; refresh its history"); const revisions = latest.reduce((count, link) => count + link.revision, 0); // ponytail: above 1024 owned revisions, history is unknown. Upgrade to paged verified history commitments before widening this window. if (!Number.isSafeInteger(revisions) || revisions > EVIDENCE_HISTORY_WINDOW) return unknown; 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 ?`) .all(project, taskId, ...latest.map(link => link.id), EVIDENCE_HISTORY_WINDOW + 1) as { id: string; revision: number }[] : []; if (rows.length > EVIDENCE_HISTORY_WINDOW) return unknown; const seen = new Map(), contradicted = new Set(), sources = new Set(), canonical: string[] = []; for (const row of rows) { const last = latest.find(link => link.id === row.id), prior = this.evidenceLink(project, row.id, row.revision); if (!last || !prior || prior.taskId !== taskId || prior.claimId !== claimId || row.revision !== (seen.get(row.id) ?? 0) + 1 || row.revision > last.revision) throw new Error("evidence history is incomplete or changed; restore trusted evidence storage and retry"); seen.set(row.id, row.revision); sources.add(prior.sourceId); canonical.push(evidenceLinkCanonical(prior)); if (prior.relation === "contradicts") contradicted.add(row.id); if (row.revision === last.revision && evidenceLinkCanonical(prior) !== evidenceLinkCanonical(last)) throw new Error("evidence inventory changed; refresh its history before retrying"); } if (latest.some(link => seen.get(link.id) !== link.revision)) throw new Error("evidence history is incomplete; restore trusted evidence storage and retry"); const sha256 = createHash("sha256").update(JSON.stringify({ project, taskId, claimId, rows: canonical })).digest("hex"); return { ids: [...contradicted].sort(), sources: [...sources].sort(), members: latest.map(link => link.id), binding: { revision: revisions, sha256 }, complete: true }; } recordEvidenceLink(project: string, input: EvidenceLinkV1, fence: { taskFlowRevision: number; taskCreated: number; owner: PeerId; personWithdrawal?: true }): EvidenceLinkV1 { const link = parseEvidenceLink(input), canonical = evidenceLinkCanonical(link); const personWithdrawal = fence.personWithdrawal === true && link.recordedBy === USER && link.status === "withdrawn"; 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"); return this.atomic(() => { const task = this.get(link.taskId); if (!task || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision || task.owner !== fence.owner || task.state !== "in_progress" || task.profile !== "research" || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new Error("evidence task authority changed; refresh ahub task show before retrying"); const identity = taskClaimIdentity(task, Number(link.claimId.split(":").at(-1))); if (identity.claimId !== link.claimId || identity.claimRevision !== link.claimRevision) throw new Error("evidence claim revision changed; refresh the claim binding before retrying"); const latest = this.evidenceLink(project, link.id), next = (latest?.revision ?? 0) + 1; if (latest && (latest.taskId !== link.taskId || latest.claimId !== link.claimId)) throw new Error("evidence id belongs to another claim; use a new evidence id"); const known = this.evidenceLink(project, link.id, link.revision); if (known) { if (evidenceLinkCanonical(known) !== canonical) throw new Error(`evidence revision already records different content; use next revision ${next} or a new evidence id`); return known; } if (link.revision !== next) throw new Error(`evidence revision is out of sequence; expected next revision ${next}; use that revision or replay an unchanged recorded revision`); this.taskWrite(() => this.db.query("INSERT INTO research_evidence_links(project,id,revision,task_id,body,body_sha256) VALUES(?,?,?,?,?,?)") .run(project, link.id, link.revision, link.taskId, canonical, createHash("sha256").update(canonical).digest("hex"))); return this.evidenceLink(project, link.id, link.revision)!; }); } /** Fixed experiment scope; SQL bounds JSON before it reaches JavaScript. No caller may widen a page. */ guidanceExperiment(projectKey: string, taskId: number, taskCreated: number, experimentId: string): GuidanceExperimentRecord | undefined { const row = this.db.query(`SELECT CASE WHEN typeof(baseline_json)='text' AND length(CAST(baseline_json AS BLOB))<=? THEN baseline_json END AS baseline FROM guidance_experiments WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=?`) .get(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, experimentId) as { baseline: unknown } | null; if (!row) return undefined; if (typeof row.baseline !== "string") throw new Error("guidance experiment storage is invalid"); const record = parseGuidanceExperiment({ projectKey, taskId, taskCreated, experimentId, baseline: JSON.parse(row.baseline) }); if (JSON.stringify(record.baseline) !== row.baseline) throw new Error("guidance experiment storage is not canonical"); return record; } guidanceVariants(projectKey: string, taskId: number, taskCreated: number, experimentId: string): GuidanceStoredRecord[] { const experiment = this.guidanceExperiment(projectKey, taskId, taskCreated, experimentId); const rows = this.db.query(`${GUIDANCE_VARIANT_SELECT} FROM guidance_variants WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=? ORDER BY guidance_variants.id LIMIT ?`) .all(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, experimentId, GUIDANCE_VARIANT_LIMITS.variants + 1) as Record[]; if (rows.length > GUIDANCE_VARIANT_LIMITS.variants || rows.length && !experiment) throw new Error("guidance variant storage is invalid"); return rows.map(row => this.guidanceVariantRow(row, experiment!)); } private guidanceVariantRow(row: Record, experiment: GuidanceExperimentRecord): GuidanceStoredRecord { if (row.valid_withdrawn_by !== 1 || row.valid_withdrawn_at !== 1 || typeof row.body !== "string" || createHash("sha256").update(row.body).digest("hex") !== row.body_sha256 || (row.withdrawn_by === null) !== (row.withdrawn_at === null)) throw new Error("guidance variant storage is invalid"); const record = parseGuidanceStoredRecord({ variant: JSON.parse(row.body), createdBy: row.created_by, createdAt: row.created_at, ...(row.withdrawn_by === null ? {} : { withdrawn: { by: row.withdrawn_by, at: row.withdrawn_at } }) }); const value = record.variant; if (JSON.stringify(value) !== row.body || value.id !== row.id || value.projectKey !== experiment.projectKey || value.taskId !== experiment.taskId || value.taskCreated !== experiment.taskCreated || value.experimentId !== experiment.experimentId || JSON.stringify(value.baseline) !== JSON.stringify(experiment.baseline)) throw new Error("guidance variant binding is invalid"); return record; } /** After Tasks admission only. The raw experiment id is never part of the public selector. */ guidanceVariantLocation(projectKey: string, taskId: number, taskCreated: number, id: string): string | undefined { const rows = this.db.query(`SELECT CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=? THEN experiment_id END AS experiment_id FROM guidance_variants INDEXED BY guidance_variant_task_id WHERE project_id=? AND task_id=? AND task_created=? AND id=? LIMIT 2`) .all(EXECUTION_REFERENCE_LIMITS.id, projectKey, taskId, taskCreated, id) as { experiment_id: unknown }[]; if (rows.length > 1 || rows.some(row => typeof row.experiment_id !== "string")) throw new Error("guidance variant selection is ambiguous or unavailable"); return rows[0]?.experiment_id as string | undefined; } /** One fixed keyset page: no OFFSET, task history, experiment-count cap or unbounded payload scan. */ guidanceVariantPage(projectKey: string, taskId: number, taskCreated: number, after = ""): GuidanceStoredRecord[] { const rows = this.db.query(`${GUIDANCE_VARIANT_SELECT},CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN experiment_id END AS experiment_id FROM guidance_variants INDEXED BY guidance_variant_task_id WHERE project_id=? AND task_id=? AND task_created=? AND guidance_variants.id>? ORDER BY guidance_variants.id LIMIT ?`) .all(GUIDANCE_VARIANT_LIMITS.recordBytes, projectKey, taskId, taskCreated, after, GUIDANCE_PAGE_MAX_RECORDS + 1) as Record[]; if (new Set(rows.map(row => row.id)).size !== rows.length) throw new Error("guidance variant selection is ambiguous"); const experiments = new Map(); return rows.map(row => { if (typeof row.experiment_id !== "string") throw new Error("guidance experiment scope is invalid"); let experiment = experiments.get(row.experiment_id); if (!experiment) { experiment = this.guidanceExperiment(projectKey, taskId, taskCreated, row.experiment_id); if (!experiment) throw new Error("guidance experiment is unavailable"); experiments.set(row.experiment_id, experiment); } return this.guidanceVariantRow(row, experiment); }); } private guidanceWriteTask(fence: GuidanceWriteFence): Task { const task = this.get(fence.taskId); if (!executionLinkActor(fence.by) || !executionLinkInteger(fence.at) || !task || task.created !== fence.taskCreated || task.history.length !== fence.flowRevision || task.owner !== fence.owner || task.state !== fence.state || task.role !== fence.roleId || task.state === "approved" || task.state === "cancelled" || fence.by !== USER && (task.owner !== fence.by || task.state === "in_review") || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new Error("guidance task binding changed"); return task; } /** Tasks alone supplies current runtime/privacy/catalog authority; persisted facts are checked again inside this transaction. */ recordGuidanceVariant(value: GuidanceVariantV1, fence: GuidanceWriteFence): { record: GuidanceStoredRecord; already: boolean } { const variant = parseGuidanceVariantV1(value); return this.atomic(() => { this.guidanceWriteTask(fence); if (variant.author !== fence.by || variant.taskId !== fence.taskId || variant.taskCreated !== fence.taskCreated || variant.flowRevision !== fence.flowRevision || variant.baseline.roleId !== fence.roleId) throw new Error("guidance task binding changed"); const original = this.guidanceExperiment(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId); const records = this.guidanceVariants(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId); validateGuidanceVariantV1(variant, { projectKey: variant.projectKey, taskId: variant.taskId, taskCreated: variant.taskCreated, experimentId: variant.experimentId, flowRevision: fence.flowRevision, actor: fence.by, baseline: original?.baseline ?? variant.baseline, currentBaseline: { id: variant.baseline.roleId, layer: variant.baseline.layer, hash: variant.baseline.sha256 }, variantIds: records.map(item => item.variant.id) }); const known = records.find(item => item.variant.id === variant.id); if (known) { if (JSON.stringify(known.variant) !== JSON.stringify(variant)) throw new Error("guidance variant id has changed content"); return { record: known, already: true }; } const body = JSON.stringify(variant), stored = parseGuidanceStoredRecord({ variant, createdBy: fence.by, createdAt: fence.at }); if (!original) this.taskWrite(() => this.db.query("INSERT INTO guidance_experiments(project_id,task_id,task_created,experiment_id,baseline_json) VALUES(?,?,?,?,?)") .run(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId, JSON.stringify(variant.baseline))); this.taskWrite(() => this.db.query(`INSERT INTO guidance_variants(project_id,task_id,task_created,experiment_id,id,body,body_sha256,created_by,created_at) VALUES(?,?,?,?,?,?,?,?,?)`) .run(variant.projectKey, variant.taskId, variant.taskCreated, variant.experimentId, variant.id, body, createHash("sha256").update(body).digest("hex"), fence.by, fence.at)); return { record: stored, already: false }; }); } withdrawGuidanceVariant(projectKey: string, experimentId: string, id: string, fence: GuidanceWriteFence): { record: GuidanceStoredRecord; already: boolean } { return this.atomic(() => { this.guidanceWriteTask(fence); const record = this.guidanceVariants(projectKey, fence.taskId, fence.taskCreated, experimentId).find(item => item.variant.id === id); if (!record) throw new Error("guidance variant is unavailable"); if (record.withdrawn) return { record, already: true }; const next = parseGuidanceStoredRecord({ ...record, withdrawn: { by: fence.by, at: fence.at } }); const result = this.taskWrite(() => this.db.query(`UPDATE guidance_variants SET withdrawn_by=?,withdrawn_at=? WHERE project_id=? AND task_id=? AND task_created=? AND experiment_id=? AND id=? AND withdrawn_by IS NULL AND withdrawn_at IS NULL`) .run(fence.by, fence.at, projectKey, fence.taskId, fence.taskCreated, experimentId, id)); if (result.changes !== 1) throw new Error("guidance withdrawal binding changed"); return { record: next, already: false }; }); } /** Private survey metadata, linked to the existing task incarnation. */ surveyCreate(input: { task: number; taskCreated: number; repo: string; ref: string; focus?: SurveyFocus; by: string; at: number; withheld?: true }): number { const row = surveyCreateInput(input); const write = () => { const task = this.get(row.task); if (!task || task.created !== row.taskCreated || task.class !== "plan" || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure(); const known = this.surveyOfTask(row.task, row.taskCreated); if (known) { const { id: _id, withheld: _private, ...prior } = known, { withheld: _nextPrivate, ...next } = row; if (JSON.stringify(prior) !== JSON.stringify(next)) return surveyInputFailure(); if (row.withheld && !known.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(known.id)); return known.id; } const body = JSON.stringify(row); const saved = this.taskWrite(() => this.db.query("INSERT INTO advisor_surveys(task_id,task_created,body,body_sha256,withheld) VALUES(?,?,?,?,?)") .run(row.task, row.taskCreated, body, surveyHash(body), row.withheld ? 1 : 0)); return Number(saved.lastInsertRowid); }; // The host-only proposal hook already owns the transaction and deferred notifications. return this.pendingChanges ? write() : this.atomic(write); } surveyOfTask(taskId: number, created: number): StoredSurvey | undefined { surveyInteger(taskId); surveyInteger(created, 0); const row = this.db.query("SELECT id FROM advisor_surveys WHERE task_id=? AND task_created=?").get(taskId, created) as { id: number } | null; return row ? this.survey(row.id) : undefined; } surveyOpen(repo: string): { id: number; task: number; taskCreated: number } | undefined { surveyText(repo, 1024); 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 }[]; if (rows.length > SURVEY_STORE_LIMIT) throw new Error("open survey inventory unavailable; reduce open surveys and retry"); const found = rows.map(row => this.survey(row.id)!).filter(row => row.repo === repo); if (found.length > 1) throw new Error("multiple surveys are open; finish or cancel them before starting another"); const row = found[0]; return row ? { id: row.id, task: row.task, taskCreated: row.taskCreated } : undefined; } survey(id: number): StoredSurvey | undefined { surveyInteger(id); 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; if (!row) return; try { if (!row.body || surveyHash(row.body) !== row.body_sha256 || row.withheld !== 0 && row.withheld !== 1) return surveyStorageFailure(); const value = surveyCreateInput(JSON.parse(row.body)); if (value.task !== row.task_id || value.taskCreated !== row.task_created) return surveyStorageFailure(); return { id: row.id, ...value, ...(row.withheld ? { withheld: true } : {}) }; } catch { return surveyStorageFailure(); } } surveyFindings(id: number): StoredSurveyFinding[] { surveyInteger(id); 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 }[]; try { if (rows.length > 64) return surveyStorageFailure(); return rows.map(row => { if (!row.body || surveyHash(row.body) !== row.body_sha256) return surveyStorageFailure(); const value = surveyStoredFinding(JSON.parse(row.body)); if (value.finding.id !== row.finding_id) return surveyStorageFailure(); return value; }); } catch { return surveyStorageFailure(); } } private consideredWrite(input: unknown, kind: "rejected" | "reconsidered", priorIDs: readonly number[] = []): number { const entry = parseConsideredEntry(input), task = this.get(entry.source.task); if (!task || task.created !== entry.source.created) return surveyInputFailure(); const prior = surveyArray(priorIDs, SURVEY_STORE_LIMIT).map(value => surveyInteger(value)).sort((a, b) => a - b); if (new Set(prior).size !== prior.length || kind === "rejected" && prior.length || kind === "reconsidered" && !prior.length) return surveyInputFailure(); for (const id of prior) { 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; if (!found || found.kind !== "rejected" || found.repo !== entry.repo || found.finding_id !== entry.id || found.pass !== entry.pass) return surveyInputFailure(); } const { withheld: _private, ...identity } = entry, body = JSON.stringify(entry), priorBody = JSON.stringify(prior); const replay = surveyHash(JSON.stringify({ kind, entry: identity, prior })); const known = this.db.query("SELECT id FROM considered_findings WHERE replay_key=?").get(replay) as { id: number } | null; if (known) { if (entry.withheld) this.taskWrite(() => this.db.query("UPDATE considered_findings SET withheld=1 WHERE id=? AND withheld=0").run(known.id)); return known.id; } 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(?,?,?,?,?,?,?,?,?)") .run(entry.repo, entry.id, entry.pass, kind, body, surveyHash(body), replay, priorBody, entry.withheld || entry.pass === "security" ? 1 : 0)); return Number(saved.lastInsertRowid); } recordRejectedFinding(entry: ConsideredEntry): number { return this.atomic(() => this.consideredWrite(entry, "rejected")); } recordReconsideredFinding(entry: ConsideredEntry, priorIDs: readonly number[]): number { return this.atomic(() => this.consideredWrite(entry, "reconsidered", priorIDs)); } /** Closed proposals are history, not dedupe. Caller screens any new reference before the atomic apply. */ surveyCardHistory(key: string): { active?: number; closed?: number } { surveyText(key, 512); // ponytail: at most 1000 matching host-created cards; overflow is unknown, not permission to duplicate. Page this proof if a key outgrows the window. 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 ?") .all(key, HUB, SURVEY_STORE_LIMIT + 1) as { id: number; state: string }[]; if (rows.length > SURVEY_STORE_LIMIT) return surveyStorageFailure(); const active = rows.filter(row => !isClosedTaskState(row.state)); if (active.length > 1) return surveyStorageFailure(); const closed = rows.find(row => isClosedTaskState(row.state)); return { ...(active[0] ? { active: surveyInteger(active[0].id) } : {}), ...(closed ? { closed: surveyInteger(closed.id) } : {}) }; } rejectedFindingsFor(repo: string, pass: string, id: string, limit = 100): { rows: StoredRejectedFinding[]; complete: boolean } { return this.rejectedFindings(repo, limit, { pass: surveyPass(pass), id: surveyFindingId(id) }); } rejectedFindings(repo: string, limit = 100, selector?: { pass: string; id: string }): { rows: StoredRejectedFinding[]; complete: boolean } { surveyText(repo, 1024); surveyInteger(limit); if (limit > SURVEY_STORE_LIMIT) return surveyInputFailure(); const selected = selector === undefined ? undefined : surveyObject(selector, ["pass", "id"]); const args: (string | number)[] = [repo]; if (selected) args.push(surveyFindingId(selected.id), surveyPass(selected.pass)); args.push(limit + 1); 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, 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, 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, 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 }[]; if (rows.length > limit) return { rows: [], complete: false }; try { const parsed = rows.map(row => { 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(); const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value)); 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(); const { withheld: _private, ...identity } = entry; if (surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key || prior.some(id => id >= row.id)) return surveyStorageFailure(); return { id: row.id, entry: { ...entry, ...(row.withheld ? { withheld: true as const } : {}) }, kind: row.kind, prior }; }); 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(); 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 }; } catch { return surveyStorageFailure(); } } surveyApply(id: number, input: SurveyApplyInput, fenceInput: SurveyWriteFence): { createdIDs: number[]; dedupedIDs: number[]; already: boolean } { surveyInteger(id); const given = surveyObject(input, ["findings", "decisions", "by", "at", "cards", "rejections", "reconsiderations", "withheld"]); const findings = parseSurveyFindings(given.findings), decisions = parseSurveyVetDecisions(given.decisions), by = surveyText(given.by, 128), at = surveyInteger(given.at, 0); if (given.withheld !== undefined && given.withheld !== true) return surveyInputFailure(); const cards = surveyArray(given.cards ?? [], 64).map(value => { const row = surveyObject(value, ["id", "key", "title", "detail", "class", "refs", "signals", "reopens", "reopenReason"]), key = surveyText(row.key, 512), title = surveyText(row.title, 512); 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(); const rawRefs = row.refs === undefined ? undefined : surveyObject(row.refs, ["repo", "branch", "commit", "paths"]), refs: TaskRefs | undefined = rawRefs ? {} : undefined; if (rawRefs && refs) { for (const key of ["repo", "branch", "commit"] as const) if (rawRefs[key] !== undefined) refs[key] = surveyText(rawRefs[key], 1024); if (rawRefs.paths !== undefined) refs.paths = surveyArray(rawRefs.paths, 64).map(surveyPath); } const signals = row.signals === undefined ? undefined : surveyArray(row.signals, 64).map(value => surveyText(value, 128)); if ((row.reopens === undefined) !== (row.reopenReason === undefined)) return surveyInputFailure(); const reopening = row.reopens === undefined ? {} : { reopens: surveyInteger(row.reopens), reopenReason: surveyText(row.reopenReason) }; return { id: surveyText(row.id, 96), key, title, detail: row.detail, class: row.class, ...(refs ? { refs } : {}), ...(signals ? { signals } : {}), ...reopening }; }); if (new Set(cards.map(card => card.id)).size !== cards.length || new Set(cards.map(card => card.key)).size !== cards.length) return surveyInputFailure(); const rejections = surveyArray(given.rejections ?? [], 64).map(parseConsideredEntry), reconsiderations = surveyArray(given.reconsiderations ?? [], 64).map(parseConsideredEntry); const fence = surveyObject(fenceInput, ["boardRevision", "taskCreated", "taskFlowRevision", "owner"]); surveyInteger(fence.boardRevision, 0); surveyInteger(fence.taskCreated, 0); surveyInteger(fence.taskFlowRevision, 0); surveyText(fence.owner, 128); return this.atomic(() => { const revision = this.statusRevision(), survey = this.survey(id), task = survey && this.get(survey.task); if (!survey || !task || revision !== fence.boardRevision || task.created !== survey.taskCreated || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision || task.class !== "plan" || task.state !== "in_progress" || task.owner !== fence.owner || by !== task.owner && by !== USER || task.signals.includes("pii") || task.signals.includes("pii_path")) return surveyInputFailure(); const existing = this.surveyFindings(id), merged = new Map(existing.map(row => [row.finding.id, { ...row }])); for (const finding of findings) { const prior = merged.get(finding.id); if (prior && JSON.stringify(prior.finding) !== JSON.stringify(finding)) return surveyInputFailure(); if (!prior) merged.set(finding.id, { finding, foundBy: by, foundAt: at }); } if (merged.size > 64) return surveyInputFailure(); parseSurveyFindings([...merged.values()].map(row => row.finding)); const prepared = [...rejections, ...reconsiderations]; for (const entry of prepared) { const finding = merged.get(entry.id)?.finding; if (!finding || entry.repo !== survey.repo || entry.pass !== finding.pass || entry.ref !== survey.ref || entry.source.kind !== "survey" || entry.source.task !== task.id || entry.source.created !== task.created || JSON.stringify(entry.paths) !== JSON.stringify(finding.paths)) return surveyInputFailure(); } for (const decision of decisions) { const row = merged.get(decision.id); if (!row) return surveyInputFailure(); const prior = row.decision; if (prior && JSON.stringify(prior) === JSON.stringify(decision)) continue; if (prior && !(prior.verdict === "rejected" && decision.verdict === "vetted" && decision.reason) && !(prior.verdict === "vetted" && decision.verdict === "vetted" && decision.reason && reconsiderations.some(entry => entry.id === decision.id && entry.reason === decision.reason))) return surveyInputFailure(); const ledger = decision.verdict === "rejected" ? rejections : prior?.verdict === "rejected" ? reconsiderations : []; if ((decision.verdict === "rejected" || prior?.verdict === "rejected") && !ledger.some(entry => entry.id === decision.id && entry.reason === decision.reason)) return surveyInputFailure(); row.decision = decision; row.decisionBy = by; row.decisionAt = at; } parseSurveyVetDecisions([...merged.values()].flatMap(row => row.decision ? [row.decision] : [])); for (const entry of rejections) if (!decisions.some(row => row.id === entry.id && row.verdict === "rejected" && row.reason === entry.reason)) return surveyInputFailure(); for (const entry of reconsiderations) if (!decisions.some(row => row.id === entry.id && row.verdict === "vetted" && row.reason === entry.reason)) return surveyInputFailure(); for (const entry of rejections) this.consideredWrite(entry, "rejected"); for (const entry of reconsiderations) { const ledger = this.rejectedFindingsFor(survey.repo, entry.pass, entry.id, SURVEY_STORE_LIMIT); if (!ledger.complete) return surveyInputFailure(); const prior = ledger.rows.filter(row => row.entry.id === entry.id && row.entry.pass === entry.pass).map(row => row.id); this.consideredWrite(entry, "reconsidered", prior); } const createdIDs: number[] = [], dedupedIDs: number[] = []; for (const card of cards) { const row = merged.get(card.id); if (!row || row.decision?.verdict !== "vetted" || card.class !== (row.finding.confidence === "low" ? "triage" : "plan")) return surveyInputFailure(); if (row.finding.pass === "security" && card.refs && Object.keys(card.refs).length) return surveyInputFailure(); const history = this.surveyCardHistory(card.key); if (history.active) dedupedIDs.push(history.active); else { if (history.closed !== card.reopens || card.reopens !== undefined && !card.detail.includes(`Reopened from hub task ${card.reopens}: ${card.reopenReason}`)) return surveyInputFailure(); 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); } } for (const row of merged.values()) { const prior = existing.find(old => old.finding.id === row.finding.id), body = JSON.stringify(row); if (Buffer.byteLength(body) > SURVEY_STORE_BYTES) return surveyInputFailure(); 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))); } if (given.withheld && !survey.withheld) this.taskWrite(() => this.db.query("UPDATE advisor_surveys SET withheld=1 WHERE id=?").run(id)); return { createdIDs, dedupedIDs, already: this.statusRevision() === revision }; }); } hasSurveyState(): boolean { 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; } /** Stream bounded validated private rows into recovery proof; output never includes finding or ledger text. */ surveyIntegrity(): { surveys: number; findings: number; considered: number; digest: string } { try { return this.db.transaction(() => { const digest = createHash("sha256"); let surveys = 0, findings = 0, considered = 0; for (const key of this.db.query("SELECT id FROM advisor_surveys ORDER BY id").iterate() as Iterable<{ id: number }>) { const row = this.survey(key.id); if (!row) return surveyStorageFailure(); const task = this.get(row.task); if (!task || task.created !== row.taskCreated) return surveyStorageFailure(); digest.update(JSON.stringify({ survey: row })); surveys++; const candidates = this.surveyFindings(row.id); parseSurveyFindings(candidates.map(candidate => candidate.finding)); parseSurveyVetDecisions(candidates.flatMap(candidate => candidate.decision ? [candidate.decision] : [])); for (const candidate of candidates) { digest.update(JSON.stringify({ survey: row.id, candidate })); findings++; } } const count = this.db.query("SELECT COUNT(*) AS count FROM advisor_survey_findings").get() as { count: number }; if (count.count !== findings) return surveyStorageFailure(); 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, 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, 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, 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`; 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 }>) { 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(); const entry = parseConsideredEntry(JSON.parse(row.body)), prior = surveyArray(JSON.parse(row.prior_ids), SURVEY_STORE_LIMIT).map(value => surveyInteger(value)); const { withheld: _private, ...identity } = entry, task = this.get(entry.source.task); if (!task || task.created !== entry.source.created || entry.repo !== row.repo || entry.id !== row.finding_id || entry.pass !== row.pass || new Set(prior).size !== prior.length || prior.some(id => id >= row.id) || row.kind === "rejected" && prior.length || row.kind === "reconsidered" && !prior.length || surveyHash(JSON.stringify({ kind: row.kind, entry: identity, prior })) !== row.replay_key) return surveyStorageFailure(); for (const id of prior) { 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); if (!parent) return surveyStorageFailure(); } digest.update(JSON.stringify({ id: row.id, kind: row.kind, entry, prior, withheld: row.withheld })); considered++; } return { surveys, findings, considered, digest: digest.digest("hex") }; })(); } catch { return surveyStorageFailure(); } } /** #1403 A4: a new audit with its seeded ledger, in one transaction. Only `Tasks.auditStart` calls this. */ auditCreate(row: { task: number; taskCreated: number; ref: string; since?: string; profile: string; scoped: boolean; by: string; at: number; units: readonly AuditUnit[] }): number { return this.atomic(() => { const result = this.db.query("INSERT INTO security_audits(task_id,task_created,ref,since,profile,scoped,at,by_peer,units) VALUES(?,?,?,?,?,?,?,?,?)") .run(row.task, row.taskCreated, row.ref, row.since ?? null, row.profile, row.scoped ? 1 : 0, row.at, row.by, JSON.stringify(row.units)); return Number(result.lastInsertRowid); }); } 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 { if (!row) return undefined; const units = JSON.parse(row.units) as AuditUnit[]; if (!Array.isArray(units)) throw new Error("security audit storage is invalid"); 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 }; } audit(id: number): StoredAudit | undefined { return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE id=?").get(id) as never); } auditOfTask(task: number, taskCreated: number): StoredAudit | undefined { return this.auditRow(this.db.query("SELECT * FROM security_audits WHERE task_id=? AND task_created=?").get(task, taskCreated) as never); } /** 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). */ audits(limit = 32, recorded = false): StoredAudit[] { const rows = this.db.query("SELECT * FROM security_audits ORDER BY id DESC LIMIT ?").all(limit) as never[]; const all = rows.map(row => this.auditRow(row)!); return recorded ? all.filter(row => row.units.some(unit => unit.reportedBy)) : all; } /** * 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 * 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 * needs the finding verified, not rejected and not yet settled. */ 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 { const skipped: string[] = []; try { this.atomic(() => { if (change.units) this.db.query("UPDATE security_audits SET units=? WHERE id=?").run(JSON.stringify(change.units), id); let seq = (this.db.query("SELECT COALESCE(MAX(seq),0) AS seq FROM security_audit_findings WHERE audit=?").get(id) as { seq: number }).seq; for (const item of change.findings) { 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; 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; } 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; if (changed !== 1) skipped.push(item.finding.id); } for (const decision of change.decisions) { const column = decision.verdict === "verified" ? "verified_by" : "rejected_by"; 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; if (done !== 1) throw new Error("audit decision lost"); } for (const settlement of change.settlements ?? []) { 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; if (done !== 1) throw new Error("audit decision lost"); } }); } catch (error) { if (error instanceof Error && error.message === "audit decision lost") return undefined; throw error; } return skipped; } auditFindings(id: number): AuditFinding[] { 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 }[]; // A settled finding reads with its settled disposition, so every reader that already shows a `fixed` or `false_positive` finding treats it as one. return rows.map(row => { const settled = row.settled_by && (row.settled_as === "fixed" || row.settled_as === "false_positive") ? row.settled_as : undefined; const body = JSON.parse(row.body) as ReviewFinding; 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 } : {}) }; }); } hasGuidanceVariants(): boolean { 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; } /** Recovery only. Normal reads always address one indexed experiment. */ guidanceVariantsIntegrity(): { experiments: number; variants: number; digest: string } { try { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.guidance-variants/v1\n"); let experiments = 0, variants = 0; // ponytail: recovery streams O(historical experiments), with bounded row/page memory. If measured recovery cost warrants it, // upgrade to keyset pages plus a verification budget; a partial scan must never certify complete integrity. const statement = this.db.prepare(`SELECT CASE WHEN typeof(project_id)='text' AND length(CAST(project_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.projectKey} THEN project_id END AS project_id,CASE WHEN typeof(task_id)='integer' THEN task_id END AS task_id,CASE WHEN typeof(task_created)='integer' THEN task_created END AS task_created, CASE WHEN typeof(experiment_id)='text' AND length(CAST(experiment_id AS BLOB))<=${EXECUTION_REFERENCE_LIMITS.id} THEN experiment_id END AS experiment_id FROM guidance_experiments ORDER BY project_id,task_id,task_created,experiment_id`); try { for (const row of statement.iterate() as Iterable<{ project_id: string; task_id: number; task_created: number; experiment_id: string }>) { if (typeof row.project_id !== "string" || typeof row.experiment_id !== "string" || !executionLinkInteger(row.task_id, 1) || !executionLinkInteger(row.task_created)) throw new Error("guidance experiment scope is invalid"); const experiment = this.guidanceExperiment(row.project_id, row.task_id, row.task_created, row.experiment_id)!; const records = this.guidanceVariants(row.project_id, row.task_id, row.task_created, row.experiment_id); if (!records.length) throw new Error("guidance experiment is empty"); digest.update(JSON.stringify(experiment)).update("\n"); experiments++; for (const record of records) { digest.update(JSON.stringify(record)).update("\n"); variants++; } } } finally { statement.finalize(); } const orphan = this.db.query(`SELECT EXISTS(SELECT 1 FROM guidance_variants AS v WHERE NOT EXISTS(SELECT 1 FROM guidance_experiments AS e WHERE e.project_id=v.project_id AND e.task_id=v.task_id AND e.task_created=v.task_created AND e.experiment_id=v.experiment_id)) AS present`).get() as { present: number }; if (orphan.present) throw new Error("guidance variant experiment is unavailable"); return { experiments, variants, digest: digest.digest("hex") }; })(); } catch { throw new Error("guidance variant integrity is unavailable; inspect retained project state before retrying"); } } private executionReferenceRow(row: Record): ExecutionLinkRecord { try { if (typeof row.from_json !== "string" || typeof row.reference_json !== "string") throw new Error(); const record = parseExecutionLinkRecord({ id: row.id, projectKey: row.project_id, taskId: row.task_id, taskCreated: row.task_created, from: JSON.parse(row.from_json), reference: JSON.parse(row.reference_json), strength: "declared", recordedBy: row.recorded_by, recordedAt: row.recorded_at }); if (executionReferenceKey(record.from) !== row.from_json || executionReferenceKey(record.reference) !== row.reference_json || executionReferenceDigest(record.from) !== row.from_sha256 || executionReferenceDigest(record.reference) !== row.reference_sha256) throw new Error(); return record; } catch { throw new ExecutionLinkError("corrupt"); } } /** Tasks is the only writer; it additionally fences current private/observer/read-only context and exact from membership. */ recordExecutionReference(projectKey: string, value: ExecutionLinkInput, fence: ExecutionLinkFence): { record: ExecutionLinkRecord; already: boolean } { const input = parseExecutionLinkInput(value), refs = executionLinkReferences(projectKey, input), id = executionLinkId(projectKey, input); if (!executionLinkActor(fence.by) || !executionLinkInteger(fence.at)) throw new ExecutionLinkError("invalid"); try { return this.atomic(() => { const task = this.get(input.taskId); if (!task || task.created !== input.taskCreated || task.history.length !== input.flowRevision || fence.by !== USER && task.owner !== fence.by && task.reviewer !== fence.by || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new ExecutionLinkError("changed"); // Fence precedes dedup: a private, stale or removed actor cannot replay an old authorization. const known = this.db.query(`${EXECUTION_REFERENCE_SELECT} WHERE id=?`).get(id) as Record | null; if (known) { const record = this.executionReferenceRow(known); if (record.projectKey !== projectKey || record.taskId !== input.taskId || record.taskCreated !== input.taskCreated || executionReferenceKey(record.from) !== executionReferenceKey(refs.from) || executionReferenceKey(record.reference) !== executionReferenceKey(refs.reference)) throw new ExecutionLinkError("corrupt"); return { record, already: true }; } const count = this.db.query("SELECT COUNT(*) AS n FROM (SELECT 1 FROM execution_reference_links WHERE project_id=? AND task_id=? AND task_created=? LIMIT ?)") .get(projectKey, input.taskId, input.taskCreated, EXECUTION_LINK_LIMITS.read) as { n: number }; if (count.n >= EXECUTION_LINK_LIMITS.perTask) throw new ExecutionLinkError("limit"); this.taskWrite(() => this.db.query(`INSERT INTO execution_reference_links (id,project_id,task_id,task_created,from_json,from_sha256,reference_json,reference_sha256,recorded_by,recorded_at) VALUES(?,?,?,?,?,?,?,?,?,?)`) .run(id, projectKey, input.taskId, input.taskCreated, executionReferenceKey(refs.from), executionReferenceDigest(refs.from), executionReferenceKey(refs.reference), executionReferenceDigest(refs.reference), fence.by, fence.at)); return { record: parseExecutionLinkRecord({ id, projectKey, taskId: input.taskId, taskCreated: input.taskCreated, ...refs, strength: "declared", recordedBy: fence.by, recordedAt: fence.at }), already: false }; }); } catch (error) { if (error instanceof ExecutionLinkError) throw error; throw new ExecutionLinkError("corrupt"); } } /** Metadata only, after Tasks source authorization. 65 is an overflow sentinel, never a truncated complete neighborhood. */ executionReferences(projectKey: string, taskId: number, taskCreated: number, limit: number = EXECUTION_LINK_LIMITS.read): ExecutionLinkRecord[] { // Reuse the address boundary without looking up any source, task body or foreign producer. executionLinkReferences(projectKey, { taskId, taskCreated, flowRevision: 0, reference: { v: 1, tool: "ahub", projectKey, kind: "task", id: `${taskId}:${taskCreated}` } }); if (!executionLinkInteger(limit, 1) || limit > EXECUTION_LINK_LIMITS.read) throw new ExecutionLinkError("invalid"); try { return (this.db.query(`${EXECUTION_REFERENCE_SELECT} WHERE project_id=? AND task_id=? AND task_created=? ORDER BY id LIMIT ?`) .all(projectKey, taskId, taskCreated, limit) as Record[]).map(row => this.executionReferenceRow(row)); } catch { throw new ExecutionLinkError("corrupt"); } } hasExecutionReferences(): boolean { try { return (this.db.query("SELECT EXISTS(SELECT 1 FROM execution_reference_links) AS present").get() as { present: number }).present === 1; } catch { throw new ExecutionLinkError("corrupt"); } } /** Every persisted field, streamed without retaining all rows; reads never resolve references or mutate state. */ executionReferencesIntegrity(): { count: number; digest: string } { try { return this.db.transaction(() => { const statement = this.db.prepare(`${EXECUTION_REFERENCE_SELECT} ORDER BY project_id,task_id,task_created,id`); const digest = createHash("sha256").update("agent-hub.execution-reference-links/v1\n"); let count = 0, perTask = 0, priorScope: string | undefined; try { for (const row of statement.iterate() as Iterable>) { const record = this.executionReferenceRow(row), scope = JSON.stringify([record.projectKey, record.taskId, record.taskCreated]); if (scope !== priorScope) { priorScope = scope; perTask = 0; } if (++perTask > EXECUTION_LINK_LIMITS.perTask) throw new ExecutionLinkError("corrupt"); const canonical = JSON.stringify(record); digest.update(String(Buffer.byteLength(canonical))).update(":").update(canonical).update("\n"); count++; } } finally { statement.finalize(); } return { count, digest: digest.digest("hex") }; })(); } catch { throw new ExecutionLinkError("corrupt"); } } hasResearchEvidenceState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_evidence_links) AS present").get() as { present: number }).present === 1; } /** Older evidence readers reject the new optional stored withdrawal field. Keep that downgrade fence conditional. */ hasWithdrawnEvidenceState(): boolean { 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; } /** Same #901 history record, with the host's completed observation fenced against intervening database writes. No source I/O in this transaction. */ recordSynthesisClaimVerdict(id: number, claim: ClaimVerdict, fence: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task { return this.atomic(() => { const task = this.get(id); if (!task || this.statusRevision() !== fence.boardRevision || task.created !== fence.taskCreated || task.history.length !== fence.taskFlowRevision || !claim.synthesis || claim.list !== fence.claimRevision || taskClaimIdentity(task, claim.slot).claimRevision !== fence.claimRevision) throw new Error("synthesis context changed before the claim verdict write; refresh the manifest and explicitly record the disposition again"); return this.update(id, USER, "claim verdict", {}, undefined, { claim }, fence.taskFlowRevision); }); } researchEvidenceIntegrity(): { links: number; revisions: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.research-evidence/v1\n"); let links = 0, revisions = 0, previous: string | undefined, previousRevision = 0; let claim: string | undefined, task: number | undefined; for (const row of this.db.query("SELECT project,id,revision FROM research_evidence_links ORDER BY project,id,revision").iterate() as Iterable<{ project: string; id: string; revision: number }>) { const link = this.evidenceLink(row.project, row.id, row.revision); if (!link) throw new Error("evidence storage changed during integrity read; retry recovery inspection"); const key = JSON.stringify([row.project, row.id]); if (key !== previous) { links++; previous = key; previousRevision = 0; claim = link.claimId; task = link.taskId; } if (row.revision !== previousRevision + 1 || link.claimId !== claim || link.taskId !== task) throw new Error("evidence revision history is incomplete or changed claims; stop the hub and restore a trusted hub.db backup; then restart and retry recovery"); previousRevision = row.revision; revisions++; digest.update(JSON.stringify([row.project, evidenceLinkCanonical(link)])).update("\n"); } return { links, revisions, digest: digest.digest("hex") }; })(); } reviewComments(task: number, created: number): ReviewCommentRecord[] { const rows = this.db.query(`SELECT id,lifecycle,revision,CASE WHEN length(CAST(body AS BLOB))<=32768 THEN body END AS body FROM review_comments WHERE task_id=? AND task_created=? ORDER BY id LIMIT ${REVIEW_COMMENT_LIMIT + 1}`).all(task, created) as { id: string; lifecycle: string; revision: number; body: string | null }[]; if (rows.length > REVIEW_COMMENT_LIMIT) throw new Error("review comment storage limit invalid; restore a trusted hub.db backup before retrying"); return rows.map(row => { try { if (typeof row.body !== "string") throw new Error("missing body"); const record = parseStoredReviewComment(JSON.parse(row.body)); if (record.task !== task || record.taskCreated !== created || record.thread.id !== row.id || record.lifecycle !== row.lifecycle || record.revision !== row.revision) throw new Error("binding differs"); return record; } catch { throw new Error("review comment storage invalid; stop the hub and restore a trusted hub.db backup, then restart and retry"); } }); } reviewCommentCounts(task: number, created: number): ReviewCommentCounts { const counts = emptyReviewCommentCounts(); for (const row of this.db.query("SELECT lifecycle,COUNT(*) AS n FROM review_comments WHERE task_id=? AND task_created=? GROUP BY lifecycle").all(task, created) as { lifecycle: string; n: number }[]) { if (!Object.hasOwn(counts, row.lifecycle)) throw new Error("review comment storage invalid; restore a trusted hub.db backup before retrying"); counts[row.lifecycle as keyof ReviewCommentCounts] = row.n; } return counts; } private reviewCommentFence(fence: ReviewCommentFence): Task { const task = this.get(fence.task); if (!task || task.created !== fence.taskCreated || task.history.length !== fence.flow || task.owner !== fence.owner || (task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead) !== fence.head) throw new Error("review task changed; refresh the task review before retrying"); return task; } putReviewComment(input: ReviewCommentRecord, fence: ReviewCommentFence, expected?: number): ReviewCommentRecord { const record = parseStoredReviewComment(input); return this.atomic(() => { this.reviewCommentFence(fence); if (record.task !== fence.task || record.taskCreated !== fence.taskCreated || record.lifecycle !== "draft") throw new Error("review comment binding changed; refresh the draft before retrying"); const comments = this.reviewComments(record.task, record.taskCreated), previous = comments.find(row => row.thread.id === record.thread.id); if (previous ? previous.lifecycle !== "draft" || previous.revision !== expected || record.revision !== previous.revision + 1 : expected !== undefined || record.revision !== 1 || comments.length >= REVIEW_COMMENT_LIMIT) throw new Error("review draft changed or the comment limit is full; refresh the draft list before retrying"); this.taskWrite(() => this.db.query("INSERT INTO review_comments(task_id,task_created,id,body,lifecycle,revision) VALUES(?,?,?,?,?,?) ON CONFLICT(task_id,task_created,id) DO UPDATE SET body=excluded.body,lifecycle=excluded.lifecycle,revision=excluded.revision") .run(record.task, record.taskCreated, record.thread.id, JSON.stringify(record), record.lifecycle, record.revision)); return this.reviewComments(record.task, record.taskCreated).find(row => row.thread.id === record.thread.id)!; }); } deleteReviewComment(id: string, revision: number, fence: ReviewCommentFence): { deleted: boolean; record: ReviewCommentRecord } { return this.atomic(() => { this.reviewCommentFence(fence); const record = this.reviewComments(fence.task, fence.taskCreated).find(row => row.thread.id === id); if (!record) throw new Error("review comment is unavailable; refresh the draft list before retrying"); if (record.lifecycle === "dismissed") return { deleted: false, record }; if (record.revision !== revision) throw new Error("review comment revision changed; refresh the list before retrying"); if (record.lifecycle === "draft") { this.taskWrite(() => this.db.query("DELETE FROM review_comments WHERE task_id=? AND task_created=? AND id=?").run(fence.task, fence.taskCreated, id)); return { deleted: true, record }; } const dismissed: ReviewCommentRecord = { ...record, lifecycle: "dismissed", revision: record.revision + 1 }; this.taskWrite(() => this.db.query("UPDATE review_comments SET body=?,lifecycle=?,revision=? WHERE task_id=? AND task_created=? AND id=?").run(JSON.stringify(dismissed), dismissed.lifecycle, dismissed.revision, fence.task, fence.taskCreated, id)); return { deleted: false, record: dismissed }; }); } sendReviewComments(selected: readonly ReviewCommentRecord[], packet: ReviewCommentPackage, fence: ReviewCommentFence): Task { return this.atomic(() => { const task = this.reviewCommentFence(fence), rows = this.reviewComments(task.id, task.created); if (!selected.length || selected.length > REVIEW_COMMENT_LIMIT || new Set(selected.map(row => row.thread.id)).size !== selected.length || selected.length !== packet.ids.length || task.id !== packet.task || task.created !== packet.taskCreated || task.owner !== packet.owner || selected.some(row => !packet.ids.includes(row.thread.id))) throw new Error("review package binding changed; refresh the selected drafts before sending"); const encodedPacket = JSON.stringify(packet); if (typeof encodedPacket !== "string" || Buffer.byteLength(encodedPacket, "utf8") > 32768) throw new Error("review package storage exceeds 32768 UTF-8 bytes; select fewer ids before sending"); for (const expected of selected) { const record = rows.find(row => row.thread.id === expected.thread.id); if (!record || record.lifecycle !== "draft" || record.revision !== expected.revision) throw new Error("review drafts changed; refresh the list before sending"); const sent: ReviewCommentRecord = { ...record, lifecycle: "sent", sentAt: packet.at, revision: record.revision + 1 }; this.taskWrite(() => this.db.query("UPDATE review_comments SET body=?,lifecycle=?,revision=? WHERE task_id=? AND task_created=? AND id=?").run(JSON.stringify(sent), sent.lifecycle, sent.revision, task.id, task.created, record.thread.id)); } this.taskWrite(() => this.db.query("INSERT INTO review_comment_packages(id,task_id,task_created,body) VALUES(?,?,?,?)").run(packet.id, task.id, task.created, encodedPacket)); return this.update(task.id, "user", `person review comments sent (${selected.length})`, {}, undefined, {}, task.history.length); }); } reviewCommentPackages(task: number, created: number): ReviewCommentPackageView[] { const rows = this.db.query("SELECT id,CASE WHEN length(CAST(body AS BLOB))<=32768 THEN body END AS body FROM review_comment_packages WHERE task_id=? AND task_created=? ORDER BY id LIMIT 65").all(task, created) as { id: string; body: string | null }[]; if (rows.length > 64) throw new Error("review comment package storage limit invalid; restore a trusted hub.db backup before retrying"); return rows.map(row => { try { if (typeof row.body !== "string") throw new Error(); const packet = JSON.parse(row.body) as ReviewCommentPackage; if (!packet || packet.id !== row.id || packet.task !== task || packet.taskCreated !== created || !Array.isArray(packet.ids) || packet.ids.length < 1 || packet.ids.length > REVIEW_COMMENT_LIMIT) throw new Error(); const ids = reviewCommentIds(packet.ids); if (packet.visibleIds !== undefined && (reviewCommentIds(packet.visibleIds).some(id => !ids.includes(id)))) throw new Error(); const delivery = packet.delivery ?? "unconfirmed"; if (delivery !== "queued" && delivery !== "unconfirmed") throw new Error(); return { id: row.id, count: packet.ids.length, delivery: packet.body && packet.envelopeId && packet.trace && packet.ts !== undefined && packet.publicationEvidenceVersion === 1 ? delivery : "unavailable" }; } catch { throw new Error("review comment package storage invalid; stop the hub and restore a trusted hub.db backup, then restart and retry"); } }); } reviewCommentPackage(id: string): ReviewCommentPackage | undefined { const row = this.db.query("SELECT CASE WHEN length(CAST(body AS BLOB))<=32768 THEN body END AS body FROM review_comment_packages WHERE id=?").get(id) as { body: string | null } | null; if (!row) return undefined; try { if (typeof row.body !== "string") throw new Error(); const packet = JSON.parse(row.body) as ReviewCommentPackage; if (!packet || packet.id !== id || !Number.isSafeInteger(packet.task) || !Number.isSafeInteger(packet.taskCreated) || !Array.isArray(packet.ids) || packet.ids.length < 1 || packet.ids.length > REVIEW_COMMENT_LIMIT || reviewCommentIds(packet.ids).length !== packet.ids.length || typeof packet.owner !== "string" || typeof packet.head !== "string" || typeof packet.at !== "string" || packet.delivery !== undefined && packet.delivery !== "queued" && packet.delivery !== "unconfirmed" || packet.publicationEvidenceVersion !== undefined && packet.publicationEvidenceVersion !== 1 || packet.visibleIds !== undefined && (reviewCommentIds(packet.visibleIds).some(value => !packet.ids.includes(value))) || packet.body !== undefined && (typeof packet.body !== "string" || Buffer.byteLength(packet.body, "utf8") > 12000) || packet.envelopeId !== undefined && !/^[a-f0-9-]{36}$/.test(packet.envelopeId) || packet.trace !== undefined && !/^[a-f0-9-]{36}$/.test(packet.trace) || packet.ts !== undefined && (!Number.isSafeInteger(packet.ts) || packet.ts < 0)) throw new Error(); return packet; } catch { throw new Error("review comment package storage invalid; stop the hub and restore a trusted hub.db backup, then restart and retry"); } } markReviewCommentPackageQueued(id: string): void { this.taskWrite(() => { const packet = this.reviewCommentPackage(id); if (!packet || !packet.body || !packet.envelopeId || !packet.trace || packet.ts === undefined) throw new Error("review comment package is unavailable for retry; inspect the task review before sending a new comment"); return this.db.query("UPDATE review_comment_packages SET body=? WHERE id=?").run(JSON.stringify({ ...packet, delivery: "queued" }), id); }); } hasOpenReviewCommentsFor(owner: string, taskId?: number): boolean { const taskScope = taskId === undefined ? "" : " AND task.id=?", packetScope = taskId === undefined ? "" : " AND packet.task_id=?"; const currentOwner = this.db.query(`SELECT EXISTS(SELECT 1 FROM review_comments AS comment JOIN tasks AS task ON task.id=comment.task_id AND task.created=comment.task_created WHERE task.owner=? AND comment.lifecycle='sent'${taskScope}) AS present`).get(...(taskId === undefined ? [owner] : [owner, taskId])) as { present: number }; if (currentOwner.present === 1) return true; const savedOwner = this.db.query(`WITH candidates AS ( SELECT packet.id,packet.task_id,packet.task_created FROM review_comment_packages AS packet WHERE CASE WHEN json_valid(packet.body)=1 THEN json_extract(packet.body,'$.owner') END=?${packetScope} AND EXISTS(SELECT 1 FROM json_each(packet.body,'$.ids') AS package_id JOIN review_comments AS comment ON comment.task_id=packet.task_id AND comment.task_created=packet.task_created AND comment.id=package_id.value WHERE comment.lifecycle='sent') LIMIT 501 ) SELECT COUNT(*) AS count FROM candidates`).get(...(taskId === undefined ? [owner] : [owner, taskId])) as { count: number }; return savedOwner.count > 0; } /** * Durable task-scoped exclusion for sent person comments and anchored findings; resolved/dismissed comments no longer hold memory. * ponytail: anchored-finding scope is conservative until task close; upgrade to a persisted review-package epoch for precise closure. Scans cap at 500 * tasks and 16 MiB aggregate history; corrupt or over-limit state fails closed. A stamp over local total_changes and cross-connection * data_version makes repeated progress reads O(1) until the board changes. */ hasReviewObserverScope(peer: string, taskId: number): boolean { try { const dataVersion = this.db.query("PRAGMA data_version").get() as { data_version: number }; const totalChanges = this.db.query("SELECT total_changes() AS changes").get() as { changes: number }; const stamp = `${dataVersion.data_version}:${totalChanges.changes}`; if (stamp !== this.reviewObserverCacheStamp) { this.reviewObserverScopeCache.clear(); this.reviewObserverCacheStamp = stamp; } const cacheKey = JSON.stringify([peer, taskId]), cached = this.reviewObserverScopeCache.get(cacheKey); if (cached !== undefined) return cached; const scope = " AND id=?"; const params = [peer, peer, taskId]; const counts = this.db.query(`WITH candidate AS ( SELECT history FROM tasks WHERE state NOT IN ('approved','cancelled') AND (owner=? OR reviewer=?)${scope} LIMIT 501 ) SELECT COUNT(*) AS tasks, COALESCE(SUM(length(CAST(history AS BLOB))),0) AS bytes, SUM(CASE WHEN json_valid(history)<>1 THEN 1 ELSE 0 END) AS invalid FROM candidate`).get(...params) as { tasks: number; bytes: number; invalid: number }; let scoped = counts.tasks > 500 || counts.bytes > 16 * 1024 * 1024 || counts.invalid > 0; if (!scoped) { const comments = this.hasOpenReviewCommentsFor(peer, taskId); const reviewerCommentScope = this.db.query(`WITH candidate AS ( SELECT id,created FROM tasks WHERE state='in_review' AND reviewer=?${scope} LIMIT 501 ) SELECT EXISTS(SELECT 1 FROM candidate JOIN review_comments AS comment ON comment.task_id=candidate.id AND comment.task_created=candidate.created WHERE comment.lifecycle='sent') AS present`).get(peer, taskId) as { present: number }; const findings = this.db.query(`WITH candidate AS ( SELECT id,history FROM tasks WHERE state NOT IN ('approved','cancelled') AND (owner=? OR reviewer=?)${scope} LIMIT 501 ) SELECT EXISTS(SELECT 1 FROM candidate, json_each(candidate.history) AS history, json_each(json_extract(history.value,'$.reviewFindings.items')) AS item WHERE json_type(history.value,'$.reviewFindings.items')='array' AND json_type(item.value,'$.anchor')='object') AS present`).get(...params) as { present: number }; scoped = comments || reviewerCommentScope.present === 1 || findings.present === 1; } this.reviewObserverScopeCache.set(cacheKey, scoped); if (this.reviewObserverScopeCache.size > 512) this.reviewObserverScopeCache.delete(this.reviewObserverScopeCache.keys().next().value as string); return scoped; } catch { return true; } } reviewCommentResolution(task: Task, ids: readonly string[]): string[] { const parsed = reviewCommentIds(ids), records = this.reviewComments(task.id, task.created); return parsed.flatMap(id => { const record = records.find(row => row.thread.id === id); if (!record || record.lifecycle === "draft") throw new Error("only sent comments can be resolved; refresh the task review and use sent comment ids"); return record.lifecycle === "sent" ? [id] : []; // Dismissal is terminal and can never be reopened by the owner. }); } hasReviewCommentsState(): boolean { return (this.db.query(`SELECT EXISTS(SELECT 1 FROM review_comments) OR EXISTS(SELECT 1 FROM review_comment_packages) OR EXISTS(SELECT 1 FROM tasks AS task,json_each(task.history) AS history,json_each(json_extract(history.value,'$.reviewFindings.items')) AS finding WHERE json_type(finding.value,'$.anchor')='object') AS present`).get() as { present: number }).present === 1; } reviewCommentsIntegrity(): { comments: number; packages: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.review-comments/v1\n"); let comments = 0, packages = 0; for (const row of this.db.query("SELECT DISTINCT task_id,task_created FROM review_comments ORDER BY task_id,task_created").iterate() as Iterable<{ task_id: number; task_created: number }>) for (const record of this.reviewComments(row.task_id, row.task_created)) { digest.update(JSON.stringify(record)).update("\n"); comments++; } for (const row of this.db.query("SELECT id,task_id,task_created,body FROM review_comment_packages ORDER BY id").iterate()) { digest.update(JSON.stringify(row)).update("\n"); packages++; } return { comments, packages, digest: digest.digest("hex") }; })(); } hasResearchState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_campaigns) OR EXISTS(SELECT 1 FROM research_units) OR EXISTS(SELECT 1 FROM research_protocols) OR EXISTS(SELECT 1 FROM research_attempts) OR EXISTS(SELECT 1 FROM research_attempt_events) OR EXISTS(SELECT 1 FROM research_attempt_observations) OR EXISTS(SELECT 1 FROM research_runner_receipts) AS present").get() as { present: number }).present === 1; } /** A consistent, streaming digest includes metadata and body hashes, not merely row counts. */ researchIntegrity(): { campaigns: number; units: number; revision: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.research-integrity/v1\n"); let campaigns = 0, units = 0, revision = 0; for (const row of this.db.query(`${RESEARCH_CAMPAIGN_SELECT} ORDER BY id,revision`).iterate() as Iterable) { const campaign = researchCampaignFromRow(row), bindings = this.researchBindings(campaign); const { contract: _body, ...metadata } = campaign; digest.update(JSON.stringify(metadata)).update("\n"); for (const binding of bindings) digest.update(JSON.stringify(binding)).update("\n"); campaigns++; units += bindings.length; revision = Math.max(revision, campaign.revision); } if ((this.db.query("SELECT COUNT(*) AS count FROM research_units").get() as { count: number }).count !== units) throw researchFailure(); return { campaigns, units, revision, digest: digest.digest("hex") }; })(); } private experimentFence(fence: ExperimentWriteFence): { task: Task; campaign: ResearchCampaignRecord } { if (!researchText(fence.project) || !researchInteger(fence.taskId) || !researchInteger(fence.taskFlowRevision, 0) || !researchText(fence.owner) || !researchId(fence.campaignId) || !researchInteger(fence.campaignRevision) || !experimentHashValid(fence.campaignHash)) throw experimentFailure(); const task = this.get(fence.taskId), current = this.researchDispatchBinding(fence.taskId), campaign = current?.campaign; if (!task || task.owner !== fence.owner || task.state !== "in_progress" || task.history.length !== fence.taskFlowRevision || !campaign || !current?.binding || campaign.project !== fence.project || campaign.id !== fence.campaignId || campaign.revision !== fence.campaignRevision || campaign.hash !== fence.campaignHash || campaign.status !== "approved") throw experimentFailure(); return { task, campaign }; } experimentProtocol(hash: string): ExperimentProtocolRecord | undefined { if (!experimentHashValid(hash)) throw experimentFailure(); const row = this.db.query(`${EXPERIMENT_PROTOCOL_SELECT} WHERE hash=?`).get(hash) as ExperimentProtocolRow | null; if (!row) return undefined; try { if (typeof row.body !== "string" || !researchText(row.project) || !researchInteger(row.task_id) || !researchText(row.by_peer) || !researchInteger(row.at, 0) || ![0, 1].includes(row.private)) throw experimentFailure(); const protocol = parseExperimentProtocol(JSON.parse(row.body)); if (protocolHash(protocol) !== row.hash || protocol.campaignId !== row.campaign_id || protocol.campaignRevision !== row.campaign_revision) throw experimentFailure(); const campaign = this.researchCampaign(protocol.campaignId, protocol.campaignRevision), task = this.get(row.task_id); if (!campaign || campaign.project !== row.project || !task || !this.researchCampaignBindings(campaign.id, campaign.revision).some(binding => binding.taskId === task.id) || protocol.inputs.some(input => !campaign.contract.sourceIds.includes(input.sourceId))) throw experimentFailure(); return { hash: row.hash, project: row.project, recordedForTaskId: row.task_id, protocol, by: row.by_peer, at: row.at, private: row.private === 1 || campaign.private || task.signals.some(signal => signal === "pii" || signal === "pii_path") }; } catch { throw experimentFailure(); } } saveExperimentProtocol(record: ExperimentProtocolRecord, fence: ExperimentWriteFence): ExperimentProtocolRecord { const protocol = parseExperimentProtocol(record.protocol), hash = protocolHash(protocol); if (hash !== record.hash || record.project !== fence.project || record.recordedForTaskId !== fence.taskId || record.by !== fence.owner || !researchInteger(record.at, 0) || typeof record.private !== "boolean") throw experimentFailure(); return this.atomic(() => { const { task, campaign } = this.experimentFence(fence); if (protocol.campaignId !== campaign.id || protocol.campaignRevision !== campaign.revision || protocol.inputs.some(input => !campaign.contract.sourceIds.includes(input.sourceId))) throw experimentFailure(); if (protocol.variantOf !== undefined) { const baseline = this.experimentProtocol(protocol.variantOf); if (!baseline || baseline.project !== record.project || baseline.protocol.campaignId !== campaign.id || baseline.protocol.campaignRevision !== campaign.revision || baseline.protocol.role !== "baseline") throw experimentFailure(); } if (protocol.supersedes !== undefined) { const previous = this.experimentProtocol(protocol.supersedes); if (!previous || previous.project !== record.project || previous.protocol.campaignId !== campaign.id || previous.protocol.lineage !== protocol.lineage) throw experimentFailure(); } const priv = record.private || campaign.private || task.signals.some(signal => signal === "pii" || signal === "pii_path"); const previous = this.experimentProtocol(hash); if (previous) { if (previous.project !== record.project || previous.recordedForTaskId !== record.recordedForTaskId || canonicalJson(previous.protocol) !== canonicalJson(protocol)) throw experimentFailure(); if (priv) this.taskWrite(() => this.db.query("UPDATE research_protocols SET private=1 WHERE hash=? AND private=0").run(hash)); return this.experimentProtocol(hash)!; } // Capture recording order in this transaction, never from caller or wall-clock timestamps. Legacy rows are not backfilled. const priorFinal = this.experimentPriorFinal(record.project, campaign.id, protocol.lineage); this.taskWrite(() => this.db.query("INSERT INTO research_protocols(hash,project,campaign_id,campaign_revision,task_id,body,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?)") .run(hash, record.project, campaign.id, campaign.revision, task.id, canonicalJson(protocol), record.by, record.at, priv ? 1 : 0)); this.taskWrite(() => this.db.query("INSERT INTO research_protocol_context(protocol_hash,prior_attempt_id,prior_end_seq,context_sha256) VALUES(?,?,?,?)") .run(hash, priorFinal?.attemptId ?? null, priorFinal?.endSeq ?? null, experimentHash({ protocolHash: hash, priorFinal: priorFinal ?? null }))); return this.experimentProtocol(hash)!; }); } experimentComparisonPlan(hash: string): ExperimentComparisonPlanRecord | undefined { if (!experimentHashValid(hash)) throw experimentFailure(); const row = this.db.query(`${EXPERIMENT_PLAN_SELECT} WHERE hash=?`).get(hash) as ExperimentComparisonPlanRow | null; return row ? this.experimentComparisonPlanFromRow(row) : undefined; } private experimentComparisonPlanFromRow(row: ExperimentComparisonPlanRow): ExperimentComparisonPlanRecord { try { if (typeof row.body !== "string" || !researchText(row.project) || !researchInteger(row.task_id) || !researchText(row.by_peer) || !researchInteger(row.at, 0) || ![0, 1].includes(row.private)) throw experimentFailure(); const plan = parseComparisonPlan(JSON.parse(row.body)), campaign = this.researchCampaign(row.campaign_id, row.campaign_revision), task = this.get(row.task_id); if (comparisonPlanHash(plan) !== row.hash || plan.campaignId !== row.campaign_id || !campaign || campaign.project !== row.project || !task || !this.researchCampaignBindings(campaign.id, campaign.revision).some(binding => binding.taskId === task.id) || plan.fixed.inputs.some(input => !campaign.contract.sourceIds.includes(input.sourceId))) throw experimentFailure(); return { hash: row.hash, project: row.project, recordedForTaskId: row.task_id, plan, by: row.by_peer, at: row.at, private: row.private === 1 || campaign.private || task.signals.some(signal => signal === "pii" || signal === "pii_path") }; } catch { throw experimentFailure(); } } saveExperimentComparisonPlan(record: ExperimentComparisonPlanRecord, fence: ExperimentWriteFence): ExperimentComparisonPlanRecord { const plan = parseComparisonPlan(record.plan), hash = comparisonPlanHash(plan); if (hash !== record.hash || record.project !== fence.project || record.recordedForTaskId !== fence.taskId || record.by !== fence.owner || !researchInteger(record.at, 0) || typeof record.private !== "boolean") throw experimentFailure(); return this.atomic(() => { const { task, campaign } = this.experimentFence(fence); if (plan.campaignId !== campaign.id || plan.fixed.inputs.some(input => !campaign.contract.sourceIds.includes(input.sourceId))) throw experimentFailure(); const priv = record.private || campaign.private || task.signals.some(signal => signal === "pii" || signal === "pii_path"), previous = this.experimentComparisonPlan(hash); if (previous) { if (previous.project !== record.project || previous.recordedForTaskId !== record.recordedForTaskId || canonicalJson(previous.plan) !== canonicalJson(plan)) throw experimentFailure(); if (priv) this.taskWrite(() => this.db.query("UPDATE research_plans SET private=1 WHERE hash=? AND private=0").run(hash)); return this.experimentComparisonPlan(hash)!; } this.taskWrite(() => this.db.query("INSERT INTO research_plans(hash,project,campaign_id,campaign_revision,task_id,body,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?)") .run(hash, record.project, campaign.id, campaign.revision, task.id, canonicalJson(plan), record.by, record.at, priv ? 1 : 0)); return this.experimentComparisonPlan(hash)!; }); } experimentComparisonPlans(project: string, campaignId: string, afterRow = 0, limit = 50): { rows: ExperimentComparisonPlanRecord[]; afterRow: number; done: boolean } { if (!researchText(project) || !researchId(campaignId)) throw experimentFailure(); experimentPage(afterRow, limit); const campaign = this.researchCampaign(campaignId); if (!campaign || campaign.project !== project) throw experimentFailure(); const page = this.db.query(`${EXPERIMENT_PLAN_SELECT} WHERE project=? AND campaign_id=? AND rowid>? ORDER BY rowid LIMIT ?`).all(project, campaignId, afterRow, limit + 1) as ExperimentComparisonPlanRow[]; return { rows: page.slice(0, limit).map(row => this.experimentComparisonPlanFromRow(row)), afterRow: page.slice(0, limit).at(-1)?.row_id ?? afterRow, done: page.length <= limit }; } experimentProtocolApproval(hash: string): ExperimentProtocolApproval | undefined { const protocol = this.experimentProtocol(hash); if (!protocol) throw experimentFailure(); const row = this.db.query("SELECT protocol_hash,evaluator_hash,approved_by,at FROM research_protocol_approvals WHERE protocol_hash=?").get(hash) as ExperimentProtocolApprovalRow | null; if (!row) return undefined; if (row.protocol_hash !== hash || row.evaluator_hash !== evaluatorIdentityHash(protocol.protocol) || row.approved_by !== USER || !researchInteger(row.at, 0)) throw experimentFailure(); return { protocolHash: hash, evaluatorHash: row.evaluator_hash, approvedBy: row.approved_by, at: row.at }; } /** Explicit approval names one immutable historical or current protocol; nothing copies to a changed protocol. */ approveExperimentProtocol(project: string, hash: string, evaluatorHash: string, by: PeerId, at: number): ExperimentProtocolApproval { if (by !== USER || !researchText(project) || !experimentHashValid(hash) || !experimentHashValid(evaluatorHash) || !researchInteger(at, 0)) throw experimentFailure(); return this.atomic(() => { const protocol = this.experimentProtocol(hash); if (!protocol || protocol.project !== project || evaluatorIdentityHash(protocol.protocol) !== evaluatorHash) throw experimentFailure(); const previous = this.experimentProtocolApproval(hash); if (previous) return previous; this.taskWrite(() => this.db.query("INSERT INTO research_protocol_approvals(protocol_hash,evaluator_hash,approved_by,at) VALUES(?,?,?,?)").run(hash, evaluatorHash, by, at)); return this.experimentProtocolApproval(hash)!; }); } // ponytail: first insertion streams ended attempts until a matching lineage is found; index lineage/phase if campaign histories become large. private experimentPriorFinal(project: string, campaignId: string, lineage: string): { attemptId: string; endSeq: number } | undefined { const ends = this.db.query("SELECT e.attempt_id,e.seq FROM research_attempt_events AS e JOIN research_attempts AS a ON a.attempt_id=e.attempt_id WHERE a.project=? AND a.campaign_id=? AND e.kind='end' ORDER BY e.rowid DESC").iterate(project, campaignId) as Iterable<{ attempt_id: string; seq: number }>; for (const end of ends) { const attempt = this.experimentAttempt(end.attempt_id), protocol = attempt && this.experimentProtocol(attempt.attempt.protocolHash); if (!attempt || !protocol || attempt.project !== project || protocol.protocol.campaignId !== campaignId) throw experimentFailure(); const event = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq=?`).get(end.attempt_id, end.seq) as ExperimentEventRow | null; if (!event || this.experimentEventFromRow(event).event.kind !== "end") throw experimentFailure(); if (attempt.attempt.phase === "final" && protocol.protocol.lineage === lineage) return { attemptId: attempt.attemptId, endSeq: end.seq }; } return undefined; } experimentProtocolContext(hash: string): ExperimentProtocolContext { const protocol = this.experimentProtocol(hash); if (!protocol) throw experimentFailure(); const row = this.db.query("SELECT protocol_hash,prior_attempt_id,prior_end_seq,context_sha256 FROM research_protocol_context WHERE protocol_hash=?").get(hash) as ExperimentProtocolContextRow | null; if (!row) return { state: "unknown" }; if (row.protocol_hash !== hash || (row.prior_attempt_id === null) !== (row.prior_end_seq === null)) throw experimentFailure(); if (row.prior_attempt_id === null) { if (row.context_sha256 !== experimentHash({ protocolHash: hash, priorFinal: null })) throw experimentFailure(); return { state: "predeclared" }; } if (!experimentIdValid(row.prior_attempt_id) || !researchInteger(row.prior_end_seq)) throw experimentFailure(); const attempt = this.experimentAttempt(row.prior_attempt_id), previous = attempt && this.experimentProtocol(attempt.attempt.protocolHash); const event = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq=?`).get(row.prior_attempt_id, row.prior_end_seq) as ExperimentEventRow | null; const priorFinal = { attemptId: row.prior_attempt_id, endSeq: row.prior_end_seq }; if (!attempt || !previous || !event || attempt.project !== protocol.project || attempt.attempt.phase !== "final" || previous.protocol.campaignId !== protocol.protocol.campaignId || previous.protocol.lineage !== protocol.protocol.lineage || this.experimentEventFromRow(event).event.kind !== "end" || row.context_sha256 !== experimentHash({ protocolHash: hash, priorFinal })) throw experimentFailure(); return { state: "post-hoc", priorFinal }; } hasResearchComparisonState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_plans) OR EXISTS(SELECT 1 FROM research_protocol_approvals) OR EXISTS(SELECT 1 FROM research_protocol_context) AS present").get() as { present: number }).present === 1; } researchComparisonIntegrity(): { plans: number; approvals: number; contexts: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.research-comparison-integrity/v1\n"); let plans = 0, approvals = 0, contexts = 0; for (const row of this.db.query(`${EXPERIMENT_PLAN_SELECT} ORDER BY hash`).iterate() as Iterable) { digest.update(canonicalJson({ record: this.experimentComparisonPlanFromRow(row), campaignRevision: row.campaign_revision })).update("\n"); plans++; } for (const row of this.db.query("SELECT protocol_hash,evaluator_hash,approved_by,at FROM research_protocol_approvals ORDER BY protocol_hash").iterate() as Iterable) { digest.update(canonicalJson(this.experimentProtocolApproval(row.protocol_hash))).update("\n"); approvals++; } for (const row of this.db.query("SELECT protocol_hash FROM research_protocol_context ORDER BY protocol_hash").iterate() as Iterable<{ protocol_hash: string }>) { digest.update(canonicalJson({ protocolHash: row.protocol_hash, context: this.experimentProtocolContext(row.protocol_hash) })).update("\n"); contexts++; } return { plans, approvals, contexts, digest: digest.digest("hex") }; })(); } experimentAttempt(id: string): ExperimentAttemptRecord | undefined { if (!experimentIdValid(id)) throw experimentFailure(); const row = this.db.query(`${EXPERIMENT_ATTEMPT_SELECT} WHERE attempt_id=?`).get(id) as ExperimentAttemptRow | null; return row ? this.experimentAttemptFromRow(row) : undefined; } private experimentAttemptFromRow(row: ExperimentAttemptRow): ExperimentAttemptRecord { try { if (!experimentIdValid(row.attempt_id) || typeof row.body !== "string" || !researchText(row.project) || !researchText(row.by_peer) || !researchInteger(row.at, 0) || ![0, 1].includes(row.private)) throw experimentFailure(); const attempt = parseExperimentAttempt(JSON.parse(row.body)), protocol = this.experimentProtocol(row.protocol_hash); if (experimentHash(attempt) !== row.body_sha256 || attempt.protocolHash !== row.protocol_hash || attempt.taskId !== row.task_id || attempt.idempotencyKey !== row.idempotency_key || !protocol || protocol.project !== row.project || protocol.protocol.campaignId !== row.campaign_id || protocol.protocol.campaignRevision !== row.campaign_revision || !this.researchCampaignBindings(row.campaign_id, row.campaign_revision).some(binding => binding.taskId === attempt.taskId)) throw experimentFailure(); const privateEvent = !!this.db.query("SELECT 1 FROM research_attempt_events WHERE attempt_id=? AND private=1 LIMIT 1").get(row.attempt_id); return { attemptId: row.attempt_id, project: row.project, attempt, bodyHash: row.body_sha256, by: row.by_peer, at: row.at, private: row.private === 1 || protocol.private || privateEvent }; } catch { throw experimentFailure(); } } createExperimentAttempt(record: ExperimentAttemptRecord, fence: ExperimentWriteFence): ExperimentAttemptRecord { const attempt = parseExperimentAttempt(record.attempt), bodyHash = experimentHash(attempt); if (!experimentIdValid(record.attemptId) || record.bodyHash !== bodyHash || record.project !== fence.project || attempt.taskId !== fence.taskId || record.by !== fence.owner || !researchInteger(record.at, 0) || typeof record.private !== "boolean") throw experimentFailure(); return this.atomic(() => { const { campaign } = this.experimentFence(fence), protocol = this.experimentProtocol(attempt.protocolHash); const origin = protocol && this.researchDispatchBinding(protocol.recordedForTaskId); if (!protocol || protocol.project !== record.project || protocol.protocol.campaignId !== campaign.id || protocol.protocol.campaignRevision !== campaign.revision || !origin?.binding || origin.campaign.id !== campaign.id || origin.campaign.revision !== campaign.revision || origin.campaign.status !== "approved") throw experimentFailure(); const previous = this.db.query(`${EXPERIMENT_ATTEMPT_SELECT} WHERE project=? AND idempotency_key=?`).get(record.project, attempt.idempotencyKey) as ExperimentAttemptRow | null; if (previous) { const stored = this.experimentAttemptFromRow(previous); if (stored.bodyHash !== bodyHash || canonicalJson(stored.attempt) !== canonicalJson(attempt)) throw new Error("attempt idempotency key already records different data"); if (record.private || protocol.private) this.taskWrite(() => this.db.query("UPDATE research_attempts SET private=1 WHERE attempt_id=? AND private=0").run(stored.attemptId)); return this.experimentAttempt(stored.attemptId)!; } for (const linked of [attempt.retryOf, attempt.reproducesAttemptId]) if (linked !== undefined) { const prior = this.experimentAttempt(linked), priorProtocol = prior && this.experimentProtocol(prior.attempt.protocolHash); if (!prior || !priorProtocol || prior.project !== record.project || priorProtocol.protocol.campaignId !== campaign.id) throw experimentFailure(); } this.taskWrite(() => this.db.query("INSERT INTO research_attempts(attempt_id,project,campaign_id,campaign_revision,protocol_hash,task_id,idempotency_key,body,body_sha256,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)") .run(record.attemptId, record.project, campaign.id, campaign.revision, attempt.protocolHash, attempt.taskId, attempt.idempotencyKey, canonicalJson(attempt), bodyHash, record.by, record.at, record.private || protocol.private ? 1 : 0)); return this.experimentAttempt(record.attemptId)!; }); } private experimentEventFromRow(row: ExperimentEventRow): ExperimentEventRecord { try { if (typeof row.body !== "string" || !researchInteger(row.seq) || !researchInteger(row.at, 0) || !researchText(row.by_peer) || ![0, 1].includes(row.private) || !researchText(row.idempotency_key, 64)) throw experimentFailure(); const attempt = this.experimentAttempt(row.attempt_id), protocol = attempt && this.experimentProtocol(attempt.attempt.protocolHash); if (!attempt || !protocol || row.project !== attempt.project) throw experimentFailure(); if (row.kind === "attestation") { const raw = JSON.parse(row.body), body = raw?.body, receipt = typeof body?.receiptId === "string" && this.runnerReceipt(body.receiptId); if (!receipt || raw.kind !== "attestation" || Object.keys(raw).length !== 2 || Object.keys(body).length !== 1 || receipt.receipt.attemptId !== row.attempt_id || receipt.seq !== row.seq || receipt.at !== row.at || receipt.by !== row.by_peer || row.body_sha256 !== experimentHash({ kind: "attestation", body }) || row.idempotency_key !== `rr-${receipt.bodyHash.slice(0, 61)}` || this.db.query("SELECT 1 FROM research_attempt_observations WHERE attempt_id=? AND event_seq=?").get(row.attempt_id, row.seq)) throw experimentFailure(); return { attemptId: row.attempt_id, idempotencyKey: row.idempotency_key, event: { kind: "attestation", body: { receiptId: receipt.receipt.receiptId }, seq: row.seq, at: row.at, provenance: "runner-attested" }, bodyHash: row.body_sha256, by: row.by_peer, private: row.private === 1 || attempt.private || receipt.private, observations: [] }; } const input = parseExperimentEvent(JSON.parse(row.body), protocol.protocol); if (input.kind !== row.kind || experimentHash(input) !== row.body_sha256) throw experimentFailure(); const event = { ...input, seq: row.seq, at: row.at, provenance: "declared" as const }; const observations = (this.db.query("SELECT attempt_id,event_seq,CASE WHEN length(CAST(body AS BLOB))<=65536 THEN body END AS body,body_sha256 FROM research_attempt_observations WHERE attempt_id=? AND event_seq=?").all(row.attempt_id, row.seq) as ExperimentObservationRow[]).map(observed => { if (typeof observed.body !== "string" || observed.attempt_id !== row.attempt_id || observed.event_seq !== row.seq) throw experimentFailure(); const observation = parseExperimentHostEvidence(JSON.parse(observed.body)); if (experimentHash(observation) !== observed.body_sha256) throw experimentFailure(); return { eventSeq: row.seq, observation }; }); projectExperimentWithObservations(protocol.protocol, [event], observations); return { attemptId: row.attempt_id, idempotencyKey: row.idempotency_key, event, bodyHash: row.body_sha256, by: row.by_peer, private: row.private === 1 || attempt.private, observations }; } catch { throw experimentFailure(); } } appendExperimentEvent(attemptId: string, key: string, input: DeclaredExperimentEventInput, hostEvidence: readonly ExperimentHostEvidence[], by: PeerId, at: number, priv: boolean, expectedLastSeq: number, fence: ExperimentWriteFence): ExperimentEventRecord { if (!experimentIdValid(attemptId) || !researchText(key, 64) || by !== fence.owner || !researchInteger(at, 0) || typeof priv !== "boolean" || !researchInteger(expectedLastSeq, 0) || !Array.isArray(hostEvidence) || hostEvidence.length > 1) throw experimentFailure(); return this.atomic(() => { const { campaign } = this.experimentFence(fence), attempt = this.experimentAttempt(attemptId), protocol = attempt && this.experimentProtocol(attempt.attempt.protocolHash); if (!attempt || !protocol || attempt.project !== fence.project || attempt.attempt.taskId !== fence.taskId || protocol.protocol.campaignId !== campaign.id || protocol.protocol.campaignRevision !== campaign.revision) throw experimentFailure(); const value = parseExperimentEvent(input, protocol.protocol), bodyHash = experimentHash(value); const previous = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE project=? AND idempotency_key=?`).get(fence.project, key) as ExperimentEventRow | null; if (previous) { const stored = this.experimentEventFromRow(previous); if (stored.attemptId !== attemptId || stored.bodyHash !== bodyHash || canonicalJson({ kind: stored.event.kind, body: stored.event.body }) !== canonicalJson(value)) throw new Error("event idempotency key already records different data"); if (priv || attempt.private) { this.taskWrite(() => this.db.query("UPDATE research_attempt_events SET private=1 WHERE attempt_id=? AND seq=? AND private=0").run(attemptId, stored.event.seq)); this.taskWrite(() => this.db.query("UPDATE research_attempts SET private=1 WHERE attempt_id=? AND private=0").run(attemptId)); } return this.experimentEventFromRow(this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq=?`).get(attemptId, stored.event.seq) as ExperimentEventRow); } if (this.experimentLastSeq(attemptId) !== expectedLastSeq || !researchInteger(expectedLastSeq + 1)) throw new Error("experiment event sequence changed"); if (value.kind === "end" && this.db.query("SELECT 1 FROM research_attempt_events WHERE attempt_id=? AND kind='end'").get(attemptId)) throw new Error("an experiment attempt has at most one end event"); const seq = expectedLastSeq + 1, observations = hostEvidence.map(observation => ({ eventSeq: seq, observation: parseExperimentHostEvidence(observation) })); projectExperimentWithObservations(protocol.protocol, [{ ...value, seq, at, provenance: "declared" }], observations); this.taskWrite(() => this.db.query("INSERT INTO research_attempt_events(attempt_id,project,seq,idempotency_key,kind,body,body_sha256,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?,?)") .run(attemptId, fence.project, seq, key, value.kind, canonicalJson(value), bodyHash, by, at, priv || attempt.private ? 1 : 0)); for (const observed of observations) this.taskWrite(() => this.db.query("INSERT INTO research_attempt_observations(attempt_id,event_seq,body,body_sha256) VALUES(?,?,?,?)") .run(attemptId, seq, canonicalJson(observed.observation), experimentHash(observed.observation))); if (priv || attempt.private) this.taskWrite(() => this.db.query("UPDATE research_attempts SET private=1 WHERE attempt_id=? AND private=0").run(attemptId)); return this.experimentEventFromRow(this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq=?`).get(attemptId, seq) as ExperimentEventRow); }); } private runnerReceiptFromRow(row: RunnerReceiptRow): RunnerReceiptRecord { try { if (typeof row.body !== "string" || !researchInteger(row.event_seq) || !researchInteger(row.at, 0) || !researchText(row.by_peer) || ![0, 1].includes(row.private)) throw experimentFailure(); const raw = JSON.parse(row.body); if (!raw || Object.keys(raw).sort().join(",") !== "publicKey,receipt,signature") throw experimentFailure(); const receipt = parseAttemptReceipt(raw.receipt); const runner = parseResearchRunners({ [receipt.runner]: { publicKey: raw.publicKey, projects: [receipt.projectId], revoked: false } })[receipt.runner]!; if (typeof raw.signature !== "string" || raw.signature.length !== 88 || Buffer.from(raw.signature, "base64").length !== 64 || Buffer.from(raw.signature, "base64").toString("base64") !== raw.signature) throw experimentFailure(); const body = { receipt, signature: raw.signature as string, publicKey: runner.publicKey }; const attempt = this.experimentAttempt(receipt.attemptId), protocol = attempt && this.experimentProtocol(attempt.attempt.protocolHash); if (!attempt || !protocol || row.receipt_id !== receipt.receiptId || row.attempt_id !== receipt.attemptId || row.project !== receipt.projectId || row.project !== attempt.project || receipt.protocolHash !== attempt.attempt.protocolHash || experimentHash(body) !== row.body_sha256 || receipt.codeCommit !== undefined && "commit" in protocol.protocol.code && receipt.codeCommit !== protocol.protocol.code.commit) throw experimentFailure(); const event = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq=?`).get(row.attempt_id, row.event_seq) as ExperimentEventRow | null; const expectedEvent = { kind: "attestation", body: { receiptId: receipt.receiptId } }; if (!event || event.kind !== "attestation" || typeof event.body !== "string" || event.body !== canonicalJson(expectedEvent) || event.body_sha256 !== experimentHash(expectedEvent) || event.project !== row.project || event.by_peer !== row.by_peer || event.at !== row.at || event.idempotency_key !== `rr-${row.body_sha256.slice(0, 61)}` || ![0, 1].includes(event.private) || this.db.query("SELECT 1 FROM research_attempt_observations WHERE attempt_id=? AND event_seq=?").get(row.attempt_id, row.event_seq)) throw experimentFailure(); return { ...body, keyHash: createHash("sha256").update(Buffer.from(runner.publicKey, "base64")).digest("hex"), bodyHash: row.body_sha256, seq: row.event_seq, by: row.by_peer, at: row.at, private: row.private === 1 || event.private === 1 || attempt.private }; } catch { throw experimentFailure(); } } runnerReceipt(id: string): RunnerReceiptRecord | undefined { const row = this.db.query(`${RUNNER_RECEIPT_SELECT} WHERE receipt_id=?`).get(id) as RunnerReceiptRow | null; return row ? this.runnerReceiptFromRow(row) : undefined; } runnerReceipts(attemptId: string): RunnerReceiptRecord[] { if (!this.experimentAttempt(attemptId)) throw experimentFailure(); // ponytail: at most 64 signed receipts per attempt; paginate only with a reviewed evidence-page contract. const rows = this.db.query(`${RUNNER_RECEIPT_SELECT} WHERE attempt_id=? ORDER BY event_seq LIMIT 65`).all(attemptId) as RunnerReceiptRow[]; if (rows.length > 64) throw experimentFailure(); return rows.map(row => this.runnerReceiptFromRow(row)); } appendRunnerReceipt(record: Pick, expectedLastSeq: number, fence: ExperimentWriteFence): RunnerReceiptRecord { const receipt = parseAttemptReceipt(record.receipt), attempt = this.experimentAttempt(receipt.attemptId), protocol = attempt && this.experimentProtocol(attempt.attempt.protocolHash); if (!attempt || !protocol || record.by !== fence.owner && record.by !== USER || !researchInteger(record.at, 0) || typeof record.private !== "boolean" || !researchInteger(expectedLastSeq, 0)) throw experimentFailure(); const body = { receipt, signature: record.signature, publicKey: record.publicKey }, bodyHash = experimentHash(body); return this.atomic(() => { const { campaign } = this.experimentFence(fence); if (attempt.project !== fence.project || attempt.attempt.taskId !== fence.taskId || protocol.protocol.campaignId !== campaign.id || protocol.protocol.campaignRevision !== campaign.revision) throw experimentFailure(); const prior = this.runnerReceipt(receipt.receiptId); if (prior) { if (prior.bodyHash !== bodyHash || canonicalJson({ receipt: prior.receipt, signature: prior.signature, publicKey: prior.publicKey }) !== canonicalJson(body)) throw new Error("receiptId already records different signed bytes"); return prior; } verifyAttemptReceipt(receipt, record.signature, { runners: { [receipt.runner]: { publicKey: record.publicKey, projects: [fence.project], revoked: false } }, projectId: fence.project, attempt: { id: attempt.attemptId, projectId: attempt.project, protocolHash: attempt.attempt.protocolHash, ...("commit" in protocol.protocol.code ? { codeCommit: protocol.protocol.code.commit } : {}) } }); if (this.runnerReceipts(attempt.attemptId).length >= 64) throw new Error("an attempt supports at most 64 runner receipts"); if (this.experimentLastSeq(attempt.attemptId) !== expectedLastSeq || !researchInteger(expectedLastSeq + 1)) throw new Error("experiment event sequence changed"); const seq = expectedLastSeq + 1, event = { kind: "attestation", body: { receiptId: receipt.receiptId } }; // The first attestation is incompatible with older event readers, so both writes and the format floor commit together. advanceHubDbSchema(this.db, 2, "0.26.0"); this.taskWrite(() => this.db.query("INSERT INTO research_attempt_events(attempt_id,project,seq,idempotency_key,kind,body,body_sha256,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?,?)") .run(attempt.attemptId, fence.project, seq, `rr-${bodyHash.slice(0, 61)}`, "attestation", canonicalJson(event), experimentHash(event), record.by, record.at, record.private || attempt.private ? 1 : 0)); this.taskWrite(() => this.db.query("INSERT INTO research_runner_receipts(receipt_id,project,attempt_id,event_seq,body,body_sha256,by_peer,at,private) VALUES(?,?,?,?,?,?,?,?,?)") .run(receipt.receiptId, fence.project, attempt.attemptId, seq, canonicalJson(body), bodyHash, record.by, record.at, record.private || attempt.private ? 1 : 0)); if (record.private || attempt.private) this.taskWrite(() => this.db.query("UPDATE research_attempts SET private=1 WHERE attempt_id=? AND private=0").run(attempt.attemptId)); return this.runnerReceipt(receipt.receiptId)!; }); } hasRunnerReceipts(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_runner_receipts) OR EXISTS(SELECT 1 FROM research_attempt_events WHERE kind='attestation') AS present").get() as { present: number }).present === 1; } runnerReceiptIntegrity(): { count: number; digest: string } { return this.db.transaction(() => { if (this.db.query("SELECT 1 FROM research_attempt_events AS e LEFT JOIN research_runner_receipts AS r ON r.attempt_id=e.attempt_id AND r.event_seq=e.seq WHERE e.kind='attestation' AND r.receipt_id IS NULL LIMIT 1").get()) throw experimentFailure(); const digest = createHash("sha256").update("agent-hub.runner-receipts-integrity/v1\n"); let count = 0; for (const row of this.db.query(`${RUNNER_RECEIPT_SELECT} ORDER BY receipt_id`).iterate() as Iterable) { digest.update(canonicalJson(this.runnerReceiptFromRow(row))).update("\n"); count++; } return { count, digest: digest.digest("hex") }; }).deferred(); } experimentLastSeq(attemptId: string): number { if (!this.experimentAttempt(attemptId)) throw experimentFailure(); const last = this.db.query("SELECT MAX(seq) AS seq,COUNT(*) AS count FROM research_attempt_events WHERE attempt_id=?").get(attemptId) as { seq: number | null; count: number }; const seq = last.seq ?? 0; if (!researchInteger(seq, 0) || last.count !== seq) throw experimentFailure(); return seq; } experimentEvents(attemptId: string, afterSeq = 0, limit = 50): { rows: ExperimentEventRecord[]; afterSeq: number; done: boolean } { if (!this.experimentAttempt(attemptId)) throw experimentFailure(); experimentPage(afterSeq, limit); const page = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND seq>? ORDER BY seq LIMIT ?`).all(attemptId, afterSeq, limit + 1) as ExperimentEventRow[]; const rows = page.slice(0, limit).map(row => this.experimentEventFromRow(row)); return { rows, afterSeq: rows.at(-1)?.event.seq ?? afterSeq, done: page.length <= limit }; } experimentAttempts(project: string, campaignId: string, afterRow = 0, limit = 50): { rows: ExperimentAttemptRecord[]; afterRow: number; done: boolean } { if (!researchText(project) || !researchId(campaignId)) throw experimentFailure(); experimentPage(afterRow, limit); const campaign = this.researchCampaign(campaignId); if (!campaign || campaign.project !== project) throw experimentFailure(); const page = this.db.query(`${EXPERIMENT_ATTEMPT_SELECT} WHERE project=? AND rowid>? AND campaign_id=? ORDER BY rowid LIMIT ?`) .all(project, afterRow, campaignId, limit + 1) as ExperimentAttemptRow[]; return { rows: page.slice(0, limit).map(row => this.experimentAttemptFromRow(row)), afterRow: page.slice(0, limit).at(-1)?.row_id ?? afterRow, done: page.length <= limit }; } experimentAttemptStatus(attemptId: string): ExperimentStatus { const attempt = this.experimentAttempt(attemptId); if (!attempt) throw experimentFailure(); const endRows = this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND kind='end' ORDER BY seq LIMIT 2`).all(attemptId) as ExperimentEventRow[]; if (endRows.length > 1) throw experimentFailure(); const end = endRows[0], start = !end && this.db.query(`${EXPERIMENT_EVENT_SELECT} WHERE attempt_id=? AND kind='start' ORDER BY seq LIMIT 1`).get(attemptId) as ExperimentEventRow | null; const events = end ? [this.experimentEventFromRow(end).event] : start ? [this.experimentEventFromRow(start).event] : []; return experimentStatus(declaredExperimentEvents(events), this.get(attempt.attempt.taskId)?.state); } // ponytail: exact counts validate all campaign attempts on each show (linear in attempt count). Upgrade to a transactional status projection maintained on event and task-state changes. experimentSummary(project: string, campaignId: string): { total: number; statuses: Record } { const campaign = this.researchCampaign(campaignId); if (!campaign || campaign.project !== project) throw experimentFailure(); const statuses: Record = { declared: 0, running: 0, succeeded: 0, failed: 0, cancelled: 0, unknown: 0 }; let total = 0; for (const row of this.db.query(`${EXPERIMENT_ATTEMPT_SELECT} WHERE project=? AND campaign_id=? ORDER BY rowid`).iterate(project, campaignId) as Iterable) { const attempt = this.experimentAttemptFromRow(row); // Status needs only the unique terminal event or presence of a start, not an unbounded event read. statuses[this.experimentAttemptStatus(attempt.attemptId)]++; total++; } return { total, statuses }; } hasResearchExperimentState(): boolean { return (this.db.query("SELECT EXISTS(SELECT 1 FROM research_protocols) OR EXISTS(SELECT 1 FROM research_attempts) OR EXISTS(SELECT 1 FROM research_attempt_events) OR EXISTS(SELECT 1 FROM research_attempt_observations) OR EXISTS(SELECT 1 FROM research_runner_receipts) AS present").get() as { present: number }).present === 1; } researchExperimentsIntegrity(): { protocols: number; attempts: number; events: number; observations: number; digest: string } { return this.db.transaction(() => { const digest = createHash("sha256").update("agent-hub.research-experiments-integrity/v1\n"); let protocols = 0, attempts = 0, events = 0, observations = 0; for (const row of this.db.query(`${EXPERIMENT_PROTOCOL_SELECT} ORDER BY hash`).iterate() as Iterable) { digest.update(canonicalJson(this.experimentProtocol(row.hash))).update("\n"); protocols++; } for (const row of this.db.query(`${EXPERIMENT_ATTEMPT_SELECT} ORDER BY attempt_id`).iterate() as Iterable) { digest.update(canonicalJson(this.experimentAttemptFromRow(row))).update("\n"); attempts++; } let currentAttempt = "", nextSeq = 0, ended = false; for (const row of this.db.query(`${EXPERIMENT_EVENT_SELECT} ORDER BY attempt_id,seq`).iterate() as Iterable) { if (row.attempt_id !== currentAttempt) { currentAttempt = row.attempt_id; nextSeq = 1; ended = false; } if (row.seq !== nextSeq++ || row.kind === "end" && ended) throw experimentFailure(); if (row.kind === "end") ended = true; const record = this.experimentEventFromRow(row); digest.update(canonicalJson(record)).update("\n"); events++; observations += record.observations.length; } if ((this.db.query("SELECT COUNT(*) AS count FROM research_attempt_observations").get() as { count: number }).count !== observations) throw experimentFailure(); return { protocols, attempts, events, observations, digest: digest.digest("hex") }; })(); } 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 { // Host-only synchronous DB bookkeeping. Never sourced from task input or called with I/O/screens. if (createdHook !== undefined) { if (typeof createdHook !== "function") throw new Error("invalid host proposal hook"); return this.atomic(() => { const task = this.propose(by, t); createdHook(task); return task; }); } const now = Date.now(), planner = plannerValue(t.planner); const chosen = Object.hasOwn(t, "planner") || t.plannerReason !== undefined ? plannerMetadata(planner, t.plannerReason) : {}; const history: HistoryEntry[] = [{ at: now, by, ...instructedHistory(by), ...chosen, event: t.backlog ? "backlogged" : "proposed", ...(this.trackPlanRevisions?.() && t.plan && Object.keys(t.plan).length ? { planRevision: { revision: 1, fingerprint: planFingerprint(t.plan) } } : {}) }]; const { lastInsertRowid } = this.taskWrite(() => { const inserted = this.db .query("INSERT INTO tasks (title, detail, class, state, refs, plan, deps, reserved, signals, history, created, updated, project_profile, task_role, external_repo, external_issue, planner, draft) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") .run(t.title, t.detail ?? "", t.class, t.backlog ? "backlog" : "proposed", JSON.stringify(t.refs ?? {}), JSON.stringify(t.plan ?? {}), JSON.stringify(t.deps ?? []), t.reserved ?? null, JSON.stringify(t.signals ?? []), JSON.stringify(history), now, now, t.profile && (t.profile !== "dev" || t.customProfile || t.profileClass !== undefined && t.profileClass !== t.class) ? JSON.stringify({ profile: t.profile, profileClass: t.profileClass ?? t.class }) : null, t.role ?? null, t.external?.repo.toLowerCase() ?? null, t.external?.issue ?? null, planner, t.draft && t.backlog ? 1 : 0); if (this.proposalPlanner && !Object.hasOwn(t, "planner") && t.plannerReason === undefined) { const selected = this.proposalPlanner(this.get(Number(inserted.lastInsertRowid))!); const binding = plannerMetadata(selected.planner, selected.plannerReason); Object.assign(history[0]!, binding); this.db.query("UPDATE tasks SET planner=?,history=? WHERE id=?").run(binding.planner ?? null, JSON.stringify(history), inserted.lastInsertRowid); } return inserted; }); const task = this.get(Number(lastInsertRowid))!; this.changed(task, history[0]!); return task; } imported(repo: string, issue: number): Task | undefined { const row = this.db.query(`${TASK_SELECT} WHERE external_repo=? AND external_issue=?`).get(repo.toLowerCase(), issue) as Record | null; return row ? parse(row) : undefined; } get(id: number): Task | undefined { const row = this.db.query(`${TASK_SELECT} WHERE id = ?`).get(id) as Record | null; return row ? parse(row) : undefined; } list(state?: TaskState): Task[] { const rows = state ? this.db.query(`${TASK_SELECT} WHERE state = ? ORDER BY id`).all(state) : this.db.query(`${TASK_SELECT} ORDER BY id`).all(); return (rows as Record[]).map(parse); } /** A bounded, read-only source projection. Unknown/capped results never authorize carry. */ specAcceptanceCandidates(destination: number): { rows: SpecAcceptanceCandidate[]; complete: boolean } { const unavailable = { rows: [], complete: false }; if (!Number.isSafeInteger(destination) || destination <= 0) return unavailable; const object = (column: string) => `CASE WHEN length(CAST(${column} AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN CASE WHEN json_valid(${column}) THEN json_type(${column})='object' ELSE 0 END ELSE 0 END`; const cancel = object("cancelled"), receipt = object("sdlc"); try { const found = this.db.query(`WITH candidates AS ( SELECT id,created, CASE WHEN length(CAST(refs AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN refs END AS refs, CASE WHEN length(CAST(signals AS BLOB)) <= ${SPEC_ACCEPTANCE_FIELD_BYTES} THEN signals END AS signals, CASE WHEN ${cancel} THEN json_extract(cancelled,'$.supersededBy') END AS superseded_by, CASE WHEN ${cancel} THEN json_extract(cancelled,'$.flowRevision') END AS cancellation_revision, CASE WHEN ${cancel} THEN json_extract(cancelled,'$.withheld') END AS withheld, CASE WHEN sdlc IS NULL THEN 1 WHEN ${receipt} THEN 1 ELSE 0 END AS receipt_valid, CASE WHEN ${receipt} THEN json_extract(sdlc,'$.repo') END AS repo, CASE WHEN ${receipt} THEN json_extract(sdlc,'$.issue') END AS issue, CASE WHEN ${receipt} THEN CAST(json_extract(sdlc,'$.acceptance') AS TEXT) END AS acceptance FROM tasks WHERE state='cancelled' AND id < ? AND CASE WHEN ${cancel} THEN json_extract(cancelled,'$.supersededBy') IN (?,?,?) ELSE 0 END ORDER BY id DESC LIMIT ? ), projections AS ( SELECT id,json_object('id',id,'created',created,'refs',refs,'signals',signals,'superseded_by',superseded_by, 'cancellation_revision',cancellation_revision,'withheld',withheld,'repo',repo,'issue',issue,'acceptance',acceptance) AS payload, receipt_valid AND refs IS NOT NULL AND signals IS NOT NULL AS valid FROM candidates ), budget AS ( SELECT COUNT(*) <= ${SPEC_ACCEPTANCE_SOURCE_LIMIT} AND MIN(valid) AND SUM(length(CAST(payload AS BLOB))) <= ${SPEC_ACCEPTANCE_TOTAL_BYTES} AS complete FROM projections ) SELECT budget.complete, CASE WHEN budget.complete THEN projections.payload END AS payload FROM projections,budget ORDER BY projections.id DESC`) .all(destination, `task #${destination}`, `#${destination}`, String(destination), SPEC_ACCEPTANCE_SOURCE_LIMIT + 1) as { complete: number; payload: string | null }[]; if (found.some(row => row.complete !== 1 || row.payload === null)) return unavailable; const rows: SpecAcceptanceCandidate[] = []; for (const projected of found) { const row = JSON.parse(projected.payload!) as Record; if (typeof row.refs !== "string" || typeof row.signals !== "string") return unavailable; const refs = JSON.parse(row.refs), signals = JSON.parse(row.signals); if (!refs || typeof refs !== "object" || Array.isArray(refs) || refs.repo !== undefined && typeof refs.repo !== "string" || refs.paths !== undefined && (!Array.isArray(refs.paths) || refs.paths.some((value: unknown) => typeof value !== "string")) || !Array.isArray(signals) || signals.some((value: unknown) => typeof value !== "string") || !Number.isSafeInteger(row.id) || typeof row.created !== "number" || !Number.isFinite(row.created) || typeof row.superseded_by !== "string" || !Number.isSafeInteger(row.cancellation_revision) || Number(row.cancellation_revision) <= 0 || ![null, 0, 1].includes(row.withheld as null | number)) return unavailable; const acceptance = row.acceptance == null ? undefined : JSON.parse(String(row.acceptance)); rows.push({ id: row.id as number, created: row.created, state: "cancelled", refs, signals, supersededBy: row.superseded_by, cancellationRevision: row.cancellation_revision as number, withheld: row.withheld === 1, repo: row.repo, issue: row.issue, acceptance }); } return { rows, complete: true }; } catch { return unavailable; } } /** Structural status facts only; avoid decoding text, plans and growing history on each status write. */ statusTasks(): Pick[] { return this.db.query("SELECT id, state, owner, reviewer FROM tasks WHERE state NOT IN ('approved','cancelled') ORDER BY id").all() as Pick[]; } /** Fresh privacy classification inputs only; no task history, title, detail or plan decoding. */ peerTaskSignals(peer: string): Pick[] { const rows = this.db.query("SELECT state, signals FROM tasks WHERE owner=? OR reviewer=?").all(peer, peer) as { state: unknown; signals: unknown }[]; return rows.map(row => { const signals: unknown = JSON.parse(String(row.signals)); if (typeof row.state !== "string" || !Array.isArray(signals) || signals.some(signal => typeof signal !== "string")) throw new Error("invalid task privacy projection"); return { state: row.state as TaskState, signals: signals as string[] }; }); } /** Fresh privacy facts for a bounded explicit reference set; no task history or text decoding. */ taskPrivacySignals(ids: readonly number[]): Pick[] { if (!Array.isArray(ids) || ids.length > 64 || ids.some(id => !Number.isSafeInteger(id) || id < 1) || new Set(ids).size !== ids.length) throw new Error("invalid task privacy reference set"); if (!ids.length) return []; const rows = this.db.query(`SELECT id, signals FROM tasks WHERE id IN (${ids.map(() => "?").join(",")})`).all(...ids) as { id: unknown; signals: unknown }[]; return rows.map(row => { const signals: unknown = JSON.parse(String(row.signals)); if (!Number.isSafeInteger(row.id) || !Array.isArray(signals) || signals.some(signal => typeof signal !== "string")) throw new Error("invalid task privacy projection"); return { id: row.id as number, signals: signals as string[] }; }); } statusReservations(): string[] { return (this.db.query("SELECT DISTINCT reserved FROM tasks WHERE state NOT IN ('approved', 'cancelled', 'backlog') AND reserved IS NOT NULL ORDER BY reserved").all() as { reserved: string }[]).map(row => row.reserved); } plannerWip(peer: string, except?: number): number { const row = this.db.query(`SELECT COUNT(*) AS n FROM tasks WHERE state NOT IN ('approved', 'cancelled', 'backlog') AND (? IS NULL OR id != ?) AND (owner = ? OR (owner IS NULL AND state = 'proposed' AND reserved = ? AND needs_person = 0 AND json_extract((SELECT value FROM json_each(tasks.history) WHERE json_extract(value, '$.event') IN ('backlog pulled', 'backlog returned') ORDER BY CAST(key AS INTEGER) DESC LIMIT 1), '$.planning.pull') = 1))`).get(except ?? null, except ?? null, peer, peer) as { n: number }; return row.n; } /** * #784 AC3: what `plannerWip` counts, split per peer in ONE grouped query (no per-peer or per-task reads on the status hot path). `active` is owned work that is not * waiting for review, `reviewWait` is owned work in `in_review`, `reserved` is unowned proposed work a planner pull reserved. For every peer the three add up to * `plannerWip(peer)`: this is a read-only view, admission keeps using `plannerWip` unchanged. */ plannerWipBreakdown(): Record { const rows = this.db.query(`SELECT peer, kind, COUNT(*) AS n FROM ( SELECT owner AS peer, CASE WHEN state = 'in_review' THEN 'reviewWait' ELSE 'active' END AS kind FROM tasks WHERE state NOT IN ('approved', 'cancelled', 'backlog') AND owner IS NOT NULL UNION ALL SELECT reserved AS peer, 'reserved' AS kind FROM tasks WHERE state = 'proposed' AND owner IS NULL AND reserved IS NOT NULL AND needs_person = 0 AND json_extract((SELECT value FROM json_each(tasks.history) WHERE json_extract(value, '$.event') IN ('backlog pulled', 'backlog returned') ORDER BY CAST(key AS INTEGER) DESC LIMIT 1), '$.planning.pull') = 1 ) GROUP BY peer, kind`).all() as { peer: string; kind: "active" | "reviewWait" | "reserved"; n: number }[]; const result: Record = {}; for (const row of rows) (result[row.peer] ??= { active: 0, reviewWait: 0, reserved: 0 })[row.kind] = row.n; return result; } recordTaskOffer(id: number, offer: TaskOffer, expectedFlowRevision: number): void { const task = this.get(id); if (!task || task.owner !== offer.owner || isClosedTaskState(task.state) || task.history.length !== expectedFlowRevision || offer.assignmentFlowRevision !== expectedFlowRevision) throw new Error("task offer changed"); const changed = this.taskWrite(() => this.db.query("UPDATE tasks SET offer=? WHERE id=? AND owner=? AND history=?").run(JSON.stringify(offer), id, offer.owner, JSON.stringify(task.history))); if (!changed.changes) throw new Error("task offer changed"); } recordStall(stall: TaskStall): boolean { const old = this.stalls().find(row => row.task === stall.task); if (old?.signature === stall.signature && old.replanRevision === stall.replanRevision) return false; this.taskWrite(() => this.db.query("INSERT INTO task_stalls(task,payload) VALUES(?,?) ON CONFLICT(task) DO UPDATE SET payload=excluded.payload").run(stall.task, JSON.stringify(stall))); return true; } /** #481 S7: the scan history of one repository and source set, oldest first. Counts and times only. */ /** `knownOnly` filters unknown totals in SQL, before the limit, so rows with no total never use up the rows a series needs. */ securityScans(repo: string, sources: string, limit = 200, knownOnly = false): { id: number; at: number; total: number | null }[] { const rows = this.db.query(`SELECT id, at, total FROM security_scans WHERE repo=? AND sources=?${knownOnly ? " AND total IS NOT NULL" : ""} ORDER BY id DESC LIMIT ?`).all(repo.toLowerCase(), sources, Math.max(1, Math.min(1000, limit))) as { id: number; at: number; total: number | null }[]; return rows.reverse(); } /** The latest recorded per-source scan counts, with unreadable values kept unknown. */ latestSecurityScanCounts(repo: string, sources: string): Record | undefined { const row = this.db.query("SELECT counts FROM security_scans WHERE repo=? AND sources=? ORDER BY id DESC LIMIT 1").get(repo.toLowerCase(), sources) as { counts: string } | null; if (!row) return undefined; let counts: unknown; try { counts = JSON.parse(row.counts); } catch { counts = undefined; } const raw = counts && typeof counts === "object" && !Array.isArray(counts) ? counts as Record : {}; return Object.fromEntries(sources.split(",").filter(source => ["dependabot", "secret_scanning", "code_scanning"].includes(source)).map(source => { const value = raw[source]; return [source, typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null]; })); } recordSecurityScan(row: { repo: string; sources: string; counts: Record; total: number | null }): number { if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(row.repo) || !/^[a-z_,]{1,80}$/.test(row.sources) || (row.total !== null && (!Number.isSafeInteger(row.total) || row.total < 0))) throw new Error("invalid security scan row"); return Number(this.db.query("INSERT INTO security_scans(at, repo, sources, counts, total) VALUES(?,?,?,?,?)").run(Date.now(), row.repo.toLowerCase(), row.sources, JSON.stringify(row.counts), row.total).lastInsertRowid); } /** True when the marker was new (and is now recorded), false when it was announced before. Ids, metric names and task numbers only. */ recordBandNotice(marker: string): boolean { if (!/^[a-z_]{1,64}:#[1-9][0-9]{0,9}:log$/.test(marker)) throw new Error("invalid band notice marker"); return this.db.query("INSERT OR IGNORE INTO band_notices(marker, at) VALUES(?, ?)").run(marker, Date.now()).changes > 0; } hasRoadmapNotice(marker: string): boolean { if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker"); return !!this.db.query("SELECT 1 FROM roadmap_notices WHERE marker=?").get(marker); } recordRoadmapNotice(marker: string): boolean { if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker"); return this.db.query("INSERT OR IGNORE INTO roadmap_notices(marker,at) VALUES(?,?)").run(marker, Date.now()).changes > 0; } /** True when the (id, version, planner) marker was new and is now recorded; false when it was announced before. */ recordAgentDriftNotice(marker: string): boolean { if (!/^[a-z][a-z0-9-]{0,31}:[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}@[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(marker)) throw new Error("invalid agent drift marker"); return this.db.query("INSERT OR IGNORE INTO agent_drift_notices(marker, at) VALUES(?, ?)").run(marker, Date.now()).changes > 0; } forgetAgentDriftNotice(marker: string): void { this.db.query("DELETE FROM agent_drift_notices WHERE marker=?").run(marker); } /** #1057 D2: every override, newest first, bounded. Rows made inert by later activity are removed lazily by the next write (`setWorktreeOverride`). */ worktreeOverrides(): { path: string; value: "settled" | "active"; at: number }[] { return this.db.query("SELECT path, value, at FROM worktree_override ORDER BY at DESC LIMIT 1024").all() as { path: string; value: "settled" | "active"; at: number }[]; } /** One override per path; a new write replaces the old. `path` is the absolute host path the shelf listed, never a name a request invented. */ setWorktreeOverride(path: string, value: "settled" | "active", at: number): void { if (typeof path !== "string" || !path.startsWith("/") || path.length > 4096 || path.includes("\0")) throw new Error("invalid worktree path"); if (value !== "settled" && value !== "active") throw new Error("invalid worktree override"); if (!Number.isFinite(at) || at <= 0) throw new Error("invalid worktree override time"); this.db.query("INSERT INTO worktree_override(path, value, at) VALUES(?,?,?) ON CONFLICT(path) DO UPDATE SET value=excluded.value, at=excluded.at").run(path, value, at); } clearWorktreeOverride(path: string): boolean { return this.db.query("DELETE FROM worktree_override WHERE path=?").run(path).changes > 0; } /** The lazy removal D2 names: an override whose worktree has newer activity is inert, so a write deletes it. `active` maps path to its lastActiveAt. */ pruneInertWorktreeOverrides(activity: ReadonlyMap): number { let removed = 0; for (const row of this.worktreeOverrides()) { const last = activity.get(row.path); if (last !== undefined && last > row.at) removed += this.clearWorktreeOverride(row.path) ? 1 : 0; } return removed; } clearStall(task: number): void { this.taskWrite(() => this.db.query("DELETE FROM task_stalls WHERE task=?").run(task)); } /** One bounded primary-key metadata read for a retry's saved replacement cause. */ stall(task: number): TaskStall | undefined { if (!Number.isSafeInteger(task) || task < 1) return undefined; const saved = this.db.query<{ payload: string | null }, [number]>("SELECT CASE WHEN length(CAST(payload AS BLOB)) <= 65536 THEN payload END AS payload FROM task_stalls WHERE task=?").get(task); return saved?.payload == null ? undefined : parseStall(saved.payload, task); } stalls(): TaskStall[] { return (this.db.query("SELECT task,payload FROM task_stalls ORDER BY task").all() as { task: number; payload: string }[]).flatMap(row => { const value = parseStall(row.payload, row.task); return value ? [value] : []; }); } /** Bounded ids/hold metadata only; a corrupt skipped payload still advances the cursor. */ queuePressureStallPage(afterTask = 0, limit = 64): QueuePressureStallPage { if (!Number.isSafeInteger(afterTask) || afterTask < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 64) throw new Error("invalid queue pressure stall page"); const saved = this.db.query<{ task: number; payload: string }, [number, number]>(`SELECT task,payload FROM task_stalls WHERE task>? AND ${QUEUE_PRESSURE_STALL} ORDER BY task LIMIT ?`).all(afterTask, limit); return { rows: saved.flatMap(row => { const value = parseStall(row.payload, row.task); return value ? [value] : []; }), afterTask: saved.at(-1)?.task ?? afterTask, done: saved.length < limit }; } /** Current human-review candidates, by indexed state/role/id metadata without opening task history. */ humanReviewPage(afterId = 0, limit = 64): number[] { if (!Number.isSafeInteger(afterId) || afterId < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 64) throw new Error("invalid human review page"); return this.db.query<{ id: number }, [number, number]>("SELECT id FROM tasks WHERE id>? AND state='in_review' AND reviewer='user' ORDER BY id LIMIT ?").all(afterId, limit).map(row => row.id); } /** Tasks per state, without parsing a single row: `status.json` is rewritten on every bus event and the board only grows. */ /** #1176: ids of open cards only the person can run, for status and the board (ids only, never text). Backlog first, then the rest, by id. */ personRunIds(): number[] { return (this.db.query("SELECT id FROM tasks WHERE needs_person = 1 AND state NOT IN ('approved', 'cancelled') ORDER BY id").all() as { id: number }[]).map(row => row.id); } counts(): Record { const rows = this.db.query("SELECT state, COUNT(*) AS n FROM tasks GROUP BY state").all() as { state: string; n: number }[]; return Object.fromEntries(rows.map((r) => [r.state, r.n])); } /** Tasks alone calls this after current actor, privacy, artifact and GitHub evidence fences. Generic MOVES stays unchanged. */ adoptMerge(id: number, by: PeerId, receipt: SdlcReceipt, head: string, expectedFlowRevision: number, authority: typeof HOST_MERGE_ADOPTION): Task { if (authority !== HOST_MERGE_ADOPTION || !Number.isSafeInteger(expectedFlowRevision) || expectedFlowRevision < 0) throw new Error("merge adoption requires host authority and a current flow revision; retry through Tasks.adoptMerge"); return this.update(id, by, "merged outside the hub", { state: "approved", rejections: 0, sdlc: receipt }, `PR #${receipt.pr} merged outside the hub at ${head}`, undefined, expectedFlowRevision, undefined, authority); } /** Consent and the admitted outer event publish together, including observer/status-generation rollback. */ updateWithSpecAcceptance(carry: SpecAcceptanceCommit, authority: typeof HOST_SPEC_ACCEPTANCE_CARRY, ...args: Parameters): Task { const [id, by, event, patch, note, extra, revision, codeSymbolsAuthority, adoptionAuthority] = args; if (authority !== HOST_SPEC_ACCEPTANCE_CARRY || revision === undefined || !["accepted", "lifecycle", "done", "done (checking)", "integration requested", "integration unresolved", "integrated"].includes(event)) throw new Error("spec carry requires host admission authority; inspect the current task and invoke the action through Tasks"); return this.atomic(() => { const task = this.get(id), acceptance = carry.acceptance, receipt = patch.sdlc ?? task?.sdlc; if (!task || task.sdlc?.acceptance || !Number.isSafeInteger(carry.source) || carry.source >= id || carry.source <= 0 || !Number.isSafeInteger(carry.cancellationRevision) || carry.cancellationRevision <= 0 || !receipt || receipt.repo !== acceptance.repo || receipt.issue !== acceptance.issue || task.sdlc?.repo !== acceptance.repo || task.sdlc.issue !== acceptance.issue) throw new Error("spec carry identity changed before publication; inspect the current task and held deliveries before repeating this action"); const carried = this.update(id, HUB, "spec acceptance carried", { sdlc: { ...task.sdlc, acceptance } }, `from task #${carry.source}; original person acceptance at ${acceptance.acceptedAt}; cancellation revision ${carry.cancellationRevision}`, {}, revision); return this.update(id, by, event, { ...patch, sdlc: { ...receipt, acceptance } }, note, extra, carried.history.length, codeSymbolsAuthority, adoptionAuthority); }); } /** The only way a task changes. Validates the move, records who did what, returns the new row. */ /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */ update(id: number, by: PeerId, event: string, patch: Partial>, note?: string, extra: Pick = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task { const instruction = instructedExecution.getStore(); if (instruction?.active && instruction.taskId === id) instruction.current(); if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority)); const task = this.get(id); if (!task) throw new Error(`no task #${id}`); if (expectedFlowRevision !== undefined && (!Number.isSafeInteger(expectedFlowRevision) || expectedFlowRevision < 0 || task.history.length !== expectedFlowRevision)) throw new Error("task flow revision changed"); const adoption = event === "merged outside the hub" && adoptionAuthority === HOST_MERGE_ADOPTION && expectedFlowRevision !== undefined && ["in_progress", "in_review", "changes_requested"].includes(task.state) && !task.draft && !task.signals.includes("pii") && !task.signals.includes("pii_path") && patch.state === "approved" && Object.keys(patch).every(key => ["state", "rejections", "sdlc"].includes(key)); if (event === "merged outside the hub" && !adoption) throw new Error(`task #${id} in state ${task.state}: merge adoption requires a host-only eligible transition and current flow revision; retry through Tasks.adoptMerge`); const untouchedReturn = event === "backlog returned untouched" && patch.state === "backlog" && patch.owner === null && patch.reviewer === null && ["proposed", "in_progress"].includes(task.state) && expectedFlowRevision !== undefined && !!note?.trim() && !taskHasWorkEvidence(task); const returnPlanning: HistoryEntry["planning"] = untouchedReturn && Object.hasOwn(patch, "reserved") ? { revision: (task.planningRevision ?? 0) + 1, fields: ["reserved"], previous: { reserved: task.reserved ?? null } } : undefined; if (returnPlanning) patch = { ...patch, reserved: planningPatch({ reserved: patch.reserved }).reserved }; // A new delivered head with a configured check is owner work again until that check finishes. const reviewCheck = task.sdlc?.merge?.state !== "merged" && event === "done (checking)" && ["in_review", "approved"].includes(task.state) && patch.state === "in_progress" && expectedFlowRevision !== undefined && (by === task.owner || by === "user") && patch.owner === undefined && (patch.reviewer === undefined || task.state === "approved" && !task.reviewer && patch.reviewer === "user") && typeof patch.refs?.commit === "string" && /^[a-f0-9]{40}$/.test(patch.refs.commit) && patch.refs.commit !== (task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead); const approvalReopen = task.state === "approved" && task.sdlc?.merge?.state !== "merged" && expectedFlowRevision !== undefined && patch.owner === undefined && ( event === "done" && patch.state === "in_review" && (by === task.owner || by === "user") && typeof patch.refs?.commit === "string" && /^[a-f0-9]{40}$/.test(patch.refs.commit) && patch.refs.commit !== (task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead) || event === "changes_requested" && patch.state === "changes_requested" && (by === task.reviewer || by === "user")); if (extra.reviewedHead !== undefined && (!/^[a-f0-9]{40}$/.test(extra.reviewedHead) || !["approved", "changes_requested"].includes(event))) throw new Error("invalid verdict head"); if (task.draft && patch.state && patch.state !== "backlog" && patch.state !== "cancelled") throw new Error(`task #${id} is an intake draft; the person approves it first`); if (patch.state && patch.state !== task.state && !MOVES[task.state].includes(patch.state) && !untouchedReturn && !reviewCheck && !approvalReopen && !adoption) { throw new Error(`task #${id} is ${task.state}: cannot move to ${patch.state}`); } const planner = Object.hasOwn(patch, "planner") ? plannerValue(patch.planner) : task.planner ?? null; const plannerHistory = Object.hasOwn(patch, "planner") || extra.plannerReason !== undefined ? plannerMetadata(planner, extra.plannerReason) : {}; const authorHistory = Object.hasOwn(extra, "planAuthor") ? { planAuthor: plannerValue(extra.planAuthor) } : {}; if (extra.selfReview !== undefined && extra.selfReview !== true) throw new Error("invalid self-review metadata"); const specMetadata = extra.specReport !== undefined || extra.specRefBinding !== undefined ? specReportHistory(extra.specReport, extra.specRefBinding, event) : {}; if (extra.conductorManual !== undefined && (extra.conductorManual !== true || by === "user" || by === "hub" || extra.reason !== "manual" || !["assigned", "reassigned", "reserved", "unassigned", "reviewer changed"].includes(event))) throw new Error("invalid conductor manual metadata"); if (extra.invocation && (by !== HUB || event !== "invocation")) throw new Error("invocation audit is host-only"); const next = { ...task, ...patch, planner, refs: { ...task.refs, ...patch.refs } }; const headOf = (row: Task) => row.refs.commit ?? row.sdlc?.head ?? row.sdlc?.localHead; const privateSymbols = next.signals.includes("pii") || next.signals.includes("pii_path"); if (Object.hasOwn(patch, "codeSymbols")) { if (codeSymbolsAuthority !== HOST_CODE_SYMBOLS) throw new Error("code symbols require host authority"); const observation = patch.codeSymbols === undefined ? undefined : parseTaskCodeSymbols(patch.codeSymbols); if (patch.codeSymbols !== undefined && !observation) throw new Error("invalid task code symbols"); if (observation && (privateSymbols || observation.head !== headOf(next))) throw new Error("code symbol head or privacy differs from task"); next.codeSymbols = observation; } else if (privateSymbols || headOf(task) !== headOf(next) || task.refs.repo !== next.refs.repo || JSON.stringify(task.refs.paths) !== JSON.stringify(next.refs.paths) || task.sdlc?.repo !== next.sdlc?.repo) { next.codeSymbols = undefined; } if (next.state === "backlog" && (next.owner || next.reviewer)) throw new Error(`task #${id}: backlog cannot have an owner or reviewer`); if (!untouchedReturn) { if (patch.state === "backlog" && task.owner) throw new Error(`task #${id}: owned work cannot return to backlog`); } if (patch.state === "backlog" && taskHasStarted(task) && !untouchedReturn) throw new Error(`task #${id}: started work cannot return to backlog`); const requestedReviewComments = extra.resolvedReviewComments === undefined ? undefined : reviewCommentIds(extra.resolvedReviewComments); if (requestedReviewComments?.length && (!["done", "done (checking)"].includes(event) || by !== task.owner || expectedFlowRevision === undefined)) throw new Error("comment resolution requires an admitted owner completion; use hub_task_done with sent comment ids"); const resolvedReviewComments = requestedReviewComments?.length ? this.reviewCommentResolution(task, requestedReviewComments) : undefined; const reviewMetadata = reviewerHistory(extra); let reviewFindings: ReviewFindingSet | undefined; if (extra.reviewFindings !== undefined) { if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("finding metadata requires a saved review verdict"); const head = extra.reviewFindings.head; if (head !== undefined && !/^[a-f0-9]{40}$/.test(head)) throw new Error("finding metadata requires a full reviewed head"); reviewFindings = { ...(head ? { head } : {}), items: parseReviewFindings(extra.reviewFindings.items, { person: by === "user", maxNits: 64, contract: "stored" }) }; } let deliverables: DeliverableRecord[] | undefined; if (extra.deliverables !== undefined) { if (!["done", "done (checking)", "lifecycle", "approved"].includes(event)) throw new Error("deliverable records require a done, a lifecycle record or an approval"); deliverables = parseDeliverableRecords(extra.deliverables); } let securityPass: SecurityPassRecord | undefined; if (extra.securityPass !== undefined) { if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("a security pass requires a saved review verdict"); securityPass = storedSecurityPass(extra.securityPass); } let unmetCriteria: string[] | undefined; if (extra.unmetCriteria !== undefined) { if (!["approved", "changes_requested"].includes(event) || patch.state !== event) throw new Error("unmet criteria require a saved review verdict"); unmetCriteria = criterionIdList(extra.unmetCriteria); } if (extra.planDeparture && (by !== "user" || event !== "plan departure accepted")) throw new Error("plan departure acceptance is person-only"); const trackPlan = this.trackPlanRevisions?.() === true, hasDeparture = task.history.some(h => h.planDeparture); const fingerprint = patch.plan && (trackPlan || hasDeparture) ? planFingerprint(next.plan ?? {}) : undefined; const planChanged = fingerprint !== undefined && fingerprint !== planFingerprint(task.plan ?? {}); const planRevision = trackPlan && planChanged ? { revision: (task.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0) + 1, fingerprint: fingerprint! } : undefined; // Disabling reporting must not let plan or repository refs edits/reverts resurrect prior consent. const repositoryRefsChanged = patch.refs !== undefined && JSON.stringify([task.refs.repo, task.refs.paths]) !== JSON.stringify([next.refs.repo, next.refs.paths]); const departureInvalidated = extra.planDepartureInvalidated === true || hasDeparture && (planChanged || repositoryRefsChanged); // Older verdict rows kept their bound head only on the receipt. Preserve it atomically before reopening drops that receipt. const priorApproval = task.history.findLastIndex(entry => entry.event === "approved"); const priorHead = task.sdlc?.reviewedHead; const backfill = (approvalReopen || reviewCheck && task.state === "approved") && priorApproval >= 0 && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead); const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history; const history = [...previousHistory, { at: Date.now(), by, event, ...instructedHistory(by), ...(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 } : {}), ...(["done", "check run passed", "check run failed"].includes(event) && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed", "check run passed", "check run 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 } : {}) }]; this.taskWrite(() => { if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) { if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue; const resolved: ReviewCommentRecord = { ...record, lifecycle: "resolved", revision: record.revision + 1 }; this.db.query("UPDATE review_comments SET body=?,lifecycle=?,revision=? WHERE task_id=? AND task_created=? AND id=?").run(JSON.stringify(resolved), resolved.lifecycle, resolved.revision, task.id, task.created, record.thread.id); } const result = this.db.query("UPDATE tasks SET state = ?, owner = ?, reviewer = ?, reserved = ?, refs = ?, plan = ?, rejections = ?, signals = ?, history = ?, sdlc = ?, task_role = ?, cancelled = ?, updated = ?, planner = ?, planning_revision = ? WHERE id = ?") .run(next.state, next.owner, next.reviewer, next.reserved ?? null, JSON.stringify(next.refs), JSON.stringify(next.plan ?? {}), next.rejections, JSON.stringify(next.signals), JSON.stringify(history), next.sdlc ? JSON.stringify(next.sdlc) : null, next.role ?? null, next.cancelled ? JSON.stringify(next.cancelled) : null, Date.now(), planner, returnPlanning?.revision ?? task.planningRevision ?? 0, id); if (result.changes) { if (next.codeSymbols) this.db.query("INSERT INTO task_code_symbols(task,payload) VALUES(?,?) ON CONFLICT(task) DO UPDATE SET payload=excluded.payload").run(id, JSON.stringify(next.codeSymbols)); else this.db.query("DELETE FROM task_code_symbols WHERE task=?").run(id); } return result; }); const updated = this.get(id)!; this.changed(updated, history.at(-1)!); return updated; } /** Internal persistence; caller authority and frozen scope are owned by Tasks. */ plan(id: number, by: PeerId, input: PlanningFields, revision: number, note?: string, withheld = false, receipt?: SdlcReceipt): Task { const patch = planningPatch(input); const task = this.get(id); if (!task || (task.planningRevision ?? 0) !== revision) throw new Error("planning revision changed"); if ((patch.sdlc !== undefined) !== (receipt !== undefined)) throw new Error("planning issue identity requires a normalized host receipt"); const next = { ...task, ...patch, sdlc: receipt ?? task.sdlc }; if (next.plannedStart != null && next.due != null && next.plannedStart > next.due) throw new Error("planned start must not follow due"); if (next.release != null && !this.release(next.release)) throw new Error("no such release"); const fields = Object.keys(patch) as (keyof PlanningFields)[], previous = Object.fromEntries(fields.map(key => [key, key === "sdlc" ? { repo: task.sdlc?.repo ?? null, issue: task.sdlc?.issue ?? null } : task[key] ?? (key === "pinned" || key === "needsPerson" ? false : key === "deps" ? [] : null)])) as PlanningFields; const now = Date.now(), entry: HistoryEntry = { at: now, by, ...instructedHistory(by), event: "planned", planning: { revision: revision + 1, fields, previous }, ...(note ? { note } : {}), ...(withheld && note ? { withheld: true as const } : {}) }; const result = this.taskWrite(() => this.db.query(`UPDATE tasks SET rank=?, priority=?, "release"=?, planned_start=?, due=?, pinned=?, needs_person=?, deps=?, reserved=?, planning_revision=planning_revision+1, history=?, updated=?, sdlc=? WHERE id=? AND planning_revision=?`) .run(next.rank ?? null, next.priority ?? null, next.release ?? null, next.plannedStart ?? null, next.due ?? null, next.pinned ? 1 : 0, next.needsPerson ? 1 : 0, JSON.stringify(next.deps ?? []), next.reserved ?? null, JSON.stringify([...task.history, entry]), now, next.sdlc === undefined ? null : JSON.stringify(next.sdlc), id, revision)); if (result.changes !== 1) throw new Error("planning revision changed"); const updated = this.get(id)!; this.changed(updated, entry); return updated; } /** A planner reserves a routing slot without claiming or dispatching the work. */ pullPlanned(id: number, by: PeerId, reserved: PeerId, revision: number, note: string, withheld = false, binding?: PlannerBinding): Task { const task = this.get(id); if (!task || (task.planningRevision ?? 0) !== revision || task.state !== "backlog" || task.owner || !taskCanPlan(task)) throw new Error("planner pull changed or already started"); if (task.draft) throw new Error(`task #${id} is an intake draft; the person approves it first`); const selected = binding ? plannerMetadata(binding.planner, binding.plannerReason) : {}; const now = Date.now(), entry: HistoryEntry = { at: now, by, ...instructedHistory(by), ...selected, event: "backlog pulled", planning: { revision: revision + 1, fields: ["reserved"], previous: { reserved: task.reserved ?? null }, pull: true }, note, ...(withheld ? { withheld: true as const } : {}) }; const result = this.taskWrite(() => this.db.query("UPDATE tasks SET state='proposed',owner=NULL,reviewer=NULL,offer=NULL,reserved=?,planning_revision=planning_revision+1,history=?,updated=?,planner=? WHERE id=? AND planning_revision=? AND state='backlog' AND owner IS NULL") .run(reserved, JSON.stringify([...task.history, entry]), now, binding ? selected.planner ?? null : task.planner ?? null, id, revision)); if (result.changes !== 1) throw new Error("planner pull changed"); const updated = this.get(id)!; this.changed(updated, entry); return updated; } /** Publish no intermediate ownerless pull: Tasks has already admitted the exact reserved peer. */ pullAssigned(id: number, by: PeerId, owner: PeerId, revision: number, note: string, withheld: boolean, reviewer: PeerId | null, assignmentNote: string, extra: Parameters[5], expectedFlowRevision: number, binding?: PlannerBinding): Task { return this.atomic(() => { const current = this.get(id); if (!current || current.history.length !== expectedFlowRevision) throw new Error("task flow revision changed"); const pulled = this.pullPlanned(id, by, owner, revision, note, withheld, binding); const assigned = this.update(id, by, "assigned", { owner, reviewer, ...(binding ? { planner: binding.planner } : {}) }, assignmentNote, { ...extra, ...(binding ? { plannerReason: binding.plannerReason } : {}) }, pulled.history.length); // Both deferred events describe the committed handoff, including the callback payload. for (const change of this.pendingChanges ?? []) if (change.task.id === id) change.task = assigned; return assigned; }); } /** No owner or execution evidence may be taken back by planning undo. */ undoPlannedPull(id: number, by: PeerId, revision: number): Task { const task = this.get(id), pull = task ? planningUndoEntry(task)?.planning : undefined; if (!task || task.state !== "proposed" || task.owner || taskHasStarted(task) || (task.planningRevision ?? 0) !== revision || !pull?.pull || pull.revision !== revision) throw new Error("planner pull undo changed or already offered"); const now = Date.now(), entry: HistoryEntry = { at: now, by, event: "backlog returned", note: `undo planner pull revision ${revision}` }; const result = this.taskWrite(() => this.db.query("UPDATE tasks SET state='backlog',owner=NULL,reviewer=NULL,reserved=?,planning_revision=planning_revision+1,history=?,updated=? WHERE id=? AND planning_revision=? AND state='proposed' AND owner IS NULL") .run(pull.previous.reserved ?? null, JSON.stringify([...task.history, entry]), now, id, revision)); if (result.changes !== 1) throw new Error("planner pull undo changed"); const updated = this.get(id)!; this.changed(updated, entry); return updated; } /** #334: set by `Tasks` for exactly the next `splitBacklog` and cleared by it, so the hub's own intake split requires its parent to still be a draft. */ requireDraftForNextSplit = false; splitBacklog(id: number, by: PeerId, revision: number, parts: (Parameters[1] & { fields?: PlanningFields; afterParts?: number[]; screeningNote?: string })[], note: string, withheld = false): { parent: Task; children: Task[] } { const requireDraft = this.requireDraftForNextSplit; this.requireDraftForNextSplit = false; return this.atomic(() => { const parent = this.get(id); if (!parent || parent.state !== "backlog" || parent.owner || taskHasStarted(parent) || (parent.planningRevision ?? 0) !== revision || parts.length < 2 || parts.length > 8) throw new Error("split changed or invalid"); // #334: the hub's own intake split is only ever for a draft. An approval clears the mark without moving the planning revision, so the revision alone cannot tell the // person approved the card while the model answered; checked here, in the same transaction as the write, nothing can slip between this and the children. if (requireDraft && !parent.draft) throw new Error("split changed or invalid"); // #1176: an agent's split of a person-run card, checked in the transaction so nothing slips in between the planner's check and the write. if (by !== USER && parent.needsPerson) throw new Error("a person-run card is the person's to split"); const children: Task[] = []; for (const part of parts) { const inherited = part.afterParts?.length ? (part.deps ?? []).filter(dep => !parent.deps?.includes(dep)) : part.deps ?? []; const deps = [...new Set([...inherited, ...(part.afterParts ?? []).map(index => { const child = children[index]; if (!child) throw new Error("split dependencies must name an earlier part"); return child.id; })])]; let child = this.propose(by, { ...part, deps, backlog: true, ...(parent.draft ? { draft: true } : {}) }); if (part.screeningNote !== undefined) child = this.update(child.id, HUB, "screened", {}, part.screeningNote); if (part.fields && Object.keys(part.fields).length) child = this.plan(child.id, by, part.fields, 0, note, withheld); children.push(child); } const deps = children.map(child => child.id); const updated = this.plan(id, by, { deps }, revision, note, withheld); const entry = updated.history.at(-1)!; entry.planning!.split = { children: children.map(child => ({ id: child.id, revision: child.planningRevision ?? 0, history: child.history.length })) }; this.taskWrite(() => this.db.query("UPDATE tasks SET history=? WHERE id=?").run(JSON.stringify(updated.history), id)); const notification = this.pendingChanges?.findLast(change => change.task.id === id && change.entry.planning?.revision === revision + 1); if (notification) { notification.task = updated; notification.entry = entry; } return { parent: this.get(id)!, children }; }); } /** * #334: approve an intake draft and its children in one transaction. Only the person's approval reaches here (Tasks.approveIntake); * each card must still be an unstarted, ownerless backlog draft, or nothing changes. */ approveDrafts(ids: readonly number[], by: PeerId, note: string): Task[] { return this.atomic(() => { const rows = ids.map(id => this.get(id)); for (const row of rows) if (!row || row.state !== "backlog" || !row.draft || row.owner || taskHasStarted(row)) throw new Error("draft changed, approved or started"); return rows.map(row => { const now = Date.now(), entry: HistoryEntry = { at: now, by, event: "draft approved", note }; const result = this.taskWrite(() => this.db.query("UPDATE tasks SET draft=0, history=?, updated=? WHERE id=? AND draft=1").run(JSON.stringify([...row!.history, entry]), now, row!.id)); if (result.changes !== 1) throw new Error("draft changed, approved or started"); const updated = this.get(row!.id)!; this.changed(updated, entry); return updated; }); }); } undoBacklogSplit(id: number, by: PeerId, revision: number): Task { return this.atomic(() => { const parent = this.get(id), entry = parent ? planningUndoEntry(parent) : undefined, split = entry?.planning?.split; if (!parent || parent.state !== "backlog" || parent.owner || taskHasStarted(parent) || (parent.planningRevision ?? 0) !== revision || !split || entry?.planning?.revision !== revision) throw new Error("split undo changed"); const ids = new Set(split.children.map(child => child.id)); for (const saved of split.children) { const child = this.get(saved.id); if (!child || child.state !== "backlog" || child.owner || taskHasStarted(child) || (child.planningRevision ?? 0) !== saved.revision || child.history.length !== saved.history) throw new Error("split child changed or started"); } if (this.list().some(task => task.id !== id && !ids.has(task.id) && (task.deps?.some(dep => ids.has(dep)) || task.sdlc?.phase?.tasks.some(ref => ids.has(ref.id) || ref.after.some(dep => ids.has(dep)))))) throw new Error("split children are referenced by other work"); const restored = this.plan(id, by, { deps: entry!.planning!.previous.deps ?? [] }, revision, `undo split revision ${revision}`); for (const child of ids) this.taskWrite(() => { this.db.query("DELETE FROM task_code_symbols WHERE task=?").run(child); return this.db.query("DELETE FROM tasks WHERE id=?").run(child); }); return restored; }); } /** Raw roadmap storage. Every external writer is admitted by Tasks. */ newMilestone(input: MilestoneInput, by: string, now = Date.now()): Milestone { const value = parseMilestoneInput(input), actor = milestoneActor(by), at = milestoneId(now); return this.db.transaction(() => { this.milestoneParent(undefined, value.parent); const history = milestoneHistory([{ at, by: actor, event: "created" }]); const inserted = this.db.query("INSERT INTO milestones(title,outcome,state,horizon,milestone_order,target,parent,history,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?)") .run(value.title, value.outcome, value.state, value.horizon, value.order, value.target, value.parent, JSON.stringify(history), at, at); return this.milestone(Number(inserted.lastInsertRowid))!; })(); } milestone(id: number): Milestone | undefined { milestoneId(id); const row = this.db.query("SELECT * FROM milestones WHERE id=?").get(id) as Record | null; return row ? parseMilestone(row) : undefined; } milestones(): Milestone[] { return (this.db.query("SELECT * FROM milestones ORDER BY milestone_order,id").all() as Record[]).map(parseMilestone); } milestoneLinks(id?: number): MilestoneLink[] { if (id !== undefined) milestoneId(id); const rows = (id === undefined ? this.db.query("SELECT * FROM milestone_links ORDER BY milestone,kind,ref").all() : this.db.query("SELECT * FROM milestone_links WHERE milestone=? ORDER BY kind,ref").all(id)) as Record[]; return rows.map(row => ({ milestone: milestoneId(row.milestone), kind: row.kind as MilestoneLinkKind, ref: milestoneLinkRef(row.kind as MilestoneLinkKind, row.ref), by: milestoneActor(row.by), at: milestoneId(row.at) })); } /** #1622 family 4: whether any milestone history holds an instructed entry; a daemon without `roadmap_instructed` cannot read such a row. */ hasInstructedMilestoneHistory(): boolean { const row = this.db.query("SELECT EXISTS(SELECT 1 FROM milestones WHERE history LIKE '%\"instructed\"%') AS present").get() as { present: number }; return row.present === 1; } hasMilestoneState(): boolean { const row = this.db.query("SELECT EXISTS(SELECT 1 FROM milestones) OR EXISTS(SELECT 1 FROM milestone_links) AS present").get() as { present: number }; return row.present === 1; } roadmapIntegrity(): { milestones: number; links: number; digest: string } { return this.db.transaction(() => { const milestones = this.milestones().sort((a, b) => a.id - b.id), links = this.milestoneLinks(); return { milestones: milestones.length, links: links.length, digest: createHash("sha256").update(JSON.stringify({ milestones, links })).digest("hex") }; })(); } /** Parent shape and compare-and-set are checked under the same write transaction. */ updateMilestone(id: number, patch: MilestonePatch, revision: number, event: MilestoneHistoryEntry): Milestone { const fields = parseMilestonePatch(patch), entry = milestoneHistory([event])[0]!; return this.db.transaction(() => this.writeMilestone(id, fields, revision, entry))(); } linkMilestone(id: number, kind: MilestoneLinkKind, ref: string, by: string, revision: number, now = Date.now()): Milestone { const key = milestoneLinkRef(kind, ref), actor = milestoneActor(by), at = milestoneId(now); return this.db.transaction(() => { const before = this.currentMilestone(id, revision); if (this.db.query("SELECT 1 FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").get(id, kind, key)) return before; const updated = this.writeMilestone(id, {}, revision, { at, by: actor, event: "linked", kind }); this.db.query("INSERT INTO milestone_links(milestone,kind,ref,by,at) VALUES(?,?,?,?,?)").run(id, kind, key, actor, at); return updated; })(); } unlinkMilestone(id: number, kind: MilestoneLinkKind, ref: string, by: string, revision: number, now = Date.now()): Milestone { const key = milestoneLinkRef(kind, ref), actor = milestoneActor(by), at = milestoneId(now); return this.db.transaction(() => { const before = this.currentMilestone(id, revision); if (!this.db.query("SELECT 1 FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").get(id, kind, key)) return before; const updated = this.writeMilestone(id, {}, revision, { at, by: actor, event: "unlinked", kind }); this.db.query("DELETE FROM milestone_links WHERE milestone=? AND kind=? AND ref=?").run(id, kind, key); return updated; })(); } /** R3: a pending model suggestion. One per item at a time; a repeat for the same item is ignored, never doubled. */ 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 { const actor = milestoneActor(by), at = milestoneId(now); return this.db.transaction(() => { if (this.db.query("SELECT 1 FROM milestone_suggestions WHERE kind=? AND ref=? AND state='pending'").get(row.kind, row.ref)) return undefined; const inserted = this.db.query("INSERT INTO milestone_suggestions(kind,ref,milestone,proposal,cite_milestone,cite_item,state,by,created) VALUES(?,?,?,?,?,?,'pending',?,?)") .run(row.kind, row.ref, row.milestone, row.proposal ? JSON.stringify(row.proposal) : null, row.citeMilestone, row.citeItem, actor, at); // Settled rows are history, not storage: keep the newest 500. 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(); return this.suggestion(Number(inserted.lastInsertRowid))!; })(); } suggestion(id: number): MilestoneSuggestion | undefined { milestoneId(id); const row = this.db.query("SELECT * FROM milestone_suggestions WHERE id=?").get(id) as Record | null; return row ? parseSuggestion(row) : undefined; } suggestions(state?: SuggestionState): MilestoneSuggestion[] { 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[]; return rows.map(parseSuggestion); } /** Remember the milestone an accepted "new milestone" suggestion created, so a retry after a failed link never creates a second one. */ suggestionCreated(id: number): number | undefined { const row = this.db.query("SELECT created_milestone AS made FROM milestone_suggestions WHERE id=?").get(milestoneId(id)) as { made: number | null } | null; return row?.made ?? undefined; } setSuggestionCreated(id: number, milestone: number): void { this.db.query("UPDATE milestone_suggestions SET created_milestone=? WHERE id=? AND state='pending' AND created_milestone IS NULL").run(milestoneId(milestone), milestoneId(id)); } /** R2: one pending decomposition per milestone. A newer answer supersedes the older one in the same transaction, never doubles it. */ addDecomposition(row: { milestone: number; parts: DecomposePart[] }, by: string, now = Date.now()): MilestoneDecomposition { const actor = milestoneActor(by), at = milestoneId(now), milestone = milestoneId(row.milestone); return this.db.transaction(() => { this.db.query("UPDATE milestone_decompositions SET state='superseded', settled=?, settled_by=? WHERE milestone=? AND state='pending'").run(at, actor, milestone); const inserted = this.db.query("INSERT INTO milestone_decompositions(milestone,parts,state,by,created) VALUES(?,?,'pending',?,?)").run(milestone, JSON.stringify(row.parts), actor, at); // Settled rows are history, not storage: keep the newest 200. this.db.query("DELETE FROM milestone_decompositions WHERE state<>'pending' AND id NOT IN (SELECT id FROM milestone_decompositions WHERE state<>'pending' ORDER BY id DESC LIMIT 200)").run(); return this.decomposition(Number(inserted.lastInsertRowid))!; })(); } decomposition(id: number): MilestoneDecomposition | undefined { milestoneId(id); const row = this.db.query("SELECT * FROM milestone_decompositions WHERE id=?").get(id) as Record | null; return row ? parseDecomposition(row) : undefined; } decompositions(state?: DecompositionState): MilestoneDecomposition[] { const rows = (state === undefined ? this.db.query("SELECT * FROM milestone_decompositions ORDER BY id").all() : this.db.query("SELECT * FROM milestone_decompositions WHERE state=? ORDER BY id").all(state)) as Record[]; return rows.map(parseDecomposition); } /** R2 part 2: the answer an accept reads its parts from. A superseded one is not pending, so an accept cannot land on it. */ pendingDecomposition(milestone: number): MilestoneDecomposition | undefined { const row = this.db.query("SELECT * FROM milestone_decompositions WHERE milestone=? AND state='pending'").get(milestoneId(milestone)) as Record | null; return row ? parseDecomposition(row) : undefined; } /** R2 part 2: the draft one part already made, if it was accepted before. */ decompositionAccept(decomposition: number, part: number): DecompositionAccept | undefined { const row = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record | null; return row ? parseDecompositionAccept(row) : undefined; } /** * R2 part 2: record that a part is held as a draft. The insert is ignored on a repeated accept, so the row that already names * the first draft is the one a retry reads, and no second draft is ever keyed here. */ acceptDecompositionPart(row: { decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake }, by: string, now = Date.now()): DecompositionAccept { const actor = milestoneActor(by), at = milestoneId(now); this.db.query("INSERT OR IGNORE INTO milestone_decomposition_accepts(decomposition,milestone,part,task,intake,by,at) VALUES(?,?,?,?,?,?,?)") .run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.task), row.intake, actor, at); return this.decompositionAccept(row.decomposition, row.part)!; } /** R2 part 3: every part held for one milestone, oldest answer and lowest position first, whatever answer it came from. */ decompositionAcceptsFor(milestone: number): DecompositionAccept[] { const rows = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE milestone=? ORDER BY decomposition, part").all(milestoneId(milestone)) as Record[]; return rows.map(parseDecompositionAccept); } /** R2 part 3: the issue a published part created, if an earlier apply made one. */ decompositionPublish(decomposition: number, part: number): number | undefined { const row = this.db.query("SELECT issue FROM milestone_decomposition_publishes WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record | null; return row ? milestoneId(row.issue) : undefined; } /** R2 part 3: record the issue one apply created. A repeated apply of the same part keeps the first row. */ recordDecompositionPublish(row: { decomposition: number; milestone: number; part: number; issue: number }, by: string, now = Date.now()): number { const actor = milestoneActor(by), at = milestoneId(now); this.db.query("INSERT OR IGNORE INTO milestone_decomposition_publishes(decomposition,milestone,part,issue,by,at) VALUES(?,?,?,?,?,?)") .run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.issue), actor, at); return this.decompositionPublish(row.decomposition, row.part)!; } /** Compare-and-set from pending: a second settle of the same suggestion changes nothing. */ settleSuggestion(id: number, state: "accepted" | "rejected" | "superseded", by: string, now = Date.now()): MilestoneSuggestion { const actor = milestoneActor(by), at = milestoneId(now); return this.db.transaction(() => { const result = this.db.query("UPDATE milestone_suggestions SET state=?,settled=?,settled_by=? WHERE id=? AND state='pending'").run(state, at, actor, milestoneId(id)); const row = this.suggestion(id); if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage"); if (result.changes !== 1 && row.state !== state) throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`); return row; })(); } importedMilestone(repo: string, number: number): number | undefined { const row = this.db.query("SELECT milestone FROM milestone_imports WHERE repo=? AND number=?").get(repo.toLowerCase(), milestoneId(number)) as { milestone: number } | null; return row?.milestone; } /** R4 uses the same durable marks as R3 imports; conflicting legacy marks are never guessed. */ mirrorMilestone(repo: string, id: number): number | undefined { const rows = this.db.query("SELECT number FROM milestone_imports WHERE repo=? AND milestone=? ORDER BY number LIMIT 2").all(githubRepo(repo), milestoneId(id)) as { number: number }[]; if (rows.length > 1) throw new PreEffectToolRefusal("roadmap milestone has conflicting GitHub bindings; inspect imports before syncing"); return rows[0]?.number; } bindMirrorMilestone(repo: string, id: number, number: number, now = Date.now()): void { const key = githubRepo(repo), local = milestoneId(id), remote = milestoneId(number), at = milestoneId(now); this.db.transaction(() => { if (!this.milestone(local)) throw new PreEffectToolRefusal("roadmap milestone no longer exists; inspect ahub roadmap list"); const prior = this.mirrorMilestone(key, local), owner = this.importedMilestone(key, remote); if (prior !== undefined && prior !== remote || owner !== undefined && owner !== local) throw new PreEffectToolRefusal("roadmap GitHub binding conflicts with an existing milestone; inspect imports before syncing"); if (prior === remote && owner === local) return; this.db.query("INSERT INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, remote, local, at); })(); } /** One transaction: the milestone and its import mark exist together or not at all, so a repeat finds the mark. */ importMilestone(repo: string, number: number, input: MilestoneInput, by: string, now = Date.now()): { milestone: Milestone; created: boolean } { const key = repo.toLowerCase(); return this.db.transaction(() => { const prior = this.importedMilestone(key, number); const existing = prior === undefined ? undefined : this.milestone(prior); if (existing) return { milestone: existing, created: false }; const milestone = this.newMilestone(input, by, now); this.db.query("INSERT OR REPLACE INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, milestoneId(number), milestone.id, milestoneId(now)); return { milestone, created: true }; })(); } private currentMilestone(id: number, revision: number): Milestone { milestoneRevision(revision); const row = this.milestone(id); if (!row || row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before retrying"); return row; } private milestoneParent(id: number | undefined, parent: number | null): void { if (parent === null) return; if (parent === id) throw new PreEffectToolRefusal("roadmap milestone cannot parent itself; choose another parent with ahub roadmap edit"); const ancestor = this.milestone(parent); if (!ancestor || ancestor.parent !== null) throw new PreEffectToolRefusal("roadmap parent must exist at the top level; inspect ahub roadmap list"); 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"); } private writeMilestone(id: number, patch: MilestonePatch, revision: number, event: MilestoneHistoryEntry): Milestone { const current = this.currentMilestone(id, revision), next = { ...current, ...patch }; this.milestoneParent(id, next.parent); const settling = current.state !== next.state && (next.state === "done" || next.state === "dropped"); if (event.instructed && !(settling && event.event === "state")) throw new PreEffectToolRefusal("instructed provenance is recorded only on a done or dropped verdict; ask the person to run ahub roadmap state"); if (current.history.length >= MILESTONE_HISTORY_LIMIT - 1 && !settling) 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`); const history = milestoneHistory([...current.history, event]); 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=?") .run(next.title, next.outcome, next.state, next.horizon, next.order, next.target, next.parent, JSON.stringify(history), event.at, id, revision); if (result.changes !== 1) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before retrying"); return this.milestone(id)!; } newRelease(name: string, goal: string, order: number, planner?: PeerId | null): Release { const now = Date.now(), selected = plannerValue(planner); const result = this.db.query("INSERT INTO releases(name,goal,release_order,created,updated,planner) VALUES(?,?,?,?,?,?)").run(name, goal, order, now, now, selected); return this.release(Number(result.lastInsertRowid))!; } release(id: number): Release | undefined { const row = this.db.query("SELECT * FROM releases WHERE id=?").get(id) as Record | null; return row ? parseRelease(row) : undefined; } releases(): Release[] { return (this.db.query("SELECT * FROM releases ORDER BY release_order,id").all() as Record[]).map(parseRelease); } updateRelease(id: number, patch: Partial>, revision: number): Release { const release = this.release(id); if (!release || release.revision !== revision) throw new Error("release revision changed"); const next = { ...release, ...patch, planner: Object.hasOwn(patch, "planner") ? plannerValue(patch.planner) : release.planner ?? null }, now = Date.now(); const moves: Record = { planning: ["active", "dropped"], active: ["frozen", "dropped"], frozen: ["shipped", "dropped"], shipped: [], dropped: [] }; if (next.state !== release.state && !moves[release.state].includes(next.state)) throw new Error("invalid release transition"); if (patch.train && next.state !== release.state && ["frozen", "shipped"].includes(next.state)) { const event = next.train?.history.at(-1); if (event?.event === (next.state === "frozen" ? "cut" : "shipped")) event.at = now; } const dates = [next.plannedStart, next.cut, next.ship].filter((date): date is number => date !== null); if (dates.some(date => !Number.isSafeInteger(date) || date <= 0 || date > 8_640_000_000_000_000) || dates.some((date, i) => i > 0 && dates[i-1]! > date)) throw new Error("invalid release planned dates"); const result = this.db.query("UPDATE releases SET state=?,planned_start=?,cut=?,ship=?,activated_at=?,frozen_at=?,shipped_at=?,updated=?,train=?,planner=?,revision=revision+1 WHERE id=? AND revision=?") .run(next.state, next.plannedStart, next.cut, next.ship, release.activatedAt ?? (next.state === "active" ? now : null), release.frozenAt ?? (next.state === "frozen" ? now : null), release.shippedAt ?? (next.state === "shipped" ? now : null), now, next.train === undefined ? null : JSON.stringify(next.train), next.planner, id, revision); if (result.changes !== 1) throw new Error("release revision changed"); return this.release(id)!; } /** Cross-connection scope changes cannot race the final freeze write. */ freezeRelease(id: number, revision: number, scope: Task[], train: NonNullable): Release { return this.db.transaction(() => { const release = this.release(id); if (!release || release.revision !== revision || release.state !== "active" || this.releases().some(row => row.id !== id && ["active", "frozen"].includes(row.state)) || JSON.stringify(this.list().filter(task => task.release === id)) !== JSON.stringify(scope)) throw new Error("release scope changed before freeze"); return this.updateRelease(id, { state: "frozen", train }, revision); })(); } recordOutcome(peer: PeerId, cls: TaskClass, ok: boolean, at = Date.now()): void { this.db.query("INSERT INTO outcomes (peer, class, ok, at) VALUES (?, ?, ?, ?)").run(peer, cls, ok ? 1 : 0, at); this.db.query("DELETE FROM outcomes WHERE at < ?").run(at - OUTCOMES_KEPT_MS); // nothing older is read } outcomes(cls: TaskClass, since: number): { peer: PeerId; ok: number; at: number }[] { return this.db.query("SELECT peer, ok, at FROM outcomes WHERE class = ? AND at >= ?").all(cls, since) as { peer: PeerId; ok: number; at: number }[]; } recordReview(r: Omit, at = Date.now()): void { this.db.query("INSERT INTO reviews (implementer, reviewer, class, kind, task, at) VALUES (?, ?, ?, ?, ?, ?)").run(r.implementer, r.reviewer, r.class, r.kind, r.task, at); } /** One task's review outcomes, or a class's (for reviewer choice). */ reviews(where: { task: number } | { class: TaskClass }): ReviewOutcome[] { return ("task" in where ? this.db.query("SELECT * FROM reviews WHERE task = ? ORDER BY at").all(where.task) : this.db.query("SELECT * FROM reviews WHERE class = ? ORDER BY at").all(where.class)) as ReviewOutcome[]; } /** A short-circuit SQL presence read; no task, receipt or history body is hydrated into JS. */ hasConductorManualState(): boolean { const row = this.db.query(`SELECT EXISTS( SELECT 1 FROM tasks, json_each(CASE WHEN json_valid(tasks.history) THEN tasks.history ELSE '[]' END) AS entry WHERE tasks.state NOT IN ('approved','cancelled') AND CASE WHEN json_valid(entry.value) THEN json_type(entry.value,'$.conductorManual') IS NOT NULL ELSE 0 END ) AS present`).get() as { present: number }; return row.present === 1; } hasPlannerState(): boolean { const row = this.db.query(`SELECT EXISTS(SELECT 1 FROM tasks WHERE planner IS NOT NULL) OR EXISTS(SELECT 1 FROM releases WHERE planner IS NOT NULL) OR EXISTS(SELECT 1 FROM tasks WHERE CASE WHEN json_valid(sdlc) THEN json_type(sdlc,'$.planReview.planAuthor') IS NOT NULL OR json_type(sdlc,'$.planReview.selfReview') IS NOT NULL ELSE 0 END) OR EXISTS(SELECT 1 FROM tasks, json_each(CASE WHEN json_valid(tasks.history) THEN tasks.history ELSE '[]' END) AS entry WHERE CASE WHEN json_valid(entry.value) THEN json_type(entry.value,'$.planAuthor') IS NOT NULL OR json_type(entry.value,'$.selfReview') IS NOT NULL ELSE 0 END) AS present`).get() as { present: number }; return row.present === 1; } close(): void { this.db.close(); } } export interface ReviewOutcome { implementer: PeerId; reviewer: PeerId; class: TaskClass; /** approved; contradicted (a later check failure or changes requested on the same places); caught (changes requested, then the redo passed); escalated */ kind: "approved" | "contradicted" | "caught" | "escalated"; task: number; at: number; } function parse(row: Record): Task { const out = { ...row } as Record; for (const key of ["offer", "cancelled"]) if (row[key] == null) delete out[key]; else out[key] = JSON.parse(String(row[key])); for (const col of JSON_COLS) { if (col === "sdlc" && row[col] == null) delete out[col]; else out[col] = JSON.parse(String(row[col])); } try { const rawSymbols = row.code_symbols == null ? undefined : String(row.code_symbols); const symbols = rawSymbols === undefined || Buffer.byteLength(rawSymbols) > 64 * 1024 ? undefined : parseTaskCodeSymbols(JSON.parse(rawSymbols)); const head = (out.refs as TaskRefs).commit ?? (out.sdlc as SdlcReceipt | undefined)?.head ?? (out.sdlc as SdlcReceipt | undefined)?.localHead; const privateSymbols = (out.signals as string[]).some(signal => signal === "pii" || signal === "pii_path"); if (symbols && symbols.head === head && !privateSymbols) out.codeSymbols = symbols; } catch { /* Malformed optional derived evidence stays unavailable. */ } delete out.code_symbols; if (out.project_profile != null) Object.assign(out, JSON.parse(String(out.project_profile))); delete out.project_profile; if (out.external_repo != null && out.external_issue != null) out.external = { provider: "github", repo: String(out.external_repo), issue: Number(out.external_issue), url: `https://github.com/${out.external_repo}/issues/${out.external_issue}` }; delete out.external_repo; delete out.external_issue; if (out.task_role != null) out.role = out.task_role; delete out.task_role; if (out.planned_start != null) out.plannedStart = out.planned_start; delete out.planned_start; if (out.planning_revision) out.planningRevision = out.planning_revision; delete out.planning_revision; if (out.pinned) out.pinned = true; else delete out.pinned; if (out.needs_person) out.needsPerson = true; delete out.needs_person; if (out.draft) out.draft = true; else delete out.draft; for (const key of ["rank", "priority", "release", "due"]) if (out[key] == null) delete out[key]; out.planner = row.planner ?? null; return out as unknown as Task; } function parseMilestone(row: Record): Milestone { return { ...parseMilestoneInput({ title: row.title, outcome: row.outcome, state: row.state, horizon: row.horizon, order: row.milestone_order, target: row.target, parent: row.parent }), id: milestoneId(row.id), revision: milestoneRevision(row.revision), history: milestoneHistory(JSON.parse(String(row.history))), created: milestoneId(row.created), updated: milestoneId(row.updated) }; } function parseSuggestion(row: Record): MilestoneSuggestion { return { id: milestoneId(row.id), kind: row.kind as SuggestionItemKind, ref: String(row.ref), milestone: row.milestone == null ? null : milestoneId(row.milestone), 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), citeItem: String(row.cite_item), state: row.state as SuggestionState, by: milestoneActor(row.by), created: milestoneId(row.created), settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) }; } function parseDecomposition(row: Record): MilestoneDecomposition { return { id: milestoneId(row.id), milestone: milestoneId(row.milestone), parts: JSON.parse(String(row.parts)) as DecomposePart[], state: row.state as DecompositionState, by: milestoneActor(row.by), created: milestoneId(row.created), settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) }; } function parseDecompositionAccept(row: Record): DecompositionAccept { return { decomposition: milestoneId(row.decomposition), milestone: milestoneId(row.milestone), part: milestoneId(row.part), task: milestoneId(row.task), intake: row.intake as DecomposeIntake, by: milestoneActor(row.by), at: milestoneId(row.at) }; } function parseRelease(row: Record): Release { 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, plannedStart: row.planned_start as number | null, cut: row.cut as number | null, ship: row.ship as number | null, activatedAt: row.activated_at as number | null, frozenAt: row.frozen_at as number | null, shippedAt: row.shipped_at as number | null, created: Number(row.created), updated: Number(row.updated), revision: Number(row.revision) }; }