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
//! WO-45 phase 3 (ADR 0137) — project-level contracts.
//!
//! These exercise what a single-source compile cannot: the scoped-column seam
//! against a real drizzle schema, the emitted server handler and its erasure
//! to the unchanged runtime shape, the graph audit query that lists every
//! site where a principal leaves its type, and the repository's own website
//! dogfood build.

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

static COUNTER: AtomicUsize = AtomicUsize::new(0);

struct Fixture {
    root: PathBuf,
}

impl Fixture {
    fn new(tag: &str) -> Self {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock after epoch")
            .as_nanos();
        let ordinal = COUNTER.fetch_add(1, Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "noxid-wo45-phase3-{tag}-{}-{nonce}-{ordinal}",
            std::process::id()
        ));
        fs::create_dir_all(&root).expect("create WO-45 phase-3 fixture");
        fs::write(
            root.join("Noxid.toml"),
            "[app]\ntitle = \"WO-45 phase 3\"\n\n[server]\nruntime = \"node\"\n",
        )
        .expect("write project config");
        fs::write(root.join("package.json"), "{\"type\":\"module\"}\n")
            .expect("write Node module marker");
        let fixture = Self { root };
        fixture.write(
            "src/routes/+page.nox",
            "component Page {\n    view { <p>ok</p> }\n}\n",
        );
        fixture
    }

    fn path(&self, relative: &str) -> PathBuf {
        self.root.join(relative)
    }

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

    /// Copy the repository's real drizzle adapter and its two static imports
    /// so `server/utils/schema.ts` resolves exactly as it does in a real
    /// project. The adapter itself is never edited by this order.
    fn install_drizzle_adapter(&self) {
        let repository = repository_root();
        for relative in [
            "plugins/drizzle-orm/adapter.js",
            "tools/database-url.mjs",
            "tools/node-sqlite.mjs",
        ] {
            let source = repository.join(relative);
            if !source.is_file() {
                continue;
            }
            let target = self.path(relative);
            fs::create_dir_all(target.parent().expect("adapter parent"))
                .expect("create adapter directory");
            fs::copy(&source, &target).expect("copy adapter source");
        }
    }

    fn noxid(&self, arguments: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_noxid"))
            .args(arguments)
            .output()
            .expect("run noxid CLI")
    }

    fn build(&self) -> Output {
        self.noxid(&[
            "build",
            self.root.to_str().expect("UTF-8 fixture path"),
            "--out-dir",
            self.path("dist").to_str().expect("UTF-8 output path"),
        ])
    }

    fn impact(&self, target: &str) -> Output {
        self.noxid(&[
            "impact",
            self.root.to_str().expect("UTF-8 fixture path"),
            target,
        ])
    }

    fn read_dist(&self, relative: &str) -> String {
        fs::read_to_string(self.path(&format!("dist/{relative}")))
            .unwrap_or_else(|error| panic!("read dist/{relative}: {error}"))
    }
}

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

fn repository_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}

fn output_text(output: &Output) -> String {
    format!(
        "{}{}",
        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)
    );
}

const SCOPED_SCHEMA: &str = r#"import { pgTable, text } from "drizzle-orm/pg-core";
import { scopedTable } from "../../plugins/drizzle-orm/adapter.js";

export const notes = scopedTable(pgTable("notes", {
  userId: text("user_id").notNull(),
  body: text("body").notNull(),
}), "user_id");
"#;

const SCOPED_HOST: &str = r#"import { notes } from "./utils/schema.js";

export const endpoints = Object.freeze({
  "endpoint:SaveNote@1": async () => notes !== undefined,
});
"#;

fn scoped_fixture(tag: &str, note_body: &str) -> Fixture {
    let fixture = Fixture::new(tag);
    fixture.install_drizzle_adapter();
    fixture.write("server/utils/schema.ts", SCOPED_SCHEMA);
    fixture.write("server/host.ts", SCOPED_HOST);
    fixture.write("server/api/notes.post.nox", note_body);
    fixture
}

#[test]
fn a_scoped_column_declared_as_a_string_fails_the_build() {
    let fixture = scoped_fixture(
        "scoped-string",
        "endpoint SaveNote {\n    version: 1\n    body {\n        userId: String\n        note: String\n    }\n    result: Boolean\n}\n",
    );
    let output = fixture.build();
    assert!(
        !output.status.success(),
        "a String scoped column must fail the build:\n{}",
        output_text(&output)
    );
    let text = output_text(&output);
    assert!(
        text.contains("error[SCOPED_COLUMN_REQUIRES_PRINCIPAL_ID]"),
        "{text}"
    );
    assert!(text.contains("`userId: String`"), "{text}");
    assert!(text.contains("scoped table `notes`"), "{text}");
    assert!(text.contains("PrincipalId"), "{text}");
    assert!(
        !fixture.path("dist").exists(),
        "the refusal must land before the first output-directory mutation"
    );
}

#[test]
fn a_scoped_column_typed_principal_id_builds_and_reaches_the_manifest() {
    let fixture = scoped_fixture(
        "scoped-typed",
        "endpoint SaveNote {\n    version: 1\n    body {\n        userId: PrincipalId\n        note: String\n    }\n    result: Boolean\n}\n",
    );
    assert_success(&fixture.build(), "build a PrincipalId-typed scoped column");

    let manifest = fixture.read_dist("server/security.manifest.json");
    assert!(
        manifest.contains(
            r#"{"table":"notes","policy":"scoped","principalColumn":"user_id","principalType":"PrincipalId"}"#
        ),
        "the security manifest must record the typed column:\n{manifest}"
    );

    // The wire representation is still the base String, and OpenAPI keeps the
    // semantic name so an agent reading the API sees the meaning.
    let openapi = fixture.read_dist("api.openapi.json");
    assert!(openapi.contains("\"T_PrincipalId\""), "{openapi}");
    assert!(
        openapi.contains("\"x-noxid-distinct-base\":\"String\"")
            || openapi.contains("\"x-noxid-distinct-base\": \"String\""),
        "{openapi}"
    );
}

const WHOAMI_ENDPOINT: &str = r#"endpoint Whoami {
    version: 1
    result: String

    handler {
        #match context.principal {
            System { return "system" }
            User(user) { return user.id.base() }
            Agent(actor) { return actor.id.base() }
        }
    }
}
"#;

#[test]
fn the_emitted_handler_erases_to_the_unchanged_runtime_principal_shape() {
    let fixture = Fixture::new("erasure");
    fixture.write("server/api/whoami.get.nox", WHOAMI_ENDPOINT);
    assert_success(&fixture.build(), "build a principal-matching handler");

    let handler = fixture.read_dist("server/handler.js");
    assert!(
        handler.contains("\"endpoint:Whoami@1\": async (args, context) =>"),
        "the emitted handler must bind the context the dispatcher already passes"
    );
    // ADR 0137 rule 5: the runtime value is unchanged, so the tag is `kind`,
    // `PrincipalId` is `scope`, and `AgentId` is `agent`.
    for fragment in [
        "= (context)[\"principal\"]",
        ".kind === \"system\"",
        ".kind === \"user\"",
        ".kind === \"agent\"",
        "\"id\": __noxidPrincipal_endpoint_Whoami_0.scope",
        "\"id\": __noxidPrincipal_endpoint_Whoami_0.agent",
        "\"actingFor\": __noxidPrincipal_endpoint_Whoami_0.scope",
    ] {
        assert!(
            handler.contains(fragment),
            "missing `{fragment}` in emitted handler:\n{handler}"
        );
    }
    // `PRINCIPAL_RUNTIME` itself is untouched by this stage.
    assert!(
        handler.contains("function __noxidPrincipal(middlewareContext, environment, agent = null)"),
        "the principal runtime must keep its existing shape"
    );
}

#[test]
fn the_graph_lists_every_site_where_a_principal_leaves_its_type() {
    let fixture = Fixture::new("graph");
    // Compiler-owned task and queue surfaces still route through the server
    // host module, even when every handler body is compiler-owned.
    fixture.write(
        "server/host.ts",
        "export const endpoints = Object.freeze({});\n",
    );
    fixture.write("server/api/whoami.get.nox", WHOAMI_ENDPOINT);
    fixture.write(
        "server/tasks/Audit.nox",
        r#"task Audit {
    schedule: "0 3 * * *"
    handler {
        #match context.principal {
            System { let who = "system" }
            User(user) { let who = user.id.base() }
            Agent(actor) { let who = actor.id.base() }
        }
    }
}
"#,
    );
    fixture.write(
        "server/queues/Reindex.nox",
        r#"queue Reindex {
    payload { key: String }
    retry: 1
    backoff: 1s
    handler {
        #match context.principal {
            System { let who = "system" }
            User(user) { let who = user.id.base() }
            Agent(actor) { let who = actor.id.base() }
        }
    }
}
"#,
    );
    // A typed-only handler that never unwraps is the negative control.
    fixture.write(
        "server/api/kind.get.nox",
        r#"endpoint PrincipalKind {
    version: 1
    result: String

    handler {
        #match context.principal {
            System { return "system" }
            User(user) { return "user" }
            Agent(actor) { return "agent" }
        }
    }
}
"#,
    );
    assert_success(&fixture.build(), "build the graph fixture");

    let output = fixture.impact("distinct-unwrap:PrincipalId");
    assert_success(&output, "query PrincipalId unwrap sites");
    let report = output_text(&output);
    for owner in [
        "endpoint:Whoami@1",
        "task:Audit",
        "queue:Reindex",
        "type:PrincipalId",
    ] {
        assert!(
            report.contains(owner),
            "`noxid impact distinct-unwrap:PrincipalId` must list {owner}:\n{report}"
        );
    }
    assert!(
        !report.contains("endpoint:PrincipalKind@1"),
        "a handler that never unwraps must not appear:\n{report}"
    );

    let agents = fixture.impact("distinct-unwrap:AgentId");
    assert_success(&agents, "query AgentId unwrap sites");
    let agents = output_text(&agents);
    for owner in ["endpoint:Whoami@1", "task:Audit", "queue:Reindex"] {
        assert!(agents.contains(owner), "{agents}");
    }
}

#[test]
fn the_principal_union_is_in_every_project_graph() {
    let fixture = Fixture::new("union");
    assert_success(&fixture.build(), "build a project with no principal use");
    let graph = fixture.read_dist("app.graph.json");
    for node in [
        "machine:compiler.Principal",
        "variant:compiler.Principal.System",
        "variant:compiler.Principal.User",
        "variant:compiler.Principal.Agent",
        "type:PrincipalId",
        "type:AgentId",
    ] {
        assert!(
            graph.contains(node),
            "the compiler-owned principal contract must be in every graph: {node}"
        );
    }
}

#[test]
fn the_website_learn_session_path_matches_on_the_principal() {
    let website = repository_root().join("website");
    let dogfood = fs::read_to_string(website.join("server/api/progress/learner.get.nox"))
        .expect("read the website principal dogfood");
    assert!(
        dogfood.contains("#match context.principal"),
        "the website dogfood must consume the principal:\n{dogfood}"
    );
    assert!(
        dogfood.contains("User(user)") && dogfood.contains("user.id.base()"),
        "the dogfood must match on User and unwrap explicitly:\n{dogfood}"
    );
    assert!(
        dogfood.contains("learnSession"),
        "the dogfood must sit on the Learn session path:\n{dogfood}"
    );

    let output_root = std::env::temp_dir().join(format!(
        "noxid-wo45-phase3-website-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    let output = Command::new(env!("CARGO_BIN_EXE_noxid"))
        .args([
            "build",
            website.to_str().expect("UTF-8 website path"),
            "--out-dir",
        ])
        .arg(&output_root)
        .output()
        .expect("build the website dogfood");
    let emitted = fs::read_to_string(output_root.join("server/actions.js")).unwrap_or_default();
    let _ = fs::remove_dir_all(&output_root);
    assert_success(&output, "build the website with the principal dogfood");
    assert!(
        emitted.contains("\"endpoint:LearnerIdentity@1\": async (args, context) =>"),
        "the website must emit the compiler-owned principal handler"
    );
}