noxid-cli 0.2.0

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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
//! WO-31 stages (b) and (c): the agent engine's loop, its durable pause, and
//! the client session's `Paused`/`resume` case.
//!
//! Every model turn here is scripted through a local HTTP sink started inside
//! the test's own node process, in the same shape WO-30's recorded wire
//! fixtures use, so CI never calls a provider. The sink also records what the
//! compiler-generated client sent, which is how the "a denied tool is never
//! even described to the model" assertion stays honest.
//!
//! The tools are real endpoints reached through the whole endpoint path, and
//! the pause test kills and restarts the emitted server between the pause and
//! the resume, against a PostgreSQL-backed store and queue.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

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

// --------------------------------------------------------------- the project

/// One agent, two endpoints, one model. `ReadTickets` needs `tickets.read`,
/// which the agent holds; `RefundBilling` needs `billing.refund`, which the
/// agent explicitly denies, so the compiler leaves it out of the registry.
const AGENT_SOURCE: &str = r#"type SupportRequest {
    prompt: String
}

type SupportResponse {
    answer: String
}

type ToolCall {
    name: String
    capability: String
}

type ToolResult {
    name: String
    summary: String
    ok: Boolean
}

type Permission {
    capability: String
    runId: String
}

agent Support {
    model: Assistant
    instructions: "server/agents/support.md"
    maxTurns: 4
    input SupportRequest
    output SupportResponse
    event Token(String)
    event ToolStarted(ToolCall)
    event ToolCompleted(ToolResult)
    event PermissionRequired(Permission)
    can [tickets.read]
    cannot [billing.refund]
}

component Page {
    state {
        prompt: String = "look up 42"
    }

    agents {
        session = Support(SupportRequest(prompt = prompt))
    }

    view {
        <section>
            #stream session {
                Started { <p>starting</p> }
                Token(text) { <p>{text}</p> }
                ToolStarted(tool) { <p>{tool.name}</p> }
                ToolCompleted(result) { <p>{result.summary}</p> }
                PermissionRequired(permission) { <p>{permission.capability}</p> }
                Paused(runId) { <p>paused {runId}</p> }
                Completed(answer) { <p>{answer.answer}</p> }
                Failed(error) { <p>{error.code}</p> }
                Cancelled { <p>cancelled</p> }
            }
        </section>
    }
}
"#;

const HOST: &str = r#"export const endpoints = Object.freeze({
  "endpoint:ReadTickets@1": async ({ customer }) => ({ id: `T-${customer}`, subject: "Password reset" }),
  "endpoint:RefundBilling@1": async ({ amount }) => `refunded ${amount}`,
});

// The authorizer is scripted per process through an environment variable, so a
// restarted server can answer differently from the one that paused the run.
export async function authorize({ capability }) {
  const decisions = JSON.parse(process.env.PROBE_AUTHORIZER ?? "{}");
  if (Object.hasOwn(decisions, capability)) return decisions[capability];
  return capability === "agents.Support.run";
}
"#;

struct Fixture {
    root: PathBuf,
}

impl Fixture {
    fn new(label: &str, storage: &str) -> Self {
        let ordinal = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "noxid-wo31-{label}-{}-{ordinal}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("create WO-31 fixture");
        let fixture = Self { root };
        fixture.write("package.json", "{\"private\":true,\"type\":\"module\"}\n");
        fixture.write(
            "Noxid.toml",
            &format!(
                "[app]\ntitle = \"WO-31 agent engine\"\nroutes = \"src/routes\"\n\n[server]\nruntime = \"node\"\nstorage = \"{storage}\"\nsecrets = [\"ANTHROPIC_API_KEY\", \"MODEL_GATEWAY_URL\"]\ntracing = \"full\"\n"
            ),
        );
        fixture.write("src/routes/+page.nox", AGENT_SOURCE);
        fixture.write(
            "server/models/Assistant.nox",
            "model Assistant {\n    provider: anthropic\n    id: \"claude-sonnet-5\"\n    baseUrl: MODEL_GATEWAY_URL\n    maxTokens: 512\n    retries: 1\n    secret: ANTHROPIC_API_KEY\n}\n",
        );
        fixture.write(
            "server/api/tickets.get.nox",
            "type Ticket {\n    id: String\n    subject: String\n}\n\nendpoint ReadTickets {\n    version: 1\n    capabilities [tickets.read]\n    query { customer: String }\n    result: Ticket\n}\n",
        );
        fixture.write(
            "server/api/refund.post.nox",
            "endpoint RefundBilling {\n    version: 1\n    capabilities [billing.refund]\n    body { amount: Int }\n    result: String\n}\n",
        );
        // Declares no capability at all: the endpoint path authorizes nothing
        // for it, so no `can` entry can admit it and it is in no registry.
        fixture.write(
            "server/api/status.get.nox",
            "endpoint OpenStatus {\n    version: 1\n    result: String\n}\n",
        );
        fixture.write(
            "server/agents/support.md",
            "You are a support agent. Use the tools you are given.\n",
        );
        fixture.write("server/host.js", HOST);
        fixture
    }

    /// Link the workspace's admitted `postgres` driver into the fixture, so a
    /// Postgres-backed store and queue resolve it. Returns false when the
    /// driver is unavailable and the test should skip.
    #[cfg(unix)]
    fn link_postgres_driver(&self) -> bool {
        let repository_modules = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../node_modules");
        if !repository_modules.join("postgres").exists() {
            eprintln!(
                "WO-31 durable agent pause: SKIP (workspace postgres Node driver unavailable)"
            );
            return false;
        }
        let link = self.root.join("node_modules");
        if link.exists() {
            return true;
        }
        std::os::unix::fs::symlink(&repository_modules, link)
            .expect("link the admitted postgres driver");
        true
    }

    /// The queue a durable agent pause is reconciled by: WO-24's worker owns
    /// startup reconciliation, and a worker needs a declared queue.
    fn with_queue(self) -> Self {
        self.write(
            "server/queues/AuditTrail.nox",
            "queue AuditTrail {\n    payload { note: String }\n    retry: 1\n    backoff: 30s\n}\n",
        );
        self
    }

    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 fixture parent");
        }
        fs::write(path, contents).expect("write fixture file");
    }

    fn build(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_noxid"))
            .args(["build", ".", "--out-dir", "dist"])
            .current_dir(&self.root)
            .output()
            .expect("build WO-31 fixture")
    }

    /// Adapt the fixture for the Node adapter, which is the front door the
    /// checkpoint-3 read found did not forward a run start.
    fn adapt(&self, out_dir: &str) -> Output {
        Command::new(env!("CARGO_BIN_EXE_noxid"))
            .args(["adapt", ".", "--adapter", "node", "--out-dir", out_dir])
            .current_dir(&self.root)
            .env_remove("VERCEL")
            .env_remove("NETLIFY")
            .env_remove("CF_PAGES")
            .env_remove("DENO_DEPLOYMENT_ID")
            .env_remove("RAILWAY_ENVIRONMENT")
            .output()
            .expect("adapt WO-31 fixture for node")
    }

    fn read(&self, relative: &str) -> String {
        fs::read_to_string(self.root.join(relative))
            .unwrap_or_else(|error| panic!("read {relative}: {error}"))
    }

    /// Run one node probe inside `dist/`. `authorizer` scripts the host
    /// authorizer for this process only, which is what makes "the resuming
    /// principal decides" testable across a restart.
    fn run(
        &self,
        name: &str,
        script: &str,
        authorizer: &str,
        environment: &[(&str, &str)],
    ) -> Output {
        let file = format!("probe-{name}.mjs");
        self.write(&format!("dist/{file}"), &format!("{}{script}", preamble()));
        let mut command = Command::new("node");
        command
            .arg(&file)
            .current_dir(self.root.join("dist"))
            .env("PROBE_AUTHORIZER", authorizer)
            .env("ANTHROPIC_API_KEY", "wo31-test-key");
        for (key, value) in environment {
            command.env(key, value);
        }
        command.output().expect("execute agent probe")
    }
}

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

/// The scripted model sink plus the SSE decoding every probe needs. It speaks
/// the Anthropic streaming wire format, which is the one the emitted graph
/// builds for a `provider: anthropic` model.
fn preamble() -> String {
    r#"import http from "node:http";

const scripted = [];
const recorded = [];
function expect(frames) { scripted.push(frames); }
function sse(events) { return events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""); }
function textTurn(text) {
  return sse([
    { type: "message_start", message: { usage: { input_tokens: 11 } } },
    { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
    ...[...text].map((character) => ({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: character } })),
    { type: "content_block_stop", index: 0 },
    { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
  ]);
}
function toolTurn(name, input, id = "toolu_1") {
  return sse([
    { type: "message_start", message: { usage: { input_tokens: 12 } } },
    { type: "content_block_start", index: 0, content_block: { type: "tool_use", id, name } },
    { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } },
    { type: "content_block_stop", index: 0 },
    { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 7 } },
  ]);
}

let holdOpen = false;
const held = [];
const sink = http.createServer((request, response) => {
  const chunks = [];
  request.on("data", (chunk) => chunks.push(chunk));
  request.on("end", () => {
    let body = null;
    try { body = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch {}
    recorded.push(body);
    if (holdOpen) { held.push(response); return; }
    const next = scripted.shift();
    if (next === undefined) {
      response.writeHead(500, { "content-type": "application/json" });
      response.end(JSON.stringify({ error: { type: "sink_unscripted", code: "sink_unscripted" } }));
      return;
    }
    response.writeHead(200, { "content-type": "text/event-stream" });
    response.end(next);
  });
});
await new Promise((resolve) => sink.listen(0, "127.0.0.1", resolve));
process.env.MODEL_GATEWAY_URL = `http://127.0.0.1:${sink.address().port}`;

const handler = await import("./server/handler.js");
const { storage } = await import("./server/noxid-server.js");

function report(name, value) { console.log(`PROBE ${name} ${JSON.stringify(value)}`); }

async function post(path, body, init = {}) {
  const response = await handler.fetch(new Request(`http://noxid.test${path}`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body ?? {}),
    ...init,
  }), { sessionId: "session-1" }, {});
  return { status: response.status, response, text: init.signal === undefined ? await response.text() : null };
}

function frames(text) {
  const out = [];
  for (const block of text.split("\n\n")) {
    if (block.trim().length === 0) continue;
    const lines = block.split("\n");
    const event = lines.find((line) => line.startsWith("event: "))?.slice(7) ?? "message";
    const data = lines.filter((line) => line.startsWith("data: ")).map((line) => line.slice(6)).join("\n");
    out.push({ event, data: JSON.parse(data) });
  }
  return out;
}
const tags = (text) => frames(text).map((frame) => frame.event === "message" ? frame.data.tag : `!${frame.data.error.code}`);
const done = () => { for (const response of held) response.destroy(); sink.close(); };
// A Postgres-backed store keeps its pool open for the life of the process, so
// a probe that used one ends by flushing stdout and exiting rather than
// waiting for a handle that never closes.
async function exitProbe() {
  done();
  try { await handler.closeQueueDatabase(); } catch {}
  await new Promise((resolve) => process.stdout.write("\n", resolve));
  process.exit(0);
}
"#
    .to_string()
}

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 stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

/// Trace records and probe reports share stdout; only the `PROBE` lines are
/// assertions, and the trace lines are read separately by the spans test.
fn probe(log: &str, name: &str) -> String {
    log.lines()
        .find_map(|line| line.strip_prefix(&format!("PROBE {name} ")))
        .unwrap_or_else(|| panic!("probe `{name}` is missing from:\n{log}"))
        .to_string()
}

// ------------------------------------------------------------------ the loop

/// The whole contract in one run: a scripted model turn calls a real endpoint
/// tool, the endpoint runs through its full path under the agent principal,
/// its validated result comes back as a tool result, and the second turn's
/// final answer is validated against the declared `output` type.
#[test]
fn a_full_loop_dispatches_a_real_endpoint_tool_and_validates_the_final_answer() {
    let fixture = Fixture::new("loop", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "loop",
        r#"
expect(toolTurn("ReadTickets", { customer: "42" }));
expect(toolTurn("noxid_final_answer", { answer: "Ticket T-42 is a password reset" }, "toolu_2"));
const run = await post("/_noxid/agents/Support/runs", { input: { prompt: "look up 42" } });
report("status", run.status);
report("contentType", run.response.headers.get("content-type"));
report("tags", tags(run.text));
report("completed", frames(run.text).at(-1).data.value);
report("toolStarted", frames(run.text).find((frame) => frame.data.tag === "ToolStarted").data.value);
report("toolCompleted", frames(run.text).find((frame) => frame.data.tag === "ToolCompleted").data.value);
// The second provider request carries the first turn's tool result verbatim,
// which is how the model learns what the endpoint returned.
report("toolResultSeen", recorded[1].messages.at(-1).content[0].content);
report("systemPrompt", recorded[0].system);
const keys = await storage("agent_runs").list("");
const record = await storage("agent_runs").get(keys[0]);
report("persistedState", record.state);
report("persistedTurns", record.turns.length);
report("persistedPrincipal", record.principal);
done();
"#,
        r#"{"agents.Support.run": true, "tickets.read": true}"#,
        &[],
    );
    assert_success(&output, "run the full loop probe");
    let log = stdout(&output);
    assert_eq!(probe(&log, "status"), "200");
    assert!(
        probe(&log, "contentType").contains("text/event-stream"),
        "{log}"
    );
    assert_eq!(
        probe(&log, "tags"),
        r#"["Started","ToolStarted","ToolCompleted","Completed"]"#
    );
    assert_eq!(
        probe(&log, "completed"),
        r#"{"answer":"Ticket T-42 is a password reset"}"#
    );
    assert_eq!(
        probe(&log, "toolStarted"),
        r#"{"name":"ReadTickets","capability":"tickets.read"}"#
    );
    assert_eq!(
        probe(&log, "toolCompleted"),
        r#"{"name":"ReadTickets","summary":"ReadTickets completed","ok":true}"#
    );
    assert!(
        probe(&log, "toolResultSeen").contains("Password reset"),
        "the endpoint's validated result must reach the next model turn: {log}"
    );
    assert!(
        probe(&log, "systemPrompt").contains("support agent"),
        "the embedded instructions asset is the system prompt: {log}"
    );
    assert_eq!(probe(&log, "persistedState"), "\"Completed\"");
    assert_eq!(probe(&log, "persistedTurns"), "2");
    assert_eq!(
        probe(&log, "persistedPrincipal"),
        "\"agent:Support:acting:session:session-1\"",
        "the run executes under Principal.Agent {{ id: AgentId(Support), actingFor }}"
    );
}

/// `cannot [billing.refund]` is enforced by absence, not by refusal: the
/// denied endpoint is not in the derived registry, so it is never described to
/// the model and asking for it by name reaches no endpoint at all.
#[test]
fn a_denied_tool_is_never_described_and_never_reachable() {
    let fixture = Fixture::new("denied", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "denied",
        r#"
expect(toolTurn("RefundBilling", { amount: 100 }));
expect(toolTurn("noxid_final_answer", { answer: "no refund was issued" }, "toolu_2"));
const run = await post("/_noxid/agents/Support/runs", { input: { prompt: "refund me" } });
report("tags", tags(run.text));
report("offeredTools", recorded[0].tools.map((tool) => tool.name));
report("modelWasTold", recorded[1].messages.at(-1).content[0].content);
report("endpointRan", process.env.PROBE_REFUND_RAN ?? "no");
done();
"#,
        r#"{"agents.Support.run": true, "billing.refund": true, "tickets.read": true}"#,
        &[],
    );
    assert_success(&output, "run the denied-tool probe");
    let log = stdout(&output);
    // No ToolStarted at all: the call never became a dispatch.
    assert_eq!(probe(&log, "tags"), r#"["Started","Completed"]"#);
    assert_eq!(
        probe(&log, "offeredTools"),
        r#"["ReadTickets","noxid_final_answer"]"#,
        "the denied endpoint must not appear in the provider request: {log}"
    );
    assert!(
        probe(&log, "modelWasTold").contains("AGENT_TOOL_NOT_AVAILABLE"),
        "{log}"
    );
    assert!(
        !probe(&log, "modelWasTold").contains("refunded"),
        "the denied endpoint must not have run: {log}"
    );
    // The security manifest agrees: the registry the runtime dispatches from
    // is the one a reviewer reads.
    let manifest = fixture.read("dist/server/security.manifest.json");
    let registry = manifest
        .split_once("\"agents\":[")
        .expect("agents section")
        .1;
    assert!(
        registry.contains("\"endpoint\":\"ReadTickets\""),
        "{manifest}"
    );
    assert!(!registry.contains("RefundBilling"), "{manifest}");
    assert!(!registry.contains("OpenStatus"), "{manifest}");
    let handler = fixture.read("dist/server/handler.js");
    assert!(
        handler.contains("// noxid-runtime:feature-start:agents"),
        "the agents section is behind its feature marker"
    );
}

/// WO-31 stage (a) QA round 1, finding 3's ruling: "listed nowhere" is a claim
/// about the agent-facing surfaces. This is the stage (b) half — the tool list
/// and the schema bytes the engine actually sends to the provider equal the
/// manifest registry exactly, with the compiler-owned final-answer tool the
/// only addition.
#[test]
fn the_provider_tool_list_equals_the_manifest_registry_exactly() {
    let fixture = Fixture::new("registry", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "registry",
        r#"
import nodeFs from "node:fs";
expect(textTurn(JSON.stringify({ answer: "done" })));
await post("/_noxid/agents/Support/runs", { input: { prompt: "list tools" } });

const manifest = JSON.parse(nodeFs.readFileSync("server/security.manifest.json", "utf8"));
report("registry", manifest.agents[0].tools.map((tool) => tool.endpoint).sort());
report("offered", recorded[0].tools.map((tool) => tool.name).sort());

// Every deployment endpoint, so the assertion is about a real subtraction.
const endpoints = JSON.parse(nodeFs.readFileSync("server/execution.manifest.json", "utf8")).endpoints ?? [];
report("deploymentEndpoints", endpoints.map((endpoint) => endpoint.name).sort());

// The schema bytes, not just the name: the tool the model sees must describe
// exactly the endpoint's declared inputs.
const readTickets = recorded[0].tools.find((tool) => tool.name === "ReadTickets");
report("toolSchema", readTickets.input_schema);
report("finalAnswerSchema", recorded[0].tools.find((tool) => tool.name === "noxid_final_answer").input_schema);
done();
"#,
        r#"{"agents.Support.run": true}"#,
        &[],
    );
    assert_success(&output, "run the registry-equality probe");
    let log = stdout(&output);
    assert_eq!(probe(&log, "registry"), r#"["ReadTickets"]"#);
    assert_eq!(
        probe(&log, "offered"),
        r#"["ReadTickets","noxid_final_answer"]"#,
        "the provider-visible tool list is the manifest registry plus the \
         compiler-owned final-answer tool, and nothing else: {log}"
    );
    let deployment = probe(&log, "deploymentEndpoints");
    assert!(
        deployment.contains("RefundBilling") && deployment.contains("OpenStatus"),
        "the deployment really does declare the endpoints the registry subtracts: {deployment}"
    );
    assert_eq!(
        probe(&log, "toolSchema"),
        r#"{"type":"object","properties":{"customer":{"type":"string"}},"required":["customer"],"additionalProperties":false}"#,
        "the tool schema describes the endpoint's declared inputs exactly"
    );
    assert_eq!(
        probe(&log, "finalAnswerSchema"),
        r#"{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false}"#,
        "the final-answer tool describes the agent's declared output type"
    );
}

/// A model that never answers is bounded twice over: `maxTurns` ends the run
/// with `AGENT_MAX_TURNS`, and the WO-18 endpoint deadline ends a single
/// wedged provider call with `AGENT_TIMEOUT`.
#[test]
fn max_turns_bounds_a_runaway_loop() {
    let fixture = Fixture::new("maxturns", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "maxturns",
        r#"
for (let index = 0; index < 12; index += 1) expect(toolTurn("ReadTickets", { customer: String(index) }, `toolu_${index}`));
const run = await post("/_noxid/agents/Support/runs", { input: { prompt: "loop forever" } });
report("tags", tags(run.text));
report("failure", frames(run.text).at(-1).data.value);
report("providerCalls", recorded.length);
const keys = await storage("agent_runs").list("");
const record = await storage("agent_runs").get(keys[0]);
report("persistedState", record.state);
report("declaredCeiling", 4);
done();
"#,
        r#"{"agents.Support.run": true, "tickets.read": true}"#,
        &[],
    );
    assert_success(&output, "run the maxTurns probe");
    let log = stdout(&output);
    assert_eq!(
        probe(&log, "tags"),
        r#"["Started","ToolStarted","ToolCompleted","ToolStarted","ToolCompleted","ToolStarted","ToolCompleted","ToolStarted","ToolCompleted","Failed"]"#
    );
    let failure = probe(&log, "failure");
    assert!(failure.contains("\"code\":\"AGENT_MAX_TURNS\""), "{log}");
    assert!(failure.contains("ceiling of 4 turns"), "{log}");
    assert_eq!(
        probe(&log, "providerCalls"),
        "4",
        "the declared ceiling is a hard stop on provider calls: {log}"
    );
    assert_eq!(probe(&log, "persistedState"), "\"Failed\"");
}

/// The run's other bound. This test waits out the real WO-18 endpoint
/// deadline (`DEFAULT_ENDPOINT_TIMEOUT_MS`, 30 s), because that deadline is
/// the contract: an agent declaration carries no timeout clause, so a run gets
/// the same deadline every generated endpoint gets.
#[test]
fn the_wo18_deadline_bounds_a_wedged_model_call() {
    let fixture = Fixture::new("timeout", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "timeout",
        r#"
report("declaredTimeoutMs", JSON.parse(process.env.PROBE_EXPECTED_TIMEOUT));
holdOpen = true;   // the provider accepts the request and never answers
const started = Date.now();
const run = await post("/_noxid/agents/Support/runs", { input: { prompt: "hang" } });
report("elapsedMs", Date.now() - started);
report("tags", tags(run.text));
report("failure", frames(run.text).at(-1).data.value);
const keys = await storage("agent_runs").list("");
report("persistedState", (await storage("agent_runs").get(keys[0])).state);
done();
"#,
        r#"{"agents.Support.run": true}"#,
        &[("PROBE_EXPECTED_TIMEOUT", "30000")],
    );
    assert_success(&output, "run the deadline probe");
    let log = stdout(&output);
    let handler = fixture.read("dist/server/handler.js");
    assert!(
        handler.contains("timeoutMs: 30000"),
        "the run endpoint carries the WO-18 default deadline"
    );
    assert_eq!(probe(&log, "tags"), r#"["Started","Failed"]"#);
    assert!(
        probe(&log, "failure").contains("\"code\":\"AGENT_TIMEOUT\""),
        "{log}"
    );
    let elapsed: u64 = probe(&log, "elapsedMs").parse().expect("elapsed ms");
    assert!(
        (29_000..60_000).contains(&elapsed),
        "the run must end at its declared deadline, not before or long after: {elapsed} ms"
    );
    assert_eq!(probe(&log, "persistedState"), "\"Failed\"");
}

/// A client that disconnects stops the model call and the run, and the session
/// ends with `Cancelled` rather than hanging on a provider that never answers.
#[test]
fn cancellation_stops_the_model_call_the_run_and_the_session() {
    let fixture = Fixture::new("cancel", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "cancel",
        r#"
holdOpen = true;
const controller = new AbortController();
const response = await handler.fetch(new Request("http://noxid.test/_noxid/agents/Support/runs", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ input: { prompt: "hang" } }),
  signal: controller.signal,
}), { sessionId: "session-1" }, {});
const reader = response.body.getReader();
const first = await reader.read();
report("firstFrame", new TextDecoder().decode(first.value).includes("\"tag\":\"Started\""));
setTimeout(() => controller.abort("client left"), 50);
const rest = [];
for (;;) {
  const chunk = await reader.read();
  if (chunk.done) break;
  rest.push(new TextDecoder().decode(chunk.value));
}
report("afterCancel", tags(rest.join("")));
report("providerCalls", recorded.length);
const keys = await storage("agent_runs").list("");
report("persistedState", (await storage("agent_runs").get(keys[0])).state);
done();
"#,
        r#"{"agents.Support.run": true}"#,
        &[],
    );
    assert_success(&output, "run the cancellation probe");
    let log = stdout(&output);
    assert_eq!(probe(&log, "firstFrame"), "true");
    assert_eq!(probe(&log, "afterCancel"), r#"["Cancelled"]"#);
    assert_eq!(
        probe(&log, "providerCalls"),
        "1",
        "the wedged provider call is abandoned rather than retried: {log}"
    );
    assert_eq!(probe(&log, "persistedState"), "\"Cancelled\"");
}

/// The whole declared algebra, in order, across two sessions of one run:
/// `Started`, `Token`, `ToolStarted`, `ToolCompleted`, `PermissionRequired`,
/// `Paused`, `Completed`, `Failed`, and `Cancelled`.
#[test]
fn every_event_in_the_declared_algebra_is_emitted() {
    let fixture = Fixture::new("algebra", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "algebra",
        r#"
const seen = new Set();
function observe(text) { for (const tag of tags(text)) seen.add(tag); }

// Started + Token, then a Completed answer parsed from plain text.
expect(textTurn(JSON.stringify({ answer: "hello" })));
observe((await post("/_noxid/agents/Support/runs", { input: { prompt: "greet" } })).text);

// ToolStarted + ToolCompleted.
expect(toolTurn("ReadTickets", { customer: "42" }));
expect(toolTurn("noxid_final_answer", { answer: "found" }, "toolu_2"));
observe((await post("/_noxid/agents/Support/runs", { input: { prompt: "look up" } })).text);

// Failed, through an output that violates the declared type.
expect(toolTurn("noxid_final_answer", { answer: 7 }, "toolu_3"));
const invalid = await post("/_noxid/agents/Support/runs", { input: { prompt: "bad output" } });
observe(invalid.text);
report("outputInvalid", frames(invalid.text).at(-1).data.value.code);

// PermissionRequired + Paused, through a deferred capability.
process.env.PROBE_AUTHORIZER = JSON.stringify({ "agents.Support.run": true, "tickets.read": "defer" });
expect(toolTurn("ReadTickets", { customer: "9" }, "toolu_4"));
const paused = await post("/_noxid/agents/Support/runs", { input: { prompt: "needs approval" } });
observe(paused.text);
report("pausedRunId", frames(paused.text).at(-1).data.value);

// Cancelled.
holdOpen = true;
const controller = new AbortController();
const response = await handler.fetch(new Request("http://noxid.test/_noxid/agents/Support/runs", {
  method: "POST", headers: { "content-type": "application/json" },
  body: JSON.stringify({ input: { prompt: "hang" } }), signal: controller.signal,
}), { sessionId: "session-1" }, {});
const reader = response.body.getReader();
await reader.read();
setTimeout(() => controller.abort("client left"), 50);
const rest = [];
for (;;) { const chunk = await reader.read(); if (chunk.done) break; rest.push(new TextDecoder().decode(chunk.value)); }
observe(rest.join(""));

report("algebra", [...seen].sort());
done();
"#,
        r#"{"agents.Support.run": true, "tickets.read": true}"#,
        &[],
    );
    assert_success(&output, "run the event-algebra probe");
    let log = stdout(&output);
    assert_eq!(probe(&log, "outputInvalid"), "\"AGENT_OUTPUT_INVALID\"");
    assert_eq!(
        probe(&log, "algebra"),
        r#"["Cancelled","Completed","Failed","Paused","PermissionRequired","Started","Token","ToolCompleted","ToolStarted"]"#,
        "every declared event, compiler-owned and developer-declared, must be reachable"
    );
    assert!(
        probe(&log, "pausedRunId").len() >= 18,
        "the Paused event carries the run id the resume endpoint takes: {log}"
    );
}

/// The client half of the algebra: the emitted agent definition carries the
/// engine contract, `#stream session` receives `Paused(runId)`, and
/// `session.resume(runId)` continues the same session.
#[test]
fn the_client_session_handles_paused_and_resumes_by_run_id() {
    let fixture = Fixture::new("client", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    fixture.write(
        "dist/assets/client-probe.mjs",
        r#"import { Support } from "./Page.agents.js";
import { createOwner } from "./noxid-runtime.js";

const owner = createOwner();
let phase = 0;
const session = Support.create({ prompt: "hi" }, {
  owner,
  async invoke(input, api) {
    phase += 1;
    if (phase === 1) {
      api.emit("Token", "thinking");
      api.pause("run-01234567890123456789");
      return null;
    }
    console.log(`PROBE resumedWith ${JSON.stringify(api.resume)}`);
    return { answer: "done" };
  },
});
console.log(`PROBE engine ${JSON.stringify(Support.engine)}`);
await session.start();
console.log(`PROBE pausedStatus ${JSON.stringify(session.status.get())}`);
const runId = session.events.get().find((entry) => entry.event.tag === "Paused").event.value;
console.log(`PROBE pausedRunId ${JSON.stringify(runId)}`);
await session.resume(runId);
console.log(`PROBE resumedStatus ${JSON.stringify(session.status.get())}`);
console.log(`PROBE output ${JSON.stringify(session.output.get())}`);
try { await session.resume(runId); } catch (error) { console.log(`PROBE refused ${JSON.stringify(error.code)}`); }
"#,
    );
    let output = Command::new("node")
        .arg("client-probe.mjs")
        .current_dir(fixture.root.join("dist/assets"))
        .output()
        .expect("execute the client probe");
    assert_success(&output, "run the client session probe");
    let log = stdout(&output);
    let engine = probe(&log, "engine");
    assert!(engine.contains("\"agent\":\"Support\""), "{log}");
    assert!(
        engine.contains("\"resumePath\":\"/_noxid/agents/Support/runs/\""),
        "{log}"
    );
    assert!(
        engine.contains("\"resumeCapability\":\"agents.Support.resume\""),
        "{log}"
    );
    assert_eq!(probe(&log, "pausedStatus"), "\"Paused\"");
    assert_eq!(probe(&log, "pausedRunId"), "\"run-01234567890123456789\"");
    assert_eq!(probe(&log, "resumedWith"), "\"run-01234567890123456789\"");
    assert_eq!(probe(&log, "resumedStatus"), "\"Completed\"");
    assert_eq!(probe(&log, "output"), r#"{"answer":"done"}"#);
    assert_eq!(probe(&log, "refused"), "\"AGENT_NOT_PAUSED\"");
}

/// The spans the WO-25 kernel receives, and — the point — what they do not
/// carry. No prompt, no instruction text, no tool argument, no tool result.
#[test]
fn agent_spans_carry_identity_and_tokens_and_no_content() {
    let fixture = Fixture::new("spans", "fs");
    assert_success(&fixture.build(), "build the agent fixture");
    let output = fixture.run(
        "spans",
        r#"
expect(toolTurn("ReadTickets", { customer: "secret-customer-4242" }));
expect(toolTurn("noxid_final_answer", { answer: "confidential-answer-text" }, "toolu_2"));
await post("/_noxid/agents/Support/runs", { input: { prompt: "confidential-prompt-text" } });
done();
"#,
        r#"{"agents.Support.run": true, "tickets.read": true}"#,
        &[],
    );
    assert_success(&output, "run the spans probe");
    let log = stdout(&output);
    let spans = log
        .lines()
        .filter(|line| line.contains("\"event\":\"agent."))
        .collect::<Vec<_>>();
    assert!(
        spans
            .iter()
            .any(|line| line.contains("\"event\":\"agent.run\""))
            && spans
                .iter()
                .any(|line| line.contains("\"event\":\"agent.turn\""))
            && spans
                .iter()
                .any(|line| line.contains("\"event\":\"agent.tool\"")),
        "all three spans must reach the kernel:\n{log}"
    );
    let run_span = spans
        .iter()
        .find(|line| line.contains("\"event\":\"agent.run\""))
        .expect("agent.run span");
    assert!(run_span.contains("\"agent\":\"Support\""), "{run_span}");
    assert!(run_span.contains("\"agentRun\":\""), "{run_span}");
    assert!(run_span.contains("\"tokensInput\":"), "{run_span}");
    let tool_span = spans
        .iter()
        .find(|line| line.contains("\"event\":\"agent.tool\""))
        .expect("agent.tool span");
    assert!(
        tool_span.contains("\"toolEndpoint\":\"endpoint:ReadTickets@1\""),
        "{tool_span}"
    );
    for span in &spans {
        for secret in [
            "confidential-prompt-text",
            "confidential-answer-text",
            "secret-customer-4242",
            "support agent",
        ] {
            assert!(
                !span.contains(secret),
                "an agent span must never carry prompt, argument, or result content: {span}"
            );
        }
    }
}

// ---------------------------------------------------- the durable pause (pg)

struct ComposePostgres {
    file: PathBuf,
    project: String,
}

impl ComposePostgres {
    fn start() -> Option<Self> {
        for probe in [vec!["info"], vec!["compose", "version"]] {
            if !Command::new("docker")
                .args(&probe)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .is_ok_and(|status| status.success())
            {
                eprintln!(
                    "WO-31 durable agent pause: SKIP (Docker unavailable; the restart-and-resume path was not exercised)"
                );
                return None;
            }
        }
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock after epoch")
            .as_nanos();
        let postgres = Self {
            file: Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/wo19-postgres/compose.yaml"),
            project: format!("noxidwo31{}{}", std::process::id(), nonce),
        };
        let output = postgres
            .command()
            .args(["up", "--detach"])
            .output()
            .expect("start agent-run Postgres");
        assert!(
            output.status.success(),
            "Docker was available but Postgres failed to start: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        for _ in 0..480 {
            if postgres
                .command()
                .args([
                    "exec",
                    "--no-TTY",
                    "postgres",
                    "pg_isready",
                    "-U",
                    "noxid_test",
                    "-d",
                    "noxid_test",
                ])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .expect("probe agent-run Postgres")
                .success()
            {
                return Some(postgres);
            }
            thread::sleep(Duration::from_millis(250));
        }
        panic!("agent-run Postgres did not become ready within 120 seconds");
    }

    fn command(&self) -> Command {
        let mut command = Command::new("docker");
        command
            .args(["compose", "-f"])
            .arg(&self.file)
            .args(["--project-name", &self.project]);
        command
    }

    fn database_url(&self) -> String {
        let output = self
            .command()
            .args(["port", "postgres", "5432"])
            .output()
            .expect("resolve agent-run Postgres port");
        assert!(output.status.success());
        let mapping = String::from_utf8(output.stdout).expect("UTF-8 port mapping");
        let port = mapping
            .trim()
            .rsplit_once(':')
            .map(|(_, port)| port)
            .expect("mapped port");
        format!("postgres://noxid_test:noxid_test@127.0.0.1:{port}/noxid_test")
    }
}

impl Drop for ComposePostgres {
    fn drop(&mut self) {
        let _ = self
            .command()
            .args(["down", "--volumes", "--remove-orphans"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// The pause is durable, so it outlives the process that created it: one node
/// process pauses the run and exits, a second process — a fresh server — is
/// refused the resume without the capability, reconciles the store on the
/// queue worker's startup, and then resumes the same run to completion.
#[test]
fn a_permission_pause_survives_a_restart_and_resumes_through_the_endpoint() {
    let Some(postgres) = ComposePostgres::start() else {
        return;
    };
    let database_url = postgres.database_url();
    let fixture = Fixture::new("pause", "postgres").with_queue();
    if !fixture.link_postgres_driver() {
        return;
    }
    assert_success(&fixture.build(), "build the postgres agent fixture");

    // Process one: the deferred capability pauses the run, and the process
    // exits without ever resuming it.
    let pause = fixture.run(
        "pause",
        r#"
expect(toolTurn("ReadTickets", { customer: "42" }));
const run = await post("/_noxid/agents/Support/runs", { input: { prompt: "needs approval" } });
report("tags", tags(run.text));
report("permission", frames(run.text).find((frame) => frame.data.tag === "PermissionRequired").data.value);
report("runId", frames(run.text).at(-1).data.value);
await exitProbe();
"#,
        r#"{"agents.Support.run": true, "tickets.read": "defer"}"#,
        &[("DATABASE_URL", &database_url)],
    );
    assert_success(&pause, "run the pause probe");
    let pause_log = stdout(&pause);
    assert_eq!(
        probe(&pause_log, "tags"),
        r#"["Started","PermissionRequired","Paused"]"#
    );
    assert!(
        probe(&pause_log, "permission").contains("\"capability\":\"tickets.read\""),
        "{pause_log}"
    );
    let run_id = probe(&pause_log, "runId");
    let run_id = run_id.trim_matches('"').to_string();

    // Process two: a fresh server. The run survived only because it is a
    // durable record — nothing about the paused turn lives in a process.
    let resume = fixture.run(
        "resume",
        &format!(
            r#"
const runId = {run_id:?};

// The queue worker reconciles the store on startup: paused runs stay
// resumable, and any run left `Running` by the previous process is failed.
const worker = handler.startQueueWorker({{ queue: "AuditTrail", pollIntervalMs: 25 }});
await new Promise((resolve) => setTimeout(resolve, 300));
await worker.stop();

const beforeResume = await storage("agent_runs").get(`Support:${{runId}}`);
report("survivedState", beforeResume.state);
report("survivedPending", beforeResume.pending.endpoint);
report("survivedTurns", beforeResume.turns.length);

// Without the resume capability the endpoint refuses before the run is
// touched at all.
process.env.PROBE_AUTHORIZER = JSON.stringify({{ "agents.Support.resume": false, "tickets.read": true }});
const refused = await post(`/_noxid/agents/Support/runs/${{runId}}/resume`, {{}});
report("refusedStatus", refused.status);
report("refusedCode", JSON.parse(refused.text).error.code);
report("stateAfterRefusal", (await storage("agent_runs").get(`Support:${{runId}}`)).state);

// With the resume capability but the deferred capability still deferred, the
// run stays paused: approval is re-checked with the resuming principal.
process.env.PROBE_AUTHORIZER = JSON.stringify({{ "agents.Support.resume": true, "tickets.read": "defer" }});
const stillDeferred = await post(`/_noxid/agents/Support/runs/${{runId}}/resume`, {{}});
report("stillDeferredStatus", stillDeferred.status);
report("stillDeferredCode", JSON.parse(stillDeferred.text).error.code);

// With both, the approved call is the first work the resumed run does.
process.env.PROBE_AUTHORIZER = JSON.stringify({{ "agents.Support.resume": true, "tickets.read": true }});
expect(toolTurn("noxid_final_answer", {{ answer: "Ticket T-42 is a password reset" }}, "toolu_2"));
const resumed = await post(`/_noxid/agents/Support/runs/${{runId}}/resume`, {{}});
report("resumedTags", tags(resumed.text));
report("resumedAnswer", frames(resumed.text).at(-1).data.value);
report("providerCallsAfterResume", recorded.length);
report("finalState", (await storage("agent_runs").get(`Support:${{runId}}`)).state);

// A finished run does not resume twice.
const again = await post(`/_noxid/agents/Support/runs/${{runId}}/resume`, {{}});
report("againStatus", again.status);
report("againCode", JSON.parse(again.text).error.code);
await exitProbe();
"#
        ),
        r#"{"agents.Support.resume": true, "tickets.read": true}"#,
        &[("DATABASE_URL", &database_url)],
    );
    assert_success(&resume, "run the restart-and-resume probe");
    let log = stdout(&resume);
    assert_eq!(probe(&log, "survivedState"), "\"Paused\"");
    assert_eq!(probe(&log, "survivedPending"), "\"ReadTickets\"");
    assert_eq!(probe(&log, "survivedTurns"), "1");
    assert_eq!(probe(&log, "refusedStatus"), "403");
    assert_eq!(probe(&log, "refusedCode"), "\"ENDPOINT_CAPABILITY_DENIED\"");
    assert_eq!(
        probe(&log, "stateAfterRefusal"),
        "\"Paused\"",
        "a refused resume must leave the run exactly as it was"
    );
    assert_eq!(probe(&log, "stillDeferredStatus"), "403");
    assert_eq!(
        probe(&log, "stillDeferredCode"),
        "\"AGENT_PERMISSION_DENIED\""
    );
    assert_eq!(
        probe(&log, "resumedTags"),
        r#"["Started","ToolStarted","ToolCompleted","Completed"]"#
    );
    assert_eq!(
        probe(&log, "resumedAnswer"),
        r#"{"answer":"Ticket T-42 is a password reset"}"#
    );
    assert_eq!(
        probe(&log, "providerCallsAfterResume"),
        "1",
        "the resumed run replays the approved call, then asks the model once: {log}"
    );
    assert_eq!(probe(&log, "finalState"), "\"Completed\"");
    assert_eq!(probe(&log, "againStatus"), "409");
    assert_eq!(probe(&log, "againCode"), "\"AGENT_RUN_NOT_PAUSED\"");
}

// ------------------------------------------------ the adapted front door

/// Checkpoint-3 security read F3. Every probe above drives the emitted
/// handler's `fetch` export directly, which is exactly why the gap survived:
/// the adapter front doors forwarded only `.../runs/<id>/resume`, so
/// `POST /_noxid/agents/<name>/runs` fell through to the SPA document and
/// WO-31's whole runtime surface was unreachable on a deployed build. The
/// security read measured it: `runs/<id>/resume` reached the engine with a
/// structured 404, `runs` answered `200 text/html`.
///
/// This driver runs inside the adapted deployment: it starts the scripted
/// Anthropic sink, spawns `node server.mjs` against it, and drives a whole run
/// through the real front door. A second server, started with an authorizer
/// that denies the agent's `run` capability, holds the refusal open.
const ADAPTED_RUN_DOOR_DRIVER: &str = r##"import http from "node:http";
import net from "node:net";
import { spawn } from "node:child_process";

const sse = (events) => events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("");
const textTurn = (text) => sse([
  { type: "message_start", message: { usage: { input_tokens: 11 } } },
  { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  ...[...text].map((character) => ({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: character } })),
  { type: "content_block_stop", index: 0 },
  { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
]);

const scripted = [textTurn(JSON.stringify({ answer: "adapted" }))];
let providerRequests = 0;
const sink = http.createServer((request, response) => {
  request.resume();
  request.on("end", () => {
    providerRequests += 1;
    const next = scripted.shift();
    if (next === undefined) {
      response.writeHead(500, { "content-type": "application/json" });
      response.end(JSON.stringify({ error: { type: "sink_unscripted", code: "sink_unscripted" } }));
      return;
    }
    response.writeHead(200, { "content-type": "text/event-stream" });
    response.end(next);
  });
});
await new Promise((resolve) => sink.listen(0, "127.0.0.1", resolve));
const gateway = `http://127.0.0.1:${sink.address().port}`;

const freePort = () => new Promise((resolve, reject) => {
  const probe = net.createServer();
  probe.on("error", reject);
  probe.listen(0, "127.0.0.1", () => {
    const chosen = probe.address().port;
    probe.close(() => resolve(chosen));
  });
});

const children = [];
// Only ever the children this driver spawned.
const stopAll = () => { for (const child of children) { try { child.kill("SIGKILL"); } catch {} } };
process.on("exit", stopAll);

const start = async (authorizer) => {
  const port = await freePort();
  const child = spawn(process.execPath, ["server.mjs"], {
    cwd: process.cwd(),
    env: {
      ...process.env,
      PORT: String(port),
      MODEL_GATEWAY_URL: gateway,
      ANTHROPIC_API_KEY: "wo31-adapted-key",
      PROBE_AUTHORIZER: authorizer,
    },
    stdio: "ignore",
  });
  children.push(child);
  for (let attempt = 0; attempt < 300; attempt += 1) {
    try {
      const response = await fetch(`http://127.0.0.1:${port}/`);
      await response.arrayBuffer();
      if (response.status === 200) return port;
    } catch {}
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  throw new Error("the adapted server never served its shell");
};

const post = async (port, path, body) => {
  const response = await fetch(`http://127.0.0.1:${port}${path}`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body ?? {}),
  });
  return { status: response.status, contentType: response.headers.get("content-type") ?? "", text: await response.text() };
};

function frames(text) {
  const out = [];
  for (const block of text.split("\n\n")) {
    if (block.trim().length === 0) continue;
    const lines = block.split("\n");
    const event = lines.find((line) => line.startsWith("event: "))?.slice(7) ?? "message";
    const data = lines.filter((line) => line.startsWith("data: ")).map((line) => line.slice(6)).join("\n");
    out.push({ event, data: JSON.parse(data) });
  }
  return out;
}
const tags = (text) => frames(text).map((frame) => frame.event === "message" ? frame.data.tag : `!${frame.data.error.code}`);
const report = (name, value) => console.log(`PROBE ${name} ${JSON.stringify(value)}`);
const code = (text) => { try { return JSON.parse(text)?.error?.code ?? null; } catch { return null; } };

const allowed = await start('{"agents.Support.run": true, "agents.Support.resume": true, "tickets.read": true}');
const run = await post(allowed, "/_noxid/agents/Support/runs", { input: { prompt: "look up 42" } });
report("run-status", run.status);
report("run-content-type", run.contentType);
const runTags = run.contentType.includes("text/event-stream") ? tags(run.text) : [run.text.slice(0, 120)];
report("run-tags", [runTags[0] ?? null, runTags.at(-1) ?? null]);
report("run-token-events", runTags.filter((tag) => tag === "Token").length > 0);
report("run-completed", run.contentType.includes("text/event-stream") ? (frames(run.text).at(-1)?.data?.value ?? null) : null);
report("provider-requests", providerRequests);

// The door this build already forwarded, unchanged: it still reaches the
// engine and still answers structurally.
const resume = await post(allowed, "/_noxid/agents/Support/runs/aaaaaaaaaaaaaaaa/resume", {});
report("resume-status", resume.status);
report("resume-code", code(resume.text));

// A path that is not a run door must still fall through to the document.
const shell = await fetch(`http://127.0.0.1:${allowed}/_noxid/agents/Support/runs/aaaaaaaaaaaaaaaa`, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: "{}",
});
await shell.arrayBuffer();
report("not-a-door-status", shell.status);

const denied = await start('{"agents.Support.run": false}');
const refused = await post(denied, "/_noxid/agents/Support/runs", { input: { prompt: "look up 42" } });
report("denied-status", refused.status);
report("denied-content-type", refused.contentType);
report("denied-code", code(refused.text));
report("provider-requests-after-refusal", providerRequests);

stopAll();
sink.close();
await new Promise((resolve) => process.stdout.write("\n", resolve));
process.exit(0);
"##;

#[test]
fn a_run_starts_through_the_adapted_front_door_and_the_door_enforces_the_run_capability() {
    let fixture = Fixture::new("adapted-run-door", "fs");
    let adapted = fixture.adapt("deploy");
    assert_success(&adapted, "adapt the agent fixture for node");
    fixture.write("deploy/driver.mjs", ADAPTED_RUN_DOOR_DRIVER);

    let driven = Command::new("node")
        .arg("driver.mjs")
        .current_dir(fixture.root.join("deploy"))
        .output()
        .expect("drive the adapted front door");
    let log = stdout(&driven);
    assert!(
        driven.status.success(),
        "{log}\nstderr:\n{}",
        String::from_utf8_lossy(&driven.stderr)
    );

    // Before this fix the run-start door answered `200` with the SPA document
    // and the scripted provider was never called.
    assert_eq!(probe(&log, "run-status"), "200", "{log}");
    assert!(
        probe(&log, "run-content-type").contains("text/event-stream"),
        "the run start did not reach the engine; it fell through to the document:\n{log}"
    );
    assert_eq!(
        probe(&log, "run-tags"),
        r#"["Started","Completed"]"#,
        "{log}"
    );
    assert_eq!(
        probe(&log, "run-completed"),
        r#"{"answer":"adapted"}"#,
        "{log}"
    );
    assert_eq!(
        probe(&log, "provider-requests"),
        "1",
        "the scripted provider was never reached, so the run did not execute:\n{log}"
    );

    // The door that already worked still works, and a path that is not a run
    // door is still not forwarded.
    assert_eq!(probe(&log, "resume-status"), "404", "{log}");
    assert_eq!(
        probe(&log, "resume-code"),
        "\"AGENT_RUN_NOT_FOUND\"",
        "{log}"
    );
    assert_eq!(probe(&log, "not-a-door-status"), "200", "{log}");

    // The widened door is not an open door: the agent's declared `run`
    // capability is enforced at the front door, before the model is called.
    assert_eq!(probe(&log, "denied-status"), "403", "{log}");
    assert!(
        probe(&log, "denied-content-type").contains("application/json"),
        "{log}"
    );
    assert_eq!(
        probe(&log, "denied-code"),
        "\"ENDPOINT_CAPABILITY_DENIED\"",
        "{log}"
    );
    assert_eq!(
        probe(&log, "provider-requests-after-refusal"),
        "1",
        "a refused run still called the model:\n{log}"
    );
}