--- name: neode-audit description: Audit how a codebase uses neode/Neo4j — inventory every query and CRUD operation, map the graph model, detect N+1s / find-feeders / check-then-create / guard-write pairs / re-read tax / row plumbing, project the after-state, and triage findings into library issues vs adoption tasks vs bugs. Use when asked to audit, inventory, review or reduce Neo4j/OGM usage. --- # neode-audit — audit runbook Audit how a codebase uses neode / Neo4j: inventory the queries, map the graph model, detect the inefficiencies mechanically, project the after-state, triage the findings. The audit is read-only — its deliverables are one report document and Linear issues. API facts come from the generated docs, never from training data: the [neode skill](../neode/SKILL.md), [llms-full.txt](../../llms-full.txt) and the per-area pages under [docs/agent/](../../docs/agent/). This file is hand-maintained — the generated outputs regenerate with `pnpm docs:agents`; this one you edit. ## Phase 0 — scope the data access - **The audit is read-only.** It writes exactly two kinds of artifacts: the report document and Linear issues. No source changes, ever — findings become tasks, not edits. - Exclude the library's own source, node_modules, lockfiles; include app service/domain code and (only if asked) tests. - Locate: model definition package(s), the raw-Cypher entry points (`db.cypher` / `writeCypher` or equivalents), the connection setup (real driver vs embedded engine), and how the DB handle reaches call sites (context object? singleton?). - **Disclose the backend dialect**: record which engine the audit's claims were checked against (embedded Relate vs real server) — several behaviours differ (e.g. pattern expressions rejected in RETURN projections on the embedded engine) and every projection inherits that caveat. ## Phase 1 — inventory - Count call sites per file: raw reads, raw writes, and each OGM method (`create` / `merge` / `update` / `find` / `all` / `relate` / `delete`). - List every exported function that touches the DB: CRUD classification (C/R/U/D, note multi-step), one-line purpose, and a query-count note when it runs several (e.g. "5 queries", "N+1 per row"). - Note model registry order and decorators of consequence: `unique` / `index` / `@Filter` / cascade / soft-delete. ## Phase 2 — graph model - Extract node labels and relationship types from BOTH the Cypher strings and the model declarations; mark which relationships are declared vs edge-only (written via relate() / matched in raw Cypher only). - Note self-referential edges and declared-but-unused models. - Render a mermaid diagram grouped by domain subgraphs; solid arrows = declared, dotted = edge-only. ## Phase 3 — mechanical inefficiency scan Run each detector and record counts with **file:line anchors on every finding** (unanchored findings waste review time): 1. **Loop-nested queries** — `await cypher(...)` / `find(...)` within a few lines after a `for` / `forEach` opener. Classify: per-row enrichment (→ with-specs or `IN $ids` batch), per-spec validation loops (→ batch `IN` read), seed loops (→ mergeOn). 2. **Create-paired relates** — relate() within ~8 lines after create() → nested-create candidates (NTS-627: pk values relate in the root statement). 3. **Find-before-relate feeders** — a find whose result only feeds relate() → die with nested create. 4. **Check-then-create probes** — existence `MATCH … count` before create → mergeOn / conditional create (the outcome's `created` flag reports which happened, NTS-630). 5. **Read→validate→write pairs** — a read gating a guarded write → single guard statement (`MATCH … WHERE … SET … RETURN n`, zero rows → 404); removes the TOCTOU race. 6. **Write re-read tax** — check whether the library re-hydrates writes (FindByIdService or similar); if so every write is ≥2 statements (fixed by RETURN hydration, NTS-633). 7. **Row plumbing** — count `.get('col')` calls, inline `{ get: … }` casts, `records[0]` scalar probes → rows() / recordTransformer candidates (NTS-632). 8. **Compute-then-write patterns** — head-of-chain reads (`ORDER BY … LIMIT 1` before create), `SET copy = properties(src)` clones, derived-stamp follow-up updates → write-time expression candidates (NTS-629). 9. **Quirks** — writes executed through the read API, queries missing the tenancy predicate, deletes without guards (NTS-634's `where` + `ifExists`), missing indexes on hot lookup properties. ## Phase 4 — decision rules - **Fold a probe into the main read UNLESS**: it is per-request security revalidation (keep); JS-side validation needs more than a predicate (keep separate); folding changes failure semantics (404 vs 403); or ordering/idempotency requires per-iteration queries. - **Convert to eager with-spec UNLESS**: JS-side post-filters dominate (reveal gating, per-row redaction); the read is a variable-length path; it is a tenant-wide aggregate. Prerequisite: the many-sides must be declared (`@OneToMany`) first — list declaration-only work separately. Respect deliberate modelling (e.g. a primary-owner `@OneToOne` with multi-owner reads kept in Cypher). - **Always raw Cypher, name them in the report so nobody "fixes" them**: GROUP BY aggregates, variable-length walks, reveal/redaction post-filtering, per-request session checks. - Never recommend folding a hash-chain head read into application JS; that is a write-time-expression candidate (NTS-629). ## Phase 5 — projection - Per-file call-site table: before → after, with the per-issue mechanics that produce each delta. - Statements-per-key-operation table (today → after) for the hot paths — call sites understate the win. - Separate three metrics: call sites, statements per operation, round trips (parallel()/batching reduces the third only — NTS-631). - Mark everything as derived estimates with noise bounds; list what deliberately does not change. ## Phase 6 — triage & deliverable - Classify every finding: **library gap** (file upstream: problem, proposal, acceptance ideas) / **adoption task** (feature exists, app hasn't used it) / **app bug** (unscoped reads, read-API writes, missing indexes, non-idempotent seeds). - Tag each finding **quick win vs structural** (guard-updates and indexes are quick wins; with-spec conversions are structural — the report should let the reader start with the quick wins). - Write ONE report document mirroring this layout: 1 architecture · 2 per-module CRUD · 3 labels+rels · 4 counts · 5 notable patterns · 6 graph-model diagram · 7 follow-ups in the three buckets · 8 projected before/after. End with the exact paths written. - **Emit the counts machine-readably too** (a JSON sidecar: per-file/method counts, detector hits) — so a re-run of the audit after changes is diff-able and shows what actually moved. The report is a baseline, not a one-off. ## Phase 7 — review artifacts (produce these for every library gap filed) 1. **Expected-Cypher snapshots**: for each proposal, render the target Cypher as it should read after implementation (before/after pairs where the change rewrites a statement). Reviewers argue with Cypher, not prose. Label them review targets, not contracts — real aliasing/WITH-bridging may differ. 2. **Statement-count meter**: the library emits QUERY_EXECUTED per statement — propose/ship a test helper (`expectStatements(runner, n)`) and assert it in every acceptance idea that claims "reduces queries". One small file; the objective meter for the whole issue family. 3. **Spike protocol**: any design with an unresolved risk gets a spike BEFORE implementation, or the issue is labelled needs-spike. Typical spike triggers: atomicity across sessions (two-phase commit), hydration from RETURN on ON CREATE/ON MATCH branches, engine-dialect support for write-side expressions. 4. **Evidence bundle**: the report lives in the consumer's repo — maintainers can't see it. Produce a sanitized excerpt (counts tables, detector hits, worked example) attachable to the issues or a gist. 5. **Reference conversion**: for adoption tasks, convert ONE function end-to-end (declarations + eager read + test reshape) as the pattern PR the rest follows. ## Detection commands Adapt `` / entry-point names to the consumer before running: ```sh # N+1 detector: query sites inside loop bodies grep -rn -B6 "await .cypher(" --include='*.ts' src | grep -E "for ?\(|forEach" # proximity pairs (create→relate, find→relate): run the python proximity pass shown in the worked example's report ``` ## Agent notes Worked example (the consumer audit that produced this runbook): a repo of ~340 raw + ~360 OGM call sites yielded 118 relate sites of which 87 create-paired; 49 of 122 find sites were relate-feeders; 33 loop-nested query sites; ~70–90 DB-hitting auth probes; ~270 lines of row plumbing; read projection 277 → ~232 conservative / ~170 with the full pass. Related library issues: NTS-627 (nested create), NTS-628 (edge properties), NTS-629 (write-time expressions), NTS-630 (mergeOn summary), NTS-631 (parallel), NTS-632 (rows/recordTransformer), NTS-633 (RETURN hydration), NTS-634 (single-statement deletes).