@happyvertical/smrt-ingestion 0.55.12 → 0.55.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/FEEDBACK.md +6 -0
  2. package/PROPOSALS.md +8 -0
  3. package/README.md +26 -1
  4. package/REVIEW.md +31 -0
  5. package/agents/execution.md +2 -1
  6. package/dist/chunks/{execution-C7sTFXFU.js → execution-TWeIv0o-.js} +2 -2
  7. package/dist/chunks/{execution-C7sTFXFU.js.map → execution-TWeIv0o-.js.map} +1 -1
  8. package/dist/chunks/{feedback-C3OHD4sA.js → feedback-DmuvGO2o.js} +17 -7
  9. package/dist/chunks/feedback-DmuvGO2o.js.map +1 -0
  10. package/dist/chunks/{proposal-errors-z24VKWnQ.js → proposal-errors-BQjFXSOt.js} +15 -2
  11. package/dist/chunks/proposal-errors-BQjFXSOt.js.map +1 -0
  12. package/dist/execution.js +1 -1
  13. package/dist/feedback.d.ts +4 -0
  14. package/dist/feedback.d.ts.map +1 -1
  15. package/dist/index.js +2 -16
  16. package/dist/index.js.map +1 -1
  17. package/dist/manifest.json +3 -21
  18. package/dist/models.js +1 -1
  19. package/dist/models.js.map +1 -1
  20. package/dist/proposal-dto.d.ts +4 -0
  21. package/dist/proposal-dto.d.ts.map +1 -1
  22. package/dist/proposal-limits.d.ts +4 -0
  23. package/dist/proposal-limits.d.ts.map +1 -0
  24. package/dist/proposals.d.ts.map +1 -1
  25. package/dist/proposals.js +18 -22
  26. package/dist/proposals.js.map +1 -1
  27. package/dist/recipes.d.ts +2 -16
  28. package/dist/recipes.d.ts.map +1 -1
  29. package/dist/review-analysis.d.ts +10 -0
  30. package/dist/review-analysis.d.ts.map +1 -0
  31. package/dist/review-host.d.ts +26 -0
  32. package/dist/review-host.d.ts.map +1 -0
  33. package/dist/review-summary.d.ts +9 -0
  34. package/dist/review-summary.d.ts.map +1 -0
  35. package/dist/server.d.ts +1 -0
  36. package/dist/server.d.ts.map +1 -1
  37. package/dist/server.js +166 -3
  38. package/dist/server.js.map +1 -1
  39. package/dist/smrt-knowledge.json +20 -38
  40. package/package.json +17 -17
  41. package/dist/chunks/feedback-C3OHD4sA.js.map +0 -1
  42. package/dist/chunks/proposal-errors-z24VKWnQ.js.map +0 -1
@@ -3,21 +3,21 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-ingestion",
6
- "packageVersion": "0.55.12",
6
+ "packageVersion": "0.55.14",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "b79e475587ede8db65e5708b30cdd9ab3cf31f79dc519fed894c1e0aa8f2874b",
11
- "packageJson": "79986fa08003e24deb5b4992e8d7e932cd2028b9bb80b86d81a50508471b5f82",
10
+ "manifest": "04043738bc10d7456fd7a4223db6e19b4c0a621c978ce0e25361488fcbc0df7e",
11
+ "packageJson": "eadf9dd62fb9cc5a79a389f6c0990bd42d1e418858788aa1134fe78f70531a68",
12
12
  "agents": "dea14442054ec1de798cba9be1fbdd955f44b0e4672639cbf3db8101d290c1fb",
13
- "moduleDoc:agents/execution.md": "6153206adeea46fee1be57ccc01d171621ffb3dc3a754b3634bfe2ce367e8416",
14
- "moduleDoc:README.md": "810edf32fc35d12a6d1d4d8c506dca2c803f1db4bffd44201cb83993a1f06b25",
13
+ "moduleDoc:agents/execution.md": "b9ce254892a5dbd44c762b6f8b718d2f2705779d67b893418fc8fcc5677e2179",
14
+ "moduleDoc:README.md": "c7a4399b07fb5e2b8e26f4ef19364ca0a39046d4575813d8ec9386fb2c6aa241",
15
15
  "moduleDoc:EXTRACTION.md": "b735a25a7be75f3a13f3f9e92b0c25834c1394835c16ccd73a076d5720c14243",
16
- "moduleDoc:PROPOSALS.md": "3accad9430e917e65319b7b7708d5c1df277eea7eaa0490df913cf361e80b7bc",
17
- "moduleDoc:FEEDBACK.md": "795337ba256b486ecf0e836c4ad090d12f60c8c31dfb7c83155a8689da3d4dc5",
18
- "moduleDoc:REVIEW.md": "a64c652cf862e8c064a965231b1cf9a49c4494f9e98fbec171403221dfa8e4b4",
16
+ "moduleDoc:PROPOSALS.md": "15109f9a3f1fd5fb5c4390b4d8e691cdef7a2a35e7491791baeb30f602c342e9",
17
+ "moduleDoc:FEEDBACK.md": "1da3dcf033d60aaf3e67c9813efcfe58cb69d3c238aa4526c33edaa884357f06",
18
+ "moduleDoc:REVIEW.md": "ca3e7d9275d42ca3daabfdced0492df80770a438d007cc0d06608192cc841200",
19
19
  "agentSurface:src/test-support/execution.ts": "1df56aaf1a692d822ed45ecb7e50df7d6806977ff3c03f9eeaf171c64f496865",
20
- "agentSurface:src/test-support/proposals.ts": "260483ad7407191365bfe514f0d1625856f1001c11905299954508d885559497"
20
+ "agentSurface:src/test-support/proposals.ts": "ab60bd15118400974893041ead2d3e95276c35b4b355bb91b971668fd20aa1dd"
21
21
  },
