Skip to content

feat(rag): expose bounded multi-section document context over MCP - #25

Merged
ipiton merged 5 commits into
ipiton:mainfrom
glockbender:codex/mcp-document-context
Nov 19, 2026
Merged

ipiton merged 5 commits into
ipiton:mainfrom
glockbender:codex/mcp-document-context

Conversation

@glockbender

@glockbender glockbender commented Nov 16, 2026 •

Copy link
Copy Markdown

After semantic_search finds a file, document_context reads several indexed sections within a shared character budget. Pass section keys, the original question for in-file ranking, or neither to read in document order. The tool is available in the full profile, including grouped search with action: "context". Search in that profile prints section keys.

The tool uses the section assembly behind Engine.ExpandSection. In project scope it applies the existing allowlist rules relative to the configured index root, so a linked worktree can read indexed sections from the main checkout. Repository file tools still resolve against the calling worktree. The index root captured by path authorization is compared with the root recorded at indexing time.

This revision removes per-file origin metadata, indexing-time resolution of each source file, and the special SQLite snapshot. It reads the existing document rows and checks readiness and publication stamps. A completed index that records the resolved root needs no schema change or per-file backfill. For an older index without the resolved-root marker, indexing resolves the stored alias at upgrade time. If it matches the current physical root, indexing upgrades the root stamps while retaining records under unavailable sources. A new per-index marker distinguishes resolved roots from legacy aliases; it needs no schema change or per-file backfill. If no root is recorded, automatic adoption waits for unavailable sources that still contain indexed files. The returned text reflects the index and can lag edits or source-link changes.

Integration with #21

The branch includes current main at cba46cf. Indexing uses the same resolved root to record and compare the index identity. A temporary source outage preserves existing fragments when the root is unchanged, including with --allow-root-change. If a linked project root stops resolving, the override cannot discard protected records based on an unverified root change.

The legacy-upgrade regressions also cover a partial outage, an outage of the only source, and a partial outage with --allow-root-change. Available documents remain readable through document_context after the upgrade. Separate negative cases retain the foreign-root guard, including replacement of a previously resolved physical root by a link.

Validation

  • make build test vet eval plugin-smoke
  • go test -race ./...
  • Regression tests for an unavailable source under a symlinked root, with and without --allow-root-change, and for a dangling root with a readable external source.
  • Synthetic MCP tests cover a path present only in the main checkout, the search-to-context handoff, allowlist and link-escape rejection, unrelated databases, full and core profile behavior, and the shared Unicode budget.
  • Engine tests cover shared expansion, mixed heading and headingless fragments, model handling, and changes to the index publication stamps during a read.
  • Independent code and documentation reviews.
  • All five GitHub checks passed on adf9d6c, including both macOS smoke jobs.

@ipiton ipiton left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks — the use case is real, and tests/eval/plugin-smoke pass on current main. Two design issues before this can go in:

  1. It does not work from a worktree under the Claude Code plugin. The plugin runs with MCP_DATA_SCOPE=project (plugin/scripts/launch.sh), where the index is built from the main checkout (RAG.IndexRoot, T165) while pathGuard resolves against RootPath (the worktree). callDocumentContext requires the guard-resolved path to equal the indexed physical path, so every call from a worktree fails with "indexed source does not match the allowed file" — even for a path semantic_search just returned. TestDocumentContextCannotBypassAllowlistOrReadAnotherIndexRoot asserts this "cross-root" refusal, but that layout is the supported default, not an attack. The logical path should be resolved against the index root the server is configured with.
  2. We already have the read side: Engine.ExpandSection (internal/rag/rag.go, T49 "pointer-based context") — semantic_search returns section_key, and ExpandSection(doc_path, section_key) materialises the whole section. It just isn't exposed over MCP. Please build on it (expose it, then extend to several sections + a shared budget + optional in-file query ranking) instead of a parallel breadcrumb/merge path.

With that, the per-file source_path:* rows in index_metadata, EvalSymlinks in processFile and the snapshot transaction look unnecessary: repo_read relies on pathGuard alone, and indexed text shouldn't need a stricter provenance model than a live file read. If you think physical-origin binding is still needed, let's discuss it separately — and it would belong in indexed_files, not as one metadata key per file. Smaller points: the tool description should tell an agent when to use it (and describe path), and I'd keep it out of the core profile for now.

@glockbender

Copy link
Copy Markdown
Author

Updated against current main at 3e6fe5e and addressed the review.

  • A linked checkout now uses the existing allowlist relative to the configured index root for document_context. The test indexes a file present only in the main checkout, obtains its path and section key through search, and reads its indexed sections from the linked checkout.
  • document_context shares the section assembly behind Engine.ExpandSection for explicit keys and extends it to several sections, one shared character budget, and optional in-file query ranking. Search prints section keys in the full profile.
  • The tool stays in the full profile, including for grouped calls. Its description now explains when to use it, the meaning of path, and the selector options.
  • Removed the per-file source_path:* entries, the per-file EvalSymlinks call at indexing time, and the special SQLite snapshot. The read uses existing document rows and checks readiness and publication stamps. It binds the read to the resolved repository root already authorized by the server. Per-file origin history is left for a separate discussion. The help page explains that indexed text can lag source changes.

make test vet eval, the Go race tests for RAG, server and vector store, and the focused MCP and section expansion tests passed. Cases include allowlist rejection, another project's database, a moved root symlink, consistent expansion of mixed fragments, and a Unicode text budget.

All five upstream GitHub checks passed on 4d70a4e.

@ipiton

ipiton commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks — both blockers from the previous review are addressed, and this branch passes build, vet, go test -race ./..., make eval and plugin-smoke on its own.

One integration issue with #21, which is landing first: on main + #21 + #25, 13 tests in internal/rag/discovery_failure_test.go fail with

cannot adopt the index from a different or unknown root while N indexed file(s) are unavailable; restore the sources or use --allow-root-change

This branch now stores the EvalSymlinks-resolved root in index_root, while #21's checks in indexer.go compare the stored value with the unresolved re.repoRoot. On macOS t.TempDir() is under /var → /private/var, so the roots never match and every partial scan is treated as a foreign root (e.g. TestIndexRootAdoptionCannotKeepUnavailableForeignFiles sees index root = "/private/var/..."). Users whose project path goes through a symlink would hit the same thing. Each PR is green alone, so CI can't see it.

Please rebase on main once #21 is merged and make all root comparisons (#21's oldRoot checks and allowRootChange handling included) use the same resolved root you store. A test with the project root reached through a symlink would pin it down.

@glockbender

Copy link
Copy Markdown
Author

Thanks for testing the two changes together. I merged current main (cba46cf, including #21) into this branch and resolved the server startup conflict.

Indexing now uses the same resolved root to write index_root and make all root-change decisions. I reproduced two failures on macOS with an explicit project-root symlink: the default run refused to update the index, and --allow-root-change dropped the unavailable source's chunks. The regression test now passes in both modes and checks that a healthy source still updates. A second test covers a dangling root link: the override returns an error and leaves the published chunks and metadata intact.

The discovery, document-context and linked-checkout tests and make build test vet eval plugin-smoke passed. The full go test -race ./... run also passed.

On 4d4e879, four GitHub checks have passed. The macOS plugin smoke job is still pending in GitHub Actions. The same smoke target passed locally on macOS.

@ipiton

ipiton commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thanks — the #21 conflict is resolved, and 4d4e879 passes build, gofmt, vet (including eval and corpus tags), go test -race ./..., make eval and plugin-smoke locally on macOS.

One gap remains: upgrading an existing index when the project root is reached through a symlink. Indexes written by current main store the unresolved root, so oldRoot != indexRoot and the index is treated as foreign, although it is the same project. With all sources available this heals itself, because the stamp is rewritten. With a source temporarily unavailable, I reproduced three failures by indexing through a symlinked root, setting index_root back to the link path, and then making a source unavailable:

Case Result
Part of the sources unavailable (notes/ of docs, notes) cannot adopt the index from a different or unknown root while 1 indexed file(s) are unavailable
The only source unavailable (docs/) refusing to index <link>: the index was built from <link> and this run would remove 2 of its 2 files
First case with --allow-root-change, as the error suggests notes/b.md is dropped from the index

The last one is the loss #21 is meant to prevent, reached by following our own error message.

A candidate fix, right after sameRoot is computed:

if !sameRoot && oldRoot != "" && rootResolutionErr == nil {
	if resolvedOld, err := filepath.EvalSymlinks(oldRoot); err == nil && resolvedOld == indexRoot {
		sameRoot = true
	}
}

With it, these three cases and all of internal/rag pass. It does not widen the existing behaviour: main already treats an unchanged link path as the same root, whatever it points to now. Feel free to solve it differently.

Please add a regression test for a legacy unresolved index_root covering these three cases. The new commit will also re-trigger plugin-smoke (macos-latest): on 4d4e879 it was cancelled after 15 minutes without running a step, so it looks like it never got a runner.

@glockbender

Copy link
Copy Markdown
Author

Fixed the legacy-root upgrade cases in adf9d6c.

The stored alias is resolved at upgrade time when the index has no matching resolved-root marker. If it resolves to the current physical root, indexing retains unavailable records and publishes the canonical root even when no document content changed. A small per-index marker prevents a newly recorded physical root from later being reinterpreted as an old alias. No schema change or per-file backfill is needed.

Regression tests reproduce all three reported cases: a partial outage, the only source unavailable, and a partial outage with --allow-root-change. They check unchanged file records and chunks, successful context reads for an available document, and recovery when sources return. Negative cases cover a different or unavailable old alias and replacement of a recorded physical root by a link. The failing cases were reproduced before applying the fixes.

Local validation passed: make build test vet eval plugin-smoke, go test -race ./..., and focused document-context/discovery tests. The fixtures are synthetic. All five GitHub checks passed on adf9d6c, including plugin-smoke (macos-latest).

@ipiton
ipiton merged commit 645196e into ipiton:main Nov 19, 2026
5 checks passed
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.

2 participants