Skip to content

Enforce root-only content membership for member_of edges as a store-aware relationship validation #1742

Closed

Description

@malibio

Overview

A content node may be member_of a collection only if it is a root node (no has_child parent). This is decided in ADR-059 §2 but nothing enforces it. Because collection membership is what carries access classification, an unenforced constraint here silently breaks two things at once: the access model's separation of organization from outline position, and the invariant that keeps embedding aggregation single-domain.

Note what the constraint is not: it limits which nodes may hold a membership edge, not which nodes may be restricted. A restricted task inside an open, team-visible project remains entirely legitimate.

Problem Statement

Filing is an act on a whole unit. The outline position of an interior node is a detail of how its root is written, so letting an interior node carry independent classification makes access a property of document structure — the exact conflation ADR-059 exists to remove.

Today the rule holds only by the absence of a UI affordance, which is not enforcement. Every one of these paths can write a member_of edge:

  • the CLI
  • graph imports
  • the sync-apply path (an edge arriving from another device)
  • playbook add_relationship actions
  • any future API surface

An invariant that holds only because one picker was never built breaks silently, with no surface admitting it happened.

The rule also cannot be expressed where per-node validation lives. NodeBehavior::validate() is strictly per-node and cannot consult the store, but deciding whether a node is a root requires reading that node's has_child in-edges. This is the same seam #1734 opens for store-aware property rules.

Why it is load-bearing beyond access

The constraint is what makes an access boundary unable to appear inside an embeddable root's aggregate. Combined with the embeddable-type list (task, date, person, ai-chat contribute nothing to a parent's vector), it means subtree aggregation is always single-domain. That is why #1737 no longer needs access filtering inside aggregate_children_content, and no longer needs re-embedding to trigger on access changes.

The invariant is a conjunction of two otherwise-unrelated facts — root-only membership and the embeddable-type list. Either one changing reintroduces the leak, which is why it is enforced rather than assumed.

Proposed Solution

Express the rule in the schema system as a store-aware relationship validation on the member_of edge type — declared where a reader can see it, rather than as a check embedded in one write path.

Hard enforcement is correct here

Unlike a global uniqueness rule, this constraint can be rejected at write time. It is evaluated against the node's own local parent edges, not against a global set, so two offline devices cannot each validly produce a state that only conflicts at sync convergence. There is no local-first objection to hard rejection, and no suggest-don't-block fallback is needed.

This is the key difference from #1734, where global uniqueness must be suggest-don't-block plus a convergence policy.

Sync-apply parity

The sync-apply path must apply the same rule to incoming edges. A device running older code must not be able to introduce an edge that local validation would refuse — otherwise the invariant is only as strong as the oldest client in the tenant.

Architecture Impact

  • ADR-059 (../nodespace-docs/decisions/059-access-classification-not-outline-position.md) §2 — decides root-only content membership and specifies it as a store-aware relationship validation in the schema system. This issue implements that decision; it does not reverse or supersede it. No companion docs change is required.
  • ADR-059 §7 and ../nodespace-docs/architecture/data-layer.md ("Aggregation Never Spans an Access Boundary") — both depend on this constraint holding. They state that aggregation asserts rather than filters, which is only sound if the constraint is enforced.
  • ADR-037 (../nodespace-docs/decisions/037-collection-access-model.md) — establishes member_of as the grouping primitive and permission carrier. Unaffected; this narrows which nodes may hold such an edge, not what the edge means.

Acceptance Criteria

  • A member_of edge write from a content node that has a has_child parent is rejected
  • A member_of edge write from a root content node succeeds
  • Person-node member_of edges (grantee membership per ADR-037 §4) are unaffected by the constraint
  • Collection-to-collection member_of edges (collection nesting) remain permitted
  • The rule is declared in the schema system, not hardcoded in a single write path
  • The constraint is enforced on the sync-apply path for incoming edges, not only on local writes
  • Rejection surfaces an actionable error naming the node and why it was refused
  • A node that becomes non-root (gains a has_child parent) while holding a membership edge has a defined, tested outcome
  • Regression test: an interior node cannot be filed into a restricted collection via the CLI
  • Regression test: a restricted task inside an open project still works end to end
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Behavior/validation seam: packages/core/src/behaviors/mod.rs — NodeBehavior::validate() is per-node and store-blind; the store-aware phase must sit outside it (NodeService at create/update, or an async store-backed validation phase)
  • Relationship writes: packages/core/src/db/ — member_of edge insert path
  • Sync apply: the incoming-edge application path must call the same validation
  • Playbook actions: packages/core/src/playbook/ — add_relationship action must be subject to the same rule
  • Schema system: packages/core/src/ schema definitions — where the relationship constraint is declared

