Skip to content

Make the graph the source of truth for the NodeSpace skill (channel-independent half) - #2284

Merged
malibio merged 7 commits into
mainfrom
issue-1958-skill-source-of-truth
Aug 25, 2026
Merged

malibio merged 7 commits into
mainfrom
issue-1958-skill-source-of-truth

Conversation

@malibio

@malibio malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

Closes the channel-independent half of #1958. The delivery-channel decision (rendered vs fetched-from-graph) is deliberately not made here — it needs the manual harness test, which needs an installable skill (#2283). Everything in this PR is correct under either outcome.

What was wrong

The skill is the only channel by which an external agent (Claude Code, Codex, Gemini CLI, OpenCode) learns what NodeSpace is and how to drive it. Four independent problems, all silent:

1. The CLI reference was a hand-maintained restatement of the clap definitions, and had drifted. Every row of the drift table on #1958 is now verified closed:

Drift Before Now
nodespace session (launch/attach/list/kill) 0 occurrences generated
nodespace uninstall 0 occurrences generated
nodespace model (list/load/recommended) mentioned once, never documented generated
import dir flags (7 of them) all omitted generated
node query --id omitted generated

2. Three of four targets installed a spec-invalid skill. Under the Agent Skills standard a skill is discovered by its frontmatter name + description; a folder without them is not a valid skill anywhere. Only Claude Code got a block — codex, gemini, and opencode were installing something that could never activate.

3. The description was the wrong shape for its job. It is the entire discovery surface (progressive disclosure loads only name+description at startup), and it was framed as personal memory — "remember this for later", "what did we save" — with no spec, ADR, architecture, design, or planning vocabulary. An agent about to write an ADR had nothing to match on. SKILL.md's opening line ("stores notes, tasks, and structured data") would equally describe a notes app.

4. The skill was stricter than the system. It said a relationship name "must be defined on the source node's schema", full stop. Four structural names (member_of, has_child, mentions, has_role) are legal between any two nodes without declaration — the local agent's seeded guidance says so, the external skill didn't. An agent following the skill would refuse an edge the system accepts.

What this does

Generalizes the generator from one hardcoded region to a registry of (marker_id, file, render_fn), now rendering three regions from three sources of truth: skill_rules.rs, the clap definitions, and BUILTIN_RELATIONSHIP_NAMES in nodespace-core.

Moves the generator to nodespace-cli, as an example. It must read both skill_rules and clap, and the dependency graph is cli → daemon → agent — so a binary in nodespace-agent (where it lived) cannot reach clap without a cycle. An example keeps it on the dev-target graph, where nodespace-agent is already a dev-dependency, so generation adds no dependency to the shipped nodespace binary.

Brings the body within spec. SKILL.md was 534 lines; generating the previously-missing CLI surface pushed it to 786 lines / ~11.1k tokens against recommendations of 500 lines / 5k tokens. The body is loaded in full on every activation, so that is a cost every agent pays on every matching task. The CLI reference was 70% of the file and moved to references/cli.md — the on-demand tier the standard defines, portable across all four targets.

259 lines / ~3.8k tokens. Inside both limits, with a test holding the line.

Fixes the definition to the product's own framing: the repository holds what was built, NodeSpace holds why it was built, how it should be built, and what agents need to know to build it correctly.

Enforcement is structural, not a checklist

Coverage is computed by walking Cli::command(), seed_skill_nodes(), and BUILTIN_RELATIONSHIP_NAMES at test time. A checked-in list of expected names would itself be a second representation that drifts — and it fails in the worst direction, silently by omission. This follows the existing precedent in agent_guidance.rs's guidance_corpus().

Eight tests, covering: every command, every flag (global and per-leaf), every seeded skill, every built-in relationship name, body size, reference reachability, and generator freshness.

The contract runs one way only: every source must have a rendered section. It is never asserted that every section has a source. That asymmetry is load-bearing — judgment prose (what NodeSpace is, when to reach for it, how to install it) has no upstream and must survive regeneration untouched. A test demanding the reverse would delete exactly the content a generator cannot produce.

All eight seeded skills are covered, not six. Enumeration is from the returned vector, so the two defined as inline raw strings (Research & Search, Node Creation) cannot be skipped the way a check keyed on builder-function names would skip them.

Guards verified to fail

An assertion that never fires is worthless, so each was checked by injecting the defect:

  • undocumented flag → SKILL.md does not document these CLI flags: ["node query --zzz-fake-negative-test-flag"]
  • uncovered seeded skill → these seeded skills have no counterpart in SKILL.md: ["ZZZ Negative Test Skill (no coverage rule defined)"]
  • installer flattening references/ → claude-code: references/cli.md: expected false to be true

Three silent seams from the split

Moving content out of the body has three failure modes that each break quietly. Each is fixed and covered:

  • build-skill.ts copied a fixed list excluding references/ — would have bundled a body linking to a file that wasn't there.
  • The installer flattened every shim to its basename — would have installed references/cli.md as cli.md, breaking the relative link.
  • context_assembly.rs embeds SKILL.md for PTY sessions — would have written a body whose link pointed at nothing. (The PTY path is out of scope for the decision, but this was a live regression the split would have introduced.)

Tests now read the whole shipped skill (body + references/) rather than SKILL.md alone, so content that changes tier is not misreported as drift.

Orchestration

  • bun run skill:gen — regenerate
  • bun run skill:check — fail on drift
  • build:skill runs the check first, so a stale skill cannot be bundled. It is already in scripts/test-gate.ts, so the check runs pre-push.

Rendering stays in Rust: all three sources of truth are Rust, and reading them from TypeScript would mean re-encoding them — recreating the drift this issue exists to kill. Bun is the interface; Rust is the implementation.

Not in this PR

  • The delivery-channel decision and the manual harness test — blocked on Publish the NodeSpace skill so users can actually install it: public import repo + automated release #2283 making the skill installable.
  • Description activation verified by hand. The description now carries the right vocabulary and is length- and field-validated, but whether it actually activates is exactly the thing that must be measured in a real harness, not assumed because it reads well.
  • Seeded guidance never reaching existing installs (seeding skips by node type) — a prerequisite for any model where users control guidance through NodeSpace.

⚠️ The description text is product positioning. I used #1958's own starting point verbatim rather than inventing wording — worth a look before merge.

Testing

  • bun run test:all — exit 0. Frontend 227 files / 4794 tests, identical to the recorded baseline. Skill package 29 (was 24). 54 Rust crates green.
  • bun run quality:fix — 0 errors, 0 warnings; clippy clean under -D warnings. No unrelated workspace churn.
  • Full pre-push gate passed, including cold cargo build, test:e2e, and build:skill.

🤖 Generated with Claude Code

https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3

malibio and others added 4 commits August 25, 2026 01:41
…rally

The skill is what an external agent reads to learn how to drive NodeSpace.
Its CLI reference was a hand-maintained restatement of the clap definitions
and had fallen behind: `session`, `uninstall`, and the `import dir` flag set
had zero occurrences, `model` was mentioned once and never documented, and
`node query --id` was absent. Nothing caught any of it — a stale skill just
makes the agent act on instructions that no longer match the binary.

Generalize the generator from one hardcoded region to a registry of
(marker_id, render_fn) pairs and add a second region rendering the whole CLI
surface by walking `Cli::command()`. All five drift rows close as a result.

Move the generator from `nodespace-agent` to a `nodespace-cli` example. It
must read both `skill_rules` and the clap definitions, and the dependency
graph is cli -> daemon -> agent, so a binary in `nodespace-agent` cannot
reach clap without a cycle. An example keeps it on the dev-target graph,
where `nodespace-agent` is already a dev-dependency, so generation adds no
dependency to the shipped `nodespace` binary.

