Skip to content

Implement extends schema relationship with real node_type subtype identity #2598

Closed

Description

@malibio

Overview

NodeSpace has no way for one schema to declare "I am a task, plus these additional fields," and no way for an instance of such a schema to report its real, specific type via node_type. This issue implements ../nodespace-docs/decisions/078-schema-extends-relationship-for-field-composition.md (ADR-078): a new extends SchemaRelationship, real node_type-as-extending-type for created instances, subtype-aware query/trigger engines, write-path field-bucketing changes, and the maps_to/scope-relative property resolution mechanism that lets an inherited enum field (e.g. task.status) carry a richer vocabulary on a descendant schema while base-scoped Plays and queries keep matching it unmodified. This is the full scope of ADR-078 — an earlier draft of this issue covered structural extends only and did not include maps_to; that gap is closed here.

Updated 2026-09-17 after reading the code against the ADR. Three things changed, and ADR-078 + components/schema-management.md were corrected to match (nodespace-docs 4c7d8cd):

  1. extends is structural vocabulary, authored as a first-class extends key rather than a hand-written relationships entry, and reserved from user authorship without joining BUILTIN_RELATIONSHIP_NAMES (that array is the rejection list for declared relationships and would block the very write the ADR specifies).
  2. Reads are scope-relative projections, not a flat merge of every ancestor bucket — a task-scoped query sees an issue's status but not its severity.
  3. All four read surfaces need changes; the earlier claim that they did not is false.

Problem Statement

A schema extending task today can only restate every field task already has — there is no composition mechanism, and no way for a node created under such a schema to report anything other than node_type: "task". This blocks any methodology-recipe or domain-specific specialization (a Linear-style issue extending task, a marketing campaign_task extending task) from having real, queryable, trigger-matchable type identity distinct from its base type — and, separately, blocks any such specialization from safely extending an inherited enum field's vocabulary (e.g. issue wanting task.status to also support backlog/in_review) without breaking every base-scoped Play or query already written against that field's original values.

Architecture Impact

This issue implements ../nodespace-docs/decisions/078-schema-extends-relationship-for-field-composition.md (ADR-078) in full, including the maps_to/scope-relative property resolution mechanism (see Acceptance Criteria) — Status: Proposed, becomes Accepted once implemented and merged per this repo's ADR convention.

For context on the ADR's own design history (not this issue's scope, but useful background): ADR-078 reversed an earlier, narrower version of its own design (kept node_type as the base type) after four rounds of architect review found that version couldn't satisfy the real requirement (a node's own node_type should tell the truth about what it is). Read ADR-078's Context/Revision-history section for the full reasoning and the two intermediate designs it rejects.

