Repository navigation
Description
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):
extendsis structural vocabulary, authored as a first-classextendskey rather than a hand-writtenrelationshipsentry, and reserved from user authorship without joiningBUILTIN_RELATIONSHIP_NAMES(that array is the rejection list for declared relationships and would block the very write the ADR specifies).- Reads are scope-relative projections, not a flat merge of every ancestor bucket — a
task-scoped query sees an issue'sstatusbut not itsseverity. - 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
-
extendsis authored as a first-class key in the schema definition ({"name": "Issue", "extends": "task", "fields": [...]}), added toCreateSchemaParams/UpdateSchemaParams(both aredeny_unknown_fields, so the key must be declared explicitly or the call is rejected) -
extends/extended_byare reserved from user authorship —reject_reserved_relationship_names(packages/core/src/schema/mod.rs) rejects them on both thenameandreverseNamesides, in create and update alike (test) -
extendsis NOT added toBUILTIN_RELATIONSHIP_NAMES. That array is the rejection list for schema-declared relationships and feedsbuiltin_exclusion_sql(db/sqlite_store/relationships.rs:10); addingextendsthere would makeset_schema_declarationsreject 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
SchemaRelationshipfrom theextendskey (directionout, cardinalityone, reverseextended_by/many) and persists it via the existingset_schema_declarationspath —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
extendschain, run at bothcreate_schemaandupdate_schematime, rejectingA extends B extends A(test: direct cycle, transitive cycle through 2+ intermediate schemas) - Cardinality enforcement: a second
extendsdeclaration 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 viaadd_field_valuesis 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-declaredfields
Real node_type
- Creating an instance of a schema declaring
extendsproduces a node withnode_typeequal to that schema's own id (not the base type) — test -
create_node/update_node's schema-fetch feedingvalidate_node_with_fields(currently a single, non-chain-walkingget_schema_for_typecall) switches to the effective-field-set resolver, so creating anissue-typed node correctly validates/defaultstask's inherited fields — test
Query engine
- A descendant-closure
WITH RECURSIVEquery (walkingout_node → in_nodeonrelationship_type = 'extends'edges, modeled directly onMENTION_CONTAINERS_QUERY/the collection-subtree query inpackages/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 = ?intonode_type IN (...)— test: queryingnode_type: "task"returns instances oftaskand every schema transitively extending it, with zero changes to any of the callers that constructNodeQuery - Note
build_scalar_conditions(packages/core/src/db/sqlite_store/nodes.rs:1556) isfn(&NodeQuery)— noself, no connection, synchronous — so it cannot issue the closure query itself. Resolve it in its two callers (query_nodes,count_nodes, bothasync fnon&self) and pass the resolved set in. The choke-point guarantee is unaffected -
query_nodes_title_stem_fallbacktakesnode_typeas a bareOption<&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 exactlyissueinstances (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 offidx_rel_typeand 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 RECURSIVEquery (walkingin_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
extendsedge changes, wired alongside the existinghandle_schema_updatedpath (packages/core/src/playbook/engine.rs) - A Play trigger registered against
node_type: "task"fires on aNodeCreated/NodeUpdatedevent carryingnode_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 theresolve_effective_fieldsresolver above — but not its own directly-declaredfields), every appended value must includemaps_to, and eachmaps_tomust resolve to a value already present on the field at any scope in the chain — reject otherwise (test: missingmaps_toon an inherited-field addition;maps_tonaming 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) -> Valueimplemented as one shared function, walkingmaps_toupward along the sameextendsancestor closure the Trigger engine section caches — not reimplemented per call site -
node_matches_property_filter(packages/core/src/services/node_service/query.rs) routes astatus-style filter comparison throughresolve_property_at_scopewhen evaluated against a matched descendant instance, using the query's ownnode_typefilter astarget_schema_id— test: a query filteringnode_type: "task", status: "todo"matches anissuenode stored withstatus: "backlog"(backlogmapping totodo) -
node_to_cel_value/the trigger-index (packages/core/src/playbook/cel.rs,packages/core/src/playbook/lifecycle.rs) resolvesnode.status-style CEL reads the same way for a Play trigger registered attaskscope firing on anissuenode — test: a base-scoped Play condition (node.status == "todo") matches when the concrete node carries the extended valuebacklog - A Play's CEL environment is projected to the scope its trigger was registered against — a Play on
taskfiring against anissueseestask's fields only, sonode.severitydoes 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_tocompose at two levels — projection selects which fields exist at a scope,maps_tonormalizes what a surviving field reads as.maps_toonly ever applies to fields that survived projection - A Play or query authored explicitly against
issueitself (nottask) 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 ownnode_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
issueatissuescope flattens["issue","task"]→status+severity; attaskscope flattens["task"]→statusonly, withseverityabsent (test both) - A query's
node_typesets the result scope:query(node_type: "task")returns tasks and extending instances, each projected totask's field set — test that a returnedissuecarriesstatusand notseverity. Queryingnode_type: "issue"projects atissuescope (test). A plain unextendedtaskattaskscope 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 fullissueview (test) -
flatten_namespaced_properties(packages/nodespace-types/src/convert.rs:85) requires a signature change — it takes a singlenode_typetoday and returns exactlyproperties[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, CLIoutput.rs:126) pass it -
get_node_property(playbook/graph_resolver.rs:265),node_to_cel_value(playbook/cel.rs:170) andvalidate_node_with_fields(crud.rs:2452) all read onlyproperties[node.node_type]today and must resolve against the projected scope chain.node_to_cel_valueis not merely lossy if left alone — itselse if !k.starts_with('_')branch hoists an unprojected sibling bucket into the CEL map wholesale as a nestednode.taskmap (test that it does not) - Correction to an earlier draft of this issue: the claim that
get_node_property/flatten_namespaced_propertiesneed 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
taskitself, 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— confirmsPlaybookNode's scope no longer includes display identity; unrelated to this issue's implementation workpackages/nodespace-types/src/schema.rs—SchemaNode,SchemaRelationshippackages/core/src/models/schema.rs—BUILTIN_RELATIONSHIP_NAMESpackages/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_QUERYand the collection-subtreeWITH RECURSIVEquery (~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 expansionpackages/core/src/playbook/lifecycle.rs—PlaybookLifecycleManager's trigger-index,trigger_keys_for_graph_event/play_references_node_type— where ancestor-closure resolution and caching landpackages/core/src/playbook/engine.rs—handle_schema_updated(~line 467) — existing schema-write invalidation hook to extendpackages/core/src/services/node_service/crud.rs—normalize_flat_properties_to_namespace,validate_node_with_fields, andcreate_node's current single-schemaget_schema_for_typefetch (~line 109) — the write-path call site requiring the chain resolverpackages/core/src/schema/mod.rs:1397-1464—add_field_valueshandling insidehandle_update_schema; gains the inherited-fieldmaps_to-required validationpackages/core/src/playbook/graph_resolver.rs—get_node_property— no change expected; newresolve_property_at_scopefunction should live near here or alongside the ancestor-closure cache inlifecycle.rs, implementer's callpackages/core/src/services/node_service/query.rs—node_matches_property_filter— REQUIRES a change: routes throughresolve_property_at_scopefor matched descendant instances (see Acceptance Criteria)packages/nodespace-types/src/convert.rs—flatten_namespaced_properties— no change expectedpackages/core/src/playbook/cel.rs—node_to_cel_value— REQUIRES a change: routes throughresolve_property_at_scopefor 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'smaps_torequirement 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
SchemaNodetypes. The core one (packages/core/src/models/schema_node.rs:47) is what everyhandle_*_schemahandler uses, and itsrelationshipsfield is empty afterfrom_node— the store hydrates it from therelationshiptable, which is whyhandle_update_schemare-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 useget_schema_node(hydrates relationships) rather thanget_schema_for_type(raw JSON, no hydration). SchemaFieldisdeny_unknown_fieldsand derives noPartialEq(nodespace-types/src/schema.rs:118). Somaps_tocannot be smuggled onto a field — adding it is a deliberate wire-shape change — and the no-redeclaration check cannot compare fields with==.CreateSchemaParams/UpdateSchemaParamsare bothdeny_unknown_fields— theextendskey must be declared on the struct or the call is rejected outright.add_field_valuesgates onextensible == Some(true), independent ofprotection(ADR-076), and checks collisions on.value, never.label.get_schema_for_typeis a single, uncached choke point returningserde_json::Value(services/node_service/schema.rs:129). The create/update paths consumeschema_json["fields"]in five duplicated fetch-and-validate blocks incrud.rs(the create path at ~:252, plus ~:864, ~:984, ~:1110) — all must move to the chain resolver together.PlaybookLifecycleManagerholds no lock and no DB handle (playbook/lifecycle.rs:19); thestd::sync::RwLocklives inPlaybookEngine. The ancestor-closure cache must therefore be populated fromengine.rs, which has store access, and stored as a field on the manager.handle_schema_updatedis atengine.rs:758, not ~467. It currently invalidates only plays (viadisable_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
- Implement PlaybookNode as installable bundle record with display identity #2570 (PlaybookNode) — independent; PlaybookNode's scope no longer overlaps with this issue per ADR-075's rewrite
- Add methodology recipe mechanism (TS source, generated CLI reference doc) with Linear-style as first recipe #2596 (Linear-style methodology recipe) — currently Blocked on this issue; its Issue-extends-Task design depends on
extendsexisting, AND specifically depends onmaps_to/scope-relative resolution forissue'sbacklog/in_reviewstatus-vocabulary extension to keep base-scopedtaskPlays/queries working unmodified - Add methodology recipe: Jira-style work tracking (Epic/Story/Bug hierarchy, Sprints) #2652 (Jira-style methodology recipe) — same dependency shape as Add methodology recipe mechanism (TS source, generated CLI reference doc) with Linear-style as first recipe #2596, for Jira-style status-vocabulary extension via
add_field_values - Seed a core Play that completes a parent task when all its children are done #2636 (core auto-complete-parent Play) — its condition ("every
has_childchild reaches a done-category status") explicitly requires readingstatusvia scope-relative resolution, not the literal stored value — cannot be correctly implemented against anyextends-descendant type without this issue'smaps_tomechanism
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
extendschain — 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
malibio commentedon Sep 17, 2026
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.