mod ai;
mod app;
mod data_security;
mod db;
mod deployment;
mod farm;
mod mcp;
mod modules;
mod npm_admission;
mod project;
mod queue;
mod repair_transaction;
mod scaffold;
mod scenario_test;
mod sha256;
mod task;
use noxid_compiler_core::{devtools_javascript, runtime_javascript_for_imports};
use noxid_formatter::format_source;
use noxid_ir::SemanticId;
use noxid_semantic_ops::{Provenance, plan_project_rename, rename_symbol};
use noxid_source::{SourceFile, SourceId};
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Instant;
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("noxid: {message}");
ExitCode::FAILURE
}
}
}
fn run() -> Result<(), String> {
let mut args = env::args().skip(1);
let command = args.next().ok_or_else(usage)?;
if command == "--help" || command == "help" {
println!("{}", usage());
return Ok(());
}
if command == "lsp" {
if args.next().is_some() {
return Err("noxid lsp does not accept a source path".into());
}
return noxid_lsp::run_stdio();
}
if command == "port" {
return run_port_command(args);
}
if command == "db" {
return db::run(args);
}
if command == "task" {
return task::run(args);
}
if command == "queue" {
return queue::run(args);
}
if command == "describe" {
return ai::run_describe(args);
}
if command == "test" {
// `cd my-app && noxid test --gate` is the loop the scaffolded project
// teaches, so an omitted path means the current directory. Every other
// command still requires its input explicitly.
let mut input = PathBuf::from(".");
let mut gate = false;
let mut json_only = false;
let mut saw_input = false;
let mut seed = None;
let mut property = None;
while let Some(argument) = args.next() {
match argument.as_str() {
"--gate" => gate = true,
"--json" => json_only = true,
"--seed" => {
if seed.is_some() {
return Err("noxid test accepts --seed at most once".into());
}
let value = args
.next()
.ok_or("noxid test --seed requires an unsigned 64-bit integer")?;
seed = Some(value.parse::<u64>().map_err(|_| {
format!(
"noxid test --seed requires an unsigned 64-bit integer, got `{value}`"
)
})?);
}
"--property" => {
if property.is_some() {
return Err("noxid test accepts --property at most once".into());
}
property = Some(
args.next()
.ok_or("noxid test --property requires a semantic property ID")?,
);
}
other if other.starts_with("--") => {
return Err(format!("unknown test argument `{other}`\n{}", usage()));
}
other if saw_input => {
return Err(format!(
"noxid test accepts one file or project; received a second, `{other}`\n{}",
usage()
));
}
other => {
input = PathBuf::from(other);
saw_input = true;
}
}
}
if property.is_some() && seed.is_none() {
return Err(
"PROPERTY_REPLAY_SEED_REQUIRED: noxid test --property selects a seeded replay; add --seed <n>, or omit --property to run every declared property"
.into(),
);
}
if gate && seed.is_some() {
return Err(
"PROPERTY_REPLAY_GATE_CONFLICT: noxid test --gate enforces the 100-run property floor and cannot be combined with --seed; run the gate without --seed, then run --seed <n> with --property <semantic-id> separately to replay one case"
.into(),
);
}
// `test` resolves its own input because the path is optional, so it
// settles an interrupted `repair --safe` here rather than through the
// shared positional hook below.
if input.exists() {
repair_transaction::recover_before_read(&input)?;
}
return scenario_test::run(
&input,
scenario_test::Options { gate, json_only },
seed,
property.as_deref(),
);
}
if command == "vet" {
// `vet` takes no path: with a package name it vets an npm release, and
// with none it checks the vendored plugins of the project it is run in.
// It is dispatched before the shared positional input so `noxid vet
// --sync` is not read as a file name.
return npm_admission::run_vet_command(args);
}
let input = PathBuf::from(args.next().ok_or_else(usage)?);
// WO-51: `repair --inspect` is the remedy a refused journal's error names,
// so it is the one reader that must run *before* the recovery hook — the
// hook is exactly what it exists to unblock. It reads the journals and
// changes nothing unless `--discard` names one.
let repair_args: Vec<String> = if command == "repair" {
args.by_ref().collect()
} else {
Vec::new()
};
if repair_args.iter().any(|argument| argument == "--inspect") {
return repair_transaction::run_inspect(&input, &repair_args);
}
// An interrupted `repair --safe` is settled before this command reads a
// single source byte, so no entry point ever compiles a project that is
// part repaired and part original. The guard keeps the hook off the
// commands whose "input" is a name rather than a path (`example`,
// `agent-guide`, `vet`, `new`).
if input.exists() {
repair_transaction::recover_before_read(&input)?;
}
if command == "drift" {
let after = PathBuf::from(
args.next()
.ok_or("noxid drift requires before and after files or projects")?,
);
if args.next().is_some() {
return Err("noxid drift accepts exactly two files or projects".into());
}
if after.exists() {
// `drift` reads two projects; both are settled before either is read.
repair_transaction::recover_before_read(&after)?;
}
return ai::run_drift(&input, &after);
}
if command == "agent-guide" {
if args.next().is_some() {
return Err("noxid agent-guide accepts one topic".into());
}
let topic = input.to_string_lossy();
println!("{}", agent_guide(topic.as_ref())?);
return Ok(());
}
if command == "example" {
if args.next().is_some() {
return Err("noxid example accepts one example name".into());
}
println!("{}", compiler_example(input.to_string_lossy().as_ref())?);
return Ok(());
}
if command == "new" {
let mut render: Option<String> = None;
let mut template = "counter".to_string();
while let Some(argument) = args.next() {
match argument.as_str() {
"--render" => {
render = Some(args.next().ok_or("--render requires client or universal")?)
}
"--template" => {
template = args.next().ok_or_else(|| {
format!(
"--template requires one of {}",
scaffold::TEMPLATE_NAMES.join(", ")
)
})?
}
other => return Err(format!("unknown new argument `{other}`")),
}
}
let target = scaffold::resolve_target(&input)?;
scaffold::scaffold_project(&target, &template, render.as_deref())?;
// The target is echoed exactly as it was typed. The counter template's
// output — file set, bytes, and this line — stays byte-identical to the
// pre-WO-50 scaffolder, which reported the argument verbatim.
println!(
"created Noxid {} project -> {}",
scaffold::output_label(&template, render.as_deref()),
input.display()
);
return Ok(());
}
if command == "mcp" {
if args.next().is_some() {
return Err("noxid mcp accepts exactly one project or .nox path".into());
}
return mcp::run(&input);
}
if command == "mcp-http" {
let mut bind = "127.0.0.1:4321".to_string();
let mut token_env = "NOXID_MCP_TOKEN".to_string();
let mut allowed_origins = Vec::new();
let mut stream_responses = false;
while let Some(argument) = args.next() {
match argument.as_str() {
"--bind" => bind = args.next().ok_or("--bind requires an address")?,
"--token-env" => {
token_env = args.next().ok_or("--token-env requires a variable name")?
}
"--allow-origin" => allowed_origins.push(
args.next()
.ok_or("--allow-origin requires an exact origin")?,
),
"--stream" => stream_responses = true,
other => {
return Err(format!("unknown mcp-http argument `{other}`\n{}", usage()));
}
}
}
return mcp::run_http(&input, bind, &token_env, allowed_origins, stream_responses);
}
if command == "undo" {
let transaction_id = args
.next()
.ok_or("noxid undo requires a local transaction ID")?;
if args.next().is_some() {
return Err(
"noxid undo accepts exactly one file or project and one transaction ID".into(),
);
}
println!("{}", mcp::undo_local(&input, &transaction_id)?);
return Ok(());
}
if matches!(
command.as_str(),
"plan"
| "context"
| "manifest"
| "simulate"
| "test-affected"
| "index"
| "search"
| "repair"
| "scaffold"
) {
return ai::run(&command, &input, repair_args.into_iter().chain(args));
}
let operation_symbol = if matches!(command.as_str(), "impact" | "rename") {
Some(
args.next()
.ok_or_else(|| format!("noxid {command} requires a semantic ID"))?,
)
} else {
None
};
let rename_name = if command == "rename" {
Some(
args.next()
.ok_or("noxid rename requires a new identifier")?,
)
} else {
None
};
if command == "vue-island" {
if input.extension().and_then(|value| value.to_str()) != Some("vue") || !input.is_file() {
return Err(format!(
"noxid vue-island requires an existing `.vue` file: {}",
input.display()
));
}
let default_name = input
.file_stem()
.and_then(|value| value.to_str())
.ok_or("Vue island input has no valid file stem")?
.to_string();
let mut name = default_name;
let mut props = Vec::new();
let mut events = Vec::new();
let mut write_adapter = false;
while let Some(arg) = args.next() {
match arg.as_str() {
"--name" => name = args.next().ok_or("--name requires a component name")?,
"--prop" => props.push(parse_vue_island_field(
&args.next().ok_or("--prop requires name:Type")?,
)?),
"--event" => events.push(parse_vue_island_field(
&args.next().ok_or("--event requires name:Type")?,
)?),
"--write" => write_adapter = true,
_ => return Err(format!("unknown vue-island argument `{arg}`\n{}", usage())),
}
}
let file_name = input
.file_name()
.and_then(|value| value.to_str())
.ok_or("Vue island input has no valid file name")?;
let contract = noxid_vue_island::VueIslandContract {
component: name.clone(),
source: format!("./{file_name}"),
props,
events,
};
let javascript = contract.javascript().map_err(|diagnostics| {
diagnostics
.into_iter()
.map(|item| format!("error[{}]: {}", item.code, item.message))
.collect::<Vec<_>>()
.join("\n")
})?;
if write_adapter {
let output = input.with_file_name(format!("{name}.vue-island.js"));
write(&output, &javascript)?;
println!("generated Vue island adapter -> {}", output.display());
} else {
print!("{javascript}");
}
return Ok(());
}
let mut out_dir = PathBuf::from("dist");
let mut out_dir_explicit = false;
let mut json_diagnostics = false;
let mut entry = None;
let mut title = None;
let mut port = 4173_u16;
let mut adapter = None;
let mut write_changes = false;
let mut check_format = false;
let mut agent_output = false;
let mut strict_npm = false;
while let Some(arg) = args.next() {
if arg == "--out-dir" {
out_dir = PathBuf::from(args.next().ok_or("--out-dir requires a path")?);
out_dir_explicit = true;
} else if arg == "--json" {
json_diagnostics = true;
} else if arg == "--entry" {
entry = Some(args.next().ok_or("--entry requires a component name")?);
} else if arg == "--title" {
title = Some(args.next().ok_or("--title requires text")?);
} else if arg == "--strict-npm" {
strict_npm = true;
} else if arg == "--port" {
port = args
.next()
.ok_or("--port requires a number")?
.parse()
.map_err(|_| "--port must be an integer from 1 to 65535")?;
if port == 0 {
return Err("--port must be an integer from 1 to 65535".into());
}
} else if arg == "--adapter" {
adapter = Some(args.next().ok_or("--adapter requires a target")?);
} else if arg == "--write" {
write_changes = true;
} else if arg == "--check" {
check_format = true;
} else if arg == "--agent" {
agent_output = true;
} else {
return Err(format!("unknown argument `{arg}`\n{}", usage()));
}
}
if command == "port-vue" {
if out_dir_explicit
|| entry.is_some()
|| title.is_some()
|| adapter.is_some()
|| write_changes
|| check_format
{
return Err("noxid port-vue only supports the input path and --json".into());
}
let report = noxid_port_vue::analyze_path(&input, &noxid_port_vue::PortOptions::default())
.map_err(|error| format!("cannot analyze {}: {error}", input.display()))?;
if json_diagnostics {
println!("{}", report.to_json());
} else {
println!("{}", report.render_human());
println!(
"migration summary: {} converted, {} TODO, {} blocked, {} externalized, {} ignored",
report.summary.converted,
report.summary.todo,
report.summary.blocked,
report.summary.externalized,
report.summary.ignored,
);
}
if report.has_blockers() {
return Err(format!(
"migration is blocked by {} unsafe or unsupported construct(s)",
report.summary.blocked
));
}
return Ok(());
}
if command == "headless" {
if json_diagnostics
|| entry.is_some()
|| title.is_some()
|| adapter.is_some()
|| write_changes
|| check_format
{
return Err("noxid headless only supports a recipe list and --out-dir".into());
}
let recipes = input
.to_string_lossy()
.split(',')
.map(parse_headless_recipe)
.collect::<Result<Vec<_>, _>>()?;
if recipes.is_empty() {
return Err("noxid headless requires at least one component recipe".into());
}
let imports = noxid_headless_components::runtime_imports_for(recipes.iter().copied())
.into_iter()
.map(str::to_string)
.collect::<BTreeSet<_>>();
let mut javascript = format!(
"import {{ {} }} from \"./noxid-runtime.js\";\n",
imports.iter().cloned().collect::<Vec<_>>().join(", ")
);
javascript.push_str(&noxid_headless_components::javascript_for(
recipes.iter().copied(),
));
fs::create_dir_all(&out_dir)
.map_err(|error| format!("cannot create {}: {error}", out_dir.display()))?;
write(&out_dir.join("noxid-headless.js"), &javascript)?;
write(
&out_dir.join("noxid-runtime.js"),
&runtime_javascript_for_imports(&imports),
)?;
println!(
"generated {} native headless recipe(s) -> {}",
recipes.len(),
out_dir.display()
);
return Ok(());
}
if project::is_project_input(&input) {
if entry.is_some() {
return Err("folder-routed projects select entries from +page.nox files; --entry is not supported".into());
}
if !out_dir_explicit {
out_dir = project::default_out_dir(&input, command == "dev");
}
let options = project::ProjectBuildOptions {
out_dir: out_dir.clone(),
title: title.clone(),
development: command == "dev",
strict_npm,
};
return match command.as_str() {
"build" => {
let build = project::build_project(&input, &options)?;
project::prerender_output(&out_dir, &build)?;
if agent_output {
println!(
"{{\"ok\":true,\"command\":\"build\",\"routes\":{},\"endpoints\":{},\"components\":{},\"assets\":{},\"cacheHit\":{},\"output\":\"{}\"}}",
build.routes,
build.endpoints,
build.components,
build.assets,
build.persistent_cache_hit,
noxid_source::json_escape(&out_dir.display().to_string())
);
} else {
println!(
"built {} -> {} ({} route(s), {} endpoint(s), {} SSR route(s), {} prerender route pattern(s)/{} concrete output(s), {} ISR route(s), {} SWR route(s), {} route loader(s), {} component chunk(s), {} middleware module(s), {} emitted asset(s), persistent cache: {})",
input.display(),
out_dir.display(),
build.routes,
build.endpoints,
build.ssr_routes,
build.prerender_routes,
build.prerender_entries,
build.isr_routes,
build.swr_routes,
build.route_loaders,
build.components,
build.middleware,
build.assets,
if build.persistent_cache_hit {
"hit"
} else {
"miss"
},
);
}
Ok(())
}
"bundle" => {
let build = farm::bundle_project(&input, &out_dir, title)?;
if agent_output {
println!(
"{{\"ok\":true,\"command\":\"bundle\",\"routes\":{},\"endpoints\":{},\"components\":{},\"cacheHit\":{},\"output\":\"{}\"}}",
build.routes,
build.endpoints,
build.components,
build.persistent_cache_hit,
noxid_source::json_escape(&out_dir.display().to_string())
);
} else {
println!(
"bundled {} with {} -> {} ({} route(s), {} endpoint(s), {} component chunk(s), persistent compiler cache: {})",
input.display(),
if build.native_esm_eligible {
"Farm native ESM"
} else {
"Farm runtime"
},
out_dir.display(),
build.routes,
build.endpoints,
build.components,
if build.persistent_cache_hit {
"hit"
} else {
"miss"
},
);
}
Ok(())
}
"adapt" => {
let plan = deployment::adapt_project(&input, &out_dir, title, adapter.as_deref())?;
println!(
"adapted {} for {} -> {}",
input.display(),
plan.selected,
out_dir.display(),
);
Ok(())
}
"dev" => project::serve_project(input, options, port),
"benchmark" => {
println!("{}", project::benchmark_json(&input)?);
Ok(())
}
"routes" => {
println!("{}", project::routes_json(&input)?);
Ok(())
}
"graph" => {
println!("{}", project::graph_json(&input)?);
Ok(())
}
"impact" => {
println!(
"{}",
project::impact_json(
&input,
operation_symbol.as_deref().expect("impact symbol")
)?
);
Ok(())
}
"product" => {
println!("{}", project::product_json(&input)?);
Ok(())
}
"accessibility" | "design-system" | "devtools" => {
println!("{}", project::mcp_resource_json(&input, &command)?);
Ok(())
}
other => Err(format!(
"project input supports build, bundle, adapt, dev, benchmark, routes, graph, impact, product, accessibility, design-system, or devtools; received `{other}`"
)),
};
}
ensure_noxid_source(&input)?;
if command == "benchmark" {
let text = fs::read_to_string(&input)
.map_err(|error| format!("cannot read {}: {error}", input.display()))?;
let mut parse_samples = Vec::new();
let mut compile_samples = Vec::new();
for index in 0..30 {
let source = SourceFile::new(SourceId(index), &input, text.clone());
let started = Instant::now();
let parsed = noxid_parser::parse(&source);
parse_samples.push(started.elapsed().as_secs_f64() * 1_000.0);
std::hint::black_box(parsed);
let started = Instant::now();
let compiled = noxid_compiler_core::compile(&source);
compile_samples.push(started.elapsed().as_secs_f64() * 1_000.0);
std::hint::black_box(compiled);
}
parse_samples.sort_by(f64::total_cmp);
compile_samples.sort_by(f64::total_cmp);
println!(
"{{\"schemaVersion\":1,\"kind\":\"file\",\"samples\":30,\"sourceBytes\":{},\"parseMedianMs\":{:.3},\"parseP95Ms\":{:.3},\"compileMedianMs\":{:.3},\"compileP95Ms\":{:.3}}}",
text.len(),
parse_samples[15],
parse_samples[28],
compile_samples[15],
compile_samples[28],
);
return Ok(());
}
if command == "format" {
if json_diagnostics || entry.is_some() || title.is_some() || adapter.is_some() {
return Err("noxid format only supports --write or --check".into());
}
if write_changes && check_format {
return Err("noxid format cannot combine --write and --check".into());
}
let source = fs::read_to_string(&input)
.map_err(|error| format!("cannot read {}: {error}", input.display()))?;
let formatted = format_source(&source);
if check_format {
if formatted.changed {
return Err(format!("{} is not formatted", input.display()));
}
println!("{}: formatted", input.display());
} else if write_changes {
if formatted.changed {
write(&input, &formatted.text)?;
}
println!("formatted {}", input.display());
} else {
print!("{}", formatted.text);
}
return Ok(());
}
if command == "dev" {
if json_diagnostics {
return Err("noxid dev does not support --json".into());
}
if !out_dir_explicit {
let stem = input
.file_stem()
.and_then(|value| value.to_str())
.ok_or("input has no valid file stem")?;
out_dir = PathBuf::from("target/noxid-dev").join(stem);
}
return app::serve(
input,
app::AppOptions {
entry,
title,
out_dir,
development: true,
},
port,
);
}
// A bare file name has an empty parent; the import root is the current
// directory in that case, so `noxid compile Counter.nox` works in place.
let (source_root, auto_components) = match project::source_import_context(&input)? {
Some(context) => context,
None => {
let source_root = input
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
let auto_components = source_root.join("components");
(source_root, auto_components)
}
};
let module_graph = modules::compile_module_graph_with_options(
&input,
&source_root,
auto_components
.exists()
.then_some(auto_components.as_path()),
&std::collections::BTreeMap::new(),
// A single-file door still honors the enclosing project's declared
// `[server] secrets`, so `noxid check server/models/X.nox` agrees with
// `noxid build .` instead of refusing a legitimately declared key.
&project::project_analysis_options(&source_root),
)?;
let source = &module_graph.root().source;
let output = &module_graph.root().compilation;
if json_diagnostics {
println!("{}", output.diagnostics_json());
} else {
for diagnostic in &output.diagnostics {
eprintln!("{}", diagnostic.render(source));
}
}
match command.as_str() {
"a11y" => {
let findings = output
.diagnostics
.iter()
.filter(|diagnostic| diagnostic.code.starts_with("A11Y_"))
.count();
if findings != 0 {
return Err(format!("{findings} accessibility diagnostic(s)"));
}
if !json_diagnostics {
println!("{}: accessible", input.display());
}
}
"check" => {
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
if agent_output {
println!("{{\"ok\":true,\"diagnostics\":0}}");
} else if !json_diagnostics {
println!("{}: valid", input.display());
}
}
"inspect" => {
println!("{}", output.program.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"graph" => {
print!("{}", module_graph.merged_graph().render_text());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"impact" => {
let id = SemanticId::parse(operation_symbol.as_deref().expect("impact symbol"))
.ok_or("impact requires a stable semantic ID such as state:Counter.count")?;
let graph = module_graph.merged_graph();
let impact = graph
.impact(&id)
.ok_or_else(|| format!("unknown semantic symbol `{id}`"))?;
println!("{}", impact.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"product" => {
println!("{}", output.program.product_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"rename" => {
if output.has_errors() {
return Err("semantic rename requires a valid source file".into());
}
let id = SemanticId::parse(operation_symbol.as_deref().expect("rename symbol"))
.ok_or("rename requires a stable semantic ID")?;
let graph = module_graph.merged_graph();
if graph
.nodes
.get(&id)
.is_some_and(|node| node.kind == noxid_graph::NodeKind::TypeDefinition)
{
let sources = module_graph
.modules()
.map(|(_, module)| module.source.clone())
.collect::<Vec<_>>();
plan_project_rename(
&sources,
&graph,
&id,
rename_name.as_deref().expect("rename name"),
Provenance::default(),
)?;
}
let result = rename_symbol(
source,
&graph,
&id,
rename_name.as_deref().expect("rename name"),
)?;
let candidate = SourceFile::new(SourceId(0), &input, result.source.clone());
let parsed = noxid_parser::parse(&candidate);
if !parsed.diagnostics.is_empty() {
return Err(format!(
"rename was rejected because the transformed source has {} syntax diagnostic(s)",
parsed.diagnostics.len()
));
}
if write_changes {
write(&input, &result.source)?;
}
println!("{}", result.to_json());
}
"machines" => {
println!("{}", output.machines.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"collections" => {
println!("{}", output.collections.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"resources" => {
println!("{}", output.resources.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"streams" => {
println!("{}", output.streams.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"agents" => {
println!("{}", output.agents.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"execution" => {
println!("{}", output.execution.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"validators" => {
println!("{}", output.validation.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"styles" => {
println!("{}", output.styles.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"devtools" => {
println!("{}", output.devtools.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"accessibility" => {
println!("{}", output.accessibility.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"design-system" => {
println!("{}", output.design.to_json());
if output.has_errors() {
return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
}
}
"compile" => {
if output.has_errors() {
return Err(format!(
"{} diagnostic(s); no output emitted",
output.diagnostics.len()
));
}
fs::create_dir_all(&out_dir)
.map_err(|error| format!("cannot create {}: {error}", out_dir.display()))?;
let stem = input
.file_stem()
.and_then(|value| value.to_str())
.ok_or("input has no valid file stem")?;
if let Some(generated) = &output.generated {
if generated.modules.is_empty() {
write(&out_dir.join(format!("{stem}.js")), &generated.javascript)?;
} else {
for module in &generated.modules {
write(
&out_dir.join(format!("{}.js", module.component)),
&module.javascript,
)?;
}
if !generated
.modules
.iter()
.any(|module| module.component == stem)
{
let legacy = out_dir.join(format!("{stem}.js"));
if legacy.exists() {
fs::remove_file(&legacy).map_err(|error| {
format!("cannot remove stale {}: {error}", legacy.display())
})?;
}
}
}
let css = module_graph
.modules()
.map(|(_, module)| {
module
.compilation
.generated
.as_ref()
.map(|item| item.css.as_str())
.unwrap_or("")
})
.collect::<Vec<_>>()
.join("\n");
write(&out_dir.join(format!("{stem}.css")), &css)?;
}
for (_, module) in module_graph.modules() {
if std::ptr::eq(module, module_graph.root()) {
continue;
}
let generated = module.compilation.generated.as_ref().ok_or_else(|| {
format!(
"{} did not generate JavaScript",
module.source.path().display()
)
})?;
if generated.modules.is_empty() {
let component =
module
.compilation
.program
.components
.first()
.ok_or_else(|| {
format!("{} exports no component", module.source.path().display())
})?;
write(
&out_dir.join(format!("{}.js", component.name)),
&generated.javascript,
)?;
} else {
for component in &generated.modules {
write(
&out_dir.join(format!("{}.js", component.component)),
&component.javascript,
)?;
}
}
}
if let Some(validators) = &output.generated_validators {
write(&out_dir.join(format!("{stem}.validators.js")), validators)?;
}
if let Some(resources) = &output.generated_resources {
write(&out_dir.join(format!("{stem}.resources.js")), resources)?;
}
if let Some(streams) = &output.generated_streams {
write(&out_dir.join(format!("{stem}.streams.js")), streams)?;
}
if let Some(agents) = &output.generated_agents {
write(&out_dir.join(format!("{stem}.agents.js")), agents)?;
}
if output.generated.is_some()
|| output.generated_resources.is_some()
|| output.generated_streams.is_some()
|| output.generated_agents.is_some()
{
let runtime_imports = module_graph
.modules()
.flat_map(|(_, module)| module.compilation.runtime_imports())
.collect::<BTreeSet<_>>();
write(
&out_dir.join("noxid-runtime.js"),
&runtime_javascript_for_imports(&runtime_imports),
)?;
write(&out_dir.join("noxid-devtools.js"), devtools_javascript())?;
write(
&out_dir.join(format!("{stem}.bundle.json")),
&output.bundle_json(),
)?;
}
write(
&out_dir.join(format!("{stem}.meta.json")),
&output.metadata_json(),
)?;
write(
&out_dir.join(format!("{stem}.devtools.json")),
&output.devtools.to_json(),
)?;
println!("compiled {} -> {}", input.display(), out_dir.display());
}
"build" => {
let build = app::build_app(
&input,
output,
Some(&module_graph),
&app::AppOptions {
entry,
title,
out_dir: out_dir.clone(),
development: false,
},
)?;
println!(
"built {} as component:{} -> {} ({} component chunk(s), {} emitted asset(s))",
input.display(),
build.entry,
out_dir.display(),
build.components.len(),
build.assets.len()
);
}
other => return Err(format!("unknown command `{other}`\n{}", usage())),
}
Ok(())
}
fn ensure_noxid_source(path: &Path) -> Result<(), String> {
if path.extension().and_then(|extension| extension.to_str()) == Some("nox") {
return Ok(());
}
Err(format!(
"Noxid source files must use the `.nox` extension: {}",
path.display()
))
}
fn write(path: &Path, contents: &str) -> Result<(), String> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
}
fs::write(path, contents).map_err(|error| format!("cannot write {}: {error}", path.display()))
}
fn parse_vue_island_field(value: &str) -> Result<noxid_vue_island::VueIslandField, String> {
let (name, ty) = value
.split_once(':')
.ok_or_else(|| format!("Vue island field `{value}` must use name:Type"))?;
Ok(noxid_vue_island::VueIslandField {
name: name.into(),
ty: ty.into(),
})
}
fn run_port_command(mut args: impl Iterator<Item = String>) -> Result<(), String> {
let kind = args.next().ok_or_else(usage)?;
let input = PathBuf::from(args.next().ok_or_else(usage)?);
let mut out_dir = PathBuf::from("ported-noxid");
let mut write_changes = false;
let mut json = false;
let mut include_generated = false;
while let Some(argument) = args.next() {
match argument.as_str() {
"--out-dir" => out_dir = PathBuf::from(args.next().ok_or("--out-dir requires a path")?),
"--write" => write_changes = true,
"--json" => json = true,
"--include-generated" => include_generated = true,
other => return Err(format!("unknown port argument `{other}`\n{}", usage())),
}
}
let options = noxid_port_vue::PortOptions {
include_generated,
..noxid_port_vue::PortOptions::default()
};
match kind.as_str() {
"project" | "nuxt" | "vue-project" => {
let forced = match kind.as_str() {
"nuxt" => Some(noxid_port_vue::project::VueProjectKind::Nuxt),
"vue-project" => Some(noxid_port_vue::project::VueProjectKind::Vue),
_ => None,
};
let plan = noxid_port_vue::project::plan_project(&input, forced, &options)
.map_err(|error| format!("cannot plan project port: {error}"))?;
if json {
println!("{}", plan.to_json());
} else {
println!("{}", plan.render_human());
}
if write_changes {
write_project_port(&plan, &out_dir)?;
println!("ported and validated project -> {}", out_dir.display());
}
}
"vue-package" | "package" => {
let plan = noxid_port_vue::package::plan_package(&input, &options)
.map_err(|error| format!("cannot plan Vue package port: {error}"))?;
if json {
println!("{}", plan.to_json());
} else {
println!("{}", plan.render_human());
}
if write_changes {
write_package_port(&plan, &out_dir)?;
println!("ported Vue package -> {}", out_dir.display());
}
}
other => {
return Err(format!(
"unknown port kind `{other}`; expected project, nuxt, vue-project, or vue-package"
));
}
}
Ok(())
}
fn fresh_port_staging(out_dir: &Path) -> Result<PathBuf, String> {
if out_dir.exists() {
return Err(format!(
"port output already exists; refusing to replace {}",
out_dir.display()
));
}
let parent = out_dir.parent().unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent)
.map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
let name = out_dir
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("ported-noxid");
let staging = parent.join(format!(".{name}.noxid-port-{}", std::process::id()));
if staging.exists() {
return Err(format!(
"stale port staging directory exists: {}",
staging.display()
));
}
fs::create_dir_all(&staging)
.map_err(|error| format!("cannot create {}: {error}", staging.display()))?;
Ok(staging)
}
fn commit_port_staging(staging: &Path, out_dir: &Path) -> Result<(), String> {
fs::rename(staging, out_dir).map_err(|error| {
format!(
"cannot commit port output {} -> {}: {error}",
staging.display(),
out_dir.display()
)
})
}
fn write_project_port(
plan: &noxid_port_vue::project::VueProjectPort,
out_dir: &Path,
) -> Result<(), String> {
let staging = fresh_port_staging(out_dir)?;
let result = (|| {
for file in &plan.files {
let Some(content) = &file.content else {
continue;
};
write(&staging.join(&file.output), content)?;
}
write(
&staging.join("noxid-port-report.json"),
&plan.manifest_json(),
)?;
project::routes_json(&staging)
.map_err(|error| format!("ported route graph failed validation: {error}"))?;
commit_port_staging(&staging, out_dir)
})();
if result.is_err() && staging.exists() {
let _ = fs::remove_dir_all(&staging);
}
result
}
fn write_package_port(
plan: &noxid_port_vue::package::VuePortPackage,
out_dir: &Path,
) -> Result<(), String> {
let staging = fresh_port_staging(out_dir)?;
let result = (|| {
for component in &plan.components {
let Some(content) = &component.noxid_source else {
continue;
};
write(&staging.join(&component.output), content)?;
}
write(
&staging.join("noxid-port-report.json"),
&plan.manifest_json(),
)?;
commit_port_staging(&staging, out_dir)
})();
if result.is_err() && staging.exists() {
let _ = fs::remove_dir_all(&staging);
}
result
}
fn parse_headless_recipe(
value: &str,
) -> Result<noxid_headless_components::ComponentRecipe, String> {
use noxid_headless_components::ComponentRecipe;
match value.trim() {
"Dialog" => Ok(ComponentRecipe::Dialog),
"AlertDialog" => Ok(ComponentRecipe::AlertDialog),
"Popover" => Ok(ComponentRecipe::Popover),
"Tooltip" => Ok(ComponentRecipe::Tooltip),
"Menu" => Ok(ComponentRecipe::Menu),
"Select" => Ok(ComponentRecipe::Select),
"Listbox" => Ok(ComponentRecipe::Listbox),
"Tabs" => Ok(ComponentRecipe::Tabs),
"Toolbar" => Ok(ComponentRecipe::Toolbar),
"ToggleGroup" => Ok(ComponentRecipe::ToggleGroup),
"Accordion" => Ok(ComponentRecipe::Accordion),
"Collapsible" => Ok(ComponentRecipe::Collapsible),
other => Err(format!("unknown native headless recipe `{other}`")),
}
}
fn usage() -> String {
base_usage().replace(
" noxid vet <package[@version]>\n noxid vet [--sync]",
" noxid queue work [--queue name]\n noxid queue status [--queue name]\n noxid vet <package[@version]>\n noxid vet [--sync]",
)
}
fn base_usage() -> String {
"usage: noxid <check|a11y|accessibility|design-system|inspect|graph|impact|rename|format|product|routes|machines|collections|resources|streams|agents|execution|validators|styles|devtools|compile|build|bundle|adapt|dev|benchmark> <file.nox|project-directory|Noxid.toml> [options]\n noxid test [file.nox|project-directory|Noxid.toml] [--gate] [--json] [--seed <n> [--property <semantic-id>]] (default: the current directory)\n stdout is exactly one line, the JSON report; the run's logs and every [server] tracing record go to stderr as NDJSON\n property timeout measures validator CPU time; a timeout + 1s wall-clock backstop kills synchronous hangs\n noxid plan <file|project> <goal> [--constraint <text>] [--symbol <semantic-id>]\n noxid context <file|project> <task> [--max-bytes <n>] [--max-nodes <n>] [--no-edges]\n noxid manifest <file|project> [--projection compact|agent|full]\n noxid describe <feature|operation|type|diagnostic|guide> [name]\n noxid simulate <file|project> <component-id> <action-id>... [--state <machine-id=variant-id>]\n noxid drift <before-file|project> <after-file|project>\n noxid test-affected <file|project> <semantic-id>...\n noxid index <file|project>\n noxid search <file|project> <query> [--limit <n>]\n noxid repair <file|project> [--safe|--inspect [--discard <transaction-id>]]\n plan only by default; --safe applies the automatic set atomically and revalidates\n --inspect lists the repair journals a refused recovery is blocking on and settles none;\n --discard <id> then abandons that transaction, leaving every target exactly as it is\n noxid scaffold <directory> <component|route|form|list-page|resource|state-machine> <Name> [contract options] [--write]\n noxid undo <file.nox|project-directory|Noxid.toml> <transaction-id>\n noxid new <directory> [--template app|counter] [--render client|universal]\n noxid db new <name>\n noxid db migrate\n noxid db status\n noxid vet <package[@version]>\n noxid vet [--sync]\n noxid agent-guide <core|scaffolding|interop|types|routing|storage|realtime|observability|reactivity|motion|remote-actions|ssr|testing|semantic-tools>\n noxid example <counter|routed-app|reactive-effects|keyed-list|interactive-list|state-machine>\n noxid mcp <file.nox|project-directory|Noxid.toml>\n noxid mcp-http <file.nox|project-directory|Noxid.toml> [--bind <loopback-address>] [--token-env <name>] [--allow-origin <loopback-origin>]... [--stream]\n noxid port <project|nuxt|vue-project|vue-package> <directory> [--out-dir <directory>] [--write] [--json]\n noxid port-vue <file.vue|directory> [--json]\n noxid vue-island <component.vue> [--name <name>] [--prop <name:Type>]... [--event <name:Type>]... [--write]\n noxid headless <Recipe[,Recipe...]> [--out-dir <directory>]\n noxid lsp".into()
}
const CONTEXT_PREAMBLE: &str = "Context first: call query_project { operation: \"context\" } with a byte budget and read only the surface it points you to; reach for this guide's detail after that, not before.";
const ROUTING_GUIDE_HEAD: &str = "Noxid routing\n- src/routes/+page.nox defines a page; +layout.nox wraps descendants.\n- Folder names form paths; [id] is a typed dynamic segment. Top-level `/server`, `/public`, `/netlify`, and `/.vercel` are compiler-owned deployment roots; put similarly named pages below a product prefix such as `/docs/server`.\n- Optional query inputs are consumed with `page ?? 1`, or exhaustively rendered with `#match page { Some(value) { ... } None { ... } }`; missing values use the compiler's Optional representation.\n- route { title: \"...\" render: ssr } opts into SSR.\n- Typed HTTP endpoints are .nox files under server/api/ (with /api prefix) or server/routes/ (root paths). End filenames with one explicit .get.nox, .post.nox, .put.nox, .patch.nox, or .delete.nox method.\n- endpoint Name { version: 1 params { ... } query { ... } body { ... } result: Type ... } declares the whole JSON boundary. Versions are positive and default to 1. Array query fields use one JSON-array query value, never repeated keys.\n- A bodyless endpoint is implemented by the exact `endpoint:<Name>@<version>` key in server/host.ts or server/host.js. Declared timeout, rate limit, idempotency, capabilities, and middleware are enforced; builds emit server/security.manifest.json.";
const ROUTING_GUIDE_TAIL: &str = "\n- `noxid adapt` forwards only the exact compiler-derived typed endpoint path shapes and enabled live/presence/OpenAPI/MCP doors to the generated handler; unrelated assets and prerendered routes keep static ownership. `noxid bundle`, `noxid dev`, and server-capable adaptation require `@farmfe/core`; the project installation takes precedence over the compiler installation. If a relocated compiler cannot find either, install it in the project with `pnpm add -D @farmfe/core@^1.7.0` to resolve `BUILD_HOST_MISSING`.\n- Browser middleware lives in src/middleware/<name>.js and may be declared by a layout, page, component, or endpoint. Its server-only variant lives in server/route-middleware/<name>.ts (or .js).\n- Modules directly under server/middleware/ are auto-discovered global server middleware. They run on every server request in lexical filename order before route middleware; no registration is required.\n- Browser code is emitted per route/component; unrelated chunks are not loaded.\n- GET endpoints may declare `cache: swr <seconds>` or `cache: isr <seconds>`; invalidate the versioned `endpoint:<Name>@<version>` tag through `/_noxid/revalidate`.\n- Every build emits `dist/api-contract.json`; commit the project-root `api-contract.json`. `noxid test --gate` rejects removed endpoints or fields, narrowed types, new required inputs, and method/path changes unless that endpoint's version increments. Additive changes update the baseline only after the whole gate passes.\n- An optional endpoint `description: \"...\"` supplies OpenAPI and MCP prose without changing authority. Every build emits deterministic OpenAPI 3.1 to `dist/api.openapi.json` (or the selected output directory), including the compiler-owned `x-noxid-signature`.\n- `[server] api_docs = true` serves `/_noxid/openapi.json`; `[server] mcp = true` serves streamable HTTP at `POST /_noxid/mcp` with exactly one typed tool per endpoint. Both default false and 404 while disabled. MCP reuses endpoint validation, capabilities, middleware, sessions, limits, and implementation dispatch. The security manifest records both opt-ins under `surfaces`.\n- Breaking contract differences fail with `error[API_CONTRACT_BREAKING_CHANGE]` and name every required endpoint version decision.\n- Netlify and Cloudflare publish only the filtered `public/` subtree; server bundles, API contracts, and compiler `app.*.json` metadata stay outside direct static hosting.\n- A page route and a `server/routes/` endpoint may not overlap the same request path, including through dynamic or catch-all segments. `ROUTE_PATH_CONFLICT` names both owners; move the endpoint under `server/api/` or give them distinct static segments.";
/// The routing guide quotes the multipart parser's uniform ceilings, so it
/// is generated rather than written down. The numbers have exactly one
/// source — the `noxid_ir` constants the emitted parser, the security
/// manifest, and OpenAPI are all built from — and spelling them here as
/// prose would create a fourth copy that can drift without failing a build.
static ROUTING_GUIDE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
format!(
concat!(
"{head}",
"\n- Uploads are declared, never inferred: a mutating endpoint body may use `File(maxSize: 10mb, types: [image/png])` or `Array<File(...)>`. Both constraints are mandatory; the magic-byte allow-list is image/png, image/jpeg, image/gif, image/webp, application/pdf, application/zip, or text/plain. Only declared upload endpoints accept multipart; each part is cut at its own limit plus one byte, and Content-Type is never trusted. OpenAPI and security.manifest.json publish every constraint. Put scalar sibling fields BEFORE the file parts in a multipart body: a streaming parser cannot see a later part, so a scalar sent after a file is only refused once that file has been fully ingested. An empty part is refused with UPLOAD_EMPTY_FILE — there are no bytes to verify a declared type against. The manifest and OpenAPI also publish the parser's own uniform ceilings, and these are the numbers the emitted parser enforces: maxParts: {parts} for Array<File> and 1 otherwise, aggregateMaxSizeBytes = maxSizeBytes x maxParts, partHeaderMaxBytes: {header}, scalarFieldsMaxBytes: {scalar}, filenameMaxBytes: {filename} UTF-8 bytes, truncated at a code-point boundary rather than refused. Refusals are MULTIPART_PART_LIMIT, MULTIPART_HEADERS_TOO_LARGE, and ENDPOINT_BODY_TOO_LARGE; an Array<File> field's real bound is its per-part cap times maxParts.",
"{tail}"
),
head = ROUTING_GUIDE_HEAD,
tail = ROUTING_GUIDE_TAIL,
parts = noxid_ir::MULTIPART_MAX_PARTS,
header = noxid_ir::MULTIPART_PART_HEADER_MAX_BYTES,
scalar = noxid_ir::MULTIPART_SCALAR_MAX_BYTES,
filename = noxid_ir::UPLOAD_FILENAME_MAX_BYTES,
)
});
fn agent_guide(topic: &str) -> Result<String, String> {
Ok(format!("{CONTEXT_PREAMBLE}\n{}", agent_guide_body(topic)?))
}
fn agent_guide_body(topic: &str) -> Result<&'static str, String> {
match topic {
"core" => Ok(
"Noxid agent quick reference\n- Source files use .nox; projects use Noxid.toml and src/routes/+page.nox.\n- Start from `noxid new <dir> --template app` (or `--template counter` for the minimal single-page project), then `pnpm install --frozen-lockfile`; the `scaffolding` topic states what that template already contains and how its vendored plugins stay honest.\n- Run `noxid check <file>` or `noxid build <project>`; do not infer success from prose.\n- Author typed scenario blocks for component behavior and run `noxid test [file-or-project] --gate` (the path defaults to the current directory); it executes emitted JavaScript and returns structured results.\n- Components use state, computed, actions, view, and style blocks. Actions batch writes.\n- Expressions support + - * / == != < <= > >= && || ??, unary ! and unary -, Int, Float, String, and Boolean literals. Int and Float never mix implicitly; arrays, maps, structs, and tagged variants compare recursively by language value.\n- Compiler-owned pure scalar functions need no import: len, contains, startsWith, trim, lower, upper, min, max, abs, round, floor, ceil, toFloat, toInt, and toString. They are free functions, not methods; toInt truncates toward zero, and numeric overloads never mix Int with Float.\n- Use `maybe ?? fallback` to consume Optional<T>; the fallback must be T (or Optional<T> for chaining), and the result is typed by the compiler. Use exhaustive `#match maybe { Some(value) { ... } None { ... } }` when the cases render different structure.\n- Views branch with #if / #else if / #else; conditions must be Boolean. Use `#if open transition 200ms { ... }` for a compiler-visible bounded exit that can be interrupted without remounting.\n- Actions support `let` locals, if/else statements, calls to sibling actions (recursion is rejected), and struct field assignment like todo.note.text = next.\n- Event handlers take arguments evaluated at event time: +click={remove(todo.id)}. The bare form +click={save} receives the typed DOM event.\n- Components compose with one <slot />: <Card>...</Card> children render in the parent's scope.\n- File-scoped `fn name(params): Type` declares pure reusable functions (defined before use); backtick template strings interpolate: `Hello {name}`. Share components, document types, and file-scoped functions with `import { Card, Incident, severityLabel } from \"./domain.nox\"`; each name keeps the defining module's stable semantic ID, and cross-file cycles are rejected.\n- Scalar builtins include len, contains, startsWith, endsWith, trim, lower, upper, capitalize, camelCase, kebabCase, snakeCase, padStart, padEnd, repeat, replaceAll, min, max, abs, clamp, round, roundTo, floor, ceil, toInt, toFloat, toString, and range(a, b) for numeric loops.\n- Prefer tagged machines and exhaustive #match over correlated booleans.\n- Prefer keyed #for and explicit +event handlers. There is no VDOM.\n- An LLM call is a declared boundary: `model Name { provider: anthropic|openai|openai-compatible id: \"...\" secret: DECLARED_KEY }` in a direct server/models/<name>.nox file. Server modules import models/types/generateText/generateObject/streamText from \"noxid:server\". generateObject validates the answer through the emitted boundary validator, retries up to the declared `retries:` (re-attempts after the first, so `retries: N` makes at most N+1 provider attempts), then fails MODEL_OUTPUT_INVALID. Scenarios stub with `given: model Name = text|object|tokens|fails ...`; an unstubbed call fails MODEL_STUB_REQUIRED naming the model and the call site, and never reaches a provider.\n- An agent becomes a server-side loop when it declares `model:`; without it, it stays the client-only typed session. Add `instructions:` (inline prose or a `server/agents/<name>.md` path embedded at build time) and optional `maxTurns:` (1..64, default 8).\n- An agent has no separate tool definitions: its tools are the endpoints whose declared capabilities its `can` covers in full and its `cannot` does not touch. A denied endpoint is absent from the registry, never described to the model, and not in `server/security.manifest.json` under `agents[].tools`. A tool call crosses the endpoint's own validator, middleware, limits, and audit, under `Principal.Agent { id: AgentId(<name>), actingFor }`.\n- The generated doors are `POST /_noxid/agents/<Agent>/runs` (capability `agents.<name>.run`) and `POST /_noxid/agents/<Agent>/runs/<runId>/resume` (`agents.<name>.resume`). A host authorizer that answers \"defer\" pauses the run durably and emits PermissionRequired then Paused(runId); `#stream` exhaustiveness requires the Paused case and `session.resume(runId)` continues it.\n- ToolStarted/ToolCompleted/PermissionRequired payloads are filled by the loop, so their declared type must be String or a record whose fields are among name, tool, endpoint, capability, arguments, summary, status, ok, code, message, runId, turn, agent, result. Anything else is AGENT_EVENT_UNREPRESENTABLE at build time.\n- Query the local semantic compiler with query_project before reading many files.\n- Reference prose is chunked: `noxid describe guide <topic>` returns one topic under 6 KB, and `llms.txt` indexes byte-sized `llms/<topic>.txt` chunks. Load the index and the chunk your task needs, never `llms-full.txt`.\n- MCP is local-only; remote binds and origins are rejected.",
),
"scaffolding" => Ok(
"Noxid scaffolding\n- Start from `noxid new <dir> --template app`, then `pnpm install --frozen-lockfile`: a compile-tested full-stack project that passes `noxid test --gate`, `noxid build`, and `noxid adapt node` with zero edits and no service running (SQLite through Node's builtin node:sqlite). It already contains one route with a typed form, one typed endpoint under server/api with params/result/capabilities/timeout/limit plus a scenario that makes a real request through the shipped handler, one scoped and one unscoped table in server/utils/schema.ts that the endpoint reads and the action writes through the vendored Drizzle adapter, a forward migration, global session middleware, three requirements with passing scenarios, and a `live` resource rendered over every lifecycle case. The scaffold is secure by default and there is no anonymous principal in it: the page shows a sign-in form until there is a session and the board once there is, `signIn`/`signOut` mint and expire the signed noxid_session cookie inside server/middleware/session.ts, and every other endpoint and remote action arriving without that cookie is refused before any handler runs — an endpoint answers 403 with error.code SESSION_PRINCIPAL_REQUIRED and a teaching message, a remote action answers the runtime's own 403 BOUNDARY_MIDDLEWARE_DENIED carrying x-noxid-refusal: SESSION_PRINCIPAL_REQUIRED, because direct middleware responses are reserved to SSR routes. The sign-in action is a starter placeholder that signs a cookie for the display name the page collected; replace it with the identity provider you actually run and keep the shape — one principal resolved in middleware, a refusal when there is none. `noxid new` runs no package manager: it vendors the vetted plugin files into plugins/ byte-identically with a hash ledger (.noxid-plugins.json), pins the reviewed package versions, and `noxid build` refuses a drifted file (PLUGIN_VENDOR_DRIFT) or a lockfile that disagrees (NPM_IMPORT_UNVETTED). Run `noxid vet` inside the project to compare those vendored files with the copies your `noxid` embeds, and `noxid vet --sync` to rewrite the drifted ones and the ledger from your compiler; neither ever updates a file silently. Edit that shape instead of assembling one; `--template counter` is the minimal single-page project. `noxid new` refuses a non-empty directory (SCAFFOLD_TARGET_NOT_EMPTY), refuses a target outside the current directory (SCAFFOLD_TARGET_ESCAPES), and never overwrites.",
),
"interop" => Ok(
"Noxid JavaScript interop\n- Every import is typed by declarations, typed JSDoc, or an adjacent `.nox-contract`; untyped JavaScript fails closed.\n- `pure` functions may be used in typed expressions.\n- `impure` functions may be evaluated only inside explicit client actions; calls, arguments, returned values, reads, writes, and graph invocation edges stay compiler-visible.\n- Impure calls remain illegal in state initializers, computed values, views, file-scoped functions, effects, watches, SSR/server/edge/worker actions, and remote bodies.\n- External return values cross generated validators before trusted application state can observe them. Promise-like results fail closed.\n- Project-local JavaScript is copied into deterministic external assets by `noxid build`; `[assets] directory = \"src/assets\"` declares additional regular files. Symlinks and output collisions are rejected.",
),
"types" => Ok(
"Noxid types and data vocabulary\n- `type UserId = distinct String` declares a nominal scalar over String, Int, Float, or Date. It inherits nothing: equality with itself, plus whatever the declaration opts into with `allow [concat|add|subtract|compare]`. No implicit widening to the base, no builtins, no cross-distinct operations. Construct with `UserId(value)` and unwrap with `.base()`; both have stable semantic IDs and appear as invokes edges wherever they occur, including inside action, effect, and handler bodies, so `noxid impact <project> distinct-unwrap:UserId` lists every site where an id leaves its type. Construction and `.base()` erase to the value itself in all three emitters, so the wire and database representation is always the base; boundary validators re-check the base shape, and OpenAPI and `api-contract.json` keep the distinct name. Imported structs carry their distinct field types across the file boundary. Use `.base()` where a plain scalar is structurally required, such as a `#for` key.\n- `PrincipalId` and `AgentId` are compiler-owned `distinct String` types with an empty allow list, and `Principal` is the compiler-owned union of `System`, `User { id: PrincipalId }`, and `Agent { id: AgentId, actingFor: Optional<PrincipalId> }`. All three are pre-declared in every program: declaring one refuses with `PRINCIPAL_ID_RESERVED`, and constructing one in source — `PrincipalId(value)`, `AgentId(value)`, any `Principal` variant, or the named-field spelling `User(id = value)` — refuses with `PRINCIPAL_CONSTRUCTION_RESERVED`, because only the generated server request boundary builds a principal, from the middleware context. A compiler-owned `handler` for an endpoint, task, or queue binds `context`, whose single field is `principal: Principal`; those three are the only surfaces that bind it today, a remote action receives no `context` (pass what it needs as a typed parameter) and a live resource has no compiler-owned handler; consume it with an exhaustive statement `#match context.principal { System { } User(user) { } Agent(actor) { } }`. Omitting a case fails to compile, and the `Agent` case is real: an agent acting for a user resolves scoped access through `actingFor`, never through its own id. `user.id` is a `PrincipalId`; `.base()` is the deliberate way out and every unwrap is graph-visible, so `noxid impact <project> distinct-unwrap:PrincipalId` lists every place a principal leaves its type. Client and SSR code never sees a principal, and `Principal` is not a wire type; `PrincipalId` and `AgentId` are, erasing to `String` and publishing as named OpenAPI/MCP schemas. Where a Noxid declaration names a scoped table's principal column, its type must be `PrincipalId` (`SCOPED_COLUMN_REQUIRES_PRINCIPAL_ID`).\n- Struct rows are removed by key with items.removeWhere(field, value).\n- Collection queries are typed Array/Map methods. Arrays support count, countWhere, where, firstWhere, first, last, reversed, unique, sum, average, take, drop, contains, join, sortBy, sortByDesc, minOf, maxOf, sumOf, averageOf, groupBy, and countBy. Maps support get, count, keys, values, and entries. first/last/minOf/maxOf/average/get return Optional values (use ?? or #match). Field-based forms take a bare field name; there are no lambdas.\n- Dates are instants: parseDate(s) -> Optional<Date>; formatDate(date, pattern, tz) and startOfDay(date, tz) require an explicit IANA timezone; addDays/addHours/addMinutes/addSeconds and diffMillis/diffDays are fixed-duration math; dateFromMillis/dateToMillis bridge Int; Date compares with == < > etc. There is no now() yet - time enters through data.\n- Arrays derive values with items.count(); Array<Struct> adds countWhere/where and scalar-field groupBy/countBy. Maps are frozen plain objects with no v1 literals or mutation; consume them with get/count/keys/values/entries, whose key-facing views are sorted. entries returns Array<MapEntry<K,V>> for keyed #for. Use bare typed field names, not predicate closures or items.length.",
),
"routing" => Ok(ROUTING_GUIDE.as_str()),
"storage" => Ok(
"Noxid storage\n- Server host, utility, and middleware modules may `import { storage } from \"noxid:server\"`. `storage(namespace)` provides async JSON get/set/delete/list; set accepts `{ ttl: seconds }`. `[server] storage = \"memory\"` is the default; use `\"fs\"` for one-process persistence or `\"postgres\"` for shared state across replicas. `[server] db_pool` defaults to 10 and configures the database adapter and queue pool; serverless functions with an external pooler should normally set it to 1. The Node adapter drains requests, tasks, the current queue job, and SSE on SIGTERM/SIGINT; `[server] shutdown_timeout_ms` defaults to 20000. It refuses startup with `SERVER_LIFECYCLE_EXPORT_MISSING` when the Farm handler lacks a lifecycle export required by the built features.\n- Hosts receive an opaque FileRef with sniffedType, size, sha256, sanitized metadata-only name, plus stream(), bounded bytes(), and store(namespace). `[server] blob_dir` defaults to `.noxid/blobs`; stored paths are namespace/content-hash only.\n- Database migrations are forward-only SQL files under server/db/migrations/. Use `noxid db new <name>`, inspect the SQL, then run `noxid db migrate`; `noxid db status` reports applied and pending files. Applied checksums are immutable. DATABASE_URL accepts `postgres://`, `mysql://`, `sqlite://<path>`, or `sqlite::memory:`. Install the selected network driver with `pnpm add postgres@3.4.9` or `pnpm add mysql2@3.23.4`; the migration runner uses project-rooted Node resolution, including hoisted workspace dependencies, and never falls back to the compiler installation. Relative SQLite paths resolve from the project root and require an existing parent; SQLite uses Node 22.16+'s full builtin node:sqlite API with transactional DDL. MySQL reports its implicit DDL-commit limit while retaining transactional DML apply.\n- Scoped database access takes only a runtime-created endpoint/task/queue context, the adapter-owned eq predicate, and db.transaction. Missing, mismatched, system-only, raw-Drizzle, or fabricated authority fails with DATA_SCOPE_VIOLATION. PostgreSQL adds forced RLS through transaction-local noxid.principal; MySQL and SQLite retain the same adapter enforcement. Agents have closed typed endpoints and no raw SQL surface. Runtime adapter enforcement is the security boundary. Compiler-emitted server output is eval-free and limited to an exact literal driver-import allowlist. Developer-authored server/host.* and server/** modules are a trusted deployment tier and are not policed by the generated-output scanner. Queue principals serialize stably and legacy NULL _noxid_jobs.principal rows mean system.\n- Redis is the lower-latency shared storage option: set `[server] storage = \"redis\"`, declare `REDIS_URL` in `[server] secrets`, and provide one `redis://` or TLS `rediss://` endpoint. Cluster and sentinel layouts fail closed in v1. During a disconnect, rate admission denies, cache reads miss, and idempotent requests return a retryable 503; the driver never falls back to process memory.\n- Durable jobs live in direct server/queues/<name>.nox files as `queue Name { payload { ... } retry: 3 backoff: 30s }`. Omit the handler for the exact `queue:<Name>` host key. Payloads validate on enqueue and Postgres claim; exhausted retries are queryable as dead-letter. Server modules import `enqueue` from `noxid:server`. Run `noxid queue work [--queue name]` or `noxid queue status [--queue name]`; `[server] queue_worker = true` embeds the Node worker. Queues require a shared `postgres://` DATABASE_URL; when a MySQL, SQLite, or other non-Postgres URL is known during build or adaptation, the compiler refuses with `QUEUE_REQUIRES_SHARED_DATABASE` instead of emitting an unusable worker. Queue scenarios require `when: enqueue(...)` and an explicit UTC clock.\n- Startup modules in server/plugins/*.{ts,js} default-export a function receiving frozen { environment, storage, host }; they run once in lexical filename order, and a throw aborts startup.\n- Scheduled server work lives in server/tasks/<name>.nox as `task Name { schedule: \"0 3 * * *\" handler { ... } }`; cron has exactly five fields and no seconds. Omit the handler to use the exact `task:<Name>` host key; builds emit server/tasks.manifest.json.\n- Task triggers use POST /_noxid/tasks/<name> and require the `tasks.run` capability. Run one manually with `noxid task run <name>`; adapters own production scheduling.",
),
"realtime" => Ok(
"Noxid realtime\n- Add bare `live` inside a resource declaration to enable compiler-owned invalidation publication. Successful actions, mutating endpoints, and completed queues derive one module-local live target; multiple live candidates require `invalidates [Name]` or `invalidates none`. GET/stream reads never publish and cannot declare invalidation. Existing action invalidation of non-live cache resources is unchanged. Publication follows result validation or durable completion and uses the exact request/restored queue principal.\n- Compiler-owned live publishing follows `[server] storage`: memory/fs use process fan-out, Postgres uses LISTEN/NOTIFY, and Redis extends the first-party RESP connection roles. `[server] live_driver` may override with memory/postgres/redis; `[server] live_coalescing_ms` defaults to 250. A project with live resources or presence must declare a deployment-stable `[app] id` matching `[a-z][a-z0-9_]{0,31}`; replicas and rolling versions reuse it, while unrelated applications sharing a backend use distinct IDs. Topics are derived from that application security domain, semantic IDs, and the runtime-owned canonical principal; invalidations carry no payload, and the substrate is byte-pruned without `live`/presence declarations. Commit and publication are deliberately separate: a post-commit driver failure is reported but cannot pretend to roll application state back.\n- Live resource acquisition has no authored subscription API. The compiler installs one project SSE controller at `<base>/_noxid/live`; mounted live resources register internally and invalidations flow through the existing Refreshing(previous) -> Ready validated refetch lifecycle. The endpoint replays only the compiler-selected route middleware, authorizes each resource capability, partitions by the canonical principal, and emits only semantic resource IDs. Bursts coalesce per resource, dirty in-flight requests earn one trailing refetch, and every fresh/resumed exact set receives a cursor-free sync fence after subscription installation. Resume cursors are bounded to the exact principal, route, and resource set; unsafe cursors reset and invalidate once. Client and server transport bytes are pruned when no resource is live.\n- Declare typed ephemeral membership inside a client-owned component with `presence { ttl 30s name: String = displayName cursor: Optional<Point> = cursor }`. The compiler creates component-qualified record/member/snapshot types and the fixed exhaustive `#stream presence` cases Snapshot, Joined, Updated, Left, Completed, and Failed. There are no authored channels, tokens, member IDs, joins, subscriptions, or transport calls. Fields are reactive; writes and heartbeats serialize; owner disposal leaves; transient failure rejoins from a fresh Snapshot with the same bounded credential; permanent failure closes the typed stream.\n- Presence shares the live SSE controller, canonical WO-40 principal, compiler-selected typed route middleware, pub/sub driver, storage driver, and generic development trace capture door. Storage, rate/lease/sweep keys, logical topics, and physical driver channels are partitioned first by `[app] id`, then by canonical principal plus route instance as appropriate; every external record/event is validated closed. A finite shared lease serializes mutations and TTL repair, and unclean expiry emits one Left without persisting to application tables. Operational abuse/join/member admission accepts bounded authenticated middleware/session identity, bounded host-adapter `environment.requestIdentity`, or a canonical non-system principal independently of visibility; request-controlled forwarding headers are never trusted. Anonymous system-principal writes without one fail 403 before rate buckets are created, and membership is authenticated before selecting a member bucket. SSR/prerender-only ownership and unstubbed scenarios are rejected.\n- Typed server push is `stream endpoint Name { result: Stream<T> timeout: 5m ... }` in `server/api/**/*.get.nox`. The exact `endpoint:<Name>@<version>` host function returns AsyncIterable<T>; every event is validated before compiler-framed SSE emission.\n- Stream endpoint timeout and rate limit apply per connection. Heartbeats and bounded Last-Event-ID resume are generated; body, cache, idempotency, compiler-owned handlers, ordinary endpoint scenarios, non-GET methods, and server/routes placement fail closed. Client code consumes a matching ordinary stream through `streams` and exhaustive `#stream`; WebSocket syntax is not available in phase one.",
),
"observability" => Ok(
"Noxid observability\n- `[server] tracing = \"requests\"` is the default and emits one-line `noxid.trace.v1` request start/end JSON to stdout. Use `\"full\"` for middleware, endpoint/action, refusal, capability-denial, task, queue, queue-worker, and live publish/delivery duration spans keyed by semantic IDs; use `\"off\"` for silence. `[server] tracing_export = \"stdout\"` is the default; select `\"otlp\"` for the first-party OTLP/HTTP JSON exporter. Declare `OTEL_EXPORTER_OTLP_ENDPOINT` and credential-bearing `OTEL_EXPORTER_OTLP_HEADERS` in `[server] secrets`; OTLP without an endpoint declaration fails with `TRACING_EXPORT_ENDPOINT_REQUIRED`. OTLP `service.name` uses the declared `[app] title`, then the package name, then `noxid.application`; set `[server] tracing_service_name` for an explicit deployment identity. `durationMs`/`noxid.duration_ms` appears only for measured intervals; unmeasured starts, refusals, and state transitions omit it. Valid W3C `traceparent` propagates and wins over `x-noxid-trace`; its remote parent attaches only to the request root, while endpoint and loader work nest locally. Span fields are allowlisted: bodies, arguments, queue/live payloads, middleware context, environment data, and secret names or values are never logged. Generated server entry points expose a bounded tracing drain hook; development handlers expose one schema-generic capture door for all spans, while production handlers prune that capture door completely.",
),
"reactivity" => Ok(
"Noxid reactivity\n- state values are signals; computed dependencies are compiler-derived.\n- watch observes selected state; effect owns side effects and cleanup. Neither returns a value.\n- +input/+change/+click are explicit listeners. value:bind is explicit two-way state binding.\n- Call-form handlers +click={remove(item.id)} evaluate arguments when the event fires, so keyed #for rows pass their current values.\n- Actions are batched transactions; `let` locals are not reactive, and struct field assignment replaces the whole signal so subscribers see one change.\n- Resource identity is derived from declaration plus ordered typed arguments; equal identities share one cache entry and in-flight request. Declare `cache 30s`, `refresh on focus`, `refresh on reconnect`, and `refresh every 5m`; unused trigger runtime is pruned.\n- Use `prefetch on hover` / `prefetch on visible` on supported route links or resource-owning component invocations with inputs available before mount. Prefetch fills the ordinary shared cache.\n- Array and Map queries are typed derived expressions whose base, field, and value references remain reactive dependencies; grouping maps update keyed #for regions through the ordinary entries() Array.\n- Dynamic regions own subscriptions and dispose deterministically. `#if condition transition 200ms` keeps the same owner reactive during exit, cancels false-to-true interruption without remounting, and force-disposes at the deadline.\n- #for must have a stable key when identity matters.",
),
"motion" => Ok(
"Noxid motion\n- Property transitions and enter animations use ordinary scoped CSS.\n- Use `#if open transition 200ms { ... }` for a compiler-visible, bounded, interruptible exit lifetime.\n- Use `<ul attach:animate={ duration: 150ms }>` only on an element whose direct dynamic region is a keyed #for. The duration is a bounded literal, not an expression.\n- attach:animate installs after client mount or hydration adoption and is destroyed with the owning Owner; SSR renders unchanged markup.\n- The vetted @formkit/auto-animate adapter and its runtime feature are pruned when no attachment declares them.\n- Unknown names/keys, non-keyed containers, and direct exit-transition conflicts fail with structured teaching diagnostics.",
),
"remote-actions" => Ok(
"Noxid typed remote actions\n- A client action may perform one top-level sequential remote await: `let outcome = await siblingRemote(name: value)`.\n- Every remote argument is named and statically checked against the sibling server, edge, or worker action.\n- Consume the binding immediately and exhaustively with `#match outcome { Ok(value) { ... } Err(error) { ... } }`.\n- The result is `Result<T, RemoteError>`; RemoteError has compiler-owned String fields `code` and `message`, so remote failure is not a JavaScript exception channel.\n- State writes before await commit in the first action transaction. The remote boundary runs outside a transaction; the selected arm and following statements run in a second transaction.\n- After success, resource invalidation is graph-derived when exactly one target exists. Multiple candidates fail with `AMBIGUOUS_RESOURCE_INVALIDATION`; write `invalidates [Products]` or `invalidates none` on the remote action. Failures do not invalidate.\n- There is no implicit retry, parallel await, cancellation, discarded result, or nested await in v1. Unsupported shapes fail with structured diagnostics.\n- Executable scenarios must stub the exact boundary with `given action = Ok(<literal>)` or `given action = Err(RemoteError(code = \"...\", message = \"...\"))`. Unstubbed remote awaits fail closed and never reach the network.\n- SSR never executes actions, and production runtime options cannot forge scenario boundary stubs.",
),
"ssr" => Ok(
"Noxid rendering\n- Client is the default. route render: ssr plus render { mode: universal } enables SSR and hydration.\n- Default-slot children render through a parent-scope server thunk; eager hydration adopts the matching slot marker range and preserves node identity. Deferred-hydration islands with slot children are rejected.\n- On SSR routes, default-slot children keep the parent's scope; eager hydration adopts their server marker range without recreating DOM. Deferred-hydration islands with slot children fail closed.\n- SSR-validated resource snapshots seed the shared client cache with the server `renderedAt` timestamp. Transit time counts toward `cache <duration>`, so an already-stale snapshot hydrates as Refreshing rather than restarting its TTL.\n- Exit-transition timing is client-only: SSR renders the final #if state, while eager hydration adopts a true region and then enforces its declared owned deadline.\n- Server-only components emit no browser module. Islands hydrate by declared strategy.\n- Use loaders for request data and keep host implementations in the auto-detected server/host.ts (or server/host.js); [server] runtime and secrets remain in Noxid.toml, but [server] entry was removed.\n- Keep shared server modules under server/utils/. Global server middleware in server/middleware/ runs before route middleware on SSR documents and action requests.\n- Build output is route-isolated and exposes a server fetch handler only when needed.",
),
"testing" => Ok(
"Noxid testing\n- `noxid test` writes exactly one line to stdout: the JSON report. The run's logs and every [server] tracing record go to stderr as NDJSON, so stdout parses as one JSON object even under `tracing = \"full\"`.\n- Write `scenario Name` blocks beside the component behavior they verify.\n- `given: state = literal` accepts deterministic typed literals only.\n- Stub an owned resource with its closed lifecycle, such as `given customers = Ready([...])`; add deterministic cache age with `given customers = Ready([...]) aged 45s`. `aged` requires a cached resource and Ready/Refreshing data; unaged givens pass no age.\n- Resource scenario seeds are compiler-authorized and non-I/O. Successful stubbed remote mutations still apply derived or explicit invalidation; `invalidates none` preserves Ready. Request-count/dedup proof belongs in runtime behavioral tests because scenarios have no request-count or JavaScript escape expression.\n- Stub an owned stream with a finite typed event array, such as `given feed = [Started, Completed(result)]`. Compiler-owned presence uses the same closed boundary: `given presence = [Snapshot(...), Joined(...), Left(\"member-id\")]`; scenario expressions may assert the exact sequence, but actions and general views cannot inspect the buffer.\n- Only acquisitions named by validated givens are stubbed, so resource factories, network requests, stream connectors, and live presence transport do not run. Agents and unstubbed external boundaries fail closed.\n- Coalescing and principal isolation are transport properties, proven against the generated memory driver with two canonical principals and exactly one same-principal delivery; do not invent scenario counters or a JavaScript escape.\n- `when: action(args)` invokes compiler-checked client actions; remote actions fail closed.\n- A task scenario uses `when: run()` to invoke its handler directly. A bodyless task may be stubbed with `given: TaskName = value`; the scheduler is never mocked, and compiler-owned task handlers cannot be replaced.\n- Test the loop with a `scenario` block on the agent: `given: agent Name = turns [ text \"...\", tool <Endpoint> { field = value }, final { field = value } ]`, optional `given: authorizer defers <capability>`, `when: run(input: <typed input>, resume: true)`, and `expect:` over emitted, tools, output, refusal, paused, resumed, turns. Scripted turns are checked against the registry and the tool endpoint's contract at build time; an unscripted turn fails MODEL_STUB_REQUIRED and never reaches a provider.\n- Endpoint scenarios use `given: [\"file <body-field> bytes <canonical-base64> as <mime>\"]` for deterministic success, oversize, and wrong-magic cases.\n- `expect: booleanExpression` observes state and computed values through the ordinary typed expression grammar.\n- Typed `invariant` assertions run after mount, after every given, and after every action; a breach stops later steps and reports its semantic ID, checkpoint, expression, and actual referenced values.\n- Equal arrays, maps, structs, and tagged variants compare recursively by language value, so a compound literal given can be asserted directly.\n- Run `noxid test <file-or-project> --gate`; stdout is deterministic JSON and stderr is the human summary.\n- `--gate` requires every requirement to have a passing covering scenario and rejects prose-only scenarios.\n- Use local read-scoped MCP `run_scenarios` for the same JSON report, or `run_affected_tests` to execute only graph-selected scenarios; neither operation writes project files.\n- Pagination/infinite resources and automatic optimistic rollback are phase 2; do not invent scenario syntax for them.\n- Prose steps and prose invariant assertions are migration documentation, not proof, and emit warnings.\n- Scenario execution uses compiler-emitted component or task JavaScript and the feature-pruned runtime rather than a Rust interpreter.\n- Endpoint and queue boundaries may declare `property Name { runs: 100 expect: validates or refuses }` or `expect: refusal is structured`; this is a closed vocabulary.\n- Property generation is deterministic from the property identity plus run index and mixes compiler-known type categories with the versioned hostile corpus, including getter, prototype-key, and cyclic JS shapes.\n- Property failures report the exact seed, faithful shrunk JavaScript value, and a paste-ready seeded CLI replay command. Omitted runs default to 100, and `--gate` enforces a 100-run floor.\n- Tasks have no input contract, so task properties fail closed; use task scenarios for cron handler behavior.\n- Pagination/infinite resources, property roundtrip, custom property predicates, and automatic optimistic rollback are later phases; do not invent syntax for them.\n- Property execution uses compiler-emitted boundary-validator JavaScript and the feature-pruned runtime rather than a Rust interpreter.\n- On an input with multiple properties, replay with `--seed <n> --property <semantic-id>`; the selector prevents one property's seed from being applied to another. Run replay separately from `--gate`, which always owns the full 100-run floor. A boundary's `timeout:` bounds validator CPU time after import; the runner also kills validation after that timeout plus a 1s wall-clock backstop so synchronous hangs stay killable.",
),
"semantic-tools" => Ok(
"Noxid semantic tools\n- Start with query_project operation=summary and reuse its snapshot.\n- Use operation=delta with since=<snapshot> after edits.\n- Set limit/maxBytes on queries.\n- semantic_edit accepts a stable-ID operation and JSON payload, validates, then requires confirmation.\n- validate_project returns structured diagnostics and a repairPlan.\n- Every classified diagnostic carries classification (automatic|review), rewrite, the uniqueness condition, the before/after span text, and the alternatives the diagnostic already enumerates. Read alternatives instead of guessing a name.\n- `noxid repair <file|project>` plans only and writes nothing; `--safe` applies just the automatic set as one compiler-revalidated transaction and restores byte-exact originals on failure.\n- A multi-file rename is not atomic on POSIX, so the promise is about the compiler's view: every command that reads project sources settles an interrupted `repair --safe` before it reads a source byte. A journal whose renames all finished is completed; any other rolls back to the originals byte for byte. You never need to run `repair` to clean up after one — `check` will do it, and says so on stderr with the transaction id.\n- A repair is automatic only when the diagnostic determines it uniquely: array `.length` to `count()`, a single near-candidate rename for a collection query, function, or field, `toFloat(...)` on the Int side of an Int/Float mix, an Int literal in a declared Float position, dropping a pure `??` fallback, one expected punctuation token, and a mismatched closing tag. Each applied repair carries a proof: the recompile, the noxid drift result, and the graph scope it stayed inside.\n- Everything else is review with a concrete proposed edit: missing cases, placeholder values, duplicates, units, imports, accessibility meaning, and every security or styling boundary. Apply those yourself; the compiler will not.\n- `noxid dev` exposes a development-only semantic panel with compiler/build overview, exact route matching, bounded graph/impact traversal, reverse DOM ownership, and reduced {id,title,description?} route cards. Impact follows emitted graph edges only and never invents cross-wire relationships.\n- Production runtimes prune the panel, recorder, and DevTools runtime feature; app.devtools.json remains inert compiler metadata.\n- The published context surface is budgeted the same way as query_project: `llms.txt` indexes every `llms/<topic>.txt` chunk with its exact byte size and a one-line scope (each chunk at most 24 KB), and the MCP describe operation takes kind=guide for one agent-guide topic. Point a model at the index and a chunk, never at `llms-full.txt`.\n- stdio is preferred; MCP HTTP is loopback-only and bearer authenticated.",
),
_ => Err(format!("unknown agent-guide topic `{topic}`")),
}
}
fn compiler_example(name: &str) -> Result<&'static str, String> {
match name {
"counter" => Ok(
"component Counter {\n state { count: Int = 0 }\n computed { doubled = count * 2 }\n actions { increment() { count = count + 1 } }\n view { <button +click={increment}>Count {count}; double {doubled}</button> }\n}",
),
"routed-app" => Ok(
"src/routes/+page.nox\ncomponent HomePage {\n route { title: \"Home\" }\n view { <main><h1>Home</h1><a href=\"/about\">About</a></main> }\n}",
),
"reactive-effects" => Ok(
"state { query: String = \"\" change: String = \"Waiting\" }\ncomputed { label = \"Filter: \" + query }\neffects { watch query as recordQuery(current, previous) { change = previous + \" -> \" + current } }\nview { <input value:bind={query} /><p>{label}</p><p>{change}</p> }",
),
"keyed-list" => Ok(
"state { items: Array<Int> = [1, 2, 3] }\nview { <ul>#for item in items key item { <li>{item}</li> }</ul> }",
),
"interactive-list" => Ok(
"state { items: Array<Int> = [1, 2, 3] selected: Int = 0 }\nactions {\n select(value: Int) { selected = value }\n drop(value: Int) { items.remove(value) }\n}\nview {\n <ul>\n #for item in items key item {\n <li>\n {item}\n <button +click={select(item)}>select</button>\n <button +click={drop(item)}>delete</button>\n </li>\n }\n </ul>\n #if selected > 0 {\n <p>selected: {selected}</p>\n } #else {\n <p>nothing selected</p>\n }\n}",
),
"state-machine" => Ok(
"machine Request { Idle; Loading; Ready(String); Failed(String); Idle -> Loading on submit; Loading -> Ready on resolve; Loading -> Failed on reject; }\nstate { request: Request = Idle }\n#match request { Idle { <p>Idle</p> } Loading { <p>Loading</p> } Ready(value) { <p>{value}</p> } Failed(message) { <p>{message}</p> } }",
),
_ => Err(format!("unknown compiler example `{name}`")),
}
}
#[cfg(test)]
mod tests {
use super::scaffold::scaffold_project;
use super::{agent_guide, ensure_noxid_source, parse_headless_recipe, parse_vue_island_field};
use std::fs;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn accepts_noxid_sources() {
assert!(ensure_noxid_source(Path::new("Counter.nox")).is_ok());
}
#[test]
fn rejects_non_noxid_sources() {
let error = ensure_noxid_source(Path::new("Counter.txt")).unwrap_err();
assert!(error.contains("`.nox`"));
}
#[test]
fn parses_typed_vue_island_fields() {
let field = parse_vue_island_field("value:Optional<String>").unwrap();
assert_eq!(field.name, "value");
assert_eq!(field.ty, "Optional<String>");
assert!(parse_vue_island_field("value").is_err());
}
#[test]
fn headless_recipe_names_are_closed() {
assert!(parse_headless_recipe("Dialog").is_ok());
assert!(parse_headless_recipe("Tabs").is_ok());
assert!(parse_headless_recipe("UnknownWidget").is_err());
}
#[test]
fn core_agent_guide_exposes_the_closed_scalar_builtin_vocabulary() {
let guide = agent_guide("core").expect("core guide");
for builtin in [
"len",
"contains",
"startsWith",
"trim",
"lower",
"upper",
"min",
"max",
"abs",
"round",
"floor",
"ceil",
"toFloat",
"toInt",
"toString",
] {
assert!(guide.contains(builtin), "core guide omitted `{builtin}`");
}
assert!(guide.contains("free functions, not methods"));
assert!(guide.contains("toInt truncates toward zero"));
}
#[test]
fn remote_action_agent_guide_exposes_the_closed_await_contract() {
let guide = agent_guide("remote-actions").expect("remote action guide");
for contract in [
"one top-level sequential remote await",
"Result<T, RemoteError>",
"second transaction",
"given action = Ok",
"Unstubbed remote awaits fail closed",
] {
assert!(
guide.contains(contract),
"remote guide omitted `{contract}`"
);
}
}
#[test]
fn agent_guides_describe_the_auto_discovered_server_layout() {
let routing = agent_guide("routing").expect("routing guide");
for contract in [
"server/route-middleware/<name>.ts",
"server/middleware/",
"lexical filename order",
"no registration is required",
"server/api/",
"endpoint:<Name>@<version>",
"server/security.manifest.json",
"one JSON-array query value",
"description: \"...\"",
"api.openapi.json",
"x-noxid-signature",
"[server] api_docs = true",
"[server] mcp = true",
"/_noxid/openapi.json",
"/_noxid/mcp",
"default false and 404",
"surfaces",
"api-contract.json",
"API_CONTRACT_BREAKING_CHANGE",
] {
assert!(
routing.contains(contract),
"routing guide omitted `{contract}`"
);
}
// WO-53 split the oversized routing guide into routing/storage/realtime.
// The persistence and background-work surface now lives in `storage`.
let storage = agent_guide("storage").expect("storage guide");
for contract in [
"noxid:server",
"storage(namespace)",
"server/db/migrations/",
"DATA_SCOPE_VIOLATION",
"server/queues/<name>.nox",
"queue:<Name>",
"noxid queue work",
"noxid queue status",
"queue_worker = true",
"server/plugins/*.{ts,js}",
"frozen { environment, storage, host }",
"server/tasks/<name>.nox",
"exactly five fields and no seconds",
"task:<Name>",
"server/tasks.manifest.json",
"POST /_noxid/tasks/<name>",
"tasks.run",
"noxid task run <name>",
] {
assert!(
storage.contains(contract),
"storage guide omitted `{contract}`"
);
}
// Merging WO-53 with main's tracing growth pushed `routing` over the
// 6 KB budget, so the `[server] tracing` surface split off into its own
// `observability` topic under the same rule that produced `storage`,
// `realtime`, and `types`.
let observability = agent_guide("observability").expect("observability guide");
for contract in [
"tracing = \"requests\"",
"noxid.trace.v1",
"x-noxid-trace",
"tracing_service_name",
"secret names or values are never logged",
] {
assert!(
observability.contains(contract),
"observability guide omitted `{contract}`"
);
}
// The live/presence/stream surface now lives in `realtime`.
let realtime = agent_guide("realtime").expect("realtime guide");
for contract in [
"stream endpoint Name",
"AsyncIterable<T>",
"Last-Event-ID",
"matching ordinary stream",
"WebSocket syntax is not available",
"presence {",
] {
assert!(
realtime.contains(contract),
"realtime guide omitted `{contract}`"
);
}
// Moved contracts must not linger in routing.
for moved in [
"server/queues/<name>.nox",
"stream endpoint Name",
"presence {",
"DATA_SCOPE_VIOLATION",
"server/plugins/*.{ts,js}",
"server/tasks/<name>.nox",
"noxid.trace.v1",
] {
assert!(
!routing.contains(moved),
"routing guide should no longer contain moved contract `{moved}`"
);
}
let ssr = agent_guide("ssr").expect("SSR guide");
for contract in [
"auto-detected server/host.ts",
"[server] entry was removed",
"server/utils/",
"SSR documents and action requests",
] {
assert!(ssr.contains(contract), "SSR guide omitted `{contract}`");
}
assert!(!routing.contains("src/middleware/server/"));
assert!(!ssr.contains("src/server.js"));
}
#[test]
fn agent_guide_topics_are_budgeted_and_context_first() {
// WO-53: every agent-guide topic must fit a model's window (<= 6 KB)
// and open with the context-first instruction, so a model routes through
// query_project { operation: "context" } before loading reference prose.
const MAX_TOPIC_BYTES: usize = 6 * 1024;
for topic in [
"core",
"scaffolding",
"interop",
"types",
"routing",
"storage",
"realtime",
"observability",
"reactivity",
"motion",
"remote-actions",
"ssr",
"testing",
"semantic-tools",
] {
let guide = agent_guide(topic).expect("known guide topic");
assert!(
guide.len() <= MAX_TOPIC_BYTES,
"agent-guide topic `{topic}` is {} bytes, over the {MAX_TOPIC_BYTES}-byte budget",
guide.len()
);
assert!(
guide.starts_with(super::CONTEXT_PREAMBLE),
"agent-guide topic `{topic}` did not open with the context-first instruction"
);
}
}
#[test]
fn testing_agent_guide_exposes_direct_task_scenarios() {
let testing = agent_guide("testing").expect("testing guide");
for contract in [
"when: run()",
"given: TaskName = value",
"scheduler is never mocked",
"compiler-owned task handlers cannot be replaced",
] {
assert!(
testing.contains(contract),
"testing guide omitted `{contract}`"
);
}
}
#[test]
fn semantic_tools_agent_guide_exposes_phase_one_devtools_contract() {
let guide = agent_guide("semantic-tools").expect("semantic tools guide");
for contract in [
"classification (automatic|review)",
"proof: the recompile, the noxid drift result",
"Everything else is review with a concrete proposed edit",
"exact route matching",
"bounded graph/impact traversal",
"reverse DOM ownership",
"{id,title,description?}",
"never invents cross-wire relationships",
"Production runtimes prune",
"app.devtools.json remains inert compiler metadata",
] {
assert!(
guide.contains(contract),
"semantic tools guide omitted `{contract}`"
);
}
}
#[test]
fn agent_guides_expose_the_resource_cache_algebra() {
let reactivity = agent_guide("reactivity").expect("reactivity guide");
for contract in [
"declaration plus ordered typed arguments",
"refresh on focus",
"refresh on reconnect",
"refresh every 5m",
"prefetch on hover",
"unused trigger runtime is pruned",
] {
assert!(
reactivity.contains(contract),
"reactivity guide omitted `{contract}`"
);
}
let remote = agent_guide("remote-actions").expect("remote guide");
for contract in [
"AMBIGUOUS_RESOURCE_INVALIDATION",
"invalidates [Products]",
"invalidates none",
"Failures do not invalidate",
] {
assert!(
remote.contains(contract),
"remote guide omitted `{contract}`"
);
}
let testing = agent_guide("testing").expect("testing guide");
for contract in [
"Ready([...]) aged 45s",
"compiler-authorized and non-I/O",
"unaged givens pass no age",
"Pagination/infinite resources",
"automatic optimistic rollback",
"given presence = [Snapshot(...), Joined(...), Left",
"exactly one same-principal delivery",
] {
assert!(
testing.contains(contract),
"testing guide omitted `{contract}`"
);
}
let ssr = agent_guide("ssr").expect("SSR guide");
assert!(ssr.contains("renderedAt"));
assert!(ssr.contains("Transit time counts"));
}
#[test]
fn universal_scaffold_uses_the_auto_discovered_server_host() {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock after Unix epoch")
.as_nanos();
let root = std::env::temp_dir().join(format!(
"noxid-universal-scaffold-{}-{nonce}",
std::process::id()
));
scaffold_project(&root, "counter", Some("universal")).expect("scaffold universal project");
let manifest = fs::read_to_string(root.join("Noxid.toml")).expect("read manifest");
assert!(manifest.contains("[server]\nruntime = \"node\""));
assert!(!manifest.contains("entry ="));
assert!(root.join("server/host.js").is_file());
assert!(!root.join("src/server.js").exists());
fs::remove_dir_all(&root).expect("remove scaffold fixture");
}
}