Enforce coverage by dynamic enumeration rather than a checked-in list, which
would be another second representation that drifts silently by omission:
- every command/subcommand from `Cli::command()` is documented
- every flag, global and per-leaf, is documented
- every skill from `seed_skill_nodes()` has a counterpart, enumerated from
  the vector so the two inline raw-string skills (Research & Search, Node
  Creation) cannot be skipped the way a check keyed on builder-function
  names would skip them
- the checked-in file matches generator output

The contract runs one way only: every source must have a rendered section,
never that every section has a source. Judgment prose — what NodeSpace is,
when to reach for it, how to install it — has no upstream and must survive
regeneration untouched.

Both guards were verified to fail: injecting an undocumented flag and an
uncovered seeded skill each produced a failure naming the offender.

`bun run skill:gen` / `bun run skill:check` wrap the generator, and
`build:skill` now runs the check first, so a stale skill cannot be bundled.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
…in spec

Three problems, one artifact.

**Frontmatter shipped for one target of four.** Under the Agent Skills
standard a skill is discovered by its frontmatter `name` + `description`, and
a folder without them is not a valid skill anywhere. Only Claude Code got a
block, so codex, gemini, and opencode were installing something that could
never activate. The block is now shared and uses only the six spec-defined
fields, since other distribution paths hard-error on keys they don't
recognize.

