Skip to content

Decompose NodeService god-object into focused sub-services (facade delegation)Β #1238

Closed

Description

@malibio

Background (from architectural audit #1228)

B1 β€” NodeService is a god-object πŸ”΄
packages/core/src/services/node_service.rs β€” 58 pub async fn, ~11,891 lines. Mixes CRUD, hierarchy, relationships/mentions, embeddings/search, playbook execution context, and schema field ops.
Proposed action: split into focused services (NodeCrud / Hierarchy / Relationship / Embedding); move playbook execution-context out of the core service into a wrapper/middleware.

Cross-cutting theme of the audit: business logic in the wrong layer β€” pull it down into focused services. This issue is the structural half of that theme. It is the highest-blast-radius refactor in the codebase β€” see Risks.

Current state (verified)

NodeService is a single struct holding store: Arc<SqliteStore>, behaviors, migration_registry, event_tx, client_id, execution_context, and (under nlp) embedding_waker. It is Clone (cheap β€” all Arc/Option). It is consumed widely as Arc<CoreNodeService> or by clone:

  • packages/daemon/src/main.rs builds the one canonical instance and clones it into every gRPC service impl (NodeServiceImpl, EmbeddingsServiceImpl, agent/capture/import services).
  • packages/daemon/src/services/*.rs, packages/agent/src/**, packages/cli/src/**, packages/core/src/playbook/**, CollectionService, EmbeddingProcessor, and a large test surface all call its methods directly.
  • with_client() (:1150) and with_execution_context() (:1160) return a cloned instance with one field set; events read client_id/execution_context in emit_event (:1177). Only one production caller of with_execution_context exists: packages/core/src/playbook/actions.rs:434.

Because callers hold the concrete type and call ~40 distinct methods, we cannot change the public call surface without editing every consumer. The chosen architecture below keeps NodeService as the public facade so the blast radius stays inside packages/core.

Target architecture

Keep NodeService as a thin facade that owns the shared state and delegates to focused sub-services. Do NOT expose sub-services to external callers (daemon/agent/cli keep calling node_service.create_node(...) etc. unchanged). This is the only option that bounds the blast radius; exposing sub-services directly would force edits across daemon/agent/cli/playbook and is explicitly out of scope.

Shared state moves into one internal context struct, cloned cheaply and shared by all sub-services:

// internal, pub(crate)
struct NodeServiceCtx {
    store: Arc<SqliteStore>,
    behaviors: Arc<NodeBehaviorRegistry>,
    migration_registry: Arc<MigrationRegistry>,
    event_tx: broadcast::Sender<EventEnvelope>,
    client_id: Option<String>,
    execution_context: Option<PlaybookExecutionContext>,
    #[cfg(feature = "nlp")] embedding_waker: Option<EmbeddingWaker>,
}

Sub-services (each a pub(crate) struct holding NodeServiceCtx, or methods grouped in impl blocks across files sharing the ctx β€” implementer's choice, but one file per concern):

Sub-service Owns Functions (current line refs)
NodeCrud create/read/update/delete + version-checked variants create_node(1850), create_node_with_parent(2069), get_node(2489), update_node_unchecked(2920), update_node(3292), delete_node_unchecked(3465), delete_with_version_check(3527), delete_node(3586), update_node_with_version_bump(4840)
Hierarchy tree reads, ordering, moves, parent edges get_children(3686), get_roots(3696), get_descendants(3730), get_children_tree(3764), get_subtree_data(3818), get_parent(3889), get_root_id(3939), move_node_unchecked(4265), move_node(4368), reorder_node(4478), create_parent_edge(4560), reorder_child(4773), upsert_node_with_parent(5845)
Relationship mentions + typed relationships create_mention(2348), delete_mention(2434), add_mention(6022), remove_mention(6105), get_mentions(6159), get_mentioned_by(6191), get_mentioning_containers(6229), create_relationship(6296), delete_relationship(6529), get_related_nodes(6607), get_inbound_relationships(6744), get_relationship_graph(6796)
Schema type/schema queries + field ops query_nodes_by_type(1195), get_schema_for_type(1288), get_task_node(2563), update_task_node(2618), get_schema_node(2702), rename_schema_field(2723), get_all_schemas(6660), get_schema_with_relationships(6703)
Bulk batch ops bulk_create(5278), bulk_create_hierarchy(5326), bulk_create_hierarchy_root_notify(5440), bulk_create_hierarchy_trusted(5568), bulk_update(5700), bulk_delete(5807)
Embedding embedding queue/waker (nlp) queue_root_for_embedding(3982), set_embedding_waker(865)
Query ad-hoc queries query_nodes(4917), query_nodes_simple(5160)

Note: create_node_with_parent straddles CRUD + Hierarchy (it calls create_parent_edge). Place it in NodeCrud and have it call into Hierarchy; do NOT duplicate hierarchy logic.

The facade keeps construction (new(769), store(1082), behaviors(1087), subscribe_to_events(1170)) and re-exposes every current pub async fn with an identical signature that delegates: pub async fn create_node(&self, ...) { self.crud().create_node(...).await } (or equivalent). No public signature changes. Private helpers (emit_event, compute_title, normalize_*, ensure_date_exists, node_exists, is_descendant, is_root_node, etc.) move to the sub-service that uses them, or to a shared pub(crate) helper module if used by more than one.

Playbook execution-context β€” move out of the core service

with_execution_context/execution_context exist only to tag emitted events with playbook_context metadata. Only playbook/actions.rs:434 sets it in production. Move this concern out of NodeService proper:

  • Keep execution_context in NodeServiceCtx (events still need it at emit time) but stop treating "scoped NodeService" as the mechanism. Introduce a lightweight wrapper in the playbook layer β€” e.g. PlaybookScopedNodes { inner: Arc<NodeService>, ctx: PlaybookExecutionContext } in packages/core/src/playbook/ that forwards the handful of mutating calls the playbook actually uses and injects the context. Delete with_execution_context from NodeService's public API.
  • If forwarding the full surface is impractical, the acceptable fallback is: keep a single pub(crate) fn scoped_for_playbook(&self, ctx) -> NodeService used only by the playbook module, and make it pub(crate) (not pub). Either way, the public API must no longer advertise playbook execution context as a first-class concern. Pick whichever is smaller; document the choice in the PR.
  • with_client(1150) stays on the facade β€” it is general-purpose event-source tagging used by tests and daemon wiring, not playbook-specific.

Phased plan

This is large; land it in reviewable phases on the same branch (separate commits, one PR):

  1. Extract NodeServiceCtx + make the facade hold it. No behavior change, all methods still on facade. Compile + full test pass. (Pure mechanical, lowest risk β€” get this green first.)
  2. Move Relationship + Schema + Query + Embedding + Bulk functions into their sub-modules, facade delegates. These have no overlap with B2. Compile + test after each group.
  3. Move CRUD, facade delegates.
  4. Move Hierarchy LAST (see Coordination β€” this is the B2 collision zone). Facade delegates.
  5. Extract playbook execution-context wrapper; delete with_execution_context from public API; fix actions.rs.

Each phase ends green (cargo test -p nodespace-core + cargo build --workspace). Do not proceed to the next phase with a red tree.

Acceptance criteria

  • NodeService retains every current pub async fn with byte-identical signatures; all external consumers (daemon, agent, cli, playbook, tests) compile without edits to their call sites (except the intentional with_execution_context removal in actions.rs).
  • Internal logic lives in focused sub-modules per the table above; node_service.rs is the facade + delegation only.
  • Each sub-service file is independently readable (< ~2k lines; no single file remains a god-object).
  • Shared mutable/Arc state consolidated in NodeServiceCtx; no field duplicated across sub-services.
  • with_execution_context removed from NodeService public API; playbook context handled by a playbook-layer wrapper; playbook/actions.rs:434 updated accordingly.
  • with_client still present and unchanged.
  • NO #[allow(dead_code)], NO #[deprecated], NO backward-compat shims, NO commented-out old code. Delete what you replace.
  • All logging via tracing; no new println!.
  • cargo clippy --workspace --all-targets -- -D warnings clean (no new suppressions).

Testing requirements

  • cargo test -p nodespace-core green (the ~3k-line in-file test section at node_service.rs:~8900+ must pass unchanged β€” it is the regression oracle for this refactor; do not weaken it).
  • cargo test --workspace green (daemon gRPC round-trips, agent, cli integration all exercise the facade).
  • bun run test:all green (frontend talks to daemon β†’ exercises the facade end-to-end).
  • No new test failures vs. baseline recorded at startup.

Risks

  • Highest blast radius in the repo. Mitigation: facade pattern keeps signatures identical so consumers don't change; phase it; keep the tree green between phases.
  • Private helpers are shared across concerns (e.g. node_exists, is_descendant, compute_title). Audit each before moving β€” put genuinely shared ones in a pub(crate) helper module rather than duplicating.
  • Phase 4 (Hierarchy) collides with B2 β€” see Coordination.

Coordination with #1237 (remove eventual-consistency retry loops)

#1237 lands first. #1237 strips the sleep/retry loops out of the hierarchy functions (create_node_with_parent lookup retry at 2098, and the entire retry/verify machinery in create_parent_edge at 4566–4742). B1 must not start Phase 4 (Hierarchy extraction) until #1237 is merged. Phases 1–3 + 5 touch code B2 does not, so they may proceed in parallel with B2. After #1237 merges, rebase, then move the now-simplified hierarchy functions in Phase 4. This avoids B1 carefully relocating retry loops that #1237 is simultaneously deleting.

Startup / PR sequence (NodeSpace standard)

  1. git status + git pull origin main on primary checkout, then EnterWorktree({name: "issue-<N>-decompose-nodeservice"}).
  2. Inside worktree: bun install, run baseline cargo test -p nodespace-core + bun run test, bun run gh:comment <N> "baseline: ...", bun run gh:assign <N> "@me", bun run gh:status <N> "In Progress".
  3. Implement in phases (above). Use tracing not println!. No lint suppression.
  4. Before PR: cargo test --workspace, bun run test:all (no new failures), bun run quality:fix then commit (note: quality:fix runs cargo fmt --all and may reformat unrelated files β€” git status and revert stray changes before committing).
  5. bun run gh:pr <N>. Run /pragmatic-code-review. After approval: gh pr view <PR#>, ExitWorktree({action: "remove", discard_changes: true}), gh pr merge <PR#> --squash --delete-branch, git pull origin main, bun run gh:status <N> "Done".

Spun off from #1228 (architectural audit), finding B1.

Activity

  1. malibio commented on May 29, 2026

    @malibio
    CollaboratorAuthor

    Baseline: Frontend 131 files / 3924 tests passed. Rust core: 132 passed, 0 failed. Starting implementation of Phases 1-3 and 5 (Phase 4/Hierarchy deferred until #1237 merges).

  2. self-assigned this
    on May 29, 2026
  3. added 2 commits that reference this issue on May 30, 2026
    7dde74a
    7a861f4
  4. added a commit that references this issue on Jun 22, 2026
    afcce16
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