@happyvertical/smrt-ingestion 0.55.6 → 0.55.8

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 (77) hide show
  1. package/AGENTS.md +13 -3
  2. package/FEEDBACK.md +156 -0
  3. package/README.md +15 -3
  4. package/REVIEW.md +137 -0
  5. package/dist/chunks/{execution-C6HJvl9e.js → execution-C7sTFXFU.js} +375 -11
  6. package/dist/chunks/execution-C7sTFXFU.js.map +1 -0
  7. package/dist/chunks/execution-internal-DWteDHM2.js.map +1 -1
  8. package/dist/chunks/feedback-C3OHD4sA.js +625 -0
  9. package/dist/chunks/feedback-C3OHD4sA.js.map +1 -0
  10. package/dist/chunks/{extraction-bseWZuWN.js → proposal-errors-z24VKWnQ.js} +10 -2
  11. package/dist/chunks/proposal-errors-z24VKWnQ.js.map +1 -0
  12. package/dist/dto.d.ts +2 -0
  13. package/dist/dto.d.ts.map +1 -1
  14. package/dist/execution-internal.d.ts +3 -1
  15. package/dist/execution-internal.d.ts.map +1 -1
  16. package/dist/execution.d.ts +15 -1
  17. package/dist/execution.d.ts.map +1 -1
  18. package/dist/execution.js +1 -1
  19. package/dist/feedback-contracts.d.ts +51 -0
  20. package/dist/feedback-contracts.d.ts.map +1 -0
  21. package/dist/feedback-dto.d.ts +106 -0
  22. package/dist/feedback-dto.d.ts.map +1 -0
  23. package/dist/feedback-internal.d.ts +19 -0
  24. package/dist/feedback-internal.d.ts.map +1 -0
  25. package/dist/feedback.d.ts +54 -0
  26. package/dist/feedback.d.ts.map +1 -0
  27. package/dist/manifest.json +34 -1
  28. package/dist/models.js +1 -1
  29. package/dist/models.js.map +1 -1
  30. package/dist/proposal-contracts.d.ts +4 -0
  31. package/dist/proposal-contracts.d.ts.map +1 -1
  32. package/dist/proposal-dto.d.ts +4 -0
  33. package/dist/proposal-dto.d.ts.map +1 -1
  34. package/dist/proposal-errors.d.ts +5 -0
  35. package/dist/proposal-errors.d.ts.map +1 -0
  36. package/dist/proposal-sdk.d.ts.map +1 -1
  37. package/dist/proposals.d.ts +4 -1
  38. package/dist/proposals.d.ts.map +1 -1
  39. package/dist/proposals.js +114 -15
  40. package/dist/proposals.js.map +1 -1
  41. package/dist/review-dto.d.ts +115 -0
  42. package/dist/review-dto.d.ts.map +1 -0
  43. package/dist/server.d.ts +24 -0
  44. package/dist/server.d.ts.map +1 -1
  45. package/dist/server.js +146 -54
  46. package/dist/server.js.map +1 -1
  47. package/dist/smrt-knowledge.json +97 -14
  48. package/dist/svelte/components/ActionReview.svelte +232 -0
  49. package/dist/svelte/components/ActionReview.svelte.d.ts +15 -0
  50. package/dist/svelte/components/ActionReview.svelte.d.ts.map +1 -0
  51. package/dist/svelte/components/EvidenceViewer.svelte +31 -0
  52. package/dist/svelte/components/EvidenceViewer.svelte.d.ts +8 -0
  53. package/dist/svelte/components/EvidenceViewer.svelte.d.ts.map +1 -0
  54. package/dist/svelte/components/InboxView.svelte +119 -0
  55. package/dist/svelte/components/InboxView.svelte.d.ts +9 -0
  56. package/dist/svelte/components/InboxView.svelte.d.ts.map +1 -0
  57. package/dist/svelte/components/IntakeInbox.svelte +11 -0
  58. package/dist/svelte/components/IntakeInbox.svelte.d.ts +10 -0
  59. package/dist/svelte/components/IntakeInbox.svelte.d.ts.map +1 -0
  60. package/dist/svelte/components/IntakeReview.svelte +11 -0
  61. package/dist/svelte/components/IntakeReview.svelte.d.ts +10 -0
  62. package/dist/svelte/components/IntakeReview.svelte.d.ts.map +1 -0
  63. package/dist/svelte/components/ReviewView.svelte +243 -0
  64. package/dist/svelte/components/ReviewView.svelte.d.ts +9 -0
  65. package/dist/svelte/components/ReviewView.svelte.d.ts.map +1 -0
  66. package/dist/svelte/i18n.d.ts +72 -0
  67. package/dist/svelte/i18n.d.ts.map +1 -0
  68. package/dist/svelte/i18n.js +72 -0
  69. package/dist/svelte/index.d.ts +5 -0
  70. package/dist/svelte/index.d.ts.map +1 -0
  71. package/dist/svelte/index.js +3 -0
  72. package/dist/svelte/view-utils.d.ts +13 -0
  73. package/dist/svelte/view-utils.d.ts.map +1 -0
  74. package/dist/svelte/view-utils.js +96 -0
  75. package/package.json +49 -22
  76. package/dist/chunks/execution-C6HJvl9e.js.map +0 -1
  77. package/dist/chunks/extraction-bseWZuWN.js.map +0 -1
@@ -3,19 +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.6",
6
+ "packageVersion": "0.55.8",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "d79161b90fb56e63e5d88658a58943c662f26d49e400466664c457508a429fdb",
11
- "packageJson": "7d352d56fcd07a61126e99cadc33dfc5f2a33c63a16aa053793241e03c593173",
12
- "agents": "641b3e98116c5eb0c6b4dec127beaeacd293fe87e0ed98d2d07d8ed264fe36b6",
10
+ "manifest": "c1c496cd1c89cd95614c46e10a7291611ee804745322f42c1daf85089d211a6f",
11
+ "packageJson": "449a59551333b1e68201ebcb171f1e72bf2930bf6f838aa545c18c9fc7a89895",
12
+ "agents": "dea14442054ec1de798cba9be1fbdd955f44b0e4672639cbf3db8101d290c1fb",
13
13
  "moduleDoc:agents/execution.md": "6153206adeea46fee1be57ccc01d171621ffb3dc3a754b3634bfe2ce367e8416",
14
- "moduleDoc:README.md": "8c22e7879e7d7caaedd87de59e7603192d909b8a8d60c15496afac179fb39f13",
14
+ "moduleDoc:README.md": "c95d019573db738fa250b41e9e80527dee376fb9ff17efd6714e4debd4038c68",
15
15
  "moduleDoc:EXTRACTION.md": "b735a25a7be75f3a13f3f9e92b0c25834c1394835c16ccd73a076d5720c14243",
16
16
  "moduleDoc:PROPOSALS.md": "3accad9430e917e65319b7b7708d5c1df277eea7eaa0490df913cf361e80b7bc",
17
- "agentSurface:src/test-support/execution.ts": "80a8d4661f6f09091d7c20d5a825de129a8e1acbda20984d87dc42cdec557d59",
18
- "agentSurface:src/test-support/proposals.ts": "ab304c4e83e326c382bdb2b68d00f951b7707543041270c99fab0801302db842"
17
+ "moduleDoc:FEEDBACK.md": "795337ba256b486ecf0e836c4ad090d12f60c8c31dfb7c83155a8689da3d4dc5",
18
+ "moduleDoc:REVIEW.md": "a64c652cf862e8c064a965231b1cf9a49c4494f9e98fbec171403221dfa8e4b4",
19
+ "agentSurface:src/test-support/execution.ts": "1df56aaf1a692d822ed45ecb7e50df7d6806977ff3c03f9eeaf171c64f496865",
20
+ "agentSurface:src/test-support/proposals.ts": "260483ad7407191365bfe514f0d1625856f1001c11905299954508d885559497"
19
21
  },
20
22
  "exports": [
21
23
  ".",
@@ -25,7 +27,8 @@
25
27
  "./manifest.json",
26
28
  "./models",
27
29
  "./proposals",
28
- "./server"
30
+ "./server",
31
+ "./svelte"
29
32
  ],
30
33
  "dependencies": {
31
34
  "@happyvertical/smrt-core": "workspace:*",
@@ -42,13 +45,24 @@
42
45
  "@happyvertical/smrt-agents": "workspace:*",
43
46
  "@happyvertical/smrt-playbooks": "workspace:*",
44
47
  "ajv": "8.20.0",
48
+ "@happyvertical/smrt-ui": "workspace:*",
45
49
  "@happyvertical/smrt-vitest": "workspace:*",
46
50
  "@types/node": "24.13.6",
47
51
  "typescript": "6.0.3",
48
52
  "vite": "8.1.4",
49
53
  "vitest": "4.1.10",
50
54
  "@happyvertical/smrt-content": "workspace:*",
51
- "@happyvertical/smrt-users": "workspace:*"
55
+ "@happyvertical/smrt-messages": "workspace:*",
56
+ "@happyvertical/email": "catalog:",
57
+ "@happyvertical/smrt-users": "workspace:*",
58
+ "@sveltejs/package": "^2.5.8",
59
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
60
+ "svelte": "^5.57.0",
61
+ "svelte-check": "^4.7.6",
62
+ "@testing-library/svelte": "^5.4.2",
63
+ "@testing-library/user-event": "^14.6.7",
64
+ "jsdom": "^29.1.1",
65
+ "@playwright/test": "^1.63.0"
52
66
  },
53
67
  "smrtDependencies": [
54
68
  "@happyvertical/smrt-agents",
@@ -56,14 +70,17 @@
56
70
  "@happyvertical/smrt-content",
57
71
  "@happyvertical/smrt-core",
58
72
  "@happyvertical/smrt-jobs",
73
+ "@happyvertical/smrt-messages",
59
74
  "@happyvertical/smrt-playbooks",
60
75
  "@happyvertical/smrt-tenancy",
61
76
  "@happyvertical/smrt-types",
77
+ "@happyvertical/smrt-ui",
62
78
  "@happyvertical/smrt-users",
63
79
  "@happyvertical/smrt-vitest"
64
80
  ],
65
81
  "sdkDependencies": [
66
82
  "@happyvertical/ai",
83
+ "@happyvertical/email",
67
84
  "@happyvertical/ocr",
68
85
  "@happyvertical/pdf",
69
86
  "@happyvertical/sql"
@@ -80,6 +97,7 @@
80
97
  "name": "IntakeItem",
81
98
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeItem",
82
99
  "collection": "intakeitems",
100
+ "description": "Durable IntakeItem record; mutations belong to the server service.",
83
101
  "tableName": "intake_items",
84
102
  "packageName": "@happyvertical/smrt-ingestion",
85
103
  "extends": "SmrtObject",
@@ -245,6 +263,7 @@
245
263
  "name": "IntakeEvidence",
246
264
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeEvidence",
247
265
  "collection": "intakeevidences",
266
+ "description": "Durable IntakeEvidence record; mutations belong to the server service.",
248
267
  "tableName": "intake_evidence",
249
268
  "packageName": "@happyvertical/smrt-ingestion",
250
269
  "extends": "SmrtObject",
@@ -389,6 +408,7 @@
389
408
  "name": "IntakeAnalysis",
390
409
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeAnalysis",
391
410
  "collection": "intakeanalysises",
411
+ "description": "Durable IntakeAnalysis record; mutations belong to the server service.",
392
412
  "tableName": "intake_analyses",
393
413
  "packageName": "@happyvertical/smrt-ingestion",
394
414
  "extends": "SmrtObject",
@@ -512,6 +532,7 @@
512
532
  "name": "IntakeAnalysisAttempt",
513
533
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeAnalysisAttempt",
514
534
  "collection": "intakeanalysisattempts",
535
+ "description": "Durable IntakeAnalysisAttempt record; mutations belong to the server service.",
515
536
  "tableName": "intake_analysis_attempts",
516
537
  "packageName": "@happyvertical/smrt-ingestion",
517
538
  "extends": "SmrtObject",
@@ -653,6 +674,7 @@
653
674
  "name": "IntakePlan",
654
675
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakePlan",
655
676
  "collection": "intakeplans",
677
+ "description": "Durable IntakePlan record; mutations belong to the server service.",
656
678
  "tableName": "intake_plans",
657
679
  "packageName": "@happyvertical/smrt-ingestion",
658
680
  "extends": "SmrtObject",
@@ -751,6 +773,7 @@
751
773
  "name": "IntakeAction",
752
774
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeAction",
753
775
  "collection": "intakeactions",
776
+ "description": "Durable IntakeAction record; mutations belong to the server service.",
754
777
  "tableName": "intake_actions",
755
778
  "packageName": "@happyvertical/smrt-ingestion",
756
779
  "extends": "SmrtObject",
@@ -872,6 +895,7 @@
872
895
  "name": "IntakeProposal",
873
896
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeProposal",
874
897
  "collection": "intakeproposals",
898
+ "description": "Durable IntakeProposal record; mutations belong to the server service.",
875
899
  "tableName": "intake_proposals",
876
900
  "packageName": "@happyvertical/smrt-ingestion",
877
901
  "extends": "SmrtObject",
@@ -1005,6 +1029,7 @@
1005
1029
  "name": "IntakeReviewDecision",
1006
1030
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeReviewDecision",
1007
1031
  "collection": "intakereviewdecisions",
1032
+ "description": "Durable IntakeReviewDecision record; mutations belong to the server service.",
1008
1033
  "tableName": "intake_review_decisions",
1009
1034
  "packageName": "@happyvertical/smrt-ingestion",
1010
1035
  "extends": "SmrtObject",
@@ -1130,6 +1155,7 @@
1130
1155
  "name": "IntakeExecution",
1131
1156
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeExecution",
1132
1157
  "collection": "intakeexecutions",
1158
+ "description": "Durable IntakeExecution record; mutations belong to the server service.",
1133
1159
  "tableName": "intake_executions",
1134
1160
  "packageName": "@happyvertical/smrt-ingestion",
1135
1161
  "extends": "SmrtObject",
@@ -1259,6 +1285,7 @@
1259
1285
  "name": "IntakeFeedback",
1260
1286
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeFeedback",
1261
1287
  "collection": "intakefeedbacks",
1288
+ "description": "Durable IntakeFeedback record; mutations belong to the server service.",
1262
1289
  "tableName": "intake_feedback",
1263
1290
  "packageName": "@happyvertical/smrt-ingestion",
1264
1291
  "extends": "SmrtObject",
@@ -1364,6 +1391,7 @@
1364
1391
  "name": "IntakeDispatch",
1365
1392
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeDispatch",
1366
1393
  "collection": "intakedispatches",
1394
+ "description": "Durable IntakeDispatch record; mutations belong to the server service.",
1367
1395
  "tableName": "intake_dispatches",
1368
1396
  "packageName": "@happyvertical/smrt-ingestion",
1369
1397
  "extends": "SmrtObject",
@@ -1474,6 +1502,7 @@
1474
1502
  "name": "IntakeDeletion",
1475
1503
  "qualifiedName": "@happyvertical/smrt-ingestion:IntakeDeletion",
1476
1504
  "collection": "intakedeletions",
1505
+ "description": "Durable IntakeDeletion record; mutations belong to the server service.",
1477
1506
  "tableName": "intake_deletions",
1478
1507
  "packageName": "@happyvertical/smrt-ingestion",
1479
1508
  "extends": "SmrtObject",
@@ -1565,7 +1594,7 @@
1565
1594
  "polymorphicAssociations": 0,
1566
1595
  "uuidColumns": 46
1567
1596
  },
1568
- "agentDoc": "# @happyvertical/smrt-ingestion\n\nDurable foundation for ADR 0004. `src/models.ts` owns all ingestion tables;\n`src/server.ts` owns authenticated service boundaries and lifecycle primitives.\n`src/execution.ts` owns authoritative review/apply and imports server-only principals.\nSee [execution integration](agents/execution.md) for host transaction guarantees,\ncatalog contracts, deployment dependencies and continuation bindings.\nRoot, `/models`, and `/dto` remain browser-safe; provider/network/filesystem code\nbelongs under `/server`. Generated REST/CLI/MCP model mutation is disabled.\n\nSee [README.md](README.md) for host integration and recovery/deletion operation.\nSee [EXTRACTION.md](EXTRACTION.md) for extraction contracts, provider isolation\nrequirements and corpus validation.\nSee [PROPOSALS.md](PROPOSALS.md) for the optional server-only proposal stage,\ncurrent catalog/candidate authority and immutable source pinning.\n\nAll records require tenant and confidential scope. Hosts create service scopes\nfrom authenticated sessions; source metadata is never authority. Every read and\nwrite rechecks the host scope predicate. Analysis input revisions, attempts,\nproposals, decisions, executions and feedback are append-only except documented\nstate projections and retention redaction. Terminal actions outlive job cleanup.\n\nOnly SQLite and PostgreSQL are supported. Deploy manifest migrations before\nstarting services; runtime performs no application DDL. Storage planning and\npreservation use AssetRuntime/AssetStore public methods. Blob I/O and queue\nsubmission never run inside ingestion database transactions.\n\nValidation: `pnpm test`, `pnpm test:postgres`, `pnpm test:providers`, `pnpm typecheck`, `pnpm build`.\nThe PostgreSQL command provisions a real database and fails if unavailable.\nBuild includes browser import validation. The provider lane exercises local SDK\nadapters and process isolation, without claiming live remote recognition quality.\nThe component/e2e/evaluation\ncommands are reserved by ADR 0004 and fail explicitly until their owning children\nsupply real suites.\nSee ../../docs/test-matrix/3670-ingestion-foundation.md for behavior coverage.\n",
1597
+ "agentDoc": "# @happyvertical/smrt-ingestion\n\nDurable foundation for ADR 0004. `src/models.ts` owns all ingestion tables;\n`src/server.ts` owns authenticated service boundaries and lifecycle primitives.\n`src/execution.ts` owns authoritative review/apply and imports server-only principals.\nSee [execution integration](agents/execution.md) for host transaction guarantees,\ncatalog contracts, deployment dependencies and continuation bindings.\nRoot, `/models`, and `/dto` remain browser-safe; provider/network/filesystem code\nbelongs under `/server`. Generated REST/CLI/MCP model mutation is disabled.\n\nSee [README.md](README.md) for host integration and recovery/deletion operation.\nSee [EXTRACTION.md](EXTRACTION.md) for extraction contracts, provider isolation\nrequirements and corpus validation.\nSee [PROPOSALS.md](PROPOSALS.md) for the optional server-only proposal stage,\ncurrent catalog/candidate authority and immutable source pinning.\n\nAll records require tenant and confidential scope. Hosts create service scopes\nfrom authenticated sessions; source metadata is never authority. Every read and\nwrite rechecks the host scope predicate. Analysis input revisions, attempts,\nproposals, decisions, executions and feedback are append-only except documented\nstate projections and retention redaction. Terminal actions outlive job cleanup.\n\nOnly SQLite and PostgreSQL are supported. Deploy manifest migrations before\nstarting services; runtime performs no application DDL. Storage planning and\npreservation use AssetRuntime/AssetStore public methods. Blob I/O and queue\nsubmission never run inside ingestion database transactions.\n\nValidation: `pnpm test`, `pnpm test:postgres`, `pnpm test:providers`, `pnpm typecheck`, `pnpm build`.\nThe PostgreSQL command provisions a real database and fails if unavailable.\nFixture teardown uses `src/test-support/postgres-cleanup.ts`: only owned\nexec_/ing_/ext_/sources_ names, normal DROP, bounded 55006-only retry. Never\nforce-terminate backends, grant signal privileges, or ignore leaked sessions.\nBuild includes browser import validation. The provider lane exercises local SDK\nadapters and process isolation, without claiming live remote recognition quality.\n`src/svelte` owns transport-neutral review components and browser-safe host callbacks.\nSee [FEEDBACK.md](FEEDBACK.md) for revision-bound explicit feedback, scoped example retrieval,\nprovider-boundary revalidation and authorized routing policy adoption.\nSee [REVIEW.md](REVIEW.md) for authenticated hosts, bounded saved-review reloads,\nassignment ownership, logical split re-extraction and the maintained browser proof.\nUI validation additionally requires `pnpm test:components` and `pnpm test:e2e`;\n`typecheck` includes Svelte and `build` includes the types-first `/svelte` entry.\n`pnpm test:evaluation` runs repository evaluation tooling/format/fault contracts.\nMeasured held-out quality is a separate frozen-protocol, budget-gated run; tooling\nsuccess does not establish reference quality or permit automatic actions.\nSee ../../docs/test-matrix/3670-ingestion-foundation.md for behavior coverage.\n",
1569
1598
  "moduleDocs": [
1570
1599
  {
1571
1600
  "path": "agents/execution.md",
@@ -1575,7 +1604,7 @@
1575
1604
  {
1576
1605
  "path": "README.md",
1577
1606
  "module": "README",
1578
- "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. Component, e2e and evaluation command names are reserved by the ADR and\nexplicitly unavailable until their owning children deliver the corresponding\ncapability. 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"
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"
1579
1608
  },
1580
1609
  {
1581
1610
  "path": "EXTRACTION.md",
@@ -1586,6 +1615,16 @@
1586
1615
  "path": "PROPOSALS.md",
1587
1616
  "module": "PROPOSALS",
1588
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"
1618
+ },
1619
+ {
1620
+ "path": "FEEDBACK.md",
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"
1623
+ },
1624
+ {
1625
+ "path": "REVIEW.md",
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"
1589
1628
  }
1590
1629
  ],
1591
1630
  "agentSurface": {
@@ -1596,7 +1635,7 @@
1596
1635
  "code": "not-module-scope",
1597
1636
  "helper": "definePlaybook",
1598
1637
  "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.",
1599
- "line": 316,
1638
+ "line": 429,
1600
1639
  "column": 7,
1601
1640
  "sourceFile": "src/test-support/execution.ts"
1602
1641
  },
@@ -1604,7 +1643,7 @@
1604
1643
  "code": "not-module-scope",
1605
1644
  "helper": "definePlaybook",
1606
1645
  "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.",
1607
- "line": 1761,
1646
+ "line": 2089,
1608
1647
  "column": 9,
1609
1648
  "sourceFile": "src/test-support/execution.ts"
1610
1649
  },
