@beyondwork/xlsx-substrate-bindings 0.0.0-stage → 0.2.0

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/LICENSE.md +31 -0
  2. package/README.md +135 -2
  3. package/dist/ai/agent-metadata.d.ts +363 -0
  4. package/dist/ai/agent-metadata.js +227 -0
  5. package/dist/ai/index.d.ts +6 -0
  6. package/dist/ai/index.js +7 -0
  7. package/dist/ai/mutation-bridge.d.ts +82 -0
  8. package/dist/ai/mutation-bridge.js +179 -0
  9. package/dist/ai/types.d.ts +765 -0
  10. package/dist/ai/types.js +23 -0
  11. package/dist/index.d.ts +50 -0
  12. package/dist/index.js +90 -0
  13. package/dist/runtime/index.d.ts +2 -0
  14. package/dist/runtime/index.js +1 -0
  15. package/dist/runtime/types.d.ts +1435 -0
  16. package/dist/runtime/types.js +15 -0
  17. package/dist/shared.d.ts +69 -0
  18. package/dist/shared.js +1 -0
  19. package/dist/ui/index.d.ts +2 -0
  20. package/dist/ui/index.js +1 -0
  21. package/dist/ui/types.d.ts +765 -0
  22. package/dist/ui/types.js +12 -0
  23. package/dist/wasm/ai-session-bridge.d.ts +97 -0
  24. package/dist/wasm/ai-session-bridge.js +154 -0
  25. package/dist/wasm/bridge-contract.d.ts +643 -0
  26. package/dist/wasm/bridge-contract.js +1001 -0
  27. package/dist/wasm/index.d.ts +50 -0
  28. package/dist/wasm/index.js +297 -0
  29. package/dist/wasm/memory-budget.d.ts +77 -0
  30. package/dist/wasm/memory-budget.js +532 -0
  31. package/dist/wasm/runtime-guard.d.ts +141 -0
  32. package/dist/wasm/runtime-guard.js +373 -0
  33. package/dist/wasm/session-router.d.ts +98 -0
  34. package/dist/wasm/session-router.js +184 -0
  35. package/dist/wasm/sheet-window-binary-reference.d.ts +9 -0
  36. package/dist/wasm/sheet-window-binary-reference.js +308 -0
  37. package/dist/wasm/sheet-window-binary.d.ts +279 -0
  38. package/dist/wasm/sheet-window-binary.js +636 -0
  39. package/dist/wasm/web.d.ts +72 -0
  40. package/dist/wasm/web.js +142 -0
  41. package/generated/wasm-web/package.json +3 -0
  42. package/generated/wasm-web/snippets/ironcalc_base-89b4f49381e1e289/inline0.js +42 -0
  43. package/generated/wasm-web/xlsx_substrate_wasm.d.ts +532 -0
  44. package/generated/wasm-web/xlsx_substrate_wasm.js +2493 -0
  45. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm +0 -0
  46. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm.d.ts +120 -0
  47. package/package.json +55 -3
@@ -0,0 +1,227 @@
1
+ // XB11 (design record Q9 "Conductor tools in the generated catalogue", Q8
2
+ // "Bindings package surface", §3 "agent-metadata.ts", §8 XB11): the Conductor
3
+ // AI lane's agent metadata — ONE record per wrapped `/ai` verb of the
4
+ // xlsx-conductor service, and the ONE fence record the route guard
5
+ // (`services/xlsx-conductor/lib/ai-service.ts`) and the catalogue generator
6
+ // (`scripts/generate-agent-catalogue.mjs`) both import.
7
+ //
8
+ // This module is PLAIN DATA. It imports nothing from the repository's `src/`
9
+ // (the dist build's `rootDir: "src"` refuses it, TS6059) and nothing at
10
+ // runtime from the rest of the bindings: the type-only imports below name the
11
+ // DTOs the tool inputs are made of. Structural parity with the root
12
+ // `EnsembleToolFence` and `EnsembleToolEntry` is asserted by the root-level
13
+ // `test/agent-contract/conductor-catalogue.test.ts`, never here.
14
+ //
15
+ // The route truth each record states (the bijection test pins it against the
16
+ // route files under `app/api/sessions/[sessionId]/ai/**`):
17
+ // - every wrapped verb is `POST /api/sessions/{sessionId}/ai/<verb>`, agent
18
+ // lane (a registry bearer; XB6);
19
+ // - `effect` says whether the call can change the workbook or the staged
20
+ // subjects an agent owns: the four XB7 reads and the two fenced
21
+ // mutation-free verbs (`preview`, `validate`) are `read`; `propose` (stages
22
+ // a subject and mints its ref), `apply`, `plan`, `undo` and `discard`
23
+ // (releases a staged subject) are `mutate`;
24
+ // - the fence record is on every verb that reads `expectedSessionFence`
25
+ // (Q1), and the record EQUALS the route's enforcement (R-XB11-2 item 2):
26
+ // on every carrying row an agent-origin call without the field is refused
27
+ // `refusalCode` (`input:fence-required`) — the four reads and `propose`,
28
+ // `plan` and `apply` read it at the top level, `preview` and `validate`
29
+ // inside `proposal`. `apply` only grammar-checks the echoed value and
30
+ // dispatches on the STAGED fence (Q7 check 3). `discard` names a
31
+ // `proposalRef` and mutates no workbook state (Q9, Revision 4), and `undo`
32
+ // names its target by `targetRequestId` + `undoBoundaryId` under the
33
+ // persist lock (Q5): neither body carries the fence field, so neither
34
+ // record declares a fence.
35
+ // - `output` names the STAMPED answer the route writes (R-XB11-2 item 3),
36
+ // declared below next to the inputs: the reads' results as the runtime
37
+ // minted them plus the service's stale tag (`staleCause`) and, for
38
+ // `/ai/read`, the `page`; the mutating verbs' `XlsxAiMutationOutcome`,
39
+ // the discard's `XlsxAiDiscardAnswer`. The service's own declarations
40
+ // (`lib/ai-mutation-outcome.ts`, `lib/ai-service.ts`) are pinned equal to
41
+ // these by `test/agent-contract/conductor-output-parity.test.ts` (compile).
42
+ // - `refusalCategories` is derived PER ROUTE from the frozen `ScopeRefusal`
43
+ // roster (`crates/sheets-scope/tests/fixtures/ai-refusal-roster.json`):
44
+ // the service's `lib/ai-route-refusals.ts` names the roster codes each
45
+ // verb produces and maps them to their categories; each record PINS that
46
+ // derivation (R-XB11-2 item 4). `declared_refusal_categories_derive_from_
47
+ // roster` re-derives from the service and the fixture and fails on a
48
+ // record that differs; this module cannot read either (published data).
49
+ // ---------------------------------------------------------------------------
50
+ // The fence record (Q9): one constant, imported by the route guard and the generator
51
+ // ---------------------------------------------------------------------------
52
+ /**
53
+ * The optimistic-concurrency fence of the Conductor AI lane, as the catalogue
54
+ * publishes it (structurally the root `EnsembleToolFence`):
55
+ * - `field` is the input member carrying the caller's assertion about the
56
+ * session state it reasoned against;
57
+ * - `echoFrom` is the result member it is echoed from (every stamped answer's
58
+ * `sessionFence`);
59
+ * - omitting it on an `agent`-origin call is the refusal `refusalCode`
60
+ * (§6 `input:fence-required`), never a warning;
61
+ * - `warningCode` is `input:fence-missing`, a RESERVED roster row of category
62
+ * `warning`: never emitted today, because no origin reaches a fenced
63
+ * Conductor verb without the fence being required. `EnsembleToolFence`
64
+ * requires the member, so the reserved code keeps the record total.
65
+ */
66
+ export const CONDUCTOR_AI_FENCE = {
67
+ field: "expectedSessionFence",
68
+ echoFrom: "sessionFence",
69
+ requiredForOrigins: ["agent"],
70
+ refusalCode: "input:fence-required",
71
+ warningCode: "input:fence-missing",
72
+ };
73
+ // ---------------------------------------------------------------------------
74
+ // The records
75
+ // ---------------------------------------------------------------------------
76
+ /**
77
+ * The per-route category sets, as `lib/ai-route-refusals.ts` derives them
78
+ * (R-XB11-2 item 4): every verb answers `input` (the body and fence gates),
79
+ * `blocked` (the service, transport, memo and governance rows) and
80
+ * `unresolved-target` (`input:unknown-session`); every verb that dispatches
81
+ * to the Rust AI layer adds `unsupported` (capability and scope rows) and
82
+ * `ambiguous-target` (`policy:lookup-reference-ambiguous`); `warning` rides
83
+ * only the verbs with a warning row — preview's and propose's
84
+ * `preview:simulated-unavailable` (the simulated arm's size gate, on
85
+ * `/ai/propose {proposal, fidelity: "simulated"}` too; XBC-2), apply's and
86
+ * plan's `apply:drain-*`, undo's `undo:history-inconsistent`. `discard`
87
+ * reaches no runtime.
88
+ */
89
+ const DISPATCHING = ["ambiguous-target", "blocked", "input", "unresolved-target", "unsupported"];
90
+ const DISPATCHING_WITH_WARNING = [...DISPATCHING, "warning"];
91
+ const DISCARD_CATEGORIES = ["blocked", "input", "unresolved-target"];
92
+ const UNDO_CATEGORIES = ["blocked", "input", "unresolved-target", "warning"];
93
+ function record(entry) {
94
+ return { ...entry, readOrMutate: entry.effect, scope: "workbook" };
95
+ }
96
+ /**
97
+ * One record per wrapped `/ai` verb, in the service's route order (the four
98
+ * XB7 reads, then XB8's five, then XB9's two). The bijection test pins this
99
+ * list against the route files; a verb added without a record, or a record
100
+ * without a verb, fails there.
101
+ */
102
+ export const XLSX_AI_AGENT_TOOLS = [
103
+ record({
104
+ name: "xlsx.ai.bundle",
105
+ refusalCategories: DISPATCHING,
106
+ wireName: "xlsx_ai_bundle",
107
+ http: { method: "POST", path: "/ai/bundle" },
108
+ input: { type: "XlsxAiScopeBundleReadRequest", schema: "Input" },
109
+ output: "XlsxAiBundleToolResult",
110
+ effect: "read",
111
+ summary: "Read one scope handle's bundle (classifications, capability verdict, readback) on a fenced session; mutates nothing.",
112
+ fence: CONDUCTOR_AI_FENCE,
113
+ }),
114
+ record({
115
+ name: "xlsx.ai.resolve",
116
+ refusalCategories: DISPATCHING,
117
+ wireName: "xlsx_ai_resolve",
118
+ http: { method: "POST", path: "/ai/resolve" },
119
+ input: { type: "XlsxAiSessionReferenceRequest", schema: "Input" },
120
+ output: "XlsxAiResolveToolResult",
121
+ effect: "read",
122
+ summary: "Resolve a deterministic workbook reference (a scope id, A1 or sheet-qualified A1, a defined name or a table name) to scope handles on a fenced session; natural-language queries are refused typed; mutates nothing.",
123
+ fence: CONDUCTOR_AI_FENCE,
124
+ }),
125
+ record({
126
+ name: "xlsx.ai.read",
127
+ refusalCategories: DISPATCHING,
128
+ wireName: "xlsx_ai_read",
129
+ http: { method: "POST", path: "/ai/read" },
130
+ input: { type: "XlsxAiScopeReadToolInput", schema: "Input" },
131
+ output: "XlsxAiScopeReadToolResult",
132
+ effect: "read",
133
+ summary: "Read one handle's cells, paged (at most 2000 per page, the cursor fenced to the state it was minted on); mutates nothing.",
134
+ fence: CONDUCTOR_AI_FENCE,
135
+ }),
136
+ record({
137
+ name: "xlsx.ai.neighborhood",
138
+ refusalCategories: DISPATCHING,
139
+ wireName: "xlsx_ai_neighborhood",
140
+ http: { method: "POST", path: "/ai/neighborhood" },
141
+ input: { type: "XlsxAiScopeNeighborhoodRequest", schema: "Input" },
142
+ output: "XlsxAiNeighborhoodToolResult",
143
+ effect: "read",
144
+ summary: "Read one handle's formula precedents and dependents to depth 2 on a fenced session; mutates nothing.",
145
+ fence: CONDUCTOR_AI_FENCE,
146
+ }),
147
+ record({
148
+ name: "xlsx.ai.preview",
149
+ refusalCategories: DISPATCHING_WITH_WARNING,
150
+ wireName: "xlsx_ai_preview",
151
+ http: { method: "POST", path: "/ai/preview" },
152
+ input: { type: "XlsxAiPreviewToolInput", schema: "Input" },
153
+ output: "XlsxAiPreviewToolResult",
154
+ effect: "read",
155
+ summary: "Preview one replacement proposal (guards, or the simulated arm on a clone) with before/proposed readbacks and impact; writes nothing.",
156
+ fence: CONDUCTOR_AI_FENCE,
157
+ }),
158
+ record({
159
+ name: "xlsx.ai.validate",
160
+ refusalCategories: DISPATCHING,
161
+ wireName: "xlsx_ai_validate",
162
+ http: { method: "POST", path: "/ai/validate" },
163
+ input: { type: "XlsxAiValidateToolInput", schema: "Input" },
164
+ output: "XlsxAiValidateToolResult",
165
+ effect: "read",
166
+ summary: "Validate one replacement proposal with ai_check only (warnings and the refusal, no readbacks); writes nothing.",
167
+ fence: CONDUCTOR_AI_FENCE,
168
+ }),
169
+ record({
170
+ name: "xlsx.ai.propose",
171
+ refusalCategories: DISPATCHING_WITH_WARNING,
172
+ wireName: "xlsx_ai_propose",
173
+ http: { method: "POST", path: "/ai/propose" },
174
+ input: { type: "XlsxAiProposeToolInput", schema: "Input" },
175
+ output: "XlsxAiMutationOutcome",
176
+ effect: "mutate",
177
+ auditCategory: "ai.request",
178
+ summary: "Stage exactly one subject (a proposal, a plan or an undo) under a requestId and mint its proposalRef; the workbook is unchanged until apply or undo.",
179
+ fence: CONDUCTOR_AI_FENCE,
180
+ }),
181
+ record({
182
+ name: "xlsx.ai.apply",
183
+ refusalCategories: DISPATCHING_WITH_WARNING,
184
+ wireName: "xlsx_ai_apply",
185
+ http: { method: "POST", path: "/ai/apply" },
186
+ input: { type: "XlsxAiApplyToolInput", schema: "ApplyInput" },
187
+ output: "XlsxAiMutationOutcome",
188
+ effect: "mutate",
189
+ auditCategory: "ai.request",
190
+ summary: "Execute a staged proposal or plan subject by its proposalRef (owner-only, single use; a decision in governed mode) on the staged fence, then persist.",
191
+ fence: CONDUCTOR_AI_FENCE,
192
+ }),
193
+ record({
194
+ name: "xlsx.ai.discard",
195
+ refusalCategories: DISCARD_CATEGORIES,
196
+ wireName: "xlsx_ai_discard",
197
+ http: { method: "POST", path: "/ai/discard" },
198
+ input: { type: "XlsxAiDiscardToolInput", schema: "Input" },
199
+ output: "XlsxAiDiscardToolResult",
200
+ effect: "mutate",
201
+ auditCategory: "ai.discard",
202
+ summary: "Release one staged subject the caller owns (its quota, bytes and propose memo entry) and mark its live decision refused/withdrawn; the workbook is unchanged.",
203
+ }),
204
+ record({
205
+ name: "xlsx.ai.plan",
206
+ refusalCategories: DISPATCHING_WITH_WARNING,
207
+ wireName: "xlsx_ai_plan",
208
+ http: { method: "POST", path: "/ai/plan" },
209
+ input: { type: "XlsxAiPlanToolInput", schema: "ApplyInput" },
210
+ output: "XlsxAiMutationOutcome",
211
+ effect: "mutate",
212
+ auditCategory: "ai.request",
213
+ summary: "Preview (the default) or apply one all-or-nothing plan of at most 50 disjoint replacement steps inline; governed deployments refuse the inline apply and stage the plan instead.",
214
+ fence: CONDUCTOR_AI_FENCE,
215
+ }),
216
+ record({
217
+ name: "xlsx.ai.undo",
218
+ refusalCategories: UNDO_CATEGORIES,
219
+ wireName: "xlsx_ai_undo",
220
+ http: { method: "POST", path: "/ai/undo" },
221
+ input: { type: "XlsxAiUndoToolInput", schema: "Input" },
222
+ output: "XlsxAiMutationOutcome",
223
+ effect: "mutate",
224
+ auditCategory: "ai.request",
225
+ summary: "Reverse the newest settled apply or plan named by targetRequestId and undoBoundaryId (its own requestId; a staged undo subject and decision in governed mode).",
226
+ }),
227
+ ];
@@ -0,0 +1,6 @@
1
+ export type { XlsxAiBlocker, XlsxAiBlockerCode, XlsxAiCompressedAnchor, XlsxAiCompressedAxisBand, XlsxAiCompressedContextRequest, XlsxAiCompressedContextResult, XlsxAiCompressedDrilldownRequest, XlsxAiCompressedDrilldownResult, XlsxAiCompressedFormatPostureCounts, XlsxAiCompressedInverseIndex, XlsxAiCompressedRegion, XlsxAiCompressedSheetContext, XlsxAiCompressedValueCounts, XlsxAiCompressedWorkbookContext, XlsxAiCompressedWorkbookTotals, XlsxAiFormulaDiagnostic, XlsxAiFormulaExplanation, XlsxAiFormulaExplanationResult, XlsxAiFormulaPrecedent, XlsxAiKernelActionKind, XlsxAiKernelActionProposal, XlsxAiKernelActionValidation, XlsxAiReferenceMatch, XlsxAiReferenceQuery, XlsxAiReferenceReadback, XlsxAiReferenceResolution, XlsxAiReplacementApplyResult, XlsxAiReplacementProposal, XlsxAiReplacementValidation, XlsxAiScopeBundleResult, XlsxAiScopeListRequest, XlsxAiScopeListResult, XlsxAiUnsupportedAction, XlsxAiUnsupportedActionResult, XlsxAiWorkbookInspection, XlsxKernelScopeEvidence, XlsxRangeWriteCell, XlsxScopeBundle, XlsxScopePageCursor, XlsxAiApplyPlanRequest, XlsxAiApplyProposalRequest, XlsxAiApplyReceipt, XlsxAiCellReadback, XlsxAiCellValue, XlsxAiDrain, XlsxAiFenceTriple, XlsxAiImpact, XlsxAiNeighborhoodNode, XlsxAiPlan, XlsxAiPlanReceipt, XlsxAiPlanStepReceipt, XlsxAiPreviewRequest, XlsxAiPreviewResult, XlsxAiRangeWriteCell, XlsxAiRefusal, XlsxAiReplacementOperation, XlsxAiScopeBundleReadRequest, XlsxAiCalcGraphDescriptor, XlsxAiCalcGraphEdge, XlsxAiCalcGraphEdgesRequest, XlsxAiCalcGraphEdgesResult, XlsxAiScopeNeighborhoodRequest, XlsxAiScopeNeighborhoodResult, XlsxAiScopeReadResult, XlsxAiSessionProposal, XlsxAiSessionReferenceRequest, XlsxAiSessionReferenceResult, XlsxAiSessionScopeBundle, XlsxAiSessionScopeBundleResult, XlsxAiSessionStamp, XlsxAiSettledFence, XlsxAiAfterState, XlsxAiSimulatedGate, XlsxAiSimulatedPreview, XlsxAiUnknownOpRefusal, XlsxAiValidateRequest, XlsxAiValidateResult, XlsxSessionFence } from "./types.ts";
2
+ export { aiKernelActionRequiresHost, aiUnsupportedAction } from "./types.ts";
3
+ export { createXlsxAiMutationBridge, XLSX_AI_MUTATION_RANGE_FILL_BLOCKER, XLSX_AI_MUTATION_WORKBOOK_MISMATCH_BLOCKER } from "./mutation-bridge.ts";
4
+ export type { XlsxAiMutationApplyResult, XlsxAiMutationBridge, XlsxAiMutationBridgeOptions, XlsxAiMutationBridgeSession, XlsxAiMutationProposal, XlsxAiMutationProposeInput, XlsxAiMutationProposeResult, XlsxAiMutationReadback } from "./mutation-bridge.ts";
5
+ export { CONDUCTOR_AI_FENCE, XLSX_AI_AGENT_TOOLS } from "./agent-metadata.ts";
6
+ export type { XlsxAiAgentRefusalCategory, XlsxAiAgentToolEffect, XlsxAiAgentToolFence, XlsxAiAgentToolHttp, XlsxAiAgentToolInput, XlsxAiAgentToolRecord, XlsxAiApplyToolInput, XlsxAiAttestation, XlsxAiBundleToolResult, XlsxAiDiscardAnswer, XlsxAiDiscardToolInput, XlsxAiDiscardToolResult, XlsxAiImpactMeasured, XlsxAiImpactStatus, XlsxAiImpactUnmeasured, XlsxAiInvalidationCause, XlsxAiMutationOutcome, XlsxAiNeighborhoodToolResult, XlsxAiOutcomeInvalidation, XlsxAiOutcomeWarning, XlsxAiPlanToolBody, XlsxAiPlanToolInput, XlsxAiPlanToolStep, XlsxAiPreviewToolInput, XlsxAiPreviewToolResult, XlsxAiPreviewToolValidation, XlsxAiProposePlanToolInput, XlsxAiProposeProposalToolInput, XlsxAiProposeToolInput, XlsxAiProposeUndoToolInput, XlsxAiResolveToolResult, XlsxAiScopeReadPage, XlsxAiScopeReadToolInput, XlsxAiScopeReadToolResult, XlsxAiStaleCause, XlsxAiStaleTaggedRefusal, XlsxAiUndoAttestation, XlsxAiUndoSubjectToolInput, XlsxAiUndoToolInput, XlsxAiValidateToolInput, XlsxAiValidateToolResult } from "./agent-metadata.ts";
@@ -0,0 +1,7 @@
1
+ export { aiKernelActionRequiresHost, aiUnsupportedAction } from "./types.js";
2
+ // XB10 (Q8 "Bindings package surface"): the package's synchronous Cadence seam.
3
+ export { createXlsxAiMutationBridge, XLSX_AI_MUTATION_RANGE_FILL_BLOCKER, XLSX_AI_MUTATION_WORKBOOK_MISMATCH_BLOCKER } from "./mutation-bridge.js";
4
+ // XB11 (Q9 "Catalogue", Q8 "Bindings package surface"): the Conductor agent
5
+ // metadata — one record per wrapped `/ai` verb and the ONE fence record the
6
+ // route guard and the catalogue generator import. Plain data.
7
+ export { CONDUCTOR_AI_FENCE, XLSX_AI_AGENT_TOOLS } from "./agent-metadata.js";
@@ -0,0 +1,82 @@
1
+ import type { XlsxCellRange, XlsxRuntimeActor, XlsxScopeHandle } from "../shared.ts";
2
+ import type { XlsxAiSessionBridgeMethods } from "../wasm/ai-session-bridge.ts";
3
+ import type { XlsxSessionFence } from "./types.ts";
4
+ /** Structural twin of Cadence's `ConductorMutationReadback`. */
5
+ export interface XlsxAiMutationReadback {
6
+ readonly workbookId: string;
7
+ readonly scopeId: string;
8
+ /** The session fence token at the read, never a counter. */
9
+ readonly revision: string;
10
+ readonly value: string;
11
+ readonly formulaText?: string;
12
+ }
13
+ /** Structural twin of the input `ConductorMutationBridge.propose` receives. */
14
+ export interface XlsxAiMutationProposeInput {
15
+ readonly handle: XlsxScopeHandle;
16
+ /** The fence token a prior `read()` returned as `revision`. */
17
+ readonly expectedRevision: string;
18
+ readonly expectedWorkbookId: string;
19
+ readonly proposedValue: string;
20
+ }
21
+ export interface XlsxAiMutationProposeResult {
22
+ readonly accepted: boolean;
23
+ readonly proposalId: string;
24
+ readonly blockers: readonly string[];
25
+ }
26
+ /** Structural twin of Cadence's `ConductorMutationProposal`. */
27
+ export interface XlsxAiMutationProposal extends XlsxAiMutationProposeInput {
28
+ readonly proposalId: string;
29
+ /** Passthrough for parity: a range proposal is still refused `unsupported:range-fill`. */
30
+ readonly range?: XlsxCellRange;
31
+ }
32
+ export interface XlsxAiMutationApplyResult {
33
+ readonly applied: boolean;
34
+ /** The restamped undo-boundary id; empty when nothing applied. */
35
+ readonly receiptId: string;
36
+ /** The post-drain settled fence when applied; the live stamp otherwise. */
37
+ readonly revision: string;
38
+ }
39
+ /** The seam: structurally `ConductorMutationBridge` (`src/cadence/conductor/mutation.ts`). */
40
+ export interface XlsxAiMutationBridge {
41
+ readonly read: (handle: XlsxScopeHandle) => XlsxAiMutationReadback | null;
42
+ readonly propose: (input: XlsxAiMutationProposeInput) => XlsxAiMutationProposeResult;
43
+ readonly apply: (proposal: XlsxAiMutationProposal) => XlsxAiMutationApplyResult;
44
+ }
45
+ /**
46
+ * What the seam needs of the mounted bridge: three of the eight typed AI
47
+ * methods, nothing else. A full `XlsxWasmBridge` satisfies it.
48
+ */
49
+ export type XlsxAiMutationBridgeSession = Pick<XlsxAiSessionBridgeMethods, "readRuntimeSessionScope" | "validateRuntimeSessionAiProposal" | "applyRuntimeSessionAiProposal">;
50
+ interface XlsxAiMutationBridgeBaseOptions {
51
+ /** The request actor every validate and apply carries (D6: audit actor = request actor). */
52
+ readonly actor: XlsxRuntimeActor;
53
+ /** Echoed as `workbookId` on every readback; a proposal naming another workbook is refused. */
54
+ readonly workbookId: string;
55
+ }
56
+ /**
57
+ * The fence source is REQUIRED (one of the two forms): the seam never builds
58
+ * a token. `sessionFence` is a token the host already holds (the stamp of a
59
+ * fenced bundle or read it made on this session); `fenceSource` is asked once,
60
+ * when the seam holds no token. Afterwards every stamped wasm answer (reads,
61
+ * validate, apply, refused ones included) refreshes the seam's cached token.
62
+ * Construction without either throws a `TypeError`.
63
+ */
64
+ export type XlsxAiMutationBridgeOptions = XlsxAiMutationBridgeBaseOptions & ({
65
+ readonly sessionFence: XlsxSessionFence;
66
+ readonly fenceSource?: undefined;
67
+ } | {
68
+ readonly sessionFence?: undefined;
69
+ readonly fenceSource: () => XlsxSessionFence;
70
+ });
71
+ /** The local blocker for a range fill: the shipped DTO has no fill form. */
72
+ export declare const XLSX_AI_MUTATION_RANGE_FILL_BLOCKER = "unsupported:range-fill";
73
+ /** The local blocker for a proposal naming a workbook other than the seam's. */
74
+ export declare const XLSX_AI_MUTATION_WORKBOOK_MISMATCH_BLOCKER = "input:workbook-mismatch";
75
+ /**
76
+ * Build the synchronous Cadence seam over one mounted session handle. One
77
+ * wasm call per seam method, except the single re-read when a read's fence
78
+ * turns out stale (a human edit between two seam calls). Throws `TypeError`
79
+ * when the options carry no fence source.
80
+ */
81
+ export declare function createXlsxAiMutationBridge(bridge: XlsxAiMutationBridgeSession, handleId: string, options: XlsxAiMutationBridgeOptions): XlsxAiMutationBridge;
82
+ export {};
@@ -0,0 +1,179 @@
1
+ // XB10 (design record D11 "The Cadence synchronous seam", §8 XB10, Q8
2
+ // "Bindings package surface"): the package's synchronous seam for a host
3
+ // that drives Cadence's `ConductorMutationTransaction`
4
+ // (`src/cadence/conductor/mutation.ts`) over one mounted WASM session.
5
+ //
6
+ // The seam is a `{read, propose, apply}` triple with the member signatures
7
+ // of `ConductorMutationBridge`, declared HERE as `XlsxAiMutationBridge`: the
8
+ // bindings never import the repository's `src/` (the dist build's
9
+ // `rootDir: "src"` refuses it), so the parity is structural and asserted by
10
+ // the root-level test `test/cadence/conductor/wasm-ai-mutation-bridge.test.ts`
11
+ // with `satisfies` and annotated assignments both ways, compiled under tsgo.
12
+ //
13
+ // The D11 mapping:
14
+ // - `revision` IS the session fence token (`XlsxSessionFence`): `read()`
15
+ // returns the read's stamp, `apply()` returns the POST-DRAIN
16
+ // `settled.sessionFence`, so `read().revision === apply().revision`, which
17
+ // `ConductorMutationTransaction.apply` requires (`mutation.ts:116-121`).
18
+ // - `receiptId` is the restamped undo-boundary id (`undoBoundary.id`).
19
+ // - `propose()` is `validateRuntimeSessionAiProposal`: it never advances the
20
+ // identity, as the transaction's re-read requires (`mutation.ts:87-90`).
21
+ // - The fence travels as `expectedSessionFence = expectedRevision`. The seam
22
+ // NEVER composes a fence token (Q1 §5 "TypeScript never composes a token";
23
+ // the legacy translation Q1 6(c) is withdrawn): the host supplies the fence
24
+ // source in the options (`sessionFence`, a token it already holds from a
25
+ // fenced bundle or read, or `fenceSource`, asked once when the seam holds
26
+ // none), and from then on every stamped answer the wasm gives refreshes
27
+ // the seam's cached token. The one re-read at a stale refusal's LIVE stamp
28
+ // (a token Rust minted) covers an out-of-band edit between two seam calls.
29
+ // - `expectedWorkbookId` must name this seam's workbook: a proposal for
30
+ // another workbook is refused `input:workbook-mismatch` with no dispatch.
31
+ // - AI dispatch only through the typed bindings methods; every wasm
32
+ // REFUSAL becomes a non-accepted / non-applied answer with its code in
33
+ // `blockers`. Nothing is caught: a thrown `XlsxAiUnknownOpRefusalError`
34
+ // (a stale bundle) or a wasm throw propagates to the host, as the
35
+ // transaction's own contract expects of an uncertain dispatch.
36
+ // - Operation: `cell-set-value` for a `cell` handle. The shipped
37
+ // `range-write` form carries explicit `cells`, not a fill, so a `range`
38
+ // handle with one `proposedValue` is refused locally with the blocker
39
+ // `unsupported:range-fill` (no wasm op is invented). `range` travels on the
40
+ // proposal twin as a passthrough, for parity with Cadence's proposal.
41
+ /** The local blocker for a range fill: the shipped DTO has no fill form. */
42
+ export const XLSX_AI_MUTATION_RANGE_FILL_BLOCKER = "unsupported:range-fill";
43
+ /** The local blocker for a proposal naming a workbook other than the seam's. */
44
+ export const XLSX_AI_MUTATION_WORKBOOK_MISMATCH_BLOCKER = "input:workbook-mismatch";
45
+ const STALE_TARGET = "runtime:stale-target";
46
+ const NO_FENCE_SOURCE = "createXlsxAiMutationBridge: options.sessionFence or options.fenceSource is required; the seam echoes a session fence the host obtained from a fenced bundle or read and never composes one";
47
+ /**
48
+ * A canonical decimal literal (no sign on zero, no leading or trailing
49
+ * zeros) is written as a number so it reads back as the same text; every
50
+ * other string is written as text. The transaction's readback equality is
51
+ * the truth gate for anything the engine would re-render.
52
+ */
53
+ const CANONICAL_DECIMAL = /^(0|-?[1-9]\d*)(\.\d*[1-9])?$/;
54
+ function cellValue(text) {
55
+ return CANONICAL_DECIMAL.test(text) ? { kind: "number", value: text } : { kind: "text", value: text };
56
+ }
57
+ function sessionProposal(handle, proposedValue, expectedRevision) {
58
+ return {
59
+ handle,
60
+ operation: "cell-set-value",
61
+ value: cellValue(proposedValue),
62
+ // The revision IS the fence (D11); a malformed one is the wasm's
63
+ // `input:fence-format` refusal, surfaced in `blockers`, never thrown.
64
+ expectedSessionFence: expectedRevision
65
+ };
66
+ }
67
+ /**
68
+ * A deterministic proposal id over (scopeId, expectedRevision, proposedValue):
69
+ * FNV-1a 32 over the triple, prefixed with the scope id for legibility. An
70
+ * echo token for the transaction, not a secret and not a receipt.
71
+ */
72
+ function proposalId(input) {
73
+ const text = `${input.handle.scopeId}\u0000${input.expectedRevision}\u0000${input.proposedValue}`;
74
+ let hash = 0x811c9dc5;
75
+ for (let index = 0; index < text.length; index++) {
76
+ hash ^= text.charCodeAt(index);
77
+ hash = Math.imul(hash, 0x01000193) >>> 0;
78
+ }
79
+ return `xlsx-ai-proposal:${input.handle.scopeId}:${hash.toString(16).padStart(8, "0")}`;
80
+ }
81
+ /**
82
+ * One cell's footprint is its scalar `value` (blank reads as "") and its
83
+ * formula text. A multi-cell footprint has no writable scalar: its `value`
84
+ * is a drift digest over the cells (the transaction compares it across
85
+ * reads), and `propose()` refuses the fill.
86
+ */
87
+ function scalar(cells) {
88
+ if (cells.length === 1) {
89
+ const [cell] = cells;
90
+ return { value: cell.value ?? "", ...(cell.formulaText !== undefined ? { formulaText: cell.formulaText } : {}) };
91
+ }
92
+ return { value: JSON.stringify(cells.map((cell) => [cell.value ?? null, cell.formulaText ?? null])) };
93
+ }
94
+ function isApplied(receipt) {
95
+ return receipt.verdict === "applied" || receipt.verdict === "applied-with-warnings";
96
+ }
97
+ /**
98
+ * Build the synchronous Cadence seam over one mounted session handle. One
99
+ * wasm call per seam method, except the single re-read when a read's fence
100
+ * turns out stale (a human edit between two seam calls). Throws `TypeError`
101
+ * when the options carry no fence source.
102
+ */
103
+ export function createXlsxAiMutationBridge(bridge, handleId, options) {
104
+ let fence = typeof options.sessionFence === "string" ? options.sessionFence : undefined;
105
+ const source = typeof options.fenceSource === "function" ? options.fenceSource : undefined;
106
+ if (fence === undefined && source === undefined)
107
+ throw new TypeError(NO_FENCE_SOURCE);
108
+ const currentFence = () => {
109
+ if (fence !== undefined)
110
+ return fence;
111
+ // Construction refused an options object with neither; this guard only
112
+ // narrows the type.
113
+ if (source === undefined)
114
+ throw new TypeError(NO_FENCE_SOURCE);
115
+ fence = source();
116
+ return fence;
117
+ };
118
+ // Every stamped answer names the live fence; the refusal of a stale fence
119
+ // does too, which is how the seam learns of an out-of-band edit.
120
+ const adopt = (stamp) => {
121
+ if (stamp.sessionFence !== undefined)
122
+ fence = stamp.sessionFence;
123
+ };
124
+ const namesThisWorkbook = (expectedWorkbookId) => expectedWorkbookId === options.workbookId;
125
+ const read = (handle) => {
126
+ const first = currentFence();
127
+ let result = bridge.readRuntimeSessionScope(handleId, { handle, expectedSessionFence: first });
128
+ if (result.verdict === "refused" && result.refusal?.code === STALE_TARGET && result.sessionFence !== first) {
129
+ result = bridge.readRuntimeSessionScope(handleId, { handle, expectedSessionFence: result.sessionFence });
130
+ }
131
+ adopt(result);
132
+ if (result.verdict !== "available")
133
+ return null;
134
+ return {
135
+ workbookId: options.workbookId,
136
+ scopeId: result.handle?.scopeId ?? handle.scopeId,
137
+ revision: result.sessionFence,
138
+ ...scalar(result.cells)
139
+ };
140
+ };
141
+ const propose = (input) => {
142
+ if (!namesThisWorkbook(input.expectedWorkbookId))
143
+ return { accepted: false, proposalId: "", blockers: [XLSX_AI_MUTATION_WORKBOOK_MISMATCH_BLOCKER] };
144
+ if (input.handle.kind !== "cell")
145
+ return { accepted: false, proposalId: "", blockers: [XLSX_AI_MUTATION_RANGE_FILL_BLOCKER] };
146
+ const validated = bridge.validateRuntimeSessionAiProposal(handleId, {
147
+ proposal: sessionProposal(input.handle, input.proposedValue, input.expectedRevision),
148
+ actor: options.actor
149
+ });
150
+ adopt(validated);
151
+ if (validated.verdict !== "validated")
152
+ return { accepted: false, proposalId: "", blockers: [validated.refusal?.code ?? "refused"] };
153
+ return { accepted: true, proposalId: proposalId(input), blockers: [] };
154
+ };
155
+ const apply = (proposal) => {
156
+ if (!namesThisWorkbook(proposal.expectedWorkbookId) || proposal.handle.kind !== "cell") {
157
+ return { applied: false, receiptId: "", revision: currentFence() };
158
+ }
159
+ const receipt = bridge.applyRuntimeSessionAiProposal(handleId, {
160
+ proposal: sessionProposal(proposal.handle, proposal.proposedValue, proposal.expectedRevision),
161
+ actor: options.actor
162
+ });
163
+ adopt(receipt);
164
+ const { settled, undoBoundary, audit } = receipt;
165
+ if (!isApplied(receipt) ||
166
+ settled === undefined ||
167
+ undoBoundary === undefined ||
168
+ audit === undefined ||
169
+ audit.beforeCanonicalHash === audit.afterCanonicalHash) {
170
+ // Refused (stale fence, blocked, malformed), applied without the
171
+ // attestation that the identity moved, or applied without a settled
172
+ // fence (drain failed, session disposed): nothing the transaction may
173
+ // treat as applied. The live stamp is the revision.
174
+ return { applied: false, receiptId: "", revision: receipt.sessionFence ?? currentFence() };
175
+ }
176
+ return { applied: true, receiptId: undoBoundary.id, revision: settled.sessionFence };
177
+ };
178
+ return { read, propose, apply };
179
+ }