@mowaos/host-browser 0.7.0 → 0.8.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/README.md CHANGED
@@ -33,6 +33,22 @@ const host = new MowaBrowserHost(new WasmKernelBridge(wasm), {
33
33
  });
34
34
  ```
35
35
 
36
+ **Conformance suite** (since 0.8.0): a storage adapter written elsewhere runs the same
37
+ tests as `MemoryStorage` and `SqliteStorage`, under `node --test`:
38
+
39
+ ```js
40
+ import * as lib from "@mowaos/host-browser";
41
+ import { hostSuite } from "@mowaos/host-browser/conformance";
42
+ import { loadKernel } from "@mowaos/kernel";
43
+
44
+ hostSuite("MyStorage", {
45
+ lib,
46
+ wasmPkg: await loadKernel(),
47
+ makeStorage: () => new MyStorage(),
48
+ clearSteps: (storage) => storage.deleteAllSteps(), // imitates a host from before 0.5.0
49
+ });
50
+ ```
51
+
36
52
  What every host must guarantee is specified in the
37
53
  [host contract](../../docs/host-contract.md). Each release attaches the WASM build and its
38
54
  SHA-256 checksum. Licensed under Apache-2.0.
@@ -0,0 +1,15 @@
1
+ import type { MowaStorage } from "../dist/index.js";
2
+
3
+ export interface HostSuiteOptions {
4
+ /** The @mowaos/host-browser module the storage was built against. */
5
+ lib: typeof import("../dist/index.js");
6
+ /** The kernel's bindings: startJson, advanceJson, loadFlowJson, dedupKeyJson, kernelVersion. */
7
+ wasmPkg: unknown;
8
+ /** A new, empty storage for each test. */
9
+ makeStorage: () => MowaStorage | Promise<MowaStorage>;
10
+ /** Deletes every step record from a storage, to imitate a host from before 0.5.0. */
11
+ clearSteps: (storage: MowaStorage) => void | Promise<void>;
12
+ }
13
+
14
+ /** Registers the host conformance tests (node:test) for one storage adapter. */
15
+ export function hostSuite(name: string, options: HostSuiteOptions): void;
@@ -0,0 +1,960 @@
1
+ /**
2
+ * Host conformance suite: the behaviour every MO·WA host built on MowaBrowserHost must
3
+ * keep, whatever its storage (docs/host-contract.md, section 9). Published as
4
+ * `@mowaos/host-browser/conformance`, so a storage adapter outside this repository runs
5
+ * exactly the suite that MemoryStorage and SqliteStorage pass. It uses node:test, so it
6
+ * runs under Node's test runner (`node --test`).
7
+ *
8
+ * import * as lib from "@mowaos/host-browser";
9
+ * import { hostSuite } from "@mowaos/host-browser/conformance";
10
+ * import { loadKernel } from "@mowaos/kernel";
11
+ *
12
+ * hostSuite("MyStorage", {
13
+ * lib, // the module your storage was built against
14
+ * wasmPkg: await loadKernel(), // startJson, advanceJson, loadFlowJson, kernelVersion
15
+ * makeStorage: () => new MyStorage(), // a new, empty MowaStorage (may be async)
16
+ * clearSteps: (storage) => …, // delete every step record, to imitate an older host
17
+ * });
18
+ */
19
+
20
+ import assert from "node:assert/strict";
21
+ import { describe, it } from "node:test";
22
+
23
+ /** Wraps a storage so every commit waits first, as IndexedDB does while it opens. */
24
+ function slowCommits(storage) {
25
+ return new Proxy(storage, {
26
+ get(target, key) {
27
+ const value = target[key];
28
+ if (key === "atomicCommit") {
29
+ return async (...args) => {
30
+ await new Promise((r) => setTimeout(r, 5));
31
+ return value.apply(target, args);
32
+ };
33
+ }
34
+ return typeof value === "function" ? value.bind(target) : value;
35
+ },
36
+ });
37
+ }
38
+
39
+ function sampleFlow() {
40
+ return {
41
+ id: "APPROVAL_FLOW",
42
+ version: "1.0.0",
43
+ status: "ACTIVE",
44
+ startNode: "INTAKE",
45
+ startActors: ["SYSTEM", "OPERATOR"],
46
+ effectiveFrom: 0,
47
+ declaredFacts: {
48
+ "doc:invoice": ["MISSING", "VERIFIED", "CONFLICTED"],
49
+ },
50
+ nodes: {
51
+ INTAKE: {
52
+ id: "INTAKE",
53
+ type: "t",
54
+ tier: "T1",
55
+ onEnter: [{ kind: "EMIT_INTAKE_NOTIFICATION" }],
56
+ transitions: {
57
+ SUBMIT_DOCS: {
58
+ to: "APPROVED",
59
+ allowedActors: ["SYSTEM", "OPERATOR"],
60
+ guard: {
61
+ op: "status_is",
62
+ target: "doc:invoice",
63
+ status: "VERIFIED",
64
+ },
65
+ onGuardFail: "REVIEW",
66
+ },
67
+ },
68
+ },
69
+ REVIEW: {
70
+ id: "REVIEW",
71
+ type: "t",
72
+ tier: "T2",
73
+ onEnter: [{ kind: "REQUEST_REVIEW", payload: { reason: "Missing invoice" } }],
74
+ transitions: {
75
+ RESOLVE: {
76
+ to: "APPROVED",
77
+ allowedActors: ["OPERATOR"],
78
+ },
79
+ },
80
+ },
81
+ APPROVED: {
82
+ id: "APPROVED",
83
+ type: "t",
84
+ tier: "T1",
85
+ terminal: true,
86
+ onEnter: [{ kind: "EMIT_APPROVED" }],
87
+ },
88
+ },
89
+ };
90
+ }
91
+
92
+ export function hostSuite(name, { lib, wasmPkg, makeStorage, clearSteps }) {
93
+ const {
94
+ MowaBrowserHost,
95
+ WasmKernelBridge,
96
+ AnchorImportError,
97
+ MemorySessionLock,
98
+ OutboxDispatcher,
99
+ IdempotencyConflictError,
100
+ IncompleteStepHistoryError,
101
+ CasConflictError,
102
+ } = lib;
103
+
104
+ describe(`host conformance: ${name}`, () => {
105
+ const kernel = new WasmKernelBridge(wasmPkg);
106
+
107
+ it("1. installFlow validates, caches in WASM, and stores in storage", async () => {
108
+ const storage = await makeStorage();
109
+ const host = new MowaBrowserHost(kernel, { storage });
110
+
111
+ const flow = sampleFlow();
112
+ const { flowHash, flowHandle } = await host.installFlow(flow);
113
+
114
+ assert.equal(flowHash.length, 64);
115
+ assert.ok(flowHandle.startsWith(flowHash));
116
+
117
+ const stored = await storage.getFlow(flowHash);
118
+ assert.ok(stored);
119
+ assert.equal(stored.id, "APPROVAL_FLOW");
120
+ });
121
+
122
+ it("2. startSession creates session version 0 and writes atomic 4-store commit", async () => {
123
+ const storage = await makeStorage();
124
+ const host = new MowaBrowserHost(kernel, { storage });
125
+ const { flowHash } = await host.installFlow(sampleFlow());
126
+
127
+ const sessionId = "SESSION_101";
128
+ const event = {
129
+ id: "EVT_1",
130
+ type: "INITIALIZE",
131
+ source: "chrome_extension_action",
132
+ caseId: "CASE_9921",
133
+ timestamp: 1000,
134
+ idempotencyKey: "idem_start_1",
135
+ actor: { type: "OPERATOR", id: "OPERATOR_ALICE" },
136
+ payload: {},
137
+ };
138
+ const ctx = { asOf: 1000, contextRefs: { manifestVersion: "2026.11" } };
139
+
140
+ const commit = await host.startSession({
141
+ sessionId,
142
+ event,
143
+ flowHash,
144
+ ctx,
145
+ });
146
+
147
+ assert.equal(commit.newSession.id, sessionId);
148
+ assert.equal(commit.newSession.state, "INTAKE");
149
+ assert.equal(commit.newSession.version, 0);
150
+ assert.equal(commit.newSession.flowHash, flowHash);
151
+ assert.equal(commit.outbox.length, 1);
152
+ assert.equal(commit.outbox[0].kind, "EMIT_INTAKE_NOTIFICATION");
153
+ assert.equal(commit.audit.prevResultHash, null);
154
+ assert.equal(commit.newSession.lastResultHash, commit.audit.resultHash);
155
+
156
+ // Verify storage persistence
157
+ const savedSession = await storage.getSession(sessionId);
158
+ assert.ok(savedSession);
159
+ assert.equal(savedSession.version, 0);
160
+
161
+ const audit = await storage.getAudit(commit.audit.transitionId);
162
+ assert.ok(audit);
163
+ assert.equal(audit.toState, "INTAKE");
164
+ });
165
+
166
+ it("3. idempotent start: duplicate start event returns cached commit immediately", async () => {
167
+ const storage = await makeStorage();
168
+ const host = new MowaBrowserHost(kernel, { storage });
169
+ const { flowHash } = await host.installFlow(sampleFlow());
170
+
171
+ const startParams = {
172
+ sessionId: "SESSION_IDEM_START",
173
+ event: {
174
+ id: "EVT_START_IDEM",
175
+ type: "INITIALIZE",
176
+ source: "action_card",
177
+ caseId: "CASE_IDEM",
178
+ timestamp: 1000,
179
+ idempotencyKey: "idem_key_unique_1",
180
+ actor: { type: "SYSTEM", id: "SYS_1" },
181
+ payload: {},
182
+ },
183
+ flowHash,
184
+ ctx: { asOf: 1000, contextRefs: {} },
185
+ };
186
+
187
+ const first = await host.startSession(startParams);
188
+ const second = await host.startSession(startParams);
189
+
190
+ assert.equal(first.dedupKey, second.dedupKey);
191
+ assert.equal(first.audit.transitionId, second.audit.transitionId);
192
+ assert.equal(JSON.stringify(first), JSON.stringify(second));
193
+ });
194
+
195
+ it("4. advanceSession transitions state, increments version, and chains audit hashes", async () => {
196
+ const storage = await makeStorage();
197
+ const outbox = new OutboxDispatcher(storage);
198
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
199
+ const { flowHash } = await host.installFlow(sampleFlow());
200
+
201
+ const sessionId = "SESSION_ADV_1";
202
+ const startCommit = await host.startSession({
203
+ sessionId,
204
+ event: {
205
+ id: "EVT_INIT",
206
+ type: "INITIALIZE",
207
+ source: "action_card",
208
+ caseId: "CASE_ADV",
209
+ timestamp: 1000,
210
+ idempotencyKey: "idem_init",
211
+ actor: { type: "OPERATOR", id: "BOB" },
212
+ payload: {},
213
+ },
214
+ flowHash,
215
+ ctx: { asOf: 1000, contextRefs: {} },
216
+ });
217
+
218
+ // Advance with verified invoice fact
219
+ const advanceCommit = await host.advanceSession({
220
+ sessionId,
221
+ event: {
222
+ id: "EVT_DOCS",
223
+ type: "SUBMIT_DOCS",
224
+ source: "action_card",
225
+ caseId: "CASE_ADV",
226
+ timestamp: 2000,
227
+ idempotencyKey: "idem_docs",
228
+ actor: { type: "OPERATOR", id: "BOB" },
229
+ payload: {},
230
+ },
231
+ facts: {
232
+ facts: { "doc:invoice": "VERIFIED" },
233
+ },
234
+ ctx: { asOf: 2000, contextRefs: {} },
235
+ });
236
+
237
+ assert.equal(advanceCommit.newSession.state, "APPROVED");
238
+ assert.equal(advanceCommit.newSession.version, 1);
239
+ assert.equal(advanceCommit.audit.fromState, "INTAKE");
240
+ assert.equal(advanceCommit.audit.toState, "APPROVED");
241
+ assert.equal(advanceCommit.outbox[0].kind, "EMIT_APPROVED");
242
+ assert.equal(advanceCommit.audit.prevResultHash, startCommit.audit.resultHash);
243
+ assert.equal(advanceCommit.newSession.lastResultHash, advanceCommit.audit.resultHash);
244
+
245
+ // Verify session updated in storage
246
+ const updated = await storage.getSession(sessionId);
247
+ assert.equal(updated?.version, 1);
248
+ assert.equal(updated?.state, "APPROVED");
249
+ });
250
+
251
+ it("5. guard failure routes deterministically to REVIEW with Pre-fill outbox", async () => {
252
+ const storage = await makeStorage();
253
+ const outbox = new OutboxDispatcher(storage);
254
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
255
+ const { flowHash } = await host.installFlow(sampleFlow());
256
+
257
+ const sessionId = "SESSION_REVIEW_1";
258
+ await host.startSession({
259
+ sessionId,
260
+ event: {
261
+ id: "EVT_0",
262
+ type: "INIT",
263
+ source: "action_card",
264
+ caseId: "CASE_REV",
265
+ timestamp: 1000,
266
+ idempotencyKey: "idem_rev_0",
267
+ actor: { type: "SYSTEM", id: "SYS" },
268
+ payload: {},
269
+ },
270
+ flowHash,
271
+ ctx: { asOf: 1000, contextRefs: {} },
272
+ });
273
+ await outbox.idle(); // the host's own pass after the commit
274
+
275
+ // Advance with MISSING invoice fact -> guard fails, routes to REVIEW
276
+ const commit = await host.advanceSession({
277
+ sessionId,
278
+ event: {
279
+ id: "EVT_SUBMIT_MISSING",
280
+ type: "SUBMIT_DOCS",
281
+ source: "action_card",
282
+ caseId: "CASE_REV",
283
+ timestamp: 2000,
284
+ idempotencyKey: "idem_missing",
285
+ actor: { type: "SYSTEM", id: "SYS" },
286
+ payload: {},
287
+ },
288
+ facts: {
289
+ facts: { "doc:invoice": "MISSING" },
290
+ },
291
+ ctx: { asOf: 2000, contextRefs: {} },
292
+ });
293
+ await outbox.idle(); // the host's own pass after the commit
294
+
295
+ assert.equal(commit.newSession.state, "REVIEW");
296
+ assert.equal(commit.audit.guardFailed, true);
297
+ assert.equal(commit.outbox[0].kind, "REQUEST_REVIEW");
298
+ });
299
+
300
+ it("6. outbox dispatcher handles AWAIT_CONFIRMATION without attempt increment, reject, and confirm", async () => {
301
+ const storage = await makeStorage();
302
+ const outbox = new OutboxDispatcher(storage, { maxAttempts: 3 });
303
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
304
+ const { flowHash } = await host.installFlow(sampleFlow());
305
+
306
+ let emailDrafted = false;
307
+ outbox.registerHandler("REQUEST_REVIEW", async (record) => {
308
+ emailDrafted = true;
309
+ // Pre-filled action card awaiting human confirmation
310
+ return "AWAIT_CONFIRMATION";
311
+ });
312
+
313
+ const sessionId = "SESSION_OUTBOX_TEST";
314
+ await host.startSession({
315
+ sessionId,
316
+ event: {
317
+ id: "E0",
318
+ type: "INIT",
319
+ source: "test",
320
+ caseId: "CASE_OB",
321
+ timestamp: 1,
322
+ idempotencyKey: "k0",
323
+ actor: { type: "SYSTEM", id: "S" },
324
+ payload: {},
325
+ },
326
+ flowHash,
327
+ ctx: { asOf: 1, contextRefs: {} },
328
+ });
329
+ await outbox.idle(); // the host's own pass after the commit
330
+
331
+ const commit = await host.advanceSession({
332
+ sessionId,
333
+ event: {
334
+ id: "E1",
335
+ type: "SUBMIT_DOCS",
336
+ source: "test",
337
+ caseId: "CASE_OB",
338
+ timestamp: 2,
339
+ idempotencyKey: "k1",
340
+ actor: { type: "SYSTEM", id: "S" },
341
+ payload: {},
342
+ },
343
+ facts: { facts: { "doc:invoice": "MISSING" } },
344
+ ctx: { asOf: 2, contextRefs: {} },
345
+ });
346
+ await outbox.idle(); // the host's own pass after the commit
347
+
348
+ const draftEffectId = commit.outbox[0].id;
349
+
350
+ // Run outbox dispatch: should transition to AWAIT_CONFIRMATION
351
+ await outbox.dispatchPending();
352
+ assert.equal(emailDrafted, true);
353
+
354
+ const record1 = await storage.getOutbox(draftEffectId);
355
+ assert.ok(record1);
356
+ assert.equal(record1.status, "AWAIT_CONFIRMATION");
357
+ assert.equal(record1.attempts, 0); // Must NOT increment attempts!
358
+
359
+ // Run 5 more unrelated dispatch passes: attempts MUST STAY 0 and NOT die in FAILED_DLQ!
360
+ for (let i = 0; i < 5; i++) {
361
+ await outbox.dispatchPending();
362
+ }
363
+ const recordAfterPasses = await storage.getOutbox(draftEffectId);
364
+ assert.equal(recordAfterPasses?.status, "AWAIT_CONFIRMATION");
365
+ assert.equal(recordAfterPasses?.attempts, 0);
366
+
367
+ // Confirm effect
368
+ await host.confirmEffect(draftEffectId);
369
+ const confirmedRecord = await storage.getOutbox(draftEffectId);
370
+ assert.equal(confirmedRecord?.status, "DISPATCHED");
371
+
372
+ // Cannot confirm an already dispatched effect
373
+ await assert.rejects(
374
+ () => host.confirmEffect(draftEffectId),
375
+ /expected 'AWAIT_CONFIRMATION'/
376
+ );
377
+ });
378
+
379
+ it("7. unhandled effect kind pushes backoff without blocking other effects", async () => {
380
+ const storage = await makeStorage();
381
+ const outbox = new OutboxDispatcher(storage, {
382
+ maxAttempts: 3,
383
+ unhandledGraceIntervalMs: 1000,
384
+ maxUnhandledGraceMs: 5000,
385
+ });
386
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
387
+ const { flowHash } = await host.installFlow(sampleFlow());
388
+
389
+ // Register handler for INTAKE effect but leave REQUEST_REVIEW unhandled
390
+ let intakeHandled = false;
391
+ outbox.registerHandler("EMIT_INTAKE_NOTIFICATION", async () => {
392
+ intakeHandled = true;
393
+ return "SUCCESS";
394
+ });
395
+
396
+ const sessionId = "SESSION_UNHANDLED_TEST";
397
+ await host.startSession({
398
+ sessionId,
399
+ event: {
400
+ id: "E0",
401
+ type: "INIT",
402
+ source: "test",
403
+ caseId: "CASE_UNH",
404
+ timestamp: 1,
405
+ idempotencyKey: "k_unh_0",
406
+ actor: { type: "SYSTEM", id: "S" },
407
+ payload: {},
408
+ },
409
+ flowHash,
410
+ ctx: { asOf: 1, contextRefs: {} },
411
+ });
412
+ await outbox.idle(); // the host's own pass after the commit
413
+
414
+ // Advance creates REQUEST_REVIEW which has NO handler registered
415
+ await host.advanceSession({
416
+ sessionId,
417
+ event: {
418
+ id: "E1",
419
+ type: "SUBMIT_DOCS",
420
+ source: "test",
421
+ caseId: "CASE_UNH",
422
+ timestamp: 2,
423
+ idempotencyKey: "k_unh_1",
424
+ actor: { type: "SYSTEM", id: "S" },
425
+ payload: {},
426
+ },
427
+ facts: { facts: { "doc:invoice": "MISSING" } },
428
+ ctx: { asOf: 2, contextRefs: {} },
429
+ });
430
+ await outbox.idle(); // the host's own pass after the commit
431
+
432
+ // Intake effect was already handled during startSession
433
+ assert.equal(intakeHandled, true);
434
+
435
+ // REQUEST_REVIEW was unhandled: verify it was deferred with grace interval
436
+ const pending = await storage.getPendingOutbox(10, Date.now() + 20000);
437
+ const unhandledRecord = pending.find((p) => p.effect.kind === "REQUEST_REVIEW");
438
+ assert.ok(unhandledRecord);
439
+ assert.equal(unhandledRecord.status, "PENDING");
440
+ assert.ok(unhandledRecord.nextAttemptAt > 0);
441
+
442
+ // Register handler now (simulating late registration in service worker)
443
+ let reviewHandled = false;
444
+ outbox.registerHandler("REQUEST_REVIEW", async () => {
445
+ reviewHandled = true;
446
+ return "SUCCESS";
447
+ });
448
+
449
+ // Make it immediately due and dispatch
450
+ await storage.updateOutboxStatus(unhandledRecord.outboxId, "PENDING", {
451
+ nextAttemptAt: Date.now() - 100,
452
+ });
453
+ const res = await outbox.dispatchPending();
454
+ assert.equal(res.processed, 1);
455
+ assert.equal(reviewHandled, true);
456
+ });
457
+
458
+ it("7b. requeueEffect clears unhandledSince and lastError, giving fresh grace period", async () => {
459
+ const storage = await makeStorage();
460
+ const outbox = new OutboxDispatcher(storage, {
461
+ maxAttempts: 3,
462
+ unhandledGraceIntervalMs: 500,
463
+ maxUnhandledGraceMs: 1000,
464
+ });
465
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
466
+ const { flowHash } = await host.installFlow(sampleFlow());
467
+
468
+ const sessionId = "SESSION_REQUEUE_GRACE";
469
+ await host.startSession({
470
+ sessionId,
471
+ event: {
472
+ id: "E0",
473
+ type: "INIT",
474
+ source: "test",
475
+ caseId: "CASE_REQ",
476
+ timestamp: 1,
477
+ idempotencyKey: "k_req_0",
478
+ actor: { type: "SYSTEM", id: "S" },
479
+ payload: {},
480
+ },
481
+ flowHash,
482
+ ctx: { asOf: 1, contextRefs: {} },
483
+ });
484
+ await outbox.idle(); // the host's own pass after the commit
485
+
486
+ await host.advanceSession({
487
+ sessionId,
488
+ event: {
489
+ id: "E1",
490
+ type: "SUBMIT_DOCS",
491
+ source: "test",
492
+ caseId: "CASE_REQ",
493
+ timestamp: 2,
494
+ idempotencyKey: "k_req_1",
495
+ actor: { type: "SYSTEM", id: "S" },
496
+ payload: {},
497
+ },
498
+ facts: { facts: { "doc:invoice": "MISSING" } },
499
+ ctx: { asOf: 2, contextRefs: {} },
500
+ });
501
+ await outbox.idle(); // the host's own pass after the commit
502
+
503
+ const pending = await storage.getPendingOutbox(10, Date.now() + 20000);
504
+ const unhandled = pending.find((p) => p.effect.kind === "REQUEST_REVIEW");
505
+ assert.ok(unhandled);
506
+
507
+ // Simulate grace period expiry (past 1000ms)
508
+ await storage.updateOutboxStatus(unhandled.outboxId, "PENDING", {
509
+ unhandledSince: Date.now() - 2000,
510
+ nextAttemptAt: Date.now() - 10,
511
+ });
512
+ await outbox.dispatchPending();
513
+
514
+ // Effect should now be in FAILED_DLQ with UNHANDLED_EFFECT_KIND
515
+ const dlqRecord = await storage.getOutbox(unhandled.outboxId);
516
+ assert.equal(dlqRecord?.status, "FAILED_DLQ");
517
+ assert.match(dlqRecord?.lastError ?? "", /UNHANDLED_EFFECT_KIND/);
518
+
519
+ // Requeue effect
520
+ await host.requeueEffect(unhandled.outboxId);
521
+
522
+ // Verify unhandledSince and lastError are cleared
523
+ const requeuedRecord = await storage.getOutbox(unhandled.outboxId);
524
+ assert.equal(requeuedRecord?.status, "PENDING");
525
+ assert.equal(requeuedRecord?.unhandledSince, undefined);
526
+ assert.equal(requeuedRecord?.lastError, undefined);
527
+
528
+ // Run dispatch again without registered handler: should be granted a FRESH grace period, NOT go straight back to DLQ!
529
+ await outbox.dispatchPending();
530
+ const freshRecord = await storage.getOutbox(unhandled.outboxId);
531
+ assert.equal(freshRecord?.status, "PENDING"); // Must still be pending under its new grace period!
532
+ });
533
+
534
+ it("8. idempotency conflict: reusing dedupKey with altered event intent throws IdempotencyConflictError", async () => {
535
+ const storage = await makeStorage();
536
+ const host = new MowaBrowserHost(kernel, { storage });
537
+ const { flowHash } = await host.installFlow(sampleFlow());
538
+
539
+ const sessionId = "SESSION_IDEM_CONFLICT";
540
+ const baseEvent = {
541
+ id: "EVT_BASE",
542
+ type: "INIT",
543
+ source: "client_app",
544
+ caseId: "CASE_IDEM_CONF",
545
+ timestamp: 1000,
546
+ idempotencyKey: "reused_idem_key",
547
+ actor: { type: "SYSTEM", id: "S1" },
548
+ payload: { value: 100 },
549
+ };
550
+
551
+ // First call succeeds
552
+ await host.startSession({
553
+ sessionId,
554
+ event: baseEvent,
555
+ flowHash,
556
+ ctx: { asOf: 1000, contextRefs: {} },
557
+ });
558
+
559
+ // Replay with exact same intent (even with different ephemeral event id) succeeds idempotently
560
+ const replayEvent = { ...baseEvent, id: "EVT_NEW_EPHEMERAL_ID", timestamp: 1050 };
561
+ const replayCommit = await host.startSession({
562
+ sessionId,
563
+ event: replayEvent,
564
+ flowHash,
565
+ ctx: { asOf: 1000, contextRefs: {} },
566
+ });
567
+ assert.equal(replayCommit.newSession.id, sessionId);
568
+
569
+ // Replay with CONFLICTING semantic intent (different payload value) throws IdempotencyConflictError!
570
+ const conflictingEvent = { ...baseEvent, payload: { value: 999 } };
571
+ await assert.rejects(
572
+ () =>
573
+ host.startSession({
574
+ sessionId,
575
+ event: conflictingEvent,
576
+ flowHash,
577
+ ctx: { asOf: 1000, contextRefs: {} },
578
+ }),
579
+ (err) => {
580
+ assert.ok(err instanceof IdempotencyConflictError);
581
+ assert.equal(err.dedupKey, replayCommit.dedupKey);
582
+ return true;
583
+ }
584
+ );
585
+ });
586
+
587
+ it("9. wasm cache eviction auto-reload: evicted flow reloads seamlessly from storage", async () => {
588
+ const storage = await makeStorage();
589
+ const host = new MowaBrowserHost(kernel, { storage });
590
+
591
+ // Install 35 distinct flows to exceed the 32-capacity WASM cache
592
+ const flows = [];
593
+ for (let i = 0; i < 35; i++) {
594
+ const f = {
595
+ ...sampleFlow(),
596
+ id: `FLOW_${i}`,
597
+ };
598
+ const { flowHash } = await host.installFlow(f);
599
+ flows.push({ flowHash, id: `FLOW_${i}` });
600
+ }
601
+
602
+ // The first installed flow (FLOW_0) has been evicted from the WASM cache
603
+ const oldest = flows[0];
604
+
605
+ // Starting a session with the evicted flow must auto-reload from storage without error!
606
+ const commit = await host.startSession({
607
+ sessionId: "SESSION_RELOAD_TEST",
608
+ event: {
609
+ id: "E0",
610
+ type: "INIT",
611
+ source: "test",
612
+ caseId: "CASE_RELOAD",
613
+ timestamp: 1,
614
+ idempotencyKey: "k_reload",
615
+ actor: { type: "SYSTEM", id: "S" },
616
+ payload: {},
617
+ },
618
+ flowHash: oldest.flowHash,
619
+ ctx: { asOf: 1, contextRefs: {} },
620
+ });
621
+
622
+ assert.equal(commit.newSession.workflowId, oldest.id);
623
+ });
624
+
625
+ it("10. concurrent calls on same session serialize with zero CAS conflicts", async () => {
626
+ const storage = await makeStorage();
627
+ const lock = new MemorySessionLock();
628
+ const host = new MowaBrowserHost(kernel, { storage, lock });
629
+ const { flowHash } = await host.installFlow(sampleFlow());
630
+
631
+ const sessionId = "SESSION_CONCURRENT";
632
+ await host.startSession({
633
+ sessionId,
634
+ event: {
635
+ id: "E_START",
636
+ type: "INIT",
637
+ source: "test",
638
+ caseId: "CASE_CONCUR",
639
+ timestamp: 1,
640
+ idempotencyKey: "k_concur_start",
641
+ actor: { type: "SYSTEM", id: "S" },
642
+ payload: {},
643
+ },
644
+ flowHash,
645
+ ctx: { asOf: 1, contextRefs: {} },
646
+ });
647
+
648
+ // Fire 5 identical requests concurrently
649
+ const promises = Array.from({ length: 5 }, (_, i) =>
650
+ host.advanceSession({
651
+ sessionId,
652
+ event: {
653
+ id: `EVT_CONCUR_${i}`,
654
+ type: "SUBMIT_DOCS",
655
+ source: "action_card",
656
+ caseId: "CASE_CONCUR",
657
+ timestamp: 10 + i,
658
+ idempotencyKey: `idem_concur_identical`, // Same idempotency key!
659
+ actor: { type: "SYSTEM", id: "S" },
660
+ payload: {},
661
+ },
662
+ facts: { facts: { "doc:invoice": "VERIFIED" } },
663
+ ctx: { asOf: 10 + i, contextRefs: {} },
664
+ })
665
+ );
666
+
667
+ const results = await Promise.all(promises);
668
+
669
+ // All 5 must succeed with the exact same commit and zero CAS errors!
670
+ const firstCommit = results[0];
671
+ for (const r of results) {
672
+ assert.equal(r.newSession.version, 1);
673
+ assert.equal(r.audit.transitionId, firstCommit.audit.transitionId);
674
+ }
675
+ });
676
+
677
+ it("11. getOutboxByStatus queries outbox records by status", async () => {
678
+ const storage = await makeStorage();
679
+ const outbox = new OutboxDispatcher(storage);
680
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
681
+ const { flowHash } = await host.installFlow(sampleFlow());
682
+
683
+ outbox.registerHandler("EMIT_INTAKE_NOTIFICATION", async () => "AWAIT_CONFIRMATION");
684
+
685
+ const sessionId = "SESSION_STATUS_QUERY";
686
+ const commit = await host.startSession({
687
+ sessionId,
688
+ event: {
689
+ id: "E0_STATUS",
690
+ type: "START",
691
+ source: "test",
692
+ caseId: "CASE_STATUS",
693
+ timestamp: 1000,
694
+ idempotencyKey: "k_status",
695
+ actor: { type: "SYSTEM", id: "S" },
696
+ payload: {},
697
+ },
698
+ flowHash,
699
+ ctx: { asOf: 1000, contextRefs: {} },
700
+ });
701
+ await outbox.idle(); // the host's own pass after the commit
702
+
703
+ // Run outbox dispatch to move effect to AWAIT_CONFIRMATION
704
+ await outbox.dispatchPending();
705
+
706
+ const pendingConfirmation = await host.getOutboxByStatus("AWAIT_CONFIRMATION");
707
+ assert.equal(pendingConfirmation.length, 1);
708
+ assert.equal(pendingConfirmation[0].outboxId, commit.outbox[0].id);
709
+ assert.equal(pendingConfirmation[0].status, "AWAIT_CONFIRMATION");
710
+
711
+ const dispatched = await host.getOutboxByStatus("DISPATCHED");
712
+ assert.equal(dispatched.length, 0);
713
+ });
714
+
715
+ it("12. every step's inputs are kept, and an exported bundle replays to identical commits", async () => {
716
+ const storage = await makeStorage();
717
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: new OutboxDispatcher(storage) });
718
+ const { flowHash } = await host.installFlow(sampleFlow());
719
+ const sessionId = "SESSION_REPLAY";
720
+ const ev = (id, type, actor, ts) => ({
721
+ id, type, source: "test", caseId: "CASE_REPLAY", timestamp: ts,
722
+ idempotencyKey: `k_${id}`, actor: { type: actor, id: "u1" }, payload: {},
723
+ });
724
+
725
+ await host.startSession({ sessionId, event: ev("E0", "INIT", "SYSTEM", 1000), flowHash, ctx: { asOf: 1000 } });
726
+ const facts = { facts: { "doc:invoice": "MISSING", "other:ignored": "X" } };
727
+ const submit = { sessionId, event: ev("E1", "SUBMIT_DOCS", "OPERATOR", 2000), facts, ctx: { asOf: 2000, contextRefs: { feed: "v1" } } };
728
+ await host.advanceSession(submit);
729
+ await host.advanceSession(submit); // duplicate delivery: returns the stored commit, adds no step
730
+ await host.advanceSession({ sessionId, event: ev("E2", "RESOLVE", "OPERATOR", 3000), ctx: { asOf: 3000 } });
731
+
732
+ const steps = await storage.getSteps(sessionId);
733
+ assert.deepEqual(steps.map((s) => [s.call, s.version]), [["start", 0], ["advance", 1], ["advance", 2]]);
734
+ assert.deepEqual(steps[1].facts, facts, "facts are kept exactly as supplied");
735
+ assert.deepEqual(steps[1].ctx, { asOf: 2000, contextRefs: { feed: "v1" } });
736
+ assert.equal(steps[0].facts, undefined, "start takes no facts");
737
+
738
+ const bundle = await host.exportVerificationBundle([sessionId], { feed: "reference data v1" });
739
+ assert.equal(bundle.format, "mowa.verification-bundle/1");
740
+ assert.equal(bundle.kernelVersion, wasmPkg.kernelVersion());
741
+ assert.deepEqual(Object.keys(bundle.flows), [flowHash]);
742
+ assert.deepEqual(bundle.contextData, { feed: "reference data v1" });
743
+
744
+ // Replay: a verifier with only the bundle and the open kernel reproduces every commit.
745
+ const replayed = JSON.parse(JSON.stringify(bundle)); // as if read from a file
746
+ let session = null;
747
+ for (const step of replayed.sessions[0].steps) {
748
+ const flow = replayed.flows[step.commit.newSession.flowHash];
749
+ const out = JSON.parse(
750
+ step.call === "start"
751
+ ? wasmPkg.startJson(JSON.stringify({ sessionId: replayed.sessions[0].sessionId, event: step.event, flow, ctx: step.ctx }))
752
+ : wasmPkg.advanceJson(JSON.stringify({ session, event: step.event, flow, facts: step.facts, ctx: step.ctx }))
753
+ );
754
+ assert.equal(out.status, "OK");
755
+ assert.deepEqual(out.commit, step.commit, `${step.call} v${step.commit.newSession.version} replays identically`);
756
+ assert.equal(step.commit.audit.prevResultHash, session ? session.lastResultHash : null, "chain link");
757
+ session = out.commit.newSession;
758
+ }
759
+ });
760
+
761
+ it("13. export refuses a session without a complete step history", async () => {
762
+ const storage = await makeStorage();
763
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: new OutboxDispatcher(storage) });
764
+ const { flowHash } = await host.installFlow(sampleFlow());
765
+ const commit = await host.startSession({
766
+ sessionId: "S_OLD",
767
+ event: { id: "E", type: "INIT", source: "t", caseId: "C", timestamp: 1, idempotencyKey: "k", actor: { type: "SYSTEM", id: "s" }, payload: {} },
768
+ flowHash,
769
+ ctx: { asOf: 1 },
770
+ });
771
+ // Simulate a session written by an older host: same session, no step records.
772
+ const legacy = await makeStorage();
773
+ await legacy.saveFlow(flowHash, sampleFlow());
774
+ await legacy.atomicCommit("S_OLD", null, commit, { intentHash: "x", inputs: { call: "start", event: {}, ctx: {} } });
775
+ await clearSteps(legacy);
776
+ const legacyHost = new MowaBrowserHost(kernel, { storage: legacy, outboxDispatcher: new OutboxDispatcher(legacy) });
777
+ await assert.rejects(legacyHost.exportVerificationBundle(["S_OLD"]), (err) => {
778
+ assert.ok(err instanceof IncompleteStepHistoryError);
779
+ assert.equal(err.name, "IncompleteStepHistoryError");
780
+ assert.equal(err.sessionId, "S_OLD");
781
+ assert.equal(err.stepCount, 0);
782
+ assert.equal(err.sessionVersion, 0);
783
+ assert.match(err.message, /incomplete step history/);
784
+ return true;
785
+ });
786
+ await assert.rejects(host.exportVerificationBundle(["NOPE"]), /not found/);
787
+ });
788
+
789
+ it("14. the host decides and stores a snapshot of its inputs, not the caller's live objects", async () => {
790
+ // Storage that waits before writing, as IndexedDB does while it opens the database.
791
+ const storage = slowCommits(await makeStorage());
792
+ const host = new MowaBrowserHost(kernel, { storage });
793
+ const flow = sampleFlow();
794
+ const { flowHash } = await host.installFlow(flow);
795
+ flow.nodes.INTAKE.type = "changed after install";
796
+ assert.equal((await storage.getFlow(flowHash)).nodes.INTAKE.type, "t", "installed flow is a snapshot");
797
+
798
+ // 1. The caller changes its event while the commit is waiting on storage.
799
+ const event = {
800
+ id: "EVT_SNAP", type: "INITIALIZE", source: "test", caseId: "CASE_SNAP", timestamp: 1000,
801
+ idempotencyKey: "idem_snap", actor: { type: "OPERATOR", id: "A" }, payload: { amount: 1 },
802
+ };
803
+ const ctx = { asOf: 1000, contextRefs: { ref: "r1" } };
804
+ const pending = host.startSession({ sessionId: "S_SNAP", event, flowHash, ctx });
805
+ setTimeout(() => { event.payload.amount = 999; ctx.contextRefs.ref = "r2"; }, 1);
806
+ const commit = await pending;
807
+ const [step] = await storage.getSteps("S_SNAP");
808
+ assert.deepEqual(step.event.payload, { amount: 1 });
809
+ assert.deepEqual(step.ctx.contextRefs, { ref: "r1" });
810
+ const replay = kernel.start("S_SNAP", step.event, sampleFlow(), step.ctx);
811
+ assert.equal(replay.audit.resultHash, commit.audit.resultHash, "stored inputs replay to the same commit");
812
+
813
+ // 2. A getter is read once, so the dedup key, the decision and the stored step agree.
814
+ let reads = 0;
815
+ const tricky = {
816
+ id: "EVT_GET", type: "INITIALIZE", source: "test", caseId: "CASE_GET", timestamp: 1000,
817
+ actor: { type: "OPERATOR", id: "A" }, payload: {},
818
+ };
819
+ Object.defineProperty(tricky, "idempotencyKey", { enumerable: true, get: () => `k${reads++}` });
820
+ const c2 = await host.startSession({ sessionId: "S_GET", event: tricky, flowHash, ctx: { asOf: 1000, contextRefs: {} } });
821
+ assert.equal(reads, 1);
822
+ const [step2] = await storage.getSteps("S_GET");
823
+ assert.equal(step2.event.idempotencyKey, "k0");
824
+ assert.equal(kernel.start("S_GET", step2.event, sampleFlow(), step2.ctx).audit.resultHash, c2.audit.resultHash);
825
+
826
+ // 3. Values JSON cannot carry are rejected at the boundary, not passed on.
827
+ const looped = { ...event, idempotencyKey: "idem_loop" };
828
+ looped.payload = { self: null };
829
+ looped.payload.self = looped.payload;
830
+ await assert.rejects(host.startSession({ sessionId: "S_LOOP", event: looped, flowHash, ctx }), /Validation failed at 'event': not JSON-serialisable/);
831
+ });
832
+
833
+ it("15. a commit decided on a stale session version is refused and writes nothing", async () => {
834
+ const storage = await makeStorage();
835
+ const host = new MowaBrowserHost(kernel, { storage });
836
+ const { flowHash } = await host.installFlow(sampleFlow());
837
+ const ev = (id, type, ts) => ({
838
+ id, type, source: "test", caseId: "CASE_CAS", timestamp: ts,
839
+ idempotencyKey: `k_${id}`, actor: { type: "SYSTEM", id: "S" }, payload: {},
840
+ });
841
+ const ctx = (asOf) => ({ asOf, contextRefs: {} });
842
+ const start = await host.startSession({ sessionId: "S_CAS", event: ev("E0", "INIT", 1), flowHash, ctx: ctx(1) });
843
+ await host.advanceSession({
844
+ sessionId: "S_CAS", event: ev("E1", "SUBMIT_DOCS", 2), facts: { facts: { "doc:invoice": "VERIFIED" } }, ctx: ctx(2),
845
+ });
846
+
847
+ // A second writer decided from version 0 and tries to commit after version 1 landed.
848
+ const event = ev("E2", "SUBMIT_DOCS", 3);
849
+ const facts = { facts: { "doc:invoice": "MISSING" } };
850
+ const stale = kernel.advance(start.newSession, event, sampleFlow(), facts, ctx(3));
851
+ assert.equal(stale.expectedSessionVersion, 0);
852
+ await assert.rejects(
853
+ storage.atomicCommit("S_CAS", 0, stale, { intentHash: "stale", inputs: { call: "advance", event, facts, ctx: ctx(3) } }),
854
+ (err) => err instanceof CasConflictError
855
+ );
856
+
857
+ assert.equal((await storage.getSession("S_CAS")).version, 1, "session unchanged");
858
+ assert.equal((await storage.getSession("S_CAS")).state, "APPROVED");
859
+ assert.equal(await storage.getAudit(stale.audit.transitionId), null, "no audit record");
860
+ assert.equal(await storage.getIdempotency(stale.dedupKey), null, "no duplicate record");
861
+ assert.equal((await storage.getSteps("S_CAS")).length, 2, "no step record");
862
+ for (const effect of stale.outbox) assert.equal(await storage.getOutbox(effect.id), null, "no outbox record");
863
+ });
864
+
865
+ it("16. anchors: imported only when they fit the records, exported only when present", async () => {
866
+ const storage = await makeStorage();
867
+ const host = new MowaBrowserHost(kernel, { storage });
868
+ const { flowHash } = await host.installFlow(sampleFlow());
869
+ const ev = (id, type, ts) => ({
870
+ id, type, source: "test", caseId: "CASE_ANCHOR", timestamp: ts,
871
+ idempotencyKey: `k_${id}`, actor: { type: "SYSTEM", id: "S" }, payload: {},
872
+ });
873
+ const start = await host.startSession({ sessionId: "S_ANC", event: ev("E0", "INIT", 1), flowHash, ctx: { asOf: 1, contextRefs: {} } });
874
+ const step1 = await host.advanceSession({
875
+ sessionId: "S_ANC", event: ev("E1", "SUBMIT_DOCS", 2), facts: { facts: { "doc:invoice": "VERIFIED" } }, ctx: { asOf: 2, contextRefs: {} },
876
+ });
877
+
878
+ // No anchors yet: the export has no anchors field at all.
879
+ const plain = await host.exportVerificationBundle(["S_ANC"]);
880
+ assert.equal("anchors" in plain, false);
881
+
882
+ // The host checks shape and the match with its own steps; hashing is the verifier's job.
883
+ const h = (c) => c.repeat(64);
884
+ const anchor = (version, resultHash, over = {}) => ({
885
+ type: "mowa.anchor/1", sessionId: "S_ANC", version, resultHash, leafIndex: 0, inclusionPath: [h("a")],
886
+ checkpoint: { type: "mowa.anchor-checkpoint/1", origin: "test/log", treeSize: 2, rootHash: h("b"), time: 1000 + version },
887
+ signatures: [{ keyId: h("c"), signature: "AAAA" }],
888
+ ...over,
889
+ });
890
+ const a0 = anchor(0, start.audit.resultHash);
891
+ const a1 = anchor(1, step1.audit.resultHash);
892
+
893
+ const refuse = async (list, pattern) =>
894
+ assert.rejects(host.importAnchors(list), (err) => err instanceof AnchorImportError && pattern.test(err.message));
895
+ await refuse([a0, anchor(1, h("d"))], /different resultHash/);
896
+ await refuse([anchor(5, h("d"))], /has no step 5/);
897
+ await refuse([{ ...a0, sessionId: "S_NOPE" }], /no session 'S_NOPE'/);
898
+ await refuse([{ ...a0, type: "mowa.anchor/2" }], /type must be/);
899
+ await refuse([{ ...a0, inclusionPath: ["XYZ"] }], /inclusionPath/);
900
+ await refuse([{ ...a0, signatures: [] }], /signatures/);
901
+ assert.deepEqual(await storage.getAnchors("S_ANC"), [], "a refused batch stores nothing, not even its valid anchors");
902
+
903
+ assert.deepEqual(await host.importAnchors([a1, a0, a0]), { imported: 2, unchanged: 1 });
904
+ assert.deepEqual(await host.importAnchors([a0]), { imported: 0, unchanged: 1 }, "importing again is a no-op");
905
+ await refuse([{ ...a0, leafIndex: 1 }], /different anchor for the same session, step, log and tree/);
906
+
907
+ const bundle = await host.exportVerificationBundle(["S_ANC"]);
908
+ assert.deepEqual(bundle.anchors, [a0, a1], "exported in version order");
909
+
910
+ // Storage without anchor support exports none and refuses imports.
911
+ const bare = new Proxy(storage, {
912
+ get: (t, k) => (k === "saveAnchor" || k === "getAnchors" ? undefined : typeof t[k] === "function" ? t[k].bind(t) : t[k]),
913
+ });
914
+ const bareHost = new MowaBrowserHost(kernel, { storage: bare });
915
+ assert.equal("anchors" in (await bareHost.exportVerificationBundle(["S_ANC"])), false);
916
+ await assert.rejects(bareHost.importAnchors([a0]), /does not support anchors/);
917
+ });
918
+
919
+ it("17. dispatchPending during a running pass waits for it and drains; idle() waits for quiet", async () => {
920
+ // Slow storage, as a networked database is: the host's own pass after a commit is
921
+ // still running when the caller asks to dispatch. Before 0.8.1 that call returned
922
+ // at once, having done nothing.
923
+ const base = await makeStorage();
924
+ const storage = new Proxy(base, {
925
+ get(target, key) {
926
+ const value = target[key];
927
+ if (key === "getPendingOutbox") {
928
+ return async (...args) => {
929
+ await new Promise((r) => setTimeout(r, 20));
930
+ return value.apply(target, args);
931
+ };
932
+ }
933
+ return typeof value === "function" ? value.bind(target) : value;
934
+ },
935
+ });
936
+ const outbox = new OutboxDispatcher(storage);
937
+ const host = new MowaBrowserHost(kernel, { storage, outboxDispatcher: outbox });
938
+ const { flowHash } = await host.installFlow(sampleFlow());
939
+ let calls = 0;
940
+ outbox.registerHandler("EMIT_INTAKE_NOTIFICATION", async () => {
941
+ calls += 1;
942
+ return "SUCCESS";
943
+ });
944
+ const ev = (id) => ({
945
+ id, type: "INIT", source: "test", caseId: `CASE_${id}`, timestamp: 1, idempotencyKey: `k_${id}`,
946
+ actor: { type: "SYSTEM", id: "S" }, payload: {},
947
+ });
948
+
949
+ const first = await host.startSession({ sessionId: "S_DISPATCH", event: ev("A"), flowHash, ctx: { asOf: 1, contextRefs: {} } });
950
+ await outbox.dispatchPending();
951
+ assert.equal((await storage.getOutbox(first.outbox[0].id)).status, "DISPATCHED", "dispatched when dispatchPending returns");
952
+ assert.equal(calls, 1, "and only once");
953
+
954
+ const second = await host.startSession({ sessionId: "S_IDLE", event: ev("B"), flowHash, ctx: { asOf: 1, contextRefs: {} } });
955
+ await outbox.idle();
956
+ assert.equal((await storage.getOutbox(second.outbox[0].id)).status, "DISPATCHED", "the host's own pass is done when idle() returns");
957
+ assert.equal(calls, 2);
958
+ });
959
+ });
960
+ }
package/dist/outbox.d.ts CHANGED
@@ -30,7 +30,8 @@ export declare class OutboxDispatcher {
30
30
  private readonly maxBackoffMs;
31
31
  private readonly unhandledGraceIntervalMs;
32
32
  private readonly maxUnhandledGraceMs;
33
- private isRunning;
33
+ /** The pass in progress, if any. */
34
+ private running;
34
35
  constructor(storage: MowaStorage, options?: OutboxDispatcherOptions);
35
36
  registerHandler(kind: string, handler: EffectHandler): void;
36
37
  /**
@@ -57,12 +58,19 @@ export declare class OutboxDispatcher {
57
58
  */
58
59
  requeueEffect(outboxId: string): Promise<void>;
59
60
  /**
60
- * Drain pending outbox records asynchronously outside the session lock.
61
+ * Drain pending outbox records, outside the session lock. If a pass is already
62
+ * running (the host starts one after every commit), this waits for it and then runs
63
+ * its own, so it never returns before the records due when it was called have been
64
+ * tried. Before 0.8.1 it returned at once in that case, having done nothing, which
65
+ * only showed with storage slower than memory.
61
66
  */
62
67
  dispatchPending(): Promise<{
63
68
  processed: number;
64
69
  failed: number;
65
70
  pending: number;
66
71
  }>;
72
+ /** Resolves once no pass is running: after a commit, to see settled effect statuses. */
73
+ idle(): Promise<void>;
74
+ private runPass;
67
75
  }
68
76
  //# sourceMappingURL=outbox.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../src/outbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,MAAM,MAAM,qBAAqB,GAC7B,SAAS,GACT,oBAAoB,GACpB,OAAO,CAAC;AAEZ,MAAM,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAErF,MAAM,WAAW,uBAAuB;IACtC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,qBAAa,gBAAgB;IAWzB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAV1B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoC;IAC7D,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,O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MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAWxF,wFAAwF;IAClF,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YAIb,OAAO;CAgGtB"}
package/dist/outbox.js CHANGED
@@ -18,7 +18,8 @@ export class OutboxDispatcher {
18
18
  maxBackoffMs;
19
19
  unhandledGraceIntervalMs;
20
20
  maxUnhandledGraceMs;
21
- isRunning = false;
21
+ /** The pass in progress, if any. */
22
+ running = null;
22
23
  constructor(storage, options = {}) {
23
24
  this.storage = storage;
24
25
  this.maxAttempts = options.maxAttempts ?? 5;
@@ -101,92 +102,84 @@ export class OutboxDispatcher {
101
102
  });
102
103
  }
103
104
  /**
104
- * Drain pending outbox records asynchronously outside the session lock.
105
+ * Drain pending outbox records, outside the session lock. If a pass is already
106
+ * running (the host starts one after every commit), this waits for it and then runs
107
+ * its own, so it never returns before the records due when it was called have been
108
+ * tried. Before 0.8.1 it returned at once in that case, having done nothing, which
109
+ * only showed with storage slower than memory.
105
110
  */
106
111
  async dispatchPending() {
107
- if (this.isRunning) {
108
- return { processed: 0, failed: 0, pending: 0 };
112
+ while (this.running)
113
+ await this.running.catch(() => undefined);
114
+ const pass = this.runPass();
115
+ this.running = pass;
116
+ try {
117
+ return await pass;
118
+ }
119
+ finally {
120
+ if (this.running === pass)
121
+ this.running = null;
109
122
  }
110
- this.isRunning = true;
123
+ }
124
+ /** Resolves once no pass is running: after a commit, to see settled effect statuses. */
125
+ async idle() {
126
+ while (this.running)
127
+ await this.running.catch(() => undefined);
128
+ }
129
+ async runPass() {
111
130
  let processed = 0;
112
131
  let failed = 0;
113
132
  let pending = 0;
114
- try {
115
- const now = Date.now();
116
- const records = await this.storage.getPendingOutbox(this.batchSize, now);
117
- for (const record of records) {
118
- const handler = this.handlers.get(record.effect.kind);
119
- if (!handler) {
120
- // Effect kind has no handler registered.
121
- // In MV3 service workers, handlers might register after initial wake-up.
122
- // Push nextAttemptAt forward so it leaves the due window without blocking other records.
123
- const unhandledSince = record.unhandledSince ?? now;
124
- if (now - unhandledSince >= this.maxUnhandledGraceMs) {
125
- await this.storage.updateOutboxStatus(record.outboxId, "FAILED_DLQ", {
126
- lastAttemptAt: now,
127
- lastError: `UNHANDLED_EFFECT_KIND: No handler registered for '${record.effect.kind}' within grace period`,
128
- });
129
- failed++;
130
- }
131
- else {
132
- await this.storage.updateOutboxStatus(record.outboxId, "PENDING", {
133
- nextAttemptAt: now + this.unhandledGraceIntervalMs,
134
- unhandledSince,
135
- });
136
- pending++;
137
- }
138
- continue;
133
+ const now = Date.now();
134
+ const records = await this.storage.getPendingOutbox(this.batchSize, now);
135
+ for (const record of records) {
136
+ const handler = this.handlers.get(record.effect.kind);
137
+ if (!handler) {
138
+ // Effect kind has no handler registered.
139
+ // In MV3 service workers, handlers might register after initial wake-up.
140
+ // Push nextAttemptAt forward so it leaves the due window without blocking other records.
141
+ const unhandledSince = record.unhandledSince ?? now;
142
+ if (now - unhandledSince >= this.maxUnhandledGraceMs) {
143
+ await this.storage.updateOutboxStatus(record.outboxId, "FAILED_DLQ", {
144
+ lastAttemptAt: now,
145
+ lastError: `UNHANDLED_EFFECT_KIND: No handler registered for '${record.effect.kind}' within grace period`,
146
+ });
147
+ failed++;
139
148
  }
140
- try {
141
- // Attempt dispatch
142
- const result = await handler(record);
143
- if (result === "SUCCESS") {
144
- // Success: mark DISPATCHED without incrementing retry attempts
145
- await this.storage.updateOutboxStatus(record.outboxId, "DISPATCHED", {
146
- lastAttemptAt: Date.now(),
147
- });
148
- processed++;
149
- }
150
- else if (result === "AWAIT_CONFIRMATION") {
151
- // Awaiting operator approval: move to AWAIT_CONFIRMATION, do NOT increment attempts!
152
- await this.storage.updateOutboxStatus(record.outboxId, "AWAIT_CONFIRMATION", {
153
- lastAttemptAt: Date.now(),
154
- });
155
- pending++;
156
- }
157
- else {
158
- // Handler explicitly requested RETRY
159
- const nextAttempts = record.attempts + 1;
160
- if (nextAttempts >= this.maxAttempts) {
161
- await this.storage.updateOutboxStatus(record.outboxId, "FAILED_DLQ", {
162
- attempts: nextAttempts,
163
- lastAttemptAt: Date.now(),
164
- lastError: `Exceeded max retry attempts (${this.maxAttempts})`,
165
- });
166
- failed++;
167
- }
168
- else {
169
- const delay = this.calculateBackoff(nextAttempts);
170
- await this.storage.updateOutboxStatus(record.outboxId, "PENDING", {
171
- attempts: nextAttempts,
172
- nextAttemptAt: Date.now() + delay,
173
- lastAttemptAt: Date.now(),
174
- lastError: "Handler requested retry",
175
- });
176
- pending++;
177
- }
178
- }
149
+ else {
150
+ await this.storage.updateOutboxStatus(record.outboxId, "PENDING", {
151
+ nextAttemptAt: now + this.unhandledGraceIntervalMs,
152
+ unhandledSince,
153
+ });
154
+ pending++;
179
155
  }
180
- catch (err) {
181
- // Handler threw exception during execution
182
- const errMsg = err instanceof Error ? err.message : String(err);
156
+ continue;
157
+ }
158
+ try {
159
+ // Attempt dispatch
160
+ const result = await handler(record);
161
+ if (result === "SUCCESS") {
162
+ // Success: mark DISPATCHED without incrementing retry attempts
163
+ await this.storage.updateOutboxStatus(record.outboxId, "DISPATCHED", {
164
+ lastAttemptAt: Date.now(),
165
+ });
166
+ processed++;
167
+ }
168
+ else if (result === "AWAIT_CONFIRMATION") {
169
+ // Awaiting operator approval: move to AWAIT_CONFIRMATION, do NOT increment attempts!
170
+ await this.storage.updateOutboxStatus(record.outboxId, "AWAIT_CONFIRMATION", {
171
+ lastAttemptAt: Date.now(),
172
+ });
173
+ pending++;
174
+ }
175
+ else {
176
+ // Handler explicitly requested RETRY
183
177
  const nextAttempts = record.attempts + 1;
184
- const isDlq = nextAttempts >= this.maxAttempts;
185
- if (isDlq) {
178
+ if (nextAttempts >= this.maxAttempts) {
186
179
  await this.storage.updateOutboxStatus(record.outboxId, "FAILED_DLQ", {
187
180
  attempts: nextAttempts,
188
181
  lastAttemptAt: Date.now(),
189
- lastError: errMsg,
182
+ lastError: `Exceeded max retry attempts (${this.maxAttempts})`,
190
183
  });
191
184
  failed++;
192
185
  }
@@ -196,15 +189,36 @@ export class OutboxDispatcher {
196
189
  attempts: nextAttempts,
197
190
  nextAttemptAt: Date.now() + delay,
198
191
  lastAttemptAt: Date.now(),
199
- lastError: errMsg,
192
+ lastError: "Handler requested retry",
200
193
  });
201
194
  pending++;
202
195
  }
203
196
  }
204
197
  }
205
- }
206
- finally {
207
- this.isRunning = false;
198
+ catch (err) {
199
+ // Handler threw exception during execution
200
+ const errMsg = err instanceof Error ? err.message : String(err);
201
+ const nextAttempts = record.attempts + 1;
202
+ const isDlq = nextAttempts >= this.maxAttempts;
203
+ if (isDlq) {
204
+ await this.storage.updateOutboxStatus(record.outboxId, "FAILED_DLQ", {
205
+ attempts: nextAttempts,
206
+ lastAttemptAt: Date.now(),
207
+ lastError: errMsg,
208
+ });
209
+ failed++;
210
+ }
211
+ else {
212
+ const delay = this.calculateBackoff(nextAttempts);
213
+ await this.storage.updateOutboxStatus(record.outboxId, "PENDING", {
214
+ attempts: nextAttempts,
215
+ nextAttemptAt: Date.now() + delay,
216
+ lastAttemptAt: Date.now(),
217
+ lastError: errMsg,
218
+ });
219
+ pending++;
220
+ }
221
+ }
208
222
  }
209
223
  return { processed, failed, pending };
210
224
  }
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.js","sourceRoot":"","sources":["../src/outbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAqBH,MAAM,OAAO,gBAAgB;IAWR;IAVF,QAAQ,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC5C,WAAW,CAAS;IACpB,SAAS,CAAS;IAClB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,wBAAwB,CAAS;IACjC,mBAAmB,CAAS;IACrC,SAAS,GAAG,KAAK,CAAC;IAE1B,YACmB,OAAoB,EACrC,UAAmC,EAAE;QADpB,YAAO,GAAP,OAAO,CAAa;QAGrC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,CAAC;QAC5C,IAAI,CAAC,SAAS,GA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CAAC,WAAW,CAAC;gBAE/C,IAAI,KAAK,EAAE,CAAC;oBACV,MAAM,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE;wBACnE,QAAQ,EAAE,YAAY;wBACtB,aAAa,EAAE,IAAI,CAAC,GAAG,EAAE;wBACzB,SAAS,EAAE,MAAM;qBAClB,CAAC,CAAC;oBACH,MAAM,EAAE,CAAC;gBACX,CAAC;qBAAM,CAAC;oBACN,MAAM,KAAK,GAAG,IAAI,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;oBAClD,MAAM,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,SAAS,EAAE;wBAChE,QAAQ,EAAE,YAAY;wBACtB,aAAa,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK;wBACjC,aAAa,EAAE,IAAI,CAAC,GAAG,EAAE;wBACzB,SAAS,EAAE,MAAM;qBAClB,CAAC,CAAC;oBACH,OAAO,EAAE,CAAC;gBACZ,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IACxC,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mowaos/host-browser",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "MO·WA OS Browser Extension Host Adapter (WASM + IndexedDB + Web Locks)",
6
6
  "author": "Bruce Gardiner (ScrAtcH)",
@@ -11,10 +11,15 @@
11
11
  ".": {
12
12
  "types": "./dist/index.d.ts",
13
13
  "import": "./dist/index.js"
14
+ },
15
+ "./conformance": {
16
+ "types": "./conformance/host-suite.d.ts",
17
+ "import": "./conformance/host-suite.mjs"
14
18
  }
15
19
  },
16
20
  "files": [
17
21
  "dist",
22
+ "conformance",
18
23
  "README.md",
19
24
  "LICENSE",
20
25
  "NOTICE"