@@ -1612,10 +1651,54 @@
1612
1651
  "code": "not-module-scope",
1613
1652
  "helper": "definePlaybook",
1614
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.",
1615
- "line": 1535,
1654
+ "line": 779,
1655
+ "column": 9,
1656
+ "sourceFile": "src/test-support/proposals.ts"
1657
+ },
1658
+ {
1659
+ "code": "not-module-scope",
1660
+ "helper": "definePlaybook",
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,
1663
+ "column": 9,
1664
+ "sourceFile": "src/test-support/proposals.ts"
1665
+ },
1666
+ {
1667
+ "code": "not-module-scope",
1668
+ "helper": "definePlaybook",
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,
1671
+ "column": 9,
1672
+ "sourceFile": "src/test-support/proposals.ts"
1673
+ },
1674
+ {
1675
+ "code": "not-module-scope",
1676
+ "helper": "definePlaybook",
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,
1616
1679
  "column": 7,
1617
1680
  "sourceFile": "src/test-support/proposals.ts"
1618
1681
  }
1619
1682
  ]
1683
+ },
1684
+ "browser": {
1685
+ "status": "server-only",
1686
+ "issues": [
1687
+ "#3615",
1688
+ "#3617",
1689
+ "#3624",
1690
+ "#3625",
1691
+ "#3626",
1692
+ "#3627"
1693
+ ],
1694
+ "via": [
1695
+ "@happyvertical/smrt-agents",
1696
+ "@happyvertical/smrt-jobs",
1697
+ "@happyvertical/smrt-profiles",
1698
+ "@happyvertical/smrt-reports",
1699
+ "@happyvertical/smrt-secrets",
1700
+ "@happyvertical/smrt-tenancy",
1701
+ "@happyvertical/smrt-users"
1702
+ ]
1620
1703
  }
