jsfe 1.7.9 → 1.7.11

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 (47) hide show
  1. package/README.md +2 -3
  2. package/dist/forms/authoring.d.ts +1 -1
  3. package/dist/forms/authoring.d.ts.map +1 -1
  4. package/dist/forms/authoring.js +7 -6
  5. package/dist/forms/choice-flow.d.ts +0 -4
  6. package/dist/forms/choice-flow.d.ts.map +1 -1
  7. package/dist/forms/choice-flow.js +10 -14
  8. package/dist/forms/continuation-safety.d.ts.map +1 -1
  9. package/dist/forms/continuation-safety.js +2 -1
  10. package/dist/forms/contracts.d.ts +1 -1
  11. package/dist/forms/contracts.d.ts.map +1 -1
  12. package/dist/forms/contracts.js +6 -5
  13. package/dist/forms/declaration-capture.d.ts +7 -0
  14. package/dist/forms/declaration-capture.d.ts.map +1 -0
  15. package/dist/forms/declaration-capture.js +15 -0
  16. package/dist/forms/declarations.d.ts +20 -0
  17. package/dist/forms/declarations.d.ts.map +1 -0
  18. package/dist/forms/declarations.js +272 -0
  19. package/dist/forms/flows.js +13 -13
  20. package/dist/forms/identity-flows.js +8 -8
  21. package/dist/forms/index.d.ts +2 -0
  22. package/dist/forms/index.js +2 -0
  23. package/dist/forms/prompt-compiler.d.ts.map +1 -1
  24. package/dist/forms/prompt-compiler.js +5 -1
  25. package/dist/helpers/answer.d.ts +1 -1
  26. package/dist/helpers/answer.js +2 -2
  27. package/dist/helpers/form-sources.js +1 -1
  28. package/dist/helpers/index.d.ts +1 -0
  29. package/dist/helpers/index.d.ts.map +1 -1
  30. package/dist/helpers/index.js +1 -0
  31. package/dist/helpers/match-inputs.js +5 -5
  32. package/dist/helpers/named-functions.d.ts +5 -0
  33. package/dist/helpers/named-functions.d.ts.map +1 -0
  34. package/dist/helpers/named-functions.js +54 -0
  35. package/dist/helpers/proposal-contract.js +4 -4
  36. package/dist/host/capabilities.d.ts.map +1 -1
  37. package/dist/host/capabilities.js +10 -1
  38. package/dist/host/registry-composition.d.ts.map +1 -1
  39. package/dist/host/registry-composition.js +9 -3
  40. package/dist/index.d.ts +13 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +66 -2
  43. package/dist/runtime-identity.js +1 -1
  44. package/docs/copilot-reference.md +336 -66
  45. package/docs/development-release.md +10 -1
  46. package/package.json +1 -2
  47. package/docs/forms.md +0 -309
package/docs/forms.md DELETED
@@ -1,309 +0,0 @@
1
- # Native forms, providers and performers
2
-
3
- Implemented locally on 2026-10-19 in `jsfe/src/forms` and `jsfe/src/helpers`. These changes are a local, unpublished development candidate. Record the package version and runtime byte fingerprint; a matching version string alone does not identify a build. No production deployment is implied.
4
-
5
- This is the current authoring reference. Earlier `collect-input-pattern.md` and `manifests.md` preserve the original design discussion; their carry/lift migration recipe and definition-keyed state examples are superseded.
6
-
7
- ## Ownership
8
-
9
- - JSFE owns generic matching, input validation protocol, form instances/dependencies, provider retrieval, confirmation, action identity and durable recovery policy. Import builders and shared declarations from `jsfe/forms`; expression helpers come from `jsfe/helpers`.
10
- - The host owns credentialed transport, storage adapters and persistence acknowledgments. Shared behavior does not belong in tenant-local or host-local support copies.
11
- - Tenant modules own catalogs, API payloads, business eligibility and presentation. Pure domain rules may be authored as source functions and embedded at build time. Do not read legacy generators or snapshots to construct runtime steps.
12
- - `defineForm`, `defineProvider`, `definePerformer`, `defineWorker`, `operationWorkers` and `linkFormSchemas` compile native declarations. `validateFlowContracts` checks contracts and references; it does not prove behavioral parity.
13
-
14
- ## One instance per owned task
15
-
16
- `cargo.forms[instance]` contains `definition`, `task`, `parent`, `result_input`, canonical `specs`, `values`, accepted proofs, pending readings, errors, preparation state, `data`, saved arguments and child instances. Instance IDs are opaque. `cargo.formTasks[definition]` identifies an active root; nested ownership is `(parent instance, input slot)`, allowing two address slots or independent tasks to coexist.
17
-
18
- Use the supplied `form_instance` only for internal reentry. A form resumes its saved arguments and validated progress. A sub-form returns through the same acceptance/invalidation transition as a field. Context service forms use `parent_form` with no `result_input`; they inherit the owner’s task without fabricating a value slot.
19
-
20
- Never mutate accepted values directly for ordinary input. Use the common acceptance protocol. Explicit business-derived values and service results must have declared owning paths and dependencies.
21
-
22
- ## Input declarations
23
-
24
- Use presets (`field`), an owned sub-form (`form`), or a narrow inline `profile`. Include labels and prompts in both languages. Relevant attributes:
25
-
26
- - `when` / `unless`: relevance and readability. Conditions can reference sibling values, `cargo.*`, or `form.data.*`. Unknown conditions wait; they do not silently count as false.
27
- - `required_when`: whether a relevant field must be collected. False makes the field optional while retaining voluntary recognition. Unknown blocks completion until its premise is known. Omit for required fields.
28
- - `depends_on`: preparation/validation waits for committed prerequisite evidence; changing the prerequisite invalidates the dependent transitively.
29
- - `reset_on`: invalidation only. It does not add a validation prerequisite.
30
- - `validator`: receives `{form,input,value,values,reading}` and writes `cargo.inputCheck={ok,value?,message?,message_es?}`. Missing result fails closed. Activation and conversational answers use this same path.
31
- - `prepare`: runs once before first validation or prompt; `refresh` runs before each prompt. `choices_from` / `question_from` read owner `data`. Use `compileFormPrompts` for contextual template prompts; it preserves declarations and generates workers.
32
- - `activate` / `activate_on`: nominate dormant child entry fields that may propose controller assignments, such as a card number selecting a new-card branch. The controller and nominated entry validate as one atomic group; rejection cannot flip the controller. Use narrow descendant paths, never broad matching of every child field.
33
- - `validate_always:true`: revalidate even an unchanged value when its business assumptions must be refreshed. Validator `revalidate:true` provides the same explicit cache bypass at validator declaration.
34
- - `after`: post-commit callback. `any_of` groups can be `exclusive`; conflicting members require clarification.
35
- - `confirm_against`: explicitly requires clarification when two field interpretations overlap, including current-field priority exceptions.
36
- - `choices[].keys`: whole-answer keypad aliases, recognized only for the current field. An explicit current keypad key wins an overlapping current-field claim, including an `any_of` group; `confirm_against` can still require clarification. Keys never become aliases for noncurrent fields. `words` are semantic aliases; `current_only` restricts a choice. Grouped digit aliases and marked currency must not steal each other’s spans. English and Spanish word amounts require explicit currency and follow the shared cardinal grammar; sequential card digits are not money.
37
-
38
- A batch retains independent valid fields if another field fails. Dependent early values remain pending until prerequisites validate. An invalid prerequisite cannot authorize an effect. Structured submissions are read leaf by leaf; objects are never coerced into scalar values. Primary nested extraction schemas derive from the same input declarations.
39
-
40
- ## Resolution and reentry
41
-
42
- Resolve overlapping evidence in this order: current field, one matching field at the nearest owning scope, then ancestors. Multiple competing claims at the same applicable scope are clarified. Independent spans fill independent fields. Typed evidence beats an unconstrained text fallback. A noncurrent, already-filled choice mentioned incidentally in the current text answer does not displace that answer; a whole-answer repetition (including courtesy) remains a claim to that choice. Explicit new choices and structured data remain eligible out of order. Resolve losing fallback evidence before computing overlapping groups, so one whole-answer text span cannot make independent email/phone clauses ambiguous. `confirm_against` deliberately retains paired interpretations and overrides ordinary priority.
43
-
44
- FORM collectors preserve the original answer by default (`as_spoken:true`), including on voice channels. Their declared profile readers normalize typed evidence and match out-of-order fields before validation; question-specific voice cleanup must not discard other fields first. Explicit `as_spoken:false` remains available for a field that deliberately needs that cleanup. Direct `SAY-GET` and ordinary `ask-choice` defaults remain unchanged.
45
-
46
- For an open rationale or description, opt into `profile:{kind:'text',narrative:true}`. The current narrative retains the full answer while independently shaped phone/email fields spend only their own spans. A structured-only number or address does not fill the rationale. Incidental ancestor choices and same-form choices listed in the requested field’s `reset_on` dependencies are context; a whole-answer declared choice or a bounded explicit correction such as “actually insurance” or “en realidad seguro” can still revise the ancestor. Other sibling choices remain independently collectable, including in compound answers. Whole-answer choices, explicit corrections, independently typed fields and explicit `confirm_against` ambiguity retain their normal behavior. A choice field may also opt into `narrative:true` when its answer commonly includes surrounding explanation; a valid current selection then owns that explanation without changing another discriminator from an incidental word. This does not infer an unmatched choice or bypass its validator. Ordinary text profiles keep their existing structured-input precedence.
47
-
48
- Narrative collection reads email fields in explicit literal mode: a complete visible `owner@example.com` token stays that exact recipient, even inside prose. The standalone API `readEmail(text,{literal:true})` and `profile:{kind:'email',literal:true}` offer the same behavior. Different visible addresses fail closed; with no visible email token, spoken/spelled parsing remains available. Default `readEmail(text)` is unchanged, including joining intentional local-name fragments such as “Maria jose@gmail.com”. Use the explicit contextual mode when surrounding prose must not become part of the recipient.
49
-
50
- The common loop asks the first ready missing required input, skips accepted data, unwinds inapplicable children and blocks unresolved prerequisites. A context service may use `stop` and `close_on_stop:true` to close itself without handing a value to its parent. With `resume_on_parent_change:true`, an accepted owner correction closes the stale context branch and resumes the highest changed opted-in ancestor with its retained progress, requiring a fresh confirmation. Nested contexts cannot return through obsolete callback tails or restore an old draft or action token; unrelated tasks remain intact. `RETURN` ends the entire engine transaction; ordinary worker completion uses `END`.
51
-
52
- Optional follow-ups may declare `incomplete_outcome:{outcome:'resolved',reason:'payment_made'}` to preserve an already completed task’s outcome when collection cannot finish or the user leaves. Accepted outcome values are `resolved`, `unresolved` and `deflected`, with a nonempty reason. A reusable form may instead use `incomplete_outcome:{from:'completed_outcome'}` with a declared object parameter; its runtime value must pass the same validation. The nearest actual owned ancestor supplies a fallback to a child. Another task’s outcome never does. The policy covers missing input specifications, blocked dependencies, exhausted validation/retries and unmatched collection/confirmation dispatch; it does not complete missing inputs or authorize effects. Omit it for ordinary required forms: contextual yields are pending, while actual validation or service failures remain unresolved.
53
-
54
- For bounded collection recovery, declare `on_exhausted:'recovery-worker'` on an input or FORM. On attempt exhaustion, the resolver checks the failed input/member, its group, then its containing form before walking actual owned ancestors. The worker receives `{form,failed_form,input,failed_input,reason:'attempts_exhausted'}`: `form` and `input` identify the selected policy’s owner, while `failed_form` and `failed_input` identify the original failure. Shared recovery resets only the selected input branch, closes its child without handing off an incomplete value, withdraws confirmation and reboots to that worker. Independent draft fields remain. The callback must deliberately collect a new choice and obtain any required fresh confirmation before an effect; exhaustion is not consent. Worker names and references are validated. With no callback, the existing incomplete-outcome or give-up path applies.
55
-
56
- The common collector passes `form_context:{form,current,names,questions}` to `ask-choice`. The reader checks declared current-field or unique same-scope form readings before classifying an answer as a stale verification-code echo. A valid ZIP, amount or current menu key must not be discarded merely because its digits occur in the prior OTP. Use this shared context instead of a tenant-specific code filter.
57
-
58
- Private provider questions during collection preserve the owner and pending verification. Repeated questions join the pending provider request instead of stacking another authentication flow. Independent field clauses are accepted before a provider suspends for verification. Questions cannot become invalid OTP attempts or arbitrary text answers.
59
-
60
- ## Input proposal confirmation (unpublished candidate)
61
-
62
- Use `input.proposal` when an inferred or ambiguous **field value** needs the caller's approval before acceptance. This is independent of a performer's final action confirmation: accepting a payment option never authorizes a charge. Declare it on readable leaf inputs, including members of an `any_of` group; group, bound-value and subform declarations reject this attribute instead of silently ignoring it. Ordinary inputs without this declaration retain their existing path.
63
-
64
- ```js
65
- {
66
- name:'reason', profile:{kind:'choice',choices:[/* canonical choices */]},
67
- proposal:{prepare:'describe-reason',origins:['activation'],when:{reason:['lost','stolen']}}
68
- }
69
- ```
70
-
71
- An optional pure `prepare` worker receives `{form,input,value,values,reading}`. `value` is validator-normalized; `values` includes validated peers and this candidate. It writes `cargo.proposalCheck={question,question_es,binding?,on_declined?,words?,no_keys?,clarifications?,interrupts?}`, or explicitly `null` when no proposal is required. A static policy may supply the question directly. An ordinary validator can independently return `cargo.inputCheck={ok:true,value,proposal:{question,question_es,binding,...}}`. Missing or malformed descriptors fail closed. Declare dynamic proposal workers with `contract.requires:['jsfe:input-proposals:v1']`; static policies and linked descendant schemas derive that requirement automatically.
72
-
73
- Formatters must be pure apart from their output slot: no authentication, business updates or external effects. Bind the semantic subject and facts that make the question true (account, option, plan, prior receipt). Avoid volatile unrelated history. `origins` restricts initial triggering to `activation` or `answer`; corrections to a pending proposal still require a fresh applicable decision. `when`/`unless` use normal form conditions against candidate values.
74
-
75
- JSFE owns `owner.inputProposals[input]`, separate from canonical `values` and the existing **action** `proposal`. Candidates survive contextual yield and bare reentry. An owned `confirm-input-proposal` context uses ordinary exact confirmation and treats the proposed field as current for corrections. Independent inputs commit normally. Accepting a member of an exclusive `any_of` group withdraws pending or confirmed proposals for its peer members. YES is provisional proof bound to owner identity, revision, candidate, prompt and business binding; ordinary validation reruns before canonical acceptance and post-commit callbacks. A changed candidate, policy, subject or binding revokes old proof. Rejected/inapplicable candidates are withdrawn; unmet prerequisites defer them. Approval is consumed once. Do not set proposal state or approval tokens in tenant expressions.
76
-
77
- NO never commits the candidate or hands an incomplete value to a parent. It closes the confirmation context and optionally calls `on_declined` with `{form,input,value,reading}` once; this worker chooses the business alternative and may close its owner. Yield retains the proposal and has no decline effect. Do not add separate yes/no collector children, cargo permission flags or ad hoc stack restoration.
78
-
79
- The versioned intrinsic requirement is supported by JSFE itself, with no host feature switch. Unknown `jsfe:*` versions reject admission even if a caller supplies a matching boolean. Compiled proposal entries also include a strict `formProposalProtocol() === 1` guard, so an older direct engine cannot silently skip consent. Deploy matched runtime, shared workers and tenant declarations; these candidate artifacts must not be activated with published 1.7.2.
80
-
81
- Test actual EN/ES voice/text conversations: activation, unreadable-answer yield, no-argument root reentry, explicit NO, mixed YES plus correction, provider detours, independent fields, nested/foreign owners, stale bindings and consumed proof. Assert canonical values, callbacks, authentication and effects, then run the complete engine and tenant acceptance matrices against installed package bytes.
82
-
83
- ## Providers
84
-
85
- Declare a `provides` catalog: subject, gate (`flow`, verified paths), source (`flow`, result path, subject/freshness policy), facts and fact sets. Each fact has a key, phrasings, source path or dedicated worker, rendering rules and explicit missing-data text. A private catalog requires an explicit gate. Derive `asked` and mid-form question choices with the builder; do not maintain another list.
86
-
87
- `provide-data`, `load-source` and `answer-facts` retrieve and answer requested facts. An explicit fact request does not require a generic account summary. Source refresh clears old results first and records freshness only after success. Subject changes invalidate incompatible data and verification. `no_gate` may skip rerunning a gate only when its declared verification paths hold; it never bypasses their check.
88
-
89
- ## Performers
90
-
91
- Declare each action’s name, effect, subject, gate, execution worker/tool, idempotency or reconciliation policy, exact confirmation where applicable, and outcomes. `definePerformer` gathers inputs, prepares an immutable request, selects one applicable action, confirms it, calls `perform-action`, runs its required pure projector, consumes the exact durable receipt, then presents the stored result. Presenter arguments are `{form,request,result}`; retain that explicit result across nested performers rather than rereading the shared last-result cargo slot.
92
-
93
- Declare `project:[SET steps]` for deterministic session updates such as payment and case ledgers. Its expression locals are `{form,formSnapshot,request,result,key}`: `form` is the owned instance ID and `formSnapshot` is its state at the recorded action. Projection writes target current `cargo`; detached recovery does not replace current forms with that snapshot. Use the durable key for idempotence, the original result timestamp for ordering and explicit ownership guards to preserve newer task drafts or facts. The compiler accepts only SET expressions with local temporary variables and rejects flow/tool/message orchestration. Projectors must be effect-free; expression failure prevents receipt consumption. Presenters own conversation and optional subsequent performers. Ledger updates belong in `project`, because detached late recovery runs this projector without replaying the presenter, `after` steps or caller continuation.
94
-
95
- Bind subjects to owner data, including composite identities where necessary: `{account,service}` for cancellation or `{contact,type,reason}` for CRM filing. Compare the prepared subject to the current verification evidence before execution. An old unknown result holds that action scope; it cannot capture unrelated requests.
96
-
97
- Confirmation is separate from fields. It binds the current form revision, values and prepared request. A correction invalidates that binding. Use `confirm.no_keys` only when a declared menu needs different keypad semantics; default `2` remains NO. Confirmation events receive `{form,event,text}` and reenter through ordinary validation. A YES embedded in other content is not consent. `confirm.clarifications` may list exact whole-answer clarification phrases in both languages, such as `['what does that mean','qué significa eso']`. Matching ignores question punctuation and uses the bounded ordinary unclear-answer retry path. These phrases neither consent nor change the request; other unrelated requests still dispatch normally.
98
-
99
- ## Durable actions and host save boundary
100
-
101
- Hosts inject `createActionJournal({storage,namespace})` from `jsfe/host`; storage implements atomic attempt/scope/session-index compare-and-swap. A journal must expose claim, complete, checkpoint and pending recovery. The built-in `jsfe:action-claim` and `jsfe:action-complete` ports are reserved. Missing storage fails closed before native effects unless the host explicitly selects session-only execution. In hy-rag-lambdas, `config.jsfe.durableActions` defaults to false: the journal stays unattached, and ordinary legacy turns make no journal reads or add native recovery progress. Only an explicitly opted-in tenant activates this policy.
102
-
103
- `engine.getActionRecoveryIdentity()` privately caches a verified build stamp and a canonical digest of the loaded compiled flow and tool execution contracts. The stamp is verified before bundling and remains available inside the bundle; production recovery performs no runtime filesystem scan. Checkpoints carry `{protocol:1,runtime,definitions}`. Before full restoration or pure projection, JSFE requires an exact identity match. Missing, unsupported or different identities hold the pending outcome, preserve current task state, defer the incoming message and run no effect, projector or acknowledgment. A package version label is not a compatibility identity. Loaded definitions are immutable after activation; hot reload constructs a new engine, and execution counters/default data belong to individual frames.
104
-
105
- The journal records a resumable engine checkpoint before an effect and the result afterward. For an opted-in native tenant, JSFE examines unconsumed versions per action key before consuming a new user message. Only an exact compatible recovery identity proceeds to continuation selection. A storage sequence orders journal writes, not workflow progress. A checkpoint from progress absent in the saved session restores its continuation; a late completion after saved progress runs only its pure projector against the current session, preserving current tasks and never replaying its presenter or caller tail. The arriving input is recorded as deferred recovery metadata. It never treats that message as retroactive consent. A higher journal sequence alone cannot justify restoring an older workflow; per-key applied versions, saved workflow progress, recovery epoch and host invalidation revision determine whether continuation restore is safe.
106
-
107
- The host saves the resulting session first, then awaits `checkpointActionSession`. Failed or rejected saves never release action scopes. Versioned `{key,sequence}` receipts stay persisted for acknowledgment retry. Freeze those versions at the successful save boundary: an older attempted/unknown receipt must never acknowledge a later completion. Late tool callbacks return results without advancing the active session’s applied watermark. The performer advances it only after consuming and projecting the durable result. Acknowledging an unknown outcome clears its recovery checkpoint but retains its scope hold. No elapsed timeout resolves an uncertain financial action; a balance change alone is not transaction identity evidence. Explicit fresh consent may supersede an uncertain SEND only under a declared send retry policy.
108
-
109
- Host invalidations use `retainRecoveryState(session,paths)` after changing or deleting host-owned cargo. Newer invalidations, including deletion tombstones, select pure result projection against the current session instead of restoring the older workflow or its private presenter. Explicit conversation resets rotate the persisted recovery epoch: old outcomes can be projected, but discarded workflows cannot resume. Before every fresh effect, `perform-action` reruns the declared `gate.flow` and checks current verification paths; a stale derived permission flag cannot replace that gate.
110
-
111
- The host’s DynamoDB adapter shares the configured chats table with reserved internal keys. Chat entry points reject those keys. Do not deploy a performer in durable mode without configuring this port and testing the actual save boundary.
112
-
113
- ## Explicit session-only action persistence (1.7.1)
114
-
115
- The engine defaults to `engine.actionPersistence = 'durable'`. A host can explicitly set `engine.actionPersistence = 'session-only'` and leave `engine.actionJournal` unattached. In hy-rag-lambdas, the tenant setting is `jsfe: {actionPersistence: 'session-only'}`; `durableActions` must be omitted or false. Selecting session-only with `durableActions: true` is a configuration error. Omitting the mode or disabling `durableActions` alone never opts out of durability for native performers. Storage encoding remains independent and defaults to plain.
116
-
117
- Both modes use the same request ownership, input revision, authentication gate and exact confirmation checks. Session-only records the claim and first observed outcome in the form's action record. A saved attempted/unknown action cannot execute again on reentry, even after form replacement; saved completed requests replay their result while that task remains owned. Unknown charges cannot be automatically retried. An intentionally new task still requires its own confirmation. Session-only creates no durable receipts, journal reads/writes or cross-invocation recovery checkpoint.
118
-
119
- The host must serialize turns and persist the complete returned session. If an external charge succeeds but that updated session is lost, a later invocation can repeat the effect from the older snapshot. Session-only therefore does not provide crash-safe double-charge prevention or protection against concurrently forked session snapshots. Such protection requires durable action storage and/or backend idempotency with a key recoverable after the failure. Acknowledgment is not evidence of business-level exactly-once processing in either mode.
120
-
121
- The selected persistence mode is recorded in action-enabled conversations before the first effect. A mode change rejects processing instead of silently migrating a live conversation. Existing durable recovery metadata and receipts also reject session-only execution. Route existing conversations to their original mode; use the new policy for fresh conversations. Switching a policy flag is not a durable-state migration, especially for older snapshots that predate the policy marker.
122
-
123
- ## Checkpoint storage codec
124
-
125
- The Node host storage boundary imports `encodeCheckpoint`, `decodeCheckpoint` and `isEncodedCheckpoint` from `jsfe/host/node`. This Node-only entry uses asynchronous Brotli; the universal `jsfe/host` entry remains free of Node imports. The version-1 envelope stores binary `Uint8Array` data, the original UTF-8 JSON byte count and a SHA-256 integrity digest. It losslessly round-trips JSON-compatible session data without trimming history, forms or action records.
126
-
127
- The default limits are 16 MiB of decoded JSON and 350 KiB of encoded binary. Decompression is bounded before decoding, and the host separately checks the complete DynamoDB item against a conservative 400 KiB bound, including all metadata and other fields. Compression does not guarantee that arbitrary data fits; an oversized item fails before the database write.
128
-
129
- The host journal adapter encodes only the attempt checkpoint and decodes it when reading; successful acknowledgment removes that checkpoint payload. Journal-internal storage remains separate from conversation storage. Conversation writers default to `config.jsfe.sessionEncoding:'plain'`; only an explicit `'br-v1'` enables binary `engineSession` writes. This capability is independent of `durableActions`. The configuration group and both keys may be omitted; malformed values and unknown keys reject configuration. Conversation readers always decode supported envelopes before constructing a session, including when writers are disabled. Receipt versions are frozen at the actual save boundary, and other host fields retain their normal representation.
130
-
131
- Historical plaintext remains readable. Unsupported envelopes, corrupt data, integrity failures and codec limits raise `CheckpointCodecError`; whole-item overflow raises `JSFEStorageSizeLimit`. A corrupt saved conversation must not become a fresh session or overwrite its stored row. Failed writes never acknowledge action receipts. Disabling encoding converts a decoded row to plaintext only on its next successful size-bounded save; it does not convert dormant rows, and oversized plaintext fails without trimming or modifying the old envelope.
132
-
133
- Roll out decoder-capable readers before enabling any tenant’s binary writer. Old workers in a mixed fleet cannot read new envelopes. A pre-reader rollback requires lossless, revision-checked conversion and verification of every affected row; a flag toggle alone is insufficient. Existing native continuations and pending/unknown actions must remain on a compatible recovery service when native starts are disabled. Never hand them to legacy execution or reset them to manufacture rollback compatibility.
134
-
135
- ## Retry, yield and recovery contract (1.7.2)
136
-
137
- Unreadable answers and rejected candidate values are different events. Native collection records consecutive unrecognized answers in `forms[id].misses[input]`. `max_misses` defaults to 2: the first miss gets one clarification, and the second DISPATCHes that exact current utterance without giving up or erasing the draft. A positive integer override can declare another bounded policy. `max_attempts` continues to bound validator-rejected candidates independently; declared `on_exhausted` workers retain their precedence and branch recovery. Recognition of a field, ambiguity, or provider question resets the current contextual-miss budget. An accepted out-of-order answer never produces a miss apology.
138
-
139
- The shared renderer builds the active question after preparation/refresh, including `question_from`. After a miss it uses the explicit retry for that language, if supplied; otherwise it prefixes the current localized question with “Sorry, I didn't catch that.” / “Disculpe, no le entendí.” Feedback is consumed once, so provider detours and ordinary reentry do not repeat an apology. Validator feedback does not acquire a generic unreadable-answer apology. Exact confirmation and ambiguity clarification use the same two-miss yield policy; declared clarification questions do not consume that budget. None of these paths authorizes an action, and a correction still invalidates consent.
140
-
141
- Business outcome and recovery guidance are independent. Contextual DISPATCH declares `pending`; affected transactions are `yielded`, neither completed nor failed. An actual validation/service failure remains `unresolved`. An owned completed-task fallback remains `resolved`, including abandonment of an optional receipt after an approved payment. Existing declared incomplete-outcome overrides retain their business meaning.
142
-
143
- An optional step attribute `recovery` declares `{version:1,mode,reason,form?,flow?}`. Modes are `resume`, `restart`, `hold` and `none`. `resume` requires the identity of a retained owned form and its definition. The runtime validates that identity before executing the annotated step. A SET or FLOW may annotate a subsequent failure handoff; terminal END/RETURN/DISPATCH can declare it directly. Attribute strings support normal step interpolation. The engine exposes the validated declaration as `session.lastFlowRecovery` for that turn only. A matched DISPATCH target consumes the earlier flow's outcome and recovery; a no-match handoff preserves them for the host. The next turn clears both one-shot records.
144
-
145
- Shared native yields refer to the actual root form and retain accepted values and nested drafts. Structural/provider failures declare no automatic recovery when resumability is not established. An attempted/unknown action in the owned task instead requires `hold`: elapsed time, an unrelated question or a renewed YES cannot authorize another charge. No recovery descriptor executes an action or bypasses authentication, validation or fresh confirmation.
146
-
147
- Hosts compose guidance using `flowHandoffInfo(result)` and `renderFlowRecovery(note)` from `jsfe/host`. A contextual yield answers the current request without claiming the task failed. A resumable failure can offer return to the retained task. Only explicit `restart` can require starting over; `hold` prohibits repeat/restart advice for an uncertain effect, and `none` makes no invented recovery promise. Explicit resolved/deflected outcomes clear an obsolete note. Without recovery metadata the helpers return undefined, preserving the host's historical compatibility path. Internal IDs and machine reasons are not user-facing wording.
148
-
149
- These changes belong to the new shared native workers and declarations. Existing loaded legacy flow/step JSON without these attributes keeps its prior retry and outcome behavior. Regenerate the dev system and tenant native sets from the matched JSFE package; do not deploy a new shared set with an older engine or helper registry. Hosts retain responsibility for serializing turns and persisting the whole returned session; action persistence guarantees are unchanged.
150
-
151
- ## Explicit monetary grammar and compatibility
152
-
153
- `amountInAnswer(text)` and `isAmountAnswer(text)` preserve the published JSFE 1.6 behavior. Installing native FORM support does not make existing production flows accept cardinal words or treat pesos as dollar markers.
154
-
155
- Native inputs can declare enhanced grammar explicitly:
156
-
157
- ```js
158
- { name: 'amount', profile: { kind: 'amount', min: 0.50,
159
- money: { currency: 'USD', cardinals: true, intent: 'payment' } },
160
- validator: 'validate-payment-amount' }
161
- ```
162
-
163
- `readMoneyAmount(text, options)` returns a number or `NaN`; `isMoneyAmount` is true exactly for a finite result, including bare numeric input. Options require `currency: 'USD'`; `cardinals` defaults to false, and `intent` is optional. Currently USD is the only supported currency. Explicit pesos/MXN, euros and other named foreign currencies fail closed; no currency conversion or equivalence is inferred. The optional cardinal grammar supports complete English/Spanish dollar and cents phrases and preserves source spans. Unequal independent amounts, malformed cardinal phrases and signed negative amounts are rejected.
164
-
165
- With `intent: 'payment'`, the shared `moneyIntentAllows` policy recognizes explicit English/Spanish payment-refusal, inability and deferral forms while allowing uncertainty followed by a positive correction (for example, “no entiendo, quiero pagar250”). The vocabulary is deterministic, not an exhaustive linguistic classifier. A recognized declined monetary instruction is not accepted as a numeric correction. Matching may pass an uncommittable `refused: true` candidate with raw text to a declared validator so that it can route to domain recovery. The common validation batch withholds that candidate even when a permissive validator returns success; activation and conversational paths use the same rule. Confirmation remains a separate, later action decision.
166
-
167
- ## Acceptance
168
-
169
- Map every original behavior to native definitions or an explicit consolidation. Runtime import graphs must exclude carried JSON, lifted steps, source-renaming adapters and the old generator. Historical fixtures can remain outside the runtime graph. Counts and valid contracts alone do not establish completion.
170
-
171
- Run independent rule tests, real-engine journeys with JSON session round trips, original behavioral suites, anonymized production response-shape journeys and intent/parameter probes in English and Spanish. Include nested out-of-order input, optional-field recognition, multiple ambiguity groups, corrections, subject changes, provider questions during OTP, duplicate turns, refused APIs, unknown effects and process loss before host save. Preserve intentional interaction differences explicitly rather than weakening effects or consent assertions.
172
-
173
- Generation failures, stale artifacts, empty suite selections, crashed suites and failed expectations must fail acceptance. Record engine/build identity, source revisions, model configuration and exact executed evidence. Production deployment still requires Ron’s explicit authorization.
174
-
175
- ### Host capability admission
176
-
177
- `definePerformer` declares `guardedActions` in its contract requirements. A host must call `assertFlowHostCapabilities(flows, capabilities)` from `jsfe/host` before activation. Durable remains the default: supply `durableActions: true` and attach the journal. An explicit `actionPersistence: 'session-only'` is the alternative; a bare `guardedActions: true` cannot enable it. An additional `contract.requires: ['durableActions']` insists on durable storage even when the host selects session-only. Existing serialized 1.7.0 declarations with that durable-only requirement remain strict; rebuild a flow set with 1.7.1 to use the host-selectable policy. The check does not enable a journal or choose a conversation encoding. Missing requirements reject activation before customer input or effects. Other flow builders may declare additional boolean host requirements through `contract.requires`.
178
-
179
- ## Provider menu terminal intent
180
-
181
- Provider menus keep terminal phrases distinct from neutral menu answers. If an answer selects an action only because courtesy normalization also matches a shorter phrase, an explicitly declared whole-answer `menu.done.words` phrase takes its terminal meaning. For example, a neutral action keyed by “no” can ask what else the caller needs while “no thanks” remains terminal. Fact requests retain their existing priority and the existing done/deferral fallback is preserved. Reuse provider-menu actions and shared phrase renderers instead of adding tenant-specific parsing to the engine.
182
-
183
- ### Identification handoff on an unmapped answer
184
-
185
- The shared contact/account collector uses contextual `DISPATCH` (`onResponse: "continue"`, `responseContext`) before abandoning an unmapped conversational answer. The current input request is offered as a scoped `ContinueCurrent` disposition alongside the primary flows. A classified response retains the live continuation and enters the existing retry/options menu, where a complete identifier can still be supplied. A supported new intent replaces the workflow; an unrelated request without a workflow hands off to the host. This is a decision before state mutation, not a session snapshot restore. Ordinary FORM yields and exhausted retries retain their existing behavior; confirmations and action guards are unchanged.
186
-
187
-
188
- ### Typed contextual responses
189
-
190
- The reviewed contextual-response extension is **unreleased**. Use its matched JSFE runtime, builders and `STANDARD_FUNCTIONS` registry; do not infer support from a package version label. Ordinary `DISPATCH` remains unchanged. Every explicit contextual `DISPATCH` (`onResponse: 'continue'`) passes its resolved `responseContext` to workflow detection and to parameter extraction when that stage runs, including when another primary is selected. The context is an additional assistant turn for this decision; it does not overwrite `lastChatTurn` or restore a session snapshot. Supply a concise description of the current request and the data actually offered.
191
-
192
- A contextual step may additionally declare **both** `responseParameters` and `responseVariable`. `responseParameters` is a nonempty array of canonical flow parameter descriptors (`name`, `description`, optional `type` and string `enum`). Contextual response v1 accepts only `string` (the default), `boolean`, `number`, and `integer` fields; it rejects `object`, `array`, and `jsonSchema`. Ordinary flow parameter support is unchanged. Derive it from the provider's existing parameter catalog instead of maintaining a second semantic vocabulary. `responseVariable` must name an object variable declared in the same flow: a safe identifier, never a cargo path or reserved engine variable.
193
-
194
- When detection chooses `ContinueCurrent`, JSFE extracts those parameters through the existing parameter stage, normalizes their declared types/enums, drops unoffered fields, and binds a cloned object to that variable before the following authored steps run. The live stack, transaction ownership, outcome and recovery declaration remain intact. A named primary replaces the continuation normally; `None` hands off normally. Neither disposition writes the response variable.
195
-
196
- ```js
197
- import { defineWorker } from 'jsfe/forms';
198
-
199
- const replyParameters = [
200
- { name: 'asked', type: 'string', enum: ['stock', 'price', 'search'],
201
- description: 'An existing stock/price fact, or a new search with changed features.' },
202
- { name: 'refinement', type: 'string',
203
- description: 'Changed features for the previously shown products; otherwise absent.' },
204
- ];
205
-
206
- const reply = defineWorker({
207
- id: 'product-reply', name: 'ProductReply',
208
- contract: { role: 'worker', summary: 'Interpret a question about shown products' },
209
- variables: {
210
- answer: { type: 'string', value: '' },
211
- response: { type: 'object', value: null },
212
- },
213
- steps: [
214
- { id: 'ask', type: 'SAY-GET', variable: 'answer', asSpoken: true,
215
- value: 'Ask about these products, or describe the features you want.' },
216
- { id: 'read', type: 'DISPATCH', onResponse: 'continue',
217
- responseContext: 'The current product query is {{cargo.productQuery}}. Questions about its shown results or changed product features continue this task.',
218
- responseParameters: replyParameters, responseVariable: 'response' },
219
- { id: 'result', type: 'SET', variable: 'noop',
220
- value: '(cargo.productReply = response, true)' },
221
- ],
222
- });
223
- ```
224
-
225
- Builders automatically declare the intrinsic requirement `jsfe:contextual-responses:v1` and add a fail-closed entry guard requiring `contextualResponseProtocol() === 1`. This is runtime support, not a host permission or a new configuration switch. Hosts still run capability admission; unsupported intrinsic versions cannot be enabled by supplying a boolean. An older helper registry fails before tenant steps execute.
226
-
227
- Missing or invalid extracted parameters may yield an empty object. The caller must check the required fields and use its normal bounded collection/retry policy; choosing `ContinueCurrent` is not evidence that every requested value exists and never authorizes an effect. A model exception during typed continuation detection or extraction preserves the pending step and prior response object. One decision is reused per turn: incompatible typed context/schema reuse fails closed, as does reaching a typed classification after another workflow has already been activated that turn. Ordinary and untyped dispatch retain their prior routing/cache semantics.
228
-
229
- ### Open-ended answers through contextual DISPATCH
230
-
231
- A readable leaf field can declare `response: { description }`. Describe the information to extract concisely, for example `{name:'issue_details',profile:{kind:'text',narrative:true},response:{description:'The specific issue or desired resolution in the caller words; omit a fragment or a generic complaint announcement.'},question:'What happened?'}`.
232
-
233
- The common collector uses existing `DISPATCH` with `onResponse:'continue'` and an `answer` extraction parameter. Its context includes the actual prepared question and the field description. An extracted answer permits ordinary deterministic validation; the stored candidate retains the caller wording. A different workflow is routed normally. `None` or a continuation without a usable answer yields to the host with the form progress saved. The host can answer with its full conversation context. Detection/extraction errors preserve the pending step and never commit the candidate.
234
-
235
- This uses the existing tenant-configured intent/extraction roles. There is no separate classifier, model assignment, verdict taxonomy or extra request-withdrawal inference. Public activation parameters use the same descriptions, and already extracted activation or deferred candidates are not classified again. Ordinary fields keep their existing deterministic readers. Exact consent and action guards still apply independently.
236
-
237
- Legacy callers use `collect-contextual-answer` with `question`, `question_es`, `description`, optional `choices` and `digits`, and `context` / `context_es`. It returns `cargo.choice` and preserves `cargo.choiceText`. These definitions require the existing `jsfe:contextual-responses:v1` runtime. Retired `meaning` declarations and the removed classifier capability are rejected rather than silently accepted.
238
-
239
- Payment-intent amount reading accepts a bounded whole monetary answer. Uncertain prose yields to DISPATCH rather than inferring refusal, deferral or an earlier payment. Currency, range, identifier and partial-amount checks remain deterministic. Narrative matching preserves strict whole choices and independent structured fields without parsing conversational correction phrases.
240
-
241
- When a declared dependency (including an ancestor subform dependency) has a pending input proposal, dependent candidates wait for that proposal rather than using the previous committed context. Deferred candidates retain the exact proposal identity. Confirming the controller preserves those candidates through dependency invalidation and validates them under the new context; declining or superseding it discards them. Independent fields still collect normally. Declare `depends_on` for contextual prerequisites and `reset_on` for changes that invalidate previously collected data.
242
-
243
- ### Safety revisions for saved continuations
244
-
245
- `withSafetyRevision(flow, token)` opts a definition into the `jsfe:continuation-safety:v1` contract. The token is a nonempty string, independent of the informational flow version. Change it when old serialized steps or retained FORM schemas must no longer execute. The helper adds an executable protocol guard and augments an existing contract's requirements; it does not invent a FORM contract for legacy workers. Hosts register the current `STANDARD_FUNCTIONS`.
246
-
247
- New frames save the token. Sessions also save the definition-token snapshot so yielded FORM tasks with no active frames are checked. Before new input is processed, and after durable checkpoint restoration, a missing or different token retires obsolete stacks and safely closes unexecuted FORM tasks. The engine does not rebase old steps, restart a request, forward the old answer, or repeat effects. It returns a localized explanation and `unresolved / obsolete_continuation`; a subsequent fresh request must collect new confirmation. Unopted definitions retain their previous behavior.
248
-
249
- If retirement encounters any attempted/unknown FORM action, session journal record, or existing payment uncertainty hold, it preserves the effect evidence and quarantines the old task. Its confirmation/proposal approvals and task index are invalidated. The session receives `continuationSafetyHold`; later turns cannot execute flows or consume durable checkpoints. This conservative restriction applies only to obsolete continuations with uncertain effects, and directs the user to configured support outside that conversation. There is no automatic release, timeout or retry. External reconciliation must resolve the effect and retire the quarantined task before deliberately clearing the hold. Cargo, identity data, action ledgers and payment holds are preserved.
250
-
251
- The runtime never treats the informational `version` as a hot-reload instruction. An older runtime without the intrinsic contract must not activate revised definitions: matched capability admission rejects unsupported intrinsic requirements, and the executable protocol guard fails closed in standalone engines.
252
-
253
- Semantic dispositions describe the caller's intent, not permission to perform an action. An explicit replacement request yields with `redirect`; withdrawing the owning request or prohibiting its intended action yields `cancel`. Refusing one field while continuing the same request yields `retry`, unless the declaration permits that answer (such as an unknown date). Factual negative allegations remain eligible data. Candidate instructions are evidence for this classification; they cannot change the evaluator's rules or authorize backend cancellation.
254
-
255
- A field meaning must explicitly identify both the field and its owning service/action in `purpose`, for example collecting a date before filing a caller-requested investigation. A vague instruction to collect information does not identify what a withdrawal applies to. Author this context in the declaration; never derive it from caller keywords or rewrite it at runtime.
256
-
257
- ## Concise authoring pilot: four components
258
-
259
- `Form`, `Provider`, `Performer` and `Worker` from `jsfe/forms` are the preferred concise declarations for the account-info/make-payment pilot. They compile through the existing `define*` builders and validators; they add no runtime protocol. Existing declarations remain supported.
260
-
261
- Declare `id` once; the conventional name is derived unless overridden. Parameters can be an array or a map. A string map entry supplies a string parameter description; an object entry supplies a typed descriptor and optional `default`. JSFE derives its runtime variable and removes the authoring-only default from extraction metadata. Existing advanced variable definitions remain available.
262
-
263
- ```js
264
- const lookup = Provider({
265
- id: 'account-info',
266
- description: 'Answer questions about a verified account',
267
- parameters: { acct_number: 'The caller account number' },
268
- provides: {
269
- default: 'balance',
270
- gate: { flow: 'verify-account', verified: ['cargo.verified'] },
271
- source: { flow: 'load-account', result: 'cargo.account', refresh: 'per_turn' },
272
- facts: [{ key: 'balance', gloss: 'The account balance', path: 'balance' }]
273
- },
274
- gateParameters: { acct_number: '{{acct_number}}' }
275
- });
276
- ```
277
-
278
- The provider compiles its default selection and gate argument plumbing. Gate arguments can use whole template expressions; JSFE lowers them into SET steps so FLOW argument validation remains path-only. The gate and subject freshness checks are still enforced by the shared provider workers. Actual account authentication policy stays in its declaration.
279
-
280
- A primary `Form` or `Performer` can put a public extraction `description` directly on a readable field, including a group member. JSFE derives that parameter before generating collection/reentry steps. Explicit parameters remain useful for aliases or a more restricted extraction enum. A performer can declare `provides` once; its provider question list is generated.
281
-
282
- ```js
283
- const payment = Performer({
284
- id: 'make-payment', primary: true,
285
- description: 'Make a payment',
286
- inputs: [{ name: 'amount', field: 'amount', description: 'The requested amount' }],
287
- performs: [chargeAction],
288
- prepare: 'prepare-payment', present: 'present-payment',
289
- confirm: { question: 'Authorize this exact payment?' },
290
- project: { apply: applyPaymentResult, helpers: { recordPayment } }
291
- });
292
- ```
293
-
294
- An action still declares its real effect, authentication gate, outcomes and idempotency/reconciliation policy. JSFE owns proposal identity, fresh confirmation, guarded execution and receipt application. `project.apply(cargo, {form, formSnapshot, request, result, key})` is a synchronous domain result projection that returns true; it compiles into the same validated SET-only projection used for ordinary and recovered results. It cannot replace the action executor. Helpers must be explicit; captured module closures are not serialized.
295
-
296
- A `Worker` can use ordinary `steps`, one `call: {flow, parameters}`, or one `calculate: {value, args, result, helpers}`. Calculations are plain synchronous functions with explicit argument paths and a safe cargo result path. Use registered tools/flows for external effects. A worker's calculation result metadata and parameter variables are generated. `before` retains ordinary sequencing where needed.
297
-
298
- ### Explain a session without another state store
299
-
300
- ```js
301
- const explanation = explainSession(session, { flows, previous: previousSnapshot });
302
- // {status: 'confirmation', entries: [{kind, message, component, flowId, input, ...}]}
303
- ```
304
-
305
- The inspector reads existing state only. It identifies missing inputs, current proposals, recorded outcomes, holds, handoffs and source component/worker/step references. Comparing two snapshots adds changed field names and invalidated confirmations without outputting collected values. Unknown/attempted evidence takes precedence over contradictory completed records. Component provenance is compiler-generated metadata, not author-maintained bookkeeping.
306
-
307
- This is a snapshot explanation and optional difference, not a persistent event history, model role, authorization decision or new logging stream. An empty stack does not prove that an action succeeded or that no action was attempted. A generic last result without source identity is labelled only as the most recent recorded outcome. Callers can show the messages in a debugger or retain synthetic snapshots in tests.
308
-
309
- For a calculation embedded in an existing SET or CASE, use `compileExpression(fn, ...args)` instead of a tenant `fn.toString()` wrapper. Each argument is **developer-authored JavaScript expression source**, not a caller value; bind caller data through existing variables and paths. Functions must be synchronous and use declared arguments or existing runtime helpers. `Worker.calculate` remains the simpler choice for a whole calculation and retains its path-only argument checks. Collectors may also declare `provides` once; JSFE derives their provider question list just as it does for performers.