@happyvertical/smrt-ingestion 0.55.5 → 0.55.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +13 -3
- package/FEEDBACK.md +117 -0
- package/PROPOSALS.md +173 -0
- package/README.md +14 -0
- package/REVIEW.md +136 -0
- package/agents/execution.md +132 -0
- package/dist/chunks/execution-CYjtj9_l.js +8031 -0
- package/dist/chunks/execution-CYjtj9_l.js.map +1 -0
- package/dist/chunks/execution-internal-DWteDHM2.js +7 -0
- package/dist/chunks/execution-internal-DWteDHM2.js.map +1 -0
- package/dist/chunks/feedback-B_NILilH.js +577 -0
- package/dist/chunks/feedback-B_NILilH.js.map +1 -0
- package/dist/chunks/proposal-errors-z24VKWnQ.js +301 -0
- package/dist/chunks/proposal-errors-z24VKWnQ.js.map +1 -0
- package/dist/dto.d.ts +3 -0
- package/dist/dto.d.ts.map +1 -1
- package/dist/execution-contracts.d.ts +3 -0
- package/dist/execution-contracts.d.ts.map +1 -1
- package/dist/execution-internal.d.ts +9 -0
- package/dist/execution-internal.d.ts.map +1 -0
- package/dist/execution.d.ts +23 -1
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +1 -7614
- package/dist/extraction.d.ts.map +1 -1
- package/dist/feedback-contracts.d.ts +40 -0
- package/dist/feedback-contracts.d.ts.map +1 -0
- package/dist/feedback-dto.d.ts +100 -0
- package/dist/feedback-dto.d.ts.map +1 -0
- package/dist/feedback-internal.d.ts +19 -0
- package/dist/feedback-internal.d.ts.map +1 -0
- package/dist/feedback.d.ts +53 -0
- package/dist/feedback.d.ts.map +1 -0
- package/dist/manifest.json +13 -1
- package/dist/models.js +1 -1
- package/dist/models.js.map +1 -1
- package/dist/proposal-contracts.d.ts +89 -0
- package/dist/proposal-contracts.d.ts.map +1 -0
- package/dist/proposal-dto.d.ts +124 -0
- package/dist/proposal-dto.d.ts.map +1 -0
- package/dist/proposal-errors.d.ts +5 -0
- package/dist/proposal-errors.d.ts.map +1 -0
- package/dist/proposal-sdk.d.ts +12 -0
- package/dist/proposal-sdk.d.ts.map +1 -0
- package/dist/proposal-validation.d.ts +188 -0
- package/dist/proposal-validation.d.ts.map +1 -0
- package/dist/proposals.d.ts +44 -0
- package/dist/proposals.d.ts.map +1 -0
- package/dist/proposals.js +964 -0
- package/dist/proposals.js.map +1 -0
- package/dist/review-dto.d.ts +115 -0
- package/dist/review-dto.d.ts.map +1 -0
- package/dist/server.d.ts +56 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +263 -341
- package/dist/server.js.map +1 -1
- package/dist/smrt-knowledge.json +87 -12
- package/dist/svelte/components/ActionReview.svelte +232 -0
- package/dist/svelte/components/ActionReview.svelte.d.ts +15 -0
- package/dist/svelte/components/ActionReview.svelte.d.ts.map +1 -0
- package/dist/svelte/components/EvidenceViewer.svelte +31 -0
- package/dist/svelte/components/EvidenceViewer.svelte.d.ts +8 -0
- package/dist/svelte/components/EvidenceViewer.svelte.d.ts.map +1 -0
- package/dist/svelte/components/InboxView.svelte +119 -0
- package/dist/svelte/components/InboxView.svelte.d.ts +9 -0
- package/dist/svelte/components/InboxView.svelte.d.ts.map +1 -0
- package/dist/svelte/components/IntakeInbox.svelte +11 -0
- package/dist/svelte/components/IntakeInbox.svelte.d.ts +10 -0
- package/dist/svelte/components/IntakeInbox.svelte.d.ts.map +1 -0
- package/dist/svelte/components/IntakeReview.svelte +11 -0
- package/dist/svelte/components/IntakeReview.svelte.d.ts +10 -0
- package/dist/svelte/components/IntakeReview.svelte.d.ts.map +1 -0
- package/dist/svelte/components/ReviewView.svelte +243 -0
- package/dist/svelte/components/ReviewView.svelte.d.ts +9 -0
- package/dist/svelte/components/ReviewView.svelte.d.ts.map +1 -0
- package/dist/svelte/i18n.d.ts +72 -0
- package/dist/svelte/i18n.d.ts.map +1 -0
- package/dist/svelte/i18n.js +72 -0
- package/dist/svelte/index.d.ts +5 -0
- package/dist/svelte/index.d.ts.map +1 -0
- package/dist/svelte/index.js +3 -0
- package/dist/svelte/view-utils.d.ts +13 -0
- package/dist/svelte/view-utils.d.ts.map +1 -0
- package/dist/svelte/view-utils.js +96 -0
- package/package.json +53 -22
- package/dist/execution.js.map +0 -1
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,17 +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
|
+
"packageVersion": "0.55.7",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "d2b8807cdaf4690eeff056356bce545f23533df00f482a6fdf220016eafca25d",
|
|
11
|
+
"packageJson": "29755f98deeebc0a33df0bd274b0735044fb7e7920d8219b3cb2557a8c3e38ce",
|
|
12
|
+
"agents": "0ba8291b29534bbc8e4bd6178bac09d1ca301c3193f89fdec9453bac47bbfbd9",
|
|
13
13
|
"moduleDoc:agents/execution.md": "6153206adeea46fee1be57ccc01d171621ffb3dc3a754b3634bfe2ce367e8416",
|
|
14
|
-
"moduleDoc:README.md": "
|
|
14
|
+
"moduleDoc:README.md": "be2a2fffb4642c387baef4b45a7f246795c431a98735977702c10c2187ecde83",
|
|
15
15
|
"moduleDoc:EXTRACTION.md": "b735a25a7be75f3a13f3f9e92b0c25834c1394835c16ccd73a076d5720c14243",
|
|
16
|
-
"
|
|
16
|
+
"moduleDoc:PROPOSALS.md": "3accad9430e917e65319b7b7708d5c1df277eea7eaa0490df913cf361e80b7bc",
|
|
17
|
+
"moduleDoc:FEEDBACK.md": "f834778a8d0c0c86b1667c2eda101c1b9de3c510cd9b42d794110db844b69824",
|
|
18
|
+
"moduleDoc:REVIEW.md": "e3418b54de2620cbc761ab6a49e698172424f6e601785b48f156a780746578e9",
|
|
19
|
+
"agentSurface:src/test-support/execution.ts": "1df56aaf1a692d822ed45ecb7e50df7d6806977ff3c03f9eeaf171c64f496865",
|
|
20
|
+
"agentSurface:src/test-support/proposals.ts": "bcb2d540c4e31517702f55cdbbc11d12f0e7fa4992aad5d89cd44437c4e45c7a"
|
|
17
21
|
},
|
|
18
22
|
"exports": [
|
|
19
23
|
".",
|
|
@@ -22,7 +26,9 @@
|
|
|
22
26
|
"./manifest",
|
|
23
27
|
"./manifest.json",
|
|
24
28
|
"./models",
|
|
25
|
-
"./
|
|
29
|
+
"./proposals",
|
|
30
|
+
"./server",
|
|
31
|
+
"./svelte"
|
|
26
32
|
],
|
|
27
33
|
"dependencies": {
|
|
28
34
|
"@happyvertical/smrt-core": "workspace:*",
|
|
@@ -39,13 +45,22 @@
|
|
|
39
45
|
"@happyvertical/smrt-agents": "workspace:*",
|
|
40
46
|
"@happyvertical/smrt-playbooks": "workspace:*",
|
|
41
47
|
"ajv": "8.20.0",
|
|
48
|
+
"@happyvertical/smrt-ui": "workspace:*",
|
|
42
49
|
"@happyvertical/smrt-vitest": "workspace:*",
|
|
43
50
|
"@types/node": "24.13.6",
|
|
44
51
|
"typescript": "6.0.3",
|
|
45
52
|
"vite": "8.1.4",
|
|
46
53
|
"vitest": "4.1.10",
|
|
47
54
|
"@happyvertical/smrt-content": "workspace:*",
|
|
48
|
-
"@happyvertical/smrt-users": "workspace:*"
|
|
55
|
+
"@happyvertical/smrt-users": "workspace:*",
|
|
56
|
+
"@sveltejs/package": "^2.5.8",
|
|
57
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
58
|
+
"svelte": "^5.57.0",
|
|
59
|
+
"svelte-check": "^4.7.6",
|
|
60
|
+
"@testing-library/svelte": "^5.4.2",
|
|
61
|
+
"@testing-library/user-event": "^14.6.7",
|
|
62
|
+
"jsdom": "^29.1.1",
|
|
63
|
+
"@playwright/test": "^1.63.0"
|
|
49
64
|
},
|
|
50
65
|
"smrtDependencies": [
|
|
51
66
|
"@happyvertical/smrt-agents",
|
|
@@ -56,6 +71,7 @@
|
|
|
56
71
|
"@happyvertical/smrt-playbooks",
|
|
57
72
|
"@happyvertical/smrt-tenancy",
|
|
58
73
|
"@happyvertical/smrt-types",
|
|
74
|
+
"@happyvertical/smrt-ui",
|
|
59
75
|
"@happyvertical/smrt-users",
|
|
60
76
|
"@happyvertical/smrt-vitest"
|
|
61
77
|
],
|
|
@@ -77,6 +93,7 @@
|
|
|
77
93
|
"name": "IntakeItem",
|
|
78
94
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeItem",
|
|
79
95
|
"collection": "intakeitems",
|
|
96
|
+
"description": "Durable IntakeItem record; mutations belong to the server service.",
|
|
80
97
|
"tableName": "intake_items",
|
|
81
98
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
82
99
|
"extends": "SmrtObject",
|
|
@@ -242,6 +259,7 @@
|
|
|
242
259
|
"name": "IntakeEvidence",
|
|
243
260
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeEvidence",
|
|
244
261
|
"collection": "intakeevidences",
|
|
262
|
+
"description": "Durable IntakeEvidence record; mutations belong to the server service.",
|
|
245
263
|
"tableName": "intake_evidence",
|
|
246
264
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
247
265
|
"extends": "SmrtObject",
|
|
@@ -386,6 +404,7 @@
|
|
|
386
404
|
"name": "IntakeAnalysis",
|
|
387
405
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeAnalysis",
|
|
388
406
|
"collection": "intakeanalysises",
|
|
407
|
+
"description": "Durable IntakeAnalysis record; mutations belong to the server service.",
|
|
389
408
|
"tableName": "intake_analyses",
|
|
390
409
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
391
410
|
"extends": "SmrtObject",
|
|
@@ -509,6 +528,7 @@
|
|
|
509
528
|
"name": "IntakeAnalysisAttempt",
|
|
510
529
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeAnalysisAttempt",
|
|
511
530
|
"collection": "intakeanalysisattempts",
|
|
531
|
+
"description": "Durable IntakeAnalysisAttempt record; mutations belong to the server service.",
|
|
512
532
|
"tableName": "intake_analysis_attempts",
|
|
513
533
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
514
534
|
"extends": "SmrtObject",
|
|
@@ -650,6 +670,7 @@
|
|
|
650
670
|
"name": "IntakePlan",
|
|
651
671
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakePlan",
|
|
652
672
|
"collection": "intakeplans",
|
|
673
|
+
"description": "Durable IntakePlan record; mutations belong to the server service.",
|
|
653
674
|
"tableName": "intake_plans",
|
|
654
675
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
655
676
|
"extends": "SmrtObject",
|
|
@@ -748,6 +769,7 @@
|
|
|
748
769
|
"name": "IntakeAction",
|
|
749
770
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeAction",
|
|
750
771
|
"collection": "intakeactions",
|
|
772
|
+
"description": "Durable IntakeAction record; mutations belong to the server service.",
|
|
751
773
|
"tableName": "intake_actions",
|
|
752
774
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
753
775
|
"extends": "SmrtObject",
|
|
@@ -869,6 +891,7 @@
|
|
|
869
891
|
"name": "IntakeProposal",
|
|
870
892
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeProposal",
|
|
871
893
|
"collection": "intakeproposals",
|
|
894
|
+
"description": "Durable IntakeProposal record; mutations belong to the server service.",
|
|
872
895
|
"tableName": "intake_proposals",
|
|
873
896
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
874
897
|
"extends": "SmrtObject",
|
|
@@ -1002,6 +1025,7 @@
|
|
|
1002
1025
|
"name": "IntakeReviewDecision",
|
|
1003
1026
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeReviewDecision",
|
|
1004
1027
|
"collection": "intakereviewdecisions",
|
|
1028
|
+
"description": "Durable IntakeReviewDecision record; mutations belong to the server service.",
|
|
1005
1029
|
"tableName": "intake_review_decisions",
|
|
1006
1030
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
1007
1031
|
"extends": "SmrtObject",
|
|
@@ -1127,6 +1151,7 @@
|
|
|
1127
1151
|
"name": "IntakeExecution",
|
|
1128
1152
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeExecution",
|
|
1129
1153
|
"collection": "intakeexecutions",
|
|
1154
|
+
"description": "Durable IntakeExecution record; mutations belong to the server service.",
|
|
1130
1155
|
"tableName": "intake_executions",
|
|
1131
1156
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
1132
1157
|
"extends": "SmrtObject",
|
|
@@ -1256,6 +1281,7 @@
|
|
|
1256
1281
|
"name": "IntakeFeedback",
|
|
1257
1282
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeFeedback",
|
|
1258
1283
|
"collection": "intakefeedbacks",
|
|
1284
|
+
"description": "Durable IntakeFeedback record; mutations belong to the server service.",
|
|
1259
1285
|
"tableName": "intake_feedback",
|
|
1260
1286
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
1261
1287
|
"extends": "SmrtObject",
|
|
@@ -1361,6 +1387,7 @@
|
|
|
1361
1387
|
"name": "IntakeDispatch",
|
|
1362
1388
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeDispatch",
|
|
1363
1389
|
"collection": "intakedispatches",
|
|
1390
|
+
"description": "Durable IntakeDispatch record; mutations belong to the server service.",
|
|
1364
1391
|
"tableName": "intake_dispatches",
|
|
1365
1392
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
1366
1393
|
"extends": "SmrtObject",
|
|
@@ -1471,6 +1498,7 @@
|
|
|
1471
1498
|
"name": "IntakeDeletion",
|
|
1472
1499
|
"qualifiedName": "@happyvertical/smrt-ingestion:IntakeDeletion",
|
|
1473
1500
|
"collection": "intakedeletions",
|
|
1501
|
+
"description": "Durable IntakeDeletion record; mutations belong to the server service.",
|
|
1474
1502
|
"tableName": "intake_deletions",
|
|
1475
1503
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
1476
1504
|
"extends": "SmrtObject",
|
|
@@ -1562,7 +1590,7 @@
|
|
|
1562
1590
|
"polymorphicAssociations": 0,
|
|
1563
1591
|
"uuidColumns": 46
|
|
1564
1592
|
},
|
|
1565
|
-
"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.\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.\
|
|
1593
|
+
"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.\nThe evaluation command remains reserved for #3677 and fails explicitly.\nSee ../../docs/test-matrix/3670-ingestion-foundation.md for behavior coverage.\n",
|
|
1566
1594
|
"moduleDocs": [
|
|
1567
1595
|
{
|
|
1568
1596
|
"path": "agents/execution.md",
|
|
@@ -1572,12 +1600,27 @@
|
|
|
1572
1600
|
{
|
|
1573
1601
|
"path": "README.md",
|
|
1574
1602
|
"module": "README",
|
|
1575
|
-
"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"
|
|
1603
|
+
"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\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"
|
|
1576
1604
|
},
|
|
1577
1605
|
{
|
|
1578
1606
|
"path": "EXTRACTION.md",
|
|
1579
1607
|
"module": "EXTRACTION",
|
|
1580
1608
|
"content": "# Extraction adapters\n\n`@happyvertical/smrt-ingestion/server` exports `createSDKExtractionAdapter`,\n`extractAnalysis`, extraction types, and `proposeDocumentSplits`. Root and DTO\nexports remain browser-safe. No extraction result authorizes a business action.\n\nHosts construct the SDK adapter with explicit provider/model/version identities\n(`unknown` for unavailable model/version), credential-bearing SDK options, and\n`nativeMemoryIsolation: 'host-enforced'`. This last setting is an assertion by\ntrusted deployment configuration, never a source/body/client option. Deploy the\nprovider child under an OS/container native-memory ceiling. Node's heap limit\ncannot bound native allocations, and PDF's renderer has no pre-render pixel\nlimit. Without that host guarantee, adapter construction refuses to run. A\nconfigured provider must be pinned, not `auto`; OCR fallback is disabled so\ncapability provenance cannot silently change. Identity objects are projected onto\nexactly `provider`, `model`, and `version`, each a required nonblank string. Extra\nhost fields never enter capability or segment identities, including through\ntrusted custom adapter results at the publication boundary.\n\nThe adapter forks one disposable Node process per retained part. Deadline or\ncancellation kills it (and its process group on POSIX); provider stdout/stderr\nare discarded. Calls are sequential and bounded by input bytes, page count,\nimage decode pixels, serialized output, vision tokens, elapsed time and Node\nheap. Native memory remains the host boundary described above. Remote compute\nalready accepted by a provider may continue/bill after the local process dies.\nDo not interpret a local cancellation as remote billing cancellation.\n\nPersist `{extraction: {configurationRevision, limits}}` using `service.analyze`,\nthen claim its lease. Call `extractAnalysis(service, lease, adapter, options)`\nwith exactly that revision and limits. The service reloads the immutable input\nsnapshot and rechecks current processing authority before each provider and\nbefore publication. The production child requests a parent-side authorization\nhandshake before each PDF/OCR/vision/speech operation, including calls on later\npages. Denial kills the child; already transmitted material cannot be recalled.\nCustom trusted adapters must await `request.beforeProviderCall` before every\nprovider invocation. Bytes are read through the service's integrity-checked\nreader; revoked, expired, foreign-scope, forged and stale leases fail closed.\nA retry keeps the same analysis input revision; changed provider/model/options\nmust use a new configuration revision and `analyze` request key. Credentials are\nnever placed in persisted configuration or provider identity.\n\nResults retain the original evidence ID/hash/part/parent references. Ordered\nsegments form whole-document context; extraction does not split originals into\nbusiness records. Valid UTF-8 JSON, text and HTML remain literal source text (render HTML\nonly through an application sanitizer). JSON syntax is validated without rewriting\nits source text; malformed JSON or UTF-8 fails extraction. PDF text is extracted one page at a\ntime, falling back to actual rendered-page OCR for empty pages. Embedded text\nis not evidence that every visual element was understood. TIFF is actually\ndecoded page-by-page with sharp to PNG; each result cites its original TIFF page.\nAnimated non-TIFF images are unsupported. Ordinary image OCR and scene vision\nare separately configured. Speech uses source-level text unless actual segment\ntimestamps are returned; absent speech confidence calibration is unknown.\n\nConfidence and boxes are explicitly null unless an OCR provider advertises and\nreturns them. Unlimited-OCR's synthetic common confidence is always discarded,\neven if an injected capability claims otherwise. Measured OCR values retain an\nunknown calibration label; they are not routing certainty or approval. Boxes\nare in decoded image pixels, attached only to that actual page/source. No tables\nare invented: the current PDF/OCR text APIs do not supply a table contract.\n\nThe persisted receipt's `maxOutputBytes`, exposed by `getAnalysisInput`, bounds\nthe complete serialized analysis envelope across all parts, including provenance,\ncapabilities, usage, and failure metadata. Extraction reserves room for a `limit`\noutcome and retains fitting earlier parts/segments when the aggregate is too\nlarge. Top-level `truncated` and `omittedEvidenceCount` identify publication\nomissions; per-result omissions retain every discarded segment's exact page or\ntime location. Existing errors and omitted ranges survive trimming unchanged.\nIf those diagnostic records cannot fit, the entire result is omitted rather than\npublishing an incomplete account of its known failures. If the ceiling\ncannot fit the minimum result envelope, no provider runs: `failAnalysis` records\nonly a fixed safe category and terminal lifecycle state, with no provider output\nor output digest. That service-owned failure accounting is outside the provider\npayload budget; `completeAnalysis` never accepts an oversized result.\n\nPartial page results survive later failures or process timeout. Warnings and\nomitted page/source references remain inspectable. `unsupported_type` covers\nvideo, unconfigured media and encrypted PDF; corrupt decoder failures without a\nsafe typed SDK category are `unavailable`, never raw exception strings. A host\ncan repair/reconfigure and create a fresh analysis without rewriting originals.\n`proposeDocumentSplits` produces a hashed, versioned, non-executable grouping of\nobserved pages; overlap, unordered groups and nonexistent pages are rejected.\n\n## Evidence and limitations\n\n`pnpm --filter @happyvertical/smrt-ingestion test:providers` runs actual local PDF\nSDK extraction, actual sharp multipage TIFF decoding, and packaged process/HTTP\nadapter lifecycle tests. The local speech server tests adapter transport and\ntermination, not transcription quality. The tiny TIFF fixture proves IFD/page\nmapping, not fax OCR accuracy. `extraction.test.ts` injects deterministic SDK\nboundaries for mixed/scanned PDF, Unlimited-OCR, camera observations, message\nattachments, audio timestamps and malformed/partial output. These fixtures are\nnot real remote-provider integrations and are not the ADR evaluation corpus.\n\nNo live Unlimited-OCR, speech recognition or vision quality run is claimed.\nNo recorded-human-audio recognition accuracy, real camera-scene quality,\ncalibrated confidence, table extraction, or automatic-action acceptance is\nestablished by these tests. Deployment owners must run the intended provider,\nmodel and representative retained corpus before making those claims. The\n[behavior matrix](../../docs/test-matrix/3672-ingestion-extraction.md) records the\nrelease commands and authority obligations.\n\nThe versioned on-disk corpus manifest records exact hashes for valid embedded,\nraster and mixed PDFs, two-page TIFF, a synthetic camera-format JPEG, a valid\nPCM WAV recording of a generated tone, email text, corrupt PDF and unsupported\nvideo. The tone is not human speech; the illustrated scene is not a photograph.\nReal local HTTP fixture runs execute Unlimited-OCR's installed SDK and speech\ntransport against deterministic responses/timeouts. They verify adapters, not\nremote models. Unlimited-OCR 0.61.6 rejects valid encoded images smaller than\n100 bytes; ingestion reports `unavailable` without altering them. This owning\nSDK defect is tracked in [happyvertical/ocr#143](https://github.com/happyvertical/ocr/issues/143).\n\nEach capability record explicitly reports `truncation` and `usage` as `unknown`\nor `reported`. Unlimited-OCR's current SDK discards upstream `finish_reason`\nand token usage, so both are `unknown` even for nonempty output. Downstream\nrules must not interpret `status: 'complete'` or `truncated: false` as proof of\nuntruncated OCR: they describe completed input processing and *detected*\ntruncation only. The adapter never bypasses the SDK to recover hidden fields.\nThe missing SDK metadata is tracked in [happyvertical/ocr#144](https://github.com/happyvertical/ocr/issues/144).\nAI vision retains reported truncation when supplied by its SDK. Missing provider\ncost is unknown, not zero; no cost estimate is invented.\n"
|
|
1609
|
+
},
|
|
1610
|
+
{
|
|
1611
|
+
"path": "PROPOSALS.md",
|
|
1612
|
+
"module": "PROPOSALS",
|
|
1613
|
+
"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"
|
|
1614
|
+
},
|
|
1615
|
+
{
|
|
1616
|
+
"path": "FEEDBACK.md",
|
|
1617
|
+
"module": "FEEDBACK",
|
|
1618
|
+
"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 with\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\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. 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"
|
|
1619
|
+
},
|
|
1620
|
+
{
|
|
1621
|
+
"path": "REVIEW.md",
|
|
1622
|
+
"module": "REVIEW",
|
|
1623
|
+
"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.\nThe evaluation lane remains explicitly unavailable until #3677.\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"
|
|
1581
1624
|
}
|
|
1582
1625
|
],
|
|
1583
1626
|
"agentSurface": {
|
|
@@ -1588,7 +1631,7 @@
|
|
|
1588
1631
|
"code": "not-module-scope",
|
|
1589
1632
|
"helper": "definePlaybook",
|
|
1590
1633
|
"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.",
|
|
1591
|
-
"line":
|
|
1634
|
+
"line": 429,
|
|
1592
1635
|
"column": 7,
|
|
1593
1636
|
"sourceFile": "src/test-support/execution.ts"
|
|
1594
1637
|
},
|
|
@@ -1596,9 +1639,41 @@
|
|
|
1596
1639
|
"code": "not-module-scope",
|
|
1597
1640
|
"helper": "definePlaybook",
|
|
1598
1641
|
"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":
|
|
1642
|
+
"line": 2089,
|
|
1600
1643
|
"column": 9,
|
|
1601
1644
|
"sourceFile": "src/test-support/execution.ts"
|
|
1645
|
+
},
|
|
1646
|
+
{
|
|
1647
|
+
"code": "not-module-scope",
|
|
1648
|
+
"helper": "definePlaybook",
|
|
1649
|
+
"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.",
|
|
1650
|
+
"line": 779,
|
|
1651
|
+
"column": 9,
|
|
1652
|
+
"sourceFile": "src/test-support/proposals.ts"
|
|
1653
|
+
},
|
|
1654
|
+
{
|
|
1655
|
+
"code": "not-module-scope",
|
|
1656
|
+
"helper": "definePlaybook",
|
|
1657
|
+
"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.",
|
|
1658
|
+
"line": 1351,
|
|
1659
|
+
"column": 9,
|
|
1660
|
+
"sourceFile": "src/test-support/proposals.ts"
|
|
1661
|
+
},
|
|
1662
|
+
{
|
|
1663
|
+
"code": "not-module-scope",
|
|
1664
|
+
"helper": "definePlaybook",
|
|
1665
|
+
"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.",
|
|
1666
|
+
"line": 3473,
|
|
1667
|
+
"column": 9,
|
|
1668
|
+
"sourceFile": "src/test-support/proposals.ts"
|
|
1669
|
+
},
|
|
1670
|
+
{
|
|
1671
|
+
"code": "not-module-scope",
|
|
1672
|
+
"helper": "definePlaybook",
|
|
1673
|
+
"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.",
|
|
1674
|
+
"line": 4098,
|
|
1675
|
+
"column": 7,
|
|
1676
|
+
"sourceFile": "src/test-support/proposals.ts"
|
|
1602
1677
|
}
|
|
1603
1678
|
]
|
|
1604
1679
|
}
|
|
@@ -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>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ProposalCatalogEntry } from '../../proposal-dto.js';
|
|
2
|
+
import type { IntakeReviewHost, ReviewAction } from '../../review-dto.js';
|
|
3
|
+
export interface Props {
|
|
4
|
+
host: IntakeReviewHost;
|
|
5
|
+
itemId: string;
|
|
6
|
+
action: ReviewAction;
|
|
7
|
+
catalog?: ProposalCatalogEntry;
|
|
8
|
+
currentAttemptId?: string;
|
|
9
|
+
run: (operation: () => Promise<unknown>) => Promise<void>;
|
|
10
|
+
deny: () => void;
|
|
11
|
+
}
|
|
12
|
+
declare const ActionReview: import("svelte").Component<Props, {}, "">;
|
|
13
|
+
type ActionReview = ReturnType<typeof ActionReview>;
|
|
14
|
+
export default ActionReview;
|
|
15
|
+
//# sourceMappingURL=ActionReview.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ActionReview.svelte.d.ts","sourceRoot":"","sources":["../../../src/svelte/components/ActionReview.svelte.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,oBAAoB,EACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAI1E,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,gBAAgB,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,CAAC,EAAE,oBAAoB,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,GAAG,EAAE,CAAC,SAAS,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,IAAI,EAAE,MAAM,IAAI,CAAC;CAClB;AA+ND,QAAA,MAAM,YAAY,2CAAwC,CAAC;AAC3D,KAAK,YAAY,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AACpD,eAAe,YAAY,CAAC"}
|