noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
use std::fs;
use std::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-wo24-qa4-{label}-{}-{ordinal}",
            std::process::id()
        ));
        fs::create_dir_all(root.join("server/queues")).expect("create queue fixture");
        fs::write(
            root.join("Noxid.toml"),
            "[app]\ntitle = \"WO-24 QA round 4\"\n",
        )
        .expect("write project manifest");
        fs::write(root.join("package.json"), "{\"type\":\"module\"}\n")
            .expect("write ESM package marker");
        fs::write(
            root.join("server/host.js"),
            "export const queues = Object.freeze({});\n",
        )
        .expect("write inert host");
        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 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 queue fixture")
    }

    fn run_node(&self, name: &str, source: &str) -> Output {
        self.write(&format!("dist/{name}.mjs"), source);
        Command::new("node")
            .arg(format!("{name}.mjs"))
            .current_dir(self.root.join("dist"))
            .env_remove("DATABASE_URL")
            .output()
            .expect("execute generated queue runtime")
    }

    fn run_node_with_database(&self, name: &str, source: &str) -> Output {
        self.write(&format!("dist/{name}.mjs"), source);
        Command::new("node")
            .arg(format!("{name}.mjs"))
            .current_dir(self.root.join("dist"))
            .env("DATABASE_URL", "postgres://qa.invalid/noxid")
            .output()
            .expect("execute generated queue runtime with fake database")
    }
}

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

