noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);

struct Fixture {
    root: PathBuf,
}

impl Fixture {
    fn new(label: &str) -> Self {
        let ordinal = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "noxid-wo19-storage-{label}-{}-{ordinal}",
            std::process::id()
        ));
        fs::create_dir_all(&root).expect("create WO-19 storage fixture");
        fs::write(root.join("package.json"), "{\"type\":\"module\"}\n")
            .expect("write ESM package marker");
        Self { root }
    }

    fn write(&self, relative: &str, contents: &str) {
        let path = self.root.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("create WO-19 storage fixture parent");
        }
        fs::write(path, contents).expect("write WO-19 storage fixture file");
    }

    fn build(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_noxid"))
            .args(["build", self.root.to_str().expect("UTF-8 fixture")])
            .arg("--out-dir")
            .arg(self.root.join("dist"))
            .output()
            .expect("run WO-19 storage build")
    }

    fn run_node(&self, name: &str, source: &str, storage_root: &Path) -> Output {
        let script = self.root.join("dist").join(format!("{name}.mjs"));
        fs::write(&script, source).expect("write WO-19 storage Node script");
        Command::new("node")
            .arg(script.file_name().expect("Node script filename"))
            .current_dir(self.root.join("dist"))
            .env("NOXID_STORAGE_DIR", storage_root)
            .output()
            .expect("run WO-19 storage Node script")
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

fn assert_success(output: &Output, context: &str) {
    assert!(
        output.status.success(),
        "{context}:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

fn storage_fixture(driver: &str) -> Fixture {
    let fixture = Fixture::new(driver);
    fixture.write(
        "Noxid.toml",
        &format!("[app]\ntitle = \"WO-19 {driver} storage\"\n\n[server]\nstorage = \"{driver}\"\n"),
    );
    fixture.write(
        "src/routes/+page.nox",
        r#"component StoragePage {
    route { title: "Storage" }
    middleware { gate }
    actions {
        server ping(): String { }
    }
    view { <main>Storage</main> }
}
"#,
    );
    fixture.write(
        "src/middleware/gate.js",
        "export default () => ({ allow: true });\n",
    );
    fixture.write(
        "server/utils/store.js",
        r#"import { storage } from "noxid:server";
export const utilityStore = storage("shared/../namespace");
"#,
    );
    fixture.write(
        "server/middleware/10.storage.js",
        r#"import { storage } from "noxid:server";
export default async () => {
  await storage("middleware").set("global", { source: "global" });
  return { allow: true };
};
"#,
    );
    fixture.write(
        "server/route-middleware/gate.js",
        r#"import { storage } from "noxid:server";
export default async () => {
  await storage("middleware").set("route", { source: "route" });
  return { allow: true };
};
"#,
    );
    fixture.write(
        "server/host.js",
        r#"import { storage } from "noxid:server";
import { utilityStore } from "./utils/store.js";

export const actions = Object.freeze({
  "action:StoragePage.ping": async () => "pong",
});
export const untouchedSpecifierText = "noxid:server";

export async function stores() {
  return { direct: storage("direct"), utility: utilityStore };
}
"#,
    );
    fixture
}

const EXERCISE_STORAGE: &str = r#"import { stores } from "./server/host.js";
import globalMiddleware from "./server/global-middleware/10.storage.js";
import routeMiddleware from "./server/middleware/gate.js";

const { direct, utility } = await stores();
const original = { nested: { count: 1 }, values: [true, null, "ok"] };
await direct.set("path/../key", original);
original.nested.count = 99;
const first = await direct.get("path/../key");
if (first.nested.count !== 1) throw new Error("set retained caller-owned JSON identity");
first.nested.count = 88;
if ((await direct.get("path/../key")).nested.count !== 1) throw new Error("get exposed stored JSON identity");

await direct.set("alpha", 1);
await direct.set("alphabet", 2);
await direct.set("beta", 3);
await direct.set("null-value", null);
const all = await direct.list();
if (JSON.stringify(all) !== JSON.stringify(["alpha", "alphabet", "beta", "null-value", "path/../key"])) throw new Error(`list was not sorted or omitted stored null: ${JSON.stringify(all)}`);
const prefixed = await direct.list("alpha");
if (JSON.stringify(prefixed) !== JSON.stringify(["alpha", "alphabet"])) throw new Error(`prefix list changed: ${JSON.stringify(prefixed)}`);
if (!Object.isFrozen(all)) throw new Error("list result was mutable");

await utility.set("alpha", { isolated: true });
if ((await direct.get("alpha")) !== 1) throw new Error("namespaces aliased");
await direct.set("expired", "gone", { ttl: 0.01 });
await new Promise((resolve) => setTimeout(resolve, 30));
if ((await direct.get("expired")) !== null || (await direct.list()).includes("expired")) throw new Error("TTL did not expire from get/list");

await direct.set("persist", { acrossProcess: true });
if (!(await direct.delete("beta")) || await direct.delete("beta")) throw new Error("delete result or missing delete changed");
if ((await direct.get("beta")) !== null) throw new Error("delete retained value");

for (const [label, value] of [["NaN", NaN], ["undefined", undefined], ["Date", new Date()]]) {
  let refused = false;
  try { await direct.set(`bad-${label}`, value); } catch (error) { refused = error instanceof TypeError; }
  if (!refused) throw new Error(`non-JSON ${label} was accepted`);
}
const cycle = {}; cycle.self = cycle;
let cycleRefused = false;
try { await direct.set("cycle", cycle); } catch (error) { cycleRefused = error instanceof TypeError; }
if (!cycleRefused) throw new Error("cyclic value was accepted");
let ttlRefused = false;
try { await direct.set("bad-ttl", true, { ttl: -1 }); } catch (error) { ttlRefused = error instanceof TypeError; }
if (!ttlRefused) throw new Error("negative TTL was accepted");
let hugeTtlRefused = false;
try { await direct.set("huge-ttl", true, { ttl: Number.MAX_VALUE }); } catch (error) { hugeTtlRefused = error instanceof TypeError; }
if (!hugeTtlRefused) throw new Error("overflowing TTL was accepted");
const ttlOptions = {};
Object.defineProperty(ttlOptions, "ttl", { enumerable: true, get() { throw new Error("TTL getter executed"); } });
let ttlGetterRefused = false;
try { await direct.set("getter-ttl", true, ttlOptions); } catch (error) { ttlGetterRefused = error instanceof TypeError; }
if (!ttlGetterRefused) throw new Error("TTL accessor was accepted or executed");
const getterArray = [];
Object.defineProperty(getterArray, "0", { enumerable: true, get() { throw new Error("getter executed"); } });
getterArray.length = 1;
let getterRefused = false;
try { await direct.set("getter", getterArray); } catch (error) { getterRefused = error instanceof TypeError; }
if (!getterRefused) throw new Error("array accessor was accepted or executed");
let valueProxyTraps = 0;
const valueProxy = new Proxy({ changed: true }, {
  getPrototypeOf(target) { valueProxyTraps += 1; return Reflect.getPrototypeOf(target); },
});
let valueProxyRefused = false;
try { await direct.set("persist", valueProxy); } catch (error) { valueProxyRefused = error instanceof TypeError; }
if (!valueProxyRefused || valueProxyTraps !== 0 || (await direct.get("persist"))?.acrossProcess !== true) {
  throw new Error(`Proxy value crossed the JSON boundary: ${JSON.stringify({ valueProxyRefused, valueProxyTraps })}`);
}
let optionsProxyTraps = 0;
const optionsProxy = new Proxy({ ttl: 60 }, {
  getPrototypeOf(target) { optionsProxyTraps += 1; return Reflect.getPrototypeOf(target); },
});
let optionsProxyRefused = false;
try { await direct.set("proxy-options", true, optionsProxy); } catch (error) { optionsProxyRefused = error instanceof TypeError; }
if (!optionsProxyRefused || optionsProxyTraps !== 0 || await direct.get("proxy-options") !== null) {
  throw new Error(`Proxy options crossed the TTL boundary: ${JSON.stringify({ optionsProxyRefused, optionsProxyTraps })}`);
}

await globalMiddleware({});
await routeMiddleware({});
const { storage } = await import("./server/noxid-server.js");
const middleware = storage("middleware");
if ((await middleware.get("global"))?.source !== "global" || (await middleware.get("route"))?.source !== "route") {
  throw new Error("host/utils/middleware virtual imports did not share the generated runtime");
}
"#;

#[test]
fn storage_memory_and_fs_execute_get_set_ttl_delete_and_sorted_list() {
    for driver in ["memory", "fs"] {
        let fixture = storage_fixture(driver);
        let build = fixture.build();
        assert_success(&build, &format!("build {driver} storage fixture"));

        let host = fs::read_to_string(fixture.root.join("dist/server/host.js"))
            .expect("read rewritten host");
        let utility = fs::read_to_string(
            fixture
                .root
                .join("dist/server/modules/server__utils__store.js"),
        )
        .expect("read rewritten utility");
        let global = fs::read_to_string(
            fixture
                .root
                .join("dist/server/global-middleware/10.storage.js"),
        )
        .expect("read rewritten global middleware");
        let route = fs::read_to_string(fixture.root.join("dist/server/middleware/gate.js"))
            .expect("read rewritten route middleware");
        assert!(host.contains("./noxid-server.js"));
        assert!(host.contains("untouchedSpecifierText = \"noxid:server\""));
        assert_eq!(host.matches("noxid:server").count(), 1);
        assert!(utility.contains("../noxid-server.js"));
        assert!(global.contains("../noxid-server.js"));
        assert!(route.contains("../noxid-server.js"));
        for emitted in [&utility, &global, &route] {
            assert!(!emitted.contains("noxid:server"));
        }

        let storage_root = fixture.root.join("storage-data");
        let node = fixture.run_node("exercise-storage", EXERCISE_STORAGE, &storage_root);
        assert_success(&node, &format!("execute {driver} storage contract"));

        let persistence = fixture.run_node(
            "check-persistence",
            &format!(
                r#"import {{ storage }} from "./server/noxid-server.js";
const value = await storage("direct").get("persist");
if ({expects_value} ? value?.acrossProcess !== true : value !== null) {{
  throw new Error(`unexpected cross-process value: ${{JSON.stringify(value)}}`);
}}
"#,
                expects_value = driver == "fs"
            ),
            &storage_root,
        );
        assert_success(
            &persistence,
            &format!("verify {driver} cross-process contract"),
        );
    }

    let default = storage_fixture("memory-default");
    default.write(
        "Noxid.toml",
        "[app]\ntitle = \"WO-19 default storage\"\n\n[server]\n",
    );
    let build = default.build();
    assert_success(&build, "build default storage fixture");
    let runtime = fs::read_to_string(default.root.join("dist/server/noxid-server.js"))
        .expect("read default storage runtime");
    assert!(runtime.contains("const __namespaces = new Map()"));
    assert!(!runtime.contains("node:fs/promises"));
}

#[test]
fn built_storage_drivers_preserve_javascript_string_names_and_fs_filename_identity() {
    for driver in ["memory", "fs"] {
        let fixture = storage_fixture(driver);
        let build = fixture.build();
        assert_success(
            &build,
            &format!("build {driver} storage string-domain fixture"),
        );
        let storage_root = fixture.root.join("storage-data");
        let node = fixture.run_node(
            &format!("storage-string-domain-{driver}"),
            &format!(
                r#"import {{ storage }} from "./server/noxid-server.js";
const values = storage("namespace-\ud800");
for (const [index, key] of ["high-\ud800", "low-\udfff"].entries()) {{
  await values.set(key, {{ index }});
  if ((await values.get(key))?.index !== index) throw new Error(`key ${{index}} did not round trip`);
}}
const keys = await values.list();
if (keys.length !== 2 || !["high-\ud800", "low-\udfff"].every((key) => keys.includes(key))) {{
  throw new Error(`full JavaScript string domain did not survive list: ${{JSON.stringify(keys)}}`);
}}
{}
"#,
                if driver == "fs" {
                    r#"const { writeFile } = await import("node:fs/promises");
const path = (await import("node:path")).default;
const directory = path.join(process.env.NOXID_STORAGE_DIR, "namespace-%uD800");
await writeFile(path.join(directory, "%68igh-%uD800.json"), '{"version":1,"expiresAt":null,"value":{"index":99}}');
let refused = false;
try { await values.list(); }
catch (error) { refused = /canonical|filename|record/i.test(String(error)); }
if (!refused) throw new Error("noncanonical record filename aliased a logical key");"#
                } else {
                    ""
                }
            ),
            &storage_root,
        );
        assert_success(
            &node,
            &format!("exercise {driver} storage string-domain contract"),
        );
    }
}

#[test]
fn storage_driver_and_virtual_import_context_fail_closed() {
    let invalid = Fixture::new("invalid-driver");
    invalid.write(
        "Noxid.toml",
        "[app]\ntitle = \"invalid\"\n\n[server]\nstorage = \"s3\"\n",
    );
    let output = invalid.build();
    assert!(!output.status.success(), "unknown storage driver compiled");
    let error = String::from_utf8_lossy(&output.stderr);
    assert!(error.contains("error[SERVER_STORAGE_DRIVER_INVALID]"));
    assert!(error.contains("`memory`, `fs`, `postgres`, or `redis`"));
    assert!(!invalid.root.join("dist").exists());

    let context = Fixture::new("invalid-context");
    context.write("Noxid.toml", "[app]\ntitle = \"invalid context\"\n");
    context.write(
        "src/routes/+page.nox",
        r#"component InvalidContextPage {
    route { title: "Invalid" }
    middleware { gate }
    actions { server ping(): String { } }
    view { <main>Invalid</main> }
}
"#,
    );
    context.write(
        "src/middleware/gate.js",
        r#"import { storage } from "noxid:server";
export default async () => {
  await storage("leak").set("key", true);
  return { allow: true };
};
"#,
    );
    context.write(
        "server/host.js",
        r#"export const actions = Object.freeze({
  "action:InvalidContextPage.ping": async () => "pong",
});
"#,
    );
    let output = context.build();
    assert!(
        !output.status.success(),
        "browser middleware imported noxid:server"
    );
    let error = String::from_utf8_lossy(&output.stderr);
    assert!(error.contains("error[NOXID_SERVER_IMPORT_CONTEXT_INVALID]"));
    assert!(error.contains("server/utils/"));
    assert!(
        !context.root.join("dist").exists(),
        "rejected virtual import published partial output"
    );
}

#[test]
fn dynamic_virtual_import_is_refused_before_server_artifacts_are_published() {
    let fixture = Fixture::new("dynamic-virtual-import");
    fixture.write(
        "Noxid.toml",
        "[app]\ntitle = \"dynamic virtual import\"\n\n[server]\nstorage = \"memory\"\n",
    );
    fixture.write(
        "server/api/probe.get.nox",
        "endpoint Probe { result: String handler { return \"ok\" } }\n",
    );
    fixture.write(
        "server/host.js",
        r#"export async function values() {
  const { storage } = await import("noxid:\u0073erver");
  return storage("dynamic");
}
"#,
    );

    let output = fixture.build();
    assert!(!output.status.success(), "dynamic virtual import built");
    let error = String::from_utf8_lossy(&output.stderr);
    assert!(
        error.contains("error[NOXID_SERVER_DYNAMIC_IMPORT_UNSUPPORTED]"),
        "dynamic virtual import lacked a structured teaching diagnostic: {error}"
    );
    assert!(
        error.contains("top-level static import"),
        "dynamic virtual import diagnostic omitted the legal alternative: {error}"
    );
    assert!(
        !fixture.root.join("dist/server/host.js").exists(),
        "rejected dynamic virtual import published a host artifact"
    );
}

#[test]
fn storage_virtual_import_is_rewritten_before_typescript_host_erasure() {
    let fixture = storage_fixture("memory");
    fs::remove_file(fixture.root.join("server/host.js")).expect("remove JavaScript fixture host");
    fixture.write(
        "server/host.ts",
        r#"import { storage } from "noxid:server";

export const actions = Object.freeze({
  "action:StoragePage.ping": async (): Promise<string> => "pong",
});

export async function typedStorageProbe(): Promise<unknown> {
  const values = storage("typed-host");
  await values.set("answer", { value: 42 });
  return values.get("answer");
}
"#,
    );
    let build = fixture.build();
    assert_success(&build, "build TypeScript storage host");
    let host = fs::read_to_string(fixture.root.join("dist/server/host.js"))
        .expect("read transpiled TypeScript host");
    assert!(host.contains("from \"./noxid-server.js\""));
    assert!(!host.contains("Promise<unknown>"));
    let node = fixture.run_node(
        "typed-storage-host",
        r#"import { typedStorageProbe } from "./server/host.js";
const value = await typedStorageProbe();
if (value?.value !== 42) throw new Error(`typed host storage failed: ${JSON.stringify(value)}`);
"#,
        &fixture.root.join("storage-data"),
    );
    assert_success(&node, "execute transpiled TypeScript storage host");
}

#[cfg(unix)]
#[test]
fn fs_storage_refuses_shared_record_inodes_before_every_operation() {
    let fixture = Fixture::new("fs-shared-record-inodes");
    fixture.write(
        "Noxid.toml",
        "[app]\ntitle = \"WO-19 hard-link containment\"\n\n[server]\nstorage = \"fs\"\n",
    );
    fixture.write(
        "server/host.js",
        "import { storage } from \"noxid:server\";\nexport const records = storage(\"contained\");\n",
    );
    fixture.write(
        "server/api/ping.get.nox",
        "endpoint Ping { result: String handler { return \"pong\" } }\n",
    );
    assert_success(&fixture.build(), "build hard-link containment fixture");

    let storage_root = fixture.root.join("storage-data");
    let namespace = storage_root.join("contained");
    fs::create_dir_all(&namespace).expect("create fs storage namespace");
    let outside = fixture.root.join("outside-record.json");
    let outside_record = r#"{"version":1,"expiresAt":null,"value":{"outside":true}}"#;
    fs::write(&outside, outside_record).expect("write outside record");
    for key in ["read", "write", "delete", "list"] {
        fs::hard_link(&outside, namespace.join(format!("{key}.json")))
            .expect("hard-link outside record into namespace");
    }

    let node = fixture.run_node(
        "shared-record-inodes",
        r#"import { records } from "./server/host.js";
import { lstat, readdir } from "node:fs/promises";
import path from "node:path";

async function expectBoundary(label, operation) {
  let refusal;
  try { await operation(); } catch (error) { refusal = error; }
  if (refusal?.code !== "SERVER_STORAGE_RECORD_BOUNDARY") {
    throw new Error(`${label} lacked structured record-boundary refusal: ${String(refusal)}`);
  }
  if (!/exactly one filesystem link/.test(String(refusal.message)) || !/storage\.set/.test(String(refusal.message))) {
    throw new Error(`${label} boundary refusal did not teach the ownership rule: ${refusal.message}`);
  }
}

await expectBoundary("get", () => records.get("read"));
await expectBoundary("set", () => records.set("write", { replaced: true }));
await expectBoundary("delete", () => records.delete("delete"));
await expectBoundary("list", () => records.list());

await records.set("ordinary", { generation: 1 });
await records.set("ordinary", { generation: 2 });
if ((await records.get("ordinary"))?.generation !== 2) throw new Error("ordinary atomic replacement changed");
const directory = path.join(process.env.NOXID_STORAGE_DIR, "contained");
const ordinary = await lstat(path.join(directory, "ordinary.json"));
if (!ordinary.isFile() || ordinary.nlink !== 1) throw new Error("driver-created record is not exclusively linked");
if ((await readdir(directory)).some((name) => name.endsWith(".tmp"))) throw new Error("atomic replacement leaked a temporary file");
"#,
        &storage_root,
    );
    assert_success(
        &node,
        "refuse shared fs record inodes without changing atomic replacement",
    );
    assert_eq!(
        fs::read_to_string(&outside).expect("read outside record after refused operations"),
        outside_record,
        "a refused storage mutation changed the outside inode"
    );
    for key in ["read", "write", "delete", "list"] {
        assert!(
            namespace.join(format!("{key}.json")).exists(),
            "refused {key} operation removed a shared record"
        );
    }
}

#[test]
fn fs_storage_repeated_same_key_contention_accepts_detached_open_inodes() {
    let fixture = Fixture::new("fs-repeated-same-key-contention");
    fixture.write(
        "Noxid.toml",
        "[app]\ntitle = \"WO-19 repeated same-key contention\"\n\n[server]\nstorage = \"fs\"\n",
    );
    fixture.write(
        "server/host.js",
        "import { storage } from \"noxid:server\";\nexport const records = storage(\"contended\");\n",
    );
    fixture.write(
        "server/api/ping.get.nox",
        "endpoint Ping { result: String handler { return \"pong\" } }\n",
    );
    assert_success(
        &fixture.build(),
        "build repeated same-key contention fixture",
    );

    let storage_root = fixture.root.join("storage-data");
    let node = fixture.run_node(
        "repeated-same-key-contention",
        r#"import { spawn } from "node:child_process";
import { readdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { records } from "./server/host.js";

await records.set("shared", { writer: -1, iteration: -1, payload: "seed" });
await writeFile("contending-writer.mjs", `import { records } from "./server/host.js";
const writer = Number(process.argv[2]);
for (let iteration = 0; iteration < 200; iteration += 1) {
  const prefix = writer + ":" + iteration + ":";
  await records.set("shared", { writer, iteration, payload: prefix.repeat(128) });
  const observed = await records.get("shared");
  if (!Number.isInteger(observed?.writer) || !Number.isInteger(observed?.iteration)) throw new Error("read missed an atomically replaced record");
  const observedPrefix = observed.writer + ":" + observed.iteration + ":";
  if (observed.payload !== observedPrefix.repeat(128)) throw new Error("read observed a torn record");
}
`);

const workers = Array.from({ length: 12 }, (_, writer) => new Promise((resolve, reject) => {
  const child = spawn(process.execPath, ["contending-writer.mjs", String(writer)], { stdio: ["ignore", "pipe", "pipe"] });
  let stderr = "";
  child.stderr.setEncoding("utf8");
  child.stderr.on("data", (chunk) => { stderr += chunk; });
  child.on("error", reject);
  child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`writer ${writer} exited ${code}: ${stderr}`)));
}));
await Promise.all(workers);

const value = await records.get("shared");
const prefix = value.writer + ":" + value.iteration + ":";
if (value.payload !== prefix.repeat(128)) throw new Error("final record was torn");
const entries = await readdir(path.join(process.env.NOXID_STORAGE_DIR, "contended"));
if (entries.some((entry) => entry.endsWith(".tmp"))) throw new Error(`successful contention left temporary files: ${entries}`);
"#,
        &storage_root,
    );
    assert_success(
        &node,
        "exercise repeated same-key writer and reader contention",
    );
}

#[test]
fn fs_storage_persists_declared_rate_and_idempotency_state_across_processes() {
    let fixture = Fixture::new("endpoint-operational-state");
    fixture.write(
        "Noxid.toml",
        "[app]\ntitle = \"WO-19 endpoint storage\"\n\n[server]\nstorage = \"fs\"\n",
    );
    fixture.write(
        "server/api/rate.post.nox",
        r#"endpoint StoredRate {
    result: Int
    limit: 1 per minute per ip
    handler { return 1 }
}
"#,
    );
    fixture.write(
        "server/api/save.post.nox",
        r#"endpoint StoredReplay {
    body { value: Int }
    result: Int
    idempotent
    handler { return value }
}
"#,
    );
    let build = fixture.build();
    assert_success(&build, "build endpoint operational storage fixture");
    assert!(
        fixture.root.join("dist/server/noxid-server.js").is_file(),
        "declared endpoint operational state did not emit storage runtime"
    );
    let handler = fs::read_to_string(fixture.root.join("dist/server/handler.js"))
        .expect("read storage-backed endpoint handler");
    assert!(handler.contains("import * as __noxidServerStorageRuntime"));
    assert!(!handler.contains("endpointRateBuckets = new Map"));
    assert!(!handler.contains("endpointIdempotency = new Map"));

    let storage_root = fixture.root.join("operational-data");
    let first = fixture.run_node(
        "endpoint-storage-first",
        r#"import { fetch as handle } from "./server/handler.js";
let response = await handle(new Request("http://noxid.test/api/rate", { method: "POST" }), { ip: "203.0.113.7" });
if (response.status !== 200) throw new Error(`first rate request failed: ${response.status} ${await response.text()}`);
response = await handle(new Request("http://noxid.test/api/save", {
  method: "POST",
  headers: { "content-type": "application/json", "idempotency-key": "persisted" },
  body: JSON.stringify({ value: 7 }),
}), { ip: "203.0.113.8" });
const body = await response.json();
if (response.status !== 200 || body.value !== 7) throw new Error(`first idempotent request failed: ${response.status} ${JSON.stringify(body)}`);
"#,
        &storage_root,
    );
    assert_success(&first, "seed endpoint operational storage");

    let second = fixture.run_node(
        "endpoint-storage-second",
        r#"import { fetch as handle } from "./server/handler.js";
let response = await handle(new Request("http://noxid.test/api/rate", { method: "POST" }), { ip: "203.0.113.7" });
let body = await response.json();
if (response.status !== 429 || body.error?.code !== "ENDPOINT_RATE_LIMITED") throw new Error(`rate bucket did not persist: ${response.status} ${JSON.stringify(body)}`);
response = await handle(new Request("http://noxid.test/api/save", {
  method: "POST",
  headers: { "content-type": "application/json", "idempotency-key": "persisted" },
  body: JSON.stringify({ value: 99 }),
}), { ip: "203.0.113.8" });
body = await response.json();
if (response.status !== 200 || body.value !== 7) throw new Error(`idempotency snapshot did not persist: ${response.status} ${JSON.stringify(body)}`);
"#,
        &storage_root,
    );
    assert_success(&second, "replay endpoint operational storage");
}