1621
1704
  }
@@ -0,0 +1,232 @@
1
+ <script lang="ts">
2
+ import { Input, Select, Textarea } from '@happyvertical/smrt-ui/forms';
3
+ import { useI18n } from '@happyvertical/smrt-ui/i18n';
4
+ import { Button } from '@happyvertical/smrt-ui/ui';
5
+ import { onDestroy, untrack } from 'svelte';
6
+ import type { ReviewInput } from '../../execution-dto.js';
7
+ import type {
8
+ CandidatePage,
9
+ ProposalCatalogEntry,
10
+ } from '../../proposal-dto.js';
11
+ import type { IntakeReviewHost, ReviewAction } from '../../review-dto.js';
12
+ import { M } from '../i18n.js';
13
+ import { argumentsObject } from '../view-utils.js';
14
+ export interface Props {
15
+ host: IntakeReviewHost;
16
+ itemId: string;
17
+ action: ReviewAction;
18
+ catalog?: ProposalCatalogEntry;
19
+ currentAttemptId?: string;
20
+ run: (operation: () => Promise<unknown>) => Promise<void>;
21
+ deny: () => void;
22
+ }
23
+ let { host, itemId, action, catalog, currentAttemptId, run, deny }: Props =
24
+ $props();
25
+ const { t } = useI18n();
26
+ // ReviewView keys this editor by action/revision/reviewVersion; edits are local to that binding.
27
+ let args = $state(untrack(() => JSON.stringify(action.args, null, 2) ?? '')),
28
+ reason = $state(''),
29
+ query = $state(''),
30
+ field = $state(''),
31
+ candidates = $state<CandidatePage>(),
32
+ searching = $state(false),
33
+ invalid = $state(false),
34
+ comment = $state(''),
35
+ planArgs = $state(
36
+ untrack(() => JSON.stringify(action.plan?.args, null, 2) ?? ''),
37
+ );
38
+ let alive = true;
39
+ onDestroy(() => {
40
+ alive = false;
41
+ });
42
+ const dirty = $derived(
43
+ args !== (JSON.stringify(action.args, null, 2) ?? '') ||
44
+ planArgs !== (JSON.stringify(action.plan?.args, null, 2) ?? ''),
45
+ );
46
+ const waiting = $derived(
47
+ action.args !== undefined && action.review.state === 'waiting_review',
48
+ );
49
+ const revisable = $derived(
50
+ ['authorized', 'deferred', 'rejected', 'failed'].includes(
51
+ action.review.state,
52
+ ),
53
+ );
54
+ const editable = $derived(
55
+ action.args !== undefined &&
56
+ (waiting ||
57
+ (!action.plan &&
58
+ revisable &&
59
+ !!host.editAction &&
60
+ !!action.attemptId &&
61
+ !!action.handlerId &&
62
+ !!action.handlerVersion)),
63
+ );
64
+ const planEditable = $derived(
65
+ action.args !== undefined && (waiting || revisable),
66
+ );
67
+ async function decide(decision: ReviewInput['decision']) {
68
+ if (!waiting) return;
69
+ let correctedArgs: ReviewInput['correctedArgs'];
70
+ try {
71
+ if (decision === 'correct' && action.plan) return;
72
+ if (decision === 'correct') correctedArgs = argumentsObject(args);
73
+ } catch {
74
+ invalid = true;
75
+ return;
76
+ }
77
+ const review = action.review;
78
+ await run(() =>
79
+ host.decide({
80
+ actionId: review.actionId,
81
+ expectedRevision: review.revision,
82
+ expectedReviewVersion: review.reviewVersion,
83
+ bindingHash: review.bindingHash,
84
+ requestId: crypto.randomUUID(),
85
+ decision,
86
+ ...(reason ? { reason } : {}),
87
+ ...(correctedArgs ? { correctedArgs } : {}),
88
+ }),
89
+ );
90
+ }
91
+ async function saveEdits() {
92
+ if (waiting) return decide('correct');
93
+ if (
94
+ (!editable && action.review.state !== 'stale') ||
95
+ action.plan ||
96
+ action.stalePlan ||
97
+ !host.editAction ||
98
+ !action.attemptId ||
99
+ !action.handlerId ||
100
+ !action.handlerVersion
101
+ )
102
+ return;
103
+ let values;
104
+ try {
105
+ values = argumentsObject(args);
106
+ } catch {
107
+ invalid = true;
108
+ return;
109
+ }
110
+ const input = {
111
+ itemId,
112
+ actionId: action.review.actionId,
113
+ attemptId: action.attemptId,
114
+ expectedRevision: action.review.revision,
115
+ handlerId: action.handlerId,
116
+ handlerVersion: action.handlerVersion,
117
+ args: values,
118
+ requestId: crypto.randomUUID(),
119
+ ...(action.dependencies ? { dependencies: action.dependencies } : {}),
120
+ };
121
+ await run(() => host.editAction?.(input) ?? Promise.resolve());
122
+ }
123
+ async function search() {
124
+ if (!action.handlerId || !action.handlerVersion || searching) return;
125
+ searching = true;
126
+ candidates = undefined;
127
+ try {
128
+ const result = await host.candidates({
129
+ itemId,
130
+ handlerId: action.handlerId,
131
+ handlerVersion: action.handlerVersion,
132
+ query,
133
+ });
134
+ if (alive) candidates = result;
135
+ } catch {
136
+ if (alive) deny();
137
+ } finally {
138
+ if (alive) searching = false;
139
+ }
140
+ }
141
+ async function editPlan() {
142
+ const plan = action.plan ?? action.stalePlan;
143
+ const attemptId = action.plan?.attemptId ?? currentAttemptId;
144
+ if (
145
+ !plan ||
146
+ !plan.handlerId ||
147
+ !plan.handlerVersion ||
148
+ !attemptId ||
149
+ !host.editPlan
150
+ )
151
+ return;
152
+ let values;
153
+ try {
154
+ values = argumentsObject(planArgs);
155
+ } catch {
156
+ invalid = true;
157
+ return;
158
+ }
159
+ const input = {
160
+ itemId,
161
+ planKey: plan.key,
162
+ attemptId,
163
+ expectedRevision: plan.revision,
164
+ handlerId: plan.handlerId,
165
+ handlerVersion: plan.handlerVersion,
166
+ args: values,
167
+ requestId: crypto.randomUUID(),
168
+ };
169
+ await run(() => host.editPlan?.(input) ?? Promise.resolve());
170
+ }
171
+ function choose(id: string) {
172
+ try {
173
+ const values = argumentsObject(args);
174
+ const ref = catalog?.references[field];
175
+ if (
176
+ ref?.kind !== 'candidate' ||
177
+ !candidates?.items.some(
178
+ (candidate) => candidate.id === id && candidate.model === ref.model,
179
+ )
180
+ )
181
+ return;
182
+ args = JSON.stringify({ ...values, [field]: id }, null, 2);
183
+ } catch {
184
+ invalid = true;
185
+ }
186
+ }
187
+ </script>
188
+ <article data-testid={`action-${action.review.actionId}`}>
189
+ <h3>{action.handlerId ?? action.review.actionId}</h3>
190
+ <p>{t(M['ingestion.state'])}: {action.review.state}</p>
191
+ {#if action.args !== undefined}
192
+ <h4>{t(M['ingestion.effects'])}</h4><pre>{JSON.stringify(action.review.display,null,2)}</pre>
193
+ <Textarea aria-label={t(M['ingestion.args'])} bind:value={args} readonly={!editable || !!action.plan} rows={8} />
194
+ {#if editable}
195
+ <Input aria-label={t(M['ingestion.reason'])} bind:value={reason} />
196
+ {#if !action.plan && catalog && Object.values(catalog.references).some((ref) => ref.kind === 'candidate')}
197
+ <h4>{t(M['ingestion.candidates'])}</h4>
198
+ <Select aria-label={t(M['ingestion.field'])} bind:value={field}><option value="">{t(M['ingestion.field'])}</option>{#each Object.entries(catalog.references) as [name,ref]}{#if ref.kind === 'candidate'}<option value={name}>{name}</option>{/if}{/each}</Select>
199
+ <Input aria-label={t(M['ingestion.query'])} bind:value={query} />
200
+ <Button onclick={search} disabled={searching}>{t(M['ingestion.search'])}</Button>
201
+ {#if candidates}<ul>{#each candidates.items as candidate (candidate.key)}<li>{candidate.label} <Button disabled={!field} onclick={() => choose(candidate.id)}>{t(M['ingestion.choose'])}</Button></li>{/each}</ul>{#if candidates.truncated}<p>{t(M['ingestion.truncated'])}</p>{/if}{/if}
202
+ {/if}
203
+ {#if dirty}<p>{t(M['ingestion.reviewAgain'])}</p>{/if}
204
+ {#if invalid}<p role="alert">{t(M['ingestion.invalid'])}</p>{/if}
205
+ <div class="controls">{#if waiting}<Button disabled={dirty} onclick={() => decide('approve')}>{t(M['ingestion.approve'])}</Button>{/if}{#if !action.plan}<Button disabled={!dirty} onclick={saveEdits}>{t(M['ingestion.correct'])}</Button>{/if}{#if waiting}<Button onclick={() => decide('reject')}>{t(M['ingestion.reject'])}</Button><Button onclick={() => decide('defer')}>{t(M['ingestion.defer'])}</Button>{/if}</div>
206
+ {/if}
207
+ {#if action.plan?.stepIndex === 0 && action.plan.args && host.editPlan && planEditable}
208
+ <Textarea aria-label={t(M['ingestion.planArgs'])} bind:value={planArgs} rows={8} />
209
+ {#if !editable && dirty}<p>{t(M['ingestion.reviewAgain'])}</p>{/if}
210
+ {#if !editable && invalid}<p role="alert">{t(M['ingestion.invalid'])}</p>{/if}
211
+ <Button onclick={editPlan}>{t(M['ingestion.editPlan'])}</Button>
212
+ {/if}
213
+ {#if action.review.state === 'authorized'}<Button disabled={dirty} onclick={() => { if (!dirty) void run(() => host.apply(action.review.actionId)); }}>{t(M['ingestion.apply'])}</Button>{/if}
214
+ {/if}
215
+ {#if action.review.state === 'stale' && !action.stalePlan && action.attemptId && host.editAction}
216
+ <p>{t(M['ingestion.reviewAgain'])}</p>
217
+ <Textarea aria-label={t(M['ingestion.args'])} bind:value={args} rows={8} />
218
+ {#if invalid}<p role="alert">{t(M['ingestion.invalid'])}</p>{/if}
219
+ <Button onclick={saveEdits}>{t(M['ingestion.correct'])}</Button>
220
+ {/if}
221
+ {#if action.review.state === 'stale' && action.stalePlan && currentAttemptId && host.editPlan}
222
+ <p>{t(M['ingestion.reviewAgain'])}</p>
223
+ <Textarea aria-label={t(M['ingestion.planArgs'])} bind:value={planArgs} rows={8} />
224
+ {#if invalid}<p role="alert">{t(M['ingestion.invalid'])}</p>{/if}
225
+ <Button onclick={editPlan}>{t(M['ingestion.editPlan'])}</Button>
226
+ {/if}
227
+ {#if action.result}<h4>{t(M['ingestion.result'])}</h4><pre>{JSON.stringify(action.result,null,2)}</pre>{/if}
228
+ {#if host.feedback && action.args !== undefined}<fieldset><legend>{t(M['ingestion.feedback'])}</legend><Textarea aria-label={t(M['ingestion.comment'])} bind:value={comment} /><Button disabled={dirty} onclick={() => run(() => host.feedback?.({itemId,actionId:action.review.actionId,expectedRevision:action.review.revision,expectedReviewVersion:action.review.reviewVersion,bindingHash:action.review.bindingHash,judgment:'correct',comment,requestId:crypto.randomUUID()}) ?? Promise.resolve())}>{t(M['ingestion.correctJudgment'])}</Button><Button disabled={dirty} onclick={() => run(() => host.feedback?.({itemId,actionId:action.review.actionId,expectedRevision:action.review.revision,expectedReviewVersion:action.review.reviewVersion,bindingHash:action.review.bindingHash,judgment:'incorrect',comment,requestId:crypto.randomUUID()}) ?? Promise.resolve())}>{t(M['ingestion.incorrectJudgment'])}</Button></fieldset>{/if}
229
+ </article>
230
+ <style>
231
+ article{min-width:0;overflow-wrap:anywhere;border-block-start:1px solid var(--smrt-color-outline-variant,#ccc);padding-block:1rem}.controls{display:flex;flex-wrap:wrap;gap:.5rem;margin-block:.75rem}pre{white-space:pre-wrap;overflow-wrap:anywhere}fieldset{margin-block:1rem;min-width:0}
232
+ </style>