**The description was the wrong shape for the job.** It is the entire
discovery surface — under progressive disclosure an agent loads only
name+description at startup and reads the body after deciding relevance — and
it was framed as personal memory ("remember this for later", "what did we
save"), carrying no spec, ADR, architecture, design, or planning vocabulary.
An agent about to write an ADR had nothing to match on. It now leads with what
NodeSpace is, matching the product's own framing: the repository holds what
was built, NodeSpace holds why it was built. The opening line of SKILL.md said
"stores notes, tasks, and structured data", which would equally describe a
notes app; it now states the same distinction, and says plainly to read before
writing and write back on deciding.

The description stays hand-tuned and excluded from generation. Its job is to
match how a user phrases a request — measurement-and-judgment work with no
upstream source to render from.

**The body was over budget.** 534 lines before this work; generating the
previously-missing CLI surface pushed it to 786 lines / ~11.1k tokens against
recommendations of 500 lines / 5k tokens. The body is loaded in full on every
activation, so that is a cost every agent pays on every matching task. The CLI
reference was 70% of the file and is now `references/cli.md` — the on-demand
tier the standard defines, portable across all four targets. The body is 259
lines / ~3.8k tokens, inside both limits, and a test holds the line.

Splitting content out has three seams that each fail silently, so each is
covered:
- `build-skill.ts` copied a fixed list that excluded `references/`, which
  would have shipped a body linking to a file that wasn't bundled.
- The installer flattened every shim to its basename, which would have
  installed `references/cli.md` as `cli.md` and broken the relative link.
- `context_assembly.rs` embeds SKILL.md for PTY sessions and would have
  written a body whose link pointed at nothing.

Tests now read the whole shipped skill (body + references) rather than
SKILL.md alone, so content that changes tier is not reported as drift. The
reference-path guard was verified to fail when the installer flattens.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
…nt rule

The skill told an agent that a relationship name "must be defined on the
source node's schema" — full stop. That is stricter than the system: four
structural names (member_of, has_child, mentions, has_role) are legal between
any two nodes without a declaration, and a schema that tries to declare one is
rejected. The local agent's own seeded guidance says so; the external skill did
not, so the two surfaces disagreed and an agent following the skill would
refuse an edge the system would have accepted.

Render the list from BUILTIN_RELATIONSHIP_NAMES in nodespace-core — the
constant the validator itself checks against — so the two cannot diverge again,
and add a test enumerating it so a name added later cannot be omitted.

Also record the issue-assignment rule in CLAUDE.md: an assignee means work is
in progress, so issues are assigned in the startup sequence when work actually
begins, never at creation time to signal intent or ownership.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2284

Review Type: Initial Review

Verified against the code, not the PR description. Ran: cargo test -p nodespace-cli --test skill_md_generation (8/8 pass), bun run --cwd packages/skill test (29/29 pass), cargo clippy -p nodespace-cli --tests --examples (clean), cargo tree, plus three mutation experiments and a live install/uninstall round-trip. All mutations reverted; both checkouts clean.


Requirements Check

Issue #1958 has 15 acceptance criteria.

# Criterion Status
1 Delivery channel decided, harness test recorded ⬜ Deferred — legitimately blocked
2 Manual test vs Claude Code + Codex ⬜ Deferred — legitimately blocked
3 Guidance authored in graph; no second hand-maintained copy 🟡 Partial — see 📝 A
4 Descriptions hand-tuned, explicitly excluded from generation ✅ Met
5 Frontmatter description carries docs/specs/architecture vocabulary + effect verified by hand 🟡 Partial — text ✅, hand-verification ⬜ (blocked with #1/#2)
6 Spec-compliant frontmatter for all four targets ✅ Met — verified in agents.ts; test asserts all four
7 Opening definition uses vision framing (repo=what, NodeSpace=why) ✅ Met
8 Schemas/types fetched live via CLI, never baked in ✅ Met — SKILL.md:133-134
9 CLI reference derives from clap; model/session/uninstall/import dir flags/node query --id reachable ✅ Met — verified all present in generated block
10 All eight seeded skills covered, not six ✅ Met — seed_skill_nodes() returns exactly 8; test enumerates dynamically
11 New skill/command/flag without coverage fails a test, via dynamic enumeration 🟡 Partial — see 🔴 F2
12 Judgment prose survives regeneration untouched ✅ Met — contract is one-way; verified in regions()/splice_generated_block
13 SKILL.md body ≤500 lines, <5000 tokens ✅ Met — 259 lines / ~3,755 tokens (measured)
14 Drift check runs via bun run skill:check in scripts/test-gate.ts ✅ Met — build:skill = skill:check && …, gate line 47
15 gen_skill_md.rs module doc no longer claims CLI has no generatable analog ✅ Met — grep for the old claim returns empty

Tally: 9 met, 3 partial, 2 legitimately deferred, 1 defect (F2).

📝 Deviation notes

  • A — Criterion 3 is met only in the narrow sense. The CLI half is genuinely derived. The guidance half is not: SchemaRule.prose still lives in skill_rules.rs (Rust source), not in the graph. The issue's stated principle is "the graph is the source of truth"; today the source of truth is a Rust constant that also seeds the graph. That is a real improvement over a hand-copied restatement, and moving it into the graph is exactly what the deferred delivery-channel decision governs — so this is correctly sequenced, not skipped. Worth stating plainly in the PR body so criterion 3 isn't later read as closed.
  • B — Deferring Set up Tauri + Svelte project structure #1/Create design system foundation #2/Basic storage integration #5's hand-verification is justified. The issue itself mandates a manual harness test, and that test needs an installable skill (Publish the NodeSpace skill so users can actually install it: public import repo + automated release #2283). Shipping the channel-independent half first is the right call. The PR is honest about this.
  • C — Criterion 13 is now enforced by a test, which is stronger than the criterion asked for.

Code Review Findings

🔴 Critical

F1 — uninstall() leaks references/cli.md and leaves a malformed skill folder behind

📁 packages/skill/src/installer.ts:88

install() was updated to preserve the references/ directory, but uninstall() was not — it still flattens every shim to basename(shim):

const dest = join(config.installDir, basename(shim));   // uninstall — NOT updated

vs. install's new:

const relative = shim.startsWith('references/') ? shim : basename(shim);

So uninstall looks for <installDir>/cli.md, which never exists — the file was installed to <installDir>/references/cli.md.

Concrete failure scenario — reproduced live, not theorized. I ran a real install/uninstall round-trip against a throwaway $HOME:

AFTER INSTALL:  [ "references/cli.md", "SKILL.md", "nodespace-hook.ts" ]
UNINSTALL removed: [ ".../SKILL.md", ".../nodespace-hook.ts" ]   # cli.md absent
DIR STILL EXISTS: true  [ "references/cli.md" ]

Two consequences, the second worse than the first:

  1. readdirSync(installDir) is non-empty, so the remaining.length === 0 cleanup never fires and the install directory survives uninstall.
  2. What survives is a directory named skills/nodespace/ containing references/cli.md and no SKILL.md. That is a malformed skill folder under the Agent Skills standard, not merely an orphan file — a harness scanning the skills directory finds an entry with no name/description frontmatter. Best case it is ignored with a warning; worse, a strict loader errors. The user ran uninstall and is left in a state that is arguably worse than before.

Why the 29 passing tests miss it: the uninstall tests seed their fixtures with writeFileSync(join(agent.installDir, basename(shim)), …) (installer.test.ts:288) — i.e. they construct the flattened layout that matches the buggy code, rather than the layout install() actually produces. The test encodes the bug's assumption, so it can never catch it.

Fix: extract the path mapping into one shared helper used by both functions, and remove the empty references/ directory during cleanup:

const installedRelativePath = (shim: string) =>
  shim.startsWith('references/') ? shim : basename(shim);

Then have the uninstall test assert a genuine round-trip — call install() first, then uninstall(), and assert existsSync(installDir) === false. A test that seeds its own fixture cannot validate the other function's output format.

Principle: DRY / single source of truth for a derived value. The install-path rule is one decision expressed in two places; the second copy silently disagreed. This is precisely the drift class this PR exists to eliminate — worth fixing here for consistency with the PR's own thesis.


F2 — every_cli_flag_is_documented cannot fail for a new flag whose name already appears anywhere in the corpus (criterion 11)

📁 packages/cli/tests/skill_md_generation.rs:127-170

The test checks bare skill.contains("--{long}") against a concatenation of SKILL.md + every file in references/. It never associates a flag with its command.

Concrete failure scenario — reproduced by mutation. I added a genuinely new, entirely undocumented --limit flag to ExportArgs (node export, which has no --limit today), then ran the test:

test every_cli_flag_is_documented ... ok        # PASSES — should have failed

It passes because node query --limit already documents the string --limit elsewhere in the corpus. The corpus makes this likely, not exotic: --limit appears 10×, --json 10×, --collection 8×, --id 7×. Any new flag reusing a common name — --limit, --json, --type, --id, --collection, --offset, --replace — is invisible to this test.

However — the impact is contained, and this is the important half of the finding. I ran the same mutation against the drift test:

stale generated content in: references/cli.md
test checked_in_skill_md_is_up_to_date ... FAILED

checked_in_skill_md_is_up_to_date catches it, because the generated block is exhaustive and byte-compared. So criterion 11 is satisfied in effect — a new flag does fail a test — just not the test that appears to be responsible for it.

That gap matters for a specific reason: the two tests have different blast radii. checked_in_skill_md_is_up_to_date only guards content inside the generated markers. every_cli_flag_is_documented is the only test covering the hand-written prose around them. Today all three regions live in references/cli.md, so the byte-compare covers the CLI surface completely. But the region registry explicitly supports regions moving between files (GeneratedRegion.file), and if CLI content is ever partly hand-written or moved out of a marker, the substring test is the sole guard — and it is one that cannot fail.

Recommendation (not a merge blocker, given the backstop): scope the needle to its command by searching within that command's rendered section rather than the whole corpus — e.g. slice the corpus at the ### \nodespace {cmd}`` heading and search within it. Alternatively, add a comment stating explicitly that the byte-compare is the real guarantee and this test is a coarse secondary net, so a future reader does not over-trust it.

Principle: a test that cannot fail is not a test. Its value is the confidence it conveys, and mis-stated confidence is a liability.


🟡 Important

F3 — packages/skill/package.json files array omits references, so an npm-published package ships a dangling link

📁 packages/skill/package.json:17-21

The PR updated three consumers (build-skill.ts, installer.ts, context_assembly.rs) but not the fourth — the npm packaging manifest:

"files": [ "dist", "shims", "SKILL.md" ]

Concrete failure scenario: npm publish (or npm pack) of @nodespaceai/skill produces a tarball containing SKILL.md whose body links to references/cli.md, with no references/ directory in it. A user installing from npm gets a skill whose entire CLI reference — 568 lines, the bulk of the operational content — is unreachable. The body still says to read it, so the agent follows the link, finds nothing, and proceeds without knowing the CLI surface. Silent degradation, exactly the failure mode the PR's own write_skill_md test and build-skill.ts comment guard against on the other two paths.

Mitigating: @nodespaceai/skill currently 404s on npm (noted in #1958's own Related section, via #2271), and today's shipping path is the Tauri resource bundle — which build-skill.ts does handle correctly. So this is latent, not live. But it is a one-word fix, and #1958 explicitly anticipates that publication path being revived. Add "references" to the array.

Principle: when a path-shaped invariant changes, enumerate every consumer. Three of four were found; this is the fourth. (I searched exhaustively for others — include_str!, resources/skill, hardcoded path lists, Tauri config, skill_setup.rs, the onboarding/settings Svelte components — and found no additional missed consumers. The resources/skill/ tree is gitignored and regenerated by build-skill.ts, so it needs no change.)


F4 — every_seeded_skill_is_represented's match arms are a hand-maintained list wearing dynamic-enumeration clothing

📁 packages/cli/tests/skill_md_generation.rs:206-231

The enumeration is genuinely dynamic (it walks seed_skill_nodes()), and the other => catch-all correctly forces a decision when a skill is added — that part is a real improvement and satisfies the spirit of criterion 10. Credit where due.

But the needles are hand-written substrings, and several are so weak they cannot fail. Measured occurrence counts in the shipped corpus:

Skill Needle Occurrences
Research & Search "search" 36
Organization "collection" 33
Bulk Import "import" 16

Concrete failure scenario: delete the entire Research & Search section from SKILL.md. The word "search" still appears 35 other times — in search_nodes, semantic search, --search, prose asides. Test passes. The skill the issue singles out as "the largest body of the set, and the un-generated source of SKILL.md's own Tool Decision Guide" is the one with the weakest possible guard.

This is defensible as a coarse smoke test, and the doc comment is honest that it matches "the distinguishing noun rather than its exact title." But the module doc claims this approach avoids a "checked-in list [that] is itself a second representation that drifts" — and a match arm mapping a title to a magic string is that second representation. The mechanism moved; it did not disappear.

Recommendation: anchor the needles to markdown headings (e.g. require a #-prefixed line containing the term) rather than bare words, so the test asserts a section exists rather than that a common word appears somewhere. Low cost, and it makes the guard real.

Principle: prefer structural assertions over lexical ones — lexical absence over a large corpus proves very little.


🟢 Suggestions

F5 — checked_in_skill_md_is_up_to_date nests cargo run inside cargo test, duplicating the gate

📁 packages/cli/tests/skill_md_generation.rs:334-358

I probed the concerns raised and can largely clear them:

  • Deadlock/lock contention: Does not occur. The nested invocation completed in ~9s within a cargo test run, and re-ran cleanly under mutation. Cargo's package lock is held during build, not during test execution, and the child builds a target the parent already built.
  • Cost: ~9s vs ~0.01s for the pure tests — noticeable but not prohibitive, and it is by far the highest-value test in the file (per F2, it is the only thing that reliably catches a new flag).
  • Duplication with bun run skill:check: Real but deliberate, and the doc comment justifies it explicitly — a contributor editing skill_rules.rs or a clap doc comment sees the failure under plain cargo test, without knowing a separate bun command exists. That is a reasonable trade.

The one genuine fragility: env!("CARGO") plus current_dir(manifest_dir/../..) assumes a workspace layout and an available cargo binary. In a packaged-crate or vendored context this would fail with a confusing message. Given this is a workspace-only dev tool with no such consumer, I'd leave it as-is — flagging only so the trade is on record. Consider #[ignore]-ing it if the 9s ever becomes an irritant in tight TDD loops.

F6 — shim.startsWith('references/') is narrow but correct for the current design

📁 packages/skill/src/installer.ts:56

I probed the raised concerns and they are not live defects:

  • Path traversal: Not reachable. config.shims is a compile-time constant array in agents.ts, never user input. There is no attacker-controlled path here.
  • Windows separators: Not a live concern — the four installDir values are all POSIX ~/.… paths, and detectionDir gates installation, so Windows never reaches this code today.
  • Nested references/ subdirectory: Already works. mkdirSync(dirname(dest), { recursive: true }) handles arbitrary depth, so references/cli/advanced.md would install correctly with no change.

The one real asymmetry is conceptual: the rule is "flatten everything except this one prefix," which is a special case rather than a policy. A cleaner expression is to flatten only shims/ and preserve everything else — that inverts the special case to match intent ("shims flatten; content keeps its shape"). Nit-level, and I'd not block on it. But note it interacts with F1: whichever rule is chosen must be applied in both install and uninstall.

F7 — The examples/ placement is the right call

📁 packages/cli/examples/gen_skill_md.rs:20-33

I verified the justification independently rather than taking it on faith:

  • The cycle claim is true. cargo tree confirms nodespace-agent → nodespace-daemon → nodespace-cli. A binary in nodespace-agent genuinely cannot reach Cli::command() without inverting that.
  • nodespace-agent is a dev-dependency of nodespace-cli — confirmed in packages/cli/Cargo.toml:31.
  • No production dependency is added. cargo tree -p nodespace-cli --edges normal --depth 1 shows the shipped binary's direct deps unchanged.

One precision note on the module doc's framing: it says the example target "keeps it on the dev-target graph, where nodespace-agent is already a dev-dependency — so generation adds no dependency to the shipped nodespace binary." The conclusion is correct, but the reasoning is slightly off — nodespace-agent already reaches the production binary transitively via nodespace-daemon, so the dev-dependency isn't what protects the shipped binary. What actually protects it is that examples/ is simply not a [[bin]] and is never built for release. Worth a one-line correction so a future reader doesn't rely on a load-bearing claim that isn't the real mechanism.

Versus the alternatives: a tests/-only helper couldn't be invoked by bun run skill:gen; a build script would run on every compile and write into a sibling package (bad); a separate crate is real overhead for one file. examples/ is correct.

F8 — render_arg_list is sound; collapse_whitespace is safe

📁 packages/cli/examples/gen_skill_md.rs:236-300

Checked each raised concern against the generated output:

  • Positional-vs-flag handling is correct. The takes_value guard suppresses the placeholder for positionals, and I confirmed no <ID> <ID> doubling anywhere in the 568-line output — positionals render cleanly as `<ID>` — Node ID (UUID) (required).
  • is_global_set() != globals_only correctly documents the three global flags once at the top rather than repeating them under ~40 leaves. Verified in output.
  • Value-name fallback (get_value_names() → uppercased id) produces sensible results throughout (<SOCKET>, <MODEL_ID>, <DIRECTORY>).
  • collapse_whitespace mangling markdown: I grepped every clap doc comment in packages/cli/src/ for fenced code blocks and intentional bullet lists — there are none. Every multi-line doc comment is hard-wrapped prose, which is exactly what folding is for. The one embedded JSON example (query.rs) is backtick-inline and survives folding intact. Not a defect. If a fenced block is ever added to a doc comment it would flatten — a comment noting that constraint would be cheap insurance, but there is nothing to fix today.

F9 — Description is spec-compliant

📁 packages/skill/src/agents.ts:37-48

Verified mechanically: folded description is 493 characters (spec max 1024 — comfortable headroom), name: nodespace matches the install directory skills/nodespace/ for all four targets, and only the six spec-defined fields appear (name, description, allowed-tools), so the harnesses that hard-error on unknown keys are safe.

On content: it now carries the ADR/spec/architecture/planning vocabulary criterion 5 asks for, and the text is taken verbatim from the issue's own proposal. Flagging for the human as the PR requests: the description is entirely forward-looking — "before writing or changing a spec, ADR, design doc, or plan." The previous phrasing's recall triggers ("what did we save", "recall what was decided") are mostly gone, and "check nodespace" is the only survivor. If users habitually phrase retrieval as "what did we decide about X", activation may regress on that axis even as it improves for authoring. This is exactly what criterion 5's hand-verification is for — worth watching in the deferred harness test rather than resolving now.


Summary

This is a clear net positive and the engineering quality is high. The generator design is genuinely good: the region registry is a real extension point, the one-way completeness contract is well-reasoned and correctly protects judgment prose, the marker-splicing rejects duplicate/missing markers rather than silently no-op-ing, and the examples/ placement is properly justified against a dependency cycle I confirmed independently. The four stated problems are all really fixed — I verified the drift closure (session, uninstall, model, the import dir flags, node query --id are all now present and generated), all-four-target frontmatter, and the 786→259-line reduction with a test that keeps it there.

The blocker is F1, and it is worth being precise about why: it is not a cosmetic leftover. Uninstall leaves behind a directory that looks like an installed skill but has no SKILL.md — a malformed folder in the harness's skills path, produced by the very command the user ran to clean up. It is a small fix (one shared helper) with a disproportionate user-visible consequence, and the existing tests structurally cannot catch it because they seed the flattened layout the bug assumes.

F2 deserves fixing but is not a blocker: I confirmed by mutation that the byte-compare drift test does catch the case the substring test misses, so criterion 11 holds in effect. The concern is that the guard is mis-attributed, and the substring test would become load-bearing if any CLI content ever moves outside a generated marker.

F3 is a one-word fix on a currently-dormant path. F4 is a real weakness in a test that is nonetheless better than what it replaced. F5–F9 are cleared or nit-level — several suspicious-looking things (path traversal, collapse_whitespace, nested cargo, positional doubling) I probed and found genuinely fine, for the reasons given.

Deferring the delivery-channel decision is the right call and honestly scoped.

Recommendation: REQUEST CHANGES — F1 only. F2/F3/F4 are strongly recommended in the same pass but would not, alone, hold up the merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

… guards

**F1 (critical) — uninstall left a malformed skill folder behind.**
install() was taught to preserve `references/`; uninstall() still flattened to
basename(), so it looked for a `cli.md` that never existed. The real file
survived, the "directory is now empty" check then saw it and kept the folder —
leaving `skills/nodespace/` containing `references/cli.md` and no SKILL.md, a
malformed skill in the harness's scan path produced by the cleanup command
itself.

The cause was the mapping existing twice and only one copy learning about
references/. It is now one `installedName()` function both sides call, so they
cannot disagree again. Uninstall also prunes emptied subdirectories before the
is-empty check, which otherwise strands the folder on the leftover
`references/`.

The existing tests missed this because the uninstall fixtures seeded install
dirs by hand with basename(), encoding the bug's own assumption. They now drive
the real install() so the two sides are tested against each other rather than
against a fixture that agrees with whichever one is wrong. Verified: reverting
the fix fails all three new tests.

**F3 — packages/skill/package.json `files` omitted `references`**, the fourth
place enumerating what the skill is made of. Added, plus a test asserting every
top-level directory the agents install from is published — the list had already
drifted once across four consumers.

**F2 — every_cli_flag_is_documented could not fail for a name collision.**
It searched the whole corpus for a bare `--flag`, so an undocumented `--limit`
on one command passed because a different command documents `--limit`. The
check is now scoped to the command's own section. Verified against the
reviewer's exact mutation (`--limit` on ExportArgs): previously passed, now
fails with "node export --limit".

**F4 — seeded-skill needles were too loose** ("search" matched 36 places, so a
skill whose commands were entirely absent could pass). Needles are now full CLI
invocations, most requiring two. The mapping stays hand-written and now says
why: the two sides share no identifier — a skill's tool_whitelist names
internal tools that appear nowhere in the skill, because the CLI is the
external surface. What is not hand-maintained is the list of skills.

Also corrected a wrong mechanism in the generator's module doc: `examples/`
does not keep nodespace-agent out of the shipped binary (it already arrives
transitively via nodespace-daemon) — it keeps a dev-time tool out of the
release artifact, since `cargo build --release` builds bins, not examples.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — ecaf73b1

All four findings addressed. Thanks for the live install/uninstall round-trip and the --limit mutation — both found real defects that green tests were hiding.

🔴 F1 — uninstall() stranding references/cli.md — fixed

Confirmed exactly as reported. install() was taught to preserve references/; uninstall() still flattened to basename(), so it looked for a cli.md that never existed, the real file survived, and the is-empty check then kept the folder — leaving skills/nodespace/ with a reference and no SKILL.md.

Rather than patch the second copy, I removed the duplication: both sides now call one installedName(), so they cannot disagree again. Uninstall also prunes emptied subdirectories before the is-empty check, which otherwise strands the folder on the leftover references/.

Your point about the fixtures was the more important half — seeding install dirs by hand with basename() encoded the bug's own assumption, which is why 29 tests passed over it. The uninstall tests now drive the real install(), so the two sides are tested against each other rather than against a fixture that agrees with whichever one is wrong.

Verified by reverting the fix: all three new tests fail, naming the symptom (references/cli.md survived uninstall).

🔴 F2 — flag check couldn't fail on a name collision — fixed

Reproduced your mutation exactly (--limit on ExportArgs): it passed before, and now fails with node export --limit. The check is scoped to the command's own section instead of searching the whole corpus.

Your note that checked_in_skill_md_is_up_to_date caught the same mutation is right, and it's why I treated this as mis-attribution rather than a coverage hole — but a guard that can't fail for the thing it names is worth fixing regardless of what backstops it.

🟡 F3 — package.json files missing references — fixed

Added. That was the fourth consumer of the same list, and it had already drifted once across four places, so I added a test asserting every top-level directory the agents install from is published.

🟡 F4 — weak seeded-skill needles — fixed

Needles are now full CLI invocations, most requiring two (nodespace schema create and nodespace schema list).

On your sharper point — that the match arms are the hand-maintained list relocated — that's fair, and I looked for a derivable source. There isn't one: a skill's tool_whitelist names internal tools (create_node, search_semantic) that appear nowhere in the shipped skill, because the CLI is the external surface. So the mapping has to be hand-written. What is not hand-maintained is the list of skills, which still comes from seed_skill_nodes() — a new skill hits the fallback arm and fails. The comment now says this explicitly rather than implying the whole thing is derived.

📝 Precision note — corrected

You were right that the module doc's stated mechanism was wrong: examples/ does not keep nodespace-agent out of the shipped binary, since it already arrives transitively via nodespace-daemon. The real reason is that cargo build --release builds bins, not examples, so a dev-time tool stays out of the release artifact. Doc corrected.

📝 On criterion 3

Agreed, and worth keeping visible: the CLI half is derived, but SchemaRule.prose still lives in skill_rules.rs, not the graph. That is sequenced behind the deferred channel decision and should not be read as closed.

Testing

  • Skill package: 33 tests (was 29 at review time, 24 before this PR)
  • cargo test -p nodespace-cli --test skill_md_generation: 8/8
  • bun run quality:fix: 0 errors, 0 warnings, clippy clean under -D warnings; no unrelated churn
  • Full pre-push gate passed

Every fix was verified by reverting it and confirming the new test fails.

@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2284 (Re-Review of ecaf73b1)

Review Type: Re-Review — scoped to git diff 6e74648a..HEAD only.

Verified by running and mutating, not by reading claims. Ran: bun run --cwd packages/skill test (33/33), cargo test -p nodespace-cli --test skill_md_generation (8/8), cargo clippy -p nodespace-cli --tests --examples -- -D warnings (clean), a shuffled-order test run, plus six mutation experiments and five live filesystem probes against a mocked $HOME. All mutations reverted; worktree and primary checkout verified clean.


Previous Review Summary

  • Number of previous recommendations: 4 (+1 precision note)
  • Addressed: 3 fully (F1, F2, F3) + precision note
  • Partially addressed: 1 (F4)
  • New issues found: 3
# Finding Verdict
🔴 F1 uninstall() stranded references/cli.md ✅ Fixed — mutation-confirmed
🔴 F2 Flag check couldn't fail on name collision ✅ Fixed — mutation-confirmed
🟡 F3 package.json files missing references ✅ Fixed — mutation-confirmed
🟡 F4 Weak seeded-skill needles 🟡 Partially fixed — see N1; still cannot fail
📝 Note Generator module doc mechanism ✅ Corrected

Verification of the Previous Findings

✅ F1 — genuinely fixed. I reverted installedName(shim) back to basename(shim) in uninstall() and re-ran: exactly 3 tests failed, naming the symptom (references/cli.md survived uninstall, install dir survived a full uninstall). The single-helper refactor is the right structural fix — DRY applied to a derived value that two call sites must agree on. Rewriting the fixtures to drive the real install() is the more valuable half, and it is correctly done.

✅ F2 — genuinely fixed. I reproduced the exact mutation (added an undocumented --limit to ExportArgs). Before: passed. Now:

these CLI flags are not documented under their own command's section: [ "node export --limit" ]

I also confirmed the prefix-collision concern is not a live risk: the markers are backtick-delimited (**`nodespace node get`**), so node get cannot match a hypothetical node get-related, and the alt form's trailing \n guards the group headings identically. Verified both by probe.

✅ F3 — genuinely fixed. Removing "references" from files fails the new test with a precise message. Confirmed.

✅ Precision note — correctly corrected. The new wording (cargo build --release builds bins, not examples) is the actual mechanism, and the parenthetical explicitly retracts the wrong claim.

🟡 F4 — see N1. The needles are stronger in isolation, but the test still cannot fail. Details below.


New Findings

🔴 N1 — every_seeded_skill_is_represented still cannot fail: every needle is satisfied by the generated block alone

📁 packages/cli/tests/skill_md_generation.rs:243-280

The needles were tightened from bare nouns to full CLI invocations, which reads like a real improvement. But skill_md() concatenates SKILL.md plus every file in references/ — and references/cli.md is machine-generated from clap, so it contains every command string by construction.

I measured where each needle actually resolves:

Skill Needle in SKILL.md in generated cli.md
Research & Search nodespace search / nodespace node query 9 / 3 8 / 8
Node Deletion nodespace node delete 0 2
Graph Editing nodespace node update / set-status 1 / 1 3 / 3
Organization member_of 2 1

Every single needle is satisfiable by cli.md alone. Node Deletion's needle appears zero times in the hand-written body — it is already passing purely on generated content today.

Concrete failure scenario — reproduced by mutation, not theorized. I replaced the entire hand-written SKILL.md body with a three-line stub:

# NodeSpace

See references/cli.md

Then ran the guard:

test every_seeded_skill_is_represented ... ok

All eight seeded skills' guidance deleted in full — the test passes. The generator regenerates cli.md from clap regardless, so the needles are permanently satisfied no matter what happens to the prose the test is supposed to protect.

I also ran the narrower mutation the review anticipated: deleting only the ### Organize a node into a collection section. Passes, because member_of survives in the built-in-relationships block that this same PR added to cli.md — so the reviewer's suspicion about that needle was correct, and it is the general case, not a one-off.

Why this matters more than it looks: the test's stated purpose is that "someone must decide how [a skill] surfaces to an external agent rather than have it silently omitted." That decision is about the judgment prose — the task-oriented guidance a generator cannot produce, which the module doc calls out as the thing the one-way contract exists to protect. Right now the guard measures the one artifact that is automatically correct and is blind to the one that can actually rot.

Fix — scope the needle to the hand-written body. skill_md() is the wrong corpus for this specific test; the CLI-derived tests should keep using it, but this one should read SKILL.md only:

fn skill_body() -> String { /* SKILL.md alone, no references/ */ }

Then re-check the needles: Node Deletion will immediately fail (0 occurrences), which is the test correctly reporting a real gap it is currently hiding. Anchoring to headings (### Delete a node exists in the body) would be even stronger and matches the reviewer's original suggestion.

Principle: a test must be able to fail for the reason it names. Concatenating a generated artifact into the corpus of a test that guards hand-written content silently defeats the assertion — the guard measures the half that cannot break.


🟡 N2 — the subdirectory-pruning loop deletes user-created empty directories, and can take the whole install dir with them

📁 packages/skill/src/installer.ts:110-118

for (const entry of readdirSync(config.installDir, { withFileTypes: true })) {
  if (entry.isDirectory()) {
    const subdir = join(config.installDir, entry.name);
    if (readdirSync(subdir).length === 0) rmSync(subdir, { recursive: true });
  }
}

The loop prunes any empty subdirectory, not just the ones install() created. It has no reference to config.shims, so it cannot tell references/ (which uninstall emptied and should remove) from a directory the user made themselves.

Concrete failure scenario — reproduced live against a mocked $HOME:

install() → user runs: mkdir ~/.claude/skills/nodespace/user-scripts
uninstall() →
  user-scripts survives:  false   ← silently deleted
  installDir survives:    false   ← whole folder removed too
  removed[] mentions it:  false   ← and uninstall never reports it

The user's own directory is deleted, and because pruning it empties the parent, the remaining.length === 0 branch then removes skills/nodespace/ entirely. removed[] reports only the 3 shim paths, so nothing surfaces the extra deletion — neither to the caller nor to the user.

This is the exact class the prior review warned about: uninstall now removes MORE than it should. It is narrower in blast radius than F1 (an empty directory holds no data), so I am rating it 🟡 rather than 🔴 — but it is a real behavioral regression introduced by the fix, and the existing tests do not cover it.

Fix — prune only what install would have created. The information is already in hand:

const ownedDirs = new Set(
  config.shims.map(installedName).filter(n => n.includes('/')).map(n => dirname(n))
);
for (const dir of ownedDirs) {
  const subdir = join(config.installDir, dir);
  if (existsSync(subdir) && readdirSync(subdir).length === 0) rmSync(subdir);
}

This also removes the need for the withFileTypes scan entirely.

Principle: a cleanup routine must be bounded by what it installed. Deleting by a structural predicate ("is empty") rather than by ownership makes the blast radius depend on unrelated state.


🟢 N3 — three smaller issues in the same delta

(a) unwrap_or("") is safe, but its justifying comment is wrong.
📁 packages/cli/tests/skill_md_generation.rs:177-181

The doc comment says a missing section is fine because "every_cli_command_is_documented reports" it. I mutated the generated heading ### \nodespace search`→### Semantic search command` and ran both:

every_cli_flag_is_documented   ... FAILED  (6 search flags reported)
every_cli_command_is_documented ... ok      ← did NOT report it

The command test passed because it does a bare skill.contains("nodespace search"), which prose elsewhere satisfies. So the behavior is correct (the flag test fails loudly, no silent pass — good), but the stated reason is not. Worth correcting so a future reader doesn't relax unwrap_or("") into something permissive on the strength of a backstop that isn't there.

(b) The .md-stripping clause in the new packaging test is dead code.
📁 packages/skill/src/tests/installer.test.ts:126

pkg.files.some(f => f === entry || f === entry.replace(/\.md$/, ''))

entry is a top-level path segment — the full set is exactly {SKILL.md, references, shims}. SKILL.md matches the first clause; the other two don't end in .md. The second clause never fires. It is also subtly wrong in intent: were it ever to fire, it would accept files: ["SKILL"] as publishing SKILL.md, which npm would not do. Recommend deleting the clause — the test is correct and does catch the F3 regression (verified), it just carries an inert branch that implies a case that doesn't exist.

(c) readdirSync on an unreadable subdirectory throws and aborts uninstall.
📁 packages/skill/src/installer.ts:113

Probed with a chmod 000 subdirectory:

D THREW: EACCES - EACCES: permission denied, scandir '.../skills/nodespace/locked'

The exception propagates out of uninstall(), so remaining agents in the loop are never processed and the caller gets no UninstallResult at all. Broken symlinks and symlinks-to-directories are both handled fine (verified separately — no throw, external target untouched). This is an unlikely state, and the ownership-scoped fix in N2 largely sidesteps it by not scanning arbitrary entries; a try/catch around the prune would close it completely.


What I Checked and Found Clean

  • Test isolation / ordering. afterEach does rmSync(TMP, {recursive, force}), which removes the mocked $HOME and FAKE_PKG_ROOT wholesale. Ran the suite with --sequence.shuffle=true: 33/33 pass. No cross-test pollution or ordering dependence.
  • removed[] accuracy for the normal path. Reports exactly the shim paths actually deleted (3 for claude-code). Accurate except for the N2 case.
  • Nested pruning depth. One level is not enough for a hypothetical references/deep/deeper, but the current shim set has no nested reference dirs, so this is latent only. The N2 ownership fix makes it a non-issue.
  • Prefix collisions in command_section. Backtick-delimited markers make node get vs node get-related and search vs search-v2 both safe. Verified by probe.
  • Section absorption. Removing a leaf heading causes the previous section to absorb the next command's flags — but this requires hand-editing generated content, which checked_in_skill_md_is_up_to_date byte-compares and rejects. Not reachable in practice.
  • installedName() symmetry. Install and uninstall now provably agree; the F1 mutation confirms the coupling is real and tested.

Summary

The two 🔴 blockers from the previous review are properly fixed, and fixed at the right level — F1 by removing the duplication rather than patching the second copy, F2 by scoping the assertion to answer its own question. Both are mutation-confirmed. F3 is fixed and now guarded. The precision note is correctly retracted and replaced with the real mechanism. Rewriting the uninstall fixtures to drive the real install() is the most valuable change in this delta and closes the structural reason the original bug survived 29 green tests.

Two things keep this from a clean approve. N1 is the more important: F4 was addressed at the needle level but not at the corpus level, and I demonstrated by mutation that the entire hand-written skill body can be deleted with the guard still green. That is the same "a test that cannot fail" defect F2 was fixed for, in the one test whose subject — judgment prose — is the thing this PR's whole one-way-contract design exists to protect. N2 is a genuine behavioral regression introduced by the F1 fix: uninstall now deletes empty directories it never created and can remove the install folder as a result, without reporting it. Smaller blast radius than the bug it replaced, but it is the "removes more than it should" case the previous review explicitly flagged as worse than the original.

Both fixes are small and local — N1 is a corpus swap in one test, N2 is deriving the prune set from config.shims. The rest of the delta is solid work.

Recommendation: REQUEST CHANGES — N1 and N2. N3(a)/(b)/(c) are cleanups worth folding into the same pass but would not alone hold up the merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

… pruning

**N1 (critical) — `every_seeded_skill_is_represented` could not fail.** It read
SKILL.md concatenated with references/cli.md, and the generated CLI surface
contains every command string by construction — so every needle was satisfiable
by generated content alone. Confirmed: replacing the whole body with a 3-line
stub left the test green. The one test whose subject is judgment prose was
measuring the generator instead, which is the exact defect the one-way contract
in this file exists to prevent.

The test now reads a prose-only corpus with every generated region stripped.
With the stub mutation it fails as it should.

This exposed a real content gap the weak assertion was hiding: `nodespace node
delete` appeared **zero times** in hand-written prose. An agent reading the
body never learned deletion exists. Added a "Delete a node" task covering the
two things a generator cannot state — that deletion is permanent and takes
children with it, and that moving beats deleting when the user just wants
something out of the way.

**N2 (important) — uninstall deleted directories it never created.** Pruning
"any empty subdirectory" cannot tell `references/` from a user's own folder:
removing theirs empties the parent, which then takes the whole install
directory, with none of it reported in `removed`. Pruning is now derived from
`config.shims`, so uninstall never reaches outside what it installed. Removing
more than we installed is a worse failure than leaving something behind.

**N3** — three smaller items:
- `command_section()` returning `None` now fails explicitly. The comment
  claiming `every_cli_command_is_documented` covered it was wrong: that test
  matches the bare string "nodespace <path>" anywhere, which a worked example
  satisfies with no generated section present.
- Dropped the dead `.md`-stripping clause in the packaging test.
- An unreadable subdirectory no longer aborts uninstall for the remaining
  agents; it is left in place and the install dir conservatively kept.

Every fix verified by reverting it and confirming the new test fails.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed — ed4caa79

Both new findings fixed, plus all three N3 items. The stub-body experiment was the right instrument — N1 was a genuine hole and I'd have defended the test as sound without it.

🔴 N1 — the prose guard couldn't fail — fixed

You're right, and the framing is the part worth keeping: the one test whose subject is judgment prose was reading generated content, which is precisely the failure mode this file's one-way contract exists to prevent. I built the corpus for the CLI tests and then reused it for a test that needed the opposite thing.

every_seeded_skill_is_represented now reads a prose-only corpus with every generated region stripped. Verified with your exact mutation: stub body → test fails.

It also exposed a real content gap the weak assertion was hiding. nodespace node delete appeared zero times in hand-written prose — an agent reading the body never learned deletion exists at all. Added a "Delete a node" task covering the two things no generator can state: deletion is permanent and takes children with it, and moving beats deleting when the user just wants something out of the way. So the guard was concealing exactly the class of omission it was written to catch.

Note on the partial result you'd expect: with the stub, two skills report rather than eight. That's correct — the hand-written worked examples in references/cli.md survive the strip and legitimately represent those skills. references/ is shipped, agent-readable prose a human wrote; a skill documented only there is genuinely covered. Your point about member_of being incidental was right and is now resolved by the same change: its only occurrence in references/cli.md is inside the generated built-in-relationships block, which the strip removes.

🟡 N2 — uninstall deleting user directories — fixed

Pruning is now derived from config.shims rather than "any empty directory". Verified: reverting it fails the new test with uninstall deleted a user-created directory.

Your framing that this is worse than the original bug is the right call, and it's what makes the narrow version obviously correct — uninstall should never reach outside what it installed. Added a second test confirming a user file inside references/ also survives.

🟢 N3 — all three — fixed

(a) You're right that my comment was wrong, and I checked your claim rather than just editing the prose: every_cli_command_is_documented matches the bare string nodespace <path> anywhere, which a worked example satisfies with no generated section present. Rather than fix the comment, a missing section now fails explicitly in every_cli_flag_is_documented itself.

(b) Dead clause dropped; the test is now a plain toContain.

(c) Wrapped in try/catch. An unreadable subdirectory leaves the directory in place and the is-empty check then conservatively keeps the install dir, rather than aborting cleanup for every remaining agent.

Testing

  • Skill package: 35 tests (31 → 33 → 35 across the three rounds; 24 before this PR)
  • cargo test -p nodespace-cli --test skill_md_generation: 8/8
  • SKILL.md body: 270 lines / ~3,876 tokens — still inside spec after adding the deletion section
  • bun run quality:fix: 0 errors, 0 warnings, clippy clean under -D warnings; no unrelated churn
  • Full pre-push gate passed

Every fix verified by reverting it and confirming the new test fails.

@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2284 (Re-Review round 3 of ed4caa79)

Review Type: Re-Review — scoped to git diff ecaf73b1..HEAD only.

Verified by running and mutating, not by reading claims. Ran: cargo test -p nodespace-cli --test skill_md_generation (8/8), bun run --cwd packages/skill test (35/35), cargo clippy -p nodespace-cli --tests --examples -- -D warnings (clean), cargo run -p nodespace-cli --example gen_skill_md -- --check (up to date), a standalone 10-case fuzz of the new string-slicing helper, a per-needle occurrence census across both tiers, and six mutation experiments. All mutations reverted; worktree clean and primary checkout untouched (verified — no file under packages/skill or packages/cli/tests in the primary checkout modified in the last two hours).


Previous Review Summary

  • Number of previous recommendations: 2 (N1, N2) + 3 sub-items (N3a/b/c)
  • Addressed: 5 — N1, N2, N3(a), N3(b), N3(c)
  • Partially addressed: 0
  • Not addressed: 0
  • New issues found: 1 (🟢, latent)
# Finding Verdict
🔴 N1 Prose guard read generated text; could not fail ✅ Fixed — mutation-confirmed, and it caught a real content gap
🟡 N2 Uninstall pruned user-created empty directories ✅ Fixed — mutation-confirmed
🟢 N3(a) unwrap_or("") justification comment was wrong ✅ Fixed — and fixed better than asked
🟢 N3(b) Dead .md-stripping clause ✅ Fixed
🟢 N3(c) readdirSync on unreadable subdir aborted uninstall ✅ Fixed

Verification of the Previous Findings

✅ N1 — genuinely fixed, and the fix is better than "narrowed".

I ran the exact round-2 mutation. Before: green. Now:

these seeded skills have no counterpart in SKILL.md: [ "Bulk Import", "Organization" ]
test result: FAILED

The 2-of-8 result was the thing I most wanted to test, because on its face it reads like the guard is still 75% blind. It is not, and the census settles it. I counted where every one of the 12 needles resolves, splitting references/cli.md into hand-written prose vs. generated regions:

Needle SKILL.md cli.md prose cli.md generated-only
nodespace search 9 7 1
nodespace node query 4 7 1
nodespace node create 7 3 1
nodespace schema create 2 3 1
nodespace schema list 2 1 2
nodespace node update 1 2 1
nodespace node set-status 1 2 1
nodespace relationship create 3 2 1
nodespace relationship get 1 2 1
nodespace node delete 1 (was 0) 1 1
nodespace import 2 0 3
member_of 2 0 1

Every needle now resolves inside SKILL.md itself — including the two that previously did not. So the stub mutation reporting only 2 skills is not the guard being blind to the other 6; it is those 6 being additionally covered by hand-written worked examples in references/cli.md that the stub mutation left standing. The author's justification is sound, and I verified the content it rests on: references/cli.md:78-84 is a real hand-authored "Delete a node" section carrying judgment a generator cannot emit ("confirm the title matches what the user described", "one node per call", "don't search again afterward to verify"). That is legitimately agent-readable prose a human wrote, and skill_md()'s own documented rationale — content that moves between the body tier and the references tier is still shipped and still reachable — applies to it directly.

The decisive evidence is the narrow mutation, which is the realistic rot scenario rather than the stub:

  • Delete ### Organize a node into a collection → FAILS ("Organization"). This is the precise mutation that passed in round 2 because member_of survived in the generated built-in-relationships block. The strip removed exactly the incidental match I flagged.
  • Delete ### Bulk import from markdown → FAILS ("Bulk Import").

The weak assertion was concealing a real gap, as claimed. nodespace node delete was 0 in hand-written prose. I verified the new SKILL.md section's safety claims against the code rather than the prose, since a confidently-worded wrong claim here is worse than silence:

  • "takes the node's children with it" — accurate. CLI node delete → DeleteNode RPC (packages/daemon/src/services/node_service.rs:312) → node_ops::delete_node → NodeService::delete_node (packages/core/src/services/node_service/crud.rs:1253), which calls collect_subtree_ids and delete_subtree_atomic. Proven by an existing test at packages/core/src/services/node_service/mod.rs:3854: root + child + grandchild, deleted_count == 3, all three gone.
  • "permanent" — accurate. No soft-delete or trash on this path; the store issues DELETE FROM node with FK CASCADE for relationships and embeddings.
  • --content-contains in the worked example is a real flag (packages/cli/src/commands/node.rs:122).

✅ N2 — genuinely fixed. I mutated ownedDirs back to prune-any-empty-dir and re-ran: exactly one test fails, naming the symptom — uninstall deleted a user-created directory. dirname(installedName(shim)) produces . for all three flattened shim forms (filtered out) and references for the one nested case, so the prune set is exactly {references} for every agent. Both new tests are the right pair: one for a sibling directory, one for a user file inside a directory the installer does own.

✅ N3(a) — fixed, and better than I asked for. I asked for the comment to be corrected; the author instead made the case fail explicitly. I verified both halves of the claim by renaming two generated headings at once:

"node delete (no generated section at all)",
"search (no generated section at all)",
test result: FAILED

Both are reported together — the return exits only the per-command check, pushes to the shared missing vec, and hides nothing. And every_cli_command_is_documented passed with both headings gone, confirming the author's corrected claim that it does not cover this case. Side benefit: search now reports as one missing section rather than as six individually-missing flags, which is the more useful diagnostic.

✅ N3(b)/(c) — fixed. The packaging test is now a plain toContain and still guards the F3 regression. The try/catch is correctly narrow: it wraps only the owned-subdirectory prune, while the outer readdirSync(config.installDir) at installer.ts:141 stays outside it — so a genuinely unreadable install directory still throws, which is a state the caller should know about. It does not swallow anything that should surface.


New Findings

🟢 R1 — ownedDirs prunes one level, so a future nested reference would strand its parent

📁 packages/skill/src/installer.ts:120-124

ownedDirs is a flat set of dirname() results, and each is checked once. For today's shim set this is exactly right — references is the only entry and it has no parent to strand. But if a shim were ever added as references/api/cli.md, ownedDirs becomes {references/api}: the prune removes references/api, leaving references/ empty, the remaining.length === 0 check then sees a non-empty install dir, and the whole folder is stranded — which is the original F1 bug class returning by a different route.

I confirmed the dirname behavior by probe rather than assuming it. This is latent, not live: no such shim exists, and the failure mode is the safe direction (stranding rather than deleting). Walking parents up to the install dir would close it, but that is speculative generality for a shim set that has been flat plus one references/ for the life of this package — YAGNI applies. Recording it so the next person adding a nested reference knows the prune is one level deep; the existing comment does not say so.

🟢 R2 — Nit: the swallowed prune exception is entirely silent

📁 packages/skill/src/installer.ts:130-133

The catch {} is correct in its recovery (leave the directory, let the conservative is-empty check keep the install dir) but emits nothing. A user whose references/ is left behind by a permissions problem gets no signal at all, and removed[] looks like a clean uninstall. There is already a process.stderr.write precedent for a user-facing warning in this same file (installer.ts:35), so one line there would cost nothing. Genuinely optional — the failure is self-correcting and re-running uninstall is idempotent.


What I Checked and Found Clean

  • skill_prose_only() robustness. I extracted the function into a standalone binary and ran 10 adversarial inputs: unterminated BEGIN, END-before-BEGIN, nested BEGIN inside a region, --> appearing inside a region body, an END marker missing its own -->, three regions in one string, multi-byte UTF-8 immediately before a marker, empty input, and markers mentioned in running prose. No panics, no marker fragments left behind, no generated text retained in any case. Byte-index slicing is safe because every marker literal is pure ASCII, so find() offsets always land on char boundaries. Every degenerate case fails closed — it drops content rather than keeping generated text — which is the correct direction for a guard: over-stripping produces a false failure someone must investigate, never a false pass.
  • The doc comment's claim about the generator rejecting malformed regions. Verified, not assumed: splice_generated_block (gen_skill_md.rs:365-382) errors on a missing begin or end marker and on duplicate markers, and checked_in_skill_md_is_up_to_date runs that path — so a malformed region is caught by a different test before the conservative tail-drop could ever matter.
  • Round-trip. --check reports "Skill content is up to date". The three generated regions (builtin-relationships, schema-rules, cli-surface, all in references/cli.md) still splice byte-identically.
  • Size, independently. 270/500 lines, 15,505 chars → ~3,876/5,000 approx tokens. Comfortable headroom, and it still holds with the 12-line install-time frontmatter prepended (283 lines, ~4,021 tokens) — which the test does not measure, but does not need to at this margin.
  • removed[] accuracy. Still exact: it lists the shim files actually rmSync'd, and the prune now only touches a directory the installer created.
  • Suite health. 35/35 skill tests, 8/8 Rust, clippy clean under -D warnings.

Summary

All five items from round 2 are fixed, each verified by reverting the fix and confirming the corresponding test fails. Two are fixed better than the review asked: N3(a) was raised as a wrong comment and was resolved by making the case fail explicitly instead, and N1's fix surfaced a genuine content gap — an agent reading the body previously never learned deletion exists — whose new prose I checked against the delete path in core rather than taking on faith.

On the question the review brief put hardest: N1 is fixed, not merely narrowed. The 2-of-8 stub result looks like partial blindness but is not — every needle now resolves inside SKILL.md itself, and the two mutations that matter (deleting a real section) both fail, including the exact member_of case that slipped through round 2. The guard now measures hand-written prose across both shipped tiers, which is the corpus it should measure; references/cli.md's worked examples are human-authored guidance, not generator output, and the strip proves the distinction rather than assuming it.

What remains is one latent one-level-prune limitation with no live trigger and a safe failure direction, and one optional stderr line. Neither is worth another round. This is done.

Recommendation: APPROVE

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (round 3): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

The prune covers the immediate parent only, which is correct for every shim
today — `references/` is the one nested case. A deeper shim such as
`references/api/cli.md` would prune `references/api` and strand `references/`,
reviving the stranded-directory bug the prune exists to prevent.

Documenting the limitation rather than building leaf-upward pruning now: there
is no such shim, and the failure direction is safe (leaves a directory behind
rather than deleting one it shouldn't). The gap was that nothing said the prune
was one level, which is what would let the next person miss it.

Not changing the swallowed prune exception to warn on stderr. The line-35
precedent warns about something the user must act on (CLI not installed); a
prune failure is already handled conservatively and there is nothing for them
to do, so a warning there is noise.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018MjZqs9VFFHnXNdyXcFEw3
@malibio

malibio commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Approved-round follow-up — d1df45d7

Both 🟢 nits triaged.

R1 — one-level prune limitation: documented, not fixed. Agreed it's latent with no live trigger, and building leaf-upward pruning now would be speculative generality. But your framing was that the comment doesn't say the prune is one level — that's the part that would let the next person miss it, so the comment now names the failure explicitly (a references/api/cli.md shim would prune references/api and strand references/, reviving the exact bug class the prune exists to prevent).

R2 — skipped, with reasoning. The line-35 stderr.write precedent warns about something the user must act on (CLI not on $PATH). A prune failure is already handled conservatively and there's nothing for them to do about it, so a warning there is noise on an unactionable path. Happy to add it if you read that differently.

No behavior change in this commit; 35/35 skill tests, quality clean, full gate passed.


Thanks for three substantive rounds. The two that mattered most were both cases where my tests were green for the wrong reason — F1's fixtures encoding the bug's own assumption, and N1's guard reading the generated text it was meant to be independent of. Neither was reachable by reading the diff; both took the mutation experiments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant