Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

“We went all the way down south We were frothing at the mouth Coming down to Derby town We’d beaten everyone around, singing” — Sumo

Crua

Crua is a planned cross-language Rust CLI that checks whether the pieces of a codebase cost more than their shape implies — cache-line layout, dispatch/type stability, thread vs. event-loop concurrency models, and lock/STM contention — independent of whether that code is logically correct or well-composed.

Draft and unimplemented

EARS 1.0.0 and any OpenSpec changes are active proposals awaiting human approval. This site documents intended behavior; it does not claim that the CLI has been implemented.

Start here

Documentation provenance

The Pages site is assembled directly from crua-ears-spec.md and openspec/changes/ during CI. The rendered copies are generated artifacts; the repository source files remain authoritative.

Source: Generated from openspec/project.md during the documentation build.

Project Context

Purpose

Crua is a cross-language static-analysis CLI that checks whether code respects the raw hardware and runtime cost model it executes on — cache-line layout, dispatch/type stability, thread vs. event-loop concurrency models, and lock/STM contention — independent of whether that code is logically correct or well-composed.

The authoritative product requirements are in crua-ears-spec.md. Preserve its requirement IDs (REQ-*) in proposals, tests, findings, and traceability notes.

Tech Stack

  • Implementation language: Rust, organized as a Cargo workspace and exposed as the crua CLI binary.
  • Rust baseline: stable toolchain, rustfmt formatting, Clippy linting, and Cargo-native unit, integration, and documentation tests.
  • Language analysis: tree-sitter or a language-native parser behind front-end plugins.
  • Core model: a language-agnostic representation of nodes, cost patterns, hotness classes, and shape sources.
  • CLI output: human-readable, JSON, and SARIF.
  • Benchmark generation: per-language native benchmarking toolchains (BenchmarkDotNet for C#, BenchmarkTools.jl for Julia, pyperf for Python, criterium for Clojure).

Project Conventions

Code Style

  • Format with rustfmt and keep Clippy clean.
  • Use domain terms from the EARS specification consistently: cost pattern, cost pattern kind, tier, hotness class, confirmation status, setup strategy, shape source, effect channel.
  • Keep built-in vocabularies closed and project extensions explicitly declared and validated. Unknown cost patterns remain unclassified; never silently coerce them to a successful/default case.
  • Use stable requirement and rule IDs. A finding always has a rule ID, file, line, cost pattern kind, tier, hotness class, and shape source.

Architecture Patterns

  • Keep language-specific pattern recognition in versioned, conformance-tested front-end plugins.
  • Maintain a versioned cost catalogue mapping each (cost pattern kind, language) pair to a matcher, severity floor, and explanation template.
  • Prefer consuming shape/effect data from an installed composability checker (Vampiro) when available; fall back to standalone extraction at reduced precision otherwise.
  • Support diff-scoped analysis as the interactive/agent default and full repository analysis as an incremental mode.
  • Never generate or modify source or test files by default; benchmark generation is an explicitly opt-in mode (crua verify).

Testing Strategy

  • Develop every behavior from an OpenSpec scenario traceable to one or more EARS requirement IDs.
  • Maintain a shared, versioned conformance-fixture suite for every front-end plugin and cost catalogue entry.
  • Test all supported output formats against the same underlying finding data.
  • Include negative fixtures for unclassified patterns, unavailable toolchains, inconclusive benchmarks, and suppressed concurrency-model findings.
  • Benchmark diff-scoped scans with moderate cost-pattern count; the target is single-digit seconds.

Git Workflow

  • Use OpenSpec changes for new capabilities, architecture changes, breaking behavior, and performance work. Do not implement a proposal before approval.
  • Keep commits focused and preserve requirement IDs in change artifacts and test names where practical.
  • Pull-request CI should run diff-scoped scan in gate mode at the configured severity threshold.

Domain Context

Crua checks whether code costs more than its shape implies. Its core taxonomy of cost pattern kinds:

  • layout — false sharing, missing padding/alignment, AoS vs. SoA mismatch
  • dispatch — type instability, boxed math, reflection-based interop, megamorphic call sites
  • vectorization — scalar loop where a vectorized/bulk operation exists
  • concurrency-model-mismatch — code written as if a runtime provides parallelism it does not (e.g. CPU-bound work inside a GIL-bound thread)
  • contention — lock, atomic-CAS, or STM retry storms driven by write-frequency or layout

Findings are tiered (0–3) by evidentiary strength: lexical match, structural cross-reference, hotness-adjusted, or empirically verified via generated benchmark.

Important Constraints

  • Static analysis must never execute analyzed source code.
  • Unknown or unsupported cost patterns must be visible in output, never silently omitted or treated as absent.
  • Benchmark generation (crua verify) must never run as part of crua scan; it is an explicitly separate, separately-budgeted step.
  • guidance mode never fails solely because of findings; gate mode fails only when findings on diff-touched nodes meet the configured threshold.
  • Toolchain unavailability is ToolchainUnavailable, not disconfirmed or success.
  • The repository is greenfield. openspec/specs/ describes built truth, so do not copy aspirational EARS requirements there before implementation; add them through reviewed changes and archive them as capabilities ship.

External Dependencies

  • Git diff/repository metadata for diff-scoped analysis and hotness reachability estimation.
  • Per-language tree-sitter grammars or native parser APIs.
  • Per-language benchmarking toolchains for crua verify mode.
  • Optionally: installed Vampiro composability checker for shape/effect data.
  • CI platforms capable of consuming generated pipeline configuration and SARIF.

Document status: Draft, not yet approved. The source file crua-ears-spec.md is authoritative.

EARS Specification: Crua

Crua (Spanish/Portuguese, fem. of crudo/cru — “raw”) is a cross-language CLI that checks whether code respects the raw hardware and runtime cost model it executes on — cache-line layout, dispatch/type stability, thread vs. event-loop concurrency models, and lock/STM contention — independent of whether that code is logically correct or well-composed.

This document is self-contained. It assumes no prior conversation and no familiarity with any other tool, though Section 1 notes where Crua optionally consumes shape and effect-channel data already produced by a composability checker called Vampiro, and where a coverage checker called Livin can consume Crua’s hotness data in return, if either is present.

Normative status

This file is the normative product-requirements source. OpenSpec changes define reviewed implementation slices and SHALL trace to, but cannot override, the REQ IDs here. openspec/project.md, README files, and generated copies under docs/ are explanatory when they conflict with this file. A deliberate requirements change therefore updates this file first and preserves existing REQ IDs unless a requirement is explicitly retired.


0. Background & Motivation

Two functions can each pass every test and every composability check and still be five times slower than necessary, because tests and type checkers verify what a value is, not where it lives or how the runtime schedules it. A thread-safe counter implemented as long[] counters with one slot per thread is logically correct, passes every unit test, and is five times slower under contention than the equivalent padded layout — because adjacent slots share a cache line, and every core’s write invalidates every other core’s cached copy of that line. The same shape of problem recurs, differently, in every language: a Julia function that looks numeric but returns Union{Float64, Nothing} from one branch forces boxing and dynamic dispatch on every call; a Python loop over a numpy array that could vectorize instead pays per-element interpreter overhead; a Clojure atom updated from four threads at high frequency causes CAS-retry storms that look like contention but are actually a data-layout problem wearing a concurrency costume.

None of these are caught by a type checker (types matched), a linter (no syntax rule was violated), a test suite (behavior was correct), or a composability checker (the pieces fit together structurally and compose in the right category). They require knowing, per language, which structural shapes carry a disproportionate hardware or runtime cost, and whether the code as written falls into one of them — and, where that matters enough to act on, whether the claimed cost is real rather than folklore, which requires actually measuring it in isolation rather than asserting it from a rule.

Crua explicitly does not adjudicate correctness of concurrent interleavings (races, lost updates, deadlock) — that is a job for a model checker, not a cost-pattern linter. Crua also does not decide whether two implementations are substitutable (that is Vampiro’s optionality axis) or whether a test suite reaches enough boundary values (that is Livin’s job) — Crua asks only whether a given, already-correct, already-composed piece of code costs more than its own shape implies it should.


1. Scope & Definitions

  • Cost pattern: a named, structural antipattern associated with a disproportionate hardware or runtime cost relative to a straightforward fix of the same logical behavior.
  • Cost pattern kind: a closed-but-extensible taxonomy tag on a cost pattern: layout (false sharing, missing padding/alignment, array-of-structs vs. struct-of-arrays mismatch), dispatch (type instability, boxed math, reflection-based interop, megamorphic call sites), vectorization (scalar loop over a structure with an available vectorized/bulk operation), concurrency-model-mismatch (code written as if a runtime provides parallelism it does not — e.g. CPU-bound work inside a GIL-bound thread, or vice versa), or contention (lock, atomic-CAS, or STM retry storms driven by write-frequency or layout, not by genuine logical contention).
  • Tier: the evidentiary strength behind a finding. 0 (lexical — syntactic pattern match only), 1 (structural — cross-referenced against declared size/adjacency/type information), 2 (hotness-adjusted — Tier 1 combined with a static reachability estimate for how often the site executes), 3 (empirically verified — an isolated microbenchmark was generated and run, producing a measured ratio).
  • Cost catalogue: a versioned, per-(cost pattern kind, language) table mapping a matcher to a severity floor and an explanation template, validated by conformance fixtures, the same mechanism used by Vampiro’s idiom table and Livin’s boundary catalogue.
  • Hotness class: reachable (the site is statically reachable from a thread-spawn, parallel-loop, or otherwise repeated-invocation context with no upstream constraint ruling that out), unreachable (an upstream constraint establishes the site cannot execute at meaningful frequency — e.g. it runs once at process start), or unknown (cannot be determined from available shape/effect information). This mirrors Livin’s reachability class, applied to execution frequency rather than value reachability.
  • Effect channel (consumed, not computed, when Vampiro is installed): Vampiro’s plain/result/option/throws/async/stream classification for a node. Crua uses this to determine a node’s actual concurrency model — an async node in a single-threaded event-loop runtime (e.g. Python asyncio) cannot exhibit true cache-line contention between concurrent writers, regardless of how the code looks syntactically.
  • Confirmation status: unconfirmed (Tier 0–2, no benchmark run), confirmed (Tier 3, measured ratio cleared the configured threshold with acceptable variance), disconfirmed (Tier 3, measured ratio did not clear the threshold — the pattern matched syntactically but did not cost what the catalogue predicted), or inconclusive (Tier 3 attempted, but variance across runs exceeded the acceptable bound).
  • Benchmark decision protocol: unless project configuration overrides it, run the native benchmark tool for 5 warm-up rounds followed by 30 measured rounds for each variant in the same process and alternating order. The measured ratio is median(as-found) / median(canonical-fixed), the confirmation threshold is 1.20, and acceptable variance means each variant’s measured-round coefficient of variation (sample standard deviation divided by mean) is at most 0.05. The repro artifact records the effective values, tool/toolchain versions, OS, CPU model and logical core count. A ratio at least 1.20 with acceptable variance is confirmed; a lower ratio with acceptable variance is disconfirmed; excessive variance is inconclusive.
  • Severity: the ordered levels low < medium < high < critical. Unless project configuration overrides it, gate mode uses threshold high.
  • Setup strategy: the method used to construct inputs for a generated benchmark, in the precedence defined normatively by REQ-17: verbatim, then harvested-fixture (an existing repo-native constructor, property-test generator, test-file factory, or spec generator reused as-is), then structural-synthesis (a mechanically-generated instance built from an all-primitive type declaration), then needs-agent-input (no safe construction method found; a stub is emitted rather than a guessed value).
  • Repro artifact: a generated, standalone benchmark file produced only under crua verify, containing an as-found variant and a canonical-fixed variant of the flagged site, run with the target language’s native benchmarking tool (BenchmarkDotNet for C#, BenchmarkTools.jl for Julia, pyperf for Python, criterium for Clojure).
  • Shape source: vampiro (shape/effect data consumed from an installed composability checker) or standalone (Crua’s own reduced- precision extraction). Every finding records which source produced it.

2. Ubiquitous Requirements

  • REQ-1: The tool shall obtain domain/codomain shape and effect-channel data for analyzed nodes, preferentially by consuming an installed composability checker’s extracted data when available, and shall record shape source on every finding.
  • REQ-2: The tool shall classify every candidate site into exactly one cost pattern kind from the closed-but-extensible taxonomy in Section 1, or unclassified if none applies.
  • REQ-3: The tool shall maintain a versioned cost catalogue mapping each (cost pattern kind, language) pair to a matcher, a severity floor, and an explanation template, validated by conformance fixtures using the same mechanism as the family’s other tools.
  • REQ-4: Every finding shall carry a tier (0–3) and the evidence supporting that tier (query match, structural cross-reference, hotness class, or measured benchmark ratio).
  • REQ-5: Every finding shall carry a rule ID, file and line, cost pattern kind, tier, hotness class, and shape source.
  • REQ-6: The default crua scan command shall never generate or modify source or test files; it shall only report findings. Benchmark generation is a separate, explicitly opt-in mode (Section 5), consistent with the tool family’s enforcement-not-generation default.

3. Event-Driven Requirements

  • REQ-7: When a candidate site matches a Tier-0 lexical query, the tool shall attempt Tier-1 structural cross-reference (element size, adjacency, distinct-writer-context count, presence of padding/alignment annotation) before reporting a finding at or above the catalogue’s severity floor.

    Example: long[] counters = new long[threadCount] written from distinct thread contexts with Interlocked.Increment raises a Tier-1 layout finding once cross-referenced against sizeof(long) and thread count showing multiple counters share a 64-byte line.

  • REQ-8: When a cost pattern kind is dispatch and the language exposes a static type-narrowing signal (an untyped/Any-typed field reachable from a hot path in Julia, a reflection warning in Clojure, a boxed generic in C#), the tool shall raise a Tier-1 finding citing the specific untyped or reflective path.

  • REQ-9: When a site’s hotness class is reachable and the cost pattern kind’s severity floor is met, the tool shall escalate the finding’s severity by one level relative to an otherwise-identical finding whose hotness class is unreachable.

  • REQ-10: When effect-channel data (consumed from an installed composability checker, or derived standalone) indicates a node executes under a single-threaded concurrency model despite an async or thread-like syntactic appearance (e.g. Python asyncio coroutines), the tool shall suppress layout and contention findings for that node and evaluate only dispatch and vectorization findings.

  • REQ-11: When crua verify is invoked against a Tier-1 or Tier-2 finding, the tool shall attempt benchmark synthesis using the setup-strategy order in Section 5 and shall set confirmation status to confirmed only if the measured ratio between the as-found and canonical-fixed variants clears the configured threshold with acceptable variance across repeated rounds; otherwise it shall set disconfirmed or inconclusive as appropriate, never silently discarding the attempt.


4. State-Driven Requirements

  • REQ-12: While gate mode is gate, the tool shall exit non-zero if any Tier-2-or-higher finding on a diff-touched node with hotness class reachable meets or exceeds the configured severity threshold.
  • REQ-13: While gate mode is guidance, the tool shall report all findings without forcing a non-zero exit.
  • REQ-14: While a candidate site’s cost pattern kind cannot be classified into the taxonomy, the tool shall report it as unclassified explicitly, rather than silently excluding it.
  • REQ-15: While crua verify is running and the required language toolchain (e.g. dotnet, julia, pyperf, criterium) is unavailable, the tool shall report ToolchainUnavailable, distinct from disconfirmed, and shall never treat unavailability as a pass.

5. Optional Feature Requirements

  • REQ-16: Where no composability checker’s shape/effect data is installed, the tool shall fall back to its own standalone extraction at reduced precision, recording shape-source: standalone on every finding produced in that run.
  • REQ-17: Where crua verify is enabled, the tool shall select setup by this single precedence order: (1) use verbatim if it produces a compilable repro; otherwise (2) use harvested-fixture if a matching repo-native aid described by REQ-18 exists and produces a compilable repro; otherwise (3) use structural-synthesis if it produces a compilable repro; otherwise (4) use needs-agent-input. The tool shall stop at the first successful step.
  • REQ-18: Where a repo-native construction aid is present (a property-test generator such as Hypothesis, clojure.spec generators, or a test-file factory function matching a Create*/Build*/Make* naming convention) for the flagged type, the tool shall try harvesting it after verbatim and before structural synthesis, exactly as ordered by REQ-17; an aid that does not produce a compilable repro shall not prevent fallback to structural synthesis.
  • REQ-19: Where custom cost catalogue entries are supplied for project-specific types, the tool shall use them in place of, or in addition to, the built-in catalogue.
  • REQ-20: Where diff-scoped mode is selected, the tool shall restrict scanning to nodes touched by the diff.
  • REQ-21: Where output format human, json, or sarif is selected, the tool shall serialize identical underlying finding data in that format.

6. Unwanted Behavior Requirements

  • REQ-22: If a cost catalogue entry has no defined matcher for the active language, the tool shall report matcher:undefined for that entry rather than silently treat it as absent.
  • REQ-23: If benchmark synthesis lands on setup strategy needs-agent-input, the tool shall emit a stub repro file clearly marked as requiring agent completion, and shall not itself invent semantically arbitrary fixture values for non-primitive types.
  • REQ-24: If a benchmark run’s variance across repeated rounds exceeds the configured acceptable bound, the tool shall report confirmation status inconclusive rather than promote or silently discard the finding.
  • REQ-25: If the same underlying cost pattern would be reported by both a full-repository scan and a diff-scoped scan, the tool shall deduplicate findings by a stable ID derived from rule, location, and shape hash.

7. Complex Requirements

  • REQ-26: While shape source is standalone, when a finding’s hotness class would otherwise be reachable, the tool shall instead report unknown unless standalone extraction can itself establish the upstream loop or thread-spawn context, since standalone mode’s reduced precision cannot reliably confirm reachability on its own.
  • REQ-27: When crua verify produces a confirmed Tier-3 finding for a node that also participates in an implementation cluster with a declared law suite (per a composability checker’s optionality checks), the tool shall attach the measured performance divergence to the same finding as the law-suite result rather than reporting them separately.

8. Non-Functional Requirements

  • REQ-28: A diff-scoped crua scan (Tiers 0–2 only) shall have a 95th percentile wall-clock duration below 9.0 seconds across 20 measured runs on the versioned scan-moderate fixture (100 diff-touched source files and 200 candidate sites), after one unmeasured warm-up run, on the project’s CI Linux runner with at least 4 logical CPUs, 8 GiB RAM, and SSD-backed storage. The verification report shall record the fixture hash, Crua build profile, OS, CPU model/core count, RAM, storage class, and all 20 durations. Runs in which another repository job shares the runner are invalid and shall be repeated.
  • REQ-29: crua verify (Tier 3) is not subject to REQ-28’s bound and shall be invoked as an explicit, separately-budgeted step, never run implicitly as part of crua scan.
  • REQ-30: The cost catalogue and its conformance fixtures shall be versioned and reproducible byte-for-byte across repeated runs on unchanged input.

9. Traceability Notes

  • Cost pattern classification and taxonomy → REQ-2, REQ-3, REQ-14.
  • Tiering and hotness derivation → REQ-4, REQ-7, REQ-8, REQ-9, REQ-26.
  • Concurrency-model awareness via consumed effect-channel data → REQ-1, REQ-10, REQ-16.
  • Benchmark synthesis / verify mode → REQ-6, REQ-11, REQ-15, REQ-17, REQ-18, REQ-23, REQ-24, REQ-29.
  • Reporting discipline (never silently omit, never silently generate) → REQ-5, REQ-6, REQ-14, REQ-15, REQ-22, REQ-24.
  • Operational modes → REQ-12, REQ-13, REQ-19, REQ-20, REQ-21, REQ-28, REQ-30.
  • Cross-tool combination with a composability checker → REQ-1, REQ-10, REQ-16, REQ-26, REQ-27.

Appendix: Worked Examples

Layout finding, Tier 1 → Tier 3 (C#)

long[] counters = new long[threadCount];
Parallel.For(0, threadCount, t => {
    for (int i = 0; i < iterations; i++)
        Interlocked.Increment(ref counters[t]);
});

Tier-0 query matches “atomic write into array element inside a parallel context.” Tier-1 cross-reference shows sizeof(long) == 8 and threadCount counters packed with no padding, so up to 8 counters share a 64-byte line — Tier-1 layout finding. Hotness class reachable (inside Parallel.For) escalates severity per REQ-9. Under crua verify, setup strategy verbatim lifts the declaration directly (REQ-17); BenchmarkDotNet runs the as-found version against a [StructLayout]-padded variant, measuring roughly a 5x ratio — confirmation status confirmed.

Dispatch finding, standalone mode (Julia)

global total = 0
function accumulate!(x)
    global total += x
    return total
end

total is a non-const global with no declared type, read and written inside a function reachable from a hot loop. Without an installed composability checker, standalone extraction (shape-source: standalone) can see the untyped global but, per REQ-26, cannot itself confirm the loop-hotness context with full precision — hotness class reported as unknown rather than reachable unless the calling loop is also visible in the scanned scope.

Concurrency-model suppression (Python)

async def handle(counters, idx):
    counters[idx] += 1

Without effect-channel data, a Tier-0 query might flag this as a false-sharing candidate (array indexed inside a concurrent-looking context). Per REQ-10, if effect-channel data (consumed from an installed composability checker or derived standalone) shows this runs under Python’s single-threaded asyncio event loop rather than true OS threads, the layout/contention finding is suppressed entirely — no cache-line contention is possible here regardless of syntactic appearance.

Contention finding (Clojure)

(def counter (atom 0))
;; four threads, high frequency:
(dotimes [_ n] (future (swap! counter inc)))

High-frequency swap! from multiple threads on one atom is a contention finding: CAS-retry storms driven by write frequency, not by any logical necessity for shared mutable state. Tier-1 cross-reference notes no sharding/striping of the counter. crua verify setup strategy structural-synthesis builds a minimal repro (bare atom, N futures, fixed iteration count) since the declaration is already self-contained; criterium measures the as-found version against a striped/java.util. concurrent.atomic.LongAdder-style variant.

Harvested-fixture setup (C#, non-trivial type)

public class ShardedCounter {
    private readonly OrderContext _ctx;   // DI-injected, non-trivial ctor
    public long[] Shards;
}

OrderContext cannot be structurally synthesized (Level C). Rather than invent a fake OrderContext, crua verify scans test files for a CreateOrderContext()/BuildOrderContext() factory already used in the suite (REQ-18) and reuses it verbatim in the generated repro. If no such factory is found, setup strategy falls to needs-agent-input, and the tool emits a stub repro file with a // TODO: provide OrderContext fixture marker (REQ-23) rather than guessing.

Implementation roadmap

Status: These are active, unimplemented OpenSpec changes. They become built truth only after implementation, review, and archival.

ChangeStatusTasks complete
add-rust-cli-foundationActive proposal0/12
depend-on-genesisActive proposal0/9

Each change page includes its proposal, capability delta, design, and approval-gated tracer-bullet task plan.

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

Change: Add Rust CLI foundation

Why

Crua needs one executable contract that later analysis changes can extend without redefining command, configuration, finding, or exit semantics.

What Changes

  • Create a stable-toolchain Cargo workspace exposing a thin crua binary.
  • Reserve scan and verify without claiming analysis or benchmark execution.
  • Establish deterministic configuration precedence, shared finding types, and numeric exit categories.

Impact

  • Affected capability: cli-foundation
  • Future code: Cargo workspace, CLI/configuration boundary, shared domain types
  • Source requirements: REQ-4, REQ-5, REQ-6; contract references: REQ-11–REQ-15, REQ-21, REQ-29

Approval

Implementation SHALL NOT begin until a human approves this proposal and the normative EARS source.

Capability delta

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

ADDED Requirements

Requirement: Stable command and configuration foundation

The system SHALL expose a crua binary with discoverable scan and verify command families. It SHALL discover at most one crua.toml from the working directory through the repository root and apply configuration precedence CLI argument > CRUA_* environment variable > crua.toml > normative EARS default; an invalid higher-precedence value SHALL produce a configuration failure rather than fall through. This capability SHALL NOT claim source analysis or benchmark execution. Source references: REQ-6, REQ-11, REQ-29.

Scenario: Commands are discoverable before analysis exists

  • WHEN a user requests top-level help
  • THEN scan, verify, and configuration options are shown without reporting findings or running a benchmark

Scenario: Configuration sources conflict

  • WHEN a setting has different valid values in a CLI argument, CRUA_* environment variable, and discovered crua.toml
  • THEN the CLI value is selected

Scenario: Higher-precedence configuration is invalid

  • WHEN an invalid environment value overrides a valid file value and no CLI value is supplied
  • THEN command handling fails with exit code 2 and does not use the file value

Requirement: Stable exit categories

The system SHALL reserve numeric exit code 0 for successful command handling, 1 for policy/gate failure, and 2 for configuration or operational failure. The foundation SHALL NOT produce policy failures because gate evaluation is outside this capability. Contract references: REQ-12, REQ-13, REQ-15.

Scenario: Help succeeds

  • WHEN the user requests valid help or version information
  • THEN the process exits with code 0

Requirement: Shared finding contract

The system SHALL define a finding type requiring rule ID, file path and line, cost pattern kind, tier, hotness class, shape source, and tier evidence. Cost pattern kind, tier, hotness class, and shape source SHALL use the closed values defined by the normative EARS source. The foundation SHALL NOT create or serialize findings. Source references: REQ-2, REQ-4, REQ-5.

Scenario: A successor constructs a finding

  • WHEN a later capability constructs a finding through the shared type
  • THEN every REQ-5 field and tier evidence are required and unknown closed-vocabulary values cannot be represented

Design

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

Context

This greenfield tracer establishes only contracts needed by later capabilities.

Goals / Non-Goals

  • Goals: discoverable command families, deterministic configuration, domain-safe finding fields, and stable exit categories.
  • Non-goals: parsing source, producing findings, serializing output, applying gate policy, generating benchmarks, or invoking toolchains.

Decisions

  • Use a Cargo workspace with a thin crua binary and library-owned CLI/configuration/domain contracts.
  • Discover at most one crua.toml by walking from the working directory to the repository root; apply precedence CLI > CRUA_* environment > crua.toml > EARS defaults. Invalid values fail rather than falling through.
  • Reserve exits 0 for successful command handling, 1 for a future policy/gate failure, and 2 for configuration or operational failure. This change can exercise only 0 and 2.
  • Model closed vocabularies as Rust enums and require the REQ-5 finding fields at construction; do not add output-format serialization yet.

Risks / Trade-offs

  • Reserved contracts constrain successors; snapshots make intentional breaking changes visible.
  • Combining configuration and operational failures at exit 2 limits shell-level diagnosis; structured diagnostics can distinguish them later.

Tasks

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

Implementation is blocked until human approval of the normative EARS source and this proposal.

1. CLI Tracer

  • 1.1 RED: add failing help/version snapshots that require scan, verify, and configuration options without claiming either operation ran.
  • 1.2 GREEN: create the minimal stable-toolchain Cargo workspace and thin crua binary that satisfy the snapshots.
  • 1.3 REFACTOR: separate parsing from command transport without adding analysis, then run focused tests, workspace tests, rustfmt, and Clippy with warnings denied.

2. Configuration and Exit Tracer

  • 2.1 RED: add failing tests for CLI > CRUA_* > crua.toml > EARS defaults, nearest-file discovery, invalid-value failure, and exact exit codes 0/2.
  • 2.2 GREEN: implement only configuration loading and typed exit categories; reserve policy exit 1 without implementing gate behavior.
  • 2.3 REFACTOR: remove parsing duplication, snapshot the configuration/exit contract, and rerun workspace quality gates.

3. Finding Contract Tracer

  • 3.1 RED: add compile-fail/construction tests requiring every REQ-5 field and closed enums for cost pattern kind, tier, hotness class, and shape source.
  • 3.2 GREEN: implement the minimal shared finding types without scanners, output serialization, or policy behavior.
  • 3.3 REFACTOR: centralize validation invariants and run focused plus workspace quality gates.

4. Acceptance

  • 4.1 Run all unit, integration, documentation, and snapshot tests plus cargo fmt --check and Clippy with warnings denied.
  • 4.2 Trace tests to REQ-4/REQ-5/REQ-6 and confirm no analysis, reporting, gating, benchmark, or toolchain behavior is claimed.
  • 4.3 Run openspec validate add-rust-cli-foundation --strict and record approval and verification evidence before implementation completion.

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

Change: Depend on genesis-vibes

Why

crua is spec-stage with no src/ yet — the right time to build on genesis-vibes from day one rather than reimplement CLI/AIX/self-healing infra and port later. crua’s add-rust-cli-foundation change establishes the CLI skeleton; this change composes with it by sourcing the cross-cutting pieces from genesis-vibes (the shared crate the tool-craft playbook §8 and Appendix A.4 describe).

What Changes

  • Add genesis-vibes dependency ("0.2") to Cargo.toml.
  • Source the JSON envelope from genesis::envelope (crua’s cli-foundation “Shared finding contract” maps findings under data).
  • Source self-healing errors from genesis::suggestions (crua’s cli-foundation “Stable exit categories” gains the Suggestion footer).
  • Source the managed-block injector from genesis::managed_block so crua carries WAI/OPENSPEC/DONT blocks and participates in wai status detection (the wai-bdqw.9 signal).
  • Ship llms.txt/llm.txt via genesis-vibes::aix once stable.
  • Keep all crua domain logic (cost-pattern catalogue, hotness classes, tree-sitter front ends, benchmark generation). The genesis boundary rule protects this.

Impact

  • Affected specs: cli-foundation (MODIFIED — envelope, suggestions, managed block sourced from genesis-vibes). Composes with, does not replace, add-rust-cli-foundation.
  • Blocked by: genesis-vibes v0.2.0 published on crates.io.
  • Coordinates with crua’s EARS spec (crua-ears-spec.md) — no REQ changes there; this is CLI infrastructure, not domain behavior.

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

cli-foundation spec delta: depend on genesis

MODIFIED Requirements

Requirement: Shared finding contract

crua’s JSON finding output SHALL wrap its findings in genesis::envelope::Envelope, nesting the finding list under data, so crua’s --json shape matches the rest of the suite.

Scenario: scan emits shared envelope

  • WHEN crua scan --json is run
  • THEN the emitted JSON SHALL have top-level keys ok, envelope_version, cli_version, envelope_kind, data, warnings, hints, meta
  • AND the cost-pattern findings SHALL be nested under data.

Requirement: Stable exit categories

crua SHALL source its self-healing error footers from genesis::suggestions (the Suggestion enum: DidYouMean/WrongOrder/ContextHint/Fix), rather than implementing a local copy.

Scenario: typo suggestion from genesis

  • WHEN an unknown crua subcommand is run
  • THEN crua SHALL emit a “Did you mean …?” footer via genesis::suggestions
  • AND SHALL NOT define a local Suggestion enum.

Tasks

Status: Active OpenSpec proposal; not implemented or deployed. The source under openspec/changes/ is authoritative.

1. Dependency

  • 1.1 Add genesis = { git = "https://github.com/charly-vibes/genesis", tag = "v0.1.0" } to Cargo.toml (once add-rust-cli-foundation lands the skeleton).
  • 1.2 Verify build with envelope/suggestions/managed_block modules stable.

2. Source envelope

  • 2.1 Route --json (findings) through genesis::envelope, findings under data.
  • 2.2 Conformance: top-level keys match the shared shape.

3. Source suggestions

  • 3.1 Register crua’s command list with genesis::suggestions::SuggestionEngine.
  • 3.2 Wire the error sink to emit genesis::suggestions fix-footers.

4. Source managed_block

  • 4.1 Source injector mechanics from genesis::managed_block.
  • 4.2 Carry WAI/OPENSPEC/DONT blocks so wai status detects crua (wai-bdqw.9).

5. AIX artifacts

  • 5.1 Ship llms.txt/llm.txt via genesis::aix (hand-write minimally until stable).

Contributing

Current phase

Crua is in the planning and approval phase. Do not implement application code until the human approval gate accepts EARS 1.0.0 and all active OpenSpec proposals.

Change workflow

  1. Update the authoritative EARS document when product requirements change.
  2. Update the affected OpenSpec proposal, design, capability delta, and tasks.
  3. Run strict OpenSpec validation.
  4. Keep .beads/issues.jsonl synchronized with the approved task graph.
  5. Build the documentation site.
openspec validate --all --strict --no-interactive
python scripts/check_planning.py
python scripts/build_docs.py
mdbook build

Documentation rules

  • Do not hand-edit generated files under docs/book/.
  • Requirement IDs must remain stable and traceable.
  • Active proposal pages must not claim deployed behavior.
  • OpenSpec deltas remain under openspec/changes/ until implementation, review, and archival are complete.

GitHub Pages

Pages uses GitHub’s official artifact deployment actions. Pull requests build the site but do not deploy it. Pushes to main upload the rendered docs/book/ directory and deploy it to the protected github-pages environment. No publishing branch is created.