Skip to content

Emit flat node properties from the CLI (closes #2381) - #2423

Merged
malibio merged 6 commits into
mainfrom
issue-2381-cli-flat-properties
Sep 7, 2026
Merged

malibio merged 6 commits into
mainfrom
issue-2381-cli-flat-properties

Conversation

@malibio

@malibio malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Problem

Storage nests a node's properties under its schema id. The CLI passed that shape straight through --json:

"properties": { "task": { "_schema_version": 1, "status": "open" } }

A consumer reading .properties.status got None — and could report "status unknown" about real data. The reporting agent caught it only because status is required with a default, so a task cannot legitimately lack one.

Why this is a bug, not a docs gap

The flat contract already exists and is already intended:

  • flatten_properties_for_api (nodespace-types/src/convert.rs) defines it, and the frontend gets it via node_to_typed_value.
  • output.rs's own comments promise jq '.properties.foo' works with no second parse — bare.
  • Writes (--property status=…) and filters ({"property":"status"}) already take bare names.

Only reads leaked, so the CLI was half-flat: bare on input, nested on output. Documenting the nesting would have enshrined the leak.

Fix

Flatten in output.rs, which every node-emitting command funnels through — node get, query, search, schema, and the batch path — covering both --json and human-readable output.

_-prefixed internals (_schema_version, and sibling namespaces like _seed) and dormant namespaces from a previous type change are dropped, matching the frontend contract.

The logic is mirrored rather than reused: the CLI only ever holds the gRPC NodeData, whose properties is a JSON-encoded string, while the canonical helper takes a Node. Both sites cross-reference each other.

Storage is unchanged. A seeded node's _seed and skill namespaces coexist at rest, which a flat bag could not represent.

Docs

  • SKILL.md — the only properties example was {}, which reads as a flat bag and taught the wrong shape. Now shows populated flat properties.
  • references/cli.md — documented only that --json exists; now specifies the node shape.
  • cli.md's "namespace prefixes" note conflated schema-authoring field-name prefixes with runtime nesting, reinforcing the wrong inference. Clarified.

A downstream consumer

scripts/eval/graph.ts reads nodespace --json and unwraps the nested shape. That is now a no-op against a current build, but it is kept and documented rather than deleted: NS_BIN is overridable and defaults to a prebuilt target/release/nodespace that can predate this change — the stale-binary case preflight.ts already warns about. Failing to unwrap an older binary's output would silently zero populatedCount and red-line correct writes. This is input tolerance at a test harness's trust boundary, not a compatibility shim in the product.

Testing

  • Six unit tests over the flattening rules: namespaced → bare, _-prefixed internals hidden, sibling _seed namespaces, dormant namespaces, user-defined types, already-flat passthrough.
  • An end-to-end integration test against the real service stack asserting both halves at once — storage stays nested, CLI output is flat — for a core type (task) and a user-defined type (venue).
  • bun run test:all green, matching baseline exactly (232 files / 4863 frontend tests, 0 new failures). quality:fix clean; clippy passes with -D warnings.

Closes #2381

🤖 Generated with Claude Code

https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2423

Type: Initial Review (no prior reviews)
Scope: b06ca679 + 1adef8a3 (note: 1adef8a3 is local-only, not yet pushed to origin)
Verdict: 🟡 REQUEST CHANGES — the core fix is correct and well-argued, but the issue's own completeness criterion is not met.


Summary

This is a genuinely good change. The diagnosis is right, the framing is right, and the resistance to the easy fix (documenting the leak) is exactly the right instinct — the issue is a real correctness bug, not a docs gap, and the PR treats it as one. The flattening logic is a faithful mirror of flatten_properties_for_api, the unit tests are well-chosen and each carries a why, the integration test asserting both halves of the contract at once (storage nested / output flat) is the right shape of test, and the docs changes fix the specific misleading text the issue called out. Clippy passes clean with -D warnings; all 10 unit tests pass.

Two findings block merge. Both are completeness, which the issue explicitly calls out as the one thing that must not be left half-done:

  1. nodespace relationship get --json still emits the nested storage shape. It bypasses output.rs entirely.
  2. A user-created object-valued property never reaches the type namespace on write, so it is silently dropped from output — a hazard the codebase already documents by name.

Neither is a flaw in the flattening rules as written. Both are paths the change didn't reach.


Findings

🔴 Critical

1. relationship get --json still leaks properties.<schema-id>.<field>

📁 packages/cli/src/commands/relationship.rs:114-127

The PR's central claim is that output.rs is the funnel every node-emitting command passes through. That holds for node get, node create, node update, node set-status, node children, node batch-get, query, search, schema list, and schema get — I verified each. It does not hold for relationship get, which takes an entirely separate route:

let related: serde_json::Value = serde_json::from_str(&response.related_nodes_json)
    .context("daemon returned malformed related_nodes_json")?;
// ... printed verbatim, both --json and human mode

That payload is built in packages/core/src/ops/rel_ops.rs:383-386:

let related_nodes: Vec<Value> = nodes
    .into_iter()
    .map(|n| serde_json::to_value(n).unwrap_or(json!(null)))
    .collect();

serde_json::to_value(Node) serializes Node.properties (packages/nodespace-types/src/node.rs:26) exactly as stored — no flatten_properties_for_api anywhere on this path. So nodespace relationship get <id> --type has_task --json | jq '.related_nodes[0].properties.status' returns null against real data, which is precisely the failure mode the issue was filed for, in a different command.

This isn't an obscure corner. relationship get is a first-class documented read path — packages/skill/references/cli.md:237-259 gives it ~25 lines including reverse-traversal guidance, and SKILL.md:146 recommends it explicitly as the follow-up to query "if you need connected nodes". An agent that follows the skill's own advice lands on the one command still leaking.

Against the issue's checklist this fails three boxes outright:

  • Nesting is not observable anywhere on the CLI surface — no command's output, input, filter syntax, help text, doc or example exposes properties.<schema-id>
  • All read paths apply the existing flatten_properties_for_api contract — node get, query, search, schema-adjacent output, and any other command emitting a node
  • Any skill docs or example scripts that assume the nested shape are updated in the same change (breaking output change — fine per CLAUDE.md's zero-users rule, but must not be left half-done)

The principle: an invariant enforced at some boundaries is not an invariant — it is a trap with better odds. The value of "a CLI consumer can never observe the nesting" is entirely in its universality; one exception restores the full cost of the original bug (a consumer cannot trust .properties.foo and must defensively handle both shapes) while adding the new cost that the exception is now surprising.

Two ways to fix, and I'd argue for the second:

(a) Flatten in the CLI, symmetric with this PR — but related_nodes is a Value array of Node-shaped objects, not NodeData, so flatten_properties would need a third caller shape. That's a third copy of the same rule.

(b) Flatten at the source, in rel_ops.rs:383 — call the canonical flatten_properties_for_api (or node_to_typed_value) where the Node still exists, before it is serialized. This is strictly better: rel_ops holds a real Node, which is exactly what the canonical helper takes, so there is no duplication justification here — the reason given for mirroring in the CLI (only a gRPC NodeData is available) simply does not apply. It also fixes every consumer of GetRelatedNodes, not just the CLI. Worth checking whether the frontend or agent tools consume this RPC and already compensate.

If (b) turns out to have a consumer that depends on the nested shape, say so in the PR body and take (a) — but the current state, where the path isn't addressed at all, is the one option that should not ship.


2. An object-valued property is silently dropped, because it never reaches the type namespace on write

📁 packages/cli/src/output.rs:108-131, interacting with 📁 packages/core/src/services/node_service/crud.rs:1699-1707

Commit 1adef8a3 pins that an object inside the type namespace survives — correct, and good that it's now tested. But it establishes the invariant for a state the write path does not reliably produce.

normalize_flat_properties_to_namespace classifies a top-level key as a namespace when it is object-valued and not in schema_field_names:

if value.is_object() && !schema_field_names.contains(key.as_str()) {
    // This is likely a namespace (dormant or active) - preserve it
    namespaced.insert(key.clone(), value.clone());
} else {
    flat_props.insert(key.clone(), value.clone());
}

So the whole thing turns on schema_fields being populated. In create_node (crud.rs:98-139), it is populated for exactly one type:

if node.node_type == "task" {
    // ... get_schema_for_type(...) → Some(&fields)
} else if node.node_type != "schema" {
    node.properties = Self::normalize_flat_properties_to_namespace(
        &node.node_type, &node.properties, None,   // ← no schema fields
    );
}

None → empty schema_field_names → every object-valued property on a non-task type is misclassified as a namespace and hoisted to top level, sitting beside properties[node_type] rather than inside it. The update path does the same (crud.rs:649-653, also None).

Concretely, given a Venue schema with an object field address (object is a supported field type — packages/nodespace-types/src/schema.rs:159-160, and packages/agent/src/local_agent/tools.rs:1208 advertises it to agents as "Field type: text, number, date, enum, array, object, boolean"):

stored:   {"venue": {"capacity": 250}, "address": {"city": "Berlin"}}
emitted:  {"capacity": 250}                              ← address gone

The primary branch fires (a "venue" namespace exists), reads only inside it, and the hoisted address is never looked at. Not mangled, not null — absent, with no signal. That is the same failure class as the bug this PR fixes: a consumer concludes "no address" about real data.

This is not speculative. The codebase already names this exact hazard, in a comment written to explain a workaround for it — packages/agent/src/skill_pipeline.rs:482-487, on why tool seed templates pre-namespace themselves: without it, parameter_schema is misclassified as a dormant namespace and "flatten_properties_for_api later silently drops it." The same reasoning appears at packages/core/src/services/node_service/mod.rs:1429-1434 for _seed.

Both are seed templates that hand-pre-namespace to dodge the misclassification. A user creating a node through nodespace node create --property address='{"city":"Berlin"}' has no such escape hatch — and references/cli.md:84 advertises that --property values "are parsed as JSON when possible (numbers, booleans, arrays, objects)", so this is a documented, supported input.

Scope, to be precise about what is and isn't broken today (I checked every core type): no built-in type currently loses data. schema nodes are excluded from namespacing (crud.rs:133) and hit the fallback branch, but every value there is a scalar or an array — and arrays are not is_object(), so fields survives. ai-chat, query, and skill use arrays too. tool is the only built-in with a bare object, and it is pre-namespaced. The exposure is latent, not active: it fires on a user-defined schema declaring an object field, or on any tool node that ever lands flat.

Why this is the PR's problem and not purely a pre-existing storage bug: the misclassification already existed, but before this change it was visible — the raw nested output showed address sitting at top level, and a consumer could see it. This change makes the output authoritative and lossy at the same time: it now promises "flat, complete, keyed by the schema's field names" (references/cli.md:31) while silently omitting a field. Tightening a contract without tightening what feeds it converts a visible-but-wrong shape into an invisible omission, which is the harder bug.

Options, roughly in order of preference:

  1. Fix the classification at the source — thread schema fields into the non-task branch of crud.rs:98-139 so object-valued schema fields land inside the namespace. This makes 1adef8a3's invariant true in practice and is the only option that fixes storage, the frontend (flatten_properties_for_api drops these identically at convert.rs:88-93), and the CLI at once. Likely larger than this PR wants to be — reasonable to split into a follow-up issue, provided (2) or (3) ships here.
  2. Merge, don't drop, in the fallback — keep the type namespace's fields, and additionally surface top-level non-object keys. Doesn't solve the hoisted-object case but stops the fallback branch from being a second dropper.
  3. At minimum: document the limitation honestly. references/cli.md:31-36 currently states an unconditional guarantee. If object-valued fields can be omitted, that sentence is wrong as written, and this PR's own docs then teach a second incorrect shape — the exact failure mode the issue is about.

Whatever route is taken, 1adef8a3's comment ("an object there is a real schema-defined field value... and must survive intact") should note that the write path does not currently guarantee the object gets there — otherwise the test reads as proof of a property the system doesn't have.


🟡 Important

3. Nothing keeps the two flattening implementations in step

📁 packages/cli/src/output.rs:108-131 ↔ 📁 packages/nodespace-types/src/convert.rs:69-93

I compared the two line by line: they agree semantically today. Same namespace-first lookup, same _-prefix filter, same !v.is_object() fallback filter, same non-object passthrough. The mirroring is faithful.

The duplication justification is also sound as far as it goes — flatten_properties_for_api is private and takes &mut Node; the CLI holds a gRPC NodeData whose properties is a JSON string. Reaching the canonical helper would mean either reconstructing a Node (needs created_at/modified_at as DateTime<Utc>, plus fields NodeData doesn't carry) or widening the helper's signature. Both are real costs, and DRY is about a single source of knowledge, not identical-looking text — two callers with genuinely different input types is a defensible place to duplicate.

What's missing is the enforcement. convert.rs:29-32 states in the strongest terms:

This is the single canonical implementation ... and the SOLE authority for property flattening ... Do NOT re-implement either in another layer

This PR re-implements it. Cross-referencing doc comments is the weakest possible coupling: nothing fails if someone edits convert.rs and not output.rs, and the divergence surfaces as a wrong CLI answer, not a red test. Note also that convert.rs:408 already has property tests guarding the canonical version against silent field-drop — the CLI copy has example-based tests only, so the two aren't even guarded to the same standard.

The cheapest real fix: extract the rule into a pub fn flatten_namespaced_properties(props: &serde_json::Value, node_type: &str) -> serde_json::Value in nodespace-types::convert, have flatten_properties_for_api call it on node.properties, and have the CLI call it on its parsed Value. Both callers keep their own input types; the rule lives once. That removes the duplication and the "keep the two in step" instruction along with it, and it gives finding #1 a natural home too. Failing that, at minimum amend convert.rs's "SOLE authority" comment to acknowledge the sanctioned second copy — right now that comment is stale, and a future reader who trusts it will miss the CLI.


4. references/cli.md's list of node-emitting commands is incomplete

📁 packages/skill/references/cli.md:14-16

Commands that emit a node (node get, node create, node update, query, search, schema list, schema get)

Also emitting nodes through the same path: node children, node batch-get, and node set-status (packages/cli/src/commands/node.rs:272, :295, :353). And per finding #1, relationship get emits nodes on a different path.

An enumeration invites the reader to treat omissions as meaningful — an agent parsing node children --json now has grounds to think it might differ. Since the shape is uniform for everything routed through output.rs, prefer stating the rule over listing instances: "Every command that emits a node returns this shape; list-returning commands wrap them as {"count": N, "nodes": [...]}." Fewer words, no maintenance burden, and it stays true when a command is added.


🟢 Suggestions

5. has_properties's non-object/non-string arm is unreachable and slightly misleading

📁 packages/cli/src/output.rs:71-76

let has_properties = match &properties {
    serde_json::Value::Object(map) => !map.is_empty(),
    serde_json::Value::String(s) => !s.is_empty() && s != "{}",
    _ => true,
};

I traced both arms and the logic is correct, including the two cases flagged for scrutiny:

  • Flattens to {} → Object(empty) → false → line omitted. Right, and matches the old != "{}" behavior.
  • Malformed JSON → properties_to_json returns Value::String(raw) → the string arm reproduces the old test exactly. Right, and node_to_json_falls_back_to_raw_string_for_malformed_properties still covers it.

The nit is the _ => true arm. properties_to_json returns only Object (both flatten_properties branches build one), String (parse failure), or a passthrough clone when the parsed value isn't an object — a top-level […], 42, or null. That last case is what _ catches, and true is defensible for an array or number but prints a bare properties: null for JSON null. Since the daemon can't produce any of these, this is cosmetic — but the arm currently reads as "some other case exists" without saying which. A one-line comment naming it (// non-object JSON at top level — daemon can't produce this; show it rather than hide it) would cost nothing and stop the next reader from re-deriving what I just did.

6. pub(crate) → pub on node_to_json is fine

📁 packages/cli/src/output.rs:148

Flagged for review; I don't think it needs changing. print_node, print_delete, and print_node_list in the same module are already pub, and lib.rs:3-5 states the crate surface exists specifically "so integration tests can drive the command handlers". This is consistent with an established convention, not a new precedent, and node_to_json is a pure &NodeData → Value function with no invariants to protect. Testing the actual public contract directly is better than the alternatives (capturing stdout, or #[cfg(test)]-gating visibility, which would make the integration test exercise a different build than users get).

7. Keeping flattenTypeKeyedProperties is justified — the reasoning holds

📁 scripts/eval/graph.ts:155-165

I checked this against CLAUDE.md's no-backward-compatibility rule and I think the PR's argument survives.

The rule targets product code carrying old data shapes forward — "delete old patterns immediately when replaced", no dual-mode support, no transition periods. The load-bearing distinction is that scripts/eval/ doesn't build the binary it reads; it shells out to whatever NS_BIN points at, defaulting to a prebuilt target/release/nodespace (scripts/eval/env.ts:47). That binary's build time is genuinely unknown to the harness, which is why preflight.ts:149 already warns when NS_BIN "is an older build without…" — the stale-binary case is a pre-existing, acknowledged condition of this harness, not something invented to justify keeping the function.

That makes this input validation at a trust boundary, which is the standard exception. A parser tolerating a shape its own producer no longer emits is normal defensive practice when the producer is not version-locked to the consumer. The asymmetry in the comment is the clincher and is correct: unwrapping a shape that no longer arrives is a no-op, while failing to unwrap one that does silently zeroes populatedCount and red-lines correct writes — which the comment notes actually happened (scenarios 9, 10b, 13, 3/3 reps).

The NOTE block documents all of this well. If you want to close the loop entirely, the stronger move is to make the harness build-lock rather than shape-tolerant — have preflight.ts assert NS_BIN is newer than some marker, and then delete the function. Not required for this PR; worth a follow-up issue if the stale-binary condition keeps generating exceptions like this one.

8. Test naming: one test's name overstates what it asserts

📁 packages/cli/src/output.rs:222-232

node_to_json_hides_underscore_prefixed_internals uses the same fixture as the test immediately above it and asserts one additional line (_schema_version absent). Since the first test already covers this fixture, consider either folding the assertion into it or giving this one a distinct fixture — e.g. an _-prefixed key in the fallback branch, which no current test covers and which is where the !k.starts_with('_') filter is easier to drop by accident.


Acceptance Criteria

# Criterion Status
1 Nesting not observable anywhere on the CLI surface ❌ relationship get --json (finding #1)
2 All read paths apply the flat contract, incl. "any other command emitting a node" ❌ relationship get (finding #1)
3 Both human-readable and --json covered ✅ output.rs:69-78 and :148
4 jq '.properties.foo' works with no second parse ✅
5 _-prefixed internals absent ✅ both branches, tested
6 Storage stays namespaced, no change at rest ✅ asserted in the integration test
7 Input and output agree on bare field names ✅ for scalar fields; ⚠️ an object written via --property is not readable back (finding #2)
8 SKILL.md shows populated flat properties ✅ SKILL.md:298-316
9 references/cli.md documents the --json shape ⚠️ documented, but the command list is incomplete (#4) and the guarantee is unconditional where it shouldn't be (#2)
10 Verified against a core type and a user-defined type ✅ task + venue, end-to-end against the real stack
11 Nothing left half-done ❌ findings #1 and #2

What's good

Worth stating plainly, because the parts that are right are the hard parts:

  • The diagnosis is the contribution. Recognizing this as a broken contract rather than a docs gap — and refusing to document the nesting, which would have enshrined it — is the judgment call the whole issue turned on.
  • The integration test asserts both halves at once. Storage nested and output flat, in one test, against the real service stack. A test that only checked the output would pass if someone "fixed" this by flattening at rest, which the issue explains is unsafe (colliding _seed/skill namespaces). This test would catch that.
  • Every test comment says why, not what. node_to_json_flattens_namespaced_properties_to_bare_field_names explains the "status unknown" failure mode it prevents. That's the difference between a test that survives a refactor and one that gets deleted as noise.
  • The duplication decision was made deliberately and documented at both sites, rather than happening by accident. My objection in Desktop shell with resizable panels #3 is only that documentation isn't enforcement — not that the call was wrong.
  • 1adef8a3 is exactly the right instinct: the fallback branch's object-drop looked suspicious, and rather than hand-waving, it pinned the adjacent behavior with a test. It just stopped one layer short of the write path, which is where the actual gap turned out to be.
  • Commit messages and PR body are unusually good — they explain reasoning, not just changes, and pre-empt most of the questions a reviewer would ask.

Recommendation

REQUEST CHANGES, on findings #1 and #2 — both are the same failure mode as the bug being fixed, in paths this change didn't reach, and the issue is explicit that partial completion is the one unacceptable outcome.

Finding #1 is the harder blocker and I'd fix it in rel_ops.rs where a real Node is in hand — the canonical helper applies directly there, so it costs no new duplication.

Finding #2 can reasonably ship as a follow-up issue if the docs guarantee is corrected here; what shouldn't ship is a documented promise of completeness alongside a path that silently drops a field.

Findings #3 and #4 are worth doing in this PR (both are small). #5–#8 are optional.

Also: 1adef8a3 is local-only — push it before merge, or the reviewed state isn't the merged state.

@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.

Verdict: REQUEST CHANGES

(Posted as a comment because GitHub rejects --request-changes on a self-authored PR.)

Full review: #2423 (comment)

The fix itself is correct and the diagnosis is the valuable part — treating this as a broken contract rather than a docs gap was the right call, and the integration test asserting both halves at once (storage nested / output flat) is the right shape of test. Clippy clean, all 10 unit tests pass.

Two blockers, both completeness — which the issue singles out as the one unacceptable outcome:

  1. 🔴 relationship get --json still emits the nested shape. It bypasses output.rs entirely, serializing raw Node structs at packages/core/src/ops/rel_ops.rs:383-386. It is a first-class documented read path (references/cli.md:237-259), and SKILL.md:146 explicitly recommends it as the follow-up to query. Best fixed at the source in rel_ops.rs, where a real Node is in hand — the canonical helper applies directly there, so the duplication argument that justifies the CLI mirror does not apply.

  2. 🔴 An object-valued property never reaches the type namespace on write, so it is silently dropped from output. create_node only fetches schema fields for node_type == "task" (crud.rs:98-139); every other type normalizes with None, so any object-valued property is misclassified as a namespace and hoisted beside the type key, where the flattener never looks. The codebase already names this hazard verbatim at packages/agent/src/skill_pipeline.rs:482-487 — "the normalizer misclassifies parameter_schema (an object) as a dormant namespace ... so flatten_properties_for_api later silently drops it." No built-in type loses data today (tool pre-namespaces; schema is object-free), but a user-defined object field would. The concern is that this PR tightens the output contract to promise completeness while the write path can't deliver it — turning a visible-but-wrong shape into an invisible omission.

Also flagged: nothing enforces that the two flattening implementations stay in step (they agree today — I checked line by line), and references/cli.md:14-16 omits node children, node batch-get, and node set-status from its list of node-emitting commands.

On the two items raised for scrutiny: widening node_to_json to pub is fine (consistent with the module's existing pub helpers and lib.rs's stated purpose), and keeping flattenTypeKeyedProperties in scripts/eval/ does hold up against CLAUDE.md — NS_BIN points at a binary the harness doesn't build, and preflight.ts:149 already treats stale builds as a live condition, so that's input tolerance at a trust boundary rather than a product compat shim.

One housekeeping note: 1adef8a3 is local-only and not yet pushed.

malibio added a commit that referenced this pull request Sep 7, 2026
Review of #2423 found the change incomplete in two places.

`relationship get` still leaked `properties.<schema-id>.<field>`. My claim
that output.rs is the funnel every node-emitting command passes through was
wrong: this path prints `related_nodes_json`, which rel_ops.rs builds with a
plain `to_value(Node)` — properties exactly as stored. It is a documented
read path that SKILL.md recommends as the follow-up to `query`, so an agent
following the skill's own advice landed on the one command still leaking.
Fixed at the source via `nodes_to_typed_values`, which fixes every consumer
of GetRelatedNodes rather than just the CLI, and pinned by a new test.

The flattening logic was duplicated between output.rs and convert.rs, whose
own docs declare it the "SOLE authority ... Do NOT re-implement". The two
agreed, but nothing kept them in step and divergence would surface as a
wrong answer rather than a red test. Extracted the rule as
`flatten_namespaced_properties` in nodespace-types; both callers now share
one body while keeping their own input types (Node vs the CLI's
JSON-encoded string).

Also from the review:
- cli.md claimed properties are complete, which the write path cannot
  deliver: create_node only resolves schema fields for `task`, so for other
  types `normalize_flat_properties_to_namespace` misclassifies an
  object-valued property as a namespace and hoists it out of the type key,
  where the flattener never looks. That is a pre-existing write-path bug
  (already documented at skill_pipeline.rs:482) and out of scope here, but
  the docs must not promise what it breaks — noted the gap instead.
- Replaced the enumerated command list with the general rule; it was
  already missing `node children`, `node batch-get` and `node set-status`.
- Repointed a duplicate-fixture test at the untested fallback branch.
- Explained the unreachable match arm in `has_properties`.

Kept `flattenTypeKeyedProperties` in scripts/eval — the review agreed the
stale-NS_BIN argument holds.

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

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed

All findings from the review are in 1adef8a3 + cc389ec3. I verified each finding independently before acting on it; both criticals were real.

🔴 Addressed

#1 — relationship get leaked the nested shape. Confirmed: my "output.rs is the single funnel" claim was wrong. relationship.rs:114 prints related_nodes_json, which rel_ops.rs:383 built with a plain to_value(Node) — properties exactly as stored. Since SKILL.md:146 recommends this command as the follow-up to query, an agent following the skill's own advice landed on the one command still leaking.

Fixed at the source via nodes_to_typed_values, per the review's reasoning — a real Node is in hand there, so the CLI's duplication rationale doesn't apply, and it fixes every consumer of GetRelatedNodes rather than just the CLI. Pinned by relationship_get_emits_flat_properties.

#2 — object-valued properties dropped on write. Confirmed, including the reviewer's read of crud.rs:99 (schema fields resolved only for task) and the hazard already documented verbatim at skill_pipeline.rs:482.

This is a pre-existing write-path bug, not one this PR introduces, and fixing normalize_flat_properties_to_namespace is out of scope here. But the review's real point was that my cli.md text promised completeness the write path cannot deliver — that part was mine, and it's corrected: the docs now state the gap plainly instead of guaranteeing against it. Worth its own issue; happy to file one.

🟡 Addressed

#3 — nothing kept the two implementations in step. Extracted flatten_namespaced_properties into nodespace-types; both callers now share one body while keeping their own input types. This resolves the convert.rs:29 "SOLE authority — do NOT re-implement" contradiction the review flagged, and the CLI's 10 unit tests now guard the canonical rule.

#4 — enumerated command list. Replaced with the general rule (it was already missing node children, node batch-get, node set-status).

🟢 Addressed

#5 Documented the unreachable _ => true arm. #8 Repointed the duplicate-fixture test at the untested fallback branch.

#6 (pub on node_to_json) and #7 (keeping flattenTypeKeyedProperties) — no change needed; the review concurred on both.

Verification

test:all green, matching baseline exactly (232 files / 4863 frontend tests, 0 new failures). 88 CLI tests, 1225+ core tests, quality:fix clean, clippy -D warnings clean. Full pre-push gate passed.

Housekeeping: 1adef8a3 is now pushed — the reviewed state is the merged state.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Filed the write-path bug from finding #2 as #2430.

I checked the size before filing rather than defaulting to "out of scope": the obvious fix (resolve schema fields for all types, not just task) is explicitly blocked by a measured constraint at crud.rs:91 — "avoids a ~760ms database lookup for every node creation." That comment's premise is stale now that user-defined schemas have fields, but removing the gate would reintroduce the regression, so a real fix needs a caching/narrowing decision plus fresh measurement. That is genuinely separate scope per issue-workflow.md, and #2430 records the constraint so the next agent starts from it rather than rediscovering it.

Happy to pick #2430 up next if you'd like it prioritized — your call on sequencing.

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary — RE-REVIEW (round 2)

Review Type: Re-review, scoped to b06ca679..HEAD (1adef8a3, cc389ec3).

Previous Review Summary

Count
Previous recommendations addressed 5 of 6 actioned (#1, #3, #4, #5, #8)
Previous recommendations deliberately deferred 1 (#2 — write-path bug, filed separately)
New issues found in this round 3 (1 🔴, 1 🟡, 1 🟢)

The two headline fixes are real, and I verified them rather than trusting the claims:

  • Set up Tauri + Svelte project structure #1 (relationship leak) — genuinely fixed, and genuinely pinned. I reverted rel_ops.rs to the old to_value(Node) body and re-ran the new test: it fails with left: Null, right: "high" at cli_integration.rs:1094. Restored afterwards; the worktree is clean. This is a real regression guard, not a test that merely passes.
  • Desktop shell with resizable panels #3 (duplicated flattening rule) — extraction is semantically identical. I checked every branch against git show b06ca679:packages/nodespace-types/src/convert.rs, including the two cases the brief flagged. The nested if let → .and_then(|v| v.as_object()) rewrite preserves fall-through when the namespace key holds a non-object (verified: {"task":"scalar","x":1} → {"task":"scalar","x":1} in both, because the fallback's !v.is_object() filter retains the scalar). The non-object early return is also equivalent — the original left node.properties untouched, the new one returns properties.clone() and flatten_properties_for_api assigns it back to the same field, so the value is unchanged either way. flatten_properties_for_api is still applied in place and still called first in node_to_typed_value, before the type match reads node.properties.
  • Development server works with hot reload #8 (repointed unit test) — genuinely covers the fallback. node_type = "text" with {"_schema_version":1,"_seed":{...},"note":"keep"} has no text key, so it takes the fallback branch, and it now asserts the positive case (note == "keep") alongside the two exclusions. The old version duplicated the primary-branch fixture. 1adef8a3's new test correctly covers the complementary primary-branch case.
  • Enhanced BaseNode with Hierarchical Circle Indicators + TextNode Implementation #4, Basic storage integration #5 — both fine. The generalized doc sentence is more honest than the enumeration, and every_cli_command_is_documented still passes.
  • Create design system foundation #2 (deferral) — the deferral judgment is right; the caveat's scoping is not. Deferring is correct: the defect is in normalize_flat_properties_to_namespace, a shared write helper with six call sites across crud.rs and bulk.rs, and fixing it properly means schema-field resolution for every type, not just task. That is a different change with a different blast radius, and bundling it would have broken the atomicity this PR otherwise has. But the caveat's boundary is wrong — see 🔴 below.

Layering is fine. nodespace-types is the right home for the rule (minimal crate: serde/serde_json/chrono/uuid/thiserror, no DB/HTTP/NLP), and pub is the right visibility given the CLI is a separate crate that cannot reach a pub(crate). The new CLI dependency adds no layering concern — the CLI already depends on nodespace-daemon, which is far heavier and transitively includes nodespace-types anyway; the Cargo.lock delta is the single expected line. cargo clippy -p nodespace-cli -p nodespace-types -p nodespace-core --all-targets is clean. cargo test -p nodespace-cli is green (46 + 29 + 3 + 10). The one nodespace-core lib failure (bulk_add_to_collections_notify_emits_push_events) passes in isolation and touches bulk collection push events — pre-existing flake, unrelated to this diff.

On the error-handling change in rel_ops.rs: unwrap_or(json!(null)) → map_err(OpsError::Internal)? is an improvement, and the widened failure mode is acceptable. The old code turned a serialization failure into a silent null element that every downstream consumer would misread as a node; the new code fails loudly. In practice neither fires for the generic path (Node has no non-serializable field), and the new Err arms are SchemaNode::from_node's type mismatch and the to_value calls — all unreachable here since node_type is matched immediately before. Failing a batch over one bad node is the same trade-off nodes_to_typed_values already makes on every other read path, so this is consistency, not a new risk.


Findings

🔴 Critical

📁 packages/skill/references/cli.md:37-41 — the caveat under-scopes the gap it documents, and the sentence above it now over-promises for relationship get.

Two problems, both from the same root: the docs assert one uniform node shape that the code no longer delivers.

(a) "and objects on task are unaffected" is false. The caveat pins the gap to create_node's task-only schema resolution, which is accurate for create (crud.rs:99 gates the Some(&fields) call on node.node_type == "task"). But node update is a separate path, and both update call sites pass None for schema fields regardless of type:

// crud.rs:649 and again at :779
let normalized_properties = Self::normalize_flat_properties_to_namespace(
    &updated.node_type,
    &properties,
    None, // Schema fields are fetched later if needed
);

With schema_fields: None, schema_field_names is empty (crud.rs:1685-1687), so the classifier at crud.rs:1704 — if value.is_object() && !schema_field_names.contains(key) — hoists any object-valued property out of the type namespace for task too. And the CLI can trigger it directly: parse_property (packages/cli/src/commands/node.rs:80-89) JSON-parses the value, so nodespace node update <task-id> --property billing='{"city":"Berlin"}' lands in exactly this branch. An agent reading "objects on task are unaffected" and then losing an object on a task has been actively misled — worse than not documenting the gap at all. The fix is to widen the caveat to "an object-valued property set via node update on any type, or via node create on any type other than task", or to drop the type/command qualifiers entirely and say object-valued properties may not read back.

(b) The generalized "Every command that emits a node returns objects of this shape" is now wrong for the command this PR just changed. node get/query/search go through the CLI's own node_to_json (packages/cli/src/output.rs:116-131), which emits hand-written snake_case: node_type, lifecycle_status, created_at, modified_at, and no uri. relationship get prints related_nodes_json straight through (packages/cli/src/commands/relationship.rs:114-142), which is now nodes_to_typed_values output — camelCase plus an injected uri. I verified against the real crate:

# node get / query / search        # relationship get (after this PR)
"node_type": "ticket"             "nodeType": "ticket"
"created_at": ...                 "createdAt": ...
"lifecycle_status": ...           "uri": "nodespace://<id>"

And for schema nodes the SchemaNode::from_node reshape drops nodeType, title and properties entirely, replacing them with fields/relationships/isCore/schemaVersion/description. That branch is reachable: mentions is a universal built-in legal between any two nodes (cli.md:270), so relationship get <doc-id> --type mentions can return a schema node. An agent that read the doc's promise and does jq '.related_nodes[].node_type' gets null.

Note the previous round narrowed this sentence from a correct enumeration to an incorrect universal, so the doc got less accurate on exactly the point this PR is about. Per the project's own standard the fix is not to reference an issue but to state the behavior: either say relationship get returns the richer typed shape (camelCase, uri, typed nodes reshaped), or — better, and closer to the PR's stated goal of one uniform CLI shape — have relationship get render its nodes through the CLI's own node_to_json so the promise becomes true. The principle at stake is the one this PR is built on: a documented contract must describe what the code emits (Documentation & API consistency). Silent incompleteness is precisely what CLAUDE.md's zero-users rule does not excuse — a breaking shape change is free here, an inaccurate description of it is not.

🟡 Improvement

📁 packages/core/src/ops/rel_ops.rs:382-388 — the fix reaches further than the stated goal, and nothing pins the extra reshaping.

The comment justifies the change purely as de-nesting properties ("A plain to_value(Node) here would serialize properties exactly as stored"). But nodes_to_typed_values does four things: flatten, promote typed fields to top level (task, ai-chat), reshape via SchemaNode::from_node (schema), and inject uri. Three of those are unrelated to the leak being fixed.

I checked the blast radius and it is genuinely small — this is why this is 🟡 and not 🔴. The op has exactly two production callers:

  • packages/daemon/src/services/node_service.rs:1039 → the CLI (this PR's target).
  • packages/agent/src/local_agent/tools.rs:2988 → reads only id, title, and node_type/type from each value.

There is no frontend or Tauri consumer: grep get_related over packages/desktop-app/src{,-tauri}/src returns nothing, and the relationship viewer uses the different, untouched get_node_relationships op (backend-adapter.ts:283). graph_resolver.rs:194 and search_ops.rs:473,495 call the NodeService method, not this op, so they still get typed Nodes. Good — the risk the brief raised does not materialize.

The agent tool's lookups do degrade for schema nodes, though: node_val.get("node_type").or(node_val.get("type")) (tools.rs:2999) and get("title") both return None, because SchemaNode has neither field. That is a real behavior change on the agent path, and it is invisible — the tool emits "type": "" rather than erroring. (Its node_type lookup was already dead before this PR, since plain Node also serializes #[serde(rename_all = "camelCase")] → nodeType; the title loss and the properties loss are new.)

Two things worth doing: (1) extend the comment to say what else the call brings — the promotion, the reshape, the uri — so the next reader knows the payload changed by more than de-nesting, and doesn't reintroduce a plain to_value thinking it is equivalent modulo properties; (2) either fix tools.rs:2999 to read nodeType (it is one word and currently silently wrong) or file it. The principle is least surprise / explicit intent: a fix whose comment describes a narrower change than the code performs invites the next person to undo it.

🟢 Nits

Nit: 📁 packages/nodespace-types/src/lib.rs:3-6 — crate doc is now stale. It states the crate is "shared between nodespace-core (storage layer) and the Tauri command layer". nodespace-cli is now a third consumer, and the whole point of finding #3's fix was to make that sharing load-bearing. One clause.

Nit: 📁 packages/nodespace-types/src/convert.rs:63-81 — the doc block is excellent (the branch-asymmetry paragraph in particular is exactly the "why" a future reader needs). Worth adding that the function is also the definition the CLI's human-readable output honours, not only --json, since write_human_node shares properties_to_json.


Verdict: REQUEST CHANGES

The engineering in this round is strong. Both headline fixes are correct, the extraction is provably behavior-preserving, the new integration test is a real guard (I confirmed it red against the old code), the error-handling change is a net improvement, and the deferral of the write-path bug is the right call for atomicity. The blast radius of the rel_ops.rs change is smaller than feared — no frontend or Tauri consumer exists.

What blocks is documentation correctness, and it blocks because of what this PR is for. The entire change exists so that an agent reading cli.md can trust properties is flat. Round 2 fixed the last command that leaked, then in the same commit widened the doc's promise to a universal that relationship get — the very command just fixed — does not satisfy, and scoped the object-valued caveat to exclude a case (node update on a task) that is broken and CLI-reachable. Both are the same failure mode the PR set out to eliminate: an agent trusting the documented shape and reading null off real data. That is silent incompleteness, which the zero-users rule does not cover.

Fix 🔴 (a) and (b); 🟡 is a comment expansion plus a one-word agent-tool fix or a filed issue. Neither requires touching the code this round got right.

@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.

Verdict: REQUEST CHANGES (posted as a comment — GitHub rejects --request-changes on a self-authored PR).

Re-review of b06ca679..HEAD is posted in full at #2423 (comment)

Previous round: 5 of 6 recommendations addressed, 1 deliberately deferred (correctly). 3 new findings (1 🔴, 1 🟡, 1 🟢).

Verified rather than assumed:

  • The rel_ops.rs fix is real and the new test is a real guard — I reverted rel_ops.rs to the old to_value(Node) body and relationship_get_emits_flat_properties failed (left: Null, right: "high"). Restored; worktree clean.
  • flatten_namespaced_properties is provably behavior-preserving vs the original private body on every branch, including the non-object early return and the namespace-key-holds-a-scalar case.
  • No frontend or Tauri consumer of GetRelatedNodes exists (the relationship viewer uses the untouched get_node_relationships), so that risk does not materialize. The unwrap_or(json!(null)) → OpsError::Internal change is a net improvement.
  • Layering is fine; pub in nodespace-types is the right home and visibility. Clippy clean, cargo test -p nodespace-cli green.

🔴 What blocks — packages/skill/references/cli.md:37-41, both halves of the same failure mode this PR exists to eliminate:

  1. "objects on task are unaffected" is false. node update passes schema_fields: None for every type (crud.rs:649 and :779), so the classifier at crud.rs:1704 hoists object-valued properties out of the namespace on tasks too — and it is CLI-reachable via node update <task-id> --property billing='{"city":"Berlin"}'. An agent told tasks are safe, then losing an object on a task, is worse off than with no caveat.
  2. "Every command that emits a node returns objects of this shape" is now wrong for the command this PR just fixed. node get/query/search emit snake_case via the CLI's node_to_json; relationship get now passes nodes_to_typed_values output straight through — camelCase (nodeType, createdAt) plus an injected uri, and for schema nodes no nodeType/title/properties at all. That branch is reachable via the universal mentions edge.

Round 2 narrowed this sentence from a correct enumeration to an incorrect universal, so the doc got less accurate on exactly the point at issue. A breaking shape change is free under the zero-users rule; an inaccurate description of it is not.

🟡 rel_ops.rs:382-388 — the comment justifies the change as de-nesting only, but nodes_to_typed_values also promotes typed fields, reshapes schema via SchemaNode::from_node, and injects uri. Small blast radius, but tools.rs:2999 silently loses title and type for schema nodes. Expand the comment; fix or file the agent-tool lookup.

The engineering this round is strong and none of the code that landed needs reverting — the fixes are documentation-side.

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review feedback addressed — bc74023e

The 🔴 was correct and worth stating plainly: round 2 fixed the last leaking command and then, in the same commit, made two doc claims the code didn't satisfy. That's the exact failure mode this PR exists to eliminate, so I fixed both properly rather than documenting around them.

🔴 (a) — "objects on task are unaffected" was false

Verified: both node update sites (crud.rs:649, :779) pass None for schema fields regardless of type, so an object property is hoisted out of the type namespace for task too — and it's CLI-reachable via parse_property's JSON parsing. An agent told tasks were safe and then losing one is worse off than with no caveat.

Caveat rescoped to what actually breaks: update for every type, create for every type but task, with a concrete example of what "object-valued" means. Also corrected the scope on #2430, which I'd filed with the same too-narrow boundary.

🔴 (b) — the generalized sentence was wrong for the command this PR just changed

Confirmed the divergence empirically (throwaway probe, since deleted): node get/query/search emit snake_case with no uri; relationship get was emitting camelCase + injected uri + promoted typed fields.

Took the option closer to the PR's goal rather than documenting a second shape: the CLI now re-keys these nodes into its own shape via output::related_node_to_json, dropping uri and the promoted duplicates properties already carries. schema nodes pass through untouched — SchemaNode::from_node has already dropped nodeType/title/properties, and a half-mapped node that looks like the CLI shape while missing its fields is worse than an honest passthrough. Three unit tests cover re-keying, dropping, and the schema passthrough.

So the generalized sentence is now true rather than narrowed back to an enumeration.

🟡 — rel_ops.rs comment expanded

Now names the promotion, the schema reshape and the uri, so nobody "simplifies" it back to a plain to_value assuming equivalence.

Bonus: fixed the dead lookup you flagged

tools.rs:2999 read node_type, but Node serializes camelCase — so that lookup never matched and the agent reported every node's type to the model as empty. Pre-existing and independent of this PR, but a one-line fix in code I was already reading, which issue-workflow.md puts in "fix it now" rather than "file it."

🟢 Both done

Crate doc now lists nodespace-cli as a third consumer; convert.rs records that the rule governs human-readable output too, since both modes share one call into it.

Verification

test:all green, matching baseline exactly (232 files / 4863 frontend, 0 new failures). 91 CLI tests, 593 agent tests, skill:check up to date, quality:fix clean, clippy -D warnings clean. Full pre-push gate passed.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary — RE-REVIEW (round 3)

Review Type: Re-review, scoped to cc389ec3..HEAD (bc74023e).

Previous Review Summary

Count
Round-2 recommendations addressed 4 of 4 actioned (🔴a, 🔴b, 🟡, both 🟢)
Round-2 recommendations correctly addressed 3 of 4 (🔴b's fix is incomplete)
New issues found in this round 4 (1 🔴, 2 🟡, 1 🟢)

Three of the four items are done properly and I verified each rather than trusting the claim:

  • 🔴(a) — correct, and the new wording is precisely right. I read all six normalize_flat_properties_to_namespace call sites. create_node gates Some(&fields) on node_type == "task" (crud.rs:99, passing at :115) and passes None for every other non-schema type (:135). Both update sites pass None unconditionally (:649, :779), so with an empty schema_field_names the classifier at :1704 hoists any object-valued key for task too. The "already namespaced" early return at :1691 does not rescue update, because the incoming value is the flat patch ({"billing":{…}}), which carries no task key. So "update for every type (including task), create for every type except task" is exactly the boundary — neither over- nor under-claimed. The bulk.rs sites do not widen it: bulk create resolves schema fields from a cache for all types (:139, :252), which is strictly better than create's task-only gate, and bulk update passes None (:536), which the "update for every type" clause already covers. Adding the concrete --property address='{"city":"Berlin"}' example is a real improvement — "object-valued" was ambiguous to an agent that had just typed a JSON string.
  • 🟡 — done. The rel_ops.rs comment now names the promotion, the SchemaNode reshape and the uri, and points at the CLI re-keying. That is what was asked.
  • 🟢 — both done. Crate doc lists nodespace-cli; the convert.rs note about human-readable output is accurate (write_human_node and node_to_json both route through properties_to_json).
  • The tools.rs fix is genuinely correct. nodeType is the right key: Node is rename_all = "camelCase", and TaskNode/AiChatNode both carry an explicit #[serde(rename = "nodeType")]. I confirmed empirically that all three emit nodeType. Fixing it in code already being read is the right call under issue-workflow.md.

What I did to verify: built throwaway probe tests against the real crates that ran node_to_typed_value over a task with populated properties, a task with empty properties, a generic node with title/mentions/mentionedIn/archived, an ai-chat, a schema, and a non-schema node with a user-defined fields property — then piped each real payload through the committed related_node_to_json. Both probe files are deleted and the worktree is back to its pre-review state.

One process note before the findings: packages/cli/src/output.rs has uncommitted modifications in the worktree (timestamped after bc74023e) that substantially rewrite related_node_to_json — replacing DROPPED with a CLI_KEYS allowlist that folds promoted fields back under properties, and swapping the three phantom renames for mentionedIn. That in-flight version fixes 🔴 #1, 🟡 #2 and 🟢 #4 below. Since my scope is the commit, the findings below are against bc74023e as committed; if that working-tree work is the intended fix, committing it resolves most of this review, and the remaining item is 🟡 #3 (the fields heuristic), which the in-flight version does not change.


Findings

🔴 Critical

📁 packages/cli/src/output.rs:167-173 — the DROPPED list loses a task's status outright whenever properties does not carry it.

The doc comment justifies dropping the promoted fields "since properties already carries the promoted values". For five of the six that holds, because TaskNode marks them skip_serializing_if = "Option::is_none" — an absent dueDate is never emitted, so there is nothing to drop. status is the exception. It is not an Option: task_node_to_value does

let status: TaskStatus = props.get("status").and_then(|v| v.as_str())
    .and_then(|s| s.parse().ok())
    .unwrap_or_default();   // → TaskStatus::Open

so a task with no stored status still serializes "status": "open" at the top level while properties stays {}. DROPPED then unconditionally continues on it. Verified against the real crates — this is the committed function's actual output:

input  (node_to_typed_value)          output (related_node_to_json)
"status": "open"                      { "id": "t2", "node_type": "task",
"properties": {}                        "content": "Bare", "properties": {},
                                        "version": 1, … }        ← no status

nodespace relationship get <id> --type blocks on a task whose status was never explicitly written returns a task with no status at all — while node get on the same node returns "status": "open". That is precisely the defect this PR exists to eliminate, one command later: a consumer reads .properties.status, gets None, and concludes "status unknown" about a real task. Worse than round 2's version, which at least surfaced the value under a camelCase key.

ai_chat_node_to_value has the same non-Option shape for status (unwrap_or_default() → ""), so ai-chat is affected identically.

The principle is no lossy transformation on a read path. Dropping a key is only safe when it is provably a duplicate, and skip_serializing_if is what makes five of the six provable — status has no such guard, so it must be folded into properties rather than dropped. (The uncommitted working-tree rewrite does exactly this, with stored values winning over synthesized ones, which is the right precedence.)

🟡 Improvements

📁 packages/cli/src/output.rs:151-155, 167-173 — RENAMES lists three keys that cannot occur and omits one that does; DROPPED omits three promoted ai-chat fields.

The doc comment says only the keys the CLI shape defines are re-keyed, but the lists were not derived from the structs. Enumerating Node's serialized fields (node.rs:16-37, rename_all = "camelCase") gives: id, nodeType, content, version, createdAt, modifiedAt, properties, mentions, mentionedIn, title, lifecycleStatus.

  • parentId, rootId, beforeSiblingId are dead entries. None is a field of Node, TaskNode, AiChatNode or SchemaNode — hierarchy moved to edges, and the proto even reserveds parent_id (node_service.proto:125-126). They are three lines of code that can never fire.
  • mentionedIn is missing, and it is real. Confirmed emitted: a node with mentioned_in populated comes out of the committed function as "mentionedIn": [...] — one camelCase key surviving in an otherwise snake_case object, which is the exact inconsistency this function exists to remove. (mentions needs no rename; title is already bare.)
  • DROPPED covers only status of ai-chat's four promoted fields. Verified: provider, model and messages pass straight through to the top level alongside their copies in properties, so an ai-chat node emerges with duplicated data and three keys no other command emits.

An allowlist of the keys the CLI shape defines is more robust than a denylist of the ones it doesn't, because it fails closed when a new typed field is promoted — a denylist silently leaks it. Principle: derive the mapping from the type, don't hand-maintain a parallel list (DRY / single source of truth). Worth a comment naming nodespace_types::Node as the list's source so the next promoted field gets handled.

📁 packages/cli/src/output.rs:135-139 — the schema-node heuristic can false-positive on a user-defined type with a field named fields.

obj.contains_key("fields") || obj.contains_key("schemaVersion") is structural, and fields is not a reserved name: RESERVED_CORE_PROPERTIES (packages/core/src/schema/mod.rs:16-28) lists id/node_type/content/parent_id/root_id/created_at/modified_at/status/priority/due_date/due — not fields. So a form or survey type with a fields array is legal, warning-free, and flattens to a top-level properties.fields… but the node keeps fields inside properties, not at the top level. I checked this: a non-schema node's fields lives under properties, so obj.contains_key("fields") is false and the heuristic does not fire. Good — but only by accident of where flattening puts it, and the code doesn't say so.

The consequence if it ever did fire is a silent full passthrough: camelCase keys, a leaked uri, no re-keying — the bug this function fixes, for one node type. The robust test is the one the payload actually supports: !obj.contains_key("nodeType"), since SchemaNode is the only shape in this union that lacks it. That is a positive identification rather than an inference from an optional field name, and it cannot be shadowed by user schema authorship. Principle: discriminate on an invariant, not on a coincidence. At minimum, extend the comment to record why a user-defined fields cannot reach this branch, so a future change to flattening doesn't quietly break the assumption.

🟢 Nit

Nit: 📁 packages/skill/references/cli.md:14-15 — "Every command that emits a node returns objects of this shape" is still not true for schema nodes out of relationship get.

The re-keying makes this true for generic, task and ai-chat nodes (modulo the 🔴 and 🟡 above), which is real progress. But the schema passthrough is deliberate, and a passed-through schema node is a visibly different shape — verified output: createdAt/modifiedAt camelCase, a uri, no node_type, no title, no properties, plus fields/relationships/isCore/schemaVersion/description. So jq '.related_nodes[].node_type' still yields null for a schema node reached via --type mentions, and no caveat covers it (the object-valued caveat is about a different thing entirely).

I think the passthrough decision itself is right — SchemaNode::from_node has genuinely discarded nodeType/title/properties, and a half-mapped node claiming the CLI shape while missing its fields would be worse. This is a 🟢 rather than a 🔴 because the reachability is narrow and the honest-passthrough reasoning is sound. But the doc sentence is a universal quantifier with a known exception. One clause fixes it: note that a schema node reached through relationship get comes back in the schema shape (fields, schemaVersion, no node_type), and that schema get is the command to use for schemas. Principle: a documented contract must describe what the code emits — the same one that drove round 2's 🔴(b).


Verdict: REQUEST CHANGES

The round-3 work is directionally right and the analysis behind it is honest — 🔴(a)'s rescoped caveat is now exactly accurate (I checked all six write call sites), the rel_ops.rs comment and both 🟢s are done, and the tools.rs catch is a genuine bug fix with the correct key. Choosing to re-key rather than document a second shape was the better of the two options round 2 offered.

What blocks is that the re-keying is incomplete in the same failure mode the PR exists to close. DROPPED treats all six promoted task fields as duplicates, but only the five Option ones are protected by skip_serializing_if; status is synthesized by unwrap_or_default() and gets dropped with nothing carrying it, so a task with no explicitly stored status comes back from relationship get with no status at all while node get reports "open". That is the "reads None off real data" bug, relocated. Alongside it, the hand-maintained key lists don't match the structs — three renames that can never fire, mentionedIn missing so one camelCase key survives, and three ai-chat fields duplicated at the top level.

The uncommitted output.rs in the worktree appears to be exactly this fix (allowlist + fold-back with stored-value precedence + mentionedIn), so this may be a matter of committing work already done. If so, 🔴 #1, 🟡 #2 and 🟢 #4's underlying inconsistency go away, and what remains is 🟡 #3's discriminator (!obj.contains_key("nodeType") over the fields heuristic, or a comment recording why the false positive is unreachable) and the one-clause cli.md caveat for the schema shape. Please also add a test for the bare-status task — it is the case that broke, and nothing currently pins it.

@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.

Verdict: REQUEST CHANGES (round 3 re-review — posted as a comment because GitHub rejects --request-changes on a self-authored PR).

Full review: #2423 (comment)

Round 3 addressed all four round-2 items and three are correct — the rescoped object-valued caveat is now exactly accurate (verified against all six normalize_flat_properties_to_namespace call sites in crud.rs and bulk.rs), the rel_ops.rs comment and both nits are done, and the tools.rs nodeType fix is a genuine bug fix with the right key.

What blocks: the new related_node_to_json re-keying is incomplete in the same failure mode the PR exists to close.

  • 🔴 output.rs:167-173 — DROPPED treats all six promoted task fields as duplicates of properties, but only the five Option ones are protected by skip_serializing_if. status is synthesized by task_node_to_value's unwrap_or_default(), so a task with no stored status serializes "status": "open" with properties: {} — and the drop loses it entirely. Verified against the real crates: relationship get returns that task with no status at all, while node get reports "open". Same non-Option shape for ai-chat's status.
  • 🟡 output.rs:151-155, 167-173 — the key lists don't match the structs: parentId/rootId/beforeSiblingId are not fields of any node shape and can never fire; mentionedIn is missing and does occur, leaving one camelCase key in an otherwise snake_case object; ai-chat's provider/model/messages pass through duplicated at the top level.
  • 🟡 output.rs:135-139 — the fields/schemaVersion schema heuristic is a coincidence, not an invariant (fields is not in RESERVED_CORE_PROPERTIES). It happens not to false-positive only because flattening puts a user-defined fields under properties. !obj.contains_key("nodeType") identifies SchemaNode positively.
  • 🟢 cli.md:14-15 — "Every command that emits a node returns objects of this shape" still has a known exception: a passed-through schema node keeps camelCase timestamps, a uri, and no node_type/title/properties.

Note: packages/cli/src/output.rs has uncommitted changes in the worktree (timestamped after bc74023e) that appear to be exactly this fix — a CLI_KEYS allowlist folding promoted fields back under properties with stored values winning, plus mentionedIn. If that is the intended fix, committing it resolves the 🔴 and the first 🟡; please add a test for the bare-status task, since that is the case that broke and nothing pins it.

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Round 3 feedback addressed — 8094994c

You were right on all four, and I'd independently caught the 🔴 and first 🟡 while probing my own code — good convergence. The in-flight edit you spotted was that fix mid-flight; it's now committed with your two remaining items folded in.

🔴 status lost when properties doesn't carry it

Confirmed exactly as diagnosed. Probing real payloads: a task with properties: {"priority": "high"} serialized "status": "open" at the top level (unwrap_or_default(), and status isn't an Option), and my blanket drop discarded it — relationship get showed no status where node get showed "open". The other five promoted fields are skip_serializing_if = "Option::is_none", which is precisely why this hid behind them.

Fixed by folding promoted fields into properties rather than dropping them, stored value winning. That also generalizes past a hardcoded list — it picks up ai-chat's provider/model/messages, which you noted were passing through duplicated.

🟡 Key lists didn't match the structs

Checked against Node rather than guessed: parentId/rootId/beforeSiblingId are fields of no node shape and could never fire — removed. mentionedIn is real and was missing; verified it was surviving as the one camelCase key in an otherwise snake_case object. Now re-keyed, with a test.

🟡 Schema discriminator keyed off a coincidence

Adopted your suggestion: keys off the absence of nodeType, which every node shape carries and SchemaNode does not. Added the false-positive case as a test — a form type with a fields property must still be re-keyed, and now is.

🟢 The doc's remaining exception

Documented: a schema node reached via relationship get comes back in the schema's own shape, and schema get is the right way to read schemas. The passthrough itself stays.

Verification

16 output unit tests (up from 13), 94 CLI tests total, test:all green and matching baseline exactly (232 files / 4863 frontend, 0 new failures). quality:fix and clippy -D warnings clean. Full pre-push gate passed. Worktree clean — my throwaway probes are deleted.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2423 (Round 4)

Type: Re-review
Scope: 8094994c only (git diff bc74023e..HEAD). Rounds 1–3 covered b06ca679, 1adef8a3, cc389ec3, bc74023e.
Verdict: 🟡 REQUEST CHANGES — one genuine documentation defect, verified empirically. The code change itself is correct and I'd approve it standalone.


Previous Review Summary

Round 3 finding Status
🔴 DROPPED list lost a task's synthesized status ✅ Addressed — verified
🟡 Rename list carried three impossible keys, missed mentionedIn ✅ Addressed — verified
🟡 schema passthrough keyed off fields/schemaVersion coincidence ✅ Addressed — verified
🟢 cli.md universal-shape claim needed an exception clause ✅ Addressed, but the clause it added is factually wrong (new 🟡 below)

Counts: 4 addressed / 0 unaddressed / 1 new 🟡 + 1 new 🟢.


Verification method

I did not take the summary on trust. I enumerated what node_to_typed_value actually emits by running each of its four branches and dumping the key sets, then piped those real payloads through related_node_to_json. Ground truth (probe files since removed; tree is clean):

Branch Top-level keys emitted
task → TaskNode id, nodeType, content, title, version, createdAt, modifiedAt, properties, lifecycleStatus, status, priority, dueDate, assignee, startedAt, completedAt, uri
ai-chat → AiChatNode id, nodeType, content, version, createdAt, modifiedAt, properties, lifecycleStatus, status, provider, model, messages, uri
generic → Node id, nodeType, content, version, createdAt, modifiedAt, properties, mentions, mentionedIn, title, lifecycleStatus, uri
schema → SchemaNode id, content, version, createdAt, modifiedAt, isCore, schemaVersion, description, fields, relationships, uri — no nodeType

I also confirmed via packages/core/src/ops/rel_ops.rs:394 that related_nodes is always built by nodes_to_typed_values, so these four branches are exhaustive for this function's input. That makes the enumeration complete rather than illustrative.


What I confirmed correct

The CLI_KEYS allowlist is complete and correctly partitioned. Every key above is either in CLI_KEYS, folded, or dropped, with no leftovers:

  • Folded to properties: status, priority, dueDate, assignee, startedAt, completedAt (task); status, provider, model, messages (ai-chat). All ten are genuinely promoted-out-of-properties values, not node fields — correct classification.
  • Dropped: uri only.
  • Kept top-level: the eleven CLI_KEYS. The four RENAMES cover exactly the camelCase-vs-snake_case deltas that can occur, and I confirmed the three deleted entries (parentId/rootId/beforeSiblingId) appear on no shape — deleting them was right, and mentionedIn was the real omission.

The allowlist is the right architecture, not just a working one. The drop-list was a denylist over an open set — anything new defaults to leaking. CLI_KEYS inverts that: a new promoted field defaults to being folded into properties, which is the safe direction. That is the Open/Closed principle applied correctly, and it is why the round-3 🔴 class of bug cannot recur.

messages folded under properties is right, despite being large. I specifically checked whether this misrepresents it. It does not: messages is a stored property (properties["ai-chat"]["messages"]), and the probe confirms node_to_typed_value leaves it in properties as well as promoting it. So folding restores the stored location rather than inventing one, and or_insert finds the key already present and keeps the stored copy — the promoted copy is discarded, so no duplication and no size increase. Verified: output contains properties.messages and no top-level messages.

or_insert precedence is correct. For the disagreement case you asked about: stored-wins is right because properties is the verbatim stored value while the promoted field has passed through lossy normalization. Concretely, dueDate stored as 2026-01-01T00:00:00Z is promoted as 2026-01-01 (normalize_date_field); or_insert keeps the stored timestamp, which matches what node get reports, since node get flattens raw storage and never normalizes. Precedence the other way round would have made the two commands disagree. Also worth noting the promoted value can only differ when the key is stored, and status — the one synthesized field — is only inserted when absent. Both halves land correctly.

The !contains_key("nodeType") discriminator is sound. SchemaNode (packages/nodespace-types/src/schema.rs:249-270) has no node_type field at all, so it structurally cannot emit the key — this is stronger than a skip_serializing_if guarantee, which could be flipped by a value. Conversely all three non-schema branches have node_type: String with no skip attribute, so the key is unconditionally present even when empty. There is no payload that can reach this function and be misclassified in either direction.


Findings

🟡 Improvement

1. cli.md's schema exception names three keys, and one of them does not exist

📁 packages/skill/references/cli.md:16-21

The new clause says a schema node reached via relationship get "comes back in the schema's own shape (name, fields, relationships)".

SchemaNode has no name field. Verified against the struct (schema.rs:249-270) and against the actual serialized output, which is id, content, version, createdAt, modifiedAt, isCore, schemaVersion, description, fields, relationships, uri. The name field at schema.rs:124 belongs to SchemaField, not SchemaNode — a plausible misread, but the doc is a contract an agent parses against, and it now names a key that will never be there.

This is the same defect class the PR exists to fix: a documented shape that does not match the emitted shape. Round 3's 🟢 asked for an exception clause; the clause arrived but is itself inaccurate, so the finding is not really closed.

Two further inaccuracies in the same sentence, worth fixing in one pass since it is three words either way:

  • The keys are camelCase, not snake_case. isCore, schemaVersion, createdAt, modifiedAt pass straight through the early return untouched. The surrounding paragraph tells the reader every key is snake_case and to "parse against these names and nothing else" — for this one payload that is wrong, and the exception clause is the natural place to say so.
  • uri survives here. The early return node.clone() precedes the uri drop, so a schema node via relationship get is the one CLI payload that carries a uri. The function's own doc comment asserts "no other command emits a uri", which is true of the folding path but not of the passthrough it sits directly above.

Suggested replacement for the parenthetical: …comes back in the schema's own camelCase shape (isCore, schemaVersion, description, fields, relationships, plus a uri) rather than the node shape…

Principle: documentation is an interface contract. A generated-adjacent reference that an agent parses against is load-bearing, and a wrong key name in it is a defect, not a typo. Standalone-accuracy is also the standard CLAUDE.md sets for docs in this repo.


🟢 Nitpick

2. node_to_json cannot emit title/mentions/mentioned_in, so three CLI_KEYS are relationship get-only

📁 packages/cli/src/output.rs:167-179

You asked specifically about residual divergence between the two constructions. There is one, and it is inherent rather than introduced: NodeData (packages/proto/proto/node_service.proto:121-136) has no title, mentions, or mentioned_in fields, so node_to_json structurally cannot emit them, while related_node_to_json passes all three through. Verified: a generic node via relationship get emits title, mentions, mentioned_in; the same node via node get emits none of them.

I am flagging this 🟢, not 🟡, because it is the correct call in both directions: dropping real inbound-mention data to match a proto that lacks the field would be silent information loss, which is exactly what this PR set out to stop. cli.md:17-18 already discloses the title half ("relationship get may additionally include title"), so the docs are not silent — they are just incomplete by two keys. Extending that clause to mentions and mentioned_in would close the gap; alternatively note that mentioned_in entries are themselves camelCase (nodeType), since NodeReference is passed through unrekeyed.

Also genuinely confirmed absent: related_node_to_json emits nothing that node_to_json lacks aside from these three, and no collection_id (the proto reserves that field name). Field-for-field, the shared eight keys agree exactly, including key spelling and properties flatness.


Assessment

The code in 8094994c is correct. I tried to break the allowlist, the precedence rule and the discriminator with real payloads from all four branches and could not — the round-3 🔴 is genuinely fixed, and fixed structurally rather than patched. The three new tests each pin a distinct real hazard (synthesized status, mentionedIn re-keying, fields-as-user-property) and each carries a why, matching the standard set by the rest of this file. cargo clippy -p nodespace-cli --all-targets -- -D warnings is clean; all 52 CLI unit tests pass.

What holds it back is one sentence of documentation that got three details wrong while fixing a fourth. Given that the PR's entire premise is "the documented shape must match the emitted shape", shipping an exception clause that misnames a key undercuts the change on its own terms. It is a small, contained edit — one sentence, no code, no test changes.

Verdict: 🟡 REQUEST CHANGES — fix finding #1; #2 is optional polish.


🤖 Generated with Claude Code

https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea

@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.

Round 4 re-review verdict: 🟡 REQUEST CHANGES (posted as a comment — GitHub rejects --request-changes on a self-authored PR).

All four round-3 findings are addressed, and I verified each independently rather than on trust: I enumerated the real key sets emitted by all four node_to_typed_value branches and piped those payloads through related_node_to_json. The CLI_KEYS allowlist is complete, the stored-value-wins precedence is the correct direction (it matches what node get reports, since promoted dueDate is lossily normalized while properties is verbatim), messages is correctly folded with no duplication, and the !contains_key("nodeType") discriminator is structurally sound — SchemaNode has no node_type field at all. The round-3 🔴 is genuinely fixed, and fixed structurally. Clippy clean, 52/52 CLI tests pass.

One blocking finding, in documentation rather than code:

🟡 packages/skill/references/cli.md:16-21 — the new schema exception clause says the payload comes back as (name, fields, relationships), but SchemaNode has no name field; that field belongs to SchemaField. The actual shape is id, content, version, createdAt, modifiedAt, isCore, schemaVersion, description, fields, relationships, uri. Two related details are also wrong in the same sentence: those keys are camelCase (the surrounding text says parse snake_case names 'and nothing else'), and uri survives on this one path because the early return precedes the uri drop.

That is the same defect class this PR exists to eliminate — a documented shape that does not match the emitted shape — so it should not ship in the commit that fixes the others. It is a one-sentence edit, no code or test changes.

🟢 Optional: title/mentions/mentioned_in are relationship get-only, since NodeData has no such proto fields. Passing them through is the right call; cli.md already discloses title and could mention the other two.

Full review with the verification tables: #2423 (comment)

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Round 4 feedback addressed — a3bba4d9

Good catch on the 🟡, and thank you for confirming the code by enumerating all four node_to_typed_value branches — that's the check I'd wanted and it's more thorough than my own probing.

🟡 The schema exception clause was wrong in three ways

You were right on every detail, and I verified each before rewriting:

  • name doesn't exist. SchemaNode has no such field — it belongs to SchemaField (schema.rs:124). My sentence invented a key.
  • camelCase, not snake_case. SchemaNode is rename_all = "camelCase", which contradicted the surrounding "parse against these names and nothing else."
  • uri survives. The passthrough returns before the uri drop, so it contradicted the function's own comment.

Rather than re-read the struct, I ran a real schema node through node_to_typed_value → related_node_to_json and wrote the clause from the actual output:

keys: [content, createdAt, description, fields, id, isCore, modifiedAt, relationships, schemaVersion, uri, version]
has node_type? false   has properties? false   has uri? true   has name? false

That's the sentence now in cli.md. Fitting that the fix for a docs-vs-reality bug had its own docs-vs-reality bug — the lesson I'm taking is to generate doc claims from output, not from struct definitions.

🟢 title/mentions/mentioned_in disclosed

Extended the doc to name all three. Also recorded in output.rs that two of them are forward-looking rather than live: every store construction site leaves mentions/mentioned_in as vec![] and both are skip_serializing_if = "Vec::is_empty", so only title occurs in practice. They stay in CLI_KEYS so that if the daemon ever populates them they remain top-level instead of being misfiled as stored properties — but the comment no longer implies they fire today.

Note on the pre-push gate

The first push attempt was blocked by watch-nodes.e2e.ts > delivers nodeCreated event timing out at 5s. I re-ran the suite four times before concluding anything: 26/26 every time, and the gate's own run passed on the successful push. It's a flake in an SSE stream this PR doesn't touch — the sibling nodeUpdated/nodeDeleted tests in the same file passed even on the failing run. Flagging it rather than burying it, since an intermittent e2e failure is worth someone's attention independently of this PR.

Verification

52 CLI unit + 29 integration tests, test:all green and matching baseline exactly (232 files / 4863 frontend, 0 new failures), skill:check up to date, quality:fix and clippy -D warnings clean. Worktree clean.

🤖 Generated with Claude Code

malibio and others added 6 commits September 7, 2026 20:38
Storage nests a node's properties under its schema id
(`{"task": {"status": "open"}}`), and the CLI was passing that shape
straight through `--json`. A consumer reading `.properties.status` got
`None` and could report "status unknown" about real data.

The nesting is a storage concern that was never meant to cross the API
boundary: `flatten_properties_for_api` in nodespace-types already defines
the flat contract the frontend receives, and `output.rs`'s own comments
promise `jq '.properties.foo'` works without a second parse. Writes
(`--property status=…`) and filters (`{"property":"status"}`) already take
bare field names, so only reads leaked.

Flatten in `output.rs`, which every node-emitting command funnels through
(`node get`, `query`, `search`, `schema`, and the batch path), covering
both `--json` and human-readable output. `_`-prefixed internals
(`_schema_version`, sibling namespaces like `_seed`) and dormant
namespaces from a previous type change are dropped, matching the frontend.

The logic is mirrored rather than reused because the CLI only ever holds
the gRPC `NodeData`, whose `properties` is a JSON-encoded string, while
the canonical helper takes a `Node`.

Storage is unchanged — a seeded node's `_seed` and `skill` namespaces
coexist at rest, which a flat bag could not represent.

Docs: SKILL.md's node example showed `"properties": {}`, which reads as a
flat bag and taught the wrong shape; it now shows populated flat
properties. references/cli.md documented only that `--json` exists, so it
now specifies the node shape. Its "namespace prefixes" note conflated
schema-authoring field prefixes with runtime nesting and is clarified.

scripts/eval unwraps the nested shape defensively; that is now a no-op
against a current build but is kept and documented, since NS_BIN is
overridable and defaults to a prebuilt binary that can predate this change.

Tests: six unit tests over the flattening rules, plus an end-to-end
integration test asserting storage stays nested while CLI output is flat,
for a core type and a user-defined type.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
The fallback branch drops nested objects because, with no namespace for
the node's type, a nested object can only be another type's namespace.
Inside the type namespace the opposite holds: an object there is a real
schema-defined field value (schemas support "object" fields) and must
survive intact. The primary branch already did this; the case was untested.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
Review of #2423 found the change incomplete in two places.

`relationship get` still leaked `properties.<schema-id>.<field>`. My claim
that output.rs is the funnel every node-emitting command passes through was
wrong: this path prints `related_nodes_json`, which rel_ops.rs builds with a
plain `to_value(Node)` — properties exactly as stored. It is a documented
read path that SKILL.md recommends as the follow-up to `query`, so an agent
following the skill's own advice landed on the one command still leaking.
Fixed at the source via `nodes_to_typed_values`, which fixes every consumer
of GetRelatedNodes rather than just the CLI, and pinned by a new test.

The flattening logic was duplicated between output.rs and convert.rs, whose
own docs declare it the "SOLE authority ... Do NOT re-implement". The two
agreed, but nothing kept them in step and divergence would surface as a
wrong answer rather than a red test. Extracted the rule as
`flatten_namespaced_properties` in nodespace-types; both callers now share
one body while keeping their own input types (Node vs the CLI's
JSON-encoded string).

Also from the review:
- cli.md claimed properties are complete, which the write path cannot
  deliver: create_node only resolves schema fields for `task`, so for other
  types `normalize_flat_properties_to_namespace` misclassifies an
  object-valued property as a namespace and hoists it out of the type key,
  where the flattener never looks. That is a pre-existing write-path bug
  (already documented at skill_pipeline.rs:482) and out of scope here, but
  the docs must not promise what it breaks — noted the gap instead.
- Replaced the enumerated command list with the general rule; it was
  already missing `node children`, `node batch-get` and `node set-status`.
- Repointed a duplicate-fixture test at the untested fallback branch.
- Explained the unreachable match arm in `has_properties`.

Kept `flattenTypeKeyedProperties` in scripts/eval — the review agreed the
stale-NS_BIN argument holds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
Round 2 fixed the last leaking command and then, in the same commit, made
two documentation claims that the code does not satisfy — the same failure
mode this PR exists to eliminate. Both are now fixed properly rather than
documented around.

`relationship get` emitted a different node shape from every other command.
Routing it through `nodes_to_typed_values` removed the property nesting but
left the frontend's wire shape: camelCase keys, an injected `uri`, and
promoted type fields. So a consumer had to know which command it called
before it could read `node_type` — two shapes on one surface, which is the
same defect as two property layouts. The CLI now re-keys these nodes into
its own snake_case shape (`output::related_node_to_json`), dropping the
`uri` and the promoted duplicates that `properties` already carries.
`schema` nodes pass through untouched: `SchemaNode::from_node` has already
dropped `nodeType`/`title`/`properties`, and a half-mapped node that looks
like the CLI shape but is missing its fields would be worse than an honest
passthrough. The generalized "every command that emits a node" sentence is
therefore true again.

The object-valued-property caveat was scoped wrong. It named `task` as safe,
but both `node update` call sites (crud.rs:649, :779) pass `None` for schema
fields regardless of type, so an object property is hoisted out of the type
namespace for `task` too — and it is CLI-reachable, since `parse_property`
JSON-parses the value. An agent told tasks were safe and then losing one
would be worse off than with no caveat at all. Now scoped to what actually
breaks: update for every type, create for every type but `task`.

Also from the review:
- Expanded the rel_ops.rs comment to name the promotion, the `schema`
  reshape and the `uri`, so nobody "simplifies" it back to a plain
  `to_value` on the assumption the shapes are equivalent.
- Fixed a pre-existing bug found next door: the agent's get_related_nodes
  tool read `node_type`, but `Node` serializes camelCase, so that lookup
  never matched and every node's type was reported to the model as empty.
- Noted nodespace-cli as a third consumer in the nodespace-types crate doc,
  and recorded that the flattening rule governs human-readable CLI output
  too, since both modes share one call into it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
Round 3's re-keying dropped promoted typed fields on the assumption that
`properties` always carries the same value. It does not: `status` is not an
`Option` on `TaskNode`, so `task_node_to_value` synthesizes it via
`unwrap_or_default()` and serializes "open" even when nothing was stored.
Dropping it lost the field outright — `relationship get` reported no status
where `node get` reported "open". The other five promoted fields are
`skip_serializing_if = "Option::is_none"` and so were safe, which is why
this hid behind them.

Promoted fields are now folded back under `properties`, with a stored value
winning over the promoted copy. That keeps one shape without discarding
anything, and generalizes past the hardcoded key list: `ai-chat`'s
`provider`/`model`/`messages` were also passing through duplicated at the
top level.

The rename list was checked against the structs rather than guessed.
`parentId`/`rootId`/`beforeSiblingId` are fields of no node shape and could
never fire; `mentionedIn` is real and was missing, so it survived as the one
camelCase key in an otherwise snake_case object.

The `schema` passthrough now keys off the ABSENCE of `nodeType`, which every
node shape carries and `SchemaNode` does not. Keying off `fields` was
discriminating on a coincidence — `fields` is not a reserved property name,
so a user-defined type may declare one.

Documented the one real exception to the uniform shape: a `schema` node
reached through `relationship get` comes back in the schema's own shape, and
`schema get` is the right way to read schemas.

Tests: the bare-status task that broke, `mentionedIn` re-keying, and a user
type with a `fields` property that must still be re-keyed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
The exception clause added last round got three details wrong while fixing a
fourth. It named a `name` key that does not exist — `SchemaNode` has no such
field; `name` belongs to `SchemaField`. It implied snake_case, but
`SchemaNode` is `rename_all = "camelCase"`. And it omitted that `uri`
survives on this path, because the passthrough returns before the `uri` drop.

Every claim in the replacement was checked against real output from
`node_to_typed_value` piped through `related_node_to_json`, rather than read
off the struct: keys are `isCore`, `schemaVersion`, `description`, `fields`,
`relationships` plus `uri`, with no `node_type` and no `properties`.

Also disclosed `mentions`/`mentioned_in` alongside `title` as keys
`relationship get` may carry that `node_get` cannot, since `NodeData` has no
such fields.

Recorded in `output.rs` that those three entries in `CLI_KEYS` are
forward-looking rather than live: every store construction site leaves
`mentions`/`mentioned_in` empty and both are
`skip_serializing_if = "Vec::is_empty"`, so only `title` occurs in practice.
They stay listed so that if the daemon ever populates them they remain
top-level instead of being misfiled as stored properties.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018rQHweNGgEiuYpA5NZNwea
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.

CLI --json leaks the nested storage shape instead of the flat API shape the flattener already defines

1 participant