diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f2d73dc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# Fixtures are byte-exact test inputs; never let a checkout rewrite their line endings. +crates/**/tests/fixtures/**/*.json text eol=lf +# The CRLF fixture is a Windows checkout's file, kept as written; a later rule overrides the one above. +crates/rdm-engine/tests/fixtures/noncanonical/crlf_*.json -text +# The committed schemas are generated output compared byte for byte with the generator's. +crates/rdm-schema/schemas/*.json text eol=lf diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..0e5b6d0 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,73 @@ +name: Rust workspace + +on: + pull_request: + paths: + - "crates/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/rust.yml" + push: + branches: [main, "feat/**"] + paths: + - "crates/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/rust.yml" + workflow_dispatch: + inputs: + soak: + description: "Run the kill harness and proptest at high counts" + type: boolean + default: false + +jobs: + test: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + # Left unset on ordinary runs so the suite uses its short defaults. + - name: Soak counts + if: ${{ inputs.soak }} + shell: bash + run: | + echo "RDM_SOAK_ITERS=1000" >> "$GITHUB_ENV" + echo "PROPTEST_CASES=10000" >> "$GITHUB_ENV" + - name: Fixture line endings (CRLF probe) + if: ${{ runner.os == 'Windows' }} + shell: bash + run: git ls-files --eol ':(glob)crates/**/tests/fixtures/**/*.json' + - run: cargo test --workspace --locked --no-fail-fast + + lint: + name: lint (fmt, clippy) + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - run: cargo fmt --all --check + - run: cargo clippy --locked --workspace --all-targets -- -D warnings + + msrv: + name: msrv (1.88) + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.88 + - name: Soak counts + if: ${{ inputs.soak }} + run: | + echo "RDM_SOAK_ITERS=1000" >> "$GITHUB_ENV" + echo "PROPTEST_CASES=10000" >> "$GITHUB_ENV" + - run: cargo test --workspace --locked --no-fail-fast diff --git a/.gitignore b/.gitignore index 36e1821..7c55884 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,8 @@ __pycache__/ # macOS .DS_Store +/target + +# rdm store scratch and property-test regressions +.rdm/ +proptest-regressions/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e72b477 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,486 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix", + "windows-sys", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "unarray", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rdm-engine" +version = "0.1.0" +dependencies = [ + "fs4", + "getrandom", + "proptest", + "rdm-engine", + "rdm-schema", + "rustix", + "serde", + "serde_json", + "sha2", + "tempfile", +] + +[[package]] +name = "rdm-schema" +version = "0.1.0" +dependencies = [ + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a4f0f45 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[workspace] +resolver = "3" +members = ["crates/*"] +exclude = [ + "skills/managing-roadmaps/scripts/dirtree-rdm", + "plugins/managing-roadmaps/skills/managing-roadmaps/scripts/dirtree-rdm", +] + +[workspace.package] +edition = "2024" +rust-version = "1.88" +license = "AGPL-3.0-or-later" +repository = "https://github.com/CrackingShells/cracking-shells-playbook" diff --git a/__design__/rdm/architecture.md b/__design__/rdm/architecture.md index d73c4df..63c8d23 100644 --- a/__design__/rdm/architecture.md +++ b/__design__/rdm/architecture.md @@ -6,7 +6,13 @@ once code meets real hosts; points marked *suggestion* are left to the milestone rest stand unless implementation proves them wrong, and then this document changes together with the code. Decisions were taken with the maintainer on 2026-11-11. Amended on 2026-11-16 (A1 of the meta-roadmap): the domain model and the stored types move to a fourth crate, `rdm-schema`, owned by a -spec-first milestone M0b. +spec-first milestone M0b. M0b settled it on 2026-11-16: status meanings in +[statuses.md](statuses.md), the stored schema in [stored-schema.md](stored-schema.md) with its +[traceability.md](traceability.md), and the read model in [read-model.md](read-model.md). Where +this document and those four differ, they win. Amended on 2026-11-25 (A2 of the meta-roadmap, M1): +the store is flat and id-addressed, specified in [store.md](store.md), and the contracts M1 freezes +(ids, campaign model, `MOVES`, operations, errors, links, version chain) are in +[contracts.md](contracts.md). Where this document and those two differ, they win. ## Executive Summary @@ -15,7 +21,7 @@ spec-first milestone M0b. part of what a roadmap needs: no leaf editing, no batch, no amendment or progress writer, no graph walk. Re-planning a long roadmap is therefore hand-editing a grammar. The markdown itself serves a human review that no longer happens. -- **Proposed change.** One Rust library, `rdm-core`, owns the roadmap model, its JSON store and +- **Proposed change.** One Rust library, `rdm-engine`, owns the roadmap model, its JSON store and every graph operation. Two thin consumers sit on it: `rdm-mcp`, a stdio MCP server for agents, and `rdm-cli` (binary `rdm`) for humans. JSON is the stored format; markdown is an export. The server carries a graph view for MCP Apps hosts. The stored types and the read model live in a fourth crate, `rdm-schema`, versioned on its own. All four crates are published to crates.io. @@ -64,33 +70,33 @@ graph TD CLI[rdm-cli: binary rdm, for humans] UI[graph view: Svelte page served as a ui:// resource] end - subgraph Core [rdm-core] + subgraph Core [rdm-engine] OPS[ops: CRUD, structural edits, batch, impact] ORD[order: waves, ready set, status FSM] VAL[validate] IO[interchange: markdown export, legacy import] - ST[store: canonical JSON, lock, journal, revisions] + ST[store: canonical JSON, lock, intent record, revisions, cache] end MCP --> OPS CLI --> OPS - UI -->|app-only tool| MCP + UI -->|result _meta; app-only tool where the host has serverTools| MCP OPS --> ORD OPS --> VAL OPS --> ST IO --> ST - ST --> FS[__roadmap__/campaign/*.json] + ST --> FS[__roadmap__/campaign/nodes/*.json] ``` | Decision | Value | |:--|:--| | Graph model | Depth is ordering: siblings parallel, deeper level later. No explicit edges. | -| Stored format | JSON, one file per node, under `__roadmap__//`. Markdown is export only. | +| Stored format | JSON, one file per node, flat under `__roadmap__//nodes/`, named by id. Markdown is export only. | | Transport | stdio only. Concurrency safety comes from the filesystem. | | Mutations | Full CRUD, single or batch. Content and structure edits carry a mandatory amendment description and are logged. Status and progress go to a per-leaf history, with no description. | -| Protocol | MCP 2026-07-28 conformance only. `rmcp` pinned exactly (3.9.0 at design time, MSRV 1.88). | -| UI | MCP Apps (`io.modelcontextprotocol/ui`, spec 2026-01-26). Svelte 5, one inlined HTML file embedded in the server binary. Read-only in the first version. | +| Protocol | MCP 2026-07-28 conformance only. `rmcp` pinned exactly: `=3.10.0` with features `server`, `macros`, `transport-io` (3.9.0 at design time, MSRV 1.88). rmcp has no typed Apps API: the tool `_meta.ui`, the capability `io.modelcontextprotocol/ui` and the MIME type `text/html;profile=mcp-app` are built by hand. All three hosts tested speak 2026-07-28. | +| UI | MCP Apps (`io.modelcontextprotocol/ui`, spec 2026-01-26). Svelte 5, one inlined HTML file embedded in the server binary. Read-only in the first version. M0 proved the host split: Claude Code Desktop has no `serverTools`, so its inline page is fed once from the tool result `_meta`; VS Code Copilot offers tool calls, resource reads and a localhost stream; the Claude Code CLI renders no Apps. `structuredContent` stays a minimal summary valid against `outputSchema`, because Claude Code puts it in the model context. | | Home | A Cargo workspace in this repository under `crates/`, outside `skills/`. | -| Crates | `rdm-schema` (stored types, read-model types, JSON Schemas, format version), `rdm-core` (library), `rdm-mcp` (server), `rdm-cli` (binary `rdm`). | +| Crates | `rdm-schema` (stored types, read-model types, JSON Schemas, format version), `rdm-engine` (library), `rdm-mcp` (server), `rdm-cli` (binary `rdm`). | **The consumer rule.** `rdm-mcp` and `rdm-cli` hold no roadmap logic. Each maps its inputs to one core call and renders the result. A behaviour that exists in one consumer and not in the core is a @@ -100,53 +106,71 @@ defect. ``` __roadmap__// - _dir.json campaign root + nodes/.json one file per node (root, directories, leaves), named by its id _amendments/.json one file per amendment, append-only - .json leaf node - /_dir.json directory node - /.json - .rdm/ untracked scratch: lock, journal/, staging/ + _comments/.json one file per comment, append-only + .rdm/ untracked: lock, holder.json, tmp/, intent/, cache/ ``` -- **Names are paths.** A node's name is its path segment (`^[a-z][a-z0-9_-]*$`) and is not stored - in the file, so it cannot disagree with the filesystem. `_dir.json` cannot collide with a node. -- **Identity is separate.** Every node carries an immutable `id`. Tools accept a path or an id and - return both. References between nodes hold ids, so they survive a rename or a move. +- **Flat and id-addressed** (Eliott, 2026-11-25). A node file holds its `name` + (`^[a-z][a-z0-9_-]*$`), its `parent_id` and an `order` key among its siblings. Paths, depth and + children are derived from the `parent_id` chain on load and never stored, so depth is still the + only ordering (I1). A rename or a move rewrites one file, and no directory is ever renamed. +- **The root** is the parentless node of kind `campaign` whose `name` is the campaign slug; `open` + is given that slug. It has no `parent_id` and no `order`. +- **Ids.** A node id is `n_` and 8 characters of lower-case Crockford base32; criteria are `c_` and + steps `s_`, with 6. Callers mint them from a seeded or system RNG and the store refuses a + collision. Comments and amendments keep ULIDs, which order them. Checks and references have no + id. References between nodes hold ids, so they survive a rename or a move. Details in + [store.md](store.md) §Ids and [contracts.md](contracts.md) §Id inventory. +- **Sibling order** is a fractional key in base 62: an insert writes one file, and a rare rebalance + rewrites one parent's children. It is a position, not a dependency. +- **Merge damage is reported, not refused.** A file that cannot be read alone (unparsable, a + malformed id, a name that differs from its id, a newer format) fails `open`. Damage across files + that a git merge leaves (an orphan, a cycle, a name collision, a second root) is loaded and + reported, the nodes that do not trace back to the root are unvalidated, and writes that build on + them are refused except repairs. - **Stored:** node prose, leaf status, steps, progress, per-leaf status history. - **Derived on every read, never stored:** directory status, the node table, the mermaid graph, the progress table, waves, the ready set. Derived data cannot go stale, and a status change never writes to an ancestor. -- **One file per leaf and per amendment** keeps task branches in separate worktrees from touching +- **One file per node and per amendment** keeps task branches in separate worktrees from touching the same file, so merges do not conflict. - **Canonical form:** fixed field order, two-space indent, LF, trailing newline. Multi-line prose is stored as an array of lines, which git merges far better than one escaped string; the API accepts and returns plain strings. -- **Forward compatibility:** every file carries `schema_version`; unknown fields round-trip; a - reader refuses a newer major version with an upgrade message. JSON Schemas are generated from - the Rust types and committed; CI fails when they drift. +- **Forward compatibility:** every file carries `schema_version` (`"0.X.Y"`, `"0.1.0"` until M1 + merges to `main`). The version is read first, and a file newer than the binary, whether X or Y is + higher, is refused with `NewerFormat` before anything else is parsed (Eliott, 2026-11-25). Older + files read through a chain of format layers, each overriding only what its version changed. + Unknown fields round-trip in place, and each one is reported as a warning. JSON Schemas are + generated from the Rust types and committed; CI fails when they drift. -Schema sketch (field names *provisional*, owned by M0b, which holds them as types in `rdm-schema`): +The stored types are settled in [stored-schema.md](stored-schema.md) and held by the +`rdm-schema` crate, whose JSON Schemas are generated and checked for drift. In outline: ``` -_dir.json { schema_version, id, kind: campaign|directory, title, context, goal, - references[], preconditions[], success_gates[], gotchas[] } - -.json { schema_version, id, kind: leaf, title, status, blocked_reason?, - goal, preconditions[], success_gates[], references[], - steps[1..5], progress{branch?, notes}, history[] } - -step { id, goal, implementation_logic, deliverables[], checks[{command, expected}], - commit{type, scope, summary}, references[], requires[], done, commit_sha? } - -history { ts, from, to, actor, note?, override? } - -amendment { schema_version, id, ts, actor, description, source?, op_id?, - changes[{node_id, op, path_before?, path_after?, field?, old?, new?}], - snapshot? } +directory { schema_version, id, kind: campaign|directory, name, parent_id?, order?, title, context, + goal, references[], preconditions[Criterion], success_gates[Criterion], gotchas, notes, marks[] } +leaf { schema_version, id, kind: leaf, name, parent_id, order, title, status, status_reason?, goal, + preconditions[Criterion], success_gates[Criterion], references[], steps[1..5], + progress{branch?, commits?, notes}, history[], marks[] } +step { id, title, goal, implementation_logic, deliverables, references[], + checks[{text, expected, command?}], commit{type, scope?, breaking, summary}, + requires?, done, commit_sha?, done_at? } +Criterion { id, text, met } (enforced: see I8) +Reference { label?, title, target?, note?, node_id? } (target relative to the root, absent when node_id is set) +history { ts, from, to, actor{kind: agent|human|import, name?}, reason?, override?, op_id?, correction? } +mark { ts, actor, criterion_id, met, evidence?, reason?, correction? } (trace of every criterion mark) +comment { schema_version, id, node_id, ts, actor, text } +amendment { schema_version, id, legacy_id?, ts, actor, description, source?, op_id?, correction?, + changes[{node_id, op, item_id?, field?, old?, new?}], snapshot? } (paths derive from node_id) ``` -The sketch omits facts the legacy grammars carry (per-criterion state, step title, the breaking mark of a -commit, a reference shape, a step timestamp, a readable amendment id). M0b decides whether each is stored. +Every legacy grammar production is stored, derived or dropped with a reason in +[traceability.md](traceability.md). The read model that every consumer receives (MCP outputs, +CLI `--json`, the view) is four projections in [read-model.md](read-model.md); each leaf there +reports its `level` together with `level_source: depth`. The amendment log of a node is the set of amendment files whose `changes` name its id. A delete stores the removed subtree in `snapshot`, so it can be restored. @@ -161,11 +185,11 @@ sequenceDiagram participant A as process A participant L as campaign lock participant F as files - A->>F: read (returns rev, tree_rev) - A->>L: acquire + A->>F: read, no lock (returns rev, tree_rev) + A->>L: acquire, then recover any intent left behind A->>F: re-read, compare with expected rev alt revision matches - A->>F: stage, journal, apply, remove journal + A->>F: write intent (multi-file only), apply in order, remove intent A->>L: release else stale A->>L: release @@ -173,53 +197,84 @@ sequenceDiagram end ``` -- **Lock:** one operating-system advisory lock per campaign (`.rdm/lock`), held only for the write - window. The kernel releases it when a process dies, so there is no stale lock. A waiter retries - for a few seconds, then returns a `LOCKED` error naming the holder. -- **Atomic single-file write:** temporary file in the same directory, fsync, rename. -- **Multi-file transaction:** stage the new contents, write a journal of idempotent steps, mark it - committed, apply, remove it. The amendment file is part of the transaction. On the next lock - acquisition a committed journal is rolled forward and an uncommitted one discarded. -- **Optimistic revisions:** a read returns a content hash per node (`rev`) and per campaign - (`tree_rev`). A field edit presents `expected_rev`; a structural batch presents - `expected_tree_rev`; a status move presents the status it expects to leave. A mismatch returns an - error result with the current state. Nothing is merged automatically. -- **Retries:** a write may carry an `op_id`; replaying it returns the first result. +The algorithm and its sources are in [store.md](store.md); in outline: + +- **Readers take no lock.** Every file is replaced whole, so a reader sees the old or the new + version, never a part. +- **Lock:** one operating-system advisory lock per campaign (`.rdm/lock`, the `fs4` crate), held + only for the write window. The kernel releases it when a process dies, so there is no stale lock. + A waiter retries for 5 s, then gets `Locked`, naming the holder from the advisory + `.rdm/holder.json`. +- **Atomic single-file write** (Maildir): temporary file in `.rdm/tmp/`, fsync, rename; `link()` + for a file that must not exist yet. On Windows the rename retries on sharing violations. +- **Ordered writes** (the three Soft Updates rules): a new node before anything that points at it, + the amendment before the deletes it records, children deleted before their parent. +- **Intent record** for a multi-file operation: a redo-only record in `.rdm/intent/` holding the + whole-file after-images. Its rename is the commit point; the next writer redoes it after taking + the lock, and an unfinished one is dropped. The amendment is not the intent. +- **Durability:** plain `fsync` by default, so an acknowledged write survives a killed process; + a full flush on macOS is opt-in. +- **Optimistic revisions:** a read returns a hash per node (`rev`, over the decoded value, so + formatting never changes it), per subtree and per campaign (`tree_rev`, over the nodes only). A + field edit presents `expected_rev`, a delete `expected_subtree_rev`, a structural batch + `expected_tree_rev`. A mismatch returns `Stale` with the current state. Nothing is merged + automatically. +- **Retries:** a write may carry an `op_id`; the store keeps an index of the ids its records carry + and, under the lock, returns the first result instead of writing again. +- **Hot cache:** a long-lived server keeps the decoded campaign, checks every file's identity, + mtime and size on each read (git's racily-clean rule for edits within one tick) and writes + through. It is never the source of truth. - **Worktrees are separate copies.** A lock in one worktree does not coordinate with another. Status written on a task branch reaches the coordinator when that branch merges. The coordinator - records `inprogress` in its own tree when it dispatches a leaf. + records `ongoing` in its own tree when it dispatches a leaf. ## Graph operations - **Load and validate** a whole campaign, returning diagnostics with a stable code, a severity, a path and a JSON pointer. -- **Order.** The wave of a leaf is its depth. A leaf is ready when it is not done and every leaf of - smaller depth is done. Leaves before sibling directories follows from depth. Wave semantics are - global: a leaf also waits for shallower leaves in unrelated branches. +- **Order.** The wave of a leaf is its depth, shown as `level`. A leaf is ready when it is + `planned` and every leaf that holds it back is `done` or `cancelled`. The rule is scoped + (Eliott, 2026-11-16): an unfinished leaf holds back only the deeper leaves under its own + parent, never a leaf in an unrelated branch. Waves are a display of depth, not a readiness + fact. Details and examples in [statuses.md](statuses.md) §Ready set. - **Status FSM.** ```mermaid stateDiagram-v2 [*] --> planned - planned --> inprogress - inprogress --> done - planned --> blocked - inprogress --> blocked - blocked --> inprogress - done --> amendment: content edit - amendment --> inprogress - amendment --> done: re-verified + planned --> ongoing + planned --> paused + planned --> cancelled + ongoing --> paused + ongoing --> cancelled + ongoing --> done + paused --> planned + paused --> ongoing + paused --> cancelled + cancelled --> planned: undo, to the pre-cancel status + cancelled --> ongoing: undo + cancelled --> paused: undo + cancelled --> done: undo of a cancel made from done + done --> ongoing: reversal, with a reason + done --> paused: reversal, with a reason + done --> cancelled: reversal, with a reason ``` - `done` requires every step recorded done with its commit. Starting a leaf outside the ready set - is refused unless an override with a reason is given, and the override is recorded. A directory's - status is derived from its descendants. + The full table of moves, who may make them and their reasons is in [statuses.md](statuses.md). + `done` is the normal end state, not a lock: a reversal out of it needs a reason. Entering `paused` or `cancelled` needs a reason, and undoing + a cancel restores the status before it. Pausing or cancelling a directory applies to every + unfinished leaf under it as one operation, and a directory cancel is undone through its + `op_id`. `done` requires every step recorded done with its commit. Starting a leaf outside the + ready set is refused unless an override with a reason is given, and the override is recorded. + A directory's status is derived from its leaves. **Finished nodes:** a `done` or `cancelled` node + accepts every edit, with a non-blank reason; each is flagged as a correction and counted. Every content edit to a `planned`, `ongoing` or `paused` node carries an + amendment description. - **Primitives:** add, remove (subtree), set field, rename, move to another parent. - **Composites,** each expanding to primitives: wrap siblings in a new level, unwrap a level, split a leaf, merge leaves, promote a leaf to a directory, reorder steps, "run X after Y" (expressed as depth edits, with candidate plans ranked by nodes moved). -- **Impact analysis** on every structural edit: wave changes per node, done work reopened, progress - destroyed, in-progress leaves moved. A destructive effect needs an explicit acknowledgement. +- **Impact analysis** on every structural edit: wave changes per node, leaves made ready by a cancel, + progress destroyed, ongoing leaves moved. A destructive effect needs an explicit acknowledgement. - **Batch:** an ordered list of operations, validated one by one and as a whole, applied atomically, with a dry-run. Later operations may refer to nodes created earlier in the batch. @@ -261,7 +316,7 @@ receives the same data as text and structured content. | Flow | Sequence | |:--|:--| | Author a campaign | `init` with a nested tree, then `validate`. | -| Execute | `next` → `transition` to `inprogress` → work → `transition` recording each step's commit → `transition` to `done`. | +| Execute | `next` → `transition` to `ongoing` → work → `transition` recording each step's commit → `transition` to `done`. | | Edit a field | `get` (revision) → `update` with the new value and the amendment description. | | Re-plan | `apply` with dry-run → read the impact report → `apply` with acknowledgements. | | Read as a human | `rdm export ` or `roadmap_export`. | @@ -273,28 +328,31 @@ receives the same data as text and structured content. |:--|:--| | I1 | Depth is the only ordering. No stored field expresses a dependency between siblings. | | I2 | A consumer holds no roadmap logic; the CLI and the MCP tools give the same result on the same input. | -| I3 | No write leaves a campaign in a state `validate` rejects, including after a crash at any point. | +| I3 | A write cut at any point leaves a campaign that loads, and recovery takes it to the state before or after the write. No write adds a defect that `open` reports. | | I4 | A write based on a stale revision is refused and changes nothing. | -| I5 | Every content or structure edit produces exactly one amendment with a non-empty description. Status and progress never do. | +| I5 | Every content or structure edit produces exactly one amendment with a non-empty description. Status, progress, criterion marks and comments never do. A content edit of a finished node needs a reason and is a correction. | | I6 | Derived data is never stored. | -| I7 | A node's `id` never changes; a rename or move changes only its path. | -| I8 | A leaf is `done` only when every step is done with its commit recorded. | -| I9 | Deleting or reopening done work, or moving work in progress, needs an explicit acknowledgement. | -| I10 | The server keeps no state between calls; every call names its campaign. | +| I7 | A node's `id` never changes; a rename or move rewrites that node's file only, and its descendants' paths change because they are derived. | +| I8 | The move to `done` is allowed only when every step is done with its commit recorded and every success gate is `met`; the move to `ongoing` needs every pre-condition `met`, an override of the ready set included. Both are checked at the move, and every change of a criterion mark leaves a `mark` record. A directory is `done` only when its leaves are finished and its own gates are met. A stored `done` leaf has every step done (a leaf imported from legacy markdown has no commit SHA, and keeps its legacy count in `progress.commits`). A legacy `done` node with an unmet criterion is imported as it is, and `validate` reports it as an error to reconcile. | +| I9 | Deleting finished work, or moving ongoing work, needs an explicit acknowledgement. Reopening done work needs a reason and is counted as a correction. | +| I10 | A cached read returns what a cold read would at that moment; every call names its campaign. | | I11 | No tool requires user interaction, and no read tool writes. | -| I12 | A reader never drops a field it does not know. | +| I12 | A reader never drops a field it does not know, and reports each one as a warning. | ## Launch and distribution (*provisional*, owned by M7) - **Publication:** the four crates on crates.io, released by CI after a merge to `main` - (`release-plz`; `rdm-schema` on its own version line, the other three on one product version), beside the existing skill releases. In one workflow run: + (`rdm-schema` on its own `0.X.Y` version line, the other three on one product version; a breaking format or + read-model change forces an `rdm-schema` X bump and a compatible one at least a Y bump, as in [read-model.md](read-model.md) §Versions). Bumps come from commit types and scopes through the existing multi-semantic-release setup (`@semantic-release/commit-analyzer`, `release-config.js`): a `!` or BREAKING commit gives X, `feat` or `fix` gives Y, and the crate stays `0.x`. M7 wires the crates into that job, with a rule that keeps a breaking change at `0.x`. It runs beside the existing skill releases. In one workflow run: crates (schema, core, then server and CLI), then prebuilt binaries and checksums on the GitHub release, then the plugin pinned to that version. The plugin never names an unpublished server. - **Launch:** the plugin runs `rdm-mcp serve --require-version X.Y.Z`. A binary of another version fetches the matching prebuilt one from the release, checks its sha256, caches it per version and runs it. A consumer installs once; later plugin updates bring their own server. When the download fails, an installed binary of the same major version runs with a warning; otherwise the server - exits with the exact install command. + exits with the exact install command. (A2, 2026-11-25: M1 only refuses a newer file with + `NewerFormat`; M7 may start an installed binary that supports it, and never downloads one without + the user's consent. This paragraph is M7's to rewrite.) ## Alternatives Considered @@ -302,12 +360,12 @@ receives the same data as text and structured content. |:--|:--|:--|:--| | Graph model | Explicit edges / hybrid / **depth** | depth | The tree over-sequences; "run X after Y" is a structural edit, with its impact reported | | Transport | HTTP daemon / stdio + HTTP / **stdio** | stdio | Concurrency is the store's job; no host that needs a URL is served | -| File layout | One file per campaign / per directory / **per node** | per node | More files; no hot file, clean merges | +| File layout | One file per campaign / per directory / per node in a tree / **per node, flat and id-addressed** | flat per node | Paths are derived on load, and a merge can leave damage across files, which `open` reports; a rename or move writes one file | | Amendments | In each node / one log file / **one file per amendment** | per amendment | A node's log is a query, not a field | | Revisions | Counter / **content hash** | hash | No base to merge from, so a conflict is refused, never merged | | Lock | Lock file as existence / per file / **one OS lock per campaign** | per campaign | Writers on one campaign are serialised, for milliseconds | | Amendment scope | Every write / **content and structure** | content and structure | Status history is kept apart from the amendment log | -| Mutation policy | Additive only / **full CRUD with guards on done work** | full CRUD | History lives in amendments, not in undeletable nodes | +| Mutation policy | Additive only / **full CRUD, finished nodes edited with a reason** | full CRUD | History lives in amendments, not in undeletable nodes | | Consumers | MCP only / **MCP and CLI over one core** | both | A second surface to keep thin | | UI | None / server-rendered image / **Svelte page as an MCP App** | Svelte | A Node build in CI and a committed artefact | | Registry | PyPI wheels / npm / **crates.io** | crates.io | No pinned-run launcher, hence the self-provisioning launch | @@ -317,21 +375,24 @@ receives the same data as text and structured content. | Risk | Mitigation | |:--|:--| -| A host does not speak 2026-07-28 | M0 tests the real hosts first; the transport stays isolated in `rdm-mcp` | -| rmcp API churn, untyped Apps support, a wrong extension id in its documentation | Exact pin; M0 fixes the calls; one module owns the Apps metadata | -| Lost or torn writes under concurrency | Lock, journal, revisions; a multi-process test with kill injection on three operating systems | -| Directory renames fail on Windows while a handle is open | Retry with backoff; a Windows test job | +| A host does not speak 2026-07-28 | Settled by M0: Desktop, VS Code and the CLI all connect to a server that refuses other versions. The transport stays isolated in `rdm-mcp` | +| A host cannot take page-to-server calls, resource reads or a stream (Claude Code Desktop) | Feed the inline page once from the result `_meta`; use polling or streaming only where the host advertises `serverTools` or the stream domain; a standalone viewer for large or live views (M6 decides) | +| rmcp API churn, untyped Apps support, a wrong extension id in its documentation | Exact pin `=3.10.0`; M0 fixed the calls; one module owns the Apps metadata | +| Lost or torn writes under concurrency | Lock, ordered writes, intent record, revisions; every write prefix tested to load and recover; a multi-process test with kill injection on three operating systems | +| A file rename fails on Windows while another program holds the target open | Retry on sharing violations with backoff; the `replace_while_target_open` guard on a Windows runner | +| A git merge leaves a cycle, an orphan or a name collision without a conflict | `open` reports each defect with its file and rule; writes on the damaged part are refused except repairs | | A consumer grows logic | I2 as a test: the same input through both consumers | -| The graph view grows past a small bundle | Size budget in CI; a hand-written bridge if the Apps client library is heavy | +| The graph view grows past a small bundle | M0 measured 279 to 286 KB, about 234 KB of it ext-apps with zod. Size budget in CI; a hand-written bridge if the Apps client library is heavy | +| A binary is overwritten in place on macOS | The kernel kills it with SIGKILL. Install to a new inode (`rm` then `cp`) | | A restructure silently reorders work | Impact analysis and acknowledgements (I9) | | The launch cannot reach the release | Same-major fallback; a loud failure with the install command | -| The allow-rule string for a hyphenated plugin name is guessed wrong | Read from a real session in M0, never hard-coded from a guess | +| The allow-rule string for a hyphenated plugin name is guessed wrong | Read in M0 from a real session: `mcp____` for a project server, `mcp__plugin____` for a plugin, with hyphens kept. A same-named project server wins over the plugin | | Legacy roadmaps import wrongly | The eight campaigns of this repository as golden fixtures, one of them invalid by design | ## Deliberately open -Decided by the milestone that owns it: field names, status meanings, the read model and the format version (M0b); the id minting and the journal format (M1); the -exact operation set and its error codes (M2); whether a cross-worktree claim hint is worth having +Decided by the milestone that owns it: the exact graph operation set above the store primitives +and its error codes (M2); whether a cross-worktree claim hint is worth having (M2); markdown layout of the export and what the importer does with invalid input (M3); tool names, count and output budgets (M4); CLI verbs and output style (M5); layout and refresh of the view (M6); the launch, the release order and binary targets (M7); what the skill says and which diff --git a/__design__/rdm/contracts.md b/__design__/rdm/contracts.md new file mode 100644 index 0000000..b73cebd --- /dev/null +++ b/__design__/rdm/contracts.md @@ -0,0 +1,840 @@ +# rdm — Contracts + +The types and data layouts that M1 freezes, in the crate `rdm-schema`. The Rust types are the +contract: JSON and the JSON Schemas are derived from them, and "schema" here means the data +structures broadly (stored nodes, the campaign model, operation signatures), not only the schema +files. Rulings of Eliott, 2026-11-25, are in the +[A2 gap analysis](../../__reports__/m1-core-foundation/00-gap_analysis_v0.md) and are not reopened +here. + +Scope: the stored types, the campaign model, `MOVES` as data, and the store operation request, +result and error types. Tool input and output are M4's. M2 adds semantics (the FSM, impact +analysis) on top of these shapes and never changes them. The disk layout, the id string format, +the order-key format, `rev` hashing, the lock, write order, recovery and the cache are in +[store.md](store.md). This document names them and does not restate them. + +The settled meaning of every stored field stays in [stored-schema.md](stored-schema.md); this +document adds the Rust names, what each type derives instead of storing, and who relies on it. + +Three consumers read it: the **codec** (`rdm-engine`, serialises the types), the **store** +(`rdm-engine`, persists them), and **M2/M4** (graph semantics, tools). Each type below says which +one relies on a rule. + +## Id inventory + +**Rule.** A record gets an id when it is pointed at from outside **and** its natural key can +change. The natural key is whatever else would name it: a path segment, a position, a title, a +label. A record that nothing points at, or whose only key never changes, gets none. Every id costs +a minting rule, a uniqueness rule and a link to declare, so an id with no pointer is excess. + +| Record | Pointed at from outside | Natural key | Verdict | Reason | +|:--|:--|:--|:--|:--| +| Node (campaign root, directory, leaf) | `parent_id`, `Reference.node_id`, `Comment.node_id`, `Change.node_id`, `Amendment.snapshot` keys | `name` among siblings, and the chain of parents: both change on a rename or a move | **id** (`NodeId`) | I7: a rename or a move changes no id | +| Criterion | `Mark.criterion_id`, `Change.item_id` | position and text: a reorder or an edit changes both | **id** (`CriterionId`) | A mark must survive a reorder | +| Step | `Change.item_id` | position (shown as the step number) and title | **id** (`StepId`) | A recorded step correction names the step | +| Check | none: a step owns its checks, and no record marks, runs or cites one | position | **no id** | An edit of a check is recorded at the array level: a `set` of `/checks` on the step, with the whole old and new array | +| Reference | none: `Reference.node_id` points *out*, nothing points *in*. Prose cites `label` (`R01`), and a text cite is not a declared link | `label`, unique within its array | **no id** | As for a check: a `set` of `/references` on the owner (the node, or the step through its `item_id`) | +| Comment | none stored | none: a file named by its id, ordered by it | **id** (`CommentId`, a ULID) | Identity is the file name and the order. Not by the rule: there is no natural key to protect | +| Amendment | none stored (the display id is derived from it) | none | **id** (`AmendmentId`, a ULID) | As a comment | +| History entry | none: entries are append-only, and `op_id` groups them without naming one | position, never used | **no id** | `op_id` is a shared retry key, not the id of an entry | +| Mark | none: append-only | position, never used | **no id** | As a history entry | +| Change | none | position in `changes` | **no id** | Part of its amendment | +| `Commit`, `Progress`, `Actor` | none | none | **no id** | Single objects reached through their owner | +| `op_id` | the records an operation wrote | the caller | **`OpId`**, caller-supplied | A retry key, not minted by the store, never a record id | + +**Decided (Eliott, 2026-11-25), proposal confirmed.** Nodes, criteria and steps keep ids. Checks and references +do not, and are recorded at the array level in a change. This **overturns** the current +[stored-schema.md](stored-schema.md) (M0b), which gave ids to checks and references, and the +current code, whose `Check` and `Reference` carry an `id`. The consequence is that `Change.item_id` +names a criterion or a step only. A reference or a check that later gains a pointer (a check result +record, say) gets an id then, as a compatible addition (see `Version chain`). + +### Id types + +Three newtypes over `String`, one validation, written once in `rdm-schema`. + +| Rust type | Names | Kind prefix | +|:--|:--|:--| +| `NodeId` | a node, whatever its `kind`: promoting a leaf to a directory keeps its id (I7), so the id does not encode the kind | the node prefix | +| `CriterionId` | a criterion, in `preconditions` or `success_gates` | the criterion prefix | +| `StepId` | a step | the step prefix | + +```rust +pub struct NodeId(String); // likewise CriterionId, StepId (one macro) +impl NodeId { + pub fn parse(s: &str) -> Result; // the only constructor from a string + pub fn as_str(&self) -> &str; +} +// FromStr, TryFrom, Display; Serialize as a JSON string; +// Deserialize through `parse`; Ord, Hash. JsonSchema: a string with the id pattern. +pub enum IdError { Empty, WrongPrefix { expected: &'static str }, BadChar, BadLength } +pub enum ItemId { Criterion(CriterionId), Step(StepId) } // JSON form: the bare string +``` + +- **Validation.** Each type accepts exactly a string in the format of [store.md](store.md) §Ids + with the kind prefix of this type. The grammar is implemented once, in `rdm-schema`, from that + section, and the generated JSON Schema pattern comes from the same constant. A deserialised id + is always valid, so a function that takes a `NodeId` never re-checks. +- **`ItemId`** is the one place the prefix carries meaning: it reads as a `CriterionId` or a + `StepId` by its prefix, so the prefixes of the two must differ. +- **`CommentId` and `AmendmentId`** are ULIDs, not store.md ids: the read model orders comments and + amendments by id, oldest first, which only a time-ordered id gives. Both validate as 26 + characters of Crockford base32. +- **`OpId`** is one line of 1 to 128 characters with no control character. The caller chooses it; + the store never mints one. +- **Never reused.** An id, once minted, is not given to another record, including after a delete + (`stored-schema.md`, `Stable identity`). Sub-item ids (`CriterionId`, `StepId`) are unique within + their node file. `NodeId`s are unique within the campaign. + +## Node fields + +A node is one file, `nodes/.json` (layout: store.md). Three fields say where it sits; the +rest of the file is as in stored-schema.md. + +| Field | Rust type | On | Stored | Meaning and consumer | +|:--|:--|:--|:--|:--| +| `id` | `NodeId` | every node | yes | Identity. Immutable (I7) | +| `name` | `Name` | every node | yes | The path segment, `^[a-z][a-z0-9_-]*$`. Unique among the children of one parent. **For the campaign root it is the campaign slug**, which `Campaign::open` is given and checks (`Campaign model`); the root's name is not part of any path | +| `parent_id` | `NodeId` | every node but the campaign root | yes | The directory this node is in. Always a `Directory` node | +| `order` | `OrderKey` | every node but the campaign root | yes | Position among siblings. An opaque newtype: its format and how a key is made between two others are store.md's (§Order key). Compared as given, never parsed. Ties break by `id` | +| `kind` | `DirectoryKind` or `LeafKind` | every node | yes | `campaign` exactly when `parent_id` is absent, so the type of the root is checked against its place | + +On `Directory`, `parent_id` and `order` are `Option`: they are absent for the campaign root and for +it only (`root_shape` rule below). `name` is required on every node, the root included. On `Leaf` +all three are required, so a leaf cannot be a root by construction. The root's path is `""`. The +campaign slug is the anchor of validation: the root is the parentless node that carries it. + +```rust +pub struct Name(String); // parse(&str) -> Result +pub struct OrderKey(String); // opaque; format in store.md §Order key +pub enum Node { Directory(Directory), Leaf(Leaf) } // discriminated by `kind` in the file +impl Node { + pub fn id(&self) -> &NodeId; + pub fn name(&self) -> &Name; + pub fn parent_id(&self) -> Option<&NodeId>; + pub fn order(&self) -> Option<&OrderKey>; + pub fn decode(raw: serde_json::Value) -> Result; // by `kind`; see Version chain +} +``` + +`Node` is not a serde-tagged enum: `Directory.kind` already holds `campaign` or `directory`, so +`Node::decode` reads `kind` and picks `Leaf` (`leaf`) or `Directory` (`campaign`, `directory`). Any +other value is `Invalid` with the rule `kind`. + +**Derived from these fields, never stored (I6)**, by the campaign model (below): the children of a +node, its depth (the ordering rule I1), its path, its siblings' order. Nothing in a file holds a +child list or a path. + +**Rules the validator checks per node** (each is an `Invalid` rule code, see `Errors`): + +| Rule code | Statement | +|:--|:--| +| `root_shape` | `parent_id` and `order` are both absent exactly when `kind` is `campaign` | +| `name_format` | `name` matches the `Name` pattern | +| `malformed_id` | an id field does not parse as its type | + +Rules that need the whole campaign (one root, the parent exists and is a directory, no cycle, +sibling names unique) are in `Campaign model`. + +**What changes against the current code.** `Directory` and `Leaf` gain the three fields, in the +canonical order `schema_version`, `id`, `kind`, `name`, `parent_id`, `order`, then the rest of the existing +order. +`Check` and `Reference` lose `id`. Every `id`, `node_id`, `criterion_id` and `item_id` field changes +from `String` to its newtype. `Leaf.kind`, `Check.expected` and the other enums are unchanged. +`stored-schema.md` is edited to match. + +## Campaign model + +The shape M2 consumes instead of designing it: the nodes of one campaign as a table by id, with +everything about the tree derived from `parent_id`, `name` and `order`. A **parent-pointer tree** +(adjacency by parent id), not a nested value: a rename or a move edits one record and rebuilds no +subtree. + +```rust +// In rdm-schema, pure: no I/O. The engine's `Store` (held by the public `CachedCampaign` handle) reads and decodes the files and calls `open`. +pub struct Campaign { /* nodes; root: Option; children index; depth memo; + unvalidated: set of NodeId; diagnostics: Vec */ } +#[must_use = "an opened campaign carries diagnostics; read them"] +pub struct Opened { pub campaign: Campaign, pub diagnostics: Vec } +pub struct Diagnostic { pub file: String, pub rule: Rule, pub detail: String } // always a warning + +impl Campaign { + /// The only constructor. `expected_slug` is the campaign's name as its caller knows it. + pub fn open(nodes: impl IntoIterator, expected_slug: &Name) -> Result; + pub fn diagnostics(&self) -> &[Diagnostic]; // the same list, kept on the value + pub fn is_validated(&self, id: &NodeId) -> bool; + pub fn root(&self) -> Option<&NodeId>; // None: no validated root + pub fn get(&self, id: &NodeId) -> Option<&Node>; + pub fn nodes(&self) -> impl Iterator; // by NodeId, validated or not + pub fn parent(&self, id: &NodeId) -> Option<&NodeId>; // None for a root or an orphan + pub fn children(&self, id: &NodeId) -> &[NodeId]; // sorted by (order, id); empty for a leaf + pub fn depth(&self, id: &NodeId) -> Option; // I1; None for an unvalidated node + pub fn path(&self, id: &NodeId) -> Option; // "" for the root; None if unvalidated + pub fn resolve(&self, path: &str) -> Option<&NodeId>; // inverse of `path`, validated nodes only + pub fn subtree(&self, id: &NodeId) -> impl Iterator; // pre-order, `id` first + pub fn insert(&mut self, node: Node); // incremental: derived indexes and the + pub fn remove_subtree(&mut self, id: &NodeId) -> Vec; // validated set equal a rebuild +} +``` + +| Derived | Definition | Never stored because | Relied on by | +|:--|:--|:--|:--| +| `children(id)` | the nodes whose `parent_id` is `id`, sorted by `(order, id)` | a child list in the parent would be a second copy that a move must edit in two files | M2 (waves, ready set), the read model | +| `depth(id)` | the number of **directories between the campaign root and the node**: a node directly under the root has depth 0, so this is `level` in `read-model.md`. The ordering rule I1 is this number, computed from the `parent_id` chain | it would go stale on every move of an ancestor | M2 (ready set), the read model | +| `path(id)` | the `name`s from the root's child down to the node, joined by `/`; `""` for the root | it would go stale on every rename or move above it, and a stored path is the value a flat layout exists to avoid | M3 (export), the read model, M4 (a tool takes a path or an id) | + +### Open: refuse a bad file, report a bad tree + +`open` separates two kinds of fault (Eliott, 2026-11-25). + +**Per-file faults refuse `open`** with a `StoreError`, because the file itself is not sound. Any +one of these in any file fails the whole open, naming the file: + +| Fault | Error | +|:--|:--| +| the text is not JSON, or not an object of the expected type | `Invalid`, rule `parse` | +| `schema_version` missing or malformed | `Invalid`, rule `schema_version` | +| the file is newer than the binary | `NewerFormat` (raised first, `Version chain`) | +| the campaign root is not a directory (missing, or a file): nothing is read and nothing is created | `Io`, file `.` | +| an id field does not parse as its type | `Invalid`, rule `malformed_id` | +| `nodes/.json` holds another `id` | `Invalid`, rule `file_id_mismatch` | +| a node breaks a rule of its own record: `kind`, `root_shape`, `name_format`, the stored-schema rules, `sub_item_id_unique`, `reference_target_derived` | `Invalid`, that rule | + +**Cross-file damage is loaded and reported.** A git merge of two branches can leave files that are +each sound and wrong together. They are loaded, and each defect is **one `Diagnostic`** naming the +file or files and the rule. What cannot be done is validating the node against the tree. + +| Rule code | Defect | Which nodes become unvalidated | +|:--|:--|:--| +| `parent_missing` | a `parent_id` names no node (an orphan) | the node and its subtree | +| `parent_not_directory` | a `parent_id` names a leaf | the node and its subtree | +| `cycle` | following `parent_id` never reaches a parentless node | every node on the cycle and every node below it | +| `root_count` | no parentless node carries the expected slug, or more than one does (one diagnostic, filed under the smallest of their ids, naming the others) | every node: there is no validated root, and none of the slug-named nodes is chosen as one | +| `root_name_mismatch` | a parentless node carries another name than the slug | that node and its subtree | +| `name_collision` | two children of one parent share a `name` | the colliding siblings and their subtrees (a path through them is ambiguous) | +| `duplicate_id` | two node records hold one `NodeId` (reachable through `open` over nodes; through the store a copied file is already `file_id_mismatch`) | both records | + +**The anchor.** `expected_slug` is the campaign's slug as the caller knows it (the campaign +directory's name, as M4 and the CLI resolve it). The **root** is the one parentless node whose +`name` equals the slug. Every node reachable from the root by `parent_id` is **validated**: it has +a depth and a path. Every other node is **loaded but unvalidated**: an orphan, a node on a cycle, a +second parentless node, a node under a root whose name does not match, a node below a name +collision. When no parentless node carries the slug, `open` still succeeds: `root()` is `None`, +**every node is unvalidated**, and the diagnostics say so (`root_count`, and `root_name_mismatch` +for each parentless node of another name). A caller then sees the campaign, damaged, instead of +nothing, and cannot mistake it for a sound one. + +**How "loud" is enforced.** The diagnostics are part of the return value: `open` returns +`Opened { campaign, diagnostics }`, a `#[must_use]` struct whose fields must be taken apart to reach +the campaign, so dropping it unread is a compiler warning (the workspace builds with `-D warnings`). +The same list stays on the `Campaign` (`diagnostics()`), so every later read can surface it again: +M4's read tools carry it in their output, and the CLI prints it to standard error on every command. +`depth` and `path` return `Option`, so a consumer cannot compute with a position that was never +validated. The cache reopens with the same slug on revalidation (store.md §Cache), so a repaired +campaign loses its warnings and a damaged one keeps them. + +**Writes and unvalidated nodes.** + +| Write | On an unvalidated node | Rule code | +|:--|:--|:--| +| create under it, replace its content | **refused**: the write would build on a position no one verified | `unvalidated_node` | +| comment on it | **allowed**: a comment is an append-only record that depends on the node's id, not its position; it is how a reader annotates the damage | | +| relocate it into the validated tree (new `parent_id` validated) | **allowed**: a repair | | +| relocate or rename a colliding sibling | **allowed**: a repair | | +| delete it (its subtree) | **allowed**: a repair. A node on a cycle is deleted with every node below it, the whole cycle included | | +| any other relocate of it (a rename of an orphan, say) | **allowed**: it builds nothing on the unverified position, and the rule below still holds | | + +A write never adds a defect: after it the set of diagnostics is a subset of the set before. A +batch is checked as a whole under this rule, so a repair that fixes one defect and a write that +opens another are refused. + +**The one exception, the root family.** While the campaign has **no validated root**, `root_count` +and `root_name_mismatch` may change form in a repair: renaming one of two slug-named roots away +turns one `root_count` into a `root_name_mismatch` on the renamed node, and that write is allowed. +While a validated root exists, the two codes follow the rule above like every other code, so a write +that takes the validated root away (a rename of a sound root, a second slug-named root) is refused. +In particular **a sound root cannot be renamed**: renaming the campaign is renaming its directory +first, after which the root is unsound (`root_name_mismatch`) and its rename is the repair. + +`open` builds the children index in one pass, then computes depth by walking from the root down +with a memo and a visiting mark (a depth-first search with three colours), so a cycle is found, +not followed, and the whole open is O(n). `insert` and `remove_subtree` update the same indexes in +O(depth) and O(subtree); a rebuild is the oracle for them (`reverse_index_equals_brute_force_scan` +also compares children, depth and path with a rebuild). + +Siblings are parallel (I1): `order` only fixes how they are listed, never when they run, and no +stored field expresses a dependency between them. `Campaign` holds nodes only. Comments and +amendments are separate files, read by the cache (store.md §Cache) and joined to a node by id. + +### Diagnostics + +One type for every warning, from three producers: + +| Producer | Rules | When | +|:--|:--|:--| +| a layer's `decode_*` | `unknown_key` | per unknown key kept without interpretation: `file` is the file, `detail` is the key's JSON pointer (`/steps/0/x_note`). The decode returns it with the value (`Decoded`, `Version chain`) | +| `Campaign::open` | the cross-file rules above | per defect | +| `Campaign::open`, from the link table | `dangling_reference`, `references_empty` | per reference whose `node_id` names no node; per leaf with no reference | + +`open` aggregates the decode diagnostics of every file with its own and returns them sorted by +`(file, rule, detail)`, so two opens of the same files give the same list. A defect that spans +several files (a cycle, a collision, a second root) names in `file` the file of the smallest id +involved, and lists the other ids in `detail`. + +**Settled while building the store (coordinator, 2026-11-25).** The root has depth 0. A change +that adds, removes or moves a sub-item names in `field` the array's pointer (`/steps`). A mark +names its criterion by id, so `Mark.criterion` is a declared link: a write that leaves a mark on a +missing criterion is refused like a dangling reference, and `open` reports one. `id_changed` +applies only when a replace payload carries an id of its own that differs from the target. A diagnostic is a +warning by type; an error is a `StoreError`. + +## Moves + +`MOVES` is the move table of [statuses.md](statuses.md) as data. Its consumers are M2 (the FSM: +which move is allowed, who may make it, what it needs, what it does to the ready set) and M4 and the +CLI (the refusal text). The document is the oracle: the test `move_table_matches_statuses_doc` +parses it and compares it with `MOVES`, so a change to the table of the document fails the build +until `MOVES` follows. + +**The table it encodes** is the first table after the heading `## Transitions` in +`__design__/rdm/statuses.md`, whose header row is exactly + +`| From | To | Allowed | Who | Reason | Precondition | Ready set |` + +Cells hold no `|`, so the test splits a row on it. Rows are the 25 ordered pairs of the five +statuses, each once. A column added, renamed or reordered in the document fails the test by +design: the header is part of the contract. + +```rust +pub struct Move { + pub from: Status, pub to: Status, + pub allowed: bool, + pub who: Option, + pub reason: ReasonRule, + pub precondition: &'static str, + pub ready_set: &'static [ReadyEffect], +} +pub enum Who { Agent, Human, Both } +pub enum ReasonRule { Required, OnlyForOverride, NotRequired } +pub enum ReadyEffect { Enter, Leave, Release, Hold } +pub static MOVES: [Move; 25]; // row-major: index = from * 5 + to +pub fn lookup(from: Status, to: Status) -> &'static Move; // total: all 25 pairs exist +``` + +| Column | Cell | Field | Parse rule | +|:--|:--|:--|:--| +| From, To | `` `planned` `` … `` `done` `` | `from`, `to` | the backticked word, as the serde name of `Status` | +| Allowed | `allowed` or `refused` | `allowed` | `allowed` is `true` | +| Who | `agent`, `human`, `both`, or empty | `who` | empty is `None`; the document uses `both` on every allowed row (no move is human-only) | +| Reason | `required`, `only for an override`, `none`, or empty | `reason` | `required` is `Required`; `only for an override` is `OnlyForOverride`; `none` and empty are `NotRequired` | +| Precondition | prose | `precondition` | **verbatim**, trimmed, backticks kept. On a refused row it is the refusal message; M2 owns the logic that checks an allowed row's precondition, keyed on `(from, to)` | +| Ready set | `none`, or uppercase tokens then optional prose | `ready_set` | the leading tokens `^[A-Z]+(, [A-Z]+)*` as `Enter`, `Leave`, `Release`, `Hold`; `none` is empty. The prose after them ("if nothing shallower holds it back", the `HOLD:` explanation) restates the ready-set definition and is not encoded | + +At the date of this document 16 rows are allowed and 9 refused; the test reads the document, not +these numbers. The test also requires, for every row, `allowed` exactly when `who` is `Some`, and +that `MOVES[i]` is the pair its index says. Verbatim preconditions mean M2 re-reads a move whenever +its prose changes, which is the point. `statuses.md` is not edited. + +The test reads the document at `../../__design__/rdm/statuses.md` from the crate directory. The +file is not part of a published crate, so the test is a development-time guard only. + +## Links + +Eliott, 2026-11-25: every key-value link between records is declared, so an update or a delete +reaches every reference automatically, and a value derivable from an id is never stored. A **link** +is a field of one record that holds the id of another. `LINKS` is the list of all of them, and the +reverse index is derived from it on load. + +```rust +pub struct Link { + pub owner: Owner, // the file kind that holds the field + pub pointer: &'static str, // JSON pointer; `*` is any array index, `{key}` is a map key + pub target: Target, + pub scope: Scope, + pub on_delete: OnDelete, +} +pub enum Owner { Directory, Leaf, Comment, Amendment } +pub enum Target { Node, Criterion, Step, Item } // `Item`: a criterion or a step (`ItemId`) +pub enum Scope { Campaign, OwnerFile, ChangeNode } +pub enum OnDelete { Cascade, Report, Keep } +pub static LINKS: [Link; 11]; +``` + +| # | Owner | Pointer | Target | Scope | On delete of the target | +|:--|:--|:--|:--|:--|:--| +| 1 | `Directory` | `/parent_id` | node | campaign | `Cascade` | +| 2 | `Leaf` | `/parent_id` | node | campaign | `Cascade` | +| 3 | `Directory` | `/references/*/node_id` | node | campaign | `Report` | +| 4 | `Leaf` | `/references/*/node_id` | node | campaign | `Report` | +| 5 | `Leaf` | `/steps/*/references/*/node_id` | node | campaign | `Report` | +| 6 | `Directory` | `/marks/*/criterion_id` | criterion | owner file | `Keep` | +| 7 | `Leaf` | `/marks/*/criterion_id` | criterion | owner file | `Keep` | +| 8 | `Comment` | `/node_id` | node | campaign | `Keep` | +| 9 | `Amendment` | `/changes/*/node_id` | node | campaign | `Keep` | +| 10 | `Amendment` | `/changes/*/item_id` | criterion or step | the node of that change | `Keep` | +| 11 | `Amendment` | `/snapshot/{key}` | node | campaign | `Keep` | + +The `id` field of each record is its identity, not a link, and is not listed. Targets in the +**campaign** scope are nodes anywhere. Criterion and step ids are unique within a node file only +(`Id types`), so a link to one resolves inside a file (`OwnerFile`) or inside the node a change +names (`ChangeNode`), and is not a key of the reverse index. + +**What a delete does to a referenced node.** A subtree delete never rewrites a record outside the +subtree. Per class: + +| `OnDelete` | Meaning | Rows | Reason | +|:--|:--|:--|:--| +| `Cascade` | the referrer is inside the subtree and goes with it | `parent_id` | a child of a deleted node is by definition in the subtree, so a `parent_id` to a deleted node cannot survive outside it | +| `Report` | the referrer stays untouched, and the delete **reports** it to the caller (`Deleted.referrers`, `Operations`); M2's impact analysis decides what to do with it (I9) | `Reference.node_id` | a delete is **not refused** by a reference: a document pointer is not corruption, and refusing would make a documented node undeletable. It is **not rewritten** either: clearing the pointer is a content edit of another node, so it needs its own amendment (I5) and changes that node's `rev` under another writer, and a delete would then write an unbounded set of unrelated files. The reference keeps its `title`, and a reader shows it as dangling (warning `dangling_reference`, never an error, so I3 holds) | +| `Keep` | the referrer is history and is never edited | comments, amendments, marks | append-only records (I5): a comment or a change that names a deleted node resolves through the `snapshot` of the amendment that removed it. A mark that names a removed criterion resolves through the `old` of the `remove` change that removed it | + +**Writes check what they introduce.** A write that sets a `Campaign`-scope link, or changes it, +must point at an existing node, else `Invalid` (rule `dangling_id`) or, for a comment, `NotFound`. +A link may dangle only by a later delete of its target. + +**Historical copies are not links.** The values below hold ids inside opaque JSON and are copies of +the past, not references: the values under `/snapshot/*`, and `old` and `new` of a change (a node +`move` holds `{"parent_id", "order"}` there). They are excluded from `LINKS`, from the reverse +index, and from the scan that tests it. Nothing reads them as live; a restore reads them through +the version chain of the time they were written. + +### Reverse index + +Derived from `LINKS` on load, never stored (I6), and kept in step by write-through (store.md +§Cache). It answers "who points at this node", for the delete report and for M2's impact analysis. + +```rust +pub enum RecordRef { Node(NodeId), Comment(CommentId), Amendment(AmendmentId) } +pub struct Referrer { pub link: usize, pub from: RecordRef, pub at: String } // `at`: the concrete JSON pointer +pub struct ReverseIndex { /* BTreeMap> */ } +impl ReverseIndex { + pub fn build(c: &Campaign, comments: &[Comment], amendments: &[Amendment]) -> ReverseIndex; + pub fn referrers(&self, target: &NodeId) -> &[Referrer]; // every class, ordered by (from, at) + pub fn replace_record(&mut self, from: RecordRef, record: Option<&Record>); // None: the record is gone +} +``` + +`build` walks each record once and follows every `LINKS` row whose owner matches, so it is +O(records × links). `replace_record` drops the old entries of one record and adds its new ones, so +a write touches the index in proportion to the record, not the campaign. The `children` index of +the campaign model is the `parent_id` slice of the same data, built in the same pass. + +The oracle is independent of `LINKS`: for each record, a **brute-force scan** serialises it and +finds every string equal to a campaign node id outside the identity field and the historical +copies above. Both must give the same referrers. A new id field that is not in `LINKS` shows as a +difference, and `links_cover_every_id_field` catches it earlier: it reads the generated JSON Schema +of every record, collects each property whose schema is an id newtype (`NodeId`, `CriterionId`, +`StepId`, `ItemId`) other than `id`, and requires the set to equal the pointers of `LINKS`. The +`{key}` row 11 is a map key, which a property walk does not see, and is checked by its own +assertion in the same guard: a `snapshot` key that is not a `NodeId` is refused. + +**Reference.target is derived, not stored, when `node_id` is set** (`stored-schema.md`, +`Reference`). A record holding both is `Invalid` (rule `reference_target_derived`). The derived +value is the path of the node (`Campaign model`), relative to the campaign root. + +## Operations + +One request type and one result type per store primitive. These are the signatures M2 composes +and M4 wraps as tool inputs (tool envelopes, names and output budgets are M4's). The types live in +`rdm-schema` and derive `Serialize`, `Deserialize` and `JsonSchema`, so M4 builds its input schemas +from them. The trait that implements them lives in `rdm-engine`, because `rdm-schema` holds no I/O. + +**The split of work.** The store is persistence, structural validity, the revision check (I4), +the amendment record (I5), atomicity and replay. It does **not** decide whether a status move is +legal, whether a finished node needs a reason, or what an operation means for the ready set: M2 +computes the new node values and calls the store. A caller that states a rule the store does not +check (the FSM) cannot get it from the store; a rule the store checks (a shape rule, a stale +revision) cannot be skipped by a caller. + +```rust +pub struct Rev(String); // one node: hash of its canonical encoding. Format: store.md §Revisions +pub struct SubtreeRev(String); // a node and every descendant; defined in store.md §Revisions, as tree_rev over the subtree +pub struct TreeRev(String); // the campaign. Consumers compare for equality, never parse + +pub struct Request { pub header: Header, pub op: T } +pub struct Header { + pub op_id: Option, // the retry key; see `op_id replay` + pub actor: Actor, // stamped on the amendment or comment the operation writes + pub note: Option, // the amendment's words; see `The amendment rule` +} +pub struct EditNote { pub description: String, pub source: Option, pub correction: bool } + +pub enum Position { First, Last, Before(NodeId), After(NodeId) } // a sibling, resolved to an OrderKey by the store + +pub struct CreateOp { pub node: Node, pub position: Option } +pub struct ReplaceOp { pub expected_rev: Option, pub node: Node } +pub struct RelocateOp { pub id: NodeId, pub expected_rev: Option, + pub parent_id: Option, pub name: Option, pub position: Option } +pub struct DeleteOp { pub id: NodeId, pub expected_subtree_rev: Option } +pub struct CommentOp { pub node_id: NodeId, pub text: Lines } +pub struct BatchOp { pub expected_tree_rev: Option, pub ops: Vec, pub dry_run: bool } +pub enum Op { Create(CreateOp), Replace(ReplaceOp), Relocate(RelocateOp), Delete(DeleteOp), Comment(CommentOp) } + +pub struct Written { pub id: NodeId, pub rev: Rev } +pub struct Deleted { pub removed: Vec, pub referrers: Vec } // pre-order; `Report` links only +pub struct Commented { pub id: CommentId } +pub enum OpResult { Written(Written), Deleted(Deleted), Commented(Commented) } +pub struct Receipt { + pub result: R, + pub amendment: Option, // the one amendment the operation wrote, if any + pub tree_rev: TreeRev, // after the write + pub replayed: bool, // true: nothing was written, the first outcome is returned +} +``` + +**`expected_rev` is `Option` only for a batch.** Outside a batch it is required (a `None` is +`Invalid`, rule `expected_rev_required`). Inside a batch, `None` is allowed solely for a node the +same batch created earlier, which has no revision yet. The same holds for `expected_subtree_rev`. + +| Primitive | Request, result | What it does | Refused (`Invalid` rule) | +|:--|:--|:--|:--| +| create | `Request` → `Receipt` | writes a new node file. The ids in `node` (its own, its criteria and its steps) are minted **by the caller, outside the lock**, from the engine's minter (store.md §Ids), so a batch can name a node it creates, an importer can build a campaign, and a replay returns the same ids. The store checks uniqueness **under the lock** and refuses a collision (`duplicate_id`); the caller re-mints. `node.order` is **not read**: the store sets it from `position`. `parent_id` is `None` only for the campaign root, which is created into an empty campaign (`position` is then `None`) | `duplicate_id`, `parent_missing`, `parent_not_directory`, `name_collision`, `root_count`, `root_name_mismatch` (the root's `name` is not the campaign slug), `unvalidated_node` (the parent is unvalidated), any shape or stored-schema rule, `position_not_sibling`, `note_required` | +| replace | `Request` → `Receipt` | replaces one node file with `node` if its current `rev` equals `expected_rev` (I4). It cannot change `id`, `name`, `parent_id` or `order`. `kind` may change (promoting a leaf to a directory keeps the id, I7) | `id_changed`, `use_relocate`, `note_required`, `empty_edit`, `leaf_has_children`, `unvalidated_node`, any shape or stored-schema rule | +| relocate | `Request` → `Receipt` | **rename or move**: one primitive that changes `name`, `parent_id` and `order` of one node. A field left `None` is kept; a new `parent_id` with no `position` means `Last`. At least one of the three is given. It writes **one node file** and one amendment, and renames no directory (I7). Children follow because they point at the id. On the root only `name` may change: that is the repair for `root_name_mismatch` after a campaign is renamed, and the caller then opens with the new slug. A new `parent_id` or `order` on the root is `root_delete_or_move` | `nothing_to_do`, `parent_missing`, `parent_not_directory`, `cycle` (the new parent is in the node's own subtree), `name_collision`, `position_not_sibling`, `root_delete_or_move`, `note_required` | +| delete | `Request` → `Receipt` | removes the node and every descendant if the `SubtreeRev` matches. Writes one amendment whose `snapshot` holds the removed nodes. Reports the `Report`-class referrers outside the subtree (`Links`); rewrites nothing outside it | `root_delete_or_move`, `note_required` | +| comment | `Request` → `Receipt` | writes one comment file. It has no `expected_rev`: it is append-only and never conflicts, and a comment never changes a `rev` (`stored-schema.md`) | `NotFound` for a missing node; `note_forbidden` when `header.note` is set | +| batch | `Request` → `Receipt>` | applies `ops` in order as **one transaction**. Each op is checked against the state the earlier ops produced, then the whole result is checked once (shape rules, I3). All or nothing: a failed op leaves nothing written. `dry_run` runs every check and writes nothing, for M2's impact report. The batch writes **one amendment** carrying every change of its ops | the first failing op, as `InBatch { index, source }`; `expected_tree_rev` stale is `Stale` | + +A single-op request behaves as a batch of one; the write algorithm for each primitive is the row of +the same name in store.md §Write order. A batch has no nested batch. + +### The amendment rule (I5) + +The store enforces the half of I5 that is mechanical: no content change goes unrecorded. M2 decides +when a state edit also carries a note. + +Let the **diff** of a replace be the changes between the old and the new node, computed by one pure +function in `rdm-schema` (`diff(&Node, &Node) -> Vec`), not by the caller. It reports +`criteria` and `steps` by id (`add`, `remove`, `move`, `set` with `item_id`), every other array as +one `set` of the whole array, and every other field as a `set` at its pointer. It leaves out +`/schema_version`, `/history`, `/marks`, `/status` and `/status_reason`: those are state moves, +recorded by the history and mark entries themselves. A diff entry is **state** when its pointer is +under `/progress`, or is a criterion's `/met`, or a step's `/done`, `/commit_sha` or `/done_at` +(`statuses.md`, `Finished nodes`); every other entry is **content**. + +| `header.note` | Diff | Result | +|:--|:--|:--| +| absent | no content entry | applied, **no amendment** (a status move, a mark, a step recorded done) | +| absent | a content entry | `Invalid`, rule `note_required` | +| present | at least one entry | applied, **one amendment**: `description`, `source`, `correction` from the note, `actor` and `op_id` from the header, `changes` = the whole diff (state entries included: a correction of a finished node's progress is recorded) | +| present | none | `Invalid`, rule `empty_edit` (no amendment with nothing in it) | + +Create, relocate and delete are structure edits: the note is required, and their `changes` are +`add`, `move` or `rename`, and `remove` as `stored-schema.md` (`Change`) defines. A comment forbids a +note. A note's `description` is non-blank and, when `correction` is true, is the reason. + +### `op_id` replay + +**The store owns it, not M2.** A retried write must be checked and applied inside one critical +section: the check "has this `op_id` been applied" and the write are one step under the writer lock +(store.md §Lock), and only the store holds the lock and the records. M2 sits above the lock and +could only check and then write, which two processes retrying the same `op_id` race through. + +How it works, with no state beyond the records: + +- Every write that is not rev-guarded leaves a record that carries the `op_id`: an amendment + (create, relocate, delete, a noted replace) or a comment. A status move carries it in the + `History.op_id` that M2 sets; a directory pause or cancel writes one entry per leaf with the + same `op_id`, which is how the store recognises the whole batch (it was atomic). +- Under the lock, before applying, the store looks the `op_id` up in an **op index** (built on load + with the reverse index, kept in step by write-through: store.md §Cache). If any record carries it, + the store writes nothing and returns `Receipt { replayed: true, .. }` with the result rebuilt from + those records (created ids from the amendment's `add` changes, `removed` from its `remove` + changes, the comment id) and the *current* `tree_rev`. +- A write that carries no `op_id` is never replayed. + +**Limits, stated.** (1) An edit that writes no `op_id`-bearing record (a progress edit, a mark, a +step recorded done) is not replayed, but it is rev-guarded: a retry after success meets a changed +`rev` and returns `Stale`, and the caller re-reads. (2) The store holds no fingerprint of the +request, so it cannot detect every reuse of an `op_id` for a *different* request. An `op_id` is unique +per logical operation, by the caller's contract. Where the records cannot rebuild the result the +request asks for (the node a create or relocate names is not among the amendment's changes, a +delete's subtree root is not among its `remove`s, a batch names more comments than carry the +`op_id`, the records are of another kind than the request), the store never fabricates one: it +refuses with `Invalid`, rule `op_id_reused`, and writes nothing. (3) Replay lasts as long as the records do. +Choosing the records as the ledger over a separate store of operations keeps one source of truth +and adds no file to any write order; the price is limit (1), which `expected_rev` already covers. + +M2 keeps what only it can: choosing the `op_id` of a composite, setting it on every history entry +the composite writes, and finding the leaves of a directory `uncancel` through it. + +## Errors + +One error type for every store operation and load. M4 maps its variants to tool errors, the CLI to +exit codes; nothing maps a message string. + +```rust +#[non_exhaustive] +pub enum StoreError { + Stale { current: Current }, + Locked { holder: Option }, + NewerFormat { found: Version, supported: Version, file: String }, + Invalid { file: String, rule: Rule, detail: String }, + NotFound { target: RecordRef }, + Io { file: String, message: String }, + InBatch { index: usize, source: Box }, +} +pub enum Current { // what the presented revision should have been + Node { id: NodeId, rev: Rev }, // a node that no longer exists is NotFound, not Stale + Subtree { id: NodeId, rev: SubtreeRev }, + Tree { tree_rev: TreeRev }, +} +pub struct LockHolder { pub pid: u32, pub host: String, pub since: Ts } // the record of store.md §Lock; advisory +impl StoreError { + pub fn root(&self) -> &StoreError; // unwraps `InBatch` + pub fn code(&self) -> &'static str; // of the root: STALE, LOCKED, NEWER_FORMAT, INVALID, NOT_FOUND, IO +} +``` + +| Variant | Raised when | Writes happened | Consumer's move | +|:--|:--|:--|:--| +| `Stale { current }` | a presented `expected_rev`, `expected_subtree_rev` or `expected_tree_rev` is not the current one (I4). `current` holds the one that should have been presented | none | re-read, reapply the intent | +| `Locked { holder }` | the writer lock was not taken within the wait of store.md §Lock. `holder` is the advisory record, `None` if it is absent or unreadable | none | retry later | +| `NewerFormat { found, supported, file }` | a file's `schema_version` is not readable by this binary (`Version chain`). Raised before anything else of the file is parsed, by a load or a write that must read it | none | upgrade; M7 may do it for the user | +| `Invalid { file, rule, detail }` | a file or a request breaks a rule. `file` is the path relative to the campaign root (`nodes/.json`), or `` (`rdm_schema::error::REQUEST_FILE`) when the fault is in the request. `rule` is the code below | none | fix the input, or repair the file by hand | +| `NotFound { target }` | a node a request names does not exist (an unknown `node_id` of a comment, an unknown `id` to replace, relocate or delete). Checked before any presented revision, so a node another writer removed is `NotFound`, never `Stale` | none | re-read | +| `Io { file, message }` | the operating system refused a read or a write | maybe a recoverable prefix (store.md §Intent and recovery) | retry or report | +| `InBatch { index, source }` | one op of a batch failed. `source` is any of the above | none: a batch is atomic | as `source` | + +**`#[non_exhaustive]` policy.** A public enum is `#[non_exhaustive]` when a consumer outside its +crate must survive it growing: the errors and diagnostics (`StoreError`, `Rule`, `Current`, +`IdError`, `NameError`, `KeyError`, `MintError`, `LockError`) and the result and effect kinds +that report what an operation did (`OpResult`, `Pending`, `Durability`). It is not on an enum whose +closed set is the stored or wire contract (`Status`, `ActorKind`, `Node`, `Op`, `Position`, +`RecordRef`, `IntentEffect`, the `LINKS` and `moves` tables, the read-model projections), nor on +the test-support `Effect` log: a new case there is a format version or a new `Fs` operation, and the +exhaustive match that stops compiling is the point. A new enum states its side when it is added. + +`Rule` is `#[non_exhaustive]`, each variant with a stable snake-case code. +M2 may add codes without changing existing ones. A warning (`unknown_key`, `dangling_reference`, +`references_empty`, and the cross-file rules of `Campaign model`) is a `Diagnostic`, not a `StoreError`. + +| Rule code | Statement | Defined in | +|:--|:--|:--| +| `parse` | the file is not JSON, or not an object of the expected type | codec | +| `schema_version` | `schema_version` is missing, not a string, or not `N.N.N` | `Version chain` | +| `unknown_format` | no layer reads this version though it is not newer (older than the first layer) | `Version chain` | +| `not_in_version` | a layer reports `NotInVersion` for a behaviour the file needs | `Version chain` | +| `kind` | `kind` is not `leaf`, `directory` or `campaign` | `Node fields` | +| `malformed_id` | an id field does not parse as its type | `Id types` | +| `root_shape`, `name_format` | see `Node fields` | `Node fields` | +| `unknown_key` | a key the decoder keeps without interpreting (a warning) | `Campaign model`, `Diagnostics` | +| `unvalidated_node` | a write builds on a node that does not trace back to the root | `Campaign model` | +| `file_id_mismatch`, `sub_item_id_unique` | per-file: refuse `open` | `Campaign model` | +| `duplicate_id`, `root_count`, `root_name_mismatch`, `parent_missing`, `parent_not_directory`, `cycle`, `name_collision` | cross-file: reported by `open`, and refused as an `Invalid` when a write would introduce one | `Campaign model` | +| `dangling_id`, `reference_target_derived` | see `Links` | `Links` | +| `goal_line`, `criteria_required`, `steps_range`, `status_steps`, `status_reason`, `step_state`, `mark_target`, `correction_reason` | the rules of `stored-schema.md` (`Directory`, `Leaf`, `Step`, `Mark`, `History`), one code each, in the order they are listed there | `stored-schema.md` | +| `expected_rev_required`, `note_required`, `note_forbidden`, `empty_edit`, `id_changed`, `use_relocate`, `leaf_has_children`, `nothing_to_do`, `position_not_sibling`, `root_delete_or_move`, `op_id_reused` | request rules | `Operations` | + +**Stale, replay and the lock.** `Locked` is the only error a caller retries unchanged. `Stale` is +never retried unchanged: the intent is reapplied on the fresh state. A replayed write returns +`Ok`, never `Stale`. + +## Version chain + +Eliott, 2026-11-25: each format version is a layer that overrides only what changed; behaviour a +version lacks defaults to "not in this version"; a field removed later is overridden back to that +default; an older file falls through to the layer that reads it; a file newer than the binary is +refused. The pattern is a **chain of responsibility** whose handlers are upcasters (as in event +sourcing): a layer reads the files of its own version into the *current* in-memory types, so the +rest of the code knows one model. + +```rust +pub struct NotInVersion { pub behaviour: &'static str } // the caller names the file and its version +pub type Behaviour = Result; +pub struct Decoded { pub value: T, pub diagnostics: Vec } // one `unknown_key` per key kept + +pub trait FormatLayer: Sync { + /// The format line this layer reads: (major, minor). A patch bump (Y) is compatible and has no layer. + fn line(&self) -> (u16, u16); + /// The layer this one overrides. `&Nothing` under the first layer. + fn base(&self) -> &dyn FormatLayer; + // Each behaviour defaults to the base layer's. A layer overrides only the ones that changed. + // The outer Result says whether the version has the behaviour; the inner one whether this file decodes. + fn decode_node(&self, file: &str, raw: serde_json::Value) -> Behaviour, StoreError>> { self.base().decode_node(file, raw) } + fn decode_comment(&self, file: &str, raw: serde_json::Value) -> Behaviour, StoreError>> { self.base().decode_comment(file, raw) } + fn decode_amendment(&self, file: &str, raw: serde_json::Value) -> Behaviour, StoreError>> { self.base().decode_amendment(file, raw) } +} +pub struct Nothing; // the root of the chain: every behaviour is Err(NotInVersion) +pub static CHAIN: &[&dyn FormatLayer]; // oldest first; one entry today +pub fn is_newer(found: Version, supported: Version) -> bool; // the whole triple, compared field by field +pub fn layer_for(found: Version) -> Option<&'static dyn FormatLayer>; // the newest layer whose line <= found's +``` + +- **`NotInVersion`.** `Nothing` implements every behaviour as `Err(NotInVersion)`, so a behaviour no + layer defines is absent by default. A layer **removes** a behaviour by overriding it back to + `Err(NotInVersion)`: that stops the lookup before it reaches an older layer that still has it. + A caller turns `NotInVersion` into `Invalid` with the rule `not_in_version`, naming the file + and its version in the detail (`Nothing` has no version of its own to report). No behaviour is + absent today, so no code path reaches it yet. +- **A layer is a struct holding `base`.** It overrides a behaviour by implementing the method, and + inherits every other by not mentioning it. The layer of the current format (`0.1`) decodes with + the serde of the types of this document, so its decoders are one line each. The decoded value is + always the current type, with every unknown key kept in `extra` (I12) and reported as one + `unknown_key` diagnostic in the returned `Decoded` (the decode produces it, `open` aggregates + it). Old data is *upgraded on read*, never converted in place. +- **There is one encoder, not one per layer.** Writing always serialises the current types. A + layer cannot write, so no version can be written that is not the current one. + +### Reading order + +The version is read first. Every file read, a node, a comment or an amendment, goes through the +same steps, in this order: + +1. Parse the bytes **once** into a `serde_json::Value` and read **only** `schema_version` from it. + No typed value is built, no id is validated and no shape rule runs; the same value is handed + to the layer in step 5, so the file is never parsed twice. The text must be valid JSON and its + top level an object; otherwise `Invalid` (rule `parse`). A missing or non-string stamp is + `Invalid` (rule `schema_version`). +2. `parse_version` the stamp (strict, as today). A malformed one is `Invalid` (rule `schema_version`). +3. If `is_newer(found, FORMAT_VERSION)`, return `NewerFormat { found, supported: FORMAT_VERSION, file }` + **and stop**. Nothing of the file is parsed past the stamp. A load that meets such a file fails + as a whole (a per-file fault, `Campaign model`); the error names the file. +4. Otherwise pick `layer_for(found)`. If there is none (older than the first layer), `Invalid` + (rule `unknown_format`). +5. Call the layer's `decode_*` on the value. An older version falls through to its own layer + here, not through the current one, and the layer's inherited behaviours come from its `base`. + +**Every newer file is refused, a higher Y included** (Eliott, 2026-11-25). He is not convinced a +patch change will only ever add optional fields, and an older binary that misread one would break +the rule that old code never misreads a field. So `is_newer` compares the whole triple, and `0.1.1` +is refused by a `0.1.0` binary. This **overrules** the earlier reading of the `Format version` +table, which read a higher Y; stored-schema.md is edited to match. Unknown keys still survive in +place (I12), but only in a file the binary can read at all; each one is reported +(`unknown_key`). + +`is_newer` replaces `is_readable`, which is removed. **One rule serves stored files and the read +model** (Eliott, 2026-11-25): a consumer refuses a projection whose `read_model_version` is newer than +its own, a higher Y included, and reads an older one (`read-model.md`, `Versions`, decision 10). An +older stored file goes to its layer, or `unknown_format` (step 4). Making the refusal transparent is M7's (A2, ruling 5, and the answer recorded +for M7). + +### Write-version rule + +**An edit rewrites the files it touches in the current version, and no others.** A write encodes +the whole file with the current types and stamps `FORMAT_VERSION`: the store sets +`schema_version` on the value before it calls `encode`, which is a pure serialiser and stamps +nothing. A file the operation does not +touch keeps its version; **a read never writes** (readers need no coordination). So one campaign may +hold files of different versions, and of different patch levels, and that is legal. + +Consequences, accepted: after a new binary edits a node, an older binary refuses the campaign on +that file with `NewerFormat`, which is the refusal doing its job, and now whether the bump was X or +Y. Rewriting on touch (not keeping the old stamp) is the only choice that needs no per-layer +encoder, and it stops an old shape from outliving the code that reads it. A stamp never +understates its content, since a binary cannot read, hence cannot rewrite, a file newer than it. + +### `FORMAT_VERSION` + +**It stays `0.1.0`, redefined, and is frozen when M1 merges to `main`** (decided, Eliott, 2026-11-25). Nothing is stored yet: the importer is M3, the store is built after this +document, and the only `0.1.0` files that exist are the crate's own hand-written fixtures, in a +shape this document replaces (the flat node fields, no ids on checks and references, no `Change` +paths). There is no old file to read, so no layer for the old shape, and the campaign rule +"fixtures come only from real producers" forbids writing one. `0.1.0` is therefore **redefined** +by this document, and the chain starts with one layer, `0.1`. The fixtures are rewritten, not read. + +**From now on**, with the freeze at the merge of the M1 campaign into `main` (until then a change +edits layer `0.1` in place and amends this document): + +| Change to a stored type | Bump | Chain | +|:--|:--|:--| +| a field removed, renamed, given another meaning, or made required; a record kind removed | X (`0.X.y`) | a **new layer**, with `base` the previous one; `CHAIN` gains an entry; the older layer stays | +| a new optional field, a new enum value, a new record kind in a new directory: additive in meaning | Y (`0.x.Y`) | none: the same layer reads it. **Older binaries refuse it too** (`NewerFormat`); the bump is a promise about meaning, not about compatibility | +| a field added with a default for old files | Y if optional, else X | a layer only if the default needs code | + +A bump changes, in one commit: `FORMAT_VERSION`, the types, the committed JSON Schemas (re-blessed +and reviewed), `stored-schema.md`, and, for X, the layer. The commit type and scope decide the +crate version (`stored-schema.md`, `Release`; wiring is M7's). Nothing checks "bumped when the +schema changed" automatically: the schema drift guard shows the change in the diff, and a reviewer +decides X or Y. + +## Invariants and guards + +Every invariant of this document, with its final guard. The names are those of the campaign +README, of [store.md](store.md) for what it owns, or **new** (marked †, to be added to the README's +guard list by the coordinator). Several rows share one guard when a distinct failure each row +turns red is a parameter row of it (the guards below say which). "Not tested" is followed by the +reason. + +| # | Invariant | Guarded by | +|:--|:--|:--| +| C1 | An id field holds a string of the format of store.md §Ids with its type's kind prefix; a malformed one is refused at deserialisation | `malformed_ids_are_refused` | +| C2 | `NodeId`s are unique in the campaign; `CriterionId`s and `StepId`s are unique within their node file | `open_names_invalid_campaigns` (rows: a sub-item duplicate is refused; a cross-file `duplicate_id` is reported) | +| C3 | Checks and references have no id; `Change.item_id` names a criterion or a step | `committed_schemas_match_the_types` (the generated schema has no such field) | +| C4 | A node holds `name`, `parent_id` and `order`; the root shape rule holds | `open_names_invalid_campaigns` (row: per-file faults are refused) | +| C5 | Per-file faults refuse `open`; each cross-file defect is reported, naming file and rule, and the sound files load; nodes off the root are unvalidated | `open_names_invalid_campaigns` (rows: per-file faults are refused; each cross-file defect is reported naming file and rule, and the sound files load; no parentless node with the slug leaves every node unvalidated) | +| C6 | Children, depth and path are derived from the `parent_id` chain and never stored; the incremental indexes equal a rebuild | `reverse_index_equals_brute_force_scan` (the proptest also compares children, depth and path with a rebuild) | +| C7 | A move or rename writes one node file and one amendment, and changes no id (I7) | `move_writes_one_file_and_keeps_ids` | +| C8 | `MOVES` equals the move table of `statuses.md` | `move_table_matches_statuses_doc` | +| C9 | `LINKS` lists every id field of every record | `links_cover_every_id_field` | +| C10 | The reverse index equals a brute-force scan, after any operation sequence | `reverse_index_equals_brute_force_scan` | +| C11 | A delete rewrites nothing outside the subtree, and reports every `Report` referrer | `delete_reports_referrers_and_touches_only_the_subtree` † | +| C12 | No stored field holds a value derivable from an id: a `Reference` with both `node_id` and `target` is refused | `open_names_invalid_campaigns` (row: an editor adds `target` beside `node_id`) | +| C13 | The committed JSON Schemas equal those generated from the types, request and result types included | `committed_schemas_match_the_types` | +| C14 | Every object keeps the keys it does not know, in place, at every level (I12), and each one yields exactly one `unknown_key` diagnostic with its JSON path | `unknown_keys_survive_in_place_at_every_level` (extended: also asserts one diagnostic per unknown key, with its path) | +| C15 | A canonical file round-trips byte for byte; valid non-canonical input reads and re-encodes canonically | `canonical_files_round_trip_byte_for_byte` (the codec guard of the campaign) | +| C16 | A file newer than the binary, whether the higher part is X or Y, is refused with `NewerFormat { found, supported }` before anything else of it is parsed | `newer_file_refused_before_parsing` (rows: a higher X; a higher Y; each a hand-written canonical file of the shape a newer layer would write, with a body that would not parse as the current type) | +| C17 | An older version reads through its own layer; a removed behaviour is `NotInVersion` | Not tested: one layer exists, and the README defers chain fall-through "until a second real layer exists" | +| C18 | An edit rewrites only the files it touches, in the current version; a read writes nothing | Not tested for the version stamp: with one layer every write is the current version, so the test would restate the encoder (as C17). "A read writes nothing" is `cached_read_equals_cold_read` of store.md (the files do not change) | +| C19 | A stale `expected_rev`, `expected_subtree_rev` or `expected_tree_rev` changes nothing (I4) | `stale_replace_changes_nothing` | +| C20 | No content change goes unrecorded; an amendment is written only with a note, and never empty (I5) | `requests_breaking_a_rule_are_refused` † (rows: `note_required`, `empty_edit`); the success path is exercised by every store write with a note | +| C21 | A replace cannot change `id`, `name`, `parent_id` or `order` | `requests_breaking_a_rule_are_refused` † (row: a replace that changes `parent_id` or `name` is refused with `use_relocate`) | +| C22 | A batch is atomic: a failed op leaves nothing written; a dry run writes nothing | `every_write_prefix_loads_and_recovers_to_pre_or_post` (store.md) for the crash side; `failed_batch_writes_nothing` † for the logical side | +| C23 | A retried `op_id` returns the first outcome and writes nothing | `replayed_op_id_writes_nothing` † | +| C24 | A held lock yields `Locked { holder }` and is released when the holder dies | `lock_survives_holder_kill` (store.md) | +| C25 | Every `StoreError` variant has a stable `code()`, and `root()` unwraps `InBatch` | Not tested: a total `match` the compiler checks; M4 tests its own mapping | +| C26 | `FORMAT_VERSION` is `0.1.0` and its string round-trips | `version_constants_and_strings` (existing) | +| C27 | A bump of X or Y accompanies a change to a stored type | Not tested: needs the git history of the schemas; a reviewer reads the drift diff | +| C28 | A write builds on no unvalidated node, except to repair; a write never adds a defect | `requests_breaking_a_rule_are_refused` † (rows: create under, and replace of, an unvalidated node are refused with `unvalidated_node`; relocate into the tree, rename of a colliding sibling or of the root, and delete are accepted) | +| C29 | The diagnostics of `open` cannot be dropped silently: `Opened` is `#[must_use]`, `depth` and `path` are `Option` | Not tested: a compiler check (`-D warnings` holds `unused_must_use`), and the types are the guard | + +### Guards by leaf + +What each implementing leaf owes, with the bug that turns each red (the leaf report records it +seen red). + +| Leaf | Guard | Red when | +|:--|:--|:--| +| `schema_contracts` | `malformed_ids_are_refused` | an id newtype accepts a wrong prefix, a wrong length or a char outside the alphabet | +| | `committed_schemas_match_the_types` | a field is added to a type and the schema is not re-blessed | +| | `move_table_matches_statuses_doc` | one cell of `statuses.md` changes and `MOVES` does not | +| | `links_cover_every_id_field` | an id field is added to a record and not to `LINKS` | +| | `version_constants_and_strings` | `FORMAT_VERSION` or its string changes unnoticed | +| `codec_and_versions` | `newer_file_refused_before_parsing` | the newer-file check runs after the typed decode (a newer body then fails as `parse`), or it ignores the patch | +| | `unknown_keys_survive_in_place_at_every_level` | a level drops a key, moves it, or reports none or two diagnostics | +| | `canonical_files_round_trip_byte_for_byte` | the encoder reorders keys or changes the indent | +| `campaign_store` | `stale_replace_changes_nothing` | the revision is compared before the lock is taken | +| | `move_writes_one_file_and_keeps_ids` | a move rewrites a child or a parent, or re-mints an id | +| | `requests_breaking_a_rule_are_refused` | a content change passes without a note, an empty note writes an amendment, a replace moves a node, or a write builds on an unvalidated node | +| | `replayed_op_id_writes_nothing` | the `op_id` lookup runs before the lock, or after the write | +| | `failed_batch_writes_nothing` | a batch applies its ops one by one with no whole-batch check | +| | `delete_reports_referrers_and_touches_only_the_subtree` | a delete rewrites a `Reference.node_id` outside the subtree, or omits a referrer from the report | +| | `open_names_invalid_campaigns` | an orphan, a cycle, a name collision or a second root is silently loaded as sound; or a per-file fault is only reported; or a node off the root gets a path | +| | `reverse_index_equals_brute_force_scan` | `replace_record` forgets to drop a record's old entries, or `remove_subtree` leaves a stale child | + +The coordinator assigned the leaves (2026-11-25): `open` and the reverse index are guarded through +the store, where a real merge produces the damage. store.md §Invariants and guards lists the store's +own guards (revisions, minting, order keys, crash prefixes, lock, cache). + +### Existing tests that change on purpose + +`schema_contracts` changes these first, so each failure is a decision and not a surprise: + +| Test (`crates/rdm-schema/tests/`) | Why its behaviour changes | +|:--|:--| +| `stored.rs`: `ids_are_unique_and_changes_name_items_by_id` | checks and references no longer have ids, so the collected id set shrinks to criteria and steps; the ids are typed; the fixture change `item_id` names a step | +| `stored.rs`: `reordering_criteria_leaves_marks_valid` | it builds a `Criterion` with the literal id `cg_new`, which is now malformed; it mints a valid `CriterionId` | +| `stored.rs`: `unknown_keys_keep_their_order_in_the_output_string`, `unknown_field_keeps_its_place_after_known_ones` | their inline JSON uses ids such as `"c"` and `"n"`, now malformed | +| `stored.rs`: `amendment_fixture_round_trips_and_keeps_null_new` | the fixture's `remove` and `move` changes carry `path_before` and `path_after`, which `Change` no longer has | +| `stored.rs`: `unknown_fields_survive_at_every_level` | gains the assertion of exactly one `unknown_key` diagnostic per injected key, with its path | +| `stored.rs`: `leaf_fixture_round_trips`, `directory_fixture_round_trips`, `comment_fixture_round_trips` | every fixture is rewritten with valid ids, the node fields, no check or reference ids, and no `Reference.target` beside a `node_id`; the injection counts are recomputed | +| `stored.rs`: `marks_point_by_criterion_id_and_corrections_are_flagged` | reads fixture ids that become typed | +| `schemas.rs`: `committed_schemas_match_the_types` | the generated schemas change on purpose and are re-blessed under review; request and result schemas join the list | +| `read.rs` and `fixtures/{outline,node,ready,ready_scoped,amendments}.json` | read-model id fields (`id`, `leaf_ids`, `held_by`, the holder keys) become the newtypes (`parent` is a path in `read-model.md` and stays a string), and `rev` and `tree_rev` become `Rev` and `TreeRev`; their fixtures hold valid ids. The read model stays a projection, outside `LINKS` | +| `Reference.target` fixtures (`stored_leaf.json`, `node.json`) | `target` is relative to the campaign root, not the node file (`../../../__design__/…` becomes `../../__design__/…` from `__roadmap__//`); a reference with `node_id` has none | + +`parse_version_is_strict` does not change. `reader_refuses_per_the_read_model_rule` changes on +purpose, before the code: `is_readable` is removed, and the guard becomes +`only_newer_versions_are_refused`, over `is_newer`, with rows a higher major, a higher X and a higher +Y refused, and the same and lower versions accepted (bug caught: the patch ignored, or an older +version refused). The stored-file path is guarded besides by `newer_file_refused_before_parsing`. diff --git a/__design__/rdm/read-model.md b/__design__/rdm/read-model.md new file mode 100644 index 0000000..e9fbfa0 --- /dev/null +++ b/__design__/rdm/read-model.md @@ -0,0 +1,565 @@ +# rdm — Read model + +The shape every consumer receives. Four projections over the stored files. Each one has a field +list, the consumer that uses it, and a worked example computed by hand from +`__roadmap__/roadmap-mcp-rework/`. + +The stored facts are in [stored-schema.md](stored-schema.md). The meaning of each status, the +ready rule and the derivation of a directory's status are in [statuses.md](statuses.md). The +legacy campaign is read through its legacy mapping first: `inprogress` is `ongoing`, `planned` is +`planned`. + +## Projections + +| Projection | Section | Consumers | Answers | +|:--|:--|:--|:--| +| Campaign outline with waves | `Campaign outline` | M4 `roadmap_view` and the app-only tool behind it (R01 `ui_snapshot`), M5 `--json`, M6 view | What is in the campaign, in what status, in which wave | +| Node detail | `Node detail` | M4 `roadmap_get`, M5 `--json`, M6 detail pane | Everything about one node | +| Ready set | `Ready set` | M4 `roadmap_next`, M5 `--json` | What may start now, and what holds the rest back | +| Amendment log | `Amendment log` | M4 `roadmap_amendments`, M5 `--json`, M6 timeline | What was changed, by whom, why | + +M4 owns the final tool names; R01's table is a suggestion. The campaign list and the diagnostics +of `validate` are not projections of this document. M2 owns the diagnostics. + +**Every projection field has a source.** The `Source` column of each field table names a stored +field (path in `stored-schema.md`) or a derivation. A field with neither is a defect. + +**Envelope.** Every projection starts with these fields. + +| Field | Type | Source | +|:--|:--|:--| +| `read_model_version` | `string` | The constant `READ_MODEL_VERSION` | +| `format_version` | `string` | The highest `schema_version` among the files read | +| `projection` | `"outline"`, `"node"`, `"ready"` or `"amendments"` | Fixed by the projection | +| `campaign` | `{id, path, title}` | `id` and `title` from the campaign root node. `path` is the argument of the call | +| `tree_rev` | `string` | Opaque. Computed by M1 over the campaign | + +**Revisions.** `rev` (one node) and `tree_rev` (the campaign) are opaque strings. A consumer +compares them for equality and sends them back as `expected_rev` and `expected_tree_rev`. It +never parses them. They are defined in [store.md](store.md) §Revisions. A comment never changes a `rev` +(`stored-schema.md`, `Comment`). + +**Order.** Siblings carry a stored `order` key (contracts.md §Node fields), a position for +presentation that never expresses a dependency (I1). Every list below orders nodes by `level`, then +siblings by `(order, id)`, as `Campaign::children` does. Lists of amendments and comments order by ULID, oldest first. + +**Types in `rdm-schema`.** The crate leaf holds these as types: + +| Type | Holds | +|:--|:--| +| `Envelope` | The envelope fields, flattened into each view | +| `OutlineView`, `NodeView`, `ReadyView`, `AmendmentsView` | The four projections | +| `LevelSource` | Enum, one value today: `depth` | +| `StatusCounts` | `{planned, ongoing, paused, cancelled, done}`, five integers, all always present | +| `Holder` | `{path, title, status, status_reason?}`, the value of a `holders` map | +| `WaveView`, `OutlineNode`, `StepView`, `AmendmentEntry`, `ChangeView` | Parts named in the field tables | + +**Examples.** Ids are stand-ins (`n_m1`): M1 mints the real ones. Revisions are stand-ins +(`rev-m1`). A string ending in `[cut]` or a string element `"[cut: …]"` marks text left out. It is +not part of the shape. + +## Campaign outline + +One call returns the whole tree, its waves, and the flags a graph needs. + +| Field | Type | Source | +|:--|:--|:--| +| `root` | `OutlineNode` of kind `directory`, `is_campaign: true` | The campaign root, see below. The envelope's `campaign` holds only the identity | +| `waves` | `WaveView[]` | Derived: the leaves grouped by `level`, ascending, one entry per level that has a leaf | + +`OutlineNode`, directory: + +| Field | Type | Source | +|:--|:--|:--| +| `id`, `title` | `string` | `Directory.id`, `.title` | +| `path` | `string` | Derived: the path segments from the campaign root. `""` for the root | +| `kind` | `"directory"` | `Directory.kind`, with `campaign` shown as `is_campaign: true` | +| `is_campaign` | `bool` | `Directory.kind == "campaign"` | +| `goal` | `string` | `Directory.goal`. Root only | +| `status` | status | Derived, `statuses.md` `Subtrees and directories` | +| `counts` | `StatusCounts` | Derived: the leaves under the directory, any depth, counted by `status`. Needed because a directory shows `done` even when some leaves are cancelled | +| `amendment_count` | `integer` | Derived: the `Amendment` files. Root only | +| `rev` | `string` | Opaque, M1 | +| `children` | `OutlineNode[]` | Derived from the directory listing, in the order above | + +`OutlineNode`, leaf: + +| Field | Type | Source | +|:--|:--|:--| +| `id`, `title`, `status` | | `Leaf.id`, `.title`, `.status` | +| `status_reason` | `string?` | `Leaf.status_reason` | +| `path` | `string` | Derived, as above | +| `kind` | `"leaf"` | `Leaf.kind` | +| `level`, `level_source` | `integer`, `"depth"` | `Level and its source` | +| `ready` | `bool` | Derived: the leaf is in the ready set (`Ready set`) | +| `steps` | `{done, total}` | Derived: count of `Leaf.steps[].done`, and of `Leaf.steps` | +| `added_by` | `string?` | Derived: the display id of the amendment with a change `{op: add}` naming this node. Absent when none | +| `rev` | `string` | Opaque, M1 | + +`WaveView`: + +| Field | Type | Source | +|:--|:--|:--| +| `level`, `level_source` | `integer`, `"depth"` | `Level and its source` | +| `leaf_ids` | `string[]` | Derived: ids of the leaves at this level, in the order above | +| `counts` | `StatusCounts` | Derived: those leaves counted by `status` | + +A wave is a display group. It is not a readiness fact: readiness is in `Ready set`. + +### Worked example + +Counts and statuses of `roadmap-mcp-rework`: ten leaves. M0 and M0b are `ongoing` (legacy +`inprogress`). M1 to M8 are `planned`. Every leaf has three steps, none done. The one amendment, +legacy `A1`, added `m0b_domain_model_spec`. The ready set is empty (see `Ready set`), so every +`ready` is `false`. Directory statuses: the root has an `ongoing` leaf, so `ongoing` (row 4). The +six directories hold only `planned` leaves, so `planned` (row 7). + +```json +{ + "read_model_version": "0.1.0", "format_version": "0.1.0", "projection": "outline", + "campaign": { "id": "c_rework", "path": "__roadmap__/roadmap-mcp-rework", + "title": "rdm rework — meta-roadmap" }, + "tree_rev": "tree-1", + "root": { + "id": "c_rework", "path": "", "kind": "directory", "is_campaign": true, + "title": "rdm rework — meta-roadmap", + "goal": "`managing-roadmaps` ships as a plugin whose tools are a published Rust MCP server and CLI over one core, with JSON roadmaps, full CRUD under an amendment log, and a graph view.", + "status": "ongoing", + "counts": { "planned": 8, "ongoing": 2, "paused": 0, "cancelled": 0, "done": 0 }, + "amendment_count": 1, "rev": "rev-root", + "children": [ + { "id": "n_m0", "path": "m0_feasibility_spike", "kind": "leaf", "title": "M0 Feasibility spike", + "status": "ongoing", "level": 0, "level_source": "depth", "ready": false, + "steps": { "done": 0, "total": 3 }, "rev": "rev-m0" }, + { "id": "n_m0b", "path": "m0b_domain_model_spec", "kind": "leaf", "title": "M0b Domain model spec", + "status": "ongoing", "level": 0, "level_source": "depth", "ready": false, + "steps": { "done": 0, "total": 3 }, "added_by": "A1", "rev": "rev-m0b" }, + { "id": "d_core", "path": "core", "kind": "directory", "is_campaign": false, "title": "Core", + "status": "planned", + "counts": { "planned": 8, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, "rev": "rev-core", + "children": [ + { "id": "n_m1", "path": "core/m1_core_foundation", "kind": "leaf", "title": "M1 Core foundation", + "status": "planned", "level": 1, "level_source": "depth", "ready": false, + "steps": { "done": 0, "total": 3 }, "rev": "rev-m1" }, + { "id": "d_engine", "path": "core/engine", "kind": "directory", "is_campaign": false, "title": "Engine", + "status": "planned", + "counts": { "planned": 7, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, "rev": "rev-engine", + "children": [ + { "id": "n_m2", "path": "core/engine/m2_graph_engine", "kind": "leaf", "title": "M2 Graph engine", + "status": "planned", "level": 2, "level_source": "depth", "ready": false, + "steps": { "done": 0, "total": 3 }, "rev": "rev-m2" }, + { "id": "d_interchange", "path": "core/engine/interchange", "kind": "directory", + "is_campaign": false, "title": "Interchange", "status": "planned", + "counts": { "planned": 6, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, + "rev": "rev-interchange", + "children": [ + { "id": "n_m3", "path": "core/engine/interchange/m3_interchange", "kind": "leaf", + "title": "M3 Interchange", "status": "planned", "level": 3, "level_source": "depth", + "ready": false, "steps": { "done": 0, "total": 3 }, "rev": "rev-m3" }, + { "id": "d_consumers", "path": "core/engine/interchange/consumers", "kind": "directory", + "is_campaign": false, "title": "Consumers", "status": "planned", + "counts": { "planned": 5, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, + "rev": "rev-consumers", + "children": [ + { "id": "n_m4", "path": "core/engine/interchange/consumers/m4_mcp_server", "kind": "leaf", + "title": "M4 MCP server", "status": "planned", "level": 4, "level_source": "depth", + "ready": false, "steps": { "done": 0, "total": 3 }, "rev": "rev-m4" }, + { "id": "n_m5", "path": "core/engine/interchange/consumers/m5_cli", "kind": "leaf", + "title": "M5 CLI", "status": "planned", "level": 4, "level_source": "depth", + "ready": false, "steps": { "done": 0, "total": 3 }, "rev": "rev-m5" }, + { "id": "d_delivery", "path": "core/engine/interchange/consumers/delivery", + "kind": "directory", "is_campaign": false, "title": "Delivery", "status": "planned", + "counts": { "planned": 3, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, + "rev": "rev-delivery", + "children": [ + { "id": "n_m6", "path": "core/engine/interchange/consumers/delivery/m6_apps_view", + "kind": "leaf", "title": "M6 Apps view", "status": "planned", "level": 5, + "level_source": "depth", "ready": false, "steps": { "done": 0, "total": 3 }, + "rev": "rev-m6" }, + { "id": "n_m7", "path": "core/engine/interchange/consumers/delivery/m7_distribution", + "kind": "leaf", "title": "M7 Distribution", "status": "planned", "level": 5, + "level_source": "depth", "ready": false, "steps": { "done": 0, "total": 3 }, + "rev": "rev-m7" }, + { "id": "d_cutover", "path": "core/engine/interchange/consumers/delivery/cutover", + "kind": "directory", "is_campaign": false, "title": "Cutover", "status": "planned", + "counts": { "planned": 1, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 }, + "rev": "rev-cutover", + "children": [ + { "id": "n_m8", + "path": "core/engine/interchange/consumers/delivery/cutover/m8_cutover", + "kind": "leaf", "title": "M8 Cutover", "status": "planned", "level": 6, + "level_source": "depth", "ready": false, "steps": { "done": 0, "total": 3 }, + "rev": "rev-m8" } ] } ] } ] } ] } ] } ] } ] + }, + "waves": [ + { "level": 0, "level_source": "depth", "leaf_ids": ["n_m0", "n_m0b"], + "counts": { "planned": 0, "ongoing": 2, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 1, "level_source": "depth", "leaf_ids": ["n_m1"], + "counts": { "planned": 1, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 2, "level_source": "depth", "leaf_ids": ["n_m2"], + "counts": { "planned": 1, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 3, "level_source": "depth", "leaf_ids": ["n_m3"], + "counts": { "planned": 1, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 4, "level_source": "depth", "leaf_ids": ["n_m4", "n_m5"], + "counts": { "planned": 2, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 5, "level_source": "depth", "leaf_ids": ["n_m6", "n_m7"], + "counts": { "planned": 2, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } }, + { "level": 6, "level_source": "depth", "leaf_ids": ["n_m8"], + "counts": { "planned": 1, "ongoing": 0, "paused": 0, "cancelled": 0, "done": 0 } } + ] +} +``` + +## Node detail + +One node, with everything stored about it and what is derived. `kind` says which of two shapes. + +Common to both kinds: + +| Field | Type | Source | +|:--|:--|:--| +| `id`, `title`, `kind` | | `id`, `title`, `kind` of the file | +| `path` | `string` | Derived: path segments from the campaign root | +| `parent` | `string` | Derived: the path of the parent directory. `""` for a node under the root | +| `rev` | `string` | Opaque, M1 | +| `finished` | `bool` | Derived from `statuses.md` `Finished nodes`: `true` when an edit needs a reason and is a correction (leaf `cancelled` or `done`, directory with derived status `cancelled` or `done`) | +| `correction_count` | `integer` | Derived, never stored: the number of records with `correction: true` that name this node (its amendments, its `marks`, its `history`). It measures how often corrections and reversals happen. `0` for a node never corrected | +| `comments` | `Comment[]` | The `_comments/` files whose `node_id` is this node, oldest first. The stored `Comment` shape | +| `amendments` | `string[]` | Derived: display ids of the amendments whose `changes` name this node | +| `added_by` | `string?` | As in `Campaign outline` | + +Leaf only: + +| Field | Type | Source | +|:--|:--|:--| +| `status`, `status_reason?` | | `Leaf.status`, `.status_reason` | +| `status_since` | `ts?` | Derived: `ts` of the last `Leaf.history` entry. Absent when `history` is empty, as for an imported leaf | +| `level`, `level_source` | | `Level and its source` | +| `ready` | `bool` | Derived, `Ready set` | +| `held_by` | `string[]` | Derived: ids of the unfinished leaves that hold this leaf back, by the ready rule. Empty when none. Also set for a leaf that is not `planned`, so a reader sees what a paused leaf waits for | +| `goal`, `preconditions`, `success_gates`, `references` | | The stored fields of `Leaf` | +| `steps` | `StepView[]` | `StepView`: every stored `Step` field, plus `number`. A consumer addresses a step by `id`, never by `number` | +| `progress` | | `Leaf.progress`, as stored | +| `commit_count` | `integer?` | Derived: the number of steps with a `commit_sha`; else `progress.commits`; else absent | +| `step_progress` | `{done, total}` | Derived, as `steps` in `Campaign outline` | +| `history` | `History[]` | `Leaf.history`, as stored, oldest first | +| `marks` | `Mark[]` | `Leaf.marks`, as stored, oldest first: the trace of every criterion mark | + +`StepView.number` is derived for display: the position in `Leaf.steps` plus one. It is not a reference: a reorder changes it, and `Step.id` does not. Criteria, references and checks are likewise addressed by their `id` (`stored-schema.md`, `Stable identity`). + +Directory only: + +| Field | Type | Source | +|:--|:--|:--| +| `is_campaign` | `bool` | `Directory.kind == "campaign"` | +| `status` | status | Derived, `statuses.md` | +| `counts` | `StatusCounts` | Derived, as in `Campaign outline` | +| `context`, `goal`, `preconditions`, `success_gates`, `references`, `gotchas`, `notes` | | The stored fields of `Directory` | +| `marks` | `Mark[]` | `Directory.marks`, as stored, oldest first | +| `children` | `{id, path, kind, title, status}[]` | Derived from the directory listing, in the order above | + +Both kinds: a top-level `holders` map, id to `Holder`, holds every id named in `held_by`, so the +caller needs no second read. + +### Worked example + +`core/m1_core_foundation`, a `planned` leaf held back by M0 and M0b. Its three-step file is cut to +step 1. + +```json +{ + "read_model_version": "0.1.0", "format_version": "0.1.0", "projection": "node", + "campaign": { "id": "c_rework", "path": "__roadmap__/roadmap-mcp-rework", + "title": "rdm rework — meta-roadmap" }, + "tree_rev": "tree-1", + "node": { + "id": "n_m1", "path": "core/m1_core_foundation", "parent": "core", "kind": "leaf", + "rev": "rev-m1", "title": "M1 Core foundation", + "status": "planned", "level": 1, "level_source": "depth", + "ready": false, "held_by": ["n_m0", "n_m0b"], "finished": false, "correction_count": 0, + "goal": "`rdm-engine` stores a roadmap as JSON, one file per node, and N processes can read and write one campaign without losing or tearing a write.", + "preconditions": [ + { "id": "k_1", "text": "`../m0_feasibility_spike.md` is `done` with a go", "met": false }, + { "id": "k_2", "text": "`../m0b_domain_model_spec.md` is `done`", "met": false }, + { "id": "k_3", "text": "Reminder `skills-rdm-M1` read", "met": false } ], + "success_gates": [ + { "id": "k_4", "text": "`rdm-engine` depends on `rdm-schema` for every stored type and holds none of its own; a file with a newer format major is refused with an upgrade message", "met": false }, + "[cut: 4 more gates, same shape]" ], + "references": [ + { "id": "r_1", "label": "R01", "title": "§Data Model, §Concurrency, §Contracts & Invariants", + "target": "../../../__design__/rdm/architecture.md", + "note": "the file layout, the schema sketch, the lock, the journal and the revisions" } ], + "steps": [ + { "id": "s_m1_1", "number": 1, "title": "Plan the milestone", + "goal": "The campaign `__roadmap__/m1-core-foundation/` exists and Eliott has approved it.", + "implementation_logic": [ + "In plan mode, author the campaign with `managing-roadmaps`, deciding: the id minting, to the format M0b fixes; … [cut]", + "[cut: 1 more line]" ], + "deliverables": [ "`__roadmap__/m1-core-foundation/README.md` and its leaves" ], + "references": [], + "checks": [ { "id": "ck_1", "text": "`bash skills/managing-roadmaps/scripts/dirtree-rdm.sh validate __roadmap__/m1-core-foundation/`", + "expected": "PASS" } ], + "commit": { "type": "chore", "scope": "roadmap", "breaking": false, + "summary": "plan the m1-core-foundation milestone" }, + "done": false }, + "[cut: steps 2 and 3, same shape]" ], + "progress": { "notes": [] }, + "step_progress": { "done": 0, "total": 3 }, + "history": [], "marks": [], "comments": [], "amendments": [] + }, + "holders": { + "n_m0": { "path": "m0_feasibility_spike", "title": "M0 Feasibility spike", "status": "ongoing" }, + "n_m0b": { "path": "m0b_domain_model_spec", "title": "M0b Domain model spec", "status": "ongoing" } + } +} +``` + +The imported leaf has no `history`, no `commit_count`, no `status_since` and no `branch`: the +legacy file held none of them, and its Progress table is empty. + +## Ready set + +**The rule** is the scoped rule of `statuses.md` (Eliott, 2026-11-16). A leaf is ready when it is +`planned` and no leaf holds it back. An unfinished leaf (`planned`, `ongoing`, `paused`) holds +back only the deeper leaves under its own parent. In steps: for a leaf L, take every directory +above L's own directory, up to and including the campaign root. Every unfinished leaf that sits +directly in one of those directories holds L back. Sibling leaves are parallel. `done` and +`cancelled` leaves hold nothing back. + +| Field | Type | Source | +|:--|:--|:--| +| `ready` | `ReadyLeaf[]` | Derived: the leaves that are `planned` and held by none | +| `stalled` | `StalledLeaf[]` | Derived: the `planned` leaves held by at least one leaf | +| `holders` | map id to `Holder` | Derived: every leaf named in a `held_by` | + +`ReadyLeaf`: `id`, `path`, `title` (stored or derived as in the outline), `level` and +`level_source`. `StalledLeaf`: the same, plus `held_by`, the ids of the unfinished leaves that hold +it, in the order above. A leaf that is `ongoing`, `paused` or finished is in neither list. A +`paused` leaf shows in `holders` with its `status_reason`. + +### Worked example: the real campaign + +Statuses: M0, M0b `ongoing`; M1 to M8 `planned`. The campaign is a chain: each leaf sits in a +directory under the previous leaf's directory, so each holds back everything deeper. M0 and M0b +sit at the root and hold back every directory leaf. No `planned` leaf is free: `ready` is empty. +M1 is held by M0 and M0b. M2 adds M1, and so on down the chain. + +```json +{ + "read_model_version": "0.1.0", "format_version": "0.1.0", "projection": "ready", + "campaign": { "id": "c_rework", "path": "__roadmap__/roadmap-mcp-rework", + "title": "rdm rework — meta-roadmap" }, + "tree_rev": "tree-1", + "ready": [], + "stalled": [ + { "id": "n_m1", "path": "core/m1_core_foundation", "title": "M1 Core foundation", "level": 1, "level_source": "depth", + "held_by": ["n_m0", "n_m0b"] }, + { "id": "n_m2", "path": "core/engine/m2_graph_engine", "title": "M2 Graph engine", "level": 2, "level_source": "depth", + "held_by": ["n_m0", "n_m0b", "n_m1"] }, + { "id": "n_m3", "path": "core/engine/interchange/m3_interchange", "title": "M3 Interchange", "level": 3, + "level_source": "depth", "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2"] }, + { "id": "n_m4", "path": "core/engine/interchange/consumers/m4_mcp_server", "title": "M4 MCP server", "level": 4, + "level_source": "depth", "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2", "n_m3"] }, + { "id": "n_m5", "path": "core/engine/interchange/consumers/m5_cli", "title": "M5 CLI", "level": 4, + "level_source": "depth", "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2", "n_m3"] }, + { "id": "n_m6", "path": "core/engine/interchange/consumers/delivery/m6_apps_view", "title": "M6 Apps view", + "level": 5, "level_source": "depth", + "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2", "n_m3", "n_m4", "n_m5"] }, + { "id": "n_m7", "path": "core/engine/interchange/consumers/delivery/m7_distribution", "title": "M7 Distribution", + "level": 5, "level_source": "depth", + "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2", "n_m3", "n_m4", "n_m5"] }, + { "id": "n_m8", "path": "core/engine/interchange/consumers/delivery/cutover/m8_cutover", "title": "M8 Cutover", + "level": 6, "level_source": "depth", + "held_by": ["n_m0", "n_m0b", "n_m1", "n_m2", "n_m3", "n_m4", "n_m5", "n_m6", "n_m7"] } + ], + "holders": { + "n_m0": { "path": "m0_feasibility_spike", "title": "M0 Feasibility spike", "status": "ongoing" }, + "n_m0b": { "path": "m0b_domain_model_spec", "title": "M0b Domain model spec", "status": "ongoing" }, + "n_m1": { "path": "core/m1_core_foundation", "title": "M1 Core foundation", "status": "planned" }, + "n_m2": { "path": "core/engine/m2_graph_engine", "title": "M2 Graph engine", "status": "planned" }, + "n_m3": { "path": "core/engine/interchange/m3_interchange", "title": "M3 Interchange", "status": "planned" }, + "n_m4": { "path": "core/engine/interchange/consumers/m4_mcp_server", "title": "M4 MCP server", "status": "planned" }, + "n_m5": { "path": "core/engine/interchange/consumers/m5_cli", "title": "M5 CLI", "status": "planned" }, + "n_m6": { "path": "core/engine/interchange/consumers/delivery/m6_apps_view", "title": "M6 Apps view", "status": "planned" }, + "n_m7": { "path": "core/engine/interchange/consumers/delivery/m7_distribution", "title": "M7 Distribution", "status": "planned" } + } +} +``` + +### Worked example: where the scoped and the global rule differ + +A hypothetical campaign with two branches. Global rule: a leaf waits for every unfinished leaf of +a smaller level, in any branch (R01's first reading). + +| Path | Level | Status | +|:--|:--|:--| +| `a_setup` | 0 | `done` | +| `core/m1_core` | 1 | `paused` | +| `docs/d1_docs` | 1 | `done` | +| `core/engine/m2_engine` | 2 | `planned` | +| `docs/guide/g1_guide` | 2 | `planned` | + +| Leaf | Held by, scoped | Held by, global | +|:--|:--|:--| +| `m2_engine` | `m1_core` (leaf of `core/`, above `core/engine/`) | `m1_core` | +| `g1_guide` | none: `d1_docs` is `done`, `a_setup` is `done` | `m1_core` (paused, in the unrelated branch `core/`) | + +Scoped: `ready` is `[g1_guide]`, `stalled` is `[m2_engine]`. Global: `ready` is empty. The paused +leaf in `core/` halts the whole campaign under the global rule and only its own branch under the +scoped one. The scoped projection: + +```json +{ "ready": [ { "id": "n_g1", "path": "docs/guide/g1_guide", "title": "G1 Guide", "level": 2, "level_source": "depth" } ], + "stalled": [ { "id": "n_m2", "path": "core/engine/m2_engine", "title": "M2 Engine", "level": 2, "level_source": "depth", + "held_by": ["n_m1"] } ], + "holders": { "n_m1": { "path": "core/m1_core", "title": "M1 Core", "status": "paused", + "status_reason": "waiting for the schema review" } } } +``` + +## Amendment log + +The amendments of a campaign, oldest first, optionally filtered. One entry per `Amendment` file. + +Request parameters: `node` (an id or a path: keep amendments whose `changes` name that node), +`since` and `until` (a `ts` range, inclusive). All optional. No parameter gives the whole log. + +| Field | Type | Source | +|:--|:--|:--| +| `amendments` | `AmendmentEntry[]` | The `_amendments/` files that pass the filters, ordered by ULID | +| `total` | `integer` | Derived: the count of all amendments of the campaign, before filtering | + +`AmendmentEntry`: + +| Field | Type | Source | +|:--|:--|:--| +| `id` | `ulid` | `Amendment.id` | +| `display_id` | `string` | Derived: `Amendment.legacy_id` when present, else `A-` and the shortest ULID suffix, at least 6 characters, unique in the campaign (`stored-schema.md`, `Amendment`) | +| `legacy_id` | `string?` | `Amendment.legacy_id` | +| `ts`, `actor`, `description` | | `Amendment.ts`, `.actor`, `.description` | +| `source` | `string?` | `Amendment.source` | +| `op_id` | `string?` | `Amendment.op_id` | +| `correction` | `bool?` | `Amendment.correction`: `true` for an edit that needed a reason on a finished node or a recorded step | +| `has_snapshot` | `bool` | Derived: `Amendment.snapshot` is present. The snapshot itself is not returned | +| `changes` | `ChangeView[]` | `Amendment.changes`, each as below | + +`ChangeView` carries the stored `Change` fields (`node_id`, `op`, `path_before?`, `path_after?`, +`item_id?`, `field?`, `old?`, `new?`) and two derived ones: + +| Field | Type | Source | +|:--|:--|:--| +| `node_path` | `string?` | Derived: the current path of `node_id`. Absent when the node no longer exists | +| `node_title` | `string?` | Derived: the current `title` of `node_id`. Absent when the node no longer exists | + +A display id can lengthen when a later amendment shares its suffix. Cite `id` for a stable +reference. + +### Worked example + +The whole log of `roadmap-mcp-rework`: one amendment, imported from the legacy row `A1`. + +```json +{ + "read_model_version": "0.1.0", "format_version": "0.1.0", "projection": "amendments", + "campaign": { "id": "c_rework", "path": "__roadmap__/roadmap-mcp-rework", + "title": "rdm rework — meta-roadmap" }, + "tree_rev": "tree-1", + "total": 1, + "amendments": [ + { "id": "am_a1", "display_id": "A1", "legacy_id": "A1", + "ts": "2026-11-16T00:00:00Z", "actor": { "kind": "import" }, + "description": "No milestone owned the domain model; also edits the planned leaves m0, m1, m2, m4, m6, m7 and this README, and Eliott chose to keep the label M0b", + "source": "__reports__/rdm_domain_model_review/01-gap_analysis_v0.md", + "has_snapshot": false, + "changes": [ { "node_id": "n_m0b", "op": "add", "node_path": "m0b_domain_model_spec", + "node_title": "M0b Domain model spec" } ] } + ] +} +``` + +With `node=n_m0b` the call returns the same entry. With `node=n_m1` it returns an empty list and +`total` stays 1. `ts` is the row's date at midnight UTC, `actor.kind` is `import` and the change +has no `path_after`, as `stored-schema.md` says of a legacy row. + +## Level and its source + +`level` is the wave of a leaf. Today it is the depth: the number of directories between the +campaign root and the leaf. A leaf in the root has level 0. It is derived from the path and never +stored. + +Every leaf in every projection carries both fields: + +```json +{ "level": 2, "level_source": "depth" } +``` + +| Field | Type | Meaning | +|:--|:--|:--| +| `level` | `integer` | The position of the leaf in the order, from 0 | +| `level_source` | `LevelSource` | The rule that produced `level`. One value today: `depth` | + +Why the source is reported: depth is the only ordering rule, and the ordering open question +(R04) keeps other rules possible. If a rule other than depth is added later, `level` changes +meaning and `level_source` says which. A consumer groups by `level` only for a `level_source` it +knows, and shows a flat list for another. A new `level_source` value is a Y change of the +read-model version (`Versions`). The ready rule does not read `level`: it reads the directory +tree, so a change of `level_source` alone cannot change the ready set. + +Directories have no level. + +## Versions + +Two version numbers, two constants, both in `rdm-schema`. Eliott, 2026-11-16: both are +three-part, `0.X.Y`. + +| Item | Format version | Read-model version | +|:--|:--|:--| +| Constant | `FORMAT_VERSION` | `READ_MODEL_VERSION` | +| Form | `"0.X.Y"` string | `"0.X.Y"` string | +| First value | `"0.1.0"` | `"0.1.0"` | +| Where it appears | `schema_version` in every stored file | `read_model_version` in every projection | +| Format of what it covers | The stored files (`stored-schema.md`) | The four projections of this document | +| Bump Y | A new optional stored field, or a new enum value old readers can ignore; a compatible fix | A new optional field, a new projection, a new request parameter, a new `level_source` value; a compatible fix | +| Bump X (breaking, while the major is 0) | A stored field removed, renamed, retyped, given another meaning, or made required | A projection field removed, renamed, retyped or given another meaning; a changed derivation (the ready rule, the order, a status derivation); a required request parameter added | +| Reader | Refuses every file newer than it, the whole triple compared, so a higher major, X or Y (Eliott, 2026-11-25), with an upgrade message. Reads an older file through the layer of its version and keeps unknown fields (I12), warning once per key | The same rule: a consumer refuses every payload newer than it, a higher Y included (Eliott, 2026-11-25), and reads an older one. It ignores unknown fields | +| Crate rule | A breaking format change forces a crate X bump. A compatible one forces at least a crate Y bump | A breaking read-model change forces a crate X bump. A compatible one forces at least a crate Y bump | + +**Bumps come from commit messages.** The crate's version is decided from commit types and scopes +by the repository's existing multi-semantic-release setup (`@semantic-release/commit-analyzer`, +`release-config.js`, `.github/workflows/release.yml`, which release `skills/**` only today). A +`!` or BREAKING commit gives X and `feat` or `fix` gives Y, while the crate stays `0.x`. Wiring +the crate into that release job, with a rule that keeps a breaking change at `0.x` (semantic-release +goes to 1.0.0 by default), is M7's job. No CI check is added. "Forces at least a Y bump" means the +crate may bump more for its own reasons. While the crate is `0.x`, an X bump is the breaking one +in Rust's own rules. + +A format change can leave the read model alone: a new optional stored field that no projection +shows is a format Y bump and no read-model change. A breaking format change needs a read-model review, +because a projection may read the field that changed. The read-model version moves only if a +projection field does. + +`format_version` in a projection is not the read-model version. It tells a consumer which stored +format the data came from, as the highest `schema_version` among the files read. + +## Gaps + +No stored field a projection needs is missing. Two limits, neither one blocking: + +| Limit | Effect | +|:--|:--| +| An imported leaf has no history | `status_since` is absent and `commit_count` comes from `progress.commits`. Consumers must treat both as optional | +| A display id is not stable | It can lengthen when a later amendment shares its ULID suffix. `id` is the stable key | + +## Decisions + +| # | Decision | Decided | +|:--|:--|:--| +| 1 | The ready set uses the scoped rule: an unfinished leaf holds back only the deeper leaves under its own parent | Eliott, 2026-11-16 | +| 2 | `level` is reported as `{level, level_source: "depth"}` | Eliott, 2026-11-16 | +| 3 | The read-model version is separate from the format version, with its own bump rule and constant. A breaking read-model change forces a crate X bump, a compatible one at least a Y bump, as the format does | coordinator, 2026-11-16 | +| 4 | `held_by` and `holders`: a ready projection names what stalls each leaf by id, with one map of holders to avoid repeating them | coordinator, 2026-11-16 | +| 5 | Sibling order is not stored. Projections order by level, then leaves before directories, then path (`traceability.md`, `Sibling order`) | Eliott, 2026-11-16 | +| 6 | Versions are three-part `0.X.Y`, first value `0.1.0`, for the format, the read model and the crate. A reader refuses a different major or a higher X and reads a higher Y (superseded by decision 10). Bumps come from commit messages through the existing release setup; M7 wires the crate | Eliott, 2026-11-16 | +| 7 | The node projections carry `marks`, the trace of criterion marks. `ready` is unchanged: it does not read pre-conditions, which gate the start separately (`statuses.md`, `Criteria`) | Eliott, 2026-11-16 (rule), coordinator (projection) | +| 8 | Sealing becomes a reason requirement, so the node projections carry `finished` (replacing `sealed`) and a derived `correction_count`, the number of records with `correction: true` that name the node. It is never stored | Eliott, 2026-11-16 | +| 9 | Projections address sub-items by `id`; `StepView.number` and `level` are display positions and never references | Eliott, 2026-11-16 | +| 10 | One version rule for stored files and projections: every version newer than the reader, a higher Y included, is refused (`is_newer`, the whole triple). A Y bump still promises additive meaning, not that older readers accept it | Eliott, 2026-11-25 (review) | diff --git a/__design__/rdm/statuses.md b/__design__/rdm/statuses.md new file mode 100644 index 0000000..0d75271 --- /dev/null +++ b/__design__/rdm/statuses.md @@ -0,0 +1,243 @@ +# rdm — Status semantics + +What each status of a leaf means, how it may change, and what it does to the order of work. The +vocabulary and the editing rules are Eliott's decisions of 2026-11-16 (M0b README, Gotchas). Where +this document goes beyond them, a note says who decided it: Eliott or the coordinator, both on +2026-11-16. No question is open. + +This document settles the meaning. The stored shape of the fields it names (`status`, +`status_reason`, `history`, and the comment files) is in [stored-schema.md](stored-schema.md). R01 +(`architecture.md`) is not edited here; section `R01 deltas` lists what `r01_sync` must change. + +## Statuses + +Only a leaf has a stored status. A directory's status is derived (see `Subtrees and directories`). + +| Status | Meaning | Finished | Edits | +|:--|:--|:--|:--| +| `planned` | The leaf is written and not started. No step is recorded done. | no | amendment note | +| `ongoing` | Work has started on the leaf. Steps may be recorded done. | no | amendment note; a correction of a recorded step needs a reason | +| `paused` | Work is held and can be resumed: a bug, a decision to wait, or a downstream branch held on purpose. | no | as `ongoing` | +| `cancelled` | The leaf is abandoned. It holds nothing back while it is cancelled. Whatever was done stays on record. A mistaken cancel can be undone: the leaf returns to the status it had just before the cancel. | yes | any edit, with a reason (a correction) | +| `done` | Every step is done with its commit recorded and every gate `met`. The normal end state. It can be reversed or corrected, each time with a reason. | yes | any edit, with a reason (a correction) | + +`blocked` and `amendment` are not statuses. A "blocked" situation is `paused` (resumable) or +`cancelled` (abandoned). An "amendment" is an edit recorded in the amendment log, and a node +added by one starts as `planned`. + +An unfinished leaf (`planned`, `ongoing`, `paused`) holds back deeper leaves. A finished leaf +(`done`, `cancelled`) holds back nothing. `done` is the normal end state, not a lock: a finished node can be edited or reversed with a reason (`Finished nodes`). + +## Transitions + +All 25 ordered pairs. A move out of `done` is a reversal: its history entry carries `correction: true` and a non-blank reason. "Who" is the actor kind recorded in `history[].actor`: `agent`, `human` or +`both`. "Reason" is the `reason` of the history entry (copied to `status_reason` when the new +status is `paused` or `cancelled`). "Ready set" says what the move does to the set defined in +`Ready set`: ENTER, LEAVE, RELEASE (deeper leaves may become ready), HOLD (a finished leaf is unfinished again, so deeper ready leaves stop being ready) or none. + +| From | To | Allowed | Who | Reason | Precondition | Ready set | +|:--|:--|:--|:--|:--|:--|:--| +| `planned` | `planned` | refused | | | A move to the same status is a no-op and writes no history | none | +| `planned` | `ongoing` | allowed | both | only for an override | Every pre-condition is `met`, and the leaf is in the ready set. Outside the set, an override with a reason is needed, and the entry records `override: true`. The override skips the ready set, never the pre-conditions (Eliott, 2026-11-16) | LEAVE | +| `planned` | `paused` | allowed | both | required | none | LEAVE | +| `planned` | `cancelled` | allowed | both | required | none | LEAVE, RELEASE | +| `planned` | `done` | refused | | | Start the leaf first: `done` needs the steps recorded (I8) and the gates `met` | none | +| `ongoing` | `planned` | refused | | | Use `paused`, then `planned` while no step is done | none | +| `ongoing` | `ongoing` | refused | | | No-op | none | +| `ongoing` | `paused` | allowed | both | required | none | none | +| `ongoing` | `cancelled` | allowed | both | required | none. Steps already done stay recorded | RELEASE | +| `ongoing` | `done` | allowed | both | none | Every step is done with its commit recorded (I8), and every success gate is `met` (Eliott, 2026-11-16). See `Criteria` | RELEASE | +| `paused` | `planned` | allowed | both | required | No step is recorded done (coordinator, 2026-11-16) | ENTER if nothing shallower holds it back | +| `paused` | `ongoing` | allowed | both | required | The leaf was `ongoing` before the pause (last pause entry has `from: ongoing`), or it is in the ready set. Otherwise an override with a reason | none | +| `paused` | `paused` | refused | | | No-op | none | +| `paused` | `cancelled` | allowed | both | required | none | RELEASE | +| `paused` | `done` | refused | | | Resume to `ongoing` first | none | +| `cancelled` | `planned` | allowed | both | required | Undo: the status before the cancel, read from history (the `from` of the last cancel entry), is `planned`. Eliott's intent 2026-11-16, ruling (coordinator, 2026-11-16) | ENTER if nothing shallower holds it back | +| `cancelled` | `ongoing` | allowed | both | required | Undo: the status before the cancel was `ongoing`. Any other target is refused (coordinator, 2026-11-16) | none | +| `cancelled` | `paused` | allowed | both | required | Undo: the status before the cancel was `paused`. Any other target is refused (coordinator, 2026-11-16) | none | +| `cancelled` | `cancelled` | refused | | | No-op | none | +| `cancelled` | `done` | allowed | both | required | Undo only: the status before the cancel was `done` (a leaf cancelled by a reversal out of `done`). Flagged `correction: true`. Any other route into `done` from `cancelled` is refused (coordinator, 2026-11-16) | RELEASE | +| `done` | `planned` | refused | | | The leaf has steps recorded done, and `planned` means not started. Reverse to `ongoing` | none | +| `done` | `ongoing` | allowed | both | required | A reversal (Eliott, 2026-11-16). Recorded with `correction: true`. No gate or step is changed: they stay as recorded | HOLD: deeper leaves that were ready stop being ready; deeper leaves already started are not stopped | +| `done` | `paused` | allowed | both | required | A reversal, `correction: true` | HOLD | +| `done` | `cancelled` | allowed | both | required | A reversal, `correction: true`. Steps and gates stay as recorded | none | +| `done` | `done` | refused | | | No-op | none | + +Rules that hold for every row: + +- No move is human-only. `history[].actor` records who made it. +- A move presents the status it expects to leave. A mismatch is refused (R01 §Concurrency). +- A move writes one history entry and never an amendment (I5). A criterion mark writes a mark record, see `Criteria`. +- A move into `done` or `cancelled` may carry the final `progress` in the same operation. After it, every edit is still accepted, with a reason (`Finished nodes`). +- The reason is required text, not blank, for `paused`, `cancelled`, `paused → planned`, `paused → ongoing`, every undo out of `cancelled` and every move out of `done`. + +**`paused → planned` needs "no step is recorded done".** A step recorded done has its +commit on record, so a `planned` leaf holding a recorded commit would contradict "not started". A leaf with a recorded step goes to `ongoing` +instead. Decided 2026-11-16 (coordinator). + +**`cancelled` is undoable.** A cancel is one call with a reason, and a directory cancel is one +call over many leaves, so a mistake must be reversible. Undoing a cancel restores the status the +node had just before the cancel, with a required reason, recorded in history. That status is read +from history: the `from` of the last cancel entry. It may be `planned`, `ongoing`, `paused` or, for a leaf reversed out of `done` and then cancelled, `done`. Any +other target out of `cancelled` is refused. A leaf with no cancel entry in its history (one imported from legacy `blocked`) returns to `planned`, as the importer writes no steps done. A leaf cancelled from `done` is restored to `done`, as the table says. +Eliott's intent 2026-11-16 ("undo a mistaken cancel with a reason"); the restore rule is the +coordinator's ruling, 2026-11-16. + +**Closed gap: a cancelled leaf with a recorded step.** The first form of the undo moved only to +`planned`, which a leaf with a done step cannot take, so such a leaf could never be resumed. The +restore rule fixes it: a leaf cancelled from `ongoing` or `paused` returns there. + +**Note: a cancel releases work without saying so.** Because `cancelled` holds nothing back, a +cancelled leaf can release a deeper leaf that really needed it. That is Eliott's intent. The +impact report of a cancel (M2) should list the leaves it makes ready, so the release is never +silent. + +## Criteria + +Eliott, 2026-11-16: verified pre- and post-conditions are cornerstones of AI planning, an +unmaintained checklist is pointless, and a wrong check must be traceable. So criteria are +enforced, and every mark leaves a trace. + +- **Pre-conditions gate the start.** `planned → ongoing` needs every pre-condition `met`. This holds for an override too: an override skips the ready set, never the pre-conditions. The same holds for `paused → ongoing` by override. +- **Success gates gate the finish.** `ongoing → done` needs every success gate `met`, in addition to I8. +- **Every mark is traced.** A change of a criterion's `met` mark, on a leaf or a directory, writes a mark record: `ts`, `actor`, the criterion's `criterion_id` (the stable id of the criterion, never its position), the new value, `evidence?` (free text: a command, its result, a commit), and on a finished node `reason` and `correction: true`. Leaves and directories keep the records in their own `marks` array, apart from `history` (stored-schema.md). +- **`met` is a state mark, not content.** Setting it makes no amendment. On a `done` or `cancelled` node a mark needs a non-blank reason and carries `correction: true` (`Finished nodes`). A wrong mark is corrected by another mark record, at any time; both records stay. +- **Legacy data.** 30 of 48 done leaves under `__roadmap__/` carry open gates. The importer never invents a tick: it imports them as they are, and `validate` reports each `done` node with an unmet criterion as an error to reconcile. Whoever reconciles ticks the criterion with an ordinary reasoned mark (`correction: true`, `reason` or `evidence`), which writes a mark record. The count of such corrections is data (`Finished nodes`). + +## Ready set + +A leaf is ready when it is `planned` and every leaf that holds it back is `done` or `cancelled`. +So `cancelled` holds nothing back while it is cancelled. Undoing a cancel returns the leaf to its earlier status; if that is +`planned`, `ongoing` or `paused` it holds back again; deeper leaves that already started are not stopped. + +**The rule (scoped, the legacy rule; Eliott, 2026-11-16).** An unfinished leaf holds back only +the deeper leaves under its own parent. Precisely: leaf L is held back by every unfinished leaf +that is a leaf child of the parent of A, for A = L's own directory and each ancestor directory of +L below the campaign root. Leaves in an unrelated branch never hold L back, and sibling leaves are +parallel. + +Equivalently: a leaf directly under directory P holds back every leaf found in the directories +under P, at any depth, and nothing else. A leaf directly under the campaign root holds back every +leaf in the campaign's directories. + +The same rule applies to `planned`, `ongoing` and `paused`: a `paused` leaf holds back exactly what +a `planned` or `ongoing` one does. To hold a branch on purpose, pause its directory. + +Worked on `__roadmap__/roadmap-mcp-rework/`, a chain: M5 sits in `consumers/`, so pausing it holds +back M6, M7 and M8 in `consumers/delivery/` and below. A global rule would give the same set +there. The two differ with a second branch. Hypothetical: a directory `docs/guide/` at the +campaign root, with a leaf at depth 2, next to `core/`. Pausing M1 (parent `core/`) holds back M2 +to M8, which sit under `core/`, and does not hold back the docs leaf. The global rule (R01's) +would have. + +An `ongoing` leaf is not in the ready set, because it is not `planned`. A leaf started by an +override (`planned → ongoing` outside the set) is recorded and allowed. + +## Subtrees and directories + +**Pausing or cancelling a directory** is one operation over its leaves. + +- `pause` sets every `planned` and `ongoing` leaf under the directory to `paused`. +- `cancel` sets every `planned`, `ongoing` and `paused` leaf under it to `cancelled`. +- Leaves already finished are left alone. A leaf where the move is refused is skipped, never an error for the whole operation. +- One reason, one timestamp and one `op_id` are shared by every history entry the operation writes. The operation is one call and one transaction, so it is "recorded once". +- It is a snapshot, not a standing flag. A leaf added to the directory later starts `planned`. +- `resume` of a directory sets each `paused` leaf under it to the `from` of its last pause entry (`planned` or `ongoing`). A leaf whose last pause came from another operation is resumed too, each by its own rule. The reason is required. +- `uncancel` of a directory restores every `cancelled` leaf whose last history entry carries the `op_id` of the cancel being undone. Each leaf returns to the `from` of that entry, so a leaf may come back `planned`, `ongoing` or `paused`. One reason and one new `op_id` are shared. Leaves cancelled by another operation are left alone. + +**A directory's status is derived on every read and never stored (I6).** It is computed from all +leaves under it, at any depth. The first matching row wins. + +| # | Leaves under the directory | Derived status | +|:--|:--|:--| +| 1 | none | `planned` | +| 2 | all `cancelled` | `cancelled` | +| 3 | all finished, at least one `done`, and the directory's own gates all `met` | `done` | +| 3b | all finished, at least one `done`, and a gate of the directory not `met` | `ongoing` | +| 4 | at least one `ongoing` | `ongoing` | +| 5 | at least one `paused` | `paused` | +| 6 | at least one `done`, the others `planned` or `cancelled` | `ongoing` | +| 7 | otherwise (`planned`, with or without `cancelled`) | `planned` | + +Row 3 reads a directory whose leaves are all finished as `done` even if some were cancelled, once its own gates are met. Until then it is `ongoing` (row 3b): the directory's gates are the last thing left to check. A +reader that must tell them apart uses the counts per status, which the read model carries. + +## Finished nodes + +Eliott, 2026-11-16: much of the data is best effort and should not be modified once set, but for +convenience anything may be edited as long as a reason or comment is given, and the count of such +reasons is data in itself: it measures how often corrections and reversals happen. So nothing is +locked. A node is *finished* when it is `done` or `cancelled` (a directory: derived status `done` +or `cancelled`). Every edit of a finished node needs a non-blank reason and is recorded as a +**correction**. + +| Status | Content edit | Comment | Status move | Progress | Criterion mark | +|:--|:--|:--|:--|:--|:--| +| `planned` | allowed, amendment note required | allowed | per `Transitions` | allowed | allowed | +| `ongoing` | allowed, amendment note required. Correcting a step recorded done is a correction | allowed | per `Transitions` | allowed | allowed | +| `paused` | as `ongoing` | allowed | per `Transitions` | allowed | allowed | +| `cancelled` | allowed, as a correction | allowed | the undo, to the pre-cancel status | allowed, as a correction | allowed, as a correction | +| `done` | allowed, as a correction | allowed | to `ongoing`, `paused` or `cancelled`, as a reversal | allowed, as a correction | allowed, as a correction | + +- **Content** is every stored field except `status`, `status_reason`, `history`, `marks`, `progress` and the state marks. The state marks are a criterion's `met` with its mark record, and a step's `done`, `commit_sha` and `done_at`. +- **The amendment rule is uniform.** Any content edit to a `planned`, `ongoing` or `paused` node carries the amendment note, whatever the status. Those edits are unchanged and are not corrections. +- **A correction is identifiable.** It carries `correction: true` on its record: the amendment (content edit, progress edit, or correction of a recorded step), the mark record (a mark on a finished node), or the history entry (a reversal out of `done`). Its reason is the amendment `description`, the mark `reason` (or `evidence`), or the history `reason`. The reason is not blank, and the engine refuses a blank one. +- **Corrections are counted.** The node detail carries `correction_count`, derived on read and never stored: the number of records with `correction: true` that name the node (amendments, marks and history entries). It measures how often corrections and reversals happen. +- **Correcting a recorded step.** Recording a step done is a state mark and writes no amendment. Correcting it afterwards (a changed `commit_sha`, a cleared `done`, an edit of its content) is an amendment with `correction: true` and a `set` change that names the step by `item_id`, on any node, finished or not. The step keeps its id, so records that point at it stay valid. Steps and criteria can be inserted, removed and reordered; stable ids keep every reference valid (`stored-schema.md`, `Stable identity`). +- **Status moves, progress, comments and state marks never produce an amendment (I5)** on an unfinished node. Setting `met` is a state change like a move, and writes a mark record. +- **Reversal.** A move out of `done` to `ongoing`, `paused` or `cancelled` needs a reason and is recorded in history with `correction: true`. Steps and gates stay as recorded. `done → planned` stays refused. +- **Directories follow their derived status.** An edit of the content of a directory (or the campaign root) whose derived status is `done` or `cancelled` is a correction. A directory in any other derived status takes edits with an amendment note. Adding or removing a child is a structure edit of the child, not a correction of the directory. +- **Criteria gate the moves.** `done` needs I8 and every gate `met`; the start needs every pre-condition `met` (see `Criteria`). A directory is `done` only when its leaves are finished and its own gates are met. A reversal out of `done` ignores both: the leaf is already past them. +- **Structure edits on finished nodes.** Deleting a `done` or `cancelled` leaf keeps its acknowledgement (I9) and its snapshot in the amendment. Moving a finished leaf changes no content. Whether a move that changes the ready set of other leaves needs the acknowledgement is left to M2's impact analysis. + +## Legacy mapping + +For the importer (M3). Counts are from `__roadmap__/` at the date of this document. + +| Legacy status | New status | Reason and provenance | In real campaigns | +|:--|:--|:--|:--| +| `planned` | `planned` | Same meaning | 26 rows | +| `inprogress` | `ongoing` | Rename | 4 rows, all in campaigns being planned now | +| `done` | `done` | Same meaning. Legacy `done` was "immutable; reopen via a new amendment node"; a `done` node can now be corrected or reversed with a reason | 65 rows | +| `blocked` | `cancelled` | The legacy skill defined `blocked` as terminal within a campaign, never auto-resolved, which is how it was used to abandon work. The legacy file holds no reason, so the importer writes `status_reason: "imported from legacy status blocked"` and warns | 0 rows | +| `amendment` | `planned` | Legacy `amendment` was the initial status of a node added by an amendment, never a state an existing node moved to. The provenance stays in the amendment: the importer writes the `A` row as an amendment (`legacy_id`) with a change `op: add` for each filename in its "Nodes Added" cell | 0 rows. The one node added by an amendment (`hub_mode_reconciliation.md`, A1) is `done` | + +Legacy files carry no timestamps and no history of moves. The importer writes no history entries: +the status is set directly and `history` starts empty. + +## R01 deltas + +For `r01_sync`. R01 is not edited by this leaf. + +| R01 location | Change | +|:--|:--| +| §Graph operations, Status FSM diagram | Replace with the five-status machine of `Transitions`: `planned → ongoing, paused, cancelled`; `ongoing → paused, cancelled, done`; `paused → planned, ongoing, cancelled`; `cancelled → planned, ongoing, paused, done` (only the pre-cancel status); `done → ongoing, paused, cancelled` (reversals with a reason). Remove `blocked`, `amendment` and the `done → amendment` edge | +| §Graph operations, Order | "not done" becomes "`planned`"; "every leaf of smaller depth is done" becomes "`done` or `cancelled`". The ready rule becomes the scoped rule of `Ready set`. The sentence "Wave semantics are global: a leaf also waits for shallower leaves in unrelated branches" is replaced: a leaf waits only for shallower leaves under its own ancestors' parents. "Waves" stay a display of depth (`level`), not a readiness fact | +| §Graph operations, after the FSM | "Starting a leaf outside the ready set is refused unless an override with a reason is given" stays. Add the directory pause and cancel operation and the derivation table | +| §Graph operations, Impact analysis | "done work reopened" stays, now for a reversal out of `done`. Add "leaves made ready by a cancel" | +| §Contracts, I5 | Add: comments (separate append-only files) and state marks never produce an amendment. A content edit of a finished node needs a reason and is a correction | +| §Contracts, I8 | Keep I8. Add: `done` also needs every success gate `met`, and the start needs every pre-condition `met`; every mark is traced | +| §Contracts, I9 | "Deleting or reopening done work, or moving work in progress, needs an explicit acknowledgement" becomes "Deleting finished work, or moving work in progress, needs an explicit acknowledgement. Reopening done work needs a reason and is counted as a correction" | +| §Data Model, schema sketch | criteria carry an `id` and `met`, with mark records (`criterion_id`, `correction?`) in `marks`; `blocked_reason?` becomes `status_reason?`; history `note?` becomes `reason?`; comments are not a node field: they are files `_comments/.json` (details in stored-schema.md), so the §Data Model tree gains `_comments/` | +| §Concurrency, last bullet | "records `inprogress`" becomes "records `ongoing`" | +| §Graph operations, after the FSM | Add a directory `uncancel` through the `op_id` of the cancel | +| §Key Flows, Execute | `inprogress` becomes `ongoing` | +| §Alternatives Considered, Mutation policy | "full CRUD with guards on done work" is now "full CRUD, finished nodes edited with a reason" | + +## Decisions + +Nothing is open. Who decided what: + +| # | Decision | Decided | +|:--|:--|:--| +| 1 | Ready rule: an unfinished leaf holds back only the deeper leaves under its own parent (legacy rule). Applies to `planned`, `ongoing` and `paused` alike | Eliott, 2026-11-16 | +| 2 | Comments are one file each, `_comments/.json`, append-only | Eliott, 2026-11-16 | +| 3 | A mistaken cancel can be undone with a required reason; `done` stays the normal end state | Eliott, 2026-11-16 | +| 4 | `paused → planned` needs no step recorded done | coordinator, 2026-11-16 | +| 5 | A mistyped `commit_sha` or a wrongly recorded step is corrected by an amendment with a reason and `correction: true` (replaces the earlier permanent `commit_sha` and the recorded objection) | Eliott, 2026-11-16 | +| 6 | Undoing a cancel restores the status the node had just before the cancel, read from history, with a required reason: `planned`, `ongoing` or `paused`. A directory undo restores each leaf through the cancel's `op_id`. `done` is reversible with a reason (row 9). Replaces the earlier `cancelled → planned` only form and closes its gap (coordinator, 2026-11-16) | coordinator, 2026-11-16 | +| 7 | Criteria are enforced: `planned → ongoing` needs every pre-condition `met` (override included), `ongoing → done` needs every success gate `met` plus I8, and a directory is `done` only when its leaves are finished and its own gates are met. Every mark leaves a mark record (`ts`, `actor`, kind, index, value, `evidence?`). Legacy done leaves with open gates are imported as they are and reported by `validate`. Reverses the earlier rule that gate marks do not gate `done` | Eliott, 2026-11-16 | +| 8 | Reconciling a legacy done leaf's open gate is an ordinary reasoned mark (`reason` or `evidence`, `correction: true`). Closes the earlier open defect | Eliott, 2026-11-16 | +| 9 | Sealing becomes a reason requirement. `done` and `cancelled` nodes accept every edit (content as an amendment, marks as mark records, a recorded step as a correction amendment) and status reversals out of `done` (to `ongoing`, `paused`, `cancelled`), each with a non-blank reason and flagged `correction: true`. Unfinished nodes are unchanged. Replaces "sealed", "terminal" and "nothing reopens done work" | Eliott, 2026-11-16 | +| 10 | The count of corrections is data: the node detail carries a derived `correction_count`, never stored | Eliott, 2026-11-16 | +| 11 | A cancel made by a reversal out of `done` can be undone back to `done`, with a reason, so the undo rule has no dead end | coordinator, 2026-11-16 (gap closed, flagged) | diff --git a/__design__/rdm/store.md b/__design__/rdm/store.md new file mode 100644 index 0000000..d8df9bb --- /dev/null +++ b/__design__/rdm/store.md @@ -0,0 +1,526 @@ +# rdm — Store + +How a campaign lives on disk and how it is read, written, recovered and cached. It replaces +R01's `§Concurrency` (lock, staging, journal) and the "names are paths" layout of `§Data Model` +(`architecture.md`), under the rulings of the A2 gap analysis (2026-11-25). + +What this document owns: the on-disk layout, the id string format and minting, the order key, `rev` +and `tree_rev`, the writer lock and its holder record, the write order of each primitive, the +intent and recovery, durability, cache revalidation and Windows. What it does not own, and only +references: the Rust types, the id newtypes and the record inventory, the operation requests and +results, the error type, declared links, `MOVES` and the version chain, all in +[contracts.md](contracts.md). Errors are named by their variant (`Stale { current }`, +`Locked { holder }`, `NewerFormat { found, supported }`, `Invalid`). The stored fields are in +[stored-schema.md](stored-schema.md), the meaning of `rev` and `tree_rev` for consumers in +[read-model.md](read-model.md). + +Rulings this document builds on and does not reopen: flat `nodes/.json` holding `name`, +`parent_id` and an order key, depth computed from `parent_id`; readers take no lock; Rust types are +the contract and JSON is derived; a file newer than the binary is refused with `NewerFormat` (any higher part of the `0.X.Y` triple); +declared links; tracked data stays text; the cache is write-through, revalidated on every read, +never the source of truth. + +Where a claim is this design's own and not a source's, it says so. Guard names are those of the +[campaign README](../../__roadmap__/m1-core-foundation/README.md). + +## Layout + +``` +__roadmap__// + nodes/.json every node: the campaign root, directories and leaves (tracked) + _amendments/.json one file per amendment, append-only (tracked) + _comments/.json one file per comment, append-only (tracked) + .rdm/ untracked, created by the store + .gitignore holds `*`, so the repository's own .gitignore needs no entry + lock the writer lock; empty, never read or written + holder.json advisory record of the lock holder + tmp/ files being written, before they are published + intent/.json redo records of operations in flight + cache/ optional persisted cache (the hot_cache leaf decides if any) +``` + +A node is one file, whatever its kind. The tree is not in the file system: a node's place is its +`parent_id`, its place among siblings its order key. + +| Stored in the node file | Rule | +|:--|:--| +| `name` | `^[a-z][a-z0-9_-]*$`, unique among the children of one parent. On the root it is the campaign slug, which `open` is given by its caller: the root is the parentless node with that name | +| `parent_id` | The `id` of the parent node. Absent on the root and only there | +| `order` | The sibling order key (Order key). Every node but the root has one; the root has none | + +| Derived on every read, never stored | From | +|:--|:--| +| Path (`a/b/c`) | The `name`s along the `parent_id` chain | +| Depth (`level`) | The length of that chain: the one ordering rule, I1 | +| Order of siblings | `(order, id)`, both compared bytewise, ascending | + +**What the loader reads.** In `nodes/` only entries named `n_` followed by eight characters of the id +alphabet and `.json`; in `_amendments/` and `_comments/` only 26-character ULIDs and `.json`. Other +names are ignored, so an editor's backup file or a stray temporary cannot be loaded as a node. The +store's own temporary files are not in these directories at all: they live in `.rdm/tmp/`. That keeps +them out of `git status` as well, and `nodes/` changes only when a node is published. + +**Why this layout.** Each fact a writer changes is one small file, so git merges two branches that +edit different nodes without a conflict, and a rename, a move or an insert among siblings writes +one file. No directory is ever renamed, so R01's risk "directory renames fail on Windows while a +handle is open" disappears. A path is `nodes/n_xxxxxxxx.json` below the campaign directory +whatever the depth of the tree, so the Windows 260-character limit no longer depends on nesting. +A node's `name` can be any valid slug, including `con` or `nul`, because it is no longer a file name. + +**Faults and merge damage: report, do not refuse.** Git merges files, not the invariants between +them, so a merge can leave a campaign that no single writer would have produced. The rule of `open` +(R3 of Eliott's review, 2026-11-25) separates two classes. + +- **Per-file faults fail `open`**, naming the file: an unparsable file, a malformed id, `file_id_mismatch`, a file newer than the binary (`NewerFormat`). One file cannot be loaded, so nothing can be said of the campaign. +- **Cross-file merge damage is loaded and reported loudly**, as one diagnostic per defect naming the file or files and the rule. The rule codes are contracts.md's. + +| Defect | Rule | Produced by | +|:--|:--|:--| +| A `parent_id` naming no node (orphan) | `parent_missing` | One branch deletes a node while another adds or moves a child under it | +| A `parent_id` naming a leaf | `parent_not_directory` | One branch replaces a directory by a leaf of the same id while another adds a child under it | +| A cycle in the `parent_id` chain | `cycle` | Two branches each move one of two nodes under the other | +| No parentless node carries the slug `open` was given, or more than one does | `root_count` | A merge of unrelated histories | +| A parentless node whose `name` is not the slug | `root_name_mismatch` | A campaign directory renamed by hand; the repair is a rename of the root through the store | +| Two siblings with one `name` | `name_collision` | Two branches each add a node of that name under one parent. The two files differ, so git sees no conflict | +| Two files with one id, across files | `duplicate_id` | Minting collided across branches: the same path, so git reports an add/add conflict, but a hand-copied file passes unseen | + +**The anchor.** The root is the node without `parent_id` whose `name` equals the slug the caller gave +`open`. Nodes reachable from it by `parent_id` are **validated**; everything else (an orphan, a cycle, a +second parentless node, a root whose name does not match) is loaded but **unvalidated**. A campaign +with damage is therefore readable, which is what a person repairing it needs. + +**What a write may build on.** A write that builds on an unvalidated node (it names one, or places +something under it) is refused with `Invalid`, rule `unvalidated_node`. A repair write is +allowed: relocating a node into the validated tree, renaming a colliding sibling or the root, or deleting. +A comment is allowed too: it is append-only and points at the id, not the position (contracts.md §Campaign model). The +check sits in step 3 of the write algorithm, under the lock, on the files as they are then. + +These are consequences of the flat-layout ruling, not objections to it. Guarded by +`open_names_invalid_campaigns` (S20) and `requests_breaking_a_rule_are_refused` (S22). + +## Order key + +**Technique:** fractional indexing (Figma; Greenspan's midpoint algorithm as in +`rocicorp/fractional-indexing`), in the form below. What the sources support: Sources. + +- **Alphabet.** The 62 digits `0-9A-Za-z`, in ascending ASCII order, value = position. A key is a non-empty string of digits that does not end in `0`, read as a base-62 fraction between 0 and 1. Keys compare with plain bytewise comparison, never locale order. `validate` rejects any other string. +- **A first key** is `V`, the middle digit. +- **A key between `a` and `b`** (`a < b`; `none` stands for 0 as a lower bound and for 1 as an upper bound): + 1. Strip the common prefix (`a` is read as padded with `0`), apply the rules below to what is left, and put the prefix back. + 2. If the first digits differ by more than one, take the middle digit (rounded down). + 3. If they are adjacent and `b` has more than one digit, take `b`'s first digit alone: it lies between because `b` has a non-zero tail. + 4. Otherwise take `a`'s first digit followed by a key between the rest of `a` and `none`. + + | between `a` and `b` | key | + |:--|:--| + | `none`, `none` | `V` | + | `V`, `none` | `k` | + | `none`, `V` | `F` | + | `V`, `o` | `e` | + | `V`, `W` | `VV` | + | `V`, `VV` | `VF` | +- **An insert** between neighbours `a` and `b` writes one file, the inserted node, and nothing else. Two branches that insert at the same spot produce equal keys; the order is then `(order, id)`, so every reader agrees without jitter, and jitter would only lengthen keys. The root has no key. +- **Length stays short.** Each insert into one gap halves it, so a run of inserts at one spot, or appends at the end, adds about one character per six inserts. Measured on a model of this algorithm: after 10, 50, 100 and 200 appends the key is 2, 9, 17 and 34 characters; after 200 inserts at one spot, 41. Bulk creation (an import, the 160-node benchmark) uses the recursive form that places `n` keys at once: 160 keys are at most 2 characters, and so are 1 000. +- **Rebalance.** A key longer than 24 characters (about 130 inserts at one spot, far beyond the size of a directory in a real campaign) makes the insert rebalance its siblings: the same operation rewrites all `n` order keys evenly with the bulk form, as one batch, and its amendment records each as a `set` of `/order`. This rule is this design's own; neither source names one. Only the nodes whose key changes get a new `rev`. +- Guarded by `order_keys_sort_strictly_between_their_bounds` (a property test over random bounds, in `campaign_store`). + +Sibling order is therefore stored. This supersedes the line of `read-model.md` that says siblings have +no stored order and are listed by `level`, leaves before directories, then `path` (reported as a finding). + +## Ids + +| Kind | Prefix | Body | Example | Unique within | +|:--|:--|:--|:--|:--| +| Node (root, directory, leaf) | `n_` | 8 characters | `n_7k3q9x2m` | the campaign (its file name) | +| Criterion | `c_` | 6 characters | `c_8m2xqv` | its node file | +| Step | `s_` | 6 characters | `s_0f4tzn` | its node file | +| Amendment, comment | none | a ULID, 26 characters | `01J9ZQ3M8R5K7V2N4X6Y8A0B1C` | the campaign; the ULID is the order | + +Checks and references carry no id under the proposed inventory (`contracts.md` fixes the inventory; +the table gains one row per kind that gets an id). + +- **Alphabet.** Crockford base32 in lower case, `0123456789abcdefghjkmnpqrstvwxyz`: no `i`, `l`, `o` or `u`, so no id is misread as a number. Lower case because the default macOS and Windows file systems are case-insensitive and a node's id is its file name; mixed-case ids could collide there and not on Linux. The ULIDs of amendments and comments stay in the canonical upper case that the stored schema already fixes; their order is time order. +- **Why random.** A counter collides across worktrees (two branches mint `n_0042`). A hash of content changes with the content, and I7 says an id never changes. A UUID is 36 characters for no gain. A random body needs no coordination. +- **Why this length.** Eight characters are 40 bits. With 2 000 nodes present, a new mint collides with probability 2 000 / 2^40 = 1.8e-9. Two branches that each mint 500 ids share one with probability about 500^2 / 2^40 = 2.3e-7, and that case is loud, not silent: the same id is the same path, which git reports as an add/add conflict. Six characters (30 bits) suffice for sub-items, which only have to be unique inside one file of a few dozen of them: 50 / 2^30 = 4.7e-8 per mint. +- **Minting.** The caller mints ids, outside the lock, with the engine's minter (contracts.md); the store never mints a node, criterion or step id, which is what lets a batch name a node it creates and a retried request carry the same ids. The minter draws the body from an RNG injected at construction (seeded in tests, the operating system's generator otherwise). Each character takes five bits of a random byte, which is exactly uniform because 256 is a multiple of 32. It checks the candidate against the ids its caller can see: the campaign as last read, and the ids the same batch has already minted. On a collision it draws again; after 32 collisions in a row it fails (a real generator never gets there, and a test generator that always collides must still end). Guarded by `minting_retries_on_collision`. +- **The store refuses a collision it finds.** Between the caller's read and the write, another process can have created the same id. Under the lock the store checks every id the request introduces against the disk and refuses a collision with `Invalid`, rule `duplicate_id`; the caller mints again and retries. Guarded by `open_names_invalid_campaigns` for the across-files case; the store's own refusal under the lock has no separate guard (S8). +- **Never reused.** The check sees live ids only. A deleted node's id could be minted again with probability under 2e-9 per mint, and a reference to the deleted id would then resolve to the new node instead of the amendment's snapshot. This residual risk is accepted and not tested: scanning every amendment on each mint would cost more than the risk is worth. + +## Revisions + +| | Definition | +|:--|:--| +| `rev` of a node | The first 16 hexadecimal characters (64 bits) of SHA-256 over the canonical encoding of the node as decoded, with `schema_version` left out | +| `tree_rev` | The first 16 hexadecimal characters of SHA-256 over the text `rdm-tree\n` followed by one line ` \n` per node, in ascending bytewise order of `id` | +| `SubtreeRev` | The same form with its own domain prefix `rdm-subtree\n`, over the ` \n` lines of a node and all its descendants, sorted by `id`. It is `DeleteOp.expected_subtree_rev` | + +- **What `rev` counts:** every field of the node file in canonical order, including `name`, `parent_id` and `order`, and the unknown fields the file carries (I12), in their order. Not counted: the file's bytes (whitespace, CRLF, `\u` escapes), its mtime, the `schema_version` stamp, amendments and comments. The hash is taken over what the serialiser would write for the decoded value, so a whitespace-only edit keeps the `rev` and a change of any value changes it. A number keeps its JSON form where no type fixes it: a typed integer field refuses `1e5`, while in an unknown key `1e5` re-encodes as `100000.0` and so has another `rev` than `100000` (I12 keeps unknown values as written, so they are not normalised). Guarded by `rev_tracks_value_not_formatting`. +- **`SubtreeRev`** changes when any node in the subtree is created, removed, moved into or out of it, or edited. A move of the subtree's root changes that node's `rev` and so its `SubtreeRev`; the subtree's descendants keep their `rev`s. The distinct prefix keeps a subtree whose lines happen to equal the whole campaign's from sharing its `tree_rev`. +- **Consequences.** A move changes the `rev` of the moved node only: its children keep theirs because they name their parent by id. A comment or an amendment changes no `rev` and not the `tree_rev`, because `tree_rev` covers `nodes/` only. Creating, deleting, moving or editing any node, a status move included, changes `tree_rev`. It is deliberately coarse: a batch that presents `expected_tree_rev` is refused when any node changed anywhere, which is what a structural batch wants and a field edit does not use. Guarded by `tree_rev_changes_on_node_ops_not_comments`. +- **Why SHA-256.** It is a published function with an independent implementation in every language, so another tool (the importer, a CI script) can recompute a `rev` from a file. It needs no C build (`blake3` compiles C and assembly by default and declares an MSRV of exactly 1.88). A node is a few kilobytes, so speed does not matter, and an unchanged node is not re-hashed (see Cache). +- **Why 64 bits.** `rev` is compared only with the value the same node had when the caller read it. A different value with the same `rev` would let one stale write through, with probability 2^-64. Sixteen characters keep the opaque string short in every tool output. It is not a security boundary. +- **A function of the value and of the current types.** The decoder upgrades an older file through the version chain before the encoder runs, so one old file read by two binaries with different layers can have two `rev`s. A consumer compares `rev`s it got from one server, and the `rev` of an unmodified file is stable for a given binary. +- **Opaque to consumers** (`read-model.md`): they send it back as `expected_rev` and never parse it. + +## Reads + +Readers take no lock and write nothing (I11). + +1. List `nodes/` and read every matching file whole (the cache turns this into a revalidation, see Cache). +2. Decode each file through the version chain. A file whose `schema_version` is newer than the binary's, whether the higher part is X or Y of `0.X.Y` (the whole triple is compared), fails with `NewerFormat { found, supported, .. }` before anything else in it is parsed. +3. A key the decoder does not know is kept in place (I12) and produces a warning, a `Diagnostic` naming the file and the key path with the rule `unknown_key` (the type is contracts.md's). A read reports the diagnostics of the files it read. +4. Faults and cross-file damage follow the rule of Layout: per-file faults fail `open`; merge damage is loaded and reported with its diagnostics. + +**Technique:** publish by rename (Maildir delivery, Sources). Every file a writer publishes is written +completely under another name first and then renamed into place, so a reader opening a path gets the +old file or the new one, never a torn one. Guarded by `reader_sees_old_or_new_never_partial`. + +What a reader is **not** given is a snapshot across files. During a multi-file operation it can read +some files before and some after. The write order below makes every such mixture a valid campaign +(no node names a missing parent, no later step is needed to make the files parse), and that is all it +promises: the guard is "every prefix loads" (`every_write_prefix_loads_and_recovers_to_pre_or_post`), +not isolation. A reader never recovers a crashed operation; recovery belongs to the next writer. +`rev` and `tree_rev` come from the files actually read, so a mixture yields a `tree_rev` that no +committed state has. A write that presents it is judged under the lock against the files as they are +then (Write algorithm), so such a read cannot cause a lost update. + +A file an external program is rewriting in place (an editor that truncates, then writes) can be read +half-written. That is a decode failure of that one file, reported for it and not cached, and the next +read tries again. The store's own writes never do this. + +## Lock + +**Technique:** one advisory whole-file lock per campaign on `.rdm/lock`, taken with the `fs4` crate +(Probe answers), held for the write window only: from before recovery to after the cache update. +The kernel releases it when the process dies, so no stale lock exists. Readers never touch it. + +- **Acquire.** `try_lock`, repeated with a back-off that starts at 5 ms and doubles to 50 ms, until a timeout of 5 seconds. A write takes milliseconds, so five seconds is three orders of magnitude of contention. At the timeout the operation fails with `Locked { holder }` and has changed nothing. The timeout and back-off are store options; the numbers here are the defaults. +- **In-process.** A second open of the lock file in the same process is also refused (probed on macOS), so two threads or two server tasks of one process are serialised by the same mechanism. +- **Holder record.** After acquiring the lock the writer replaces `.rdm/holder.json` with `{pid, host, since}` (process id, host name, UTC instant of the acquisition: contracts.md's `LockHolder`). It is removed before the lock is released. It is advisory only: it fills `Locked { holder }` so the caller can say who is writing, and nothing ever decides by it. It can lag by one writer (a waiter may read the previous holder's record in the instant before the new one is written), name a dead process after a kill (the next holder overwrites it), and a process id means nothing across hosts. +- **Why a separate file.** On Windows an exclusive `LockFileEx` region denies other processes read as well as write access to it, and `fs4` locks the whole file there (its source passes the maximum length). A holder record inside the lock file would be unreadable by exactly the process that needs it. Hence the lock file stays empty and is never read or written. Verified from the Microsoft documentation of `LockFileEx`; `second_writer_gets_locked_with_holder` runs on Windows in CI. +- **A missing, truncated or garbage holder record** never blocks or fails the lock: it is only read to fill the error, and a record that does not parse is reported as an unknown holder. Guarded by `garbage_holder_record_does_not_break_locking`. +- **A killed holder.** The lock is free as soon as the kernel has released it, which `lock_survives_holder_kill` shows on all three systems. On Windows the documentation says the release after a process ends "depends upon available system resources", so a waiter must expect a short delay, which the five-second timeout covers. +- **Not covered.** A campaign on a network file system (NFS, SMB), where advisory locks are unreliable, is out of scope. Worktrees are separate copies of the files, so their locks are independent (R01 said the same); git reconciles them. + +Guarded by `second_writer_gets_locked_with_holder` and `lock_survives_holder_kill`. + +## Write order + +### The write algorithm + +Every primitive runs these steps; the table below gives step 5 per primitive. + +1. Take the lock (Lock). +2. Recover: if `.rdm/intent/` or `.rdm/tmp/` holds anything, run Intent and recovery first. +3. Under the lock, in this order: + 1. **Replay.** If the request carries an `op_id` and the op index finds a record that carries it (Cache), write nothing and return the first outcome with `replayed: true`. The check and the write are one critical section, which is why the store, not M2, owns it. Guarded by `replayed_op_id_writes_nothing`. + 2. Read the files the operation touches **from disk**, not from the cache: the nodes the request names, their parents, and a deleted subtree, read again until the set is closed; a sibling the plan rewrites (an order-key rebalance) is read before it is written, and the plan is recomputed if it differed. Check `expected_rev`, `expected_subtree_rev` and `expected_tree_rev` where given. On a mismatch release the lock and return `Stale { current }`; nothing has been written. This makes a stale write harmless whatever any cache or earlier read held. Guarded by `stale_replace_changes_nothing`. + 3. Check the structure: sibling `name` unique, no cycle, the parent exists and is a directory, and every id the request introduces is absent from the disk (`duplicate_id`). + 4. **Unvalidated nodes.** If the request builds on a node that is not reachable from the root, refuse it with `Invalid` unless it is a repair (relocate it into the validated tree, rename a colliding sibling, delete). Guarded by `open_names_invalid_campaigns`. +4. Compute every after-image, mint the amendment's ULID (the only id the store mints), build the amendment. +5. Apply (table). +6. Update the cache from the written values (Cache), and remove `holder.json`. +7. Release the lock, then return. A write is acknowledged only by returning `Ok`, after step 5 is complete under the durability tier in force. + +The `op_id` replay rule, what it returns and its limits are in `contracts.md`; the check sits in step 3.1 and reads the op index of the Cache section. + +### The three rules + +**Technique:** Soft Updates ordering rules (McKusick and Ganger, Sources), applied to files instead +of disk blocks. In this store the only pointers are `parent_id` (child to parent), a `node_id`, `item_id` +or `Reference.node_id` held by a comment, an amendment or another node, and an id inside a `Mark`. + +| Rule | Applied as | +|:--|:--| +| 1. Never point to a structure before it is initialised | Created nodes are written before anything that names them: the parents of a batch before their children, and every node before the amendment that lists it and before a node that was edited to point at it | +| 2. Never re-use a resource before nullifying every earlier pointer to it | Ids are never reused (Ids), so no pointer can come to name a different thing. Before a node is removed, the nodes that pointed at it as their parent are removed first (deepest first) or re-pointed first (edits come before deletes), so no intermediate state has an orphan | +| 3. Never reset the last pointer to a live resource before the new pointer is set | Replacing a file is one rename, so the name never points at nothing. A removed subtree is first copied into the amendment's `snapshot`, which is written and durable before the first unlink: the snapshot is the new pointer to the data | + +The apply order that follows from the rules, for any operation: **(a) creates, parents first; (b) +replaces; (c) the amendment; (d) deletes, deepest first.** The amendment sits after the replaces so +that an amendment never claims an edit that has not happened; the only exception the rules force is +a delete, whose before-image must precede the unlink. + +### Effects + +Notation. `I`: publish the intent record `.rdm/intent/.json` (written under `.rdm/tmp/`, +synced, renamed into place). `put X`: write the new bytes under `.rdm/tmp/`, sync them, rename over +`X`. `create X`: the same, but publish with `link()` and then unlink the temporary name, so it fails +if `X` exists instead of replacing it. `del X`: unlink. `N`, `A`, `C`: a node, an amendment, a comment. +After the last effect of an operation with an intent: sync every touched directory, remove `I`, sync +`.rdm/intent/`. `pre` and `post` are the states before and after the operation. + +| Primitive | Ordered file effects | A reader sees after each prefix | Recovery from each prefix | +|:--|:--|:--|:--| +| **Replace**, no amendment (a status move, progress, a criterion mark; one node) | `put N` | Before the rename: `pre`. After it: `post` | Nothing to recover: stray temp file removed | +| **Replace**, content edit | `I`, `put N`, `create A` | After `I`: `pre`. After `put N`: new `N`, no amendment yet. After `create A`: `post` | Any prefix after `I`: redo what is missing, giving `post`. Before `I` completes: `pre` | +| **Create** a node | `I`, `create N`, `create A` | After `I`: `pre`. After `create N`: the node exists without its amendment. After `create A`: `post` | As above | +| **Move or rename** | `I`, `put N` (new `parent_id`, `name`, `order`), `create A` | After `put N`: the node at its new place, no amendment yet. No other node file changes | As above | +| **Delete a subtree** of `k` nodes | `I`, `create A` (with the `snapshot`), `del N_k` to `del N_1` (deepest first, the subtree's root last) | After `create A`: the amendment, every node still present. After `j` deletes: a smaller subtree, a valid campaign (no orphan). The deletes are ordered by depth along the `parent_id` chain **on disk before the write**, not in the tree the operation leaves, so a node a batch moved between two deleted subtrees is never left hanging from a deleted parent. One exception: deleting a node on a `parent_id` cycle leaves the members not yet deleted with `parent_missing`, whatever the order, because a cycle has no deepest member; this is damage the cycle already held, and recovery removes it | As above: redo the remaining deletes. A `del` of a missing file is skipped | +| **Comment** | `create C` | Before the link: `pre`. After it: `post` | Nothing to recover | +| **Batch** (any mix of the above) | `I`, creates (parents first), puts, `create A` (one amendment, all its changes), deletes (deepest first) | After each effect, the prefix of that order | As above | +| **Batch with no amendment** (a directory pause or cancel: several leaves, one `op_id`) | `I`, puts | After `j` puts: `j` of the leaves moved | As above: redo the rest | + +Notes on the table: + +- A comment never changes a node file, so it changes no `rev`; creating its file needs no intent. +- A move writes one node file and one amendment. `move_writes_one_file_and_keeps_ids` counts files under `nodes/` only (the amendment is written besides, in `_amendments/`): exactly one node file is written and no id changes. +- Every operation that writes two or more files publishes the intent first. A prefix without an intent would be valid for readers, but nothing would complete it: an edit with no amendment, or an amendment for an edit never made. The intent is what turns "every prefix loads" into "every prefix recovers to `pre` or `post`". +- Before `I` is renamed into place the operation has done nothing a reader can see (only temporary files in `.rdm/tmp/`). The rename of `I` is the commit point of a multi-file operation; the rename of the node file is that of a single-file one. +- Guarded by `every_write_prefix_loads_and_recovers_to_pre_or_post`, which cuts each operation after every one of these effects, including the effects inside `I`, and by `killed_workers_lose_no_acknowledged_write`. + +### Alternatives considered + +| Alternative | Why not | +|:--|:--| +| R01's staged journal: stage files, write a journal of steps, mark it committed, apply | The same idea with two phases. The intent here is one record and one rename, with whole-file after-images, so the commit point is one atomic step and recovery has no "uncommitted" case to discard | +| Copy the campaign, edit the copy, swap the directory | Costs a write of the whole campaign per edit, renames a directory (the Windows hazard the flat layout removed), and breaks every reader that holds a path | +| A database (SQLite in WAL mode) | Tracked data stays text (ruling): a binary file neither merges per node nor shows in a pull request | +| An append-only operation log as the source of truth | Same ruling, and it makes every reader replay | + +## Intent and recovery + +**Technique:** a redo-only record written before the data (write-ahead logging, ARIES, Sources), in +the form of whole-file after-images, so redo is idempotent by construction. ARIES has no such +"intent" record; this is this design's own application of the log-before-data and repeat-history +ideas, simplified to one record per operation and no undo, because a stale or failed operation has +written nothing before its intent. + +**The intent record** (untracked, `.rdm/intent/.json`): the format version of the record itself +(an unknown newer one is refused with `NewerFormat`), and the ordered list of effects of step 5: +for each, its action (`put`, `create` or `del`), its path relative to the campaign, and for `put` and +`create` the full new bytes as text. The record is complete before it is published, so a reader of +`.rdm/intent/` never sees a partial one. It holds the amendment's bytes too: **the amendment cannot +serve as the intent**, which the leaf proposed, because a stored `Change` carries no after-image of an +added node and only a field-level `old` and `new` for an edit, and because an old amendment +and a crashed one look alike (a delete's amendment, replayed after a later restore, would delete +the restored node again). See the findings in the leaf report. + +**Recovery** runs under the lock on every acquisition, before the operation's own work. It costs +two directory listings when there is nothing to do. + +1. Remove everything in `.rdm/tmp/`: stray temporary files of killed writers. +2. For each record in `.rdm/intent/`, oldest ULID first, redo its effects in order: + - `put`: if the destination already holds exactly these bytes, skip it; otherwise write it as a put. + - `create`: if the destination holds exactly these bytes, skip it. If it holds other bytes the file was made by something else (a checkout, a merge) after the crash: stop, leave the record, and fail with `Invalid` naming the file. A create never overwrites. + - `del`: unlink; a file already gone is skipped. +3. Sync the touched directories, remove the record, sync `.rdm/intent/`. +4. A record that does not decode (a power-loss artefact under the weak durability tier) is removed and reported; the ordering rules above mean the files it was meant to complete form a valid prefix anyway. A record decodes only if every path is relative, has no `..` component and lies under `nodes/`, `_amendments/` or `_comments/`: recovery never touches a file outside the campaign's records. + +"Reported" holds on every path that runs recovery: `recover()` returns the report, and a write that +ran recovery first keeps it on the store, where `last_recovered()` returns it until the next recovery. + +Recovery is itself restartable: every step is idempotent, so a kill during recovery is repaired by +the next recovery. Not tested by a named guard (see Invariants and guards). + +**Why whole-file puts rather than patches.** A `put` of a given file is idempotent whatever the file +holds, so redo needs no log sequence number and no comparison of versions (ARIES needs the page LSN +for that). The price is size: an intent holds each file it writes once more, in untracked, deleted-at-commit storage. A +160-node import is about 0.5 to 1 MB for a moment. + + +- **A newer intent record.** The intent format is one integer (`INTENT_FORMAT`). A record whose + format is higher refuses the write with `NewerFormat`, reported as `found = (0, n, 0)` and + `supported = (0, INTENT_FORMAT, 0)`, so one error type covers both kinds of newer file. + +## Durability + +Three tiers, chosen when the store is opened. The default is `Fsync`. + +| Tier | What each publish does | A process kill (`SIGKILL`, a crash, a panic) | An operating-system crash or power loss | +|:--|:--|:--|:--| +| `Process` | No sync. The rename and the intent still give the ordering | Every acknowledged write survives: the data is in the kernel's cache, which a kill does not discard | The last seconds can be lost, and the disk may have written files out of order, so even the prefixes are not promised | +| `Fsync` (default) | Sync every temporary file before it is published; after the renames, sync each touched directory; the intent, its directory, and the removal of the intent likewise | Same | Writes whose sync returned survive on Linux and Windows file systems that honour it. On macOS this tier is plain `fsync(2)`, whose manual describes `F_FULLFSYNC` as the call that asks the drive to flush its cache, so the last writes can still be lost in a power cut, but the intent plus the ordering rules (each prefix valid, the intent redone) still bound the damage to "pre or post" as long as the drive keeps its own writes in order | +| `Full` | As `Fsync`, with `F_FULLFSYNC` on macOS (the drive flushes its cache). Equal to `Fsync` elsewhere | Same | Survives on macOS as it does elsewhere. About 65 times the cost of a plain publish (probe: 5 ms to 10 ms per file and directory against 0.16 ms) | + +- **The standard library's `sync_all` is the `Full` tier on macOS**: measured 4.9 ms median, the same as `F_FULLFSYNC`, because std issues `F_FULLFSYNC` there. The `Fsync` tier therefore calls `fsync(2)` itself (through `rustix`, already in the tree through `fs4`) on macOS, and `sync_all` everywhere else. +- **Directory sync** is not possible on Windows through the standard library and is skipped there: the rename is then left to the file system's own metadata journal (an assumption of this design, not a sourced claim). This is the weakest point of the Windows tier and is stated, not tested. +- **Why `Fsync` as the default for a git-tracked store.** What a power cut can cost is the last acknowledged writes, not the history: committed work is in git, and uncommitted work in a worktree has the same exposure as every source file beside it. A plain `fsync` costs a measured 0.16 ms per file and directory, so an edit (an intent, a node, an amendment and three directories) costs about a millisecond; `F_FULLFSYNC` would cost about 30 ms per edit and 1.6 seconds for a 160-node import, which an agent doing many small edits would feel. `Full` stays available for a user who wants it. +- **What a process kill guarantees is the contract the tests hold** (`killed_workers_lose_no_acknowledged_write`). Power loss is not tested: it needs a file system that injects reordering, which this campaign does not build (README, "Deliberately not tested"). The argument above is the evidence, and it rests on the Soft Updates ordering and the ALICE observation that rename ordering and directory durability vary between file systems, which is why `Fsync` syncs both. + +## Cache + +The long-lived server keeps the decoded campaign in memory. It is a cache: other processes (another +worktree's server, the CLI, an editor, `git checkout`) change the files under it, so it is +revalidated against the files on every read, writes go straight through to the files, and it is +never the source of truth. A writer never trusts it for the files it touches: step 3 of the write +algorithm reads those files from disk under the lock, so a stale cache cannot cause a lost update, +only a stale read, and only in the one case named below. The other files a write depends on +(`expected_tree_rev` over untouched nodes, the reverse index, the op index) come from a revalidation +made under the lock, so they rely on the signature like any read. + +**What a read returns.** There is one public handle, `CachedCampaign`: it opens the campaign, carries +the seven writes and the recovery, and its `read` (which takes `&mut self`) revalidates and then +answers, so its readers are serialized. `Store` is the state it holds and the only thing `read` +returns; its accessors answer as of that revalidation, and it has no public way to open or write, so +no read skips the revalidation. The M4 server holds it behind a mutex; a read costs one revalidation, so the +lock is held for milliseconds. + +**An entry** holds, per file: the decoded record, its `rev`, a **signature** `(identity, mtime, size, ctime)` +where identity is the inode on Unix and the creation time on Windows (a replace by rename gives the +new file a new identity) and ctime is the inode change time on Unix (absent on Windows), the wall-clock instant `read_at` taken before the file was statted, and a +`racy` flag. The same entry shape serves `nodes/`, `_amendments/` and `_comments/`: append-only files +are checked like the rest, so every kind of external change is covered by one rule. Derived structures +(paths, depth, the reverse link index, `tree_rev`, the op index and the diagnostics) belong to a generation counter that is bumped when +any entry changes; they are rebuilt from the entries and never outlive them. Guarded by `reverse_index_equals_brute_force_scan`, whose op sequences also compare every derived view to a rebuild. + +**Warnings and diagnostics are kept with the decoded nodes.** The `unknown_key` warnings of a file are stored in its entry, and the cross-file diagnostics (orphan, cycle, root, name collision, duplicate id) are derived with the other views. A warm read therefore reports exactly what a cold open would. This is part of `cached_read_equals_cold_read`. + +**The op index** maps an `op_id` to the records that carry it (amendments, comments, `History.op_id` entries). It is built on open with the reverse index, updated by write-through, and read in step 3.1 of the write algorithm, under the lock. Its limits: it knows only what the records carry, so an edit that writes no `op_id`-bearing record is not replayed (it is rev-guarded instead); it keeps no fingerprint of the request, so the same `op_id` reused for a different request is not detected; and, being derived from the entries, it is only as fresh as the revalidation, which is why the replay check runs after taking the lock and a recovery, on a validation made then. The full statement of the rule is `contracts.md`'s (`op_id` replay). + +**Revalidation, on every read:** + +1. List the directory and take each entry's metadata (one `metadata` call per file, which follows symlinks, on Unix; free with the listing on Windows). +2. A cached entry whose signature is unchanged and whose `racy` flag is clear is kept. +3. Every other file is read, decoded and hashed again. The signature stored is the one statted before the read, so a change made during the read shows up on the next validation. +4. Entries whose file is no longer listed are dropped; a new name is read. A file listed and then gone before its stat or read (a concurrent delete or rename) is treated as absent, as if it had not been listed, never as an `Io` error. +5. If anything changed, bump the generation. + +A racy entry is read and hashed again but decoded only if its digest changed. On the probe's shared +machine its cost was lost in the noise: at 1 600 nodes a revalidation took 11 to 13 ms with every +entry racy and 15 to 16 ms with every entry aged, near the 13 ms floor of the listing and stats +alone (`01-cache_probe_v0.md`). + +**Why not the directory `stat`.** The probe shows a directory's mtime changes for a create, a rename and +an unlink but not for an in-place write (a text editor saving, `git merge-file`). A directory-stat fast +path would serve stale data after exactly the edits a person makes by hand, which breaks +`cached_read_equals_cold_read`. The directory is therefore not trusted to say "nothing changed"; a +per-file check on every read is. Its measured cost, 0.25 ms for 160 files and 2.7 ms for 2 000 (from +Python, so an upper bound), is small next to a tool call. + +**The racily-clean rule** (git, racy-git, Sources, adapted). A file changed twice within one +timestamp tick has the same mtime and, if the size matches, the same signature. So an entry whose +mtime is not older than its `read_at` by at least `RACY_WINDOW` is marked `racy` and re-read on every +validation until a read finds it old enough. `RACY_WINDOW` is 2 seconds, which covers FAT (2 s) and +HFS+ (1 s); APFS and NTFS are finer but the rule does not depend on it. A future mtime is also racy. +Git zeroes the cached size to force this; this store keeps an explicit flag, because it has no index +file whose own timestamp to compare with. + +**What stays undetected.** An external program that rewrites a file in place keeping its size and +setting its mtime back to the old value (`touch -r`, some synchronisers) leaves identity, mtime and +size unchanged. On Unix the ctime still moves (no user-level call sets it), so the change is found. +On Windows, which has no ctime in the signature, it is not detected until the entry is evicted or +the server restarts; the same limit holds for git's index. Nothing is written from such a stale +entry for the files the write touches (they are read from disk). The Unix case is part of +`cached_read_equals_cold_read`; the Windows case is not tested. + +**`notify` is not adopted in M1.** File-event services (inotify, FSEvents, `ReadDirectoryChangesW`) +coalesce, overflow and miss events, so they can only be an accelerator beside the scan; the scan costs +under a millisecond at the expected size, so there is nothing to accelerate. + +**Write-through.** Step 6 of the write algorithm updates the entries from what was written, after the +files have been published and before the lock is released: + +- The value is the decoded after-image the writer holds; the `rev` is that of the after-image's bytes. +- The signature is statted from the published path afterwards, with `read_at` taken before the write began, so the entry is `racy`: the next reads within two seconds re-read the file once, and if an external program replaced it in between, the re-read finds it. +- Created files are added and deleted files dropped. The cache is never updated before its files are written, so it is never ahead of the disk. +- If the operation fails after writing anything, the entries of every path it touched are dropped, not guessed. + +A write returns after step 5 under the durability tier in force, so a cold reader (another process, +a fresh open) that starts after the return sees the written files. Guarded by +`write_through_visible_to_cold_reader_on_return`; and by `cached_read_equals_cold_read` for external +change: an editor writing in place, an atomic replacement by another process, `git checkout`, a new +file, a deleted file, a same-size edit within one tick, and, on aged entries (past `RACY_WINDOW`), a +same-size replace by rename keeping the old mtime, a size-only edit with the mtime restored, and on +Unix a same-size edit with the mtime restored (`touch -r`). On Unix the ctime sees all three, so the +first two rows each stand for the component that sees them where no ctime exists; the racy row is +also run on a file system without ctime. Its oracle is a loader independent of the cache: each file +decoded by the codec and hashed by `rev`. That a write judges the files it touches against the disk, +even when the signature cannot see an edit, is guarded by +`a_write_judges_the_files_it_touches_against_the_disk`. + +**Persisted form.** Whether a binary cache is built at all is decided by the `hot_cache` leaf from its +cold-versus-warm measurement. If one is, it lives in `.rdm/cache/` (untracked), carries the crate +version and format version in a header, is validated by the same signatures, and is discarded when +any check fails. It is never read as a source of truth and never tracked. + +## Windows + +Windows has no `rename(2)`: the semantics below are the ones the design relies on, with the evidence +that is and is not available (Probe answers, Sources). + +| Concern | Decision | +|:--|:--| +| Replace a file | `std::fs::rename`, which on the MSRV (1.88) is `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING` (from Rust 1.86). Microsoft documents neither atomicity nor the error for a held-open target, so atomic replace on NTFS is an observed property that `killed_workers_lose_no_acknowledged_write` and `every_write_prefix_loads_and_recovers_to_pre_or_post` test on the Windows runner. `ReplaceFile` is not used: its documented failure states can leave the replaced file renamed or absent, and its write-through flag is documented as unsupported | +| Create-only publish | `std::fs::hard_link` (`CreateHardLinkW`, NTFS), as on Unix. If the volume refuses hard links, the store falls back to "check the name is free, then rename" under the lock; the only remaining race is an external writer creating that exact name in the same instant | +| Held-open target | A program that has the target open without `FILE_SHARE_DELETE` (an editor, a scanner, an indexer) makes the rename or an unlink fail. Retry on `ERROR_ACCESS_DENIED` (5) and `ERROR_SHARING_VIOLATION` (32): up to 10 attempts, so 9 waits of 5, 10, 20, 40, 80 ms and then 100 ms for the rest, about 555 ms in all, then fail with the I/O error of the last attempt, its path and its code. That is inside the lock timeout (5 s), and the lock is held throughout, so no other writer interleaves. These two codes, and that holders release within that window, are this design's expectations, not the documentation's; `replace_while_target_open` measures them and the numbers are set by what it shows | +| This store's own readers | They open with `std`'s default share mode, `FILE_SHARE_READ`, `WRITE` and `DELETE`, so they never block a replace or an unlink. Only foreign programs do | +| Lock | `fs4` locks the whole file with `LockFileEx`; the holder record is a separate file for that reason (Lock). A killed process's lock is released by the system after a short, resource-dependent delay, which the lock timeout covers | +| Directory sync | Not available through `std`; skipped (Durability) | +| Long paths | A path below a campaign is at most 40 characters (`_amendments/<26>.json` is 39), whatever the depth of the tree, so only the campaign's own location counts against 260 characters. `std` adds the `\\?\` prefix to long absolute paths, but the store does not rely on it | +| Names | Ids are lower case and carry a prefix, so they cannot collide on a case-insensitive file system or be a reserved device name (`con`, `nul`); a node's `name` is not a file name | +| Line endings | A checkout with `core.autocrlf` can turn LF into CRLF. The decoder accepts CRLF and `rev` is taken over the decoded value, so neither changes a `rev`. `ci_matrix` confirms what a runner does (`git ls-files --eol`) | + +## Invariants and guards + +Every row names the guard from the campaign README that holds it, or says "not tested" with the +reason. Invariant numbers are those of R01 `§Contracts & Invariants` (I10 is reworded by the A2 +rulings from "the server keeps no state between calls" to the cache rule of this document). + +| # | Invariant | Rule above | Guarded by | +|:--|:--|:--|:--| +| S1 | Readers take no lock, and see each file as the old or the new version, never a torn one | Reads | `reader_sees_old_or_new_never_partial` | +| S2 | Every prefix of every operation's file effects loads, and recovery makes it exactly the state before or after the operation (I3) | Write order, Intent and recovery | `every_write_prefix_loads_and_recovers_to_pre_or_post` | +| S3 | A process kill loses no acknowledged write (I3) | Durability | `killed_workers_lose_no_acknowledged_write` | +| S4 | A write based on a stale `rev`, `SubtreeRev` or `tree_rev` is refused with `Stale { current }` and changes nothing (I4) | Write algorithm, step 3 | `stale_replace_changes_nothing` | +| S5 | A move writes exactly one file under `nodes/` (the amendment is written besides), and no id changes (I7) | Write order | `move_writes_one_file_and_keeps_ids` | +| S6 | `rev` follows the decoded value, not the bytes | Revisions | `rev_tracks_value_not_formatting` | +| S7 | `tree_rev` changes on any node operation and not on a comment or an amendment | Revisions | `tree_rev_changes_on_node_ops_not_comments` | +| S8 | A minted id that collides is drawn again, and minting ends; an id the store finds already on disk under the lock is refused with `duplicate_id` | Ids | `minting_retries_on_collision` for the minter. The store's own refusal is not tested separately by a named guard: it shares the cross-file `duplicate_id` row of `open_names_invalid_campaigns` | +| S9 | A second writer, after the timeout, gets `Locked { holder }` and the file is unchanged | Lock | `second_writer_gets_locked_with_holder` | +| S10 | A killed holder does not leave the lock held | Lock | `lock_survives_holder_kill` | +| S11 | A missing, truncated or garbage holder record never breaks locking | Lock | `garbage_holder_record_does_not_break_locking` | +| S12 | A replace or unlink against a target another program holds open succeeds once it is released inside the retry window, and fails cleanly otherwise | Windows | `replace_while_target_open` | +| S13 | A cached read equals a cold read after any kind of external change (I10, reworded) | Cache | `cached_read_equals_cold_read` | +| S14 | A write returns only after its files are written, and a cold reader then sees them | Cache, write-through | `write_through_visible_to_cold_reader_on_return` | +| S15 | `between` returns a key strictly between its bounds, of the allowed characters, not ending in `0`, and keys stay short | Order key | `order_keys_sort_strictly_between_their_bounds` | +| S16 | An id of a deleted record is never minted again | Ids | Not tested: a probability under 2e-9 per mint, accepted | +| S17 | Power loss leaves a valid campaign | Durability | Not tested: needs a fault-injecting file system (README, "Deliberately not tested"); argued under Durability | +| S18 | A kill at any point of recovery's own effects is repaired by the next recovery | Intent and recovery | `every_write_prefix_loads_and_recovers_to_pre_or_post` (a row that cuts recovery's own effects too, `crash_test`) | +| S19 | Recovery never overwrites a create-only file that holds other bytes | Intent and recovery | Not tested: it needs an external writer in the crash window | +| S20 | `open` fails on a per-file fault (unparsable file, malformed id, `file_id_mismatch`, `NewerFormat`), and loads and reports cross-file damage (`parent_missing`, `cycle`, `root_count`, `name_collision`, cross-file `duplicate_id`) as one diagnostic per defect | Layout, Reads | `open_names_invalid_campaigns` | +| S21 | An in-place edit that preserves size and restores mtime is detected | Cache | Not tested: documented limit, undetectable by stat | +| S22 | A write that builds on an unvalidated node is refused; a repair write is allowed | Write algorithm, step 3.4 | `requests_breaking_a_rule_are_refused` | +| S23 | A retried `op_id` returns the first outcome and writes nothing | Write algorithm, step 3.1 | `replayed_op_id_writes_nothing` | +| S24 | An unknown key survives in place and produces an `unknown_key` diagnostic, and a warm read reports the same diagnostics as a cold open | Reads, Cache | `unknown_keys_survive_in_place_at_every_level` (survival) and `cached_read_equals_cold_read` (equal diagnostics) | +| S25 | A file newer than the binary, at any part of `0.X.Y`, is refused with `NewerFormat` | Reads | Not tested here: `codec_and_versions` owns the version refusal and its guard; the store only carries it | + +## Probe answers + +Four probes were assigned to this leaf. Probe code lived in a scratch directory and is deleted; +nothing of it is committed. Machine: macOS 26 (Darwin 25.6), APFS, local `cargo` stable 1.99 and +`cargo +1.88`. + +| Question | Answer | Decision | +|:--|:--|:--| +| Lock crate: do `fs4` and `fd-lock` build on 1.88, does a second process see the lock, is it released by `kill -9` of the holder? | `fs4` 1.1.0 (declares MSRV 1.75) and `fd-lock` 4.0.4 both build with `cargo +1.88`. With both, a second process got `BUSY` while the holder lived and acquired the lock right after `kill -9` of the holder (the lock file stays on disk, unlocked). A second `open` of the lock file inside the holder's own process also got `BUSY` (per-open-file-description `flock`, not per-process) | `fs4`. Same semantics as `fd-lock`, a plain `lock`/`try_lock` on the `File` (the names std adopted in 1.89, so dropping the crate later is mechanical), and no guard that borrows the lock owner. std's own `File::lock` is not usable at the 1.88 MSRV | +| Does a rename into `nodes/` change the directory mtime; does an in-place write of an existing file? | Create, rename to a new name, rename over an existing name, and unlink each changed the directory mtime. An in-place write (`r+`, or truncate and rewrite) did not (delta 0), though it changed the file's own mtime. A rename over an existing file also changes its inode, and its mtime even at equal size | The directory mtime cannot certify "nothing changed": an editor writing in place is missed. It is not a fast path. Revalidation is one `readdir` plus a `stat` per entry (see Cache) | +| Granularity of the mtimes? | Nanoseconds: 300 file writes gave 300 distinct `mtime_ns`, none a multiple of 1 000; consecutive renames into one directory gave distinct directory mtimes (156 µs and 277 µs apart) | APFS needs no coarse-timestamp care, but the cache does not rely on it: a conservative racy window (see Cache) covers FAT (2 s), HFS+ (1 s) and the coarse kernel clock of ext4 | +| Cost of `fsync` on a file, on its directory, and `F_FULLFSYNC`? (300 iterations, 1.5 KB file, write + rename) | No fsync: median 0.148 ms, p95 0.255. `fsync` file: 0.157 / 0.222. `fsync` file and directory: 0.157 / 0.289. `F_FULLFSYNC` file: 4.99 / 6.04. `F_FULLFSYNC` file and directory: 9.97 / 10.98. On macOS plain `fsync` does not flush the drive's cache, which is why it is as cheap as no fsync | Default tier `Fsync` (file and directory); `Full` is an opt-in (see Durability). `F_FULLFSYNC` costs about 65 times a plain write and would turn a 160-node import into 1.6 s of waiting | +| What does a revalidation scan cost? (extra probe, feeds the cache decision) | `scandir` plus `stat` of every entry: median 0.25 ms (p95 0.35) for 160 files, 2.7 ms (p95 3.4) for 2 000 files, measured from Python, so an upper bound for Rust. Stat of the directory alone: 1 µs | A full scan on every read is affordable at the expected size. No fast path is built, and `notify` is not adopted in M1 | +| Which hash for `rev`: do `sha2` and `blake3` build on 1.88? | `sha2` 0.11.1 and `blake3` 1.8.7 both build. `blake3` declares MSRV 1.88, exactly the floor, and its default build compiles C and assembly (`cc`) | SHA-256 (see Revisions) | +| Win32 `MoveFileEx` with `MOVEFILE_REPLACE_EXISTING`, and `ReplaceFile`, against a target another program holds open without `FILE_SHARE_DELETE`: which error, when? | **The Microsoft pages do not say.** Neither page names `ERROR_ACCESS_DENIED` (5) or `ERROR_SHARING_VIOLATION` (32) for this case, neither promises atomicity, and `MoveFileEx` says nothing about `FILE_SHARE_DELETE`. What the pages do say: `MoveFileEx` fails if the new name is an existing directory; `ReplaceFile` opens the replaced file with read, delete and synchronize access and share mode read, write and delete, and the replacement with no sharing; `ReplaceFile`'s `REPLACEFILE_WRITE_THROUGH` is documented as not supported; a failed `ReplaceFile` can leave the replaced file renamed or absent (error 1175, 1176, 1177). Rust's `OpenOptions` opens with `FILE_SHARE_READ`, `WRITE` and `DELETE` by default, so this program's own readers never block a replace. Rust's `fs::rename` calls `MoveFileExW(REPLACE_EXISTING)` from Rust 1.86 and falls back to a POSIX-semantics `SetFileInformationByHandle` only on `ERROR_ACCESS_DENIED` (1.85 used the POSIX path first) | The replace is `std::fs::rename`, not `ReplaceFile`: its failure states are not documented as atomic and it leaves the replaced file absent in some of them. Retry on 5 and 32 (the two codes a held-open target is reported with in practice, which is this design's own claim) with a bounded back-off, then fail. Numbers under Windows. `replace_while_target_open` settles the codes on a real Windows runner | + +### What the probes did not settle + +- Linux and Windows lock release on kill: only macOS was run. `lock_survives_holder_kill` runs on all three operating systems in CI. +- The Windows error code of a held-open target and whether `std::fs::rename` is atomic there: from documentation only, as the table says. `replace_while_target_open` and `killed_workers_lose_no_acknowledged_write` on the Windows runner are the evidence. +- Power loss: no probe can show it on this machine. See Durability. + +## Sources + +Each source was read, by a research subagent for the PDFs and pages, and by this author for the +Rust `OpenOptionsExt` page. The third column is what the source supports; a claim it does not +support is dropped or marked as this design's own wherever it would have appeared. + +| Technique | Source read | What it supports | What it does not, and what this design does with that | +|:--|:--|:--|:--| +| Ordering of dependent writes | [McKusick and Ganger, "Soft Updates", USENIX ATC 1999](https://www.usenix.org/legacy/publications/library/proceedings/usenix99/full_papers/mckusick/mckusick.pdf), §2 | Three rules: never point to a structure before it is initialised; never re-use a resource before nullifying every earlier pointer to it; never reset the old pointer to a live resource before the new one is set (its example is a rename: do not drop the old name before the new one is written) | Soft Updates is about a file system's own metadata and a per-block dependency tracker. This design borrows the rules for the order of files, not the tracker | +| Publish by write-then-link | [Bernstein, Maildir](https://cr.yp.to/proto/maildir.html) and [maildir(5)](https://manpages.debian.org/testing/qmail/maildir.5.en.html) | Write the message under `tmp/`, then `link()` it into `new/`; a reader never sees a partial message; unique names built from time, process id, host and a counter need no lock; the man page requires `write`, `fsync`, `close` each checked before the `link()`; `tmp/`, `new/`, `cur/` on one file system | Bernstein's page gives the rationale and the name scheme but not the delivery steps; those and the fsync are in maildir(5). Maildir publishes with `link()`, not `rename()`. This design uses `link()` for create-only files (it fails when the name exists, which a rename does not) and `rename()` for replacement, which Maildir never does | +| Redo from a durable log | [Mohan et al., ARIES, ACM TODS 17(1), 1992](https://web.stanford.edu/class/cs345d-01/rl/aries.pdf) | Write-ahead logging; the redo pass repeats history; compensation log records are redo-only | Redo idempotence by page LSN: only partly confirmed from the OCR copy read. A "redo-only intent record that recovery rolls forward" is not a construct of ARIES. This design's intent is its own application of log-before-data, with whole-file after-images, so redo is idempotent by construction (putting the same bytes twice) and needs no LSN | +| What a crash can expose | [Pillai et al., "All File Systems Are Not Created Equal", OSDI 2014](https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-pillai.pdf) | Applications assume rename is atomic; most of the vulnerabilities it found sit in missing `fsync` of a parent directory or of data before a rename; whether an append persists before a later rename differs between file systems and even between configurations of one; a single-sector write is not atomic on every file system | The claim "an unsynced temp file renamed into place can leave a zero-length file" was not found in those words and is not cited. This design fsyncs the temp file before the rename and the directory after it because the paper shows the behaviour varies, not because it measured that outcome | +| Racily clean entries | [git, racy-git](https://git-scm.com/docs/racy-git) | An entry whose mtime is not older than the index's own timestamp may have changed within one timestamp tick and must be compared by content; git ignores the nanosecond fields by default; coarse file systems stay problematic | Git also zeroes the cached size so a later stat check fails. This design has no index file to timestamp, so it keeps a per-entry flag and re-reads flagged entries (see Cache): an adaptation, not git's mechanism | +| Atomic replace on Windows | [`MoveFileExW`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw), [`ReplaceFileW`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew), [`std::fs::rename`](https://doc.rust-lang.org/std/fs/fn.rename.html), [`OpenOptionsExt::share_mode`](https://doc.rust-lang.org/std/os/windows/fs/trait.OpenOptionsExt.html) | See the probe answer above | Neither Microsoft page promises atomicity or names the error for a held-open target. Atomic replace on NTFS is therefore an observed property this design relies on and tests (`killed_workers_lose_no_acknowledged_write`, `replace_while_target_open`), not a documented guarantee | +| Fractional indexing | [Figma, "Realtime editing of ordered sequences"](https://www.figma.com/blog/realtime-editing-of-ordered-sequences/), [rocicorp/fractional-indexing](https://github.com/rocicorp/fractional-indexing) (Greenspan's design; the article was unreachable, the README states it is based on it) | A key between two keys is a string midpoint; keys compare with plain lexicographic order over an ascending digit alphabet (base 62 by default in rocicorp, base 95 in Figma's post); Figma lists growth of the key length as a known drawback and not a practical concern; `generateNKeysBetween` is advised for bulk inserts | Neither source names a rebalancing step, and jitter appears only as advice to reduce concurrent collisions. The rebalance threshold and the choice of tie-break instead of jitter are this design's own | +| Lock range on Windows | [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) | An exclusive lock denies other processes read and write access to the region; the operating system releases the locks of a process that ends, but how long that takes depends on available resources | Not a statement about `fs4`: that the crate locks the whole file on Windows was read in its source (`LockFileEx` with the maximum length) | +| Advisory locks | [`fs4` 1.1.0](https://docs.rs/fs4/1.1.0/), [`fd-lock` 4.0.4](https://docs.rs/fd-lock/4.0.4/) | Crate behaviour as probed above | Not a literature source. The kernel's release of a `flock` on process death is shown by the probe on macOS only | diff --git a/__design__/rdm/stored-schema.md b/__design__/rdm/stored-schema.md new file mode 100644 index 0000000..73ea2f4 --- /dev/null +++ b/__design__/rdm/stored-schema.md @@ -0,0 +1,456 @@ +# rdm — Stored schema + +Every fact `rdm` stores, with its name, type, whether it is required, and its meaning. This is the +settled form of R01's provisional schema sketch (`architecture.md` §Data Model). The legacy +grammars it must cover are traced production by production in [traceability.md](traceability.md). +Status meanings are in [statuses.md](statuses.md). The read model that consumers receive is a +separate document (`read-model.md`). + +Where this document departs from a default of the M0b plan, a one-line note says who decided it +(Eliott or the coordinator, 2026-11-16). Two recorded objections stand, with the default kept. +Fields new against R01 are marked **new**. + +**Revision, 2026-11-25 (A2, Eliott's rulings).** The layout is flat and id-addressed, a node holds +its own `name`, `parent_id` and `order`, and the Rust types in [contracts.md](contracts.md) are the +contract this document describes. Checks and references lose their ids (`Stable identity`), and the +id types, the id string format and the order key are named in contracts.md and +[store.md](store.md). Edited sections carry a "Revised 2026-11-25" note. + +Notation: + +| Type | Meaning | +|:--|:--| +| `string` | One line, no line break | +| `lines` | Array of strings, each one line. Used for all multi-line prose, so git merges it line by line. The API accepts and returns plain strings and splits or joins on `\n` | +| `ts` | UTC instant, RFC 3339, `"2026-11-16T10:20:30Z"` | +| `ulid` | A ULID, 26 characters of Crockford base32 | +| `T[]` | Array of `T` | +| `T?` | Optional: the key is absent when there is no value. A writer never writes `null`. A reader treats `null` as absent. The exception is `Change.old` and `Change.new`, where `null` is a value | + +## Files + +``` +__roadmap__// + nodes/.json one file per node (Directory or Leaf) + _amendments/.json one file per amendment (Amendment) + _comments/.json one file per comment (Comment) + .rdm/ untracked: lock, intent/, cache/ (store.md §Layout) +``` + +Revised 2026-11-25: the files no longer mirror the tree. A node is `nodes/.json`, whatever its +kind, and its place in the tree is data inside it (`name`, `parent_id`, `order`). The campaign root +is the node whose `kind` is `campaign`. A rename or a move writes one file and renames no directory. + +| Rule | Detail | +|:--|:--| +| Names are paths | A node's `name` is its path segment, `^[a-z][a-z0-9_-]*$`, unique among the children of one parent. It is stored in the node file (revised 2026-11-25: it used to be the file's own name). The path is derived from the `parent_id` chain and never stored. The campaign root's `name` is the campaign slug, which `open` is given and checks; it is not part of any path (revised 2026-11-25, Eliott's review) | +| Identity | Every node, criterion and step has an immutable `id`, typed `NodeId`, `CriterionId` and `StepId` in [contracts.md](contracts.md) §Id types. The string format and the minting are [store.md](store.md)'s §Ids. Checks and references have none: `Stable identity` | +| Version stamp | Every file carries `schema_version` (see `Format version`) | +| Unknown fields | Every object type below keeps the keys it does not know, in order, and writes them back after the known ones. This holds for nested objects too (steps, criteria, references, commits, history and comment entries, changes). It is the stored half of I12. Each unknown key a decoder keeps without interpreting also yields one `unknown_key` warning naming the file and the key's JSON path (contracts.md §Diagnostics; revised 2026-11-25). Keys keep their order, so the crate enables `serde_json`'s `preserve_order`. Numbers outside the `i64`, `u64` and `f64` range are not preserved exactly, because `arbitrary_precision` is not enabled. `Envelope` (read model) has no `extra` of its own: it is flattened into each view, whose `extra` keeps the unknown keys | +| Canonical order | The order of the rows in each field table is the canonical field order. Two-space indent, LF, trailing newline. M1 owns the serialiser | +| Derived, never stored (I6) | Directory status, the nodes table, the mermaid graph, the progress table, waves, the ready set, a step's number, the display id of an amendment, a leaf's commit count when the engine recorded the steps, a node's children, depth and path, and a `Reference.target` when `Reference.node_id` is set. No stored field holds a value that can be derived from an id | + +## Stable identity + +Eliott, 2026-11-16: the data structures must be aligned so that mutations cannot break references. +If reordering criteria made a mark record point at the wrong criterion, the data model would be +wrong. + +**Invariant.** No record refers to a sub-item by position, and every mutation (insert, delete, +reorder, move) leaves existing references valid. + +| Sub-item | Id field | Pointed at by | +|:--|:--|:--| +| Criterion (`preconditions[]`, `success_gates[]`) | `Criterion.id` | `Mark.criterion_id`, `Change.item_id` | +| Step | `Step.id` | `Change.item_id` (an edit or a correction of the step) | + +Revised 2026-11-25. The rule for an id is "it is pointed at from outside, and its natural key can +change" ([contracts.md](contracts.md) §Id inventory). A check and a reference are pointed at by no +record, so they have no id. Their edits are recorded at the array level: a `set` change on the +owner's `/checks` or `/references`, with the whole old and new array. A reference that names a +node points *out* through `node_id`; nothing points in. + +- **Minting.** An id is minted when the sub-item is created, by the engine, or by the importer at import, with the format and the minter of [store.md](store.md) §Ids. It is unique within its node file, and is immutable. +- **Never reused, never derived.** An id is not computed from position, text or a counter, and the id of a deleted sub-item is never given to another. A delete keeps the item in its amendment's `snapshot`, so a record that still names the id resolves there. +- **Order is separate.** The order of a sub-item is the order of its array, and a reorder changes that order only. Nothing stored holds an order as an identity. A step's `number` is derived from the array for display, and is never a reference. +- **No records point by position.** A record that names a sub-item carries its id: `Mark` uses `criterion_id`, and `Change` uses `item_id` with a `field` pointer relative to that item. A node is named by `node_id`, never by its path. +- **Append-only logs** (`history`, `marks`, comments, amendments) are never reordered or edited, and their entries are not pointed at by position. The one reading of order, "the last cancel entry", reads the end of an append-only log. +- **Not addressable.** `Commit` and `Progress` are single objects reached through their step or leaf, so they have no id. Neither have a check, a reference, a history entry or a mark. + +**Audit of positional and path-based references**, fixed the same way: + +| Was | Broke on | Now | +|:--|:--|:--| +| `Mark.index` and `Mark.kind` | reorder, or a move of a criterion between `preconditions` and `success_gates` | `Mark.criterion_id`; the kind is derived by looking up the criterion | +| `Change.field` as a JSON pointer with an array index (`/steps/1/goal`) | insert, delete or reorder of steps and criteria | `Change.item_id` names the sub-item, and `field` is a pointer inside it (`/goal`) | +| `Amendment.snapshot` keyed by path | a move or rename of the removed subtree's nodes | keyed by node id | +| `Reference.target`, a relative path, when it names a node of the campaign | a move of the node | optional `Reference.node_id`; when it is set `target` is absent and derived on read (revised 2026-11-25) | + +## Directory + +`_dir.json`, for the campaign root and for every directory node. A directory has no `status`: it +is derived (`statuses.md`, `Subtrees and directories`). + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `schema_version` | `string` | yes | Format version, `"0.X.Y"` | +| `id` | `NodeId` | yes | Immutable node id | +| `kind` | `"campaign"` or `"directory"` | yes | `campaign` for the root only, which is the node with no `parent_id` | +| `name` | `Name` | yes | **new**: the path segment. For the campaign root, the campaign slug (the anchor `Campaign::open` checks). Unique among the children of one parent | +| `parent_id` | `NodeId?` | no | **new**: the directory this node is in. Absent exactly for the campaign root | +| `order` | `OrderKey?` | no | **new**: position among siblings, an opaque key (store.md §Order key). Absent exactly for the campaign root, which has no siblings | +| `title` | `string` | yes | The H1 of the legacy README | +| `context` | `lines` | yes | Where the node fits; legacy `## Context`, one or more lines | +| `references` | `Reference[]` | yes | Legacy `## Reference Documents`. May be empty (the section is optional in the legacy grammar) | +| `goal` | `string` | yes | One line. The legacy grammar allows exactly one line | +| `preconditions` | `Criterion[]` | yes | Entry criteria, one or more | +| `success_gates` | `Criterion[]` | yes | Completion criteria, one or more | +| `gotchas` | `lines` | yes | Legacy `## Gotchas`, verbatim markdown lines. May be empty (the section is optional) | +| `notes` | `lines` | yes | **new**: the `Notes` cell of the directory's own row in its parent's Progress table. May be empty | +| `marks` | `Mark[]` | yes | **new**: the trace of every change of a criterion mark of this directory, oldest first. Empty on a new or imported directory | + +Rules for `validate`: `goal` has no line break; `preconditions` and `success_gates` each have at +least one entry; `kind` is `campaign` exactly when `parent_id` and `order` are both absent +(revised 2026-11-25: it used to be "the file is at the campaign root"). A directory's children are +the nodes whose `parent_id` names it, ordered by `order`; the list is derived and never stored. + +A directory carries no branch and no commit count. The legacy Progress row of a directory repeats +the branch of one of its leaves and a count of commits; both are dropped (see `traceability.md`, +`Stretched legacy data`). + +## Leaf + +`.json`. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `schema_version` | `string` | yes | Format version, `"0.X.Y"` | +| `id` | `NodeId` | yes | Immutable node id | +| `kind` | `"leaf"` | yes | Discriminates a leaf from a directory when a reader holds only the JSON | +| `name` | `Name` | yes | **new**: the path segment. Unique among the children of one parent | +| `parent_id` | `NodeId` | yes | **new**: the directory this leaf is in | +| `order` | `OrderKey` | yes | **new**: position among siblings, opaque (store.md §Order key). Ties break by `id` | +| `title` | `string` | yes | The H1 of the legacy leaf file | +| `status` | `"planned"`, `"ongoing"`, `"paused"`, `"cancelled"` or `"done"` | yes | Meanings and moves in `statuses.md`. A new leaf is `planned` | +| `status_reason` | `string?` | no | **new** (replaces R01's `blocked_reason`). The reason of the move into the current status. Present only while the status is `paused` or `cancelled` | +| `goal` | `string` | yes | One line | +| `preconditions` | `Criterion[]` | yes | Entry criteria, one or more | +| `success_gates` | `Criterion[]` | yes | Completion criteria, one or more | +| `references` | `Reference[]` | yes | Supporting documents of the leaf | +| `steps` | `Step[]` | yes | One to five steps, in order | +| `progress` | `Progress` | yes | Where the work happened | +| `history` | `History[]` | yes | Status moves, oldest first. Empty on a new leaf, and on a leaf imported from legacy markdown | +| `marks` | `Mark[]` | yes | **new**: the trace of every change of a criterion mark of this leaf, oldest first. Empty on a new or imported leaf. Kept apart from `history` so that the last `history` entry stays the last status move | + +`Progress` is an object, not a separate type section: + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `branch` | `string?` | no | The task branch, for example `task/write-skill-md`. Absent when the legacy cell is `-`, `--`, `---` or `—` | +| `commits` | `integer?` | no | **new**: a commit count written by the importer for a leaf whose steps carry no `commit_sha`. The legacy count can exceed the step count (a fixup commit). The engine never writes it: for an engine-recorded leaf the count is derived from the steps | +| `notes` | `lines` | yes | The legacy `Notes` cell. May be empty | + +Rules for `validate`: + +- `steps` has one to five entries. A step's number is its position plus one, so no rule can break it. +- `goal` has no line break. +- `references` has at least one entry (the legacy grammar requires a non-empty `**References**` line). An empty array is a warning, not an error. Decided 2026-11-16 (coordinator). +- `status == planned` implies every step has `done: false`. +- `status == done` implies every step has `done: true`. +- `status_reason` is present exactly when `status` is `paused` or `cancelled`, and equals the `reason` of the last `history` entry when `history` is not empty. +- A leaf imported as `done` has steps with `done: true` and no `commit_sha`. I8 is checked when a move to `done` is made (see `Changes against R01`). +- A `done` leaf with a criterion that is not `met` is an **error to reconcile** (`marks`, `Criterion`). The importer never ticks a criterion, so every legacy done leaf with an open gate reports it. The same holds for a directory whose derived status is `done`. +- For each criterion, when `marks` holds a record for it, `met` equals the `met` of its last record. A legacy tick that has no record is allowed. +- Every `id` of a sub-item is unique within the file. A `Mark.criterion_id` names a criterion of the file, or a criterion that an amendment removed (its snapshot holds it). +- A record with `correction: true` has a non-blank reason: the `reason` of a mark or history entry, the `description` of an amendment. A history entry with `correction: true` has `from: done`. + +## Step + +An element of `Leaf.steps`. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `id` | `StepId` | yes | **new** (R01 had it): immutable step id, minted like node ids (`Stable identity`). Anything that points into a step uses it | +| `title` | `string` | yes | The text after `## Step N:` | +| `goal` | `string` | yes | One line: the unique change intent of the step | +| `implementation_logic` | `lines` | yes | Free prose and lists, blank lines allowed. At least one line is not blank | +| `deliverables` | `lines` | yes | Legacy: one line. Import stores it as one element, unsplit. A new step may hold several elements, one per deliverable. M3's export joins them with `; ` | +| `references` | `Reference[]` | yes | Step-level documents. May be empty (optional in the legacy grammar) | +| `checks` | `Check[]` | yes | One or more. The legacy grammar has exactly one per step, so import yields one | +| `commit` | `Commit` | yes | The commit message the step must produce | +| `requires` | `lines?` | no | Prose prerequisites that are not obvious. **Never an id or an edge**: I1 forbids a stored dependency between siblings. Never used in real campaigns, kept so the grammar's field has a home | +| `done` | `bool` | yes | The step is recorded done. A correction of a step recorded done needs a reason (`statuses.md`, `Finished nodes`) | +| `commit_sha` | `string?` | no | The commit that completed the step. Set with `done: true` by the engine | +| `done_at` | `ts?` | no | **new**: when the step was recorded done | + +`Check` (revised 2026-11-25: no `id`; nothing points at a check, and an edit is a `set` of the step's `/checks`): + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `text` | `string` | yes | **new**: the check as written, without the `(expected: …)` trailer. Prose or a command line | +| `expected` | `"PASS"` or `"FAIL"` | yes | The outcome the check expects | +| `command` | `string?` | no | A shell command, when the whole check is one runnable command. Set only by the author of a new check, never guessed by the importer | + +**A step has an `id`, and its number is derived.** The number is the step's position plus one, 1 +to 5, never stored. A stored number could disagree with the array position, and R01's composite +"reorder steps" would have to renumber it, so references into a step by number would point at +another step. The export writes the number from the position. In `traceability.md` the +`` row stores `title` and derives the number. Decided 2026-11-16 (coordinator). + +**A check is prose, not `{command, expected}`.** The plan's default made `command` +required. The legacy check is a prose line that ends in `(expected: PASS)` or `(expected: FAIL)`. +Real checks are commands in backticks, several commands joined by `;`, shell loops, or a +sentence. No parser extracts a `command` from all of them without loss or invention. Decided +2026-11-16 (coordinator): `text` is required and lossless, `expected` is parsed from the trailer (the one part +the grammar fixes), and `command` is optional and filled only by an author. Export (M3) writes +`text`, a space, and `(expected: X)`. An agent that wants to run a check uses `command` when it +exists and reads `text` otherwise. + +Rules for `validate`: `title` is not blank; `implementation_logic` has a non-blank line; a step +with `done: true` has `done_at` when the engine recorded it; `commit_sha` and `done_at` appear +only when `done` is `true`. + +## Criterion + +An element of `preconditions` or `success_gates`, at leaf and directory level. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `id` | `CriterionId` | yes | **new**: immutable criterion id (`Stable identity`). A `Mark` points at it, never at the criterion's position | +| `text` | `string` | yes | The criterion, one line. Tags such as `[static]` or `[behavioral]` stay in the text | +| `met` | `bool` | yes | Pre-condition: `[x]` is `true`. Gate: `✅` is `true`. A new criterion is `false` | + +`met` is a state mark, not content: setting it produces no amendment and is allowed on every node, with a reason on a finished one (`statuses.md`, `Finished nodes`). It is enforced (Eliott, 2026-11-16): `planned → ongoing` needs every +pre-condition `met`, `ongoing → done` needs every success gate `met`, and a directory is `done` +only when its leaves are finished and its own gates are `met` (`statuses.md`, `Criteria`). Every +change of `met` writes a `Mark`. Real campaigns hold 16 checked pre-conditions and 150 `✅` gate +marks, and 30 of 48 done leaves carry an open gate: the importer imports them as they are, and +`validate` reports each `done` node with an unmet criterion as an error to reconcile. + +## Mark + +An element of `Leaf.marks` or `Directory.marks`: one change of one criterion's `met`. Written by +the operation that sets the mark; never an amendment (I5). + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `ts` | `ts` | yes | When the mark was changed | +| `actor` | `Actor` | yes | Who changed it | +| `criterion_id` | `CriterionId` | yes | The `id` of the criterion, in `preconditions` or `success_gates`. Never a position | +| `met` | `bool` | yes | The new value | +| `evidence` | `string?` | no | Free text: a command, its result, a commit | +| `reason` | `string?` | no | **new** (Eliott, 2026-11-16): why the mark was made. Required, non-blank, when `correction` is `true` | +| `correction` | `bool?` | no | **new**: `true` when the mark was made on a `done` or `cancelled` node. Counted in `correction_count` (`read-model.md`) | + +A wrong check stays traceable: correcting it writes a new record, and the old one stays. A +reorder, an insert or a delete of criteria changes no mark, because a mark names its criterion by +id. + +## Reference + +An element of `references`, at directory, leaf and step level. One shape for all three. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `label` | `string?` | no | `R01`, `R02`, … The label other text cites. Unique within one `references` array. The legacy directory section requires it, so `validate` requires it there | +| `title` | `string` | yes | The link text without the label | +| `target` | `string?` | no | A URL, or a path relative to the campaign root directory, as written. Absent for a reference written as plain text, and **absent whenever `node_id` is set**: it is derived on read from the path of that node. Not resolved by the schema. Revised 2026-11-25: the base was the node file, and a node file no longer sits where its node is in the tree, so a tree-relative path would break on a move. The importer (M3) rewrites a legacy path to this base | +| `note` | `string?` | no | The text after ` — `, one line | +| `node_id` | `NodeId?` | no | **new**: the id of the campaign node the reference names, when it names one. A path breaks when the node moves, the id does not. It excludes `target`: a reference holds one or the other, and a record that holds both is `Invalid` (rule `reference_target_derived`). The importer sets `node_id` when a legacy target resolves to an imported node. If that node is later deleted the reference dangles: a warning, never an error (contracts.md §Links) | + +Legacy forms and how they split: + +| Legacy text | `label` | `title` | `target` | `note` | +|:--|:--|:--|:--|:--| +| `- [R01 Architecture](../a.md) — the design` (directory) | `R01` | `Architecture` | `../a.md` | `the design` | +| `[R01 §Data Model](../a.md) — the sketch` (leaf, in a `; `-separated line) | `R01` | `§Data Model` | `../a.md` | `the sketch` | +| `[Gap analysis](g.md) — why` | none | `Gap analysis` | `g.md` | `why` | +| a segment that is not a link | none | the whole segment | none | none | + +The importer splits a leaf's one-line `**References**` on `; ` outside brackets and parentheses. +A `**References**:` line followed by bullet lines (`- [text](target) — note`) is the bulleted form: each bullet is one `Reference`, split like a directory item. +A label is the prefix `R` and two digits followed by a space at the start of the link text. A +segment it cannot parse becomes a reference with only `title`, so nothing is dropped. +Note (revised 2026-11-25): a `target` relative to the campaign root does not depend on where a node +sits in the tree, so a move leaves it valid and M2 need not normalise it. + +## Commit + +The commit message a step must produce. Field of `Step.commit`. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `type` | `string` | yes | Project-defined (`docs`, `feat`, …). The legacy shape is `[^\s()`!:]+` | +| `scope` | `string?` | no | Project-defined. **The legacy grammar requires a scope**; the default makes it optional | +| `breaking` | `bool` | yes | **new**: the `!` mark. `false` when absent | +| `summary` | `string` | yes | The text after `: `. May contain colons | + +The backticks around the legacy line are presentation and are dropped. The message has no body or +trailer; the actor adds trailers at commit time. + +Consequence for M3: a commit with no `scope` cannot be exported to a line the legacy validator +accepts. Export either writes `type: summary`, which the old tool rejects, or refuses. M3 decides. + +## History + +An element of `Leaf.history`: one status move. Written by `transition`; never an amendment (I5). + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `ts` | `ts` | yes | When the move was made | +| `from` | status | yes | The status left | +| `to` | status | yes | The status entered | +| `actor` | `Actor` | yes | Who made it | +| `reason` | `string?` | no | Required for moves into `paused` and `cancelled`, and for `paused → planned`, `paused → ongoing` and every undo out of `cancelled` (`statuses.md`) | +| `override` | `bool?` | no | `true` when the leaf was started outside the ready set | +| `op_id` | `OpId?` | no | **new**: shared by every entry that one operation writes, so a directory pause or cancel is recognisable as one operation | +| `correction` | `bool?` | no | **new** (Eliott, 2026-11-16): `true` for a reversal out of `done`. `reason` is then required and non-blank | + +`Actor` (also used by `Comment` and `Amendment`): + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `kind` | `"agent"`, `"human"` or `"import"` | yes | The actor kind that `statuses.md` names in its `Who` column | +| `name` | `string?` | no | Free identifier: a user, an agent session, a tool | + +**`actor` is an object, not a string.** The plan's list gave `actor` with no type, +and R01 gives none. `statuses.md` states who may set each move, `agent`, `human` or `both`. A +bare string cannot be checked against that. `kind` is the part a rule can test, and `name` is the +part a person reads. Decided 2026-11-16 (coordinator). + +## Comment + +`_comments/.json`, at the campaign root. One file per comment, append-only, like an +amendment. A comment on a leaf, a directory or the campaign root. Allowed on every node, finished or not, with no reason. Never an amendment. A node's comments are the set of comment files whose `node_id` names +it, so a comment never changes the node's `rev`. Decided 2026-11-16 (Eliott): this replaces a +`comments[]` array in the node file, which two branches would both append to, and conflict. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `schema_version` | `string` | yes | Format version, `"0.X.Y"` | +| `id` | `CommentId` (`ulid`) | yes | Identity and order | +| `node_id` | `NodeId` | yes | The node commented on | +| `ts` | `ts` | yes | When it was added | +| `actor` | `Actor` | yes | Who added it | +| `text` | `lines` | yes | The comment, one or more lines (it is prose, so it follows the lines rule) | +| `op_id` | `OpId?` | no | The retry key of the write that made it | + +Files are never edited or removed. A correction is a new comment. Deleting a node does not delete +its comments; the removing amendment's `snapshot` keeps them with it. + +## Amendment + +`_amendments/.json`. One file per content or structure edit. Append-only. + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `schema_version` | `string` | yes | Format version, `"0.X.Y"` | +| `id` | `AmendmentId` (`ulid`) | yes | Identity and order. The display id is derived (below) | +| `legacy_id` | `string?` | no | **new**: the legacy `A1`, `A2`, … of an imported amendment | +| `ts` | `ts` | yes | When it was made. For a legacy row: the row's day at `T00:00:00Z` | +| `actor` | `Actor` | yes | Who made it | +| `description` | `string` | yes | Non-empty (I5). The legacy `Rationale` | +| `source` | `string?` | no | The report that justified it. Legacy: a path under `__reports__/` | +| `op_id` | `OpId?` | no | The retry key of the write that made it | +| `correction` | `bool?` | no | **new** (Eliott, 2026-11-16): `true` for an edit of a finished node, of a step recorded done, or of progress on a finished node. `description` is then its reason and is non-blank | +| `changes` | `Change[]` | yes | What changed, one or more | +| `snapshot` | `object?` | no | The removed subtree of a delete, as stored JSON keyed by `NodeId`, so it can be restored. The keys are links (contracts.md §Links); the values are historical copies and are not scanned. A removed sub-item is not here: its `remove` change holds it in `old` | + +`Change`: + +| Field | Type | Req | Meaning | +|:--|:--|:--:|:--| +| `node_id` | `NodeId` | yes | The node the change names. A node's amendment log is the set of amendments whose `changes` name its id | +| `op` | `"add"`, `"remove"`, `"set"`, `"rename"` or `"move"` | yes | R01's primitives. Composite operations expand to these. M2 owns any addition. With `item_id`, `add` and `remove` insert or delete the sub-item (a `remove` holds the removed sub-item in `old`, so a mark that names it resolves), and `move` reorders it: `old` and `new` hold its array position before and after, which is order data and not a reference. Without `item_id`, on a node: `add` and `remove` create and delete the node (a `remove` keeps the subtree in `snapshot`), `rename` holds the old and new `name` in `old` and `new`, and `move` holds `{"parent_id", "order"}` in `old` and `new` | +| `item_id` | `ItemId?` | no | **new**: the id of the sub-item (a criterion or a step) the change names. Absent for a change of the node itself. A check or a reference has no id: its edit is a `set` with `item_id` the step (or none, for the node) and `field` `/checks` or `/references`, `old` and `new` the whole arrays | +| `field` | `string?` | no | A JSON pointer for `set`: into the node, or, with `item_id`, into that sub-item (`/commit_sha` of a step). Never an array index of a sub-item array | +| `old` | JSON value? | no | The value before, for `set` | +| `new` | JSON value? | no | The value after, for `set` | + +**Display id.** A sequential id (`A1`, `A2`) collides when two branches mint the next number. The +display id is derived on read: `A-` followed by the shortest suffix of the ULID that is unique in +the campaign, at least 6 characters (`A-7QX3NM`). An imported amendment shows its `legacy_id` +instead (`A1`). The display id is never stored. + +**Legacy rows.** A legacy log row `| A1 | 2026-11-16 | | ["x.md"] | |` becomes one +amendment: `legacy_id: "A1"`, `ts` from the date, `actor.kind: "import"`, `source`, `description` +from the rationale, and one `{node_id, op: "add"}` change per filename in `Nodes Added`, resolved +to node ids after the nodes are imported. The cell is a JSON-like list, written as `["a.md"]` or +`[ "a.md" ]`; the importer reads both. A legacy log sits in the README of the directory that added +the nodes; the amendment is stored once, at the campaign root, and `changes` name the nodes. + +## Format version + +| Item | Decision | +|:--|:--| +| Field | `schema_version`, a string `"0.X.Y"`, in every file | +| First value | `"0.1.0"`. The crate stays at `0.x` until M7, so the format does too. Revised 2026-11-25: `0.1.0` is redefined by [contracts.md](contracts.md) (flat nodes, no ids on checks and references); nothing was stored in the old shape, so no layer reads it | +| Constant | `FORMAT_VERSION` in `rdm-schema` | +| Bump X (`0.X.y`) | A breaking change while the major is `0`: a field removed, renamed or given another meaning, or a field made required | +| Bump Y (`0.x.Y`) | An addition that does not change the meaning of what exists: a new optional field, or a new enum value. Revised 2026-11-25: older binaries refuse it too | +| Reader | Reads the `schema_version` first. **Every** file newer than the binary, a higher Y included (Eliott, 2026-11-25), is refused with `NewerFormat { found, supported }` before anything else of it is parsed. It keeps unknown fields (I12), warning once per key, and reads an older file through the layer of its version (`Layer`) | +| Layer | One `FormatLayer` per format line `(major, minor)`, each overriding only what changed; a behaviour a version lacks is `NotInVersion`. The chain, the reading order and the write-version rule are in contracts.md §Version chain | +| Writer | An edit rewrites the files it touches in the current version, stamped `FORMAT_VERSION`; a read never writes. One campaign may hold files of different versions | +| Where bumps come from | The commit messages (see `Release`): the crate's version is decided from commit types and scopes by the repository's existing multi-semantic-release setup, not by hand | +| Relation to the crate | A breaking format change forces a crate X bump, a compatible one at least a Y bump. The read-model version is a separate constant, in `read-model.md` | + +### Release + +The crate's version is decided from commit types and scopes by `@semantic-release/commit-analyzer` +(`release-config.js`, `.github/workflows/release.yml`, which release `skills/**` only today). A +`!` or BREAKING commit gives X and `feat` or `fix` gives Y, while the crate stays `0.x`. Wiring +the crate into that release job, with a rule that keeps a breaking change at `0.x` (semantic-release +goes to 1.0.0 by default), is M7's job. No CI check is added for versions. + +## Changes against R01 + +| Area | R01 sketch | This schema | +|:--|:--|:--| +| Criteria | `preconditions[]`, `success_gates[]` as plain text | `Criterion {id, text, met}`, at leaf and directory level, enforced, with `Mark` records in `marks` that point by `criterion_id` | +| Sub-item ids | `id` on a step only | an `id` on criteria and steps only, and no record pointing by position. Checks and references have none (`Stable identity`, revised 2026-11-25) | +| Layout and place | one file per node in a directory tree; the name is the path segment | `nodes/.json`; `name`, `parent_id` and `order` in the file; children, depth and path derived (A2) | +| Corrections | none | `correction?` on `Amendment`, `Mark` and `History`, with a reason; the count is derived | +| Step | `{id, goal, implementation_logic, deliverables[], checks[], commit, references[], requires[], done, commit_sha?}` | adds `title`, `done_at?`; `implementation_logic` and `deliverables` are `lines`; `requires` is optional prose; `id` is kept and the number is derived | +| Check | `{command, expected}` | `{text, expected, command?}` | +| Commit | `{type, scope, summary}` | `{type, scope?, breaking, summary}` | +| Reference | `references[]`, no shape | `{label?, title, target?, note?, node_id?}`; `target` is absent when `node_id` is set | +| Status | `blocked_reason?` | `status_reason?`; vocabulary per `statuses.md` | +| History | `{ts, from, to, actor, note?, override?}` | `note` is `reason`; adds `op_id?`; `actor` is an object | +| Comments | none | one file each, `_comments/.json`, naming the node | +| Amendment | `{… id, …}` | adds `legacy_id?`; the id is a ULID with a derived display id. `Change` drops `path_before` and `path_after` (a path is derived from ids and goes stale on a move; a rename or a move holds its old and new `name` or `parent_id` and `order`) and `item_id` names a criterion or a step only (revised 2026-11-25) | +| Directory | no notes | adds `notes` | +| Progress | `{branch?, notes}` | adds `commits?` (import only); `notes` is `lines` | +| Gotchas, context | strings or lines unstated | `lines` | +| Unknown fields | I12 stated | Every type keeps them, nested ones too | +| Format version | "every file carries `schema_version`" | `"0.X.Y"`, first value `"0.1.0"`, reader rules above; a version chain of layers (A2) | + +**Finding against R01 (invariant I8).** R01 says a leaf is `done` only when every step is done +with its commit recorded. A leaf imported from legacy markdown is `done` and has no `commit_sha` +on any step: the grammar never stored one. If I8 were checked on stored state, every imported done +leaf would fail. Resolution: I8 is checked when the move to `done` is made, and the stored-state +rule is "`done` leaf has every step `done`". The import records the legacy count in +`progress.commits`. `r01_sync` rewrites I8 to say so. This was not in `statuses.md`, whose `R01 +deltas` row for I8 says "unchanged"; this document supersedes that row. + +**Recorded objection (coordinator kept the default): `status_reason` is a copy of the last history reason.** It is derived data stored +beside its source, which I6 forbids. The default keeps it because an imported `blocked → cancelled` +leaf has no history entry to hold the reason. Alternative: the importer writes one `history` entry +with `actor.kind: "import"` and `status_reason` is derived. Default kept, with the consistency +rule in `Leaf`. Decided 2026-11-16 (coordinator). + +## Decisions + +| # | Decision | Decided | +|:--|:--|:--| +| 1 | Criteria are enforced: `met` gates the start (pre-conditions) and `done` (gates), and gates a directory's `done`. Reverses the earlier rule that `met` gates nothing | Eliott, 2026-11-16 | +| 2 | Every change of a criterion mark writes a `Mark` (`ts`, `actor`, `criterion_id`, `met`, `evidence?`, `reason?`, `correction?`), in `marks` on `Leaf` and on `Directory` | Eliott, 2026-11-16 | +| 3 | Legacy done nodes with an open criterion are imported as they are, and reported by `validate` as errors to reconcile. The importer never ticks | Eliott, 2026-11-16 | +| 4 | Versions are `0.X.Y`; a breaking change bumps X, a compatible one Y; bumps come from commit messages through the existing release setup; M7 wires the crate | Eliott, 2026-11-16 | +| 5 | The mark records live in a `marks` array beside `history`, not inside it, so the last `history` entry stays the last status move (`status_reason` rule) | coordinator, 2026-11-16 | +| 6 | Sealing becomes a reason requirement: `done` and `cancelled` nodes accept every edit with a non-blank reason, flagged `correction: true` on the `Amendment`, `Mark` or `History` record, and a reversal out of `done` is a history entry with `correction: true`. A `correction_count` is derived in the read model | Eliott, 2026-11-16 | +| 7 | Every addressable sub-item has a stable id, minted at creation and never reused or derived from position: criteria, references, checks, steps (narrowed by row 10: criteria and steps only). `Mark.criterion_id` replaces `index` and `kind`; `Change.item_id` replaces array-index pointers; the importer mints the ids. Invariant: no record refers to a sub-item by position, and every mutation leaves existing references valid | Eliott, 2026-11-16 | +| 8 | The audit also moved `Amendment.snapshot` to node-id keys and added `Reference.node_id` for node targets | coordinator, 2026-11-16 (follows from row 7) | +| 9 | Flat layout: a node holds `name`, `parent_id` and `order`; the filesystem no longer mirrors the tree; depth is computed from the `parent_id` chain | Eliott, 2026-11-25 (A2) | +| 10 | An id is given by the rule "pointed at from outside, and its natural key can change". Row 7 is narrowed: checks and references lose their ids, and their edits are recorded at the array level. `Reference.target` is absent when `node_id` is set | contracts_design, 2026-11-25, under Eliott's rulings 3 and 6 (A2) | +| 11 | The campaign root's `name` is the campaign slug (still no `parent_id`, no `order`); `open` is given the expected slug and treats the parentless node carrying it as the root. Cross-file damage is reported, not refused | Eliott, 2026-11-25 (review), coordinator, 2026-11-25 | +| 12 | A file newer than the binary is refused whether the higher part is X or Y; each unknown key kept is reported as a warning | Eliott, 2026-11-25 (review) | diff --git a/__design__/rdm/traceability.md b/__design__/rdm/traceability.md new file mode 100644 index 0000000..917ae56 --- /dev/null +++ b/__design__/rdm/traceability.md @@ -0,0 +1,156 @@ +# rdm — Traceability of the legacy grammars + +Every production of `leaf.bnf` and `readme.bnf` has one row, with a disposition: + +| Disposition | Meaning | +|:--|:--| +| `stored` | The fact is a field of the stored schema. The target is the field path in [stored-schema.md](stored-schema.md) | +| `derived` | The fact is computed on every read and never stored (I6). The target says from what | +| `dropped` | The fact is not kept. The target is the reason | + +`uv run --no-project tools/check_rdm_traceability.py` prints each grammar with +`bash skills/managing-roadmaps/scripts/dirtree-rdm.sh grammar leaf` and `grammar readme`, and +fails unless every production appears in the matching table below with a valid disposition and a +non-empty target. It also fails on a row that names no production, so a renamed production cannot +leave a stale row. + +Counts: `leaf.bnf` has 22 productions. `readme.bnf` has 57. The plan says 58; the printer's +header carries one more `::=` in a comment (` ::= production`), which defines nothing. +Four names occur in both grammars (``, ``, ``, +``) and have a row in each table. + +Cells do not contain a pipe character, so the script can split rows on it. "Presentation" means +that the export (M3) re-creates the text from stored fields. + +## Leaf grammar + +| Production | Disposition | Target or reason | +|:--|:--|:--| +| `` | `stored` | One `Leaf` file, `.json`. The order of H1, header and steps is export layout | +| `` | `stored` | Leaf `goal`, `preconditions`, `success_gates`, `references`. The grammar is order-insensitive, so no order is kept | +| `` | `stored` | Leaf `goal`, `preconditions`, `success_gates` or `references`, the four header fields below | +| `` | `stored` | `goal`, one line | +| `` | `stored` | `preconditions[]` | +| `` | `stored` | `success_gates[]` | +| `` | `stored` | `references[]`, the line split on a semicolon and a space into `Reference`, each with a minted `id` | +| `` | `stored` | `preconditions[].id` (minted by the importer), `.text` and `.met`; `[x]` is `true`, `[ ]` is `false` | +| `` | `stored` | `success_gates[].id` (minted by the importer), `.text` and `.met`; the check mark is `true`, the empty box is `false` | +| `` | `stored` | One element of `steps[]`, with a minted `steps[].id` | +| `` | `stored` | `steps[].title` is the text after the colon; the digit is dropped: the step number is derived from position and is never a reference: records point by `steps[].id` | +| `` | `stored` | `steps[]` fields `goal`, `implementation_logic`, `references`, `deliverables`, `checks` or `commit`, below | +| `` | `stored` | `steps[].goal` | +| `` | `stored` | `steps[].implementation_logic`, the body lines with blank lines kept. The header line and trailing blank lines are presentation | +| `` | `stored` | `steps[].references[]` | +| `` | `stored` | `steps[].deliverables`, one element, not split | +| `` | `stored` | `steps[].checks[].id` (minted), `.text` and `.expected`. The trailer `(expected: X)` becomes `expected`. `command` is not extracted: the check is prose | +| `` | `stored` | `steps[].commit.type`, `.scope`, `.breaking`, `.summary`. The backticks are presentation and are dropped | +| `` | `stored` | `steps[].requires`, prose lines | +| `` | `stored` | `title` | +| `` | `stored` | One element of `steps[].implementation_logic` | +| `` | `dropped` | A lexical helper. The lines it matches are stored through `implementation_logic[]` | + +Constraints the grammar states outside its productions, and where each one goes: + +| Constraint | Home | +|:--|:--| +| Step count is 1 to 5 | `validate` rule on `Leaf.steps` | +| Step numbers are sequential from 1 | Derived: a step's number is its position, so the rule cannot break | +| At least one implementation line is not blank | `validate` rule on `Step.implementation_logic` | +| All four header fields and the five required step fields are present | Required fields of `Leaf` and `Step` | +| Header and step field order is free | Dropped: the canonical order is the field table's | +| Pre-conditions and gates have one or more items | `validate` rule on `Leaf` | + +## README grammar + +| Production | Disposition | Target or reason | +|:--|:--|:--| +| `` | `stored` | One `Directory` file, `nodes/.json`. Section order is export layout | +| `` | `stored` | `title` | +| `` | `stored` | `context` | +| `` | `dropped` | Heading literal. The field name is `context` | +| `` | `stored` | `context`, the lines | +| `` | `stored` | `references[]`. The section is optional; an absent section is an empty array | +| `` | `dropped` | Heading literal, not a field | +| `` | `stored` | `references[]` | +| `` | `stored` | `references[].id` (minted) and `references[].label` is the letter R and two digits, `.title`, `.target`, `.note` from the text after the dash | +| `` | `stored` | `goal` | +| `` | `dropped` | Heading literal, not a field | +| `` | `stored` | `goal`, exactly one line | +| `` | `stored` | `preconditions[]` | +| `` | `dropped` | Heading literal, not a field | +| `` | `stored` | `preconditions[]` | +| `` | `stored` | `preconditions[].id` (minted), `.text` and `.met` | +| `` | `stored` | `success_gates[]` | +| `` | `dropped` | Heading literal, not a field | +| `` | `stored` | `success_gates[]` | +| `` | `stored` | `success_gates[].id` (minted), `.text` and `.met` | +| `` | `stored` | `gotchas`, verbatim lines. The section is optional; absent is an empty array | +| `` | `dropped` | Heading literal, not a field | +| `` | `derived` | The status view of the node's children, from their `status` or derived status | +| `` | `dropped` | Heading literal, not a field | +| `` | `derived` | The graph of the node's children, rebuilt on each export | +| `MERMAID_OPEN` | `dropped` | Markup; the export emits it | +| `MERMAID_CLOSE` | `dropped` | Markup; the export emits it | +| `` | `dropped` | The fixed line `graph TD`; the export emits it | +| `` | `derived` | One per child: the id is the child's `name`, the label is its `title`, the class is its status. 13 of 95 real labels differ from the child's H1; the title wins | +| `` | `dropped` | Colours are presentation; M6 owns the palette | +| `` | `dropped` | Colours are presentation. The class follows the status `ongoing` | +| `` | `dropped` | Colours are presentation | +| `` | `dropped` | Colours are presentation. The status `amendment` no longer exists (`statuses.md`) | +| `` | `dropped` | Colours are presentation. The status `blocked` no longer exists (`statuses.md`) | +| `` | `derived` | The table of the node's children, from the directory listing | +| `` | `dropped` | Heading literal, not a field | +| `` | `derived` | One row per child. Row order carries no meaning: siblings are parallel, so readers order by depth, kind and name. The authored row order is not kept | +| `` | `dropped` | Fixed header; the export emits it | +| `` | `dropped` | Markdown table syntax | +| `` | `derived` | A leaf row or a directory row | +| `` | `derived` | Name from the path, type from `kind`, status from `Leaf.status`. The emoji labels are presentation | +| `` | `derived` | Name from the path, status derived from the leaves under it (`statuses.md`). The emoji labels are presentation | +| `` | `stored` | `Amendment` files. The log of a directory is the amendments whose changes name its nodes | +| `` | `dropped` | Heading literal, not a field | +| `` | `stored` | `Amendment` files, one per row | +| `` | `dropped` | Fixed header; the export emits it | +| `` | `stored` | `Amendment.legacy_id`, `.ts`, `.source`, `.changes[]` (one add per filename), `.description` | +| `` | `stored` | `Leaf.progress` and `Directory.notes` | +| `` | `dropped` | Heading literal, not a field | +| `` | `derived` | Rendered from the progress of every leaf and the notes of every directory | +| `` | `dropped` | Fixed header; the export emits it | +| `` | `stored` | Leaf row: `Leaf.progress.branch`, `.commits`, `.notes`. Directory row: `Directory.notes`; its branch and commit count are dropped as copies of its leaves' | +| `` | `dropped` | A lexical helper. The lines it matches are stored through `context`, `gotchas` and `goal` | +| `` | `stored` | `Leaf.status`, through the mapping in `statuses.md`, `Legacy mapping` | +| `` | `stored` | As the node's `name`. The stored `id` (`n_` and 8 characters) is new and minted by the importer | +| `` | `stored` | As the leaf's `name`, without `.md`; the file is `nodes/.json` | +| `` | `stored` | As the directory's `name`; no directory exists on disk (flat layout, 2026-11-25) | + +## Stretched legacy data + +Data that the grammar accepts, or that the validator lets through, and that real campaigns bend. +Counts are over `__roadmap__/` at the date of this document. + +| Item | Evidence | Home or drop | Importer rule | +|:--|:--|:--|:--| +| Checked pre-conditions | 16 `[x]` pre-conditions outside the M0 and M0b campaigns; 150 gate check marks; 30 of 48 `done` leaves still carry an unmet gate | `stored`: `Criterion.met`, enforced (`statuses.md`, `Criteria`): the start needs every pre-condition `met`, `done` needs every gate `met`. Later changes of a mark are traced in `Leaf.marks` and `Directory.marks`, each pointing by `Mark.criterion_id` | `[x]` and the check mark give `true`. Nothing is inferred from the leaf's status, and no tick is invented. A `done` node left with an unmet criterion is imported as it is and reported by `validate` as an error to reconcile. The importer writes no `Mark` | +| Progress rows on directories | 3 rows: `implement/`, `finalize/` (both with dashes) and `packaging/` (branch, count 1, empty notes). R01 puts progress on leaves only | `stored`: `Directory.notes`. Branch and commit count are `dropped`, copies of the leaves' | A directory row sets `notes` and nothing else | +| Dash cells | 2 rows use an em dash (U+2014). The validator accepts only `-`, `--` and `---` | `dropped` as a value: a dash means absent | `—`, `–`, `-`, `--` and `---` all mean no value | +| Rows the validator never reads | Its row loop stops silently at the first row that does not match. Only 1 of 14 real Progress rows matches: 11 write the branch in backticks, 2 use the em dash, and 5 have an empty Notes cell, which its pattern cannot match either | No fact lost in the schema | The importer reads every row, strips backticks around the branch, and accepts an empty Notes cell. A row it cannot read is kept as text in `Directory.notes` with a warning, never skipped | +| Commit count above the step count | `dirtree-rdm-cli-ux/refine-output-rendering.md`: 5 commits for 4 steps ("4 step commits + 1 clippy fixup") | `stored`: `Leaf.progress.commits`, import only. For an engine-recorded leaf the count is derived from `commit_sha` | A numeric cell is copied. `-` leaves it absent | +| Done leaves without commit shas | Legacy markdown holds no per-step commit | `Step.commit_sha` is absent on imported steps. I8 is checked on the move to `done`, not on stored state (`stored-schema.md`, `Changes against R01`) | Imported steps of a `done` leaf are `done: true` with no sha | +| The `Requires` step field | 0 uses in any campaign | `stored`: `Step.requires`, prose lines, never ids (I1) | The line is copied as one element | +| Amendment log | 2 rows, both `A1`: `agent_plugin_nest` and `roadmap-mcp-rework`. `Nodes Added` holds filenames, written `["x.md"]` or `[ "x.md" ]`. `Source` holds a report path | `stored`: `Amendment` with `legacy_id` | Both list spellings are read. The date becomes midnight UTC. The actor is `import` | +| Amendment log per directory | Each README has its own log; R01 has one `_amendments/` per campaign | `stored` once, at the campaign root | The importer collects every row of every README | +| Node added by an amendment | The one such node, `hub_mode_reconciliation.md`, is `done`. No node carries the status `amendment` | The origin is the amendment's `add` change | Status maps as written; nothing else | +| Statuses in use | 26 planned, 4 in progress, 65 done; 0 blocked; 0 amendment | Mapping in `statuses.md` | None beyond the mapping | +| Reference items without a label | `create-reporting-skill/README.md` lists a reference with no `R01` label, so its validation fails at that line | `Reference.label` is optional in the type | The label is absent and the importer warns. `validate` requires a label in a directory | +| Mermaid labels | 13 of 95 differ from the child's H1 | `dropped`: derived from `title` | The H1 wins; the importer warns on a difference | +| Sibling order | Nodes-table row order | `stored` as each node's `order` key, in row order: a position for presentation, never a dependency | Readers order siblings by `(order, id)` | +| Bulleted References | `create-reporting-skill/write_test_definition_reference.md` (lines 13-14 and 34-35) and `write_knowledge_transfer_reference.md` (lines 11-12) write `**References**:` followed by bullet lines, not one `; `-separated line | `stored`: `references[]`, one `Reference` per bullet | Each bullet is one `Reference`, split as a directory item (`label`, `title`, `target`, `note`). Bullets and the one-line form give the same array | +| Sub-item identity | The legacy markdown has no id for a criterion, a reference, a check or a step: they are addressed by position or by text | `stored`: `Criterion.id`, `Reference.id`, `Check.id`, `Step.id` | The importer mints every id, once, at import (stable ids, `stored-schema.md`, `Stable identity`). A re-import of an edited file is not supported, so no id has to be matched to a legacy position | +| Step count | 23 leaves with 1 step, 16 with 2, 23 with 3, 3 with 4, 2 with 5 | `validate` rule: 1 to 5 | None needed; none exceeds 5 | + +## Decisions + +| # | Decision | Decided | +|:--|:--|:--| +| 1 | Criteria are enforced; legacy done nodes with open criteria are imported unchanged and reported by `validate`; the importer never ticks and writes no `Mark` | Eliott, 2026-11-16 | +| 2 | The importer mints the id of every addressable sub-item (criteria and steps; checks and references have no id since 2026-11-25, contracts.md §Id inventory). Legacy position is never stored as identity | Eliott, 2026-11-16 | +| 3 | A `done` legacy node with an open gate is reconciled by an ordinary reasoned mark (`correction: true`); the importer still writes no `Mark` | Eliott, 2026-11-16 | diff --git a/__reports__/m0-feasibility-spike/00-findings_spike_v0.md b/__reports__/m0-feasibility-spike/00-findings_spike_v0.md new file mode 100644 index 0000000..dda4f81 --- /dev/null +++ b/__reports__/m0-feasibility-spike/00-findings_spike_v0.md @@ -0,0 +1,223 @@ +# M0 feasibility spike: Findings (v0) + +Date: 2026-11-16 + +--- +type: findings +topic: m0-feasibility-spike +date: 2026-11-16 +version: v0 +prior-version: none +key-metric: data-to-paint (Desktop, 160 nodes, 438,707 B): 18 ms (prior: N/A, delta: N/A) +decision-required: confirm +--- + +## Headline Result + +metric: hosts where the stack works as designed +value: 0 of 3 as designed; 3 of 3 with a changed data path +unit: hosts +prior: N/A (first run) +direction: new + +Source: [desktop.md](trials/desktop.md), [vscode.md](trials/vscode.md), [cli.md](trials/cli.md). The pinned stack (rmcp =3.10.0, MCP 2026-07-28, Apps 2026-01-26) connects on all three hosts. Desktop cannot take page-to-server calls, so R01's "page polls an app-only tool" holds only on VS Code. + +## Results Tables + +### Gate table (gates of `__roadmap__/roadmap-mcp-rework/m0_feasibility_spike.md`) + +| # | Gate | Verdict | Evidence | +|:--|:--|:--|:--| +| 1 | Stub lists and calls its tool in Desktop, VS Code, CLI | PASS | Desktop: tool listed, called, page renders [desktop.md, Trial 1]. VS Code: connected and called [vscode.md, header]. CLI: `roadmap_view` found and called, `node_count` 16 [cli.md] | +| 2a | Page renders in Desktop and VS Code | PASS | Desktop 16 of 16 nodes and 160 of 160 from `_meta` [desktop.md, Trial 4]. VS Code 16 of 16 [vscode.md, Trial 1] | +| 2b | Leaf content through an app-only tool | DEVIATION | Desktop: BLOCKED, `IPC not available for MCP tool call`, no `serverTools` [desktop.md, Trial 1, Trial 2]. Leaf content reaches the page through the result `_meta` instead [desktop.md, Trial 4]. VS Code: PASS, `serverTools` advertised, no tool errors [vscode.md, Trial 1, Trial 2] | +| 2c | Full view | PASS (Desktop), DEVIATION (VS Code) | Desktop offers `inline` and `fullscreen` [desktop.md, Trial 2]; Eliott confirmed fullscreen works (2026-11-16, steering answer 3). VS Code offers `inline` only and fell back to the inline outline [vscode.md, Trial 1, Trial 2] | +| 2d | Zero network requests | PASS | `check:offline` passes for the built page (coordinator brief; the command output is not in a trial note). The only request is the deliberate localhost stream test [vscode.md, Trial 2; desktop.md, Trial 3: CSP-blocked] | +| 3 | Host dumps as raw JSON, protocol versions | DEVIATION | Capabilities and context are summarised per host [desktop.md, Trial 2; vscode.md, Trial 1]. Desktop's raw dump `desktop-host.json` is referenced but is not in the committed trial folder. No raw JSON for VS Code or CLI. Versions: PASS (see Protocol table) | +| 4 | Time to display, cold and warm, median and worst | PASS | Single runs accepted by Eliott (2026-11-16, steering answer 2). See Timing | +| 5 | Allow-rule string from a real session | PASS | Both forms read from `claude -p` 2.1.316 [allow-rule.md]. Desktop agrees for the project form [desktop.md, Trial 2] | +| 6 | Crate names free | DEVIATION | `rdm-core` was taken; Eliott chose `rdm-engine` on 2026-11-16 [milestone gate text; R01 commit af8ad04]. The availability check of the other three names is not in a trial note | +| 7 | Go or no-go per host | PASS | Next table | + +### Go or no-go per host + +| Host | Verdict | Reason | +|:--|:--|:--| +| Claude Code Desktop (5.11492.5) | **GO, inline and one-shot** | The page renders, and all view data can ride in the result `_meta`: 438,707 B painted 18 ms after arrival and cost the model 203 characters [desktop.md, Trial 4]. No tool call, resource read or stream works from the page [desktop.md, Trial 1, Trial 3] | +| VS Code Copilot | **GO, every channel** | `serverTools`, `serverResources` and the localhost stream all work; 4,391,237 B and 1,600 nodes paint first at 64 to 70 ms [vscode.md, Trial 2]. No fullscreen and no `ui/message` [vscode.md, Trial 1] | +| Claude Code CLI (2.1.316) | **GO for the tools** | Tool listed and called without a prompt under the allow rule [cli.md]. It renders no Apps [cli.md] | + +### Protocol versions + +| Host | MCP | Apps (view announced / host returned) | Evidence | +|:--|:--|:--|:--| +| Desktop | 2026-07-28 | 2026-01-26 / 2026-01-26 | Server refuses any other MCP version, and the host connected [desktop.md, header, Trial 2] | +| VS Code | 2026-07-28 | 2026-01-26 / 2026-01-26 | [vscode.md, header, Trial 1]. The earlier negotiation issue no longer applies | +| CLI | 2026-07-28 | not applicable | [cli.md] | + +### Host capabilities that decide the design + +| Capability | Desktop | VS Code | Source | +|:--|:--|:--|:--| +| `serverTools` | absent | present, `listChanged` | desktop.md T2; vscode.md T1 | +| `serverResources` | advertised, but every read failed `read_failed` | present, 65 reads worked | desktop.md T3; vscode.md T2 | +| Localhost stream (declared in `_meta.ui.csp.connectDomains`) | CSP-blocked in Trial 3. The Trial 4 capability list shows the domain; stream not re-tested | worked (SSE, 4,391,237 B) | desktop.md T3, T4; vscode.md T2 | +| `message` / `ui/message` | `message {text}` advertised; call returns ok, no `RDM_PROBE` in the transcript | not advertised | desktop.md T2, T4; vscode.md T1 | +| `availableDisplayModes` | `inline`, `fullscreen` | `inline` | desktop.md T2; vscode.md T1 | +| `updateModelContext` | `{text, image}`, returns ok, nothing in the transcript | `{image, audio, resource, resourceLink, structuredContent}`, ok | desktop.md T2; vscode.md T1 | + +### Model context versus page (Desktop) + +| Item | Seen by model | Delivered to page | Source | +|:--|:--|:--|:--| +| `structuredContent` | yes, contrary to the Apps spec; validated against `outputSchema` | yes | desktop.md T4 | +| Result `_meta`, scale 1 | no; 200 characters seen | 43,715 B, 16 of 16 nodes | desktop.md T4 | +| Result `_meta`, scale 10 | no; 203 characters seen | 438,707 B (about 439 KB), 160 of 160 nodes | desktop.md T4 | +| `result` channel, scale 1 | yes, 45,034 chars (about 11k tokens) | yes | desktop.md T3 | + +### Allow-rule string (CLI 2.1.316) + +| How the server loads | Rule string | Source | +|:--|:--|:--| +| Project `.mcp.json`, server `rdm` | `mcp__rdm__roadmap_view` | allow-rule.md | +| Plugin `managing-roadmaps`, server `rdm` | `mcp__plugin_managing-roadmaps_rdm__roadmap_view` | allow-rule.md | + +The hyphen of the plugin name is kept. **Trap:** a project server with the same name `rdm` wins, and the plugin name never appears. The first plugin check showed the project form for that reason [allow-rule.md]. + +### Other facts + +| Item | Value | Source | +|:--|:--|:--| +| Built page size | 279 to 286 KB, about 234 KB of it ext-apps with zod. The leaf's own limit was 250 KB [graph_view.md, Step 1 item 2] | coordinator brief; not in a trial note | +| macOS install trap | A binary overwritten in place is killed at start with SIGKILL (exit 137); the host reports "Couldn't reconnect rdm: Connection closed". Fix: `rm` then `cp`, a new inode | desktop.md T2 | +| Desktop user agent | `Claude/5.11492.5`, Electron 45.2.1, Chrome 156 | desktop.md header | + +## Timing + +Trial notes: [desktop.md](trials/desktop.md), [vscode.md](trials/vscode.md). Every figure is one sample, from the run named in its row. There are no medians and no confidence intervals. + +> **DEVIATION from the leaf.** The leaf asked for `timing.py` over a `probe.jsonl`, with a 20-run cold and warm series and bootstrap CIs. Neither exists. +> - Claude Code Desktop does not let the page call the server ([desktop.md](trials/desktop.md), Trial 1: `IPC not available for MCP tool call`). No stamp could be recorded server-side. Probes were read off an on-screen panel. +> - At Eliott's steer, the spike measured data channels and payload sizes instead of a repeated series. +> - The single samples still answer the question. The number that matters is data-to-paint, and it is tens of ms in every run. The large figures are host-side delays that follow user attention: Desktop creates the page frame only when the message is on screen ([desktop.md](trials/desktop.md), Trial 4 scale 10: 670,660 ms, Eliott scrolled back after about 11 minutes). No repetition would shrink a delay that depends on the reader. No `timing.py` was written. + +### Data to paint, per host and channel (one sample each) + +| Host | Channel | Payload [source] | Data reached page | First paint | Complete | +|:--|:--|:--|:--|:--|:--| +| Desktop | `_meta`, scale 1 | 43,715 B, 16 nodes [desktop.md, Trial 4] | 318 ms after server stamp | 371 ms | 372 ms | +| Desktop | `_meta`, scale 10 | 438,707 B, 160 nodes [desktop.md, Trial 4 scale 10] | 18 ms from data to first paint | same as data | same as first paint | +| VS Code | `result` x1 | 43,715 B, 16 nodes [vscode.md, Trial 2] | 24 ms | 41 ms | 41 ms | +| VS Code | `chunks` x100 | 4,391,237 B, 1,600 nodes, 65 `resources/read` [vscode.md, Trial 2] | 39 ms | 64 ms | 597 ms | +| VS Code | `stream` x100 (SSE) | 4,391,237 B, 1,600 nodes [vscode.md, Trial 2] | 28 ms | 70 ms | 157 ms | +| VS Code | `_meta` x1 | 43,715 B, 16 nodes [vscode.md, Trial 2] | 23 ms | 39 ms | 40 ms | + +The Desktop scale-1 and scale-10 rows are not on the same clock. Scale 1 is server stamp to paint. Scale 10 is data arrival to first paint, because the server-to-page leg was lost to the user's delay (see next table). + +### Host-side delays that are not display time (one sample each) + +| Host | Run | Delay | Cause [source] | +|:--|:--|:--|:--| +| Desktop | `result` scale 1, Trial 2 | 46,970 ms | Eliott's copy delay. The panel showed the latest probe stamp, not first paint. Eliott saw the page paint at once [desktop.md, Trial 2] | +| Desktop | `_meta` scale 10, Trial 4 | 670,660 ms | Frame created when the message was on screen; Eliott scrolled back after about 11 min [desktop.md, Trial 4] | +| VS Code | `result` scale 1, Trial 1 | 73,679 ms | Unexplained: chat turn, trust prompt or off-screen page. Did not recur; later results arrived in 18 to 24 ms [vscode.md, Trial 1, Trial 2] | +| Desktop | `result` scale 1, Trial 3 | 2.3 s | Tool round trip, call to result in the transcript [desktop.md, Trial 3] | + +### Why one sample is enough here + +| Question | Answer from the data | +|:--|:--| +| Is display slow at the sizes M6 needs? | No. 438,707 B paints 18 ms after arrival on Desktop; 4,391,237 B starts painting at 64 to 70 ms on VS Code | +| Does noise hide a difference that matters? | The spread between the fast runs is tens of ms. The delays that look large are one to three orders of magnitude bigger and come from attention, not from the host or the page | +| What would a series add? | Tighter CIs on tens of ms. It would not change a go or no-go | + +Payload by scale in `chunks` mode, as the `payload_sizes_by_scale` probe printed it once before it was deleted from `rdm-mcp/tests/stdio.rs`: scale 1 is 43,715 B in 1 chunk, scale 10 is 438,707 B in 7 chunks, scale 100 is 4,391,237 B in 65 chunks. + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:--|:--|:--|:--| +| Page-to-server calls | R01: the page polls an app-only tool | Desktop declines: no `serverTools`, `IPC not available` [desktop.md T1, T2] | Polling cannot be the only update path. It works on VS Code only | +| `structuredContent` and the model | Apps spec: not added to model context | In Desktop it is, in full, and it is schema-validated [desktop.md T4] | Keep `structuredContent` a small, valid summary | +| Result `_meta` | Reaches the page and the model, if at all | Page only. 439 KB to the page, 203 characters to the model [desktop.md T4] | `_meta` is the free channel for view data on Desktop | +| `serverResources` on Desktop | Advertised means usable | `read_failed` for every URI [desktop.md T3] | The advertised list cannot be trusted. Test each channel | +| Declared CSP domain | Host honours `connectDomains` | Desktop blocked it, VS Code adopted it [desktop.md T3; vscode.md T1] | Streaming is a VS Code feature only | +| Display time | A figure to budget | Tens of ms from data to paint [Timing] | Display is not the bottleneck. Payload size and model cost are | +| Bundle | 250 KB limit of the leaf | 279 to 286 KB (coordinator brief) | Over the limit by 29 to 36 KB. ext-apps with zod is about 82% of it | +| Install | `cp` over the old binary works | Killed with SIGKILL on macOS [desktop.md T2] | The installer must write to a new inode | + +## Charts & Visualizations + +```mermaid +graph LR + S[rdm-mcp tool result] -->|structuredContent: small summary, validated| M[model context] + S -->|result _meta: full view data| P[inline page] + P -.->|tool call, resource read, stream| S +``` + +Caption: on Desktop the solid arrows work and the dashed arrow fails (no `serverTools`, `read_failed`, CSP). On VS Code the dashed arrow works too. + +## Proposed amendments (not applied) + +| Leaf | Proposal | Evidence | +|:--|:--|:--| +| M4 | View data goes in the result `_meta`. `structuredContent` stays a minimal summary that is valid against `outputSchema` in every mode | desktop.md T4 | +| M6 | A choice for Eliott, two designs below | below | +| M7 | Pin both allow-rule strings. Install binaries by `rm` then `cp` so each install has a new inode. Size the launcher cache with that in mind | allow-rule.md; desktop.md T2 | +| R01 §Graph view | "It polls an app-only tool" is invalidated for Desktop. Propose: "It is fed once from the result `_meta`. It polls an app-only tool or streams only where the host advertises `serverTools` or the stream domain". Not edited here: §Graph view is M0b's | desktop.md T1, T2; vscode.md T1 | + +### M6 design choice (Eliott decides) + +| | (a) Inline view fed once from `_meta`, progressive only where supported | (b) Standalone viewer: Svelte in Tauri or a local page driven by `rdm`, over IPC or RPC to the Rust core | +|:--|:--|:--| +| Evidence for | 438,707 B paints 18 ms after arrival on Desktop at no model cost [desktop.md T4]. VS Code streams 1,600 nodes with first paint at 64 to 70 ms [vscode.md T2] | Desktop inline has no tool call, resource read or stream [desktop.md T1, T3], so large or live views cannot refresh there. A standalone viewer has none of these limits [desktop.md, What this means] | +| Cost | Live refresh and leaf-on-demand only on VS Code. Bundle is over 250 KB | A second shell to ship and launch (M7) | +| Fits | Snapshot of the roadmap in the chat | Large and live views | + +## Contradictions & Surprises + +- `serverResources` is advertised on Desktop, yet every read failed [desktop.md T3]. +- `structuredContent` enters the model context in Claude Code, against the Apps spec [desktop.md T4]. +- The 2026-07-28 negotiation issue known for VS Code did not occur [vscode.md header]. +- The built page is over its own size limit [coordinator brief]. + +## Steering Questions + +- [now] M6: design (a), inline from `_meta`, or (b), standalone viewer, or (a) first and (b) later? +- [now] Accept the single-sample timing as the answer to the timing gate, or ask for a series? +- [next run] Re-test the Desktop stream, since the capability list now shows the domain, and exercise Desktop fullscreen, which the notes do not record? +- [later] Accept the bundle at 279 to 286 KB, or write a hand-made bridge to cut the 234 KB of ext-apps with zod? + +## Pointers + +- [trials/desktop.md](trials/desktop.md) +- [trials/vscode.md](trials/vscode.md) +- [trials/cli.md](trials/cli.md) +- [trials/allow-rule.md](trials/allow-rule.md) +- [README.md](README.md) +- `__design__/rdm/architecture.md` +- `__roadmap__/roadmap-mcp-rework/m0_feasibility_spike.md` + +## Steering answers (Eliott, 2026-11-16) + +| # | Topic | Answer | +|:--|:--|:--| +| 1 | M6 | The inline view fed from the result `_meta` is the direction: it is the only path working on two hosts (Desktop and VS Code) | +| 2 | Timing | Single runs are accepted for these probes. The timing gate is PASS | +| 3 | Desktop fullscreen | Eliott confirmed it works. The full-view gate is PASS for Desktop (gate table row 2c updated) | +| 4 | Bundle size | Measured below. Untested on any host. The page never enters the model context, so the choice is left to M6 | + +Context for answer 1: + +- No new dated MCP Apps spec is announced. The only dated version is 2026-01-26. The draft keeps moving, most recently on 2026-11-04, when the double-sandboxed iframe requirements were relaxed. +- The spec deprecates the flat `_meta["ui/resourceUri"]` key "before general availability". We use the nested `_meta.ui.resourceUri`. +- ext-apps v2.1.0 shipped on 2026-11-10. We pin 2.0.4. + +Bundle size, measured on 2026-11-16 by the coordinator. ext-apps was swapped for a 73-line hand-written bridge making the same calls. + +| Build | Raw | Gzip | +|:--|:--|:--| +| With ext-apps 2.0.4 | 286,141 B | 78,949 B | +| Hand-written bridge | 54,487 B (-81%) | 20,415 B | + +The bridge is about 2.1 KB minified. diff --git a/__reports__/m0-feasibility-spike/01-knowledge_transfer_v0.md b/__reports__/m0-feasibility-spike/01-knowledge_transfer_v0.md new file mode 100644 index 0000000..01fd23a --- /dev/null +++ b/__reports__/m0-feasibility-spike/01-knowledge_transfer_v0.md @@ -0,0 +1,58 @@ +# M0 feasibility spike: Knowledge Transfer (v0) + +Date: 2026-11-16 + +## Executive Summary + +| Item | Outcome | +|:--|:--| +| Shipped | `rdm-mcp` spike server, Svelte graph view, trial notes for Desktop, VS Code and CLI, findings report | +| Result | The stack works on 3 of 3 hosts, but only with a changed data path: view data rides in the result `_meta` | +| Decisions | M6 goes inline from `_meta` (Eliott, 2026-11-16). See [00-findings_spike_v0.md](00-findings_spike_v0.md) | +| Budget | USD 30 for M0 and M0b. The counter reached USD 30.39. Eliott topped up USD 10 | + +## Wins + +| Win | Why it matters | +|:--|:--| +| Result-`_meta` channel, found by testing | Desktop refuses page-to-server calls. `_meta` reached the page (439 KB) and cost the model 203 characters | +| Per-host matrix | Capabilities advertised by a host proved unreliable (`serverResources`). The matrix records what works | +| Allow-rule string read from a real session | Both forms are pinned for M7 instead of guessed | + +## Pain Points and Fixes + +| Pain point | Fix for next time | +|:--|:--| +| A binary overwritten in place was SIGKILLed on macOS (exit 137) | Install as `rm` then `cp`, so the file gets a new inode | +| `structuredContent` failed `outputSchema` because `frozen_at` was dropped. A test chain still committed, because `grep` succeeded | Add a schema-validation test for every tool output. Gate commits on the test exit code, not on a `grep` | +| A project `.mcp.json` with the same server name masked the plugin server | Check which config wins before reading a rule string. Use a distinct name per trial | +| zsh `==` expansion broke a command | Quote such words, or avoid them in zsh | +| The CLI OAuth had expired | Check CLI login before scheduling a CLI trial | +| A user-attention gap was read as host latency. Desktop creates the page frame only when the message is shown (670,660 ms) | Separate data-to-paint from time-to-attention in every timing table | +| The planned 20-run cold and warm series was replaced, at Eliott's steer, by a channel and payload study | Fine: the study answered the real question. Confirm the replacement in the plan before the trial | +| The coordinator first dismissed Eliott's standalone viewer idea | Record a user idea as a design option with evidence for and against before dismissing it | +| Budget: the coordinator missed the per-level spend reports and the USD 24 checkpoint | Report spend at every level, and stop at the checkpoint | + +## Root Causes + +- Host trials came late, so host limits surfaced after the build. +- Tool outputs had no schema test, so a drift shipped. +- The budget rule existed but nothing forced the report. + +## Next-Cycle Changes + +| Area | Change | +|:--|:--| +| Workflow | Spend report at every level, with a checkpoint at 80% of budget | +| Testing | A schema-validation test for every tool output | +| Workflow | Set up host trials earlier, in parallel with the build | + +## Artifacts to Preserve + +- [00-findings_spike_v0.md](00-findings_spike_v0.md) with the steering answers +- [trials/](trials/): desktop, vscode, cli, allow-rule + +## Open Questions + +- M6: keep ext-apps 2.0.4 or take the 54 KB hand-written bridge (untested on any host)? +- Re-test the Desktop stream, since the capability list now shows the domain. diff --git a/__reports__/m0-feasibility-spike/README.md b/__reports__/m0-feasibility-spike/README.md new file mode 100644 index 0000000..80e5a14 --- /dev/null +++ b/__reports__/m0-feasibility-spike/README.md @@ -0,0 +1,21 @@ +# m0-feasibility-spike reports + +## Documents + +| Round | Document | Status | +|:--|:--|:--| +| 00 | [00-findings_spike_v0.md](00-findings_spike_v0.md) | latest, with steering answers | +| 01 | [01-knowledge_transfer_v0.md](01-knowledge_transfer_v0.md) | latest | + +## Trial notes + +| Note | Subject | +|:--|:--| +| [trials/desktop.md](trials/desktop.md) | Claude Code Desktop, four trials | +| [trials/vscode.md](trials/vscode.md) | VS Code Copilot, two trials | +| [trials/cli.md](trials/cli.md) | Claude Code CLI | +| [trials/allow-rule.md](trials/allow-rule.md) | Allow-rule string | + +## Status + +The findings report is written. M4, M6 and M7 amendments are proposed, not applied. Steering answers are recorded in the findings report. The knowledge-transfer report closes M0. diff --git a/__reports__/m0-feasibility-spike/trials/allow-rule.md b/__reports__/m0-feasibility-spike/trials/allow-rule.md new file mode 100644 index 0000000..b20557f --- /dev/null +++ b/__reports__/m0-feasibility-spike/trials/allow-rule.md @@ -0,0 +1,11 @@ +# Allow-rule string + +Read from real `claude -p` sessions on 2026-11-16, CLI version 2.1.316. + +| How the server is loaded | Tool name, and therefore the allow-rule string | +|:--|:--| +| Project `.mcp.json`, server `rdm` | `mcp__rdm__roadmap_view` | +| Plugin `managing-roadmaps` (local dev copy through `--plugin-dir`), server `rdm` | `mcp__plugin_managing-roadmaps_rdm__roadmap_view` | + +- **The hyphen survives:** the plugin form is `mcp__plugin____`, and the hyphen in `managing-roadmaps` is kept as is. +- **A same-named project server wins:** when a project `.mcp.json` also defines `rdm`, that project server takes over and the plugin name never appears. The first plugin check, run in the trial folder, showed `mcp__rdm__roadmap_view` for that reason. diff --git a/__reports__/m0-feasibility-spike/trials/cli.md b/__reports__/m0-feasibility-spike/trials/cli.md new file mode 100644 index 0000000..d83767a --- /dev/null +++ b/__reports__/m0-feasibility-spike/trials/cli.md @@ -0,0 +1,7 @@ +# Claude Code CLI trial + +CLI version 2.1.316, run with `claude -p` on 2026-11-16, using the project `.mcp.json` from `feat-m0-feasibility-spike`. + +- **Tools:** `roadmap_view` is deferred and found through ToolSearch as `mcp__rdm__roadmap_view`. It was called with `{mode: meta, scale: 1}` and returned the 2026-07-28 summary (`node_count` 16). The server refuses any other protocol version, so the CLI speaks 2026-07-28. Cost: USD 0.089. +- **Allow rule:** `--allowedTools mcp__rdm__roadmap_view` let the call run without a prompt. +- **Rendering:** the CLI does not render MCP Apps. Only the tool call was tested. diff --git a/__reports__/m0-feasibility-spike/trials/desktop.md b/__reports__/m0-feasibility-spike/trials/desktop.md new file mode 100644 index 0000000..ebbe2f7 --- /dev/null +++ b/__reports__/m0-feasibility-spike/trials/desktop.md @@ -0,0 +1,47 @@ +# Desktop trials (Claude Code Desktop) + +Host: Claude Code Desktop. The user agent reports `Claude/5.11492.5`, Electron 45.2.1 and Chrome 156. Server: the `rdm-mcp` stub on rmcp =3.10.0, 2026-07-28 only, registered as the project stdio server `rdm`. Observed by Eliott on 2026-11-16. + +## Trial 1: render and app-only tools +- `roadmap_view` is listed and called, and the page renders "rather fast": **PASS**. +- Clicking a leaf (`leaf_get`, app-only) fails with `ProtocolError: IPC not available for MCP tool call`. +- No `probe_record` line reached the server: every call from the page to the server failed. + +## Trial 2: host data (diagnostics panel) +- **`hostCapabilities`:** `openLinks`, `serverResources`, `logging`, `sandbox`, `updateModelContext {text, image}` and `message {text}`. **There is no `serverTools`.** Under the Apps spec a page may proxy tool calls only when the host advertises that, so the IPC error is the host declining by design. +- **Apps protocol:** the page announced `2026-01-26` and the host returned `2026-01-26`. +- **Display:** `displayMode` is `inline`, and `availableDisplayModes` is `["inline", "fullscreen"]`. +- **`hostContext` keys:** `toolInfo`, `theme` (dark), `styles` (host CSS variables, plus `css.fonts`, which loads fonts from `assets.claude.ai`), `displayMode`, `availableDisplayModes`, `containerDimensions` (width 731, maxHeight 5000), `locale`, `timeZone`, `userAgent`, `platform` (desktop), `deviceCapabilities` (hover, no touch) and `safeAreaInsets`. The raw dump is in [desktop-host.json](desktop-host.json), with `styles` left out. +- **`updateModelContext`:** returns ok, but nothing appears in the session transcript. +- **Timing:** the panel showed 46,970 ms, which was Eliott's copy delay. The panel displayed the stamp of the latest probe, not of first paint. Eliott saw the page paint immediately. +- **Allow-rule string (project server):** `mcp__rdm__roadmap_view`, read from the session transcript. +- **macOS install trap:** the trial binary had been overwritten in place. macOS killed it at start (exit 137), so the host reported "Couldn't reconnect rdm: Connection closed". The fix is to install onto a new inode (`rm` then `cp`). + +## Trial 3: data channels (mode × scale) +| Channel | Result | +|:--|:--| +| `result`, scale 1 (43,715 B payload) | Renders. The tool result lands in the model context in full (45,034 chars in the transcript, about 11k tokens). Tool round trip 2.3 s (call 08:14:25.573, result 08:14:27.871). | +| `resources/read` from the page (`rdm://leaf/…`, `rdm://chunk/…`) | `ProtocolError: Resource unavailable: read_failed` for every URI, although `serverResources` is advertised | +| `stream` (SSE from `127.0.0.1:`, declared in `_meta.ui.csp.connectDomains`) | `CSP violation: connect-src blocked http://127.0.0.1:60021/…`. The host does not honour the declared domain | +| Tool call from the page | Still `IPC not available` | +| `ui/message` probe | No `RDM_PROBE` message in the transcript | + +## What this means +In this host the inline page can only show what the tool result carries, and the model's context pays for every byte of it. Leaf content, large roadmaps, streaming and live refresh cannot reach an inline page here. A standalone viewer has none of these limits: Svelte in Tauri, or in a local browser page, talking to the Rust core over IPC or RPC (Eliott's suggestion). + +## Trial 4: `meta` mode (data in the tool result's `_meta`) +Run on 2026-11-16 after the fix that keeps `frozen_at` (commit `7981e5c`). The first attempt failed because the host validates `structuredContent` against the tool's `outputSchema`, and the summary lacked the required `frozen_at`. + +| Scale | Model saw (transcript tool_result) | Page got | t_result − t_server | first paint | complete | +|:--|:--|:--|:--|:--|:--| +| 1 (43,715 B) | 200 chars (the summary only) | 16 of 16 nodes from `_meta` | 318 ms | 371 ms | 372 ms | +| 10 (~439 KB) | 203 chars (the summary only) | panel not captured yet | | | | + +- **The finding:** Claude Code Desktop hands the result-level `_meta` to the page and does NOT put it in the model context. It does put `structuredContent` in the model context, contrary to the Apps spec's "not added to model context". So the full roadmap can reach the inline page at no token cost, if it travels in `_meta`. +- **The host validates `structuredContent` against `outputSchema`,** so every required field must be present in every mode. +- **Capabilities that changed on this run:** `ui/message` returned ok this time, but no `RDM_PROBE` text was found in the transcript. `hostCapabilities.sandbox.csp.connectDomains` now lists the declared `http://127.0.0.1:`, yet Trial 3's stream was CSP-blocked. Re-test the stream before concluding. + +### Trial 4, scale 10 (Eliott's panel) +- 160 of 160 nodes from `_meta` (438,707 B). First data to first paint: 18 ms. Complete paint came at the same time as first paint. +- `t_result − t_server` was 670,660 ms. Desktop creates the page frame only when the message is on screen, and Eliott scrolled back to it about 11 minutes later. So server-to-page time in Desktop measures when the user looks, and data-to-paint is the comparable number. +- `ui/message` returned ok, and no `RDM_PROBE` reached the transcript. diff --git a/__reports__/m0-feasibility-spike/trials/vscode.md b/__reports__/m0-feasibility-spike/trials/vscode.md new file mode 100644 index 0000000..6a22547 --- /dev/null +++ b/__reports__/m0-feasibility-spike/trials/vscode.md @@ -0,0 +1,32 @@ +# VS Code Copilot trials + +Host: VS Code Copilot, observed by Eliott on 2026-11-16. The server is the same stub, which speaks 2026-07-28 only. VS Code connected and called it, so it negotiated 2026-07-28. The open issue about VS Code not negotiating that version no longer applies. + +## Trial 1: `result`, scale 1 (diagnostics panel) +- **Render:** the page renders 16 of 16 nodes, receiving 43,715 bytes. +- **Timing:** `t_result − t_server` is 73,679 ms. First paint and complete paint are both 24 ms after the data arrived. The 73.7 s before the result reached the page is not yet explained: it may be the host waiting for the chat turn, a trust prompt, or the page being off-screen. To be checked with Eliott. +- **`hostCapabilities`:** + - `openLinks` and `downloadFile` + - **`serverTools {listChanged}`** and **`serverResources {listChanged}`** + - `logging` + - **`sandbox.csp.connectDomains ["http://127.0.0.1:60608"]`** (VS Code adopted the domain the page declared), and `sandbox.permissions.clipboardWrite` + - `updateModelContext {image, audio, resource, resourceLink, structuredContent}` + - **There is no `message`.** +- **`hostContext`:** theme (dark), styles (mapped to VS Code theme variables), `displayMode` inline, **`availableDisplayModes ["inline"]` only**, `containerDimensions` 902×945, locale `en-us`, platform desktop, and `toolCall {toolCallId, toolName: "rdm-roadmap_view"}`. +- **Protocol:** the Apps protocol was `2026-01-26` both ways. `ui/message` was skipped, because the host does not advertise it. `update-model-context` returned ok. There were no tool errors. + +## What this means +VS Code advertises every channel that Claude Code Desktop lacks: tool calls from the page, resource reads and the localhost stream. It does not offer fullscreen or `ui/message`. + +## Trial 2: every channel (2026-11-16, Eliott, one session, in order) +| Mode | Payload | Data reached page | First paint | Complete | +|:--|:--|:--|:--|:--| +| `result` ×1 | 43,715 B, 16 nodes | 24 ms | 41 ms | 41 ms | +| `chunks` ×100 | 4,391,237 B, 1,600 nodes (65 resources/read) | 39 ms | 64 ms | 597 ms | +| `stream` ×100 (SSE from `rdm-mcp` on 127.0.0.1) | 4,391,237 B, 1,600 nodes | 28 ms | 70 ms | 157 ms | +| `meta` ×1 (`_meta`) | 43,715 B, 16 nodes from `_meta` | 23 ms | 39 ms | 40 ms | + +- All times are measured from the server's stamp to the page, on one sample each. +- No tool errors. The full view fell back to the inline outline (`display mode: outline`), because VS Code offers no fullscreen. +- The 73.7 s of Trial 1 did not recur: every result reached the page within 18 to 24 ms. +- In VS Code all three channels work, and painting starts before the data is complete: 1,600 nodes paint first at 64 to 70 ms. diff --git a/__reports__/m0b-domain-model-spec/00-knowledge_transfer_v0.md b/__reports__/m0b-domain-model-spec/00-knowledge_transfer_v0.md new file mode 100644 index 0000000..17cc4ed --- /dev/null +++ b/__reports__/m0b-domain-model-spec/00-knowledge_transfer_v0.md @@ -0,0 +1,68 @@ +# M0b domain model spec: Knowledge Transfer (v0) + +Date: 2026-11-16 + +## Executive Summary + +| Item | Outcome | +|:--|:--| +| Shipped | Four spec docs in `__design__/rdm/` (statuses, stored schema, read model, traceability), and the `rdm-schema` crate | +| Reviewed | One adversarial verifier, then Eliott's review. Both found real defects | +| Rulings from review | Criteria are enforced (reversing an agent decision). Versions become three-part `0.X.Y` | +| Status | Both rulings are decided and being applied by the amendment node `read/crate/review/`, running in parallel with this report | + +## Wins + +| Win | Detail | +|:--|:--| +| Four spec docs | Statuses, stored schema, read model, traceability, with their Decisions sections | +| `rdm-schema` crate | 22 tests, committed JSON Schemas, and a drift test that also catches orphan schema files | +| Traceability checker | Covers all 79 grammar rules and checks stored targets against `stored.rs` | +| Legacy finding | The legacy validator silently read 1 of 14 Progress rows | + +## What the adversarial verifier caught (all fixed) + +| Defect | Fix | +|:--|:--| +| Order of unknown keys lost | `preserve_order` enabled | +| Hollow traceability checker | Targets now checked against `stored.rs` | +| Bulleted References in legacy leaves | Grammar coverage extended | +| Loose version patterns, parsing not strict | Patterns pinned, strict parsing | +| Null rule undocumented | Documented in the stored schema | +| Orphan schema files | Drift test fails on them | + +## Pain Points + +| Pain point | Fix for next time | +|:--|:--| +| **Main lesson: Eliott's review reversed one agent decision.** The specs read "30 of 48 done leaves carry an open gate" as licence to make `met` informational | Data showing a rule is broken in practice is evidence of poor upkeep, not a reason to drop the rule. Escalate such inferences instead of encoding them | +| The verifier missed that semantic error | It attacked consistency, not intent. Brief verifiers to challenge any rule an agent relaxed | + +### Eliott's rulings + +| Topic | Ruling | +|:--|:--| +| Criteria | Pre-conditions are enforced before `ongoing`, gates before `done`, and every mark is traced (who, when, evidence). Legacy done leaves with open gates become `validate` errors to reconcile, never auto-ticked | +| Versions | Three-part `0.X.Y`. Bumps come from commit types and scopes through the repo's existing multi-semantic-release setup. M7 wires the crate in | + +## Root Causes + +- An agent inferred a rule change from observed data, with no step forcing escalation. +- Verification checked internal consistency, so intent errors passed. + +## Next-Cycle Changes + +| Area | Change | +|:--|:--| +| Review process | The Eliott-review gate caught what the verifier missed. Brief verifiers to challenge any rule an agent relaxed | +| Instructions | Agents escalate any inference that relaxes a rule, instead of encoding it | + +## Artifacts to Preserve + +- `__design__/rdm/statuses.md`, `stored-schema.md`, `read-model.md`, `traceability.md` +- `crates/rdm-schema` and its committed JSON Schemas +- `tools/check_rdm_traceability.py` + +## Open Questions + +- Confirm the amendment node `read/crate/review/` lands both rulings in the specs and the crate. diff --git a/__reports__/m0b-domain-model-spec/README.md b/__reports__/m0b-domain-model-spec/README.md new file mode 100644 index 0000000..0b4909c --- /dev/null +++ b/__reports__/m0b-domain-model-spec/README.md @@ -0,0 +1,11 @@ +# m0b-domain-model-spec reports + +## Documents + +| Round | Document | Status | +|:--|:--|:--| +| 00 | [00-knowledge_transfer_v0.md](00-knowledge_transfer_v0.md) | latest | + +## Status + +The knowledge-transfer report closes M0b. Eliott's two review rulings (enforced criteria, `0.X.Y` versions) are decided and being applied by `read/crate/review/`. diff --git a/__reports__/m1-core-foundation/00-gap_analysis_v0.md b/__reports__/m1-core-foundation/00-gap_analysis_v0.md new file mode 100644 index 0000000..e34abdb --- /dev/null +++ b/__reports__/m1-core-foundation/00-gap_analysis_v0.md @@ -0,0 +1,123 @@ +# Gap Analysis: roadmap-mcp-rework — the M1 leaf predates M0 and M0b (v0) + +Date: 2026-11-25 + +This report is the source of amendment A2 of `__roadmap__/roadmap-mcp-rework/`. Eliott approved the rulings below on 2026-11-25, in the session that planned `__roadmap__/m1-core-foundation/`. A2 adds no node. It edits the prose of the M1, M2, M4 and M7 leaves and of the meta-roadmap README. + +## Problem Statement + +The M1 leaf was last edited before the M0 host trials and the two M0b review rounds finished. Its gates and its planning list rest on three assumptions those rounds replaced: +- a tree of nested directories; +- the refusal of a newer format *major* only; +- schemas that are settled and only need consuming. + +The leaf also defers three decisions to each other, so nobody owns them. M1 cannot be planned faithfully from the leaf as written. + +## Evidence + +| What | When (commit) | +|:--|:--| +| Last edit of `core/m1_core_foundation.md` | 2026-11-16 15:28 (`af8ad04`, the crate rename) | +| M0 host trials (desktop `_meta`, VS Code, CLI) | 2026-11-16 17:28–17:41 (`ff6cc8c` … `6f84ad5`) | +| M0 and M0b knowledge-transfer reports | 2026-11-16 18:33–18:34 (`ffc3b38`, `18b0615`) | +| M0b review: criteria enforced, three-part versions `0.X.Y` | 2026-11-16 18:35 (`9591a66`, `6843cc3`) | +| M0b second review: reasoned edits, stable sub-item ids | 2026-11-16 18:56–18:57 (`6a1bd41`, `265d873`, `c8b617f`) | + +Ownership loops and gaps found by reading the leaf against the M0b design docs: + +- **Id format.** `stored-schema.md` says the id format "belongs to M1". The M1 leaf says to mint ids "to the format M0b fixes". Neither owns it. +- **Newer formats.** The leaf's first gate refuses a newer *major*. The M0b review moved the format to `0.X.Y`, where a higher minor X must also be refused (`is_readable` in `crates/rdm-schema/src/lib.rs`). +- **Comments.** `_comments/` exists in the stored schema and in the read model ("a comment never changes a `rev`"). The M1 leaf names neither its layout nor its write path. +- **Testing lessons.** M0 learned to put a schema-validation test on every output. M0b learned to brief verifiers to challenge any relaxed rule. Neither lesson appears in the leaf's gates. +- **CI.** `.github/workflows/rust.yml` runs on `ubuntu-latest` only, with no MSRV job, while the leaf gates on three operating systems. It runs only on pull requests and pushes to `main`. +- **Lock files.** `.gitignore` has no `.rdm/` entry, but the lock and journal will live there. +- **Byte-for-byte round trip.** It holds only for canonical input. `serde_json` rewrites `1e5` and `\u` escapes, so a hand-edited file cannot round-trip byte for byte. The gate as written cannot be met for every input. +- **`op_id` replay.** `op_id` appears on stored records, but no leaf owns the rule for replaying an operation that was retried. +- Observed but outside A2: the meta README shows M0 and M0b `done`, while their leaves' criteria are still unticked. To be reconciled at M1 close-out, not here. + +## Root Cause + +The M1 leaf was written as a store-and-lock milestone over schemas that M0b would hand over finished. M0b did hand over the types. But the design questions that sit between the types and the files fell back to M1 without the leaf being rewritten. Those questions are: what a file holds, how a file is named, how versions evolve, and what is linked to what. The session that planned M1 then took design rulings that change the layout itself. + +## Rulings (Eliott, 2026-11-25) + +1. **Flat, id-addressed layout.** Each node is one file, `nodes/.json`, holding its `name`, its `parent_id` and a sibling order key. The filesystem no longer mirrors the tree. Depth stays the ordering rule (I1), computed from the `parent_id` chain. A rename or a move writes one file and no directory is renamed. This overrules the earlier "names are paths" layout of R01: "The value of what you are suggesting over the value of keeping the depth in the file system is higher." +2. **Concurrency is a layout problem.** Readers need no coordination. The write path uses named, established algorithms, and their trade-off is argued. +3. **The Rust types and the data layout are the contract.** JSON and JSON Schema are derived from them. "Schema" means the data structures broadly: stored nodes, the campaign model and operation signatures, not only JSON Schema files. +4. **Schema evolution uses a chain of responsibility.** + - Each format version is a layer that overrides only what changed. + - Behaviour a version lacks defaults to "not in this version". + - A field removed later is overridden back to that default. + - Older files fall through the chain to the layer that reads them. +5. **A file newer than the binary is refused.** + - The binary refuses a file whose format it does not support. No layer exists that could interpret what changed, and old code must never misread a field whose meaning changed. + - Making this transparent is M7's concern, not M1's (see M7's open question below). + - Eliott at first proposed that a higher X need not be refused. He agreed to the refusal after the case above was raised. +6. **Links are declared, never left to prose.** Every key-value link between records is declared in the contract, so an update or a delete reaches every reference automatically. A value that can be derived from an id is never stored. +7. **The tracked campaign data stays text.** + - Per-node merging is why the layout exists, and binary files neither merge nor show in a PR diff. + - Derived artefacts may come from CI: JSON Schemas, and docs rendered from the types. Campaign data is merged by git before CI runs, so CI cannot produce it. + - A binary form of the campaign, if one is ever built, is an untracked cache in `.rdm/`. +8. **A hot in-memory campaign in the long-lived server process.** + - It is a cache, revalidated against the files on every read. + - Writes go straight through to the files. + - It is never the source of truth, because other processes (another worktree, the CLI, an editor, git) change the files under it. +9. **Scope.** + - M1 freezes: the stored types, the campaign-level model, the status move table as data, and the store-level operation requests, results and errors. + - Tool input and output stay with M4. + - M2 consumes this layer, adding the operations' semantics, the FSM and impact analysis. + - Contract design leaves M4. + - Budget for the M1 campaign: USD 60, with a checkpoint at USD 48. + +## Impact Assessment + +- **Scope:** no new node in the meta-roadmap. Prose edits: + - **M1:** goal, gates, Step 1. + - **M2:** inputs. + - **M4:** tool inputs wrap M1's operation types. + - **M7:** the newer-format question. + - **Meta README:** the Gotchas ownership line. + - R01 is synced inside the M1 campaign (leaf `r01_sync`), in the same merge as the code. +- **Dependencies:** M2 now starts from M1's operation signatures and move table instead of designing them, and M4 from M1's operation types. M7 inherits a refusal that it may make transparent. +- **Risk if not addressed:** + - M1 builds a nested store whose renames touch whole subtrees. + - The id format stays ownerless. + - Old binaries misread newer files. + - Every consumer re-implements links by hand, which is the class of bug Eliott has seen in agent-written CRUD. + +## Answers recorded for later milestones + +- **M7, the newer-format hand-off.** + - It is not a hot auto-update. A running server never swaps itself mid-session: it refuses the affected campaign with `NewerFormat{found, supported}` and keeps serving the others. + - The realistic transparent path, for M7 to decide: at launch, look for a binary that supports `found` and is already on the machine. The plugin cache keeps versioned directories, and the newer file usually came from a newer plugin version that is installed. If one is found, start it. + - Downloading one is an install and needs the user's consent. + - Otherwise the user sees the message naming the version needed. +- **M4.** Tool inputs wrap the operation request types of `rdm-schema`, and tool errors map from M1's error type. + +## Proposed Solution + +| Change | Detail | +|:--|:--| +| M1 leaf | **Goal:** contracts, the version chain, the flat store with ordered writes, and the hot cache.
**Gates:** the rescoped gates of the M1 campaign, as below.
**Step 1 Implementation Logic:** points to this report and to the campaign. | +| M2 leaf | **Pre-condition and planning list:** takes M1's operation signatures, `MOVES` and declared links as given; decides semantics, not shapes. | +| M4 leaf | **Planning list:** input schemas wrap M1's operation request types; the error mapping starts from M1's error type. | +| M7 leaf | **Planning list:** gains the newer-format hand-off (look up an installed binary that supports the file's format, never download without consent). | +| Meta README | **Gotchas ownership line:** M1 owns the contracts beyond the stored types (campaign model, move table as data, operation types, declared links), the id format and minting, the error type and the version chain.
**Amendment Log:** A2 row. | + +The rescoped M1 gates: + +- `__design__/rdm/store.md` and `__design__/rdm/contracts.md` are reviewed by Eliott, and R01 matches them in the same merge. +- `rdm-engine` holds no stored or contract type of its own; it depends on `rdm-schema`. +- `MOVES` matches the move table of `statuses.md`, and the declared links cover every id field. +- Every older format version reads through the version chain. A newer one is refused with `NewerFormat` before anything else is parsed. +- Canonical files round-trip byte for byte. Valid non-canonical input reads and re-encodes canonically. Unknown keys survive (I12). +- Every write prefix of every store operation loads and recovers to the state before or after it. A multi-process kill test on macOS, Linux and Windows loses no acknowledged write (I3). +- A stale replace changes nothing (I4). A move writes one file and changes no id (I7). The reverse link index always equals a full scan. +- A cached read equals a cold read for every kind of external change (I10, reworded). + +## Recommendations + +1. Land A2 on the meta-roadmap with this report as its source, then plan `__roadmap__/m1-core-foundation/`. +2. Write the Amendment Log row of A2 by hand, as A1's was, and check it with `dirtree-rdm validate`. The legacy tool still has no amendment writer. +3. The reminder `skills-rdm-M1` was estimated (150+150 minutes) before this rescoping. Propose a re-estimate to Eliott; apply it only on his yes, through the scheduling-work writer. +4. `op_id` replay: M1's `contracts_design` leaf decides whether the store or M2 owns it, and records the decision. diff --git a/__reports__/m1-core-foundation/01-cache_probe_v0.md b/__reports__/m1-core-foundation/01-cache_probe_v0.md new file mode 100644 index 0000000..ff8466f --- /dev/null +++ b/__reports__/m1-core-foundation/01-cache_probe_v0.md @@ -0,0 +1,50 @@ +# Cache probe: cold open against warm revalidated read, and the binary cache (v0) + +Date: 2026-11-25 + +This report answers the `hot_cache` leaf's step 2 and the decision `store.md` §Cache (Persisted form) leaves to it: whether to build a binary cache in `.rdm/cache/`. The answer is no, for M1. + +## Problem Statement + +A long-lived process now serves reads from decoded entries it revalidates on every read (`CachedCampaign::read`). A binary form of the campaign (rkyv, in the untracked `.rdm/cache/`) would only be worth building if the cold path were slow enough to hurt, or if it shortened the warm one. The probe measures both at the size the design expects, 160 nodes, and at ten times that. + +## Method + +- **Campaign.** Built through the store's own create API (`CachedCampaign::create`, default `Fsync` tier): one root, 7 directories, the rest leaves of about 1 KB each (160 nodes, 163 KB; 1 600 nodes, 1.68 MB). Every create also writes an amendment, so the campaign directory holds as many amendment files as nodes, and a revalidation stats both directories: 320 and 3 200 files. +- **Cold open.** `Store::open` on the directory, median of 15, in-process, after the files were in the page cache. It reads, decodes and hashes every file and builds the campaign, reverse index and op index. +- **Warm read, aged.** `CachedCampaign::read`, median of 200, taken 3 s after the last write and after one read that cleared the racy flags: one `readdir` and one `metadata` per file (it follows symlinks), nothing decoded. +- **Warm read, all racy.** A fresh copy of the campaign (every file written within the last instant), opened and read 9 times within the 2 s window: every entry is read and hashed again each time, none is decoded because the bytes are unchanged. +- **Single-node read.** `read()` followed by `campaign().get(id)`. +- **Raw floor.** `readdir` plus `fs::metadata` of every file of `nodes/`, `_amendments/` and `_comments/`, no cache, median of 200. +- **Build.** `cargo test --release`, a throw-away test file in the crate, deleted afterwards. Four runs, minimum and median of each series. +- **Machine.** Apple M3 Pro, 12 cores, macOS 26.6.2 (25G83), APFS. The machine was shared with other agents during every run (load average 20 to 108 on 12 cores). Minimums are the figures to read; medians carry the scheduling noise, and some runs are inverted by it (see the findings). + +## Findings + +Minimum of the series over four runs (median range in brackets): + +| Measure | 160 nodes (320 files) | 1 600 nodes (3 200 files) | +|:--|--:|--:| +| Cold open | 12.6 to 17.8 ms (14 to 55 ms) | 135 to 144 ms (140 to 148 ms) | +| Warm read, aged | 1.34 to 1.41 ms (1.4 to 1.7 ms) | 15.1 to 15.6 ms (17 to 18 ms) | +| Warm read, all racy | 2.7 to 6.1 ms (3.2 to 6.2 ms) | 10.8 to 12.7 ms (11 to 17 ms) | +| `read()` plus `get` of one node | 1.31 to 1.49 ms | 15.1 to 17.2 ms | +| `get` of one node, no revalidation | 20 to 30 ns | 22 ns | +| Raw `readdir` plus `metadata` of every file | 1.18 to 1.22 ms | 13.1 to 13.7 ms | + +- **A warm read costs about a tenth of a cold open** at both sizes, and it is within 10 to 15 % of the raw `readdir` plus `metadata` floor. The cache adds almost nothing to the syscalls it cannot avoid without trusting the directory (`store.md`: an in-place write does not change the directory mtime). +- **The overhead the first version of this probe could not explain was the amendment directory.** The first floor counted `nodes/` only, and every revalidation also lists and stats `_amendments/` (one file per create). With the floor over the three directories the gap closes. The walk of the second version (one ordered merge of the sorted listing and the sorted entries, ids validated without allocating, one clock read per pass) did not change the warm read measurably: it was syscall-bound already. +- **The racy re-read is visible at 160 nodes and not resolvable at 1 600.** Right after writes, a read re-reads and re-hashes every entry the writes touched: 2 to 5 times an aged read at 160 nodes (2.7 to 6.1 ms against 1.3 to 1.4 ms). At 1 600 nodes the all-racy minimum (10.8 to 12.7 ms) is below the aged one (15.1 to 15.6 ms), which no code path explains, so the difference between the two lies inside the noise of a shared machine. The earlier figure in `store.md` (36 ms all racy against 12 ms aged at 1 600) came from the first version of this probe, which ran under a load average of 36 to 51; it is not reproduced. The cost lasts `RACY_WINDOW` after the last change of each file and is paid by the few files a tool call wrote, not by the campaign. +- **A single node costs the same as the whole revalidation**: the lookup is nanoseconds, the revalidation is the price of any read. +- **The design's earlier figure** (0.25 ms for 160 files from Python) was not reproduced from Rust: the raw floor is 0.6 ms for the 160 node files and 1.2 ms with the amendments. It is still small next to a tool call. +- **A write reads the nodes it touches from the disk**, not from the cache: a few files per request, plus the siblings a rebalance renumbers, found when the plan names them. This costs one stat, read and decode per touched file and is not in the figures above. + +## Decision + +**No binary cache in M1.** + +- A binary cache only shortens the cold open (decode and hash), which a server pays once at start. 13 to 18 ms at 160 nodes is not a cost anyone will see; even 1 600 nodes start in about 150 ms. +- It does nothing for the warm read, which is the path every tool call takes and which is bound by one `metadata` call per file, because a persisted cache must be validated by the same signatures. +- It would add a second state to keep equal to the files, with its own header, format version and discard rules, for a gain below what the probe can resolve. + +Revisit it if a campaign of several thousand nodes has to start inside a request. The first move is then to measure again on an idle machine, then to fix the warm path (the per-file work), not to persist the cold one. diff --git a/__reports__/m1-core-foundation/02-adversarial_review_v0.md b/__reports__/m1-core-foundation/02-adversarial_review_v0.md new file mode 100644 index 0000000..4cd5ece --- /dev/null +++ b/__reports__/m1-core-foundation/02-adversarial_review_v0.md @@ -0,0 +1,75 @@ +# M1 adversarial review (d6), v0 + +Verdict: the cornerstone guards catch the bugs they name, wherever a mutation was run, and the before-main findings of +every review are fixed on `feat/m1-core-foundation`. Two cornerstone guards (I7, I12) have no recorded mutation: +Eliott ruled on 2026-11-25 that the mutation checks run so far are enough and asked for an open review instead. + +## How the review was run + +The leaf planned one fresh verifier injecting each guard's named mutation. It ran as a sequence instead, each step by +fresh Sonnet agents briefed to assume something was wrong: + +| Round | Agents | Report | Outcome | +|:--|:--|:--|:--| +| Per-leaf verifiers | one per risky leaf | the leaf files' "verifier's fix round" gates | fixes landed per leaf | +| Sustainability review | 2 reviewers (src, tests) | `02-sustainability_review_{src,tests}_v0.md` | S3, S4, S5, S7, S8, S11, T1-T5, T7, T10 fixed (merges 162de9b, a0ae710) | +| Full review | 2 reviewers (harmony, safety) | `03-full_review_{harmony,safety}_v0.md` | before-main items fixed (merge 813e42f), verified by a fresh agent | + +Eliott (2026-11-25): "I think you have already run the mutation checks enough. I am more interested in the open hunt +for full safety", which replaced a second mutation pass with the full review's two lenses. + +## Cornerstone guards: mutation and result + +| Invariant | Guard | Mutation | Red? | Where recorded | +|:--|:--|:--|:--|:--| +| I3 | `every_write_prefix_loads_and_recovers_to_pre_or_post` | node files removed before the amendment is written | yes | `crash_test.md` gate | +| I3 | `killed_workers_lose_no_acknowledged_write` | lock released between the revision check and the write | yes | `crash_test.md` gate | +| I4 | `stale_replace_changes_nothing` (two-row table) | a write judges the touched files against the cache, not the disk | yes | `02-sustainability_review_tests_v0.md`, seen-red script | +| I7 | `move_writes_one_file_and_keeps_ids` | none recorded | not shown | gap, covered by Eliott's ruling | +| I10 | `cached_read_equals_cold_read` | revalidation by directory mtime alone; signature ignoring identity, size or mtime | yes | `hot_cache.md` gate; seen-red script | +| I10 | `write_through_visible_to_cold_reader_on_return` | buffered write | yes | `hot_cache.md` gate | +| I12 | `unknown_keys_survive_in_place_at_every_level` | none recorded | not shown | gap; the safety review read it as sound, and found a separate I12 breach (sS6, integers beyond 64 bits), deferred to M2 | +| Links | `reverse_index_equals_brute_force_scan` | reverse-index update on delete removed | 3 of 3 | `03-full_review_safety_v0.md` | +| Version | `newer_file_refused_before_parsing` | decoder parsing the whole struct first | yes, per the leaf's step | `codec_and_versions.md` step 1, in the implementer's hand-back only | +| C28 | `requests_breaking_a_rule_are_refused`, step and directory rows | step-reference check commented out; directory check skipped | yes | fix round 66372fc | +| S2 (store.md) | `create_on_a_volume_without_hard_links_publishes_and_still_refuses_a_taken_name` | fallback removed; fallback without the absent check | yes (re-run by the verifier) | fix round 80380bc | + +## Leaf gates against what was built; relaxed rules + +The per-leaf verifiers and the two full-review lenses checked each leaf's gates as written. Rules found relaxed and +fixed: step references unchecked (sS1); the hard-link fallback promised by `store.md` but missing (sS2); four silent +serialisation fallbacks (H2); opening a missing root creating a directory tree. None remain open before main. + +## Fixtures and seams + +- Fixtures come from real producers: hand-written canonical files, the store's own writes and their prefixes, and + real-actor transformations (CRLF checkout, `git merge-file`, `jq -S`, `touch -r`, rename-over, `git checkout`). The + test sustainability round culled the cache rows shaped by mutants rather than by actors. +- Seams: `rev` is computed once (codec helpers) and compared by store and cache; `RecordingFs` and `RealFs` share one + `Fs` trait and one effect-apply routine; `StoreError` and its constructors live in rdm-schema and both crates use + them. + +## Deferred, with milestone + +Carried in `04-knowledge_transfer_v0.md`: H6, H11-H14; sS3-sS9 except the items fixed; S1, S2, S6, S9, S10, S12, S13; +T8, T9; the four nits of the fix-round verifier. + +## CI evidence + +- Push run at 813e42f, every job green (ubuntu, macOS, Windows, MSRV 1.88, lint): + https://github.com/CrackingShells/cracking-shells-playbook/actions/runs/45618278562 +- Soak run at 813e42f (`RDM_SOAK_ITERS=1000`, `PROPTEST_CASES=10000`): ubuntu, macOS, MSRV 1.88 and lint green; + Windows cancelled at the job's 45-minute cap with `reverse_index_equals_brute_force_scan` still running. The + kill harness passed on Windows at full count (100 s). + https://github.com/CrackingShells/cracking-shells-playbook/actions/runs/45621003595 +- Cause of the Windows cancel: a test helper read the store once per candidate node (fixed in a73b07b, 37 % + faster), on a store that stats every file of the campaign, history included, on every read. +- Soak run at 825ea5d, after the helper fix, every job green. Job durations, build included: ubuntu 18 min 37 s, + macOS 17 min 56 s, Windows 33 min 6 s, MSRV 1.88 10 min 27 s. + https://github.com/CrackingShells/cracking-shells-playbook/actions/runs/45648611166 +- **Thin margin:** Windows finishes 12 minutes under its cap, and the cost behind it is the store's read path, not + the test. Eliott ruled on 2026-11-26 that the read path is redesigned in its own PR, measured first: + `__reports__/rdm_read_path_efficiency/`. +- CRLF probe: a Windows checkout with `core.autocrlf=true` did rewrite committed JSON (the schema drift guard went red + on Windows at d9331cd). `.gitattributes` now pins `eol=lf` on the test fixtures and the committed schemas, and the + CI step `git ls-files --eol` prints the fixtures' line ends on every run. diff --git a/__reports__/m1-core-foundation/02-sustainability_review_src_v0.md b/__reports__/m1-core-foundation/02-sustainability_review_src_v0.md new file mode 100644 index 0000000..2694ac7 --- /dev/null +++ b/__reports__/m1-core-foundation/02-sustainability_review_src_v0.md @@ -0,0 +1,47 @@ +# M1 core foundation: sustainability review of product code (src), v0 + +Scope: `crates/rdm-schema/src`, `crates/rdm-engine/src`, `crates/rdm-mcp/src` on `feat/m1-core-foundation`. Not correctness; not tests. + +**Verdict: sound seams and mostly consistent conventions; the debris is small (one dead stub, duplicated temp-file and effect-replay code, stale crate docs), but the write and read paths are O(N) per request with whole-campaign clones, and there are two public front doors (`Store`, `CachedCampaign`) that M4 should not inherit. Fix S3, S4, S5, S7 (layout constants) before merge; the scaling items can wait for M2/M4 but must be recorded.** + +Evidence base: one clippy pedantic+nursery run (classes only), `cargo tree -d` (no product-relevant duplicate), line-range reads, colgrep hits. Costs below are scaling arguments from the code, not measurements. + +## Findings (ranked) + +| id | category | sites | consequence | smallest fix | effort | when | +|---|---|---|---|---|---|---| +| S1 | scalability (write path) | `write.rs:319-320` `Working` clones the whole `Campaign` and `revs` per request; `write.rs:768-773` `plan` compares all N nodes; `campaign.rs:437-451` `insert`/`remove_subtree` call `derive()` over all N on every call; `rev.rs:19-27` + `store.rs:301` `tree_rev` re-hashes N lines (a `format!` per node) on every receipt, dry runs included | A single-node write costs O(N) clones (each node carries a JSON payload) plus O(N) compare plus O(N) hash, while holding the writer lock. A batch of k creates/deletes costs O(k x N log N) in `derive`. At 10k nodes a 50-op batch is 50 full re-derivations (500k node visits) before any I/O. | (a) keep `tree_rev` cached in `State` and update it in `write_through`, which already updates `revs`; (b) make `plan` iterate `w.created` plus the ids in `w.changes` instead of every node; (c) defer `derive()` to once per batch (`insert_many`, or a dirty flag); (d) later, a copy-on-write overlay instead of the clone. | (a)(b) S, (c) M, (d) L | (a)(b) can ride with S11; (c)(d) wait for M2 (graph engine reuses `Campaign`) | +| S2 | scalability (read path) | `cache.rs:330-345` `revalidate` stats every file of three directories on every `read`; `cache.rs:421-466` `build` clones every record, every comment and amendment (twice for the reverse index) and rebuilds `OpIndex` from zero; `cache.rs:621` `read(&mut self)` | Every tool call costs N `stat` plus 3 `list_dir`; any single external file change costs a full O(N) rebuild with N clones. `&mut self` forces one mutex, so 100 concurrent reads run serially: 100 x N stats (1M syscalls at N=10k). The doc comment budgets "milliseconds"; that holds at hundreds of nodes, not 10k. `write_through` already shows the incremental update, so the rebuild path is the only full-copy path left. | Coalesce: skip revalidation when the previous pass is younger than a configurable interval (reads inside the racy window already re-read); make `build` reuse `write_through`'s per-record update for the changed names (`sync_kind` already knows them); split `revalidate` (`&mut`) from the read accessor so readers can share an `RwLock`. | M | wait: before M4 serves 10k nodes; record it in the M4 brief | +| S3 | sustainability (API surface) | `write.rs:998-1074` `Store::{replace,create,move_node,delete_subtree,comment,batch,recover}` are `pub`; `cache.rs:644-690` `CachedCampaign` re-exposes the same seven with pure delegation; `cache.rs:604` and `store.rs:165` both `open` | Two public entry points with identical writes and different read contracts (`Store::campaign()` reads without revalidating; `CachedCampaign::read()` revalidates). M4 will pick one by accident, and every new op needs two edits. | Make the `Store` mutators `pub(crate)` and `CachedCampaign` the one handle (or fold `read()` into `Store` and delete the wrapper). Decide once. | S | before merge (public shape) | +| S4 | duplicates | temp names: `fs.rs:434-440` and `publish.rs:13-19` (two counters; `"{pid}-{n}.tmp"` vs `"c{pid}-{n}.tmp"`); stage-a-temp-file loop: `fs.rs:457-467` and `publish.rs:50-60` (one `continue`s on `AlreadyExists`, the other falls through the `{}` arm); effect replay: `write.rs:233-265` `redo` and `write.rs:881-907` `redo_fresh` (same Put/Create/Del dispatch, differing only in what an existing Create target means); effect path extraction: the `Put|Create|Del { path }` or-pattern at `write.rs:384-388` and `write.rs:1570-1573` | The crash-safety path exists twice, so a fix to one (for example the temp-name collision policy) misses the other. The two name shapes mean the stray-file sweep (`recover_locked`, `write.rs:175-187`) has to know both. | One `temp_name` in `fs.rs`; `fs::stage(fs, tmp_dir, bytes) -> io::Result` used by `atomic_replace` and `publish::create`; `fn apply_effect(&self, e, on_existing: ExistingCreate)` shared by `redo`/`redo_fresh`; `IntentEffect::path()`. | S | before merge (crash-safety code) | +| S5 | dead or interim code, stale docs | `write.rs:1688-1690` `_actor` with `#[allow(dead_code)]`, which exists only to keep two imports used; `write.rs:1411-1413` + `write.rs:1625-1627` `placeholder_comment_id`/`minted_ulid_invalid` and the patch-up loop `write.rs:370-378` (ids minted after the results are built); `rdm-engine/src/lib.rs:1-4` and `rdm-engine/Cargo.toml` `description` still say "filesystem primitives ... defines no contract type", but the crate now holds store, cache, codec, write, links, rev; `rdm-mcp/Cargo.toml` "Throwaway MCP Apps feasibility stub", `main.rs:343-345` `RdmSpike`, with no dependency on `rdm-engine` | The next agent reads the crate doc and builds a wrong model; the placeholder-then-patch id flow is the sort of thing that gets copied. | Delete `_actor` and its imports; mint comment ids before building results (move the `minted` loop into `op_comment`'s caller) and drop the placeholder; rewrite the two docs and the Cargo description. | S | before merge | +| S6 | non-harmonized (errors) | `StoreError::Invalid` built by `store.rs:149` `invalid(file, rule, String)`, `write.rs:42,50` `request_fault`/`node_fault` (`impl Into`), and raw literals (`write.rs` 5, `codec.rs` 1, `version.rs` 2, `store.rs` 1); `store.rs:142-147` `io_error` keeps only `e.to_string()` | Three constructors with two detail types. `Io { message }` drops the `ErrorKind`, so M4 cannot map NotFound vs PermissionDenied to different tool errors without parsing text. | One `fault` helper set in `store.rs` taking `impl Into`; add `kind: io::ErrorKind` (or a `retryable` bool) to `Io`. | S | helper unification can wait (M2); the `Io` shape is cheaper to change before M4 consumes it | +| S7 | non-harmonized (paths, layout) | `.rdm` layout is spelled in `write.rs:118,148,154,164,165,182,187,189`, `intent.rs:70,105`, `lock.rs:63-67`; record paths are `/`-joined `String`s from `campaign.rs:37` `node_file`, `cache.rs:209,223` `format!("{dir}/{name}")`, and `write.rs` effect strings, joined to `Path` at `write.rs:239,251,885,889,904` and decoded back at `fs.rs:318-331` `rel` | This is the class that just produced the Windows backslash bug: a logical name and a filesystem path are the same type (`String`/`Path`) and each module converts at its own boundary. Changing the layout (for example the `.rdm/tmp` location) means editing five files. | Phase 1: a `layout` module (`rdm_dir`, `tmp_dir`, `lock_path`, `intent_dir`, `gitignore_path`, plus the logical names `.rdm/lock` etc.). Phase 2: a `RecordPath { kind, name }` newtype with `logical()` and `under(root)`. | phase 1 S, phase 2 M | phase 1 before merge; phase 2 wait (M2) | +| S8 | efficiency (algorithm) | `write.rs:1586-1596` `chain_depth` (one `BTreeSet` per call) used as the key of `deletes.sort_by_key` at `write.rs:784`; `campaign.rs:400` already has `Campaign::depth` | `sort_by_key` evaluates the key O(r log r) times for r removed nodes, each O(depth) with a set allocation: r x log r x depth. Deleting a chain-shaped subtree of 10k nodes is on the order of 10^9 steps. Balanced trees are cheap, so tests will not show it. It is also a second depth routine beside `Campaign::depth`. | `sort_by_cached_key`, then a memoised walk (depth of parent + 1) so the whole sort is O(r); keep the cycle guard. | S | can wait (S1 batch); trivial, so ride with it | +| S9 | non-aligned types | `write.rs:125` `Store::ulid() -> String`, `ids.rs:111` `UlidMint::mint -> String`, `intent.rs:66` `is_ulid` validates through `AmendmentId::parse`, and `write.rs:783,1412` parse a fresh `String` back into `CommentId` with an `unreachable!` fallback; `ids.rs:79` `mint_id` is a typed minter that `write.rs`/`store.rs` do not call | Ids are validated newtypes everywhere else in the schema ("a consumer never re-checks it"), but the minting path round-trips through `String` and borrows another id type as a ULID check. | `Store::mint()` using `mint_id`; a `Ulid` parse in `rdm-schema::ids` for intent file names. | S | wait (M2) | +| S10 | sustainability (module size) | `write.rs` 1690 lines: recovery 169-265, pipeline `run` 269-395 (clippy: 198 lines), per-op 603-705 and 1083-1410 (`op_relocate` 144 lines), plan/apply/write-through 757-972, free helpers 1411-1690 | Too large for one head, and every M2/M4 op lands here. Three `impl Store` blocks plus ~15 free functions share no visible boundary. | Mechanical split under `write/`: `recover.rs`, `run.rs`, `ops.rs` (one file per op), `plan.rs`, `through.rs`. No logic change. | M | do before merge if no branch is open against it, since a pure move is cheapest now; otherwise first task of M2 | +| S11 | pub surface wider than its consumers | `fs.rs:67-125` `Effect`, `Effect::apply`, `replay_prefix`, and `fs.rs:289-340` `RecordingFs` are `pub` in the product lib and exist for the crash tests (colgrep shows no src caller outside `fs.rs`); `rdm-engine/src/lib.rs` makes `cache, codec, fs, ids, intent, links, lock, order, rev, store, version, write` all `pub mod` | The crate's public contract is its whole internals, so each later refactor is a breaking change, and a test fixture reads as product API. | Gate the recording fs behind `#[cfg(any(test, feature = "test-support"))]`; narrow `pub mod` to what M4 needs (`store`, `cache`, `write` types, `fs::Fs`/`RealFs`/`Durability`). | S | before merge for the gating; the module narrowing can wait for M4 | +| S12 | non-aligned vocabulary | `moves.rs:49` `Move` (a status transition), `write.rs:1030` `move_node`, `write.rs:1083` `op_relocate`/`RelocateOp` (a tree reparent); same module names in two crates with different jobs: `rdm-schema::ids` vs `rdm-engine::ids` (minting), `rdm-schema::links` vs `rdm-engine::links` | "move" means two things and the public method does not match its op type (`move_node` takes `RelocateOp`). Not checked against `contracts.md` wording beyond this collision. | Rename the public method `relocate` (or the op `MoveNodeOp`), and name engine modules `mint` and `reverse` so grep and imports are unambiguous. | S | wait (M2), but cheaper before M4 pins the tool names | +| S13 | M4 coupling | `lock.rs:15-16` sleep-poll backoff (5-50 ms) and the synchronous `Store` API with blocking `std::fs`; `write.rs:131-133` host read from the environment | In an async server each write call parks a thread while it waits for the file lock; 100 concurrent write calls need 100 blocking threads or a bounded pool, or the runtime starves. Not a defect in M1; it is the shape M4 must wrap. | State in the M4 brief: one `spawn_blocking` per call behind a per-campaign mutex, a bounded queue, and the lock timeout surfaced as `LOCKED`. | S (doc) | wait (M4) | + +Clippy classes worth one line each (not findings): 18 derive-`Eq` omissions, 21 missing `# Errors`, 5 `pub(crate)` inside a private module, 4 unused `async` (all in the spike), 3 functions over 100 lines (`run`, `op_relocate`, one more). + +## Deliberate, keep + +- `RealFs` and `RecordingFs` behind the one `Fs` trait: the recording fs is the crash-matrix oracle; keep it independent of `publish`/`write` (only gate it, S11). +- `order.rs` has its own base-62 digit table; the id alphabets in `rdm-schema/src/ids.rs:18,20` are 32-character by contract, so these are different alphabets, not a duplicate. +- `cache::digest` (std `DefaultHasher`, process-local change detection) beside `rev.rs` SHA-256 (a contract value): different jobs. Keep both, but the `digest` doc should say "not stable across Rust releases". +- Direct `SystemTime::now()` at `write.rs:290` and `cache.rs:332,356`: the racy window compares with file mtimes, which come from the real file system, so it must not use the injected `Options.clock`. Add a one-line comment saying so. +- Hand-written `Display`/`Error` impls (`StoreError`, `IdError`, `NameError`, `LockError`, `MintError`): consistent across crates and avoids a dependency; not an outlier. +- `clock.rs` hand-rolled RFC 3339 (no `chrono` dependency) and the `Unique` duplicate-key visitor in `codec.rs`: small, and the alternatives pull in dependencies. +- `version.rs` layered decode (`FormatLayer`, `Nothing`, `V0_1`): the intended version chain of responsibility. +- `redo` vs `redo_fresh` differ in meaning (recovery is idempotent, a fresh write is not): share the dispatch (S4) but keep both policies. +- The `rdm-mcp` spike is self-contained by design; do not wire M1 into it, replace it in M4. + +## Not checked + +- Test files (sibling review), `read.rs`, `stored.rs`, `diff.rs`, `moves.rs` and `order.rs` internals, `links.rs` algorithms. +- `contracts.md`/`store.md` vocabulary beyond the move/relocate collision; doc-comment style beyond the stale crate docs. +- No timing was measured: S1, S2, S8 are scaling arguments from the code. A 10k-node probe (open, one read, one 50-op batch) would turn them into numbers. +- Whether every `pub` item has an in-repo consumer: colgrep was run on a subset (`fs.rs` recording items, minting, `subtree_rev`); the rest is unverified. The `lock.rs` sleep mechanism was inferred from its constants. +- Only the one allowed clippy run; no `cargo udeps` or `cargo machete` run. diff --git a/__reports__/m1-core-foundation/02-sustainability_review_tests_v0.md b/__reports__/m1-core-foundation/02-sustainability_review_tests_v0.md new file mode 100644 index 0000000..6fdf3d2 --- /dev/null +++ b/__reports__/m1-core-foundation/02-sustainability_review_tests_v0.md @@ -0,0 +1,87 @@ +# M1 test suite: sustainability review, v0 + +Verdict: the suite is fast (about 11.5 s of test time) and its guards are well named and well explained, but the two largest files (store.rs, cache.rs) forked the campaign-builder, snapshot and copy helpers instead of using tests/common, so every cross-cutting fix (the Windows path key was one) has to be made in 3 to 4 places and was already missed in 2; fix that before M1 merges, and cull about five cache rows that were shaped by mutants rather than by actors. + +## Measured suite times + +One run: `cargo test --workspace --locked` with a warm shared target dir (`real` 19.8 s wall, including cargo's no-op build check). Load average at start 5.48 (1 min), 18.75 (5 min), 32.5 (15 min); at the end 4.86. The machine was coming down from a heavy load, so these are upper bounds. + +| binary | tests | finished in | +|---|---|---| +| crash_prefix | 1 | 4.15 s | +| crash_kill | 1 | 2.62 s (25 rounds of 30..150 ms sleeps, wall clock by design) | +| store | 27 | 1.96 s | +| lock | 5 | 1.05 s | +| rdm-mcp stdio | 14 | 0.71 s | +| codec | 6 | 0.46 s | +| cache | 8 | 0.40 s | +| fs | 3 | 0.17 s | +| everything else (schema, intent, unit) | 36 | under 0.02 s each | +| sum | | about 11.5 s | + +The must-run set is at 40 percent of the 30 s budget. Headroom is fine today; the growth shape is the concern (T9). + +## Ranked findings + +| id | category | sites | consequence | smallest fix | effort | when | +|---|---|---|---|---|---|---| +| T1 | 1 duplicated helpers | `body nid cid sid name criterion dir_node leaf_node` defined in store.rs:27-100, cache.rs:35-110 and common/campaign.rs:20-120 (the last takes `NodeId`, the first two take `u32`). `Disk` in store.rs:149, cache.rs:157, common/campaign.rs:146. `base()` in store.rs:190, cache.rs:194, crash_kill.rs:57, crash_prefix.rs:37. `git()` in store.rs:200, cache.rs:204. `copy_tree` in store.rs:2460, cache.rs:982, common/campaign.rs:215. `header actor req leaf_of rev_of delete_op` in store.rs and cache.rs (store.rs:1024 `req(note, op)` vs cache.rs:249 `req(note, op_id, op)`, same name, different signature). Neither store.rs nor cache.rs declares `mod common`. | Three copies of the node builder. A schema field added in M2 is edited three times, and `schema_version: "0.1.0"` is hard-coded in each (13 literals in tests). The next builder fix lands in one copy and the others silently diverge (T2 is that already). | Give common/campaign.rs the `u32` convenience builders (`nid(n)`, `dir_node(n, ..)`) as thin wrappers over its `NodeId` ones, add `Disk::new/write/write_all/path`, `git`, and a `req`/`header` pair, then `mod common;` in store.rs and cache.rs and delete the local copies. About 250 lines removed. | M | before M1 merges (it is the largest maintenance cost; M2 adds ops and every new test file would copy again) | +| T2 | 1 path-to-key | Directory snapshots keyed by a path string: common/campaign.rs:235 (fixed: `replace('\\', "/")`); store.rs:597 `snapshot` (`to_string_lossy().into_owned()`, no normalisation); store.rs:2473 `snapshot_dir` (same family); cache.rs:970 `names_under` (`display()`, backslashes on Windows, consistent with itself only). | The Windows bug is still present in 2 sites. They pass today only because both sides of each comparison go through the same function; any comparison with a forward-slash literal or with `files_of` output breaks on Windows. | Delete the store.rs and cache.rs walkers; use `files_of` (and a `names_under` built on it plus size and mtime where cache.rs needs them). One walker, one key rule. | S (after T1) | before M1 merges | +| T3 | 1 child-process spawning, 3 env knobs | Four mechanisms for "run this test again as a child": common `spawn_child` with `RDM_CHILD_ROLE/DIR` (crash_kill.rs:27, fs.rs:5, lock.rs:5); cache.rs:392 `run_child` with `RDM_CACHE_CHILD` and its own `child_role()` at cache.rs:406 (which shadows the common name); `RDM_HOLD_MS` read ad hoc at lock.rs:161 and fs.rs:113 (and lock.rs `timed_holder_child` vs fs.rs `holder_child` are two copies of one idea); stdio.rs:25,136 spawn the binary (a different thing, fine). `LIMIT = 60 s` is also defined in fs.rs:10 and lock.rs:10. | A fifth child test picks a fifth convention. `cache.rs` child cannot use `wait_line` or kill-on-drop, so a hang in it leaves an orphan test process. | Move cache.rs onto `spawn_child` (it needs only `run to completion`; add `ChildProc::wait_ok`). Move `LIMIT` and an `env_u64(key, default)` into common. Pass `RDM_HOLD_MS` through `spawn_child`'s `extra_env` and read it with the common helper. | S to M | before M1 merges for cache.rs; the rest at M2 | +| T4 | 3 RNG seeds and soak knobs, named inconsistently | crash_kill.rs:9 documents `RDM_CRASH_ITERS`, `RDM_CRASH_SEED`, `RDM_CRASH_WORKERS`; the same test passes the workers `RDM_KILL_SEED` (crash_kill.rs:375) and `RDM_KILL_ACKS` (:376), so one test has a `CRASH` and a `KILL` prefix for one seed lineage; crash_prefix.rs:23 has `const SEED: u64 = 0x5EED` with no env knob; the proptests hard-code `cases: 256` (codec.rs:851) and `cases: 24` (store.rs:1921), and an explicit `cases` in the config overrides the `PROPTEST_CASES` env var, so a CI soak cannot scale them. codec.rs:853 pins `failure_persistence` to `proptest-regressions/codec.txt` (relative path, no such directory is committed); the two store.rs proptests use the default. | The soak story exists for one test only and under mixed names. `PROPTEST_CASES=10000` in CI does nothing for the codec. | One prefix (`RDM_SOAK_*`, or keep `RDM_CRASH_*` and rename the worker seed `RDM_CRASH_STREAM`); drop the literal `cases:` and set the default via `ProptestConfig::with_cases` only when the env var is unset; one persistence setting for all three proptests. | S | before M1 merges (the CI soak is promised in the crash_kill.rs doc) | +| T5 | 2 leftover M0 probe code in the test suite | rdm-mcp/tests/stdio.rs:194 `probe_record_appends_one_line`, :188 `scratch_dir` (writes `probe-` dirs under `CARGO_TARGET_TMPDIR` and never removes them after the test), :415 `payload_sizes_by_scale` (prints `SIZES`, asserts three numbers grow), :322 `m0_feasibility_spike.md`, :428 `meta_mode_carries_nodes_in_result_meta`, :303 and :333 chunk and SSE streaming; module doc says "Contract test". | 14 tests, none of them in the project's guard vocabulary: names are not sentences, several are a probe or a benchmark of an M0 spike (payload sizing, "scale 11 refused in meta mode"). They will either be deleted at M2 or maintained as if they were contracts. | Decide per test with the coordinator: `payload_sizes_by_scale` and `probe_record_appends_one_line` are probes (delete once the M0 report cites the numbers); the protocol-version, ui-meta, schema-match and csp tests are real guards (rename as sentences). Remove `scratch_dir` leakage with a `tempfile` dir. | S | probes: before M1 merges; renames: M2 | +| T6 | 1 external-tool oracle | store.rs:620-640 `sha16_of_jq` shells out to `jq` and `shasum`. | Independent oracle, good, but it needs two binaries that are not on a stock Windows runner; the test either is skipped by CI config or fails there. Not checked which. | Keep the independence; replace with a hard-coded expected hash of the fixture bytes computed once by jq and recorded in a comment (the fixture is a fixed file), or use the `sha2` crate in dev-dependencies (not product code). | S | M2 | +| T7 | 2 and 4 stale shape | store.rs:1019-1022 and :148 are `use` lines and helper blocks in the middle of the file (a file that grew by appending); store.rs has two inline `mod`s (`order_keys` :940, `reverse` :1750) next to flat tests; cache.rs:1129 refers to "Step 3.2" (a roadmap step number that nobody can resolve in a year); cache.rs:1074 `Hooked` implements 10 of 10 `Fs` methods by forwarding to `RealFs` for 8 of them. `#![allow(dead_code)]` at the top of common/mod.rs:4 and rdm-schema/tests/common/mod.rs:1 (needed because each test binary compiles common separately, so this is correct, but it also hides truly dead helpers: `copy_tree`, `body` and `criterion` are not called from any crash test; they are only helpers of the pub builders). Also src/write.rs:1689 `#[allow(dead_code)] fn _actor` exists only to use two imports (product code, for the sibling reviewer). | Reading cost. store.rs at 3138 lines mixes eight topics. | Split store.rs by the topic headers it already has (open, write ops, order keys, recovery, reverse index) into `tests/store/{open,ops,recovery,index}.rs` after T1 so each part is about 500 lines. Replace "Step 3.2" with the store.md section name. Give `Hooked` a `Delegating` default (a `macro` or one `fn real()` accessor) so a new `Fs` method is not a 9th forwarder. | M | split at M2 start; the comment fix now | +| T8 | 4 naming and format conventions | Names that are not behaviour sentences: store.rs `the_table_of_the_document`, `marks_name_criteria`, `spread_is_ascending_and_short`, `keys_stay_short_under_repeated_inserts`; cache.rs `cached_read_equals_cold_read` is one test holding about 12 rows by comment (`// Bug caught:` blocks at cache.rs:405-680), and the same for `a_write_by_this_process_then_a_read_equals_a_cold_read` (:684-848, 12 rows). The project rule is one test per behaviour. rdm-mcp names are verbs without subjects (`lists_three_tools_with_ui_meta`). Failure message style: most use `"{row}: ..."` or `"{label}: ..."`; stdio.rs uses bare `.expect("close")`. | The first red in a 12-row test hides the other 11 and the test name does not say which class broke. | Turn the row blocks into a `rows!` table or a `for row in rows()` loop with the label in each message (crash_prefix.rs already does this and is the model). | M | M2 | +| T9 | 6 scaling | crash_prefix.rs:458-540: one `#[test]` loops `for row in rows()`; for each row: `oracle` (open, run, snapshot), `record`, then for every effect prefix `k` it does `at_prefix` (copy whole tree, apply k effects: O(k)), open, judge and recover; S18 then nests another loop of recovery cuts for each of 2 cut points. Cost per row is about (effects)^2 file ops plus (effects x campaign size) copies; with 18 nodes today and an average of ~30 effects it is 4.15 s for the 13 rows. | Linear in the number of rows (each new op adds one), super-linear in operation size: a batch row in M2 with 100 effects costs about 10 times a 30-effect row. A single `#[test]` also runs on one core and stops at the first failing row, so one red hides the rest. | Replay incrementally (apply effect k+1 on top of the state at k and snapshot into a scratch copy only for the judge), and make `rows()` produce one `#[test]` per row via a macro so cargo runs them in parallel; keep `RDM_PREFIX_ROWS` filter. Measure first: one row built and replayed under `time`. | M | M2 (when the first row with 100+ effects appears) | +| T10 | 5 redundancy | `facts()` at crash_prefix.rs:358-420 ends in `_ => {}`: a row renamed in `rows()` silently loses its facts check. The recovery-create guard store.rs:2594 duplicates the setup of crash_prefix (record, cut after the intent link, `at_prefix`), so it is a hand-built prefix row (see section below). | A renamed row passes with no oracle check. | Make the fall-through arm a `panic!("no facts for row {row}")`, or store the facts closure in `Row`. | S | before M1 merges | + +Categories checked and clean: +- Fixtures from real producers: node files are written by `encode` everywhere in engine tests (common/campaign.rs:150, store.rs:162, crash_prefix.rs). The only hand-written JSON is the deliberate codec oracle (codec.rs, documented) and the unknown-key edits in cache.rs, which model an editor. +- Mutant-injection: one test-side `Fs` (`Hooked`, cache.rs:1074); `RecordingFs` and `replay_prefix` are product code in src/fs.rs, used by 5 tests with one shared idiom. No second hook mechanism to harmonise. The frozen-stat closure is written out three times (cache.rs:1128, :1262 and the `first_seen` map) and should be one `frozen_stat()` constructor (part of the cull below). +- Serde and std behaviour tests: none found in the engine; rdm-schema/tests/stored.rs checks parse rules the crate defines, fine. +- Count targets: none. + +## Section: the hot-cache fix-round rows and the crash-test additions + +Method: for each row, who produces the input, and is the class already covered by an existing guard. The coordinator's note holds: these rows are shaped by which signature component the mutant dropped, not by an actor. The guard for the class is "a cached read equals a cold read for every way a file can change without the directory changing" and the cheapest honest expression of it is a small table of actors. + +| row | site | real actor? | class already covered? | verdict | +|---|---|---|---|---| +| aged same-size rename-over keeping mtime | cache.rs:627-650 | Yes: rsync with `--times`, `git checkout` with preserved time, a synchroniser. Identity (inode) is the only change. | Same class as "an aged file replaced by another version": the table below. | Keep as a row, folded. | +| aged size-only edit with mtime restored | cache.rs:652-664 | Weak. An editor that restores mtime after a grow (some IDE "preserve timestamps" saves, `touch -r` after append) exists; it is the same actor as the next row with a different size. | Covered by the touch-r row, which also restores the mtime. The two differ only in which signature component the mutant drops. | Fold into the touch -r row (one row with a size change). Delete the separate row. | +| `touch -r` after same-size in-place edit | cache.rs:665-681 | Yes: `touch -r`, `cp -p`, rsync `-t`, backup restore. Unix only; ctime is the only witness. | Not covered by anything else. | Keep (the real class "an actor restores the mtime"). | +| racy row on ctime-blanking `Hooked` Fs | cache.rs:446-474 in `cached_read_equals_cold_read` (third block) | Yes, and the Windows CI runner executes it for real: no ctime in the signature, in-place same-size edit within one tick. | The Unix-with-hook version simulates what Windows runs natively. On Windows it duplicates the previous racy row (the ctime hook is a no-op there). | Keep the hook row (it is the only way Unix CI exercises the Windows case); on Windows the first racy row is the real test and the hooked one is harmless. Document that in the row comment. Fold the two racy rows into one table row with `ctime: Option`. | +| `a_write_judges_the_files_it_touches_against_the_disk` (frozen-stat Fs) | cache.rs:1117-1170 | No actor produces a stat that always reports its first value; the nearest real input is a coarse-timestamp file system plus a same-size edit, already the racy row above. The point of the test is the write path (step "touched files are read from disk"), not the signature. | The class "a write must not trust the cache for the node it edits" is exactly `stale_replace_changes_nothing` (store.rs) run through a warm cache that holds an old entry. The frozen stat is just the cheapest way to make the entry stale. | Fold: run `stale_replace_changes_nothing` through `CachedCampaign` with the external edit made after the cache read; if a stale-hiding signature is needed to get the cache to keep the old entry, build it once (`frozen_stat()`) and share it with the rebalance row. Keep one test, not two. | +| `a_rebalance_rewrites_a_sibling_from_the_disk_not_the_cache` | cache.rs:1212-1303 | The input is real (a merge leaves two siblings with the same order key; an editor edits a sibling) but the conjunction (frozen stat, plus a rebalance that renumbers an unnamed sibling) is only reachable through the implementation. | Class "a write rewrites a file it did not name from the cached copy" is a separate class from "a write judges revisions against the cache": it is not covered by the replace guard, because the up-front read does not reach the sibling. | Keep as a real class, but as one parametrised row beside the previous one ("every file a write rewrites is read from disk"), sharing the `frozen_stat()` fixture and `age`. It must keep the real assertion that the external edit survives. | +| `a_file_that_vanishes_between_the_listing_and_its_stat_or_read...` | cache.rs:1173-1210 | Yes: `git checkout`, an editor's rename-save. | Not covered. | Keep. Its two copies of the armed-hook setup (cold and warm) should share one `vanish_at(at, path)` constructor. | +| crash_prefix `facts()` | crash_prefix.rs:358-420 | Not an actor; it is an oracle for the oracle. | The prefix guard compares every prefix to the state produced by running the operation, so if the operation silently did the wrong thing, pre/post would both be wrong and every prefix would still agree. `facts()` is what stops that. | Keep, but strengthen the fall-through arm (T10) and cut the per-row prose; it is the independence the guard needs. | +| create-over-foreign-bytes (store.rs:2594) | store.rs:2594-2630 | Yes: a merge or a checkout puts another writer's create of the same id on the destination after a kill. | Not covered by the prefix guard (that guard's states never contain bytes the operation did not write). | Keep as a real class. Move its setup onto the crash_prefix helpers (`record`, `at_prefix`) when T1 lands, and consider making it a `Row` flag `foreign_bytes_at_destination` so it rides the same prefix machinery. | + +Proposed cull, in effect: +- Delete: the "size-only edit with mtime restored" row (fold into the `touch -r` row as a size variant). +- Fold into one table-driven row: the two racy rows (native and ctime-blanking hook); the aged rename-over, `touch -r` and the folded size row become three entries of one "an aged file changes without the directory changing" table. Net: 5 blocks become 4 entries of one table with one `age()` and one `rewrite_in_place` helper. +- Fold: `a_write_judges_the_files_it_touches_against_the_disk` into the `stale_replace_changes_nothing` class run through a warm cache. +- Keep as real classes: `a_rebalance_rewrites_a_sibling...` (renamed as the sibling-write class), the vanish guard, the create-over-foreign-bytes guard, `facts()`. +- Not culled: the git-checkout, comment/amendment-directory and unknown-key rows in `cached_read_equals_cold_read`; each has a real actor. + +## Deliberate, keep + +- codec.rs fixtures hand-written from the contract documents ("Nothing here asks the encoder what canonical is"); do not generate them from `encode`. +- The `jq` plus `shasum` independent oracle (T6): keep its independence, change only how it is delivered. +- crash_prefix `oracle()`: pre and post states come from running the operation, never from replaying the log (crash_prefix.rs:~505 doc); keep it free of the replay code. +- `facts()` reading JSON plainly and walking `parent_id` instead of calling the store's tree code. +- `RecordingFs` and `replay_prefix` in src/fs.rs used by the tests: the Pillai method needs one recorder; there is no second mechanism. +- Child tests that re-execute the test binary (no helper binary to build or version) and kill with SIGKILL for real; the lock and atomic-replace tests with real processes and real `fs4` locks. +- crash_kill: wall-clock sleeps and unseeded interleavings, with the doc stating that no seed is tuned to a bug. +- `#![allow(dead_code)]` in tests/common modules (each test binary compiles its own copy). +- The codec's separate proptest persistence path if the team wants regressions committed; it only needs to be the same for all three proptests (T4). + +## Not checked + +- Whether `jq` and `shasum` are present on the Windows CI runner, and whether store.rs:1523 and crash_prefix.rs:304 (`Effect` paths turned into strings with `display()` and matched against `"nodes/"`) are separator-safe on Windows: needs a look at how `Effect` stores its paths in src/fs.rs. +- The exact number of rows in crash_prefix `rows()` (13 `row(` calls, 5 `Row {` literals), the effect count per row, and so the real cost split of the 4.15 s: not measured (the instruction allowed one timing run). +- Mutation strength of any cull above: the cull is argued from classes, not re-run against the mutants; each folded row should be re-run against the mutants that motivated it before merging. +- rdm-schema/tests (about 570 lines) read only by name; the intent tests (126 lines) read only by name. +- Product code duplication: the `#[cfg(test)]` modules in src/clock.rs and src/fs.rs were only skimmed; they test the retry schedule and `rfc3339` against constants, which looks independent. +- Cold-build time and the CI Windows/Linux run time. diff --git a/__reports__/m1-core-foundation/03-full_review_harmony_v0.md b/__reports__/m1-core-foundation/03-full_review_harmony_v0.md new file mode 100644 index 0000000..96a714a --- /dev/null +++ b/__reports__/m1-core-foundation/03-full_review_harmony_v0.md @@ -0,0 +1,218 @@ +# M1 full review, lens A (harmony): one way to do one thing + +Branch `feat/m1-core-foundation` at d9331cd. Scope: `crates/rdm-schema`, `crates/rdm-engine` (src and tests), a glance at +`crates/rdm-mcp`. Read-only; no code changed (`git diff --quiet` holds). Effort S/M/L. "Before main" means before M1 merges. + +## Verdict + +The code base is more harmonious than most at this size: zero `#[allow]` in product code, `#[must_use]` applied (55 sites; +pedantic flags only 2 missing), sentence-style test names throughout, one error enum for the store, `layout` and `tests/common` +exist and are used. What remains is four classes of drift, ranked below: record names and file suffixes still spelled in +~20 places despite `layout`; the same "this serialises" objective handled by four policies; duplicated helpers and docs that +will diverge; and conventions that nothing enforces (no `fmt`/`clippy` in CI, rdm-schema is not rustfmt-clean). None blocks M1 +on correctness. H1, H2, H3 and H7 are worth doing before main because each is small and each gets more expensive once M2 +adds callers. + +## Findings, by consequence + +### H1. Logical record names and the `.json` suffix are built in about 20 places; `layout` owns only `.rdm/` (M, before main) + +`layout.rs` says "the one place a logical name becomes a path", but it covers `record_path` (name to `PathBuf`) only. The names +themselves are made elsewhere, by four different means: + +| site | means | +|---|---| +| `schema/campaign.rs:37` `node_file(id)` | `format!("nodes/{id}.json")`, the intended one | +| `engine/write.rs:840` `node_path` closure, `:860` `Del` | `format!("nodes/{}.json", ..)`, in a file that imports `node_file` (`:11`) and uses it at `:52`, `:919`, `:935` | +| `engine/write.rs:846`, `:855` | `format!("_comments/{}.json")`, `format!("_amendments/{}.json")` | +| `engine/cache.rs:361`, `:491`, `:517`, `:543`, `:568` | `format!("{id}.json")` with the dir passed separately (`"nodes"` at `:357`, `:492`) | +| `engine/cache.rs:129-131` `kind_of`, `:163-` `NODES/COMMENTS/AMENDMENTS`, `engine/write.rs:1576` `effect_path_is_ours` | the three directory names re-listed three more times | +| `engine/store.rs:318` `Store::file_of` | a pure alias of `node_file` (see H8) | + +Scenario: renaming `_comments` or adding a fourth record kind needs edits at `cache.rs` (3 spots), `write.rs` (3 spots) and the +path guard; the guard `effect_path_is_ours` is the one that silently refuses recovery if it is missed. +Fix: one `RecordKind { Node, Comment, Amendment }` in `layout` with `dir()`, `file_name(id)`, `logical(id)` and `from_logical(&str)`; +`NODES/COMMENTS/AMENDMENTS`, `kind_of`, the plan effects and `effect_path_is_ours` all call it. Keep `node_file` in schema as +the public name and make `RecordKind::Node.logical(id)` the engine's only spelling. + +### H2. One objective, "a stored record becomes JSON", four error policies (S, before main) + +| site | policy | +|---|---| +| `codec.rs:98` `to_string_pretty(..).expect("a stored record serialises to JSON")` | panic, with a reason | +| `rev.rs:29` `to_value(node).unwrap_or(Value::Null)`; `write.rs:1538`, `:1543` the same | hide the failure as `null` | +| `rev.rs:37` `to_string_pretty(&value).unwrap_or_default()` | hide the failure as the empty string | +| `write.rs:152` `to_vec(&holder).unwrap_or_default()` | hide as an empty holder record | + +All four cannot fail for these types (string keys only; `rev.rs:36` even says so). The `expect` is the right policy because +it states the invariant; the others would make every node hash to the same `Rev` if the invariant ever broke, which is the +worst possible silent failure for an optimistic-concurrency token. Fix: one `pub(crate) fn json_value(&T) -> Value` +and one `json_text`, each with the single `expect`; the four sites call them. The same helper retires the `to_value` then +`.get("marks")` walk at `write.rs:1536-1544`, which reaches a typed field through JSON; `Node` has `Directory.marks` and +`Leaf.marks`, so a `Node::marks(&self) -> &[Mark]` accessor next to `id()`/`name()` is the idiomatic route. + +### H3. `StoreError::Invalid` has 12 construction sites, not three, and one hardcodes a magic file name across crates (S, before main) + +Known and deferred: three constructors. New evidence: the literal `StoreError::Invalid { .. }` appears at `schema/campaign.rs:103`, +`schema/stored.rs:190` (a closure with the string `""`), `engine/codec.rs:222` (`detail: &str`), `store.rs:151` +(`detail: String`), `write.rs:43` and `:51` (`impl Into`), `:270`, `:283`, `:763` (inline), `version.rs:144` and `:177` +(closures). Three different `detail` parameter types for one operation, and `REQUEST = ""` (`write.rs:40`) is +duplicated as a bare literal in rdm-schema, so the sentinel `contracts.md` names is spelled twice and cannot be searched for. +Smallest fix that does not need M2's rework: `pub const REQUEST_FILE` in `rdm-schema::error` used by both crates, and make +`store::invalid(file, rule, detail: impl Into)` the one engine-side constructor (replace `codec::invalid`, the two +`version.rs` closures and the three inline sites in `write.rs`). Leave the `Io`-drops-`ErrorKind` redesign to M2 as planned. + +### H4. `CachedCampaign` doc text is a verbatim copy of the `Store` methods it delegates to (S, before main) + +`cache.rs:626-720` (public) and `write.rs:960-1090` (`pub(crate)`) carry the same `///` blocks for `recover`, `replace`, `create`, +`move_node`, `delete_subtree`, `comment`, `batch`, `last_recovered`; `Store::open` and `CachedCampaign::open` repeat one `# Errors` paragraph. +Two copies of a contract drift: the next rule added to `replace` gets documented on one side. The public handle is the one a +consumer reads. Fix: keep the full doc on `CachedCampaign`, reduce the `pub(crate)` twins to one line plus "see +[`CachedCampaign::replace`]". Also `Store::last_recovered` is plain `pub` (`write.rs:963`) while every sibling write method is +`pub(crate)`, so the same report is reachable by two paths; make it `pub(crate)`. + +### H5. Nothing enforces the conventions; rdm-schema is not rustfmt-clean (S, before main) + +`cargo fmt -p rdm-engine --check`: 0 diffs. `-p rdm-schema`: 53 diffs and 33 lines over 100 columns (engine: 3). There is no +`rustfmt.toml`, `clippy.toml` or `[workspace.lints]`, and `.github/workflows/rust.yml` runs `cargo test` only (lines 47, 61). +The two crates were evidently written under different formatter settings. Fix: `cargo fmt --all`, add one `cargo fmt --check` +and one `cargo clippy --workspace --all-targets -- -D warnings` step, and a `[workspace.lints.rust]`/`clippy` table +(`unsafe_code = "forbid"`, `missing_docs` warn for the two lib crates). Do the format commit alone so blame survives. + +### H6. `Version` is a tuple alias with free functions; the stored form is `String` (M, M2) + +`lib.rs:12-61`: `type Version = (u16,u16,u16)`, `version_string`, `parse_version`, `is_newer`, while every stored struct holds +`schema_version: String` with the regex `^[0-9]+\.[0-9]+\.[0-9]+$` pasted six times (`stored.rs` x4, `read.rs` x2) and the +engine re-parses it (`version.rs:143 read_version`). Std idiom is a `struct Version` with `Display`, `FromStr`, `Ord`, and a +serde `String` representation; then `schema_version: Version` is validated at the type, the regex is generated once, and +`is_newer` is `>`. It matches how the id newtypes already work in this crate, so it is also the code base's own majority +pattern. Not before main (touches the on-disk contract tests); M2. + +### H7. Errors: two enums have no `Display`/`Error`, and impl style varies (S, before main) + +`order::KeyError` (no `Display`, no `std::error::Error`) and `NotInVersion` (neither) are public error types in the same +crates where `IdError`, `NameError`, `MintError`, `LockError`, `StoreError` implement both. A caller cannot `?` a `KeyError` into +`Box`. Style also differs: `ids.rs`/`error.rs` `use std::fmt` and write `fmt::Formatter`; `lock.rs:30` and `ids.rs:41` +spell `std::fmt::` in full. `StoreError::NotFound` prints `{target:?}` (Debug) in `Display` (`error.rs:253`), the only variant +that leaks Debug into a user message. `MintError` message hardcodes "32" instead of `MAX_COLLISIONS`. `LockError` has a `source()` +override while `StoreError::Io` stores `message: String` (the known ErrorKind deferral). Fix: add the two impls, use `fmt::` imports, +format `RecordRef` readably, interpolate the constant. + +### H8. Same-purpose items present twice (S, before main) + +- `Store::file_of(id)` (`store.rs:318`) is `node_file(id)` and nothing else; used by tests only (7 sites). Delete it; tests call `node_file`. + `tests/common/campaign.rs:44 file_of` is a third copy that reimplements the format string instead of calling `node_file`; make it + `node_file`. The same file defines `ALPHABET` (line 23) = `ID_ALPHABET` and `SCHEMA_VERSION` (21) = `version_string(FORMAT_VERSION)`: + tests that restate the constants cannot catch the constants changing, and cannot be found when they do. +- `read::Projection` and `read::LevelSource` are defined and tested (schema/tests) and used nowhere in either crate; `READ_MODEL_VERSION` + has one use, a test. They are M4 scaffolding by design: **keep, deliberate**, but note they are the only public items with no + production consumer. `diff::is_state` and `Campaign::is_validated` do have consumers. +- Parsing ids: product code calls the inherent `NodeId::parse` everywhere (7 sites) and never `str::parse::()`; `FromStr` + and `TryFrom` are implemented on every id type by the macro. `FromStr` is idiomatic: keep. `TryFrom` has no + consumer in either crate and `Name` lacks it, so the type family is not uniform: drop it or add it to `Name` (S, M2). + +### H9. Test helpers duplicated inside rdm-engine/tests (S, before main) + +`tests/common` was the fix, but these remain, byte for byte or nearly: + +| helper | copies | +|---|---| +| `rev_of(store, n)` | `store.rs:871`, `crash_prefix.rs:85` (identical) | +| `delete_op(store, n)` | `store.rs:905`, `crash_prefix.rs:89` | +| `diagnostic_keys(store)` | `crash_prefix.rs:297`, `crash_kill.rs:522` (identical but for a path-qualified `Rule`) | +| `at_prefix(pre_dir, log, k, into)` | `store.rs:2393`, `crash_prefix.rs:530` (signatures differ: one returns `PathBuf`) | +| `leaf_of` | `cache.rs:37` (takes `&Store`), `store.rs:403` (takes `&mut CachedCampaign`) | +| `base()` | `common/campaign.rs:186`, `crash_prefix.rs:40`, `crash_kill.rs:52`: three different fixtures under one name; each local one shadows the shared one | +| `holder_child` | `fs.rs:109`, `lock.rs:71`: different bodies, same name | + +Fix: move the first four into `common/campaign.rs`; rename the three `base()` to what they model (`hot_dirs`, `spare_and_deep`). +The local fixtures also use `let n = nid; dir_node(n(1), ..)` while common offers `dir_n(1, ..)`: use `dir_n`/`leaf_n`. +rdm-schema/tests/common (`fixture`, `round_trip`, `inject_unknown`) shares nothing with the engine's: **keep, deliberate**, the two +helper sets address different needs (JSON fixtures versus on-disk campaigns); a shared dev-only crate would cost more than it saves. + +### H10. `#[non_exhaustive]` on 2 of 40 public enums, with no stated policy (S, before main) + +Only `Rule` and `StoreError` carry it. The enums a consumer matches exhaustively and that M2-M4 will extend are unmarked: +`Current`, `LockError`, `IdError`, `NameError`, `KeyError`, `MintError`, `Durability`, `Pending`, `IntentEffect`, `Op`, `OpResult`, +`Position`, `RecordRef`. The wire enums (`Status`, `ActorKind`, `Expected`, ...) are closed by format version: **keep, deliberate**. +Fix: add it to the error enums and the engine's operational enums, and write the one-line rule (closed by format = exhaustive; closed +by implementation = `non_exhaustive`) in `lib.rs`. Do it now: adding it later is a breaking change for any in-tree consumer. + +### H11. Newtype family is three hand-written shapes (M, M2) + +`checked_string!` (NodeId, CriterionId, StepId, CommentId, AmendmentId, OpId), then `ItemId` and `Name` hand-written with the same +`FromStr`/`Display`/`Serialize`/`Deserialize`/`JsonSchema` bodies (about 90 duplicated lines, `ids.rs:238-405`), then `opaque_string!`. +Visible differences: `Name` has no `is_valid` and no `TryFrom`, `ItemId` has no `is_valid`, `Name` mixes its error +tag (`NAME_FORMAT_TAG`) with the id tag; `ItemId::parse` reports `WrongPrefix { expected: "c_" }` for an `s_`-or-`c_` choice, a +misleading message. Decoders classify a failure by string prefix (`MALFORMED_ID_TAG`): fragile, but documented and tested; **keep, +deliberate** until serde offers typed custom errors, and note the tag must move with the message text. Fix: extend the macro with +an optional error-tag argument so `Name` uses it, leave `ItemId` hand-written (it is an enum) but add `is_valid`. +`check_prefixed` also scans `ID_ALPHABET.contains(c)` linearly per character; harmless at id length, mentioned only because +`ids.rs` is the hot path of every cold open (S, M2). + +### H12. Ownership and path signatures (S, M2) + +Roots are `impl Into` in `Store::open`, `CachedCampaign::open`, `RecordingFs::new/over`, but `&Path` in `WriterLock::acquire`, +`revalidate`, `intent::*` and every `layout` function. API Guidelines (C-GENERIC) and std lean to `impl AsRef` for a path that +is only read, `impl Into` only where it is stored; the two `open`s do store it, so they are right and the `&Path` helpers are +right: **keep, deliberate**. The one genuine mismatch is `Entries::put(name: String, ..)` vs the `&str` taken everywhere else at +`cache.rs:91`, negligible. ULIDs travel as `&str`/`String` (`layout::intent_record(root, ulid: &str)`): known, M2. + +### H13. Doc-comment shape and small idioms (S, M2) + +- `# Errors` sections: present on `Store`/`CachedCampaign` and the schema crate, absent on 21 `Result` functions (13 on `fs.rs`'s + trait impls, 3 each in `version.rs`, `intent.rs`, one each `lock.rs`, `codec.rs`). A trait method documented once on the trait is + fine (`Fs`); the free functions `intent::begin/complete/pending` and `WriterLock::acquire` are public and lack it. +- Public enum variants and struct fields are mostly undocumented in `stored.rs`, `ops.rs`, `read.rs` (the stored-schema doc is the + documentation); acceptable while the design docs are normative, but then `missing_docs` cannot be enabled (H5): pick one. +- Product-code idioms clippy points at: `rev.rs:12,22` (`format!` into a `String`, use `write!`), `cache.rs:463-464` (`for_each` for side + effects), `cache.rs:562` and `write.rs:640` (unused `self`), `campaign.rs:185,231,385` (redundant closures), `write.rs:838` + (`let text = |n: &Node| encode(n)` beside direct `encode(c)`), `order.rs:70` (`midpoint` by hand; no overflow possible with 32 digits). +- `match` versus combinators: both are used for the same `Option` chains (`links.rs:58` `and_then(parse ... .ok())` vs `write.rs:589` + `if let Ok`), no majority; leave it. +- `Campaign::diagnostics` returns `&[Diagnostic]` and `Store::diagnostics` returns `Vec` (it merges two sources): **keep, + deliberate**, but the doc of the second should say it allocates. + +### H14. Naming drift (S, M2) + +`Written`/`Deleted`/`Commented` result types versus `CreateOp/ReplaceOp/RelocateOp/DeleteOp/CommentOp` and methods +`create/replace/move_node/delete_subtree/comment`: the op verb differs from the method in two of five (`Relocate`/`move_node`, +`Delete`/`delete_subtree`); "move" is the known M2 item. `fault` (`validate.rs:20`), `diag` (`campaign.rs:69`), `node_fault`, +`request_fault`, `invalid` all build an error value from `(rule, detail)`; one noun, "fault", would do. Test files: `crash_kill`/ +`crash_prefix` are named by technique, the others by module; fine. Test-function names are uniformly sentence-style: **keep**. + +### H15. rdm-mcp (spike): what to delete now + +Nothing depends on it, and it depends on neither rdm crate (zero references to `rdm_schema`/`rdm_engine`). It is labelled +"Throwaway MCP Apps feasibility stub" (`Cargo.toml` description), has its own `build.rs`, a 280K committed `view/dist`, fixtures +and a Python freezer, and every `cargo test --workspace` in CI builds `rmcp`, `tokio` and `jsonschema` for it. It also supplies 4 +of the 6 unused-`async` and the cast lints in the pedantic run, noise for the other two crates. Recommendation: do not delete before +main if M4 still wants its view and tests as a reference; but either move it out of `members = ["crates/*"]` (add to `exclude`, like +the `dirtree-rdm` entries) or delete it the day M4 starts. If it must stay in the workspace, exclude it from the CI test matrix: the +cost is paid by every other change (S, before main, only if CI time matters). + +## Clippy pedantic, counts by class (signal only) + +Whole workspace, all targets, about 110 warnings in total. By class: `# Errors` missing 21; `Map::default()` clearer 17 (tests); +function too long 17 (14 in tests; product: `Campaign::open` 198, `write.rs:1088` 132); `async` without await 4 (rdm-mcp); +`format!` from iterator 3; unused `self` 3; `map().unwrap_or()` on Result 3; items after statements 3; `for_each` 4; +single-pattern `match` 2; identical arms 2; redundant closure 8; casts 3; `#[must_use]` missing 2; other single hits 12. Product code +of the two crates accounts for about 40 of these, nearly all in the classes named in H13. No finding was raised from a lint alone. + +## Keep, deliberate (differences that are justified) + +- Zero `#[allow]` in product code; `#![allow(dead_code)]` in both `tests/common/mod.rs` (standard for a shared test module). +- `.expect(..)` with a stated reason at `ids.rs:30`, `:64`, `write.rs:140`, `codec.rs:98`: invariants, not input handling. (Contrast H2.) +- `let _ = remove_file` for scratch cleanup (`fs.rs:464`, `:491`, `publish.rs:42`, `lock.rs:128`) and `let _ = self.refresh()` after a failed + write (`write.rs:403`): best-effort on an error path that already returns the primary error, and commented. Lens B owns whether the + `refresh` failure should be logged. +- `Rule::code()` hand-written next to `serde(rename_all)`: two sources of one string, but `tests/campaign.rs:50 rule_codes_are_their_serde_names` + pins them. +- The two test-helper sets across crates (H9). The two `diagnostics` return types (H13). +- `impl Into` where the path is stored, `&Path` where it is only read (H12). + +## Not checked + +Did not read `write.rs` end to end (1718 lines) or `tests/store.rs` (3015); idiom review there is by grep and clippy only. Did not +compare `diff.rs`'s `to_value` use against H2 beyond noting it. Consumers were counted with a bypassed identifier grep, not colgrep +(a batch of 45 names in one pass; the colgrep index was not built). Did not run the test suite. rdm-mcp was only skimmed for H15. diff --git a/__reports__/m1-core-foundation/03-full_review_safety_v0.md b/__reports__/m1-core-foundation/03-full_review_safety_v0.md new file mode 100644 index 0000000..845253d --- /dev/null +++ b/__reports__/m1-core-foundation/03-full_review_safety_v0.md @@ -0,0 +1,185 @@ +# M1 full review, lens B (safety): false safety, sustainability, scalability, efficiency + +Branch `feat/m1-core-foundation` at d9331cd. Read-only review of `crates/rdm-schema` and `crates/rdm-engine` +(src and tests), against `__design__/rdm/{store,contracts}.md`. Two mutations and two probes were run; the tree +was restored each time (`git diff --quiet` held, and a `store.proptest-regressions` file that proptest wrote +during the first mutation was deleted). + +## Verdict + +M1 is sound at its core. The crash, cache, lock and revision guards use oracles outside the code under test +(jq plus SHA-256, a recorded effect log replayed on copies, a cold open, a brute-force scan), and the one +guard I broke on purpose (`reverse_index_equals_brute_force_scan`) went red three times in three. There are +two things to fix before merging to main: one write rule that is documented as guarded and is not (S1), and one +documented fallback that does not exist (S2). Everything else can wait for M2 or M4. + +## Findings, ranked by consequence + +### S1. A step reference to a node that does not exist is accepted, and no test notices (before merge, effort S) + +`crates/rdm-engine/src/write.rs:1703` (`take(s.get("references"))` in `introduced_references_exist`). +C28 says "a write never adds a defect", and the guard list names `requests_breaking_a_rule_are_refused` with a +`dangling_id` row. That row (`write.rs` test at `tests/store.rs`, the `dangling` edit) pushes onto +`l.references`, the leaf's own list. The loop over `steps[*].references` is not exercised by it. + +Proof: I commented out line 1703 and ran the whole `store` test binary: 27 passed, 0 failed. Reverted. +The property test does not help either: it creates step references to `pick(b)` ids that may be gone, but it +compares the index to a scan, and a dangling link is the same in both. + +Plausible bug missed: an agent writes a step whose reference names a typo'd or just-deleted node id. The write +succeeds, `Referrer` rows point at nothing, and `open` later reports it as damage on the next read. + +Fix: add a row to `requests_breaking_a_rule_are_refused` (a replace that adds `steps/0/references` with an unknown +`node_id`, expect `dangling_id`), and a directory row (`references` on a directory). Mutate line 1703 to see it red. + +### S2. Create-only publish has no fallback when the volume refuses hard links (before merge, effort S) + +`crates/rdm-engine/src/publish.rs:35-48` against `store.md:445`. The design says: "If the volume refuses hard +links, the store falls back to 'check the name is free, then rename' under the lock". The code has no fallback: +`fs.hard_link(&tmp, target)` fails and the error returns as `Io`. On FAT or exFAT media, and on some bind or +FUSE mounts, every `create` (every new node, comment and amendment) fails, while `put` works. +The error is loud, so this is drift and portability, not silent loss. + +Fix: on `ErrorKind::Unsupported` or `PermissionDenied` from `hard_link`, check `target` is absent and `rename`. +The writer lock is held, so the only race is an external writer, as the design says. Or edit `store.md:445` +to say there is no fallback and the platform is unsupported. Either way the two must agree. + +### S3. The shape-walking code does not follow `LINKS`: three hand-written walkers (M2, effort M) + +`links.rs:46-86` follows `LINKS` rows. Four other places hard-code field names and ignore it: +`write.rs:1534-1560` (`marks`, `preconditions`, `success_gates`), `write.rs:1683-1707` (`references`, +`steps/*/references`), `store.rs:232-262` (same marks walk, run for every node on every call) and +`write.rs:560-585` (`parent_id`, `order` of a snapshot). The guard `links_cover_every_id_field` checks `LINKS` +against the schema, so it keeps the reverse index honest, and nothing ties these walkers to `LINKS`. +The day a link field is added (a `Leaf.blocked_by`), the reverse index will find it and the dangling check of +S1 will not. All four also go through `serde_json::to_value(..).unwrap_or(Value::Null)`, so a failure there +would read as "no references, no marks" and pass. + +Fix: one function `introduced_links(before, after) -> Vec<(row, pointer, target)>` over `LINKS` (reuse `follow`), +and let `introduced_references_exist` and the mark checks consume it. This also removes S1's class of bug. + +### S4. An `Io` error leaves an intent record that the next writer completes, and no test injects one (M2, effort M) + +`write.rs:398-404` and `apply_plan` (`write.rs:874-896`). When effect k of n fails (ENOSPC, EACCES, a Windows +sharing violation past the retry window), the caller gets `Io`, the intent record stays on disk, and the next +write or `recover()` rolls it forward. This is documented (`contracts.md:595`: "maybe a recoverable prefix") and +the crash tests cover the prefix states. What no test covers is the live path: an `Fs` that returns `Err` at the +k-th effect, then the same handle reads (it sees a prefix), writes again (recovery completes the first +operation, then the second applies), and a retry of the first request with its `op_id` is replayed. `Hooked` +(`tests/common/hooked.rs`) can fail nothing; it only hides or removes files. Also `write.rs:403` is +`let _ = self.refresh();`: keeping the first error is right, but if the refresh also fails, the handle +holds a state the next `read()` repairs only because `forget` bumped the generation. State this in a comment +or test it. + +Fix: a `FailAt(k)` wrapper over `RealFs` in `tests/common`, and one test over a multi-effect op (a delete). + +### S5. Replay hands out the current revision, not the first result's, and does not compare the request (M2, effort S-M; keep the limit, narrow it) + +`write.rs:493-540`, `written()` at `write.rs:548`. Deliberate and stated (`contracts.md`, limit 2: "the store holds +no fingerprint of the request"). Two consequences are worth the numbers: +(a) the same node under the same `op_id` with other content is answered `replayed: true` and writes nothing. +`an_op_id_the_records_cannot_answer_is_refused_not_made_up` covers another node and another record kind, never +the same node with another payload. (b) `Written.rev` is the current `rev`. After a second actor edits the node, +a replayed first request returns a `rev` that includes the other edit, and a caller that treats it as the +result of its own write then replaces on it and passes the stale check over an edit it never saw. +Cheap partial mitigation: for a comment, compare `text` with the stored comment; for a replace, return +`Stale`-style information when the current `rev` differs from the `after` of the amendment. Not worth a +fingerprint in M1. + +### S6. Unknown integers beyond 64 bits are rewritten as floats (M2, effort S) + +`rdm-engine/Cargo.toml:21` and `rdm-schema/Cargo.toml:13` (`preserve_order`, `float_roundtrip`, no +`arbitrary_precision`). Probe on `canonical/campaign.json` with unknown keys added, through `decode` then `encode`: + + in : "zz_big": 18446744073709551617 out: "zz_big": 1.8446744073709552e+19 + in : "zz_neg": -9223372036854775809 out: "zz_neg": -9.223372036854776e+18 + in : "zz_exp": 1E3 out: "zz_exp": 1000.0 (documented in store.md) + in : "zz_dec": 0.1000000000000000055511151231257827 out: 0.1 + +I12 says unknown values are kept as written, and `store.md:157` documents only the `1e5` case. The proptest +(`tests/codec.rs`, `json_value`) draws `i64`, `u64` and floats within 1e15, so it cannot reach this. Any later +edit of such a node rewrites the unknown value. Fix: enable `serde_json/arbitrary_precision` (check the +`schemars` and untagged-enum interplay) or state the limit beside the `1e5` one. + +### S7. `diagnostics()` serialises every node on every call (M4, effort S) + +`store.rs:228-262`. `mark_diagnostics` runs `serde_json::to_value(node)` for every node of the campaign, plus a +`removed` set over all amendments, on each call. It depends only on the state, so it belongs in `build()` next +to `file_diags`. At 10k nodes that is 10k `Value` trees per call, on top of the known O(N) revalidation. +(Estimated, not measured.) Smaller O(N) per call: `Store::tree_rev()` (`store.rs:296`) rehashes all revs on each +`Receipt` and each replay; cache the `TreeRev` in `State`. + +### S8. A refused recovery wedges every write and the error does not name the record (M2/M4, effort S) + +`write.rs:228-236`, test `recovery_does_not_overwrite_a_create_whose_destination_holds_other_bytes`. By design +the record stays "for a person to resolve" and every write fails with `Invalid duplicate_id` naming +`nodes/.json`. A server operator sees a node file, not `.rdm/intent/.json`, which is the thing to remove. +Fix: put the record name in `detail`; M4 may want a `discard_intent` tool. + +### S9. Smaller items + +- `fs.rs:276` (`list_dir`): a non-UTF-8 file name is dropped without a trace; `cache.rs:140` (`listed`) drops every + name that is not `.json`. A node file saved as `n_0000000a.JSON`, or with a `.bak` copy beside it, is + invisible, not reported. `store.md` should say so, or `unknown_file` should be a diagnostic. (M2, S) +- `rev.rs:31,37` and `links.rs:46`: `unwrap_or(Value::Null)` / `unwrap_or_default()` on a serialisation that cannot + fail. If it ever did, every node would share one `rev` and the stale check would pass for all. Use `expect`, as + `codec.rs:98` already does. (M2, S) +- `lock.rs:108`: the holder record write is best effort and a failure is swallowed (documented, `store.md:201`). + After a `kill -9` the previous holder's `holder.json` stays, so a failed write names a dead pid. Remove stale + holder on acquire before writing. (M4, S) +- `fs.rs:204` `sync_dir` is skipped on Windows even at `Fsync`/`Full`; stated in `store.md:337` ("stated, not + tested"). Keep, deliberate. Opening the directory with `FILE_FLAG_BACKUP_SEMANTICS` and `FlushFileBuffers` is + possible through `OpenOptionsExt::custom_flags` if that claim matters later. +- `publish.rs:20-26`: `put` creates `nodes/` then syncs only that directory, not the campaign root, so the first + write's new directory is not durable. Power loss only (S17 is "not tested"). Keep, deliberate. +- `Open` on a path that does not exist succeeds with one `root_count` diagnostic, and the first lock-taking call + (`recover`, any write) creates the whole path plus `.rdm/{lock,.gitignore,tmp}` (probe, run once). A typo in + the root yields a stray directory tree. Fix: `Store::open` returns `Io(NotFound)` when `root` is not a directory, + or `WriterLock::acquire` uses `create_dir` for `.rdm` and not `create_dir_all`. (before merge is not needed; + M2, S) +- `intent.rs:97` `effect_path_is_ours` (`write.rs:1650`): on Windows a recorded `nodes/x.json:stream` is a + `Normal` component. The records are written by this binary and `.rdm/` is ignored by git, so the exposure is + an intent file planted by hand. Keep; note it. +- Tests: `replace_while_target_open` passes trivially on macOS and Linux (its own comment), so only the Windows + job guards S12. Keep, deliberate. `rev_tracks_value_not_formatting` needs `jq` on the machine and panics when + it is missing, which is loud; say so in the test or the README. +- `fs.rs` reader test spins a reader for up to 50 s; the main loop bounds at 20 s. Fine, but it is a busy loop + on a shared machine; add a `sleep(1ms)` every 25 reads. +- Sorted `Vec` tables in `cache.rs:70-110`: `insert`/`remove` are O(N) per row, so a checkout that interleaves + thousands of new names into a 10k table does O(N x changes) moves of large `Entry` rows. Rebuild the table when + changes exceed a threshold. (M4, S; not measured.) + +## What I checked and found sound (so nobody re-checks it) + +- `links_cover_every_id_field`, `move_table_matches_statuses_doc`: oracle is the schema and the markdown table, + not a copy. `links.rs` does not check `scope` and `on_delete` of each row: a flip of `Report` to `Keep` is + guarded only by the delete test (C11). +- `rev_tracks_value_not_formatting`, `tree_rev_changes_on_node_ops_not_comments`: hex computed outside the code. +- `stale_replace_changes_nothing`: both rows (another handle; same-size in-place edit under a frozen stat) are + real actors and assert the file bytes are unchanged. +- `unknown_keys_survive_in_place_at_every_level`: injection is generated from the fixtures, and the expected + pointers are computed independently. The `required` shape list is hand-kept: a new nested struct with `extra` + that no fixture contains will not be noticed, and `scan_*` in `codec.rs:290-370` is a hand list of the same. +- `reverse_index_equals_brute_force_scan`: mutation 1, removing the reverse-index update of a deleted node + (`write.rs:933`), is red 3 of 3 runs, so the generator reaches deletes that succeed. +- Duplicate JSON keys are refused at every level (`codec.rs:160-215`); CRLF and a BOM are accepted and not part of + the `rev`; the CI matrix runs Linux, macOS and Windows on stable and Linux on 1.88. +- Every guard name in `store.md` and `contracts.md` exists as a test function (28 of 28 named, listed by `fn` name). + Rows marked "not tested" are marked, with a reason. +- `#[non_exhaustive]` is on `StoreError` and `Rule`. Other public enums in `rdm-schema` are not; the crates are + `publish = false` and move in lock step, so keep. + +## rdm-mcp (M0 spike) + +Depends on neither `rdm-schema` nor `rdm-engine`; it serves its own fixture (`fixtures/roadmap.json`) and pulls in +`rmcp =3.10.0`, `tokio`, `jsonschema` and a `build.rs`. `cargo test --workspace` builds all of that on three +operating systems and the MSRV job. Nothing in it should be deleted for M1 correctness. I would delete the crate +at M1 merge (history keeps it, and M4 rewrites it over `CachedCampaign`), or, if M4 wants it as a reference, +exclude it from the CI job and say so. Decision for the owner. + +## Not reached (stopped at the tool budget) + +`write.rs` 1100-1500 (relocate, rename, rebalance, `check_whole`) beyond the guards that name them; `read.rs` and +`campaign.rs` in rdm-schema (only validation rules read); `crash_kill.rs` and `lock.rs` test bodies (guard exists, +oracle not read); `order.rs` midpoint arithmetic; id-space collision odds (`store.md` S16: 40-bit node ids make +"under 2e-9 per mint" true only up to about 2,200 deleted ids); clippy and a timing run at 10k nodes. diff --git a/__reports__/m1-core-foundation/04-knowledge_transfer_v0.md b/__reports__/m1-core-foundation/04-knowledge_transfer_v0.md new file mode 100644 index 0000000..7ad6284 --- /dev/null +++ b/__reports__/m1-core-foundation/04-knowledge_transfer_v0.md @@ -0,0 +1,81 @@ +# M1 core foundation: knowledge transfer, v0 + +M1 froze the contracts in `rdm-schema` and built the store in `rdm-engine`, on `feat/m1-core-foundation`: +- flat `nodes/.json` files; +- a canonical codec and a version chain that refuses newer files; +- ordered writes with a redo-only intent record and recovery under the lock; +- a revalidated hot cache behind one public handle, `CachedCampaign`. + +Every gate in the campaign README holds. The three-OS matrix, MSRV 1.88, lint and the soak are green at 825ea5d +(CI evidence in `02-adversarial_review_v0.md`). The Windows soak passed only after a test-helper fix, in 33 minutes +against a 45-minute cap; the cost behind that margin is the store's read path, which Eliott ruled on 2026-11-26 is +redesigned in its own PR (`__reports__/rdm_read_path_efficiency/`). The milestone is not yet on +`main`: landing it is Step 2 of the M1 leaf, and `FORMAT_VERSION` stays `0.1.0` until then (ruling R5). + +## What worked + +- **Independent oracles.** jq plus SHA-256 for `rev`, a fresh cold `open` for the cache, a brute-force scan for the + reverse index, the prefix-or-full state for crashes, and `statuses.md` parsed for `MOVES`. Every guard that was + mutated went red. +- **Depth as ordering.** Siblings ran in parallel worktrees, and each level merged `--no-ff` after a fresh verifier. +- **Open reviews late.** The two full-review lenses (harmony, safety) found real defects the mutation passes could + not: unchecked step references, a fallback the design promised and the code lacked, and four silent serialisation + fallbacks. + +## What hurt, and the change for M2 + +| Pain | Cost | Change | +|:--|:--|:--| +| Verifiers added a test row per surviving mutant | about 500 lines of cache tests, culled later | Triage survivors by real actor and class before briefing; a mutant is never a row | +| Agents re-read big files and dumped cargo output | up to 300k tokens per leaf | Fresh agent per round; reads by line range; filtered cargo output; batched calls; a tool-call cap in every brief | +| A temp worktree built into the shared target dir | rdm-schema tests ran with stale `CARGO_MANIFEST_DIR` paths | A worktree at another path gets its own target, or `cargo clean -p ` afterwards | +| Windows only seen at push time | three red rounds: backslash snapshot keys, jq CRLF output, autocrlf on committed schemas | `--no-fail-fast` on CI; `.gitattributes` `eol=lf` on every committed JSON that a test compares byte for byte | +| Helpers forked per test file | each cross-cutting fix had to be made 3-4 times | One `tests/common` from the start of M2 | +| Eliott's warning that reading JSON files would be expensive was answered by argument, and the cache probe judged 15 ms per read at 1 600 nodes against one tool call, on a machine at load 20-108 | the soak could not finish on Windows until a test-helper fix, and still takes 33 of its 45 minutes there; the read path needs its own redesign PR | A performance claim is a measurement: throughput (MB/s, files/s, reads/s) and a per-stage profile, at 10x the expected size and with history, on an idle machine and the three CI runners, judged against a fleet of agents | + +## Carried forward + +### To M2 (graph engine) + +| Id | Item | Source | +|:--|:--|:--| +| S1 | Whole-campaign clone and O(N) plan and derive per write | `02-sustainability_review_src_v0.md` | +| S9 | ULIDs round-trip through `String` | same | +| S10 | `write.rs` (about 1700 lines) to split by concern | same | +| S12 | "Move" means a status transition and a reparent (`Move`, `move_node`, `op_relocate`) | same, H14 | +| H6 | `Version` is a tuple alias with free functions; one newtype | `03-full_review_harmony_v0.md` | +| H11 | Three hand-written newtype shapes (about 90 duplicated lines) | same | +| H12, H13 | Ownership in signatures, `# Errors` sections, small idioms | same | +| sS3 | Four JSON walkers do not follow `LINKS`; one `introduced_links` | `03-full_review_safety_v0.md` | +| sS4 | No test injects an `Io` error mid-apply; `let _ = self.refresh()` at write.rs | same | +| sS5 | Replay returns the current `rev` and never compares the request payload | same | +| sS6 | Unknown integers beyond 64 bits are rewritten as floats (breaks I12) | same | +| sS9 | Non-`.json` names silently ignored; stale `holder.json` after a kill | same | +| T8 | One red row hides the rest in multi-row tests | `02-sustainability_review_tests_v0.md` | +| T9 | `crash_prefix` copies the whole tree per prefix | same | +| `op_id` | M2 chooses the `op_id`, sets `History.op_id`, and owns the directory `uncancel` lookup; the store owns replay (R4) | `00-gap_analysis_v0.md` §4 | +| Nits | `OpResult` is `#[non_exhaustive]` but mirrors the closed `Op`; `debug_assert!` on the decode at write.rs:905; the hard-link fallback replaces a dangling symlink | fix-round verifier | +| `RecordPath` | The logical-path newtype | sustainability round A | + +### To M4 (MCP server) + +| Id | Item | Source | +|:--|:--|:--| +| S2 | O(N) revalidation per read, history included, single read mutex: moved to the read-path redesign PR, before M2 | `02-sustainability_review_src_v0.md`, `__reports__/rdm_read_path_efficiency/` | +| S13 | Synchronous API and sleep-poll lock in an async server | same | +| sS7 | `diagnostics()` serialises every node per call; `tree_rev` rehashed per receipt | `03-full_review_safety_v0.md` | +| sS8 | A refused recovery wedges writes; a `discard_intent` tool may be wanted (the error now names the intent file) | same | +| F8 (F-d) | Typed ids in the read model | earlier design review, `settle` | +| `rdm-mcp` | The M0 spike was deleted at M1 (6bf8b92); its `rmcp` wiring and Svelte bridge are at 58a4a30 | M4 and M6 leaves | +| `rmcp` pin | Moves from M0 to M4 with the crate | meta README ownership line | + +## Owner decisions taken during M1 + +Recorded in the leaf gates and `__design__/rdm/{store,contracts}.md`: R1-R6 and F-c "refuse all" (Eliott). +The coordinator decided these within those rulings, and Eliott has not yet confirmed them: +- the root-family exemption; +- a rename of a sound root is refused; +- `op_id_reused`; +- the `Current` change; +- the cycle-member delete rule; +- the reading of the expected slug. diff --git a/__reports__/rdm_read_path_efficiency/00-findings_read_path_v0.md b/__reports__/rdm_read_path_efficiency/00-findings_read_path_v0.md new file mode 100644 index 0000000..e94a9b6 --- /dev/null +++ b/__reports__/rdm_read_path_efficiency/00-findings_read_path_v0.md @@ -0,0 +1,131 @@ +# rdm read path: findings (v0) + +Date: 2026-11-26 + +--- +type: findings +topic: rdm_read_path_efficiency +date: 2026-11-26 +version: v0 +prior-version: none +key-metric: cold-open throughput: 12.4 MB/s (prior: N/A, delta: N/A) +decision-required: intervene +--- + +## Headline Result + +metric: campaign bytes a cold `open` processes per second (1 600 nodes, 1.68 MB, release build, macOS) +value: 12.4 +unit: MB/s +prior: N/A (first measurement framed as throughput) +direction: new + +The store moves campaign data at about 12 MB/s cold, and every warm read pays one `stat` per file of the +campaign, history included. The M1 soak could not finish on Windows within 45 minutes. Eliott warned during the +architecture setup that reading JSON files would be expensive; the coordinator argued it would not matter and +never measured the claim against agent throughput. This report records what the numbers show. + +## Results Tables + +### Soak run 45621003595 at 813e42f (`PROPTEST_CASES=10000`, `RDM_SOAK_ITERS=1000`) + +| Job | `store` test binary | Kill harness | Job | +|:--|--:|--:|:--| +| ubuntu-latest | 702 s | 95 s | success | +| macos-latest | 1 127 s | 139 s | success | +| windows-latest | not finished at the cap | 100 s | cancelled at `timeout-minutes: 45` | + +In the `store` binary, `reverse_index_equals_brute_force_scan` takes nearly all the time: 240 cases take 17.4 s +locally, and the other 28 tests take about 1 s. + +### Where one proptest case spends its time (macOS `sample`, debug build, 8 s) + +| Part | Share of the test thread | What it is | +|:--|--:|:--| +| Test helper: one `store.read()` per candidate node | about 40 % | each read revalidates every file (test defect, fixed in a73b07b) | +| Cold `open` after each step | about 17 % | the oracle "a cold build agrees" | +| The six store writes | about 13 % | intent, publish, amendment, directory syncs | +| Brute-force scan and `held()` reads | about 9 % | the oracle, plus a revalidation | +| Set-up, tear-down, proptest | about 20 % | temporary campaigns created and removed per case | +| **System calls, after the helper fix** | **80 %** | `open` alone 28 %; decode and hash under 20 % | + +### Experiments (240 cases, local; each was reverted except the first) + +| Change | Time | Per case | +|:--|--:|--:| +| As committed at 6bf8b92 | 17.4 s | 73 ms | +| Helper reads once per step (a73b07b) | 10.9 s | 45 ms | +| plus `RACY_WINDOW` cut from 2 s to 20 ms | 10.1 s | 42 ms | +| plus dependencies built at `opt-level = 2` | 9.8 s | 41 ms | + +### The M1 cache probe, read as throughput (`01-cache_probe_v0.md`, release, macOS) + +| Measure | 160 nodes, 320 files, 163 KB | 1 600 nodes, 3 200 files, 1.68 MB | +|:--|--:|--:| +| Cold open | 12.6 ms: 12.9 MB/s, 39 µs per file | 135 ms: 12.4 MB/s, 42 µs per file | +| Warm read (aged) | 1.34 ms: 4.2 µs per file | 15.1 ms: 4.7 µs per file | +| Reads per second for the whole server (one read mutex) | about 750 | about 66 | + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:--|:--|:--|:--| +| Warm read cost | Bounded by what a call needs (one node: nanoseconds) | One `stat` per file of the campaign, nodes, comments and every amendment [source: `cache.rs:237` `sync_kind`, `01-cache_probe_v0.md`] | Read cost grows with campaign size and with history. History only grows: every write adds an amendment. | +| Amendment revalidation | Amendments and comments are append-only, never edited (`store.md` §Layout) | Stat-ed, and re-read when racy, on every read [source: profile, `load_file` under `CachedCampaign::read`] | Wasted work that grows with history. | +| Server throughput | Many agents in parallel against one campaign | `read` takes `&mut self` behind one mutex [source: `cache.rs:600-611`]: 66 reads/s at 1 600 nodes | Agents queue behind each other; per-read cost becomes the fleet's rate limit. | +| Cold throughput | Data processing at disk or parser speed | 12.4 MB/s, flat across 10x size [source: probe] | Per-file overhead (`open`, `stat`, `read`, `close`, hash, decode) dominates, not bytes. Not yet split by stage. | +| `rev` computation | One hash over the canonical bytes | Profile shows `rev` via `to_value` then `to_string_pretty` of the `Value` [source: sample, `rev::rev` → `codec::json_text`] | Encodes each record twice to hash it; to be measured in isolation. | +| Windows | Same algorithm, same order of time | The open-heavy test exceeds the cap; the process-heavy kill harness runs at Linux speed (100 s vs 95 s) [source: CI logs] | Per-file `open` is costlier on Windows (NTFS, real-time scanning of temporary directories), so per-file algorithms hurt most there. | + +## Charts & Visualizations + +Test job duration at soak counts, per OS (seconds, build included; the Windows bar is a lower bound, cut by the +45-minute cap with the `store` binary unfinished): + +``` +ubuntu ████████████████▉ 896 +macOS ██████████████████████████▋ 1407 +windows ███████████████████████████████████████▶ >2 700 + 0 500 1000 1500 2000 2500 s +``` + +Warm read cost against campaign files (release, macOS, minimum of four runs): linear, about 4.5 µs per file. + +``` +ms +15 | ● 1 600 nodes (3 200 files): 15.1 ms + | + 1 | ● 160 nodes (320 files): 1.34 ms + +----------------------------------------------- files stat-ed per read + 320 3 200 +``` + +## Contradictions & Surprises + +- The probe that should have caught this did measure it: 15 ms per read at 1 600 nodes, linear in files. Its + decision weighed that against "a tool call" for one agent, not against a fleet of agents behind one mutex, nor + against history growth, and it ran on a machine at load average 20 to 108 on 12 cores. +- The racy window (2 s) and the debug build together explain under 10 % of the time. The cost is per-file system + calls, not parsing. +- A single-node read costs the same as revalidating the whole campaign. + +## Steering Questions + +- [now] Merge M1 with the Windows soak recorded as a known limit of this implementation (Eliott, 2026-11-26), and + open a dedicated efficiency milestone before M2 builds on the read path? +- [now] Is the metric set right: MB/s for cold load and decode, files/s for revalidation, latency per operation + kind, reads/s for the shared handle, each at 160, 1 600 and 16 000 nodes and at 0x and 10x history, on all + three OS? +- [next run] Instrumented profiling of the hot paths (spans per stage: list, stat, read, hash, decode, build, index) + on an idle machine and on the three CI runners, before choosing any redesign. +- [later] Does history stay in per-write amendment files, or does its storage form change (it is tracked text that + git merges, so this is a format question)? + +## Pointers + +- `__reports__/rdm_read_path_efficiency/00-open_question_read_path_v0.md` +- `__reports__/m1-core-foundation/01-cache_probe_v0.md` +- `__reports__/m1-core-foundation/02-sustainability_review_src_v0.md` (S1, S2, S13) +- https://github.com/CrackingShells/cracking-shells-playbook/actions/runs/45621003595 +- `crates/rdm-engine/src/cache.rs` (`sync_kind`, `load_file`, `RACY_WINDOW`, `CachedCampaign::read`) +- commit a73b07b (the test helper fix) diff --git a/__reports__/rdm_read_path_efficiency/00-open_question_read_path_v0.md b/__reports__/rdm_read_path_efficiency/00-open_question_read_path_v0.md new file mode 100644 index 0000000..064509b --- /dev/null +++ b/__reports__/rdm_read_path_efficiency/00-open_question_read_path_v0.md @@ -0,0 +1,98 @@ +# rdm read path: open question (v0) + +Date: 2026-11-26 + +--- +type: open-question +question: How must rdm store, read, revalidate and process campaign data so an agent's call costs what it touches, not the whole campaign and its history? +domain: code +date-opened: 2026-11-26 +status: open +spawned-from: __reports__/rdm_read_path_efficiency/00-findings_read_path_v0.md (M1 soak cancelled on Windows) +closure-type: both +--- + +## The Question + +How should rdm read, revalidate and process campaign data so that a call's cost follows what it touches, not campaign size and history? + +## Handoff Contract + +- Receiving agent is asked to: build the measurement first (throughput benchmarks and instrumented profiles of + every hot path, on three OS), produce the numbers, then an architecture report that chooses a design from them. +- Receiving agent must NOT: change the stored format, the store's guarantees (I3, I4, I10, I12) or any public + signature before Eliott approves the architecture report; nor tune constants (racy window, opt-level) as a fix. + +## Context + +What M1 built and what it costs (release build, macOS, from `01-cache_probe_v0.md` and the findings report): + +| Path | Algorithm today | Cost grows with | Measured | +|:--|:--|:--|:--| +| Cold `open` | list three directories; `open`, `read`, SHA-256 and decode every file; build campaign, reverse index, op index | files | 12.4 MB/s; 42 µs per file | +| Warm `read` (every tool call) | list three directories; `stat` every file; re-read and hash files younger than 2 s | files, history included | 4.5 µs per file: 15 ms at 1 600 nodes | +| Single-node read | the full warm read, then a map lookup | files | same as warm read; lookup 22 ns | +| Write | refresh, re-read touched nodes, clone whole campaign and plan (S1), intent, publish, amendment, directory syncs | nodes (clone and plan), touched files (I/O) | about 1 ms of syncs per edit; the rest unmeasured | +| Shared handle | `read(&mut self)` behind one mutex (S2, S13) | concurrent agents | 66 reads/s at 1 600 nodes for the whole server | +| `rev` | `to_value`, then pretty-print the `Value`, then SHA-256 | record size | not isolated yet | + +What is fixed and must hold for any design: + +| Constraint | Source | +|:--|:--| +| Tracked campaign data stays text that git merges; a binary form may only be an untracked cache | `00-gap_analysis_v0.md`, plan rulings 2026-11-25 | +| A cached read equals a cold read for every external change class (I10), including in-place same-size edits within one mtime tick | `__design__/rdm/store.md` §Cache | +| Amendments and comments are append-only, never edited; a new write adds a new file | `__design__/rdm/store.md` §Layout (line 31), `stored-schema.md` (line 77) | +| MSRV 1.88; macOS, Linux and Windows | `rust.yml` | +| Many agents share one machine and one campaign | `~/.claude/CLAUDE.md`, "You are never alone" | + +## Option Landscape + +### Option A — Revalidate immutable records by name only +- Description: amendments (and any other append-only record) are checked by the set of names a directory lists, not by a `stat` per file. +- Benefit: warm read cost stops growing with history. +- Cost: an in-place edit of an amendment is no longer seen; I10's wording narrows to "every change a real actor makes". +- Unknown: whether any real actor rewrites an amendment in place (a merge, a rebase, a hand fix). + +### Option B — Change notifications with the stat walk as fallback +- Description: a watcher (FSEvents, inotify, ReadDirectoryChangesW) marks changed paths; a read revalidates only those. +- Benefit: warm read cost follows what changed, not what exists. +- Cost: three OS back-ends, event overflow and lost-event handling, a dependency, and a test harness for each. +- Unknown: whether events arrive reliably for `git checkout` bursts and for network or synced folders. + +### Option C — A cheaper unit of storage for history +- Description: history stored as fewer, larger text files (for example one append-only file per period) instead of one file per write. +- Benefit: fewer files to list, open and hash, on every path and every OS. +- Cost: a format change (version layer), and appends that git must merge on every branch. +- Unknown: how git merges concurrent appends to the same history file from two worktrees. + +### Option D — Faster per-file processing +- Description: one pass per file (read, hash the bytes, decode typed without an intermediate `Value`), `rev` from bytes already canonical. +- Benefit: raises MB/s on cold open and on every re-read, with no format or guarantee change. +- Cost: touches the codec and `rev`, which the drift and jq-hex oracles guard. +- Unknown: the share of the 42 µs per file that is decode and hash rather than system calls. + +## Comparison + +| Option | Reach (which paths gain) | Format change | Guarantee change | Per-OS work | Cost to learn more | +|:--|:--|:--|:--|:--|:--| +| A | warm read | no | I10 wording | none | low: count real actors that edit amendments | +| B | warm read, write refresh | no | none if the fallback is exact | high | medium: prototype on three runners | +| C | all paths | yes | none | none | medium: merge trials in two worktrees | +| D | cold open, re-reads, `rev` | no | none | none | low: the stage-split profile | + +*What this table does not settle:* the size of each gain. Without a per-stage profile (list, stat, open, read, +hash, decode, build, index) and throughput figures per OS, the options cannot be ranked, and they are not +exclusive. + +## What Would Close This Question + +[Both]: a benchmark suite that reports MB/s, files/s, per-operation latency and reads/s at 160, 1 600 and 16 000 +nodes, with 0x and 10x history, on macOS, Linux and Windows. Also an instrumented per-stage profile of each hot +path. Then an architecture report choosing the design from those numbers, approved by Eliott. The question closes +when the soak runs on all three OS within the job's existing cap. + +## Next Step to Reduce Uncertainty + +Build the measurement: a benchmark crate or target with byte and file throughput, and span-level instrumentation +of `open`, `read`, `write` and `rev`, run once on an idle machine and on the three CI runners. diff --git a/__reports__/rdm_read_path_efficiency/README.md b/__reports__/rdm_read_path_efficiency/README.md new file mode 100644 index 0000000..f699dcc --- /dev/null +++ b/__reports__/rdm_read_path_efficiency/README.md @@ -0,0 +1,22 @@ +# rdm read path efficiency + +How fast rdm reads, revalidates and processes a campaign, and the redesign that makes a call cost what it touches. +Opened when the M1 soak could not finish on Windows within 45 minutes (2026-11-26). + +## Documents + +### Round 00 (2026-11-26) + +- [00-findings_read_path_v0.md](00-findings_read_path_v0.md) (latest): what the soak, the profile and the M1 + cache probe show, read as throughput. +- [00-open_question_read_path_v0.md](00-open_question_read_path_v0.md) (latest): the question, the constraints, four + options and the measurement that must come first. + +## Status + +Open. M1 merges with this as a limit of its implementation (Eliott, 2026-11-26). After the test-helper fix +(a73b07b) the M1 soak passes at 825ea5d, Windows in 33 min 6 s against a 45-minute cap (run 45648611166); the +store's cost per read is unchanged. Before any redesign comes +the measurement: throughput benchmarks (MB/s, files/s, per-operation latency, reads/s) and instrumented +per-stage profiles on macOS, Linux and Windows. This supersedes the "no cost anyone will see" reading in +`__reports__/m1-core-foundation/01-cache_probe_v0.md`. diff --git a/__roadmap__/m0-feasibility-spike/README.md b/__roadmap__/m0-feasibility-spike/README.md new file mode 100644 index 0000000..ca31cd8 --- /dev/null +++ b/__roadmap__/m0-feasibility-spike/README.md @@ -0,0 +1,73 @@ +# M0 Feasibility spike + +## Context +Milestone M0 of the rdm meta-roadmap (`__roadmap__/roadmap-mcp-rework/m0_feasibility_spike.md`), run in parallel with M0b. It proves the pinned stack on real hosts before M1 builds on it: a stub `rdm-mcp` on `rmcp`, speaking MCP 2026-07-28 over stdio, with a Svelte `ui://` page that draws a throwaway fixture. Its report gives M4, M6 and M7 a go or no-go per host. + +## Reference Documents +- [R01 Architecture](../../__design__/rdm/architecture.md) — §Proposed State, §Graph view and §Risks & Mitigations: the pinned stack, the Apps mechanics and the risks this spike settles +- [R02 Meta-roadmap leaf](../roadmap-mcp-rework/m0_feasibility_spike.md) — the milestone gates this campaign must meet +- [R03 Domain model gap analysis](../../__reports__/rdm_domain_model_review/01-gap_analysis_v0.md) — why M0 is reduced to a feasibility check and is independent of the schema + +## Goal +Show, on the real hosts, that the stub server and its `ui://` page work: the page renders, opens a full view and one leaf's content, and makes no network request. Record each host's capabilities and context and the time to display, and give a go or no-go per host. + +## Pre-conditions +- [x] Plan approved by Eliott (2026-11-16) +- [ ] `workspace_skeleton.md` is done on the shared base before `feat/m0-feasibility-spike` is cut + +## Success Gates +- ⬜ `cargo build --workspace` and `cargo test -p rdm-mcp` pass on `feat/m0-feasibility-spike` +- ⬜ Every gate of the meta-roadmap leaf is recorded in `__reports__/m0-feasibility-spike/` as PASS, DEVIATION or BLOCKED, with its evidence +- ⬜ The report gives a go or no-go for Claude Code Desktop, VS Code Copilot and the Claude Code CLI + +## Gotchas +- **Decisions already taken (2026-11-16, Eliott):** + - The core crate is `rdm-engine`, because `rdm-core` is taken. + - The primary host is Claude Code Desktop, this app. VS Code Copilot is best effort and is not a blocker. The CLI does not render MCP Apps, so it is tested for tool calls only. + - The server speaks 2026-07-28 only, with no fallback and no diagnostic flag. A host that fails is a finding. +- **Pins:** + - `rmcp = "=3.10.0"` with the features `server`, `macros` and `transport-io`. 3.10.0 came out on 2026-11-12, after R01's 3.9.0. + - `@modelcontextprotocol/ext-apps` is pinned exactly, at 2.0.4 or later, with `vite-plugin-singlefile` 2.3.4. + - Node 26 and npm 11 are local. +- **What rmcp does and does not type:** rmcp has no typed MCP Apps API. The server builds these values by hand: + - the tool's `_meta.ui.resourceUri`, through `Tool::with_meta` + - `_meta.ui.visibility = ["app"]` on the app-only tools + - `capabilities.extensions["io.modelcontextprotocol/ui"] = {"mimeTypes":["text/html;profile=mcp-app"]}` + - the resource MIME type `text/html;profile=mcp-app` +- **The view's protocol:** the view announces Apps `protocolVersion` `2026-01-26` in `ui/initialize`. +- **Known host issues before the spike:** + - VS Code has an open issue saying it does not negotiate 2026-07-28. + - The desktop app has an open report (2026-11-07) that local stdio apps are not rendered. +- **`basic-host` is not a baseline.** The `basic-host` of ext-apps has no stdio transport, and HTTP is a non-goal. +- **The fixture shape is the contract** between `stub_server` and `graph_view`. It is fixed in `build/stub_server.md` Step 1, and neither leaf changes it alone. +- **Shared resources:** + - One shared `CARGO_TARGET_DIR` holds the builds of both M0 and M0b. + - `node_modules/` is deleted once `view/dist/index.html` is committed. + - Probe data goes to `$RDM_PROBE_DIR`, outside the repository. It is checked for personal data before any of it is copied into a report. +- **Budget:** the spike shares a USD 30 budget with M0b. It uses three Sonnet dispatches (`stub_server`, `graph_view`, `spike_report`), and the coordinator runs `host_trials` with Eliott. + +## Status +```mermaid +graph TD + workspace_skeleton[Workspace skeleton]:::done + build[Build the stub]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `workspace_skeleton.md` | 📄 Leaf Task | ✅ Done | +| `build/` | 📁 Directory | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m0-feasibility-spike/build/README.md b/__roadmap__/m0-feasibility-spike/build/README.md new file mode 100644 index 0000000..dd0b775 --- /dev/null +++ b/__roadmap__/m0-feasibility-spike/build/README.md @@ -0,0 +1,46 @@ +# Build the stub + +## Context +Depth 1 of the spike. It runs after the workspace skeleton exists. Two independent leaves build the stub server, with its fixture, and the graph page; they share only the fixture shape fixed in `stub_server.md`. Their output is what `trials/` puts in front of real hosts. + +## Goal +A stub `rdm-mcp` that serves the built graph page and passes its stdio integration test. + +## Pre-conditions +- [ ] `../workspace_skeleton.md` is done + +## Success Gates +- ⬜ `cargo test -p rdm-mcp` passes with the real `view/dist/index.html` embedded, not the placeholder +- ⬜ The coordinator's integration review finds that the server and the view agree on the fixture shape, the tool names and the probe payload + +## Gotchas +- **The two leaves never write each other's files.** `stub_server` owns `crates/rdm-mcp/` except `view/`, and `graph_view` owns `crates/rdm-mcp/view/`. +- **`build.rs` embeds a placeholder** until `view/dist/index.html` exists. Each leaf can therefore build and land alone. + +## Status +```mermaid +graph TD + stub_server[Stub server]:::done + graph_view[Graph view]:::done + trials[Host trials]:::done + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `stub_server.md` | 📄 Leaf Task | ✅ Done | +| `graph_view.md` | 📄 Leaf Task | ✅ Done | +| `trials/` | 📁 Directory | ✅ Done | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/m0-feasibility-spike/build/graph_view.md b/__roadmap__/m0-feasibility-spike/build/graph_view.md new file mode 100644 index 0000000..cfc0eb3 --- /dev/null +++ b/__roadmap__/m0-feasibility-spike/build/graph_view.md @@ -0,0 +1,55 @@ +# Graph view + +**Goal**: A Svelte 5 page, built into one HTML file with every script and style inlined, draws the fixture as a depth-ordered graph inside an MCP Apps host. It opens a full view and one leaf's content, and records its own display time and the host's data through the app-only tools. +**Pre-conditions**: +- [ ] `../workspace_skeleton.md` is done +- [ ] The fixture shape and tool names in `stub_server.md` Step 1 and Step 2 are read: they are the contract +**Success Gates**: +- ⬜ `npm --prefix crates/rdm-mcp/view ci && npm --prefix crates/rdm-mcp/view run build` produces `crates/rdm-mcp/view/dist/index.html` as one self-contained file, and the size is printed +- ⬜ `npm --prefix crates/rdm-mcp/view run check:offline` passes. It is a script that fails if the built file has any `