This issue also relies on ../nodespace-docs/decisions/075-playbooknode-installable-bundle-record.md (ADR-075) having already dropped its kinds[] mechanism — ADR-075 has been rewritten to no longer describe kinds[]/derived_from_playbook/_extension_kind at all (they were never implemented, so removed outright rather than deprecated, per this repo's pre-release convention). No code implements any of that mechanism today, so there is nothing to delete in this repo — this note exists so an implementer doesn't go looking for it.

Proposed Solution

Add extends as a structurally-reserved SchemaRelationship. A schema declaring extends composes its effective field set as its own fields plus its parent's (additive only, single parent, no override). An instance created under an extending schema gets that schema's own id as its real node_type. The query engine and trigger engine are made subtype-aware via cheap recursive-CTE closures over the relationship table (the same WITH RECURSIVE pattern already proven in production for MENTION_CONTAINERS_QUERY and the collection-subtree query), implemented at single choke points so no existing call site needs individual changes.

Acceptance Criteria

Schema layer

  • extends is authored as a first-class key in the schema definition ({"name": "Issue", "extends": "task", "fields": [...]}), added to CreateSchemaParams/UpdateSchemaParams (both are deny_unknown_fields, so the key must be declared explicitly or the call is rejected)
  • extends/extended_by are reserved from user authorship — reject_reserved_relationship_names (packages/core/src/schema/mod.rs) rejects them on both the name and reverseName sides, in create and update alike (test)
  • extends is NOT added to BUILTIN_RELATIONSHIP_NAMES. That array is the rejection list for schema-declared relationships and feeds builtin_exclusion_sql (db/sqlite_store/relationships.rs:10); adding extends there would make set_schema_declarations reject the write and filter the row out of all five declaration queries. Reserved-from-authorship and excluded-from-storage are separate questions — see ADR-078's Shape section
  • NodeSpace synthesizes the SchemaRelationship from the extends key (direction out, cardinality one, reverse extended_by/many) and persists it via the existing set_schema_declarations path — in_node = child schema, out_node = parent (test: the row lands with the expected direction)
  • Target-existence validation reuses validate_relationship_targets_exist
  • Cycle detection: a DFS/visited-set walk over the extends chain, run at both create_schema and update_schema time, rejecting A extends B extends A (test: direct cycle, transitive cycle through 2+ intermediate schemas)
  • Cardinality enforcement: a second extends declaration on the same schema is rejected (test)
  • No-field-redeclaration validation checked against the full resolved effective field set (own ∪ every ancestor's), not just the schema's own directly-declared fields (test: redeclaring an inherited field, including an inherited enum field with different core_values, is rejected)
  • resolve_effective_fields(schema_id) -> Vec<SchemaField> resolver implemented, reading parent schemas live (or through a cache correctly invalidated on any write to a schema anywhere in the chain) — test that a value appended to a parent's enum field via add_field_values is visible in a child's resolved fields on next resolution, without touching the child
  • get_schema_definition/schema-comprehension consumers use the resolver instead of a schema's own directly-declared fields

Real node_type

  • Creating an instance of a schema declaring extends produces a node with node_type equal to that schema's own id (not the base type) — test
  • create_node/update_node's schema-fetch feeding validate_node_with_fields (currently a single, non-chain-walking get_schema_for_type call) switches to the effective-field-set resolver, so creating an issue-typed node correctly validates/defaults task's inherited fields — test

Query engine

  • A descendant-closure WITH RECURSIVE query (walking out_node → in_node on relationship_type = 'extends' edges, modeled directly on MENTION_CONTAINERS_QUERY/the collection-subtree query in packages/core/src/db/sqlite_store/relationships.rs) resolves a base type's full transitive subtype set
  • This closure is resolved at one choke point, compiling node_type = ? into node_type IN (...) — test: querying node_type: "task" returns instances of task and every schema transitively extending it, with zero changes to any of the callers that construct NodeQuery
  • Note build_scalar_conditions (packages/core/src/db/sqlite_store/nodes.rs:1556) is fn(&NodeQuery) — no self, no connection, synchronous — so it cannot issue the closure query itself. Resolve it in its two callers (query_nodes, count_nodes, both async fn on &self) and pass the resolved set in. The choke-point guarantee is unaffected
  • query_nodes_title_stem_fallback takes node_type as a bare Option<&str> and must take the resolved set too, or a title-stem search silently narrows back to the exact type (test)
  • Querying the leaf type directly (node_type: "issue") continues to return exactly issue instances (test — confirms the expansion is additive, not lossy)
  • Use the correlated-subquery form for the recursive step, not a JOIN ... WHERE relationship_type = 'extends'. The JOIN form lets SQLite drive off idx_rel_type and scan every edge of that type per recursive step; MENTION_CONTAINERS_QUERY's doc comment records this as an 8ms vs 393ms difference, and a query-plan regression test in that file enforces it

Trigger engine

  • An ancestor-closure WITH RECURSIVE query (walking in_node → out_node) resolves a specific node_type's full ancestry
  • This closure is cached in PlaybookLifecycleManager (packages/core/src/playbook/lifecycle.rs), not queried per mutation event — test or diagnostic confirming trigger matching stays in-memory/no SQL round-trip on the hot path once the cache is warm
  • A schema-write-triggered invalidation hook clears this cache specifically on extends edge changes, wired alongside the existing handle_schema_updated path (packages/core/src/playbook/engine.rs)
  • A Play trigger registered against node_type: "task" fires on a NodeCreated/NodeUpdated event carrying node_type: "issue" (or any transitively-extending schema) — integration test
  • No regression: existing Plays registered against exact, unextended types continue to match exactly as before

Enum-value extension (maps_to) and scope-relative resolution

  • add_field_values (handle_update_schema, packages/core/src/schema/mod.rs:1397-1475) gains a check: when the targeted field is inherited (present in the calling schema's effective field set — via the resolve_effective_fields resolver above — but not its own directly-declared fields), every appended value must include maps_to, and each maps_to must resolve to a value already present on the field at any scope in the chain — reject otherwise (test: missing maps_to on an inherited-field addition; maps_to naming a nonexistent value; both rejected)
  • Values added to a field the schema declares itself (not inherited) continue to need no maps_to — unaffected (regression test)
  • resolve_property_at_scope(node, field_name, target_schema_id) -> Value implemented as one shared function, walking maps_to upward along the same extends ancestor closure the Trigger engine section caches — not reimplemented per call site
  • node_matches_property_filter (packages/core/src/services/node_service/query.rs) routes a status-style filter comparison through resolve_property_at_scope when evaluated against a matched descendant instance, using the query's own node_type filter as target_schema_id — test: a query filtering node_type: "task", status: "todo" matches an issue node stored with status: "backlog" (backlog mapping to todo)
  • node_to_cel_value/the trigger-index (packages/core/src/playbook/cel.rs, packages/core/src/playbook/lifecycle.rs) resolves node.status-style CEL reads the same way for a Play trigger registered at task scope firing on an issue node — test: a base-scoped Play condition (node.status == "todo") matches when the concrete node carries the extended value backlog
  • A Play's CEL environment is projected to the scope its trigger was registered against — a Play on task firing against an issue sees task's fields only, so node.severity does not resolve there (test). This is deliberate: a base-scoped Play behaves identically whether it fires on a plain task or a subtype, and cannot come to depend on a field only some of its matches carry
  • Projection and maps_to compose at two levels — projection selects which fields exist at a scope, maps_to normalizes what a surviving field reads as. maps_to only ever applies to fields that survived projection
  • A Play or query authored explicitly against issue itself (not task) sees the raw stored value (backlog) unresolved — already reading at native scope, nothing to resolve (test — confirms resolution is scope-relative, not a global rewrite)
  • The Query-engine path (build_scalar_conditions, packages/core/src/db/sqlite_store/nodes.rs) gains its own ancestor-closure cache for this resolution — ADR-078 notes this path does not share the Trigger engine's per-schema-write cache, since filter evaluation is per-row, not per-schema-write (test or diagnostic confirming no per-row SQL round-trip once warm, mirroring the Trigger engine cache test above)

Storage

  • Write path (normalize_flat_properties_to_namespace, packages/core/src/services/node_service/crud.rs) buckets each field under the schema that actually declares it (walking the chain at write time), not unconditionally under the node's own node_type
  • Scope-relative projection: a consumer receives the flattened property set of the scope it asked for, not a merge of every bucket. Reading an issue at issue scope flattens ["issue","task"] → status + severity; at task scope flattens ["task"] → status only, with severity absent (test both)
  • A query's node_type sets the result scope: query(node_type: "task") returns tasks and extending instances, each projected to task's field set — test that a returned issue carries status and not severity. Querying node_type: "issue" projects at issue scope (test). A plain unextended task at task scope is the identity case (regression test)
  • A direct read by node id (no type named) projects at the node's own type — node get <issue-id> yields the full issue view (test)
  • flatten_namespaced_properties (packages/nodespace-types/src/convert.rs:85) requires a signature change — it takes a single node_type today and returns exactly properties[node_type], silently dropping every sibling bucket. It must take the ordered scope chain (nearest scope first, so a nearer bucket wins any key collision). It stays pure and DB-free; the caller resolves the chain. Both callers (wire conversion, CLI output.rs:126) pass it
  • get_node_property (playbook/graph_resolver.rs:265), node_to_cel_value (playbook/cel.rs:170) and validate_node_with_fields (crud.rs:2452) all read only properties[node.node_type] today and must resolve against the projected scope chain. node_to_cel_value is not merely lossy if left alone — its else if !k.starts_with('_') branch hoists an unprojected sibling bucket into the CEL map wholesale as a nested node.task map (test that it does not)
  • Correction to an earlier draft of this issue: the claim that get_node_property/flatten_namespaced_properties need no changes is false. All four read surfaces read one hardcoded bucket and diverge three ways under per-schema buckets — dropped silently (flatten_namespaced_properties), never seen (node_matches_property_filter, validate_node_with_fields), or hoisted as a nested map (node_to_cel_value). Each needs scope threaded through it explicitly
  • Fields declared directly on an extending schema are stored bare, no ADR-063 namespace prefix required (test); fields added directly to task itself, unextended, still require the prefix exactly as ADR-063 specifies today (regression test)

General

  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • ../nodespace-docs/decisions/078-schema-extends-relationship-for-field-composition.md — the full design this issue implements; read in full, including Alternatives Considered for what NOT to build (multiple parents, field override/narrowing, grouped-by-type storage exposure)
  • ../nodespace-docs/decisions/075-playbooknode-installable-bundle-record.md — confirms PlaybookNode's scope no longer includes display identity; unrelated to this issue's implementation work
  • packages/nodespace-types/src/schema.rs — SchemaNode, SchemaRelationship
  • packages/core/src/models/schema.rs — BUILTIN_RELATIONSHIP_NAMES
  • packages/core/src/schema/mod.rs — handle_create_schema, handle_update_schema, validate_relationship_targets_exist (existence-check precedent, NOT a cycle-detection precedent — it does a flat check, no graph walk)
  • packages/core/src/db/sqlite_store/relationships.rs — MENTION_CONTAINERS_QUERY and the collection-subtree WITH RECURSIVE query (~line 647 onward) — the exact patterns both closure queries should be modeled on; set_schema_declarations — confirms persisted edge direction (in_node = declaring/child schema, out_node = target/parent schema)
  • packages/core/src/db/sqlite_store/nodes.rs — NodeQuery's type filter, build_scalar_conditions — the single choke point for descendant-closure expansion
  • packages/core/src/playbook/lifecycle.rs — PlaybookLifecycleManager's trigger-index, trigger_keys_for_graph_event/play_references_node_type — where ancestor-closure resolution and caching land
  • packages/core/src/playbook/engine.rs — handle_schema_updated (~line 467) — existing schema-write invalidation hook to extend
  • packages/core/src/services/node_service/crud.rs — normalize_flat_properties_to_namespace, validate_node_with_fields, and create_node's current single-schema get_schema_for_type fetch (~line 109) — the write-path call site requiring the chain resolver
  • packages/core/src/schema/mod.rs:1397-1464 — add_field_values handling inside handle_update_schema; gains the inherited-field maps_to-required validation
  • packages/core/src/playbook/graph_resolver.rs — get_node_property — no change expected; new resolve_property_at_scope function should live near here or alongside the ancestor-closure cache in lifecycle.rs, implementer's call
  • packages/core/src/services/node_service/query.rs — node_matches_property_filter — REQUIRES a change: routes through resolve_property_at_scope for matched descendant instances (see Acceptance Criteria)
  • packages/nodespace-types/src/convert.rs — flatten_namespaced_properties — no change expected
  • packages/core/src/playbook/cel.rs — node_to_cel_value — REQUIRES a change: routes through resolve_property_at_scope for a base-scoped trigger condition against a descendant node (see Acceptance Criteria)
  • ../nodespace-docs/decisions/076-schema-field-value-extension-and-task-status-enforcement.md (ADR-076) — add_field_values's additive-enforcement precedent, mirrored by this issue's no-redeclaration validation, and the mechanism this issue's maps_to requirement extends directly

Implementation Notes (verified against the code, 2026-09-17)

Facts confirmed by reading the current source; each contradicts something an earlier draft of this issue assumed.

  • Two SchemaNode types. The core one (packages/core/src/models/schema_node.rs:47) is what every handle_*_schema handler uses, and its relationships field is empty after from_node — the store hydrates it from the relationship table, which is why handle_update_schema re-attaches relationships manually before validation. The wire one (packages/nodespace-types/src/schema.rs:286) reads them from properties instead. Effective-field resolution must target the core type, and should use get_schema_node (hydrates relationships) rather than get_schema_for_type (raw JSON, no hydration).
  • SchemaField is deny_unknown_fields and derives no PartialEq (nodespace-types/src/schema.rs:118). So maps_to cannot be smuggled onto a field — adding it is a deliberate wire-shape change — and the no-redeclaration check cannot compare fields with ==.
  • CreateSchemaParams/UpdateSchemaParams are both deny_unknown_fields — the extends key must be declared on the struct or the call is rejected outright.
  • add_field_values gates on extensible == Some(true), independent of protection (ADR-076), and checks collisions on .value, never .label.
  • get_schema_for_type is a single, uncached choke point returning serde_json::Value (services/node_service/schema.rs:129). The create/update paths consume schema_json["fields"] in five duplicated fetch-and-validate blocks in crud.rs (the create path at ~:252, plus ~:864, ~:984, ~:1110) — all must move to the chain resolver together.
  • PlaybookLifecycleManager holds no lock and no DB handle (playbook/lifecycle.rs:19); the std::sync::RwLock lives in PlaybookEngine. The ancestor-closure cache must therefore be populated from engine.rs, which has store access, and stored as a field on the manager.
  • handle_schema_updated is at engine.rs:758, not ~467. It currently invalidates only plays (via disable_play) and no schema-derived cache exists yet, so the new closure cache's invalidation hangs off this same hook, under the write lock it already takes.

Dependencies

  • None

Related Issues

Non-Goals

  • Multiple-parent extends — explicitly rejected in ADR-078, not partially built or left as an open extension point
  • Field override/narrowing in the single-parent case — additive only
  • Schema deletion for a schema participating in an extends chain — schema deletion doesn't exist yet; out of scope here, to be addressed by a future schema-deletion ADR
  • Resolving the retroactive ancestor-field-collision edge case (ADR-078's Validation section) beyond detecting and erroring — no reconciliation/backfill of already-materialized instance properties, consistent with this repo's no-migration policy
  • Any UI work — schema/Play authoring remains CLI/agent-driven, matching existing convention

Activity

  1. malibio commented on Sep 17, 2026

    @malibio
    CollaboratorAuthor

    Baseline (worktree issue-2598-schema-extends): Frontend 5152 passed, 2 failed (251 test files). Both failures are in src/tests/performance/architecture-benchmarks.test.ts — timing-sensitive scaling-factor assertions (1.512 vs 1.5 threshold) that pass 13/13 when the file runs in isolation. Pre-existing flake under full-suite load, unrelated to this issue.

  2. self-assigned this
    on Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions