Skip to content

Add the core node type registry, shared envelope, closed schemas and extends-aware rules - #3462

Merged
malibio merged 1 commit into
mainfrom
issue-3439-core-node-type-registry
Oct 1, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-3439-core-node-type-registry

Conversation

@malibio

@malibio malibio commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #3439.

Lays the foundation of ADR-086: one registry of core types, one envelope on every wire shape, a type-ancestry table so SQL can apply a base type's rule to its subtypes, abstract types, closed core schemas, a closed field-type vocabulary, and the UUID id rule. The sibling ADR-086 issues build on this.

Kind and category

No new node type. This changes how every core type is registered and validated. The registry (CoreNodeType, packages/nodespace-types/src/core_type.rs) records for each of the 21 core types that exist today: parent, abstract flag, category, content role, structural rules, participation rules, titling, and wire shape.

  • Primitive: text, header, code-block, quote-block, ordered-list, checkbox, horizontal-line, table, date, agent-guidance
  • Flat: task, project, person, collection, skill, database-settings
  • Structured: query, schema, play, ai-chat, tool

ai-chat and tool are registered as they are stored today (concrete, and ai-chat structured because of messages[]). #3446, #3448 and #3450 make them abstract bases, add their subtypes and ai-chat-message, and move them to their final categories; the registry tests fail until each layer follows.

What changed

Registry and envelope (nodespace-types)

  • CoreNodeType with from_id, nearest(chain), is_a, is_exactly, and the per-type record.
  • NodeEnvelope: the generic Node is the envelope, and TaskNode, PersonNode, ProjectNode, QueryNode, AiChatNode and SchemaNode embed it. lifecycleStatus is always serialized.
  • node_to_typed_value, the promoted-field lists and typed_update_fields match on CoreNodeType with no catch-all for core types.
  • SchemaFieldType is a closed enum (text, number, boolean, date, datetime, enum, array, object) for SchemaField.type and itemType. string is refused with a message naming text. Edge-field types are unchanged.
  • The wire SchemaNode carries abstract and extends.

Type-ancestry table (core/src/db/schema.rs)

  • type_ancestry(node_type, ancestor, depth), one row per (type, ancestor) pair including the type itself.
  • Maintained by SQL triggers on schema-node and extends-edge writes, so it is updated inside the transaction that writes the schema, on every write path. Core types' rows are seeded from the registry.
  • The root-only triggers are generated from the registry's MustBeRoot types and resolve through the table, so a subtype of collection is root-only.
  • The task/project indexes are partial on the value being present rather than on node_type, so they cover subtypes and stay sparse.
  • resolve_type_chain reads the table, so there is one chain resolver.

Chain-aware rules

  • Behaviours compose through the chain, base first; a subtype's behaviour adds and cannot replace. Registering a behaviour for a core type is refused.
  • Embedding, the always-titled rule, the title template, the @ picker's exclusions, collection lookups and membership, the person membership exemption, ai-chat reference and retype guards, the settings singleton, play validation and play events all resolve through the chain.
  • scripts/check-node-type-literals.ts fails the push check and test:scripts on a literal node_type comparison in Rust, SQL or TypeScript outside tests.

Abstract types

  • abstract on a schema (create and update). Create and retype into an abstract type are refused in the service on every create path; a query for one returns its subtypes. A type with nodes of its own cannot become abstract.

The registry is the authority for core types

  • A user schema cannot take a core type's name, and a core schema's extends and abstract cannot be changed through the schema API, so the ancestry table and the registry cannot disagree.
  • A type cannot be re-targeted under a root-only base while any of its nodes has a parent.

Closed core schemas

Typed clients

  • UpdateNodeRequest.typed_client. The Tauri update_node command and the dev-proxy set it; the daemon then refuses a generic patch naming a field of a core type that has a typed update (task, person, project, query). The CLI and agent leave it unset and are validated by the same pipeline.

Ids

  • Every create path refuses a non-UUID id except a date node's date, a schema's type name and database-settings-singleton.
  • The seeded core play and the bundled playbooks' plays and views have fixed literal UUIDs. A re-keyed play or view gets a UUID derived from its preferred id.

Frontend

  • NodeEnvelope is the base interface with a required lifecycleStatus; every typed node interface extends it.
  • core-node-types.ts mirrors the registry and is pinned to the Rust source by a test. isA resolves user subtypes through the loaded schemas' extends.
  • Core plugins are checked against the registry. The unregistered user and document plugin definitions are removed.

Left exact on purpose

