Skip to content

CF-4 hierarchy and cognitive paging - #13

Merged
hardcoreerik merged 2 commits into
masterfrom
codex/context-fabric-cf4-hierarchy-paging
Jun 29, 2026
Merged

CF-4 hierarchy and cognitive paging#13
hardcoreerik merged 2 commits into
masterfrom
codex/context-fabric-cf4-hierarchy-paging

Conversation

@hardcoreerik

@hardcoreerik hardcoreerik commented Jun 29, 2026

Copy link
Copy Markdown
Owner

Summary

  • Build the CF-4 framework in one pass: hierarchy persistence, reducer, deterministic Quick/Study planning, bounded evidence packing, explicit source reopen, and citation verification.
  • Add focused CF-4 tests for coverage visibility, bounded fan-in, 8K prompt budgeting, source rereads, and citation acceptance/rejection.
  • Update the Context Fabric spec with the new CF-4 implementation status.

Verification command

  • dotnet test OrchestratorIDE.UnitTests/OrchestratorIDE.UnitTests.csproj --filter "FullyQualifiedName~ContextFabricCf4Tests"
  • dotnet test OrchestratorIDE.UnitTests/OrchestratorIDE.UnitTests.csproj --filter "FullyQualifiedName~ContextFabric"

Files changed

  • OrchestratorIDE.Avalonia/OrchestratorIDE.Avalonia.csproj
  • OrchestratorIDE/Services/ContextFabric/ContextFabricIngestionContracts.cs
  • OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs
  • OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs
  • OrchestratorIDE/Services/ContextFabric/FabricReducer.cs
  • OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
  • OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs
  • OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs
  • OrchestratorIDE/Services/Data/Migrations.cs
  • OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs
  • docs/The Orc Context Fabric.md

Scope explicitly excluded

  • CF-5 Library UI
  • CF-6 HIVE stage engine and distributed readers
  • CF-7 Exhaustive mode and benchmark runners
  • CF-8 multimodal/vector/cross-CodeGraph follow-ons
  • Avalonia UI work beyond compile wiring for the new CF-4 services

Confirmation

  • CF-3 was already merged before this work.
  • This branch starts from current master at 3cf0c34.

Summary by CodeRabbit

  • New Features

    • Added support for hierarchical context handling, including improved retrieval planning and evidence packaging.
    • Introduced clearer citation outcome labels and more reliable source-backed verification.
  • Bug Fixes

    • Improved document and memory handling to better respect coverage, limits, and source reopening when context is incomplete.
    • Strengthened validation so invalid inputs are rejected earlier and more consistently.
  • Documentation

    • Updated the design notes to reflect the latest context-processing behavior and test coverage.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Phase CF-4 adds SQLite schema migration 11 (fabric_memory_nodes, fabric_memory_memberships), new data contracts, and four new services: FabricReducer (hierarchical memory tree), FabricQueryPlanner (Quick/Study mode with source reopening), EvidencePackBuilder (token-budget greedy packing), and FabricCitationVerifier (exact-match + repair + label resolution). Repository APIs, project wiring, and an end-to-end NUnit test suite are included.

Changes

CF-4 Hierarchy and Cognitive Paging

Layer / File(s) Summary
Schema migration and data contracts
OrchestratorIDE/Services/Data/Migrations.cs, OrchestratorIDE/Services/ContextFabric/ContextFabricIngestionContracts.cs
Migration 11 creates fabric_memory_nodes and fabric_memory_memberships with CHECK constraints, foreign keys, and indexes. New constant classes define coverage status, query modes, and citation labels. New sealed records define memory node/membership entries, reducer/planner options with Validate(), evidence items/packs, and citation verification results.
Repository APIs for memory nodes and claims
OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs, OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs
DocumentGraphRepository gains ListClaimsForDocument, ReplaceMemoryNodesForDocument (transactional delete+insert with ValidateMemoryMemberships), GetMemoryNode, ListMemoryNodes, ListMemoryMemberships, MapMemoryNode, and SQL insert helpers. FabricLibraryRepository gains GetSegmentsByIds.
FabricReducer: hierarchical memory construction
OrchestratorIDE/Services/ContextFabric/FabricReducer.cs
ReduceDocument loads segments and up to 4096 claims, builds leaf nodes via CreateLeaf, iteratively chunks children by FanIn into higher-level memory nodes with aggregated summaries and coverage status, generates deterministic node IDs via SHA-256, and persists via ReplaceMemoryNodesForDocument.
FabricQueryPlanner: Quick/Study mode planning
OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
BuildPlan resolves Quick/Study mode via ClassifyMode keyword heuristic or explicit parameter, retrieves search hits, selects highest-generation summary node IDs, and in Study mode runs ReopenSegments—a BFS over memory-node memberships using token-overlap to skip well-covered nodes and reopen child segments up to maxSourceOpens.
EvidencePackBuilder and FabricCitationVerifier
OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs, OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs
EvidencePackBuilder.Build enumerates and deduplicates candidates, then greedily fills an included list within a token budget. FabricCitationVerifier.VerifyClaim attempts exact match via CharStart/CharEnd + SHA-256, optionally repairs offsets by unique substring search, and resolves an overall label via token-overlap and negation contradiction heuristics.
End-to-end tests and project wiring
OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs, OrchestratorIDE.Avalonia/OrchestratorIDE.Avalonia.csproj, docs/The Orc Context Fabric.md
ContextFabricCf4Tests covers migration table creation, reducer child counts/coverage, FanIn bounding, 8K evidence budget, Quick/Study planning, citation acceptance/rejection/contradiction, and ReplaceMemoryNodesForDocument negative cases. Avalonia csproj gains Compile entries for the four new files. Docs note CF-4 implementation status.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • hardcoreerik/TheOrc#10: Extends the same FabricLibraryRepository class that CF-4 further extends with GetSegmentsByIds, used by EvidencePackBuilder and FabricCitationVerifier.

Poem

🐇 Hoppity hop through the memory tree,
Nodes chunked by FanIn, as tidy as can be!
The planner says Quick, the planner says Study,
Citation digests keep the evidence un-muddy.
Budget of tokens? Eight thousand, no more—
This rabbit counts carefully, right to the core. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main CF-4 hierarchy and paging work.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/context-fabric-cf4-hierarchy-paging

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (1)
OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs (1)

85-102: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Batch GetSegmentsByIds instead of looping through GetSegment.

This helper still does one SQL round trip per unique ID. On the new reopen/evidence path, that turns a bounded segment fetch into avoidable N+1 queries. A single IN query plus in-memory reordering would keep the same semantics.

🤖 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 `@OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs` around
lines 85 - 102, `FabricLibraryRepository.GetSegmentsByIds` still issues one
`GetSegment` lookup per unique id, causing an N+1 query pattern. Update this
method to fetch all requested segment ids in a single batch query (for example,
via the repository/data access path used by `GetSegment`) and then de-duplicate
and preserve the requested semantics in memory, returning only non-null matches
from the batched result.
🤖 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 `@OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs`:
- Around line 87-112: The
EvidencePackBuilder_Respects_8k_Budget_And_Reserves_Response_Tokens test is not
forcing any evidence trimming, so it never validates the excluded-evidence path.
Update the test around FabricQueryPlanner.BuildPlan and
EvidencePackBuilder.Build by either lowering the prompt budget or expanding the
seeded claims so the pack exceeds budget, then assert that pack.Excluded is
non-empty instead of using a tautological count check. Keep the existing budget
and reserve assertions, but make the test explicitly cover the trimming behavior
that EvidencePackBuilder is supposed to record.

In `@OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs`:
- Around line 263-290: Validate and reject invalid hierarchy memberships before
writing them in ReplaceMemoryNodesForDocument and the related
InsertMemoryMembershipOn path. Right now only the node DocumentId is checked,
while memberships can still point to a parent/child pair that crosses documents
or references a missing/dangling child; add explicit validation that each
membership belongs to the same document/corpus as the current replacement set
and that the parent-child relationship is consistent before calling
InsertMemoryNodeOn or InsertMemoryMembershipOn. Reuse the existing symbols
ReplaceMemoryNodesForDocument and InsertMemoryMembershipOn so the checks happen
at the persistence boundary, not by rewriting ParentNodeId during insert.
- Around line 81-95: The claim listing cap in ListClaimsForDocument is too low
for the CF-4 reducer contract, which expects up to 4,096 claims per document.
Update the Math.Clamp limit in DocumentGraphRepository.ListClaimsForDocument to
allow the higher maximum (or otherwise align it with the reducer’s documented
cap), and make sure the query still bounds the request safely while returning
the full claim set needed by the reducer.

In `@OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs`:
- Around line 90-91: The token estimate in
EvidencePackBuilder.EvaluateBudget/EstimateTokens is using a whitespace-based
word count, which can undercount minified JSON, CSV, or code blocks and make
WithinBudget unreliable. Replace the EstimateTokens logic with a real token
counter used by the prompt budget path, and ensure the budget check in the
evidence pack flow uses that same tokenizer so MaxPromptTokens is enforced
accurately.

In `@OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs`:
- Around line 78-85: Negation handling in FabricCitationVerifier currently runs
after overlap scoring, so contradicted claims can be mislabeled as Supported or
PartiallySupported. In FabricCitationVerifier’s verification logic, check for
negation mismatches before computing overlap and before returning on overlap
thresholds, and make the contradiction test symmetric for claimText and
matchedQuotes (not just quotes containing " not " while the claim does not).

In `@OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs`:
- Around line 24-25: Normalize and validate inputs in BuildPlan before any
search or plan assembly: trim and canonicalize query, corpusId, and mode once,
then use the normalized values consistently for Search and the returned plan so
the plan matches what was queried. Update BuildPlan and any related mode
handling to reject or classify unknown explicit mode strings instead of echoing
them through, and ensure only the supported "study" mode preserves reopen
behavior while all other invalid modes fall back to classification or are
rejected.
- Around line 116-127: The ClassifyMode logic in FabricQueryPlanner is matching
study terms as substrings, which incorrectly upgrades unrelated queries to Study
mode. Update ClassifyMode to tokenize the query and compare whole words against
the study keyword set instead of using Contains on the lowercase string, so
terms like “show” or “exchange” do not trigger on embedded fragments. Keep the
existing mode decision in FabricQueryMode, but change the matching strategy
around ClassifyMode so only standalone keywords such as compare, across,
between, change, exception, why, and how are considered.

In `@OrchestratorIDE/Services/ContextFabric/FabricReducer.cs`:
- Around line 46-52: The parent span is being truncated because FabricReducer
only propagates a child’s first ordinal, so generation > 0 nodes build their
range from the last child’s start instead of its full end. Update the reduction
flow in FabricReducer so ReductionChild carries both start and end ordinals,
then use those values when computing the parent node’s DisplayName and NodeId in
the node-building logic. Also adjust CreateLeaf to initialize both ordinals to
the segment index so leaf spans are correct from the start.

---

Nitpick comments:
In `@OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs`:
- Around line 85-102: `FabricLibraryRepository.GetSegmentsByIds` still issues
one `GetSegment` lookup per unique id, causing an N+1 query pattern. Update this
method to fetch all requested segment ids in a single batch query (for example,
via the repository/data access path used by `GetSegment`) and then de-duplicate
and preserve the requested semantics in memory, returning only non-null matches
from the batched result.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b37110c1-8991-4e5b-bee9-fcb6279d1ee9

📥 Commits

Reviewing files that changed from the base of the PR and between 3cf0c34 and a8821f4.

📒 Files selected for processing (11)
  • OrchestratorIDE.Avalonia/OrchestratorIDE.Avalonia.csproj
  • OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs
  • OrchestratorIDE/Services/ContextFabric/ContextFabricIngestionContracts.cs
  • OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs
  • OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs
  • OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs
  • OrchestratorIDE/Services/ContextFabric/FabricLibraryRepository.cs
  • OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
  • OrchestratorIDE/Services/ContextFabric/FabricReducer.cs
  • OrchestratorIDE/Services/Data/Migrations.cs
  • docs/The Orc Context Fabric.md

Comment thread OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs Outdated
Comment thread OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
Comment thread OrchestratorIDE/Services/ContextFabric/FabricReducer.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs (1)

73-78: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Don’t derive contradiction from the union of all matched quotes.

Line 77 treats the entire citation set as contradicted if any matched quote contributes "not". That produces false negatives for multi-citation claims, or for a long quote that contains an unrelated negated sentence. For example, "The harbor route is open." would be marked Contradicted against "The ridge route is not safe. The harbor route is open."

Proposed fix
         var claimTokens = Tokenize(claimText);
-        var sourceTokens = Tokenize(string.Join(" ", matchedQuotes));
-        if (claimTokens.Count == 0 || sourceTokens.Count == 0)
+        var quoteTokens = matchedQuotes
+            .Select(Tokenize)
+            .Where(tokens => tokens.Count > 0)
+            .ToArray();
+        if (claimTokens.Count == 0 || quoteTokens.Length == 0)
             return FabricCitationVerificationLabel.Interpretive;
-        if (claimTokens.Contains("not") != sourceTokens.Contains("not"))
+
+        if (quoteTokens.Any(tokens =>
+                claimTokens.Count(tokens.Contains) / (double)claimTokens.Count >= 0.50 &&
+                claimTokens.Contains("not") != tokens.Contains("not")))
             return FabricCitationVerificationLabel.Contradicted;
+
+        var sourceTokens = quoteTokens
+            .SelectMany(tokens => tokens)
+            .ToHashSet(StringComparer.Ordinal);
 
         var overlap = claimTokens.Count(sourceTokens.Contains) / (double)claimTokens.Count;
🤖 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 `@OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs` around
lines 73 - 78, The contradiction check in FabricCitationVerifier’s citation
verification logic is too coarse because it tokenizes the joined matchedQuotes
set and flags Contradicted whenever any quote contains “not.” Update the logic
around Tokenize(...) and the claimTokens/sourceTokens comparison so
contradiction is determined per matched quote or per sentence-level match, not
from the union of all quotes. Keep the existing Interpretation/Contradicted flow
in FabricCitationVerificationLabel, but only return Contradicted when the
specific quote supporting the claim actually negates it; otherwise fall back to
the non-contradicted result.
🤖 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.

Outside diff comments:
In `@OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs`:
- Around line 73-78: The contradiction check in FabricCitationVerifier’s
citation verification logic is too coarse because it tokenizes the joined
matchedQuotes set and flags Contradicted whenever any quote contains “not.”
Update the logic around Tokenize(...) and the claimTokens/sourceTokens
comparison so contradiction is determined per matched quote or per
sentence-level match, not from the union of all quotes. Keep the existing
Interpretation/Contradicted flow in FabricCitationVerificationLabel, but only
return Contradicted when the specific quote supporting the claim actually
negates it; otherwise fall back to the non-contradicted result.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: de8e583b-a880-42e2-95e4-b0d2d8ea7740

📥 Commits

Reviewing files that changed from the base of the PR and between a8821f4 and af555fc.

📒 Files selected for processing (6)
  • OrchestratorIDE.UnitTests/ContextFabricCf4Tests.cs
  • OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs
  • OrchestratorIDE/Services/ContextFabric/EvidencePackBuilder.cs
  • OrchestratorIDE/Services/ContextFabric/FabricCitationVerifier.cs
  • OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
  • OrchestratorIDE/Services/ContextFabric/FabricReducer.cs
🚧 Files skipped from review as they are similar to previous changes (3)
  • OrchestratorIDE/Services/ContextFabric/DocumentGraphRepository.cs
  • OrchestratorIDE/Services/ContextFabric/FabricQueryPlanner.cs
  • OrchestratorIDE/Services/ContextFabric/FabricReducer.cs

@hardcoreerik
hardcoreerik merged commit d7a6af7 into master Jun 29, 2026
2 checks passed
@hardcoreerik
hardcoreerik deleted the codex/context-fabric-cf4-hierarchy-paging branch July 18, 2026 02:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant