@happyvertical/smrt-ingestion 0.55.5 → 0.55.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/AGENTS.md +2 -0
  2. package/PROPOSALS.md +173 -0
  3. package/README.md +3 -0
  4. package/agents/execution.md +132 -0
  5. package/dist/chunks/execution-C6HJvl9e.js +7667 -0
  6. package/dist/chunks/execution-C6HJvl9e.js.map +1 -0
  7. package/dist/chunks/execution-internal-DWteDHM2.js +7 -0
  8. package/dist/chunks/execution-internal-DWteDHM2.js.map +1 -0
  9. package/dist/chunks/extraction-bseWZuWN.js +293 -0
  10. package/dist/chunks/extraction-bseWZuWN.js.map +1 -0
  11. package/dist/dto.d.ts +1 -0
  12. package/dist/dto.d.ts.map +1 -1
  13. package/dist/execution-contracts.d.ts +3 -0
  14. package/dist/execution-contracts.d.ts.map +1 -1
  15. package/dist/execution-internal.d.ts +7 -0
  16. package/dist/execution-internal.d.ts.map +1 -0
  17. package/dist/execution.d.ts +9 -1
  18. package/dist/execution.d.ts.map +1 -1
  19. package/dist/execution.js +1 -7614
  20. package/dist/extraction.d.ts.map +1 -1
  21. package/dist/manifest.json +1 -1
  22. package/dist/models.js +1 -1
  23. package/dist/models.js.map +1 -1
  24. package/dist/proposal-contracts.d.ts +85 -0
  25. package/dist/proposal-contracts.d.ts.map +1 -0
  26. package/dist/proposal-dto.d.ts +120 -0
  27. package/dist/proposal-dto.d.ts.map +1 -0
  28. package/dist/proposal-sdk.d.ts +12 -0
  29. package/dist/proposal-sdk.d.ts.map +1 -0
  30. package/dist/proposal-validation.d.ts +188 -0
  31. package/dist/proposal-validation.d.ts.map +1 -0
  32. package/dist/proposals.d.ts +41 -0
  33. package/dist/proposals.d.ts.map +1 -0
  34. package/dist/proposals.js +865 -0
  35. package/dist/proposals.js.map +1 -0
  36. package/dist/server.d.ts +32 -0
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/server.js +119 -289
  39. package/dist/server.js.map +1 -1
  40. package/dist/smrt-knowledge.json +24 -8
  41. package/package.json +19 -13
  42. package/dist/execution.js.map +0 -1
package/AGENTS.md CHANGED
@@ -11,6 +11,8 @@ belongs under `/server`. Generated REST/CLI/MCP model mutation is disabled.
11
11
  See [README.md](README.md) for host integration and recovery/deletion operation.
12
12
  See [EXTRACTION.md](EXTRACTION.md) for extraction contracts, provider isolation
13
13
  requirements and corpus validation.
14
+ See [PROPOSALS.md](PROPOSALS.md) for the optional server-only proposal stage,
15
+ current catalog/candidate authority and immutable source pinning.
14
16
 
15
17
  All records require tenant and confidential scope. Hosts create service scopes
16
18
  from authenticated sessions; source metadata is never authority. Every read and
package/PROPOSALS.md ADDED
@@ -0,0 +1,173 @@
1
+ # Application-aware proposal generation
2
+
3
+ `@happyvertical/smrt-ingestion/proposals` is server-only. Configure
4
+ `IngestionOptions.proposals` and the existing `execution.handlers` catalog.
5
+ Handlers opt into discovery with `discovery.mediaTypes`, `references`, and an
6
+ optional `candidates` callback. There is one catalog: the same operation or
7
+ ordered playbook adapter is discovered, validated, previewed, and later applied
8
+ by the execution service. Generation never approves or applies.
9
+
10
+ ## Discovery and authority
11
+
12
+ `listHandlers(itemId)` returns a bounded detached catalog. The owning execution
13
+ service checks the current principal, captured permissions/handler/operation
14
+ ceiling, policy, confidential scope, public registered operation facts, and
15
+ ordered playbook definition. Every configured provider must occur in the current
16
+ policy's `providers` allowlist. Missing grants remove handlers before model input.
17
+ An authorized catalog larger than the configured bound is rejected; the host must
18
+ narrow it explicitly instead of relying on silent truncation.
19
+
20
+ `findCandidates({itemId,handlerId,handlerVersion,query,limit})` returns
21
+ `{items,truncated}`. Its trusted handler callback receives `HandlerContext` with
22
+ the authorized transaction executor. Query by tenant and confidential scope
23
+ **before** selecting, ranking, or building labels. Use a bounded query (often
24
+ `limit + 1`) and report `hasMore`. The service projects candidate identity, model,
25
+ revision and label, then checks every target with the owning execution callback.
26
+ There are no hidden counts or pagination tokens. Truncated discovery forces
27
+ `needs_review` and cannot enter generated preview.
28
+
29
+ Completed generation reload checks process authority, the current attempt, and
30
+ owner/candidate visibility in the same final transaction. Database-backed grant
31
+ callbacks must use the supplied executor. The owning retention lifecycle encloses
32
+ that transaction so a denied read cannot roll back an authorized shorter privacy
33
+ ceiling; restoration starts only after the outer transaction has rolled back.
34
+
35
+ Candidate callbacks perform bounded database reads only: no provider I/O, network,
36
+ or domain mutations. Target locks and existing retention enforcement remain
37
+ owned by execution. Hosts configure their database's statement deadlines; an
38
+ arbitrary trusted callback is not a sandbox. Each existing-record argument must
39
+ be a declared top-level `references` field of kind `candidate` with its qualified
40
+ model, or `evidence`. Closed JSON argument schemas are required. The host owns
41
+ that declaration and its target authorization semantics.
42
+
43
+ ## Durable stages
44
+
45
+ 1. Complete extraction through the existing analysis ledger.
46
+ 2. Call `prepareGeneration(itemId, extractionAttemptId)`. It reads the current
47
+ completed/partial immutable extraction and returns configuration with
48
+ `stage: 'interpret'`, pinned source attempt/revision/input/output/evidence
49
+ digests, prompt/configuration/catalog/provider versions, limits and thresholds.
50
+ 3. Pass that configuration to `analyze(itemId, configuration, requestKey)` and
51
+ claim its new revision with `claimAnalysis`.
52
+ 4. The host's existing job callback routes on the frozen `configuration.stage`:
53
+ extraction invokes `extractAnalysis`; interpretation invokes
54
+ `generateProposals(lease)`.
55
+ 5. Reload the current completed generation using `getCompletedAnalysis(itemId)`,
56
+ or pass an explicit attempt ID to additionally reject stale client state.
57
+ Queued/running revisions never return an older completed attempt.
58
+
59
+ A generation revision does not rewrite terminal extraction. Reprocessing starts
60
+ with a new extraction revision, followed by interpretation, while the host keeps
61
+ the same business intention keys. An interrupted still-current generation lease
62
+ can be retried; terminal generation output remains immutable. `getGenerationInput`
63
+ reads historical extraction only through the current generation lease and its
64
+ frozen source pin. It verifies same-item scope, immutable hashes, durable evidence,
65
+ and current process permission before returning detached data. The source must be
66
+ the immediately preceding revision, so an intervening reprocess invalidates a
67
+ prepared generation. Completed generation reads additionally recheck current
68
+ catalog and target visibility before disclosing persisted candidate labels.
69
+ Expired, cancelled, revoked, retried or superseded workers cannot read or publish late output. The
70
+ current lease and each offered handler/candidate are rechecked immediately before
71
+ each outbound generative/decision boundary and before publication.
72
+
73
+ ## Providers and validation
74
+
75
+ `createSDKProposalGenerator(client, identity, {maxTokens,timeoutMs})` uses an
76
+ existing AI SDK `chat` client. It sends a fixed system instruction and separate
77
+ JSON evidence/catalog data, requests JSON, supplies cancellation and bounds, uses
78
+ no tools or continuation, and rejects known truncation or tool calls,
79
+ unexpected models, malformed JSON and oversized output. Configure SDK clients
80
+ without automatic retry that would bypass application boundary checks. The
81
+ adapter's public identity is exactly provider/model/version; credentials and raw
82
+ provider errors are never provenance.
83
+
84
+ A trusted custom `ProposalGenerator` must likewise honor cancellation, bound its
85
+ response, and explicitly declare validated `complete` or `unknown` completion.
86
+ The SDK currently normalizes missing/unknown finish reasons to `stop`
87
+ ([owning SDK follow-up](https://github.com/happyvertical/sdk/issues/1381)), so its
88
+ adapter conservatively declares `unknown`, persisted as
89
+ `generation_completion_unknown`. Otherwise valid suggestions remain available
90
+ for human preview; automatic eligibility always remains false. The service
91
+ deadline aborts requests and prevents late publication; it does not claim to terminate computation at a remote
92
+ provider or isolate native allocations. Extractor process limits remain separate.
93
+
94
+ Model output can contain only offered handler versions, schema-valid arguments,
95
+ retained evidence locations and offered alternative handler/candidate keys.
96
+ Candidate IDs must occur in the offered set, and evidence IDs in retained source
97
+ results. Unknown enums, invented IDs, extra authority/tool/approval fields and
98
+ malformed structures fail closed. Missing required top-level fields are retained
99
+ as `missingFields`, with `needs_review`; values are never invented to satisfy a
100
+ schema. Observed page/time/source granularity is preserved. Logical scan splits
101
+ use `proposeDocumentSplits`; originals and hashes remain intact.
102
+
103
+ `createSDKProposalDecisionClient(client)` adapts an existing SDK client’s optional
104
+ capability without changing its errors or protocol. Optional `decision` uses public core `executeDecision` and the existing SDK
105
+ predicate, choice, score and batch contracts. Supported-effect predicates,
106
+ handler classification, candidate entity matching, and action ambiguity/risk
107
+ are distinct questions. Their validated probabilities and provenance are stored
108
+ separately from generative provenance and unknown OCR certainty. The complete
109
+ serialized decision request, including suggestions and questions, must fit the
110
+ minimum configured/current policy byte ceiling before capability probing and
111
+ again before deciding. A policy change between these boundaries fails closed.
112
+ Ties, support probability or selected-handler confidence below
113
+ `minimumDecisionProbability`, and actually incomplete extraction require review.
114
+ Unknown provider
115
+ completion metadata is preserved as `source_completion_unknown`; it does not
116
+ block otherwise schema-valid **human** preview or imply completeness. Automatic
117
+ action eligibility remains false. An unconfigured decision path
118
+ is recorded explicitly. Configured errors produce a durable safe failure outcome;
119
+ they never silently switch to a generative decision fallback.
120
+
121
+ Output records zero, one or multiple suggestions, alternatives, missing fields,
122
+ source links, proposed splits, versions, allowlisted usage, warnings and explicit
123
+ `unknown`, `ambiguous`, `no_action`, `needs_review` or `provider_error` outcomes.
124
+ `automaticActionEligible` is always false. Provider input/output and the complete
125
+ serialized persisted envelope are bounded by configuration, live policy and the
126
+ receipt ceiling. Oversized output becomes a bounded review/limit result; when
127
+ no safe envelope fits, the owning service records fixed `failAnalysis` metadata
128
+ outside the provider payload budget without retaining provider output.
129
+
130
+ ## Explicit preview and stable intentions
131
+
132
+ The host chooses persisted suggestion indexes and calls:
133
+
134
+ ```ts
135
+ await service.previewGeneratedProposals({
136
+ itemId,
137
+ attemptId: generationAttemptId,
138
+ selections: [{
139
+ index: 0,
140
+ intentionKey: 'document:meeting-2026-10-09',
141
+ expectedRevision: 0,
142
+ requestId: 'review-request-1',
143
+ }],
144
+ });
145
+ ```
146
+
147
+ `intentionKey` is the host's stable business-intention identity across generation
148
+ revisions. Never derive a fresh key from model output, suggestion order or a retry.
149
+ Selections must reference current persisted validated `ready_for_review` output.
150
+ Each batch requires distinct suggestion indexes and intention keys; duplicate
151
+ indexes are rejected before any operation or plan preview is written.
152
+ The service rechecks current catalog/schema/target/source provenance, then calls
153
+ the existing operation or plan preview. Each result still requires the ordinary
154
+ human review and execution APIs. Reprocessing creates no new business identity;
155
+ successful-action replay protection stays with execution.
156
+
157
+ ## Evidence and limits
158
+
159
+ The test matrix is `docs/test-matrix/3673-ingestion-proposals.md`. SQLite and real
160
+ PostgreSQL suites exercise authority, revisions, abstention, hostile output,
161
+ compound proposals, split provenance and reviewed domain effects. The upload
162
+ reference composes authenticated multipart delivery of a generated embedded-text
163
+ PDF through the actual packaged PDF child, durable interpretation, and the existing
164
+ ordered ContentDocument draft/retained-asset plan. It checks duplicate delivery,
165
+ unauthenticated and foreign-tenant denial, explicit approval of both steps,
166
+ idempotent execution replay, page provenance, and unchanged original bytes.
167
+ The compound-email case uses a declared messages-owner snapshot fixture.
168
+
169
+ Local HTTP fixtures execute the actual AI SDK transport and cancellation contract.
170
+ Generative responses and the separate injected PDF split boundaries establish
171
+ deterministic orchestration, not model accuracy or OCR quality. No held-out routing
172
+ evaluation or automatic approval is claimed. Missing/unknown AI completion remains
173
+ explicit under [SDK #1381](https://github.com/happyvertical/sdk/issues/1381).
package/README.md CHANGED
@@ -146,3 +146,6 @@ raw-body reading. The callback must verify signature, delivery time/replay windo
146
146
  and account ownership, then return trusted binding and durable delivery identity.
147
147
  No vendor implementation or hardware driver is selected. All adapters invoke
148
148
  only receipt preservation, never domain writes, AI tools or external actions.
149
+
150
+ See [PROPOSALS.md](PROPOSALS.md) for bounded application catalog discovery, durable
151
+ interpretation revisions, optional typed decisions and explicit generated preview.
@@ -0,0 +1,132 @@
1
+ # Review and execution integration
2
+
3
+ `/execution` exports `IntakeExecutionService`, handler/host types, policy
4
+ resolution, binding digests and `continueIntakeReview`. `IngestionService` exposes
5
+ these operations when its optional `execution` configuration is present. Its
6
+ loader is lazy: importing `/server` alone does not import the principal stack.
7
+ `/dto` exposes execution messages using type-only exports. No generated REST,
8
+ CLI or MCP mutation endpoint is enabled; applications authenticate their own
9
+ service surface and create `IngestionScope` from the session.
10
+
11
+ ## Catalog and authority
12
+
13
+ Applications supply a trusted `IntakeExecutionOptions.handlers` catalog.
14
+ `OperationHandler` has qualified ID, immutable version, description, object JSON
15
+ schemas for arguments/results, allowlisted `resultModels`, `validate`, `preview`,
16
+ a registered `{model, action, version}` operation and explicit effect/idempotency/
17
+ open-world capability declaration. Preview returns display, exact normalized
18
+ arguments and target revision preconditions. There is no arbitrary tool execution
19
+ or expression evaluation. Reviewer display wraps application fields under `preview`
20
+ and symbolic metadata under `dependencies`; plan steps additionally wrap that
21
+ object under `step` alongside the plan preview. Application display keys cannot
22
+ overwrite framework metadata or be silently overwritten by it. A version change
23
+ requires a new preview and approval.
24
+ `PlanHandler` references a real registered playbook key and resolved definition
25
+ hash; expansion contains only ordered operation handlers and typed earlier-step
26
+ result references. Discovery/proposal generation consumes this catalog rather
27
+ than creating another registry. Semantic model output is never host configuration.
28
+
29
+ Authenticated receipt context captures `capturedCeiling.execution` with principal
30
+ ID and permission/handler/operation ceilings. The execution host's `authorize`
31
+ resolves current grants and application/tenant/source/(optional request) policy
32
+ on the supplied executor, checking the active requester and confidential scope.
33
+ Lists intersect, budgets minimize, review requirements OR, and disabled policy
34
+ wins. Policy versions must change when policy semantics change. Normal operation
35
+ requires human review; machine authorization requires explicit evaluated opt-ins
36
+ at all three authority layers and remains separate provenance from human review.
37
+ The reference handlers always require review; no evaluation claim is made here.
38
+
39
+ `mutationBoundary: 'serialized'` is an explicit host guarantee, not an inferred
40
+ property of a permissions array: grant revocation must serialize with the supplied
41
+ transaction, or the owning mutation must revalidate under its own lock. The host
42
+ must implement that guarantee before enabling handlers. `assertTarget` similarly
43
+ locks current tenant/confidential ownership and revision against concurrent
44
+ writers using the supplied executor. The reference host demonstrates a scoped
45
+ row lock before public `Contents` reads. A current `PrincipalRun` intersects live
46
+ permissions with the captured ceiling and checks the exact registered collection
47
+ operation at every effect. No `runOnce` atomicity is assumed.
48
+
49
+ ## Durable review and effects
50
+
51
+ Preview appends a proposal bound to exact analysis attempt/evidence, handler,
52
+ arguments, policy and target preconditions. Decision requests use unique durable
53
+ request IDs; reusing an ID with changed content is rejected. First valid review
54
+ wins under the item lock. Corrections append a new revision; reject/defer remain
55
+ non-executable. Plan corrections use re-expansion. Human decisions expire and
56
+ live authority is checked again before each step. Raw foundation proposals cannot
57
+ bypass execution's schema, preview, evidence and approval verification.
58
+
59
+ Database handlers must use `context.db` for every domain effect and must perform
60
+ no external I/O. Domain result and successful execution commit together. A domain savepoint rolls failed effects
61
+ back while preserving the item lock and atomically consuming the retry attempt. Completed
62
+ actions survive job cleanup and evidence retention; expired originals leave a
63
+ minimal result digest tombstone, preventing a second effect. Active result reads
64
+ recheck host visibility and result target ownership.
65
+
66
+ External handlers reserve a stable action idempotency key before submission.
67
+ Timeout, process death or ambiguous outcome requires reconciliation; an expired
68
+ lease never means permission to resend. `reconcile` must return authoritative
69
+ `succeeded`, `not_applied` or `unknown`. `not_applied` is safe only when the provider
70
+ can exclude a late acceptance of the original send; uncertainty stays `unknown`.
71
+ The same key is reused after a conclusive non-application. Cancellation prevents
72
+ pending work but cannot retract a send already issued. Applications must arrange
73
+ provider reconciliation before privacy retention removes the binding; a redacted
74
+ unknown action fails closed and cannot automatically execute again.
75
+
76
+ Each plan step has a stable action identity. Completed steps are immutable and
77
+ return their original result. Symbolic record IDs bind to exact earlier proposal
78
+ revision, successful result digest/model and target revision; they cannot point
79
+ across items or form cycles. Failed dependent steps never repeat predecessors.
80
+ The plan preview and target preconditions are part of its digest and visible in
81
+ each step review; changed preview/preconditions require a fresh review.
82
+ Abort/continue follows the pinned public playbook definition, with fresh authority
83
+ at every step.
84
+
85
+ `continueIntakeReview` uses the existing jobs continuation context. Applications
86
+ create tasks with owner, tenant and exact `{recordId, revision, inputKey}` binding
87
+ and configure `authorizeMcpTask` to revalidate it. A continuation answer only wakes
88
+ the task; the service reloads the authoritative decision. Waiting persists without
89
+ an occupied worker and survives runner restart.
90
+
91
+ ## Deployment and evidence
92
+
93
+ Apply normal manifest migrations before runtime. Execution imports the public
94
+ agents/users principal stack, which registers profiles including `ProfileAsset`;
95
+ execution-enabled hosts must migrate their dependency graph (including profile
96
+ asset joins used by asset deletion). `/server` receipt-only imports register none
97
+ of these additional models. Content is not a runtime dependency of ingestion.
98
+ `reference/handlers.ts` is an application/test fixture, excluded from published
99
+ entries and declarations; importing it deliberately adds Content and its asset
100
+ joins, whose migrations the application then owns. No runtime DDL is performed.
101
+
102
+ Real SQLite and PostgreSQL execution suites exercise the public Content draft and
103
+ attachment APIs, transaction rollback, actor/context denials, simultaneous applies
104
+ and reviewers, retention replay, external process death and actual TaskRunner
105
+ restart. See the issue 3674 test matrix for the complete release evidence mapping.
106
+
107
+ ## Layered retention and request automation
108
+
109
+ Every automation-bearing policy layer, including an optional request layer, must
110
+ match the evaluated version. An absent request automation block adds no evaluator
111
+ restriction; it cannot replace the three required application/tenant/source opt-ins.
112
+
113
+ Authorized execution-policy access monotonically narrows the existing intake
114
+ expiry to `min(existing expires_at, item.created_at + resolved retentionMs)`.
115
+ The anchor is receipt creation, never review, retry or replay time. A longer later
116
+ policy never extends a recorded deadline. This hard maximum applies to the whole
117
+ intake item: the existing `sweepRetention` protocol removes retained originals and
118
+ derivatives, preserving replay identities. No second expiry column or hidden clock
119
+ is introduced, and no blob I/O occurs in an execution transaction.
120
+
121
+ At an observed expired deadline, execution reads/completions erase proposal,
122
+ decision, execution, plan, action and feedback payloads under the item lock. Review
123
+ reads return existing identity/hash fields with `state: 'expired'` and empty
124
+ `display`; completed action replay returns its digest-only tombstone. Failed writes, including ordinary validation/CAS/policy rejection and domain
125
+ savepoint rollback, cannot roll back an already-authorized retention ceiling or
126
+ redaction. Restoring a recorded authorized maximum needs no new content-read grant;
127
+ later revocation cannot undo it. Initial denied authorization records no intent.
128
+ Completed replay checks the deadline again after target authorization
129
+ callbacks before returning cached content. Proposal publication and automatic
130
+ authorization also recheck after preview/evaluator callbacks, before publishing
131
+ retained proposal or decision payloads. Unknown
132
+ external outcomes remain unknown/reconcile-only, never eligible for blind resend.