@loomwork/replay-vm 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Loom
2
+ Copyright 2026 Sushil Chhetri
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this project except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @loomwork/replay-vm — the fold from events to state
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Loom keeps an execution as an append-only list of events and derives its state by folding them. This
4
+ package is that fold, and nothing else: `foldEvents(events, initial?)` is a synchronous, in-memory reduce
5
+ that applies one handler per known event type and returns an `ExecutionState`. It does no I/O, runs no flow
6
+ code and calls no effects. "Replay" happens elsewhere: `@loomwork/workflow-runtime` re-runs your flow function
7
+ against the folded state and, through `ReplayVM`, answers `hasCompleted(stepId)` and `getOutput(stepId)`
8
+ from the record so a completed step is served rather than executed again. You import this directly to
9
+ reconstruct state from a log you already hold (tools, analytics, tests) or to read the event-schema version.
10
+ The runtime rebuilds state through this fold on resume, so a change to it changes how an existing log is read.
11
+
12
+ ```ts
13
+ import { EVENT_SCHEMA_VERSION, ReplayVM, foldEvents, knownEventTypes } from "@loomwork/replay-vm";
14
+ import { app, helloFlow } from "./config"; // your defineConfig result and a registered flow
15
+
16
+ const handle = await app.runtime.start(helloFlow, { name: "Ada" });
17
+ await handle.waitForCompletion();
18
+
19
+ // The log is the source of truth; the state is a fold of it.
20
+ const events = await app.stores.eventStore.read(handle.executionId);
21
+ const state = foldEvents(events); // pure and synchronous: no I/O, no flow code, no effects
22
+ console.log(state.status, state.sequence, state.variables._output); // "completed" 3 { message: "Hello, Ada!" }
23
+
24
+ // Or fold incrementally, and ask about individual steps.
25
+ const vm = new ReplayVM(events.slice(0, -1));
26
+ vm.applyEvent(events[events.length - 1]!);
27
+ console.log(vm.hasCompleted("greet"), vm.getOutput("greet"), vm.getState().status);
28
+
29
+ console.log(EVENT_SCHEMA_VERSION, knownEventTypes().length);
30
+ ```
31
+
32
+ ## Surface
33
+
34
+ - **`foldEvents(events, initial?)`.** Starts from a default `pending` state, or from `initial` such as a
35
+ snapshot's state, applies events in order, and sets `sequence` to the last event's.
36
+ `normalizeSnapshotState(state)` reads an older snapshot as the current fold would have written it.
37
+ - **`ReplayVM`.** `new ReplayVM(events, initial?)`, `applyEvent`, `getState()`, `peekState()`,
38
+ `hasCompleted`, `hasFailed`, `getOutput`, `getTypedFailure`, `hasDecision`, `getDecision`,
39
+ `flowEmitCount`, `recordedFrames`, `expectedReplayFrames`.
40
+ - **Event-schema ABI.** `EVENT_SCHEMA_VERSION` (currently 1.26.0) and `knownEventTypes()`, the sorted set
41
+ the fold handles. A governance test pins the set; the event schema is versioned and additive.
42
+ - **Fold limits and constants.** `INBOX_DEDUPE_CAP`, `QUARANTINE_FOLD_CAP`, the custom-dimension limits,
43
+ `KERNEL_STAMPED_EVENT_TYPES`, `FAILED_WHILE_PARKED`, `FLOW_DIVERGED_GATE`.
44
+
45
+ ## Behaviour that surprises people
46
+
47
+ - **An unknown event type is a no-op, but `sequence` still advances.** Application events with no handler
48
+ fold as nothing, which is also why an old log keeps folding under a newer schema.
49
+ - **Some kinds fold only when the kernel wrote them.** `EXECUTION_CONTINUED`, `MESSAGE_CONSUMED`,
50
+ `PARALLEL_COMPLETED`, `INBOX_QUARANTINED` and `INBOX_RELEASED` take effect only with
51
+ `metadata.kernel === true`, so an application event that borrows one of those names cannot change state.
52
+ - **A snapshot is a stored fold, and folds can change.** From schema 1.26.0 settled frames no longer carry
53
+ `input`, and from 1.21.0 a failed step no longer marks the whole execution failed. Run an older
54
+ snapshot's state through `normalizeSnapshotState` before treating `fold(snapshot, tail)` as equal to
55
+ `fold(events)`.
56
+ - **`getState()` and `peekState()` differ.** `getState()` returns a state that later `applyEvent` calls will
57
+ never write to, at the cost of one container copy on the next commit. `peekState()` is a borrowed live
58
+ view: read it and drop it before the next `applyEvent`.
59
+ - **`foldEvents` shares structure.** The result reuses unchanged parts of `initial`, so treat both as
60
+ immutable (ADR 0015).
61
+
62
+ ## Install
63
+
64
+ Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
65
+
66
+ ## See also
67
+
68
+ - API reference: section "`@loomwork/replay-vm` — deterministic replay" in [docs/api-reference.org](../../docs/api-reference.org).
69
+ - Guides: [event schema reference](../../docs/loom-2.0/10-event-schema-reference.md), [architecture, core runtime](../../docs/architecture.md), [determinism rules](../../docs/user-guide.md#14-determinism-rules--pitfalls).
70
+ - ADRs: [0015 DSA performance optimizations](../../docs/adr/0015-dsa-performance-optimizations.md) (structural sharing), [0105 a caught step failure is not the execution's](../../docs/adr/0105-a-caught-step-failure-is-not-the-executions.md), [0138 compaction archives](../../docs/adr/0138-compaction-archives-what-it-removes.md).
71
+ - Source: `packages/replay-vm/src`. Reading a log at a point in time: [`@loomwork/replay-inspector`](../replay-inspector/README.md).
@@ -0,0 +1,59 @@
1
+ import type { EventEnvelope, ExecutionState } from "@loomwork/core";
2
+ export declare class ReplayVM {
3
+ private state;
4
+ private owned;
5
+ private postMigration;
6
+ constructor(events: EventEnvelope[], initial?: Partial<ExecutionState>);
7
+ private track;
8
+ /**
9
+ * ADR 0113 D3 — every recorded frame in the LOG's first-start order (by `firstSeq`, never by object
10
+ * key order, which floats integer-like ids to the front). A frame folded before `firstSeq` existed
11
+ * (an old snapshot) has none: those come first, in key order.
12
+ */
13
+ recordedFrames(): Array<{
14
+ id: string;
15
+ completed: boolean;
16
+ seq?: number;
17
+ scope?: string;
18
+ }>;
19
+ /** ADR 0113 D3 — what a decision record says about the steps its decider ran. */
20
+ getDecisionInner(decisionId: string): {
21
+ steps: readonly string[];
22
+ overflow?: {
23
+ from: number;
24
+ to: number;
25
+ };
26
+ } | undefined;
27
+ /**
28
+ * ADR 0113 D3 — the ids of the COMPLETED frames a re-run of this execution is expected to
29
+ * visit: every completed frame, except those recorded before the execution's last
30
+ * `EXECUTION_MIGRATED` (a migration changes the frame set on purpose). A fresh array.
31
+ */
32
+ expectedReplayFrames(): string[];
33
+ hasCompleted(stepId: string): boolean;
34
+ hasFailed(stepId: string): boolean;
35
+ getTypedFailure(stepId: string): {
36
+ channel: string;
37
+ payload: unknown;
38
+ error?: unknown;
39
+ } | undefined;
40
+ getOutput(stepId: string): unknown;
41
+ hasDecision(decisionId: string): boolean;
42
+ getDecision(decisionId: string): unknown;
43
+ flowEmitCount(digest: string): number;
44
+ /**
45
+ * The folded state, for a caller that may KEEP it (a snapshot save, a returned handle, a
46
+ * test). It is stable: later `applyEvent`s never write to it, at the price of one container
47
+ * copy on the next commit (ownership is dropped). Callers that only read and drop the value
48
+ * within the same synchronous turn should use {@link peekState}.
49
+ */
50
+ getState(): ExecutionState;
51
+ /**
52
+ * A BORROWED view of the live state: read it and let go before the next `applyEvent`. It
53
+ * does not retire fold ownership, so the commit path stays O(1) per event. Do not retain it,
54
+ * hand it to a caller, or mutate it.
55
+ */
56
+ peekState(): ExecutionState;
57
+ applyEvent(event: EventEnvelope): void;
58
+ }
59
+ //# sourceMappingURL=ReplayVM.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReplayVM.d.ts","sourceRoot":"","sources":["../src/ReplayVM.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAIpE,qBAAa,QAAQ;IACnB,OAAO,CAAC,KAAK,CAAiB;IAI9B,OAAO,CAAC,KAAK,CAAyB;IAOtC,OAAO,CAAC,aAAa,CAA0B;gBAEn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
4
+ const eventHandlers_1 = require("./eventHandlers");
5
+ const foldEvents_1 = require("./foldEvents");
6
+ class ReplayVM {
7
+ state;
8
+ // R1a — the containers (frames, decision map, audit lists, emit trie) THIS VM created and
9
+ // may therefore write in place on the next commit. Dropped whenever the state escapes
10
+ // (`getState`), so a state a caller holds is never mutated afterwards.
11
+ owned = new WeakSet();
12
+ // ADR 0113 D3 — the step ids that completed AFTER the execution's last `EXECUTION_MIGRATED`
13
+ // (the replay-divergence detector's baseline resets there: a migration deliberately changes the
14
+ // frame set). `undefined` until a migration is known: then every completed frame is baseline.
15
+ // Allocated only for an execution that has been migrated, so the common path pays one string
16
+ // compare per applied event.
17
+ postMigration;
18
+ constructor(events, initial) {
19
+ this.state = (0, foldEvents_1.foldEvents)(events, initial, this.owned);
20
+ // A snapshot taken after a migration carries `_migrations`, but not WHEN: everything the
21
+ // snapshot already holds is exempt, so only the tail's completions count.
22
+ const migrated = initial?.variables?._migrations;
23
+ if (Array.isArray(migrated) && migrated.length > 0)
24
+ this.postMigration = new Set();
25
+ for (const e of events)
26
+ this.track(e);
27
+ }
28
+ track(event) {
29
+ if (event.eventType === "EXECUTION_MIGRATED") {
30
+ this.postMigration = new Set();
31
+ }
32
+ else if (this.postMigration !== undefined && event.eventType === "STEP_COMPLETED") {
33
+ const id = event.payload?.stepId;
34
+ if (typeof id === "string")
35
+ this.postMigration.add(id);
36
+ }
37
+ }
38
+ /**
39
+ * ADR 0113 D3 — every recorded frame in the LOG's first-start order (by `firstSeq`, never by object
40
+ * key order, which floats integer-like ids to the front). A frame folded before `firstSeq` existed
41
+ * (an old snapshot) has none: those come first, in key order.
42
+ */
43
+ recordedFrames() {
44
+ const frames = this.state.frames;
45
+ const out = Object.keys(frames).map((id, keyIndex) => {
46
+ const f = frames[id];
47
+ return {
48
+ id,
49
+ keyIndex,
50
+ completed: f.status === "completed",
51
+ ...(f.firstSeq !== undefined && { seq: f.firstSeq }),
52
+ ...(f.scope !== undefined && { scope: f.scope }),
53
+ };
54
+ });
55
+ out.sort((a, b) => (a.seq ?? -1) - (b.seq ?? -1) || a.keyIndex - b.keyIndex);
56
+ return out.map(({ keyIndex: _k, ...rest }) => rest);
57
+ }
58
+ /** ADR 0113 D3 — what a decision record says about the steps its decider ran. */
59
+ getDecisionInner(decisionId) {
60
+ const decisions = this.state.variables._decisions;
61
+ if (decisions === undefined || !Object.hasOwn(decisions, decisionId))
62
+ return undefined;
63
+ const rec = decisions[decisionId];
64
+ if (rec === undefined || !Array.isArray(rec.innerSteps))
65
+ return undefined;
66
+ return {
67
+ steps: rec.innerSteps,
68
+ ...(rec.innerStepsOverflow === true &&
69
+ rec.innerFrom !== undefined &&
70
+ rec.recordedAtSeq !== undefined && {
71
+ overflow: { from: rec.innerFrom, to: rec.recordedAtSeq },
72
+ }),
73
+ };
74
+ }
75
+ /**
76
+ * ADR 0113 D3 — the ids of the COMPLETED frames a re-run of this execution is expected to
77
+ * visit: every completed frame, except those recorded before the execution's last
78
+ * `EXECUTION_MIGRATED` (a migration changes the frame set on purpose). A fresh array.
79
+ */
80
+ expectedReplayFrames() {
81
+ const frames = this.state.frames;
82
+ const out = [];
83
+ for (const id of Object.keys(frames)) {
84
+ if (frames[id]?.status !== "completed")
85
+ continue;
86
+ if (this.postMigration !== undefined && !this.postMigration.has(id))
87
+ continue;
88
+ out.push(id);
89
+ }
90
+ return out;
91
+ }
92
+ hasCompleted(stepId) {
93
+ return this.state.frames[stepId]?.status === "completed";
94
+ }
95
+ hasFailed(stepId) {
96
+ return this.state.frames[stepId]?.status === "failed";
97
+ }
98
+ // DE-4 (ADR 0060) — the typed-failure twin of hasCompleted/getOutput. Defined
99
+ // only when the step's frame failed ON A DECLARED CHANNEL (a 1.17.0 typed
100
+ // STEP_FAILED); untyped failures return undefined and keep the legacy
101
+ // re-execute-on-replay semantics.
102
+ getTypedFailure(stepId) {
103
+ const frame = this.state.frames[stepId];
104
+ if (frame?.status !== "failed" || frame.errorChannel === undefined)
105
+ return undefined;
106
+ return {
107
+ channel: frame.errorChannel,
108
+ payload: frame.errorPayload,
109
+ ...(frame.error !== undefined && { error: frame.error }),
110
+ };
111
+ }
112
+ getOutput(stepId) {
113
+ return this.state.frames[stepId]?.output;
114
+ }
115
+ // Loom 2.0 (P9) — decision short-circuit, the twin of hasCompleted/getOutput.
116
+ // On replay, a decisionId already present in the log is served from state so the
117
+ // optimizer/router is never re-consulted.
118
+ hasDecision(decisionId) {
119
+ const decisions = this.state.variables._decisions;
120
+ return decisions !== undefined && Object.hasOwn(decisions, decisionId);
121
+ }
122
+ getDecision(decisionId) {
123
+ const decisions = this.state.variables._decisions;
124
+ // Own-key check (matches hasDecision) so a `__proto__`/inherited name can never read
125
+ // through the prototype chain.
126
+ if (decisions === undefined || !Object.hasOwn(decisions, decisionId))
127
+ return undefined;
128
+ return decisions[decisionId]?.choice;
129
+ }
130
+ // ADR 0102 — how many stamped flow-level emits with this content digest the log holds
131
+ // (the `_flowEmits` fold). A re-run serves its n-th emit of a digest from the log while
132
+ // n < this count.
133
+ flowEmitCount(digest) {
134
+ return (0, eventHandlers_1.flowEmitCount)(this.state.variables, digest);
135
+ }
136
+ /**
137
+ * The folded state, for a caller that may KEEP it (a snapshot save, a returned handle, a
138
+ * test). It is stable: later `applyEvent`s never write to it, at the price of one container
139
+ * copy on the next commit (ownership is dropped). Callers that only read and drop the value
140
+ * within the same synchronous turn should use {@link peekState}.
141
+ */
142
+ getState() {
143
+ this.owned = new WeakSet();
144
+ return this.state;
145
+ }
146
+ /**
147
+ * A BORROWED view of the live state: read it and let go before the next `applyEvent`. It
148
+ * does not retire fold ownership, so the commit path stays O(1) per event. Do not retain it,
149
+ * hand it to a caller, or mutate it.
150
+ */
151
+ peekState() {
152
+ return this.state;
153
+ }
154
+ applyEvent(event) {
155
+ this.state = (0, foldEvents_1.foldEvents)([event], this.state, this.owned);
156
+ this.track(event);
157
+ }
158
+ }
159
+ exports.ReplayVM = ReplayVM;
160
+ //# sourceMappingURL=ReplayVM.js.map
@@ -0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AC,CAAC;IACrD,CAAC;IAED;;;;;OAKG;IACH,QAAQ;QACN,IAAI,CAAC,KAAK,GAAG,IAAI,OAAO,EAAU,CAAC;QACnC,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED;;;;OAIG;IACH,SAAS;QACP,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,UAAU,CAAC,KAAoB;QAC7B,IAAI,CAAC,KAAK,GAAG,IAAA,uBAAU,EAAC,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QACzD,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;CACF;AA9KD,4BA8KC"}
@@ -0,0 +1,65 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ import type { ExecutionState } from "@loomwork/core";
3
+ type Handler = (state: ExecutionState, event: EventEnvelope) => ExecutionState;
4
+ export declare function resetFoldOwnership(): void;
5
+ /**
6
+ * R1a — install the ownership set a fold pass writes against. A one-shot fold (`foldEvents`
7
+ * with no set) starts empty every call. A LIVE fold (`ReplayVM.applyEvent`) hands in the set
8
+ * its VM keeps between commits, so containers the VM itself created stay writable in place
9
+ * across commits (O(1) per event) instead of being re-copied by every single-event fold
10
+ * (O(size) per event — quadratic over a run). The VM must drop the set the moment it lets a
11
+ * state escape to a caller (`ReplayVM.getState`), so an escaped state is never written to.
12
+ * Folding is synchronous and non-reentrant, so swapping the module-level reference is safe.
13
+ */
14
+ export declare function useFoldOwnership(owned: WeakSet<object>): void;
15
+ export declare const FLOW_EMIT_DIGEST: RegExp;
16
+ export type FlowEmitLeaf = Record<string, number>;
17
+ /** A 16-slot inner node of the `_flowEmits` trie; the third level holds leaves. */
18
+ export type FlowEmitCounts = Array<FlowEmitCounts | FlowEmitLeaf | null>;
19
+ export declare function countFlowEmit(variables: Record<string, unknown>, digest: string): Record<string, unknown>;
20
+ /** How many stamped flow-level emits with this digest the folded log holds. */
21
+ export declare function flowEmitCount(variables: Record<string, unknown>, digest: string): number;
22
+ /**
23
+ * ADR 0113 (R7 fix round 1) — the reserved gate a REFUSED re-run parks on. Like the in-doubt gate it
24
+ * is answered by the kernel's own status-only `null` resume (a re-drive after the code is fixed):
25
+ * the answer must NOT enter `_resumePayloads`, or the body's next gate would take it as its approval.
26
+ */
27
+ export declare const FLOW_DIVERGED_GATE = "__loom_diverged__";
28
+ /**
29
+ * 1.21.0 (ADR 0105) — reserved fold key: `true` while the execution is PARKED and a
30
+ * `STEP_FAILED` has landed since it parked (a parallel sibling failing after the flow reached
31
+ * its gate). Set only by that event in that state; removed by whatever ends the park — the next
32
+ * `EXECUTION_SUSPENDED` or `EXECUTION_RESUMED`, or a terminal `EXECUTION_COMPLETED` /
33
+ * `_FAILED` / `_CANCELLED`; absent otherwise, so a log without such a failure never gains it.
34
+ *
35
+ * It exists to keep one rule the 1.20.0 fold had implicitly. 1.20.0 folded that failure to
36
+ * "failed", so a following `null` resume was status-only (it answered no gate, and a 1.20.0
37
+ * `resumeAs` wrote exactly that). Since 1.21.0 the execution stays `suspended`; without this
38
+ * key the same `null` would become the gate's answer, and a replay's outcome would depend on
39
+ * whether it was seeded from a 1.20.0 snapshot — breaking snapshot + tail ≡ full log. So a
40
+ * `null` resume in this position stays status-only (fail-closed: the gate re-parks rather than
41
+ * passing without an approval). The cost: a caller's explicit `null` answer to such a gate is
42
+ * not recorded as its answer; the gate re-parks and takes the next non-null one.
43
+ */
44
+ export declare const FAILED_WHILE_PARKED = "_failedWhileParked";
45
+ /** Kinds whose fold requires the kernel stamp, and which the journal stamps when it writes one. */
46
+ export declare const KERNEL_STAMPED_EVENT_TYPES: ReadonlySet<string>;
47
+ /** Every inbox dedupe window the fold keeps is capped here; the runtime may apply a smaller one. */
48
+ export declare const INBOX_DEDUPE_CAP = 1024;
49
+ /**
50
+ * 1.25.0 (ADR 0130 residuals D9) — the fold keeps at most this many quarantined entries in total
51
+ * (`_quarantined`, across topics). A fold cannot read a runtime setting (the lesson of ADR 0110 D6),
52
+ * so the ceiling is a fold constant; the runtime's own `quarantineMax` (default 256) may be raised
53
+ * to it, never above. A fact that would exceed it is ignored.
54
+ */
55
+ export declare const QUARANTINE_FOLD_CAP = 1024;
56
+ /** ADR 0115 D2 — custom metering dimension names, count and per-value ceiling. */
57
+ export declare const CUSTOM_DIMENSION_PATTERN: RegExp;
58
+ export declare const CUSTOM_DIMENSION_MAX = 32;
59
+ export declare const CUSTOM_DIMENSION_CEILING = 1000000000000000;
60
+ export declare const BUILTIN_DIMENSION_NAMES: ReadonlySet<string>;
61
+ export declare function getHandler(eventType: string): Handler | undefined;
62
+ export declare const EVENT_SCHEMA_VERSION = "1.26.0";
63
+ export declare function knownEventTypes(): string[];
64
+ export {};
65
+ //# sourceMappingURL=eventHandlers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventHandlers.d.ts","sourceRoot":"","sources":["../src/eventHandlers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAkB,cAAc,EAAe,MAAM,gBAAgB,CAAC;AAElF,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,KAAK,cAAc,CAAC;AAsD/E,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAE7D;AA4BD,eAAO,MAAM,gBAAgB,QAAmB,CAAC;AACjD,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAClD,mFAAmF;AACnF,MAAM,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,GAAG,YAAY,GAAG,IAAI,CAAC,CAAC;AAiBzE,wBAAgB,aAAa,CAC3B,SAAS,EAAE,MAAM,CAAC,MAAM,EA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