fn output_text(output: &Output) -> String {
    format!(
        "stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

fn assert_success(output: &Output, context: &str) {
    assert!(
        output.status.success(),
        "{context}:\n{}",
        output_text(output)
    );
}

fn code_of_enqueue(source: &str) -> String {
    format!(
        r#"import {{ enqueue }} from "./server/handler.js";
async function code(payload) {{
  try {{ await enqueue("Probe", payload); }} catch (error) {{ return error?.code ?? error?.name; }}
  return null;
}}
{source}
"#
    )
}

#[test]
fn qa_round4_tagged_result_container_is_closed_descriptor_safe_and_branch_complete() {
    let fixture = Fixture::new("tagged-result-container");
    fixture.write(
        "server/queues/Probe.nox",
        r#"type Receipt { id: String at: Date }
type Failure { reason: String }
queue Probe {
    payload { outcome: Result<Receipt, Failure> }
    retry: 1
    backoff: 1s
}
"#,
    );
    assert_success(&fixture.build(), "build tagged Result fixture");

    let node = fixture.run_node(
        "tagged-result-container",
        &code_of_enqueue(
            r#"let reads = 0;
const tagAccessor = { value: { id: "r", at: "2028-02-29T12:00:00Z" } };
Object.defineProperty(tagAccessor, "tag", { enumerable: true, get() { reads += 1; return "Ok"; } });
const valueAccessor = { tag: "Err" };
Object.defineProperty(valueAccessor, "value", { enumerable: true, get() { reads += 1; return { reason: "closed" }; } });
const inherited = Object.create({ tag: "Ok", value: { id: "r", at: "2028-02-29T12:00:00Z" } });
const hidden = { tag: "Err", value: { reason: "closed" } };
Object.defineProperty(hidden, "authority", { enumerable: false, value: true });
const cases = [
  ["valid Ok", { tag: "Ok", value: { id: "r", at: "2028-02-29T12:00:00Z" } }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["valid Err", { tag: "Err", value: { reason: "closed" } }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["tag accessor", tagAccessor, "QUEUE_PAYLOAD_TYPE"],
  ["value accessor", valueAccessor, "QUEUE_PAYLOAD_TYPE"],
  ["inherited pair", inherited, "QUEUE_PAYLOAD_TYPE"],
  ["extra enumerable", { tag: "Err", value: { reason: "closed" }, retry: true }, "QUEUE_PAYLOAD_TYPE"],
  ["extra hidden", hidden, "QUEUE_PAYLOAD_TYPE"],
];
const failures = [];
for (const [label, outcome, expected] of cases) {
  const observed = await code({ outcome });
  if (observed !== expected) failures.push(`${label}: expected ${expected}, saw ${observed}`);
}
if (reads !== 0) failures.push(`Result accessors executed ${reads} time(s)`);
if (failures.length > 0) throw new Error(failures.join("; "));"#,
        ),
    );
    assert_success(&node, "enforce the external tagged Result container");
}

#[test]
fn qa_round4_maps_reject_hostile_shapes_and_cycles_but_allow_shared_values() {
    let fixture = Fixture::new("map-graph-boundary");
    fixture.write(
        "server/queues/Probe.nox",
        r#"type TreeNode { label: String children: Array<TreeNode> }
queue Probe {
    payload { roots: Map<String, TreeNode> }
    retry: 0
    backoff: 1s
}
"#,
    );
    assert_success(&fixture.build(), "build recursive Map fixture");

    let node = fixture.run_node(
        "map-graph-boundary",
        &code_of_enqueue(
            r#"let reads = 0;
const shared = { label: "leaf", children: [] };
const cyclic = { label: "cycle", children: [] };
cyclic.children.push(cyclic);
const accessor = {};
Object.defineProperty(accessor, "root", { enumerable: true, get() { reads += 1; return shared; } });
const customPrototype = Object.create({ inherited: shared });
customPrototype.root = shared;
const symbol = { root: shared, [Symbol("authority")]: shared };
const cases = [
  ["shared finite values", { left: shared, right: shared }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["recursive value cycle", { root: cyclic }, "QUEUE_PAYLOAD_TYPE"],
  ["map accessor", accessor, "QUEUE_PAYLOAD_TYPE"],
  ["custom prototype", customPrototype, "QUEUE_PAYLOAD_TYPE"],
  ["symbol key", symbol, "QUEUE_PAYLOAD_TYPE"],
  ["proto key", JSON.parse('{"__proto__":{"label":"x","children":[]}}'), "QUEUE_PAYLOAD_TYPE"],
  ["constructor key", { constructor: shared }, "QUEUE_PAYLOAD_TYPE"],
  ["prototype key", { prototype: shared }, "QUEUE_PAYLOAD_TYPE"],
];
const failures = [];
for (const [label, roots, expected] of cases) {
  const observed = await code({ roots });
  if (observed !== expected) failures.push(`${label}: expected ${expected}, saw ${observed}`);
}
if (reads !== 0) failures.push(`Map accessor executed ${reads} time(s)`);
if (failures.length > 0) throw new Error(failures.join("; "));"#,
        ),
    );
    assert_success(&node, "enforce recursive Map ordinary-data semantics");
}

#[test]
fn qa_round4_sparse_optional_arrays_normalize_only_holes_not_effectful_or_extra_data() {
    let fixture = Fixture::new("sparse-optional-array");
    fixture.write(
        "server/queues/Probe.nox",
        "queue Probe { payload { values: Array<Optional<String>> } retry: 0 backoff: 1s }\n",
    );
    assert_success(&fixture.build(), "build sparse Optional array fixture");

    let node = fixture.run_node(
        "sparse-optional-array",
        &code_of_enqueue(
            r#"let reads = 0;
const sparse = new Array(3);
sparse[1] = "present";
const inherited = new Array(1);
const inheritedPrototype = {};
Object.defineProperty(inheritedPrototype, "0", { enumerable: true, get() { reads += 1; return "inherited"; } });
Object.setPrototypeOf(inherited, inheritedPrototype);
const accessor = new Array(1);
Object.defineProperty(accessor, "0", { enumerable: true, get() { reads += 1; return "effect"; } });
const hidden = [null];
Object.defineProperty(hidden, "authority", { enumerable: false, value: true });
const cases = [
  ["dense Optional values", [null, "present", undefined], "QUEUE_DATABASE_URL_REQUIRED"],
  ["sparse Optional values", sparse, "QUEUE_DATABASE_URL_REQUIRED"],
  ["inherited array index", inherited, "QUEUE_DATABASE_URL_REQUIRED"],
  ["indexed accessor", accessor, "QUEUE_PAYLOAD_TYPE"],
  ["extra hidden key", hidden, "QUEUE_PAYLOAD_TYPE"],
];
const failures = [];
for (const [label, values, expected] of cases) {
  const observed = await code({ values });
  if (observed !== expected) failures.push(`${label}: expected ${expected}, saw ${observed}`);
}
if (reads !== 0) failures.push(`array inherited/accessor data executed ${reads} time(s)`);
if (failures.length > 0) throw new Error(failures.join("; "));"#,
        ),
    );
    assert_success(
        &node,
        "normalize sparse Optional arrays without reading behavior",
    );
}

#[test]
fn qa_round4_dates_stay_strict_below_map_optional_result_and_named_wrappers() {
    let fixture = Fixture::new("deep-date-contract");
    fixture.write(
        "server/queues/Probe.nox",
        r#"type Window { at: Date }
queue Probe {
    payload { schedules: Map<String, Optional<Result<Window, Date>>> }
    retry: 0
    backoff: 1s
}
"#,
    );
    assert_success(&fixture.build(), "build deeply wrapped Date fixture");

    let node = fixture.run_node(
        "deep-date-contract",
        &code_of_enqueue(
            r#"const exact = "2000-02-29T23:59:59.999Z";
const cases = [
  ["valid branches", { ok: { tag: "Ok", value: { at: exact } }, err: { tag: "Err", value: exact }, none: null }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["non-leap century", { bad: { tag: "Ok", value: { at: "1900-02-29T00:00:00Z" } } }, "QUEUE_PAYLOAD_TYPE"],
  ["hour 24", { bad: { tag: "Err", value: "2000-02-29T24:00:00Z" } }, "QUEUE_PAYLOAD_TYPE"],
  ["timezone offset", { bad: { tag: "Ok", value: { at: "2000-02-29T23:59:59+00:00" } } }, "QUEUE_PAYLOAD_TYPE"],
  ["four fractional digits", { bad: { tag: "Err", value: "2000-02-29T23:59:59.0000Z" } }, "QUEUE_PAYLOAD_TYPE"],
  ["genuine Date object", { bad: { tag: "Ok", value: { at: new Date(exact) } } }, "QUEUE_PAYLOAD_TYPE"],
];
const failures = [];
for (const [label, schedules, expected] of cases) {
  const observed = await code({ schedules });
  if (observed !== expected) failures.push(`${label}: expected ${expected}, saw ${observed}`);
}
if (failures.length > 0) throw new Error(failures.join("; "));"#,
        ),
    );
    assert_success(
        &node,
        "enforce strict dates through every recursive wrapper",
    );
}

#[test]
fn qa_round4_enqueue_and_claim_map_the_same_nested_failure_to_phase_specific_codes() {
    let fixture = Fixture::new("phase-code-mapping");
    fixture.write(
        "server/queues/Probe.nox",
        r#"type Receipt { id: String }
queue Probe {
    payload { outcome: Result<Receipt, String> }
    retry: 0
    backoff: 1s
}
"#,
    );
    fixture.write(
        "server/host.js",
        r#"export const queues = Object.freeze({
  "queue:Probe": async (payload) => payload,
});
"#,
    );
    assert_success(&fixture.build(), "build phase-code fixture");
    fixture.write(
        "dist/node_modules/postgres/package.json",
        "{\"type\":\"module\",\"exports\":\"./index.js\"}\n",
    );
    fixture.write(
        "dist/node_modules/postgres/index.js",
        r#"export default function postgres() {
  const sql = async (strings) => {
    const query = strings.join("?");
    globalThis.__qaQueries.push(query);
    if (query.includes("SELECT id, queue, payload")) return [globalThis.__qaRows.shift()];
    return [];
  };
  sql.unsafe = async (query) => { globalThis.__qaQueries.push(query); return []; };
  sql.begin = async (callback) => callback(sql);
  sql.end = async () => {};
  sql.json = (value) => value;
  return sql;
}
"#,
    );

    let node = fixture.run_node_with_database(
        "phase-code-mapping",
        r#"globalThis.__qaQueries = [];
globalThis.__qaRows = [{
  id: "qa-drift", queue: "Probe", principal: null, attempts: 0,
  run_at: new Date("2026-08-30T12:00:00Z"),
  payload: { outcome: { tag: "Ok", value: { id: 7 } } },
}];
const { enqueue, workQueueOnce, closeQueueDatabase } = await import("./server/handler.js");
let enqueueFailure;
try { await enqueue("Probe", { outcome: { tag: "Ok", value: { id: 7 } } }); }
catch (error) { enqueueFailure = error; }
if (enqueueFailure?.code !== "QUEUE_PAYLOAD_TYPE") throw new Error(`enqueue mapped nested failure to ${enqueueFailure?.code}`);
if (globalThis.__qaQueries.some((query) => query.includes("INSERT INTO _noxid_jobs"))) throw new Error("invalid enqueue reached persistence");
let claimFailure;
try { await workQueueOnce({ queue: "Probe", worker: "qa", now: "2026-08-30T12:00:00Z" }); }
catch (error) { claimFailure = error; }
if (claimFailure?.code !== "QUEUE_PAYLOAD_DRIFT" || claimFailure?.jobId !== "qa-drift") throw new Error(`claim mapped nested failure incorrectly: ${claimFailure?.code}/${claimFailure?.jobId}`);
const driftUpdates = globalThis.__qaQueries.filter((query) => query.includes("last_error = 'QUEUE_PAYLOAD_DRIFT'"));
if (driftUpdates.length !== 1) throw new Error(`claim drift update count changed: ${driftUpdates.length}`);
if (globalThis.__qaQueries.some((query) => query.includes("state = 'running'"))) throw new Error("drifted claim entered running state");
await closeQueueDatabase();
"#,
    );
    assert_success(&node, "preserve enqueue/claim phase-specific failure codes");
}

#[test]
fn qa_round4_worker_clock_is_ordinary_data_and_a_strict_utc_instant() {
    let fixture = Fixture::new("worker-clock-boundary");
    fixture.write(
        "server/queues/Probe.nox",
        "queue Probe { payload {} retry: 0 backoff: 1s }\n",
    );
    assert_success(&fixture.build(), "build worker clock fixture");

    let node = fixture.run_node(
        "worker-clock-boundary",
        r#"import { workQueueOnce } from "./server/handler.js";
async function code(options) {
  try { await workQueueOnce(options); } catch (error) { return error?.code ?? error?.name; }
  return null;
}
let reads = 0;
const accessor = { queue: "Probe", worker: "qa" };
Object.defineProperty(accessor, "now", { enumerable: true, get() { reads += 1; return "2028-02-29T12:00:00Z"; } });
const inherited = Object.create({ now: "2028-02-29T12:00:00Z" });
inherited.queue = "Probe";
inherited.worker = "qa";
const cases = [
  ["valid leap instant", { queue: "Probe", worker: "qa", now: "2028-02-29T12:00:00.123Z" }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["genuine Date", { queue: "Probe", worker: "qa", now: new Date("2028-02-29T12:00:00Z") }, "QUEUE_DATABASE_URL_REQUIRED"],
  ["accessor", accessor, "QUEUE_CLOCK_INVALID"],
  ["inherited", inherited, "QUEUE_CLOCK_INVALID"],
  ["impossible day", { queue: "Probe", worker: "qa", now: "2026-02-31T12:00:00Z" }, "QUEUE_CLOCK_INVALID"],
  ["human date", { queue: "Probe", worker: "qa", now: "August 30, 2026 UTC" }, "QUEUE_CLOCK_INVALID"],
  ["offset", { queue: "Probe", worker: "qa", now: "2026-08-30T12:00:00+00:00" }, "QUEUE_CLOCK_INVALID"],
  ["numeric", { queue: "Probe", worker: "qa", now: 0 }, "QUEUE_CLOCK_INVALID"],
];
const failures = [];
for (const [label, options, expected] of cases) {
  const observed = await code(options);
  if (observed !== expected) failures.push(`${label}: expected ${expected}, saw ${observed}`);
}
if (reads !== 0) failures.push(`worker clock accessor executed ${reads} time(s)`);
if (failures.length > 0) throw new Error(failures.join("; "));
"#,
    );
    assert_success(&node, "enforce the worker stub-clock boundary");
}