Repository navigation
refactor: replace graph core with deterministic directed multigraph - #583
Conversation
📝 WalkthroughWalkthroughThis PR replaces the legacy graph core with a deterministic directed multigraph domain (src/domain/graph), adds canonical JSON serialization and artifact I/O, rewrites the extraction-to-graph build pipeline, deletes legacy export/HTML/Obsidian/Cypher/GraphML surfaces, removes CLI flags (--no-html, --directed/--undirected, export toggles), updates all runtime/infrastructure consumers to the new relation-based graph API, and updates governance docs and extensive tests. ChangesDirected Multigraph Core Reset
Estimated code review effort: 5 (Critical) | ~150 minutes Possibly related issues
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/pipeline/community-details.ts (1)
88-121: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
communityDetailsMid/communityDetailsMacroeach do multiple full-graphedgeEntries()scans per community.
edge_count,externalInDegree, andexitPointMapincommunityDetailsMid(Lines 88-99, 110-116) each iterate every edge in the whole graph and filter by community membership, andcommunityDetailsMacro(Lines 187-200) does the same again. This replaces the prior degree-boundedincidentNeighborstraversal with an O(E) full scan, repeated per function. Sincedocs.ts'sgenerateDocscallscommunityDetailsMidonce per community (for every community with >1 node), total cost becomes O(communities × E), which for a large codebase with many communities can be significantly more expensive than the previous approach.Consider bounding these to the community's own nodes using the existing
graph.successors(nodeId)/graph.predecessors(nodeId)plusgraph.edgesBetween(...), so the work scales with community size × average degree instead of total edge count.Also applies to: 187-200
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/pipeline/community-details.ts` around lines 88 - 121, Update communityDetailsMid and communityDetailsMacro to avoid full-graph edgeEntries() scans for edge_count, externalInDegree, and exitPointMap. Traverse only each community’s node IDs using graph.successors(), graph.predecessors(), and graph.edgesBetween(), while preserving the existing membership filters, counts, labels, and five-item limits.
🧹 Nitpick comments (1)
src/runtime/http-server.ts (1)
232-236: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
/graph.jsonnow double-parses the artifact per request.
loadGraph(graphPath)fully deserializes the artifact (validateGraphPath + statSync + readFileSync + JSON parse) purely to trigger the regeneration-error check, and its result is discarded; the raw bytes are then read again via a secondreadFileSync. On a frequently-hit endpoint this doubles I/O and CPU cost per request for no functional benefit beyond validation.Consider reusing the already-loaded/cached
graph()loader (used by/stats,/community, etc.) for validation instead of a freshloadGraphcall, or skip the eager validation and let a parse failure surface naturally when needed.♻️ Possible approach
if (url.pathname === '/graph.json') { - loadGraph(graphPath) + graph() sendText(response, 200, readFileSync(graphPath, 'utf8'), 'application/json; charset=utf-8', resourceFreshnessHeaders(resourceFreshnessMetadata(graphPath, graphPath))) return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/http-server.ts` around lines 232 - 236, Remove the discarded loadGraph(graphPath) call from the /graph.json handler to avoid parsing and reading the artifact twice per request. Reuse the existing cached graph() loader for validation if that check must remain; otherwise rely on the subsequent response read and its natural parse/error behavior, while preserving the current response payload and headers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/workflows/ci.yml:
- Around line 36-37: Update the actions/checkout configuration associated with
fetch-depth to set persist-credentials to false, preventing the GITHUB_TOKEN
from being stored in the repository’s Git configuration. Preserve the existing
checkout behavior and fetch-depth setting; do not add authenticated Git
operations unless they are already required later in the job.
In `@src/domain/graph/directed-multigraph.ts`:
- Around line 222-229: Update the directed multigraph’s degree bookkeeping so
degree(id) reads an O(1) per-node counter instead of scanning edgeMap. Add and
maintain that counter in the graph state, increment it for both source and
target endpoints in addEdge (including twice for self-loops and once per
parallel edge), and preserve the existing degree result semantics.
In `@src/pipeline/analyze.ts`:
- Around line 955-964: Update graphDiff’s edge comparison around oldEdges,
newEdges, newEdgesList, and removedEdgesList to detect edges sharing the same
identity whose attributes, including confidence or confidence_score, changed.
Surface these attribute-only changes in the diff using the existing output
contract, such as paired old/new entries or a changed_edges collection, and add
regression coverage for a confidence-only change.
In `@src/pipeline/extract/frameworks/redux.ts`:
- Around line 1114-1118: The node construction in the Redux extraction flow must
apply the computed sourceLine even when baseNode exists. Update the addNode call
around baseNode and createNode so the copied node uses sourceLine for its
location and matching provenance while preserving baseNode’s extra attributes;
keep the existing fallback behavior for nodes without a baseNode.
---
Outside diff comments:
In `@src/pipeline/community-details.ts`:
- Around line 88-121: Update communityDetailsMid and communityDetailsMacro to
avoid full-graph edgeEntries() scans for edge_count, externalInDegree, and
exitPointMap. Traverse only each community’s node IDs using graph.successors(),
graph.predecessors(), and graph.edgesBetween(), while preserving the existing
membership filters, counts, labels, and five-item limits.
---
Nitpick comments:
In `@src/runtime/http-server.ts`:
- Around line 232-236: Remove the discarded loadGraph(graphPath) call from the
/graph.json handler to avoid parsing and reading the artifact twice per request.
Reuse the existing cached graph() loader for validation if that check must
remain; otherwise rely on the subsequent response read and its natural
parse/error behavior, while preserving the current response payload and headers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9d18b3f1-0765-45a5-9486-30c427b81b4c
📒 Files selected for processing (191)
.github/ISSUE_TEMPLATE/design_partner_report.yml.github/workflows/ci.ymldocs/auto-refresh.mddocs/benchmarks/2026-05-02-govalidate-pr-review/README.mddocs/benchmarks/2026-05-11-spi-vs-legacy/README.mddocs/benchmarks/2026-05-11-spi-vs-legacy/run.shdocs/claims-and-evidence.mddocs/core-reset/removal-manifest.ymldocs/core-reset/scorecard.mddocs/design-partners.mddocs/proof-workflows.mddocs/reference/cli-and-mcp.mddocs/roadmap.mddocs/share-safe-dashboard-decision.mddocs/tutorials/agent-quickstarts.mddocs/tutorials/getting-started.mddocs/tutorials/sample-workspace.mdexamples/sample-workspace/README.mdsrc/adapters/filesystem/graph-artifact.tssrc/application/build-graph.tssrc/cli/main.tssrc/cli/parser.tssrc/contracts/generation-policy.tssrc/contracts/graph.tssrc/core/schema/normalize.tssrc/domain/graph/artifact.tssrc/domain/graph/canonical-json.tssrc/domain/graph/directed-multigraph.tssrc/infrastructure/background-auto-refresh.tssrc/infrastructure/benchmark.tssrc/infrastructure/benchmark/generate-performance.tssrc/infrastructure/benchmark/quality.tssrc/infrastructure/benchmark/questions.tssrc/infrastructure/benchmark/runner.tssrc/infrastructure/benchmark/suite.tssrc/infrastructure/compare.tssrc/infrastructure/context-pack-command.tssrc/infrastructure/context-prompt-command.tssrc/infrastructure/doctor.tssrc/infrastructure/generate.tssrc/infrastructure/generation-policy.tssrc/infrastructure/handoff-command.tssrc/infrastructure/install-skill-templates.tssrc/infrastructure/neo4j.tssrc/infrastructure/time-travel.tssrc/infrastructure/try-command.tssrc/infrastructure/watch.tssrc/pipeline/analyze.tssrc/pipeline/build.tssrc/pipeline/cluster.tssrc/pipeline/community-details.tssrc/pipeline/community-naming.tssrc/pipeline/docs.tssrc/pipeline/export.tssrc/pipeline/export/community-summary.tssrc/pipeline/export/overview-bridges.tssrc/pipeline/export/overview-navigation.tssrc/pipeline/extract.tssrc/pipeline/extract/frameworks/redux.tssrc/pipeline/federate.tssrc/pipeline/report.tssrc/pipeline/spi/index.tssrc/pipeline/spi/projector.tssrc/pipeline/wiki.tssrc/runtime/context-pack-recovery.tssrc/runtime/context-pack.tssrc/runtime/diff.tssrc/runtime/direction.tssrc/runtime/feature-map.tssrc/runtime/freshness.tssrc/runtime/graph-summary.tssrc/runtime/http-server.tssrc/runtime/impact.tssrc/runtime/implementation-checklist.tssrc/runtime/implementation-pack.tssrc/runtime/pr-impact.tssrc/runtime/relevant-files.tssrc/runtime/retrieve.tssrc/runtime/retrieve/conceptual-fallback.tssrc/runtime/retrieve/slicing.tssrc/runtime/risk-map.tssrc/runtime/serve.tssrc/runtime/stdio-server.tssrc/runtime/stdio/prompts.tssrc/runtime/stdio/resources.tssrc/runtime/stdio/tools.tssrc/runtime/time-travel.tssrc/shared/discovery-safety.tssrc/shared/graph-source-root.tstests/fixtures/cross-layer-monitor-flow.tstests/fixtures/federation-flagship/backend/graph.jsontests/fixtures/federation-flagship/frontend/graph.jsontests/fixtures/federation-flagship/shared/graph.jsontests/fixtures/madar-self-retrieval.tstests/helpers/graph-artifact.tstests/unit/analyze.test.tstests/unit/background-auto-refresh.test.tstests/unit/benchmark-quality.test.tstests/unit/benchmark-suite.test.tstests/unit/benchmark.test.tstests/unit/build.test.tstests/unit/cli.test.tstests/unit/cluster.test.tstests/unit/community-details.test.tstests/unit/community-naming.test.tstests/unit/compare-native-agent.test.tstests/unit/compare.test.tstests/unit/context-pack-adapter-gating.test.tstests/unit/context-pack-command.test.tstests/unit/context-pack-recovery.test.tstests/unit/context-prompt-command.test.tstests/unit/core-reset-governance.test.tstests/unit/directed-multigraph.test.tstests/unit/doctor.test.tstests/unit/export.test.tstests/unit/extract-duplicate-file-stems.test.tstests/unit/extract-frameworks.test.tstests/unit/extract-go.test.tstests/unit/extract-tsconfig-alias-cross-file.test.tstests/unit/feature-map.test.tstests/unit/federate.test.tstests/unit/freshness-surfaces.test.tstests/unit/generate-spi-flag.test.tstests/unit/generate.test.tstests/unit/generation-policy.test.tstests/unit/getting-started-docs.test.tstests/unit/graph-summary.test.tstests/unit/handoff-command.test.tstests/unit/helpers/pack-quality.tstests/unit/http-server.test.tstests/unit/impact.test.tstests/unit/implementation-checklist.test.tstests/unit/implementation-pack.test.tstests/unit/indexing-completeness.test.tstests/unit/indexing-generate.test.tstests/unit/mcp-response-evidence.test.tstests/unit/neo4j.test.tstests/unit/normalize.test.tstests/unit/pack-quality-helper.test.tstests/unit/pipeline-stage-characterization.test.tstests/unit/pipeline.test.tstests/unit/pr-impact.test.tstests/unit/proof-report.test.tstests/unit/relevant-files.test.tstests/unit/report.test.tstests/unit/retrieval-gate-entry-points.test.tstests/unit/retrieval-gate-override-surface.test.tstests/unit/retrieval-pipeline-stages.test.tstests/unit/retrieve-conceptual-fallback.test.tstests/unit/retrieve-cross-layer-flow.test.tstests/unit/retrieve-framework-boost-v0-19.test.tstests/unit/retrieve-go.test.tstests/unit/retrieve-metadata-boost-133.test.tstests/unit/retrieve-production-correctness.test.tstests/unit/retrieve-prompt-symbol-boost.test.tstests/unit/retrieve-retrieval-levels.test.tstests/unit/retrieve-self-hosted-concepts.test.tstests/unit/retrieve-semantic.test.tstests/unit/retrieve-slice-surface.test.tstests/unit/retrieve-slice-v1.test.tstests/unit/retrieve.test.tstests/unit/review-compare.test.tstests/unit/risk-map.test.tstests/unit/sample-workspace.test.tstests/unit/schema-v2.test.tstests/unit/serve-queries.test.tstests/unit/serve.test.tstests/unit/spi-nest-di-runtime-calls-realistic.test.tstests/unit/spi-nest-di-runtime-calls.test.tstests/unit/spi-projector.test.tstests/unit/spi-routing-controllers-runtime.test.tstests/unit/spi-scoped-root-tsconfig.test.tstests/unit/stdio-pr-impact.test.tstests/unit/stdio-prompts.test.tstests/unit/stdio-resources.test.tstests/unit/stdio-semantic-resilience.test.tstests/unit/stdio-semantic.test.tstests/unit/stdio-server.test.tstests/unit/stdio-slice-surface.test.tstests/unit/stdio-tool-profile.test.tstests/unit/time-travel-infrastructure.test.tstests/unit/time-travel.review-regressions.test.tstests/unit/time-travel.test.tstests/unit/try-command.test.tstests/unit/watch.test.tstests/unit/why-madar-doc.test.tstests/unit/wiki.test.tstests/unit/workspace.test.tstests/unit/worktree-cli-artifacts.test.tstools/eval/core-reset/README.mdtools/eval/core-reset/record-baseline.mjs
💤 Files with no reviewable changes (16)
- src/core/schema/normalize.ts
- src/pipeline/export/overview-bridges.ts
- src/contracts/graph.ts
- src/pipeline/build.ts
- src/pipeline/export/overview-navigation.ts
- src/runtime/direction.ts
- src/infrastructure/benchmark/suite.ts
- docs/auto-refresh.md
- tests/unit/pack-quality-helper.test.ts
- src/pipeline/export.ts
- src/pipeline/export/community-summary.ts
- tests/unit/helpers/pack-quality.ts
- src/infrastructure/background-auto-refresh.ts
- tests/unit/export.test.ts
- src/cli/main.ts
- tests/unit/benchmark-suite.test.ts
|
Review follow-up for head Addressed all six substantive CodeRabbit findings:
The two generic warnings were investigated and intentionally require no code change:
Final local evidence: 205/205 test files and 2,819 tests passed (2 skipped); coverage gates passed; typecheck/build/release/registry/pack parity/isolation/audit/pack dry-run passed; generated-demo eval reached 100% recall, 1.000 MRR, and 100% snippet coverage. Production delta is |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime/freshness.ts (1)
408-412: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winValidate and hash the same bounded artifact bytes.
loadGraphArtifact()validates one read, thenreadFileSync()hashes another. A concurrent rewrite can therefore publish a version for unvalidated bytes; the mtime/size cache can also skip validation after a same-metadata replacement. Read once withreadGraphArtifact(), validate that string, and hash that same string before any cache return.Proposed fix
- loadGraphArtifact(safeGraphPath) - const graphVersion = createHash('sha256').update(readFileSync(safeGraphPath)).digest('hex').slice(0, VERSION_HASH_LENGTH) + const artifact = readGraphArtifact(safeGraphPath) + deserializeGraphArtifact(artifact) + const graphVersion = createHash('sha256').update(artifact).digest('hex').slice(0, VERSION_HASH_LENGTH)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/freshness.ts` around lines 408 - 412, Update the freshness artifact flow around loadGraphArtifact and the graphVersion calculation to call readGraphArtifact once and retain its bounded string result. Validate that same string, then hash those exact bytes before any cache return, eliminating the separate readFileSync call and ensuring concurrent rewrites or same-metadata replacements cannot produce an unvalidated version.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/unit/http-server.test.ts`:
- Line 197: Remove the duplicate const handle declarations in each affected test
block around startGraphServer, including the blocks at the referenced locations.
Retain a single handle declaration per test and preserve the existing server
setup and usage.
---
Outside diff comments:
In `@src/runtime/freshness.ts`:
- Around line 408-412: Update the freshness artifact flow around
loadGraphArtifact and the graphVersion calculation to call readGraphArtifact
once and retain its bounded string result. Validate that same string, then hash
those exact bytes before any cache return, eliminating the separate readFileSync
call and ensuring concurrent rewrites or same-metadata replacements cannot
produce an unvalidated version.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9f74ba58-bc4f-4323-9d07-d2d1f299df29
📒 Files selected for processing (18)
.github/workflows/ci.ymldocs/core-reset/removal-manifest.ymldocs/core-reset/scorecard.mddocs/roadmap.mdsrc/adapters/filesystem/graph-artifact.tssrc/application/build-graph.tssrc/domain/graph/artifact.tssrc/domain/graph/directed-multigraph.tssrc/pipeline/analyze.tssrc/pipeline/community-details.tssrc/pipeline/extract/frameworks/redux.tssrc/runtime/freshness.tssrc/runtime/http-server.tstests/unit/analyze.test.tstests/unit/community-details.test.tstests/unit/directed-multigraph.test.tstests/unit/extract-frameworks.test.tstests/unit/http-server.test.ts
🚧 Files skipped from review as they are similar to previous changes (13)
- .github/workflows/ci.yml
- src/adapters/filesystem/graph-artifact.ts
- docs/core-reset/scorecard.md
- tests/unit/community-details.test.ts
- src/domain/graph/artifact.ts
- docs/roadmap.md
- tests/unit/directed-multigraph.test.ts
- src/application/build-graph.ts
- docs/core-reset/removal-manifest.yml
- src/domain/graph/directed-multigraph.ts
- src/pipeline/analyze.ts
- tests/unit/extract-frameworks.test.ts
- src/pipeline/extract/frameworks/redux.ts
|
Follow-up for CodeRabbit incremental review on head
Focused verification: 69/69 tests, typecheck, build, packed-runtime parity, Core Reset isolation, audit, and diff checks are green. Updated production evidence: 178 TypeScript files / 93,792 LOC, |
|
@coderabbitai review |
✅ Action performedReview finished.
|
Summary
src/domain/graph/**madar.graphartifact schema, reject old artifacts withmadar generate . --update, and delete the legacy graph core plus HTML/SVG/GraphML/Cypher/Obsidian exporter surfaceThe application/filesystem boundary now builds and persists the canonical graph. Existing extractor, SPI, runtime, federation, and benchmark consumers were adapted mechanically; no second store, V1/V2 mode, converter, fallback loader, feature flag, runtime dependency, or repository-specific retrieval rule was added.
Testing
npm run test:run -- --maxWorkers=1— 205/205 files; 2,820 passed, 2 skipped (current-head CI)npx vitest run tests/unit/core-reset-baseline.test.ts tests/unit/directed-multigraph.test.ts tests/unit/core-reset-governance.test.ts --maxWorkers=1— 35/35npx vitest run tests/unit/retrieve.test.ts tests/unit/compare-native-agent.test.ts tests/unit/core-reset-governance.test.ts --maxWorkers=1— 193/193npm run test:coverage -- --maxWorkers=1— 205/205 files; 85.23% statements, 76.82% branches, 91.56% functions, 85.70% linesnpm run typechecknpm run buildnpm run release:verifynpm run registry:validatenpm run verify:pack-paritynode tools/eval/core-reset/verify-isolation.mjsnpm auditnpm run pack:dry-rungit diff --checkCore Reset contract
directed-multigraph(rebuild),provenance(preserved contract)src/contracts/graph.tssrc/pipeline/build.tssrc/pipeline/export.tssrc/core/schema/normalize.tssrc/runtime/direction.tssrc/pipeline/export/community-summary.tssrc/pipeline/export/overview-bridges.tssrc/pipeline/export/overview-navigation.tsReset scope checks
src/Checklist
Related issues
Closes #582
Summary by CodeRabbit
graph.jsonartifact format with deterministic IDs and stronger load/save validation.generate/watchand related guidance now focus ongraph.json+GRAPH_REPORT.md(and optional wiki), removing legacy HTML/export options; runtime no longer servesgraph.html.--no-htmlreferences).