moonlint

    MoonImpact: change-impact and selective regression-test planning for MoonBit modules and Vue/TypeScript projects, written in MoonBit. Also ships the moonlint convention linter.

    moonbit
    static-analysis
    cli
    change-impact
    test-planning
    developer-tools
    Download zip
    Author
    Version
    0.3.1
    License
    Apache-2.0
    Last updated
    48 minutes ago
    Downloads
    3

    #MoonImpact

    MoonImpact answers one question for a code change: which tests should run, and why. It is written in MoonBit and plans two project kinds:

    • MoonBit modules and workspaces (no configuration needed): package graphs are read from moon.pkg manifests. A root moon.work limits discovery to its explicit members and enables declared imports between member modules; ordinary, for "test" and #cfg import blocks all count. A changed file selects its owning package plus every transitive importer, and --run invokes moon test per selected package. Unsupported workspace syntax falls back to the full suite.
    • JS/TS projects (explicit moonimpact.json): static imports, bounded file-read and reader-wrapper inference, CSS/SCSS input chains, literal import.meta.glob patterns, directory reads and existence checks.

    Either way the plan is explainable: every selected test carries one deterministic shortest evidence chain, and anything the model detects as unmodeled requests the full suite instead of silently claiming "no impact". A plan is advisory, never a passing test result.

    The model can only prove the links it can see. A dependency that is never declared in a manifest is invisible to it, so a plan is not proof that every affected package was selected.

    moon build --target native # A MoonBit module: this repository is one. moon run cmd/impact -- plan --file impact_plan.mbt . moon run cmd/impact -- plan --file cmd/impact/main.mbt . # A MoonBit workspace with declared cross-module imports. moon run cmd/impact -- plan --file shared/shared.mbt \ examples/workspace-demo # A JS/TS project with its explicit configuration. moon run cmd/impact -- plan --file src/fees.ts \ --config examples/impact-demo/moonimpact.json examples/impact-demo

    Planning never runs tests, builds or installs dependencies; only --run executes the project's own runner with fixed arguments. Read the MoonImpact guide for both modes, the synthetic JS/TS demo and MoonBit workspace fixture, Git input, JSON/HTML reports and execution safety.

    Measured, not promised. On the public moonbitlang/x monorepo, pinned at commit 6b67e08 (25 packages, 19 holding tests), the plan was executed with --run and compared against the full suite:

    ChangePlanFull suiteSelected runWall time (cold)
    encoding/encoding.mbt4 / 19 packages795 tests175 tests4.67s → 0.57s
    decimal/decimal.mbt1 / 19 packages795 tests27 tests4.67s → 0.48s

    Injected faults were caught by the selection. Writing UTF-16 big-endian output as little-endian caused two encoding test failures. Together with the pre-existing crypto failure, the 4-package selection failed exactly the same three tests as the 795-test full suite. A fault in decimal's normalization was caught by the 1-package selection. Details, including the one pre-existing unrelated failure in the subject project, are in the round-five record.

    On the public wot-lynx-ui monorepo a core-utility change selects 71 of 135 test files with a 44% wall-clock reduction, and an injected off-by-one is caught by the selected subset. That wot-lynx-ui number was measured on a working tree that also holds the project's optional, git-ignored .wot-ref reference copy; on a fresh clone the five .wot-ref declarations report unresolved-explicit-dependency and the plan honestly falls back to full (135/135) — see the round-three record. Selective reduction is a per-project property, not a guarantee.

    The repository also contains moonlint, the convention and project-policy linter this tool grew from: cmd/main keeps its CLI, module identity, license notices and history intact, and MoonImpact reuses its source and filesystem foundations. The two entry points are independent.

    #How MoonImpact decides

    Given a set of changed files, MoonImpact answers three questions: which tests have a known dependency on the change, what reference chain explains each selection, and why a run must fall back to the full suite or be blocked.

    KindDetectionTest unitRunner (--run)
    MoonBit module/workspace (default)root holds moon.mod / moon.mod.json or moon.work, no --configpackagemoon test <package> per selected package
    JS/TS projectexplicit --config moonimpact.jsontest filepnpm exec vitest run with ./test-path filters

    For a MoonBit module the package graph is read straight from the moon.pkg manifests. At a workspace root, moon.work explicitly scopes inventory to its member modules and declared local imports connect packages across those members. Its supported form is a nonempty literal members = [...] list of root-relative directories; unsupported syntax, missing members or ambiguous local imports request the full suite. A changed file selects the package that owns it plus every package that transitively imports it.

    The four strategies are honest about their own reach:

    StrategyMeaning
    relatedselected test files or packages have a known dependency chain to the change
    fullthe model cannot narrow the change safely, so the full Vitest suite or unfiltered moon test is requested
    noneno changes, or no affected test files or packages with tests under the supported model
    blockedan I/O or unsafe-path condition prevents execution

    A plan is advisory and is never a passing test result. Nothing is executed unless --run is passed, and --run is not a sandbox.

    #Reproducing the measurement

    moon build --target native BIN="$PWD/_build/native/debug/build/cmd/impact/impact.exe" # The public subject project, pinned at commit 6b67e08: git clone https://github.com/moonbitlang/x /tmp/x-checkout git -C /tmp/x-checkout checkout 6b67e08 # Full suite in the subject project, then the selected subset through the tool. ( cd /tmp/x-checkout && moon test ) "$BIN" plan --file encoding/encoding.mbt --run /tmp/x-checkout

    The pinned commit is deliberate: during the round-five verification, the upstream HEAD used @io.ReaderClosed in its fs package, which the recorded local toolchain's core did not export. That checkout did not compile with that toolchain; this records version skew, not a planning defect or a claim about upstream's current build status.

    #Verification records

    Each record is a separate round of measurement, with its subject, commands and boundaries stated in the record itself:

    RecordSubjectWhat it establishes
    Initial MoonImpact verificationinitial MVPthe JS/TS impact MVP on a first evaluation project
    Round twoMVP, extendedstatic readers, symbolic paths and stylesheet inputs
    Round threewot-lynx-ui (JS/TS)whole-tree membership, declaration contract, real-project selective execution
    Round fourmoonbitlang/x (MoonBit)the MoonBit front end and its planning measurements
    Round fivemoonbitlang/x (MoonBit)end-to-end selective execution and fault injection on a pinned commit

    Round six (Chinese) records the source-layout, inline-test and full-execution fixes. Round seven (Chinese) expands the pinned corpus to seven public projects, with executable inventory and fault comparisons.

    #The moonlint linter

    The rest of this document describes moonlint, the convention and project-policy linter this tool grew from. It keeps its own CLI (cmd/main), its presets, its baselines and its history. MoonImpact reuses its source and filesystem foundations; the two entry points are independent.

    #Why this exists

    moon check checks compilation and includes the optional W74 missing_doc warning (disabled by default); moon fmt formats code. moonlint does not replace either. It puts project conventions, exception budgets, package-layer constraints and historical public-interface review into explicit CI checks. ESLint and Biome's supplied JS/TS parsers do not parse MoonBit; their JS/TS checks remain useful in mixed repositories.

    The source frontend is a lexical/declaration scanner, not a complete AST or binding/type resolver. A clean lint result is not proof that source compiles. Always run moon check separately.

    #Origin

    moonlint began as a MoonBit rewrite of the review-lint script in ximo-156/wot-lynx-ui, a Vue Lynx component library. The referenced script is scripts/review-lint.mjs; its MIT notice names 2026 wot-lynx-ui contributors. The rule catalogue informed the compatibility presets. This is a reference/porting relationship, not an independently proven absence of copied code. This repository declares Apache-2.0 in LICENSE; see third-party attribution.

    The local manifest now targets 0.3.0 because public result fields and structural-check variants changed. The verification records describe specific local runs, not a published release. The MoonBit module-planning work was committed in 1a5d8ce (2026-11-12); see the verification records for the scope of each run.

    #What it does

    moonlint scans a directory tree, applies declarative rules to each source file, and reports violations. Rules are loaded from JSON, so the same engine can enforce any project's conventions. MoonBit files are read by a declaration scanner that associates non-empty /// documentation with top-level items; ///| alone is only a block separator. JS/TS files are read by the tokenizer and import-graph layers.

    #Features

    • MoonBit first — the moonbit preset covers public documentation, naming, unwrap() / panic(), println() and TODO comments; test files are excluded recursively and CLI entry points are excluded from the print rule
    • Config-driven — rules defined in JSON, no code changes needed
    • JS/TS compatibility presets — ready-to-use rule sets for React, Vue, Angular, Svelte, Next.js, SolidJS, Astro, Nuxt, common JS/TS hygiene, file-level checks and cross-file import checks; activate with --preset <name>
    • Regex + substring matching — contains, prefix, suffix, regex, equals and word matchers
    • Matcher combinators — all / any / not nest within bounded parser limits, so match expresses any boolean formula over the leaf matchers
    • Negative guards — unless field to suppress false positives (e.g. "import from 'vue' but not 'vue-lynx'")
    • Comment-aware — // and /* */ comments are blanked out before matching, preserving line numbers and columns; in JS/TS/JSX files the scanner understands template literals, ${} interpolations, strings and regex literals, so a // inside a template string is text, not a comment. The default code view also blanks literal contents, so const q = "FORBIDDEN" is not code; rules whose target only exists as a literal value opt in with "match_literals": true, and rules that target comments opt in with "match_comments": true
    • Cross-file structural rules — a JS/TS tokenizer + parser builds a project-wide import graph, powering unused imports, duplicate imports, unresolved relative imports, import cycles, deep relative imports, require() usage, export default and dead exports (--preset imports)
    • Baseline v2 — explicit, count-limited content exemptions with reason, owner, expiry and full-tree unused-budget audits; legacy arrays remain readable
    • Package policies — direct dependency constraints over supplied compiler v3 package graphs, with separate source/test/wbtest kinds and backend selection
    • API review gate — historical .mbti declaration snapshots identify removals and conservative shape changes; optional semver policy records intentional breaking releases
    • Incremental caching — --incremental re-lints only files whose content hash changed, invalidated automatically when the effective config changes
    • Severity levels — error and warning, with exit code 1 on any error-severity finding
    • Scoped findings — global and per-rule include/exclude control reports; unselected/excluded dependency files may still be read as explicitly counted project context
    • CI output — machine-readable JSON reports, GitHub Actions annotations and SARIF 2.1.0, with read / failure / skip metadata
    • Honest counters — every selected file is reported as scanned, skipped (with a reason) or failed; a scan never silently degrades to "clean"
    • Summary mode — per-rule tally plus read/skip/failure counts

    #Installation

    # Clone and build git clone https://github.com/ximo-156/wot-lynx-ui-moonbit cd wot-lynx-ui-moonbit moon build --target native

    #Usage

    Run the linter from this checkout with moon run cmd/main --. Examples below that use the shorter moonlint command assume you have placed the built _build/native/debug/build/cmd/main/main.exe on your PATH as moonlint; moon build alone does not install that command.

    # Create a MoonBit starter config in the current directory moon run cmd/main -- --init # Lint a MoonBit package with the built-in preset moon run cmd/main -- --preset moonbit packages/ # Lint with the generated config moon run cmd/main -- . # Lint a specific directory moon run cmd/main -- /path/to/project # Use a custom config moon run cmd/main -- --config my-rules.json /path/to/project # Summary mode moon run cmd/main -- --summary /path/to/project # Only show errors moon run cmd/main -- --errors-only /path/to/project # Generate a baseline (exempts all current findings) moon run cmd/main -- --update-baseline /path/to/project # Use a baseline moon run cmd/main -- --baseline moonlint.baseline.json /path/to/project # Machine-readable JSON report on stdout, and written to a file moon run cmd/main -- --format json /path/to/project moon run cmd/main -- --report moonlint-report.json /path/to/project # GitHub Actions annotations moon run cmd/main -- --format github /path/to/project # Cross-file import checks for a JS/TS compatibility scan moon run cmd/main -- --preset imports /path/to/project # Fast repeated scans: only changed files are re-linted moon run cmd/main -- --incremental /path/to/project

    #Built-in Presets

    The primary preset is moonbit. The JS/TS presets are compatibility sets for repositories that also contain frontend code. Activate one or more with --preset <name> (repeatable); rules from multiple presets are merged with de-duplication by rule id.

    # List available presets moon run cmd/main -- --list-presets # Lint MoonBit sources moon run cmd/main -- --preset moonbit packages/ # Lint a React project moon run cmd/main -- --preset react /path/to/project # Lint a Vue project moon run cmd/main -- --preset vue /path/to/project # Combine presets (e.g. React + common hygiene) moon run cmd/main -- --preset react --preset common /path/to/project

    --preset and --config are mutually exclusive. An unknown preset name is a usage error (exit code 2).

    #Available presets

    PresetExtensionsRulesFocus
    moonbit.mbt6 structural rulesMoonBit: require-public-doc, naming, no-unwrap, no-panic, no-println, no-todo-comment
    common.js .jsx .ts .tsx .mjs .cjs .vue .svelte .astro6Framework-agnostic hygiene: no-console-log, no-debugger, no-alert, no-eval, no-var, no-todo-comment
    react.jsx .tsx20React/JSX: no-danger, no-string-refs, jsx-key, self-closing, target-blank, button-type, ...
    vue.vue .js .ts11Vue 3: no-v-html, require-v-for-key, no-v-if-with-v-for, require-scoped-style, ...
    angular.ts9Angular: no-input-rename, no-output-native, no-forward-ref, relative-url-prefix, ...
    svelte.svelte8Svelte: no-at-html, require-each-key, a11y-missing-attribute, no-goto-without-base, ...
    next.jsx .tsx .js .ts7Next.js: no-img-element, no-head-element, no-html-link-for-pages, google-font-display, ...
    solid.jsx .tsx6SolidJS: no-innerhtml, prefer-for, no-react-imports, event-directives, ...
    astro.astro5Astro: no-set-html-directive, prefer-class-list, no-unused-define-vars, ...
    nuxt.vue .js .ts5Nuxt: no-env-in-runtime, prefer-use-fetch, no-window-in-ssr, ...
    file.js .jsx .ts .tsx .mjs .cjs .vue .svelte .astro6 file rulesFile-level: max-lines, max-line-length, no-trailing-whitespace, no-tabs, final-newline, no-duplicate-lines
    imports.js .jsx .ts .tsx .mjs .cjs .mts .cts .vue .svelte .astro7 structural rulesCross-file: no-unused-imports, no-duplicate-imports, no-unresolved-relative-imports, no-import-cycles, no-deep-relative-imports, no-require-imports, no-unused-exports

    The moonbit preset's documentation and naming rules check top-level public items. Its call and TODO rules also inspect regular implementation code. *_test.mbt and *_wbtest.mbt are excluded recursively; cmd/** is excluded from the no-println rule because CLI entry points print by design.

    Every preset is also shipped as a standalone JSON file under presets/ (angular, astro, common, file, imports, moonbit, next, nuxt, react, solid, svelte, vue) for users who prefer to copy and customize them:

    moon run cmd/main -- --config presets/react.json /path/to/project

    Note: The framework presets are line-oriented — they match one source line at a time, after comments have been blanked out. Rules that need an AST (unused variables, hook dependencies, prop types) are intentionally absent from those presets; the imports preset instead uses best-effort cross-file import analysis (see Cross-File Structural Rules). The moonbit preset goes through a declaration scanner instead of the JS/TS parser; it reads non-empty documentation and top-level items, and it skips *_test.mbt / *_wbtest.mbt because tests may unwrap, panic and print.

    #Matcher Types

    A matcher object has exactly one of:

    • { "contains": "substring" } — line contains the substring
    • { "prefix": "text" } — line starts with the text
    • { "suffix": "text" } — line ends with the text
    • { "regex": "pattern" } — line matches the regex
    • { "equals": "text" } — trimmed line equals the text exactly
    • { "word": "text" } — line contains the text as a whole word

    #Matcher combinators

    Any matcher — including unless — may instead be a boolean combination of matchers, nested within bounded parser limits:

    • { "all": [ … ] } — every sub-matcher must match (an empty list matches every line)
    • { "any": [ … ] } — at least one sub-matcher must match (an empty list matches no line)
    • { "not": { … } } — the sub-matcher must not match

    { "id": "common/no-unguarded-console", "severity": "warning", "message": "console.log without a lint exemption", "extensions": [".ts"], "match_comments": true, "match": { "all": [ { "contains": "console.log" }, { "not": { "any": [ { "word": "allow" }, { "contains": "moonlint-ok" } ] } } ] } }

    This fires on console.log(x) but not on console.log(x) // moonlint-ok. The explicit match_comments option lets the guard see the comment marker; this also makes the rule inspect literal text and comments as written. A bad regex nested inside a combinator is a config error (exit 2), reported with the path to the offending sub-matcher.

    #Matching inside comments

    Line rules normally see the comment-stripped view of a file: comments are blanked to spaces before matching, so a stringified script or a URL fragment never looks like code. A rule that targets comments themselves — a no-TODO rule, say — opts into the raw view instead:

    { "id": "common/no-todo-comment", "severity": "warning", "message": "TODO/FIXME comment left in code", "extensions": [".ts"], "match": { "any": [ { "word": "TODO" }, { "word": "FIXME" } ] }, "match_comments": true }

    match_comments is per-rule and defaults to false. The opt-in sees the file exactly as written — line and block comments included, but strings and template literals too, since those are also "raw". The unless guard and inline // moonlint-disable comments apply as usual.

    #Matching inside literals

    The default view — the code view — blanks the contents of string, template and regex literals in JavaScript/TypeScript/JSX sources, so const q = "FORBIDDEN" is not code and no rule matches it. This aligns the JS/TS line matcher with the MoonBit front end, which has always blanked literal contents. Deliberately preserved: the delimiters (", ', ` , /), so attribute-shaped matches such as ref=" still work, and ${...} interpolations, because an interpolation is an expression, not a value. Line and column positions are unchanged. .vue, .svelte, .astro and unknown extensions have no literal-aware scanner, so their view is the comment-stripped one, as before.

    A rule whose target only exists as a literal value — an attribute value such as target="_blank", a module specifier such as from 'react', a URL — opts into the literal view, which is the historical comment-stripped view with literal text intact:

    { "id": "react/jsx-no-target-blank", "severity": "warning", "message": "target=\"_blank\" without rel=\"noopener\" is a security risk", "extensions": [".jsx", ".tsx"], "match": { "regex": "target=\"_blank\"" }, "unless": { "regex": "noopener" }, "match_literals": true }

    match_literals is per-rule and defaults to false. The unless guard sees the same view as the matcher. It is ignored when match_comments is set, because the raw view already contains literal text. The shipped presets use it for the rules that need it (react/jsx-no-target-blank, next/google-font-display, angular/relative-url-prefix, …), and presets/*.json carry the same flag. View selection takes part in the incremental cache fingerprint, so toggling either flag invalidates cached results.

    #File-Level Rules

    File-level rules check whole-file properties (size, whitespace, naming, duplicates) rather than individual lines. They are declared in a separate file_rules array in the config:

    { "rules": [], "file_rules": [ { "id": "file/max-lines", "severity": "warning", "message": "File exceeds 500 lines", "extensions": [".ts", ".tsx"], "check": { "max_lines": 500 } }, { "id": "file/no-trailing-whitespace", "severity": "warning", "message": "Trailing whitespace found", "extensions": [], "check": { "no_trailing_whitespace": true } }, { "id": "file/naming", "severity": "warning", "message": "File name must be kebab-case", "extensions": [".ts"], "check": { "file_naming": "kebab-case" } } ] }

    #File check types

    CheckJSONDescription
    max_lines{ "max_lines": 500 }File must not exceed N lines
    max_line_length{ "max_line_length": 120 }No line may exceed N characters
    no_trailing_whitespace{ "no_trailing_whitespace": true }No trailing whitespace on any line
    no_tabs{ "no_tabs": true }No tab characters
    final_newline{ "final_newline": true }File must end with a newline
    no_duplicate_lines{ "no_duplicate_lines": true } or { "no_duplicate_lines": 40 }No repeated line of at least N trimmed characters (default 24; 0 compares any non-empty line)
    file_naming{ "file_naming": "kebab-case" }File name must follow a convention (camelCase, PascalCase, snake_case, kebab-case)
    max_file_size{ "max_file_size": 10000 }File must not exceed N bytes
    no_empty_files{ "no_empty_files": true }File must not be empty
    line_ending{ "line_ending": "lf" }File must use consistent line endings (lf or crlf)
    no_bom{ "no_bom": true }File must not start with a UTF-8 BOM

    The rules array is optional when file_rules is present.

    no_duplicate_lines only compares lines long enough to be substantive: a minimum trimmed length (24 by default) keeps }, </view>, /** and return — which repeat in every file by construction — from flooding the report. Set an explicit number to tune it, or 0 to compare every non-empty line.

    #Cross-File Structural Rules

    Line and file rules see one file at a time. JS/TS structural rules use a best-effort tokenizer/declaration/import model, not a complete JS/TS AST or Node module/type resolver. Cross-file checks load additional dependency context and report findings only for selected paths; context read failures return exit 2.

    { "rules": [], "structural_rules": [ { "id": "imports/no-unused-imports", "severity": "error", "message": "Imported binding is never used", "extensions": [".ts", ".tsx"], "check": { "no_unused_imports": true } }, { "id": "imports/no-import-cycles", "severity": "error", "message": "Import cycle detected", "extensions": [], "check": { "no_import_cycles": true } } ] }

    Or activate the whole set with --preset imports.

    #Structural check types

    CheckJSONDescription
    no_unused_imports{ "no_unused_imports": true }An imported binding is never referenced in the importing file
    no_duplicate_imports{ "no_duplicate_imports": true }The same module is imported by more than one import statement
    no_unresolved_relative_imports{ "no_unresolved_relative_imports": true }A relative import cannot be resolved in the supplied project/context membership
    no_import_cycles{ "no_import_cycles": true }The file takes part in a cycle of relative imports (reported per file)
    no_default_export{ "no_default_export": true }export default is used
    no_deep_relative_imports{ "no_deep_relative_imports": 2 }A relative import climbs more than N directories with ../
    no_require_imports{ "no_require_imports": true }require() is used in an ES module codebase
    no_unused_exports{ "no_unused_exports": true }An exported name is never imported by the available project/context files (ambient .d.ts files are exempt)

    The rules array is optional when structural_rules is present. Structural findings respect inline // moonlint-disable <rule-id> comments and rule scopes, exactly like line findings.

    Cross-file checks read unselected dependencies as context. When the selection is empty there is nothing they could report — findings outside the selection are dropped — so the context read is skipped entirely and an unrelated unreadable file cannot turn an empty scan into exit 2.

    #Path aliases

    Bare specifiers that go through a path alias (@/api/ka, ~/utils/date) do not resolve on their own, so no_unused_exports would count every alias-imported export as dead. Declare the aliases so the cross-file pass can follow them:

    { "aliases": { "@": "src", "~": "." }, "structural_rules": [ { "id": "imports/no-unused-exports", "severity": "warning", "message": "dead export", "extensions": [], "check": { "no_unused_exports": true } } ] }

    Alias targets are relative to the scan root (the directory being linted), so a config used with moonlint src maps @ to ., while one used with moonlint . maps @ to src. A prefix matches on a segment boundary — @ matches @/x but not the package @scope/pkg — and a longer prefix wins over a shorter one (@/lib before @). Absolute targets, .. escapes and non-string values are configuration errors (exit 2). Independently of alias resolution, Vue template bindings such as :src="logo" count as usages for no_unused_imports.

    #Inline Disable Comments

    Suppress findings without editing the config:

    // moonlint-disable-next-line const x = 1; // this line is not linted // moonlint-disable-next-line no-console-log console.log('debug'); // only no-console-log is suppressed here // moonlint-disable // everything below is not linted const y = 2; // moonlint-enable // linting resumes here const z = 3;

    • // moonlint-disable [rule-id ...] — disable from this line onward
    • // moonlint-disable-next-line [rule-id ...] — disable on the next line only
    • // moonlint-enable [rule-id ...] — re-enable from this line onward
    • Without rule ids, all rules are affected

    #Config Inheritance

    Configs can extend other configs with the extends field:

    { "extends": "presets/react.json", "rules": [ { "id": "custom/no-foo", "message": "...", "match": { "contains": "foo" } } ] }

    extends accepts a string or an array of strings. Inheritance is recursive: each path resolves relative to the config file that declares it, so a lvl1/mid.json may itself extend lvl2/leaf.json. Rules from extended configs are merged with the current config's rules; the current config takes precedence on id conflicts, which is the intended overriding mechanism.

    Cyclic extends chains (a.json → b.json → a.json) are detected and reported as a config error (exit 2) rather than recursing indefinitely. Duplicate ids within a file, including across rule kinds, are rejected. Same-kind ids may deliberately override inherited rules. Unknown fields, ignored scope objects (use top-level include/exclude), invalid severities, empty extension entries, duplicate JSON keys and ambiguous match/check objects are errors rather than silently ignored configuration.

    #Auto-Fix

    The --fix flag repairs fixable file-level violations in place:

    # Fix trailing whitespace and missing final newlines moonlint --preset file --fix /path/to/project # Additionally normalise tabs to 4 spaces (opt-in) moonlint --preset file --fix --fix-tab-width 4 /path/to/project # Show what would change without writing anything moonlint --preset file --fix --dry-run /path/to/project

    Candidate checks: no_trailing_whitespace, final_newline, and no_tabs. MoonBit fixes protect quoted/raw/interpolated literal spans and preserve BOM, Unicode and CRLF. File checks still inspect original literal whitespace, so unfixable literal properties remain findings; fixes never suppress them. A final raw-content line is conservatively left without an inserted newline.

    Non-MoonBit fixes are deliberately narrower: simple script sources only; templates/markup remain untouched, and tab replacement is skipped when quote or regex-like spans could carry values. Other languages are not automatically rewritten. A remaining finding is not a successful repair. Properties that make --fix safe to run on a real tree:

    BehaviourDetail
    Scope-awareA rule's include/exclude and extensions are honoured, so excluded trees (e.g. vendor/**) are never written
    Line-ending preservingfinal_newline appends \r\n to a CRLF file, never a bare \n
    Tab opt-inTabs change indentation width and can alter semantics (Python, YAML, Makefiles), so no_tabs is only fixed with an explicit --fix-tab-width
    Safe target / atomic writesReject symlink targets/ancestors, reread before replacement and refuse an observed content change; this is not a filesystem compare-and-swap transaction
    stderr messagesProgress goes to stderr, keeping --format json/sarif stdout parseable
    Working tree only--fix is rejected together with --changed/--staged, which read Git blobs rather than the working tree
    Dry run--dry-run reports would fix <file> and writes nothing; findings are reported as they still are, since the tree is unchanged

    Every run reports a per-file line plus a total (fixed N file(s) / would fix N file(s)) on stderr. After fixing, the linter re-scans and reports remaining findings.

    #Inline Disable Scope

    Inline moonlint-disable comments suppress line-level findings only. Whole-file properties — bom, line_ending, max_file_size, no_empty_files, file_naming, max_lines — cannot be masked by a comment, because they describe the file rather than a line. Per-line file checks (no_trailing_whitespace, no_tabs, max_line_length) remain suppressible.

    #Quick Start

    # Create a starter config moonlint --init # Lint MoonBit sources moonlint --preset moonbit packages/ # Lint with a framework preset moonlint --preset react /path/to/project # Run cross-file import analysis moonlint --preset imports /path/to/project # Auto-fix and re-lint moonlint --preset file --fix /path/to/project # See every layer fire at once on the shipped demos moonlint --config examples/demo/moonlint.json examples/demo/src moonlint --preset moonbit examples/moonbit-demo/src

    #Scan Modes

    By default, moonlint walks the directory tree recursively. Four alternative scan modes are available:

    # Only scan files changed since a git ref (ideal for CI) moon run cmd/main -- --changed origin/main /path/to/project # Only scan staged files (ideal for pre-commit hooks) moon run cmd/main -- --staged /path/to/project # Only scan files matching a glob pattern moon run cmd/main -- --glob "src/**/*.ts" /path/to/project # Read file paths from stdin, one per line git diff --name-only | moon run cmd/main -- --stdin /path/to/project

    --watch is not implemented; it is rejected with exit code 2 and an unsupported message rather than being accepted and silently ignored. For fast repeated scans use --incremental (see below).

    Scan modes are mutually exclusive. Every mode shares one selection contract: paths are root-relative, de-duplicated, sorted, extension-filtered and scope-filtered. --glob may be repeated; the patterns form a union.

    • --changed <ref> compares merge-base(ref, HEAD) with HEAD, so a pull request is measured against its true base, and reads the committed HEAD blobs — not the working tree and not only the changed lines.
    • --staged reads the actual index contents, so a clean working tree cannot mask a dirty staged file (or vice versa).
    • Git failures (not a repository, unknown ref, unmerged index) exit 2 instead of producing an empty, apparently clean scan.

    #Package dependency policies

    Generate the official graph in the owning module, then pass it to moonlint:

    (cd examples/package-policy-demo && moon tree --package --json --target native > graph.native.json) moonlint --package-graph examples/package-policy-demo/graph.native.json \ --config examples/package-policy-demo/policy.json --format json # Expected exit 1: the acyclic domain -> ui edge violates the team rule.

    The example compiles and tests before the policy gate. Policy v1 requires package_rules with stable id, severity, from, exactly one of allow/deny, kinds (source, test, wbtest), optional targets, and a reason. Empty allow denies every applicable edge; empty deny is invalid. Graph v3 validation is strict. The gate covers direct selected-root edges to supplied non-stdlib nodes, not transitive dependencies or stdlib edges. Zero applicability is explicitly reported, not presented as proof that every target was checked. No compiler build/download is triggered.

    #Historical public-interface gate

    # First generate each interface with the intended compiler/backend. moon info moonlint --api-snapshot pkg.generated.mbti \ --api-toolchain "moon 0.1.20261102; moonc v0.10.19+bee578715" \ --api-backend native --api-module-version 0.3.0 > api.snapshot.json moonlint --api-check before.snapshot.json after.snapshot.json --format sarif # Opt in to an intentional breaking 0.x minor / stable major release: moonlint --api-check before.snapshot.json after.snapshot.json --api-version-policy semver

    Snapshots record package, toolchain, backend and module version. Metadata is caller-supplied, not compiler provenance attestation: use the same actual compiler/backend before and after. Different contexts, malformed data and unsupported declaration syntax are inconclusive (exit 2). Removals and shape changes block by default, even if the version changed. Opt-in semver changes review findings to warnings only after a sufficient version increment; prerelease/build versions are explicitly unsupported by that policy.

    This compares supported historical public declarations/symbols, not just interface text or export count. It is conservative review evidence, not an ABI, type-assignability or behavioral-compatibility proof. Bodies/docs/private or hidden exports are outside the snapshot surface; member additions may require review. See the compiling before/after example.

    Package/API/audit reports use mode, metadata, counts, findings and identity details, not fabricated scan counters or source coordinates. SARIF results have no locations for those project findings; GitHub annotations omit file/line properties. --report writes the same project JSON schema.

    #Baseline v2 and exception auditing

    A baseline is never discovered implicitly. A write registers debt and returns write-mode 0; it is not a successful lint/CI verdict.

    moonlint --preset moonbit --update-baseline --baseline-format v2 \ --baseline debt.json --baseline-reason "existing review debt" \ --baseline-owner "package-maintainer" --baseline-expires 2026-12-31 . moonlint --preset moonbit --baseline debt.json . moonlint --preset moonbit --baseline debt.json --changed origin/main . # Full-tree audit, with reproducible UTC-date override if needed: moonlint --preset moonbit --audit-baseline --baseline debt.json \ --baseline-today 2026-11-04 --format json . # Convert only still-matching old exemptions, not newly introduced errors: moonlint --preset moonbit --migrate-baseline --baseline legacy.json \ --baseline-reason "reviewed legacy debt" --baseline-owner "package-maintainer" .

    V2 fingerprints omit line/column, retain rule/file/severity/message and the end-trimmed snippet, and preserve internal/literal whitespace. Each entry has a positive occurrence budget, nonempty reason/owner, and nullable expiry. The expiry day itself is valid; earlier expiry never suppresses. Default date is host UTC. Audit errors identify expired, unused and partially unused budgets; unused_occurrences totals the unused quota. Normal lint warns about audit issues but does not silently turn normal suppression into an audit gate.

    This is a non-cryptographic content-identity MVP, not ancestor or semantic identity. Identical replacement within the stored count is indistinguishable; rename, message/severity or snippet changes lose the exemption. Full-tree audits must not be narrowed by --changed, --staged, --glob, stdin or --ext. Migration returns 1 when unsuppressed errors remain; it never approves newly introduced debt. Update/migration/audit cannot combine with fixes/project modes. Legacy arrays remain explicit, line-sensitive inputs; overwriting a v2 baseline requires an explicit v2 write and metadata rather than downgrading it silently.

    #Frontend limits

    MoonBit source checks share code/declaration/comment/literal views. Nonempty documentation is required; comment-looking raw text and an empty separator are not docs. Calls after literals and within supported single-line interpolations are visible; definitions and test bodies are not mistaken for ordinary calls. These are syntactic name policies, not binding resolution (a local bare panic can still be a name-policy match). Qualified user Foo::panic/println are not assumed to be builtin calls. Unknown public-declaration forms and unfinished lexical input are inconclusive. Cross-physical-line interpolation is currently unsupported and rejected, not counted as successfully parsed source.

    The JS/TS front end is a tokenizer and structural parser, not a Vue SFC compiler. For .vue files it reads the script for imports/exports and extracts the template's binding expressions (:prop, v-*, @event) as identifier reads, so a binding used only in a template still counts as a usage. It does not evaluate template control flow, resolve component registration, or follow aliases unless they are declared in aliases.

    Git modes capture immutable blob-id maps for selected/context sources; replace refs are disabled. Selection precedes capture, so concurrent changes during selection are not an atomic repository snapshot. Avoid concurrent Git edits when selecting files. Tree/glob/stdin context is likewise a live-tree read, not a filesystem transaction. Context counters/failures disclose these extra reads.

    #Incremental caching

    --incremental keeps a content-hash cache of per-file results, so a repeated scan only re-lints files whose source changed:

    # First run populates .moonlint-cache.json; later runs reuse unchanged files moon run cmd/main -- --incremental /path/to/project # Custom cache location moon run cmd/main -- --incremental --cache-file /tmp/moonlint.cache.json /path/to/project

    Properties that make the cache safe:

    BehaviourDetail
    Content-keyedEach entry is keyed by a non-cryptographic hash of strictly decoded source (BOM/Unicode preserved); an edit, even whitespace, re-lints that file
    Config-awareThe cache stores a fingerprint of the effective rules, file rules, structural rules and scopes; any change invalidates every entry
    Self-healingA missing, empty or unreadable cache starts a full scan; a non-empty cache that fails parsing or version validation also emits a warning
    Structural-safeCached runs still collect project sources for cross-file checks, and refresh full dependency context under the same rules; context failures block the verdict
    Opt-inWithout --incremental no cache file is read or written

    The cache also keeps each file's parsed structural model (imports, exports and the set of used names), keyed by the same content hash. Findings still never come from the cache for cross-file rules on a changed tree — a dead export can become live when an unrelated file is edited — but the expensive tokenize/parse step is skipped for unchanged files, which is what made --incremental worthwhile for --preset imports scans. Models are rule-independent, so they survive a configuration change, and they carry a parser generation: bumping the parser drops stale models without discarding the per-file findings.

    On top of that, a full-tree scan records the structural verdict itself, keyed by the rule fingerprint plus every participating file's content hash. When an unchanged tree is scanned again under the same rules, the whole cross-file pass is skipped — no context reads, no analysis. Because that key covers every file that took part, any edit, addition or deletion changes it and forces a recompute. Partial scans (--glob, --stdin, --changed, --staged) and scans that exclude files by scope are never reused this way, since their unselected dependency context is not part of the key.

    BehaviourDetail
    Content-keyed modelsA model is reused only when its stored hash equals the source being scanned
    Rule-independentModels are reused across rule changes; only cross-file findings are re-derived
    Parser generationA model written by an older parser (model_version) is dropped, so a front-end fix is never masked by a stale parse
    BoundedOnly files in the current selection keep an entry; a deleted file leaves no model behind
    Verdict identityThe cached structural verdict is keyed by the rule fingerprint plus every participating file's digest, so any edit invalidates it
    No snippets storedCached structural findings omit snippets (a minified line can be larger than the cache); they are re-derived from the scanned source, so reports stay byte-identical

    #Glob syntax

    PatternMatches
    *Any characters except /
    **Any characters including /
    ?Any single character except /
    LiteralExact match

    A pattern that matches a directory also covers everything below it, so the scope pattern vendor excludes vendor/pkg/index.ts while leaving vendorless/index.ts alone.

    #Configuration

    Rules are defined in a JSON file (default: moonlint.json):

    { "rules": [ { "id": "vue/import-from-vue", "severity": "error", "message": "Must import from 'vue-lynx', not 'vue'", "extensions": [".vue", ".ts"], "match_literals": true, "match": { "regex": "from[[:space:]]+['\"]vue['\"]" }, "unless": { "regex": "from[[:space:]]+['\"]vue-lynx['\"]" } } ] }

    #Rule fields

    FieldTypeDescription
    idstringStable identifier, e.g. vue/import-from-vue
    severitystring"error" or "warning" (default: "warning")
    messagestringHuman-readable explanation
    extensionsstring[]File extensions to check (empty = all files)
    matchobjectPrimary matcher (see below)
    unlessobjectOptional negative guard
    match_commentsboolMatch the raw view (comments included). Default false
    match_literalsboolMatch the literal view (string/template/regex contents intact). Default false; ignored when match_comments is set
    includestring[]Optional paths this rule applies to
    excludestring[]Optional paths this rule never applies to

    #Scopes

    The same include / exclude keys may appear at the top level of the config (global scope) and inside each rule (rule scope). Both take root-relative glob patterns using the syntax above; a leading ./ is accepted.

    { "include": ["src/**", "app/**"], "exclude": ["**/*.generated.ts", "src/vendor"], "rules": [ { "id": "vue/import-from-vue", "include": ["src/components/**"], "exclude": ["**/*.test.ts"], "message": "…", "match": { "regex": "…" } } ] }

    • An empty include list means "no restriction"; any exclude match wins over include.
    • The global scope is applied first: rejected files are counted in files_out_of_scope and receive no findings. They can still be read as dependency context for cross-file checks.
    • A rule scope only decides which rules see an already-selected file. It cannot widen the global scan set. A selected file that no rule applies to is counted in files_skipped with the reason no-applicable-rule.
    • Invalid or unsupported patterns (braces, character classes, absolute paths, ..) are configuration errors — exit code 2, not a silently narrower scan.

    Run moonlint from the repository root so reported paths (and GitHub annotations) resolve correctly.

    #Matcher types

    See Matcher Types above for the leaf matchers and the all / any / not combinators. Both match and unless accept any of them.

    Note: MoonBit's regex engine supports POSIX character classes ([[:space:]], [[:digit:]], [[:alpha:]]) but not Perl-style escapes (\d, \w, \s).

    #Output

    #--format text (default)

    One block per finding, plus a notice when nothing was selected:

    src/app.ts:12: [error] vue/import-from-vue — Must import from 'vue-lynx', not 'vue' import { createApp } from 'vue'

    --summary prints a per-rule tally with the scan counters instead.

    #--format json

    A versioned document ("version": 1):

    { "tool": "moonlint", "version": 1, "scan": { "mode": "tree", "root": "/repo", "extensions": [".ts", ".vue"], "files_selected": 12, "files_scanned": 10, "files_skipped": 1, "files_failed": 1, "files_out_of_scope": 3, "context_files_scanned": 2, "context_files_failed": 0, "source_snapshot": "working-tree", "baseline_suppressed": 0, "skipped_files": [{ "file": "docs/notes.md", "reason": "no-applicable-rule" }] }, "counts": { "findings": 1, "errors": 1, "warnings": 0 }, "findings": [ { "rule_id": "vue/import-from-vue", "severity": "error", "message": "Must import from 'vue-lynx', not 'vue'", "file": "src/app.ts", "line": 12, "column": 22, "snippet": "import { createApp } from 'vue'" } ], "diagnostics": [{ "file": "src/broken.ts", "message": "source is not valid UTF-8" }] }

    line and column are 1-based and count characters, not bytes, so a finding after multi-byte text points at the right place. column is the first character of the match: for contains, prefix and whole-word rules that is where the pattern text appears, for suffix rules the start of the trailing text, and for regex rules the first non-space character (the match offset is not recoverable from the pattern alone). SARIF startColumn uses the same value with columnKind: unicodeCodePoints.

    files_selected is counted after path normalization, extension filtering and de-duplication. Every selected file is either scanned, skipped (with a reason in skipped_files) or failed (with a diagnostic). --errors-only filters the findings and their counts, but never the scan metadata.

    --report <file> writes the same JSON document to a file atomically, in addition to whatever goes to stdout; it is also written when the scan fails.

    #--format github

    Emits GitHub Actions workflow commands:

    ::error file=src/app.ts,line=12,col=22,title=vue/import-from-vue::Must import from 'vue-lynx', not 'vue' ::error file=src/broken.ts,title=moonlint/scan-failed::source is not valid UTF-8 ::notice file=docs/notes.md,title=moonlint/skipped::no-applicable-rule ::notice title=moonlint::files selected: 12, scanned: 10, skipped: 1, failed: 1, …

    Property values and messages are escaped as GitHub requires, so a newline in a rule message can never forge an extra command.

    #--format sarif

    Emits a SARIF 2.1.0 document ($schema, runs[].tool.driver.rules and results[] with ruleId, level and physicalLocation), suitable for GitHub code scanning, VS Code and most CI static-analysis integrations.

    #Exit Codes

    • 0 — no error-severity findings
    • 1 — error-severity findings found
    • 2 — argument, configuration, Git, or I/O error (including any file that could not be read, a reference that cannot be resolved, an unmerged index, a cyclic or unreadable extends chain, and --fix combined with --changed/--staged)

    #Architecture

    repo root/ ├── cmd/impact/ — MoonImpact CLI entry point ├── cmd/main/ — moonlint CLI entry point ├── impact_types.mbt — plan/config/edge/issue/trace types ├── impact_config.mbt — strict inert MoonImpact JSON configuration ├── impact_moonbit.mbt — MoonBit front end: module discovery, moon.pkg import │ parsing (`import`, `test-import`, `#cfg` blocks), │ ownership, package graph, strategies ├── impact_dependencies.mbt — JS/TS/Vue reference extraction: imports, file │ reads, directory reads, existence checks, glob imports ├── impact_styles.mbt — CSS/SCSS reference scanner (imports, Sass modules, urls) ├── impact_style_resolution.mbt — stylesheet candidate resolution, load paths ├── impact_plan.mbt — plan construction: membership, reference resolution, │ reverse BFS, strategies, declaration contracts ├── impact_report.mbt — text/JSON/script-free HTML plan rendering ├── impact_native.mbt — native bridge for Git input, runner execution, reports ├── impact_native.c — process-group execution, atomic create-only report write ├── git.mbt — native filesystem/Git bridge (fixed argv, no shell) ├── git_native.c — lstat, Git (merge-base/changed/staged/blob), atomic write ├── scanner.mbt — file walking, line splitting, source reading ├── scope.mbt — include/exclude glob scopes ├── scan.mbt — scan modes, glob matching, file selection ├── types.mbt — Severity, MatchKind (leaves + all/any/not), Rule, │ Finding, FileRule, StructuralRule, LintResult, ScanInfo ├── matcher.mbt — MatchKind evaluation; `prepare()` compiles each regex │ once per rule, not per line, and pre-compiles nested │ combinators depth-first ├── comment.mbt — comment blanking: JS/TS mode (template literals, │ interpolations, strings, regex) and plain mode ├── lex.mbt — JS/TS tokenizer: strings, template literals with ${} │ interpolation, regex literals, comments, identifiers ├── parse.mbt — structured parser: import/export statements, bindings, │ usage positions, relative specifiers ├── analysis.mbt — cross-file engine: project index, import resolution, │ import graph, and the 8 structural checks ├── moonbit_lang.mbt — MoonBit declaration scanner: comment/string blanking, │ top-level items, ///| attachment, public-doc and naming ├── engine.mbt — rule application, scope filtering, scan accounting, │ structural pass and incremental-cache plumbing ├── cache.mbt — incremental cache: content hashes, config fingerprint, │ JSON render/parse (strict; corrupt input degrades to │ a full scan) ├── config.mbt — JSON config parsing, validation, and extends ├── presets.mbt — built-in presets (common, react, vue, angular, svelte, │ next, solid, astro, nuxt, file, imports, moonbit) ├── presets/ — standalone JSON copies of each preset for customization ├── disable.mbt — inline disable comment parsing (// moonlint-disable) ├── baseline.mbt — hash-based finding exemption ├── report.mbt — detail and summary rendering ├── report_json.mbt — JSON report ├── report_github.mbt — GitHub Actions annotations ├── report_sarif.mbt — SARIF 2.1.0 report ├── tests/ — dependency-free CLI integration tests └── examples/ — TS and MoonBit demos with hand-verified reports

    The two entry points share the filesystem, Git, walking and reporting layers but plan different things. MoonImpact's MoonBit front end reads moon.pkg manifests into a package graph and plans against it; its JS/TS front end is the tokenizer → parser → project index/import graph. moonlint's front ends are the MoonBit declaration scanner and the JS/TS tokenizer/import graph, feeding the rule engine, cache and baseline layers.

    The implementation is pure MoonBit except for the native filesystem/Git bridge in git_native.c and the process boundary in impact_native.c; each layer is unit-tested in isolation.

    #Development and verification

    The executable requires the native backend on macOS/Linux for filesystem, Git and UTC-date operations. Building it requires MoonBit plus a C toolchain; using the built executable does not require a Node.js or Rust toolchain.

    moon check --target native moon test --target native moon build --target native python3 tests/integration.py \ --binary "$PWD/_build/native/debug/build/cmd/main/main.exe" --phase all python3 tests/impact_integration.py \ --binary "$PWD/_build/native/debug/build/cmd/impact/impact.exe" python3 tests/impact_native.py moon info && moon fmt # Review generated interface/source diffs, then rerun affected gates.

    CI runs explicit native gates and compiles the examples. Its installer fetches latest, not a pinned toolchain; versions are recorded and interface/format drift is checked. A historical CI failure recorded in commit e318b9e reported that the job could not start because of an account billing lock. That record does not establish the current remote CI status. The commands above cover the core local gates; CI also runs stability audits and builds/tests the example modules, as listed in the workflow.

    The moonlint verification notes describe the 2026-11-04 run and its limitations, not the current test results. Later MoonImpact measurements are in round three, round four and round five. The two former JS/TS literal-text expected failures are now ordinary regression tests: the default code view blanks literal contents. Historical wasm failures are not claimed fixed.

    moonlint . uses the repository config, which deliberately excludes the negative examples. No new blanket baseline was added to hide missing public documentation.

    #License

    ConfigError

    pub(all) suberror ConfigError {
    ConfigError(String)
    }

    A configuration error with a human-readable message.

    NativeError

    pub(all) suberror NativeError {
    NativeError(String)
    } derive(
    Debug
    )

    Native filesystem and Git operations use fixed argv, never a shell. Source text is strict UTF-8 with BOMs and embedded NULs preserved.

    NativeError::to_repr

    #deprecated("`NativeError::to_repr` is deprecated, use `@moonbitlang/core/debug.Debug::to_repr` instead.")
    fn NativeError::to_repr(NativeError) ->
    Repr
    automatically derived

    Baseline

    pub struct Baseline {
    hashes :
    Set
    [String]
    }

    A baseline: a set of exempted finding hashes.

    Baseline::contains

    fn Baseline::contains(self : Baseline, f : Finding) -> Bool

    Whether a finding is exempted by this baseline.

    Baseline::load

    fn Baseline::load(src : String) -> Baseline

    Load a baseline from its JSON array text. An empty or invalid file yields an empty baseline (adopting the linter should never hard-fail on a stale baseline).

    Baseline::parse

    fn Baseline::parse(src : String) -> Baseline raise

    Strict loader used by the CLI. A corrupt or misspecified baseline is an operational error, not an empty exemption list.

    Baseline::partition

    fn Baseline::partition(self : Baseline, findings : Array[Finding]) -> (Array[Finding], Array[Finding])

    Split findings into (kept, suppressed) using this baseline.

    Baseline::render

    fn Baseline::render(findings : Array[Finding]) -> String

    Render a stable, deduplicated legacy baseline from all raw findings.

    BaselineV2

    pub struct BaselineV2 {
    // private fields
    }

    A version-2, count-limited baseline of location-independent content keys. Keys use rule id, file, severity, message, and the snippet with only its ends trimmed. Line and column are excluded; internal and literal whitespace are preserved. This is not semantic or ancestor identity: renamed declarations invalidate keys when their names are present in the finding message. Fingerprints use non-cryptographic FNV-1a and are not a security boundary.

    BaselineV2::capture

    fn BaselineV2::capture(findings : Array[Finding], reason : String, owner : String, expires : String?) -> Result[BaselineV2, ConfigError]

    Capture only the supplied findings as a version-2 baseline. Equal content keys share an entry whose count limits future suppressions. Requires nonblank reason/owner and a nullable, valid Gregorian YYYY-MM-DD expiry (years 0001..9999). Expiry is not inferred from the current clock. Reads no files, so findings from immutable Git blobs remain authoritative.

    BaselineV2::parse

    fn BaselineV2::parse(src : String) -> Result[BaselineV2, ConfigError]

    Parse the strict version-2 moonlint-content-v2 baseline JSON format. Unknown or duplicate fields, duplicate keys, invalid positive integer counts, blank reason/owner, malformed dates, and legacy arrays are errors. An explicitly empty entries array is valid and suppresses nothing.

    BaselineV2::partition

    fn BaselineV2::partition(self : BaselineV2, findings : Array[Finding], today : String) -> Result[(Array[Finding], Array[Finding], PolicyReport), ConfigError]

    Partition findings into (remaining, suppressed, baseline-audit report). Each unexpired key suppresses at most its stored count, preserving input order in both arrays; copied findings cannot expand the old count budget. today is an explicit valid Gregorian YYYY-MM-DD date. Expiry before today does not suppress, while expiry equal to today remains valid. Audit counts are suppressed, unused_entries, expired_entries, and unused_occurrences (sum of positive count minus current match count). Completely unmatched entries produce one unused issue; partially unused budgets produce an unused-budget issue. Expiry and unused are independent and may both be reported for one entry. Audit issues have Error severity for an explicit audit gate. Ordinary lint callers use remaining/suppressed and must not implicitly gate on audit.

    BaselineV2::render

    fn BaselineV2::render(self : BaselineV2) -> String

    Render a stable version-2 JSON document with entries sorted by key. JSON escaping preserves metadata; nullable expiry is always emitted.

    Cache

    pub struct Cache {
    version : Int
    fingerprint : String
    files : Map[String, CacheEntry]
    models : Map[String, ModelEntry]
    structural : StructuralCache?
    } derive(
    Debug
    )

    The on-disk cache: a format version, a fingerprint of the effective configuration, one entry per cached file, and the parsed structural models used by the cross-file pass.

    Cache::get

    fn Cache::get(self : Cache, rel : String) -> CacheEntry?

    The cached entry for a file, if any.

    Cache::get_model

    fn Cache::get_model(self : Cache, rel : String) -> ModelEntry?

    The cached structural model for a file, if any.

    Cache::get_structural

    fn Cache::get_structural(self : Cache) -> StructuralCache?

    The cached structural verdict, if any.

    Cache::is_current

    fn Cache::is_current(self : Cache, fingerprint : String) -> Bool

    Whether a loaded cache may be reused for a configuration with this fingerprint. A version mismatch means the layout changed; a fingerprint mismatch means the rules did. Either way the cache is discarded.

    Cache::new

    fn Cache::new(fingerprint : String) -> Cache

    A fresh, empty cache for the given configuration fingerprint.

    Cache::parse

    fn Cache::parse(src : String) -> Cache?

    Parse a cache file. Any malformation — bad JSON, wrong shape, unknown version — yields None, which the caller treats as "no cache".

    Cache::put

    fn Cache::put(self : Cache, rel : String, hash : String, findings : Array[Finding]) -> Unit

    Record the result of scanning one file.

    Cache::put_model

    fn Cache::put_model(self : Cache, rel : String, hash : String, model : FileModel) -> Unit

    Record the structural model parsed for one file.

    Cache::put_structural

    fn Cache::put_structural(self : Cache, key : String, findings : Array[Finding]) -> Unit

    Record the structural verdict for the given key.

    Cache::render

    fn Cache::render(self : Cache) -> String

    Render the cache as JSON for atomic writing.

    Cache::to_repr

    automatically derived

    CacheEntry

    pub struct CacheEntry {
    hash : String
    findings : Array[Finding]
    } derive(
    Debug
    )

    One cached file: the digest of its content and the findings the rules produced for it on the previous run.

    CacheEntry::to_repr

    automatically derived

    CommentMode

    pub enum CommentMode {
    Js
    Plain
    Moonbit
    } derive(Eq,
    Debug
    )

    The comment syntax in use for a file. Js understands template literals and regex literals, so // inside a multi-line template string (a stringified script, a URL fragment) is not treated as a comment; Plain treats quotes as opaque and knows nothing about regex literals.

    CommentMode::equal

    fn CommentMode::equal(CommentMode, CommentMode) -> Bool
    automatically derived

    CommentMode::not_equal

    fn CommentMode::not_equal(x : CommentMode, y : CommentMode) -> Bool
    automatically derived

    CommentMode::to_repr

    automatically derived

    Decl

    pub struct Decl {
    name : String
    kind : DeclKind
    line : Int
    column : Int
    } derive(
    Debug
    )

    A declared binding name with its position.

    Decl::to_repr

    automatically derived

    DeclKind

    pub enum DeclKind {
    Var
    Function
    Class
    } derive(Eq,
    Debug
    )

    The kind of a top-level binding.

    DeclKind::equal

    fn DeclKind::equal(DeclKind, DeclKind) -> Bool
    automatically derived

    DeclKind::not_equal

    fn DeclKind::not_equal(x : DeclKind, y : DeclKind) -> Bool
    automatically derived

    DeclKind::to_repr

    automatically derived

    Diagnostic

    pub struct Diagnostic {
    file : String
    message : String
    } derive(
    Debug
    )

    A scan failure. These are operational errors, not lint findings.

    Diagnostic::to_repr

    automatically derived

    DisableMap

    pub struct DisableMap {
    line_state : Map[Int,
    Set
    [String]]
    disabled_on : Map[Int,
    Set
    [String]]
    }

    A parsed set of inline disable directives for one file.

    DisableMap::is_disabled

    fn DisableMap::is_disabled(self : DisableMap, rule_id : String, line : Int) -> Bool

    Whether a rule is disabled at a given line.

    ExportSpec

    pub struct ExportSpec {
    names : Array[String]
    source : String?
    line : Int
    column : Int
    } derive(
    Debug
    )

    A name this file exports. "default" marks a default export; "*" marks export * from. source is set for re-exports.

    ExportSpec::to_repr

    automatically derived

    FileCheck

    pub enum FileCheck {
    MaxLines(Int)
    MaxLineLength(Int)
    NoTrailingWhitespace
    NoTabs
    FinalNewline
    NoDuplicateLines(Int)
    FileNaming(NamingStyle)
    MaxFileSize(Int)
    NoEmptyFiles
    LineEnding(LineEndingStyle)
    NoBom
    } derive(Eq,
    Debug
    )

    A file-level check evaluated once per file, not per line.

    FileCheck::equal

    fn FileCheck::equal(FileCheck, FileCheck) -> Bool
    automatically derived

    FileCheck::not_equal

    fn FileCheck::not_equal(x : FileCheck, y : FileCheck) -> Bool
    automatically derived

    FileCheck::to_repr

    automatically derived

    FileModel

    pub struct FileModel {
    imports : Array[ImportSpec]
    exports : Array[ExportSpec]
    decls : Array[Decl]
    used : Array[UsedIdent]
    } derive(
    Debug
    )

    The structural model of one source file.

    FileModel::to_repr

    automatically derived

    FileRule

    pub struct FileRule {
    id : String
    severity : Severity
    message : String
    extensions : Array[String]
    check : FileCheck
    scope : Scope
    } derive(
    Debug
    )

    A file-level lint rule.

    FileRule::applies_to

    fn FileRule::applies_to(self : FileRule, rel : String) -> Bool

    Public view of file_rule_applies, so the CLI's --fix path honours the same extension and include/exclude scope as the scan.

    FileRule::to_repr

    automatically derived

    Finding

    pub struct Finding {
    rule_id : String
    severity : Severity
    message : String
    file : String
    line : Int
    column : Int
    snippet : String
    } derive(
    Debug
    )

    A single rule violation located in a file.

    Finding::to_repr

    automatically derived

    GlobPattern

    pub struct GlobPattern {
    segments : Array[String]
    } derive(Eq,
    Debug
    )

    Match path segments separately: ** means zero or more complete segments, never part of a filename. Dynamic programming avoids exponential backtracking.

    GlobPattern::equal

    fn GlobPattern::equal(GlobPattern, GlobPattern) -> Bool
    automatically derived

    GlobPattern::matches

    fn GlobPattern::matches(self : GlobPattern, path : String) -> Bool

    Match the entire relative path; unlike matches_path, a directory match does not cover descendants.

    GlobPattern::matches_path

    fn GlobPattern::matches_path(self : GlobPattern, path : String) -> Bool

    Match a root-relative path, treating a matched directory as covering everything below it. vendor therefore matches vendor/pkg/index.ts while still not matching vendorless/index.ts.

    GlobPattern::new

    fn GlobPattern::new(pattern : String) -> GlobPattern

    Split an already validated root-relative glob into path segments; call validate_glob for untrusted input.

    GlobPattern::not_equal

    fn GlobPattern::not_equal(x : GlobPattern, y : GlobPattern) -> Bool
    automatically derived

    GlobPattern::to_repr

    automatically derived

    ImpactConfig

    pub struct ImpactConfig {
    includes : Array[String]
    excludes : Array[String]
    tests : Array[String]
    aliases : Array[(String, String)]
    file_readers : Array[String]
    dependencies : Array[ImpactEdge]
    global_inputs : Array[String]
    style_load_paths : Array[String]
    skip_dirs : Array[String]
    runner_dir : String
    max_source_bytes : Int
    } derive(
    Debug
    )

    MoonImpact configuration. Paths and glob patterns are relative to the scan root. File-reader names are explicit contracts: their first argument names a root-relative input. No user commands are evaluated from configuration.

    ImpactConfig::to_repr

    automatically derived

    ImpactEdge

    pub struct ImpactEdge {
    dependency : String
    dependent : String
    kind : String
    line : Int
    column : Int
    } derive(
    Debug
    )

    A dependency edge with the location of the reference in the dependent file. Manual edges use line/column zero because there is no source coordinate.

    ImpactEdge::to_repr

    automatically derived

    ImpactIssue

    pub struct ImpactIssue {
    file : String
    line : Int
    reason : String
    } derive(
    Debug
    )

    A limitation or operational observation. Uncertainty forces a full test plan; it must never be interpreted as evidence that no test is affected.

    ImpactIssue::to_repr

    automatically derived

    ImpactPlan

    pub struct ImpactPlan {
    root : String
    input : String
    changed : Array[String]
    strategy : String
    tests : Array[String]
    inventory : Array[String]
    affected : Array[String]
    traces : Array[ImpactTrace]
    issues : Array[ImpactIssue]
    reasons : Array[String]
    source_count : Int
    edge_count : Int
    mode : String
    } derive(
    Debug
    )

    An advisory test plan, not a passing test result. Strategy is none, related, full or blocked. Tests are the effective execution set; inventory contains all configured test files. A full fallback includes tests lacking a known chain instead of pretending those tests were proved affected.

    ImpactPlan::to_repr

    automatically derived

    ImpactTrace

    pub struct ImpactTrace {
    test_file : String
    changed : String
    chain : Array[ImpactEdge]
    } derive(
    Debug
    )

    One deterministic shortest known dependency chain from a change to a test.

    ImpactTrace::to_repr

    automatically derived

    ImportKind

    pub enum ImportKind {
    Static
    Dynamic
    Require
    ReExport
    } derive(Eq,
    Debug
    )

    How a module reference entered the file.

    ImportKind::equal

    fn ImportKind::equal(ImportKind, ImportKind) -> Bool
    automatically derived

    ImportKind::not_equal

    fn ImportKind::not_equal(x : ImportKind, y : ImportKind) -> Bool
    automatically derived

    ImportKind::to_repr

    automatically derived

    ImportName

    pub struct ImportName {
    local : String
    imported : String
    } derive(
    Debug
    )

    One name introduced by an import: the local binding and the name as the imported module exports it ("default" for default imports, "*" for namespace imports).

    ImportName::to_repr

    automatically derived

    ImportSpec

    pub struct ImportSpec {
    kind : ImportKind
    source : String
    names : Array[ImportName]
    line : Int
    column : Int
    type_only : Bool
    } derive(
    Debug
    )

    A module reference with its position (1-based, pointing at the import, export or require keyword that starts it).

    ImportSpec::to_repr

    automatically derived

    JsState

    type JsState

    What the scanner is currently reading.

    LineEndingStyle

    pub enum LineEndingStyle {
    Lf
    Crlf
    } derive(Eq,
    Debug
    )

    Line ending style for file-level checks.

    LineEndingStyle::equal

    automatically derived

    LineEndingStyle::not_equal

    fn LineEndingStyle::not_equal(x : LineEndingStyle, y : LineEndingStyle) -> Bool
    automatically derived

    LineEndingStyle::parse

    fn LineEndingStyle::parse(s : String) -> LineEndingStyle?

    Parse a line ending style from its string tag.

    LineEndingStyle::to_repr

    automatically derived

    LintConfig

    pub struct LintConfig {
    rules : Array[Rule]
    file_rules : Array[FileRule]
    structural_rules : Array[StructuralRule]
    scope : Scope
    aliases : Array[(String, String)]
    } derive(
    Debug
    )

    A parsed configuration: the rule set plus the global file scope.

    LintConfig::to_repr

    automatically derived

    LintResult

    pub struct LintResult {
    findings : Array[Finding]
    files_selected : Int
    files_scanned : Int
    files_skipped : Int
    files_failed : Int
    files_out_of_scope : Int
    context_files_scanned : Int
    context_files_failed : Int
    source_snapshot : String?
    baseline_hits : Int
    diagnostics : Array[Diagnostic]
    skipped_files : Array[SkippedFile]
    } derive(
    Debug
    )

    Aggregate result. Selection is counted after path normalization, extension filtering and de-duplication; each selected file is scanned, skipped or failed.

    LintResult::count_by

    fn LintResult::count_by(self : LintResult, sev : Severity) -> Int

    Count findings by severity.

    LintResult::has_errors

    fn LintResult::has_errors(self : LintResult) -> Bool

    Whether the result contains any error-severity finding.

    LintResult::new

    fn LintResult::new(findings : Array[Finding], files_scanned : Int, baseline_hits : Int) -> LintResult

    Backwards-compatible constructor for callers supplying successful findings.

    LintResult::to_repr

    automatically derived

    LintResult::with_findings

    fn LintResult::with_findings(self : LintResult, findings : Array[Finding], baseline_hits : Int) -> LintResult

    Replace displayed findings without losing the run's IO counters.

    MatchKind

    pub enum MatchKind {
    Contains(String)
    HasPrefix(String)
    HasSuffix(String)
    Regex(String)
    Equals(String)
    Word(String)
    All(Array[MatchKind])
    Any(Array[MatchKind])
    Not(MatchKind)
    } derive(Eq,
    Debug
    )

    A single line-matching primitive, or a boolean combination of matchers. A rule pairs one match kind with an optional unless kind (a negative guard) to express "match X but not Y"; the combinators below express the rest — all / any / not nest arbitrarily deep.

    MatchKind::column_of

    fn MatchKind::column_of(self : MatchKind, line : String) -> Int

    1-based column of the first match of this matcher on line.

    A matcher only reports "this line matches", so the column is the position of the first occurrence of the pattern text the matcher was built from. Regex and Word fall back to the first non-space character, because their match position is not recoverable from the pattern alone. The combinators report the column of the first sub-matcher that actually matches on the line (Not has no positive pattern, so it always falls back to the first non-space character).

    MatchKind::equal

    fn MatchKind::equal(MatchKind, MatchKind) -> Bool
    automatically derived

    MatchKind::matches

    fn MatchKind::matches(self : MatchKind, line : String) -> Bool

    Test whether a single line matches this matcher. Combinators evaluate recursively: All is conjunction, Any disjunction, Not negation.

    MatchKind::not_equal

    fn MatchKind::not_equal(x : MatchKind, y : MatchKind) -> Bool
    automatically derived

    MatchKind::prepare

    fn MatchKind::prepare(self : MatchKind) -> Prepared

    Compile this matcher once for reuse across all lines of a file.

    MatchKind::to_repr

    automatically derived

    MatchKind::validate

    fn MatchKind::validate(self : MatchKind) -> String?

    Validate that a matcher's regex (if any) compiles. Returns an error message string on failure, or None when the matcher is well-formed. Combinators are validated depth-first, so a bad pattern nested inside all / any / not is still reported before scanning begins.

    ModelEntry

    pub struct ModelEntry {
    hash : String
    model : FileModel
    } derive(
    Debug
    )

    One cached structural model: the digest of the source it was parsed from and the model itself.

    NamingStyle

    pub enum NamingStyle {
    CamelCase
    PascalCase
    SnakeCase
    KebabCase
    } derive(Eq,
    Debug
    )

    Naming convention for file-level naming checks.

    NamingStyle::equal

    fn NamingStyle::equal(NamingStyle, NamingStyle) -> Bool
    automatically derived

    NamingStyle::not_equal

    fn NamingStyle::not_equal(x : NamingStyle, y : NamingStyle) -> Bool
    automatically derived

    NamingStyle::parse

    fn NamingStyle::parse(s : String) -> NamingStyle?

    Parse a naming style from its string tag.

    NamingStyle::to_repr

    automatically derived

    PackagePolicyRule

    pub struct PackagePolicyRule {
    id : String
    severity : Severity
    from : Array[String]
    allow : Array[String]?
    deny : Array[String]?
    kinds : Array[String]
    targets : Array[String]?
    reason : String
    } derive(Eq,
    Debug
    )

    One version-1 architecture rule over compiler package identities. Identities are module for the root package or module/rel otherwise. Pattern lists use the existing portable GlobPattern syntax and match the complete identity, not every descendant of a matched directory.

    PackagePolicyRule::equal

    Expose structural equality and inequality as regular rule methods.

    PackagePolicyRule::not_equal

    fn PackagePolicyRule::not_equal(x : PackagePolicyRule, y : PackagePolicyRule) -> Bool

    Expose structural equality and inequality as regular rule methods.

    PackagePolicyRule::to_repr

    Expose the derived debugging representation as a regular rule method.

    PolicyIssue

    pub struct PolicyIssue {
    rule_id : String
    severity : Severity
    message : String
    details : Map[String, String]
    } derive(
    Debug
    )

    A project-policy finding. Details identify the API or dependency edge; no invented source line is attached when compiler output has no location.

    PolicyReport

    pub struct PolicyReport {
    mode : String
    metadata : Map[String, String]
    counts : Map[String, Int]
    issues : Array[PolicyIssue]
    } derive(
    Debug
    )

    Result of a package-graph or interface-snapshot policy check. Counts describe project entities, not source files read by the linter.

    PolicyReport::errors_only

    fn PolicyReport::errors_only(self : PolicyReport) -> PolicyReport

    Filter presentation without changing the project scan counters.

    PolicyReport::has_errors

    fn PolicyReport::has_errors(self : PolicyReport) -> Bool

    Whether this policy run has any blocking findings.

    Prepared

    pub enum Prepared {
    NeverMatch
    Plain(MatchKind)
    Compiled(
    Regex
    )
    AllOf(Array[Prepared])
    AnyOf(Array[Prepared])
    NotOf(Prepared)
    }

    A matcher prepared for repeated evaluation against many lines.

    Regex compiles its pattern once here instead of once per line: a single rule evaluated over an N-line file previously cost N regex compilations, which dominates scan time. A pattern that fails to compile becomes Prep::NeverMatch, so a bad pattern yields no findings rather than aborting (config validation reports bad patterns up front).

    The combinator variants (AllOf / AnyOf / NotOf) hold their sub-matchers in prepared form too, so a nested Regex is likewise compiled once and shared across every line.

    Prepared::matches

    fn Prepared::matches(self : Prepared, line : StringView) -> Bool

    Test a prepared matcher against one line.

    Preset

    pub struct Preset {
    name : String
    description : String
    rules : Array[Rule]
    file_rules : Array[FileRule]
    structural_rules : Array[StructuralRule]
    }

    A built-in preset: a name, a one-line description, and its rules.

    ProjectFile

    pub struct ProjectFile {
    rel : String
    source : String
    model : FileModel
    snippets : Map[Int, String]
    } derive(
    Debug
    )

    One parsed file in the project index.

    ProjectFile::to_repr

    automatically derived

    ProjectIndex

    pub struct ProjectIndex {
    files : Array[ProjectFile]
    paths :
    Set
    [String]
    aliases : Array[(String, String)]
    } derive(
    Debug
    )

    The parsed project: every scanned file plus a membership set used for extension-less module resolution.

    ProjectIndex::resolve

    fn ProjectIndex::resolve(self : ProjectIndex, from_rel : String, specifier : String) -> String?

    Resolve a relative specifier from one file to a file in the index. The literal path is tried first, then path + ext, then path/index + ext for every probe extension — the same order bundlers use.

    Rule

    pub struct Rule {
    id : String
    severity : Severity
    message : String
    extensions : Array[String]
    match_ : MatchKind
    unless : MatchKind?
    scope : Scope
    match_comments : Bool
    match_literals : Bool
    } derive(
    Debug
    )

    A declarative lint rule.

    Rule::to_repr

    automatically derived

    ScanInfo

    pub struct ScanInfo {
    mode : String
    root : String
    extensions : Array[String]
    } derive(
    Debug
    )

    Scan metadata attached to machine-readable reports.

    ScanInfo::new

    fn ScanInfo::new(mode : String, root : String, extensions : Array[String]) -> ScanInfo

    Build the scan metadata carried by machine-readable reports.

    ScanInfo::to_repr

    automatically derived

    ScanMode

    pub enum ScanMode {
    Tree
    Changed(String)
    Staged
    Glob(String)
    Stdin
    Stdin0
    } derive(Eq,
    Debug
    )

    File selection. Git modes read immutable HEAD/index contents in the engine.

    ScanMode::changed

    fn ScanMode::changed(git_ref : String) -> ScanMode

    Select committed changes since merge-base(git_ref, HEAD); the engine reads captured HEAD blobs.

    ScanMode::equal

    fn ScanMode::equal(ScanMode, ScanMode) -> Bool
    automatically derived

    ScanMode::glob

    fn ScanMode::glob(pattern : String) -> ScanMode

    Select working-tree paths matching one root-relative glob, validated during selection.

    ScanMode::not_equal

    fn ScanMode::not_equal(x : ScanMode, y : ScanMode) -> Bool
    automatically derived

    ScanMode::staged

    fn ScanMode::staged() -> ScanMode

    Select index changes; the engine captures index blob ids and ignores unstaged source text.

    ScanMode::stdin

    fn ScanMode::stdin() -> ScanMode

    Read newline-delimited working-tree paths from standard input.

    ScanMode::stdin0

    fn ScanMode::stdin0() -> ScanMode

    Read NUL-delimited working-tree paths, including names containing newlines.

    ScanMode::tag

    fn ScanMode::tag(self : ScanMode) -> String

    Return the stable lowercase scan-mode name used in machine reports.

    ScanMode::to_repr

    automatically derived

    ScanMode::tree

    fn ScanMode::tree() -> ScanMode

    Select the working-tree directory recursively under the common path filters.

    Scope

    pub struct Scope {
    includes : Array[GlobPattern]
    excludes : Array[GlobPattern]
    } derive(Eq,
    Debug
    )

    Compiled include/exclude filters for finding paths. An empty include allows all paths; every exclude wins. Project dependencies may still be read as context.

    Scope::allows

    fn Scope::allows(self : Scope, rel : String) -> Bool

    Whether a root-relative path is inside this scope. Exclusion wins over inclusion, so an excluded path is out of scope even when an include pattern matches it.

    Scope::empty

    fn Scope::empty() -> Scope

    A scope that places no restriction on paths.

    Scope::equal

    fn Scope::equal(Scope, Scope) -> Bool
    automatically derived

    Scope::is_empty

    fn Scope::is_empty(self : Scope) -> Bool

    Whether the scope restricts paths at all.

    Scope::new

    fn Scope::new(includes : Array[String], excludes : Array[String]) -> Result[Scope, String]

    Compile a scope from raw patterns. The first invalid pattern is reported with a human-readable reason; no scope is applied until compilation succeeds.

    Scope::not_equal

    fn Scope::not_equal(x : Scope, y : Scope) -> Bool
    automatically derived

    Scope::to_repr

    automatically derived

    Severity

    pub enum Severity {
    Error
    Warning
    } derive(Eq,
    Debug
    )

    Severity of a rule violation.

    Severity::equal

    fn Severity::equal(Severity, Severity) -> Bool
    automatically derived

    Severity::error

    fn Severity::error() -> Severity

    Convenience constructors (pub so external packages can build values).

    Severity::not_equal

    fn Severity::not_equal(x : Severity, y : Severity) -> Bool
    automatically derived

    Severity::parse

    fn Severity::parse(self : String) -> Severity

    Parse a severity from its lowercase tag. Unknown values default to Warning so a typo in config never silently drops an error-level rule.

    Severity::tag

    fn Severity::tag(self : Severity) -> String

    Render a severity as a lowercase tag used in reports.

    Severity::to_repr

    automatically derived

    Severity::warning

    fn Severity::warning() -> Severity

    Construct a non-blocking warning severity for external rule definitions.

    SkippedFile

    pub struct SkippedFile {
    file : String
    reason : String
    } derive(
    Debug
    )

    A file that entered the scan but was not read.

    SkippedFile::to_repr

    automatically derived

    StructuralCache

    pub struct StructuralCache {
    key : String
    findings : Array[Finding]
    } derive(
    Debug
    )

    The cached verdict of the whole structural pass. Reusable only when the key — the effective rule fingerprint plus every participating file's content digest — matches exactly, because any file can change a cross-file answer. Snippets are deliberately not stored: a minified one-line file can make one snippet larger than the entire cache, and the line is re-derived from the source that was just scanned.

    StructuralCheck

    pub enum StructuralCheck {
    NoUnusedImports
    NoDuplicateImports
    NoUnresolvedRelativeImports
    NoImportCycles
    NoDefaultExport
    NoDeepRelativeImports(Int)
    NoRequireImports
    NoUnusedExports
    MoonbitRequirePublicDoc
    MoonbitNaming
    MoonbitNoUnwrap
    MoonbitNoPanic
    MoonbitNoPrintln
    MoonbitNoTodo
    } derive(Eq,
    Debug
    )

    A cross-file structural check evaluated over the whole parsed project index. Unlike line and file checks these require a second pass that sees every file at once, so they are expressed as project-level checks.

    StructuralCheck::equal

    automatically derived

    StructuralCheck::not_equal

    fn StructuralCheck::not_equal(x : StructuralCheck, y : StructuralCheck) -> Bool
    automatically derived

    StructuralCheck::to_repr

    automatically derived

    StructuralRule

    pub struct StructuralRule {
    id : String
    severity : Severity
    message : String
    extensions : Array[String]
    check : StructuralCheck
    scope : Scope
    } derive(
    Debug
    )

    A project-level lint rule.

    StructuralRule::applies_to

    fn StructuralRule::applies_to(self : StructuralRule, rel : String) -> Bool

    Whether a structural (project-level) rule applies to a given path.

    StructuralRule::to_repr

    automatically derived

    Token

    pub struct Token {
    kind : TokenKind
    text : String
    line : Int
    column : Int
    } derive(
    Debug
    )

    A token with its source position. line and column are 1-based and count characters; text is the exact source slice the token covers.

    Token::to_repr

    automatically derived

    TokenKind

    pub enum TokenKind {
    Ident
    Number
    Str
    TemplateText
    Backtick
    InterpOpen
    InterpClose
    RegexLit
    Punct
    } derive(Eq,
    Debug
    )

    The lexical class of a token.

    TokenKind::equal

    fn TokenKind::equal(TokenKind, TokenKind) -> Bool
    automatically derived

    TokenKind::not_equal

    fn TokenKind::not_equal(x : TokenKind, y : TokenKind) -> Bool
    automatically derived

    TokenKind::to_repr

    automatically derived

    UsedIdent

    pub struct UsedIdent {
    name : String
    line : Int
    column : Int
    } derive(
    Debug
    )

    An identifier read in code (not as part of an import statement), used to decide whether an imported binding is referenced.

    UsedIdent::to_repr

    automatically derived

    analyze

    fn analyze(index : ProjectIndex, rules : Array[StructuralRule]) -> Array[Finding]

    Run every structural rule against the index and collect the findings. Cross-file data (the import graph and the export-usage map) is computed once and shared by every rule that needs it.

    baseline_audit_with_findings

    fn baseline_audit_with_findings(audit : PolicyReport, result : LintResult) -> PolicyReport

    Add unsuppressed source findings to an explicit exception-audit report. File/line facts are retained as details, with no synthetic source locations.

    build_impact_plan

    fn build_impact_plan(root : String, sources : Array[(String, String)], paths : Array[String], changes : Array[String], config : ImpactConfig, input : String, observations : Array[ImpactIssue]) -> ImpactPlan raise

    Pure test-plan construction from known files. Only dependencies discovered under the documented adapters are considered proven; uncertainty requests all inventory tests. This is not a whole-language semantic proof.

    build_index

    fn build_index(sources : Array[(String, String)]) -> ProjectIndex

    Build the project index from (relative path, source) pairs. Sources are parsed with the structural parser; every file enters the index so later checks see a consistent file list even when a file parses to an empty model.

    canonical_root

    fn canonical_root(root : String) -> String raise NativeError

    Resolve an existing directory to its absolute realpath.

    check_api_snapshots

    fn check_api_snapshots(before_src : String, after_src : String, version_policy : String) -> Result[PolicyReport, ConfigError]

    Compare strict v1 snapshots with identical package/toolchain/backend metadata. Removals and signature/type-shape changes require review; standalone additions are counted without errors. Ignore comments, whitespace, declaration/member order, implementation bodies, and equivalent old/new derive display styles.

    Policy none reports review findings as errors without interpreting versions. Explicit semver permits warnings after a major increase for stable releases, or minor/major increase for 0.x; insufficient bumps add a blocking policy issue. Versions must be three non-leading-zero Int32 components. Prerelease/build metadata is deliberately inconclusive. Unsupported syntax, unknown policy, malformed snapshots, or mismatched identity metadata return ConfigError.

    check_package_graph

    fn check_package_graph(src : String, rules : Array[PackagePolicyRule]) -> Result[PolicyReport, ConfigError]

    Check one actual moon tree --package --json version-3 graph. Fully validates the graph, even when no rule applies. Only direct edges originating at selected root packages and ending at supplied non-stdlib nodes are checked. The compiler omits stdlib imports; neither stdlib nor transitive dependencies are covered. Backends are never combined, and each source/test/wbtest edge kind is evaluated independently. Duplicate edges are collapsed by origin, destination, kind, and alias; findings are sorted by rule id, origin, destination, kind, target, and alias. Details contain from/to/kind/target/alias/reason, never invented locations. packages counts unique graph root packages; edges_checked counts unique edge-kind/alias records to which at least one rule applies, not rule matches. Empty rule sets fail. A valid graph with no applicable rule or edge returns checked0 with an explicit applicability metadata marker, not an unqualified pass. Graph versions and indices must be nonnegative integer JSON literals.

    collect_extensions

    fn collect_extensions(rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule]) -> Array[String]

    Collect the union of all rule and file-rule extensions (for the default scan set). An empty rule list keeps the scan set empty rather than scanning every file.

    comment_mode_for

    fn comment_mode_for(rel : String) -> CommentMode

    Pick the comment syntax for a path: JavaScript/TypeScript-family sources get the template- and regex-aware scanner; everything else keeps the plain view.

    config_fingerprint

    fn config_fingerprint(rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope) -> String

    Fingerprint of the effective rule set. Everything that can change a finding is folded in: rule ids, severities, messages, extension filters, matcher/check parameters, per-rule scopes and the global scope. The digest is taken over a canonical, order-sensitive rendering so that reordering rules is still a cache invalidation (it changes report order).

    content_hash

    fn content_hash(source : String) -> String

    Digest of a file's content, used as the cache key. FNV-1a 64-bit — the same primitive the baseline uses: collision resistance against accidental edits is all a cache needs, and it keeps the dependency surface at zero.

    error_message

    fn error_message(error : Error) -> String

    Human-readable operational errors with their useful context retained.

    finding_hash

    fn finding_hash(f : Finding) -> String

    Compute the stable hash key for a finding.

    The key is a hex digest of rule_id|file|line|snippet. We use a simple FNV-1a hash rather than a cryptographic hash: the baseline only needs collision resistance against accidental edits, not against adversaries, and this keeps the dependency surface at zero.

    fix_moonbit_whitespace

    fn fix_moonbit_whitespace(source : String, trailing : Bool, tab_width : Int?, final_newline : Bool) -> String raise

    Fix only whitespace outside MoonBit literal spans. Interpolation and raw string bodies remain byte-for-byte unchanged; incomplete input is rejected. A final newline is not inserted into a final raw-string content line.

    git_blob

    fn git_blob(root : String, rel : String, staged : Bool) -> String raise NativeError

    Read regular source from the index (true) or HEAD (false), never working tree. Missing and nonregular (including Git symlink) entries raise an error.

    git_changed_files

    fn git_changed_files(root : String, git_ref : String) -> Array[String] raise NativeError

    ACMR paths from merge-base(ref, HEAD) to committed HEAD, not working tree. Validate ref as a commit and reject failures. Names are relative to root, including when root is a repository subdirectory.

    git_source_kind

    fn git_source_kind(root : String, rel : String, staged : Bool) -> Int raise NativeError

    Index/HEAD kind: 0 missing, 1 regular, 2 tree, 3 symlink/gitlink/other. Never consult working tree; an unmerged index always raises an error.

    git_staged_files

    fn git_staged_files(root : String) -> Array[String] raise NativeError

    Actual index changes: omit deletions, retain rename destinations, support unborn HEAD, and reject an unmerged index anywhere in the repository.

    glob_pattern_error

    fn glob_pattern_error(pattern : String) -> String?

    Validate a glob pattern and return the reason it is invalid, or None when the pattern is well-formed.

    impact_default_config

    fn impact_default_config() -> ImpactConfig

    Default MoonImpact scope and test inventory. No project-local executable configuration is loaded. Filesystem reads are opt-in by wrapper name.

    impact_git_changes

    fn impact_git_changes(root : String, base : String?) -> Array[String] raise

    Files changed from base (HEAD when absent) to the live working tree, including staged, unstaged and non-ignored untracked files. Deletions and both rename endpoints are retained. root must be the repository root; this is not an immutable HEAD snapshot and callers must avoid concurrent Git/worktree edits during selection.

    impact_has_moonbit_module

    fn impact_has_moonbit_module(root : String) -> Bool

    Whether the root contains a MoonBit module or workspace descriptor. Detection never evaluates project code.

    impact_moonbit_plan

    fn impact_moonbit_plan(root : String, changed : Array[String], input : String, observations : Array[ImpactIssue]) -> ImpactPlan raise

    Plan a MoonBit module: changed files select their owning packages and every transitive importer. The plan is advisory, exactly like the JS/TS planner: an unparseable manifest or an unmodeled change requests every package rather than pretending no test is affected.

    impact_plan

    fn impact_plan(root : String, changed : Array[String], config : ImpactConfig, input : String, observations : Array[ImpactIssue]) -> ImpactPlan raise

    Read a live working tree without following links and make an advisory plan. No project command or dependency installation is performed. Source read failures block execution; unsupported syntax requests a full regression.

    impact_run_moon_test

    fn impact_run_moon_test(root : String, packages : Array[String], timeout_ms : Int) -> Int raise

    Explicitly run moon test <package paths> in root. Each package path is root-relative and passed as its own argv element, never shell text. The module root package is addressed as ".". Child stdout and stderr both go to this process's stderr.

    impact_run_moon_test_full

    fn impact_run_moon_test_full(root : String, timeout_ms : Int) -> Int raise

    Explicitly run the runner's complete MoonBit suite without package filters. This does not depend on the planner's static test inventory.

    impact_run_vitest

    fn impact_run_vitest(root : String, tests : Array[String], full : Bool, timeout_ms : Int) -> Int raise

    Explicitly run pnpm exec vitest run in root. Related mode requires a nonempty selection; full mode intentionally omits filters. Each test path is root-relative and passed as its own ./path argv element, never shell text. Child stdout and stderr both go to this process's stderr. Startup errors and timeout raise; a normal child exit status is returned unchanged.

    impact_write_report_new

    fn impact_write_report_new(path : String, content : String) -> Unit raise

    Atomically create a new UTF-8 report. Existing files, directories and symlinks are never replaced, including a target created concurrently. Parent directories must already exist. The temporary file is kept in the destination directory and linked into place with create-only semantics.

    is_relative

    fn is_relative(specifier : String) -> Bool

    Whether a module specifier is relative to the importing file. Bare specifiers (react, @scope/pkg) resolve through node_modules, which this linter does not model, so they are never "unresolved".

    lint_file

    fn lint_file(rel : String, source : String, lines : Array[(Int, String)], file_rules : Array[FileRule]) -> Array[Finding]

    Evaluate file-level rules against a file's content. Each finding points to the specific line where the violation occurs (or line 1 for file-level properties like naming).

    lint_files

    fn lint_files(root : String, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope) -> LintResult raise

    Lint explicit working-tree paths. Paths are validated and deduplicated; unreadable/missing files produce diagnostics instead of successful counters.

    lint_files_with

    fn lint_files_with(root : String, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope, aliases : Array[(String, String)]) -> LintResult raise

    Alias-aware variant of lint_files.

    lint_lines

    fn lint_lines(rel : String, code_lines : Array[(Int, String)], literal_lines : Array[(Int, String)], raw_lines : Array[(Int, String)], rules : Array[Rule]) -> Array[Finding]

    Apply declarative line rules to successfully read source content.

    Each matcher is compiled once per rule (see MatchKind::prepare), then reused for every line — compiling per line dominates scan time otherwise.

    Three views of the file are passed in: code_lines is the code view (comments blanked, and literal contents blanked for the JS/TS family — see comment.mbt), literal_lines is the comment-stripped view with literal text intact, and raw_lines is the file exactly as written. A rule matches against code_lines by default; match_literals selects literal_lines for rules whose target only exists as a literal value, and match_comments selects raw_lines — the opt-in a comment-targeting rule needs.

    lint_selected

    fn lint_selected(root : String, mode : ScanMode, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope) -> LintResult raise

    Changed uses committed HEAD blobs; Staged uses actual index blobs. Other modes read regular working-tree files without following links.

    The global scope is applied to the candidate list first: candidates it rejects are counted in files_out_of_scope and never read. Rule-level scope then decides which rules see each selected file.

    The scan runs in two stages: the per-file stage applies line rules and file rules, then — when structural rules are configured — the sources of every scanned file are parsed and analysed as one project, which is what cross-file checks (unused imports, import cycles, dead exports) need.

    lint_selected_cached

    fn lint_selected_cached(root : String, mode : ScanMode, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope, cache : Cache?) -> (LintResult, Cache) raise

    Cache-aware variant of lint_selected. Returns the lint result together with the refreshed cache, which the caller persists. Passing a cache whose fingerprint does not match the effective rule set (or a stale format version) degrades to a full scan — correctness first, speed second.

    lint_selected_cached_with

    fn lint_selected_cached_with(root : String, mode : ScanMode, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope, cache : Cache?, aliases : Array[(String, String)]) -> (LintResult, Cache) raise

    Alias-aware variant of lint_selected_cached.

    lint_selected_with

    fn lint_selected_with(root : String, mode : ScanMode, files : Array[String], rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], scope : Scope, aliases : Array[(String, String)]) -> LintResult raise

    Alias-aware variant of lint_selected.

    lint_tree

    fn lint_tree(root : String, rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], exts : Array[String], scope : Scope) -> Result[LintResult, Error]

    Select and lint a directory tree under the supplied rules and global scope. Selection failures return Err; source/context read failures stay in diagnostics.

    lint_tree_with

    fn lint_tree_with(root : String, rules : Array[Rule], file_rules : Array[FileRule], structural_rules : Array[StructuralRule], exts : Array[String], scope : Scope, aliases : Array[(String, String)]) -> Result[LintResult, Error]

    Alias-aware variant of lint_tree. aliases are (prefix, target) pairs used to resolve path-aliased imports during the structural pass.

    make_api_snapshot

    fn make_api_snapshot(interface_text : String, toolchain : String, backend : String, module_version : String) -> Result[String, ConfigError]

    Make a strict version-1 JSON snapshot of a compiler-generated MoonBit interface. The package comes from its package line; toolchain is recorded exactly and backend is native, js, wasm, wasm-gc, or llvm. Toolchain and module version must not be blank. Unsupported/malformed public syntax is inconclusive.

    Only exports present in the supplied interface are covered: omitted #doc(hidden) extensions, private implementation, behavior, and ABI are not.

    merge_presets

    fn merge_presets(names : Array[String]) -> Result[LintConfig, ConfigError]

    Merge several presets into one rule set. Rules are concatenated in preset order; a rule whose id already appeared is dropped (first occurrence wins). File rules and structural rules are merged the same way. The merged config carries no global scope.

    parse_config

    fn parse_config(src : String) -> Result[LintConfig, ConfigError]

    Parse a rules config from a JSON string.

    parse_config_with_extends

    fn parse_config_with_extends(src : String, config_dir : String) -> Result[LintConfig, ConfigError]

    Parse a config with extends support. The extends field can be a string or array of strings pointing to other config files (relative to the config file that declares them). Extended configs are loaded and merged: their rules and file_rules are appended after the current config's, so the current config takes precedence on id conflicts.

    config_dir is the directory of the config file whose text is src; it is used to resolve that file's relative extends paths.

    parse_disable_comments

    fn parse_disable_comments(source : String) -> DisableMap

    Parse inline disable directives from raw source text. Returns a DisableMap that can be queried per line and rule.

    parse_impact_config

    fn parse_impact_config(source : String) -> ImpactConfig raise

    Parse inert JSON configuration. Unknown fields, duplicate JSON keys and invalid paths are rejected before scanning. This schema is independent of moonlint rules and deliberately has no command execution or extends field.

    parse_package_policy

    fn parse_package_policy(src : String) -> Result[Array[PackagePolicyRule], ConfigError]

    Parse a strict version-1 package-policy JSON document. Requires a nonempty package_rules array; each rule requires id, severity, from, reason, and exactly one allow/deny array. Unknown fields, duplicate JSON keys or rule ids, malformed arrays, and invalid globs are ConfigError. Parsed pattern/kind/target lists are deduplicated and sorted; rule declaration order is retained. An empty allowlist is an explicit deny-all policy.

    parse_source

    fn parse_source(src : String) -> FileModel

    Parse a source string into a structural model.

    parse_source_for

    fn parse_source_for(rel : String, src : String) -> FileModel

    Parse a source file, choosing the front end by extension. A .vue file additionally gains the identifier reads of its template binding expressions, which live inside HTML attribute strings.

    parse_tokens

    fn parse_tokens(tokens : Array[Token]) -> FileModel

    Parse a token stream into a structural model.

    Two logical passes over the same array: the statement walker records imports, exports and declarations (and the token spans of import statements), then a usage walker collects identifier reads outside those spans. Import statements are excluded so that an import's own names never count as usages of themselves.

    preset_by_name

    fn preset_by_name(name : String) -> Preset?

    Look up a preset by name. Returns None for an unknown name.

    preset_names

    fn preset_names() -> Array[String]

    The names of all built-in presets, sorted alphabetically.

    read_fix_source

    fn read_fix_source(root : String, rel : String) -> String raise

    Read fix input strictly, preserving its BOM and rejecting unsafe paths.

    read_lines

    fn read_lines(path : String) -> Array[(Int, String)] raise

    Read strict UTF-8 source and return numbered, comment-masked lines. MoonBit literals are also masked; BOMs are preserved and binary NULs rejected.

    read_stdin_text

    fn read_stdin_text() -> String raise NativeError

    Read stdin incrementally until EOF, without seeking or closing stdin. Preserve whitespace, newlines, UTF-8 BOMs and embedded NULs exactly.

    render_detail

    fn render_detail(findings : Array[Finding]) -> String

    Render findings as a human-readable detail listing.

    render_github

    fn render_github(result : LintResult) -> String

    Render escaped workflow annotations at recorded source positions and a scan summary.

    render_impact_html

    fn render_impact_html(plan : ImpactPlan) -> String

    Generate a standalone, script-free HTML report. All project-controlled strings are escaped; the report fetches no external assets or scripts.

    render_impact_json

    fn render_impact_json(plan : ImpactPlan) -> String

    Render a versioned advisory plan. This schema deliberately contains no passing-test verdict: it records selection and evidence, not execution.

    render_impact_text

    fn render_impact_text(plan : ImpactPlan) -> String

    Human-readable selection with one shortest known witness per related test.

    render_json

    fn render_json(result : LintResult, scan : ScanInfo) -> String

    Render source findings, scan/context counters and diagnostics as version-1 JSON.

    render_policy_github

    fn render_policy_github(report : PolicyReport) -> String

    Workflow annotations without guessed file/line properties.

    render_policy_json

    fn render_policy_json(report : PolicyReport) -> String

    Project policy JSON reports keep package/symbol identities in details, rather than pretending compiler graph edges have source-file locations.

    render_policy_sarif

    fn render_policy_sarif(report : PolicyReport) -> String

    SARIF 2.1.0 project diagnostics. Snapshot/graph identities are properties; locations are absent because no source ranges were supplied by the input.

    render_policy_text

    fn render_policy_text(report : PolicyReport, summary? : Bool) -> String

    Human-readable policy results, including explicit coverage/applicability.

    render_preset_list

    fn render_preset_list() -> String

    Render the preset list for --list-presets: one name — description line per preset, sorted by name.

    render_sarif

    fn render_sarif(result : LintResult, scan : ScanInfo) -> String

    Render a SARIF 2.1.0 document from a lint result.

    render_summary

    fn render_summary(result : LintResult) -> String

    Render a per-rule summary tally.

    select_files

    fn select_files(mode : ScanMode, root : String, exts : Array[String]) -> Array[String] raise

    One selection contract across all modes: root-relative, deduplicated, sorted, with the same extension/noise filtering. Failures never fall back to a successful empty scan. Empty extension filters select all candidates.

    source_path_kind

    fn source_path_kind(path : String) -> Int raise NativeError

    lstat: 0 missing, 1 regular, 2 directory, 3 symlink/other. Never follow the final component; callers prohibiting ancestor symlinks must check them too.

    spec_source

    fn spec_source(spec : ImportSpec) -> String

    The module specifier of an import, with its surrounding quotes removed. The tokenizer keeps quotes in string tokens, so every consumer of ImportSpec::source goes through here first.

    strip_comments_code

    fn strip_comments_code(src : String, mode : CommentMode) -> String

    The code view: comments blanked as in strip_comments, and — for the JavaScript/TypeScript family — the contents of string, template and regex literals blanked as well, so a line rule never matches literal text.

    Deliberately preserved: the literal delimiters (", ', ` , /), so attribute-shaped matches such as ref=" still work, and ${...} interpolations, because an interpolation is code. Line breaks inside multi-line templates and strings are preserved, so line and column positions still line up with the raw source.

    Plain sources (.vue, .svelte, .astro, unknown extensions) have no literal-aware scanner, so their code view equals their literal view; the MoonBit front end already blanks literals in its own code view.

    structural_key

    fn structural_key(fingerprint : String, ids : Array[(String, String)]) -> String

    Identity of a structural pass: the configuration fingerprint plus the sorted (path, content hash) pairs of every file that took part. Equal keys mean the same rules ran over byte-identical inputs.

    tokenize

    fn tokenize(src : String) -> Array[Token]

    Tokenize a whole source file. The scan never fails: malformed input (an unterminated string, a stray $) is consumed on a best-effort basis and reported as tokens, because a linter must not lose findings to a typo.

    utc_date

    fn utc_date() -> String raise NativeError

    Return the host's UTC calendar date for default exception-expiry checks. The explicit CLI date override remains available for deterministic CI tests.

    validate_fix_path

    fn validate_fix_path(root : String, rel : String) -> Unit raise

    Refuse fixes through symlink ancestors or on nonregular files.

    validate_glob

    fn validate_glob(pattern : String) -> Unit raise

    The supported portable subset is literal segments, *, ?, and standalone **. Reject unsupported syntax instead of silently interpreting it differently.

    validate_moonbit_source

    fn validate_moonbit_source(source : String) -> Unit raise

    Reject incomplete lexical input instead of counting it as a clean scan. This checks lexical coverage only, not MoonBit types or the full grammar.

    validate_rules

    fn validate_rules(rules : Array[Rule]) -> Result[Unit, ConfigError]

    Validate that every rule's regex compiles. Returns the first error found.

    vue_template_usages

    fn vue_template_usages(src : String) -> Array[UsedIdent]

    Identifier reads that occur inside template binding expressions. Only binding attribute values are treated as expressions; plain text and static attributes such as class="..." are left alone, and <script>/<style> blocks are ignored.

    walk_files

    fn walk_files(root : String, exts : Array[String]) -> Array[String] raise

    Collect root-relative candidates in stable order. Empty exts means all files, including extensionless files. Links/other non-directories are kept as candidates so the engine can report them as skipped, never read them.

    write_atomic_text

    fn write_atomic_text(path : String, content : String) -> Unit raise NativeError

    Same-directory mkstemp, complete write, fsync, close, then atomic rename. Failure before rename preserves old file; refuse existing nonregulars.