Implementation Details

The validation needs the target node's has_child in-edge count. Scope is per-database.

Design the capability generically rather than as a one-off member_of special case: a relationship-level constraint kind that schema-driven types can also use, consistent with the hybrid core/extension behavior architecture. This mirrors how #1734 asks for a generic unique property-rule kind rather than a hardcoded person.email check.

Open question for the implementer to settle and document: what happens when an existing root node holding a membership edge is later given a parent (an outline move that makes it interior). Candidate answers are reject the move, drop the membership edge, or promote the membership to the new root. Whichever is chosen must be tested, since it is reachable through ordinary outline editing.

Testing Requirements

  • Unit tests for the validation rule itself, including the person-node and collection-nesting exemptions
  • Integration test proving the CLI path is gated, not only the UI path
  • Sync-apply test proving an incoming non-root membership edge is refused

Dependencies

Related Issues

Activity

  1. mstomar125 commented on Jul 27, 2026

    @mstomar125
    Contributor

    Attempted a service-level enforcement (in NodeService), but adversarial review shows it's the wrong layer — needs a store-level guard + cross-repo work

    I implemented the root-only check as a shared NodeService::assert_root_only_membership called from create_relationship and bulk_add_to_collections_notify. It correctly gates the local single-add, ops, playbook, and import paths (verified; full core/agent/daemon suites green, no live conflict). But review found it does not achieve the invariant the issue requires, and I'm not shipping it — a service-level check can't hold this rule. Three concrete gaps:

    1. (High) Sync cold-sweep bypasses it. sync/nodespaced-pro/.../cloud_sync/apply.rs:391 (apply_cold_rel_sweep_batched, wired at reconnect.rs:277 for a first/large pull — the dominant path) applies remote member_of via ns.store().bulk_add_to_collections(...) directly on the store, bypassing both gated entry points. So sync-apply parity is only achieved for the per-row/realtime branch (apply.rs:305), not the cold sweep. Closing it needs a sync-repo change (the cold sweep uses the raw store call to skip event emission).
    2. (Medium) Reparent transition unguarded. The rule is enforced only when a member_of edge is created, never re-checked when a node acquires a has_child parent. "File a root document into a collection, then indent it under another document" produces a forbidden interior-content member_of through ordinary UX — no member_of write happens, so no check fires. Enforcing this needs handling on the has_child/move_node side (reject, or drop the membership on reparent).
    3. (Medium) Permanent rejection can wedge incremental sync. apply.rs:305 treats every create_relationship error as a transient "endpoint not landed yet" and holds the rel cursor for re-pull. The root-only rejection is permanent: any pre-existing interior-content member_of edge in the cloud would be re-pulled, re-rejected, and hold the cursor forever — wedging edge sync. (No such edge exists today, but gap Create design system foundation #2 can create one, which then reaches cloud.)

    Correct approach (per review): enforce root-only at the store level — inside add_to_collection / bulk_add_to_collections (or a DB check/trigger on the member_of INSERT) — so all paths (single-add, bulk, cold-sweep, direct markdown import at markdown/mod.rs:1128/1173) hit it uniformly, including sync. Then add reparent-side handling (#2) and a sync-side permanent-vs-transient error distinction so a rejected edge is skipped rather than wedging the cursor (#3). That's a focused cross-repo change (core store guard + sync apply error handling + has_child-path handling).

    Confirmed correct in the attempt (reusable for the real fix): is_root_node keys strictly on incoming has_child (a member_of isn't a has_child, so a filed root stays a root; adding children later keeps it root); collection/person exemptions correct; no over-rejection of any legitimate case; playbook add_relationship and daemon import both route through gated entry points and file only roots.

    Leaving this open for the store-level rework. Closing the service-level PR unmerged.

  2. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Thanks for stopping rather than shipping the service-level version — the analysis in your comment is right, and the three gaps are all real (I verified each against source). One correction and one simplification, and I think this gets a lot smaller than "focused cross-repo change."

    Put the check in the store, and two of the three gaps disappear

    Both bypasses you found exist because the check sits in NodeService. Move it down one layer and they stop existing:

    • packages/core/src/db/sqlite_store/relationships.rs:215 — add_to_collection
    • packages/core/src/db/sqlite_store/relationships.rs:502 — bulk_add_to_collections

    Those two functions are the only places in the codebase that INSERT a member_of row. Everything funnels through them: single-add, bulk, markdown import (markdown/mod.rs:1128/1173), and the sync cold sweep. add_to_collection_by_path is not a third entry point — it delegates to create_relationship (collection_service.rs:494).

    This means gap 1 needs no nodespace-sync change at all. The cold sweep at apply.rs:391 calls ns.store().bulk_add_to_collections(...), so a store guard catches it for free. Gap 3 (the cursor wedge) also stops being a gate — it was a hazard your own service-level rejection would have introduced, not an inherited bug. Worth filing separately, but it doesn't block this.

    The "store shouldn't validate" objection doesn't apply here: the store already runs validate_no_member_of_cycle (sqlite_store/nodes.rs:1124), a recursive CTE over member_of. A root-only check is strictly simpler. The store has everything it needs — get_node (nodes.rs:143), get_node_type (nodes.rs:894), and get_parent_id (nodes.rs:881, one indexed lookup on idx_rel_out).

    One bypass you missed — and it's in core, not sync

    packages/daemon/src/services/import_service.rs:697 calls store.bulk_add_to_collections(...) directly. The PR body says daemon import routes through gated entry points; that's true of the single-file path (import_service.rs:236) but not the bulk one. A store guard covers this too.

    Your code mostly ports over

    assert_root_only_membership reuses nearly verbatim — the collection/person exemption and the error message are both right. is_root_node is just get_parent().is_none(), which at store level is get_parent_id(...).is_none(). root_only_content_membership_is_enforced moves down a layer; please add a bulk case and a case that goes through the cold-sweep path.

    Reparent (gap 2) — split it out, and block for now

    Gap 2 is real and confirmed: move_node (hierarchy.rs:391) never re-checks membership. But it's a separate issue from this one and shouldn't gate it — nothing can reach that state today, because nothing enforces the rule yet.

    When you do get to it: reject the indent, don't silently drop the membership. A node can hold multiple member_of edges (the dedup in add_to_collection is on the pair), and per ADR-059 §1/§3 those are alternative access-grant paths. Dropping them all on an indent would silently revoke every grant at once — and ADR-059 exists specifically to stop outline position from changing access. Rejecting is recoverable (un-file deliberately, then indent); silent multi-collection loss is not. Error message should name the collections.

    Scope

    Store guard + tests. One file, no nodespace-sync changes. Two follow-up issues to file: reparent handling, and sync permanent-vs-transient error classification.

    Not in scope

    ADR-059 §2 asks for this "expressed in the schema system as a store-aware relationship validation." That framework doesn't exist, and your deferral note on criterion 5 was the right call. Ship the guard; leave the declarative version for whenever the schema-validation phase gets built.

    One thing to confirm first

    I checked for other member_of INSERT sites by grepping Rust sources across core and sync and found none beyond those two functions — but I did not audit migrations or test fixtures. Please re-confirm that as step one, since the whole approach rests on it. Also worth checking whether any interior-content member_of edges already exist in a real DB before turning on hard rejection.

    Reassigning to you.

  3. mstomar125 commented on Jul 28, 2026

    @mstomar125
    Contributor

    Resolved by #1768 (squash-merged 8f13db5e).

    Enforcement — a store-level assert_root_only_membership now gates all three member_of INSERT sites in SqliteStore: add_to_collection, bulk_add_to_collections (the sync-apply cold-sweep + daemon import path), and create_generic_relationship when its rel_type is member_of (reached via the explicit-order fork of NodeService::create_relationship, playbook add_relationship, and CLI relationship create --edge-data). So every write path — CLI, import, playbook, sync-apply — is covered by construction. A content node with a has_child parent is rejected with an actionable, node-naming error; collection (nesting) and person (grantee, ADR-037 §4) nodes are exempt. The bulk check is one chunked query to keep the cold-sweep path a single round trip.

    Acceptance: criteria 1–4, 6, 7, 9, 10 met + tested (root ✓, interior ✗, exemptions, CLI/generic path, restricted-task-in-open-project, bulk cold-sweep parity). Full core lib suite 975/975; two independent adversarial reviews (the first caught a real bypass via the generic path, now fixed + tested).

    Split out (issue open questions):

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