22
22
  "exports": [
23
23
  ".",
@@ -1599,12 +1599,12 @@
1599
1599
  {
1600
1600
  "path": "agents/execution.md",
1601
1601
  "module": "execution",
1602
- "content": "# Review and execution integration\n\n`/execution` exports `IntakeExecutionService`, handler/host types, policy\nresolution, binding digests and `continueIntakeReview`. `IngestionService` exposes\nthese operations when its optional `execution` configuration is present. Its\nloader is lazy: importing `/server` alone does not import the principal stack.\n`/dto` exposes execution messages using type-only exports. No generated REST,\nCLI or MCP mutation endpoint is enabled; applications authenticate their own\nservice surface and create `IngestionScope` from the session.\n\n## Catalog and authority\n\nApplications supply a trusted `IntakeExecutionOptions.handlers` catalog.\n`OperationHandler` has qualified ID, immutable version, description, object JSON\nschemas for arguments/results, allowlisted `resultModels`, `validate`, `preview`,\na registered `{model, action, version}` operation and explicit effect/idempotency/\nopen-world capability declaration. Preview returns display, exact normalized\narguments and target revision preconditions. There is no arbitrary tool execution\nor expression evaluation. Reviewer display wraps application fields under `preview`\nand symbolic metadata under `dependencies`; plan steps additionally wrap that\nobject under `step` alongside the plan preview. Application display keys cannot\noverwrite framework metadata or be silently overwritten by it. A version change\nrequires a new preview and approval.\n`PlanHandler` references a real registered playbook key and resolved definition\nhash; expansion contains only ordered operation handlers and typed earlier-step\nresult references. Discovery/proposal generation consumes this catalog rather\nthan creating another registry. Semantic model output is never host configuration.\n\nAuthenticated receipt context captures `capturedCeiling.execution` with principal\nID and permission/handler/operation ceilings. The execution host's `authorize`\nresolves current grants and application/tenant/source/(optional request) policy\non the supplied executor, checking the active requester and confidential scope.\nLists intersect, budgets minimize, review requirements OR, and disabled policy\nwins. Policy versions must change when policy semantics change. Normal operation\nrequires human review; machine authorization requires explicit evaluated opt-ins\nat all three authority layers and remains separate provenance from human review.\nThe reference handlers always require review; no evaluation claim is made here.\n\n`mutationBoundary: 'serialized'` is an explicit host guarantee, not an inferred\nproperty of a permissions array: grant revocation must serialize with the supplied\ntransaction, or the owning mutation must revalidate under its own lock. The host\nmust implement that guarantee before enabling handlers. `assertTarget` similarly\nlocks current tenant/confidential ownership and revision against concurrent\nwriters using the supplied executor. The reference host demonstrates a scoped\nrow lock before public `Contents` reads. A current `PrincipalRun` intersects live\npermissions with the captured ceiling and checks the exact registered collection\noperation at every effect. No `runOnce` atomicity is assumed.\n\n## Durable review and effects\n\nPreview appends a proposal bound to exact analysis attempt/evidence, handler,\narguments, policy and target preconditions. Decision requests use unique durable\nrequest IDs; reusing an ID with changed content is rejected. First valid review\nwins under the item lock. Corrections append a new revision; reject/defer remain\nnon-executable. Plan corrections use re-expansion. Human decisions expire and\nlive authority is checked again before each step. Raw foundation proposals cannot\nbypass execution's schema, preview, evidence and approval verification.\n\nDatabase handlers must use `context.db` for every domain effect and must perform\nno external I/O. Domain result and successful execution commit together. A domain savepoint rolls failed effects\nback while preserving the item lock and atomically consuming the retry attempt. Completed\nactions survive job cleanup and evidence retention; expired originals leave a\nminimal result digest tombstone, preventing a second effect. Active result reads\nrecheck host visibility and result target ownership.\n\nExternal handlers reserve a stable action idempotency key before submission.\nTimeout, process death or ambiguous outcome requires reconciliation; an expired\nlease never means permission to resend. `reconcile` must return authoritative\n`succeeded`, `not_applied` or `unknown`. `not_applied` is safe only when the provider\ncan exclude a late acceptance of the original send; uncertainty stays `unknown`.\nThe same key is reused after a conclusive non-application. Cancellation prevents\npending work but cannot retract a send already issued. Applications must arrange\nprovider reconciliation before privacy retention removes the binding; a redacted\nunknown action fails closed and cannot automatically execute again.\n\nEach plan step has a stable action identity. Completed steps are immutable and\nreturn their original result. Symbolic record IDs bind to exact earlier proposal\nrevision, successful result digest/model and target revision; they cannot point\nacross items or form cycles. Failed dependent steps never repeat predecessors.\nThe plan preview and target preconditions are part of its digest and visible in\neach step review; changed preview/preconditions require a fresh review.\nAbort/continue follows the pinned public playbook definition, with fresh authority\nat every step.\n\n`continueIntakeReview` uses the existing jobs continuation context. Applications\ncreate tasks with owner, tenant and exact `{recordId, revision, inputKey}` binding\nand configure `authorizeMcpTask` to revalidate it. A continuation answer only wakes\nthe task; the service reloads the authoritative decision. Waiting persists without\nan occupied worker and survives runner restart.\n\n## Deployment and evidence\n\nApply normal manifest migrations before runtime. Execution imports the public\nagents/users principal stack, which registers profiles including `ProfileAsset`;\nexecution-enabled hosts must migrate their dependency graph (including profile\nasset joins used by asset deletion). `/server` receipt-only imports register none\nof these additional models. Content is not a runtime dependency of ingestion.\n`reference/handlers.ts` is an application/test fixture, excluded from published\nentries and declarations; importing it deliberately adds Content and its asset\njoins, whose migrations the application then owns. No runtime DDL is performed.\n\nReal SQLite and PostgreSQL execution suites exercise the public Content draft and\nattachment APIs, transaction rollback, actor/context denials, simultaneous applies\nand reviewers, retention replay, external process death and actual TaskRunner\nrestart. See the issue 3674 test matrix for the complete release evidence mapping.\n\n## Layered retention and request automation\n\nEvery automation-bearing policy layer, including an optional request layer, must\nmatch the evaluated version. An absent request automation block adds no evaluator\nrestriction; it cannot replace the three required application/tenant/source opt-ins.\n\nAuthorized execution-policy access monotonically narrows the existing intake\nexpiry to `min(existing expires_at, item.created_at + resolved retentionMs)`.\nThe anchor is receipt creation, never review, retry or replay time. A longer later\npolicy never extends a recorded deadline. This hard maximum applies to the whole\nintake item: the existing `sweepRetention` protocol removes retained originals and\nderivatives, preserving replay identities. No second expiry column or hidden clock\nis introduced, and no blob I/O occurs in an execution transaction.\n\nAt an observed expired deadline, execution reads/completions erase proposal,\ndecision, execution, plan, action and feedback payloads under the item lock. Review\nreads return existing identity/hash fields with `state: 'expired'` and empty\n`display`; completed action replay returns its digest-only tombstone. Failed writes, including ordinary validation/CAS/policy rejection and domain\nsavepoint rollback, cannot roll back an already-authorized retention ceiling or\nredaction. Restoring a recorded authorized maximum needs no new content-read grant;\nlater revocation cannot undo it. Initial denied authorization records no intent.\nCompleted replay checks the deadline again after target authorization\ncallbacks before returning cached content. Proposal publication and automatic\nauthorization also recheck after preview/evaluator callbacks, before publishing\nretained proposal or decision payloads. Unknown\nexternal outcomes remain unknown/reconcile-only, never eligible for blind resend.\n"
1602
+ "content": "# Review and execution integration\n\n`/execution` exports `IntakeExecutionService`, handler/host types, policy\nresolution, binding digests and `continueIntakeReview`. `IngestionService` exposes\nthese operations when its optional `execution` configuration is present. Its\nloader is lazy: importing `/server` alone does not import the principal stack.\n`/dto` exposes execution messages using type-only exports. No generated REST,\nCLI or MCP mutation endpoint is enabled; applications authenticate their own\nservice surface and create `IngestionScope` from the session.\n\n## Catalog and authority\n\nApplications supply a trusted `IntakeExecutionOptions.handlers` catalog.\n`OperationHandler` has qualified ID, immutable version, description, object JSON\nschemas for arguments/results, allowlisted `resultModels`, `validate`, `preview`,\na registered `{model, action, version}` operation and explicit effect/idempotency/\nopen-world capability declaration. Preview returns display, exact normalized\narguments and target revision preconditions. `normalizedArgs` must equal the\nsubmitted args exactly; default or normalize before submission, never in preview. There is no arbitrary tool execution\nor expression evaluation. Reviewer display wraps application fields under `preview`\nand symbolic metadata under `dependencies`; plan steps additionally wrap that\nobject under `step` alongside the plan preview. Application display keys cannot\noverwrite framework metadata or be silently overwritten by it. A version change\nrequires a new preview and approval.\n`PlanHandler` references a real registered playbook key and resolved definition\nhash; expansion contains only ordered operation handlers and typed earlier-step\nresult references. Discovery/proposal generation consumes this catalog rather\nthan creating another registry. Semantic model output is never host configuration.\n\nAuthenticated receipt context captures `capturedCeiling.execution` with principal\nID and permission/handler/operation ceilings. The execution host's `authorize`\nresolves current grants and application/tenant/source/(optional request) policy\non the supplied executor, checking the active requester and confidential scope.\nLists intersect, budgets minimize, review requirements OR, and disabled policy\nwins. Policy versions must change when policy semantics change. Normal operation\nrequires human review; machine authorization requires explicit evaluated opt-ins\nat all three authority layers and remains separate provenance from human review.\nThe reference handlers always require review; no evaluation claim is made here.\n\n`mutationBoundary: 'serialized'` is an explicit host guarantee, not an inferred\nproperty of a permissions array: grant revocation must serialize with the supplied\ntransaction, or the owning mutation must revalidate under its own lock. The host\nmust implement that guarantee before enabling handlers. `assertTarget` similarly\nlocks current tenant/confidential ownership and revision against concurrent\nwriters using the supplied executor. The reference host demonstrates a scoped\nrow lock before public `Contents` reads. A current `PrincipalRun` intersects live\npermissions with the captured ceiling and checks the exact registered collection\noperation at every effect. No `runOnce` atomicity is assumed.\n\n## Durable review and effects\n\nPreview appends a proposal bound to exact analysis attempt/evidence, handler,\narguments, policy and target preconditions. Decision requests use unique durable\nrequest IDs; reusing an ID with changed content is rejected. First valid review\nwins under the item lock. Corrections append a new revision; reject/defer remain\nnon-executable. Plan corrections use re-expansion. Human decisions expire and\nlive authority is checked again before each step. Raw foundation proposals cannot\nbypass execution's schema, preview, evidence and approval verification.\n\nDatabase handlers must use `context.db` for every domain effect and must perform\nno external I/O. Domain result and successful execution commit together. A domain savepoint rolls failed effects\nback while preserving the item lock and atomically consuming the retry attempt. Completed\nactions survive job cleanup and evidence retention; expired originals leave a\nminimal result digest tombstone, preventing a second effect. Active result reads\nrecheck host visibility and result target ownership.\n\nExternal handlers reserve a stable action idempotency key before submission.\nTimeout, process death or ambiguous outcome requires reconciliation; an expired\nlease never means permission to resend. `reconcile` must return authoritative\n`succeeded`, `not_applied` or `unknown`. `not_applied` is safe only when the provider\ncan exclude a late acceptance of the original send; uncertainty stays `unknown`.\nThe same key is reused after a conclusive non-application. Cancellation prevents\npending work but cannot retract a send already issued. Applications must arrange\nprovider reconciliation before privacy retention removes the binding; a redacted\nunknown action fails closed and cannot automatically execute again.\n\nEach plan step has a stable action identity. Completed steps are immutable and\nreturn their original result. Symbolic record IDs bind to exact earlier proposal\nrevision, successful result digest/model and target revision; they cannot point\nacross items or form cycles. Failed dependent steps never repeat predecessors.\nThe plan preview and target preconditions are part of its digest and visible in\neach step review; changed preview/preconditions require a fresh review.\nAbort/continue follows the pinned public playbook definition, with fresh authority\nat every step.\n\n`continueIntakeReview` uses the existing jobs continuation context. Applications\ncreate tasks with owner, tenant and exact `{recordId, revision, inputKey}` binding\nand configure `authorizeMcpTask` to revalidate it. A continuation answer only wakes\nthe task; the service reloads the authoritative decision. Waiting persists without\nan occupied worker and survives runner restart.\n\n## Deployment and evidence\n\nApply normal manifest migrations before runtime. Execution imports the public\nagents/users principal stack, which registers profiles including `ProfileAsset`;\nexecution-enabled hosts must migrate their dependency graph (including profile\nasset joins used by asset deletion). `/server` receipt-only imports register none\nof these additional models. Content is not a runtime dependency of ingestion.\n`reference/handlers.ts` is an application/test fixture, excluded from published\nentries and declarations; importing it deliberately adds Content and its asset\njoins, whose migrations the application then owns. No runtime DDL is performed.\n\nReal SQLite and PostgreSQL execution suites exercise the public Content draft and\nattachment APIs, transaction rollback, actor/context denials, simultaneous applies\nand reviewers, retention replay, external process death and actual TaskRunner\nrestart. See the issue 3674 test matrix for the complete release evidence mapping.\n\n## Layered retention and request automation\n\nEvery automation-bearing policy layer, including an optional request layer, must\nmatch the evaluated version. An absent request automation block adds no evaluator\nrestriction; it cannot replace the three required application/tenant/source opt-ins.\n\nAuthorized execution-policy access monotonically narrows the existing intake\nexpiry to `min(existing expires_at, item.created_at + resolved retentionMs)`.\nThe anchor is receipt creation, never review, retry or replay time. A longer later\npolicy never extends a recorded deadline. This hard maximum applies to the whole\nintake item: the existing `sweepRetention` protocol removes retained originals and\nderivatives, preserving replay identities. No second expiry column or hidden clock\nis introduced, and no blob I/O occurs in an execution transaction.\n\nAt an observed expired deadline, execution reads/completions erase proposal,\ndecision, execution, plan, action and feedback payloads under the item lock. Review\nreads return existing identity/hash fields with `state: 'expired'` and empty\n`display`; completed action replay returns its digest-only tombstone. Failed writes, including ordinary validation/CAS/policy rejection and domain\nsavepoint rollback, cannot roll back an already-authorized retention ceiling or\nredaction. Restoring a recorded authorized maximum needs no new content-read grant;\nlater revocation cannot undo it. Initial denied authorization records no intent.\nCompleted replay checks the deadline again after target authorization\ncallbacks before returning cached content. Proposal publication and automatic\nauthorization also recheck after preview/evaluator callbacks, before publishing\nretained proposal or decision payloads. Unknown\nexternal outcomes remain unknown/reconcile-only, never eligible for blind resend.\n"
1603
1603
  },
1604
1604
  {
1605
1605
  "path": "README.md",
1606
1606
  "module": "README",
1607
- "content": "# @happyvertical/smrt-ingestion\n\nDurable receipt, evidence, analysis attempts and action-journal foundations for\n[ADR 0004](../../docs/adr/0004-application-aware-ingestion.md).\n\nThe root, `/models` and `/dto` entry points are browser-safe. Import\n`IngestionService` from `/server` in trusted host code. Generated REST, CLI and\nMCP access to the persistence models is disabled; hosts expose authorized DTO\nmethods through their authenticated application transport.\n\nBefore starting a service, deploy the package manifest through the public s-m-r-t\nmigration APIs or `smrt db:migrate`. `assertReady()` only checks existing tables.\nSQLite and PostgreSQL are supported; other engines fail construction.\n\nA host supplies a database, AssetRuntime, authenticated tenant/actor/confidential\nscope, a live authorization callback, a registered jobs target, and an idempotent\n`purgeDerived` callback for host-owned previews, retrieval indexes and caches.\nThe authorization callback receives the captured ceiling and the current\ntransaction executor; it must intersect current grants with that ceiling. Never\nconstruct the scope, retention policy or budgets from incoming document labels.\n\n`receive` accepts bounded original byte buffers, with stable source part IDs,\nparent relationships and optional upstream identity/version. Source adapters own\nstreaming and upstream snapshot retrieval. Receipt identity is tenant + source +\ndelivery key; changing bytes or authenticated scope conflicts. Content equality\nin a different conversation does not deduplicate an arrival. The returned item\nID and version are safe acknowledgment data, never a storage URL.\n\nStorage intents contain a stable asset ID and a public AssetStore-planned URI\nbefore byte I/O. Preservation verifies existing bytes instead of replacing them.\nA receipt becomes ready only after every part is durable and its dispatch intent\ncommits. A source retries the same receive call after failure or lost\nacknowledgment. Hosts schedule `repairDispatches` after restart and periodically;\nit repairs missing/failed queue submissions through SmrtJobCollection. The host\njob restores the captured scope and calls the analysis lifecycle methods. Run\nTaskRunner with the `ingestion` queue enabled.\n\n`analyze` appends immutable input/configuration revisions. `claimAnalysis` uses\nleases, monotonic fences and attempt budgets; `completeAnalysis` rejects expired\nor superseded workers. Terminal attempt output/provenance is preserved. Queue\nsubmission budgets also stop repeated handler failures in visible\n`needs_attention`. Reprocessing does not mint actions. `createAction`,\n`publishProposal` and `appendPlan` persist explicit intentions and exact attempt\nbindings for the later review/execution layer. They do not approve or apply\nbusiness operations. Decision/execution/feedback models are persistence\nfoundations; policy, handler expansion, review and business apply belong to the\nlater epic children.\n\n`expire` revokes access and pending work before removing bytes and calling\n`purgeDerived`. Interrupted deletion is retried by `repairDeletions` and\n`sweepRetention`. Minimal receipt/action identities remain, including successful\naction result digests; all content-bearing journal payloads are redacted. Private\ncleanup locators remain in deletion tombstones so repeated sweeps can remove a\nlate stale writer's orphan bytes even after the asset owner row is gone. Source\nadapters must enforce their configured delivery-age cutoff; expired replay IDs\nnever become fresh work. Continue running the cleanup sweep for the retained\nstorage namespace. Upstream source mutation/deletion cannot change copied\noriginals; explicit privacy deletion revokes every ingestion-derived payload and\nrequires host cache/index purge.\n\nSee [EXTRACTION.md](EXTRACTION.md) for bounded extraction, lease-bound input\nsnapshots, provider isolation requirements and the extraction corpus.\n\nValidation commands are `pnpm test`, `pnpm test:postgres`, `pnpm test:providers`, `pnpm typecheck` and\n`pnpm build` (including built browser import inspection). The PostgreSQL lane\nrequires the repository's configured database service and never silently skips.\nThe provider lane exercises local SDK adapters and process isolation; it does not\nclaim live remote recognition quality. `pnpm test:components` and `pnpm test:e2e`\ncover the maintained review surface. `pnpm test:evaluation` checks repository\nevaluation tooling contracts; measured held-out quality requires a separately\nfrozen protocol and an approved aggregate provider budget. See the [behavior matrix](../../docs/test-matrix/3670-ingestion-foundation.md).\n\n## Authoritative review and execution\n\nConfigure `IngestionOptions.execution` for policy, immutable previews, authenticated\ndecisions and idempotent domain execution. See [execution integration](agents/execution.md)\nfor the public handler catalog, required host authorization/target locks, deployment\nmigrations and jobs continuation integration. The maintained application reference\nin `reference/handlers.ts` creates draft ContentDocuments and attaches retained\nevidence through public domain APIs; it is not a published runtime adapter.\n\n## Configured source adapters\n\nThe server entry exports `createSourceDeliveryHandler`, `EmailSourceAdapter`,\n`WatchFolderSourceAdapter`, and `createVendorWebhookHandler`. Construct a\n`SourceBinding` from authenticated host configuration: enabled flag, scoped\n`IngestionService`, stable source ID/version, captured authority ceiling,\nretention policy, allowed media types and receipt limits. Re-resolve this binding\nwhen grants/configuration change. Source payloads never supply authority.\n\nThe reference POST handler authenticates before reading bytes and requires\n`Idempotency-Key`. JSON accepts exactly `capturedAt` and one of `text`,\n`structured`, or `reference: { owner: 'asset'|'message', id, version }`.\nThe host's `snapshotReference` must authorize current ownership and return copied\nbytes; an absent snapshot fails rather than acknowledging a mutable locator.\nMultipart accepts one `file` plus `captureId` (equal to the idempotency key),\n`capturedAt`, `captureSource` (`camera`, `native_picker`, `audio`, `document`), and optional\nlowercase SHA-256 `sha256`. This reuses mobile's durable UUID Idempotency-Key,\nMIME-bearing file part and explicit capture metadata convention. Captures retain\noriginal bytes and a parent metadata evidence record. Configure both the wire\nlimit `maxRequestBytes` and receipt `maxBytes`/`maxParts`; include\n`application/json` in the media allowlist for capture/email metadata. Signature\nchecks cover PDF, TIFF, PNG/JPEG/WebP and WAV/Ogg/WebM/MP3/MP4 audio; signature\nacceptance promises preservation, not extraction support or codec validity.\n\nEmail is explicitly opt-in per configured account. `EmailSourceAdapter` takes a\n`readMessage` callback compatible with the messages owner's\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` snapshot.\nThe provider lookup is Gmail message ID, POP3 UIDL, or IMAP RFC Message-ID; it\nis separate from the delivery dedupe key. IMAP requires `{ folder, uidValidity,\nuid }`: the method selects the mailbox and verifies UIDVALIDITY and returned UID.\nAmbiguous sender IDs resolving to another UID fail explicitly. That method connects,\nfetches the full message including actual attachment bytes, copies the bytes,\nand disconnects. Metadata-only attachments fail explicitly. It never reads an\nattachment path supplied by a provider. A host lists provider deliveries using a\nstable account-specific locator (for IMAP include folder, UIDVALIDITY and UID),\nan explicit revision, and an opaque resumable checkpoint. Same locator/revision\nwith changed bytes conflicts; an explicit new revision creates a new receipt.\nDo not use sender-controlled RFC Message-ID as the sole transport identity.\n`receiveBatch` processes in order and stops at the first failure. The host owns\ndurable checkpoint storage and commits its `acknowledge` callback only after the\nadapter has received accepted/duplicate. If checkpoint persistence fails, retry\nreturns the original receipt. Message/thread/attachment relationships are copied;\ncredentials and arbitrary headers are excluded. The ordinary `syncFrom` metadata\nsync remains separate; `hasAttachments` is never proof of byte preservation.\n\nWatch-folder intake polls only an explicitly configured existing private local\ndirectory. Producers should close their files, preferably publishing with atomic\nrename. Two unchanged size/inode/mtime/ctime observations separated by\n`stabilityMs` are required, and the interval runs again after claim/restart.\nA private `.ingestion-claims/<UUID>/claim.json` intent is synced before atomically\nrenaming the original into that directory. Keep the directory on one filesystem,\nunder the host's ownership; symlink inputs are refused. A file descriptor still\nheld by an uncooperative producer can write after any stability window, so the\nproducer close/publish protocol is required for immutable input. Accepted or\nduplicate receipts move the entire claim to `.ingestion-processed`; do not delete\nclaims to retry. Polling recovers persisted UUIDs after process death, so receipt\nreplay deduplicates ready-without-ack. `failure.json` and poll results expose safe\ncategories while originals remain available. Intent directories without an\noriginal mean death before claim or a competing poll won; the producer original\nhas not been removed. Operators may remove these empty intents after confirming\nno active importer. Keep processed originals according to the host's retention\npolicy. This adapter does not watch arbitrary paths or start background loops.\n\nVendor webhooks use a host `verify(request, originalBytes)` callback after bounded\nraw-body reading. The callback must verify signature, delivery time/replay window\nand account ownership, then return trusted binding and durable delivery identity.\nNo vendor implementation or hardware driver is selected. All adapters invoke\nonly receipt preservation, never domain writes, AI tools or external actions.\n\nSee [PROPOSALS.md](PROPOSALS.md) for bounded application catalog discovery, durable\ninterpretation revisions, optional typed decisions and explicit generated preview.\n\n## Human review\n\nMount the `/svelte` inbox and review components through an authenticated host using\nthe browser-safe `IntakeReviewHost` DTO contract. See [REVIEW.md](REVIEW.md) for\nexact revision-bound callbacks, live evidence access, logical split corrections,\nassignment ownership, and the maintained upload-to-domain-result browser fixture.\n\nOptional explicit feedback and scoped example retrieval are documented in\n[FEEDBACK.md](FEEDBACK.md). Approval and execution outcomes remain separate from\ninterpretation correctness; routing policy adoption is explicit and versioned.\n\n## Recipe preview\n\n`ingestion.inbox` and `ingestion.review` declare the user-facing inbox and\nreview workflows for app discovery. The reference workflow and measured\nevaluation are now published, but the evaluation did not meet supported-reference\nquality gates and did not establish safety. Automation remains disabled. The\nrecipes do not configure a source or provider, expose generic CRUD routes, or\nenable automatic execution. Mount `IntakeInbox` and `IntakeReview` with an\nauthenticated `IntakeReviewHost`; [REVIEW.md](REVIEW.md) remains the source of\ntruth for its scoped callbacks and freshness checks. See the [adoption\nchecklist](../../docs/evaluation/3677-adoption.md) and [measured\nreport](../../docs/evaluation/3677-measured-evaluation.md) for the release\nlimits.\n\nThe recipe manifest registers those existing browser components as\n`/ingestion/inbox` and `/ingestion/review` routes for a host to mount. The route\nmetadata does not supply a host, source, provider, or demo fixture, and it does\nnot change the preview-only status. Both recipes declare `both` runtime: their\ncomponents render in a browser, while the authenticated review host and package\ndependency closure require a server.\n"
1607
+ "content": "# @happyvertical/smrt-ingestion\n\nDurable receipt, evidence, analysis attempts and action-journal foundations for\n[ADR 0004](../../docs/adr/0004-application-aware-ingestion.md).\n\nThe root, `/models` and `/dto` entry points are browser-safe. Import\n`IngestionService` from `/server` in trusted host code. Generated REST, CLI and\nMCP access to the persistence models is disabled; hosts expose authorized DTO\nmethods through their authenticated application transport.\n\nBefore starting a service, deploy the package manifest through the public s-m-r-t\nmigration APIs or `smrt db:migrate`. `assertReady()` only checks existing tables.\nSQLite and PostgreSQL are supported; other engines fail construction.\n\nA host supplies a database, AssetRuntime, authenticated tenant/actor/confidential\nscope, a live authorization callback, a registered jobs target, and an idempotent\n`purgeDerived` callback for host-owned previews, retrieval indexes and caches.\nThe authorization callback receives the captured ceiling and the current\ntransaction executor; it must intersect current grants with that ceiling. Never\nconstruct the scope, retention policy or budgets from incoming document labels.\n\n`receive` accepts bounded original byte buffers, with stable source part IDs,\nparent relationships and optional upstream identity/version. Source adapters own\nstreaming and upstream snapshot retrieval. Receipt identity is tenant + source +\ndelivery key; changing bytes or authenticated scope conflicts. Content equality\nin a different conversation does not deduplicate an arrival. The returned item\nID and version are safe acknowledgment data, never a storage URL.\n\nStorage intents contain a stable asset ID and a public AssetStore-planned URI\nbefore byte I/O. Preservation verifies existing bytes instead of replacing them.\nA receipt becomes ready only after every part is durable and its dispatch intent\ncommits. A source retries the same receive call after failure or lost\nacknowledgment. Hosts schedule `repairDispatches` after restart and periodically;\nit repairs missing/failed queue submissions through SmrtJobCollection. The host\njob restores the captured scope and calls the analysis lifecycle methods. Run\nTaskRunner with the `ingestion` queue enabled.\n\n`analyze` appends immutable input/configuration revisions. `claimAnalysis` uses\nleases, monotonic fences and attempt budgets; `completeAnalysis` rejects expired\nor superseded workers. Terminal attempt output/provenance is preserved. Queue\nsubmission budgets also stop repeated handler failures in visible\n`needs_attention`. Reprocessing does not mint actions. `createAction`,\n`publishProposal` and `appendPlan` persist explicit intentions and exact attempt\nbindings for the later review/execution layer. They do not approve or apply\nbusiness operations. Decision/execution/feedback models are persistence\nfoundations; policy, handler expansion, review and business apply belong to the\nlater epic children.\n\n`expire` revokes access and pending work before removing bytes and calling\n`purgeDerived`. Interrupted deletion is retried by `repairDeletions` and\n`sweepRetention`. Minimal receipt/action identities remain, including successful\naction result digests; all content-bearing journal payloads are redacted. Private\ncleanup locators remain in deletion tombstones so repeated sweeps can remove a\nlate stale writer's orphan bytes even after the asset owner row is gone. Source\nadapters must enforce their configured delivery-age cutoff; expired replay IDs\nnever become fresh work. Continue running the cleanup sweep for the retained\nstorage namespace. Upstream source mutation/deletion cannot change copied\noriginals; explicit privacy deletion revokes every ingestion-derived payload and\nrequires host cache/index purge.\n\nSee [EXTRACTION.md](EXTRACTION.md) for bounded extraction, lease-bound input\nsnapshots, provider isolation requirements and the extraction corpus.\n\nValidation commands are `pnpm test`, `pnpm test:postgres`, `pnpm test:providers`, `pnpm typecheck` and\n`pnpm build` (including built browser import inspection). The PostgreSQL lane\nrequires the repository's configured database service and never silently skips.\nThe provider lane exercises local SDK adapters and process isolation; it does not\nclaim live remote recognition quality. `pnpm test:components` and `pnpm test:e2e`\ncover the maintained review surface. `pnpm test:evaluation` checks repository\nevaluation tooling contracts; measured held-out quality requires a separately\nfrozen protocol and an approved aggregate provider budget. See the [behavior matrix](../../docs/test-matrix/3670-ingestion-foundation.md).\n\n## Authoritative review and execution\n\nConfigure `IngestionOptions.execution` for policy, immutable previews, authenticated\ndecisions and idempotent domain execution. See [execution integration](agents/execution.md)\nfor the public handler catalog, required host authorization/target locks, deployment\nmigrations and jobs continuation integration. The maintained application reference\nin `reference/handlers.ts` creates draft ContentDocuments and attaches retained\nevidence through public domain APIs; it is not a published runtime adapter.\n\n## Configured source adapters\n\nThe server entry exports `createSourceDeliveryHandler`, `EmailSourceAdapter`,\n`WatchFolderSourceAdapter`, and `createVendorWebhookHandler`. Construct a\n`SourceBinding` from authenticated host configuration: enabled flag, scoped\n`IngestionService`, stable source ID/version, captured authority ceiling,\nretention policy, allowed media types and receipt limits. Re-resolve this binding\nwhen grants/configuration change. Source payloads never supply authority.\n\nThe reference POST handler authenticates before reading bytes and requires\n`Idempotency-Key`. JSON accepts exactly `capturedAt` and one of `text`,\n`structured`, or `reference: { owner: 'asset'|'message', id, version }`.\nThe host's `snapshotReference` must authorize current ownership and return copied\nbytes; an absent snapshot fails rather than acknowledging a mutable locator.\nMultipart accepts one `file` plus `captureId` (equal to the idempotency key),\n`capturedAt`, `captureSource` (`camera`, `native_picker`, `audio`, `document`), and optional\nlowercase SHA-256 `sha256`. This reuses mobile's durable UUID Idempotency-Key,\nMIME-bearing file part and explicit capture metadata convention. Captures retain\noriginal bytes and a parent metadata evidence record. Configure both the wire\nlimit `maxRequestBytes` and receipt `maxBytes`/`maxParts`; include\n`application/json` in the media allowlist for capture/email metadata. Signature\nchecks cover PDF, TIFF, PNG/JPEG/WebP and WAV/Ogg/WebM/MP3/MP4 audio; signature\nacceptance promises preservation, not extraction support or codec validity.\n\nEmail is explicitly opt-in per configured account. `EmailSourceAdapter` takes a\n`readMessage` callback compatible with the messages owner's\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` snapshot.\nThe provider lookup is Gmail message ID, POP3 UIDL, or IMAP RFC Message-ID; it\nis separate from the delivery dedupe key. IMAP requires `{ folder, uidValidity,\nuid }`: the method selects the mailbox and verifies UIDVALIDITY and returned UID.\nAmbiguous sender IDs resolving to another UID fail explicitly. That method connects,\nfetches the full message including actual attachment bytes, copies the bytes,\nand disconnects. Metadata-only attachments fail explicitly. It never reads an\nattachment path supplied by a provider. A host lists provider deliveries using a\nstable account-specific locator (for IMAP include folder, UIDVALIDITY and UID),\nan explicit revision, and an opaque resumable checkpoint. Same locator/revision\nwith changed bytes conflicts; an explicit new revision creates a new receipt.\nDo not use sender-controlled RFC Message-ID as the sole transport identity.\n`receiveBatch` processes in order and stops at the first failure. The host owns\ndurable checkpoint storage and commits its `acknowledge` callback only after the\nadapter has received accepted/duplicate. If checkpoint persistence fails, retry\nreturns the original receipt. Message/thread/attachment relationships are copied;\ncredentials and arbitrary headers are excluded. The ordinary `syncFrom` metadata\nsync remains separate; `hasAttachments` is never proof of byte preservation.\n\nWatch-folder intake polls only an explicitly configured existing private local\ndirectory. Producers should close their files, preferably publishing with atomic\nrename. Two unchanged size/inode/mtime/ctime observations separated by\n`stabilityMs` are required, and the interval runs again after claim/restart.\nA private `.ingestion-claims/<UUID>/claim.json` intent is synced before atomically\nrenaming the original into that directory. Keep the directory on one filesystem,\nunder the host's ownership; symlink inputs are refused. A file descriptor still\nheld by an uncooperative producer can write after any stability window, so the\nproducer close/publish protocol is required for immutable input. Accepted or\nduplicate receipts move the entire claim to `.ingestion-processed`; do not delete\nclaims to retry. Polling recovers persisted UUIDs after process death, so receipt\nreplay deduplicates ready-without-ack. `failure.json` and poll results expose safe\ncategories while originals remain available. Intent directories without an\noriginal mean death before claim or a competing poll won; the producer original\nhas not been removed. Operators may remove these empty intents after confirming\nno active importer. Keep processed originals according to the host's retention\npolicy. This adapter does not watch arbitrary paths or start background loops.\n\nVendor webhooks use a host `verify(request, originalBytes)` callback after bounded\nraw-body reading. The callback must verify signature, delivery time/replay window\nand account ownership, then return trusted binding and durable delivery identity.\nNo vendor implementation or hardware driver is selected. All adapters invoke\nonly receipt preservation, never domain writes, AI tools or external actions.\n\nSee [PROPOSALS.md](PROPOSALS.md) for bounded application catalog discovery, durable\ninterpretation revisions, optional typed decisions and explicit generated preview.\n\n## Human review\n\nMount the `/svelte` inbox and review components through an authenticated host using\nthe browser-safe `IntakeReviewHost` DTO contract. See [REVIEW.md](REVIEW.md) for\nexact revision-bound callbacks, live evidence access, logical split corrections,\nassignment ownership, and the maintained upload-to-domain-result browser fixture.\n\nOptional explicit feedback and scoped example retrieval are documented in\n[FEEDBACK.md](FEEDBACK.md). Approval and execution outcomes remain separate from\ninterpretation correctness; routing policy adoption is explicit and versioned.\n\n## Recipe preview\n\n`ingestion.inbox` and `ingestion.review` declare the user-facing inbox and\nreview workflows for app discovery. The reference workflow and measured\nevaluation are now published, but the evaluation did not meet supported-reference\nquality gates and did not establish safety. Automation remains disabled. The\nrecipes do not configure a source or provider, expose generic CRUD routes, or\nenable automatic execution. Mount `IntakeInbox` and `IntakeReview` with an\nauthenticated `IntakeReviewHost`; [REVIEW.md](REVIEW.md) remains the source of\ntruth for its scoped callbacks and freshness checks. See the [adoption\nchecklist](../../docs/evaluation/3677-adoption.md) and [measured\nreport](../../docs/evaluation/3677-measured-evaluation.md) for the release\nlimits.\n\nThe recipe manifest registers those existing browser components as\n`/ingestion/inbox` and `/ingestion/review` routes for a host to mount. The route\nmetadata does not supply a host, source, provider, or demo fixture, and it does\nnot change the preview-only status. Neither recipe declares generic model\nnavigation: the ingestion records have no generated screens, so hosts use the\nauthenticated route surfaces instead. Both recipes declare `both` runtime: their\ncomponents render in a browser, while the authenticated review host and package\ndependency closure require a server.\n\n## First analysis and host constraints\n\n`receive` retains evidence and queues the initial dispatch, but does not choose\nan extraction configuration. Before a worker can analyze a new item, the host must\ncall `analyze(itemId, { stage: 'extract', extraction: { configurationRevision,\nlimits } }, requestId)`, then claim that returned revision and run `extractAnalysis`.\nUse a stable request ID for retries. `repairDispatches` repairs queue delivery;\nit does not supply the missing extraction request. After extraction, use\n`prepareGeneration` and `analyze` to request interpretation.\n\nRetention requires `replayUntil >= expiresAt`; an earlier replay deadline rejects\neven a fresh delivery as `expired`. The replay tombstone must outlive retained\nsource bytes. Set both deadlines explicitly before calling `receive`.\n\nHandler preview `normalizedArgs` must equal the submitted arguments exactly.\nIt is an integrity assertion, not a normalization hook: defaults or tidying must\nhappen before submitting args for preview, so review binds exactly what was sent.\n\nProposal limits must be positive safe integers. `maxHandlers`, `maxCandidates`\nand `maxSuggestions` are each capped at 20; `timeoutMs` is capped at 2147483647.\nInvalid limits are rejected when constructing `IngestionService`, before receipt\nor interpretation. See [REVIEW.md](REVIEW.md) for the published server review host.\n"
1608
1608
  },
1609
1609
  {
1610
1610
  "path": "EXTRACTION.md",
@@ -1614,17 +1614,17 @@
1614
1614
  {
1615
1615
  "path": "PROPOSALS.md",
1616
1616
  "module": "PROPOSALS",
1617
- "content": "# Application-aware proposal generation\n\n`@happyvertical/smrt-ingestion/proposals` is server-only. Configure\n`IngestionOptions.proposals` and the existing `execution.handlers` catalog.\nHandlers opt into discovery with `discovery.mediaTypes`, `references`, and an\noptional `candidates` callback. There is one catalog: the same operation or\nordered playbook adapter is discovered, validated, previewed, and later applied\nby the execution service. Generation never approves or applies.\n\n## Discovery and authority\n\n`listHandlers(itemId)` returns a bounded detached catalog. The owning execution\nservice checks the current principal, captured permissions/handler/operation\nceiling, policy, confidential scope, public registered operation facts, and\nordered playbook definition. Every configured provider must occur in the current\npolicy's `providers` allowlist. Missing grants remove handlers before model input.\nAn authorized catalog larger than the configured bound is rejected; the host must\nnarrow it explicitly instead of relying on silent truncation.\n\n`findCandidates({itemId,handlerId,handlerVersion,query,limit})` returns\n`{items,truncated}`. Its trusted handler callback receives `HandlerContext` with\nthe authorized transaction executor. Query by tenant and confidential scope\n**before** selecting, ranking, or building labels. Use a bounded query (often\n`limit + 1`) and report `hasMore`. The service projects candidate identity, model,\nrevision and label, then checks every target with the owning execution callback.\nThere are no hidden counts or pagination tokens. Truncated discovery forces\n`needs_review` and cannot enter generated preview.\n\nCompleted generation reload checks process authority, the current attempt, and\nowner/candidate visibility in the same final transaction. Database-backed grant\ncallbacks must use the supplied executor. The owning retention lifecycle encloses\nthat transaction so a denied read cannot roll back an authorized shorter privacy\nceiling; restoration starts only after the outer transaction has rolled back.\n\nCandidate callbacks perform bounded database reads only: no provider I/O, network,\nor domain mutations. Target locks and existing retention enforcement remain\nowned by execution. Hosts configure their database's statement deadlines; an\narbitrary trusted callback is not a sandbox. Each existing-record argument must\nbe a declared top-level `references` field of kind `candidate` with its qualified\nmodel, or `evidence`. Closed JSON argument schemas are required. The host owns\nthat declaration and its target authorization semantics.\n\n## Durable stages\n\n1. Complete extraction through the existing analysis ledger.\n2. Call `prepareGeneration(itemId, extractionAttemptId)`. It reads the current\n completed/partial immutable extraction and returns configuration with\n `stage: 'interpret'`, pinned source attempt/revision/input/output/evidence\n digests, prompt/configuration/catalog/provider versions, limits and thresholds.\n3. Pass that configuration to `analyze(itemId, configuration, requestKey)` and\n claim its new revision with `claimAnalysis`.\n4. The host's existing job callback routes on the frozen `configuration.stage`:\n extraction invokes `extractAnalysis`; interpretation invokes\n `generateProposals(lease)`.\n5. Reload the current completed generation using `getCompletedAnalysis(itemId)`,\n or pass an explicit attempt ID to additionally reject stale client state.\n Queued/running revisions never return an older completed attempt.\n\nA generation revision does not rewrite terminal extraction. Reprocessing starts\nwith a new extraction revision, followed by interpretation, while the host keeps\nthe same business intention keys. An interrupted still-current generation lease\ncan be retried; terminal generation output remains immutable. `getGenerationInput`\nreads historical extraction only through the current generation lease and its\nfrozen source pin. It verifies same-item scope, immutable hashes, durable evidence,\nand current process permission before returning detached data. The source must be\nthe immediately preceding revision, so an intervening reprocess invalidates a\nprepared generation. Completed generation reads additionally recheck current\ncatalog and target visibility before disclosing persisted candidate labels.\nExpired, cancelled, revoked, retried or superseded workers cannot read or publish late output. The\ncurrent lease and each offered handler/candidate are rechecked immediately before\neach outbound generative/decision boundary and before publication.\n\n## Providers and validation\n\n`createSDKProposalGenerator(client, identity, {maxTokens,timeoutMs})` uses an\nexisting AI SDK `chat` client. It sends a fixed system instruction and separate\nJSON evidence/catalog data, requests JSON, supplies cancellation and bounds, uses\nno tools or continuation, and rejects known truncation or tool calls,\nunexpected models, malformed JSON and oversized output. Configure SDK clients\nwithout automatic retry that would bypass application boundary checks. The\nadapter's public identity is exactly provider/model/version; credentials and raw\nprovider errors are never provenance.\n\nA trusted custom `ProposalGenerator` must likewise honor cancellation, bound its\nresponse, and explicitly declare validated `complete` or `unknown` completion.\nThe SDK currently normalizes missing/unknown finish reasons to `stop`\n([owning SDK follow-up](https://github.com/happyvertical/sdk/issues/1381)), so its\nadapter conservatively declares `unknown`, persisted as\n`generation_completion_unknown`. Otherwise valid suggestions remain available\nfor human preview; automatic eligibility always remains false. The service\ndeadline aborts requests and prevents late publication; it does not claim to terminate computation at a remote\nprovider or isolate native allocations. Extractor process limits remain separate.\n\nModel output can contain only offered handler versions, schema-valid arguments,\nretained evidence locations and offered alternative handler/candidate keys.\nCandidate IDs must occur in the offered set, and evidence IDs in retained source\nresults. Unknown enums, invented IDs, extra authority/tool/approval fields and\nmalformed structures fail closed. Missing required top-level fields are retained\nas `missingFields`, with `needs_review`; values are never invented to satisfy a\nschema. Observed page/time/source granularity is preserved. Logical scan splits\nuse `proposeDocumentSplits`; originals and hashes remain intact.\n\n`createSDKProposalDecisionClient(client)` adapts an existing SDK client’s optional\ncapability without changing its errors or protocol. Optional `decision` uses public core `executeDecision` and the existing SDK\npredicate, choice, score and batch contracts. Supported-effect predicates,\nhandler classification, candidate entity matching, and action ambiguity/risk\nare distinct questions. Their validated probabilities and provenance are stored\nseparately from generative provenance and unknown OCR certainty. The complete\nserialized decision request, including suggestions and questions, must fit the\nminimum configured/current policy byte ceiling before capability probing and\nagain before deciding. A policy change between these boundaries fails closed.\nTies, support probability or selected-handler confidence below\n`minimumDecisionProbability`, and actually incomplete extraction require review.\nUnknown provider\ncompletion metadata is preserved as `source_completion_unknown`; it does not\nblock otherwise schema-valid **human** preview or imply completeness. Automatic\naction eligibility remains false. An unconfigured decision path\nis recorded explicitly. Configured errors produce a durable safe failure outcome;\nthey never silently switch to a generative decision fallback.\n\nOutput records zero, one or multiple suggestions, alternatives, missing fields,\nsource links, proposed splits, versions, allowlisted usage, warnings and explicit\n`unknown`, `ambiguous`, `no_action`, `needs_review` or `provider_error` outcomes.\n`automaticActionEligible` is always false. Provider input/output and the complete\nserialized persisted envelope are bounded by configuration, live policy and the\nreceipt ceiling. Oversized output becomes a bounded review/limit result; when\nno safe envelope fits, the owning service records fixed `failAnalysis` metadata\noutside the provider payload budget without retaining provider output.\n\n## Explicit preview and stable intentions\n\nThe host chooses persisted suggestion indexes and calls:\n\n```ts\nawait service.previewGeneratedProposals({\n itemId,\n attemptId: generationAttemptId,\n selections: [{\n index: 0,\n intentionKey: 'document:meeting-2026-10-09',\n expectedRevision: 0,\n requestId: 'review-request-1',\n }],\n});\n```\n\n`intentionKey` is the host's stable business-intention identity across generation\nrevisions. Never derive a fresh key from model output, suggestion order or a retry.\nSelections must reference current persisted validated `ready_for_review` output.\nEach batch requires distinct suggestion indexes and intention keys; duplicate\nindexes are rejected before any operation or plan preview is written.\nThe service rechecks current catalog/schema/target/source provenance, then calls\nthe existing operation or plan preview. Each result still requires the ordinary\nhuman review and execution APIs. Reprocessing creates no new business identity;\nsuccessful-action replay protection stays with execution.\n\n## Evidence and limits\n\nThe test matrix is `docs/test-matrix/3673-ingestion-proposals.md`. SQLite and real\nPostgreSQL suites exercise authority, revisions, abstention, hostile output,\ncompound proposals, split provenance and reviewed domain effects. The upload\nreference composes authenticated multipart delivery of a generated embedded-text\nPDF through the actual packaged PDF child, durable interpretation, and the existing\nordered ContentDocument draft/retained-asset plan. It checks duplicate delivery,\nunauthenticated and foreign-tenant denial, explicit approval of both steps,\nidempotent execution replay, page provenance, and unchanged original bytes.\nThe compound-email case uses a declared messages-owner snapshot fixture.\n\nLocal HTTP fixtures execute the actual AI SDK transport and cancellation contract.\nGenerative responses and the separate injected PDF split boundaries establish\ndeterministic orchestration, not model accuracy or OCR quality. No held-out routing\nevaluation or automatic approval is claimed. Missing/unknown AI completion remains\nexplicit under [SDK #1381](https://github.com/happyvertical/sdk/issues/1381).\n"
1617
+ "content": "# Application-aware proposal generation\n\n`@happyvertical/smrt-ingestion/proposals` is server-only. Configure\n`IngestionOptions.proposals` and the existing `execution.handlers` catalog.\nHandlers opt into discovery with `discovery.mediaTypes`, `references`, and an\noptional `candidates` callback. There is one catalog: the same operation or\nordered playbook adapter is discovered, validated, previewed, and later applied\nby the execution service. Generation never approves or applies.\n\n## Discovery and authority\n\n`listHandlers(itemId)` returns a bounded detached catalog. The owning execution\nservice checks the current principal, captured permissions/handler/operation\nceiling, policy, confidential scope, public registered operation facts, and\nordered playbook definition. Every configured provider must occur in the current\npolicy's `providers` allowlist. Missing grants remove handlers before model input.\nAn authorized catalog larger than the configured bound is rejected; the host must\nnarrow it explicitly instead of relying on silent truncation.\n\n`findCandidates({itemId,handlerId,handlerVersion,query,limit})` returns\n`{items,truncated}`. Its trusted handler callback receives `HandlerContext` with\nthe authorized transaction executor. Query by tenant and confidential scope\n**before** selecting, ranking, or building labels. Use a bounded query (often\n`limit + 1`) and report `hasMore`. The service projects candidate identity, model,\nrevision and label, then checks every target with the owning execution callback.\nThere are no hidden counts or pagination tokens. Truncated discovery forces\n`needs_review` and cannot enter generated preview.\n\nCompleted generation reload checks process authority, the current attempt, and\nowner/candidate visibility in the same final transaction. Database-backed grant\ncallbacks must use the supplied executor. The owning retention lifecycle encloses\nthat transaction so a denied read cannot roll back an authorized shorter privacy\nceiling; restoration starts only after the outer transaction has rolled back.\n\nCandidate callbacks perform bounded database reads only: no provider I/O, network,\nor domain mutations. Target locks and existing retention enforcement remain\nowned by execution. Hosts configure their database's statement deadlines; an\narbitrary trusted callback is not a sandbox. Each existing-record argument must\nbe a declared top-level `references` field of kind `candidate` with its qualified\nmodel, or `evidence`. Closed JSON argument schemas are required. The host owns\nthat declaration and its target authorization semantics.\n\n## Durable stages\n\n1. Complete extraction through the existing analysis ledger.\n2. Call `prepareGeneration(itemId, extractionAttemptId)`. It reads the current\n completed/partial immutable extraction and returns configuration with\n `stage: 'interpret'`, pinned source attempt/revision/input/output/evidence\n digests, prompt/configuration/catalog/provider versions, limits and thresholds.\n3. Pass that configuration to `analyze(itemId, configuration, requestKey)` and\n claim its new revision with `claimAnalysis`.\n4. The host's existing job callback routes on the frozen `configuration.stage`:\n extraction invokes `extractAnalysis`; interpretation invokes\n `generateProposals(lease)`.\n5. Reload the current completed generation using `getCompletedAnalysis(itemId)`,\n or pass an explicit attempt ID to additionally reject stale client state.\n Queued/running revisions never return an older completed attempt.\n\nA generation revision does not rewrite terminal extraction. Reprocessing starts\nwith a new extraction revision, followed by interpretation, while the host keeps\nthe same business intention keys. An interrupted still-current generation lease\ncan be retried; terminal generation output remains immutable. `getGenerationInput`\nreads historical extraction only through the current generation lease and its\nfrozen source pin. It verifies same-item scope, immutable hashes, durable evidence,\nand current process permission before returning detached data. The source must be\nthe immediately preceding revision, so an intervening reprocess invalidates a\nprepared generation. Completed generation reads additionally recheck current\ncatalog and target visibility before disclosing persisted candidate labels.\nExpired, cancelled, revoked, retried or superseded workers cannot read or publish late output. The\ncurrent lease and each offered handler/candidate are rechecked immediately before\neach outbound generative/decision boundary and before publication.\n\n## Providers and validation\n\n`createSDKProposalGenerator(client, identity, {maxTokens,timeoutMs})` uses an\nexisting AI SDK `chat` client. It sends a fixed system instruction and separate\nJSON evidence/catalog data, requests JSON, supplies cancellation and bounds, uses\nno tools or continuation, and rejects known truncation or tool calls,\nunexpected models, malformed JSON and oversized output. Configure SDK clients\nwithout automatic retry that would bypass application boundary checks. The\nadapter's public identity is exactly provider/model/version; credentials and raw\nprovider errors are never provenance.\n\nA trusted custom `ProposalGenerator` must likewise honor cancellation, bound its\nresponse, and explicitly declare validated `complete` or `unknown` completion.\nThe SDK currently normalizes missing/unknown finish reasons to `stop`\n([owning SDK follow-up](https://github.com/happyvertical/sdk/issues/1381)), so its\nadapter conservatively declares `unknown`, persisted as\n`generation_completion_unknown`. Otherwise valid suggestions remain available\nfor human preview; automatic eligibility always remains false. The service\ndeadline aborts requests and prevents late publication; it does not claim to terminate computation at a remote\nprovider or isolate native allocations. Extractor process limits remain separate.\n\nModel output can contain only offered handler versions, schema-valid arguments,\nretained evidence locations and offered alternative handler/candidate keys.\nCandidate IDs must occur in the offered set, and evidence IDs in retained source\nresults. Unknown enums, invented IDs, extra authority/tool/approval fields and\nmalformed structures fail closed. Missing required top-level fields are retained\nas `missingFields`, with `needs_review`; values are never invented to satisfy a\nschema. Observed page/time/source granularity is preserved. Logical scan splits\nuse `proposeDocumentSplits`; originals and hashes remain intact.\n\n`createSDKProposalDecisionClient(client)` adapts an existing SDK client’s optional\ncapability without changing its errors or protocol. Optional `decision` uses public core `executeDecision` and the existing SDK\npredicate, choice, score and batch contracts. Supported-effect predicates,\nhandler classification, candidate entity matching, and action ambiguity/risk\nare distinct questions. Their validated probabilities and provenance are stored\nseparately from generative provenance and unknown OCR certainty. The complete\nserialized decision request, including suggestions and questions, must fit the\nminimum configured/current policy byte ceiling before capability probing and\nagain before deciding. A policy change between these boundaries fails closed.\nTies, support probability or selected-handler confidence below\n`minimumDecisionProbability`, and actually incomplete extraction require review.\nUnknown provider\ncompletion metadata is preserved as `source_completion_unknown`; it does not\nblock otherwise schema-valid **human** preview or imply completeness. Automatic\naction eligibility remains false. An unconfigured decision path\nis recorded explicitly. Configured errors produce a durable safe failure outcome;\nthey never silently switch to a generative decision fallback.\n\nOutput records zero, one or multiple suggestions, alternatives, missing fields,\nsource links, proposed splits, versions, allowlisted usage, warnings and explicit\n`unknown`, `ambiguous`, `no_action`, `needs_review` or `provider_error` outcomes.\n`automaticActionEligible` is always false. Provider input/output and the complete\nserialized persisted envelope are bounded by configuration, live policy and the\nreceipt ceiling. Oversized output becomes a bounded review/limit result; when\nno safe envelope fits, the owning service records fixed `failAnalysis` metadata\noutside the provider payload budget without retaining provider output.\n\n## Explicit preview and stable intentions\n\nThe host chooses persisted suggestion indexes and calls:\n\n```ts\nawait service.previewGeneratedProposals({\n itemId,\n attemptId: generationAttemptId,\n selections: [{\n index: 0,\n intentionKey: 'document:meeting-2026-10-09',\n expectedRevision: 0,\n requestId: 'review-request-1',\n }],\n});\n```\n\n`intentionKey` is the host's stable business-intention identity across generation\nrevisions. Never derive a fresh key from model output, suggestion order or a retry.\nSelections must reference current persisted validated `ready_for_review` output.\nEach batch requires distinct suggestion indexes and intention keys; duplicate\nindexes are rejected before any operation or plan preview is written.\nThe service rechecks current catalog/schema/target/source provenance, then calls\nthe existing operation or plan preview. Each result still requires the ordinary\nhuman review and execution APIs. Reprocessing creates no new business identity;\nsuccessful-action replay protection stays with execution.\n\n## Evidence and limits\n\nThe test matrix is `docs/test-matrix/3673-ingestion-proposals.md`. SQLite and real\nPostgreSQL suites exercise authority, revisions, abstention, hostile output,\ncompound proposals, split provenance and reviewed domain effects. The upload\nreference composes authenticated multipart delivery of a generated embedded-text\nPDF through the actual packaged PDF child, durable interpretation, and the existing\nordered ContentDocument draft/retained-asset plan. It checks duplicate delivery,\nunauthenticated and foreign-tenant denial, explicit approval of both steps,\nidempotent execution replay, page provenance, and unchanged original bytes.\nThe compound-email case uses a declared messages-owner snapshot fixture.\n\nLocal HTTP fixtures execute the actual AI SDK transport and cancellation contract.\nGenerative responses and the separate injected PDF split boundaries establish\ndeterministic orchestration, not model accuracy or OCR quality. No held-out routing\nevaluation or automatic approval is claimed. Missing/unknown AI completion remains\nexplicit under [SDK #1381](https://github.com/happyvertical/sdk/issues/1381).\n\nProposal limits are checked at `IngestionService` construction: positive safe\nintegers, at most 20 handlers/candidates/suggestions and 2147483647 ms timeout.\nInterpretation output uses the exported `GenerationAnalysisOutput` wrapper at\n`analysis.result.output.proposals`; the published review host unwraps it.\nAn explicit feedback `retrieve` denial omits optional examples and feedback\nprovenance and continues generation. Item/execution denials, unexpected failures,\nand revocation after examples were selected still fail closed before disclosure.\n"
1618
1618
  },
1619
1619
  {
1620
1620
  "path": "FEEDBACK.md",
1621
1621
  "module": "FEEDBACK",
1622
- "content": "# Explicit ingestion feedback\n\nConfigure `IngestionOptions.feedback` to opt in. The existing `intake_feedback`\nledger owns these records; no new schema, embedding service or provider is added.\n`FeedbackConfiguration` sets a version, maximum examples, scan count, serialized\nbytes and lexical similarity threshold, plus a live scoped authorization callback.\nHard ceilings are 20 examples, 1,000 scanned records and 1 MB. Choose substantially\nsmaller application limits. The proposal's complete serialized request, including\nexamples, must also fit the current minimum application/source/provider budget.\n\n`recordFeedback` accepts the exact displayed action revision, review version and\nbinding hash, an explicit correct/incorrect judgment, optional reason text and a\nrequest ID. The server resolves reviewer, tenant/confidential scope, retained\nsource evidence, extraction/generation versions and current handler arguments.\nA replay returns the same immutable receipt; changed payloads conflict.\n`supersedesId` appends a replacement for the specified prior interpretation\njudgment. A second successor conflicts. Revised actions make old bindings\nineligible. Approval and successful execution never imply that extracted fields\nare correct.\n\nDecision and downstream execution facts are captured inside their owning\ntransaction, keyed by immutable event ID and signal, when the configured capture\nauthority allows the optional memory projection and it fits the configured byte\ncap. Denial or an oversized automatic projection leaves the underlying\nauthoritative decision/outcome intact, including failure and reconciliation.\nExplicit `recordFeedback` and `observeFeedback` requests still reject invalid or\noversized writes; actual database failures still propagate and roll back. Failed/rolled-back domain\nwork and unknown external outcomes remain distinct. `observeFeedback` can replay\nan authorized existing event; it cannot supply a correctness label or fabricate\nan execution result. An initial denial does not mutate retention. Once authorized,\na narrowed privacy ceiling survives business rollback and later revocation.\n\n## Retrieval and provider boundaries\n\n`retrieveFeedback({ itemId, query })` derives the current offered catalog,\ncandidates and model/prompt/configuration versions on the server. Callers cannot\nprovide candidate authority. The deterministic matcher uses lowercase Unicode\nword-set Jaccard similarity (minimum 0.2), then immutable record ID for ties.\nScanning, recursive provenance checks and returned examples are bounded; a limited scan does not promise an\nexhaustive history search. Both positive and negative explicit examples are kept.\n\nEvery selected source must still be readable in the same tenant and confidential\nscope, with its current action/analysis binding, target grants, handler version,\nmodel/prompt/configuration compatibility and retention. Each source's current\nprovider policy must allow the generation recipient and any configured decision\nrecipient; the source owner rechecks that policy on both initial and final live\ncontexts. Receiving checks cover every offered handler, before and after source\nchecks, using each live grant, actual provider recipients and the narrowest byte\nceiling. Both retrieval and reference revalidation budget the full reconstructed\nexamples. A receiving item's provider grant cannot substitute for a source grant.\nSuperseded, revoked, deleted or incompatible sources are excluded. Current explicit human corrections\ntake precedence: a generation carrying one does not retrieve learned examples.\n\nFull examples exist only in the authorized provider request. The SDK proposal\nadapter includes that typed selection in its serialized user message when\npresent; disabled feedback leaves the original request shape unchanged. Saved generation\nprovenance contains the receiving query, selection configuration digest and\nimmutable feedback IDs/digests, not copied source example content. Selected\nreferences are rechecked before generation, capability probing, decision calls,\npublication and completed-result reads. A newly added example does not invalidate\nan older selection; a revoked or superseded selected example does. Feedback\nlineage is bounded and fails closed. Saved-action reads and pending decisions,\nautomatic authorization, preview publication/replay and execution also revalidate\nselected lineage under the\nowning transaction. Revoking, deleting or superseding a selected example blocks\npending actions; regenerate their proposals and obtain fresh approval to recover.\nA preview replay checks the exact persisted proposal it returns, including its\nanalysis attempt; a newer action revision cannot supply replacement lineage.\nPlan replay and final sealed plan-step publication use the same gate.\nFor already successful actions, current-authorized durable outcomes remain\nreadable/replayable, but invalid learned lineage suppresses saved proposal\ndisplay, arguments and plan payload. An empty selection carries no learned source\nand does not turn optional feedback-capture denial into action denial. Examples\nnever expand the offered catalog, candidate IDs, operation permissions or\nautomation eligibility.\n\nAll durable feedback belongs to the source item's existing retention/redaction\nlifecycle. There is no separate memory store or delayed indexing writer to clean\nup. Hosts using other derived stores still implement the existing `purgeDerived`\ncontract. Core `LearningMemory` is intentionally not used here: its success/failure\nreinforcement and default ancestor-scope fallback do not represent separate\ncorrectness/decision/outcome signals and strict confidential-scope eligibility.\n\n## Routing suggestions and adoption\n\n`suggestRoutingRule` requires repeated current explicit positive judgments\nfrom distinct source items with matching handler/version and arguments, and returns supporting immutable IDs,\nshared query terms and the policy owner's preview/version. Suggestions cannot\nexecute or modify policy. `getRoutingRule` rechecks the displayed binding and all\nsupporting examples. Arguments are routing preferences, never executable grants.\n\nBy default matching compares **all** action arguments, preserving existing host\nbehavior. Create handlers commonly have per-document content and idempotency\nkeys, which must remain distinct. Such hosts can explicitly declare a routing-only\nsubset in trusted server configuration before capturing judgments:\n\n```ts\nfeedback: {\n // ...existing limits, authorize and policy owner\n routing: [{\n handlerId: 'host:create-document',\n handlerVersion: '1',\n version: 'routing-fields-1',\n fields: ['destinationId', 'category'],\n }],\n}\n```\n\nEach declaration must name a configured handler/version and a nonempty, unique\nallowlist of its top-level `argsSchema.properties`; duplicate declarations,\nunknown properties and prototype keys reject. There are no dotted paths,\ncaller-supplied selectors or implicit exclusions (including request IDs).\nOptional absent fields stay absent and differ from explicit `null`; at least one\nselected value must be present. The host must select preferences only, never\ngrants, provider permissions or automation controls.\n\nCapture retains the full immutable action arguments and binding plus the\nversioned subset. For opted-in handlers `RoutingRule.args` contains only selected\nvalues and `RoutingRule.projection` carries the canonical sorted fields and\nversion. Independent support must match that entire contract and those values;\nfull original source arguments, provenance and current access are still checked.\nExisting unprojected feedback is not retroactively reinterpreted: record fresh\nexplicit judgments after enabling or changing a declaration. Changing a version,\nfield list or selected value invalidates old suggestions on reads, adoption and\nreplay, including changes inside policy-owner callbacks. Full argument feedback\nretrieval remains unchanged; hosts may present matching examples from\n`retrieveFeedback`, but suggestion creation revalidates every supplied ID.\n\n`adoptRoutingRule` requires the exact suggestion digest and expected policy\nversion plus current reviewer and adoption authority. The configured policy owner\nmust perform its version compare-and-swap and audit on the supplied database\nexecutor. The ingestion transaction records the exact returned version/audit ID.\nReplays do not adopt twice. Revocation or permission/policy widening rolls back\nboth changes. The host callback may store routing preferences only: it must not\nchange grants, provider permissions or automation controls. Adoption always\nreturns `automaticActionEligible: false`; subsequent proposals retain normal\ncurrent policy and explicit review requirements.\n\n## Review UI and evidence\n\nThe optional `IntakeReviewHost.feedback` callback carries the exact displayed\nrevision and binding. Correct/incorrect controls are explicit and independent of\nApprove/Apply. Unsaved argument edits disable correctness controls until the\ndisplayed binding is current again. Hosts must authenticate that callback and connect it to\n`recordFeedback`; client-supplied reviewer/scope fields are not accepted. The\nmaintained browser fixture demonstrates this transport with CSRF protection and\nrejects substituted revisions.\n\nSee [the behavior matrix](../../docs/test-matrix/3676-ingestion-feedback.md) for\nvalidation and the frozen learning protocol, and the\n[routing projection matrix](../../docs/test-matrix/3732-ingestion-routing-projection.md)\nfor the optional subset contract. The small authored deterministic\ncohort demonstrates contract-level influence, not provider quality or measured\nproduction improvement. Real-provider evaluation belongs to #3677. There are no\nsampled automatic outcomes in this feature; reporting that stratum as unavailable\navoids inventing correctness labels from successful jobs.\n"
1622
+ "content": "# Explicit ingestion feedback\n\nConfigure `IngestionOptions.feedback` to opt in. The existing `intake_feedback`\nledger owns these records; no new schema, embedding service or provider is added.\n`FeedbackConfiguration` sets a version, maximum examples, scan count, serialized\nbytes and lexical similarity threshold, plus a live scoped authorization callback.\nHard ceilings are 20 examples, 1,000 scanned records and 1 MB. Choose substantially\nsmaller application limits. The proposal's complete serialized request, including\nexamples, must also fit the current minimum application/source/provider budget.\n\n`recordFeedback` accepts the exact displayed action revision, review version and\nbinding hash, an explicit correct/incorrect judgment, optional reason text and a\nrequest ID. The server resolves reviewer, tenant/confidential scope, retained\nsource evidence, extraction/generation versions and current handler arguments.\nA replay returns the same immutable receipt; changed payloads conflict.\n`supersedesId` appends a replacement for the specified prior interpretation\njudgment. A second successor conflicts. Revised actions make old bindings\nineligible. Approval and successful execution never imply that extracted fields\nare correct.\n\nDecision and downstream execution facts are captured inside their owning\ntransaction, keyed by immutable event ID and signal, when the configured capture\nauthority allows the optional memory projection and it fits the configured byte\ncap. Denial or an oversized automatic projection leaves the underlying\nauthoritative decision/outcome intact, including failure and reconciliation.\nExplicit `recordFeedback` and `observeFeedback` requests still reject invalid or\noversized writes; actual database failures still propagate and roll back. Failed/rolled-back domain\nwork and unknown external outcomes remain distinct. `observeFeedback` can replay\nan authorized existing event; it cannot supply a correctness label or fabricate\nan execution result. An initial denial does not mutate retention. Once authorized,\na narrowed privacy ceiling survives business rollback and later revocation.\n\n## Retrieval and provider boundaries\n\n`retrieveFeedback({ itemId, query })` derives the current offered catalog,\ncandidates and model/prompt/configuration versions on the server. Callers cannot\nprovide candidate authority. The deterministic matcher uses lowercase Unicode\nword-set Jaccard similarity (minimum 0.2), then immutable record ID for ties.\nScanning, recursive provenance checks and returned examples are bounded; a limited scan does not promise an\nexhaustive history search. Both positive and negative explicit examples are kept.\n\nEvery selected source must still be readable in the same tenant and confidential\nscope, with its current action/analysis binding, target grants, handler version,\nmodel/prompt/configuration compatibility and retention. Each source's current\nprovider policy must allow the generation recipient and any configured decision\nrecipient; the source owner rechecks that policy on both initial and final live\ncontexts. Receiving checks cover every offered handler, before and after source\nchecks, using each live grant, actual provider recipients and the narrowest byte\nceiling. Both retrieval and reference revalidation budget the full reconstructed\nexamples. A receiving item's provider grant cannot substitute for a source grant.\nSuperseded, revoked, deleted or incompatible sources are excluded. Current explicit human corrections\ntake precedence: a generation carrying one does not retrieve learned examples.\n\nFull examples exist only in the authorized provider request. The SDK proposal\nadapter includes that typed selection in its serialized user message when\npresent; disabled feedback leaves the original request shape unchanged. Saved generation\nprovenance contains the receiving query, selection configuration digest and\nimmutable feedback IDs/digests, not copied source example content. Selected\nreferences are rechecked before generation, capability probing, decision calls,\npublication and completed-result reads. A newly added example does not invalidate\nan older selection; a revoked or superseded selected example does. Feedback\nlineage is bounded and fails closed. Saved-action reads and pending decisions,\nautomatic authorization, preview publication/replay and execution also revalidate\nselected lineage under the\nowning transaction. Revoking, deleting or superseding a selected example blocks\npending actions; regenerate their proposals and obtain fresh approval to recover.\nA preview replay checks the exact persisted proposal it returns, including its\nanalysis attempt; a newer action revision cannot supply replacement lineage.\nPlan replay and final sealed plan-step publication use the same gate.\nFor already successful actions, current-authorized durable outcomes remain\nreadable/replayable, but invalid learned lineage suppresses saved proposal\ndisplay, arguments and plan payload. An empty selection carries no learned source\nand does not turn optional feedback-capture denial into action denial. Examples\nnever expand the offered catalog, candidate IDs, operation permissions or\nautomation eligibility.\n\nAll durable feedback belongs to the source item's existing retention/redaction\nlifecycle. There is no separate memory store or delayed indexing writer to clean\nup. Hosts using other derived stores still implement the existing `purgeDerived`\ncontract. Core `LearningMemory` is intentionally not used here: its success/failure\nreinforcement and default ancestor-scope fallback do not represent separate\ncorrectness/decision/outcome signals and strict confidential-scope eligibility.\n\n## Routing suggestions and adoption\n\n`suggestRoutingRule` requires repeated current explicit positive judgments\nfrom distinct source items with matching handler/version and arguments, and returns supporting immutable IDs,\nshared query terms and the policy owner's preview/version. Suggestions cannot\nexecute or modify policy. `getRoutingRule` rechecks the displayed binding and all\nsupporting examples. Arguments are routing preferences, never executable grants.\n\nBy default matching compares **all** action arguments, preserving existing host\nbehavior. Create handlers commonly have per-document content and idempotency\nkeys, which must remain distinct. Such hosts can explicitly declare a routing-only\nsubset in trusted server configuration before capturing judgments:\n\n```ts\nfeedback: {\n // ...existing limits, authorize and policy owner\n routing: [{\n handlerId: 'host:create-document',\n handlerVersion: '1',\n version: 'routing-fields-1',\n fields: ['destinationId', 'category'],\n }],\n}\n```\n\nEach declaration must name a configured handler/version and a nonempty, unique\nallowlist of its top-level `argsSchema.properties`; duplicate declarations,\nunknown properties and prototype keys reject. There are no dotted paths,\ncaller-supplied selectors or implicit exclusions (including request IDs).\nOptional absent fields stay absent and differ from explicit `null`; at least one\nselected value must be present. The host must select preferences only, never\ngrants, provider permissions or automation controls.\n\nCapture retains the full immutable action arguments and binding plus the\nversioned subset. For opted-in handlers `RoutingRule.args` contains only selected\nvalues and `RoutingRule.projection` carries the canonical sorted fields and\nversion. Independent support must match that entire contract and those values;\nfull original source arguments, provenance and current access are still checked.\nExisting unprojected feedback is not retroactively reinterpreted: record fresh\nexplicit judgments after enabling or changing a declaration. Changing a version,\nfield list or selected value invalidates old suggestions on reads, adoption and\nreplay, including changes inside policy-owner callbacks. Full argument feedback\nretrieval remains unchanged; hosts may present matching examples from\n`retrieveFeedback`, but suggestion creation revalidates every supplied ID.\n\n`adoptRoutingRule` requires the exact suggestion digest and expected policy\nversion plus current reviewer and adoption authority. The configured policy owner\nmust perform its version compare-and-swap and audit on the supplied database\nexecutor. The ingestion transaction records the exact returned version/audit ID.\nReplays do not adopt twice. Revocation or permission/policy widening rolls back\nboth changes. The host callback may store routing preferences only: it must not\nchange grants, provider permissions or automation controls. Adoption always\nreturns `automaticActionEligible: false`; subsequent proposals retain normal\ncurrent policy and explicit review requirements.\n\n## Review UI and evidence\n\nThe optional `IntakeReviewHost.feedback` callback carries the exact displayed\nrevision and binding. Correct/incorrect controls are explicit and independent of\nApprove/Apply. Unsaved argument edits disable correctness controls until the\ndisplayed binding is current again. Hosts must authenticate that callback and connect it to\n`recordFeedback`; client-supplied reviewer/scope fields are not accepted. The\nmaintained browser fixture demonstrates this transport with CSRF protection and\nrejects substituted revisions.\n\nSee [the behavior matrix](../../docs/test-matrix/3676-ingestion-feedback.md) for\nvalidation and the frozen learning protocol, and the\n[routing projection matrix](../../docs/test-matrix/3732-ingestion-routing-projection.md)\nfor the optional subset contract. The small authored deterministic\ncohort demonstrates contract-level influence, not provider quality or measured\nproduction improvement. Real-provider evaluation belongs to #3677. There are no\nsampled automatic outcomes in this feature; reporting that stratum as unavailable\navoids inventing correctness labels from successful jobs.\n\nWhen interpretation requests optional examples, an explicit denial of feedback\nretrieval degrades to generation without examples or feedback provenance. Direct\n`retrieveFeedback` calls still reject denied reads. Other authorization errors\nare not swallowed, and already selected examples must pass the normal live\nprovider-boundary checks; revocation does not silently preserve selected data.\n"
1623
1623
  },
1624
1624
  {
1625
1625
  "path": "REVIEW.md",
1626
1626
  "module": "REVIEW",
1627
- "content": "# Authenticated review surfaces\n\n`@happyvertical/smrt-ingestion/svelte` exports `IntakeInbox`, `IntakeReview` and\n`EvidenceViewer`. The browser-safe DTO entry exports their `IntakeReviewHost`\ncallback contract. Import styling/theme configuration from smrt-ui in the host.\nComponents use smrt-ui primitives and the `ingestion.*` i18n catalog.\n\nThe host authenticates every request, resolves tenant/actor/confidential scope\nfrom its session, enforces CSRF on mutations, and constructs `IngestionService`.\nNever accept scope, reviewer, permissions or a principal from callback JSON.\nOnly supply authorized evidence URLs and escaped text; original URLs are\nsame-origin authenticated handlers that recheck `readEvidence` on every read.\nCandidate discovery uses `findCandidates` with current grants. Presentation\nstate and disabled buttons provide no server authority.\n\n`listReviews(itemId, {cursor?,limit?})` reloads saved action identities and their\ncurrent plan membership without browser storage. It returns at most 50 actions,\nwith an opaque action-ID cursor. Every payload requires current item, handler,\nparent plan and target access under the owning transaction. Denied reads fail\nclosed. Target reads check current authorization separately from historical\nrevision freshness: unfinished drift returns state-only stale reviews without\nremoving unrelated entries; succeeded results remain readable after authorized\ntarget changes. Apply still enforces exact bound target revisions. Expired entries\ncontain only review identity/state. Stale entries never disclose old args or target\nlabels; an authorized parent plan additionally exposes `stalePlan` identity, key,\ncurrent plan revision and handler identity. Hosts must collect fresh explicit args\nfrom the reviewer/current authorized evidence and call `previewPlan` with that\nexact plan CAS and the current completed analysis attempt. Action revision is not\nplan revision. Re-expansion preserves action identity and requires fresh approval.\nSuccess results are rechecked through the durable result reader.\nPlan membership contains the exact parent args/version so edits call\n`previewPlan`, not per-step correction. An item may have more review pages; the\nhost must aggregate state across pages when projecting a production inbox state.\n\nThe host's `load` callback supplies a current `ItemReviewView`, using\n`getCompletedAnalysis` with no historical fallback. Generated suggestions bind\nthe **current generation attempt**, not `generation.source.attemptId` (the prior\nextraction). `previewGeneratedProposals` publishes exact reviews and continues to reject stale\ngeneration candidate pins. When `listReviews` reports `generationStale`, the host\nomits obsolete generation output and renders authorized saved reviews/results.\nCompleted saved actions do not hide healthy unprepared suggestions. The saved-binding hint is not\nan authoritative generation-availability check: a fresh human preview can bind a\ncurrent target while the immutable generation still pins its former revision.\n`getCompletedAnalysis` remains strict and throws server-only\n`GenerationSnapshotStaleError` only after every current catalog/provider/candidate\nread is authorized and an immutable candidate revision differs. The maintained\nhost catches only that class, reacquires `listReviews` under current owning\nauthority, and returns that new page without generation output. It never reuses\nthe earlier page after an error. Denials and unknown failures propagate; healthy\ngeneration still exposes unprepared sibling suggestions. Stale entries expose handler\nand attempt identity only when that attempt is still the current completed/partial\nanalysis. An empty-args editor submits fresh explicit human arguments through\n`previewProposal` or `previewPlan` with the saved CAS; it never reuses old generated\narguments, rewrites the generation snapshot or transfers approval. Analysis-stale\nentries without an attempt require normal reprocessing. Approve,\nreject, defer and correct call `submitDecision`; corrected args create a new\nrevision which requires a separate human approval. After an approve/defer/reject\ndecision, optional `editAction` calls `previewProposal` with the current action\nrevision to publish a new review; completed/executing/unknown actions cannot be\nrevised. Local dirty args disable Apply but confer no authority. Plan edits re-expand through\n`previewPlan` with the current **plan** revision. `applyAction` accepts only an\naction ID. Unknown external outcomes require server reconciliation; the UI\nnever offers a blind resend. Stable result IDs survive reload and retry.\n\nReplace `contextKey` whenever authenticated tenant/session context changes.\nChanging it or itemId destroys the old view and fences late callback results.\nDenied refresh clears prior originals, candidates, arguments and results.\nMissing confidence is unavailable; page/time links exist only for observed\nlocations. Provider errors and unresolved/partial results remain review states.\n\n## Assignment and logical splits\n\nAssignment is explicitly host-owned, durable and versioned. `assign` receives\nan expected assignment version and request ID; the host must authorize the\nmanager, constrain eligible assignees, CAS the durable record and reject stale\nwrites. Assignment does not grant read, review or execution rights. The maintained\nfixture provisions its own SQLite assignment table before serving requests; no\nproduction ingestion table or migration is introduced for assignment.\n\n`reviseLogicalSplit` authorizes the current generation through the same-executor\ncatalog/candidate gate and the existing reviewer grant and policy reviewer list.\nProcess access alone cannot mint or replay a human correction; reviewer authority\nis checked before mutation and again before publication. A generation without a\nreviewable catalogue cannot be corrected through this reviewer API.\nIt requires all observed pages exactly once, an exact\ncurrent attempt/revision and a request ID. It records the authenticated actor\nand predecessor as a **human correction** in a new immutable extraction\nconfiguration, queues re-extraction and immediately makes previous suggestions\nand approvals stale. It never changes original bytes/evidence or labels a human\nedit as model output. The host processes the new extraction, then calls\n`prepareGeneration` and the normal fenced interpretation stage. The supported\nimmediate-predecessor extraction pin is unchanged. The generator receives a\nhuman correction only after its digest matches the authoritative source. Ordinary\n`analyze` calls cannot mint an extraction correction; the owning split API is the\nauthenticated origin, and forged interpretation corrections fail before provider\ndisclosure. If its proposed grouping differs from the correction, suggestions are withheld\nwith `human_split_not_respected`. New proposals require new explicit review.\nThe reference host runs these stages synchronously for browser determinism;\nproduction hosts dispatch the existing durable analysis jobs.\n\n`feedback` is an optional explicit correctness callback, separate from approval\nchoice and execution success. No learning, feedback storage or rule promotion is\nimplemented by these components; #3676 owns those services. Do not pass feedback\nor a feedback callback to readers without the relevant host grant.\n\n## Maintained browser proof\n\n`pnpm test:components` runs real Svelte component tests; `pnpm test:e2e` runs the\npackage-local authenticated Vite application under Chromium. The fixture uses\nHttpOnly same-site sessions, CSRF, real SQLite/assets/ingestion/content APIs,\nproduction unpdf child extraction and a deterministic proposal generator. Its\nhardcoded test login is fixture-only and is never a production auth provider.\nImage/audio originals remain inspectable when no OCR/speech provider is\nconfigured; the suite makes no recognition-quality claim and spends no provider\nbudget. `reference/review-host.ts` is a maintained development fixture, not a\npublished server entry. Browser tests show actual approved args and persisted\nContentDocument results, stale tabs, reload, retries and negative access.\n\nRun full package `test`, `test:postgres`, `test:providers`, `build`, `typecheck`,\n`test:components`, `test:e2e`; use the root Node/pnpm versions. Set a short\n`CI_TEST_TMPDIR`/`TMPDIR`, and optionally\n`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to the supported installed Chromium.\n`pnpm test:evaluation` checks repository evaluation tooling contracts; measured\nheld-out quality remains a separate frozen-protocol, budget-gated #3677 run.\n\nThe existing CI browser job includes ingestion changes and shared UI primitive\nchanges in affected mode, and runs the ingestion browser suite in full mode. Its\nnormal dependency build precedes the suite and failed runs upload browser evidence.\n\nThe maintained host derives inbox state by traversing bounded public review pages,\nauthorizing every action/parent/target before classification. It retains only\nscalar totals and the requested page; an off-page denial denies the whole view.\nThe component's Load more and subsequent refresh/mutation reload every displayed\npage using fresh cursors, then publish the combined authorized set together. Old\npage payloads are cleared while loading; any unavailable page clears all payloads.\nThis keeps plan controls and earlier steps visible across page boundaries without\nreusing a prior authorization decision.\n"
1627
+ "content": "# Authenticated review surfaces\n\n`@happyvertical/smrt-ingestion/svelte` exports `IntakeInbox`, `IntakeReview` and\n`EvidenceViewer`. The browser-safe DTO entry exports their `IntakeReviewHost`\ncallback contract. Import styling/theme configuration from smrt-ui in the host.\nComponents use smrt-ui primitives and the `ingestion.*` i18n catalog.\n\nThe host authenticates every request, resolves tenant/actor/confidential scope\nfrom its session, enforces CSRF on mutations, and constructs `IngestionService`.\nNever accept scope, reviewer, permissions or a principal from callback JSON.\nOnly supply authorized evidence URLs and escaped text; original URLs are\nsame-origin authenticated handlers that recheck `readEvidence` on every read.\nCandidate discovery uses `findCandidates` with current grants. Presentation\nstate and disabled buttons provide no server authority.\n\n`listReviews(itemId, {cursor?,limit?})` reloads saved action identities and their\ncurrent plan membership without browser storage. It returns at most 50 actions,\nwith an opaque action-ID cursor. Every payload requires current item, handler,\nparent plan and target access under the owning transaction. Denied reads fail\nclosed. Target reads check current authorization separately from historical\nrevision freshness: unfinished drift returns state-only stale reviews without\nremoving unrelated entries; succeeded results remain readable after authorized\ntarget changes. Apply still enforces exact bound target revisions. Expired entries\ncontain only review identity/state. Stale entries never disclose old args or target\nlabels; an authorized parent plan additionally exposes `stalePlan` identity, key,\ncurrent plan revision and handler identity. Hosts must collect fresh explicit args\nfrom the reviewer/current authorized evidence and call `previewPlan` with that\nexact plan CAS and the current completed analysis attempt. Action revision is not\nplan revision. Re-expansion preserves action identity and requires fresh approval.\nSuccess results are rechecked through the durable result reader.\nPlan membership contains the exact parent args/version so edits call\n`previewPlan`, not per-step correction. An item may have more review pages; the\nhost must aggregate state across pages when projecting a production inbox state.\n\nThe host's `load` callback supplies a current `ItemReviewView`, using\n`getCompletedAnalysis` with no historical fallback. Generated suggestions bind\nthe **current generation attempt**, not `generation.source.attemptId` (the prior\nextraction). `previewGeneratedProposals` publishes exact reviews and continues to reject stale\ngeneration candidate pins. When `listReviews` reports `generationStale`, the host\nomits obsolete generation output and renders authorized saved reviews/results.\nCompleted saved actions do not hide healthy unprepared suggestions. The saved-binding hint is not\nan authoritative generation-availability check: a fresh human preview can bind a\ncurrent target while the immutable generation still pins its former revision.\n`getCompletedAnalysis` remains strict and throws server-only\n`GenerationSnapshotStaleError` only after every current catalog/provider/candidate\nread is authorized and an immutable candidate revision differs. The maintained\nhost catches only that class, reacquires `listReviews` under current owning\nauthority, and returns that new page without generation output. It never reuses\nthe earlier page after an error. Denials and unknown failures propagate; healthy\ngeneration still exposes unprepared sibling suggestions. Stale entries expose handler\nand attempt identity only when that attempt is still the current completed/partial\nanalysis. An empty-args editor submits fresh explicit human arguments through\n`previewProposal` or `previewPlan` with the saved CAS; it never reuses old generated\narguments, rewrites the generation snapshot or transfers approval. Analysis-stale\nentries without an attempt require normal reprocessing. Approve,\nreject, defer and correct call `submitDecision`; corrected args create a new\nrevision which requires a separate human approval. After an approve/defer/reject\ndecision, optional `editAction` calls `previewProposal` with the current action\nrevision to publish a new review; completed/executing/unknown actions cannot be\nrevised. Local dirty args disable Apply but confer no authority. Plan edits re-expand through\n`previewPlan` with the current **plan** revision. `applyAction` accepts only an\naction ID. Unknown external outcomes require server reconciliation; the UI\nnever offers a blind resend. Stable result IDs survive reload and retry.\n\nReplace `contextKey` whenever authenticated tenant/session context changes.\nChanging it or itemId destroys the old view and fences late callback results.\nDenied refresh clears prior originals, candidates, arguments and results.\nMissing confidence is unavailable; page/time links exist only for observed\nlocations. Provider errors and unresolved/partial results remain review states.\n\n## Assignment and logical splits\n\nAssignment is explicitly host-owned, durable and versioned. `assign` receives\nan expected assignment version and request ID; the host must authorize the\nmanager, constrain eligible assignees, CAS the durable record and reject stale\nwrites. Assignment does not grant read, review or execution rights. The maintained\nfixture provisions its own SQLite assignment table before serving requests; no\nproduction ingestion table or migration is introduced for assignment.\n\n`reviseLogicalSplit` authorizes the current generation through the same-executor\ncatalog/candidate gate and the existing reviewer grant and policy reviewer list.\nProcess access alone cannot mint or replay a human correction; reviewer authority\nis checked before mutation and again before publication. A generation without a\nreviewable catalogue cannot be corrected through this reviewer API.\nIt requires all observed pages exactly once, an exact\ncurrent attempt/revision and a request ID. It records the authenticated actor\nand predecessor as a **human correction** in a new immutable extraction\nconfiguration, queues re-extraction and immediately makes previous suggestions\nand approvals stale. It never changes original bytes/evidence or labels a human\nedit as model output. The host processes the new extraction, then calls\n`prepareGeneration` and the normal fenced interpretation stage. The supported\nimmediate-predecessor extraction pin is unchanged. The generator receives a\nhuman correction only after its digest matches the authoritative source. Ordinary\n`analyze` calls cannot mint an extraction correction; the owning split API is the\nauthenticated origin, and forged interpretation corrections fail before provider\ndisclosure. If its proposed grouping differs from the correction, suggestions are withheld\nwith `human_split_not_respected`. New proposals require new explicit review.\nThe reference host runs these stages synchronously for browser determinism;\nproduction hosts dispatch the existing durable analysis jobs.\n\n`feedback` is an optional explicit correctness callback, separate from approval\nchoice and execution success. No learning, feedback storage or rule promotion is\nimplemented by these components; #3676 owns those services. Do not pass feedback\nor a feedback callback to readers without the relevant host grant.\n\n## Maintained browser proof\n\n`pnpm test:components` runs real Svelte component tests; `pnpm test:e2e` runs the\npackage-local authenticated Vite application under Chromium. The fixture uses\nHttpOnly same-site sessions, CSRF, real SQLite/assets/ingestion/content APIs,\nproduction unpdf child extraction and a deterministic proposal generator. Its\nhardcoded test login is fixture-only and is never a production auth provider.\nImage/audio originals remain inspectable when no OCR/speech provider is\nconfigured; the suite makes no recognition-quality claim and spends no provider\nbudget. `reference/review-host.ts` is a maintained development fixture, not a\npublished server entry. Browser tests show actual approved args and persisted\nContentDocument results, stale tabs, reload, retries and negative access.\n\nRun full package `test`, `test:postgres`, `test:providers`, `build`, `typecheck`,\n`test:components`, `test:e2e`; use the root Node/pnpm versions. Set a short\n`CI_TEST_TMPDIR`/`TMPDIR`, and optionally\n`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to the supported installed Chromium.\n`pnpm test:evaluation` checks repository evaluation tooling contracts; measured\nheld-out quality remains a separate frozen-protocol, budget-gated #3677 run.\n\nThe existing CI browser job includes ingestion changes and shared UI primitive\nchanges in affected mode, and runs the ingestion browser suite in full mode. Its\nnormal dependency build precedes the suite and failed runs upload browser evidence.\n\nThe maintained host derives inbox state by traversing bounded public review pages,\nauthorizing every action/parent/target before classification. It retains only\nscalar totals and the requested page; an off-page denial denies the whole view.\nThe component's Load more and subsequent refresh/mutation reload every displayed\npage using fresh cursors, then publish the combined authorized set together. Old\npage payloads are cleared while loading; any unavailable page clears all payloads.\nThis keeps plan controls and earlier steps visible across page boundaries without\nreusing a prior authorization decision.\n\n## Published server adapter\n\nImport `createIntakeReviewHost` and `IntakeReviewHostOptions` from\n`@happyvertical/smrt-ingestion/server`. Call `createIntakeReviewHost(service,\noptions)` with a service constructed from the current authenticated session.\nThe returned `IntakeReviewHost` implements inbox state projection across saved\nreview pages, current generation loading, stable `ui:<index>` intention keys,\naction/plan preview CAS lookup, decisions, apply, corrections, candidates, split\nand feedback. Repeated preparation of an unchanged authorized suggestion retains\nits current review instead of creating a new revision. Changed arguments still\nrequire explicit re-preview and a fresh human decision.\nLists scan 20 items per page; filtered pages may be empty with a `nextCursor`.\nContinue until the cursor is absent. Listing does not load original bytes.\n\nSupply four application adapters: `upload(files, requestId)` (authenticated\nreceipt plus first extraction request), `assignment(itemId)` (durable read),\n`assign(input)` (manager authorization, eligible assignees, durable CAS and request\nreplay protection), and `evidence(part)` (safe label/text or authenticated\nsame-origin URL). Optional `label(item)` changes presentation. Optional\n`enableFeedback: true` exposes the optional feedback callback when the service\nhas feedback configured. Optional `onSplit(itemId, revision)` wakes the host worker after the durable extraction\nrequest; repair dispatches if wakeup fails. The factory creates no assignment\nschema and grants no permissions. Create it per session, authenticate every HTTP\ncall and enforce CSRF before dispatching a mutation.\n\n`GenerationAnalysisOutput` is exported by `/dto` and describes the interpretation\nwrapper `{ proposals: GenerationOutput }` under `analysis.result.output`.\nThe factory unwraps this into `ItemReviewView.generation`. Stale generation is\nomitted while authorized saved reviews remain available; access denials propagate.\nThe reference application still owns its fixture provisioning and HTTP transport.\n"
1628
1628
  }
1629
1629
  ],
1630
1630
  "agentSurface": {
@@ -1651,7 +1651,7 @@
1651
1651
  "code": "not-module-scope",
1652
1652
  "helper": "definePlaybook",
1653
1653
  "message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
1654
- "line": 779,
1654
+ "line": 894,
1655
1655
  "column": 9,
1656
1656
  "sourceFile": "src/test-support/proposals.ts"
1657
1657
  },
@@ -1659,7 +1659,7 @@
1659
1659
  "code": "not-module-scope",
1660
1660
  "helper": "definePlaybook",
1661
1661
  "message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
1662
- "line": 1351,
1662
+ "line": 1466,
1663
1663
  "column": 9,
1664
1664
  "sourceFile": "src/test-support/proposals.ts"
1665
1665
  },
@@ -1667,7 +1667,7 @@
1667
1667
  "code": "not-module-scope",
1668
1668
  "helper": "definePlaybook",
1669
1669
  "message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
1670
- "line": 3772,
1670
+ "line": 3887,
1671
1671
  "column": 9,
1672
1672
  "sourceFile": "src/test-support/proposals.ts"
1673
1673
  },
@@ -1675,7 +1675,7 @@
1675
1675
  "code": "not-module-scope",
1676
1676
  "helper": "definePlaybook",
1677
1677
  "message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
1678
- "line": 4397,
1678
+ "line": 4512,
1679
1679
  "column": 7,
1680
1680
  "sourceFile": "src/test-support/proposals.ts"
1681
1681
  }
@@ -1696,16 +1696,7 @@
1696
1696
  "@happyvertical/smrt-ingestion:IntakeItem",
1697
1697
  "@happyvertical/smrt-ingestion:IntakeEvidence"
1698
1698
  ],
1699
- "nav": [
1700
- {
1701
- "label": "Ingestion inbox",
1702
- "model": "@happyvertical/smrt-ingestion:IntakeItem",
1703
- "icon": "archive",
1704
- "description": "Incoming material that needs authenticated attention.",
1705
- "key": "inbox",
1706
- "noun": "inbox item"
1707
- }
1708
- ],
1699
+ "nav": [],
1709
1700
  "requires": [],
1710
1701
  "group": {
1711
1702
  "id": "ingestion",
@@ -1755,16 +1746,7 @@
1755
1746
  "@happyvertical/smrt-ingestion:IntakeAction",
1756
1747
  "@happyvertical/smrt-ingestion:IntakeReviewDecision"
1757
1748
  ],
1758
- "nav": [
1759
- {
1760
- "label": "Ingestion review",
1761
- "model": "@happyvertical/smrt-ingestion:IntakeReviewDecision",
1762
- "icon": "fileText",
1763
- "description": "Revision-bound decisions on proposed actions.",
1764
- "key": "review",
1765
- "noun": "review decision"
1766
- }
1767
- ],
1749
+ "nav": [],
1768
1750
  "requires": [],
1769
1751
  "group": {
1770
1752
  "id": "ingestion",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-ingestion",
3
- "version": "0.55.12",
3
+ "version": "0.55.14",
4
4
  "description": "Durable tenant-scoped intake and evidence foundations",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -50,32 +50,32 @@
50
50
  }
51
51
  },
52
52
  "dependencies": {
53
- "@happyvertical/smrt-core": "0.55.12",
54
- "@happyvertical/smrt-types": "0.55.12",
55
- "@happyvertical/smrt-tenancy": "0.55.12",
56
- "@happyvertical/smrt-assets": "0.55.12",
57
- "@happyvertical/smrt-jobs": "0.55.12",
58
- "@happyvertical/sql": "^0.103.1",
53
+ "@happyvertical/smrt-core": "0.55.14",
54
+ "@happyvertical/smrt-types": "0.55.14",
55
+ "@happyvertical/smrt-tenancy": "0.55.14",
56
+ "@happyvertical/smrt-assets": "0.55.14",
57
+ "@happyvertical/smrt-jobs": "0.55.14",
58
+ "@happyvertical/sql": "^0.103.2",
59
59
  "@happyvertical/pdf": "^0.65.9",
60
60
  "@happyvertical/ocr": "^0.61.6",
61
- "@happyvertical/speech": "^0.103.1",
62
- "@happyvertical/ai": "^0.103.1",
61
+ "@happyvertical/speech": "^0.103.2",
62
+ "@happyvertical/ai": "^0.103.2",
63
63
  "sharp": "^0.35.5",
64
- "@happyvertical/smrt-agents": "0.55.12",
65
- "@happyvertical/smrt-playbooks": "0.55.12",
64
+ "@happyvertical/smrt-agents": "0.55.14",
65
+ "@happyvertical/smrt-playbooks": "0.55.14",
66
66
  "ajv": "8.20.0",
67
- "@happyvertical/smrt-ui": "0.55.12"
67
+ "@happyvertical/smrt-ui": "0.55.14"
68
68
  },
69
69
  "devDependencies": {
70
- "@happyvertical/smrt-vitest": "0.55.12",
70
+ "@happyvertical/smrt-vitest": "0.55.14",
71
71
  "@types/node": "24.13.6",
72
72
  "typescript": "6.0.3",
73
73
  "vite": "8.1.4",
74
74
  "vitest": "4.1.10",
75
- "@happyvertical/smrt-content": "0.55.12",
76
- "@happyvertical/smrt-messages": "0.55.12",
77
- "@happyvertical/email": "^0.103.1",
78
- "@happyvertical/smrt-users": "0.55.12",
75
+ "@happyvertical/smrt-content": "0.55.14",
76
+ "@happyvertical/smrt-messages": "0.55.14",
77
+ "@happyvertical/email": "^0.103.2",
78
+ "@happyvertical/smrt-users": "0.55.14",
79
79
  "@sveltejs/package": "^2.5.8",
80
80
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
81
81
  "svelte": "^5.57.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"feedback-C3OHD4sA.js","names":["handler","candidate","digest","id"],"sources":["../../src/feedback.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n intakeBindingDigest as digest,\n IntakeExecutionService,\n} from './execution.js';\nimport type { FeedbackConfiguration } from './feedback-contracts.js';\nimport type {\n AdoptRuleInput,\n FeedbackBinding,\n FeedbackExample,\n FeedbackReceipt,\n FeedbackReferences,\n FeedbackSelection,\n ObserveFeedbackInput,\n ReadRuleInput,\n RecordFeedbackInput,\n RoutingRule,\n RuleAdoption,\n RuleSuggestion,\n SuggestRuleInput,\n} from './feedback-dto.js';\nimport {\n type FeedbackActionContext,\n feedbackActionTransaction,\n feedbackDiscoveryContext,\n} from './feedback-internal.js';\nimport type { GenerationOutput } from './proposal-dto.js';\nimport type { IngestionOptions } from './server.js';\n\ntype Row = Record<string, unknown>;\nfunction object(value: unknown): Row {\n const result = typeof value === 'string' ? JSON.parse(value) : value;\n if (!result || typeof result !== 'object' || Array.isArray(result))\n throw new Error('Feedback unavailable');\n return result as Row;\n}\nfunction text(value: unknown, max = 512): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > max)\n throw new Error('Invalid feedback');\n}\nfunction resultData(data: Row): Row {\n return {\n status: data.status,\n provider: data.provider,\n model: data.model,\n version: data.version,\n output: data.output,\n usage: data.usage,\n ...(Object.hasOwn(data, 'error') ? { error: data.error } : {}),\n ...(Object.hasOwn(data, 'confidence')\n ? { confidence: data.confidence }\n : {}),\n };\n}\nexport function feedbackTerms(value: string): string[] {\n return [\n ...new Set(value.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []),\n ].sort();\n}\nexport function feedbackSimilarity(left: string, right: string): number {\n const a = new Set(feedbackTerms(left)),\n b = new Set(feedbackTerms(right));\n const union = new Set([...a, ...b]);\n return union.size\n ? [...a].filter((value) => b.has(value)).length / union.size\n : 0;\n}\nexport interface RetrieveFeedbackInput {\n itemId: string;\n query: string;\n offered: GenerationOutput['offered'];\n promptVersion: string;\n configurationVersion: string;\n model: { provider: string; model: string; version: string };\n providers?: string[];\n}\n/** Owning ingestion ledger. Generic LearningMemory's success/ancestor fallback semantics are deliberately not used. */\nexport class IntakeFeedbackService {\n private readonly execution: IntakeExecutionService;\n private readonly config: FeedbackConfiguration;\n private readonly lineage = new Set<string>();\n private exampleChecks = 0;\n constructor(\n private readonly options: IngestionOptions,\n execution?: IntakeExecutionService,\n ) {\n if (!options.execution || !options.feedback)\n throw new Error('Feedback not configured');\n this.config = { ...options.feedback };\n this.execution =\n execution ?? new IntakeExecutionService(options, options.execution);\n text(this.config.version);\n for (const [value, max] of [\n [this.config.maxExamples, 20],\n [this.config.maxScan, 1000],\n [this.config.maxBytes, 1000000],\n ])\n if (!Number.isSafeInteger(value) || value < 1 || value > max)\n throw new Error('Invalid feedback limits');\n if (\n !Number.isFinite(this.config.minimumSimilarity) ||\n this.config.minimumSimilarity < 0.2 ||\n this.config.minimumSimilarity > 1\n )\n throw new Error('Invalid feedback similarity');\n }\n private configurationDigest() {\n const { version, maxExamples, maxScan, maxBytes, minimumSimilarity } =\n this.config;\n return digest({\n version,\n maxExamples,\n maxScan,\n maxBytes,\n minimumSimilarity,\n });\n }\n private routing(\n ctx: FeedbackActionContext,\n ): Pick<RoutingRule, 'args' | 'projection'> {\n // Read live trusted configuration again at publication/replay boundaries.\n const declarations = this.options.feedback?.routing;\n if (declarations === undefined) return { args: ctx.args };\n if (!Array.isArray(declarations))\n throw new Error('Invalid routing projection');\n const seen = new Set<string>();\n for (const declaration of declarations) {\n const entry = object(declaration);\n text(entry.handlerId);\n text(entry.handlerVersion);\n text(entry.version);\n const key = digest([entry.handlerId, entry.handlerVersion]);\n const handler = this.options.execution!.handlers.find(\n (handler) =>\n handler.id === entry.handlerId &&\n handler.version === entry.handlerVersion,\n );\n if (!handler || seen.has(key))\n throw new Error('Invalid routing projection');\n seen.add(key);\n const properties = object(handler.argsSchema.properties);\n if (\n !Array.isArray(entry.fields) ||\n !entry.fields.length ||\n entry.fields.length > 64 ||\n new Set(entry.fields).size !== entry.fields.length\n )\n throw new Error('Invalid routing projection');\n for (const field of entry.fields) {\n text(field);\n if (\n ['__proto__', 'prototype', 'constructor'].includes(field) ||\n !Object.hasOwn(properties, field)\n )\n throw new Error('Invalid routing projection');\n }\n }\n const selected = declarations.find(\n (entry) =>\n entry.handlerId === ctx.handlerId &&\n entry.handlerVersion === ctx.handlerVersion,\n );\n if (!selected) return { args: ctx.args };\n const fields = [...selected.fields].sort();\n const args = Object.fromEntries(\n fields\n .filter((field) => Object.hasOwn(ctx.args, field))\n .map((field) => [field, structuredClone(ctx.args[field])]),\n );\n if (!Object.keys(args).length)\n throw new Error('Routing values unavailable');\n return { args, projection: { version: selected.version, fields } };\n }\n private scope() {\n return this.options.scope;\n }\n private async rows(\n db: DatabaseInterface,\n where: string,\n params: unknown[] = [],\n ): Promise<Row[]> {\n const scope = this.scope();\n return (\n await db.query(\n `SELECT * FROM intake_feedback WHERE tenant_id=? AND confidential_scope_id=? AND ${where}`,\n scope.tenantId,\n scope.confidentialScopeId,\n ...params,\n )\n ).rows;\n }\n private async authorize(\n ctx: FeedbackActionContext,\n operation: 'capture' | 'retrieve' | 'suggest' | 'adopt',\n ) {\n if (\n !(await this.config.authorize({\n db: ctx.db,\n scope: this.scope(),\n itemId: ctx.itemId,\n operation,\n }))\n )\n throw new Error('Feedback unavailable');\n }\n private checkBinding(input: FeedbackBinding, ctx: FeedbackActionContext) {\n if (\n input.itemId !== ctx.itemId ||\n input.actionId !== ctx.review.actionId ||\n input.expectedRevision !== ctx.review.revision ||\n input.expectedReviewVersion !== ctx.review.reviewVersion ||\n input.bindingHash !== ctx.review.bindingHash\n )\n throw new Error('Stale feedback binding');\n }\n private async insert(\n ctx: FeedbackActionContext,\n key: string,\n kind: string,\n data: Row,\n supersedesId: string | null = null,\n ): Promise<Row> {\n const serialized = JSON.stringify(data);\n if (\n Buffer.byteLength(serialized) >\n Math.min(this.config.maxBytes, ctx.context.policy.maxBytes)\n )\n throw new Error('Feedback limit');\n const scope = this.scope(),\n now = (this.options.now?.() ?? new Date()).toISOString();\n const row = {\n id: randomUUID(),\n slug: randomUUID(),\n context: '',\n created_at: now,\n updated_at: now,\n tenant_id: scope.tenantId,\n confidential_scope_id: scope.confidentialScopeId,\n item_id: ctx.itemId,\n request_key: key,\n supersedes_id: supersedesId,\n kind,\n data: serialized,\n };\n return (\n await ctx.db.query(\n `INSERT INTO intake_feedback (${Object.keys(row).join(',')}) VALUES (${Object.keys(\n row,\n )\n .map(() => '?')\n .join(',')}) RETURNING *`,\n ...Object.values(row),\n )\n ).rows[0];\n }\n private receipt(row: Row): FeedbackReceipt {\n return {\n id: String(row.id),\n digest: String(object(row.data).digest),\n kind: row.kind as FeedbackReceipt['kind'],\n };\n }\n private async provenance(ctx: FeedbackActionContext) {\n const output = object(ctx.result.output),\n generation = object(output.proposals),\n pin = object(generation.source),\n provenance = object(generation.provenance);\n if (provenance.feedback) {\n const inherited = object(provenance.feedback);\n const key = ctx.attemptId;\n if (this.lineage.has(key) || this.lineage.size >= 8)\n throw new Error('Feedback lineage unavailable');\n this.lineage.add(key);\n try {\n await this.assertSelection(\n {\n itemId: ctx.itemId,\n query: String(inherited.query),\n offered: generation.offered as GenerationOutput['offered'],\n promptVersion: String(provenance.promptVersion),\n configurationVersion: String(provenance.configurationVersion),\n model: provenance.generative as RetrieveFeedbackInput['model'],\n providers: [\n String(object(provenance.generative).provider),\n ...(object(provenance.decision).configured\n ? [String(object(provenance.decision).provider)]\n : []),\n ],\n },\n inherited.selection as unknown as FeedbackReferences,\n ctx.db,\n );\n } finally {\n this.lineage.delete(key);\n }\n }\n const scope = this.scope();\n const [source] = (\n await ctx.db.query(\n 'SELECT data,output_digest FROM intake_analysis_attempts WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND id=?',\n scope.tenantId,\n scope.confidentialScopeId,\n ctx.itemId,\n pin.attemptId,\n )\n ).rows;\n if (!source || source.output_digest !== pin.outputDigest)\n throw new Error('Feedback source unavailable');\n const sourceResult = resultData(object(source.data));\n if (digest(sourceResult) !== pin.outputDigest)\n throw new Error('Feedback source integrity');\n const results = object(sourceResult.output).results;\n if (!Array.isArray(results))\n throw new Error('Feedback extraction unavailable');\n const query = results\n .flatMap((entry) => {\n const segments = object(entry).segments;\n return Array.isArray(segments)\n ? segments.map((segment) => String(object(segment).text ?? ''))\n : [];\n })\n .join('\\n')\n .slice(0, 4096);\n const model = object(provenance.generative);\n for (const field of ['provider', 'model', 'version']) text(model[field]);\n text(provenance.promptVersion);\n text(provenance.configurationVersion);\n return {\n query,\n model: {\n provider: String(model.provider),\n model: String(model.model),\n version: String(model.version),\n },\n promptVersion: String(provenance.promptVersion),\n configurationVersion: String(provenance.configurationVersion),\n attemptId: ctx.attemptId,\n evidence: object(ctx.analysis).inputs,\n source: pin,\n };\n }\n /** Internal saved-action gate; the execution owner supplies its transaction. */\n async assertActionLineage(\n actionId: string,\n db: DatabaseInterface,\n proposalId: string,\n ): Promise<void> {\n await this.execution[feedbackActionTransaction](\n actionId,\n false,\n async (ctx) => {\n await this.provenance(ctx);\n },\n db,\n undefined,\n proposalId,\n );\n }\n async record(input: RecordFeedbackInput): Promise<FeedbackReceipt> {\n digest(input);\n text(input.requestId);\n if (\n !['correct', 'incorrect'].includes(input.judgment) ||\n (input.comment !== undefined &&\n (typeof input.comment !== 'string' || input.comment.length > 4000))\n )\n throw new Error('Invalid feedback');\n const frozen = structuredClone(input);\n return this.execution[feedbackActionTransaction](\n input.actionId,\n true,\n async (ctx) => {\n await this.authorize(ctx, 'capture');\n this.checkBinding(frozen, ctx);\n const requestHash = digest(frozen),\n key = `judgment:${frozen.requestId}`;\n const [replay] = await this.rows(\n ctx.db,\n 'item_id=? AND request_key=?',\n [ctx.itemId, key],\n );\n if (replay) {\n const data = object(replay.data);\n if (\n data.requestHash !== requestHash ||\n data.reviewer !== this.scope().actorId\n )\n throw new Error('Feedback request conflict');\n return this.receipt(replay);\n }\n if (frozen.supersedesId) {\n const [old] = await this.rows(\n ctx.db,\n 'item_id=? AND id=? AND kind=?',\n [ctx.itemId, frozen.supersedesId, 'interpretation'],\n );\n if (\n !old ||\n object(old.data).actionId !== frozen.actionId ||\n (await this.rows(ctx.db, 'supersedes_id=?', [old.id])).length\n )\n throw new Error('Feedback supersession conflict');\n }\n const provenance = await this.provenance(ctx),\n routing = this.routing(ctx);\n const body = {\n version: 1,\n requestHash,\n reviewer: this.scope().actorId,\n actionId: ctx.review.actionId,\n revision: ctx.review.revision,\n reviewVersion: ctx.review.reviewVersion,\n bindingHash: ctx.review.bindingHash,\n handlerId: ctx.handlerId,\n handlerVersion: ctx.handlerVersion,\n args: ctx.args,\n ...(routing.projection ? { routing } : {}),\n judgment: frozen.judgment,\n comment: frozen.comment ?? '',\n ...provenance,\n };\n const row = await this.insert(\n ctx,\n key,\n 'interpretation',\n { ...body, digest: digest(body) },\n frozen.supersedesId ?? null,\n );\n await this.authorize(ctx, 'capture');\n if (digest(routing) !== digest(this.routing(ctx)))\n throw new Error('Routing projection changed');\n return this.receipt(row);\n },\n );\n }\n /** Consume a durable owner event idempotently. Never derive correctness from these signals. */\n async observe(input: ObserveFeedbackInput): Promise<FeedbackReceipt> {\n digest(input);\n text(input.eventId);\n if (!['action_decision', 'downstream_outcome'].includes(input.kind))\n throw new Error('Invalid feedback kind');\n return this.execution[feedbackActionTransaction](\n input.actionId,\n true,\n async (ctx) => {\n await this.authorize(ctx, 'capture');\n this.checkBinding(input, ctx);\n const scope = this.scope();\n const table =\n input.kind === 'action_decision'\n ? 'intake_review_decisions'\n : 'intake_executions';\n const [event] = (\n await ctx.db.query(\n `SELECT * FROM ${table} WHERE tenant_id=? AND confidential_scope_id=? AND item_id=? AND action_id=? AND id=?`,\n scope.tenantId,\n scope.confidentialScopeId,\n ctx.itemId,\n input.actionId,\n input.eventId,\n )\n ).rows;\n if (!event || event.binding_hash !== ctx.review.bindingHash)\n throw new Error('Feedback event unavailable');\n const state =\n input.kind === 'action_decision' ? event.decision : event.state;\n if (\n input.kind === 'downstream_outcome' &&\n !['succeeded', 'failed', 'outcome_unknown'].includes(String(state))\n )\n throw new Error('Outcome is not terminal');\n const body = {\n version: 1,\n eventId: input.eventId,\n actionId: input.actionId,\n revision: ctx.review.revision,\n reviewer:\n input.kind === 'action_decision'\n ? object(event.data).reviewer\n : null,\n observedBy: this.scope().actorId,\n principalId: object(event.data).principalId ?? null,\n signal: state,\n provenance: await this.provenance(ctx),\n };\n const key = `event:${input.kind}:${input.eventId}:${String(state)}`;\n const [existing] = await this.rows(\n ctx.db,\n 'item_id=? AND request_key=?',\n [ctx.itemId, key],\n );\n if (existing) return this.receipt(existing);\n const row = await this.insert(ctx, key, input.kind, {\n ...body,\n digest: digest(body),\n });\n await this.authorize(ctx, 'capture');\n return this.receipt(row);\n },\n );\n }\n private async example(\n row: Row,\n input: RetrieveFeedbackInput,\n executor?: DatabaseInterface,\n ): Promise<FeedbackExample | undefined> {\n if (++this.exampleChecks > this.config.maxScan) return undefined;\n try {\n const candidate = object(row.data);\n // Retention deliberately redacts ledger payloads. Reject tombstones before\n // issuing a UUID query: catching a PostgreSQL cast error cannot repair its transaction.\n if (\n typeof candidate.actionId !== 'string' ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(\n candidate.actionId,\n )\n )\n return undefined;\n return await this.execution[feedbackActionTransaction](\n candidate.actionId,\n false,\n async (ctx) => {\n await this.authorize(ctx, 'retrieve');\n await this.provenance(ctx);\n const [current] = await this.rows(\n ctx.db,\n 'id=? AND kind=? AND NOT EXISTS (SELECT 1 FROM intake_feedback successor WHERE successor.tenant_id=intake_feedback.tenant_id AND successor.confidential_scope_id=intake_feedback.confidential_scope_id AND successor.supersedes_id=intake_feedback.id)',\n [row.id, 'interpretation'],\n );\n if (!current) return undefined;\n const data = object(current.data);\n const { digest: stored, ...body } = data;\n if (digest(body) !== stored) throw new Error('Feedback integrity');\n if (\n data.revision !== ctx.review.revision ||\n data.bindingHash !== ctx.review.bindingHash ||\n data.attemptId !== ctx.attemptId ||\n data.promptVersion !== input.promptVersion ||\n data.configurationVersion !== input.configurationVersion ||\n digest(data.model) !== digest(input.model)\n )\n return undefined;\n const offered = input.offered.find(\n (entry) =>\n entry.handler.id === data.handlerId &&\n entry.handler.version === data.handlerVersion,\n );\n if (!offered) return undefined;\n const args = object(data.args);\n for (const [field, reference] of Object.entries(\n offered.handler.references,\n )) {\n if (\n reference.kind === 'candidate' &&\n Object.hasOwn(args, field) &&\n !offered.candidates.some(\n (candidate) =>\n candidate.id === args[field] &&\n candidate.model === reference.model,\n )\n )\n return undefined;\n }\n return {\n feedbackId: String(current.id),\n digest: String(stored),\n itemId: ctx.itemId,\n actionId: ctx.review.actionId,\n revision: ctx.review.revision,\n handlerId: ctx.handlerId,\n handlerVersion: ctx.handlerVersion,\n judgment: data.judgment as 'correct' | 'incorrect',\n query: String(data.query),\n args,\n model: data.model as FeedbackExample['model'],\n promptVersion: String(data.promptVersion),\n configurationVersion: String(data.configurationVersion),\n };\n },\n executor,\n input.providers ?? [input.model.provider],\n );\n } catch {\n return undefined;\n }\n }\n private receivingContext(\n input: RetrieveFeedbackInput,\n executor: DatabaseInterface | undefined,\n work: (\n context: import('./execution-contracts.js').HandlerContext,\n ) => Promise<FeedbackSelection>,\n ): Promise<FeedbackSelection> {\n let limit = this.config.maxBytes;\n let bytes: number | undefined;\n const validate = async (\n context: import('./execution-contracts.js').HandlerContext,\n ) => {\n if (\n (input.providers ?? [input.model.provider]).some(\n (provider) => !context.policy.providers.includes(provider),\n )\n )\n throw new Error('Feedback recipient unavailable');\n limit = Math.min(limit, context.policy.maxBytes);\n if (bytes !== undefined && bytes > limit)\n throw new Error('Feedback limit');\n };\n const visit = (\n index: number,\n db: DatabaseInterface | undefined,\n ): Promise<FeedbackSelection> => {\n const entry = input.offered[index];\n return this.execution[feedbackDiscoveryContext](\n db,\n input.itemId,\n entry.handler.id,\n entry.handler.version,\n async (context) => {\n await validate(context);\n const selection =\n index + 1 < input.offered.length\n ? await visit(index + 1, context.db)\n : await work(context);\n bytes = Buffer.byteLength(JSON.stringify(selection));\n if (bytes > limit) throw new Error('Feedback limit');\n return selection;\n },\n validate,\n );\n };\n return visit(0, executor);\n }\n async retrieve(\n input: RetrieveFeedbackInput,\n executor?: DatabaseInterface,\n ): Promise<FeedbackSelection> {\n text(input.query, 4096);\n const offered = input.offered[0];\n if (!offered)\n return {\n version: this.config.version,\n configurationDigest: this.configurationDigest(),\n examples: [],\n };\n const work = async (\n context: import('./execution-contracts.js').HandlerContext,\n ) => {\n const authorize = async () => {\n if (\n !(await this.config.authorize({\n db: context.db,\n scope: this.scope(),\n itemId: input.itemId,\n operation: 'retrieve',\n }))\n )\n throw new Error('Feedback unavailable');\n };\n await authorize();\n const scope = this.scope();\n const rows = (\n await context.db.query(\n \"SELECT * FROM intake_feedback WHERE tenant_id=? AND confidential_scope_id=? AND kind='interpretation' ORDER BY id LIMIT ?\",\n scope.tenantId,\n scope.confidentialScopeId,\n this.config.maxScan,\n )\n ).rows;\n const ranked: Array<{ example: FeedbackExample; score: number }> = [];\n for (const row of rows) {\n const example = await this.example(row, input, context.db);\n if (!example) continue;\n const score = feedbackSimilarity(input.query, example.query);\n if (score >= this.config.minimumSimilarity)\n ranked.push({ example, score });\n }\n ranked.sort(\n (a, b) =>\n b.score - a.score ||\n a.example.feedbackId.localeCompare(b.example.feedbackId),\n );\n const selection = {\n version: this.config.version,\n configurationDigest: this.configurationDigest(),\n examples: ranked\n .slice(0, this.config.maxExamples)\n .map((entry) => entry.example),\n };\n await authorize();\n return selection;\n };\n return this.receivingContext(input, executor, work);\n }\n async assertSelection(\n input: RetrieveFeedbackInput,\n selection: FeedbackReferences,\n executor?: DatabaseInterface,\n ): Promise<void> {\n if (\n selection.version !== this.config.version ||\n selection.configurationDigest !== this.configurationDigest() ||\n !Array.isArray(selection.examples) ||\n selection.examples.length > this.config.maxExamples ||\n new Set(selection.examples.map((example) => example.feedbackId)).size !==\n selection.examples.length ||\n Buffer.byteLength(JSON.stringify(selection)) > this.config.maxBytes\n )\n throw new Error('Feedback eligibility changed');\n const offered = input.offered[0];\n if (!offered) {\n if (selection.examples.length)\n throw new Error('Feedback eligibility changed');\n return;\n }\n const work = async (\n context: import('./execution-contracts.js').HandlerContext,\n ) => {\n if (\n !(await this.config.authorize({\n db: context.db,\n scope: this.scope(),\n itemId: input.itemId,\n operation: 'retrieve',\n }))\n )\n throw new Error('Feedback unavailable');\n const examples: FeedbackExample[] = [];\n for (const expected of selection.examples) {\n const [row] = await this.rows(context.db, 'id=? AND kind=?', [\n expected.feedbackId,\n 'interpretation',\n ]);\n const current = row\n ? await this.example(row, input, context.db)\n : undefined;\n if (\n !current ||\n current.digest !== expected.digest ||\n feedbackSimilarity(input.query, current.query) <\n this.config.minimumSimilarity\n )\n throw new Error('Feedback eligibility changed');\n examples.push(current);\n }\n if (\n !(await this.config.authorize({\n db: context.db,\n scope: this.scope(),\n itemId: input.itemId,\n operation: 'retrieve',\n }))\n )\n throw new Error('Feedback unavailable');\n return { ...selection, examples };\n };\n await this.receivingContext(input, executor, work);\n }\n private async support(\n ctx: FeedbackActionContext,\n ids: string[],\n ): Promise<Array<{ id: string; digest: string; query: string }>> {\n if (\n !Array.isArray(ids) ||\n ids.length < 2 ||\n ids.length > this.config.maxExamples ||\n new Set(ids).size !== ids.length\n )\n throw new Error('Insufficient rule evidence');\n const provenance = await this.provenance(ctx),\n origins = new Set<string>(),\n result: Array<{ id: string; digest: string; query: string }> = [];\n for (const id of [...ids].sort()) {\n text(id);\n const [row] = await this.rows(ctx.db, 'id=? AND kind=?', [\n id,\n 'interpretation',\n ]);\n if (!row) throw new Error('Rule evidence unavailable');\n const data = object(row.data);\n await this.execution[feedbackActionTransaction](\n String(data.actionId),\n false,\n async (source) => {\n await this.authorize(source, 'retrieve');\n await this.provenance(source);\n if (origins.has(source.itemId))\n throw new Error('Independent rule evidence required');\n origins.add(source.itemId);\n const { digest: stored, ...body } = data;\n if (\n digest(body) !== stored ||\n data.judgment !== 'correct' ||\n data.revision !== source.review.revision ||\n data.bindingHash !== source.review.bindingHash ||\n data.attemptId !== source.attemptId ||\n data.handlerId !== source.handlerId ||\n data.handlerVersion !== source.handlerVersion ||\n data.handlerId !== ctx.handlerId ||\n data.handlerVersion !== ctx.handlerVersion ||\n digest(data.args) !== digest(source.args) ||\n digest(data.routing ?? { args: data.args }) !==\n digest(this.routing(source)) ||\n digest(this.routing(source)) !== digest(this.routing(ctx)) ||\n data.promptVersion !== provenance.promptVersion ||\n data.configurationVersion !== provenance.configurationVersion ||\n digest(data.model) !== digest(provenance.model) ||\n (await this.rows(ctx.db, 'supersedes_id=?', [id])).length\n )\n throw new Error('Rule evidence unavailable');\n result.push({\n id,\n digest: String(stored),\n query: String(data.query),\n });\n },\n ctx.db,\n );\n }\n return result;\n }\n async suggest(input: SuggestRuleInput): Promise<RuleSuggestion> {\n digest(input);\n text(input.requestId);\n if (!this.config.policy) throw new Error('Rule policy owner unavailable');\n return this.execution[feedbackActionTransaction](\n input.actionId,\n true,\n async (ctx) => {\n this.checkBinding(input, ctx);\n await this.authorize(ctx, 'suggest');\n const support = await this.support(ctx, input.supportingFeedbackIds);\n const terms = feedbackTerms(support[0].query).filter((term) =>\n support.every((example) =>\n feedbackTerms(example.query).includes(term),\n ),\n );\n if (!terms.length) throw new Error('No shared routing evidence');\n const rule: RoutingRule = {\n handlerId: ctx.handlerId,\n handlerVersion: ctx.handlerVersion,\n matchTerms: terms,\n ...this.routing(ctx),\n };\n const preview = await this.config.policy!.preview({\n db: ctx.db,\n scope: this.scope(),\n rule: structuredClone(rule),\n });\n text(preview.version);\n text(preview.preview, 4000);\n const body = {\n version: 1,\n actionId: input.actionId,\n revision: ctx.review.revision,\n bindingHash: ctx.review.bindingHash,\n rule,\n supportingFeedback: support.map(({ id, digest }) => ({ id, digest })),\n expectedPolicyVersion: preview.version,\n preview: preview.preview,\n reviewer: this.scope().actorId,\n requestHash: digest(input),\n };\n const key = `rule:${input.requestId}`;\n let [row] = await this.rows(ctx.db, 'item_id=? AND request_key=?', [\n ctx.itemId,\n key,\n ]);\n if (row) {\n if (object(row.data).requestHash !== body.requestHash)\n throw new Error('Rule request conflict');\n } else\n row = await this.insert(ctx, key, 'rule_suggestion', {\n ...body,\n digest: digest(body),\n });\n await this.authorize(ctx, 'suggest');\n await this.rule(ctx, String(row.id));\n return this.ruleDTO(row);\n },\n );\n }\n private ruleDTO(row: Row): RuleSuggestion {\n const data = object(row.data);\n return {\n id: String(row.id),\n digest: String(data.digest),\n itemId: String(row.item_id),\n rule: data.rule as unknown as RoutingRule,\n supportingFeedback:\n data.supportingFeedback as RuleSuggestion['supportingFeedback'],\n expectedPolicyVersion: String(data.expectedPolicyVersion),\n preview: String(data.preview),\n automaticActionEligible: false,\n };\n }\n private async rule(ctx: FeedbackActionContext, id: string): Promise<Row> {\n const [row] = await this.rows(ctx.db, 'item_id=? AND id=? AND kind=?', [\n ctx.itemId,\n id,\n 'rule_suggestion',\n ]);\n if (!row) throw new Error('Rule unavailable');\n const data = object(row.data),\n { digest: stored, ...body } = data;\n if (\n digest(body) !== stored ||\n data.actionId !== ctx.review.actionId ||\n data.revision !== ctx.review.revision ||\n data.bindingHash !== ctx.review.bindingHash\n )\n throw new Error('Stale rule');\n const rule = object(data.rule);\n if (\n rule.handlerId !== ctx.handlerId ||\n rule.handlerVersion !== ctx.handlerVersion ||\n digest({\n args: rule.args,\n ...(rule.projection ? { projection: rule.projection } : {}),\n }) !== digest(this.routing(ctx))\n )\n throw new Error('Rule routing projection changed');\n const support = data.supportingFeedback as Array<{\n id: string;\n digest: string;\n }>;\n const current = await this.support(\n ctx,\n support.map((entry) => entry.id),\n );\n if (\n digest(current.map(({ id, digest }) => ({ id, digest }))) !==\n digest(support)\n )\n throw new Error('Rule evidence changed');\n return row;\n }\n async readRule(input: ReadRuleInput): Promise<RuleSuggestion> {\n return this.execution[feedbackActionTransaction](\n input.actionId,\n true,\n async (ctx) => {\n this.checkBinding(input, ctx);\n await this.authorize(ctx, 'suggest');\n const suggestion = this.ruleDTO(\n await this.rule(ctx, input.suggestionId),\n );\n if (!this.config.policy)\n throw new Error('Rule policy owner unavailable');\n const current = await this.config.policy.preview({\n db: ctx.db,\n scope: this.scope(),\n rule: structuredClone(suggestion.rule),\n });\n if (\n current.version !== suggestion.expectedPolicyVersion ||\n current.preview !== suggestion.preview\n )\n throw new Error('Rule policy changed');\n await this.authorize(ctx, 'suggest');\n await this.rule(ctx, input.suggestionId);\n return suggestion;\n },\n );\n }\n async adopt(input: AdoptRuleInput): Promise<RuleAdoption> {\n digest(input);\n text(input.requestId);\n if (!this.config.policy) throw new Error('Rule policy owner unavailable');\n return this.execution[feedbackActionTransaction](\n input.actionId,\n true,\n async (ctx) => {\n this.checkBinding(input, ctx);\n await this.authorize(ctx, 'adopt');\n const row = await this.rule(ctx, input.suggestionId),\n suggestion = this.ruleDTO(row);\n if (\n input.expectedDigest !== suggestion.digest ||\n input.expectedPolicyVersion !== suggestion.expectedPolicyVersion\n )\n throw new Error('Stale rule');\n const requestHash = digest(input),\n key = `adopt:${input.requestId}`;\n const [replay] = await this.rows(\n ctx.db,\n 'item_id=? AND request_key=?',\n [ctx.itemId, key],\n );\n if (replay) {\n const data = object(replay.data);\n if (\n data.requestHash !== requestHash ||\n data.reviewer !== this.scope().actorId\n )\n throw new Error('Rule request conflict');\n return {\n id: String(replay.id),\n policyVersion: String(data.policyVersion),\n auditId: String(data.auditId),\n automaticActionEligible: false,\n };\n }\n const current = await this.config.policy!.preview({\n db: ctx.db,\n scope: this.scope(),\n rule: structuredClone(suggestion.rule),\n });\n if (current.version !== input.expectedPolicyVersion)\n throw new Error('Policy version changed');\n const applied = await this.config.policy!.adopt({\n db: ctx.db,\n scope: this.scope(),\n rule: structuredClone(suggestion.rule),\n expectedVersion: input.expectedPolicyVersion,\n requestId: input.requestId,\n });\n text(applied.version);\n text(applied.auditId);\n if (applied.version === input.expectedPolicyVersion)\n throw new Error('Policy version did not advance');\n const verified = await this.config.policy!.preview({\n db: ctx.db,\n scope: this.scope(),\n rule: structuredClone(suggestion.rule),\n });\n if (verified.version !== applied.version)\n throw new Error('Policy adoption mismatch');\n const body = {\n version: 1,\n requestHash,\n suggestionId: suggestion.id,\n suggestionDigest: suggestion.digest,\n previousPolicyVersion: input.expectedPolicyVersion,\n policyVersion: applied.version,\n auditId: applied.auditId,\n reviewer: this.scope().actorId,\n automaticActionEligible: false,\n };\n const saved = await this.insert(ctx, key, 'rule_adoption', {\n ...body,\n digest: digest(body),\n });\n await this.authorize(ctx, 'adopt');\n await this.rule(ctx, input.suggestionId);\n return {\n id: String(saved.id),\n policyVersion: applied.version,\n auditId: applied.auditId,\n automaticActionEligible: false,\n };\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AA+BA,SAAS,OAAO,OAAqB;CACnC,MAAM,SAAS,OAAO,UAAU,WAAW,KA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