is_exactly / isExactly remain where a subtype must not match, or where resolving the chain was out of reach:

  • the schema meta-type everywhere (nothing can extend it);
  • wire-shape conversion and the frontend's typed-node guards (a subtype is never converted to its base's struct);
  • the id forms for date and schema;
  • markdown import (the parser decides the type) and markdown export / search-snippet rendering, which render a subtype as plain content;
  • Priority::applies_to, which ranks priority only for a query targeting exactly task or project. A query over a subtype sorts priority as text; the query service's sort reads each row's own bucket, so ranking a subtype needs that sort made chain-aware first;
  • the agent loop's ai-chat watcher (local_agent_service.rs), which reacts to exactly ai-chat until Split ai-chat into an abstract base with ai-chat-native and ai-chat-pty subtypes #3446 adds the subtypes;
  • the frontend plugin registry, which resolves a node's component by exact type, so a user subtype of task renders with the generic component.

Not in this PR

Database

The on-disk shape changes (new table, new triggers, changed indexes, text instead of string in stored schemas, UUID ids for seeded plays). Reset the database.

Testing

  • bun run test:changed (all tiers; this diff touches the gate).
  • New: registry tests against the seeded schemas and behaviours, ancestry-table trigger tests (add, remove, re-target, rollback, delete), 18 end-to-end tests in core_type_registry_test.rs, a daemon RPC test for the typed-client flag, the lint's own tests, and the frontend registry and plugin tests.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3462

Review Type: Initial Review
Reviewed at: 77b5b778 (254 files, +9511 / -2648)
Recommendation: REQUEST CHANGES

Summary

The foundation is sound and a clear net improvement: one registry, one envelope, an ancestry table kept by triggers inside the writing statement, composed behaviours, closed core buckets, a closed field-type enum and the UUID id rule. The trigger algebra is correct for a single-parent tree (I replayed add, remove, re-target, mid-chain delete with cascade, and an INSERT OR IGNORE outer statement in SQLite), the wire conversion is exhaustive over the registry, and the new tests are substantive rather than vacuous.

One finding blocks: closing the ai-chat bucket was not followed through for the four capture:* keys that production code still writes, so PTY session capture stops working on this branch. The rest are guards the new SQL-level rules now need, two rules that still compare exactly, and cleanup.

How I verified: read every production file in the diff; ran the lint (✓ No literal node-type comparisons); replayed the trigger and index SQL in a scratch SQLite database. I did not run the Rust or frontend suites and did not add tests, so each finding states whether it was executed or read.


Requirements Check (issue #3439)

# Criterion Status Notes
1 NodeEnvelope in nodespace-types; Node and every typed struct embed it; lifecycle_status always serialized ✅ Node is an alias of the envelope; Task/Person/Project/Query/AiChat/Schema structs flatten it. Typed shapes now carry title, mentions, mentionedIn.
2 CoreNodeType covers every core type, core subtype and abstract base; registry tests pass ✅ (partial by design) 21 types as stored today. No core subtype or abstract base exists yet (ai-chat, tool registered concrete); the PR defers them to #3446/#3448/#3450. Seeded schemas == registry, behaviour ⇔ schema, category ⇔ fields, exhaustive matches and plugins ⊆ registry are all tested.
3 Rule resolution follows extends (task subtype validated/embedded as task; collection subtype root-only) ✅ Tested end to end. Two rules still compare exactly (finding 5).
4 No literal node_type comparison applies a type's rule; a lint enforces it ⚠️ Lint exists, is wired into the push check and test:scripts, and passes. It does not see comparisons against a type-name constant, and two of those apply a rule (finding 5).
5 Ancestry table maintained transactionally with schema writes ✅ Trigger-maintained; add/remove/re-target/rollback/delete tested at the DDL level. Two ways to make it wrong through the schema API (findings 3, 4).
6 Create or retype into an abstract type refused on every surface ✅ Single, with-parent, bulk, hierarchy, trusted import, in-tx and all four update paths go through ensure_creatable / ensure_retype_allowed.
7 Undeclared key in a core bucket rejected; custom: and _ accepted; nested item_fields validated ❌ The rule and its tests are right. The declare-or-delete pass missed capture:agent_type, capture:started_at, capture:ended_at, capture:exit_code (finding 1).
8 Typed client's generic update naming a core field rejected; CLI flat update succeeds ✅ Daemon RPC test covers both, plus the vocabulary check on the flat path.
9 SchemaField.type is a closed enum; string rejected ✅ With a message that names text. Edge-field type is still an open String.
10 Follows the node type sequence; node-types.md sheets updated in the same PR ⚠️ Docs untouched by intent. The code now declares fields the sheets do not have (skill.node_types, tool.source, tool.handler on the base), so "nothing here departs from it" in the PR description is not accurate (finding 2).
11 bun run test:changed passes; quality:fix clean ✅ As reported by the author; not re-run here.
12 Create path rejects a non-UUID id except the three named forms; test per form plus a rejected slug ✅ ensure_valid_node_id, reached by every service create path.

Code Review Findings

🔴 Critical

1. PTY session capture is rejected by the closed ai-chat bucket
📁 packages/daemon/src/services/capture_service.rs:133-140, packages/desktop-app/src/lib/components/viewers/ai-chat-pty-session.svelte:230-246, packages/core/src/models/core_schemas.rs:985-1033, packages/core/src/services/node_service/crud.rs:2655

  • Problem: The ai-chat schema declares capture:session_id, capture:transcript and capture:summary. Production code also writes capture:agent_type, capture:started_at, capture:ended_at and capture:exit_code. capture: is not one of the extension prefixes (custom:, org:, plugin:), so reject_undeclared_core_keys now refuses the whole patch.
  • Failing scenario: (a) Launch a PTY chat: the viewer's write of capture:agent_type + capture:session_id + session_status is refused, so the node never records the session and the store raises a write failure. (b) Session ends: finalize_capture → update_node_unchecked → normalize_flat_properties_to_namespace puts the keys in the ai-chat bucket → rebucket_and_validate → 'capture:agent_type' is not a field of the core type 'ai-chat'. The error is logged and swallowed, so transcript, summary and session_status: archived are silently lost.
  • Confidence: High. Traced through the three functions; not executed. No test reaches the service with these keys (capture_service tests only cover build_capture_properties), which is why the suite is green.
  • Recommendation: Make the declare-or-delete decision for the four keys in this PR. The smallest change consistent with ADR-088 is to drop capture:started_at / capture:ended_at (the ADR removes them as duplicates of created_at / last_active) and declare capture:agent_type and capture:exit_code until the ai-chat issue renames them. Add one test that runs finalize_capture against a real NodeService.
  • Principle: A constraint introduced in a PR must be satisfied by every existing writer in the same PR (ADR-086 names these four keys as the motivating case).

2. skill.node_types is declared as a field: ids stored where a relationship belongs (reviewer checklist item)
📁 packages/core/src/models/core_schemas.rs:1494-1512

  • Problem: The new field holds "schema ids this skill is scoped to". node-types.md gives skill four fields and models this as the applies_to → schema relationship; the node type sequence lists both "stores a list of node ids where a relationship belongs" and "changes a type without updating its sheet" as reject criteria. tool.source (ADR-086 §12 removes it) and tool.handler on the base type are the same kind of departure.
  • Context: The data pre-exists; this PR only declares it so the closed schema accepts it. That is a reasonable interim, but it is a new declared shape, and the PR description says nothing departs from the sheets.
  • Recommendation: Either convert to applies_to here, or keep the interim declaration and say so explicitly: name the issues that remove skill.node_types and tool.source in the PR description, and correct its "nothing here departs from it" line, so the next reader does not take the declaration as the decided design. This one needs a decision from Michael more than a code change.
  • Principle: One source of truth per type; a relationship is a declared edge, not a list of ids.

🟡 Important

3. The schema meta-type's ancestry row can be deleted through the schema API
📁 packages/core/src/db/schema.rs:541-545, 566-568; packages/core/src/schema/mod.rs:1859 (no reserved-name check)

  • Problem: schema is the one core type with no schema node, so its (schema, schema, 0) row comes only from bootstrap seeding. create_schema {name: "Schema"} normalizes to id schema; deleting that user schema fires type_ancestry_schema_delete, which removes the row. Until the next process start re-seeds it, everything that resolves schema through the table stops matching: the schema_is_root_* triggers, the @ picker exclusion (is_not_a_sql(not_mentionable)) and the title-search exclusion.
  • Confidence: SQL behaviour executed in a scratch database with the PR's trigger bodies (row count goes 1 → 0, a has_child edge onto a schema node is then accepted, and schema nodes pass the mention filter). That the service accepts the name Schema is from reading: I found no reserved-id check. The service-level root-only check still holds, because Rust answers from the registry.
  • Recommendation: Refuse a user schema whose id is a CoreNodeType id (one check in handle_create_schema), and make the delete trigger skip registry-seeded pairs, or guard with WHEN old.id NOT IN (<core ids>).
  • Principle: Derived data must not be destroyable by a legal user action.

4. A core schema can gain extends or abstract through update_schema, and SQL then disagrees with Rust
📁 packages/core/src/schema/mod.rs:3021-3023, 3116-3133; packages/core/src/db/sqlite_store/type_ancestry.rs:17-26, 147-165

  • Problem: core_chain answers from the registry with the comment "nothing can make a core type extend anything else", but nothing enforces it: update_schema validates only existence, cycles and field/relationship redeclaration. update_schema {schema_id: "text", extends: "collection"} passes those (text declares no fields), the extends trigger writes (text, collection, 1), and the root-only trigger then refuses every has_child edge onto a text node while the @ picker drops every text node. Rust still says text is only text. Likewise update_schema {schema_id: "query", abstract: true} on a database with no saved query makes query uncreatable, because is_abstract_type falls through to the stored flag whenever the registry says "not abstract".
  • Confidence: Medium-high, from reading; not executed. The agent can call update_schema with arbitrary arguments, so this is reachable without malice.
  • Recommendation: In handle_update_schema, refuse extends and abstract when schema.is_core. In is_abstract_type, return the registry's answer for any core type instead of falling through.
  • Principle: The registry is the single authority for core types; SQL and Rust must not be able to diverge.

5. Two rules still compare exactly, through a constant the lint cannot see
📁 packages/core/src/db/sqlite_store/relationships.rs:1617, packages/core/src/schema/mod.rs:412, scripts/check-node-type-literals.ts:56-83

  • Problem: bulk_create_mentions drops ai-chat targets with node_type == crate::models::AI_CHAT_NODE_TYPE, while its single-edge counterpart refuse_ai_chat_target was made chain-aware in this PR. A node of a type extending ai-chat can therefore be mentioned through the bulk path and not through the single one. schema/mod.rs:412 has the same exact comparison for a relationship's targetType. Both become live the moment ai-chat-native / ai-chat-pty land.
  • Lint gap: the patterns catch a quoted literal, matches! and SQL, but not a comparison against a *_NODE_TYPE constant, a match arm on a type string, or [...].contains(&node_type). query.rs:221, skill.rs:78 and ai_chat_node.rs:334 are exact for a legitimate reason (wire shape) but also bypass the "every exact comparison is greppable through is_exactly" convention the script's header states.
  • Confidence: High (read; grep confirms the four sites).
  • Recommendation: Resolve the two rule sites through the ancestry table (is_a_sql in the bulk query; type_is_a in the schema check), switch the three wire-shape checks to is_exactly, and add a constant pattern (node_type\s*(==|!=)\s*[\w:]*_NODE_TYPE) with a test case. Deleting the three *_NODE_TYPE constants in favour of CoreNodeType::X.as_str() would remove the blind spot at the source.
  • Principle: ADR-086 §5; a guard that two paths share must not be implemented twice.

6. ensure_instantiable costs one SQL read per created node, core types included
📁 packages/core/src/db/sqlite_store/type_ancestry.rs:147-165, packages/core/src/services/node_service/bulk.rs:150, 583, 716

  • Problem: is_abstract_type short-circuits only when the registry says abstract; for every concrete core type it goes on to query the schema node. ensure_creatable runs per row in bulk_create, bulk_create_hierarchy and the trusted markdown import, so a 50k-node import does 50k extra point reads on the read connection. The same loops already cache collection_types and embeddable_types per distinct type.
  • Recommendation: Answer from the registry for core types (this is also the fix for finding 4), and cache per distinct node_type in the three bulk loops.
  • Principle: No N+1 on a bulk path.

7. Legacy camelCase spellings are still read, and can no longer be stored
📁 packages/nodespace-types/src/convert.rs:282-292, 333-348; mirrored in packages/desktop-app/src/lib/services/node-normalize.ts:175-183

  • Problem: task_node_to_value reads dueDate / startedAt / completedAt before the declared snake_case keys, and without_promoted strips "the legacy dueDate". With the task bucket closed, a dueDate key is rejected on write, so these reads are compatibility code for a shape that cannot exist. Pre-existing, but this PR edits both functions and is what makes them dead.
  • Recommendation: Delete the fallback reads and the second remove, and the matching branch in node-normalize.ts.
  • Principle: CLAUDE.md, no compatibility code for an older shape.

8. Re-targeting a type under a root-only base does not check existing nodes
📁 packages/core/src/schema/mod.rs:3021-3050

  • Problem: A user type with nodes nested under parents can be given extends: collection. The ancestry row lands, and those nodes are now collections with parents, which the triggers would have refused one at a time. ADR-089 requires a check when a rule is tightened. Executed at the SQL level (the nested node survives the extends insert).
  • Recommendation: When the new parent chain contains a MustBeRoot type, refuse if any node of the type (or a subtype) has a has_child parent; assert_may_gain_parent's query is close to what is needed. If this belongs to the structural-rules issue, say so there, since this PR is what makes user subtypes root-only.

🟢 Suggestions

9. The task/project expression indexes now index every row — 📁 packages/core/src/db/schema.rs:68-77. Dropping WHERE node_type = ... is right for subtypes, but each of the six indexes now holds a NULL entry per node of every type. WHERE json_extract(properties, '$.task.status') IS NOT NULL keeps them sparse and subtype-aware; SQLite 3.54 uses such an index for both = ? and IN (...) with the ancestry subquery (checked with EXPLAIN QUERY PLAN). Worth confirming under libsql's planner before adopting.

10. Two chain resolvers, and _in_tx twins that the in-tx paths do not use — 📁 packages/core/src/db/sqlite_store/type_ancestry.rs:45-78. resolve_type_chain walks the extends edges and type_chain reads the table; both stay. Pick one. Separately, create_node_in_tx / update_node_in_tx call ensure_creatable and validate_behaviors, which read through self.read() rather than the transaction, so a schema or extends edge written earlier in the same transaction is not seen. That matches the existing resolve_field_owners behaviour, but the twins exist and the transaction is in hand.

11. Exact comparisons to revisit when the ai-chat and tool subtypes land — Priority::applies_to (models/priority.rs:72: a query over a task subtype sorts priority lexically, not by rank), local_agent_service.rs:658 (the agent loop reacts only to exactly ai-chat), markdown export and search-snippet rendering. The PR description lists most of these as deliberate; Priority is the one that is a rule rather than a rendering.

12. Test gaps — no service-level test that re-targets or deletes a schema through update_schema / delete and then reads type_chain (the trigger tests use hand-written inserts); no lint test for a constant comparison.

Nits

  • Nit: packages/core/src/behaviors/mod.rs:665 — validate_task_node is now a no-op called only by its own test; delete both.
  • Nit: packages/desktop-app/src/lib/types/core-node-types.ts:114 — isA(nodeType, base: string) accepts a typo such as 'colection'; an overload taking CoreNodeTypeId would catch it.
  • Nit: packages/core/src/methodology/install.rs:311-314 — the NAMESPACE_OID fallback maps every non-UUID preferred id to the same derived id per attempt; every preferred id is now a UUID, so return an error instead.
  • Nit: packages/nodespace-types/src/core_type.rs — the registry records ANY structure for date and for the children: none types; the PR description says the rules beyond root-only are "recorded in the registry". They are not yet.
  • Nit: packages/core/src/ops/entity_types_block.rs:386, packages/core/src/schema/mod.rs:2925 — doc comments rewritten by search-and-replace now read field_type == crate::models::SchemaFieldType::Enum mid-sentence.
  • Nit: packages/nodespace-types/src/schema.rs:312 — EdgeField.type is still a free String and accepts string; ADR-086 §7a describes one vocabulary.

What is solid

  • Trigger maintenance is exact for add, remove, in-place re-target and cascaded delete, and it runs inside the writing statement, so no write path can leave the table behind.
  • node_to_typed_value, core_promoted_fields and typed_update_fields have no catch-all over core types; adding a variant fails to compile until each is answered.
  • Behaviour composition is base-first and additive, a core behaviour cannot be replaced, and a_core_type_is_embedded_exactly_when_the_registry_says_so ties the registry's participation flags to what the behaviours actually do.
  • ensure_creatable gives every create path the same four checks in one place.
  • The typed-client rule is checked against the type the node will have after a retype, and both spellings of a field.

Recommendation

REQUEST CHANGES. Finding 1 is a functional regression and must be fixed before merge. Finding 2 needs an explicit decision. Findings 3 to 7 are small, local and best folded into this PR; 8 can move to the structural-rules issue if it is named there.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). One blocking finding: the closed ai-chat bucket rejects the four undeclared capture keys that PTY launch and session capture still write. One checklist finding needs a decision (skill.node_types declared as a list of schema ids). Full findings in the review comment above: #3462 (comment)

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (through de0c21c2)

