@happyvertical/smrt-ingestion 0.57.26 → 0.57.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/FEEDBACK.md +7 -0
- package/PROPOSALS.md +69 -3
- package/README.md +4 -1
- package/REVIEW.md +50 -11
- package/agents/execution.md +4 -2
- package/dist/argument-issues.d.ts +29 -0
- package/dist/argument-issues.d.ts.map +1 -0
- package/dist/chunks/{execution-BzVQax0n.js → execution-Dv3G0d62.js} +102 -12
- package/dist/chunks/execution-Dv3G0d62.js.map +1 -0
- package/dist/chunks/{feedback-D3UTF8fm.js → feedback-PLOZth0a.js} +3 -3
- package/dist/chunks/{feedback-D3UTF8fm.js.map → feedback-PLOZth0a.js.map} +1 -1
- package/dist/chunks/{reviewer-instruction-CEc3AOuU.js → reviewer-instruction-zn11aVA5.js} +2 -2
- package/dist/chunks/{reviewer-instruction-CEc3AOuU.js.map → reviewer-instruction-zn11aVA5.js.map} +1 -1
- package/dist/execution.d.ts +8 -5
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/models.js +1 -1
- package/dist/models.js.map +1 -1
- package/dist/proposal-dto.d.ts +14 -0
- package/dist/proposal-dto.d.ts.map +1 -1
- package/dist/proposal-errors.d.ts +8 -1
- package/dist/proposal-errors.d.ts.map +1 -1
- package/dist/proposal-validation.d.ts +19 -8
- package/dist/proposal-validation.d.ts.map +1 -1
- package/dist/proposals.d.ts +1 -1
- package/dist/proposals.d.ts.map +1 -1
- package/dist/proposals.js +50 -49
- package/dist/proposals.js.map +1 -1
- package/dist/review-dto.d.ts +26 -2
- package/dist/review-dto.d.ts.map +1 -1
- package/dist/review-host.d.ts.map +1 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +4 -4
- package/dist/server.js.map +1 -1
- package/dist/smrt-knowledge.json +21 -21
- package/dist/svelte/components/ReviewView.svelte +67 -8
- package/dist/svelte/components/ReviewView.svelte.d.ts.map +1 -1
- package/dist/svelte/i18n.d.ts +2 -0
- package/dist/svelte/i18n.d.ts.map +1 -1
- package/dist/svelte/i18n.js +2 -0
- package/dist/svelte/index.d.ts +1 -1
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/view-utils.d.ts +5 -1
- package/dist/svelte/view-utils.d.ts.map +1 -1
- package/dist/svelte/view-utils.js +5 -1
- package/package.json +13 -13
- package/dist/chunks/execution-BzVQax0n.js.map +0 -1
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["handler","bytes","value","item","asset","job","position","filename","record"],"sources":["../src/presented-filename.ts","../src/review-analysis.ts","../src/review-instruction-view.ts","../src/review-summary.ts","../src/review-host.ts","../src/sources/common.ts","../src/sources/email.ts","../src/sources/http.ts","../src/sources/watch-folder.ts","../src/server.ts"],"sourcesContent":["/**\n * Source-presented file names (#4214): untrusted text kept for labels only,\n * never identity. One definition shared by the receipt service's strict check\n * and the sources' cleaner (`deliver`), so neither can store a name the other\n * would refuse.\n *\n * Unsafe characters, all removed, are defined by Unicode properties rather\n * than a hand-kept list:\n * - `Cc` control characters (C0, C1, DEL);\n * - `Cf` format characters (bidi embeddings, overrides, isolates and marks,\n * zero-width characters, the BOM, soft hyphen, tag characters, interlinear\n * annotation marks, ...);\n * - `Cs` lone surrogate halves (invalid text; real pairs such as emoji are\n * kept, since the `u` flag matches whole code points);\n * - `Zl`/`Zp` line and paragraph separators (U+2028, U+2029);\n * - `Default_Ignorable_Code_Point` (U+034F, Hangul fillers, variation\n * selectors, U+180E, U+2060-U+206F, ...): characters that render as\n * nothing. Consequences, all display-only (nothing uses the name as\n * identity): emoji ZWJ sequences and emoji presentation selectors are\n * flattened (a family emoji shows as its members); ZWNJ/ZWJ (U+200C,\n * U+200D) are removed from Persian and Indic text, which can change how\n * letters join; and ideographic variation selectors are removed, so a CJK\n * glyph variant shows its base form.\n *\n * Bidi controls let `invoice` + U+202E + `fdp.exe` display as\n * `invoiceexe.pdf`; invisible characters make two different names look\n * identical. Out of scope: Unicode normalization (NFC/NFKC) and confusable\n * look-alike characters; the name stays untrusted display text.\n */\nconst UNSAFE =\n '[\\\\p{Cc}\\\\p{Cf}\\\\p{Cs}\\\\p{Zl}\\\\p{Zp}\\\\p{Default_Ignorable_Code_Point}]';\nconst UNSAFE_CHARACTER = new RegExp(UNSAFE, 'u');\nconst UNSAFE_CHARACTERS = new RegExp(UNSAFE, 'gu');\n\n/** The receipt service's bound on a stored filename, in UTF-16 code units. */\nexport const MAX_FILENAME_LENGTH = 512;\n\n/** Whether a filename may be stored as-is (no unsafe characters, bounded). */\nexport function isStorableFilename(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.trim().length > 0 &&\n value.length <= MAX_FILENAME_LENGTH &&\n !UNSAFE_CHARACTER.test(value)\n );\n}\n\n/**\n * Clean a source-presented name: unsafe characters removed and the result\n * trimmed; a name that is then empty or over the bound is dropped, so an odd\n * name falls back to the default label instead of failing the whole receipt.\n */\nexport function presentedFilename(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const name = value.replace(UNSAFE_CHARACTERS, '').trim();\n return isStorableFilename(name) ? name : undefined;\n}\n","import type { IntakeItemDTO } from './dto.js';\nimport type { CompletedAnalysisSnapshot } from './proposal-dto.js';\nimport { GenerationSnapshotStaleError } from './proposal-errors.js';\nimport type { ReviewPage } from './review-dto.js';\nimport type { IngestionService } from './server.js';\n/** Optional generation availability never substitutes for current saved-review authority. */\nexport async function loadReviewAnalysis(\n service: IngestionService,\n item: IntakeItemDTO,\n reviews: ReviewPage,\n cursor?: string,\n): Promise<{ reviews: ReviewPage; analysis?: CompletedAnalysisSnapshot }> {\n if (\n !['completed', 'partial'].includes(item.processingState) ||\n reviews.generationStale\n )\n return { reviews };\n try {\n return { reviews, analysis: await service.getCompletedAnalysis(item.id) };\n } catch (error) {\n if (!(error instanceof GenerationSnapshotStaleError)) throw error;\n // The old page is not a fallback: authority may have changed during snapshot reads.\n return { reviews: await service.listReviews(item.id, { cursor }) };\n }\n}\n","/** Server-side projection of an item's reviewer-instruction state for review hosts. */\nimport type { CompletedAnalysisSnapshot } from './proposal-dto.js';\nimport type { ReviewerInstructionView } from './review-dto.js';\nimport { reviewerInstructionView } from './reviewer-instruction.js';\nimport type { IngestionService } from './server.js';\n\n/**\n * Project `ItemReviewView.instruction`. History and reinterpretation state are\n * separate reads, so an instruction recorded between them would otherwise look\n * like a dropped one: when the in-effect id names a different instruction the\n * history is re-read, and `dropped` is set only when nothing is in effect.\n */\nexport async function loadInstructionView(\n service: Pick<\n IngestionService,\n 'listReviewerInstructions' | 'getReinterpretationState'\n >,\n itemId: string,\n analysis: CompletedAnalysisSnapshot | undefined,\n): Promise<ReviewerInstructionView | undefined> {\n let [latest] = await service.listReviewerInstructions(itemId);\n // Only a generation \"applies\" an instruction; a completed extraction\n // carries the same record but has produced no suggestions yet.\n const applied =\n analysis?.configuration.stage === 'interpret' &&\n analysis.configuration.reviewerInstruction\n ? reviewerInstructionView(analysis.configuration.reviewerInstruction)\n : null;\n if (!latest && !applied) return undefined;\n const state = await service.getReinterpretationState(itemId);\n if (\n state.instructionInEffect !== null &&\n state.instructionInEffect !== latest?.id\n )\n // An instruction was recorded between the two reads: re-read history.\n [latest] = await service.listReviewerInstructions(itemId);\n const current =\n latest && latest.id === state.instructionInEffect ? latest : null;\n return {\n current,\n applied,\n stale: !!analysis && !!current && current.id !== applied?.id,\n // Dropped means no instruction is in effect (a host reprocess), never\n // \"superseded by a newer instruction\".\n ...(latest && state.instructionInEffect === null\n ? { dropped: latest }\n : {}),\n ...(state.failure ? { failure: state.failure } : {}),\n ...(state.reinterpreting ? { reinterpreting: true } : {}),\n // Without a displayable generation the reviewer can still retry or change\n // the instruction against the latest completed generation.\n ...(analysis?.configuration.stage !== 'interpret' &&\n state.generationAttemptId\n ? {\n binding: {\n attemptId: state.generationAttemptId,\n expectedRevision: state.revision,\n },\n }\n : {}),\n };\n}\n","import type { IntakeItemDTO } from './dto.js';\nimport type { InboxState, ReviewPage } from './review-dto.js';\nimport type { IngestionService } from './server.js';\n\n/** Whole-item state requires each page's live handler, parent and target gates. */\nexport async function loadReviewSummary(\n service: IngestionService,\n item: IntakeItemDTO,\n requestedCursor?: string,\n): Promise<{ reviews: ReviewPage; state: InboxState }> {\n let requested: ReviewPage | undefined;\n if (requestedCursor !== undefined)\n requested = await service.listReviews(item.id, { cursor: requestedCursor });\n let cursor: string | undefined;\n let total = 0,\n succeeded = 0,\n deferred = 0,\n failed = 0;\n const cursors = new Set<string>();\n do {\n const page = await service.listReviews(item.id, { cursor });\n if (requestedCursor === undefined && cursor === undefined) requested = page;\n for (const action of page.actions) {\n total++;\n if (action.review.state === 'succeeded') succeeded++;\n if (action.review.state === 'deferred') deferred++;\n if (['failed', 'outcome_unknown'].includes(action.review.state)) failed++;\n }\n cursor = page.nextCursor;\n if (cursor && cursors.has(cursor))\n throw new Error('Repeated review cursor');\n if (cursor) cursors.add(cursor);\n // Other pages are discarded; only scalar state and the requested page survive.\n } while (cursor);\n const current = await service.getItem(item.id);\n if (!requested) throw new Error('Review page unavailable');\n // Terminal no-action disposition wins; otherwise new processing supersedes old actions.\n const state: InboxState =\n current.disposition && !succeeded\n ? 'resolved'\n : ['queued', 'running'].includes(current.processingState)\n ? 'processing'\n : total\n ? succeeded === total\n ? 'completed'\n : succeeded\n ? 'partially_completed'\n : deferred\n ? 'deferred'\n : failed\n ? 'failed'\n : 'waiting'\n : current.processingState === 'needs_attention'\n ? 'failed'\n : 'unresolved';\n return { reviews: requested, state };\n}\n","/** Server-side implementation of the transport-neutral review callback contract. */\nimport type { IntakeEvidenceDTO, IntakeItemDTO } from './dto.js';\nimport type { GenerationAnalysisOutput } from './proposal-dto.js';\nimport { loadReviewAnalysis } from './review-analysis.js';\nimport type {\n Assignment,\n EvidenceView,\n InboxEntry,\n InboxEvidence,\n IntakeReviewHost,\n ItemReviewView,\n} from './review-dto.js';\nimport { loadInstructionView } from './review-instruction-view.js';\nimport { loadReviewSummary } from './review-summary.js';\nimport {\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n} from './reviewer-instruction.js';\nimport {\n type IngestionService,\n IntakeScanLimitError,\n ITEM_ID_FILTER_CEILING,\n ITEM_PAGE_CEILING,\n ITEM_SCAN_CEILING,\n isIntakeId,\n} from './server.js';\n\n/** One listed row's primary original, as passed to `rowEvidence`. */\nexport interface RowEvidenceRequest {\n itemId: string;\n evidence: IntakeEvidenceDTO;\n}\n/** A host's preview for one row: label and same-origin URLs, never text. */\nexport type RowEvidenceView = Omit<InboxEvidence, 'evidence'>;\n\n/** Trusted application adapters, bound to the same authenticated session as service. */\nexport interface IntakeReviewHostOptions {\n /** Authenticate receipt, enforce upload limits, and request the first extraction. */\n upload: IntakeReviewHost['upload'];\n /** Read durable assignment state; assignment never grants ingestion permissions. */\n assignment(itemId: string): Promise<Assignment>;\n /**\n * Optional batched assignment read for one inbox page. Missing ids are\n * unassigned at version 0. Without it, `list` calls `assignment` per row.\n */\n assignments?(itemIds: string[]): Promise<Map<string, Assignment>>;\n /**\n * Optional assignee pushdown: the item ids currently assigned to `assigneeId`.\n * `list` restricts the page query to them, so a filtered page is cut in one\n * query. Without it (or beyond ITEM_ID_FILTER_CEILING ids) `list` scans pages\n * and filters by `assignment`, which is still honest but costs more rows.\n */\n assignedItemIds?(assigneeId: string): Promise<string[]>;\n /** Authorize manager/assignee and enforce durable CAS plus request-id replay checks. */\n assign: IntakeReviewHost['assign'];\n /** Produce safe text or an authenticated same-origin URL; never storage keys. */\n evidence(\n evidence: IntakeEvidenceDTO,\n ): Promise<Omit<EvidenceView, 'evidence'>>;\n /**\n * Optional, opt-in row previews for the inbox (#4213). Called at most once\n * per `list` page with each listed row's primary durable part (metadata\n * only, read in one batched query); return item id -> `{ label, viewUrl?,\n * thumbnailUrl? }` built from metadata, without reading bytes. Rows missing\n * from the map get no preview. When omitted, rows show no original link and\n * `list` calls no review-host adapter (`evidence`/`rowEvidence`); it still\n * reads the page's evidence metadata once for filename labels (#4214), for\n * which the host's `authorize` runs once per distinct captured ceiling, and\n * lists with item-only labels if that read fails. If `rowEvidence` throws,\n * the page still lists without previews. `load` never calls it.\n */\n rowEvidence?(\n rows: readonly RowEvidenceRequest[],\n ): Promise<ReadonlyMap<string, RowEvidenceView>>;\n /**\n * Presentation label (#4214). `evidence` is the item's durable parts with\n * the primary part first, so a host can label by the original filename;\n * one-argument implementations keep working. The default is the primary\n * part's own `filename`, else `Intake <8 hex>`.\n */\n label?(item: IntakeItemDTO, evidence: IntakeEvidenceDTO[]): string;\n /** Expose the optional feedback UI only when the service has feedback configured. */\n enableFeedback?: boolean;\n /** Optional wakeup after a durable logical split has queued extraction. */\n onSplit?(itemId: string, revision: number): Promise<void>;\n /** Optional wakeup after a durable reviewer instruction has queued reinterpretation. */\n onInstruct?(itemId: string, revision: number): Promise<void>;\n}\n\n/**\n * The original a row should preview, chosen by role rather than media type:\n * when any part has a parent, the record parts (an upload's capture record,\n * an email's message) are skipped and the shallowest child wins (the uploaded\n * file, the first attachment), even when that child is itself JSON. When no\n * part has a parent (a watched-folder file, an email without attachments),\n * the first root part is the original. Ties sort by part id, numerically.\n */\nexport function primaryEvidence(\n parts: readonly IntakeEvidenceDTO[],\n): IntakeEvidenceDTO | undefined {\n const depth = (part: IntakeEvidenceDTO): number => {\n let level = 0;\n let parent = part.parentEvidenceId;\n const seen = new Set<string>();\n while (parent && !seen.has(parent)) {\n seen.add(parent);\n level++;\n parent = parts.find((p) => p.id === parent)?.parentEvidenceId ?? null;\n }\n return level;\n };\n const ordered = [...parts].sort(\n (a, b) =>\n depth(a) - depth(b) ||\n a.partId.localeCompare(b.partId, 'en', { numeric: true }),\n );\n return ordered.find((part) => depth(part) > 0) ?? ordered[0];\n}\n\n/**\n * Create callbacks for one authenticated service scope. Create a fresh host when\n * the session changes; HTTP authentication and CSRF remain application duties.\n */\nexport function createIntakeReviewHost(\n service: IngestionService,\n options: IntakeReviewHostOptions,\n): IntakeReviewHost {\n const label =\n options.label ??\n ((item: IntakeItemDTO, evidence: IntakeEvidenceDTO[]) =>\n // The primary part's own name only, never another part's (#4214).\n primaryEvidence(evidence)?.filename ?? `Intake ${item.id.slice(0, 8)}`);\n /** The item's durable parts with the primary part first, for `label`. */\n const labelled = (\n parts: readonly IntakeEvidenceDTO[],\n ): IntakeEvidenceDTO[] => {\n const primary = primaryEvidence(parts);\n return primary\n ? [primary, ...parts.filter((part) => part !== primary)]\n : [...parts];\n };\n /**\n * Label and, when the host opts in, preview a finished page. `list` applies\n * this once to its final entries just before returning, so every return\n * path decorates the same way. It reads the page's evidence metadata in one\n * `listEvidence` query (labels use the original filename, #4214) and calls\n * `rowEvidence` at most once (#4213). Preview fields are picked explicitly\n * so a host value can never put text on a row.\n */\n const decorateRows = async (entries: InboxEntry[]): Promise<InboxEntry[]> => {\n if (!entries.length) return entries;\n let parts: Map<string, IntakeEvidenceDTO[]>;\n try {\n parts = await service.listEvidence(entries.map((entry) => entry.item.id));\n } catch (error) {\n // With `rowEvidence` the host opted into the batched read, so its\n // failure (e.g. a failing authorize) rejects the page, as #4213\n // defines. Without it, this read only improves labels: a host that\n // never asked for evidence keeps listing, labelled as rows without\n // evidence (no filenames), the way `listItems` merely hides rows.\n if (options.rowEvidence) throw error;\n return entries.map((entry) => ({\n ...entry,\n label: label(entry.item, []),\n }));\n }\n const named = entries.map((entry) => ({\n ...entry,\n label: label(entry.item, labelled(parts.get(entry.item.id) ?? [])),\n }));\n if (!options.rowEvidence) return named;\n const rows: RowEvidenceRequest[] = [];\n for (const entry of named) {\n const primary = primaryEvidence(parts.get(entry.item.id) ?? []);\n if (primary) rows.push({ itemId: entry.item.id, evidence: primary });\n }\n if (!rows.length) return named;\n const primaries = new Map(rows.map((row) => [row.itemId, row.evidence]));\n // Everything that touches the host's answer is isolated: a throw, or a\n // malformed answer (not a map, a non-text label), lists without previews\n // rather than rejecting the page.\n try {\n const views = await options.rowEvidence(rows);\n return named.map((entry) => {\n const primary = primaries.get(entry.item.id);\n // Only rows with a durable primary part can carry a preview, even if\n // the host answers for another row.\n if (!primary) return entry;\n const view = views.get(entry.item.id);\n if (!view) return entry;\n if (typeof view.label !== 'string')\n throw new Error('Invalid row evidence');\n const evidence: InboxEvidence = {\n evidence: primary,\n label: view.label,\n };\n if (typeof view.viewUrl === 'string') evidence.viewUrl = view.viewUrl;\n if (typeof view.thumbnailUrl === 'string')\n evidence.thumbnailUrl = view.thumbnailUrl;\n return { ...entry, evidence };\n });\n } catch {\n // A preview failure must not block triage: list without previews.\n return named;\n }\n };\n const assignments = async (\n itemIds: string[],\n ): Promise<Map<string, Assignment>> => {\n if (!itemIds.length) return new Map();\n if (options.assignments) return options.assignments(itemIds);\n const read = new Map<string, Assignment>();\n for (const itemId of itemIds)\n read.set(itemId, await options.assignment(itemId));\n return read;\n };\n return {\n async list(input) {\n // The contract caps `limit` at the service maximum rather than failing.\n const requested = input.limit ?? 20;\n const limit = Number.isNaN(requested)\n ? 20\n : Math.min(ITEM_PAGE_CEILING, Math.max(1, Math.floor(requested)));\n let itemIds: string[] | undefined;\n if (input.assigneeId && options.assignedItemIds) {\n // Junk ids from the host narrow nothing and must not fail the list.\n const assigned = [\n ...new Set(\n (await options.assignedItemIds(input.assigneeId)).filter(\n isIntakeId,\n ),\n ),\n ];\n if (assigned.length <= ITEM_ID_FILTER_CEILING) itemIds = assigned;\n }\n const items: InboxEntry[] = [];\n let cursor = input.cursor;\n let examined = 0;\n // One query per page when every filter is pushed down. Only an\n // assignee filter the host cannot push down scans further pages, and\n // each scan is still one query plus one batched assignment read. A\n // host call never examines more than ITEM_SCAN_CEILING rows: a short\n // service page with a cursor (the service hit its own ceiling) or the\n // host's own count ends the call with that cursor for the caller.\n for (;;) {\n let page: Awaited<ReturnType<IngestionService['listItemsPage']>>;\n try {\n page = await service.listItemsPage({\n limit,\n cursor,\n state: input.state,\n itemIds,\n // The remaining budget: the service never scans past it, so the\n // host's total stays within ITEM_SCAN_CEILING across calls.\n scanLimit: ITEM_SCAN_CEILING - examined,\n });\n } catch (error) {\n // A later call that spent a small remaining budget without\n // returning a row must not discard what earlier calls collected:\n // hand back the position reached so far (a row the actor can read)\n // and let the caller continue.\n if (error instanceof IntakeScanLimitError && cursor !== input.cursor)\n return {\n items: await decorateRows(items),\n ...(cursor ? { nextCursor: cursor } : {}),\n };\n throw error;\n }\n examined += page.scanned;\n const read = await assignments(page.items.map(({ item }) => item.id));\n for (const [\n index,\n { item, state, cursor: rowCursor },\n ] of page.items.entries()) {\n const assignment = read.get(item.id) ?? {\n assigneeId: null,\n version: 0,\n };\n if (input.assigneeId && assignment.assigneeId !== input.assigneeId)\n continue;\n // The label needs the page's evidence; `decorateRows` sets it.\n items.push({ item, label: '', state, assignment });\n // The continuation is the last row actually returned, so an\n // assignment that changed between the page read and the assignment\n // read can only cost one extra scan, never skip or repeat a row.\n if (items.length === limit)\n return {\n items: await decorateRows(items),\n ...(page.nextCursor || index < page.items.length - 1\n ? { nextCursor: rowCursor }\n : {}),\n };\n }\n if (!page.nextCursor) return { items: await decorateRows(items) };\n if (page.items.length < limit || examined >= ITEM_SCAN_CEILING)\n return {\n items: await decorateRows(items),\n nextCursor: page.nextCursor,\n };\n cursor = page.nextCursor;\n }\n },\n async load(itemId, cursor) {\n const item = await service.getItem(itemId);\n const summary = await loadReviewSummary(service, item, cursor);\n const { analysis, reviews } = await loadReviewAnalysis(\n service,\n item,\n summary.reviews,\n cursor,\n );\n const evidence: EvidenceView[] = [];\n for (const part of await service.getEvidence(itemId)) {\n evidence.push({ ...(await options.evidence(part)), evidence: part });\n }\n const assignment = await options.assignment(itemId);\n // The offered catalog lets a reviewer start any handler; it grants nothing.\n // A catalog failure (not configured, bound exceeded, denied) only hides the\n // start-action picker; existing reviews stay reviewable.\n let catalog: ItemReviewView['catalog'];\n try {\n catalog = await service.listHandlers(itemId);\n } catch {\n catalog = undefined;\n }\n // Reviewer and reason come from the review surface, not the item DTO.\n let disposition: ItemReviewView['disposition'];\n if (item.disposition)\n try {\n disposition = await service.getItemDisposition(itemId);\n } catch {\n disposition = undefined;\n }\n const instruction = await loadInstructionView(service, itemId, analysis);\n await service.getItem(itemId);\n return {\n entry: {\n item,\n label: label(item, labelled(evidence.map((view) => view.evidence))),\n state: summary.state,\n assignment,\n },\n evidence,\n analysis,\n ...(catalog ? { catalog } : {}),\n ...(disposition ? { disposition } : {}),\n reviews,\n ...(instruction ? { instruction } : {}),\n availability: 'available',\n ...(analysis?.configuration.stage === 'interpret'\n ? {\n generation: (\n analysis.result.output as unknown as GenerationAnalysisOutput\n ).proposals,\n }\n : {}),\n };\n },\n upload: (files, requestId) => options.upload(files, requestId),\n async preview(input) {\n if (\n !Number.isSafeInteger(input.index) ||\n input.index < 0 ||\n typeof input.attemptId !== 'string' ||\n !input.attemptId ||\n typeof input.requestId !== 'string' ||\n !input.requestId.trim() ||\n (input.args !== undefined &&\n (!input.args ||\n typeof input.args !== 'object' ||\n Array.isArray(input.args)))\n )\n throw new Error('Invalid preview');\n const analysis = await service.getCompletedAnalysis(\n input.itemId,\n input.attemptId,\n );\n const generation = (\n analysis.result.output as unknown as GenerationAnalysisOutput\n ).proposals;\n const suggestion = generation?.suggestions[input.index];\n // A `needs_review` suggestion is previewable by a person (#4208); a failed\n // attempt, a missing handler or a foreign stage still is not.\n if (\n analysis.configuration.stage !== 'interpret' ||\n generation?.outcome === 'provider_error' ||\n !suggestion ||\n !['ready_for_review', 'needs_review'].includes(suggestion.disposition)\n )\n throw new Error('Preview unavailable');\n const handler = generation.offered.find(\n ({ handler }) =>\n handler.id === suggestion.handlerId &&\n handler.version === suggestion.handlerVersion,\n )?.handler;\n if (!handler) throw new Error('Preview unavailable');\n // Human-completed arguments go through the same explicit preview as an\n // edit; they never rewrite the generation snapshot.\n const args = input.args ? structuredClone(input.args) : suggestion.args;\n const intentionKey = `ui:${input.index}`;\n const actionId =\n handler.kind === 'plan'\n ? undefined\n : await service.createAction(input.itemId, intentionKey, {\n origin: 'generated-proposal',\n intentionKey,\n });\n let cursor: string | undefined;\n let expectedRevision = 0;\n const cursors = new Set<string>();\n do {\n const page = await service.listReviews(input.itemId, { cursor });\n const found = page.actions.find((action) =>\n handler.kind === 'plan'\n ? (action.plan?.key ?? action.stalePlan?.key) === intentionKey\n : action.review.actionId === actionId,\n );\n if (found) {\n const binding = handler.kind === 'plan' ? found.plan : found;\n expectedRevision =\n handler.kind === 'plan'\n ? (found.plan?.revision ?? found.stalePlan?.revision ?? 0)\n : found.review.revision;\n // Preparing an unchanged, currently authorized suggestion is idempotent.\n // State-only stale entries never satisfy this shortcut.\n if (\n binding?.attemptId === input.attemptId &&\n binding.handlerId === suggestion.handlerId &&\n binding.handlerVersion === suggestion.handlerVersion &&\n binding.args\n ) {\n const { intakeBindingDigest } = await import('./execution.js');\n if (intakeBindingDigest(binding.args) === intakeBindingDigest(args))\n return;\n }\n break;\n }\n cursor = page.nextCursor;\n if (cursor && cursors.has(cursor))\n throw new Error('Repeated review cursor');\n if (cursor) cursors.add(cursor);\n } while (cursor);\n // Every failure throws, as on main. A handler's refusal of the\n // arguments throws `HandlerArgumentsInvalidError`; a transport that\n // preserves its `name` lets the component keep the draft inline.\n if (input.args) {\n const shared = {\n itemId: input.itemId,\n attemptId: input.attemptId,\n expectedRevision,\n requestId: input.requestId,\n handlerId: suggestion.handlerId,\n handlerVersion: suggestion.handlerVersion,\n args,\n };\n if (handler.kind === 'plan')\n await service.previewPlan({ ...shared, planKey: intentionKey });\n else if (actionId)\n await service.previewProposal({ ...shared, actionId });\n return;\n }\n await service.previewGeneratedProposals({\n itemId: input.itemId,\n attemptId: input.attemptId,\n selections: [\n {\n index: input.index,\n intentionKey,\n expectedRevision,\n requestId: input.requestId,\n },\n ],\n });\n },\n async decide(input) {\n await service.submitDecision(input);\n },\n apply: (actionId) => service.applyAction(actionId),\n async editPlan(input) {\n await service.previewPlan(input);\n },\n async editAction(input) {\n await service.previewProposal(input);\n },\n candidates: (input) => service.findCandidates(input),\n async assign(input) {\n await service.getItem(input.itemId);\n await options.assign(input);\n },\n async split(input) {\n const result = await service.reviseLogicalSplit(input);\n await options.onSplit?.(input.itemId, result.revision);\n },\n async startAction(input) {\n await service.startReviewerAction(input);\n },\n async resolve(input) {\n await service.resolveItem(input);\n },\n async instruct(input) {\n // Durable first; the reinterpretation runs through the normal dispatch path.\n let result: Awaited<ReturnType<typeof service.recordReviewerInstruction>>;\n try {\n result = await service.recordReviewerInstruction(input);\n } catch (error) {\n if (error instanceof ReviewerInstructionStaleError)\n return { stale: true as const };\n if (error instanceof ReviewerInstructionInvalidError)\n return { invalid: true as const };\n throw error;\n }\n await options.onInstruct?.(input.itemId, result.revision);\n },\n ...(options.enableFeedback\n ? {\n feedback: (\n input: Parameters<NonNullable<IntakeReviewHost['feedback']>>[0],\n ) => service.recordFeedback(input),\n }\n : {}),\n };\n}\n","import type { ReceiptResult } from '../dto.js';\nimport { presentedFilename } from '../presented-filename.js';\nimport type { IngestionService, IntakePart, ReceiveInput } from '../server.js';\n\n/** Host configuration, reconstructed from authenticated session/account state. */\nexport interface SourceBinding {\n enabled: boolean;\n service: Pick<IngestionService, 'receive'>;\n sourceId: string;\n sourceVersion: string;\n capturedCeiling: ReceiveInput['capturedCeiling'];\n retention: ReceiveInput['retention'];\n limits: ReceiveInput['limits'];\n allowedMediaTypes: readonly string[];\n}\nexport type SourceResult =\n | ReceiptResult\n | {\n kind: 'rejected';\n category: 'authentication' | 'unsupported_type' | 'unavailable_bytes';\n };\nexport class SourceInputError extends Error {\n constructor(\n public readonly category:\n | 'invalid'\n | 'limit'\n | 'unsupported_type'\n | 'unavailable_bytes',\n ) {\n super(category);\n }\n}\nexport function record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new SourceInputError('invalid');\n return value as Record<string, unknown>;\n}\nexport function keys(value: Record<string, unknown>, allowed: string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key)))\n throw new SourceInputError('invalid');\n}\nexport function text(value: unknown): string {\n if (typeof value !== 'string' || !value || value.length > 1024)\n throw new SourceInputError('invalid');\n return value;\n}\n/**\n * A name a source presented for a part (upload, attachment, folder entry),\n * kept for labels only (#4214); see `../presented-filename.ts` for the unsafe\n * character set it removes.\n */\nexport { presentedFilename };\n/** `{ filename }` for a usable presented name, else nothing to spread. */\nexport function withPresentedFilename(value: unknown): {\n filename?: string;\n} {\n const filename = presentedFilename(value);\n return filename ? { filename } : {};\n}\nexport function timestamp(value: unknown): Date {\n const date = new Date(text(value));\n if (!Number.isFinite(date.getTime())) throw new SourceInputError('invalid');\n return date;\n}\n/** Bound bytes before parsing or handing them to the receipt service. */\nexport async function boundedBytes(\n stream: ReadableStream<Uint8Array> | null,\n limit: number,\n): Promise<Uint8Array> {\n if (!Number.isSafeInteger(limit) || limit < 1)\n throw new SourceInputError('limit');\n if (!stream) return new Uint8Array();\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > limit) {\n await reader.cancel();\n throw new SourceInputError('limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks);\n}\n/** Intake validates signatures; decoding/format correctness belongs to extraction. */\nexport function validateMedia(\n bytes: Uint8Array,\n type: string,\n allowed: readonly string[],\n): void {\n if (!allowed.includes(type)) throw new SourceInputError('unsupported_type');\n const b = Buffer.from(bytes);\n const ascii = (start: number, end: number) =>\n b.subarray(start, end).toString('ascii');\n const valid: Record<string, boolean> = {\n 'application/pdf': ascii(0, 5) === '%PDF-',\n 'image/tiff':\n b.subarray(0, 4).equals(Buffer.from([73, 73, 42, 0])) ||\n b.subarray(0, 4).equals(Buffer.from([77, 77, 0, 42])),\n 'image/jpeg': b[0] === 255 && b[1] === 216 && b[2] === 255,\n 'image/png': b\n .subarray(0, 8)\n .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),\n 'image/webp': ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP',\n 'audio/wav': ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WAVE',\n 'audio/ogg': ascii(0, 4) === 'OggS',\n 'audio/webm': b.subarray(0, 4).equals(Buffer.from([26, 69, 223, 163])),\n 'audio/mpeg':\n ascii(0, 3) === 'ID3' || (b[0] === 255 && (b[1] & 224) === 224),\n 'audio/mp4': ascii(4, 8) === 'ftyp',\n 'text/plain': true,\n 'text/html': true,\n 'application/json': true,\n };\n if (!Object.hasOwn(valid, type) || !valid[type])\n throw new SourceInputError('unsupported_type');\n if (type.startsWith('text/') || type === 'application/json') {\n try {\n const s = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (type === 'application/json') JSON.parse(s);\n } catch {\n throw new SourceInputError('invalid');\n }\n }\n}\nexport async function deliver(\n binding: SourceBinding,\n deliveryKey: string,\n deliveredAt: Date,\n parts: IntakePart[],\n): Promise<SourceResult> {\n if (!binding.enabled) return { kind: 'rejected', category: 'authentication' };\n try {\n text(deliveryKey);\n if (!Number.isFinite(deliveredAt.getTime()))\n throw new SourceInputError('invalid');\n if (\n parts.length > binding.limits.maxParts ||\n parts.reduce((n, p) => n + p.bytes.byteLength, 0) >\n binding.limits.maxBytes\n )\n throw new SourceInputError('limit');\n for (const part of parts)\n validateMedia(part.bytes, part.mediaType, binding.allowedMediaTypes);\n return await binding.service.receive({\n sourceId: binding.sourceId,\n sourceVersion: binding.sourceVersion,\n capturedCeiling: binding.capturedCeiling,\n retention: binding.retention,\n limits: binding.limits,\n deliveryKey,\n deliveredAt,\n // The one place every source's names are cleaned (#4214): upload,\n // host snapshot, vendor webhook, email and watched folder all deliver\n // here, so an odd name never fails the receipt.\n parts: parts.map(({ filename, ...part }) => ({\n ...part,\n ...withPresentedFilename(filename),\n })),\n });\n } catch (error) {\n return safeFailure(error);\n }\n}\nexport function safeFailure(error: unknown): SourceResult {\n return error instanceof SourceInputError\n ? { kind: 'rejected', category: error.category }\n : { kind: 'retry', category: 'unavailable' };\n}\n","import type { IntakePart } from '../server.js';\nimport {\n deliver,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n text,\n} from './common.js';\n\n/** Structural messages-owner seam; EmailAccount.readIntakeMessage implements this contract. */\nexport interface EmailIntakeSnapshot {\n accountId: string;\n messageId: string;\n threadId: string;\n inReplyTo: string;\n subject: string;\n text: string;\n html: string;\n date: string;\n attachments: Array<{\n partId: string;\n filename: string;\n mediaType: string;\n bytes: Uint8Array;\n }>;\n}\nexport interface EmailDelivery {\n /** Provider/account-unique locator (e.g. folder + UIDVALIDITY + UID), not sender Message-ID alone. */\n locator: string;\n /** Explicit immutable source revision, never an automatically substituted content hash. */\n revision: string;\n checkpoint: string;\n}\nexport interface EmailSourceOptions {\n binding: SourceBinding;\n accountId: string;\n readMessage(delivery: EmailDelivery): Promise<EmailIntakeSnapshot>;\n /** Durable host checkpoint; called in input order only after accepted/duplicate. */\n acknowledge(checkpoint: string): Promise<void>;\n}\n/** Opt-in intake: hosts enumerate configured accounts and supply resumable provider locators. */\nexport class EmailSourceAdapter {\n constructor(private readonly options: EmailSourceOptions) {}\n async receive(delivery: EmailDelivery): Promise<SourceResult> {\n const { binding } = this.options;\n if (!binding.enabled)\n return { kind: 'rejected', category: 'authentication' };\n try {\n text(delivery.locator);\n text(delivery.revision);\n text(delivery.checkpoint);\n const snapshot = await this.options.readMessage(delivery);\n if (snapshot.accountId !== this.options.accountId)\n return { kind: 'rejected', category: 'authentication' };\n const { attachments } = snapshot;\n // Transport objects may carry additional provider fields. Preserve only the contract.\n const body = {\n accountId: snapshot.accountId,\n messageId: snapshot.messageId,\n threadId: snapshot.threadId,\n inReplyTo: snapshot.inReplyTo,\n subject: snapshot.subject,\n text: snapshot.text,\n html: snapshot.html,\n date: snapshot.date,\n };\n if (Object.values(body).some((value) => typeof value !== 'string')) {\n throw new SourceInputError('invalid');\n }\n const parts: IntakePart[] = [\n {\n partId: 'message',\n mediaType: 'application/json',\n bytes: Buffer.from(JSON.stringify(body)),\n sourceReference: {\n owner: 'message',\n id: delivery.locator,\n version: delivery.revision,\n },\n },\n ];\n for (const attachment of attachments) {\n if (!(attachment.bytes instanceof Uint8Array))\n throw new SourceInputError('unavailable_bytes');\n parts.push({\n partId: `attachment:${text(attachment.partId)}`,\n parentPartId: 'message',\n mediaType: attachment.mediaType,\n bytes: attachment.bytes,\n filename: attachment.filename,\n sourceReference: {\n owner: 'message-attachment',\n id: `${delivery.locator}:${attachment.partId}`,\n version: delivery.revision,\n },\n });\n }\n // Filename and part mapping are retained alongside message/thread identity.\n parts[0].bytes = Buffer.from(\n JSON.stringify({\n ...body,\n attachments: attachments.map(({ partId, filename, mediaType }) => ({\n partId,\n filename,\n mediaType,\n })),\n }),\n );\n const result = await deliver(\n binding,\n JSON.stringify([\n this.options.accountId,\n delivery.locator,\n delivery.revision,\n ]),\n new Date(snapshot.date),\n parts,\n );\n if (result.kind === 'accepted' || result.kind === 'duplicate')\n await this.options.acknowledge(delivery.checkpoint);\n return result;\n } catch (error) {\n if (\n error instanceof Error &&\n error.name === 'EmailIntakeSnapshotError' &&\n 'category' in error\n ) {\n const category = error.category;\n if (\n category === 'invalid' ||\n category === 'limit' ||\n category === 'unavailable_bytes'\n ) {\n return { kind: 'rejected', category };\n }\n }\n return safeFailure(error);\n }\n }\n async receiveBatch(\n deliveries: readonly EmailDelivery[],\n ): Promise<SourceResult[]> {\n const results: SourceResult[] = [];\n for (const delivery of deliveries) {\n const result = await this.receive(delivery);\n results.push(result);\n if (result.kind !== 'accepted' && result.kind !== 'duplicate') break;\n }\n return results;\n }\n}\n","import type { IntakePart } from '../server.js';\nimport {\n boundedBytes,\n deliver,\n keys,\n presentedFilename,\n record,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n text,\n timestamp,\n} from './common.js';\n\nexport interface AuthenticatedSource extends SourceBinding {\n /** Explicit wire limit includes multipart framing and capture metadata. */\n maxRequestBytes: number;\n /** Host proves ownership/current access and copies immutable owner bytes. */\n snapshotReference?(reference: {\n owner: 'asset' | 'message';\n id: string;\n version: string;\n }): Promise<IntakePart[]>;\n}\nexport interface SourceHttpOptions {\n /** Authenticate and select enabled source from server configuration, never body fields. */\n authenticate(request: Request): Promise<AuthenticatedSource | null>;\n}\nfunction response(result: SourceResult): Response {\n return Response.json(result, {\n status:\n result.kind === 'accepted' || result.kind === 'duplicate'\n ? 200\n : result.kind === 'retry'\n ? 503\n : 'category' in result && result.category === 'authentication'\n ? 401\n : 'category' in result && result.category === 'limit'\n ? 413\n : 400,\n });\n}\n/** Reference Web Request handler; mobile clients reuse their durable UUID Idempotency-Key. */\nexport function createSourceDeliveryHandler(\n options: SourceHttpOptions,\n): (request: Request) => Promise<Response> {\n return async (request) => {\n try {\n const binding = await options.authenticate(request);\n if (!binding?.enabled)\n return response({ kind: 'rejected', category: 'authentication' });\n if (request.method !== 'POST') throw new SourceInputError('invalid');\n const key = text(request.headers.get('idempotency-key'));\n const length = request.headers.get('content-length');\n if (\n length &&\n (!/^\\d+$/.test(length) || Number(length) > binding.maxRequestBytes)\n )\n throw new SourceInputError('limit');\n const bytes = await boundedBytes(request.body, binding.maxRequestBytes);\n const type = request.headers.get('content-type') || '';\n let deliveredAt: Date;\n const parts: IntakePart[] = [];\n if (type.split(';')[0] === 'application/json') {\n let payload: Record<string, unknown>;\n try {\n payload = record(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)),\n );\n } catch {\n throw new SourceInputError('invalid');\n }\n keys(payload, ['capturedAt', 'text', 'structured', 'reference']);\n deliveredAt = timestamp(payload.capturedAt);\n if (\n ['text', 'structured', 'reference'].filter(\n (field) => payload[field] !== undefined,\n ).length !== 1\n )\n throw new SourceInputError('invalid');\n if (payload.text !== undefined) {\n if (typeof payload.text !== 'string')\n throw new SourceInputError('invalid');\n parts.push({\n partId: 'body',\n mediaType: 'text/plain',\n bytes: Buffer.from(payload.text),\n });\n } else if (payload.structured !== undefined) {\n parts.push({\n partId: 'body',\n mediaType: 'application/json',\n bytes: Buffer.from(JSON.stringify(record(payload.structured))),\n });\n } else {\n const ref = record(payload.reference);\n keys(ref, ['owner', 'id', 'version']);\n if (\n (ref.owner !== 'asset' && ref.owner !== 'message') ||\n !binding.snapshotReference\n )\n throw new SourceInputError('invalid');\n const reference = {\n owner: ref.owner,\n id: text(ref.id),\n version: text(ref.version),\n } as const;\n const snapshots = await binding.snapshotReference(reference);\n if (!snapshots.length)\n throw new SourceInputError('unavailable_bytes');\n // A host snapshot may carry a `filename`; `deliver` cleans it.\n for (const part of snapshots)\n parts.push({\n ...part,\n sourceReference: part.sourceReference ?? reference,\n });\n }\n } else if (type.startsWith('multipart/form-data;')) {\n let form: FormData;\n try {\n form = await new Response(Buffer.from(bytes), {\n headers: { 'content-type': type },\n }).formData();\n } catch {\n throw new SourceInputError('invalid');\n }\n const fields: Record<string, string> = {};\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n if (\n !['captureId', 'capturedAt', 'captureSource', 'sha256'].includes(\n name,\n ) ||\n fields[name] !== undefined\n )\n throw new SourceInputError('invalid');\n fields[name] = value;\n } else {\n if (name !== 'file' || parts.length)\n throw new SourceInputError('invalid');\n // Keep the original name for labels; it never becomes identity.\n // `blob` is the name a nameless Blob part gets, not a real one;\n // it is compared after cleaning, and `deliver` cleans the rest.\n const presented = presentedFilename(value.name);\n const original = presented === 'blob' ? undefined : presented;\n parts.push({\n partId: 'file',\n parentPartId: 'capture',\n mediaType: value.type,\n bytes: await boundedBytes(\n value.stream(),\n binding.limits.maxBytes,\n ),\n ...(original ? { filename: original } : {}),\n });\n }\n }\n if (\n parts.length !== 1 ||\n text(fields.captureId) !== key ||\n !['camera', 'native_picker', 'audio', 'document'].includes(\n fields.captureSource,\n )\n )\n throw new SourceInputError('invalid');\n deliveredAt = timestamp(fields.capturedAt);\n if (fields.sha256) {\n if (!/^[a-f0-9]{64}$/.test(fields.sha256))\n throw new SourceInputError('invalid');\n parts[0].expectedHash = fields.sha256;\n }\n parts.unshift({\n partId: 'capture',\n mediaType: 'application/json',\n bytes: Buffer.from(\n JSON.stringify({\n captureId: fields.captureId,\n capturedAt: fields.capturedAt,\n captureSource: fields.captureSource,\n ...(fields.sha256 === undefined ? {} : { sha256: fields.sha256 }),\n }),\n ),\n });\n } else throw new SourceInputError('unsupported_type');\n return response(await deliver(binding, key, deliveredAt, parts));\n } catch (error) {\n return response(\n error instanceof SyntaxError\n ? { kind: 'rejected', category: 'invalid' }\n : safeFailure(error),\n );\n }\n };\n}\n\nexport interface VerifiedVendorDelivery {\n binding: SourceBinding;\n deliveryKey: string;\n deliveredAt: Date;\n parts: IntakePart[];\n}\n/** Vendor implementation owns signature/timestamp verification and replay identity. */\nexport function createVendorWebhookHandler(options: {\n maxRequestBytes: number;\n verify(\n request: Request,\n originalBytes: Uint8Array,\n ): Promise<VerifiedVendorDelivery | null>;\n}): (request: Request) => Promise<Response> {\n return async (request) => {\n try {\n if (request.method !== 'POST') throw new SourceInputError('invalid');\n const bytes = await boundedBytes(request.body, options.maxRequestBytes);\n const verified = await options.verify(request, bytes);\n if (!verified)\n return response({ kind: 'rejected', category: 'authentication' });\n return response(\n await deliver(\n verified.binding,\n verified.deliveryKey,\n verified.deliveredAt,\n verified.parts,\n ),\n );\n } catch (error) {\n return response(safeFailure(error));\n }\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n writeFile,\n} from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n deliver,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n} from './common.js';\n\nexport interface WatchFolderOptions {\n binding: SourceBinding;\n /** Private producer directory; claims and processed live on the same filesystem. */\n directory: string;\n stabilityMs: number;\n now?: () => number;\n /** Observability/crash injection. Never receives file content or credentials. */\n checkpoint?(boundary: 'claimed' | 'received', claimId: string): Promise<void>;\n}\nexport interface WatchFolderResult {\n claimId?: string;\n filename: string;\n result: SourceResult;\n}\ninterface Claim {\n id: string;\n filename: string;\n capturedAt: string;\n sourceId: string;\n sourceVersion: string;\n}\ninterface Observation {\n fingerprint: string;\n since: number;\n}\n/** Files remain in claims until the durable receipt succeeds. A restart safely replays them. */\nexport class WatchFolderSourceAdapter {\n private readonly observations = new Map<string, Observation>();\n private polling = false;\n constructor(private readonly options: WatchFolderOptions) {\n if (!Number.isSafeInteger(options.stabilityMs) || options.stabilityMs < 1)\n throw new Error('Positive stability interval required');\n }\n private async stable(path: string): Promise<boolean> {\n const stat = await lstat(path);\n if (!stat.isFile() || stat.isSymbolicLink())\n throw new SourceInputError('invalid');\n const fingerprint = [\n stat.dev,\n stat.ino,\n stat.size,\n stat.mtimeMs,\n stat.ctimeMs,\n ].join(':');\n const now = (this.options.now ?? Date.now)();\n const prior = this.observations.get(path);\n if (!prior || prior.fingerprint !== fingerprint) {\n this.observations.set(path, { fingerprint, since: now });\n return false;\n }\n return now - prior.since >= this.options.stabilityMs;\n }\n private async syncDirectory(path: string): Promise<void> {\n const directory = await open(path, constants.O_RDONLY);\n try {\n await directory.sync();\n } finally {\n await directory.close();\n }\n }\n private async importClaim(\n directory: string,\n claim: Claim,\n ): Promise<WatchFolderResult | null> {\n const path = join(directory, 'original');\n try {\n if (!(await this.stable(path))) return null;\n const handle = await open(\n path,\n constants.O_RDONLY | constants.O_NOFOLLOW,\n );\n let bytes: Buffer;\n try {\n const before = await handle.stat();\n if (before.size > this.options.binding.limits.maxBytes)\n throw new SourceInputError('limit');\n bytes = Buffer.alloc(before.size);\n let offset = 0;\n while (offset < bytes.length) {\n const { bytesRead } = await handle.read(\n bytes,\n offset,\n bytes.length - offset,\n offset,\n );\n if (!bytesRead) throw new SourceInputError('invalid');\n offset += bytesRead;\n }\n const after = await handle.stat();\n if (\n before.size !== after.size ||\n before.mtimeMs !== after.mtimeMs ||\n before.ctimeMs !== after.ctimeMs\n )\n throw new SourceInputError('invalid');\n } finally {\n await handle.close();\n }\n const mediaType = /\\.pdf$/i.test(claim.filename)\n ? 'application/pdf'\n : 'image/tiff';\n const result = await deliver(\n this.options.binding,\n claim.id,\n new Date(claim.capturedAt),\n [\n {\n partId: 'original',\n mediaType,\n bytes,\n filename: claim.filename,\n sourceReference: {\n owner: 'watch-folder',\n id: claim.filename,\n version: claim.id,\n },\n },\n ],\n );\n if (result.kind === 'accepted' || result.kind === 'duplicate') {\n await this.options.checkpoint?.('received', claim.id);\n await rename(\n directory,\n join(this.options.directory, '.ingestion-processed', claim.id),\n );\n await this.syncDirectory(\n join(this.options.directory, '.ingestion-processed'),\n );\n await this.syncDirectory(\n join(this.options.directory, '.ingestion-claims'),\n );\n this.observations.delete(path);\n } else\n await writeFile(\n join(directory, 'failure.json'),\n JSON.stringify(result),\n { mode: 0o600 },\n );\n return { claimId: claim.id, filename: claim.filename, result };\n } catch (error) {\n const result = safeFailure(error);\n // Error categories only; no raw transport paths, secrets or exception text.\n await writeFile(join(directory, 'failure.json'), JSON.stringify(result), {\n mode: 0o600,\n }).catch(() => {});\n return { claimId: claim.id, filename: claim.filename, result };\n }\n }\n async poll(): Promise<WatchFolderResult[]> {\n if (!this.options.binding.enabled || this.polling) return [];\n this.polling = true;\n const results: WatchFolderResult[] = [];\n try {\n const root = this.options.directory;\n const claims = join(root, '.ingestion-claims');\n const processed = join(root, '.ingestion-processed');\n // Only an explicitly configured, existing directory is touched.\n const rootStat = await lstat(root);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink())\n throw new SourceInputError('invalid');\n await mkdir(claims, { recursive: true, mode: 0o700 });\n await mkdir(processed, { recursive: true, mode: 0o700 });\n for (const privatePath of [claims, processed])\n if ((await lstat(privatePath)).isSymbolicLink())\n throw new SourceInputError('invalid');\n for (const entry of await readdir(claims, { withFileTypes: true })) {\n if (!entry.isDirectory() || !/^[a-f0-9-]{36}$/.test(entry.name))\n continue;\n const directory = join(claims, entry.name);\n try {\n const claim = JSON.parse(\n await readFile(join(directory, 'claim.json'), 'utf8'),\n ) as Claim;\n if (\n claim.id !== entry.name ||\n claim.sourceId !== this.options.binding.sourceId ||\n claim.sourceVersion !== this.options.binding.sourceVersion\n )\n throw new SourceInputError('invalid');\n // A crash before rename leaves an intent without original; producer file remains untouched.\n try {\n await lstat(join(directory, 'original'));\n } catch {\n continue;\n }\n const result = await this.importClaim(directory, claim);\n if (result) results.push(result);\n } catch (error) {\n results.push({\n claimId: entry.name,\n filename: '',\n result: safeFailure(error),\n });\n }\n }\n for (const entry of await readdir(root, { withFileTypes: true })) {\n if (!/\\.(pdf|tiff?)$/i.test(entry.name)) continue;\n const path = join(root, entry.name);\n try {\n if (!(await this.stable(path))) continue;\n const stat = await lstat(path);\n const claim: Claim = {\n id: randomUUID(),\n filename: entry.name,\n capturedAt: new Date(stat.mtimeMs).toISOString(),\n sourceId: this.options.binding.sourceId,\n sourceVersion: this.options.binding.sourceVersion,\n };\n const directory = join(claims, claim.id);\n await mkdir(directory, { mode: 0o700 });\n const metadata = await open(\n join(directory, 'claim.json'),\n 'wx',\n 0o600,\n );\n try {\n await metadata.writeFile(JSON.stringify(claim));\n await metadata.sync();\n } finally {\n await metadata.close();\n }\n await this.syncDirectory(directory);\n await this.syncDirectory(claims);\n await rename(path, join(directory, 'original'));\n await this.syncDirectory(directory);\n await this.syncDirectory(root);\n this.observations.delete(path);\n await this.options.checkpoint?.('claimed', claim.id);\n // Re-observe after rename: a producer may still hold its writing descriptor.\n await this.stable(join(directory, 'original'));\n } catch (error) {\n results.push({ filename: entry.name, result: safeFailure(error) });\n }\n }\n return results;\n } finally {\n this.polling = false;\n }\n }\n}\n","import {\n createCipheriv,\n createDecipheriv,\n createHash,\n randomBytes,\n randomUUID,\n} from 'node:crypto';\nimport { Asset, type AssetRuntimeLike } from '@happyvertical/smrt-assets';\nimport {\n detectEngine,\n isEmbeddedDatabase,\n isTransientDatabaseError,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport { SmrtJobCollection } from '@happyvertical/smrt-jobs';\nimport { withTenant } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type {\n AnalysisOutput,\n InlineInterpretation,\n InlineInterpretationInput,\n IntakeEvidenceDTO,\n IntakeFailure,\n IntakeItemDTO,\n IntakeLimits,\n OwnProposalsInput,\n ReceiptResult,\n} from './dto.js';\nimport { generationSnapshotRead, listReadGate } from './execution-internal.js';\nimport { extractAnalysis } from './extraction.js';\nimport { extractWithProviders } from './extraction-providers.js';\n\nimport { ProposalsNotConfiguredError } from './proposal-errors.js';\nimport { assertProposalLimits } from './proposal-limits.js';\nimport { redactedCeiling, UNFINISHED_ACTION_STATES } from './redaction.js';\nimport './models.js';\nimport type { IntakeExecutionService } from './execution.js';\nimport type {\n IntakeExecutionOptions,\n PreviewPlanInput,\n PreviewProposalInput,\n ResolveItemInput,\n ReviewInput,\n StartActionInput,\n} from './execution-contracts.js';\nimport type { FeedbackConfiguration } from './feedback-contracts.js';\nimport type {\n AdoptRuleInput,\n ObserveFeedbackInput,\n ReadRuleInput,\n RecordFeedbackInput,\n RetrieveFeedbackInput,\n SuggestRuleInput,\n} from './feedback-dto.js';\nimport { isStorableFilename, presentedFilename } from './presented-filename.js';\nimport {\n type ProposalConfiguration,\n type ProposalReadConfiguration,\n proposalReadConfiguration,\n} from './proposal-contracts.js';\nimport type {\n CompletedAnalysisSnapshot,\n PreviewGeneratedInput,\n} from './proposal-dto.js';\nimport { GenerationSourceStaleError } from './proposal-errors.js';\nimport type {\n InboxState,\n LogicalSplitInput,\n ReviewerInstruction,\n ReviewerInstructionInput,\n} from './review-dto.js';\nimport {\n REVIEWER_INSTRUCTION_MAX_LENGTH,\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n reviewerInstructionView,\n} from './reviewer-instruction.js';\n\n/** Authenticated host context. Never construct this from transport JSON. */\nexport interface IngestionScope {\n tenantId: string;\n actorId: string;\n confidentialScopeId: string;\n}\n/** A source part is already authenticated by the host/source adapter. */\nexport interface IntakePart {\n partId: string;\n parentPartId?: string;\n mediaType: string;\n bytes: Uint8Array;\n expectedHash?: string;\n sourceReference?: { owner: string; id: string; version: string };\n /** Original name as the source presented it; presentation only, never identity. */\n filename?: string;\n}\n/** A snapshot received by reference: the lifecycle owner keeps the bytes; no\n * blob copy is preserved. Only the text/structured snapshot a stage needs is\n * retained, redacted by the ordinary deletion path. The reference is identity,\n * never authority. */\nexport interface IntakeReferencePart {\n partId: string;\n parentPartId?: string;\n /** Host-typed owner record the snapshot was read from (for example `message`). */\n reference: { owner: string; id: string; version?: string };\n snapshot: { text: string } | { structured: Record<string, unknown> };\n}\n/** Lifecycle owner for owner-bound retention; `kind` is host-typed. */\nexport interface IntakeOwner {\n kind: string;\n id: string;\n}\n/** Host-resolved retention. Deadlines are always required: in `owner` mode they\n * are the hard privacy ceiling while `expireOwned` follows the owner's lifecycle. */\nexport type IntakeRetention =\n | {\n kind?: 'time';\n version: string;\n expiresAt: Date;\n replayUntil: Date;\n acceptAfter: Date;\n }\n | {\n kind: 'owner';\n owner: IntakeOwner;\n version: string;\n expiresAt: Date;\n replayUntil: Date;\n acceptAfter: Date;\n };\n/** Host-resolved delivery and retention policy, never untrusted content labels. */\nexport interface ReceiveInput {\n sourceId: string;\n sourceVersion: string;\n deliveryKey: string;\n deliveredAt: Date;\n parts: Array<IntakePart | IntakeReferencePart>;\n capturedCeiling: Record<string, unknown>;\n retention: IntakeRetention;\n limits: IntakeLimits;\n traceId?: string;\n /** `inline` records no queued work for any revision; the host runs\n * `interpretInline` in-process. Requires text/structured parts only. */\n dispatch?: 'job' | 'inline';\n}\n/** One inbox page request. Filters apply in the query, before the page is cut. */\nexport interface ListItemsInput {\n /** Rows per page; defaults to 20 and never exceeds 100. */\n limit?: number;\n /** Opaque continuation returned by the previous page. */\n cursor?: string;\n /** Durable inbox-state projection; see REVIEW.md for how it is derived. */\n state?: InboxState;\n /** Restrict the page to these item IDs (host-side assignment pushdown). */\n itemIds?: string[];\n /**\n * Rows this call may examine, at most ITEM_SCAN_CEILING (the default). A\n * host that scans across several calls passes its remaining budget so the\n * sum never exceeds the ceiling.\n */\n scanLimit?: number;\n}\n/** Inbox items newest-first by receipt, with their durable state projection. */\nexport interface IntakeItemPage {\n /** `cursor` continues after that row, so a host may cut a page short of it. */\n items: Array<{ item: IntakeItemDTO; state: InboxState; cursor: string }>;\n /** Rows this call examined, including denied and skipped ones; hosts cap on it. */\n scanned: number;\n nextCursor?: string;\n}\n/** Durable attempt claim. Its fence and token are verified on every completion. */\nexport interface AnalysisLease {\n itemId: string;\n analysisId: string;\n attemptId: string;\n revision: number;\n fence: number;\n token: string;\n}\n/** A server-owned dispatch route, retained independently of source metadata. */\nexport interface IntakeDispatchTarget {\n version: 1;\n objectType: string;\n method: string;\n}\nexport interface DispatchRouteInspection {\n status: 'bound' | 'unknown' | 'conflict';\n fingerprint: string;\n target: IntakeDispatchTarget | null;\n}\n/** Trusted integration points; no provider or application-policy implementation. */\nexport interface IngestionOptions {\n /** Optional server-owned interpretation configuration; independent of execution. */\n proposals?: ProposalConfiguration;\n /** Credential-free persisted proposal reads and previews; cannot generate. */\n proposalRead?: ProposalReadConfiguration;\n /** Explicit scoped learning; never inferred from analysis or execution success. */\n feedback?: FeedbackConfiguration;\n /** Optional application-owned review/execution catalog and live authority. */\n execution?: IntakeExecutionOptions;\n db: DatabaseInterface;\n assets: AssetRuntimeLike;\n scope: IngestionScope;\n /**\n * Optional server secret (at least 32 bytes) that seals inbox page cursors.\n * With it, a page that spends its scan limit on unreadable rows can hand\n * back an opaque position past them; without it, a cursor only ever names\n * the last row the actor can read. Never derive it from request data.\n */\n cursorKey?: string | Uint8Array;\n /** Recheck current access for EVERY boundary, including worker completion. */\n authorize(input: {\n scope: IngestionScope;\n operation: 'receive' | 'read' | 'process' | 'delete';\n capturedCeiling: Record<string, unknown>;\n db: DatabaseInterface;\n }): Promise<boolean>;\n /** Registered job handler supplied by the host; dispatch arguments contain IDs only. */\n jobTarget: { objectType: string; method: string };\n /** Explicit operator authority for provenance-free legacy receipts; closed when omitted.\n * Does not replace the normal current/captured process authorization.\n */\n dispatchRecovery?: {\n authorize(input: {\n scope: IngestionScope;\n itemId: string;\n capturedCeiling: Record<string, unknown>;\n evidenceRef: string;\n db: DatabaseInterface;\n }): Promise<boolean>;\n };\n /** Purge host-owned embeddings/previews/caches; retries must be idempotent. */\n purgeDerived(input: { tenantId: string; itemId: string }): Promise<void>;\n now?: () => Date;\n /** Fault injection/observability; never changes authority or persistence. */\n checkpoint?: (boundary: string) => Promise<void>;\n}\n\ntype Row = Record<string, unknown>;\nconst TABLES = [\n 'intake_items',\n 'intake_evidence',\n 'intake_analyses',\n 'intake_analysis_attempts',\n 'intake_plans',\n 'intake_actions',\n 'intake_proposals',\n 'intake_review_decisions',\n 'intake_executions',\n 'intake_feedback',\n 'intake_dispositions',\n 'intake_dispatches',\n 'intake_deletions',\n] as const;\nconst failures = new Set([\n 'unsupported_type',\n 'malformed_output',\n 'limit',\n 'timeout',\n 'unavailable',\n 'authentication',\n 'cancelled',\n 'integrity',\n]);\nconst uuid =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction object(value: unknown): Record<string, unknown> {\n const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n throw new Error('Invalid intake payload');\n return parsed as Record<string, unknown>;\n}\nfunction canonical(value: unknown): string {\n if (value === null || typeof value === 'string' || typeof value === 'boolean')\n return JSON.stringify(value);\n if (typeof value === 'number' && Number.isFinite(value))\n return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (\n value &&\n typeof value === 'object' &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n return `{${Object.keys(value)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonical((value as Row)[k])}`)\n .join(',')}}`;\n }\n throw new Error('Invalid canonical intake value');\n}\nfunction digest(value: unknown): string {\n return createHash('sha256').update(canonical(value)).digest('hex');\n}\nfunction bytesHash(value: Uint8Array): string {\n return createHash('sha256').update(value).digest('hex');\n}\nfunction nonempty(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512)\n throw new Error('Invalid intake identifier');\n}\n/** A source-supplied display name: bounded text with no unsafe characters. */\nfunction filename(value: unknown): asserts value is string {\n // Same character set the source adapters strip (presented-filename.ts).\n if (!isStorableFilename(value)) throw new Error('Invalid intake filename');\n}\nfunction integer(value: unknown, max = 2_147_483_647): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value <= 0 ||\n value > max\n )\n throw new Error('Invalid intake limit');\n}\nconst ITEM_PAGE_DEFAULT = 20;\n/** The most rows one inbox page returns. */\nexport const ITEM_PAGE_CEILING = 100;\n/**\n * The most rows one `listItemsPage` call examines, whatever its filters.\n * When it is reached the page is returned short with a `nextCursor`, or the\n * call fails with `IntakeScanLimitError` when it found no readable row and may not\n * disclose a position; no single call scans an unbounded scope.\n */\nexport const ITEM_SCAN_CEILING = 10 * ITEM_PAGE_CEILING;\n/** The most ids one page may be restricted to before the host must fall back to scanning. */\nexport const ITEM_ID_FILTER_CEILING = 1000;\n/** True for a value shaped like an intake item id; hosts use it to drop junk before a page query. */\nexport function isIntakeId(value: unknown): value is string {\n return typeof value === 'string' && uuid.test(value);\n}\nconst INBOX_STATES: readonly InboxState[] = [\n 'resolved',\n 'processing',\n 'unresolved',\n 'waiting',\n 'failed',\n 'deferred',\n 'partially_completed',\n 'completed',\n];\n/** Correlated action counters; each uses intake_actions_item_idx for one scanned row. */\nfunction actionCount(where = ''): string {\n return `(SELECT COUNT(*) FROM intake_actions a WHERE a.tenant_id = i.tenant_id AND a.confidential_scope_id = i.confidential_scope_id AND a.item_id = i.id${where ? ` AND ${where}` : ''})`;\n}\n/**\n * Durable inbox-state projection of the saved action journal plus processing\n * state. It mirrors the host's page-traversal classifier without live handler\n * or target gates, so it filters and labels a list; `load` stays authoritative.\n */\nconst dispositionWhere =\n 'd.tenant_id=i.tenant_id AND d.confidential_scope_id=i.confidential_scope_id AND d.item_id=i.id';\nconst INBOX_STATE_SQL = `CASE WHEN EXISTS (SELECT 1 FROM intake_dispositions d WHERE ${dispositionWhere}) AND ${actionCount(\"a.state = 'succeeded'\")} = 0 THEN 'resolved' WHEN i.processing_state IN ('queued','running') THEN 'processing' WHEN ${actionCount()} = 0 THEN CASE WHEN i.processing_state = 'needs_attention' THEN 'failed' ELSE 'unresolved' END WHEN ${actionCount(\"a.state <> 'succeeded'\")} = 0 THEN 'completed' WHEN ${actionCount(\"a.state = 'succeeded'\")} > 0 THEN 'partially_completed' WHEN ${actionCount(\"a.state = 'deferred'\")} > 0 THEN 'deferred' WHEN ${actionCount(\"a.state IN ('failed','outcome_unknown')\")} > 0 THEN 'failed' ELSE 'waiting' END`;\n/** The only receipt-time text the service writes, and the only cursor form. */\nconst RECEIPT_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n/**\n * The canonical receipt time of a scanned row, or undefined when the stored\n * value is not one the service writes: on SQLite the raw text must already be\n * the millisecond ISO form (no offset, no space separator, exactly three\n * fractional digits); on PostgreSQL the stored value must have no\n * sub-millisecond part, which the page query reports as `receipt_ms`.\n */\nfunction receiptTime(row: Row): string | undefined {\n const value = row.created_at;\n if (typeof value === 'string')\n return RECEIPT_TIME.test(value) &&\n Number.isFinite(Date.parse(value)) &&\n new Date(value).toISOString() === value\n ? value\n : undefined;\n if (\n value instanceof Date &&\n Number.isFinite(value.getTime()) &&\n (row.receipt_ms === true || Number(row.receipt_ms) === 1)\n )\n return value.toISOString();\n return undefined;\n}\n/**\n * A page call spent its scan limit without finding a row the actor can read,\n * or would otherwise hand back its own input cursor. Without a `cursorKey`\n * the service may not return a position derived from rows the actor cannot\n * read, so the call fails closed instead; the message names no row. Hosts\n * that already collected rows return them with their cursor.\n */\nexport class IntakeScanLimitError extends Error {\n constructor() {\n super('Intake scan limit');\n this.name = 'IntakeScanLimitError';\n }\n}\n/** A scan position: the stored receipt key and the item id. */\ninterface ItemPosition {\n key: string;\n id: string;\n}\n/**\n * Sealed cursor plaintext size; every sealed cursor has the same length. The\n * page query admits only receipt values and ids of at most 64 characters\n * (SQLite counts code points). The JSON-encoded UTF-8 position is largest\n * when every character is a control character escaped as `\\u00XX` (6 bytes):\n * 2 × 64 × 6 bytes plus 7 bytes of array syntax, which 1024 bytes holds; a\n * 4-byte UTF-8 character such as an emoji costs less.\n */\nconst SEALED_CURSOR_BYTES = 1024;\n/** The longest stored receipt value or id the page query admits on SQLite. */\nconst SCAN_KEY_CHARS = 64;\nfunction samePosition(a: ItemPosition, b: ItemPosition): boolean {\n return a.key === b.key && a.id === b.id;\n}\n/** Opaque (received-at, id) continuation; never a bare id, which is not ordered. */\nfunction encodeItemCursor(receivedAt: string, id: string): string {\n return Buffer.from(JSON.stringify([receivedAt, id])).toString('base64url');\n}\nfunction decodeItemCursor(cursor: string): { receivedAt: string; id: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));\n } catch {\n throw new Error('Invalid item page');\n }\n // The receipt time must be the normalised ISO form the service stores, so\n // the bound compares like the stored text on SQLite as well as PostgreSQL.\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== 'string' ||\n !Number.isFinite(Date.parse(parsed[0])) ||\n new Date(parsed[0]).toISOString() !== parsed[0] ||\n typeof parsed[1] !== 'string' ||\n !uuid.test(parsed[1])\n )\n throw new Error('Invalid item page');\n return { receivedAt: parsed[0], id: parsed[1] };\n}\nfunction persistedDate(value: unknown): Date {\n return value instanceof Date ? value : new Date(String(value));\n}\nconst inlineMedia = new Set(['text/plain', 'application/json']);\n/** Fixed marker for digests overwritten by privacy redaction. */\nconst REDACTED = 'redacted';\n/** Content- or identity-derived digests; successful result digests are kept as\n * the documented replay tombstone. */\nconst REDACTED_DIGESTS = [\n ['intake_analyses', 'input_digest'],\n ['intake_analysis_attempts', 'output_digest'],\n ['intake_plans', 'digest'],\n ['intake_proposals', 'binding_hash'],\n ['intake_review_decisions', 'binding_hash'],\n ['intake_executions', 'binding_hash'],\n] as const;\n\nfunction mediaKind(mediaType: string): string {\n return mediaType.split(';')[0].trim().toLowerCase();\n}\nfunction ownerKey(owner: IntakeOwner): string {\n nonempty(owner.kind);\n nonempty(owner.id);\n // Distinct owners must never collapse onto one stored key (PostgreSQL would\n // replace unpaired surrogates and reject NUL), so both parts must be storable.\n if (\n owner.kind.includes(':') ||\n !storableText(owner.kind) ||\n !storableText(owner.id)\n )\n throw new Error('Invalid intake owner');\n return `${owner.kind}:${owner.id}`;\n}\n/** PostgreSQL JSON cannot hold NUL or unpaired surrogates; SQLite can. Reject\n * them at validation so both engines answer `invalid` rather than diverge. */\nfunction storableText(value: string): boolean {\n if (value.includes('\\u0000')) return false;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(i + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false;\n i++;\n } else if (code >= 0xdc00 && code <= 0xdfff) return false;\n }\n return true;\n}\ntype ReceivedPart = IntakePart & {\n hash: string;\n retain: 'copy' | 'reference';\n snapshot?: string;\n};\n/** Normalize a copied or referenced part; referenced snapshots become bytes once. */\nfunction receivedPart(part: IntakePart | IntakeReferencePart): ReceivedPart {\n nonempty(part.partId);\n if (!('reference' in part)) {\n nonempty(part.mediaType);\n if (!(part.bytes instanceof Uint8Array)) throw new Error('Invalid part');\n const bytes = Buffer.from(part.bytes);\n const hash = bytesHash(bytes);\n if (part.expectedHash && part.expectedHash !== hash)\n throw new Error('Invalid hash');\n // #4243: a copied part's presented filename is validated, never identity.\n if (part.filename !== undefined) filename(part.filename);\n return { ...part, bytes, hash, retain: 'copy' };\n }\n const reference = object(part.reference);\n nonempty(reference.owner);\n nonempty(reference.id);\n if (reference.version !== undefined) nonempty(reference.version);\n for (const value of [reference.owner, reference.id, reference.version])\n if (typeof value === 'string' && !storableText(value))\n throw new Error('Invalid reference');\n const snapshot = object(part.snapshot);\n let mediaType: string;\n let value: string;\n if ('text' in snapshot && !('structured' in snapshot)) {\n if (typeof snapshot.text !== 'string' || !storableText(snapshot.text))\n throw new Error('Invalid snapshot');\n mediaType = 'text/plain';\n value = snapshot.text;\n } else if ('structured' in snapshot && !('text' in snapshot)) {\n mediaType = 'application/json';\n value = canonical(object(snapshot.structured));\n } else throw new Error('Invalid snapshot');\n const bytes = Buffer.from(value, 'utf8');\n return {\n partId: part.partId,\n ...(part.parentPartId === undefined\n ? {}\n : { parentPartId: part.parentPartId }),\n mediaType,\n bytes,\n hash: bytesHash(bytes),\n sourceReference: {\n owner: reference.owner,\n id: reference.id,\n version: reference.version ?? '',\n },\n retain: 'reference',\n snapshot: value,\n };\n}\nfunction date(value: Date): string {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime()))\n throw new Error('Invalid intake date');\n return value.toISOString();\n}\n\n/** Server-only durable lifecycle. Domain approval/execution remains a later layer. */\nexport class IngestionService {\n private readonly db: DatabaseInterface;\n private readonly scope: IngestionScope;\n private readonly engine: 'sqlite' | 'postgres';\n private readonly cursorKey?: Buffer;\n private readonly dispatchTarget: IntakeDispatchTarget;\n constructor(private readonly options: IngestionOptions) {\n if (options.proposals) assertProposalLimits(options.proposals.limits);\n if (options.proposalRead) {\n assertProposalLimits(options.proposalRead.limits);\n if (\n options.proposals &&\n JSON.stringify(proposalReadConfiguration(options.proposals)) !==\n JSON.stringify(proposalReadConfiguration(options.proposalRead))\n )\n throw new Error('Proposal read configuration mismatch');\n }\n this.db = options.db;\n this.scope = Object.freeze({ ...options.scope });\n if (options.cursorKey !== undefined) {\n const secret =\n typeof options.cursorKey === 'string'\n ? Buffer.from(options.cursorKey, 'utf8')\n : Buffer.from(options.cursorKey);\n if (secret.length < 32)\n throw new Error('Cursor key must be at least 32 bytes');\n this.cursorKey = createHash('sha256')\n .update('smrt-ingestion:list-cursor:v1')\n .update(secret)\n .digest();\n }\n if (!uuid.test(this.scope.tenantId))\n throw new Error('Required tenant UUID');\n nonempty(this.scope.actorId);\n nonempty(this.scope.confidentialScopeId);\n const configured = this.db as DatabaseInterface & {\n type?: string;\n config?: { type?: string; url?: string };\n };\n const engine = detectEngine(\n this.db.url || configured.config?.url || '',\n configured.type || configured.config?.type,\n );\n if (!['sqlite', 'postgres'].includes(engine) || !this.db.transaction)\n throw new Error('Ingestion requires transactional SQLite or PostgreSQL');\n this.engine = engine as 'sqlite' | 'postgres';\n nonempty(options.jobTarget.objectType);\n nonempty(options.jobTarget.method);\n this.dispatchTarget = Object.freeze({\n version: 1,\n objectType: options.jobTarget.objectType,\n method: options.jobTarget.method,\n });\n }\n private async execution() {\n if (!this.options.execution)\n throw new Error('Intake execution is not configured');\n const { IntakeExecutionService } = await import('./execution.js');\n return new IntakeExecutionService(this.options, this.options.execution);\n }\n async previewProposal(input: PreviewProposalInput) {\n return (await this.execution()).previewProposal(input);\n }\n async submitDecision(input: ReviewInput) {\n return (await this.execution()).submitDecision(input);\n }\n async applyAction(actionId: string) {\n return (await this.execution()).applyAction(actionId);\n }\n async reconcileAction(actionId: string) {\n return (await this.execution()).reconcileAction(actionId);\n }\n async listReviews(\n itemId: string,\n input: { cursor?: string; limit?: number } = {},\n ) {\n return (await this.execution()).listReviews(itemId, input);\n }\n async getAction(actionId: string) {\n return (await this.execution()).getAction(actionId);\n }\n /** Own-submission review surface; see execution for its authority gate. */\n async listOwnProposals(input: OwnProposalsInput = {}) {\n return (await this.execution()).listOwnProposals(input);\n }\n async submitOwnDecision(input: ReviewInput) {\n return (await this.execution()).submitOwnDecision(input);\n }\n async authorizeAutomatic(actionId: string) {\n return (await this.execution()).authorizeAutomatic(actionId);\n }\n /** Reviewer-chosen handler for any item; same preview/approval path, never automatic. */\n async startReviewerAction(input: StartActionInput) {\n return (await this.execution()).startAction(input);\n }\n /** Terminal \"handled, no action\" disposition; distinct from rejecting a proposal. */\n async resolveItem(input: ResolveItemInput) {\n return (await this.execution()).resolveItem(input);\n }\n /** Reviewer and reason of a resolved item; requires reviewer authority. */\n async getItemDisposition(itemId: string) {\n return (await this.execution()).getItemDisposition(itemId);\n }\n async previewPlan(input: PreviewPlanInput) {\n return (await this.execution()).previewPlan(input);\n }\n async applyPlan(planId: string) {\n return (await this.execution()).applyPlan(planId);\n }\n private async proposals() {\n if (!this.options.proposals) throw new ProposalsNotConfiguredError();\n const { IngestionProposalService } = await import('./proposals.js');\n return new IngestionProposalService(\n this,\n this.options,\n this.options.proposals,\n );\n }\n private async proposalReader() {\n const config = this.options.proposals ?? this.options.proposalRead;\n if (!config) throw new ProposalsNotConfiguredError();\n const { IngestionProposalService } = await import('./proposals.js');\n return new IngestionProposalService(this, this.options, config);\n }\n /** Currently offered reviewer catalog; needs no generation credentials. */\n async listHandlers(itemId: string) {\n return (await this.proposalReader()).listHandlers(itemId);\n }\n async findCandidates(input: {\n itemId: string;\n handlerId: string;\n handlerVersion: string;\n query: string;\n limit?: number;\n }) {\n return (await this.proposals()).findCandidates(input);\n }\n async prepareGeneration(itemId: string, attemptId: string) {\n return (await this.proposals()).prepareGeneration(itemId, attemptId);\n }\n async generateProposals(lease: AnalysisLease) {\n return (await this.proposals()).generate(lease);\n }\n async previewGeneratedProposals(input: PreviewGeneratedInput) {\n return (await this.proposalReader()).preview(input);\n }\n private async feedback() {\n const { IntakeFeedbackService } = await import('./feedback.js');\n return new IntakeFeedbackService(this.options);\n }\n async recordFeedback(input: RecordFeedbackInput) {\n return (await this.feedback()).record(input);\n }\n async observeFeedback(input: ObserveFeedbackInput) {\n return (await this.feedback()).observe(input);\n }\n async retrieveFeedback(input: RetrieveFeedbackInput) {\n return (await this.proposals()).retrieveFeedback(input);\n }\n async suggestRoutingRule(input: SuggestRuleInput) {\n return (await this.feedback()).suggest(input);\n }\n async getRoutingRule(input: ReadRuleInput) {\n return (await this.feedback()).readRule(input);\n }\n async adoptRoutingRule(input: AdoptRuleInput) {\n return (await this.feedback()).adopt(input);\n }\n private now(): Date {\n return this.options.now?.() ?? new Date();\n }\n private async point(name: string): Promise<void> {\n await this.options.checkpoint?.(name);\n }\n private async authorize(\n operation: 'receive' | 'read' | 'process' | 'delete',\n data: Row,\n db = this.db,\n ): Promise<void> {\n if (\n !(await this.options.authorize({\n scope: this.scope,\n operation,\n capturedCeiling: object(data.capturedCeiling ?? {}),\n db,\n }))\n )\n throw new Error('Intake unavailable');\n }\n private async rows(\n db: DatabaseInterface,\n table: (typeof TABLES)[number],\n where = '',\n params: unknown[] = [],\n ): Promise<Row[]> {\n return (\n await db.query(\n `SELECT * FROM ${table} WHERE tenant_id = ? AND confidential_scope_id = ?${where ? ` AND ${where}` : ''}`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n ...params,\n )\n ).rows as Row[];\n }\n private async item(\n id: string,\n operation: 'read' | 'process' | 'delete',\n db = this.db,\n allowExpired = false,\n ): Promise<Row> {\n const [item] = await this.rows(db, 'intake_items', 'id = ?', [id]);\n if (!item) throw new Error('Intake unavailable');\n await this.authorize(operation, object(item.data), db);\n if (\n !allowExpired &&\n (item.visibility !== 'active' ||\n persistedDate(item.expires_at).getTime() <= this.now().getTime())\n )\n throw new Error('Intake unavailable');\n return item;\n }\n private async tx<T>(work: (db: DatabaseInterface) => Promise<T>): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await withEmbeddedWriteTransaction(\n this.db,\n isEmbeddedDatabase(this.db),\n work,\n );\n } catch (error) {\n if (attempt >= 3 || !isTransientDatabaseError(error)) throw error;\n await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));\n }\n }\n }\n /** Refuse under the caller's item lock when a terminal disposition exists. */\n private async assertUnresolved(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<void> {\n if (\n (await this.rows(db, 'intake_dispositions', 'item_id=?', [itemId])).length\n )\n throw new Error('Item resolved');\n }\n private async lock(db: DatabaseInterface, itemId: string): Promise<void> {\n const result = await db.query(\n 'UPDATE intake_items SET analysis_revision = analysis_revision WHERE tenant_id = ? AND confidential_scope_id = ? AND id = ? RETURNING id',\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n if (!result.rows.length) throw new Error('Intake unavailable');\n }\n private async insert(\n db: DatabaseInterface,\n table: (typeof TABLES)[number],\n values: Row,\n conflict?: string,\n ): Promise<Row[]> {\n const now = this.now().toISOString();\n const row = {\n id: randomUUID(),\n slug: randomUUID(),\n context: '',\n created_at: now,\n updated_at: now,\n tenant_id: this.scope.tenantId,\n confidential_scope_id: this.scope.confidentialScopeId,\n ...values,\n };\n const keys = Object.keys(row);\n return (\n await db.query(\n `INSERT INTO ${table} (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})${conflict ? ` ON CONFLICT (${conflict}) DO NOTHING` : ''} RETURNING *`,\n ...Object.values(row),\n )\n ).rows as Row[];\n }\n /** Diagnostic only: deploy manifest migrations before starting ingestion. */\n async assertReady(): Promise<void> {\n for (const table of TABLES)\n await this.db.query(`SELECT id FROM ${table} WHERE 1 = 0`);\n }\n /** Preserve every original before acknowledgment; retries retain receipt identity. */\n async receive(input: ReceiveInput): Promise<ReceiptResult> {\n await this.authorize('receive', { capturedCeiling: input.capturedCeiling });\n const now = this.now();\n let parts: ReceivedPart[];\n let owner: IntakeOwner | null = null;\n const inline = input.dispatch === 'inline';\n try {\n for (const value of [\n input.sourceId,\n input.sourceVersion,\n input.deliveryKey,\n input.retention.version,\n ])\n nonempty(value);\n if (\n input.dispatch !== undefined &&\n !['job', 'inline'].includes(input.dispatch)\n )\n throw new Error('Invalid dispatch mode');\n const retention = input.retention;\n if (\n retention.kind !== undefined &&\n !['time', 'owner'].includes(retention.kind)\n )\n throw new Error('Invalid retention mode');\n if (retention.kind === 'owner') {\n ownerKey(retention.owner);\n owner = { kind: retention.owner.kind, id: retention.owner.id };\n }\n for (const value of Object.values(input.limits)) integer(value);\n date(input.deliveredAt);\n date(input.retention.expiresAt);\n date(input.retention.replayUntil);\n date(input.retention.acceptAfter);\n if (\n input.deliveredAt < input.retention.acceptAfter ||\n input.retention.expiresAt <= now ||\n input.retention.replayUntil < input.retention.expiresAt\n )\n return { kind: 'rejected', category: 'expired' };\n if (!input.parts.length || input.parts.length > input.limits.maxParts)\n return { kind: 'rejected', category: 'limit' };\n const ids = new Set<string>();\n let total = 0;\n parts = input.parts.map((part) => {\n const received = receivedPart(part);\n if (ids.has(received.partId)) throw new Error('Invalid part');\n ids.add(received.partId);\n total += received.bytes.byteLength;\n return received;\n });\n if (total > input.limits.maxBytes)\n return { kind: 'rejected', category: 'limit' };\n // Inline receipts never queue work, so every part must be stage-ready text.\n if (inline && parts.some((p) => !inlineMedia.has(mediaKind(p.mediaType))))\n throw new Error('Inline receipt requires text or structured parts');\n for (const part of parts)\n if (\n part.parentPartId &&\n (!ids.has(part.parentPartId) || part.parentPartId === part.partId)\n )\n throw new Error('Invalid parent');\n for (const part of parts) {\n const seen = new Set([part.partId]);\n let parent = part.parentPartId;\n while (parent) {\n if (seen.has(parent)) throw new Error('Cyclic evidence');\n seen.add(parent);\n parent = parts.find((p) => p.partId === parent)?.parentPartId;\n }\n }\n } catch {\n return { kind: 'rejected', category: 'invalid' };\n }\n // Existing copied receipts keep their exact identity; new modes extend it.\n const identity = parts\n .map((p) => ({\n partId: p.partId,\n parentPartId: p.parentPartId ?? null,\n mediaType: p.mediaType,\n hash: p.hash,\n length: p.bytes.byteLength,\n sourceReference: p.sourceReference ?? null,\n ...(p.retain === 'reference' ? { retain: 'reference' } : {}),\n }))\n .sort((a, b) => a.partId.localeCompare(b.partId));\n const payloadDigest = digest(identity);\n const scopeDigest = digest({\n scope: this.scope,\n ceiling: input.capturedCeiling,\n sourceVersion: input.sourceVersion,\n ...(inline ? { dispatch: 'inline' } : {}),\n ...(owner ? { owner } : {}),\n });\n const reservation = await this.tx(async (db) => {\n await this.authorize(\n 'receive',\n { capturedCeiling: input.capturedCeiling },\n db,\n );\n const inserted = await this.insert(\n db,\n 'intake_items',\n {\n source_id: input.sourceId,\n source_version: input.sourceVersion,\n delivery_key: input.deliveryKey,\n payload_digest: payloadDigest,\n scope_digest: scopeDigest,\n receipt_state: 'reserved',\n processing_state: 'queued',\n visibility: 'active',\n receipt_version: 1,\n analysis_revision: 0,\n fence: 0,\n lease_token: '',\n lease_until: null,\n expires_at: date(input.retention.expiresAt),\n replay_until: date(input.retention.replayUntil),\n cancelled: false,\n trace_id: input.traceId ?? randomUUID(),\n // The submitter is the authenticated actor of this service, recorded\n // server-side; payload or source metadata never supplies it.\n submitter_id: this.scope.actorId,\n owner_key: owner ? ownerKey(owner) : '',\n data: canonical({\n capturedCeiling: input.capturedCeiling,\n limits: input.limits,\n retentionVersion: input.retention.version,\n deliveredAt: date(input.deliveredAt),\n dispatchTarget: this.dispatchTarget,\n ...(inline ? { dispatch: 'inline' } : {}),\n ...(owner ? { retentionOwner: owner } : {}),\n }),\n },\n 'tenant_id,source_id,delivery_key',\n );\n const matches = await db.query(\n 'SELECT * FROM intake_items WHERE tenant_id = ? AND source_id = ? AND delivery_key = ?',\n this.scope.tenantId,\n input.sourceId,\n input.deliveryKey,\n );\n const item = matches.rows[0] as Row;\n if (\n item.scope_digest !== scopeDigest ||\n item.payload_digest !== payloadDigest ||\n !(await this.matchesDispatchRoute(db, item))\n )\n return { kind: 'conflict' as const };\n if (\n item.visibility !== 'active' ||\n persistedDate(item.replay_until) <= now ||\n persistedDate(item.expires_at) <= now\n )\n return { kind: 'expired' as const };\n if (inserted.length) {\n const evidenceIds = new Map(parts.map((p) => [p.partId, randomUUID()]));\n const ordered = [...parts].sort((a, b) => {\n const depth = (p: IntakePart): number =>\n p.parentPartId\n ? 1 + depth(parts.find((x) => x.partId === p.parentPartId)!)\n : 0;\n return depth(a) - depth(b);\n });\n for (const part of ordered)\n await this.insert(db, 'intake_evidence', {\n id: evidenceIds.get(part.partId),\n item_id: item.id,\n part_id: part.partId,\n parent_evidence_id: part.parentPartId\n ? evidenceIds.get(part.parentPartId)\n : null,\n // A referenced snapshot owns no asset: it is durable in the ledger\n // row itself and leaves with the row's ordinary redaction.\n asset_id: part.retain === 'reference' ? null : randomUUID(),\n state: part.retain === 'reference' ? 'durable' : 'intent',\n content_hash: part.hash,\n byte_length: part.bytes.byteLength,\n media_type: part.mediaType,\n source_uri: '',\n data: canonical({\n sourceReference: part.sourceReference ?? null,\n ...(part.filename === undefined\n ? {}\n : { filename: part.filename }),\n ...(part.retain === 'reference'\n ? { retain: 'reference', snapshot: part.snapshot }\n : {}),\n }),\n });\n }\n return { kind: 'reserved' as const, item, created: !!inserted.length };\n });\n if (reservation.kind !== 'reserved')\n return { kind: 'rejected', category: reservation.kind };\n const item = reservation.item;\n const itemId = String(item.id);\n await this.point('reserved');\n if (item.receipt_state === 'ready') {\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n try {\n if (!inline) await this.repairDispatches();\n } catch {\n return { kind: 'retry', category: 'unavailable' };\n }\n return {\n kind: 'duplicate',\n itemId,\n receiptVersion: Number(item.receipt_version),\n };\n }\n const token = randomUUID();\n const claimed = await this.tx((db) =>\n db.query(\n `UPDATE intake_items SET receipt_state = 'preserving', fence = fence + 1, lease_token = ?, lease_until = ? WHERE tenant_id = ? AND confidential_scope_id = ? AND id = ? AND visibility = 'active' AND receipt_state <> 'ready' AND (lease_until IS NULL OR lease_until <= ?) RETURNING fence`,\n token,\n new Date(now.getTime() + input.limits.leaseMs).toISOString(),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n now.toISOString(),\n ),\n );\n if (!claimed.rows.length)\n return (await this.revokedBeforeAck(itemId))\n ? { kind: 'rejected', category: 'expired' }\n : { kind: 'retry', category: 'busy' };\n try {\n for (const part of parts)\n if (part.retain === 'copy') await this.preserve(itemId, part, token);\n await this.point('evidence');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n const evidence = await this.rows(db, 'intake_evidence', 'item_id = ?', [\n itemId,\n ]);\n if (\n evidence.length !== parts.length ||\n evidence.some((e) => e.state !== 'durable')\n )\n throw new Error('Incomplete evidence');\n const updated = await db.query(\n `UPDATE intake_items SET receipt_state='ready',lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND lease_token=? AND lease_until>? AND visibility='active' RETURNING id`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n token,\n this.now().toISOString(),\n );\n if (!updated.rows.length) throw new Error('Lease lost');\n // An inline receipt retains its route provenance but no deliverable intent.\n await this.insert(\n db,\n 'intake_dispatches',\n {\n item_id: itemId,\n stage: 'analyze',\n revision: 1,\n state: inline ? 'completed' : 'pending',\n job_id: '',\n deliveries: 0,\n data: canonical({ dispatchTarget: this.dispatchTarget }),\n },\n 'tenant_id,item_id,stage,revision',\n );\n });\n await this.point('ready');\n if (!inline) await this.repairDispatches();\n await this.point('ack');\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n return {\n kind: reservation.created ? 'accepted' : 'duplicate',\n itemId,\n receiptVersion: 1,\n };\n } catch {\n await this.tx((db) =>\n db.query(\n `UPDATE intake_items SET receipt_state='needs_attention',lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND lease_token=? AND receipt_state<>'ready'`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n token,\n ),\n );\n // An owner deletion that won the race is final, not a retryable fault.\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n return { kind: 'retry', category: 'unavailable' };\n }\n }\n private async revokedBeforeAck(itemId: string): Promise<boolean> {\n const [row] = await this.rows(this.db, 'intake_items', 'id=?', [itemId]);\n return !row || row.visibility !== 'active';\n }\n private async preserve(\n itemId: string,\n part: IntakePart & { hash: string },\n token: string,\n ): Promise<void> {\n const [evidence] = await this.rows(\n this.db,\n 'intake_evidence',\n 'item_id=? AND part_id=?',\n [itemId, part.partId],\n );\n if (!evidence) throw new Error('Missing storage intent');\n await this.item(itemId, 'process');\n const asset = await withTenant(\n { tenantId: this.scope.tenantId },\n async () => {\n let asset = await this.options.assets.collection.get({\n id: String(evidence.asset_id),\n });\n if (!asset)\n asset = await this.options.assets.collection.create({\n id: String(evidence.asset_id),\n tenantId: this.scope.tenantId,\n name: String(evidence.id),\n mimeType: part.mediaType,\n typeSlug: 'intake',\n statusSlug: 'active',\n sourceUri: '',\n });\n if (asset.tenantId !== this.scope.tenantId)\n throw new Error('Asset unavailable');\n return asset;\n },\n );\n const uri = await this.options.assets.store.planFile(asset, {\n mimeType: part.mediaType,\n typeSlug: 'intake',\n });\n if (evidence.source_uri && evidence.source_uri !== uri)\n throw new Error('Storage plan changed');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.lease_token !== token ||\n persistedDate(item.lease_until) <= this.now()\n )\n throw new Error('Lease lost');\n await db.query(\n 'UPDATE intake_evidence SET source_uri=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n uri,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n evidence.id,\n );\n });\n asset.sourceUri = uri;\n await asset.save();\n await this.point('storage_intent');\n await this.options.assets.store.preserveFile(\n asset,\n Buffer.from(part.bytes),\n { mimeType: part.mediaType, typeSlug: 'intake' },\n );\n await this.point('storage');\n const actual = await this.options.assets.store.read(asset);\n if (\n actual.length !== Number(evidence.byte_length) ||\n bytesHash(actual) !== evidence.content_hash\n )\n throw new Error('Storage integrity');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.lease_token !== token ||\n persistedDate(item.lease_until) <= this.now()\n )\n throw new Error('Lease lost');\n await db.query(\n \"UPDATE intake_evidence SET state='durable' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n evidence.id,\n );\n });\n }\n /** Inspect retained route provenance without changing state or enqueuing work. */\n async inspectDispatchRoute(itemId: string): Promise<DispatchRouteInspection> {\n const item = await this.item(itemId, 'read');\n return this.dispatchRouteState(this.db, item);\n }\n\n /** Explicitly bind a provenance-free legacy receipt to this trusted host's route.\n * Never accepts a route from the caller, rewrites original authority, or enqueues.\n */\n async recoverDispatchRoute(input: {\n itemId: string;\n expectedFingerprint: string;\n evidenceRef: string;\n }): Promise<DispatchRouteInspection> {\n nonempty(input.evidenceRef);\n if (!/^[a-f0-9]{64}$/.test(input.expectedFingerprint))\n throw new Error('Invalid dispatch recovery fingerprint');\n if (!this.options.dispatchRecovery)\n throw new Error('Dispatch recovery unavailable');\n return this.tx(async (db) => {\n await this.lock(db, input.itemId);\n const item = await this.item(input.itemId, 'process', db);\n const data = object(item.data);\n if (\n !(await this.options.dispatchRecovery!.authorize({\n scope: this.scope,\n itemId: input.itemId,\n capturedCeiling: object(data.capturedCeiling),\n evidenceRef: input.evidenceRef,\n db,\n }))\n )\n throw new Error('Dispatch recovery unavailable');\n const current = await this.dispatchRouteState(db, item);\n const recovery =\n data.dispatchRecovery === undefined\n ? null\n : object(data.dispatchRecovery);\n if (\n recovery &&\n recovery.expectedFingerprint === input.expectedFingerprint &&\n recovery.evidenceRef === input.evidenceRef &&\n current.status === 'bound' &&\n canonical(current.target) === canonical(this.dispatchTarget)\n ) {\n return current;\n }\n if (\n current.status !== 'unknown' ||\n current.fingerprint !== input.expectedFingerprint\n )\n throw new Error('Dispatch recovery conflict');\n data.dispatchRecovery = {\n version: 1,\n expectedFingerprint: input.expectedFingerprint,\n evidenceRef: input.evidenceRef,\n actorId: this.scope.actorId,\n recordedAt: date(this.now()),\n target: this.dispatchTarget,\n };\n item.data = canonical(data);\n await this.bindDispatchRoute(db, item);\n await this.point('dispatch:recovered');\n const [updated] = await this.rows(db, 'intake_items', 'id=?', [item.id]);\n return this.dispatchRouteState(db, updated);\n });\n }\n\n private async matchesDispatchRoute(\n db: DatabaseInterface,\n item: Row,\n ): Promise<boolean> {\n const route = await this.dispatchRouteState(db, item);\n return (\n route.status === 'bound' &&\n canonical(route.target) === canonical(this.dispatchTarget)\n );\n }\n\n private async bindDispatchRoute(\n db: DatabaseInterface,\n item: Row,\n ): Promise<void> {\n const data = object(item.data);\n if (data.dispatchTarget === undefined) {\n await db.query(\n 'UPDATE intake_items SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...data, dispatchTarget: this.dispatchTarget }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n item.id,\n );\n }\n const intents = await this.rows(db, 'intake_dispatches', 'item_id=?', [\n item.id,\n ]);\n for (const intent of intents) {\n const retained = object(intent.data);\n if (retained.dispatchTarget === undefined)\n await db.query(\n 'UPDATE intake_dispatches SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...retained, dispatchTarget: this.dispatchTarget }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n }\n }\n\n private async dispatchRouteState(\n db: DatabaseInterface,\n item: Row,\n ): Promise<DispatchRouteInspection> {\n let invalid = false;\n const malformed: string[] = [];\n const payload = (value: unknown): Row => {\n try {\n return object(value);\n } catch {\n invalid = true;\n malformed.push(digest(value));\n return {};\n }\n };\n const data = payload(item.data);\n const intents = (\n await this.rows(db, 'intake_dispatches', 'item_id=?', [item.id])\n ).sort((a, b) => String(a.id).localeCompare(String(b.id)));\n const targets: IntakeDispatchTarget[] = [];\n const lineage: unknown[] = [];\n const retain = (value: unknown) => {\n if (value === undefined) return;\n try {\n const target = object(value);\n nonempty(target.objectType);\n nonempty(target.method);\n if (target.version !== 1) throw new Error('Unsupported dispatch route');\n targets.push({\n version: 1,\n objectType: target.objectType,\n method: target.method,\n });\n } catch {\n invalid = true;\n }\n };\n retain(data.dispatchTarget);\n if (data.dispatchRecovery !== undefined) {\n const recovery = payload(data.dispatchRecovery);\n if (recovery.version !== 1 || recovery.target === undefined)\n invalid = true;\n retain(recovery.target);\n }\n const jobs = await SmrtJobCollection.create({ db });\n for (const intent of intents) {\n retain(payload(intent.data).dispatchTarget);\n if (!intent.job_id) continue;\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n jobs.get({ id: String(intent.job_id) }),\n );\n // Missing jobs are absent provenance, not affirmative conflicting authority.\n // A retained route survives job retention; otherwise explicit recovery is required.\n if (!job) {\n lineage.push({ id: intent.job_id, missing: true });\n continue;\n }\n const args = payload(job.args);\n if (\n job.tenantId !== this.scope.tenantId ||\n job.queue !== 'ingestion' ||\n job.objectId ||\n args.itemId !== item.id ||\n args.dispatchId !== intent.id ||\n args.revision !== Number(intent.revision)\n ) {\n invalid = true;\n lineage.push({ id: intent.job_id, valid: false });\n continue;\n }\n const target = {\n version: 1,\n objectType: job.objectType,\n method: job.method,\n };\n retain(target);\n lineage.push({ id: job.id, target, args });\n }\n if (targets.some((target) => canonical(target) !== canonical(targets[0])))\n invalid = true;\n const status = invalid ? 'conflict' : targets.length ? 'bound' : 'unknown';\n return {\n status,\n target: status === 'bound' ? targets[0] : null,\n fingerprint: digest({\n itemId: item.id,\n tenantId: item.tenant_id,\n confidentialScopeId: item.confidential_scope_id,\n sourceId: item.source_id,\n sourceVersion: item.source_version,\n payloadDigest: item.payload_digest,\n scopeDigest: item.scope_digest,\n revision: item.analysis_revision,\n data,\n intents: intents.map((intent) => ({\n id: intent.id,\n revision: intent.revision,\n data: payload(intent.data),\n jobId: intent.job_id,\n })),\n lineage,\n malformed,\n }),\n };\n }\n\n /** Repair lost enqueue/mark writes and deleted/failed jobs. Duplicate jobs are safe. */\n async repairDispatches(): Promise<number> {\n let repaired = 0;\n const intents = await this.rows(\n this.db,\n 'intake_dispatches',\n \"state <> 'completed'\",\n );\n const jobs = await SmrtJobCollection.create({ db: this.db });\n for (const intent of intents) {\n // Scope and protected route are checked before this host's authorization:\n // unrelated hosts must not spend budgets or block one another's receipt.\n const [candidate] = await this.rows(this.db, 'intake_items', 'id=?', [\n intent.item_id,\n ]);\n if (!candidate || !(await this.matchesDispatchRoute(this.db, candidate)))\n continue;\n const item = await this.item(\n String(intent.item_id),\n 'process',\n this.db,\n true,\n );\n if (\n item.visibility !== 'active' ||\n item.cancelled ||\n persistedDate(item.expires_at) <= this.now()\n )\n continue;\n const allocation = await this.tx(async (db) => {\n await this.lock(db, String(item.id));\n const [routedItem] = await this.rows(db, 'intake_items', 'id=?', [\n item.id,\n ]);\n if (!routedItem || !(await this.matchesDispatchRoute(db, routedItem)))\n return false;\n await this.bindDispatchRoute(db, routedItem);\n const currentItem = await this.item(String(item.id), 'process', db);\n const [currentIntent] = await this.rows(\n db,\n 'intake_dispatches',\n 'id=? AND item_id=?',\n [intent.id, item.id],\n );\n if (!currentIntent || currentIntent.state === 'completed') return false;\n if (\n currentIntent.job_id &&\n Number(currentIntent.revision) ===\n Math.max(1, Number(currentItem.analysis_revision))\n ) {\n const currentJobs = await SmrtJobCollection.create({ db });\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n currentJobs.get({ id: String(currentIntent.job_id) }),\n );\n if (job && ['pending', 'running'].includes(job.status)) return false;\n }\n // Revision 1 is queued at receipt, before the first analysis exists.\n if (\n currentItem.cancelled ||\n Number(currentIntent.revision) !==\n Math.max(1, Number(currentItem.analysis_revision))\n ) {\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n currentIntent.id,\n );\n return false;\n }\n const limits = object(\n object(currentItem.data).limits,\n ) as unknown as IntakeLimits;\n if (Number(currentIntent.deliveries) >= limits.maxAttempts) {\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n item.id,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n return false;\n }\n const result = await db.query(\n \"UPDATE intake_dispatches SET deliveries=deliveries+1 WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND state<>'completed' AND deliveries<? RETURNING id\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n currentIntent.id,\n limits.maxAttempts,\n );\n return result.rows.length === 1;\n });\n if (!allocation) continue;\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n jobs.enqueueJob({\n tenantId: this.scope.tenantId,\n objectType: this.dispatchTarget.objectType,\n method: this.dispatchTarget.method,\n args: {\n itemId: intent.item_id,\n revision: Number(intent.revision),\n dispatchId: intent.id,\n },\n queue: 'ingestion',\n maxAttempts: 1,\n }),\n );\n await this.point('enqueued');\n await this.tx((db) =>\n db.query(\n \"UPDATE intake_dispatches SET state='delivered',job_id=? WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND state<>'completed'\",\n job.id,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n ),\n );\n repaired++;\n }\n return repaired;\n }\n /**\n * One authorized inbox page, newest receipt first with the id as tiebreak.\n * Tenant, confidential scope, retention and the id restriction run in the\n * query; rows are authorized before the `state` filter is applied to the\n * fetched batch, so every filter is bounded by the scan limit (default\n * ITEM_SCAN_CEILING). Authority is rechecked at two levels: the host\n * `authorize('read')` once per distinct captured ceiling, and the execution\n * read gate once per distinct (item, handler) bound by a scanned row that\n * passed the first. Without a `cursorKey` every cursor names a row the\n * actor can read; with one, all cursors are sealed and a budget-stopped\n * page may resume past rows the actor cannot read. `scanned` is for trusted\n * host accounting and must not be sent to clients.\n */\n async listItemsPage(input: ListItemsInput = {}): Promise<IntakeItemPage> {\n const limit = input.limit ?? ITEM_PAGE_DEFAULT;\n if (\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > ITEM_PAGE_CEILING ||\n (input.state !== undefined && !INBOX_STATES.includes(input.state)) ||\n (input.itemIds !== undefined &&\n (!Array.isArray(input.itemIds) ||\n input.itemIds.length > ITEM_ID_FILTER_CEILING ||\n !input.itemIds.every(isIntakeId))) ||\n (input.scanLimit !== undefined &&\n (!Number.isSafeInteger(input.scanLimit) ||\n input.scanLimit < 1 ||\n input.scanLimit > ITEM_SCAN_CEILING))\n )\n throw new Error('Invalid item page');\n if (input.itemIds && !input.itemIds.length)\n return { items: [], scanned: 0 };\n const start = input.cursor ? this.decodeCursor(input.cursor) : undefined;\n const scan = await this.scanItems(\n input,\n limit,\n input.scanLimit ?? ITEM_SCAN_CEILING,\n start,\n );\n const items = scan.items.map(({ item, state, position }) => ({\n item,\n state,\n cursor: this.encodeCursor(position),\n }));\n if (scan.done) return { items, scanned: scan.scanned };\n const last = scan.items.at(-1)?.position;\n if (scan.full && last)\n return {\n items,\n scanned: scan.scanned,\n nextCursor: this.encodeCursor(last),\n };\n // The budget ran out before the page filled. A sealed cursor may resume\n // past rows the actor cannot read; an unsealed one may only name a row\n // the actor can read. With no such position, or none past the input, the\n // call fails closed rather than return a cursor that cannot progress.\n const position = this.cursorKey ? scan.scanFrom : scan.lastReadable;\n if (!position || (start && samePosition(position, start)))\n throw new IntakeScanLimitError();\n return {\n items,\n scanned: scan.scanned,\n nextCursor: this.encodeCursor(position),\n };\n }\n /**\n * The bounded page scan behind `listItemsPage` and `listItems`. It returns\n * the rows to list with their positions, the exact scan position reached\n * (`scanFrom`, which may be a row the actor cannot read and must never\n * leave the service unsealed), and the last row the actor can read\n * (`lastReadable`, which may not match the `state` filter).\n */\n private async scanItems(\n input: Pick<ListItemsInput, 'state' | 'itemIds'>,\n limit: number,\n scanCeiling: number,\n start: ItemPosition | undefined,\n ): Promise<{\n items: Array<{\n item: IntakeItemDTO;\n state: InboxState;\n position: ItemPosition;\n }>;\n scanned: number;\n done: boolean;\n full: boolean;\n scanFrom?: ItemPosition;\n lastReadable?: ItemPosition;\n }> {\n let scanFrom = start;\n let lastReadable: ItemPosition | undefined;\n const now = this.now().toISOString();\n const allowed = this.ceilingGate();\n const handlers = this.handlerGate();\n const items: Array<{\n item: IntakeItemDTO;\n state: InboxState;\n position: ItemPosition;\n }> = [];\n let examined = 0;\n // SQLite without planner statistics prefers the expiry index plus a sort,\n // which reads the whole scope per page; pin the ordering index. An id\n // restriction is left to the planner, which then looks ids up directly.\n // A non-text receipt value (an integer, say) sorts after every text value\n // on SQLite and always satisfies `created_at < ?`, so the scan could\n // never move past it; an over-long receipt value or id could not be\n // carried by any cursor; and an embedded NUL makes SQLite's `length()`\n // stop early and the driver return truncated text, so such a row would\n // look canonical and sort above a legitimate row at the truncated value.\n // Such rows are service-foreign and excluded.\n // PostgreSQL types both columns, so neither case arises there.\n const sqlite = this.engine === 'sqlite';\n const pinned =\n sqlite && !input.itemIds ? ' INDEXED BY intake_items_received_idx' : '';\n const textOnly = sqlite\n ? ` AND typeof(i.created_at) = 'text' AND length(i.created_at) <= ${SCAN_KEY_CHARS} AND length(i.id) <= ${SCAN_KEY_CHARS} AND instr(i.created_at, char(0)) = 0 AND instr(i.id, char(0)) = 0`\n : '';\n // The exact stored receipt value (for the scan anchor) and, on\n // PostgreSQL, whether it has a sub-millisecond part a cursor cannot carry.\n const receipt = sqlite\n ? 'i.created_at AS receipt_raw, 1 AS receipt_ms'\n : \"i.created_at::text AS receipt_raw, (i.created_at = date_trunc('milliseconds', i.created_at)) AS receipt_ms\";\n for (;;) {\n const params: unknown[] = [\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n now,\n ];\n let where = textOnly;\n if (scanFrom) {\n where += ' AND (i.created_at < ? OR (i.created_at = ? AND i.id < ?))';\n params.push(scanFrom.key, scanFrom.key, scanFrom.id);\n }\n if (input.itemIds) {\n where += ` AND i.id IN (${input.itemIds.map(() => '?').join(',')})`;\n params.push(...input.itemIds);\n }\n // The first read fetches exactly the page. Refills after skipped rows\n // grow with what has already been examined, from the page size up to\n // 100 rows, and never past the scan limit.\n const wanted = limit - items.length;\n const batch = Math.min(\n scanCeiling - examined,\n Math.max(wanted, Math.min(ITEM_PAGE_CEILING, examined)),\n );\n // The state expression is evaluated once per fetched row.\n // MIN over canonical UUID text preserves getItem's first-id choice\n // without a per-item sort; both probes use the scoped item index.\n const rows = (\n await this.db.query(\n `SELECT i.*, (SELECT first_d.created_at FROM intake_dispositions first_d WHERE first_d.tenant_id=i.tenant_id AND first_d.confidential_scope_id=i.confidential_scope_id AND first_d.item_id=i.id AND CAST(first_d.id AS TEXT)=(SELECT MIN(CAST(d.id AS TEXT)) FROM intake_dispositions d WHERE ${dispositionWhere})) AS disposition_at, ${INBOX_STATE_SQL} AS inbox_state, ${actionCount()} AS action_count, ${receipt} FROM intake_items i${pinned} WHERE i.tenant_id = ? AND i.confidential_scope_id = ? AND i.visibility = 'active' AND i.expires_at > ?${where} ORDER BY i.created_at DESC, i.id DESC LIMIT ?`,\n ...params,\n batch + 1,\n )\n ).rows as Row[];\n const more = rows.length > batch;\n const candidates = rows.slice(0, batch);\n // Authority first, for every fetched row, so that a readable row the\n // state filter excludes may still anchor the cursor. Item-level\n // authority runs once per distinct ceiling. A row whose payload cannot\n // be parsed is skipped and counted; a host authorization that throws\n // rejects the whole page, as `load` does, so a transient failure can\n // never let paging move past rows the actor may be allowed to read.\n const passed = new Set<Row>();\n for (const row of candidates) {\n let data: Row;\n try {\n data = object(row.data);\n } catch {\n continue;\n }\n if (await allowed(data)) passed.add(row);\n }\n // Handler bindings once per batch, for every row that passed and binds\n // actions: one read per batch, bounded by rows scanned.\n await handlers.resolve(\n candidates.filter(\n (row) => passed.has(row) && Number(row.action_count) > 0,\n ),\n );\n let consumed = 0;\n for (const row of candidates) {\n consumed++;\n examined++;\n // A receipt time the service did not write is not listed; the scan\n // position moves past it by its exact stored value so it is neither\n // re-read nor allowed to shift the order of its neighbours.\n // A row whose id is not a UUID is likewise service-foreign: it is\n // passed by its raw id and never listed or named by an unsealed\n // cursor, which only ever carries UUIDs.\n const id = String(row.id);\n const receivedAt = receiptTime(row);\n if (receivedAt !== undefined) scanFrom = { key: receivedAt, id };\n else if (typeof row.receipt_raw === 'string')\n scanFrom = { key: row.receipt_raw, id };\n if (receivedAt === undefined || !isIntakeId(id) || !passed.has(row))\n continue;\n if (Number(row.action_count) > 0 && !(await handlers.readable(row)))\n continue;\n const position = { key: receivedAt, id };\n lastReadable = position;\n if (input.state && row.inbox_state !== input.state) continue;\n items.push({\n item: this.itemDTO(row, row.disposition_at),\n state: String(row.inbox_state) as InboxState,\n position,\n });\n if (items.length === limit) break;\n }\n const remaining = more || consumed < candidates.length;\n const full = items.length === limit;\n if (!remaining || full || examined >= scanCeiling)\n return {\n items,\n scanned: examined,\n done: !remaining,\n full,\n scanFrom,\n lastReadable,\n };\n }\n }\n /** Associated data that binds a sealed cursor to this authenticated scope. */\n private cursorScope(): Buffer {\n return Buffer.from(\n canonical({\n tenantId: this.scope.tenantId,\n confidentialScopeId: this.scope.confidentialScopeId,\n actorId: this.scope.actorId,\n }),\n );\n }\n private encodeCursor(position: ItemPosition): string {\n if (!this.cursorKey) return encodeItemCursor(position.key, position.id);\n // A fixed-size plaintext, so a sealed cursor's length says nothing about\n // whether it stopped on a canonical or a service-foreign row.\n const body = Buffer.alloc(SEALED_CURSOR_BYTES, 0x20);\n const json = Buffer.from(JSON.stringify([position.key, position.id]));\n if (json.length > SEALED_CURSOR_BYTES)\n throw new Error('Cursor position too long');\n json.copy(body);\n const iv = randomBytes(12);\n const cipher = createCipheriv('aes-256-gcm', this.cursorKey, iv);\n cipher.setAAD(this.cursorScope());\n const sealed = Buffer.concat([cipher.update(body), cipher.final()]);\n return Buffer.concat([iv, cipher.getAuthTag(), sealed]).toString(\n 'base64url',\n );\n }\n private decodeCursor(cursor: string): ItemPosition {\n if (!this.cursorKey) {\n const { receivedAt, id } = decodeItemCursor(cursor);\n return { key: receivedAt, id };\n }\n try {\n const bytes = Buffer.from(cursor, 'base64url');\n if (bytes.length !== 28 + SEALED_CURSOR_BYTES) throw new Error('size');\n const decipher = createDecipheriv(\n 'aes-256-gcm',\n this.cursorKey,\n bytes.subarray(0, 12),\n );\n decipher.setAAD(this.cursorScope());\n decipher.setAuthTag(bytes.subarray(12, 28));\n const parsed: unknown = JSON.parse(\n Buffer.concat([\n decipher.update(bytes.subarray(28)),\n decipher.final(),\n ]).toString('utf8'),\n );\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== 'string' ||\n !parsed[0] ||\n typeof parsed[1] !== 'string' ||\n !parsed[1]\n )\n throw new Error('shape');\n return { key: parsed[0], id: parsed[1] };\n } catch {\n throw new Error('Invalid item page');\n }\n }\n /**\n * Every authorized active item, newest receipt first.\n * @deprecated Use `listItemsPage`. Kept so callers of the array-returning\n * API keep working. It walks every page, so its cost grows with the scope,\n * including one execution authorization per (item, handler) across the\n * whole scope. It follows the internal scan position, which never leaves\n * the service, so runs of rows the actor cannot read never stop it. Items\n * are gated exactly as on a page.\n */\n async listItems(): Promise<IntakeItemDTO[]> {\n const all: IntakeItemDTO[] = [];\n let from: ItemPosition | undefined;\n for (;;) {\n const scan = await this.scanItems(\n {},\n ITEM_PAGE_CEILING,\n ITEM_SCAN_CEILING,\n from,\n );\n all.push(...scan.items.map(({ item }) => item));\n if (scan.done) return all;\n if (!scan.scanFrom || (from && samePosition(scan.scanFrom, from)))\n throw new Error('Intake list made no progress');\n from = scan.scanFrom;\n }\n }\n /**\n * One read authorization per distinct captured ceiling for a page of rows.\n * A refusal hides the rows; a malformed ceiling hides its row; a host\n * callback that throws rejects the page with that error.\n */\n private ceilingGate(): (data: Row) => Promise<boolean> {\n const ceilings = new Map<string, Promise<boolean>>();\n return (data) => {\n let ceiling: Record<string, unknown>;\n try {\n ceiling = object(data.capturedCeiling ?? {});\n } catch {\n return Promise.resolve(false);\n }\n const key = canonical(ceiling);\n let decision = ceilings.get(key);\n if (!decision) {\n decision = Promise.resolve(\n this.options.authorize({\n scope: this.scope,\n operation: 'read',\n capturedCeiling: ceiling,\n db: this.db,\n }),\n ).then((granted) => granted === true);\n ceilings.set(key, decision);\n }\n return decision;\n };\n }\n /**\n * The handler checks `listReviews` applies per action, batched for a page:\n * the bindings of the rows' current proposals are projected in SQL\n * (handler id, version, operation and capability; distinct per item) once\n * per fetched batch, then the execution list read gate runs once per distinct\n * (item, handler) of a row that passed the item-level gate. An item whose\n * bound handler the actor cannot currently read, whose binding drifted\n * from the configured handler, or whose bindings cannot be resolved, is\n * not listed. Actions without a proposal carry no handler and are not\n * gated, as in `listReviews`.\n */\n private handlerGate() {\n type Bound = {\n handlerId: string;\n handlerVersion: string;\n operation: unknown;\n capability: unknown;\n };\n const bound = new Map<string, Bound[]>();\n // Created only when a listed row actually binds a handler; a failure to\n // construct the execution service reads as \"not readable\", never as an\n // unhandled rejection.\n let execution: Promise<IntakeExecutionService | undefined> | undefined;\n const service = () => {\n execution ??= (\n this.options.execution\n ? this.execution()\n : Promise.resolve<IntakeExecutionService | undefined>(undefined)\n ).catch(() => undefined);\n return execution;\n };\n // The explicit cast keeps the projection valid where a deployment stores\n // the declared JSON column as json or text rather than jsonb.\n const field = (name: string, text: boolean) =>\n this.engine === 'sqlite'\n ? `json_extract(p.data, '$.binding.${name}')`\n : `(p.data::jsonb)->'binding'${text ? '->>' : '->'}'${name}'`;\n const parsed = (value: unknown): unknown => {\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n };\n return {\n resolve: async (rows: Row[]): Promise<void> => {\n const pending = rows.filter((row) => !bound.has(String(row.id)));\n if (!pending.length) return;\n for (const row of pending) bound.set(String(row.id), []);\n const found = (\n await this.db.query(\n `SELECT DISTINCT p.item_id, ${field('handlerId', true)} AS handler_id, ${field('handlerVersion', true)} AS handler_version, ${field('operation', false)} AS operation, ${field('capability', false)} AS capability FROM intake_proposals p JOIN intake_actions a ON a.tenant_id = p.tenant_id AND a.confidential_scope_id = p.confidential_scope_id AND a.id = p.action_id AND a.proposal_revision = p.revision WHERE p.tenant_id = ? AND p.confidential_scope_id = ? AND p.item_id IN (${pending.map(() => '?').join(',')})`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n ...pending.map((row) => String(row.id)),\n )\n ).rows as Row[];\n for (const row of found)\n bound.get(String(row.item_id))?.push({\n handlerId: row.handler_id == null ? '' : String(row.handler_id),\n handlerVersion:\n row.handler_version == null ? '' : String(row.handler_version),\n operation: parsed(row.operation),\n capability: parsed(row.capability),\n });\n },\n readable: async (row: Row): Promise<boolean> => {\n for (const binding of bound.get(String(row.id)) ?? []) {\n const gate = await service();\n if (!gate || !(await gate[listReadGate](row, binding))) return false;\n }\n return true;\n },\n };\n }\n /** Only the disposition state and time; reviewer and reason need review authority. */\n private itemDTO(row: Row, dispositionAt?: unknown): IntakeItemDTO {\n return {\n id: String(row.id),\n receiptState: String(row.receipt_state),\n processingState: String(row.processing_state),\n analysisRevision: Number(row.analysis_revision),\n cancelled: !!row.cancelled,\n traceId: String(row.trace_id),\n ...(dispositionAt !== undefined && dispositionAt !== null\n ? {\n disposition: {\n state: 'resolved' as const,\n at: persistedDate(dispositionAt).toISOString(),\n },\n }\n : {}),\n };\n }\n async getItem(id: string): Promise<IntakeItemDTO> {\n const item = await this.item(id, 'read');\n const [disposition] = await this.rows(\n this.db,\n 'intake_dispositions',\n 'item_id=? ORDER BY id LIMIT 1',\n [item.id],\n );\n return this.itemDTO(item, disposition?.created_at);\n }\n async getEvidence(itemId: string): Promise<IntakeEvidenceDTO[]> {\n await this.item(itemId, 'read');\n return (\n await this.rows(\n this.db,\n 'intake_evidence',\n \"item_id=? AND state='durable'\",\n [itemId],\n )\n ).map((e) => this.evidenceDTO(e));\n }\n /**\n * Durable evidence for one inbox page in a single query, keyed by item id.\n * Items that are not active, retained and readable are omitted (no\n * existence disclosure); the host authorize callback runs once per distinct\n * captured ceiling rather than once per item, through the same gate as\n * `listItemsPage`: a refusal or a malformed ceiling hides the item, and a\n * host callback that throws rejects the read.\n */\n async listEvidence(\n itemIds: string[],\n ): Promise<Map<string, IntakeEvidenceDTO[]>> {\n if (\n !Array.isArray(itemIds) ||\n itemIds.length > ITEM_PAGE_CEILING ||\n !itemIds.every(isIntakeId)\n )\n throw new Error('Invalid item page');\n const result = new Map<string, IntakeEvidenceDTO[]>();\n if (!itemIds.length) return result;\n const rows = (\n await this.db.query(\n `SELECT e.*, i.data AS item_data FROM intake_evidence e JOIN intake_items i ON i.tenant_id = e.tenant_id AND i.confidential_scope_id = e.confidential_scope_id AND i.id = e.item_id WHERE e.tenant_id = ? AND e.confidential_scope_id = ? AND e.state = 'durable' AND i.visibility = 'active' AND i.expires_at > ? AND e.item_id IN (${itemIds.map(() => '?').join(',')}) ORDER BY e.item_id, e.part_id`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n this.now().toISOString(),\n ...itemIds,\n )\n ).rows as Row[];\n const allowed = this.ceilingGate();\n for (const row of rows) {\n let data: Row;\n try {\n data = object(row.item_data);\n } catch {\n continue;\n }\n if (!(await allowed(data))) continue;\n const itemId = String(row.item_id);\n const parts = result.get(itemId) ?? [];\n parts.push(this.evidenceDTO(row));\n result.set(itemId, parts);\n }\n return result;\n }\n private evidenceDTO(e: Row): IntakeEvidenceDTO {\n // Only the cleaned name is exposed. `sourceReference` stays in storage:\n // its ids are upstream locators (mailbox paths, raw folder names), not\n // display text, and no host needs them on the DTO.\n const filename = presentedFilename(object(e.data).filename);\n return {\n id: String(e.id),\n partId: String(e.part_id),\n parentEvidenceId: e.parent_evidence_id\n ? String(e.parent_evidence_id)\n : null,\n mediaType: String(e.media_type),\n contentHash: String(e.content_hash),\n byteLength: Number(e.byte_length),\n ...(filename ? { filename } : {}),\n };\n }\n async readEvidence(itemId: string, evidenceId: string): Promise<Uint8Array> {\n await this.item(itemId, 'read');\n const [e] = await this.rows(\n this.db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [itemId, evidenceId],\n );\n if (!e) throw new Error('Intake unavailable');\n const bytes = await this.evidenceBytes(e);\n if (\n bytes.length !== Number(e.byte_length) ||\n bytesHash(bytes) !== e.content_hash\n )\n throw new Error('Intake integrity');\n await this.item(itemId, 'read');\n return bytes;\n }\n private async evidenceBytes(e: Row): Promise<Uint8Array> {\n const data = object(e.data);\n if (data.retain === 'reference') {\n // A referenced snapshot never owns an asset; one that does is corrupt.\n if (e.asset_id) throw new Error('Intake integrity');\n if (typeof data.snapshot !== 'string')\n throw new Error('Intake unavailable');\n return Buffer.from(data.snapshot, 'utf8');\n }\n // An asset-less row without its snapshot marker is corrupt; never look up\n // a null asset identifier (PostgreSQL rejects it as an invalid UUID).\n if (!e.asset_id) throw new Error('Intake unavailable');\n const asset = await withTenant({ tenantId: this.scope.tenantId }, () =>\n this.options.assets.collection.get({ id: String(e.asset_id) }),\n );\n if (\n !asset ||\n asset.tenantId !== this.scope.tenantId ||\n asset.sourceUri !== e.source_uri\n )\n throw new Error('Intake unavailable');\n return this.options.assets.store.read(asset);\n }\n /** Append an immutable input revision. Reprocessing never creates actions. */\n async analyze(\n itemId: string,\n configuration: Record<string, unknown>,\n requestKey: string,\n ): Promise<{ id: string; revision: number }> {\n const frozen = structuredClone(configuration);\n if (\n Object.hasOwn(frozen, 'humanCorrection') &&\n frozen.stage !== 'interpret'\n )\n throw new Error('Human corrections require authenticated split revision');\n // Interpretation copies are verified against the pinned extraction source\n // before any provider disclosure (getGenerationInput).\n if (\n Object.hasOwn(frozen, 'reviewerInstruction') &&\n frozen.stage !== 'interpret'\n )\n throw new Error(\n 'Reviewer instructions require authenticated instruction revision',\n );\n return this.tx((db) => this.appendAnalysis(db, itemId, frozen, requestKey));\n }\n private async appendAnalysis(\n db: DatabaseInterface,\n itemId: string,\n configuration: Record<string, unknown>,\n requestKey: string,\n /** Inline only: the extraction attempt the interpretation pins. */\n pinnedSourceAttemptId?: string,\n ): Promise<{ id: string; revision: number }> {\n nonempty(requestKey);\n const configDigest = digest(configuration);\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n // A resolved item is terminal: no reanalysis or split re-extraction.\n await this.assertUnresolved(db, itemId);\n if (!(await this.matchesDispatchRoute(db, item)))\n throw new Error('Intake dispatch route unavailable');\n await this.bindDispatchRoute(db, item);\n if (item.receipt_state !== 'ready' || item.cancelled)\n throw new Error('Intake not processable');\n const previous = await this.rows(db, 'intake_analyses', 'item_id=?', [\n itemId,\n ]);\n const replay = previous.find(\n (a) => object(a.data).requestKey === requestKey,\n );\n if (replay) {\n if (object(replay.data).configDigest !== configDigest)\n throw new Error('Analysis request conflict');\n return { id: String(replay.id), revision: Number(replay.revision) };\n }\n // An interpretation must pin the item's latest extraction. Checked under\n // the item lock before anything is superseded, so a slow host appending a\n // late interpretation cannot clobber a newer extraction (for example a\n // reviewer's retry): it is refused and nothing is appended.\n if (configuration.stage === 'interpret') {\n const pinned = Number(\n object(object(configuration.proposals).source).revision,\n );\n const latestExtraction = previous\n .filter(\n (row) => object(object(row.data).configuration).stage !== 'interpret',\n )\n .reduce(\n (max, row) => Math.max(max, Number(row.revision)),\n Number.NEGATIVE_INFINITY,\n );\n if (pinned !== latestExtraction) throw new GenerationSourceStaleError();\n }\n // Inline only, after #4228's general check: the pinned extraction must\n // also be the latest revision of any stage and its current attempt.\n if (pinnedSourceAttemptId !== undefined) {\n const latest = previous.find(\n (a) => Number(a.revision) === Number(item.analysis_revision),\n );\n if (!latest || latest.current_attempt_id !== pinnedSourceAttemptId)\n throw new Error('Generation source changed');\n }\n const evidence = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND state='durable'\",\n [itemId],\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n const revision = Number(item.analysis_revision) + 1;\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision<? AND state<>'completed'\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n const inputs = evidence\n .map((e) => ({ id: e.id, hash: e.content_hash }))\n .sort((a, b) => String(a.id).localeCompare(String(b.id)));\n const [analysis] = await this.insert(db, 'intake_analyses', {\n item_id: itemId,\n revision,\n fence: 0,\n attempt_number: 0,\n current_attempt_id: null,\n state: 'queued',\n input_digest: digest({ inputs, configuration }),\n data: canonical({ inputs, configuration, requestKey, configDigest }),\n });\n await db.query(\n \"UPDATE intake_items SET analysis_revision=?,processing_state='queued' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n revision,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await this.insert(\n db,\n 'intake_dispatches',\n {\n item_id: itemId,\n stage: 'analyze',\n revision,\n state:\n object(item.data).dispatch === 'inline' ? 'completed' : 'pending',\n job_id: '',\n deliveries: 0,\n data: canonical({ dispatchTarget: this.dispatchTarget }),\n },\n 'tenant_id,item_id,stage,revision',\n );\n return { id: String(analysis.id), revision };\n }\n /** Run one fenced stage in-process and reload its terminal projection. */\n private async inlineStage(\n itemId: string,\n revision: number,\n work: (lease: AnalysisLease) => Promise<unknown>,\n ): Promise<InlineInterpretation['extraction']> {\n const lease = await this.claimAnalysis(itemId, revision, 'inline');\n if (lease) await work(lease);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, revision],\n );\n if (!analysis) throw new Error('Analysis unavailable');\n const [attempt] = analysis.current_attempt_id\n ? await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND item_id=?',\n [analysis.current_attempt_id, itemId],\n )\n : [];\n if (\n !attempt ||\n !['completed', 'partial', 'needs_attention', 'failed'].includes(\n String(attempt.state),\n )\n )\n throw new Error('Inline interpretation busy');\n return {\n analysisId: String(analysis.id),\n revision,\n attemptId: String(attempt.id),\n state: String(\n attempt.state,\n ) as InlineInterpretation['extraction']['state'],\n error: attempt.safe_error\n ? (String(attempt.safe_error) as IntakeFailure)\n : null,\n };\n });\n }\n /** Documented in-process receive-to-proposals path for `dispatch: 'inline'`\n * receipts. Extraction (UTF-8 text/structured only) and interpretation use the\n * same immutable revisions, fenced leases, catalog-live checks, provenance and\n * failure categories as the job path; no queue intent is created or delivered. */\n async interpretInline(\n itemId: string,\n input: InlineInterpretationInput,\n ): Promise<InlineInterpretation> {\n nonempty(input.requestId);\n if (!storableText(input.requestId))\n throw new Error('Invalid intake identifier');\n if (\n typeof input.extraction?.configurationRevision !== 'string' ||\n !input.extraction.configurationRevision ||\n !storableText(input.extraction.configurationRevision)\n )\n throw new Error('Invalid extraction configuration');\n const item = await this.item(itemId, 'process');\n if (object(item.data).dispatch !== 'inline')\n throw new Error('Inline interpretation requires an inline receipt');\n const extraction = {\n configurationRevision: input.extraction.configurationRevision,\n limits: structuredClone(input.extraction.limits),\n };\n const requested = await this.analyze(\n itemId,\n { stage: 'extract', extraction },\n `inline:extract:${input.requestId}`,\n );\n const extracted = await this.inlineStage(\n itemId,\n requested.revision,\n (lease) =>\n extractAnalysis(\n this,\n lease,\n { extract: (request) => extractWithProviders(request, {}) },\n extraction,\n ),\n );\n if (!['completed', 'partial'].includes(extracted.state))\n return { itemId, extraction: extracted };\n const interpretKey = `inline:interpret:${input.requestId}`;\n // A retried request replays its immutable interpretation revision instead\n // of preparing against a source that is no longer the current revision.\n const interpretation =\n (await this.analysisByRequest(itemId, interpretKey)) ??\n (await this.appendInterpretation(\n itemId,\n extracted.attemptId,\n interpretKey,\n ));\n const generation = await this.inlineStage(\n itemId,\n interpretation.revision,\n (lease) => this.generateProposals(lease),\n );\n if (!['completed', 'partial'].includes(generation.state))\n return { itemId, extraction: extracted, generation };\n return {\n itemId,\n extraction: extracted,\n generation,\n analysis: await this.getCompletedAnalysis(itemId, generation.attemptId),\n };\n }\n /** Prepare outside the lock (it reads catalog and analysis), then append\n * under it with the source pin rechecked. A concurrent identical request\n * that appended first makes preparation fail; its revision is the replay. */\n private async appendInterpretation(\n itemId: string,\n sourceAttemptId: string,\n requestKey: string,\n ): Promise<{ id: string; revision: number }> {\n await this.point('inline:replay-miss');\n let configuration: Record<string, unknown>;\n try {\n configuration = structuredClone(\n await this.prepareGeneration(itemId, sourceAttemptId),\n );\n } catch (error) {\n const replay = await this.analysisByRequest(itemId, requestKey);\n if (replay) return replay;\n throw error;\n }\n await this.point('inline:prepared');\n return this.tx((db) =>\n this.appendAnalysis(\n db,\n itemId,\n configuration,\n requestKey,\n sourceAttemptId,\n ),\n );\n }\n private async analysisByRequest(\n itemId: string,\n requestKey: string,\n ): Promise<{ id: string; revision: number } | null> {\n const found = (\n await this.rows(this.db, 'intake_analyses', 'item_id=?', [itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n return found\n ? { id: String(found.id), revision: Number(found.revision) }\n : null;\n }\n /** Owner-lifecycle hook: expire every active receipt bound to a deleted owner\n * through the ordinary revoke-then-delete path. Returns the number scheduled. */\n async expireOwned(owner: IntakeOwner): Promise<number> {\n const key = ownerKey(owner);\n const items = await this.rows(\n this.db,\n 'intake_items',\n \"owner_key=? AND visibility='active'\",\n [key],\n );\n try {\n for (const item of items) await this.scheduleExpiry(String(item.id));\n } catch (error) {\n try {\n await this.repairDeletions();\n } catch {\n // Durable intents remain available to the next authorized repair.\n }\n throw error;\n }\n await this.repairDeletions();\n return items.length;\n }\n\n /** Record an authenticated split correction and queue fresh extraction, never copy model output. */\n async reviseLogicalSplit(\n input: LogicalSplitInput,\n ): Promise<{ id: string; revision: number }> {\n const frozen = structuredClone(input);\n nonempty(frozen.requestId);\n integer(frozen.expectedRevision);\n if (\n !Array.isArray(frozen.groups) ||\n !frozen.groups.length ||\n frozen.groups.length > 100 ||\n frozen.groups.some(\n (group) =>\n !Array.isArray(group) ||\n !group.length ||\n group.length > 1000 ||\n group.some((page) => !Number.isSafeInteger(page) || page < 1),\n )\n )\n throw new Error('Invalid logical split');\n const pages = frozen.groups.flat();\n if (pages.length > 1000 || new Set(pages).size !== pages.length)\n throw new Error('Invalid logical split');\n const requestKey = `split:${frozen.requestId}`;\n const correction = {\n ...frozen,\n actorId: this.scope.actorId,\n kind: 'logical_split',\n };\n const replay = await this.tx(async (db) => {\n await this.lock(db, frozen.itemId);\n await this.item(frozen.itemId, 'process', db);\n await this.assertUnresolved(db, frozen.itemId);\n const found = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n if (!found) return null;\n if (\n digest(object(object(found.data).configuration).humanCorrection) !==\n digest(correction)\n )\n throw new Error('Split request conflict');\n return { id: String(found.id), revision: Number(found.revision) };\n });\n if (replay) {\n // Idempotency acknowledges only an intent the current reviewer may still access.\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n undefined,\n true,\n );\n return replay;\n }\n await this.point('split:checked');\n let result: { id: string; revision: number } | undefined;\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n // Read the anchor without requiring it to be current: a concurrent\n // duplicate must reach the locked replay check below instead of failing\n // the read. Currency is enforced under the lock instead.\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n async (db, current) => {\n // Every guard read and the append run under the item lock in this one\n // transaction (the snapshot read above already took it; re-asserting it\n // keeps the invariant local to this step).\n await this.lock(db, frozen.itemId);\n await this.point('split:locked');\n const [found] = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).filter((row) => object(row.data).requestKey === requestKey);\n if (found) {\n // A duplicate that committed after our unlocked replay check.\n if (\n digest(object(object(found.data).configuration).humanCorrection) !==\n digest(correction)\n )\n throw new Error('Split request conflict');\n result = { id: String(found.id), revision: Number(found.revision) };\n return;\n }\n const item = await this.item(frozen.itemId, 'process', db);\n if (\n current.revision !== frozen.expectedRevision ||\n Number(item.analysis_revision) !== frozen.expectedRevision\n )\n throw new Error('Stale logical split');\n const pin = object(object(current.configuration.proposals).source);\n const source = await this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n String(pin.attemptId),\n false,\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key]) throw new Error('Split source changed');\n const extraction = source.result.output.results;\n if (!Array.isArray(extraction))\n throw new Error('Split source unavailable');\n const evidence = extraction.find(\n (value) => object(object(value).evidence).id === frozen.evidenceId,\n );\n if (!evidence) throw new Error('Split evidence unavailable');\n const observed = new Set<number>();\n for (const value of object(evidence).segments as unknown[]) {\n const location = object(object(value).location);\n if (location.kind === 'page') observed.add(Number(location.page));\n if (location.kind === 'pages') {\n const from = Number(location.startPage),\n to = Number(location.endPage);\n if (\n !Number.isSafeInteger(from) ||\n !Number.isSafeInteger(to) ||\n to - from > 1000\n )\n throw new Error('Invalid source range');\n for (let page = from; page <= to; page++) observed.add(page);\n }\n }\n if (\n !observed.size ||\n pages.length !== observed.size ||\n pages.some((page) => !observed.has(page))\n )\n throw new Error('Split must cover observed pages exactly');\n await this.point('split:guarded');\n // Re-extraction retains the supported immediate-predecessor interpretation pin.\n result = await this.appendAnalysis(\n db,\n frozen.itemId,\n { ...source.configuration, humanCorrection: correction },\n requestKey,\n );\n },\n true,\n );\n if (!result) throw new Error('Split unavailable');\n return result;\n }\n /**\n * Record an authenticated reviewer instruction as an immutable human correction\n * and queue a fresh extraction plus interpretation that carries it as trusted\n * guidance. The text steers the model only; it never changes the catalog,\n * candidates, schemas, permissions or automation eligibility.\n */\n async recordReviewerInstruction(input: ReviewerInstructionInput): Promise<{\n id: string;\n revision: number;\n instruction: ReviewerInstruction;\n }> {\n const frozen = structuredClone(input);\n nonempty(frozen.requestId);\n nonempty(frozen.attemptId);\n integer(frozen.expectedRevision);\n if (\n typeof frozen.text !== 'string' ||\n !frozen.text.trim() ||\n frozen.text.length > REVIEWER_INSTRUCTION_MAX_LENGTH\n )\n throw new ReviewerInstructionInvalidError();\n const requestKey = `instruction:${frozen.requestId}`;\n const intent = {\n kind: 'reviewer_instruction',\n itemId: frozen.itemId,\n attemptId: frozen.attemptId,\n expectedRevision: frozen.expectedRevision,\n requestId: frozen.requestId,\n actorId: this.scope.actorId,\n text: frozen.text,\n };\n const replayIntent = (record: Record<string, unknown>) => {\n const {\n id: _id,\n recordedAt: _recordedAt,\n supersedesId: _supersedesId,\n digest: _digest,\n ...rest\n } = record;\n return rest;\n };\n const replay = await this.tx(async (db) => {\n await this.lock(db, frozen.itemId);\n await this.item(frozen.itemId, 'process', db);\n const found = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n if (!found) return null;\n const record = object(\n object(object(found.data).configuration).reviewerInstruction,\n );\n if (digest(replayIntent(record)) !== digest(intent))\n throw new Error('Reviewer instruction request conflict');\n return {\n id: String(found.id),\n revision: Number(found.revision),\n instruction: reviewerInstructionView(record),\n };\n });\n if (replay) {\n // Idempotency acknowledges only an intent the current reviewer may still access.\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n undefined,\n true,\n );\n return replay;\n }\n await this.point('instruction:checked');\n let result:\n | { id: string; revision: number; instruction: ReviewerInstruction }\n | undefined;\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n // The anchor may be historical: after a failed reinterpretation the\n // reviewer retries against the latest completed generation.\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n async (db, current) => {\n // Every guard read, the history read for supersedesId and the append\n // run under the item lock in this one transaction (the snapshot read\n // above already took it; re-asserting it keeps the invariant local).\n await this.lock(db, frozen.itemId);\n await this.point('instruction:locked');\n const [found] = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).filter((row) => object(row.data).requestKey === requestKey);\n if (found) {\n // A duplicate (double-click) that committed after our unlocked\n // replay check: replay it rather than refusing.\n const record = object(\n object(object(found.data).configuration).reviewerInstruction,\n );\n if (digest(replayIntent(record)) !== digest(intent))\n throw new Error('Reviewer instruction request conflict');\n result = {\n id: String(found.id),\n revision: Number(found.revision),\n instruction: reviewerInstructionView(record),\n };\n return;\n }\n const item = await this.item(frozen.itemId, 'process', db);\n if (Number(item.analysis_revision) !== frozen.expectedRevision)\n throw new ReviewerInstructionStaleError();\n let carriedConfiguration: Record<string, unknown> | undefined;\n if (current.revision !== frozen.expectedRevision) {\n // The same predicate drives getReinterpretationState, so the review\n // UI and this guard always agree on \"in flight\".\n const later = await this.laterWork(db, item, current.revision);\n if (later.phase === 'in_flight' || later.phase === 'superseded')\n throw new ReviewerInstructionStaleError();\n carriedConfiguration = later.configuration;\n }\n const pin = object(object(current.configuration.proposals).source);\n const source = await this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n String(pin.attemptId),\n false,\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key])\n throw new Error('Instruction source changed');\n // Supersede the latest recorded instruction, even one whose\n // reinterpretation never completed; the ledger, not the anchor, is history.\n const [previous] = await this.recordedInstructions(db, frozen.itemId);\n const body = {\n ...intent,\n id: randomUUID(),\n recordedAt: date(this.now()),\n supersedesId: previous?.id ?? null,\n };\n const record = { ...body, digest: digest(body) };\n await this.point('instruction:guarded');\n // Re-extraction retains the supported immediate-predecessor interpretation pin\n // and any existing split correction; the instruction travels beside it.\n const appended = await this.appendAnalysis(\n db,\n frozen.itemId,\n {\n ...(carriedConfiguration ?? source.configuration),\n reviewerInstruction: record,\n },\n requestKey,\n );\n result = { ...appended, instruction: reviewerInstructionView(record) };\n },\n true,\n );\n if (!result) throw new Error('Reviewer instruction unavailable');\n return result;\n }\n /**\n * How the revisions after an anchor generation relate to it. Shared by the\n * retry guard and getReinterpretationState so they cannot disagree.\n * A completed extraction with no interpretation appended is in flight until\n * its attempt's completion plus the item's analysis lease duration\n * (`limits.leaseMs`, the same lease claimAnalysis grants); after that it is\n * treated as a reinterpretation that did not start.\n */\n private async laterWork(\n db: DatabaseInterface,\n item: Row,\n anchorRevision: number,\n ): Promise<{\n phase: 'none' | 'in_flight' | 'superseded' | 'failed';\n failure: IntakeFailure | 'not_started' | null;\n configuration: Record<string, unknown> | undefined;\n }> {\n const later = (\n await this.rows(db, 'intake_analyses', 'item_id=? AND revision>?', [\n String(item.id),\n anchorRevision,\n ])\n ).sort((a, b) => Number(b.revision) - Number(a.revision));\n const stage = (row: Row) => object(object(row.data).configuration).stage;\n // The newest later extraction's configuration is the item's current one:\n // corrections chain forward through it, and a host reprocess replaces it\n // (dropping corrections). A retry from an older anchor builds on it so it\n // neither reverts a reprocess nor drops or resurrects a split.\n const newestExtraction = later.find((row) => stage(row) !== 'interpret');\n const configuration = newestExtraction\n ? object(object(newestExtraction.data).configuration)\n : undefined;\n const [latest] = later;\n if (!latest) return { phase: 'none', failure: null, configuration };\n if (\n later.some(\n (row) =>\n ['completed', 'partial'].includes(String(row.state)) &&\n stage(row) === 'interpret',\n )\n )\n return { phase: 'superseded', failure: null, configuration };\n if (later.some((row) => ['queued', 'running'].includes(String(row.state))))\n return { phase: 'in_flight', failure: null, configuration };\n const [attempt] = latest.current_attempt_id\n ? await this.rows(db, 'intake_analysis_attempts', 'id=? AND item_id=?', [\n latest.current_attempt_id,\n String(item.id),\n ])\n : [];\n if (['completed', 'partial'].includes(String(latest.state))) {\n // Extraction done, interpretation not appended: between stages.\n const completedAt = attempt\n ? object(attempt.data).completedAt\n : undefined;\n const leaseMs = Number(object(object(item.data).limits).leaseMs);\n // Missing or malformed timing cannot hold retries forever: it counts as\n // already expired, which is safe because a late append is refused.\n const started =\n typeof completedAt === 'string'\n ? persistedDate(completedAt).getTime()\n : Number.NaN;\n const deadline =\n Number.isFinite(started) && Number.isFinite(leaseMs)\n ? started + leaseMs\n : Number.NEGATIVE_INFINITY;\n return this.now().getTime() <= deadline\n ? { phase: 'in_flight', failure: null, configuration }\n : { phase: 'failed', failure: 'not_started', configuration };\n }\n const safe = attempt?.safe_error ? String(attempt.safe_error) : '';\n return {\n phase: 'failed',\n failure: failures.has(safe) ? (safe as IntakeFailure) : null,\n configuration,\n };\n }\n /** Pollable reinterpretation state: current revision, safe failure and the retry anchor. */\n async getReinterpretationState(itemId: string): Promise<{\n revision: number;\n processingState: string;\n /** Safe category, or `not_started` when the interpretation was never appended in time. */\n failure: IntakeFailure | 'not_started' | null;\n /** True while work after the latest completed generation is in flight, including between stages. */\n reinterpreting: boolean;\n /** Latest completed generation attempt; absent when none has completed. */\n generationAttemptId: string | null;\n /**\n * Id of the instruction carried by the item's newest extraction (verified\n * by digest), or null. A host reprocess builds its own configuration and\n * cannot carry human corrections, so it drops the instruction exactly as\n * it drops a split.\n */\n instructionInEffect: string | null;\n }> {\n const item = await this.item(itemId, 'read');\n const analyses = (\n await this.rows(this.db, 'intake_analyses', 'item_id=?', [itemId])\n ).sort((a, b) => Number(b.revision) - Number(a.revision));\n const generation = analyses.find(\n (row) =>\n ['completed', 'partial'].includes(String(row.state)) &&\n row.current_attempt_id &&\n object(object(row.data).configuration).stage === 'interpret',\n );\n let failure: IntakeFailure | 'not_started' | null = null;\n let reinterpreting = false;\n if (generation) {\n const later = await this.laterWork(\n this.db,\n item,\n Number(generation.revision),\n );\n failure = later.failure;\n reinterpreting = later.phase === 'in_flight';\n } else {\n const latest = analyses[0];\n reinterpreting = ['queued', 'running'].includes(String(latest?.state));\n if (\n latest &&\n String(latest.state) === 'needs_attention' &&\n latest.current_attempt_id\n ) {\n const [attempt] = await this.rows(\n this.db,\n 'intake_analysis_attempts',\n 'id=? AND item_id=?',\n [latest.current_attempt_id, itemId],\n );\n if (attempt?.safe_error && failures.has(String(attempt.safe_error)))\n failure = String(attempt.safe_error) as IntakeFailure;\n }\n }\n const newestExtraction = analyses.find(\n (row) => object(object(row.data).configuration).stage !== 'interpret',\n );\n const carried = newestExtraction\n ? object(object(newestExtraction.data).configuration).reviewerInstruction\n : undefined;\n const instructionInEffect = carried\n ? reviewerInstructionView(carried).id\n : null;\n await this.item(itemId, 'read');\n return {\n revision: Number(item.analysis_revision),\n processingState: String(item.processing_state),\n failure,\n reinterpreting,\n instructionInEffect,\n generationAttemptId: generation\n ? String(generation.current_attempt_id)\n : null,\n };\n }\n /** Immutable instruction history, newest first. History is never deleted. */\n async listReviewerInstructions(\n itemId: string,\n ): Promise<ReviewerInstruction[]> {\n await this.item(itemId, 'read');\n const history = await this.recordedInstructions(this.db, itemId);\n await this.item(itemId, 'read');\n return history;\n }\n private async recordedInstructions(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<ReviewerInstruction[]> {\n const rows = await this.rows(db, 'intake_analyses', 'item_id=?', [itemId]);\n const seen = new Set<string>();\n const history: ReviewerInstruction[] = [];\n for (const row of rows.sort(\n (a, b) => Number(b.revision) - Number(a.revision),\n )) {\n const configuration = object(object(row.data).configuration);\n // Only the authenticated mint writes an extraction-stage record; interpret\n // copies are verified against it separately and never define history.\n if (\n configuration.stage === 'interpret' ||\n !configuration.reviewerInstruction\n )\n continue;\n const instruction = reviewerInstructionView(\n configuration.reviewerInstruction,\n );\n if (seen.has(instruction.id)) continue;\n seen.add(instruction.id);\n history.push(instruction);\n }\n return history;\n }\n /** Allocate a fenced attempt; active leases cannot be stolen before expiry. */\n async claimAnalysis(\n itemId: string,\n revision: number,\n workerId: string,\n ): Promise<AnalysisLease | null> {\n integer(revision);\n nonempty(workerId);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.cancelled ||\n item.receipt_state !== 'ready' ||\n Number(item.analysis_revision) !== revision ||\n // A resolved item is terminal; its provider is never called again.\n (await this.rows(db, 'intake_dispositions', 'item_id=?', [itemId]))\n .length\n )\n return null;\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, revision],\n );\n if (\n !analysis ||\n ['completed', 'partial'].includes(String(analysis.state))\n )\n return null;\n const limits = object(\n object(item.data).limits,\n ) as unknown as IntakeLimits;\n const attempts = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'analysis_id=?',\n [analysis.id],\n );\n const prior = attempts.find((a) => a.id === analysis.current_attempt_id);\n if (\n prior?.state === 'running' &&\n persistedDate(prior.lease_until) > this.now()\n )\n return null;\n if (Number(analysis.attempt_number) >= limits.maxAttempts) {\n if (prior?.state === 'running')\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='needs_attention',safe_error='limit' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n prior.id,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n analysis.id,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND analysis_revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n return null;\n }\n if (prior && ['running', 'queued'].includes(String(prior.state)))\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n prior.id,\n );\n const fence = Number(analysis.fence) + 1;\n const attempt = Number(analysis.attempt_number) + 1;\n const token = randomUUID();\n const [row] = await this.insert(db, 'intake_analysis_attempts', {\n item_id: itemId,\n analysis_id: analysis.id,\n attempt_number: attempt,\n fence,\n state: 'running',\n lease_token: token,\n lease_until: new Date(\n this.now().getTime() + limits.leaseMs,\n ).toISOString(),\n output_digest: '',\n safe_error: '',\n confidence: null,\n data: canonical({\n workerId,\n startedAt: this.now().toISOString(),\n limits,\n }),\n });\n await db.query(\n \"UPDATE intake_analyses SET fence=?,attempt_number=?,current_attempt_id=?,state='running' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n fence,\n attempt,\n row.id,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n analysis.id,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='running' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n return {\n itemId,\n analysisId: String(analysis.id),\n attemptId: String(row.id),\n revision,\n fence,\n token,\n };\n });\n }\n private async completedAnalysisSnapshot(\n db: DatabaseInterface,\n itemId: string,\n attemptId: string | undefined,\n current: boolean,\n ): Promise<CompletedAnalysisSnapshot> {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (item.cancelled) throw new Error('Analysis unavailable');\n if (attemptId === undefined) {\n if (!current) throw new Error('Historical attempt required');\n const [latest] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, item.analysis_revision],\n );\n if (!latest?.current_attempt_id) throw new Error('Analysis unavailable');\n attemptId = String(latest.current_attempt_id);\n }\n\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'item_id=? AND id=?',\n [itemId, attemptId],\n );\n if (\n !attempt ||\n !['completed', 'partial'].includes(String(attempt.state)) ||\n !attempt.output_digest\n )\n throw new Error('Analysis unavailable');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND id=?',\n [itemId, attempt.analysis_id],\n );\n if (\n !analysis ||\n analysis.current_attempt_id !== attemptId ||\n (current && Number(item.analysis_revision) !== Number(analysis.revision))\n )\n throw new Error('Analysis unavailable');\n const data = object(analysis.data);\n const configuration = object(data.configuration);\n if (\n !Array.isArray(data.inputs) ||\n !data.inputs.length ||\n digest({ inputs: data.inputs, configuration }) !==\n analysis.input_digest ||\n digest(configuration) !== data.configDigest\n )\n throw new Error('Analysis input integrity');\n const resultData = object(attempt.data);\n const result = {\n status: resultData.status,\n provider: resultData.provider,\n model: resultData.model,\n version: resultData.version,\n output: resultData.output,\n usage: resultData.usage,\n ...(Object.hasOwn(resultData, 'error')\n ? { error: resultData.error }\n : {}),\n ...(Object.hasOwn(resultData, 'confidence')\n ? { confidence: resultData.confidence }\n : {}),\n } as AnalysisOutput;\n if (\n result.status !== attempt.state ||\n digest(result) !== attempt.output_digest\n )\n throw new Error('Analysis output integrity');\n const evidence: IntakeEvidenceDTO[] = [];\n for (const input of data.inputs) {\n const frozen = object(input);\n const [row] = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [itemId, frozen.id],\n );\n if (!row || row.content_hash !== frozen.hash)\n throw new Error('Analysis input integrity');\n evidence.push({\n id: String(row.id),\n partId: String(row.part_id),\n parentEvidenceId: row.parent_evidence_id\n ? String(row.parent_evidence_id)\n : null,\n mediaType: String(row.media_type),\n contentHash: String(row.content_hash),\n byteLength: Number(row.byte_length),\n });\n }\n if (new Set(evidence.map((entry) => entry.id)).size !== evidence.length)\n throw new Error('Analysis input integrity');\n await this.item(itemId, 'process', db);\n return structuredClone({\n itemId,\n attemptId,\n revision: Number(analysis.revision),\n inputDigest: String(analysis.input_digest),\n outputDigest: String(attempt.output_digest),\n evidenceDigest: digest(data.inputs),\n configuration,\n evidence,\n result,\n });\n }\n /** Detached successful current revision; always current-scope/process authorized. */\n async getCompletedAnalysis(\n itemId: string,\n attemptId?: string,\n ): Promise<CompletedAnalysisSnapshot> {\n const snapshot = await this.tx((db) =>\n this.completedAnalysisSnapshot(db, itemId, attemptId, true),\n );\n await this.point('analysis:snapshot-read');\n const read = async (db: DatabaseInterface) => {\n const current = await this.completedAnalysisSnapshot(\n db,\n itemId,\n snapshot.attemptId,\n true,\n );\n if (\n current.inputDigest !== snapshot.inputDigest ||\n current.outputDigest !== snapshot.outputDigest\n )\n throw new Error('Analysis changed');\n return current;\n };\n if (snapshot.configuration.stage === 'interpret')\n return (await this.proposalReader())[generationSnapshotRead](\n itemId,\n (work) => this.tx(work),\n read,\n );\n return this.tx(read);\n }\n /** Historical source is readable only through its frozen pin on a live generation lease. */\n async getGenerationInput(lease: AnalysisLease) {\n const generation = await this.getAnalysisInput(lease);\n const configuration = generation.configuration;\n const pin = object(object(configuration.proposals).source);\n if (\n configuration.stage !== 'interpret' ||\n typeof pin.attemptId !== 'string'\n )\n throw new Error('Invalid generation source');\n const source = await this.tx((db) =>\n this.completedAnalysisSnapshot(\n db,\n lease.itemId,\n String(pin.attemptId),\n false,\n ),\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key])\n throw new Error('Generation source changed');\n if (\n source.result.provider !== 'smrt-ingestion-extraction' ||\n source.configuration.stage === 'interpret' ||\n source.revision !== generation.revision - 1 ||\n digest(configuration.humanCorrection ?? null) !==\n digest(source.configuration.humanCorrection ?? null) ||\n digest(configuration.reviewerInstruction ?? null) !==\n digest(source.configuration.reviewerInstruction ?? null) ||\n digest(\n generation.evidence.map((entry) => ({\n id: entry.id,\n hash: entry.contentHash,\n })),\n ) !== source.evidenceDigest\n )\n throw new Error('Generation evidence changed');\n await this.getAnalysisInput(lease);\n return { generation, source };\n }\n /** Reload immutable inputs only through the current live processing lease. */\n async getAnalysisInput(lease: AnalysisLease): Promise<{\n revision: number;\n attemptId: string;\n fence: number;\n inputDigest: string;\n maxOutputBytes: number;\n configuration: Record<string, unknown>;\n evidence: IntakeEvidenceDTO[];\n }> {\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n throw new Error('Analysis lease unavailable');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=? AND item_id=?',\n [lease.attemptId, lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n !attempt ||\n Number(analysis.revision) !== lease.revision ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence ||\n Number(attempt.fence) !== lease.fence ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n throw new Error('Analysis lease unavailable');\n const data = object(analysis.data);\n const configuration = object(data.configuration);\n if (\n !Array.isArray(data.inputs) ||\n !data.inputs.length ||\n digest({ inputs: data.inputs, configuration }) !==\n analysis.input_digest ||\n digest(configuration) !== data.configDigest\n )\n throw new Error('Analysis input integrity');\n const evidence: IntakeEvidenceDTO[] = [];\n for (const input of data.inputs) {\n const frozen = object(input);\n const [row] = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [lease.itemId, frozen.id],\n );\n if (!row || row.content_hash !== frozen.hash)\n throw new Error('Analysis input integrity');\n evidence.push({\n id: String(row.id),\n partId: String(row.part_id),\n parentEvidenceId: row.parent_evidence_id\n ? String(row.parent_evidence_id)\n : null,\n mediaType: String(row.media_type),\n contentHash: String(row.content_hash),\n byteLength: Number(row.byte_length),\n });\n }\n if (new Set(evidence.map((entry) => entry.id)).size !== evidence.length)\n throw new Error('Analysis input integrity');\n return {\n revision: lease.revision,\n attemptId: lease.attemptId,\n fence: lease.fence,\n inputDigest: String(analysis.input_digest),\n maxOutputBytes: Number(object(object(item.data).limits).maxOutputBytes),\n configuration,\n evidence,\n };\n });\n }\n /** Publish once, only through the current unexpired fence and captured scope. */\n async completeAnalysis(\n lease: AnalysisLease,\n output: AnalysisOutput,\n ): Promise<boolean> {\n if (\n !['completed', 'partial', 'failed', 'needs_attention'].includes(\n output.status,\n ) ||\n !output.provider ||\n !output.model ||\n !output.version ||\n (output.error && !failures.has(output.error))\n )\n throw new Error('Invalid analysis output');\n if (\n output.confidence !== undefined &&\n (!Number.isFinite(output.confidence) ||\n output.confidence < 0 ||\n output.confidence > 1)\n )\n throw new Error('Invalid confidence');\n for (const value of Object.values(output.usage))\n if (!Number.isFinite(value) || value < 0)\n throw new Error('Invalid usage');\n const serialized = canonical(output);\n const outputDigest = digest(output);\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n return false;\n const limits = object(\n object(item.data).limits,\n ) as unknown as IntakeLimits;\n if (Buffer.byteLength(serialized) > limits.maxOutputBytes)\n throw new Error('Analysis output budget exceeded');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence\n )\n return false;\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=?',\n [lease.attemptId, lease.analysisId],\n );\n if (\n !attempt ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n return false;\n const attemptData = {\n ...object(attempt.data),\n ...output,\n completedAt: this.now().toISOString(),\n };\n await db.query(\n 'UPDATE intake_analysis_attempts SET state=?,output_digest=?,safe_error=?,confidence=?,data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n outputDigest,\n output.error ?? '',\n output.confidence ?? null,\n canonical(attemptData),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.attemptId,\n );\n await db.query(\n 'UPDATE intake_analyses SET state=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.analysisId,\n );\n await db.query(\n 'UPDATE intake_items SET processing_state=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n );\n if (['completed', 'partial', 'needs_attention'].includes(output.status))\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n lease.revision,\n );\n return true;\n });\n }\n /** Terminal failure accounting without a provider payload. The fixed safe error\n * and lifecycle metadata are not charged to the provider-output byte ceiling. */\n async failAnalysis(\n lease: AnalysisLease,\n category: IntakeFailure,\n ): Promise<boolean> {\n if (!failures.has(category)) throw new Error('Invalid analysis failure');\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n return false;\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=? AND item_id=?',\n [lease.attemptId, lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n !attempt ||\n Number(analysis.revision) !== lease.revision ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence ||\n Number(attempt.fence) !== lease.fence ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n return false;\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='needs_attention',safe_error=?,data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n category,\n canonical({\n ...object(attempt.data),\n completedAt: this.now().toISOString(),\n }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.attemptId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.analysisId,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n lease.revision,\n );\n return true;\n });\n }\n /** Cancel pending processing immediately; original receipt remains ready. */\n async cancel(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n await db.query(\n \"UPDATE intake_items SET cancelled=?,processing_state='cancelled' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n true,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded',safe_error='cancelled' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n });\n }\n /** Mint an action only on an explicit host intention, never during reanalysis. */\n async createAction(\n itemId: string,\n actionKey: string,\n provenance: Record<string, unknown>,\n ): Promise<string> {\n nonempty(actionKey);\n // Reviewer-selected actions are minted only by `startReviewerAction` under\n // reviewer authority; process authority must not forge routing provenance.\n if (\n actionKey.startsWith('reviewer:') ||\n (provenance as { origin?: unknown }).origin === 'reviewer-selected'\n )\n throw new Error('Reserved action provenance');\n const payload = canonical(provenance);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (item.cancelled) throw new Error('Intake cancelled');\n await this.assertUnresolved(db, itemId);\n const [existing] = await this.rows(\n db,\n 'intake_actions',\n 'item_id=? AND action_key=?',\n [itemId, actionKey],\n );\n if (existing) {\n if (canonical(object(existing.data)) !== payload)\n throw new Error('Action identity conflict');\n return String(existing.id);\n }\n const [action] = await this.insert(db, 'intake_actions', {\n item_id: itemId,\n action_key: actionKey,\n state: 'proposed',\n proposal_revision: 0,\n review_version: 0,\n execution_attempt: 0,\n fence: 0,\n result_digest: '',\n data: payload,\n });\n return String(action.id);\n });\n }\n /** Append a proposal pinned to a completed attempt. Policy/preview is host-owned. */\n async publishProposal(input: {\n itemId: string;\n actionId: string;\n attemptId: string;\n expectedRevision: number;\n binding: Record<string, unknown>;\n }): Promise<{ id: string; revision: number; bindingHash: string }> {\n canonical(input.binding);\n return this.tx(async (db) => {\n await this.lock(db, input.itemId);\n const item = await this.item(input.itemId, 'process', db);\n if (item.cancelled) throw new Error('Intake cancelled');\n await this.assertUnresolved(db, input.itemId);\n const [action] = await this.rows(\n db,\n 'intake_actions',\n 'item_id=? AND id=?',\n [input.itemId, input.actionId],\n );\n // A reviewer-selected action is revised only through the reviewer path\n // (`previewProposal`/`submitDecision`); process authority cannot rewrite it.\n if (action && object(action.data).origin === 'reviewer-selected')\n throw new Error('Reviewer-selected action requires review');\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'item_id=? AND id=?',\n [input.itemId, input.attemptId],\n );\n if (\n !action ||\n !attempt ||\n !['completed', 'partial'].includes(String(attempt.state)) ||\n !attempt.output_digest\n )\n throw new Error('Invalid proposal evidence');\n if (\n Number(action.proposal_revision) !== input.expectedRevision ||\n ['succeeded', 'executing', 'outcome_unknown'].includes(\n String(action.state),\n )\n )\n throw new Error('Proposal conflict');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [attempt.analysis_id, input.itemId],\n );\n if (\n !analysis ||\n Number(analysis.revision) !== Number(item.analysis_revision)\n )\n throw new Error('Proposal conflict');\n const bindingHash = digest({\n binding: input.binding,\n attemptId: attempt.id,\n attemptDigest: attempt.output_digest,\n inputDigest: analysis.input_digest,\n });\n const revision = input.expectedRevision + 1;\n const [proposal] = await this.insert(db, 'intake_proposals', {\n item_id: input.itemId,\n action_id: input.actionId,\n analysis_id: attempt.analysis_id,\n analysis_attempt_id: attempt.id,\n revision,\n binding_hash: bindingHash,\n data: canonical({\n binding: input.binding,\n attemptDigest: attempt.output_digest,\n }),\n });\n await db.query(\n \"UPDATE intake_actions SET proposal_revision=?,state='waiting_review',review_version=review_version+1 WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n revision,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n input.actionId,\n );\n return { id: String(proposal.id), revision, bindingHash };\n });\n }\n /** Persist frozen plan structure; no expansion or apply authority is implied. */\n async appendPlan(\n itemId: string,\n planKey: string,\n revision: number,\n steps: Array<{ actionId: string; proposalRevision: number }>,\n definition: Record<string, unknown>,\n ): Promise<string> {\n nonempty(planKey);\n integer(revision);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n if (\n !steps.length ||\n new Set(steps.map((s) => s.actionId)).size !== steps.length\n )\n throw new Error('Invalid plan');\n for (const step of steps) {\n const [proposal] = await this.rows(\n db,\n 'intake_proposals',\n 'item_id=? AND action_id=? AND revision=?',\n [itemId, step.actionId, step.proposalRevision],\n );\n if (!proposal) throw new Error('Invalid plan binding');\n }\n const data = canonical({ steps, definition });\n const hash = digest({ steps, definition });\n const previous = await this.rows(\n db,\n 'intake_plans',\n 'item_id=? AND plan_key=?',\n [itemId, planKey],\n );\n const replay = previous.find((p) => Number(p.revision) === revision);\n if (replay) {\n if (replay.digest !== hash) throw new Error('Plan conflict');\n return String(replay.id);\n }\n if (\n revision !==\n Math.max(0, ...previous.map((p) => Number(p.revision))) + 1\n )\n throw new Error('Plan revision conflict');\n const [plan] = await this.insert(db, 'intake_plans', {\n item_id: itemId,\n plan_key: planKey,\n revision,\n digest: hash,\n data,\n });\n return String(plan.id);\n });\n }\n /** Revoke immediately and durably schedule deletion before external I/O. */\n async expire(itemId: string): Promise<void> {\n await this.scheduleExpiry(itemId);\n await this.repairDeletions();\n }\n private async scheduleExpiry(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'delete', db, true);\n await db.query(\n \"UPDATE intake_items SET visibility='expired',processing_state='expired',cancelled=?,lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n true,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_evidence SET state='revoked' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n const originals = await this.rows(db, 'intake_evidence', 'item_id=?', [\n itemId,\n ]);\n const cleanup = originals\n .filter((e) => e.asset_id && e.source_uri)\n .map((e) => ({ assetId: e.asset_id, sourceUri: e.source_uri }));\n await this.insert(\n db,\n 'intake_deletions',\n { item_id: itemId, state: 'pending', data: canonical({ cleanup }) },\n 'tenant_id,item_id',\n );\n });\n }\n /** Retry privacy propagation. Minimal receipt/action identities remain replay-safe. */\n async repairDeletions(): Promise<number> {\n let completed = 0;\n const pending = await this.rows(this.db, 'intake_deletions');\n for (const intent of pending) {\n const itemId = String(intent.item_id);\n await this.item(itemId, 'delete', this.db, true);\n const evidence = await this.rows(\n this.db,\n 'intake_evidence',\n 'item_id=?',\n [itemId],\n );\n for (const row of evidence) {\n if (!row.asset_id) continue;\n const asset = await withTenant({ tenantId: this.scope.tenantId }, () =>\n this.options.assets.collection.get({ id: String(row.asset_id) }),\n );\n if (asset) {\n if (asset.tenantId !== this.scope.tenantId)\n throw new Error('Asset unavailable');\n await this.options.assets.store.remove(asset);\n }\n }\n // Retain cleanup locators after revocation: a killed stale writer may finish\n // storage I/O after owner deletion. Repeated sweeps remove those bytes too.\n const cleanup = object(intent.data).cleanup;\n if (Array.isArray(cleanup))\n for (const entry of cleanup) {\n const locator = object(entry);\n const asset = new Asset({ db: this.db });\n asset.id = String(locator.assetId);\n asset.tenantId = this.scope.tenantId;\n asset.sourceUri = String(locator.sourceUri);\n // Remove the object directly through the public store, even when its\n // database record has already been pruned.\n await this.options.assets.store.removeFile(asset);\n }\n if (intent.state === 'completed') {\n await this.releaseRedactedPrincipal(itemId);\n continue;\n }\n await this.options.purgeDerived({\n tenantId: this.scope.tenantId,\n itemId,\n });\n await this.point('deleted');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'delete', db, true);\n for (const table of TABLES.filter(\n (t) => t !== 'intake_items' && t !== 'intake_deletions',\n ))\n await db.query(\n `UPDATE ${table} SET data='{}' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_evidence SET source_uri='',content_hash='',media_type='',byte_length=0 WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n // The owner and submitter links are payload provenance, not replay\n // identity: deletion severs them together with every other payload.\n // Digests over actor, owner, text or arguments would let a deleted\n // receipt be linked to its sender or a guessed text be confirmed.\n // Replay after redaction is already refused, so none are needed.\n for (const [table, column] of REDACTED_DIGESTS)\n await db.query(\n `UPDATE ${table} SET ${column}=? WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?`,\n REDACTED,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_items SET data=?,trace_id='',submitter_id='',owner_key='',payload_digest=?,scope_digest=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n // The ceiling stays for later delete sweeps' host authorization;\n // execution.principalId stays only while an external action may\n // still be reconciled under it, and is released once it finishes.\n canonical({\n capturedCeiling: redactedCeiling(\n object(object(item.data).capturedCeiling ?? {}),\n await this.hasUnfinishedActions(db, itemId),\n ),\n }),\n REDACTED,\n REDACTED,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_deletions SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n });\n completed++;\n }\n return completed;\n }\n private async hasUnfinishedActions(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<boolean> {\n return (\n (\n await this.rows(\n db,\n 'intake_actions',\n `item_id=? AND state IN (${UNFINISHED_ACTION_STATES.map(() => '?').join(',')})`,\n [itemId, ...UNFINISHED_ACTION_STATES],\n )\n ).length > 0\n );\n }\n /** Later sweeps drop a principal retained for a reconciliation that has\n * since reached a final state. */\n private async releaseRedactedPrincipal(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const [item] = await this.rows(db, 'intake_items', 'id=?', [itemId]);\n if (!item || item.visibility === 'active') return;\n if (await this.hasUnfinishedActions(db, itemId)) return;\n const data = object(item.data);\n const ceiling = object(data.capturedCeiling ?? {});\n const released = redactedCeiling(ceiling, false);\n if (canonical(released) === canonical(ceiling)) return;\n await db.query(\n 'UPDATE intake_items SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...data, capturedCeiling: released }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n });\n }\n /** Run host-configured expiry policy and retry interrupted deletion propagation. */\n async sweepRetention(): Promise<number> {\n const expired = await this.rows(\n this.db,\n 'intake_items',\n \"visibility='active' AND expires_at<=?\",\n [this.now().toISOString()],\n );\n try {\n for (const item of expired) await this.scheduleExpiry(String(item.id));\n } catch (error) {\n // A later denial must not strand already committed deletion intents.\n // Preserve the scheduling failure even if cleanup also needs a retry.\n try {\n await this.repairDeletions();\n } catch {\n // Durable intents remain available to the next authorized repair.\n }\n throw error;\n }\n await this.repairDeletions();\n return expired.length;\n }\n}\n\nexport * from './extraction.js';\nexport type * from './feedback-contracts.js';\nexport {\n GenerationSnapshotStaleError,\n GenerationSourceStaleError,\n HandlerArgumentsInvalidError,\n ProposalsNotConfiguredError,\n} from './proposal-errors.js';\nexport {\n createIntakeReviewHost,\n type IntakeReviewHostOptions,\n type RowEvidenceRequest,\n type RowEvidenceView,\n} from './review-host.js';\nexport {\n REVIEWER_INSTRUCTION_MAX_LENGTH,\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n reviewerInstructionView,\n} from './reviewer-instruction.js';\nexport * from './sources/index.js';\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAM,SACJ;AACF,IAAM,mBAAmB,IAAI,OAAO,QAAQ,GAAG;AAC/C,IAAM,oBAAoB,IAAI,OAAO,QAAQ,IAAI;AAM1C,SAAS,mBAAmB,OAAiC;CAClE,OACE,OAAO,UAAU,YACjB,MAAM,KAAK,CAAA,CAAE,SAAS,KACtB,MAAM,UAAA,OACN,CAAC,iBAAiB,KAAK,KAAK;AAEhC;AAOO,SAAS,kBAAkB,OAAoC;CACpE,IAAI,OAAO,UAAU,UAAU,OAAO,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,MAAM,KAAK,gBAAgB;EAC3B,OAAO,QAAQ;CACjB;AACF"}
|
|
1
|
+
{"version":3,"file":"server.js","names":["handler","bytes","value","item","asset","job","position","filename","record"],"sources":["../src/presented-filename.ts","../src/review-analysis.ts","../src/review-instruction-view.ts","../src/review-summary.ts","../src/review-host.ts","../src/sources/common.ts","../src/sources/email.ts","../src/sources/http.ts","../src/sources/watch-folder.ts","../src/server.ts"],"sourcesContent":["/**\n * Source-presented file names (#4214): untrusted text kept for labels only,\n * never identity. One definition shared by the receipt service's strict check\n * and the sources' cleaner (`deliver`), so neither can store a name the other\n * would refuse.\n *\n * Unsafe characters, all removed, are defined by Unicode properties rather\n * than a hand-kept list:\n * - `Cc` control characters (C0, C1, DEL);\n * - `Cf` format characters (bidi embeddings, overrides, isolates and marks,\n * zero-width characters, the BOM, soft hyphen, tag characters, interlinear\n * annotation marks, ...);\n * - `Cs` lone surrogate halves (invalid text; real pairs such as emoji are\n * kept, since the `u` flag matches whole code points);\n * - `Zl`/`Zp` line and paragraph separators (U+2028, U+2029);\n * - `Default_Ignorable_Code_Point` (U+034F, Hangul fillers, variation\n * selectors, U+180E, U+2060-U+206F, ...): characters that render as\n * nothing. Consequences, all display-only (nothing uses the name as\n * identity): emoji ZWJ sequences and emoji presentation selectors are\n * flattened (a family emoji shows as its members); ZWNJ/ZWJ (U+200C,\n * U+200D) are removed from Persian and Indic text, which can change how\n * letters join; and ideographic variation selectors are removed, so a CJK\n * glyph variant shows its base form.\n *\n * Bidi controls let `invoice` + U+202E + `fdp.exe` display as\n * `invoiceexe.pdf`; invisible characters make two different names look\n * identical. Out of scope: Unicode normalization (NFC/NFKC) and confusable\n * look-alike characters; the name stays untrusted display text.\n */\nconst UNSAFE =\n '[\\\\p{Cc}\\\\p{Cf}\\\\p{Cs}\\\\p{Zl}\\\\p{Zp}\\\\p{Default_Ignorable_Code_Point}]';\nconst UNSAFE_CHARACTER = new RegExp(UNSAFE, 'u');\nconst UNSAFE_CHARACTERS = new RegExp(UNSAFE, 'gu');\n\n/** The receipt service's bound on a stored filename, in UTF-16 code units. */\nexport const MAX_FILENAME_LENGTH = 512;\n\n/** Whether a filename may be stored as-is (no unsafe characters, bounded). */\nexport function isStorableFilename(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.trim().length > 0 &&\n value.length <= MAX_FILENAME_LENGTH &&\n !UNSAFE_CHARACTER.test(value)\n );\n}\n\n/**\n * Clean a source-presented name: unsafe characters removed and the result\n * trimmed; a name that is then empty or over the bound is dropped, so an odd\n * name falls back to the default label instead of failing the whole receipt.\n */\nexport function presentedFilename(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const name = value.replace(UNSAFE_CHARACTERS, '').trim();\n return isStorableFilename(name) ? name : undefined;\n}\n","import type { IntakeItemDTO } from './dto.js';\nimport type { CompletedAnalysisSnapshot } from './proposal-dto.js';\nimport { GenerationSnapshotStaleError } from './proposal-errors.js';\nimport type { ReviewPage } from './review-dto.js';\nimport type { IngestionService } from './server.js';\n/** Optional generation availability never substitutes for current saved-review authority. */\nexport async function loadReviewAnalysis(\n service: IngestionService,\n item: IntakeItemDTO,\n reviews: ReviewPage,\n cursor?: string,\n): Promise<{ reviews: ReviewPage; analysis?: CompletedAnalysisSnapshot }> {\n if (\n !['completed', 'partial'].includes(item.processingState) ||\n reviews.generationStale\n )\n return { reviews };\n try {\n return { reviews, analysis: await service.getCompletedAnalysis(item.id) };\n } catch (error) {\n if (!(error instanceof GenerationSnapshotStaleError)) throw error;\n // The old page is not a fallback: authority may have changed during snapshot reads.\n return { reviews: await service.listReviews(item.id, { cursor }) };\n }\n}\n","/** Server-side projection of an item's reviewer-instruction state for review hosts. */\nimport type { CompletedAnalysisSnapshot } from './proposal-dto.js';\nimport type { ReviewerInstructionView } from './review-dto.js';\nimport { reviewerInstructionView } from './reviewer-instruction.js';\nimport type { IngestionService } from './server.js';\n\n/**\n * Project `ItemReviewView.instruction`. History and reinterpretation state are\n * separate reads, so an instruction recorded between them would otherwise look\n * like a dropped one: when the in-effect id names a different instruction the\n * history is re-read, and `dropped` is set only when nothing is in effect.\n */\nexport async function loadInstructionView(\n service: Pick<\n IngestionService,\n 'listReviewerInstructions' | 'getReinterpretationState'\n >,\n itemId: string,\n analysis: CompletedAnalysisSnapshot | undefined,\n): Promise<ReviewerInstructionView | undefined> {\n let [latest] = await service.listReviewerInstructions(itemId);\n // Only a generation \"applies\" an instruction; a completed extraction\n // carries the same record but has produced no suggestions yet.\n const applied =\n analysis?.configuration.stage === 'interpret' &&\n analysis.configuration.reviewerInstruction\n ? reviewerInstructionView(analysis.configuration.reviewerInstruction)\n : null;\n if (!latest && !applied) return undefined;\n const state = await service.getReinterpretationState(itemId);\n if (\n state.instructionInEffect !== null &&\n state.instructionInEffect !== latest?.id\n )\n // An instruction was recorded between the two reads: re-read history.\n [latest] = await service.listReviewerInstructions(itemId);\n const current =\n latest && latest.id === state.instructionInEffect ? latest : null;\n return {\n current,\n applied,\n stale: !!analysis && !!current && current.id !== applied?.id,\n // Dropped means no instruction is in effect (a host reprocess), never\n // \"superseded by a newer instruction\".\n ...(latest && state.instructionInEffect === null\n ? { dropped: latest }\n : {}),\n ...(state.failure ? { failure: state.failure } : {}),\n ...(state.reinterpreting ? { reinterpreting: true } : {}),\n // Without a displayable generation the reviewer can still retry or change\n // the instruction against the latest completed generation.\n ...(analysis?.configuration.stage !== 'interpret' &&\n state.generationAttemptId\n ? {\n binding: {\n attemptId: state.generationAttemptId,\n expectedRevision: state.revision,\n },\n }\n : {}),\n };\n}\n","import type { IntakeItemDTO } from './dto.js';\nimport type { InboxState, ReviewPage } from './review-dto.js';\nimport type { IngestionService } from './server.js';\n\n/** Whole-item state requires each page's live handler, parent and target gates. */\nexport async function loadReviewSummary(\n service: IngestionService,\n item: IntakeItemDTO,\n requestedCursor?: string,\n): Promise<{ reviews: ReviewPage; state: InboxState }> {\n let requested: ReviewPage | undefined;\n if (requestedCursor !== undefined)\n requested = await service.listReviews(item.id, { cursor: requestedCursor });\n let cursor: string | undefined;\n let total = 0,\n succeeded = 0,\n deferred = 0,\n failed = 0;\n const cursors = new Set<string>();\n do {\n const page = await service.listReviews(item.id, { cursor });\n if (requestedCursor === undefined && cursor === undefined) requested = page;\n for (const action of page.actions) {\n total++;\n if (action.review.state === 'succeeded') succeeded++;\n if (action.review.state === 'deferred') deferred++;\n if (['failed', 'outcome_unknown'].includes(action.review.state)) failed++;\n }\n cursor = page.nextCursor;\n if (cursor && cursors.has(cursor))\n throw new Error('Repeated review cursor');\n if (cursor) cursors.add(cursor);\n // Other pages are discarded; only scalar state and the requested page survive.\n } while (cursor);\n const current = await service.getItem(item.id);\n if (!requested) throw new Error('Review page unavailable');\n // Terminal no-action disposition wins; otherwise new processing supersedes old actions.\n const state: InboxState =\n current.disposition && !succeeded\n ? 'resolved'\n : ['queued', 'running'].includes(current.processingState)\n ? 'processing'\n : total\n ? succeeded === total\n ? 'completed'\n : succeeded\n ? 'partially_completed'\n : deferred\n ? 'deferred'\n : failed\n ? 'failed'\n : 'waiting'\n : current.processingState === 'needs_attention'\n ? 'failed'\n : 'unresolved';\n return { reviews: requested, state };\n}\n","/** Server-side implementation of the transport-neutral review callback contract. */\nimport type { IntakeEvidenceDTO, IntakeItemDTO } from './dto.js';\nimport type { GenerationAnalysisOutput } from './proposal-dto.js';\nimport { loadReviewAnalysis } from './review-analysis.js';\nimport type {\n Assignment,\n EvidenceView,\n InboxEntry,\n InboxEvidence,\n IntakeReviewHost,\n ItemReviewView,\n} from './review-dto.js';\nimport { loadInstructionView } from './review-instruction-view.js';\nimport { loadReviewSummary } from './review-summary.js';\nimport {\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n} from './reviewer-instruction.js';\nimport {\n type IngestionService,\n IntakeScanLimitError,\n ITEM_ID_FILTER_CEILING,\n ITEM_PAGE_CEILING,\n ITEM_SCAN_CEILING,\n isIntakeId,\n} from './server.js';\n\n/** One listed row's primary original, as passed to `rowEvidence`. */\nexport interface RowEvidenceRequest {\n itemId: string;\n evidence: IntakeEvidenceDTO;\n}\n/** A host's preview for one row: label and same-origin URLs, never text. */\nexport type RowEvidenceView = Omit<InboxEvidence, 'evidence'>;\n\n/** Trusted application adapters, bound to the same authenticated session as service. */\nexport interface IntakeReviewHostOptions {\n /** Authenticate receipt, enforce upload limits, and request the first extraction. */\n upload: IntakeReviewHost['upload'];\n /** Read durable assignment state; assignment never grants ingestion permissions. */\n assignment(itemId: string): Promise<Assignment>;\n /**\n * Optional batched assignment read for one inbox page. Missing ids are\n * unassigned at version 0. Without it, `list` calls `assignment` per row.\n */\n assignments?(itemIds: string[]): Promise<Map<string, Assignment>>;\n /**\n * Optional assignee pushdown: the item ids currently assigned to `assigneeId`.\n * `list` restricts the page query to them, so a filtered page is cut in one\n * query. Without it (or beyond ITEM_ID_FILTER_CEILING ids) `list` scans pages\n * and filters by `assignment`, which is still honest but costs more rows.\n */\n assignedItemIds?(assigneeId: string): Promise<string[]>;\n /** Authorize manager/assignee and enforce durable CAS plus request-id replay checks. */\n assign: IntakeReviewHost['assign'];\n /** Produce safe text or an authenticated same-origin URL; never storage keys. */\n evidence(\n evidence: IntakeEvidenceDTO,\n ): Promise<Omit<EvidenceView, 'evidence'>>;\n /**\n * Optional, opt-in row previews for the inbox (#4213). Called at most once\n * per `list` page with each listed row's primary durable part (metadata\n * only, read in one batched query); return item id -> `{ label, viewUrl?,\n * thumbnailUrl? }` built from metadata, without reading bytes. Rows missing\n * from the map get no preview. When omitted, rows show no original link and\n * `list` calls no review-host adapter (`evidence`/`rowEvidence`); it still\n * reads the page's evidence metadata once for filename labels (#4214), for\n * which the host's `authorize` runs once per distinct captured ceiling, and\n * lists with item-only labels if that read fails. If `rowEvidence` throws,\n * the page still lists without previews. `load` never calls it.\n */\n rowEvidence?(\n rows: readonly RowEvidenceRequest[],\n ): Promise<ReadonlyMap<string, RowEvidenceView>>;\n /**\n * Presentation label (#4214). `evidence` is the item's durable parts with\n * the primary part first, so a host can label by the original filename;\n * one-argument implementations keep working. The default is the primary\n * part's own `filename`, else `Intake <8 hex>`.\n */\n label?(item: IntakeItemDTO, evidence: IntakeEvidenceDTO[]): string;\n /** Expose the optional feedback UI only when the service has feedback configured. */\n enableFeedback?: boolean;\n /** Optional wakeup after a durable logical split has queued extraction. */\n onSplit?(itemId: string, revision: number): Promise<void>;\n /** Optional wakeup after a durable reviewer instruction has queued reinterpretation. */\n onInstruct?(itemId: string, revision: number): Promise<void>;\n}\n\n/**\n * The original a row should preview, chosen by role rather than media type:\n * when any part has a parent, the record parts (an upload's capture record,\n * an email's message) are skipped and the shallowest child wins (the uploaded\n * file, the first attachment), even when that child is itself JSON. When no\n * part has a parent (a watched-folder file, an email without attachments),\n * the first root part is the original. Ties sort by part id, numerically.\n */\nexport function primaryEvidence(\n parts: readonly IntakeEvidenceDTO[],\n): IntakeEvidenceDTO | undefined {\n const depth = (part: IntakeEvidenceDTO): number => {\n let level = 0;\n let parent = part.parentEvidenceId;\n const seen = new Set<string>();\n while (parent && !seen.has(parent)) {\n seen.add(parent);\n level++;\n parent = parts.find((p) => p.id === parent)?.parentEvidenceId ?? null;\n }\n return level;\n };\n const ordered = [...parts].sort(\n (a, b) =>\n depth(a) - depth(b) ||\n a.partId.localeCompare(b.partId, 'en', { numeric: true }),\n );\n return ordered.find((part) => depth(part) > 0) ?? ordered[0];\n}\n\n/**\n * Create callbacks for one authenticated service scope. Create a fresh host when\n * the session changes; HTTP authentication and CSRF remain application duties.\n */\nexport function createIntakeReviewHost(\n service: IngestionService,\n options: IntakeReviewHostOptions,\n): IntakeReviewHost {\n const label =\n options.label ??\n ((item: IntakeItemDTO, evidence: IntakeEvidenceDTO[]) =>\n // The primary part's own name only, never another part's (#4214).\n primaryEvidence(evidence)?.filename ?? `Intake ${item.id.slice(0, 8)}`);\n /** The item's durable parts with the primary part first, for `label`. */\n const labelled = (\n parts: readonly IntakeEvidenceDTO[],\n ): IntakeEvidenceDTO[] => {\n const primary = primaryEvidence(parts);\n return primary\n ? [primary, ...parts.filter((part) => part !== primary)]\n : [...parts];\n };\n /**\n * Label and, when the host opts in, preview a finished page. `list` applies\n * this once to its final entries just before returning, so every return\n * path decorates the same way. It reads the page's evidence metadata in one\n * `listEvidence` query (labels use the original filename, #4214) and calls\n * `rowEvidence` at most once (#4213). Preview fields are picked explicitly\n * so a host value can never put text on a row.\n */\n const decorateRows = async (entries: InboxEntry[]): Promise<InboxEntry[]> => {\n if (!entries.length) return entries;\n let parts: Map<string, IntakeEvidenceDTO[]>;\n try {\n parts = await service.listEvidence(entries.map((entry) => entry.item.id));\n } catch (error) {\n // With `rowEvidence` the host opted into the batched read, so its\n // failure (e.g. a failing authorize) rejects the page, as #4213\n // defines. Without it, this read only improves labels: a host that\n // never asked for evidence keeps listing, labelled as rows without\n // evidence (no filenames), the way `listItems` merely hides rows.\n if (options.rowEvidence) throw error;\n return entries.map((entry) => ({\n ...entry,\n label: label(entry.item, []),\n }));\n }\n const named = entries.map((entry) => ({\n ...entry,\n label: label(entry.item, labelled(parts.get(entry.item.id) ?? [])),\n }));\n if (!options.rowEvidence) return named;\n const rows: RowEvidenceRequest[] = [];\n for (const entry of named) {\n const primary = primaryEvidence(parts.get(entry.item.id) ?? []);\n if (primary) rows.push({ itemId: entry.item.id, evidence: primary });\n }\n if (!rows.length) return named;\n const primaries = new Map(rows.map((row) => [row.itemId, row.evidence]));\n // Everything that touches the host's answer is isolated: a throw, or a\n // malformed answer (not a map, a non-text label), lists without previews\n // rather than rejecting the page.\n try {\n const views = await options.rowEvidence(rows);\n return named.map((entry) => {\n const primary = primaries.get(entry.item.id);\n // Only rows with a durable primary part can carry a preview, even if\n // the host answers for another row.\n if (!primary) return entry;\n const view = views.get(entry.item.id);\n if (!view) return entry;\n if (typeof view.label !== 'string')\n throw new Error('Invalid row evidence');\n const evidence: InboxEvidence = {\n evidence: primary,\n label: view.label,\n };\n if (typeof view.viewUrl === 'string') evidence.viewUrl = view.viewUrl;\n if (typeof view.thumbnailUrl === 'string')\n evidence.thumbnailUrl = view.thumbnailUrl;\n return { ...entry, evidence };\n });\n } catch {\n // A preview failure must not block triage: list without previews.\n return named;\n }\n };\n const assignments = async (\n itemIds: string[],\n ): Promise<Map<string, Assignment>> => {\n if (!itemIds.length) return new Map();\n if (options.assignments) return options.assignments(itemIds);\n const read = new Map<string, Assignment>();\n for (const itemId of itemIds)\n read.set(itemId, await options.assignment(itemId));\n return read;\n };\n return {\n async list(input) {\n // The contract caps `limit` at the service maximum rather than failing.\n const requested = input.limit ?? 20;\n const limit = Number.isNaN(requested)\n ? 20\n : Math.min(ITEM_PAGE_CEILING, Math.max(1, Math.floor(requested)));\n let itemIds: string[] | undefined;\n if (input.assigneeId && options.assignedItemIds) {\n // Junk ids from the host narrow nothing and must not fail the list.\n const assigned = [\n ...new Set(\n (await options.assignedItemIds(input.assigneeId)).filter(\n isIntakeId,\n ),\n ),\n ];\n if (assigned.length <= ITEM_ID_FILTER_CEILING) itemIds = assigned;\n }\n const items: InboxEntry[] = [];\n let cursor = input.cursor;\n let examined = 0;\n // One query per page when every filter is pushed down. Only an\n // assignee filter the host cannot push down scans further pages, and\n // each scan is still one query plus one batched assignment read. A\n // host call never examines more than ITEM_SCAN_CEILING rows: a short\n // service page with a cursor (the service hit its own ceiling) or the\n // host's own count ends the call with that cursor for the caller.\n for (;;) {\n let page: Awaited<ReturnType<IngestionService['listItemsPage']>>;\n try {\n page = await service.listItemsPage({\n limit,\n cursor,\n state: input.state,\n itemIds,\n // The remaining budget: the service never scans past it, so the\n // host's total stays within ITEM_SCAN_CEILING across calls.\n scanLimit: ITEM_SCAN_CEILING - examined,\n });\n } catch (error) {\n // A later call that spent a small remaining budget without\n // returning a row must not discard what earlier calls collected:\n // hand back the position reached so far (a row the actor can read)\n // and let the caller continue.\n if (error instanceof IntakeScanLimitError && cursor !== input.cursor)\n return {\n items: await decorateRows(items),\n ...(cursor ? { nextCursor: cursor } : {}),\n };\n throw error;\n }\n examined += page.scanned;\n const read = await assignments(page.items.map(({ item }) => item.id));\n for (const [\n index,\n { item, state, cursor: rowCursor },\n ] of page.items.entries()) {\n const assignment = read.get(item.id) ?? {\n assigneeId: null,\n version: 0,\n };\n if (input.assigneeId && assignment.assigneeId !== input.assigneeId)\n continue;\n // The label needs the page's evidence; `decorateRows` sets it.\n items.push({ item, label: '', state, assignment });\n // The continuation is the last row actually returned, so an\n // assignment that changed between the page read and the assignment\n // read can only cost one extra scan, never skip or repeat a row.\n if (items.length === limit)\n return {\n items: await decorateRows(items),\n ...(page.nextCursor || index < page.items.length - 1\n ? { nextCursor: rowCursor }\n : {}),\n };\n }\n if (!page.nextCursor) return { items: await decorateRows(items) };\n if (page.items.length < limit || examined >= ITEM_SCAN_CEILING)\n return {\n items: await decorateRows(items),\n nextCursor: page.nextCursor,\n };\n cursor = page.nextCursor;\n }\n },\n async load(itemId, cursor) {\n const item = await service.getItem(itemId);\n const summary = await loadReviewSummary(service, item, cursor);\n const { analysis, reviews } = await loadReviewAnalysis(\n service,\n item,\n summary.reviews,\n cursor,\n );\n const evidence: EvidenceView[] = [];\n for (const part of await service.getEvidence(itemId)) {\n evidence.push({ ...(await options.evidence(part)), evidence: part });\n }\n const assignment = await options.assignment(itemId);\n // The offered catalog lets a reviewer start any handler; it grants nothing.\n // A catalog failure (not configured, bound exceeded, denied) only hides the\n // start-action picker; existing reviews stay reviewable.\n let catalog: ItemReviewView['catalog'];\n try {\n catalog = await service.listHandlers(itemId);\n } catch {\n catalog = undefined;\n }\n // Reviewer and reason come from the review surface, not the item DTO.\n let disposition: ItemReviewView['disposition'];\n if (item.disposition)\n try {\n disposition = await service.getItemDisposition(itemId);\n } catch {\n disposition = undefined;\n }\n const instruction = await loadInstructionView(service, itemId, analysis);\n await service.getItem(itemId);\n return {\n entry: {\n item,\n label: label(item, labelled(evidence.map((view) => view.evidence))),\n state: summary.state,\n assignment,\n },\n evidence,\n analysis,\n ...(catalog ? { catalog } : {}),\n ...(disposition ? { disposition } : {}),\n reviews,\n ...(instruction ? { instruction } : {}),\n availability: 'available',\n ...(analysis?.configuration.stage === 'interpret'\n ? {\n generation: (\n analysis.result.output as unknown as GenerationAnalysisOutput\n ).proposals,\n }\n : {}),\n };\n },\n upload: (files, requestId) => options.upload(files, requestId),\n async preview(input) {\n if (\n !Number.isSafeInteger(input.index) ||\n input.index < 0 ||\n typeof input.attemptId !== 'string' ||\n !input.attemptId ||\n typeof input.requestId !== 'string' ||\n !input.requestId.trim() ||\n (input.args !== undefined &&\n (!input.args ||\n typeof input.args !== 'object' ||\n Array.isArray(input.args)))\n )\n throw new Error('Invalid preview');\n const analysis = await service.getCompletedAnalysis(\n input.itemId,\n input.attemptId,\n );\n const generation = (\n analysis.result.output as unknown as GenerationAnalysisOutput\n ).proposals;\n const suggestion = generation?.suggestions[input.index];\n // A `needs_review` suggestion is previewable by a person (#4208); a failed\n // attempt, a missing handler or a foreign stage still is not.\n if (\n analysis.configuration.stage !== 'interpret' ||\n generation?.outcome === 'provider_error' ||\n !suggestion ||\n !['ready_for_review', 'needs_review'].includes(suggestion.disposition)\n )\n throw new Error('Preview unavailable');\n const handler = generation.offered.find(\n ({ handler }) =>\n handler.id === suggestion.handlerId &&\n handler.version === suggestion.handlerVersion,\n )?.handler;\n if (!handler) throw new Error('Preview unavailable');\n // Human-completed arguments go through the same explicit preview as an\n // edit; they never rewrite the generation snapshot.\n const args = input.args ? structuredClone(input.args) : suggestion.args;\n const intentionKey = `ui:${input.index}`;\n const actionId =\n handler.kind === 'plan'\n ? undefined\n : await service.createAction(input.itemId, intentionKey, {\n origin: 'generated-proposal',\n intentionKey,\n });\n let cursor: string | undefined;\n let expectedRevision = 0;\n const cursors = new Set<string>();\n do {\n const page = await service.listReviews(input.itemId, { cursor });\n const found = page.actions.find((action) =>\n handler.kind === 'plan'\n ? (action.plan?.key ?? action.stalePlan?.key) === intentionKey\n : action.review.actionId === actionId,\n );\n if (found) {\n const binding = handler.kind === 'plan' ? found.plan : found;\n expectedRevision =\n handler.kind === 'plan'\n ? (found.plan?.revision ?? found.stalePlan?.revision ?? 0)\n : found.review.revision;\n // Preparing an unchanged, currently authorized suggestion is idempotent.\n // State-only stale entries never satisfy this shortcut.\n if (\n binding?.attemptId === input.attemptId &&\n binding.handlerId === suggestion.handlerId &&\n binding.handlerVersion === suggestion.handlerVersion &&\n binding.args\n ) {\n const { intakeBindingDigest } = await import('./execution.js');\n if (intakeBindingDigest(binding.args) === intakeBindingDigest(args))\n return;\n }\n break;\n }\n cursor = page.nextCursor;\n if (cursor && cursors.has(cursor))\n throw new Error('Repeated review cursor');\n if (cursor) cursors.add(cursor);\n } while (cursor);\n // Every failure throws, as on main. A handler's refusal of the\n // arguments throws `HandlerArgumentsInvalidError`; a transport that\n // preserves its `name` lets the component keep the draft inline.\n if (input.args) {\n const shared = {\n itemId: input.itemId,\n attemptId: input.attemptId,\n expectedRevision,\n requestId: input.requestId,\n handlerId: suggestion.handlerId,\n handlerVersion: suggestion.handlerVersion,\n args,\n };\n if (handler.kind === 'plan')\n await service.previewPlan({ ...shared, planKey: intentionKey });\n else if (actionId)\n await service.previewProposal({ ...shared, actionId });\n return;\n }\n await service.previewGeneratedProposals({\n itemId: input.itemId,\n attemptId: input.attemptId,\n selections: [\n {\n index: input.index,\n intentionKey,\n expectedRevision,\n requestId: input.requestId,\n },\n ],\n });\n },\n async decide(input) {\n await service.submitDecision(input);\n },\n apply: (actionId) => service.applyAction(actionId),\n async editPlan(input) {\n await service.previewPlan(input);\n },\n async editAction(input) {\n await service.previewProposal(input);\n },\n candidates: (input) => service.findCandidates(input),\n async assign(input) {\n await service.getItem(input.itemId);\n await options.assign(input);\n },\n async split(input) {\n const result = await service.reviseLogicalSplit(input);\n await options.onSplit?.(input.itemId, result.revision);\n },\n // Throws on every failure, like `preview`: a handler's refusal of the\n // reviewer's arguments is `HandlerArgumentsInvalidError` (name and\n // `issues` preserved in process) so the component keeps the draft inline.\n async startAction(input) {\n await service.startReviewerAction(input);\n },\n async resolve(input) {\n await service.resolveItem(input);\n },\n async instruct(input) {\n // Durable first; the reinterpretation runs through the normal dispatch path.\n let result: Awaited<ReturnType<typeof service.recordReviewerInstruction>>;\n try {\n result = await service.recordReviewerInstruction(input);\n } catch (error) {\n if (error instanceof ReviewerInstructionStaleError)\n return { stale: true as const };\n if (error instanceof ReviewerInstructionInvalidError)\n return { invalid: true as const };\n throw error;\n }\n await options.onInstruct?.(input.itemId, result.revision);\n },\n ...(options.enableFeedback\n ? {\n feedback: (\n input: Parameters<NonNullable<IntakeReviewHost['feedback']>>[0],\n ) => service.recordFeedback(input),\n }\n : {}),\n };\n}\n","import type { ReceiptResult } from '../dto.js';\nimport { presentedFilename } from '../presented-filename.js';\nimport type { IngestionService, IntakePart, ReceiveInput } from '../server.js';\n\n/** Host configuration, reconstructed from authenticated session/account state. */\nexport interface SourceBinding {\n enabled: boolean;\n service: Pick<IngestionService, 'receive'>;\n sourceId: string;\n sourceVersion: string;\n capturedCeiling: ReceiveInput['capturedCeiling'];\n retention: ReceiveInput['retention'];\n limits: ReceiveInput['limits'];\n allowedMediaTypes: readonly string[];\n}\nexport type SourceResult =\n | ReceiptResult\n | {\n kind: 'rejected';\n category: 'authentication' | 'unsupported_type' | 'unavailable_bytes';\n };\nexport class SourceInputError extends Error {\n constructor(\n public readonly category:\n | 'invalid'\n | 'limit'\n | 'unsupported_type'\n | 'unavailable_bytes',\n ) {\n super(category);\n }\n}\nexport function record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new SourceInputError('invalid');\n return value as Record<string, unknown>;\n}\nexport function keys(value: Record<string, unknown>, allowed: string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key)))\n throw new SourceInputError('invalid');\n}\nexport function text(value: unknown): string {\n if (typeof value !== 'string' || !value || value.length > 1024)\n throw new SourceInputError('invalid');\n return value;\n}\n/**\n * A name a source presented for a part (upload, attachment, folder entry),\n * kept for labels only (#4214); see `../presented-filename.ts` for the unsafe\n * character set it removes.\n */\nexport { presentedFilename };\n/** `{ filename }` for a usable presented name, else nothing to spread. */\nexport function withPresentedFilename(value: unknown): {\n filename?: string;\n} {\n const filename = presentedFilename(value);\n return filename ? { filename } : {};\n}\nexport function timestamp(value: unknown): Date {\n const date = new Date(text(value));\n if (!Number.isFinite(date.getTime())) throw new SourceInputError('invalid');\n return date;\n}\n/** Bound bytes before parsing or handing them to the receipt service. */\nexport async function boundedBytes(\n stream: ReadableStream<Uint8Array> | null,\n limit: number,\n): Promise<Uint8Array> {\n if (!Number.isSafeInteger(limit) || limit < 1)\n throw new SourceInputError('limit');\n if (!stream) return new Uint8Array();\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > limit) {\n await reader.cancel();\n throw new SourceInputError('limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks);\n}\n/** Intake validates signatures; decoding/format correctness belongs to extraction. */\nexport function validateMedia(\n bytes: Uint8Array,\n type: string,\n allowed: readonly string[],\n): void {\n if (!allowed.includes(type)) throw new SourceInputError('unsupported_type');\n const b = Buffer.from(bytes);\n const ascii = (start: number, end: number) =>\n b.subarray(start, end).toString('ascii');\n const valid: Record<string, boolean> = {\n 'application/pdf': ascii(0, 5) === '%PDF-',\n 'image/tiff':\n b.subarray(0, 4).equals(Buffer.from([73, 73, 42, 0])) ||\n b.subarray(0, 4).equals(Buffer.from([77, 77, 0, 42])),\n 'image/jpeg': b[0] === 255 && b[1] === 216 && b[2] === 255,\n 'image/png': b\n .subarray(0, 8)\n .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),\n 'image/webp': ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP',\n 'audio/wav': ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WAVE',\n 'audio/ogg': ascii(0, 4) === 'OggS',\n 'audio/webm': b.subarray(0, 4).equals(Buffer.from([26, 69, 223, 163])),\n 'audio/mpeg':\n ascii(0, 3) === 'ID3' || (b[0] === 255 && (b[1] & 224) === 224),\n 'audio/mp4': ascii(4, 8) === 'ftyp',\n 'text/plain': true,\n 'text/html': true,\n 'application/json': true,\n };\n if (!Object.hasOwn(valid, type) || !valid[type])\n throw new SourceInputError('unsupported_type');\n if (type.startsWith('text/') || type === 'application/json') {\n try {\n const s = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (type === 'application/json') JSON.parse(s);\n } catch {\n throw new SourceInputError('invalid');\n }\n }\n}\nexport async function deliver(\n binding: SourceBinding,\n deliveryKey: string,\n deliveredAt: Date,\n parts: IntakePart[],\n): Promise<SourceResult> {\n if (!binding.enabled) return { kind: 'rejected', category: 'authentication' };\n try {\n text(deliveryKey);\n if (!Number.isFinite(deliveredAt.getTime()))\n throw new SourceInputError('invalid');\n if (\n parts.length > binding.limits.maxParts ||\n parts.reduce((n, p) => n + p.bytes.byteLength, 0) >\n binding.limits.maxBytes\n )\n throw new SourceInputError('limit');\n for (const part of parts)\n validateMedia(part.bytes, part.mediaType, binding.allowedMediaTypes);\n return await binding.service.receive({\n sourceId: binding.sourceId,\n sourceVersion: binding.sourceVersion,\n capturedCeiling: binding.capturedCeiling,\n retention: binding.retention,\n limits: binding.limits,\n deliveryKey,\n deliveredAt,\n // The one place every source's names are cleaned (#4214): upload,\n // host snapshot, vendor webhook, email and watched folder all deliver\n // here, so an odd name never fails the receipt.\n parts: parts.map(({ filename, ...part }) => ({\n ...part,\n ...withPresentedFilename(filename),\n })),\n });\n } catch (error) {\n return safeFailure(error);\n }\n}\nexport function safeFailure(error: unknown): SourceResult {\n return error instanceof SourceInputError\n ? { kind: 'rejected', category: error.category }\n : { kind: 'retry', category: 'unavailable' };\n}\n","import type { IntakePart } from '../server.js';\nimport {\n deliver,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n text,\n} from './common.js';\n\n/** Structural messages-owner seam; EmailAccount.readIntakeMessage implements this contract. */\nexport interface EmailIntakeSnapshot {\n accountId: string;\n messageId: string;\n threadId: string;\n inReplyTo: string;\n subject: string;\n text: string;\n html: string;\n date: string;\n attachments: Array<{\n partId: string;\n filename: string;\n mediaType: string;\n bytes: Uint8Array;\n }>;\n}\nexport interface EmailDelivery {\n /** Provider/account-unique locator (e.g. folder + UIDVALIDITY + UID), not sender Message-ID alone. */\n locator: string;\n /** Explicit immutable source revision, never an automatically substituted content hash. */\n revision: string;\n checkpoint: string;\n}\nexport interface EmailSourceOptions {\n binding: SourceBinding;\n accountId: string;\n readMessage(delivery: EmailDelivery): Promise<EmailIntakeSnapshot>;\n /** Durable host checkpoint; called in input order only after accepted/duplicate. */\n acknowledge(checkpoint: string): Promise<void>;\n}\n/** Opt-in intake: hosts enumerate configured accounts and supply resumable provider locators. */\nexport class EmailSourceAdapter {\n constructor(private readonly options: EmailSourceOptions) {}\n async receive(delivery: EmailDelivery): Promise<SourceResult> {\n const { binding } = this.options;\n if (!binding.enabled)\n return { kind: 'rejected', category: 'authentication' };\n try {\n text(delivery.locator);\n text(delivery.revision);\n text(delivery.checkpoint);\n const snapshot = await this.options.readMessage(delivery);\n if (snapshot.accountId !== this.options.accountId)\n return { kind: 'rejected', category: 'authentication' };\n const { attachments } = snapshot;\n // Transport objects may carry additional provider fields. Preserve only the contract.\n const body = {\n accountId: snapshot.accountId,\n messageId: snapshot.messageId,\n threadId: snapshot.threadId,\n inReplyTo: snapshot.inReplyTo,\n subject: snapshot.subject,\n text: snapshot.text,\n html: snapshot.html,\n date: snapshot.date,\n };\n if (Object.values(body).some((value) => typeof value !== 'string')) {\n throw new SourceInputError('invalid');\n }\n const parts: IntakePart[] = [\n {\n partId: 'message',\n mediaType: 'application/json',\n bytes: Buffer.from(JSON.stringify(body)),\n sourceReference: {\n owner: 'message',\n id: delivery.locator,\n version: delivery.revision,\n },\n },\n ];\n for (const attachment of attachments) {\n if (!(attachment.bytes instanceof Uint8Array))\n throw new SourceInputError('unavailable_bytes');\n parts.push({\n partId: `attachment:${text(attachment.partId)}`,\n parentPartId: 'message',\n mediaType: attachment.mediaType,\n bytes: attachment.bytes,\n filename: attachment.filename,\n sourceReference: {\n owner: 'message-attachment',\n id: `${delivery.locator}:${attachment.partId}`,\n version: delivery.revision,\n },\n });\n }\n // Filename and part mapping are retained alongside message/thread identity.\n parts[0].bytes = Buffer.from(\n JSON.stringify({\n ...body,\n attachments: attachments.map(({ partId, filename, mediaType }) => ({\n partId,\n filename,\n mediaType,\n })),\n }),\n );\n const result = await deliver(\n binding,\n JSON.stringify([\n this.options.accountId,\n delivery.locator,\n delivery.revision,\n ]),\n new Date(snapshot.date),\n parts,\n );\n if (result.kind === 'accepted' || result.kind === 'duplicate')\n await this.options.acknowledge(delivery.checkpoint);\n return result;\n } catch (error) {\n if (\n error instanceof Error &&\n error.name === 'EmailIntakeSnapshotError' &&\n 'category' in error\n ) {\n const category = error.category;\n if (\n category === 'invalid' ||\n category === 'limit' ||\n category === 'unavailable_bytes'\n ) {\n return { kind: 'rejected', category };\n }\n }\n return safeFailure(error);\n }\n }\n async receiveBatch(\n deliveries: readonly EmailDelivery[],\n ): Promise<SourceResult[]> {\n const results: SourceResult[] = [];\n for (const delivery of deliveries) {\n const result = await this.receive(delivery);\n results.push(result);\n if (result.kind !== 'accepted' && result.kind !== 'duplicate') break;\n }\n return results;\n }\n}\n","import type { IntakePart } from '../server.js';\nimport {\n boundedBytes,\n deliver,\n keys,\n presentedFilename,\n record,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n text,\n timestamp,\n} from './common.js';\n\nexport interface AuthenticatedSource extends SourceBinding {\n /** Explicit wire limit includes multipart framing and capture metadata. */\n maxRequestBytes: number;\n /** Host proves ownership/current access and copies immutable owner bytes. */\n snapshotReference?(reference: {\n owner: 'asset' | 'message';\n id: string;\n version: string;\n }): Promise<IntakePart[]>;\n}\nexport interface SourceHttpOptions {\n /** Authenticate and select enabled source from server configuration, never body fields. */\n authenticate(request: Request): Promise<AuthenticatedSource | null>;\n}\nfunction response(result: SourceResult): Response {\n return Response.json(result, {\n status:\n result.kind === 'accepted' || result.kind === 'duplicate'\n ? 200\n : result.kind === 'retry'\n ? 503\n : 'category' in result && result.category === 'authentication'\n ? 401\n : 'category' in result && result.category === 'limit'\n ? 413\n : 400,\n });\n}\n/** Reference Web Request handler; mobile clients reuse their durable UUID Idempotency-Key. */\nexport function createSourceDeliveryHandler(\n options: SourceHttpOptions,\n): (request: Request) => Promise<Response> {\n return async (request) => {\n try {\n const binding = await options.authenticate(request);\n if (!binding?.enabled)\n return response({ kind: 'rejected', category: 'authentication' });\n if (request.method !== 'POST') throw new SourceInputError('invalid');\n const key = text(request.headers.get('idempotency-key'));\n const length = request.headers.get('content-length');\n if (\n length &&\n (!/^\\d+$/.test(length) || Number(length) > binding.maxRequestBytes)\n )\n throw new SourceInputError('limit');\n const bytes = await boundedBytes(request.body, binding.maxRequestBytes);\n const type = request.headers.get('content-type') || '';\n let deliveredAt: Date;\n const parts: IntakePart[] = [];\n if (type.split(';')[0] === 'application/json') {\n let payload: Record<string, unknown>;\n try {\n payload = record(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)),\n );\n } catch {\n throw new SourceInputError('invalid');\n }\n keys(payload, ['capturedAt', 'text', 'structured', 'reference']);\n deliveredAt = timestamp(payload.capturedAt);\n if (\n ['text', 'structured', 'reference'].filter(\n (field) => payload[field] !== undefined,\n ).length !== 1\n )\n throw new SourceInputError('invalid');\n if (payload.text !== undefined) {\n if (typeof payload.text !== 'string')\n throw new SourceInputError('invalid');\n parts.push({\n partId: 'body',\n mediaType: 'text/plain',\n bytes: Buffer.from(payload.text),\n });\n } else if (payload.structured !== undefined) {\n parts.push({\n partId: 'body',\n mediaType: 'application/json',\n bytes: Buffer.from(JSON.stringify(record(payload.structured))),\n });\n } else {\n const ref = record(payload.reference);\n keys(ref, ['owner', 'id', 'version']);\n if (\n (ref.owner !== 'asset' && ref.owner !== 'message') ||\n !binding.snapshotReference\n )\n throw new SourceInputError('invalid');\n const reference = {\n owner: ref.owner,\n id: text(ref.id),\n version: text(ref.version),\n } as const;\n const snapshots = await binding.snapshotReference(reference);\n if (!snapshots.length)\n throw new SourceInputError('unavailable_bytes');\n // A host snapshot may carry a `filename`; `deliver` cleans it.\n for (const part of snapshots)\n parts.push({\n ...part,\n sourceReference: part.sourceReference ?? reference,\n });\n }\n } else if (type.startsWith('multipart/form-data;')) {\n let form: FormData;\n try {\n form = await new Response(Buffer.from(bytes), {\n headers: { 'content-type': type },\n }).formData();\n } catch {\n throw new SourceInputError('invalid');\n }\n const fields: Record<string, string> = {};\n for (const [name, value] of form.entries()) {\n if (typeof value === 'string') {\n if (\n !['captureId', 'capturedAt', 'captureSource', 'sha256'].includes(\n name,\n ) ||\n fields[name] !== undefined\n )\n throw new SourceInputError('invalid');\n fields[name] = value;\n } else {\n if (name !== 'file' || parts.length)\n throw new SourceInputError('invalid');\n // Keep the original name for labels; it never becomes identity.\n // `blob` is the name a nameless Blob part gets, not a real one;\n // it is compared after cleaning, and `deliver` cleans the rest.\n const presented = presentedFilename(value.name);\n const original = presented === 'blob' ? undefined : presented;\n parts.push({\n partId: 'file',\n parentPartId: 'capture',\n mediaType: value.type,\n bytes: await boundedBytes(\n value.stream(),\n binding.limits.maxBytes,\n ),\n ...(original ? { filename: original } : {}),\n });\n }\n }\n if (\n parts.length !== 1 ||\n text(fields.captureId) !== key ||\n !['camera', 'native_picker', 'audio', 'document'].includes(\n fields.captureSource,\n )\n )\n throw new SourceInputError('invalid');\n deliveredAt = timestamp(fields.capturedAt);\n if (fields.sha256) {\n if (!/^[a-f0-9]{64}$/.test(fields.sha256))\n throw new SourceInputError('invalid');\n parts[0].expectedHash = fields.sha256;\n }\n parts.unshift({\n partId: 'capture',\n mediaType: 'application/json',\n bytes: Buffer.from(\n JSON.stringify({\n captureId: fields.captureId,\n capturedAt: fields.capturedAt,\n captureSource: fields.captureSource,\n ...(fields.sha256 === undefined ? {} : { sha256: fields.sha256 }),\n }),\n ),\n });\n } else throw new SourceInputError('unsupported_type');\n return response(await deliver(binding, key, deliveredAt, parts));\n } catch (error) {\n return response(\n error instanceof SyntaxError\n ? { kind: 'rejected', category: 'invalid' }\n : safeFailure(error),\n );\n }\n };\n}\n\nexport interface VerifiedVendorDelivery {\n binding: SourceBinding;\n deliveryKey: string;\n deliveredAt: Date;\n parts: IntakePart[];\n}\n/** Vendor implementation owns signature/timestamp verification and replay identity. */\nexport function createVendorWebhookHandler(options: {\n maxRequestBytes: number;\n verify(\n request: Request,\n originalBytes: Uint8Array,\n ): Promise<VerifiedVendorDelivery | null>;\n}): (request: Request) => Promise<Response> {\n return async (request) => {\n try {\n if (request.method !== 'POST') throw new SourceInputError('invalid');\n const bytes = await boundedBytes(request.body, options.maxRequestBytes);\n const verified = await options.verify(request, bytes);\n if (!verified)\n return response({ kind: 'rejected', category: 'authentication' });\n return response(\n await deliver(\n verified.binding,\n verified.deliveryKey,\n verified.deliveredAt,\n verified.parts,\n ),\n );\n } catch (error) {\n return response(safeFailure(error));\n }\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n writeFile,\n} from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n deliver,\n type SourceBinding,\n SourceInputError,\n type SourceResult,\n safeFailure,\n} from './common.js';\n\nexport interface WatchFolderOptions {\n binding: SourceBinding;\n /** Private producer directory; claims and processed live on the same filesystem. */\n directory: string;\n stabilityMs: number;\n now?: () => number;\n /** Observability/crash injection. Never receives file content or credentials. */\n checkpoint?(boundary: 'claimed' | 'received', claimId: string): Promise<void>;\n}\nexport interface WatchFolderResult {\n claimId?: string;\n filename: string;\n result: SourceResult;\n}\ninterface Claim {\n id: string;\n filename: string;\n capturedAt: string;\n sourceId: string;\n sourceVersion: string;\n}\ninterface Observation {\n fingerprint: string;\n since: number;\n}\n/** Files remain in claims until the durable receipt succeeds. A restart safely replays them. */\nexport class WatchFolderSourceAdapter {\n private readonly observations = new Map<string, Observation>();\n private polling = false;\n constructor(private readonly options: WatchFolderOptions) {\n if (!Number.isSafeInteger(options.stabilityMs) || options.stabilityMs < 1)\n throw new Error('Positive stability interval required');\n }\n private async stable(path: string): Promise<boolean> {\n const stat = await lstat(path);\n if (!stat.isFile() || stat.isSymbolicLink())\n throw new SourceInputError('invalid');\n const fingerprint = [\n stat.dev,\n stat.ino,\n stat.size,\n stat.mtimeMs,\n stat.ctimeMs,\n ].join(':');\n const now = (this.options.now ?? Date.now)();\n const prior = this.observations.get(path);\n if (!prior || prior.fingerprint !== fingerprint) {\n this.observations.set(path, { fingerprint, since: now });\n return false;\n }\n return now - prior.since >= this.options.stabilityMs;\n }\n private async syncDirectory(path: string): Promise<void> {\n const directory = await open(path, constants.O_RDONLY);\n try {\n await directory.sync();\n } finally {\n await directory.close();\n }\n }\n private async importClaim(\n directory: string,\n claim: Claim,\n ): Promise<WatchFolderResult | null> {\n const path = join(directory, 'original');\n try {\n if (!(await this.stable(path))) return null;\n const handle = await open(\n path,\n constants.O_RDONLY | constants.O_NOFOLLOW,\n );\n let bytes: Buffer;\n try {\n const before = await handle.stat();\n if (before.size > this.options.binding.limits.maxBytes)\n throw new SourceInputError('limit');\n bytes = Buffer.alloc(before.size);\n let offset = 0;\n while (offset < bytes.length) {\n const { bytesRead } = await handle.read(\n bytes,\n offset,\n bytes.length - offset,\n offset,\n );\n if (!bytesRead) throw new SourceInputError('invalid');\n offset += bytesRead;\n }\n const after = await handle.stat();\n if (\n before.size !== after.size ||\n before.mtimeMs !== after.mtimeMs ||\n before.ctimeMs !== after.ctimeMs\n )\n throw new SourceInputError('invalid');\n } finally {\n await handle.close();\n }\n const mediaType = /\\.pdf$/i.test(claim.filename)\n ? 'application/pdf'\n : 'image/tiff';\n const result = await deliver(\n this.options.binding,\n claim.id,\n new Date(claim.capturedAt),\n [\n {\n partId: 'original',\n mediaType,\n bytes,\n filename: claim.filename,\n sourceReference: {\n owner: 'watch-folder',\n id: claim.filename,\n version: claim.id,\n },\n },\n ],\n );\n if (result.kind === 'accepted' || result.kind === 'duplicate') {\n await this.options.checkpoint?.('received', claim.id);\n await rename(\n directory,\n join(this.options.directory, '.ingestion-processed', claim.id),\n );\n await this.syncDirectory(\n join(this.options.directory, '.ingestion-processed'),\n );\n await this.syncDirectory(\n join(this.options.directory, '.ingestion-claims'),\n );\n this.observations.delete(path);\n } else\n await writeFile(\n join(directory, 'failure.json'),\n JSON.stringify(result),\n { mode: 0o600 },\n );\n return { claimId: claim.id, filename: claim.filename, result };\n } catch (error) {\n const result = safeFailure(error);\n // Error categories only; no raw transport paths, secrets or exception text.\n await writeFile(join(directory, 'failure.json'), JSON.stringify(result), {\n mode: 0o600,\n }).catch(() => {});\n return { claimId: claim.id, filename: claim.filename, result };\n }\n }\n async poll(): Promise<WatchFolderResult[]> {\n if (!this.options.binding.enabled || this.polling) return [];\n this.polling = true;\n const results: WatchFolderResult[] = [];\n try {\n const root = this.options.directory;\n const claims = join(root, '.ingestion-claims');\n const processed = join(root, '.ingestion-processed');\n // Only an explicitly configured, existing directory is touched.\n const rootStat = await lstat(root);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink())\n throw new SourceInputError('invalid');\n await mkdir(claims, { recursive: true, mode: 0o700 });\n await mkdir(processed, { recursive: true, mode: 0o700 });\n for (const privatePath of [claims, processed])\n if ((await lstat(privatePath)).isSymbolicLink())\n throw new SourceInputError('invalid');\n for (const entry of await readdir(claims, { withFileTypes: true })) {\n if (!entry.isDirectory() || !/^[a-f0-9-]{36}$/.test(entry.name))\n continue;\n const directory = join(claims, entry.name);\n try {\n const claim = JSON.parse(\n await readFile(join(directory, 'claim.json'), 'utf8'),\n ) as Claim;\n if (\n claim.id !== entry.name ||\n claim.sourceId !== this.options.binding.sourceId ||\n claim.sourceVersion !== this.options.binding.sourceVersion\n )\n throw new SourceInputError('invalid');\n // A crash before rename leaves an intent without original; producer file remains untouched.\n try {\n await lstat(join(directory, 'original'));\n } catch {\n continue;\n }\n const result = await this.importClaim(directory, claim);\n if (result) results.push(result);\n } catch (error) {\n results.push({\n claimId: entry.name,\n filename: '',\n result: safeFailure(error),\n });\n }\n }\n for (const entry of await readdir(root, { withFileTypes: true })) {\n if (!/\\.(pdf|tiff?)$/i.test(entry.name)) continue;\n const path = join(root, entry.name);\n try {\n if (!(await this.stable(path))) continue;\n const stat = await lstat(path);\n const claim: Claim = {\n id: randomUUID(),\n filename: entry.name,\n capturedAt: new Date(stat.mtimeMs).toISOString(),\n sourceId: this.options.binding.sourceId,\n sourceVersion: this.options.binding.sourceVersion,\n };\n const directory = join(claims, claim.id);\n await mkdir(directory, { mode: 0o700 });\n const metadata = await open(\n join(directory, 'claim.json'),\n 'wx',\n 0o600,\n );\n try {\n await metadata.writeFile(JSON.stringify(claim));\n await metadata.sync();\n } finally {\n await metadata.close();\n }\n await this.syncDirectory(directory);\n await this.syncDirectory(claims);\n await rename(path, join(directory, 'original'));\n await this.syncDirectory(directory);\n await this.syncDirectory(root);\n this.observations.delete(path);\n await this.options.checkpoint?.('claimed', claim.id);\n // Re-observe after rename: a producer may still hold its writing descriptor.\n await this.stable(join(directory, 'original'));\n } catch (error) {\n results.push({ filename: entry.name, result: safeFailure(error) });\n }\n }\n return results;\n } finally {\n this.polling = false;\n }\n }\n}\n","import {\n createCipheriv,\n createDecipheriv,\n createHash,\n randomBytes,\n randomUUID,\n} from 'node:crypto';\nimport { Asset, type AssetRuntimeLike } from '@happyvertical/smrt-assets';\nimport {\n detectEngine,\n isEmbeddedDatabase,\n isTransientDatabaseError,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport { SmrtJobCollection } from '@happyvertical/smrt-jobs';\nimport { withTenant } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type {\n AnalysisOutput,\n InlineInterpretation,\n InlineInterpretationInput,\n IntakeEvidenceDTO,\n IntakeFailure,\n IntakeItemDTO,\n IntakeLimits,\n OwnProposalsInput,\n ReceiptResult,\n} from './dto.js';\nimport { generationSnapshotRead, listReadGate } from './execution-internal.js';\nimport { extractAnalysis } from './extraction.js';\nimport { extractWithProviders } from './extraction-providers.js';\n\nimport { ProposalsNotConfiguredError } from './proposal-errors.js';\nimport { assertProposalLimits } from './proposal-limits.js';\nimport { redactedCeiling, UNFINISHED_ACTION_STATES } from './redaction.js';\nimport './models.js';\nimport type { IntakeExecutionService } from './execution.js';\nimport type {\n IntakeExecutionOptions,\n PreviewPlanInput,\n PreviewProposalInput,\n ResolveItemInput,\n ReviewInput,\n StartActionInput,\n} from './execution-contracts.js';\nimport type { FeedbackConfiguration } from './feedback-contracts.js';\nimport type {\n AdoptRuleInput,\n ObserveFeedbackInput,\n ReadRuleInput,\n RecordFeedbackInput,\n RetrieveFeedbackInput,\n SuggestRuleInput,\n} from './feedback-dto.js';\nimport { isStorableFilename, presentedFilename } from './presented-filename.js';\nimport {\n type ProposalConfiguration,\n type ProposalReadConfiguration,\n proposalReadConfiguration,\n} from './proposal-contracts.js';\nimport type {\n CompletedAnalysisSnapshot,\n PreviewGeneratedInput,\n} from './proposal-dto.js';\nimport { GenerationSourceStaleError } from './proposal-errors.js';\nimport type {\n InboxState,\n LogicalSplitInput,\n ReviewerInstruction,\n ReviewerInstructionInput,\n} from './review-dto.js';\nimport {\n REVIEWER_INSTRUCTION_MAX_LENGTH,\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n reviewerInstructionView,\n} from './reviewer-instruction.js';\n\n/** Authenticated host context. Never construct this from transport JSON. */\nexport interface IngestionScope {\n tenantId: string;\n actorId: string;\n confidentialScopeId: string;\n}\n/** A source part is already authenticated by the host/source adapter. */\nexport interface IntakePart {\n partId: string;\n parentPartId?: string;\n mediaType: string;\n bytes: Uint8Array;\n expectedHash?: string;\n sourceReference?: { owner: string; id: string; version: string };\n /** Original name as the source presented it; presentation only, never identity. */\n filename?: string;\n}\n/** A snapshot received by reference: the lifecycle owner keeps the bytes; no\n * blob copy is preserved. Only the text/structured snapshot a stage needs is\n * retained, redacted by the ordinary deletion path. The reference is identity,\n * never authority. */\nexport interface IntakeReferencePart {\n partId: string;\n parentPartId?: string;\n /** Host-typed owner record the snapshot was read from (for example `message`). */\n reference: { owner: string; id: string; version?: string };\n snapshot: { text: string } | { structured: Record<string, unknown> };\n}\n/** Lifecycle owner for owner-bound retention; `kind` is host-typed. */\nexport interface IntakeOwner {\n kind: string;\n id: string;\n}\n/** Host-resolved retention. Deadlines are always required: in `owner` mode they\n * are the hard privacy ceiling while `expireOwned` follows the owner's lifecycle. */\nexport type IntakeRetention =\n | {\n kind?: 'time';\n version: string;\n expiresAt: Date;\n replayUntil: Date;\n acceptAfter: Date;\n }\n | {\n kind: 'owner';\n owner: IntakeOwner;\n version: string;\n expiresAt: Date;\n replayUntil: Date;\n acceptAfter: Date;\n };\n/** Host-resolved delivery and retention policy, never untrusted content labels. */\nexport interface ReceiveInput {\n sourceId: string;\n sourceVersion: string;\n deliveryKey: string;\n deliveredAt: Date;\n parts: Array<IntakePart | IntakeReferencePart>;\n capturedCeiling: Record<string, unknown>;\n retention: IntakeRetention;\n limits: IntakeLimits;\n traceId?: string;\n /** `inline` records no queued work for any revision; the host runs\n * `interpretInline` in-process. Requires text/structured parts only. */\n dispatch?: 'job' | 'inline';\n}\n/** One inbox page request. Filters apply in the query, before the page is cut. */\nexport interface ListItemsInput {\n /** Rows per page; defaults to 20 and never exceeds 100. */\n limit?: number;\n /** Opaque continuation returned by the previous page. */\n cursor?: string;\n /** Durable inbox-state projection; see REVIEW.md for how it is derived. */\n state?: InboxState;\n /** Restrict the page to these item IDs (host-side assignment pushdown). */\n itemIds?: string[];\n /**\n * Rows this call may examine, at most ITEM_SCAN_CEILING (the default). A\n * host that scans across several calls passes its remaining budget so the\n * sum never exceeds the ceiling.\n */\n scanLimit?: number;\n}\n/** Inbox items newest-first by receipt, with their durable state projection. */\nexport interface IntakeItemPage {\n /** `cursor` continues after that row, so a host may cut a page short of it. */\n items: Array<{ item: IntakeItemDTO; state: InboxState; cursor: string }>;\n /** Rows this call examined, including denied and skipped ones; hosts cap on it. */\n scanned: number;\n nextCursor?: string;\n}\n/** Durable attempt claim. Its fence and token are verified on every completion. */\nexport interface AnalysisLease {\n itemId: string;\n analysisId: string;\n attemptId: string;\n revision: number;\n fence: number;\n token: string;\n}\n/** A server-owned dispatch route, retained independently of source metadata. */\nexport interface IntakeDispatchTarget {\n version: 1;\n objectType: string;\n method: string;\n}\nexport interface DispatchRouteInspection {\n status: 'bound' | 'unknown' | 'conflict';\n fingerprint: string;\n target: IntakeDispatchTarget | null;\n}\n/** Trusted integration points; no provider or application-policy implementation. */\nexport interface IngestionOptions {\n /** Optional server-owned interpretation configuration; independent of execution. */\n proposals?: ProposalConfiguration;\n /** Credential-free persisted proposal reads and previews; cannot generate. */\n proposalRead?: ProposalReadConfiguration;\n /** Explicit scoped learning; never inferred from analysis or execution success. */\n feedback?: FeedbackConfiguration;\n /** Optional application-owned review/execution catalog and live authority. */\n execution?: IntakeExecutionOptions;\n db: DatabaseInterface;\n assets: AssetRuntimeLike;\n scope: IngestionScope;\n /**\n * Optional server secret (at least 32 bytes) that seals inbox page cursors.\n * With it, a page that spends its scan limit on unreadable rows can hand\n * back an opaque position past them; without it, a cursor only ever names\n * the last row the actor can read. Never derive it from request data.\n */\n cursorKey?: string | Uint8Array;\n /** Recheck current access for EVERY boundary, including worker completion. */\n authorize(input: {\n scope: IngestionScope;\n operation: 'receive' | 'read' | 'process' | 'delete';\n capturedCeiling: Record<string, unknown>;\n db: DatabaseInterface;\n }): Promise<boolean>;\n /** Registered job handler supplied by the host; dispatch arguments contain IDs only. */\n jobTarget: { objectType: string; method: string };\n /** Explicit operator authority for provenance-free legacy receipts; closed when omitted.\n * Does not replace the normal current/captured process authorization.\n */\n dispatchRecovery?: {\n authorize(input: {\n scope: IngestionScope;\n itemId: string;\n capturedCeiling: Record<string, unknown>;\n evidenceRef: string;\n db: DatabaseInterface;\n }): Promise<boolean>;\n };\n /** Purge host-owned embeddings/previews/caches; retries must be idempotent. */\n purgeDerived(input: { tenantId: string; itemId: string }): Promise<void>;\n now?: () => Date;\n /** Fault injection/observability; never changes authority or persistence. */\n checkpoint?: (boundary: string) => Promise<void>;\n}\n\ntype Row = Record<string, unknown>;\nconst TABLES = [\n 'intake_items',\n 'intake_evidence',\n 'intake_analyses',\n 'intake_analysis_attempts',\n 'intake_plans',\n 'intake_actions',\n 'intake_proposals',\n 'intake_review_decisions',\n 'intake_executions',\n 'intake_feedback',\n 'intake_dispositions',\n 'intake_dispatches',\n 'intake_deletions',\n] as const;\nconst failures = new Set([\n 'unsupported_type',\n 'malformed_output',\n 'limit',\n 'timeout',\n 'unavailable',\n 'authentication',\n 'cancelled',\n 'integrity',\n]);\nconst uuid =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction object(value: unknown): Record<string, unknown> {\n const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n throw new Error('Invalid intake payload');\n return parsed as Record<string, unknown>;\n}\nfunction canonical(value: unknown): string {\n if (value === null || typeof value === 'string' || typeof value === 'boolean')\n return JSON.stringify(value);\n if (typeof value === 'number' && Number.isFinite(value))\n return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (\n value &&\n typeof value === 'object' &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n return `{${Object.keys(value)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonical((value as Row)[k])}`)\n .join(',')}}`;\n }\n throw new Error('Invalid canonical intake value');\n}\nfunction digest(value: unknown): string {\n return createHash('sha256').update(canonical(value)).digest('hex');\n}\nfunction bytesHash(value: Uint8Array): string {\n return createHash('sha256').update(value).digest('hex');\n}\nfunction nonempty(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512)\n throw new Error('Invalid intake identifier');\n}\n/** A source-supplied display name: bounded text with no unsafe characters. */\nfunction filename(value: unknown): asserts value is string {\n // Same character set the source adapters strip (presented-filename.ts).\n if (!isStorableFilename(value)) throw new Error('Invalid intake filename');\n}\nfunction integer(value: unknown, max = 2_147_483_647): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value <= 0 ||\n value > max\n )\n throw new Error('Invalid intake limit');\n}\nconst ITEM_PAGE_DEFAULT = 20;\n/** The most rows one inbox page returns. */\nexport const ITEM_PAGE_CEILING = 100;\n/**\n * The most rows one `listItemsPage` call examines, whatever its filters.\n * When it is reached the page is returned short with a `nextCursor`, or the\n * call fails with `IntakeScanLimitError` when it found no readable row and may not\n * disclose a position; no single call scans an unbounded scope.\n */\nexport const ITEM_SCAN_CEILING = 10 * ITEM_PAGE_CEILING;\n/** The most ids one page may be restricted to before the host must fall back to scanning. */\nexport const ITEM_ID_FILTER_CEILING = 1000;\n/** True for a value shaped like an intake item id; hosts use it to drop junk before a page query. */\nexport function isIntakeId(value: unknown): value is string {\n return typeof value === 'string' && uuid.test(value);\n}\nconst INBOX_STATES: readonly InboxState[] = [\n 'resolved',\n 'processing',\n 'unresolved',\n 'waiting',\n 'failed',\n 'deferred',\n 'partially_completed',\n 'completed',\n];\n/** Correlated action counters; each uses intake_actions_item_idx for one scanned row. */\nfunction actionCount(where = ''): string {\n return `(SELECT COUNT(*) FROM intake_actions a WHERE a.tenant_id = i.tenant_id AND a.confidential_scope_id = i.confidential_scope_id AND a.item_id = i.id${where ? ` AND ${where}` : ''})`;\n}\n/**\n * Durable inbox-state projection of the saved action journal plus processing\n * state. It mirrors the host's page-traversal classifier without live handler\n * or target gates, so it filters and labels a list; `load` stays authoritative.\n */\nconst dispositionWhere =\n 'd.tenant_id=i.tenant_id AND d.confidential_scope_id=i.confidential_scope_id AND d.item_id=i.id';\nconst INBOX_STATE_SQL = `CASE WHEN EXISTS (SELECT 1 FROM intake_dispositions d WHERE ${dispositionWhere}) AND ${actionCount(\"a.state = 'succeeded'\")} = 0 THEN 'resolved' WHEN i.processing_state IN ('queued','running') THEN 'processing' WHEN ${actionCount()} = 0 THEN CASE WHEN i.processing_state = 'needs_attention' THEN 'failed' ELSE 'unresolved' END WHEN ${actionCount(\"a.state <> 'succeeded'\")} = 0 THEN 'completed' WHEN ${actionCount(\"a.state = 'succeeded'\")} > 0 THEN 'partially_completed' WHEN ${actionCount(\"a.state = 'deferred'\")} > 0 THEN 'deferred' WHEN ${actionCount(\"a.state IN ('failed','outcome_unknown')\")} > 0 THEN 'failed' ELSE 'waiting' END`;\n/** The only receipt-time text the service writes, and the only cursor form. */\nconst RECEIPT_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n/**\n * The canonical receipt time of a scanned row, or undefined when the stored\n * value is not one the service writes: on SQLite the raw text must already be\n * the millisecond ISO form (no offset, no space separator, exactly three\n * fractional digits); on PostgreSQL the stored value must have no\n * sub-millisecond part, which the page query reports as `receipt_ms`.\n */\nfunction receiptTime(row: Row): string | undefined {\n const value = row.created_at;\n if (typeof value === 'string')\n return RECEIPT_TIME.test(value) &&\n Number.isFinite(Date.parse(value)) &&\n new Date(value).toISOString() === value\n ? value\n : undefined;\n if (\n value instanceof Date &&\n Number.isFinite(value.getTime()) &&\n (row.receipt_ms === true || Number(row.receipt_ms) === 1)\n )\n return value.toISOString();\n return undefined;\n}\n/**\n * A page call spent its scan limit without finding a row the actor can read,\n * or would otherwise hand back its own input cursor. Without a `cursorKey`\n * the service may not return a position derived from rows the actor cannot\n * read, so the call fails closed instead; the message names no row. Hosts\n * that already collected rows return them with their cursor.\n */\nexport class IntakeScanLimitError extends Error {\n constructor() {\n super('Intake scan limit');\n this.name = 'IntakeScanLimitError';\n }\n}\n/** A scan position: the stored receipt key and the item id. */\ninterface ItemPosition {\n key: string;\n id: string;\n}\n/**\n * Sealed cursor plaintext size; every sealed cursor has the same length. The\n * page query admits only receipt values and ids of at most 64 characters\n * (SQLite counts code points). The JSON-encoded UTF-8 position is largest\n * when every character is a control character escaped as `\\u00XX` (6 bytes):\n * 2 × 64 × 6 bytes plus 7 bytes of array syntax, which 1024 bytes holds; a\n * 4-byte UTF-8 character such as an emoji costs less.\n */\nconst SEALED_CURSOR_BYTES = 1024;\n/** The longest stored receipt value or id the page query admits on SQLite. */\nconst SCAN_KEY_CHARS = 64;\nfunction samePosition(a: ItemPosition, b: ItemPosition): boolean {\n return a.key === b.key && a.id === b.id;\n}\n/** Opaque (received-at, id) continuation; never a bare id, which is not ordered. */\nfunction encodeItemCursor(receivedAt: string, id: string): string {\n return Buffer.from(JSON.stringify([receivedAt, id])).toString('base64url');\n}\nfunction decodeItemCursor(cursor: string): { receivedAt: string; id: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));\n } catch {\n throw new Error('Invalid item page');\n }\n // The receipt time must be the normalised ISO form the service stores, so\n // the bound compares like the stored text on SQLite as well as PostgreSQL.\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== 'string' ||\n !Number.isFinite(Date.parse(parsed[0])) ||\n new Date(parsed[0]).toISOString() !== parsed[0] ||\n typeof parsed[1] !== 'string' ||\n !uuid.test(parsed[1])\n )\n throw new Error('Invalid item page');\n return { receivedAt: parsed[0], id: parsed[1] };\n}\nfunction persistedDate(value: unknown): Date {\n return value instanceof Date ? value : new Date(String(value));\n}\nconst inlineMedia = new Set(['text/plain', 'application/json']);\n/** Fixed marker for digests overwritten by privacy redaction. */\nconst REDACTED = 'redacted';\n/** Content- or identity-derived digests; successful result digests are kept as\n * the documented replay tombstone. */\nconst REDACTED_DIGESTS = [\n ['intake_analyses', 'input_digest'],\n ['intake_analysis_attempts', 'output_digest'],\n ['intake_plans', 'digest'],\n ['intake_proposals', 'binding_hash'],\n ['intake_review_decisions', 'binding_hash'],\n ['intake_executions', 'binding_hash'],\n] as const;\n\nfunction mediaKind(mediaType: string): string {\n return mediaType.split(';')[0].trim().toLowerCase();\n}\nfunction ownerKey(owner: IntakeOwner): string {\n nonempty(owner.kind);\n nonempty(owner.id);\n // Distinct owners must never collapse onto one stored key (PostgreSQL would\n // replace unpaired surrogates and reject NUL), so both parts must be storable.\n if (\n owner.kind.includes(':') ||\n !storableText(owner.kind) ||\n !storableText(owner.id)\n )\n throw new Error('Invalid intake owner');\n return `${owner.kind}:${owner.id}`;\n}\n/** PostgreSQL JSON cannot hold NUL or unpaired surrogates; SQLite can. Reject\n * them at validation so both engines answer `invalid` rather than diverge. */\nfunction storableText(value: string): boolean {\n if (value.includes('\\u0000')) return false;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(i + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false;\n i++;\n } else if (code >= 0xdc00 && code <= 0xdfff) return false;\n }\n return true;\n}\ntype ReceivedPart = IntakePart & {\n hash: string;\n retain: 'copy' | 'reference';\n snapshot?: string;\n};\n/** Normalize a copied or referenced part; referenced snapshots become bytes once. */\nfunction receivedPart(part: IntakePart | IntakeReferencePart): ReceivedPart {\n nonempty(part.partId);\n if (!('reference' in part)) {\n nonempty(part.mediaType);\n if (!(part.bytes instanceof Uint8Array)) throw new Error('Invalid part');\n const bytes = Buffer.from(part.bytes);\n const hash = bytesHash(bytes);\n if (part.expectedHash && part.expectedHash !== hash)\n throw new Error('Invalid hash');\n // #4243: a copied part's presented filename is validated, never identity.\n if (part.filename !== undefined) filename(part.filename);\n return { ...part, bytes, hash, retain: 'copy' };\n }\n const reference = object(part.reference);\n nonempty(reference.owner);\n nonempty(reference.id);\n if (reference.version !== undefined) nonempty(reference.version);\n for (const value of [reference.owner, reference.id, reference.version])\n if (typeof value === 'string' && !storableText(value))\n throw new Error('Invalid reference');\n const snapshot = object(part.snapshot);\n let mediaType: string;\n let value: string;\n if ('text' in snapshot && !('structured' in snapshot)) {\n if (typeof snapshot.text !== 'string' || !storableText(snapshot.text))\n throw new Error('Invalid snapshot');\n mediaType = 'text/plain';\n value = snapshot.text;\n } else if ('structured' in snapshot && !('text' in snapshot)) {\n mediaType = 'application/json';\n value = canonical(object(snapshot.structured));\n } else throw new Error('Invalid snapshot');\n const bytes = Buffer.from(value, 'utf8');\n return {\n partId: part.partId,\n ...(part.parentPartId === undefined\n ? {}\n : { parentPartId: part.parentPartId }),\n mediaType,\n bytes,\n hash: bytesHash(bytes),\n sourceReference: {\n owner: reference.owner,\n id: reference.id,\n version: reference.version ?? '',\n },\n retain: 'reference',\n snapshot: value,\n };\n}\nfunction date(value: Date): string {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime()))\n throw new Error('Invalid intake date');\n return value.toISOString();\n}\n\n/** Server-only durable lifecycle. Domain approval/execution remains a later layer. */\nexport class IngestionService {\n private readonly db: DatabaseInterface;\n private readonly scope: IngestionScope;\n private readonly engine: 'sqlite' | 'postgres';\n private readonly cursorKey?: Buffer;\n private readonly dispatchTarget: IntakeDispatchTarget;\n constructor(private readonly options: IngestionOptions) {\n if (options.proposals) assertProposalLimits(options.proposals.limits);\n if (options.proposalRead) {\n assertProposalLimits(options.proposalRead.limits);\n if (\n options.proposals &&\n JSON.stringify(proposalReadConfiguration(options.proposals)) !==\n JSON.stringify(proposalReadConfiguration(options.proposalRead))\n )\n throw new Error('Proposal read configuration mismatch');\n }\n this.db = options.db;\n this.scope = Object.freeze({ ...options.scope });\n if (options.cursorKey !== undefined) {\n const secret =\n typeof options.cursorKey === 'string'\n ? Buffer.from(options.cursorKey, 'utf8')\n : Buffer.from(options.cursorKey);\n if (secret.length < 32)\n throw new Error('Cursor key must be at least 32 bytes');\n this.cursorKey = createHash('sha256')\n .update('smrt-ingestion:list-cursor:v1')\n .update(secret)\n .digest();\n }\n if (!uuid.test(this.scope.tenantId))\n throw new Error('Required tenant UUID');\n nonempty(this.scope.actorId);\n nonempty(this.scope.confidentialScopeId);\n const configured = this.db as DatabaseInterface & {\n type?: string;\n config?: { type?: string; url?: string };\n };\n const engine = detectEngine(\n this.db.url || configured.config?.url || '',\n configured.type || configured.config?.type,\n );\n if (!['sqlite', 'postgres'].includes(engine) || !this.db.transaction)\n throw new Error('Ingestion requires transactional SQLite or PostgreSQL');\n this.engine = engine as 'sqlite' | 'postgres';\n nonempty(options.jobTarget.objectType);\n nonempty(options.jobTarget.method);\n this.dispatchTarget = Object.freeze({\n version: 1,\n objectType: options.jobTarget.objectType,\n method: options.jobTarget.method,\n });\n }\n private async execution() {\n if (!this.options.execution)\n throw new Error('Intake execution is not configured');\n const { IntakeExecutionService } = await import('./execution.js');\n return new IntakeExecutionService(this.options, this.options.execution);\n }\n async previewProposal(input: PreviewProposalInput) {\n return (await this.execution()).previewProposal(input);\n }\n async submitDecision(input: ReviewInput) {\n return (await this.execution()).submitDecision(input);\n }\n async applyAction(actionId: string) {\n return (await this.execution()).applyAction(actionId);\n }\n async reconcileAction(actionId: string) {\n return (await this.execution()).reconcileAction(actionId);\n }\n async listReviews(\n itemId: string,\n input: { cursor?: string; limit?: number } = {},\n ) {\n return (await this.execution()).listReviews(itemId, input);\n }\n async getAction(actionId: string) {\n return (await this.execution()).getAction(actionId);\n }\n /** Own-submission review surface; see execution for its authority gate. */\n async listOwnProposals(input: OwnProposalsInput = {}) {\n return (await this.execution()).listOwnProposals(input);\n }\n async submitOwnDecision(input: ReviewInput) {\n return (await this.execution()).submitOwnDecision(input);\n }\n async authorizeAutomatic(actionId: string) {\n return (await this.execution()).authorizeAutomatic(actionId);\n }\n /** Reviewer-chosen handler for any item; same preview/approval path, never automatic. */\n async startReviewerAction(input: StartActionInput) {\n return (await this.execution()).startAction(input);\n }\n /** Terminal \"handled, no action\" disposition; distinct from rejecting a proposal. */\n async resolveItem(input: ResolveItemInput) {\n return (await this.execution()).resolveItem(input);\n }\n /** Reviewer and reason of a resolved item; requires reviewer authority. */\n async getItemDisposition(itemId: string) {\n return (await this.execution()).getItemDisposition(itemId);\n }\n async previewPlan(input: PreviewPlanInput) {\n return (await this.execution()).previewPlan(input);\n }\n async applyPlan(planId: string) {\n return (await this.execution()).applyPlan(planId);\n }\n private async proposals() {\n if (!this.options.proposals) throw new ProposalsNotConfiguredError();\n const { IngestionProposalService } = await import('./proposals.js');\n return new IngestionProposalService(\n this,\n this.options,\n this.options.proposals,\n );\n }\n private async proposalReader() {\n const config = this.options.proposals ?? this.options.proposalRead;\n if (!config) throw new ProposalsNotConfiguredError();\n const { IngestionProposalService } = await import('./proposals.js');\n return new IngestionProposalService(this, this.options, config);\n }\n /** Currently offered reviewer catalog; needs no generation credentials. */\n async listHandlers(itemId: string) {\n return (await this.proposalReader()).listHandlers(itemId);\n }\n async findCandidates(input: {\n itemId: string;\n handlerId: string;\n handlerVersion: string;\n query: string;\n limit?: number;\n }) {\n return (await this.proposals()).findCandidates(input);\n }\n async prepareGeneration(itemId: string, attemptId: string) {\n return (await this.proposals()).prepareGeneration(itemId, attemptId);\n }\n async generateProposals(lease: AnalysisLease) {\n return (await this.proposals()).generate(lease);\n }\n async previewGeneratedProposals(input: PreviewGeneratedInput) {\n return (await this.proposalReader()).preview(input);\n }\n private async feedback() {\n const { IntakeFeedbackService } = await import('./feedback.js');\n return new IntakeFeedbackService(this.options);\n }\n async recordFeedback(input: RecordFeedbackInput) {\n return (await this.feedback()).record(input);\n }\n async observeFeedback(input: ObserveFeedbackInput) {\n return (await this.feedback()).observe(input);\n }\n async retrieveFeedback(input: RetrieveFeedbackInput) {\n return (await this.proposals()).retrieveFeedback(input);\n }\n async suggestRoutingRule(input: SuggestRuleInput) {\n return (await this.feedback()).suggest(input);\n }\n async getRoutingRule(input: ReadRuleInput) {\n return (await this.feedback()).readRule(input);\n }\n async adoptRoutingRule(input: AdoptRuleInput) {\n return (await this.feedback()).adopt(input);\n }\n private now(): Date {\n return this.options.now?.() ?? new Date();\n }\n private async point(name: string): Promise<void> {\n await this.options.checkpoint?.(name);\n }\n private async authorize(\n operation: 'receive' | 'read' | 'process' | 'delete',\n data: Row,\n db = this.db,\n ): Promise<void> {\n if (\n !(await this.options.authorize({\n scope: this.scope,\n operation,\n capturedCeiling: object(data.capturedCeiling ?? {}),\n db,\n }))\n )\n throw new Error('Intake unavailable');\n }\n private async rows(\n db: DatabaseInterface,\n table: (typeof TABLES)[number],\n where = '',\n params: unknown[] = [],\n ): Promise<Row[]> {\n return (\n await db.query(\n `SELECT * FROM ${table} WHERE tenant_id = ? AND confidential_scope_id = ?${where ? ` AND ${where}` : ''}`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n ...params,\n )\n ).rows as Row[];\n }\n private async item(\n id: string,\n operation: 'read' | 'process' | 'delete',\n db = this.db,\n allowExpired = false,\n ): Promise<Row> {\n const [item] = await this.rows(db, 'intake_items', 'id = ?', [id]);\n if (!item) throw new Error('Intake unavailable');\n await this.authorize(operation, object(item.data), db);\n if (\n !allowExpired &&\n (item.visibility !== 'active' ||\n persistedDate(item.expires_at).getTime() <= this.now().getTime())\n )\n throw new Error('Intake unavailable');\n return item;\n }\n private async tx<T>(work: (db: DatabaseInterface) => Promise<T>): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await withEmbeddedWriteTransaction(\n this.db,\n isEmbeddedDatabase(this.db),\n work,\n );\n } catch (error) {\n if (attempt >= 3 || !isTransientDatabaseError(error)) throw error;\n await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));\n }\n }\n }\n /** Refuse under the caller's item lock when a terminal disposition exists. */\n private async assertUnresolved(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<void> {\n if (\n (await this.rows(db, 'intake_dispositions', 'item_id=?', [itemId])).length\n )\n throw new Error('Item resolved');\n }\n private async lock(db: DatabaseInterface, itemId: string): Promise<void> {\n const result = await db.query(\n 'UPDATE intake_items SET analysis_revision = analysis_revision WHERE tenant_id = ? AND confidential_scope_id = ? AND id = ? RETURNING id',\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n if (!result.rows.length) throw new Error('Intake unavailable');\n }\n private async insert(\n db: DatabaseInterface,\n table: (typeof TABLES)[number],\n values: Row,\n conflict?: string,\n ): Promise<Row[]> {\n const now = this.now().toISOString();\n const row = {\n id: randomUUID(),\n slug: randomUUID(),\n context: '',\n created_at: now,\n updated_at: now,\n tenant_id: this.scope.tenantId,\n confidential_scope_id: this.scope.confidentialScopeId,\n ...values,\n };\n const keys = Object.keys(row);\n return (\n await db.query(\n `INSERT INTO ${table} (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})${conflict ? ` ON CONFLICT (${conflict}) DO NOTHING` : ''} RETURNING *`,\n ...Object.values(row),\n )\n ).rows as Row[];\n }\n /** Diagnostic only: deploy manifest migrations before starting ingestion. */\n async assertReady(): Promise<void> {\n for (const table of TABLES)\n await this.db.query(`SELECT id FROM ${table} WHERE 1 = 0`);\n }\n /** Preserve every original before acknowledgment; retries retain receipt identity. */\n async receive(input: ReceiveInput): Promise<ReceiptResult> {\n await this.authorize('receive', { capturedCeiling: input.capturedCeiling });\n const now = this.now();\n let parts: ReceivedPart[];\n let owner: IntakeOwner | null = null;\n const inline = input.dispatch === 'inline';\n try {\n for (const value of [\n input.sourceId,\n input.sourceVersion,\n input.deliveryKey,\n input.retention.version,\n ])\n nonempty(value);\n if (\n input.dispatch !== undefined &&\n !['job', 'inline'].includes(input.dispatch)\n )\n throw new Error('Invalid dispatch mode');\n const retention = input.retention;\n if (\n retention.kind !== undefined &&\n !['time', 'owner'].includes(retention.kind)\n )\n throw new Error('Invalid retention mode');\n if (retention.kind === 'owner') {\n ownerKey(retention.owner);\n owner = { kind: retention.owner.kind, id: retention.owner.id };\n }\n for (const value of Object.values(input.limits)) integer(value);\n date(input.deliveredAt);\n date(input.retention.expiresAt);\n date(input.retention.replayUntil);\n date(input.retention.acceptAfter);\n if (\n input.deliveredAt < input.retention.acceptAfter ||\n input.retention.expiresAt <= now ||\n input.retention.replayUntil < input.retention.expiresAt\n )\n return { kind: 'rejected', category: 'expired' };\n if (!input.parts.length || input.parts.length > input.limits.maxParts)\n return { kind: 'rejected', category: 'limit' };\n const ids = new Set<string>();\n let total = 0;\n parts = input.parts.map((part) => {\n const received = receivedPart(part);\n if (ids.has(received.partId)) throw new Error('Invalid part');\n ids.add(received.partId);\n total += received.bytes.byteLength;\n return received;\n });\n if (total > input.limits.maxBytes)\n return { kind: 'rejected', category: 'limit' };\n // Inline receipts never queue work, so every part must be stage-ready text.\n if (inline && parts.some((p) => !inlineMedia.has(mediaKind(p.mediaType))))\n throw new Error('Inline receipt requires text or structured parts');\n for (const part of parts)\n if (\n part.parentPartId &&\n (!ids.has(part.parentPartId) || part.parentPartId === part.partId)\n )\n throw new Error('Invalid parent');\n for (const part of parts) {\n const seen = new Set([part.partId]);\n let parent = part.parentPartId;\n while (parent) {\n if (seen.has(parent)) throw new Error('Cyclic evidence');\n seen.add(parent);\n parent = parts.find((p) => p.partId === parent)?.parentPartId;\n }\n }\n } catch {\n return { kind: 'rejected', category: 'invalid' };\n }\n // Existing copied receipts keep their exact identity; new modes extend it.\n const identity = parts\n .map((p) => ({\n partId: p.partId,\n parentPartId: p.parentPartId ?? null,\n mediaType: p.mediaType,\n hash: p.hash,\n length: p.bytes.byteLength,\n sourceReference: p.sourceReference ?? null,\n ...(p.retain === 'reference' ? { retain: 'reference' } : {}),\n }))\n .sort((a, b) => a.partId.localeCompare(b.partId));\n const payloadDigest = digest(identity);\n const scopeDigest = digest({\n scope: this.scope,\n ceiling: input.capturedCeiling,\n sourceVersion: input.sourceVersion,\n ...(inline ? { dispatch: 'inline' } : {}),\n ...(owner ? { owner } : {}),\n });\n const reservation = await this.tx(async (db) => {\n await this.authorize(\n 'receive',\n { capturedCeiling: input.capturedCeiling },\n db,\n );\n const inserted = await this.insert(\n db,\n 'intake_items',\n {\n source_id: input.sourceId,\n source_version: input.sourceVersion,\n delivery_key: input.deliveryKey,\n payload_digest: payloadDigest,\n scope_digest: scopeDigest,\n receipt_state: 'reserved',\n processing_state: 'queued',\n visibility: 'active',\n receipt_version: 1,\n analysis_revision: 0,\n fence: 0,\n lease_token: '',\n lease_until: null,\n expires_at: date(input.retention.expiresAt),\n replay_until: date(input.retention.replayUntil),\n cancelled: false,\n trace_id: input.traceId ?? randomUUID(),\n // The submitter is the authenticated actor of this service, recorded\n // server-side; payload or source metadata never supplies it.\n submitter_id: this.scope.actorId,\n owner_key: owner ? ownerKey(owner) : '',\n data: canonical({\n capturedCeiling: input.capturedCeiling,\n limits: input.limits,\n retentionVersion: input.retention.version,\n deliveredAt: date(input.deliveredAt),\n dispatchTarget: this.dispatchTarget,\n ...(inline ? { dispatch: 'inline' } : {}),\n ...(owner ? { retentionOwner: owner } : {}),\n }),\n },\n 'tenant_id,source_id,delivery_key',\n );\n const matches = await db.query(\n 'SELECT * FROM intake_items WHERE tenant_id = ? AND source_id = ? AND delivery_key = ?',\n this.scope.tenantId,\n input.sourceId,\n input.deliveryKey,\n );\n const item = matches.rows[0] as Row;\n if (\n item.scope_digest !== scopeDigest ||\n item.payload_digest !== payloadDigest ||\n !(await this.matchesDispatchRoute(db, item))\n )\n return { kind: 'conflict' as const };\n if (\n item.visibility !== 'active' ||\n persistedDate(item.replay_until) <= now ||\n persistedDate(item.expires_at) <= now\n )\n return { kind: 'expired' as const };\n if (inserted.length) {\n const evidenceIds = new Map(parts.map((p) => [p.partId, randomUUID()]));\n const ordered = [...parts].sort((a, b) => {\n const depth = (p: IntakePart): number =>\n p.parentPartId\n ? 1 + depth(parts.find((x) => x.partId === p.parentPartId)!)\n : 0;\n return depth(a) - depth(b);\n });\n for (const part of ordered)\n await this.insert(db, 'intake_evidence', {\n id: evidenceIds.get(part.partId),\n item_id: item.id,\n part_id: part.partId,\n parent_evidence_id: part.parentPartId\n ? evidenceIds.get(part.parentPartId)\n : null,\n // A referenced snapshot owns no asset: it is durable in the ledger\n // row itself and leaves with the row's ordinary redaction.\n asset_id: part.retain === 'reference' ? null : randomUUID(),\n state: part.retain === 'reference' ? 'durable' : 'intent',\n content_hash: part.hash,\n byte_length: part.bytes.byteLength,\n media_type: part.mediaType,\n source_uri: '',\n data: canonical({\n sourceReference: part.sourceReference ?? null,\n ...(part.filename === undefined\n ? {}\n : { filename: part.filename }),\n ...(part.retain === 'reference'\n ? { retain: 'reference', snapshot: part.snapshot }\n : {}),\n }),\n });\n }\n return { kind: 'reserved' as const, item, created: !!inserted.length };\n });\n if (reservation.kind !== 'reserved')\n return { kind: 'rejected', category: reservation.kind };\n const item = reservation.item;\n const itemId = String(item.id);\n await this.point('reserved');\n if (item.receipt_state === 'ready') {\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n try {\n if (!inline) await this.repairDispatches();\n } catch {\n return { kind: 'retry', category: 'unavailable' };\n }\n return {\n kind: 'duplicate',\n itemId,\n receiptVersion: Number(item.receipt_version),\n };\n }\n const token = randomUUID();\n const claimed = await this.tx((db) =>\n db.query(\n `UPDATE intake_items SET receipt_state = 'preserving', fence = fence + 1, lease_token = ?, lease_until = ? WHERE tenant_id = ? AND confidential_scope_id = ? AND id = ? AND visibility = 'active' AND receipt_state <> 'ready' AND (lease_until IS NULL OR lease_until <= ?) RETURNING fence`,\n token,\n new Date(now.getTime() + input.limits.leaseMs).toISOString(),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n now.toISOString(),\n ),\n );\n if (!claimed.rows.length)\n return (await this.revokedBeforeAck(itemId))\n ? { kind: 'rejected', category: 'expired' }\n : { kind: 'retry', category: 'busy' };\n try {\n for (const part of parts)\n if (part.retain === 'copy') await this.preserve(itemId, part, token);\n await this.point('evidence');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n const evidence = await this.rows(db, 'intake_evidence', 'item_id = ?', [\n itemId,\n ]);\n if (\n evidence.length !== parts.length ||\n evidence.some((e) => e.state !== 'durable')\n )\n throw new Error('Incomplete evidence');\n const updated = await db.query(\n `UPDATE intake_items SET receipt_state='ready',lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND lease_token=? AND lease_until>? AND visibility='active' RETURNING id`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n token,\n this.now().toISOString(),\n );\n if (!updated.rows.length) throw new Error('Lease lost');\n // An inline receipt retains its route provenance but no deliverable intent.\n await this.insert(\n db,\n 'intake_dispatches',\n {\n item_id: itemId,\n stage: 'analyze',\n revision: 1,\n state: inline ? 'completed' : 'pending',\n job_id: '',\n deliveries: 0,\n data: canonical({ dispatchTarget: this.dispatchTarget }),\n },\n 'tenant_id,item_id,stage,revision',\n );\n });\n await this.point('ready');\n if (!inline) await this.repairDispatches();\n await this.point('ack');\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n return {\n kind: reservation.created ? 'accepted' : 'duplicate',\n itemId,\n receiptVersion: 1,\n };\n } catch {\n await this.tx((db) =>\n db.query(\n `UPDATE intake_items SET receipt_state='needs_attention',lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND lease_token=? AND receipt_state<>'ready'`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n token,\n ),\n );\n // An owner deletion that won the race is final, not a retryable fault.\n if (await this.revokedBeforeAck(itemId))\n return { kind: 'rejected', category: 'expired' };\n return { kind: 'retry', category: 'unavailable' };\n }\n }\n private async revokedBeforeAck(itemId: string): Promise<boolean> {\n const [row] = await this.rows(this.db, 'intake_items', 'id=?', [itemId]);\n return !row || row.visibility !== 'active';\n }\n private async preserve(\n itemId: string,\n part: IntakePart & { hash: string },\n token: string,\n ): Promise<void> {\n const [evidence] = await this.rows(\n this.db,\n 'intake_evidence',\n 'item_id=? AND part_id=?',\n [itemId, part.partId],\n );\n if (!evidence) throw new Error('Missing storage intent');\n await this.item(itemId, 'process');\n const asset = await withTenant(\n { tenantId: this.scope.tenantId },\n async () => {\n let asset = await this.options.assets.collection.get({\n id: String(evidence.asset_id),\n });\n if (!asset)\n asset = await this.options.assets.collection.create({\n id: String(evidence.asset_id),\n tenantId: this.scope.tenantId,\n name: String(evidence.id),\n mimeType: part.mediaType,\n typeSlug: 'intake',\n statusSlug: 'active',\n sourceUri: '',\n });\n if (asset.tenantId !== this.scope.tenantId)\n throw new Error('Asset unavailable');\n return asset;\n },\n );\n const uri = await this.options.assets.store.planFile(asset, {\n mimeType: part.mediaType,\n typeSlug: 'intake',\n });\n if (evidence.source_uri && evidence.source_uri !== uri)\n throw new Error('Storage plan changed');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.lease_token !== token ||\n persistedDate(item.lease_until) <= this.now()\n )\n throw new Error('Lease lost');\n await db.query(\n 'UPDATE intake_evidence SET source_uri=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n uri,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n evidence.id,\n );\n });\n asset.sourceUri = uri;\n await asset.save();\n await this.point('storage_intent');\n await this.options.assets.store.preserveFile(\n asset,\n Buffer.from(part.bytes),\n { mimeType: part.mediaType, typeSlug: 'intake' },\n );\n await this.point('storage');\n const actual = await this.options.assets.store.read(asset);\n if (\n actual.length !== Number(evidence.byte_length) ||\n bytesHash(actual) !== evidence.content_hash\n )\n throw new Error('Storage integrity');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.lease_token !== token ||\n persistedDate(item.lease_until) <= this.now()\n )\n throw new Error('Lease lost');\n await db.query(\n \"UPDATE intake_evidence SET state='durable' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n evidence.id,\n );\n });\n }\n /** Inspect retained route provenance without changing state or enqueuing work. */\n async inspectDispatchRoute(itemId: string): Promise<DispatchRouteInspection> {\n const item = await this.item(itemId, 'read');\n return this.dispatchRouteState(this.db, item);\n }\n\n /** Explicitly bind a provenance-free legacy receipt to this trusted host's route.\n * Never accepts a route from the caller, rewrites original authority, or enqueues.\n */\n async recoverDispatchRoute(input: {\n itemId: string;\n expectedFingerprint: string;\n evidenceRef: string;\n }): Promise<DispatchRouteInspection> {\n nonempty(input.evidenceRef);\n if (!/^[a-f0-9]{64}$/.test(input.expectedFingerprint))\n throw new Error('Invalid dispatch recovery fingerprint');\n if (!this.options.dispatchRecovery)\n throw new Error('Dispatch recovery unavailable');\n return this.tx(async (db) => {\n await this.lock(db, input.itemId);\n const item = await this.item(input.itemId, 'process', db);\n const data = object(item.data);\n if (\n !(await this.options.dispatchRecovery!.authorize({\n scope: this.scope,\n itemId: input.itemId,\n capturedCeiling: object(data.capturedCeiling),\n evidenceRef: input.evidenceRef,\n db,\n }))\n )\n throw new Error('Dispatch recovery unavailable');\n const current = await this.dispatchRouteState(db, item);\n const recovery =\n data.dispatchRecovery === undefined\n ? null\n : object(data.dispatchRecovery);\n if (\n recovery &&\n recovery.expectedFingerprint === input.expectedFingerprint &&\n recovery.evidenceRef === input.evidenceRef &&\n current.status === 'bound' &&\n canonical(current.target) === canonical(this.dispatchTarget)\n ) {\n return current;\n }\n if (\n current.status !== 'unknown' ||\n current.fingerprint !== input.expectedFingerprint\n )\n throw new Error('Dispatch recovery conflict');\n data.dispatchRecovery = {\n version: 1,\n expectedFingerprint: input.expectedFingerprint,\n evidenceRef: input.evidenceRef,\n actorId: this.scope.actorId,\n recordedAt: date(this.now()),\n target: this.dispatchTarget,\n };\n item.data = canonical(data);\n await this.bindDispatchRoute(db, item);\n await this.point('dispatch:recovered');\n const [updated] = await this.rows(db, 'intake_items', 'id=?', [item.id]);\n return this.dispatchRouteState(db, updated);\n });\n }\n\n private async matchesDispatchRoute(\n db: DatabaseInterface,\n item: Row,\n ): Promise<boolean> {\n const route = await this.dispatchRouteState(db, item);\n return (\n route.status === 'bound' &&\n canonical(route.target) === canonical(this.dispatchTarget)\n );\n }\n\n private async bindDispatchRoute(\n db: DatabaseInterface,\n item: Row,\n ): Promise<void> {\n const data = object(item.data);\n if (data.dispatchTarget === undefined) {\n await db.query(\n 'UPDATE intake_items SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...data, dispatchTarget: this.dispatchTarget }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n item.id,\n );\n }\n const intents = await this.rows(db, 'intake_dispatches', 'item_id=?', [\n item.id,\n ]);\n for (const intent of intents) {\n const retained = object(intent.data);\n if (retained.dispatchTarget === undefined)\n await db.query(\n 'UPDATE intake_dispatches SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...retained, dispatchTarget: this.dispatchTarget }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n }\n }\n\n private async dispatchRouteState(\n db: DatabaseInterface,\n item: Row,\n ): Promise<DispatchRouteInspection> {\n let invalid = false;\n const malformed: string[] = [];\n const payload = (value: unknown): Row => {\n try {\n return object(value);\n } catch {\n invalid = true;\n malformed.push(digest(value));\n return {};\n }\n };\n const data = payload(item.data);\n const intents = (\n await this.rows(db, 'intake_dispatches', 'item_id=?', [item.id])\n ).sort((a, b) => String(a.id).localeCompare(String(b.id)));\n const targets: IntakeDispatchTarget[] = [];\n const lineage: unknown[] = [];\n const retain = (value: unknown) => {\n if (value === undefined) return;\n try {\n const target = object(value);\n nonempty(target.objectType);\n nonempty(target.method);\n if (target.version !== 1) throw new Error('Unsupported dispatch route');\n targets.push({\n version: 1,\n objectType: target.objectType,\n method: target.method,\n });\n } catch {\n invalid = true;\n }\n };\n retain(data.dispatchTarget);\n if (data.dispatchRecovery !== undefined) {\n const recovery = payload(data.dispatchRecovery);\n if (recovery.version !== 1 || recovery.target === undefined)\n invalid = true;\n retain(recovery.target);\n }\n const jobs = await SmrtJobCollection.create({ db });\n for (const intent of intents) {\n retain(payload(intent.data).dispatchTarget);\n if (!intent.job_id) continue;\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n jobs.get({ id: String(intent.job_id) }),\n );\n // Missing jobs are absent provenance, not affirmative conflicting authority.\n // A retained route survives job retention; otherwise explicit recovery is required.\n if (!job) {\n lineage.push({ id: intent.job_id, missing: true });\n continue;\n }\n const args = payload(job.args);\n if (\n job.tenantId !== this.scope.tenantId ||\n job.queue !== 'ingestion' ||\n job.objectId ||\n args.itemId !== item.id ||\n args.dispatchId !== intent.id ||\n args.revision !== Number(intent.revision)\n ) {\n invalid = true;\n lineage.push({ id: intent.job_id, valid: false });\n continue;\n }\n const target = {\n version: 1,\n objectType: job.objectType,\n method: job.method,\n };\n retain(target);\n lineage.push({ id: job.id, target, args });\n }\n if (targets.some((target) => canonical(target) !== canonical(targets[0])))\n invalid = true;\n const status = invalid ? 'conflict' : targets.length ? 'bound' : 'unknown';\n return {\n status,\n target: status === 'bound' ? targets[0] : null,\n fingerprint: digest({\n itemId: item.id,\n tenantId: item.tenant_id,\n confidentialScopeId: item.confidential_scope_id,\n sourceId: item.source_id,\n sourceVersion: item.source_version,\n payloadDigest: item.payload_digest,\n scopeDigest: item.scope_digest,\n revision: item.analysis_revision,\n data,\n intents: intents.map((intent) => ({\n id: intent.id,\n revision: intent.revision,\n data: payload(intent.data),\n jobId: intent.job_id,\n })),\n lineage,\n malformed,\n }),\n };\n }\n\n /** Repair lost enqueue/mark writes and deleted/failed jobs. Duplicate jobs are safe. */\n async repairDispatches(): Promise<number> {\n let repaired = 0;\n const intents = await this.rows(\n this.db,\n 'intake_dispatches',\n \"state <> 'completed'\",\n );\n const jobs = await SmrtJobCollection.create({ db: this.db });\n for (const intent of intents) {\n // Scope and protected route are checked before this host's authorization:\n // unrelated hosts must not spend budgets or block one another's receipt.\n const [candidate] = await this.rows(this.db, 'intake_items', 'id=?', [\n intent.item_id,\n ]);\n if (!candidate || !(await this.matchesDispatchRoute(this.db, candidate)))\n continue;\n const item = await this.item(\n String(intent.item_id),\n 'process',\n this.db,\n true,\n );\n if (\n item.visibility !== 'active' ||\n item.cancelled ||\n persistedDate(item.expires_at) <= this.now()\n )\n continue;\n const allocation = await this.tx(async (db) => {\n await this.lock(db, String(item.id));\n const [routedItem] = await this.rows(db, 'intake_items', 'id=?', [\n item.id,\n ]);\n if (!routedItem || !(await this.matchesDispatchRoute(db, routedItem)))\n return false;\n await this.bindDispatchRoute(db, routedItem);\n const currentItem = await this.item(String(item.id), 'process', db);\n const [currentIntent] = await this.rows(\n db,\n 'intake_dispatches',\n 'id=? AND item_id=?',\n [intent.id, item.id],\n );\n if (!currentIntent || currentIntent.state === 'completed') return false;\n if (\n currentIntent.job_id &&\n Number(currentIntent.revision) ===\n Math.max(1, Number(currentItem.analysis_revision))\n ) {\n const currentJobs = await SmrtJobCollection.create({ db });\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n currentJobs.get({ id: String(currentIntent.job_id) }),\n );\n if (job && ['pending', 'running'].includes(job.status)) return false;\n }\n // Revision 1 is queued at receipt, before the first analysis exists.\n if (\n currentItem.cancelled ||\n Number(currentIntent.revision) !==\n Math.max(1, Number(currentItem.analysis_revision))\n ) {\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n currentIntent.id,\n );\n return false;\n }\n const limits = object(\n object(currentItem.data).limits,\n ) as unknown as IntakeLimits;\n if (Number(currentIntent.deliveries) >= limits.maxAttempts) {\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n item.id,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n return false;\n }\n const result = await db.query(\n \"UPDATE intake_dispatches SET deliveries=deliveries+1 WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND state<>'completed' AND deliveries<? RETURNING id\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n currentIntent.id,\n limits.maxAttempts,\n );\n return result.rows.length === 1;\n });\n if (!allocation) continue;\n const job = await withTenant({ tenantId: this.scope.tenantId }, () =>\n jobs.enqueueJob({\n tenantId: this.scope.tenantId,\n objectType: this.dispatchTarget.objectType,\n method: this.dispatchTarget.method,\n args: {\n itemId: intent.item_id,\n revision: Number(intent.revision),\n dispatchId: intent.id,\n },\n queue: 'ingestion',\n maxAttempts: 1,\n }),\n );\n await this.point('enqueued');\n await this.tx((db) =>\n db.query(\n \"UPDATE intake_dispatches SET state='delivered',job_id=? WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND state<>'completed'\",\n job.id,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n ),\n );\n repaired++;\n }\n return repaired;\n }\n /**\n * One authorized inbox page, newest receipt first with the id as tiebreak.\n * Tenant, confidential scope, retention and the id restriction run in the\n * query; rows are authorized before the `state` filter is applied to the\n * fetched batch, so every filter is bounded by the scan limit (default\n * ITEM_SCAN_CEILING). Authority is rechecked at two levels: the host\n * `authorize('read')` once per distinct captured ceiling, and the execution\n * read gate once per distinct (item, handler) bound by a scanned row that\n * passed the first. Without a `cursorKey` every cursor names a row the\n * actor can read; with one, all cursors are sealed and a budget-stopped\n * page may resume past rows the actor cannot read. `scanned` is for trusted\n * host accounting and must not be sent to clients.\n */\n async listItemsPage(input: ListItemsInput = {}): Promise<IntakeItemPage> {\n const limit = input.limit ?? ITEM_PAGE_DEFAULT;\n if (\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > ITEM_PAGE_CEILING ||\n (input.state !== undefined && !INBOX_STATES.includes(input.state)) ||\n (input.itemIds !== undefined &&\n (!Array.isArray(input.itemIds) ||\n input.itemIds.length > ITEM_ID_FILTER_CEILING ||\n !input.itemIds.every(isIntakeId))) ||\n (input.scanLimit !== undefined &&\n (!Number.isSafeInteger(input.scanLimit) ||\n input.scanLimit < 1 ||\n input.scanLimit > ITEM_SCAN_CEILING))\n )\n throw new Error('Invalid item page');\n if (input.itemIds && !input.itemIds.length)\n return { items: [], scanned: 0 };\n const start = input.cursor ? this.decodeCursor(input.cursor) : undefined;\n const scan = await this.scanItems(\n input,\n limit,\n input.scanLimit ?? ITEM_SCAN_CEILING,\n start,\n );\n const items = scan.items.map(({ item, state, position }) => ({\n item,\n state,\n cursor: this.encodeCursor(position),\n }));\n if (scan.done) return { items, scanned: scan.scanned };\n const last = scan.items.at(-1)?.position;\n if (scan.full && last)\n return {\n items,\n scanned: scan.scanned,\n nextCursor: this.encodeCursor(last),\n };\n // The budget ran out before the page filled. A sealed cursor may resume\n // past rows the actor cannot read; an unsealed one may only name a row\n // the actor can read. With no such position, or none past the input, the\n // call fails closed rather than return a cursor that cannot progress.\n const position = this.cursorKey ? scan.scanFrom : scan.lastReadable;\n if (!position || (start && samePosition(position, start)))\n throw new IntakeScanLimitError();\n return {\n items,\n scanned: scan.scanned,\n nextCursor: this.encodeCursor(position),\n };\n }\n /**\n * The bounded page scan behind `listItemsPage` and `listItems`. It returns\n * the rows to list with their positions, the exact scan position reached\n * (`scanFrom`, which may be a row the actor cannot read and must never\n * leave the service unsealed), and the last row the actor can read\n * (`lastReadable`, which may not match the `state` filter).\n */\n private async scanItems(\n input: Pick<ListItemsInput, 'state' | 'itemIds'>,\n limit: number,\n scanCeiling: number,\n start: ItemPosition | undefined,\n ): Promise<{\n items: Array<{\n item: IntakeItemDTO;\n state: InboxState;\n position: ItemPosition;\n }>;\n scanned: number;\n done: boolean;\n full: boolean;\n scanFrom?: ItemPosition;\n lastReadable?: ItemPosition;\n }> {\n let scanFrom = start;\n let lastReadable: ItemPosition | undefined;\n const now = this.now().toISOString();\n const allowed = this.ceilingGate();\n const handlers = this.handlerGate();\n const items: Array<{\n item: IntakeItemDTO;\n state: InboxState;\n position: ItemPosition;\n }> = [];\n let examined = 0;\n // SQLite without planner statistics prefers the expiry index plus a sort,\n // which reads the whole scope per page; pin the ordering index. An id\n // restriction is left to the planner, which then looks ids up directly.\n // A non-text receipt value (an integer, say) sorts after every text value\n // on SQLite and always satisfies `created_at < ?`, so the scan could\n // never move past it; an over-long receipt value or id could not be\n // carried by any cursor; and an embedded NUL makes SQLite's `length()`\n // stop early and the driver return truncated text, so such a row would\n // look canonical and sort above a legitimate row at the truncated value.\n // Such rows are service-foreign and excluded.\n // PostgreSQL types both columns, so neither case arises there.\n const sqlite = this.engine === 'sqlite';\n const pinned =\n sqlite && !input.itemIds ? ' INDEXED BY intake_items_received_idx' : '';\n const textOnly = sqlite\n ? ` AND typeof(i.created_at) = 'text' AND length(i.created_at) <= ${SCAN_KEY_CHARS} AND length(i.id) <= ${SCAN_KEY_CHARS} AND instr(i.created_at, char(0)) = 0 AND instr(i.id, char(0)) = 0`\n : '';\n // The exact stored receipt value (for the scan anchor) and, on\n // PostgreSQL, whether it has a sub-millisecond part a cursor cannot carry.\n const receipt = sqlite\n ? 'i.created_at AS receipt_raw, 1 AS receipt_ms'\n : \"i.created_at::text AS receipt_raw, (i.created_at = date_trunc('milliseconds', i.created_at)) AS receipt_ms\";\n for (;;) {\n const params: unknown[] = [\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n now,\n ];\n let where = textOnly;\n if (scanFrom) {\n where += ' AND (i.created_at < ? OR (i.created_at = ? AND i.id < ?))';\n params.push(scanFrom.key, scanFrom.key, scanFrom.id);\n }\n if (input.itemIds) {\n where += ` AND i.id IN (${input.itemIds.map(() => '?').join(',')})`;\n params.push(...input.itemIds);\n }\n // The first read fetches exactly the page. Refills after skipped rows\n // grow with what has already been examined, from the page size up to\n // 100 rows, and never past the scan limit.\n const wanted = limit - items.length;\n const batch = Math.min(\n scanCeiling - examined,\n Math.max(wanted, Math.min(ITEM_PAGE_CEILING, examined)),\n );\n // The state expression is evaluated once per fetched row.\n // MIN over canonical UUID text preserves getItem's first-id choice\n // without a per-item sort; both probes use the scoped item index.\n const rows = (\n await this.db.query(\n `SELECT i.*, (SELECT first_d.created_at FROM intake_dispositions first_d WHERE first_d.tenant_id=i.tenant_id AND first_d.confidential_scope_id=i.confidential_scope_id AND first_d.item_id=i.id AND CAST(first_d.id AS TEXT)=(SELECT MIN(CAST(d.id AS TEXT)) FROM intake_dispositions d WHERE ${dispositionWhere})) AS disposition_at, ${INBOX_STATE_SQL} AS inbox_state, ${actionCount()} AS action_count, ${receipt} FROM intake_items i${pinned} WHERE i.tenant_id = ? AND i.confidential_scope_id = ? AND i.visibility = 'active' AND i.expires_at > ?${where} ORDER BY i.created_at DESC, i.id DESC LIMIT ?`,\n ...params,\n batch + 1,\n )\n ).rows as Row[];\n const more = rows.length > batch;\n const candidates = rows.slice(0, batch);\n // Authority first, for every fetched row, so that a readable row the\n // state filter excludes may still anchor the cursor. Item-level\n // authority runs once per distinct ceiling. A row whose payload cannot\n // be parsed is skipped and counted; a host authorization that throws\n // rejects the whole page, as `load` does, so a transient failure can\n // never let paging move past rows the actor may be allowed to read.\n const passed = new Set<Row>();\n for (const row of candidates) {\n let data: Row;\n try {\n data = object(row.data);\n } catch {\n continue;\n }\n if (await allowed(data)) passed.add(row);\n }\n // Handler bindings once per batch, for every row that passed and binds\n // actions: one read per batch, bounded by rows scanned.\n await handlers.resolve(\n candidates.filter(\n (row) => passed.has(row) && Number(row.action_count) > 0,\n ),\n );\n let consumed = 0;\n for (const row of candidates) {\n consumed++;\n examined++;\n // A receipt time the service did not write is not listed; the scan\n // position moves past it by its exact stored value so it is neither\n // re-read nor allowed to shift the order of its neighbours.\n // A row whose id is not a UUID is likewise service-foreign: it is\n // passed by its raw id and never listed or named by an unsealed\n // cursor, which only ever carries UUIDs.\n const id = String(row.id);\n const receivedAt = receiptTime(row);\n if (receivedAt !== undefined) scanFrom = { key: receivedAt, id };\n else if (typeof row.receipt_raw === 'string')\n scanFrom = { key: row.receipt_raw, id };\n if (receivedAt === undefined || !isIntakeId(id) || !passed.has(row))\n continue;\n if (Number(row.action_count) > 0 && !(await handlers.readable(row)))\n continue;\n const position = { key: receivedAt, id };\n lastReadable = position;\n if (input.state && row.inbox_state !== input.state) continue;\n items.push({\n item: this.itemDTO(row, row.disposition_at),\n state: String(row.inbox_state) as InboxState,\n position,\n });\n if (items.length === limit) break;\n }\n const remaining = more || consumed < candidates.length;\n const full = items.length === limit;\n if (!remaining || full || examined >= scanCeiling)\n return {\n items,\n scanned: examined,\n done: !remaining,\n full,\n scanFrom,\n lastReadable,\n };\n }\n }\n /** Associated data that binds a sealed cursor to this authenticated scope. */\n private cursorScope(): Buffer {\n return Buffer.from(\n canonical({\n tenantId: this.scope.tenantId,\n confidentialScopeId: this.scope.confidentialScopeId,\n actorId: this.scope.actorId,\n }),\n );\n }\n private encodeCursor(position: ItemPosition): string {\n if (!this.cursorKey) return encodeItemCursor(position.key, position.id);\n // A fixed-size plaintext, so a sealed cursor's length says nothing about\n // whether it stopped on a canonical or a service-foreign row.\n const body = Buffer.alloc(SEALED_CURSOR_BYTES, 0x20);\n const json = Buffer.from(JSON.stringify([position.key, position.id]));\n if (json.length > SEALED_CURSOR_BYTES)\n throw new Error('Cursor position too long');\n json.copy(body);\n const iv = randomBytes(12);\n const cipher = createCipheriv('aes-256-gcm', this.cursorKey, iv);\n cipher.setAAD(this.cursorScope());\n const sealed = Buffer.concat([cipher.update(body), cipher.final()]);\n return Buffer.concat([iv, cipher.getAuthTag(), sealed]).toString(\n 'base64url',\n );\n }\n private decodeCursor(cursor: string): ItemPosition {\n if (!this.cursorKey) {\n const { receivedAt, id } = decodeItemCursor(cursor);\n return { key: receivedAt, id };\n }\n try {\n const bytes = Buffer.from(cursor, 'base64url');\n if (bytes.length !== 28 + SEALED_CURSOR_BYTES) throw new Error('size');\n const decipher = createDecipheriv(\n 'aes-256-gcm',\n this.cursorKey,\n bytes.subarray(0, 12),\n );\n decipher.setAAD(this.cursorScope());\n decipher.setAuthTag(bytes.subarray(12, 28));\n const parsed: unknown = JSON.parse(\n Buffer.concat([\n decipher.update(bytes.subarray(28)),\n decipher.final(),\n ]).toString('utf8'),\n );\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== 'string' ||\n !parsed[0] ||\n typeof parsed[1] !== 'string' ||\n !parsed[1]\n )\n throw new Error('shape');\n return { key: parsed[0], id: parsed[1] };\n } catch {\n throw new Error('Invalid item page');\n }\n }\n /**\n * Every authorized active item, newest receipt first.\n * @deprecated Use `listItemsPage`. Kept so callers of the array-returning\n * API keep working. It walks every page, so its cost grows with the scope,\n * including one execution authorization per (item, handler) across the\n * whole scope. It follows the internal scan position, which never leaves\n * the service, so runs of rows the actor cannot read never stop it. Items\n * are gated exactly as on a page.\n */\n async listItems(): Promise<IntakeItemDTO[]> {\n const all: IntakeItemDTO[] = [];\n let from: ItemPosition | undefined;\n for (;;) {\n const scan = await this.scanItems(\n {},\n ITEM_PAGE_CEILING,\n ITEM_SCAN_CEILING,\n from,\n );\n all.push(...scan.items.map(({ item }) => item));\n if (scan.done) return all;\n if (!scan.scanFrom || (from && samePosition(scan.scanFrom, from)))\n throw new Error('Intake list made no progress');\n from = scan.scanFrom;\n }\n }\n /**\n * One read authorization per distinct captured ceiling for a page of rows.\n * A refusal hides the rows; a malformed ceiling hides its row; a host\n * callback that throws rejects the page with that error.\n */\n private ceilingGate(): (data: Row) => Promise<boolean> {\n const ceilings = new Map<string, Promise<boolean>>();\n return (data) => {\n let ceiling: Record<string, unknown>;\n try {\n ceiling = object(data.capturedCeiling ?? {});\n } catch {\n return Promise.resolve(false);\n }\n const key = canonical(ceiling);\n let decision = ceilings.get(key);\n if (!decision) {\n decision = Promise.resolve(\n this.options.authorize({\n scope: this.scope,\n operation: 'read',\n capturedCeiling: ceiling,\n db: this.db,\n }),\n ).then((granted) => granted === true);\n ceilings.set(key, decision);\n }\n return decision;\n };\n }\n /**\n * The handler checks `listReviews` applies per action, batched for a page:\n * the bindings of the rows' current proposals are projected in SQL\n * (handler id, version, operation and capability; distinct per item) once\n * per fetched batch, then the execution list read gate runs once per distinct\n * (item, handler) of a row that passed the item-level gate. An item whose\n * bound handler the actor cannot currently read, whose binding drifted\n * from the configured handler, or whose bindings cannot be resolved, is\n * not listed. Actions without a proposal carry no handler and are not\n * gated, as in `listReviews`.\n */\n private handlerGate() {\n type Bound = {\n handlerId: string;\n handlerVersion: string;\n operation: unknown;\n capability: unknown;\n };\n const bound = new Map<string, Bound[]>();\n // Created only when a listed row actually binds a handler; a failure to\n // construct the execution service reads as \"not readable\", never as an\n // unhandled rejection.\n let execution: Promise<IntakeExecutionService | undefined> | undefined;\n const service = () => {\n execution ??= (\n this.options.execution\n ? this.execution()\n : Promise.resolve<IntakeExecutionService | undefined>(undefined)\n ).catch(() => undefined);\n return execution;\n };\n // The explicit cast keeps the projection valid where a deployment stores\n // the declared JSON column as json or text rather than jsonb.\n const field = (name: string, text: boolean) =>\n this.engine === 'sqlite'\n ? `json_extract(p.data, '$.binding.${name}')`\n : `(p.data::jsonb)->'binding'${text ? '->>' : '->'}'${name}'`;\n const parsed = (value: unknown): unknown => {\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n };\n return {\n resolve: async (rows: Row[]): Promise<void> => {\n const pending = rows.filter((row) => !bound.has(String(row.id)));\n if (!pending.length) return;\n for (const row of pending) bound.set(String(row.id), []);\n const found = (\n await this.db.query(\n `SELECT DISTINCT p.item_id, ${field('handlerId', true)} AS handler_id, ${field('handlerVersion', true)} AS handler_version, ${field('operation', false)} AS operation, ${field('capability', false)} AS capability FROM intake_proposals p JOIN intake_actions a ON a.tenant_id = p.tenant_id AND a.confidential_scope_id = p.confidential_scope_id AND a.id = p.action_id AND a.proposal_revision = p.revision WHERE p.tenant_id = ? AND p.confidential_scope_id = ? AND p.item_id IN (${pending.map(() => '?').join(',')})`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n ...pending.map((row) => String(row.id)),\n )\n ).rows as Row[];\n for (const row of found)\n bound.get(String(row.item_id))?.push({\n handlerId: row.handler_id == null ? '' : String(row.handler_id),\n handlerVersion:\n row.handler_version == null ? '' : String(row.handler_version),\n operation: parsed(row.operation),\n capability: parsed(row.capability),\n });\n },\n readable: async (row: Row): Promise<boolean> => {\n for (const binding of bound.get(String(row.id)) ?? []) {\n const gate = await service();\n if (!gate || !(await gate[listReadGate](row, binding))) return false;\n }\n return true;\n },\n };\n }\n /** Only the disposition state and time; reviewer and reason need review authority. */\n private itemDTO(row: Row, dispositionAt?: unknown): IntakeItemDTO {\n return {\n id: String(row.id),\n receiptState: String(row.receipt_state),\n processingState: String(row.processing_state),\n analysisRevision: Number(row.analysis_revision),\n cancelled: !!row.cancelled,\n traceId: String(row.trace_id),\n ...(dispositionAt !== undefined && dispositionAt !== null\n ? {\n disposition: {\n state: 'resolved' as const,\n at: persistedDate(dispositionAt).toISOString(),\n },\n }\n : {}),\n };\n }\n async getItem(id: string): Promise<IntakeItemDTO> {\n const item = await this.item(id, 'read');\n const [disposition] = await this.rows(\n this.db,\n 'intake_dispositions',\n 'item_id=? ORDER BY id LIMIT 1',\n [item.id],\n );\n return this.itemDTO(item, disposition?.created_at);\n }\n async getEvidence(itemId: string): Promise<IntakeEvidenceDTO[]> {\n await this.item(itemId, 'read');\n return (\n await this.rows(\n this.db,\n 'intake_evidence',\n \"item_id=? AND state='durable'\",\n [itemId],\n )\n ).map((e) => this.evidenceDTO(e));\n }\n /**\n * Durable evidence for one inbox page in a single query, keyed by item id.\n * Items that are not active, retained and readable are omitted (no\n * existence disclosure); the host authorize callback runs once per distinct\n * captured ceiling rather than once per item, through the same gate as\n * `listItemsPage`: a refusal or a malformed ceiling hides the item, and a\n * host callback that throws rejects the read.\n */\n async listEvidence(\n itemIds: string[],\n ): Promise<Map<string, IntakeEvidenceDTO[]>> {\n if (\n !Array.isArray(itemIds) ||\n itemIds.length > ITEM_PAGE_CEILING ||\n !itemIds.every(isIntakeId)\n )\n throw new Error('Invalid item page');\n const result = new Map<string, IntakeEvidenceDTO[]>();\n if (!itemIds.length) return result;\n const rows = (\n await this.db.query(\n `SELECT e.*, i.data AS item_data FROM intake_evidence e JOIN intake_items i ON i.tenant_id = e.tenant_id AND i.confidential_scope_id = e.confidential_scope_id AND i.id = e.item_id WHERE e.tenant_id = ? AND e.confidential_scope_id = ? AND e.state = 'durable' AND i.visibility = 'active' AND i.expires_at > ? AND e.item_id IN (${itemIds.map(() => '?').join(',')}) ORDER BY e.item_id, e.part_id`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n this.now().toISOString(),\n ...itemIds,\n )\n ).rows as Row[];\n const allowed = this.ceilingGate();\n for (const row of rows) {\n let data: Row;\n try {\n data = object(row.item_data);\n } catch {\n continue;\n }\n if (!(await allowed(data))) continue;\n const itemId = String(row.item_id);\n const parts = result.get(itemId) ?? [];\n parts.push(this.evidenceDTO(row));\n result.set(itemId, parts);\n }\n return result;\n }\n private evidenceDTO(e: Row): IntakeEvidenceDTO {\n // Only the cleaned name is exposed. `sourceReference` stays in storage:\n // its ids are upstream locators (mailbox paths, raw folder names), not\n // display text, and no host needs them on the DTO.\n const filename = presentedFilename(object(e.data).filename);\n return {\n id: String(e.id),\n partId: String(e.part_id),\n parentEvidenceId: e.parent_evidence_id\n ? String(e.parent_evidence_id)\n : null,\n mediaType: String(e.media_type),\n contentHash: String(e.content_hash),\n byteLength: Number(e.byte_length),\n ...(filename ? { filename } : {}),\n };\n }\n async readEvidence(itemId: string, evidenceId: string): Promise<Uint8Array> {\n await this.item(itemId, 'read');\n const [e] = await this.rows(\n this.db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [itemId, evidenceId],\n );\n if (!e) throw new Error('Intake unavailable');\n const bytes = await this.evidenceBytes(e);\n if (\n bytes.length !== Number(e.byte_length) ||\n bytesHash(bytes) !== e.content_hash\n )\n throw new Error('Intake integrity');\n await this.item(itemId, 'read');\n return bytes;\n }\n private async evidenceBytes(e: Row): Promise<Uint8Array> {\n const data = object(e.data);\n if (data.retain === 'reference') {\n // A referenced snapshot never owns an asset; one that does is corrupt.\n if (e.asset_id) throw new Error('Intake integrity');\n if (typeof data.snapshot !== 'string')\n throw new Error('Intake unavailable');\n return Buffer.from(data.snapshot, 'utf8');\n }\n // An asset-less row without its snapshot marker is corrupt; never look up\n // a null asset identifier (PostgreSQL rejects it as an invalid UUID).\n if (!e.asset_id) throw new Error('Intake unavailable');\n const asset = await withTenant({ tenantId: this.scope.tenantId }, () =>\n this.options.assets.collection.get({ id: String(e.asset_id) }),\n );\n if (\n !asset ||\n asset.tenantId !== this.scope.tenantId ||\n asset.sourceUri !== e.source_uri\n )\n throw new Error('Intake unavailable');\n return this.options.assets.store.read(asset);\n }\n /** Append an immutable input revision. Reprocessing never creates actions. */\n async analyze(\n itemId: string,\n configuration: Record<string, unknown>,\n requestKey: string,\n ): Promise<{ id: string; revision: number }> {\n const frozen = structuredClone(configuration);\n if (\n Object.hasOwn(frozen, 'humanCorrection') &&\n frozen.stage !== 'interpret'\n )\n throw new Error('Human corrections require authenticated split revision');\n // Interpretation copies are verified against the pinned extraction source\n // before any provider disclosure (getGenerationInput).\n if (\n Object.hasOwn(frozen, 'reviewerInstruction') &&\n frozen.stage !== 'interpret'\n )\n throw new Error(\n 'Reviewer instructions require authenticated instruction revision',\n );\n return this.tx((db) => this.appendAnalysis(db, itemId, frozen, requestKey));\n }\n private async appendAnalysis(\n db: DatabaseInterface,\n itemId: string,\n configuration: Record<string, unknown>,\n requestKey: string,\n /** Inline only: the extraction attempt the interpretation pins. */\n pinnedSourceAttemptId?: string,\n ): Promise<{ id: string; revision: number }> {\n nonempty(requestKey);\n const configDigest = digest(configuration);\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n // A resolved item is terminal: no reanalysis or split re-extraction.\n await this.assertUnresolved(db, itemId);\n if (!(await this.matchesDispatchRoute(db, item)))\n throw new Error('Intake dispatch route unavailable');\n await this.bindDispatchRoute(db, item);\n if (item.receipt_state !== 'ready' || item.cancelled)\n throw new Error('Intake not processable');\n const previous = await this.rows(db, 'intake_analyses', 'item_id=?', [\n itemId,\n ]);\n const replay = previous.find(\n (a) => object(a.data).requestKey === requestKey,\n );\n if (replay) {\n if (object(replay.data).configDigest !== configDigest)\n throw new Error('Analysis request conflict');\n return { id: String(replay.id), revision: Number(replay.revision) };\n }\n // An interpretation must pin the item's latest extraction. Checked under\n // the item lock before anything is superseded, so a slow host appending a\n // late interpretation cannot clobber a newer extraction (for example a\n // reviewer's retry): it is refused and nothing is appended.\n if (configuration.stage === 'interpret') {\n const pinned = Number(\n object(object(configuration.proposals).source).revision,\n );\n const latestExtraction = previous\n .filter(\n (row) => object(object(row.data).configuration).stage !== 'interpret',\n )\n .reduce(\n (max, row) => Math.max(max, Number(row.revision)),\n Number.NEGATIVE_INFINITY,\n );\n if (pinned !== latestExtraction) throw new GenerationSourceStaleError();\n }\n // Inline only, after #4228's general check: the pinned extraction must\n // also be the latest revision of any stage and its current attempt.\n if (pinnedSourceAttemptId !== undefined) {\n const latest = previous.find(\n (a) => Number(a.revision) === Number(item.analysis_revision),\n );\n if (!latest || latest.current_attempt_id !== pinnedSourceAttemptId)\n throw new Error('Generation source changed');\n }\n const evidence = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND state='durable'\",\n [itemId],\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n const revision = Number(item.analysis_revision) + 1;\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision<? AND state<>'completed'\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n const inputs = evidence\n .map((e) => ({ id: e.id, hash: e.content_hash }))\n .sort((a, b) => String(a.id).localeCompare(String(b.id)));\n const [analysis] = await this.insert(db, 'intake_analyses', {\n item_id: itemId,\n revision,\n fence: 0,\n attempt_number: 0,\n current_attempt_id: null,\n state: 'queued',\n input_digest: digest({ inputs, configuration }),\n data: canonical({ inputs, configuration, requestKey, configDigest }),\n });\n await db.query(\n \"UPDATE intake_items SET analysis_revision=?,processing_state='queued' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n revision,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await this.insert(\n db,\n 'intake_dispatches',\n {\n item_id: itemId,\n stage: 'analyze',\n revision,\n state:\n object(item.data).dispatch === 'inline' ? 'completed' : 'pending',\n job_id: '',\n deliveries: 0,\n data: canonical({ dispatchTarget: this.dispatchTarget }),\n },\n 'tenant_id,item_id,stage,revision',\n );\n return { id: String(analysis.id), revision };\n }\n /** Run one fenced stage in-process and reload its terminal projection. */\n private async inlineStage(\n itemId: string,\n revision: number,\n work: (lease: AnalysisLease) => Promise<unknown>,\n ): Promise<InlineInterpretation['extraction']> {\n const lease = await this.claimAnalysis(itemId, revision, 'inline');\n if (lease) await work(lease);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, revision],\n );\n if (!analysis) throw new Error('Analysis unavailable');\n const [attempt] = analysis.current_attempt_id\n ? await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND item_id=?',\n [analysis.current_attempt_id, itemId],\n )\n : [];\n if (\n !attempt ||\n !['completed', 'partial', 'needs_attention', 'failed'].includes(\n String(attempt.state),\n )\n )\n throw new Error('Inline interpretation busy');\n return {\n analysisId: String(analysis.id),\n revision,\n attemptId: String(attempt.id),\n state: String(\n attempt.state,\n ) as InlineInterpretation['extraction']['state'],\n error: attempt.safe_error\n ? (String(attempt.safe_error) as IntakeFailure)\n : null,\n };\n });\n }\n /** Documented in-process receive-to-proposals path for `dispatch: 'inline'`\n * receipts. Extraction (UTF-8 text/structured only) and interpretation use the\n * same immutable revisions, fenced leases, catalog-live checks, provenance and\n * failure categories as the job path; no queue intent is created or delivered. */\n async interpretInline(\n itemId: string,\n input: InlineInterpretationInput,\n ): Promise<InlineInterpretation> {\n nonempty(input.requestId);\n if (!storableText(input.requestId))\n throw new Error('Invalid intake identifier');\n if (\n typeof input.extraction?.configurationRevision !== 'string' ||\n !input.extraction.configurationRevision ||\n !storableText(input.extraction.configurationRevision)\n )\n throw new Error('Invalid extraction configuration');\n const item = await this.item(itemId, 'process');\n if (object(item.data).dispatch !== 'inline')\n throw new Error('Inline interpretation requires an inline receipt');\n const extraction = {\n configurationRevision: input.extraction.configurationRevision,\n limits: structuredClone(input.extraction.limits),\n };\n const requested = await this.analyze(\n itemId,\n { stage: 'extract', extraction },\n `inline:extract:${input.requestId}`,\n );\n const extracted = await this.inlineStage(\n itemId,\n requested.revision,\n (lease) =>\n extractAnalysis(\n this,\n lease,\n { extract: (request) => extractWithProviders(request, {}) },\n extraction,\n ),\n );\n if (!['completed', 'partial'].includes(extracted.state))\n return { itemId, extraction: extracted };\n const interpretKey = `inline:interpret:${input.requestId}`;\n // A retried request replays its immutable interpretation revision instead\n // of preparing against a source that is no longer the current revision.\n const interpretation =\n (await this.analysisByRequest(itemId, interpretKey)) ??\n (await this.appendInterpretation(\n itemId,\n extracted.attemptId,\n interpretKey,\n ));\n const generation = await this.inlineStage(\n itemId,\n interpretation.revision,\n (lease) => this.generateProposals(lease),\n );\n if (!['completed', 'partial'].includes(generation.state))\n return { itemId, extraction: extracted, generation };\n return {\n itemId,\n extraction: extracted,\n generation,\n analysis: await this.getCompletedAnalysis(itemId, generation.attemptId),\n };\n }\n /** Prepare outside the lock (it reads catalog and analysis), then append\n * under it with the source pin rechecked. A concurrent identical request\n * that appended first makes preparation fail; its revision is the replay. */\n private async appendInterpretation(\n itemId: string,\n sourceAttemptId: string,\n requestKey: string,\n ): Promise<{ id: string; revision: number }> {\n await this.point('inline:replay-miss');\n let configuration: Record<string, unknown>;\n try {\n configuration = structuredClone(\n await this.prepareGeneration(itemId, sourceAttemptId),\n );\n } catch (error) {\n const replay = await this.analysisByRequest(itemId, requestKey);\n if (replay) return replay;\n throw error;\n }\n await this.point('inline:prepared');\n return this.tx((db) =>\n this.appendAnalysis(\n db,\n itemId,\n configuration,\n requestKey,\n sourceAttemptId,\n ),\n );\n }\n private async analysisByRequest(\n itemId: string,\n requestKey: string,\n ): Promise<{ id: string; revision: number } | null> {\n const found = (\n await this.rows(this.db, 'intake_analyses', 'item_id=?', [itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n return found\n ? { id: String(found.id), revision: Number(found.revision) }\n : null;\n }\n /** Owner-lifecycle hook: expire every active receipt bound to a deleted owner\n * through the ordinary revoke-then-delete path. Returns the number scheduled. */\n async expireOwned(owner: IntakeOwner): Promise<number> {\n const key = ownerKey(owner);\n const items = await this.rows(\n this.db,\n 'intake_items',\n \"owner_key=? AND visibility='active'\",\n [key],\n );\n try {\n for (const item of items) await this.scheduleExpiry(String(item.id));\n } catch (error) {\n try {\n await this.repairDeletions();\n } catch {\n // Durable intents remain available to the next authorized repair.\n }\n throw error;\n }\n await this.repairDeletions();\n return items.length;\n }\n\n /** Record an authenticated split correction and queue fresh extraction, never copy model output. */\n async reviseLogicalSplit(\n input: LogicalSplitInput,\n ): Promise<{ id: string; revision: number }> {\n const frozen = structuredClone(input);\n nonempty(frozen.requestId);\n integer(frozen.expectedRevision);\n if (\n !Array.isArray(frozen.groups) ||\n !frozen.groups.length ||\n frozen.groups.length > 100 ||\n frozen.groups.some(\n (group) =>\n !Array.isArray(group) ||\n !group.length ||\n group.length > 1000 ||\n group.some((page) => !Number.isSafeInteger(page) || page < 1),\n )\n )\n throw new Error('Invalid logical split');\n const pages = frozen.groups.flat();\n if (pages.length > 1000 || new Set(pages).size !== pages.length)\n throw new Error('Invalid logical split');\n const requestKey = `split:${frozen.requestId}`;\n const correction = {\n ...frozen,\n actorId: this.scope.actorId,\n kind: 'logical_split',\n };\n const replay = await this.tx(async (db) => {\n await this.lock(db, frozen.itemId);\n await this.item(frozen.itemId, 'process', db);\n await this.assertUnresolved(db, frozen.itemId);\n const found = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n if (!found) return null;\n if (\n digest(object(object(found.data).configuration).humanCorrection) !==\n digest(correction)\n )\n throw new Error('Split request conflict');\n return { id: String(found.id), revision: Number(found.revision) };\n });\n if (replay) {\n // Idempotency acknowledges only an intent the current reviewer may still access.\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n undefined,\n true,\n );\n return replay;\n }\n await this.point('split:checked');\n let result: { id: string; revision: number } | undefined;\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n // Read the anchor without requiring it to be current: a concurrent\n // duplicate must reach the locked replay check below instead of failing\n // the read. Currency is enforced under the lock instead.\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n async (db, current) => {\n // Every guard read and the append run under the item lock in this one\n // transaction (the snapshot read above already took it; re-asserting it\n // keeps the invariant local to this step).\n await this.lock(db, frozen.itemId);\n await this.point('split:locked');\n const [found] = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).filter((row) => object(row.data).requestKey === requestKey);\n if (found) {\n // A duplicate that committed after our unlocked replay check.\n if (\n digest(object(object(found.data).configuration).humanCorrection) !==\n digest(correction)\n )\n throw new Error('Split request conflict');\n result = { id: String(found.id), revision: Number(found.revision) };\n return;\n }\n const item = await this.item(frozen.itemId, 'process', db);\n if (\n current.revision !== frozen.expectedRevision ||\n Number(item.analysis_revision) !== frozen.expectedRevision\n )\n throw new Error('Stale logical split');\n const pin = object(object(current.configuration.proposals).source);\n const source = await this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n String(pin.attemptId),\n false,\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key]) throw new Error('Split source changed');\n const extraction = source.result.output.results;\n if (!Array.isArray(extraction))\n throw new Error('Split source unavailable');\n const evidence = extraction.find(\n (value) => object(object(value).evidence).id === frozen.evidenceId,\n );\n if (!evidence) throw new Error('Split evidence unavailable');\n const observed = new Set<number>();\n for (const value of object(evidence).segments as unknown[]) {\n const location = object(object(value).location);\n if (location.kind === 'page') observed.add(Number(location.page));\n if (location.kind === 'pages') {\n const from = Number(location.startPage),\n to = Number(location.endPage);\n if (\n !Number.isSafeInteger(from) ||\n !Number.isSafeInteger(to) ||\n to - from > 1000\n )\n throw new Error('Invalid source range');\n for (let page = from; page <= to; page++) observed.add(page);\n }\n }\n if (\n !observed.size ||\n pages.length !== observed.size ||\n pages.some((page) => !observed.has(page))\n )\n throw new Error('Split must cover observed pages exactly');\n await this.point('split:guarded');\n // Re-extraction retains the supported immediate-predecessor interpretation pin.\n result = await this.appendAnalysis(\n db,\n frozen.itemId,\n { ...source.configuration, humanCorrection: correction },\n requestKey,\n );\n },\n true,\n );\n if (!result) throw new Error('Split unavailable');\n return result;\n }\n /**\n * Record an authenticated reviewer instruction as an immutable human correction\n * and queue a fresh extraction plus interpretation that carries it as trusted\n * guidance. The text steers the model only; it never changes the catalog,\n * candidates, schemas, permissions or automation eligibility.\n */\n async recordReviewerInstruction(input: ReviewerInstructionInput): Promise<{\n id: string;\n revision: number;\n instruction: ReviewerInstruction;\n }> {\n const frozen = structuredClone(input);\n nonempty(frozen.requestId);\n nonempty(frozen.attemptId);\n integer(frozen.expectedRevision);\n if (\n typeof frozen.text !== 'string' ||\n !frozen.text.trim() ||\n frozen.text.length > REVIEWER_INSTRUCTION_MAX_LENGTH\n )\n throw new ReviewerInstructionInvalidError();\n const requestKey = `instruction:${frozen.requestId}`;\n const intent = {\n kind: 'reviewer_instruction',\n itemId: frozen.itemId,\n attemptId: frozen.attemptId,\n expectedRevision: frozen.expectedRevision,\n requestId: frozen.requestId,\n actorId: this.scope.actorId,\n text: frozen.text,\n };\n const replayIntent = (record: Record<string, unknown>) => {\n const {\n id: _id,\n recordedAt: _recordedAt,\n supersedesId: _supersedesId,\n digest: _digest,\n ...rest\n } = record;\n return rest;\n };\n const replay = await this.tx(async (db) => {\n await this.lock(db, frozen.itemId);\n await this.item(frozen.itemId, 'process', db);\n const found = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).find((row) => object(row.data).requestKey === requestKey);\n if (!found) return null;\n const record = object(\n object(object(found.data).configuration).reviewerInstruction,\n );\n if (digest(replayIntent(record)) !== digest(intent))\n throw new Error('Reviewer instruction request conflict');\n return {\n id: String(found.id),\n revision: Number(found.revision),\n instruction: reviewerInstructionView(record),\n };\n });\n if (replay) {\n // Idempotency acknowledges only an intent the current reviewer may still access.\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n undefined,\n true,\n );\n return replay;\n }\n await this.point('instruction:checked');\n let result:\n | { id: string; revision: number; instruction: ReviewerInstruction }\n | undefined;\n await (await this.proposalReader())[generationSnapshotRead](\n frozen.itemId,\n (work) => this.tx(work),\n // The anchor may be historical: after a failed reinterpretation the\n // reviewer retries against the latest completed generation.\n (db) =>\n this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n frozen.attemptId,\n false,\n ),\n async (db, current) => {\n // Every guard read, the history read for supersedesId and the append\n // run under the item lock in this one transaction (the snapshot read\n // above already took it; re-asserting it keeps the invariant local).\n await this.lock(db, frozen.itemId);\n await this.point('instruction:locked');\n const [found] = (\n await this.rows(db, 'intake_analyses', 'item_id=?', [frozen.itemId])\n ).filter((row) => object(row.data).requestKey === requestKey);\n if (found) {\n // A duplicate (double-click) that committed after our unlocked\n // replay check: replay it rather than refusing.\n const record = object(\n object(object(found.data).configuration).reviewerInstruction,\n );\n if (digest(replayIntent(record)) !== digest(intent))\n throw new Error('Reviewer instruction request conflict');\n result = {\n id: String(found.id),\n revision: Number(found.revision),\n instruction: reviewerInstructionView(record),\n };\n return;\n }\n const item = await this.item(frozen.itemId, 'process', db);\n if (Number(item.analysis_revision) !== frozen.expectedRevision)\n throw new ReviewerInstructionStaleError();\n let carriedConfiguration: Record<string, unknown> | undefined;\n if (current.revision !== frozen.expectedRevision) {\n // The same predicate drives getReinterpretationState, so the review\n // UI and this guard always agree on \"in flight\".\n const later = await this.laterWork(db, item, current.revision);\n if (later.phase === 'in_flight' || later.phase === 'superseded')\n throw new ReviewerInstructionStaleError();\n carriedConfiguration = later.configuration;\n }\n const pin = object(object(current.configuration.proposals).source);\n const source = await this.completedAnalysisSnapshot(\n db,\n frozen.itemId,\n String(pin.attemptId),\n false,\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key])\n throw new Error('Instruction source changed');\n // Supersede the latest recorded instruction, even one whose\n // reinterpretation never completed; the ledger, not the anchor, is history.\n const [previous] = await this.recordedInstructions(db, frozen.itemId);\n const body = {\n ...intent,\n id: randomUUID(),\n recordedAt: date(this.now()),\n supersedesId: previous?.id ?? null,\n };\n const record = { ...body, digest: digest(body) };\n await this.point('instruction:guarded');\n // Re-extraction retains the supported immediate-predecessor interpretation pin\n // and any existing split correction; the instruction travels beside it.\n const appended = await this.appendAnalysis(\n db,\n frozen.itemId,\n {\n ...(carriedConfiguration ?? source.configuration),\n reviewerInstruction: record,\n },\n requestKey,\n );\n result = { ...appended, instruction: reviewerInstructionView(record) };\n },\n true,\n );\n if (!result) throw new Error('Reviewer instruction unavailable');\n return result;\n }\n /**\n * How the revisions after an anchor generation relate to it. Shared by the\n * retry guard and getReinterpretationState so they cannot disagree.\n * A completed extraction with no interpretation appended is in flight until\n * its attempt's completion plus the item's analysis lease duration\n * (`limits.leaseMs`, the same lease claimAnalysis grants); after that it is\n * treated as a reinterpretation that did not start.\n */\n private async laterWork(\n db: DatabaseInterface,\n item: Row,\n anchorRevision: number,\n ): Promise<{\n phase: 'none' | 'in_flight' | 'superseded' | 'failed';\n failure: IntakeFailure | 'not_started' | null;\n configuration: Record<string, unknown> | undefined;\n }> {\n const later = (\n await this.rows(db, 'intake_analyses', 'item_id=? AND revision>?', [\n String(item.id),\n anchorRevision,\n ])\n ).sort((a, b) => Number(b.revision) - Number(a.revision));\n const stage = (row: Row) => object(object(row.data).configuration).stage;\n // The newest later extraction's configuration is the item's current one:\n // corrections chain forward through it, and a host reprocess replaces it\n // (dropping corrections). A retry from an older anchor builds on it so it\n // neither reverts a reprocess nor drops or resurrects a split.\n const newestExtraction = later.find((row) => stage(row) !== 'interpret');\n const configuration = newestExtraction\n ? object(object(newestExtraction.data).configuration)\n : undefined;\n const [latest] = later;\n if (!latest) return { phase: 'none', failure: null, configuration };\n if (\n later.some(\n (row) =>\n ['completed', 'partial'].includes(String(row.state)) &&\n stage(row) === 'interpret',\n )\n )\n return { phase: 'superseded', failure: null, configuration };\n if (later.some((row) => ['queued', 'running'].includes(String(row.state))))\n return { phase: 'in_flight', failure: null, configuration };\n const [attempt] = latest.current_attempt_id\n ? await this.rows(db, 'intake_analysis_attempts', 'id=? AND item_id=?', [\n latest.current_attempt_id,\n String(item.id),\n ])\n : [];\n if (['completed', 'partial'].includes(String(latest.state))) {\n // Extraction done, interpretation not appended: between stages.\n const completedAt = attempt\n ? object(attempt.data).completedAt\n : undefined;\n const leaseMs = Number(object(object(item.data).limits).leaseMs);\n // Missing or malformed timing cannot hold retries forever: it counts as\n // already expired, which is safe because a late append is refused.\n const started =\n typeof completedAt === 'string'\n ? persistedDate(completedAt).getTime()\n : Number.NaN;\n const deadline =\n Number.isFinite(started) && Number.isFinite(leaseMs)\n ? started + leaseMs\n : Number.NEGATIVE_INFINITY;\n return this.now().getTime() <= deadline\n ? { phase: 'in_flight', failure: null, configuration }\n : { phase: 'failed', failure: 'not_started', configuration };\n }\n const safe = attempt?.safe_error ? String(attempt.safe_error) : '';\n return {\n phase: 'failed',\n failure: failures.has(safe) ? (safe as IntakeFailure) : null,\n configuration,\n };\n }\n /** Pollable reinterpretation state: current revision, safe failure and the retry anchor. */\n async getReinterpretationState(itemId: string): Promise<{\n revision: number;\n processingState: string;\n /** Safe category, or `not_started` when the interpretation was never appended in time. */\n failure: IntakeFailure | 'not_started' | null;\n /** True while work after the latest completed generation is in flight, including between stages. */\n reinterpreting: boolean;\n /** Latest completed generation attempt; absent when none has completed. */\n generationAttemptId: string | null;\n /**\n * Id of the instruction carried by the item's newest extraction (verified\n * by digest), or null. A host reprocess builds its own configuration and\n * cannot carry human corrections, so it drops the instruction exactly as\n * it drops a split.\n */\n instructionInEffect: string | null;\n }> {\n const item = await this.item(itemId, 'read');\n const analyses = (\n await this.rows(this.db, 'intake_analyses', 'item_id=?', [itemId])\n ).sort((a, b) => Number(b.revision) - Number(a.revision));\n const generation = analyses.find(\n (row) =>\n ['completed', 'partial'].includes(String(row.state)) &&\n row.current_attempt_id &&\n object(object(row.data).configuration).stage === 'interpret',\n );\n let failure: IntakeFailure | 'not_started' | null = null;\n let reinterpreting = false;\n if (generation) {\n const later = await this.laterWork(\n this.db,\n item,\n Number(generation.revision),\n );\n failure = later.failure;\n reinterpreting = later.phase === 'in_flight';\n } else {\n const latest = analyses[0];\n reinterpreting = ['queued', 'running'].includes(String(latest?.state));\n if (\n latest &&\n String(latest.state) === 'needs_attention' &&\n latest.current_attempt_id\n ) {\n const [attempt] = await this.rows(\n this.db,\n 'intake_analysis_attempts',\n 'id=? AND item_id=?',\n [latest.current_attempt_id, itemId],\n );\n if (attempt?.safe_error && failures.has(String(attempt.safe_error)))\n failure = String(attempt.safe_error) as IntakeFailure;\n }\n }\n const newestExtraction = analyses.find(\n (row) => object(object(row.data).configuration).stage !== 'interpret',\n );\n const carried = newestExtraction\n ? object(object(newestExtraction.data).configuration).reviewerInstruction\n : undefined;\n const instructionInEffect = carried\n ? reviewerInstructionView(carried).id\n : null;\n await this.item(itemId, 'read');\n return {\n revision: Number(item.analysis_revision),\n processingState: String(item.processing_state),\n failure,\n reinterpreting,\n instructionInEffect,\n generationAttemptId: generation\n ? String(generation.current_attempt_id)\n : null,\n };\n }\n /** Immutable instruction history, newest first. History is never deleted. */\n async listReviewerInstructions(\n itemId: string,\n ): Promise<ReviewerInstruction[]> {\n await this.item(itemId, 'read');\n const history = await this.recordedInstructions(this.db, itemId);\n await this.item(itemId, 'read');\n return history;\n }\n private async recordedInstructions(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<ReviewerInstruction[]> {\n const rows = await this.rows(db, 'intake_analyses', 'item_id=?', [itemId]);\n const seen = new Set<string>();\n const history: ReviewerInstruction[] = [];\n for (const row of rows.sort(\n (a, b) => Number(b.revision) - Number(a.revision),\n )) {\n const configuration = object(object(row.data).configuration);\n // Only the authenticated mint writes an extraction-stage record; interpret\n // copies are verified against it separately and never define history.\n if (\n configuration.stage === 'interpret' ||\n !configuration.reviewerInstruction\n )\n continue;\n const instruction = reviewerInstructionView(\n configuration.reviewerInstruction,\n );\n if (seen.has(instruction.id)) continue;\n seen.add(instruction.id);\n history.push(instruction);\n }\n return history;\n }\n /** Allocate a fenced attempt; active leases cannot be stolen before expiry. */\n async claimAnalysis(\n itemId: string,\n revision: number,\n workerId: string,\n ): Promise<AnalysisLease | null> {\n integer(revision);\n nonempty(workerId);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (\n item.cancelled ||\n item.receipt_state !== 'ready' ||\n Number(item.analysis_revision) !== revision ||\n // A resolved item is terminal; its provider is never called again.\n (await this.rows(db, 'intake_dispositions', 'item_id=?', [itemId]))\n .length\n )\n return null;\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, revision],\n );\n if (\n !analysis ||\n ['completed', 'partial'].includes(String(analysis.state))\n )\n return null;\n const limits = object(\n object(item.data).limits,\n ) as unknown as IntakeLimits;\n const attempts = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'analysis_id=?',\n [analysis.id],\n );\n const prior = attempts.find((a) => a.id === analysis.current_attempt_id);\n if (\n prior?.state === 'running' &&\n persistedDate(prior.lease_until) > this.now()\n )\n return null;\n if (Number(analysis.attempt_number) >= limits.maxAttempts) {\n if (prior?.state === 'running')\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='needs_attention',safe_error='limit' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n prior.id,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n analysis.id,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=? AND analysis_revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n revision,\n );\n return null;\n }\n if (prior && ['running', 'queued'].includes(String(prior.state)))\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n prior.id,\n );\n const fence = Number(analysis.fence) + 1;\n const attempt = Number(analysis.attempt_number) + 1;\n const token = randomUUID();\n const [row] = await this.insert(db, 'intake_analysis_attempts', {\n item_id: itemId,\n analysis_id: analysis.id,\n attempt_number: attempt,\n fence,\n state: 'running',\n lease_token: token,\n lease_until: new Date(\n this.now().getTime() + limits.leaseMs,\n ).toISOString(),\n output_digest: '',\n safe_error: '',\n confidence: null,\n data: canonical({\n workerId,\n startedAt: this.now().toISOString(),\n limits,\n }),\n });\n await db.query(\n \"UPDATE intake_analyses SET fence=?,attempt_number=?,current_attempt_id=?,state='running' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n fence,\n attempt,\n row.id,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n analysis.id,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='running' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n return {\n itemId,\n analysisId: String(analysis.id),\n attemptId: String(row.id),\n revision,\n fence,\n token,\n };\n });\n }\n private async completedAnalysisSnapshot(\n db: DatabaseInterface,\n itemId: string,\n attemptId: string | undefined,\n current: boolean,\n ): Promise<CompletedAnalysisSnapshot> {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (item.cancelled) throw new Error('Analysis unavailable');\n if (attemptId === undefined) {\n if (!current) throw new Error('Historical attempt required');\n const [latest] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND revision=?',\n [itemId, item.analysis_revision],\n );\n if (!latest?.current_attempt_id) throw new Error('Analysis unavailable');\n attemptId = String(latest.current_attempt_id);\n }\n\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'item_id=? AND id=?',\n [itemId, attemptId],\n );\n if (\n !attempt ||\n !['completed', 'partial'].includes(String(attempt.state)) ||\n !attempt.output_digest\n )\n throw new Error('Analysis unavailable');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'item_id=? AND id=?',\n [itemId, attempt.analysis_id],\n );\n if (\n !analysis ||\n analysis.current_attempt_id !== attemptId ||\n (current && Number(item.analysis_revision) !== Number(analysis.revision))\n )\n throw new Error('Analysis unavailable');\n const data = object(analysis.data);\n const configuration = object(data.configuration);\n if (\n !Array.isArray(data.inputs) ||\n !data.inputs.length ||\n digest({ inputs: data.inputs, configuration }) !==\n analysis.input_digest ||\n digest(configuration) !== data.configDigest\n )\n throw new Error('Analysis input integrity');\n const resultData = object(attempt.data);\n const result = {\n status: resultData.status,\n provider: resultData.provider,\n model: resultData.model,\n version: resultData.version,\n output: resultData.output,\n usage: resultData.usage,\n ...(Object.hasOwn(resultData, 'error')\n ? { error: resultData.error }\n : {}),\n ...(Object.hasOwn(resultData, 'confidence')\n ? { confidence: resultData.confidence }\n : {}),\n } as AnalysisOutput;\n if (\n result.status !== attempt.state ||\n digest(result) !== attempt.output_digest\n )\n throw new Error('Analysis output integrity');\n const evidence: IntakeEvidenceDTO[] = [];\n for (const input of data.inputs) {\n const frozen = object(input);\n const [row] = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [itemId, frozen.id],\n );\n if (!row || row.content_hash !== frozen.hash)\n throw new Error('Analysis input integrity');\n evidence.push({\n id: String(row.id),\n partId: String(row.part_id),\n parentEvidenceId: row.parent_evidence_id\n ? String(row.parent_evidence_id)\n : null,\n mediaType: String(row.media_type),\n contentHash: String(row.content_hash),\n byteLength: Number(row.byte_length),\n });\n }\n if (new Set(evidence.map((entry) => entry.id)).size !== evidence.length)\n throw new Error('Analysis input integrity');\n await this.item(itemId, 'process', db);\n return structuredClone({\n itemId,\n attemptId,\n revision: Number(analysis.revision),\n inputDigest: String(analysis.input_digest),\n outputDigest: String(attempt.output_digest),\n evidenceDigest: digest(data.inputs),\n configuration,\n evidence,\n result,\n });\n }\n /** Detached successful current revision; always current-scope/process authorized. */\n async getCompletedAnalysis(\n itemId: string,\n attemptId?: string,\n ): Promise<CompletedAnalysisSnapshot> {\n const snapshot = await this.tx((db) =>\n this.completedAnalysisSnapshot(db, itemId, attemptId, true),\n );\n await this.point('analysis:snapshot-read');\n const read = async (db: DatabaseInterface) => {\n const current = await this.completedAnalysisSnapshot(\n db,\n itemId,\n snapshot.attemptId,\n true,\n );\n if (\n current.inputDigest !== snapshot.inputDigest ||\n current.outputDigest !== snapshot.outputDigest\n )\n throw new Error('Analysis changed');\n return current;\n };\n if (snapshot.configuration.stage === 'interpret')\n return (await this.proposalReader())[generationSnapshotRead](\n itemId,\n (work) => this.tx(work),\n read,\n );\n return this.tx(read);\n }\n /** Historical source is readable only through its frozen pin on a live generation lease. */\n async getGenerationInput(lease: AnalysisLease) {\n const generation = await this.getAnalysisInput(lease);\n const configuration = generation.configuration;\n const pin = object(object(configuration.proposals).source);\n if (\n configuration.stage !== 'interpret' ||\n typeof pin.attemptId !== 'string'\n )\n throw new Error('Invalid generation source');\n const source = await this.tx((db) =>\n this.completedAnalysisSnapshot(\n db,\n lease.itemId,\n String(pin.attemptId),\n false,\n ),\n );\n for (const key of [\n 'attemptId',\n 'revision',\n 'inputDigest',\n 'outputDigest',\n 'evidenceDigest',\n ] as const)\n if (pin[key] !== source[key])\n throw new Error('Generation source changed');\n if (\n source.result.provider !== 'smrt-ingestion-extraction' ||\n source.configuration.stage === 'interpret' ||\n source.revision !== generation.revision - 1 ||\n digest(configuration.humanCorrection ?? null) !==\n digest(source.configuration.humanCorrection ?? null) ||\n digest(configuration.reviewerInstruction ?? null) !==\n digest(source.configuration.reviewerInstruction ?? null) ||\n digest(\n generation.evidence.map((entry) => ({\n id: entry.id,\n hash: entry.contentHash,\n })),\n ) !== source.evidenceDigest\n )\n throw new Error('Generation evidence changed');\n await this.getAnalysisInput(lease);\n return { generation, source };\n }\n /** Reload immutable inputs only through the current live processing lease. */\n async getAnalysisInput(lease: AnalysisLease): Promise<{\n revision: number;\n attemptId: string;\n fence: number;\n inputDigest: string;\n maxOutputBytes: number;\n configuration: Record<string, unknown>;\n evidence: IntakeEvidenceDTO[];\n }> {\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n throw new Error('Analysis lease unavailable');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=? AND item_id=?',\n [lease.attemptId, lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n !attempt ||\n Number(analysis.revision) !== lease.revision ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence ||\n Number(attempt.fence) !== lease.fence ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n throw new Error('Analysis lease unavailable');\n const data = object(analysis.data);\n const configuration = object(data.configuration);\n if (\n !Array.isArray(data.inputs) ||\n !data.inputs.length ||\n digest({ inputs: data.inputs, configuration }) !==\n analysis.input_digest ||\n digest(configuration) !== data.configDigest\n )\n throw new Error('Analysis input integrity');\n const evidence: IntakeEvidenceDTO[] = [];\n for (const input of data.inputs) {\n const frozen = object(input);\n const [row] = await this.rows(\n db,\n 'intake_evidence',\n \"item_id=? AND id=? AND state='durable'\",\n [lease.itemId, frozen.id],\n );\n if (!row || row.content_hash !== frozen.hash)\n throw new Error('Analysis input integrity');\n evidence.push({\n id: String(row.id),\n partId: String(row.part_id),\n parentEvidenceId: row.parent_evidence_id\n ? String(row.parent_evidence_id)\n : null,\n mediaType: String(row.media_type),\n contentHash: String(row.content_hash),\n byteLength: Number(row.byte_length),\n });\n }\n if (new Set(evidence.map((entry) => entry.id)).size !== evidence.length)\n throw new Error('Analysis input integrity');\n return {\n revision: lease.revision,\n attemptId: lease.attemptId,\n fence: lease.fence,\n inputDigest: String(analysis.input_digest),\n maxOutputBytes: Number(object(object(item.data).limits).maxOutputBytes),\n configuration,\n evidence,\n };\n });\n }\n /** Publish once, only through the current unexpired fence and captured scope. */\n async completeAnalysis(\n lease: AnalysisLease,\n output: AnalysisOutput,\n ): Promise<boolean> {\n if (\n !['completed', 'partial', 'failed', 'needs_attention'].includes(\n output.status,\n ) ||\n !output.provider ||\n !output.model ||\n !output.version ||\n (output.error && !failures.has(output.error))\n )\n throw new Error('Invalid analysis output');\n if (\n output.confidence !== undefined &&\n (!Number.isFinite(output.confidence) ||\n output.confidence < 0 ||\n output.confidence > 1)\n )\n throw new Error('Invalid confidence');\n for (const value of Object.values(output.usage))\n if (!Number.isFinite(value) || value < 0)\n throw new Error('Invalid usage');\n const serialized = canonical(output);\n const outputDigest = digest(output);\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n return false;\n const limits = object(\n object(item.data).limits,\n ) as unknown as IntakeLimits;\n if (Buffer.byteLength(serialized) > limits.maxOutputBytes)\n throw new Error('Analysis output budget exceeded');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence\n )\n return false;\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=?',\n [lease.attemptId, lease.analysisId],\n );\n if (\n !attempt ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n return false;\n const attemptData = {\n ...object(attempt.data),\n ...output,\n completedAt: this.now().toISOString(),\n };\n await db.query(\n 'UPDATE intake_analysis_attempts SET state=?,output_digest=?,safe_error=?,confidence=?,data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n outputDigest,\n output.error ?? '',\n output.confidence ?? null,\n canonical(attemptData),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.attemptId,\n );\n await db.query(\n 'UPDATE intake_analyses SET state=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.analysisId,\n );\n await db.query(\n 'UPDATE intake_items SET processing_state=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n output.status,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n );\n if (['completed', 'partial', 'needs_attention'].includes(output.status))\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n lease.revision,\n );\n return true;\n });\n }\n /** Terminal failure accounting without a provider payload. The fixed safe error\n * and lifecycle metadata are not charged to the provider-output byte ceiling. */\n async failAnalysis(\n lease: AnalysisLease,\n category: IntakeFailure,\n ): Promise<boolean> {\n if (!failures.has(category)) throw new Error('Invalid analysis failure');\n return this.tx(async (db) => {\n await this.lock(db, lease.itemId);\n const item = await this.item(lease.itemId, 'process', db);\n if (item.cancelled || Number(item.analysis_revision) !== lease.revision)\n return false;\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [lease.analysisId, lease.itemId],\n );\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'id=? AND analysis_id=? AND item_id=?',\n [lease.attemptId, lease.analysisId, lease.itemId],\n );\n if (\n !analysis ||\n !attempt ||\n Number(analysis.revision) !== lease.revision ||\n analysis.current_attempt_id !== lease.attemptId ||\n Number(analysis.fence) !== lease.fence ||\n Number(attempt.fence) !== lease.fence ||\n attempt.state !== 'running' ||\n attempt.lease_token !== lease.token ||\n persistedDate(attempt.lease_until) <= this.now()\n )\n return false;\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='needs_attention',safe_error=?,data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n category,\n canonical({\n ...object(attempt.data),\n completedAt: this.now().toISOString(),\n }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.attemptId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.analysisId,\n );\n await db.query(\n \"UPDATE intake_items SET processing_state='needs_attention' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND revision=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n lease.itemId,\n lease.revision,\n );\n return true;\n });\n }\n /** Cancel pending processing immediately; original receipt remains ready. */\n async cancel(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n await db.query(\n \"UPDATE intake_items SET cancelled=?,processing_state='cancelled' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n true,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded',safe_error='cancelled' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n });\n }\n /** Mint an action only on an explicit host intention, never during reanalysis. */\n async createAction(\n itemId: string,\n actionKey: string,\n provenance: Record<string, unknown>,\n ): Promise<string> {\n nonempty(actionKey);\n // Reviewer-selected actions are minted only by `startReviewerAction` under\n // reviewer authority; process authority must not forge routing provenance.\n if (\n actionKey.startsWith('reviewer:') ||\n (provenance as { origin?: unknown }).origin === 'reviewer-selected'\n )\n throw new Error('Reserved action provenance');\n const payload = canonical(provenance);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'process', db);\n if (item.cancelled) throw new Error('Intake cancelled');\n await this.assertUnresolved(db, itemId);\n const [existing] = await this.rows(\n db,\n 'intake_actions',\n 'item_id=? AND action_key=?',\n [itemId, actionKey],\n );\n if (existing) {\n if (canonical(object(existing.data)) !== payload)\n throw new Error('Action identity conflict');\n return String(existing.id);\n }\n const [action] = await this.insert(db, 'intake_actions', {\n item_id: itemId,\n action_key: actionKey,\n state: 'proposed',\n proposal_revision: 0,\n review_version: 0,\n execution_attempt: 0,\n fence: 0,\n result_digest: '',\n data: payload,\n });\n return String(action.id);\n });\n }\n /** Append a proposal pinned to a completed attempt. Policy/preview is host-owned. */\n async publishProposal(input: {\n itemId: string;\n actionId: string;\n attemptId: string;\n expectedRevision: number;\n binding: Record<string, unknown>;\n }): Promise<{ id: string; revision: number; bindingHash: string }> {\n canonical(input.binding);\n return this.tx(async (db) => {\n await this.lock(db, input.itemId);\n const item = await this.item(input.itemId, 'process', db);\n if (item.cancelled) throw new Error('Intake cancelled');\n await this.assertUnresolved(db, input.itemId);\n const [action] = await this.rows(\n db,\n 'intake_actions',\n 'item_id=? AND id=?',\n [input.itemId, input.actionId],\n );\n // A reviewer-selected action is revised only through the reviewer path\n // (`previewProposal`/`submitDecision`); process authority cannot rewrite it.\n if (action && object(action.data).origin === 'reviewer-selected')\n throw new Error('Reviewer-selected action requires review');\n const [attempt] = await this.rows(\n db,\n 'intake_analysis_attempts',\n 'item_id=? AND id=?',\n [input.itemId, input.attemptId],\n );\n if (\n !action ||\n !attempt ||\n !['completed', 'partial'].includes(String(attempt.state)) ||\n !attempt.output_digest\n )\n throw new Error('Invalid proposal evidence');\n if (\n Number(action.proposal_revision) !== input.expectedRevision ||\n ['succeeded', 'executing', 'outcome_unknown'].includes(\n String(action.state),\n )\n )\n throw new Error('Proposal conflict');\n const [analysis] = await this.rows(\n db,\n 'intake_analyses',\n 'id=? AND item_id=?',\n [attempt.analysis_id, input.itemId],\n );\n if (\n !analysis ||\n Number(analysis.revision) !== Number(item.analysis_revision)\n )\n throw new Error('Proposal conflict');\n const bindingHash = digest({\n binding: input.binding,\n attemptId: attempt.id,\n attemptDigest: attempt.output_digest,\n inputDigest: analysis.input_digest,\n });\n const revision = input.expectedRevision + 1;\n const [proposal] = await this.insert(db, 'intake_proposals', {\n item_id: input.itemId,\n action_id: input.actionId,\n analysis_id: attempt.analysis_id,\n analysis_attempt_id: attempt.id,\n revision,\n binding_hash: bindingHash,\n data: canonical({\n binding: input.binding,\n attemptDigest: attempt.output_digest,\n }),\n });\n await db.query(\n \"UPDATE intake_actions SET proposal_revision=?,state='waiting_review',review_version=review_version+1 WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n revision,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n input.actionId,\n );\n return { id: String(proposal.id), revision, bindingHash };\n });\n }\n /** Persist frozen plan structure; no expansion or apply authority is implied. */\n async appendPlan(\n itemId: string,\n planKey: string,\n revision: number,\n steps: Array<{ actionId: string; proposalRevision: number }>,\n definition: Record<string, unknown>,\n ): Promise<string> {\n nonempty(planKey);\n integer(revision);\n return this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'process', db);\n if (\n !steps.length ||\n new Set(steps.map((s) => s.actionId)).size !== steps.length\n )\n throw new Error('Invalid plan');\n for (const step of steps) {\n const [proposal] = await this.rows(\n db,\n 'intake_proposals',\n 'item_id=? AND action_id=? AND revision=?',\n [itemId, step.actionId, step.proposalRevision],\n );\n if (!proposal) throw new Error('Invalid plan binding');\n }\n const data = canonical({ steps, definition });\n const hash = digest({ steps, definition });\n const previous = await this.rows(\n db,\n 'intake_plans',\n 'item_id=? AND plan_key=?',\n [itemId, planKey],\n );\n const replay = previous.find((p) => Number(p.revision) === revision);\n if (replay) {\n if (replay.digest !== hash) throw new Error('Plan conflict');\n return String(replay.id);\n }\n if (\n revision !==\n Math.max(0, ...previous.map((p) => Number(p.revision))) + 1\n )\n throw new Error('Plan revision conflict');\n const [plan] = await this.insert(db, 'intake_plans', {\n item_id: itemId,\n plan_key: planKey,\n revision,\n digest: hash,\n data,\n });\n return String(plan.id);\n });\n }\n /** Revoke immediately and durably schedule deletion before external I/O. */\n async expire(itemId: string): Promise<void> {\n await this.scheduleExpiry(itemId);\n await this.repairDeletions();\n }\n private async scheduleExpiry(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n await this.item(itemId, 'delete', db, true);\n await db.query(\n \"UPDATE intake_items SET visibility='expired',processing_state='expired',cancelled=?,lease_token='',lease_until=NULL WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n true,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_evidence SET state='revoked' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_dispatches SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analyses SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_analysis_attempts SET state='superseded' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND state IN ('queued','running')\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n const originals = await this.rows(db, 'intake_evidence', 'item_id=?', [\n itemId,\n ]);\n const cleanup = originals\n .filter((e) => e.asset_id && e.source_uri)\n .map((e) => ({ assetId: e.asset_id, sourceUri: e.source_uri }));\n await this.insert(\n db,\n 'intake_deletions',\n { item_id: itemId, state: 'pending', data: canonical({ cleanup }) },\n 'tenant_id,item_id',\n );\n });\n }\n /** Retry privacy propagation. Minimal receipt/action identities remain replay-safe. */\n async repairDeletions(): Promise<number> {\n let completed = 0;\n const pending = await this.rows(this.db, 'intake_deletions');\n for (const intent of pending) {\n const itemId = String(intent.item_id);\n await this.item(itemId, 'delete', this.db, true);\n const evidence = await this.rows(\n this.db,\n 'intake_evidence',\n 'item_id=?',\n [itemId],\n );\n for (const row of evidence) {\n if (!row.asset_id) continue;\n const asset = await withTenant({ tenantId: this.scope.tenantId }, () =>\n this.options.assets.collection.get({ id: String(row.asset_id) }),\n );\n if (asset) {\n if (asset.tenantId !== this.scope.tenantId)\n throw new Error('Asset unavailable');\n await this.options.assets.store.remove(asset);\n }\n }\n // Retain cleanup locators after revocation: a killed stale writer may finish\n // storage I/O after owner deletion. Repeated sweeps remove those bytes too.\n const cleanup = object(intent.data).cleanup;\n if (Array.isArray(cleanup))\n for (const entry of cleanup) {\n const locator = object(entry);\n const asset = new Asset({ db: this.db });\n asset.id = String(locator.assetId);\n asset.tenantId = this.scope.tenantId;\n asset.sourceUri = String(locator.sourceUri);\n // Remove the object directly through the public store, even when its\n // database record has already been pruned.\n await this.options.assets.store.removeFile(asset);\n }\n if (intent.state === 'completed') {\n await this.releaseRedactedPrincipal(itemId);\n continue;\n }\n await this.options.purgeDerived({\n tenantId: this.scope.tenantId,\n itemId,\n });\n await this.point('deleted');\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const item = await this.item(itemId, 'delete', db, true);\n for (const table of TABLES.filter(\n (t) => t !== 'intake_items' && t !== 'intake_deletions',\n ))\n await db.query(\n `UPDATE ${table} SET data='{}' WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?`,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_evidence SET source_uri='',content_hash='',media_type='',byte_length=0 WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n // The owner and submitter links are payload provenance, not replay\n // identity: deletion severs them together with every other payload.\n // Digests over actor, owner, text or arguments would let a deleted\n // receipt be linked to its sender or a guessed text be confirmed.\n // Replay after redaction is already refused, so none are needed.\n for (const [table, column] of REDACTED_DIGESTS)\n await db.query(\n `UPDATE ${table} SET ${column}=? WHERE tenant_id=? AND confidential_scope_id=? AND item_id=?`,\n REDACTED,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_items SET data=?,trace_id='',submitter_id='',owner_key='',payload_digest=?,scope_digest=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n // The ceiling stays for later delete sweeps' host authorization;\n // execution.principalId stays only while an external action may\n // still be reconciled under it, and is released once it finishes.\n canonical({\n capturedCeiling: redactedCeiling(\n object(object(item.data).capturedCeiling ?? {}),\n await this.hasUnfinishedActions(db, itemId),\n ),\n }),\n REDACTED,\n REDACTED,\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n await db.query(\n \"UPDATE intake_deletions SET state='completed' WHERE tenant_id=? AND confidential_scope_id=? AND id=?\",\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n intent.id,\n );\n });\n completed++;\n }\n return completed;\n }\n private async hasUnfinishedActions(\n db: DatabaseInterface,\n itemId: string,\n ): Promise<boolean> {\n return (\n (\n await this.rows(\n db,\n 'intake_actions',\n `item_id=? AND state IN (${UNFINISHED_ACTION_STATES.map(() => '?').join(',')})`,\n [itemId, ...UNFINISHED_ACTION_STATES],\n )\n ).length > 0\n );\n }\n /** Later sweeps drop a principal retained for a reconciliation that has\n * since reached a final state. */\n private async releaseRedactedPrincipal(itemId: string): Promise<void> {\n await this.tx(async (db) => {\n await this.lock(db, itemId);\n const [item] = await this.rows(db, 'intake_items', 'id=?', [itemId]);\n if (!item || item.visibility === 'active') return;\n if (await this.hasUnfinishedActions(db, itemId)) return;\n const data = object(item.data);\n const ceiling = object(data.capturedCeiling ?? {});\n const released = redactedCeiling(ceiling, false);\n if (canonical(released) === canonical(ceiling)) return;\n await db.query(\n 'UPDATE intake_items SET data=? WHERE tenant_id=? AND confidential_scope_id=? AND id=?',\n canonical({ ...data, capturedCeiling: released }),\n this.scope.tenantId,\n this.scope.confidentialScopeId,\n itemId,\n );\n });\n }\n /** Run host-configured expiry policy and retry interrupted deletion propagation. */\n async sweepRetention(): Promise<number> {\n const expired = await this.rows(\n this.db,\n 'intake_items',\n \"visibility='active' AND expires_at<=?\",\n [this.now().toISOString()],\n );\n try {\n for (const item of expired) await this.scheduleExpiry(String(item.id));\n } catch (error) {\n // A later denial must not strand already committed deletion intents.\n // Preserve the scheduling failure even if cleanup also needs a retry.\n try {\n await this.repairDeletions();\n } catch {\n // Durable intents remain available to the next authorized repair.\n }\n throw error;\n }\n await this.repairDeletions();\n return expired.length;\n }\n}\n\nexport {\n HANDLER_ARGUMENT_ISSUE_LIMIT,\n HANDLER_ARGUMENT_PATH_LIMIT,\n} from './argument-issues.js';\nexport * from './extraction.js';\nexport type * from './feedback-contracts.js';\nexport {\n GenerationSnapshotStaleError,\n GenerationSourceStaleError,\n HandlerArgumentsInvalidError,\n ProposalsNotConfiguredError,\n} from './proposal-errors.js';\nexport type { HandlerArgumentIssue } from './review-dto.js';\nexport {\n createIntakeReviewHost,\n type IntakeReviewHostOptions,\n type RowEvidenceRequest,\n type RowEvidenceView,\n} from './review-host.js';\nexport {\n REVIEWER_INSTRUCTION_MAX_LENGTH,\n ReviewerInstructionInvalidError,\n ReviewerInstructionStaleError,\n reviewerInstructionView,\n} from './reviewer-instruction.js';\nexport * from './sources/index.js';\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAM,SACJ;AACF,IAAM,mBAAmB,IAAI,OAAO,QAAQ,GAAG;AAC/C,IAAM,oBAAoB,IAAI,OAAO,QAAQ,IAAI;AAM1C,SAAS,mBAAmB,OAAiC;CAClE,OACE,OAAO,UAAU,YACjB,MAAM,KAAK,CAAA,CAAE,SAAS,KACtB,MAAM,UAAA,OACN,CAAC,iBAAiB,KAAK,KAAK;AAEhC;AAOO,SAAS,kBAAkB,OAAoC;CACpE,IAAI,OAAO,UAAU,UAAU,OAAO,KAAA;CACtC,MAAM,OAAO,MAAM,QAAQ,mBAAmB,EAAE,CAAA,CAAE,KAAK;CACvD,OAAO,mBAAm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