Fixes are in the "Address review" commit plus a merge of current main. bun run test:changed passes on the merged tree (all tiers), quality:fix is clean.

Addressed

# Finding What changed
1 🔴 PTY capture refused by the closed ai-chat bucket capture:agent_type and capture:exit_code are declared on ai-chat. capture:started_at / capture:ended_at are no longer written (duplicates of created_at / last_active, as ADR-088 says). New tests: every key build_capture_properties writes is declared by the schema, and finalize_capture backfills a real node through NodeService.
2 🔴 skill.node_types, tool.source, tool.handler declared against the sheets Kept as interim declarations (the alternative is deleting data existing code reads, or doing #3418 / #3450 here). The PR description now lists them, names the issue that removes each, and no longer says nothing departs from the sheets. This one is Michael's call; flagged to him.
3 🟡 schema ancestry row deletable through the schema API create_schema refuses a name that normalizes to a core type id. The delete and retype-out triggers skip core ids. Trigger test and service test added.
4 🟡 Core schema could gain extends / abstract update_schema refuses both on a core schema. is_abstract_type answers from the registry for a core type. Test added.
5 🟡 Two rules compared exactly through a constant bulk_create_mentions resolves chat endpoints with is_a_sql; the relationship-target check uses type_is_a. The three wire-shape checks use is_exactly. The lint has a constantComparison pattern with tests. Test: a subtype of ai-chat is refused as a relationship target and dropped by the bulk mention path.
6 🟡 One read per created node Covered by #4 for core types; ensure_creatable_in_batch caches the instantiable check and the chain per distinct type in the three bulk loops.
7 🟡 Legacy camelCase reads Removed from task_node_to_value and without_promoted, and from the frontend mirror in node-normalize.ts; tests updated.
8 🟡 Re-target under a root-only base update_schema refuses it while any node of the type (or a subtype) has a has_child parent. Test added.
9 🟢 Indexes hold a NULL per node Now partial on the value being present. The existing planner test (schema_test.rs) still passes under libsql.
10 🟢 Two chain resolvers resolve_type_chain and the batch resolver read the ancestry table.
12 🟢 Test gaps Service-level re-target and schema-delete test reading type_chain; lint tests for constant comparisons.
Nits validate_task_node and its test deleted; the re-key no longer falls back to a shared namespace (a non-UUID preferred id fails the step); the three search-and-replace doc comments fixed; PR description corrected on what the registry records.

Not changed

  • No compilation errors or warnings #10, in-transaction reads. ensure_creatable and validate_behaviors still read through the pooled reader inside a transaction. That matches resolve_field_owners on the same paths; switching one of them would make the two disagree about what a transaction sees. Worth doing for both together.
  • Set up Tauri + Svelte project structure #11, Priority::applies_to. Still exact. The query service's sort reads each row's own bucket, so ranking a subtype's inherited priority needs that sort made chain-aware first. Listed in the PR description under "Left exact on purpose", with the agent loop's ai-chat watcher.
  • Nit, isA(nodeType, base: string). Left as string: a user-defined type id is a legitimate base.
  • Nit, EdgeField.type. Left open. The schema-management doc gives edge fields a separate, narrower set, and nothing validates their scalar types today.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: A critical fix, new guards in the schema API and DDL triggers, a changed index definition and a changed chain resolver.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3462

Review Type: Re-Review
Reviewed: 77b5b778..de0c21c2 (the "Address review" commit a64a02f7 and the merge of main, including the query_ops.rs conflict resolution)
Recommendation: APPROVE

Previous Review Summary

Count
Previous recommendations 12 findings + 6 nits
Addressed in code 10 findings (1, 3, 4, 5, 6, 7, 8, 9, 10 in part, 12) + 4 nits
Addressed by an explicit, documented decision 1 (finding 2; awaits Michael)
Deliberately not changed, with a reason I accept 1 finding (11), the in-transaction half of 10, 2 nits
New issues 1 Important, 2 nits

How I verified: read every hunk of a64a02f7 and the merge resolution against the code, not the summary; ran the lint (✓ No literal node-type comparisons); replayed the new trigger guard and the partial indexes in a scratch SQLite database (bound-parameter =, !=, range and ORDER BY plans). I did not re-run the Rust or frontend suites.


Status of previous findings

# Finding Status Verified
1 🔴 PTY capture refused by the closed ai-chat bucket ✅ Fixed capture:agent_type (text) and capture:exit_code (number; ExitStatus.code is a u32) are declared; started_at / ended_at are no longer written. every_capture_key_is_declared_by_the_ai_chat_schema guards the key set, and finalize_capture_backfills_a_real_ai_chat_node runs the real path through NodeService. The viewer's launch write uses only declared keys.
2 🔴 skill.node_types, tool.source, tool.handler declared against the sheets ⚠️ Decision recorded, not a code change The PR description now lists each interim declaration with the issue that removes it (#3418, #3450, #3446) and no longer claims nothing departs from the sheets. That is the second option I offered. It still needs Michael's sign-off; I no longer treat it as blocking.
3 🟡 schema ancestry row deletable ✅ Fixed handle_create_schema refuses an id that is a CoreNodeType id, before any write. The delete and retype-out triggers carry old.id NOT IN (<core ids>). Replayed: deleting a schema node named schema leaves (schema, schema, 0); deleting an ordinary schema still drops its rows. DDL test and service test added.
4 🟡 Core schema could gain extends / abstract ✅ Fixed (see new finding N1 for where the check sits) update_schema refuses both on schema.is_core; is_abstract_type returns the registry's answer for any core type. Tested for text extends collection and query abstract.
5 🟡 Two rules compared exactly through a constant ✅ Fixed bulk_create_mentions selects node_type IN (ancestry subquery) as an integer column and reads it as i64; validate_relationship_targets uses type_is_a. The three wire-shape checks use is_exactly. The lint's constantComparison pattern covers both operand orders, with tests. a_subtype_of_ai_chat_cannot_be_referenced covers the declaration, the single edge and the bulk path.
6 🟡 One read per created node ✅ Fixed Core types need no read. ensure_creatable_in_batch resolves the instantiable check and the chain once per distinct type in all three bulk loops; the single-node path delegates to it.
7 🟡 Legacy camelCase reads ✅ Fixed Removed from task_node_to_value, without_promoted and node-normalize.ts; the Rust and TypeScript sides still mirror each other, and the tests were rewritten rather than deleted.
8 🟡 Re-target under a root-only base ✅ Fixed (see N1) has_parented_nodes_of_type covers the type and its subtypes; the test checks both the refusal and that an all-roots type may still take the base.
9 🟢 Indexes hold a NULL per node ✅ Adopted All six are partial on the leading expression being present. The planner uses them for = ?, != ? and a range with a bound parameter.
10 🟢 Two chain resolvers; in-tx reads ✅ / not changed resolve_type_chain(s)_from_store now read the ancestry table. The in-transaction reads are left as they are; the reason given (changing one of two readers on the same path would make them disagree) is sound.
11 🟢 Exact comparisons to revisit Not changed Listed under "Left exact on purpose" with the reason for Priority::applies_to. Fine for this PR.
12 🟢 Test gaps ✅ Fixed Service-level re-target and delete test; lint tests for constants.
Nits 4 fixed, 2 declined validate_task_node deleted; the re-key fails the step for a non-UUID id; the three comments fixed; PR description corrected. isA(base: string) and EdgeField.type left, with reasons I accept.

The merge of main is clean: the query_ops.rs resolution keeps main's completed status and uses one consistent UUID for the fixture node in both places it is named.


New findings

🟡 Important

N1. The new refusals in update_schema run after Phase 1 has committed renames
📁 packages/core/src/schema/mod.rs:3043-3048 (core extends / abstract refusal), 3052-3084 (root-only re-target check); Phase 1 is 2722-2790

  • Problem: handle_update_schema commits each rename_fields entry as it goes in Phase 1, migrating node data, and the function is explicit that validation must therefore run in Phase 0 (the comment at 2494-2527 explains why validate_extends_target is hoisted there when renames are present). Both new checks sit in the Phase 2 block.
  • Failing scenario: update_schema {schema_id: "task", rename_fields: [{from: "custom:a", to: "custom:b"}], abstract: true} renames the field and rewrites every task's bucket, then returns "'task' is a core type; ...". Likewise {schema_id: "folder", rename_fields: [...], extends: "collection"} with a nested folder commits the rename and then refuses with "always a root". The caller sees an error for a call that was half applied.
  • Confidence: High from reading the phase order; not executed. The existing "cannot become abstract: nodes of that type exist" check (3177-3196, from the first round) has the same placement.
  • Recommendation: Move the three checks into Phase 0, next to the hoisted validate_extends_target; schema_before.is_core is already loaded there and none of them depends on Phase 1's result. A test that sends a rename with a refused abstract and asserts the field name is unchanged would pin it.
  • Principle: Validate before the first write; an error must mean nothing happened.
  • Why this does not block: it needs a refused change combined with a rename in one call, the refusal itself is correct, and the fix is a move, not a redesign.

Nits

  • Nit: packages/core/tests/it/core_type_registry_test.rs:107-111 — "The ancestry table and the extends edges it is derived from agree" now compares the table with itself, since resolve_type_chain reads the table. Drop it or compare against get_extends_parent_map.
  • Nit: packages/core/src/schema/mod.rs:3066-3084, 3177-3196 — both instance checks read outside the transaction that writes the schema, so a node created in between is not seen. Acceptable at this scale; worth a line in the comment.

Recommendation

APPROVE. The blocking regression is fixed and tested on the real path, the SQL and Rust views of a core type can no longer be made to disagree through the schema API, and the remaining exact comparisons are documented with reasons. Fold N1 into this PR if it is a quick move; it does not need another review round. Finding 2 stays open for Michael's decision on the interim declarations.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed (ddbc670a)

N1 🟡 (refusals ran after Phase 1 had committed renames) — fixed. The core-type refusal, the root-only re-target check and the become-abstract check are now one function, validate_type_system_changes, called in update_schema's Phase 0 against the pre-call schema, before any rename commits. The Phase 2 copies are gone. New test a_refused_type_system_change_applies_nothing_else_in_the_call sends a rename together with a refused extends and a refused abstract and asserts the field name and the node's stored value are unchanged.

Nit, self-comparing assertion — fixed. The test now compares the table against get_extends_parent_map.

Nit, instance checks read outside the writing transaction — documented on validate_type_system_changes.

Finding 2 (interim declarations of skill.node_types, tool.source, tool.handler) is unchanged and stays flagged for Michael.

Core tests: 2583 passed. quality:fix clean.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The reviewer approved and said N1 needs no further round. The change moves three existing checks earlier in the same function without altering what they refuse, and a test pins the ordering.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3462 was taken out of the queue — it conflicts with main in: packages/core/src/db/sqlite_store/search.rs. Rebase onto origin/main, push, and re-run bun run merge 3462.

@malibio
malibio force-pushed the issue-3439-core-node-type-registry branch from ddbc670 to d76e4cf Compare October 1, 2026 17:47
@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Branch rewritten as one commit on current main (d76e4cf1) so the merge queue can replay it: the queue ejected the previous push because replaying its commits re-hit a conflict that a merge commit had resolved. The tree is the reviewed tree at ddbc670a merged with main through #3469. Merge resolutions since the re-review: the six wrapper modules #3469 deleted stay deleted, models/mod.rs and behaviors/mod.rs imports follow that deletion, and the frontend Node is type Node = NodeEnvelope now that #3469 removed its two extra fields. bun run test:changed (all tiers) and quality:fix pass on this commit.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3462 was taken out of the queue — the merge gate failed on it, rebased onto main. Reproduce with git rebase origin/main and bun run test:changed, fix, push, and re-run bun run merge 3462.

❯ src/tests/e2e/node-roundtrip.e2e.ts (11 tests | 1 failed) 489ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > creates a node and reads it back 10ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > updates a node and reads back the new content 8ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > version increments on each update 6ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > deletes a node and confirms it is absent 7ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > returns null for a non-existent node 1ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > creates a parent-child hierarchy and reads children 6ms
   × Node CRUD round-trip (HTTP → gRPC → SQLite) > persists node properties through the round-trip 3ms
     → Validation failed: 'count' is not a field of the core type 'text'. A core type takes only its declared fields; to add your own, use a namespace prefix (e.g. 'custom:count').
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > serves typed nodes inside a children tree 6ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > create and move replies carry the store placement for the written edge 9ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > moveChildrenToParent returns each transferred edge’s store order 11ms
   ✓ Node CRUD round-trip (HTTP → gRPC → SQLite) > createNode returns the new node id string 1ms
 ✓ src/tests/e2e/adapter-contract.e2e.ts (9 tests) 479ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 FAIL  src/tests/e2e/node-roundtrip.e2e.ts > Node CRUD round-trip (HTTP → gRPC → SQLite) > persists node properties through the round-trip
BackendError: Validation failed: 'count' is not a field of the core type 'text'. A core type takes only its declared fields; to add your own, use a namespace prefix (e.g. 'custom:count').
 ❯ handleResponse src/lib/services/http-response.ts:70:11
     68|     }
     69| 
     70|     throw new BackendError(
       |           ^
     71|       errorData?.message || fallbackMessage,
     72|       errorData?.code,
 ❯ HttpAdapter.createNode src/lib/services/backend-adapter.ts:448:12
 ❯ src/tests/e2e/node-roundtrip.e2e.ts:94:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 Test Files  1 failed | 7 passed (8)
      Tests  1 failed | 46 passed (47)
   Start at  19:51:09
   Duration  8.84s (transform 123ms, setup 14ms, collect 225ms, tests 8.42s, environment 0ms, prepare 32ms)
error: script "test:e2e" exited with code 1
error: script "test:e2e" exited with code 1
[stage exited with code 1]

  full output: /var/folders/6c/mkxnmpkx5zqc9jwwy20tjkyr0000gn/T/nodespace-gate-logs/_gate-merge-2026-10-01T17-48-02-521Z/test-e2e-headless-daemon-round-trip.log

✗ test:e2e (headless daemon round-trip) failed — merge blocked.
  Fix the failure, push, and re-run: bun run merge <PR#>

@malibio
malibio force-pushed the issue-3439-core-node-type-registry branch from d76e4cf to 76f175a Compare October 1, 2026 17:54
…extends-aware rules (closes #3439)

Lays the foundation of ADR-086:

- CoreNodeType registry in nodespace-types: one variant per core type with its
  parent, abstract flag, category, content role, structural and participation
  rules, titling and wire shape. Seeded schemas, behaviours, the wire
  conversion and the frontend plugin list are tested against it.
- NodeEnvelope: the generic Node is the envelope and every typed wire struct
  embeds it. lifecycleStatus is always serialized.
- type_ancestry table kept by triggers inside the schema write, so SQL can
  apply a base type's rule to its subtypes. Root-only triggers and the
  mention filter resolve through it; task/project indexes cover subtypes.
- Behaviours compose through the extends chain; validation, embedding,
  titling and the collection, person, ai-chat and play rules follow it.
- Abstract schemas: create and retype into one are refused on every path.
- Closed core schemas: an undeclared key in a core bucket is rejected;
  fields and itemFields are validated recursively.
- Typed clients: the generic update refuses a core field that has a typed
  update when the request is flagged typed_client.
- SchemaField.type and itemType are a closed enum; string is not a type.
- Every create path refuses a non-UUID id outside the three named forms;
  seeded plays and views have fixed literal UUIDs.
- scripts/check-node-type-literals.ts fails the push check on a literal
  node_type comparison in Rust, SQL or TypeScript outside tests.

The on-disk shape changes: reset the database.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio
malibio force-pushed the issue-3439-core-node-type-registry branch from 76f175a to 36da2c3 Compare October 1, 2026 18:08
@malibio
malibio merged commit 2760354 into main Oct 1, 2026
@malibio
malibio deleted the issue-3439-core-node-type-registry branch October 1, 2026 18:09
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.

Add the core node type registry, shared envelope, closed schemas and extends-aware rules

1 participant