diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..295f5ee --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.venv +venv +.mimir +**/__pycache__ +**/*.pyc +**/*.egg-info +dist +build +client +backstage-plugin +docs +tests +.github +.claude +.DS_Store diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48b2461..b7b0142 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,21 +6,28 @@ on: push: branches: [main, develop] +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: test: - name: Tests + name: Tests (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest strategy: + fail-fast: false matrix: python-version: ["3.11", "3.12", "3.13"] steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v7 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} + cache: pip - name: Install dependencies run: pip install -e ".[dev]" @@ -28,50 +35,27 @@ jobs: - name: Run tests run: pytest --tb=short -q - guardrails: - name: Architectural Guardrails + build: + name: Build verification runs-on: ubuntu-latest - if: github.event_name == 'pull_request' - permissions: - contents: read - pull-requests: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: - fetch-depth: 0 + fetch-depth: 0 # setuptools-scm derives the version from git tags - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: "3.13" - - name: Install Mimir - run: pip install -e . + - name: Install build tools + run: pip install build twine - - name: Build code graph - run: mimir index + - name: Build server package + run: python -m build --outdir dist/ - - name: Run guardrail check - id: guardrails - run: | - EXIT_CODE=0 - git diff origin/${{ github.base_ref }}...${{ github.event.pull_request.head.sha }} | \ - mimir guardrail check --diff - \ - --rules mimir-rules.yaml \ - --base origin/${{ github.base_ref }} \ - --head ${{ github.event.pull_request.head.sha }} \ - --output github-pr-comment \ - --report-file guardrail-report.md \ - || EXIT_CODE=$? - echo "exit_code=$EXIT_CODE" >> $GITHUB_ENV - cat guardrail-report.md >> $GITHUB_STEP_SUMMARY - - - name: Comment on PR - if: always() && hashFiles('guardrail-report.md') != '' - uses: marocchino/sticky-pull-request-comment@v2 - with: - header: mimir-guardrails - path: guardrail-report.md + - name: Build client package + run: python -m build --outdir dist/ + working-directory: client - - name: Fail if violations - if: env.exit_code != '0' - run: exit 1 + - name: Check package metadata + run: twine check --strict dist/* client/dist/* diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index bb81d6a..031301c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,24 +6,41 @@ on: - "v*" permissions: - contents: write - id-token: write + contents: read jobs: + test: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + cache: pip + + - name: Install dependencies + run: pip install -e ".[dev]" + + - name: Run tests + run: pytest --tb=short -q + build: name: Build packages + needs: test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: "3.13" - name: Install build tools - run: pip install build + run: pip install build twine - name: Build server package run: python -m build --outdir dist/ @@ -32,8 +49,11 @@ jobs: run: python -m build --outdir dist/ working-directory: client + - name: Check package metadata + run: twine check --strict dist/* client/dist/* + - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: dist path: | @@ -42,13 +62,15 @@ jobs: github-release: name: Create GitHub Release - needs: build + needs: [publish-server, publish-client] runs-on: ubuntu-latest + permissions: + contents: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts @@ -63,7 +85,7 @@ jobs: run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" - name: Create GitHub Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: tag_name: ${{ github.ref_name }} name: Mimir ${{ steps.version.outputs.version }} @@ -79,7 +101,7 @@ jobs: id-token: write steps: - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts @@ -101,7 +123,7 @@ jobs: id-token: write steps: - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: dist path: artifacts diff --git a/.mimir/project/graph.db b/.mimir/project/graph.db index ffaf796..63b4a25 100644 Binary files a/.mimir/project/graph.db and b/.mimir/project/graph.db differ diff --git a/.mimir/project/graph.db-shm b/.mimir/project/graph.db-shm new file mode 100644 index 0000000..672f85f Binary files /dev/null and b/.mimir/project/graph.db-shm differ diff --git a/.mimir/project/graph.db-wal b/.mimir/project/graph.db-wal new file mode 100644 index 0000000..e94a255 Binary files /dev/null and b/.mimir/project/graph.db-wal differ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d68227a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,25 @@ +# Repository Guidelines + +## Project Structure & Module Organization +`mimir/` is the main server package. Keep core models in `mimir/domain/`, interfaces in `mimir/ports/`, business logic in `mimir/services/`, concrete implementations in `mimir/infra/`, and external entry points in `mimir/adapters/`. `mimir/container.py` wires dependencies. + +`tests/` mirrors the runtime layout with focused suites such as `tests/services/`, `tests/adapters/`, `tests/domain/`, and `tests/infra/`. The lightweight remote client lives in `client/mimir_client/`. The optional Backstage integration is isolated under `backstage-plugin/plugins/catalog-backend-module-mimir/`. Docs and example configs live in `docs/`, `mimir.toml`, `mimir-rules.yaml`, and `mimir-agent-policy.yaml`. + +## Build, Test, and Development Commands +Install the server for development with `pip install -e ".[dev]"`. Run the Python test suite with `pytest` or `.venv/bin/pytest` if using the checked-in virtualenv layout. Common local workflows: + +- `mimir index` rebuilds the semantic graph for the current workspace. +- `mimir serve` starts the MCP stdio server. +- `mimir serve --http` starts the shared HTTP server on port `8421`. +- `mimir guardrail check` validates the current diff against architectural rules. + +For the client package, use `cd client && pip install -e .`. For the Backstage plugin, use `cd backstage-plugin/plugins/catalog-backend-module-mimir && npm test && npm run build`. + +## Coding Style & Naming Conventions +Follow the existing hexagonal boundaries; do not let adapters reach into infra directly. Python targets 3.11+ and uses type hints, frozen dataclass-style domain models, and `snake_case` for modules, functions, and variables. Classes and enums use `PascalCase`; constants use `UPPER_SNAKE_CASE`. TypeScript in the Backstage plugin follows the same naming split: `PascalCase` for exported types/classes, `camelCase` for values. + +## Testing Guidelines +Add tests next to the affected layer and name files `test_.py` or `*.test.ts`. Prefer narrow unit tests for services and adapters, then add integration coverage when indexing, retrieval, or HTTP behavior changes. Run `pytest` before opening a PR; run `npm test` in the Backstage plugin when touching `backstage-plugin/`. + +## Commit & Pull Request Guidelines +Recent history favors short imperative subjects with prefixes like `add:`, `fix:`, and `update:`. Keep commits focused and descriptive, for example `fix: preserve token budget in retrieval`. PRs should explain behavior changes, list validation steps, link related issues, and include request/response examples or screenshots when HTTP, web UI, or Backstage behavior changes. diff --git a/BLOG.md b/BLOG.md new file mode 100644 index 0000000..3159f32 --- /dev/null +++ b/BLOG.md @@ -0,0 +1,120 @@ +# The graph was already there + +*On building a code context engine for AI agents, and why the most interesting piece of it ended up living inside a git commit message.* + +--- + +For the last few months I've been building a thing called **Mimir**. It's a code context engine for LLMs: you point it at one or more repositories, it parses them with tree-sitter, stitches the results into a typed graph of calls, imports, inheritance, API calls and cross-repo links, and then — when you or an agent asks "what do I need to know to touch this function?" — it walks that graph to assemble a minimal, token-budgeted context bundle. Think of it as the piece that sits between your code and whichever LLM you're handing code to. + +If you stopped reading there, that would sound like yet another RAG-over-code tool. And for the first couple of weeks, honestly, that's what it was. You parse, you embed, you search. Cosine similarity finds your thing. Ship it. Stop typing. + +The reason I'm writing this post is that one night, a few weeks into the project, I had the kind of realisation that makes you sit still for a minute before touching the keyboard again. I had already built a code graph. I was already walking it to assemble context. And I was staring at a completely different problem — architectural review for AI-generated code — wondering how to build it, as if it were a new system. + +It wasn't a new system. The graph was already there. + +--- + +## What the graph unlocks that RAG doesn't + +Let me back up. The thing that makes Mimir different from "vector search over your repo" is that it doesn't treat code as text. It treats code as a graph, and the graph has types. + +Nodes are what you'd expect — files, classes, functions, endpoints, config blocks. Edges are the interesting part: `IMPORTS`, `CALLS`, `INHERITS`, `IMPLEMENTS`, `USES_TYPE`, `READS_CONFIG`, `EXPOSES_API`, `API_CALLS` (cross-repo), `SHARED_LIB`, `PROTO_DEFINES`. When you query for context, Mimir does a hybrid search (semantic + BM25 + name/path), seeds a handful of starting nodes, then expands along those typed edges with a beam search, re-ranks with quality and recency signals, and only at the very end crunches everything into your token budget and topologically orders it so dependencies come before dependents. + +That last step is the thing RAG can't do. Vector search over files gives you *chunks that mention the same words*. The graph gives you *the set of things that have to be true for this change to make sense*: the interfaces it implements, the things that call it, the config it reads, the types it flows through. That's not a retrieval problem. That's a structural one. And you can't solve structural problems with cosine similarity, no matter how clever your embedding model is. + +Fine. Great. I had the graph. I had context assembly. I shipped an MCP server. Developers (and agents) could ask "show me what I need to touch `ApprovalService`" and get back a coherent, ordered bundle that fit in 4000 tokens. I was pretty pleased with myself. + +Then I started thinking about what comes after the LLM writes the change. + +--- + +## The unspoken promise of the graph + +Here is something that happens when you give a capable coding agent a coding task. It does the task. The code compiles. The tests, if you have them, pass. The review comment is "nice, shipping it." And then three weeks later, someone notices that a domain model now imports from the infrastructure layer, a module that was supposed to be a stable port has grown an outbound dependency on a concrete adapter, and the "small" change to a shared type is actually being consumed by forty-three other call sites that nobody thought to check. + +The agent did nothing wrong. It did the task. But the code doesn't know what the architecture of the project is supposed to look like, and neither does the LLM, and neither does the review system, and the combination of those three things is how architectures quietly die. + +When I noticed this, my first instinct was "oh, this is a new product I should build" — an architectural linter of some kind. Maybe wrap Semgrep. Maybe write rules. And then I remembered the graph. + +I already had a typed graph of every dependency in the repo. If you wanted to ask "is this change introducing a dependency from `*/domain/*` to `*/infra/*`?", that wasn't a new problem. That was `graph.new_edges.filter(src matches pattern and dst matches pattern)`. If you wanted to ask "does this change introduce a cycle?" — same graph, `nx.simple_cycles` on the scoped subgraph, keep the ones that contain at least one new edge. "What's the blast radius of this change?" Run impact analysis from the modified nodes along the reverse edges, bound by a hop count, count the touched nodes. + +Every single architectural question I cared about was **already expressible as a query on the graph I had built for context retrieval.** + +That's the moment Mimir stopped being "a context engine" in my head and became "an engine that answers structural questions about code, one of which happens to be 'what's the minimal context for this query'". Retrieval and guardrails aren't two products. They're the same product asking the graph two different questions. + +I wrote a rule engine on top of the existing graph in about a day. Five rule types: `dependency_ban`, `cycle_detection`, `metric_threshold` (afferent/efferent coupling, instability), `impact_threshold` (bounded blast radius), and `file_scope_ban` (protect certain paths). All five share the same underlying machinery. The rule configuration is a YAML file, severities are `warning`, `error`, `block`, and the CLI command is `mimir guardrail check`, which takes a diff, analyses it against the loaded graph, and tells you what's wrong. + +And then I hit the actually interesting part. + +--- + +## The part I got wrong three times + +`block`-severity rules were supposed to be the escape valve. The idea was: some files are so load-bearing — a DI container, a port interface, a config schema — that even a legitimate change requires a human to explicitly sign off. Warnings and errors can't express that. You need a third severity that says "this is going to fail CI until a human tells me, in writing, that it's fine." + +I called this "approvals". And I built it the way you'd build it if you were sketching a backend feature on a whiteboard. + +**Version one** was a YAML file in a directory called `.mimir/approvals/`, checked into git. Running `mimir guardrail request --rules ` created a file named something like `apr-6c971b3c.yaml`. Running `mimir guardrail approve --reason "..."` mutated the `status: pending` field to `status: approved` and recorded the approver's git identity. An `ApprovalService` in the service layer handled CRUD. There was a TTL. There was a `revoke` command. There was a `clean` command for expired entries. There was a `status` command that printed a nicely formatted table. It all worked. I was proud of it. + +It was also, I gradually realised, awful to use. + +Three specific things broke down: + +1. **`mimir guardrail check` auto-created approval requests on top of whatever `mimir guardrail request` had already made.** So there were two creation paths, and if you ran them in the wrong order you got ghost files. The CLI was technically correct and humanly confusing. +2. **The matching logic used `(rule_id, branch, not-expired)` only.** It stored a `diff_hash` in the YAML, for audit, but never actually checked it. So once you'd been approved for `protect-container` on `feature/foo`, you could push another five-hundred-line rewrite of `container.py` to the same branch and the approval would still apply, because neither the rule id nor the branch name had changed. +3. **CI could read approvals but not grant them.** The approval command had to run locally, which meant an approver had to clone the branch, run the command, commit the new YAML file, and push. The PR comment from CI could tell you "this is pending approval", but it couldn't give you anything to click, and the request ID existed only in the local terminal of whoever had last run `check`. Nobody on the PR could see it. + +I lived with this for a couple of weeks. Each time I ran into one of those three problems, I would think "I should fix that", and then mentally draw the fix, and each fix added more machinery to something that was already too much machinery. Diff-hash enforcement. A per-rule approver allowlist. Exposing the request ID in the GitHub PR comment formatter. A bot to listen for comments. A bot to dispatch re-runs. You know how this story goes. + +I eventually did what I should have done on day one, which is sit down with a blank file and write a design document without looking at the code. The brief was one sentence: *"If I were designing this from scratch, knowing what I know now, what would it look like?"* + +The answer, after about two hours of squinting at it, was: **delete the entire approval database.** + +--- + +## The commit message was the approval + +Here is the shape the new design landed on. + +There is no persisted approval object. No YAML directory. No registry. No TTL. No `request`, `revoke`, `status`, or `clean` subcommand. The only thing that exists is a `git commit` trailer on the HEAD commit of the branch being checked: + +``` +approval: protect-container + +Mimir-Approved: protect-container +Mimir-Approved-Reason: legal signoff for new DI wiring +``` + +`mimir guardrail check` reads `git log -1 --format=%B HEAD`, parses trailers, and for every BLOCK violation in its output, checks whether its rule id is listed in `Mimir-Approved:` with a non-empty `Mimir-Approved-Reason:`. That's the entire algorithm. There is a `mimir guardrail approve --reason "..."` command — it's one call to `git commit --allow-empty` with the trailer pre-filled. The CLI shrunk from seven subcommands to four. The service layer lost an entire module. + +The properties that fell out of this are the part I keep thinking about. + +Approvals are **automatically invalidated the moment HEAD moves.** There is no `revoke` command because pushing any new commit without the trailer is the revoke. The branch author can't fake it, because trailers are on a specific commit, and the specific commit is what HEAD points to right now. + +Approvals are **branch-local** without any branch-name tracking. There's no "which branch was this approved for" field anywhere. The approval lives on the commit, the commit lives on the branch, done. + +Approvals are **the audit trail.** `git log --grep="Mimir-Approved"` is your compliance report. You don't need a JSONL file. You don't need a database. The thing you were going to use for audit (git) was already the thing storing the approval. + +And it's **VCS-agnostic.** The original design was YAML-in-git, which is technically VCS-agnostic, but the UX was pushing me toward a GitHub-specific bot to actually make it tolerable. The commit-trailer design needs nothing beyond `git log` and a regex. It works identically on GitHub, GitLab, Gitea, or a server on your desk with no internet. + +There are tradeoffs. Squash-merges will concatenate the commit body by default, which preserves the trailer, but a team that customises the squash message to strip them would lose the trailer on main — I decided this is fine, because the approval was enforced before merge, and the post-merge audit is informational. I initially added a "self-approval guard" that required the HEAD committer to not be the sole author of the branch, and then removed it after talking to the user I was building this for, who pointed out that self-approval is fine in a solo project and the audit trail is anyway in `git log`. The system is deliberately lightweight. If you want harder guarantees, you sign your commits. + +Here's the part that ties back to the retrieval story: **the guardrail system didn't need a new data model.** It's the same graph. The rule engine is a pure function over a `ChangeSet`. The approval check is a pure function over a commit message. The CLI is 150 lines shorter. The hardest piece of the whole thing — figuring out whether a commit trailer should clear a BLOCK — is nine lines of code, and it's unit-tested in sub-millisecond time with no filesystem, no git, no mocks. + +--- + +## What I learned + +I'm going to try to say the thing without being too cute about it. + +When you're building a system, you have two kinds of problems: things you don't yet know how to solve, and things you've *over-solved* because you wrote code before you understood the shape of the answer. The second kind is more dangerous, because the code works. The tests pass. It ships. And it's only months later, the third time you try to use it on a real change, that you realise you're paying a UX tax every single day for a data structure you didn't need to have. + +The graph-for-retrieval / graph-for-guardrails unification was a case of the first kind. I didn't see it until I'd already built half of it twice, and then it was obvious. + +The approval-in-a-commit-trailer was a case of the second. I had built something real, with tests and a service layer and a CLI surface, and the fix wasn't to iterate on it — the fix was to delete it and notice that the underlying need ("this branch, this rule, a human said yes") was already representable in a file I was already tracking in version control. + +I keep coming back to the same loose heuristic: *before you add a new data store, check whether the semantics you want already exist somewhere in the system.* A lot of the time they do. A lot of the time the pieces you'd write are re-encoding a fact that git already knows, or the graph already knows, or the filesystem already knows. When that's true, the most principled move is to not write the pieces, and to let whatever was already there carry the meaning for you. + +Mimir is open source. The code for the guardrail rewrite I described is in `mimir/services/guardrail_trailers.py` and `apply_approvals` in `mimir/services/guardrail.py`, and it's honestly smaller than the comment block at the top of the original `ApprovalService`. If you want to read something well-named that does nothing, you can still find the old commits in the history — they're a good before/after for the rest of this post. + +I'm going to go delete more things now. diff --git a/CLAUDE.md b/CLAUDE.md index 9ed9f04..2f1b5c3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,14 +15,18 @@ pip install -e ".[dev]" # Run tests (the venv lives at ./.venv — activate it or call it directly) .venv/bin/pytest # or: source .venv/bin/activate && pytest +.venv/bin/pytest tests/test_guardrail_service.py -k test_name # Single test/module + +# No linter or formatter is configured (no ruff/black/mypy). Tests are the only gate. +# pytest runs in asyncio_mode = "auto" — async tests need no @pytest.mark.asyncio. # CLI usage mimir init # Create mimir.toml config -mimir index # Build/update semantic code graph -mimir search "query" # Search and assemble context -mimir serve # Start MCP server (stdio) -mimir serve --http # Start shared HTTP server (port 8421) -mimir quality # Analyze graph connectivity gaps +mimir indexer run # Build and publish an index version +mimir query search "query" # Search the active published index +mimir query serve # Start MCP server (stdio) +mimir query serve --http # Start shared HTTP server (port 8421) +mimir query status # Show the active index version and graph counts # Guardrails mimir guardrail init # Generate example rules + agent policy @@ -48,10 +52,10 @@ Mimir-Approved-Reason: legal signoff ticket #4821 Workflow: -1. CI fails on a BLOCK violation. PR comment lists the failing rule ids. +1. `mimir guardrail check` (local run or pre-commit hook) fails on a BLOCK violation and lists the failing rule ids. 2. Someone runs `mimir guardrail approve --reason "..."` on the PR branch. This creates an empty commit with the trailer. -3. Push. CI re-runs, reads HEAD trailers, clears the matching BLOCKs. +3. Re-run the check; it reads HEAD trailers and clears the matching BLOCKs. (Repo CI does not run guardrails.) 4. Any subsequent commit without the trailer invalidates the approval because HEAD has moved. No `revoke` command is needed. @@ -73,18 +77,18 @@ Services (business logic: indexing, retrieval, temporal, quality, intent, sessio ↓ Domain (core models: CodeGraph, Node, Edge, Config, Session — all frozen dataclasses/enums) ↓ -Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore, LLMClient) +Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore) ↓ -Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite, ChromaDB, LiteLLM) +Infra (concrete implementations: tree-sitter, ONNX Runtime embeddings (local) / Jina API, SQLite, in-memory NumPy vector index) ``` ### Key Layers - **`mimir/domain/`** — Immutable core: `models.py` (NodeKind/EdgeKind enums, Node/Edge), `graph.py` (NetworkX-backed CodeGraph), `config.py` (TOML-mapped dataclasses), `guardrails.py` (Rule/Violation/ChangeSet/GuardrailResult) - **`mimir/ports/`** — Protocol interfaces for dependency injection boundaries -- **`mimir/services/`** — All business logic. Heaviest files: `indexing.py` (parse→graph→embed pipeline), `retrieval.py` (query→seed→expand→rank→budget-fit), `guardrail.py` (rule evaluation engine), `diff_analyzer.py` (git diff→ChangeSet), `agent_policy.py` (bounded autonomy) -- **`mimir/infra/`** — Pluggable implementations: `parsers/tree_sitter.py`, `embedders/local.py`+`jina.py`, `stores/sqlite_graph.py`, `vector_stores/numpy_store.py`+`chroma.py` -- **`mimir/adapters/`** — External interfaces: `cli.py` (Typer entry point), `mcp_server.py` (MCP stdio), `http_server.py` (REST API) +- **`mimir/services/`** — All business logic (19 modules). Core pipeline: `indexing.py` (parse→graph→embed), `retrieval.py` (query→seed→expand→rank→budget-fit), `summarizer.py`, `graph_linker.py` (cross-file reference resolution). Ranking signals: `intent.py` (query classification), `quality.py`, `temporal.py`. Guardrails: `guardrail.py` (rule engine), `guardrail_report.py`, `guardrail_trailers.py` (approval trailers), `diff_analyzer.py` (git diff→ChangeSet), `agent_policy.py` (bounded autonomy). Also `impact.py` (blast-radius reverse-tracing), `session.py` (dedup w/ exponential decay), `write_context.py` (write-path bundles), `catalog.py` (Backstage), `watcher.py` (live re-index) +- **`mimir/infra/`** — Pluggable implementations: `parsers/tree_sitter.py`, `embedders/local.py`+`jina.py`, `stores/sqlite_graph.py`+`sqlite_session.py`, `vector_stores/numpy_store.py` (in-memory, rebuilt from `graph.db` embeddings on startup) +- **`mimir/adapters/`** — External interfaces: `cli.py` (Typer entry point) + `cli_support/`, `mcp_server.py` (MCP stdio), `remote_mcp.py` (proxy to remote server), `http_server.py` (REST API), `web/server.py` (Web Inspector UI), plus `ci/` (GitHub Action) and `hooks/` (pre-commit) integration assets - **`mimir/container.py`** — Wires all layers together via DI ### Retrieval Pipeline @@ -95,9 +99,15 @@ Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite 1. Tree-sitter parse → 2. Build node/edge graph → 3. Cross-file reference resolution → 4. Heuristic summarization → 5. Embedding → 6. Persist to SQLite + vector store. Supports incremental indexing via git diff. +## CI + +`.github/workflows/ci.yml` runs on PRs and pushes to `main`/`develop` and does only two things: `pytest --tb=short -q` on Python 3.11/3.12/3.13, and build verification (`python -m build` for the server and `client/` packages + `twine check --strict`). Guardrail checks are not run in CI; use `mimir guardrail check` locally or via the pre-commit hook. + +`.github/workflows/publish.yml` releases on `v*` tag pushes only: tests → build → publish both packages to PyPI (trusted publishing, `pypi` environment) → GitHub Release with the dists attached. Versions come from the git tag via setuptools-scm. + ## Configuration -Primary config: `mimir.toml` (TOML). Key sections: `[[repos]]`, `[indexing]`, `[embeddings]`, `[retrieval]`, `[temporal]`, `[session]`, `[vector_db]`, `[llm]`. +Primary config: `mimir.toml` (TOML). Key sections: `[[repos]]`, `[indexing]`, `[embeddings]`, `[retrieval]`, `[temporal]`, `[session]`, `[watcher]`. `mimir.toml` indexes the Mimir source itself (used for both development and CI). @@ -108,9 +118,9 @@ Guardrails config: `mimir-rules.yaml` (architectural rules) and `mimir-agent-pol Default location: `.mimir/`, split into two subfolders: - **`.mimir/project/`** — tracked in git. Contains `graph.db` (the code graph). Committing this lets CI skip re-indexing and lets new developers get a working context engine on clone. -- **`.mimir/session/`** — ignored by git. Contains `sessions.db` (session state), `models/` (downloaded embedding weights), `chroma/` (derived vector store). Anything personal or re-derivable lives here. +- **`.mimir/session/`** — ignored by git. Contains `sessions.db` (session state), `models/` (downloaded ONNX embedding models). Anything personal or re-derivable lives here. -Run `mimir index` and commit `.mimir/project/graph.db` after significant code changes. +Run `mimir indexer run` and commit `.mimir/project/graph.db` after significant code changes. ## Docker diff --git a/Dockerfile b/Dockerfile index 7a07ae1..bc23f64 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,10 @@ -FROM python:3.11-slim +# syntax=docker/dockerfile:1 +FROM python:3.13-slim -# Install system dependencies: git for repo operations, build-essential for native extensions +# git for repo operations (indexing, temporal signals, diffs). Every Python +# dependency ships wheels, so no compiler toolchain is needed. RUN apt-get update && \ - apt-get install -y --no-install-recommends git build-essential && \ + apt-get install -y --no-install-recommends git && \ rm -rf /var/lib/apt/lists/* # Fix for "dubious ownership" error in mounted volumes @@ -10,22 +12,29 @@ RUN git config --global --add safe.directory '*' WORKDIR /app -# Upgrade pip -RUN pip install --no-cache-dir --upgrade pip +ENV PIP_DISABLE_PIP_VERSION_CHECK=1 -# Copy project metadata and source code +# Third-party dependencies only, read from pyproject.toml. This layer (and the +# model download below) is reused across source-code changes. COPY pyproject.toml ./ -COPY mimir/ ./mimir/ +RUN --mount=type=cache,target=/root/.cache/pip \ + python -c "import tomllib; print('\n'.join(tomllib.load(open('pyproject.toml','rb'))['project']['dependencies']))" > /tmp/requirements.txt && \ + pip install -r /tmp/requirements.txt -# Install application and all dependencies -RUN pip install --no-cache-dir . +# Pre-download the standard embedding model (ONNX export) so the container +# runs 100% offline. File list matches _MODEL_FILES in mimir/infra/embedders/local.py. +RUN python -c "from huggingface_hub import snapshot_download; snapshot_download('sentence-transformers/all-mpnet-base-v2', allow_patterns=['onnx/model.onnx', 'onnx/model.onnx_data', 'tokenizer.json', 'config.json', 'modules.json', 'sentence_bert_config.json', '1_Pooling/config.json'])" -# Pre-download the standard embedding model -# This caches model weights into the Docker layer so the container runs 100% offline -RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-mpnet-base-v2')" +# The build context has no .git, so setuptools-scm cannot derive the version. +# Pass it explicitly: docker build --build-arg MIMIR_VERSION=1.2.0 . +ARG MIMIR_VERSION=0.0.0 +ENV SETUPTOOLS_SCM_PRETEND_VERSION_FOR_MIMIR_CONTEXT_SERVER=${MIMIR_VERSION} -# Remove build tools to shrink final image -RUN apt-get purge -y build-essential && apt-get autoremove -y && rm -rf /var/lib/apt/lists/* +# Application code last — only this layer rebuilds on a code change +COPY README.md ./ +COPY mimir/ ./mimir/ +RUN --mount=type=cache,target=/root/.cache/pip \ + pip install --no-deps . # Offline hugging face mode ENV HF_HUB_OFFLINE=1 diff --git a/README.md b/README.md index ad2dba9..c2aee0e 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ Mimir indexes your code into a hierarchical graph of repositories, files, classe pip install mimir-context-server cd /your/project mimir init # creates mimir.toml -mimir index # builds the semantic code graph -mimir search "how does authentication work?" -mimir serve # start MCP server for your IDE +mimir indexer run # builds and publishes the semantic code graph +mimir query search "how does authentication work?" +mimir query serve # start MCP server for your IDE # Architectural guardrails mimir guardrail init # generate example rules + agent policy diff --git a/backstage-plugin/plugins/catalog-backend-module-mimir/package-lock.json b/backstage-plugin/plugins/catalog-backend-module-mimir/package-lock.json index 58bf77a..c9921e6 100644 --- a/backstage-plugin/plugins/catalog-backend-module-mimir/package-lock.json +++ b/backstage-plugin/plugins/catalog-backend-module-mimir/package-lock.json @@ -1643,9 +1643,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.10.13", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.13.tgz", - "integrity": "sha512-BL2sTuHOdy0YT1lYieUxTw/QMtPBC3pmlJC6xk8BBYVv6vcw3SGdKemQ+Xsx9ik2F/lYDO9tqsFQH1r9PFuHKw==", + "version": "2.11.22", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.22.tgz", + "integrity": "sha512-pWc4w51fBFd7mav43/zKRC+RI6f4yfzQoVlfvE8dECePyfkn1bzLp01Fj0QACcyCZyFhiEMyD2qScfKRWgWibA==", "dev": true, "license": "Apache-2.0", "bin": { @@ -1656,9 +1656,9 @@ } }, "node_modules/body-parser": { - "version": "1.20.4", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", - "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "version": "1.20.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", "license": "MIT", "dependencies": { "bytes": "~3.1.2", @@ -1669,7 +1669,7 @@ "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", - "qs": "~6.14.0", + "qs": "~6.15.1", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" @@ -2270,9 +2270,9 @@ } }, "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -2397,14 +2397,14 @@ } }, "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "version": "4.22.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "~1.20.3", + "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", @@ -2423,7 +2423,7 @@ "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", - "qs": "~6.14.0", + "qs": "~6.15.1", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", @@ -2478,9 +2478,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", + "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", "funding": [ { "type": "github", @@ -3732,9 +3732,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -4550,9 +4550,9 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.14.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", - "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "version": "6.15.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", + "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" @@ -4858,13 +4858,13 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -5366,9 +5366,9 @@ } }, "node_modules/uuid": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", - "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", "funding": [ "https://github.com/sponsors/broofa", "https://github.com/sponsors/ctavan" diff --git a/client/pyproject.toml b/client/pyproject.toml index dafe512..77e63bb 100644 --- a/client/pyproject.toml +++ b/client/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=68.0", "wheel>=0.46", "setuptools-scm>=8"] +requires = ["setuptools>=84.0", "wheel>=0.48", "setuptools-scm>=10.3"] build-backend = "setuptools.build_meta" [project] @@ -8,13 +8,12 @@ dynamic = ["version"] description = "Lightweight MCP proxy client for remote Mimir context servers — no repos, no models, no indexing needed" readme = "README.md" requires-python = ">=3.10" -license = {text = "MIT"} +license = "MIT" keywords = ["mcp", "context", "code", "llm", "proxy", "mimir"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -25,8 +24,8 @@ classifiers = [ ] dependencies = [ - "aiohttp>=3.9", - "typer>=0.9", + "aiohttp>=3.14.3", + "typer>=0.27.2", ] [project.urls] diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 4be35f5..029e5bb 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -12,14 +12,14 @@ fi # Also triggered by "serve" with AUTO_INDEX=1 if [ "$1" = "auto" ] || [ "${AUTO_INDEX:-0}" = "1" ]; then echo "==> Indexing repositories from ${CONFIG} ..." - mimir index --config "$CONFIG" || { + mimir indexer run --config "$CONFIG" || { echo "WARNING: Indexing failed, starting server with whatever data exists" } fi # Start HTTP server echo "==> Starting Mimir HTTP server on ${MIMIR_HOST:-0.0.0.0}:${MIMIR_PORT:-8421}" -exec mimir serve \ +exec mimir query serve \ --http \ --http-host "${MIMIR_HOST:-0.0.0.0}" \ --http-port "${MIMIR_PORT:-8421}" \ diff --git a/docs/architecture.md b/docs/architecture.md index 2a1b495..73efa0a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,15 +9,15 @@ Mimir follows a hexagonal (ports & adapters) architecture with constructor-based ``` Adapters (CLI, MCP, HTTP, Web UI) ↓ -Container (DI wiring — container.py) +RuntimeFactory (indexer/query runtime wiring) ↓ -Services (business logic: indexing, retrieval, temporal, quality, intent, session, impact, guardrail, watcher) +Services (business logic: indexing, retrieval, temporal, quality, intent, session, impact, guardrail) ↓ Domain (core models: CodeGraph, Node, Edge, Config, Session — all frozen dataclasses/enums) ↓ -Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore, LLMClient) +Ports (protocol interfaces: Parser, Embedder, VectorStore, GraphStore, SessionStore) ↓ -Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite, ChromaDB, LiteLLM) +Infra (concrete implementations: tree-sitter, ONNX Runtime embeddings (local) / Jina API, SQLite, in-memory NumPy vector index) ``` ## Project Structure @@ -26,10 +26,11 @@ Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite ├── mimir/ # Server package (mimir-context-server) │ ├── domain/ # Core models, config, graph, catalog, guardrails, errors │ ├── ports/ # Interface definitions (embedder, parser, stores) -│ ├── services/ # Business logic (indexing, retrieval, catalog, impact, guardrail, temporal, session, quality, watcher) -│ ├── infra/ # Implementations (tree-sitter, embedders, SQLite, ChromaDB) +│ ├── services/ # Business logic (indexing, retrieval, catalog, impact, guardrail, temporal, session, quality) +│ ├── infra/ # Implementations (tree-sitter, embedders, SQLite, NumPy vector index) │ ├── adapters/ # External interfaces (CLI, MCP, HTTP, web UI) -│ └── container.py # Dependency injection wiring +│ ├── runtime.py # IndexerRuntime and QueryRuntime composition +│ └── container.py # Legacy local composition path ├── backstage-plugin/ # Backstage catalog backend module │ └── plugins/catalog-backend-module-mimir/ ├── client/ # Client package (mimir-server-client) @@ -47,20 +48,24 @@ Infra (concrete implementations: tree-sitter, sentence-transformers/jina, SQLite ## Data Storage -Mimir stores all index data in a local directory (default `.mimir/`, configurable via `data_dir` in config). It is split into two subfolders so git can track one and ignore the other: +Mimir stores all index data in a local directory (default `.mimir/`, configurable via `data_dir` in config). The indexer publishes immutable graph versions, and query surfaces consume only the active version. ``` .mimir/ -├── project/ # tracked in git — shared with CI & teammates -│ └── graph.db # SQLite: nodes, edges, repo_state, embeddings -└── session/ # ignored by git — personal / re-derivable +├── project/ +│ ├── graph.db # working indexer graph for full/incremental builds +│ ├── index_metadata.db # active version pointer and compatibility metadata +│ └── index_jobs.db # durable indexer job queue +├── indexes/ +│ └── /graph.db # published immutable graph snapshots +└── session/ ├── sessions.db # SQLite: session state for deduplication + ├── feedback.db # retrieval feedback signals ├── models/ # downloaded embedding weights - ├── chroma/ # ChromaDB data (only if backend = "chroma") └── guardrail_audit.jsonl # Guardrail check audit log (if enabled) ``` -Committing `.mimir/project/graph.db` lets CI run `mimir guardrail check` without rebuilding the graph from scratch, which is the biggest cold-start cost in the pipeline. +Run `mimir indexer run` or `mimir indexer worker` in the central indexing environment. Query surfaces (`mimir query serve`, MCP, HTTP, web inspector, guardrail checks) fail fast when no active index exists, rather than rebuilding implicitly. ## Supported Languages diff --git a/docs/backstage.md b/docs/backstage.md index ad1a817..593b204 100644 --- a/docs/backstage.md +++ b/docs/backstage.md @@ -17,7 +17,7 @@ Mimir includes a Backstage catalog backend module that auto-populates your servi ## Setup -1. Start the Mimir HTTP server: `mimir serve --http` +1. Build an index with `mimir indexer run`, then start the query HTTP server with `mimir query serve --http`. 2. Install the plugin in your Backstage backend: ```bash yarn --cwd packages/backend add @mimir/plugin-catalog-backend-module-mimir diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 074c08a..f311a4c 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -6,16 +6,15 @@ ``` mimir init Create a mimir.toml config file -mimir index Index all configured repositories -mimir search "query" Search and assemble context -mimir ask "query" Interactive search (retrieves context, calls LLM) -mimir serve Start the MCP server -mimir ui Launch the web inspector (localhost:8420) -mimir hotspots Show recently/frequently changed code -mimir quality Analyze graph quality and detect gaps -mimir graph Explore the code graph -mimir clear Delete locally stored index data -mimir vacuum Compact the SQLite database +mimir indexer run Build and publish an index version +mimir indexer sync Mirror one repo and publish a refreshed version +mimir indexer enqueue KIND Queue a durable index job: full, incremental, sync +mimir indexer worker Process durable index jobs +mimir query search "query" Search the active published index +mimir query status Show active index version and graph counts +mimir query serve --http Start the query-only HTTP server +mimir query serve --remote Proxy local MCP stdio to a remote query server +mimir query ui Launch the read-only web inspector mimir guardrail check Validate a diff against architectural rules mimir guardrail init Generate example rules + agent policy files mimir guardrail test Dry-run: validate rule syntax against current graph @@ -24,17 +23,16 @@ mimir guardrail approve --reason "..." trailer on HEAD to clear matching BLOCK violations mimir workspace Manage named workspaces -Index flags: +Indexer flags: --clean Force a full re-index (wipes existing data) --mode MODE Summary mode: none, heuristic + --commit-sha SHA Specific commit for repo sync -Serve modes: - (default) stdio MCP server (local IDE integration) +Query serve modes: --http Shared HTTP server (team access) --http-port PORT HTTP port (default: 8421) --http-host HOST HTTP bind address (default: 0.0.0.0) --remote / -r URL Proxy to a remote Mimir HTTP server - --watch Enable live file watching (re-indexes on save) Global flags: --workspace / -w NAME Use a named workspace from the registry diff --git a/docs/configuration.md b/docs/configuration.md index 4a4da34..3a732b5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -25,9 +25,6 @@ concurrency = 10 model = "all-mpnet-base-v2" # local, offline, no API keys needed batch_size = 64 -[vector_db] -backend = "numpy" # numpy (in-process) | chroma (persistent) - [retrieval] default_beam_width = 3 default_token_budget = 8000 @@ -44,10 +41,6 @@ co_retrieval_enabled = true context_decay_turns = 5 topic_tracking_alpha = 0.3 -[watcher] -enabled = false # set to true or use --watch flag -debounce_ms = 1000 # ms to wait after last file event before processing -batch_window_ms = 2000 # max ms to accumulate changes before forcing a flush ``` ## Reference @@ -57,16 +50,12 @@ batch_window_ms = 2000 # max ms to accumulate changes before forcing a flu | `indexing` | `summary_mode` | `heuristic` | `none` = raw code only; `heuristic` = signatures, docstrings, and dependency info | | `indexing` | `max_file_size_kb` | `500` | Skip files larger than this | | `indexing` | `concurrency` | `10` | Parallel file parsing limit | -| `embeddings` | `model` | `jina-embeddings-v2-base-code` | Any sentence-transformers model or Jina API model | -| `vector_db` | `backend` | `numpy` | `numpy` for dev/small projects; `chroma` for persistent production use | +| `embeddings` | `model` | `jina-embeddings-v2-base-code` | Any sentence-transformers or Jina model that ships an ONNX export (run locally), or `api:` for the Jina API | | `retrieval` | `default_token_budget` | `8000` | Maximum tokens per context bundle | | `retrieval` | `expansion_hops` | `2` | How many graph hops to expand from seed nodes | | `retrieval` | `hybrid_alpha` | `0.7` | Weight between semantic (1.0) and BM25 keyword (0.0) search | | `retrieval` | `relevance_gate` | `0.3` | Minimum score to include expanded nodes | | `temporal` | `recency_lambda` | `0.02` | Exponential decay rate for recency scoring | | `session` | `context_decay_turns` | `5` | Turns before previously-sent code is re-included fully | -| `watcher` | `enabled` | `false` | Enable live file watching for automatic re-indexing | -| `watcher` | `debounce_ms` | `1000` | Debounce delay after the last file event | -| `watcher` | `batch_window_ms` | `2000` | Maximum time to accumulate changes before flushing | See also: [How It Works](how-it-works.md) for what each setting controls, [Docker](docker.md) for environment variable overrides. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index ad97124..45b88e6 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -51,13 +51,13 @@ Co-retrieval learning tracks which nodes appear together and boosts similar node ## Incremental Indexing -After the initial full index, `mimir index` runs incrementally: +After the initial full index, `mimir indexer run` runs incrementally: ```bash -mimir index # first time: full; subsequent: incremental +mimir indexer run # first time: full; subsequent: incremental git pull # pull changes -mimir index # only re-indexes the diff -mimir index --clean # force full re-index (wipes existing data) +mimir indexer run # only re-indexes the diff +mimir indexer run --clean # force full re-index (wipes existing data) ``` Mimir stores the last-indexed commit hash per repo. On each run: @@ -70,31 +70,24 @@ Mimir stores the last-indexed commit hash per repo. On each run: Unchanged repos are skipped entirely. -## Live File Watching +## Fresh Indexes -For an always-fresh graph during development, Mimir can watch your repos for file changes and re-index automatically: +For an always-fresh graph during development or CI, run the indexer after changes or use the durable worker: ```bash -mimir serve --watch # start MCP server with live re-indexing +mimir indexer worker ``` -Or enable it permanently in `mimir.toml`: - -```toml -[watcher] -enabled = true -``` - -The file watcher uses a debounced approach — rapid saves (e.g., auto-format on save) are batched into a single re-index operation. Every file save triggers: +Each index refresh: 1. Tree-sitter re-parse of the changed file 2. Stale node removal + new node creation 3. Affected-set cross-file resolution (only the changed symbols, not the full graph) 4. Heuristic summary generation 5. Embedding + vector store update -6. BM25 index invalidation +6. Published index activation -The graph, vector store, and search index stay in sync with your code as you edit. +Query runtimes poll for the active published version and swap to it without running indexing work. ## Quality Scoring & Gap Detection @@ -127,4 +120,4 @@ Typical gap reasons include: Gap detection is useful after indexing to verify coverage, or periodically to catch regressions as the codebase evolves. -See also: [Configuration](configuration.md) for tuning parameters, [CLI Reference](cli-reference.md) for `mimir quality` and `mimir index`. +See also: [Configuration](configuration.md) for tuning parameters and [CLI Reference](cli-reference.md) for `mimir query` and `mimir indexer`. diff --git a/docs/serving-modes.md b/docs/serving-modes.md index afed462..62bc6dc 100644 --- a/docs/serving-modes.md +++ b/docs/serving-modes.md @@ -6,8 +6,8 @@ Mimir supports three serving modes via the [Model Context Protocol](https://mode | Mode | Command | Package needed | Use case | |---|---|---|---| -| **Local stdio MCP** | `mimir serve` | `mimir-context-server` | Solo dev with repos on their machine | -| **Shared HTTP server** | `mimir serve --http` | `mimir-context-server` | Central team server that indexes all repos | +| **Local stdio MCP** | `mimir query serve` | `mimir-context-server` | Solo dev querying a published local index | +| **Shared HTTP server** | `mimir query serve --http` | `mimir-context-server` | Query-only server over the active published index | | **Remote MCP proxy** | `mimir-client serve ` | `mimir-client` | Dev without local repos queries a shared server | ## Local MCP (Default) @@ -19,23 +19,16 @@ Add to your IDE's MCP config (`~/.cursor/mcp.json` or `claude_desktop_config.jso "mcpServers": { "mimir": { "command": "mimir", - "args": ["serve", "--config", "/path/to/your-project/mimir.toml"] + "args": ["query", "serve", "--config", "/path/to/your-project/mimir.toml"] } } } ``` -With live re-indexing: +Build the local index separately: -```json -{ - "mcpServers": { - "mimir": { - "command": "mimir", - "args": ["serve", "--watch", "--config", "/path/to/your-project/mimir.toml"] - } - } -} +```bash +mimir indexer run --config /path/to/your-project/mimir.toml ``` ## MCP Tools @@ -43,16 +36,15 @@ With live re-indexing: | Tool | Description | |---|---| | `get_context` | Retrieve relevant source code for a natural language query. Call before answering any codebase question. | -| `get_write_context` | Get everything you need before editing a file: interfaces, sibling implementations, test file, DI registrations, and import graph. | -| `get_impact` | Analyze what would break if you change a symbol or file: callers, type users, implementors, test files, and transitive dependencies. | +| `get_write_context` | Get edit-time context for a target file from the active index. | +| `get_impact` | Analyze what would break if you change a symbol or file. | | `get_quality` | Analyze graph connectivity quality and detect gaps — nodes with missing or weak connections that may indicate under-indexed areas. | | `get_catalog` | Generate a Backstage-compatible service catalog: services, APIs, dependencies, tech stack, ownership, and quality scores. | | `get_catalog_drift` | Compare declared service dependencies against code-analyzed reality. Detects undeclared and missing dependencies with a drift score. | -| `validate_change` | Validate a code diff against architectural rules (layer violations, cycles, coupling, blast radius, scope bans). Call before committing AI-generated changes. | +| `validate_change` | Validate a diff against architectural rules using the active index. | | `can_i_modify` | Check if a file is within the agent's allowed scope per the agent policy. | | `get_graph_stats` | Node/edge counts, breakdown by kind and repo | | `get_hotspots` | Recently and frequently modified code | -| `clear_data` | Wipe the index | Pass a consistent `session_id` on every turn to enable cross-turn deduplication: @@ -77,8 +69,8 @@ For teams where not everyone has access to all repos — mobile devs needing bac │ /repos/ios-app/ (Swift) │ │ │ │ Runs: │ -│ mimir index (cron or CI trigger) │ -│ mimir serve --http (always on, port 8421) │ +│ mimir indexer worker (queue-driven indexer) │ +│ mimir query serve --http (always on, port 8421) │ └──────────────────────────────┬────────────────────────────────┘ │ HTTP (port 8421) ┌────────────────────┼───────────────────┐ @@ -98,8 +90,8 @@ For teams where not everyone has access to all repos — mobile devs needing bac ### Server Setup ```bash -mimir index --config /repos/mimir.toml -mimir serve --http --config /repos/mimir.toml +mimir indexer run --config /repos/mimir.toml +mimir query serve --http --config /repos/mimir.toml # → Listening on http://0.0.0.0:8421 ``` @@ -120,13 +112,14 @@ pipx install mimir-server-client } ``` -> If you have the full `mimir-context-server` installed, `mimir serve --remote http://team-server:8421` also works. +> If you have the full `mimir-context-server` installed, `mimir query serve --remote http://team-server:8421` also works. ## HTTP API | Endpoint | Method | Description | |---|---|---| | `/api/v1/health` | GET | Health check — returns status, workspace name, node/edge counts | +| `/api/v1/index/status` | GET | Active published index version, repo commits, and graph counts | | `/api/v1/context` | POST | Search — `{"query": "...", "budget": 8000, "repos": ["api"], "session_id": "..."}` | | `/api/v1/write_context` | POST | Write-path context — `{"file_path": "src/auth/login.py"}` | | `/api/v1/impact` | POST | Impact analysis — `{"symbol_name": "AuthService", "max_hops": 3}` | @@ -137,7 +130,6 @@ pipx install mimir-server-client | `/api/v1/catalog/{repo}` | GET | Single-service catalog entry | | `/api/v1/catalog/drift` | POST | Dependency drift detection — `{"repo": "my-api", "declared_dependencies": [{"name": "svc-b"}]}` | | `/api/v1/guardrails/check` | POST | Architectural guardrail check — `{"diff": "...", "rules_path": "mimir-rules.yaml"}` | -| `/api/v1/clear` | POST | Clear index data — `{"graph": true, "sessions": true}` | | `/api/v1/mcp` | POST | Raw MCP JSON-RPC passthrough (used by `--remote` proxy) | See also: [Docker](docker.md) for containerized deployment, [Configuration](configuration.md) for `mimir.toml`. diff --git a/docs/web-inspector.md b/docs/web-inspector.md index 07f7d78..eff9597 100644 --- a/docs/web-inspector.md +++ b/docs/web-inspector.md @@ -5,8 +5,8 @@ Mimir includes a browser-based graph visualization UI: ```bash -mimir ui # launches at http://localhost:8420 -mimir ui --port 9000 # custom port +mimir query ui # launches at http://localhost:8420 +mimir query ui --port 9000 # custom port ``` Explore nodes by kind and repo, inspect edges, view cross-repo links, and drill into individual symbols. diff --git a/docs/workspaces.md b/docs/workspaces.md index 73fa037..e4c43f8 100644 --- a/docs/workspaces.md +++ b/docs/workspaces.md @@ -11,11 +11,11 @@ mimir workspace add mobile-app --config /work/mobile/mimir.toml mimir workspace list # Index each -mimir index --workspace payment-api -mimir index --workspace mobile-app +mimir indexer run --workspace payment-api +mimir indexer run --workspace mobile-app # Search a specific workspace -mimir search "auth flow" --workspace payment-api +mimir query search "auth flow" --workspace payment-api ``` MCP config — each server is locked to one workspace: @@ -23,8 +23,8 @@ MCP config — each server is locked to one workspace: ```json { "mcpServers": { - "mimir-payment": {"command": "mimir", "args": ["serve", "--workspace", "payment-api"]}, - "mimir-mobile": {"command": "mimir", "args": ["serve", "--workspace", "mobile-app"]} + "mimir-payment": {"command": "mimir", "args": ["query", "serve", "--workspace", "payment-api"]}, + "mimir-mobile": {"command": "mimir", "args": ["query", "serve", "--workspace", "mobile-app"]} } } ``` diff --git a/mimir.toml b/mimir.toml index 71983bc..11f7de1 100644 --- a/mimir.toml +++ b/mimir.toml @@ -20,9 +20,6 @@ max_file_size_kb = 500 model = "all-mpnet-base-v2" batch_size = 64 -[vector_db] -backend = "chroma" - [retrieval] default_beam_width = 3 default_token_budget = 8000 diff --git a/mimir/adapters/ci/guardrails-action.yml b/mimir/adapters/ci/guardrails-action.yml index b390146..1488e18 100644 --- a/mimir/adapters/ci/guardrails-action.yml +++ b/mimir/adapters/ci/guardrails-action.yml @@ -18,7 +18,7 @@ jobs: run: pip install mimir-context-server - name: Build index (incremental) - run: mimir index + run: mimir indexer run - name: Run guardrails run: | diff --git a/mimir/adapters/cli.py b/mimir/adapters/cli.py index 0d2414c..a7b740d 100644 --- a/mimir/adapters/cli.py +++ b/mimir/adapters/cli.py @@ -1,1171 +1,8 @@ -"""Typer CLI — primary driving adapter for Mimir. +"""Backward-compatible CLI entrypoint.""" -All commands are thin wrappers that initialise the ``Container`` -from ``mimir.toml`` and delegate to the appropriate service. -""" +from mimir.adapters.cli_support import app -from __future__ import annotations - -import asyncio -import json -import logging -import os -import sys -from pathlib import Path -from typing import Optional - -import typer -from rich.console import Console -from rich.table import Table -from rich.tree import Tree - -from mimir.domain.config import ConfigError, MimirConfig - -app = typer.Typer( - name="mimir", - help="Mimir — Context Server v1 — Context Engine for Large-Scale Codebases", - no_args_is_help=True, -) -console = Console() - -# Default config path -_DEFAULT_CONFIG = Path("mimir.toml") -_NO_WORKSPACE = "" # sentinel for Optional workspace flag - - -def _resolve_config_path( - config: Path, - workspace: Optional[str] = None, -) -> tuple[Path, Optional[str]]: - """Resolve the config path and workspace name, enforcing mutual exclusivity. - - Returns (config_path, workspace_name_or_None). - """ - err_console = Console(stderr=True) - - # Check for --workspace via env var fallback - resolved_workspace = workspace or os.environ.get("MIMIR_WORKSPACE") or None - - explicit_config = config != _DEFAULT_CONFIG # user passed --config explicitly - - if resolved_workspace and explicit_config: - err_console.print( - "[red bold]Error:[/] --workspace and --config are mutually exclusive. " - "Use one or the other." - ) - raise typer.Exit(1) - - if resolved_workspace: - from mimir.domain.workspace import WorkspaceRegistry - try: - registry = WorkspaceRegistry() - config_path = registry.resolve(resolved_workspace) - except ConfigError as exc: - err_console.print(f"[red bold]Workspace error:[/] {exc}") - raise typer.Exit(1) from exc - return config_path, resolved_workspace - - return config, None - - -def _load_config( - config: Path, - workspace: Optional[str] = None, -) -> tuple[MimirConfig, Optional[str]]: - """Load and validate config with user-friendly error messages. - - Returns (config, workspace_name_or_None). - """ - config_path, ws_name = _resolve_config_path(config, workspace) - try: - return MimirConfig.load(config_path), ws_name - except ConfigError as exc: - err_console = Console(stderr=True) - err_console.print(f"[red bold]Config error:[/] {exc}") - raise typer.Exit(1) from exc - - -def _enable_watcher(watcher_config): - """Return a copy of WatcherConfig with enabled=True.""" - from dataclasses import replace - return replace(watcher_config, enabled=True) - - -def _setup_logging(verbose: bool) -> None: - from rich.logging import RichHandler - level = logging.DEBUG if verbose else logging.INFO - handler = RichHandler(rich_tracebacks=True, console=console, markup=False, show_path=False) - handler.setFormatter(logging.Formatter("%(name)s — %(message)s", datefmt="[%X]")) - root = logging.getLogger() - root.setLevel(level) - root.handlers.clear() - root.addHandler(handler) - logging.getLogger("aiohttp.access").setLevel(logging.ERROR) - - -# ------------------------------------------------------------------ -# workspace sub-app -# ------------------------------------------------------------------ - -workspace_app = typer.Typer( - name="workspace", - help="Manage named Mimir workspaces (~/.mimir/workspaces.toml).", - no_args_is_help=True, -) -app.add_typer(workspace_app, name="workspace") - - -@workspace_app.command("add") -def workspace_add( - name: str = typer.Argument(..., help="Workspace name (letters, digits, hyphens, underscores)"), - config: Path = typer.Option( - _DEFAULT_CONFIG, "--config", "-c", - help="Path to mimir.toml (default: ./mimir.toml)", - ), -) -> None: - """Register a workspace in the global registry.""" - from mimir.domain.workspace import WorkspaceRegistry - registry = WorkspaceRegistry() - try: - registry.add(name, config) - console.print(f"[green]✓ Registered workspace:[/] {name} → {config.resolve()}") - console.print(f" Registry: {registry._path}") - except ConfigError as exc: - console.print(f"[red bold]Error:[/] {exc}") - raise typer.Exit(1) from exc - - -@workspace_app.command("list") -def workspace_list() -> None: - """List all registered workspaces.""" - from mimir.domain.workspace import WorkspaceRegistry - registry = WorkspaceRegistry() - workspaces = registry.list() - - if not workspaces: - console.print("[yellow]No workspaces registered.[/] Use [bold]mimir workspace add[/] to register one.") - return - - table = Table(title=f"Registered Workspaces ({registry._path})") - table.add_column("Name", style="cyan bold") - table.add_column("Config Path", style="green") - table.add_column("Exists?", style="yellow") - for name, path in sorted(workspaces.items()): - exists = "✓" if path.is_file() else "✗ missing" - table.add_row(name, str(path), exists) - console.print(table) - - -@workspace_app.command("remove") -def workspace_remove( - name: str = typer.Argument(..., help="Workspace name to remove"), - yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), -) -> None: - """Unregister a workspace from the global registry.""" - from mimir.domain.workspace import WorkspaceRegistry - registry = WorkspaceRegistry() - if not yes: - confirmed = typer.confirm(f"Remove workspace '{name}' from registry?") - if not confirmed: - console.print("[yellow]Aborted[/]") - raise typer.Exit(0) - try: - registry.remove(name) - console.print(f"[green]✓ Removed workspace:[/] {name}") - except ConfigError as exc: - console.print(f"[red bold]Error:[/] {exc}") - raise typer.Exit(1) from exc - - - -# ------------------------------------------------------------------ -# guardrail sub-app -# ------------------------------------------------------------------ - -guardrail_app = typer.Typer( - name="guardrail", - help="Architectural guardrails — validate changes against structural rules.", - no_args_is_help=True, -) -app.add_typer(guardrail_app, name="guardrail") - - -def _git_auto_diff(base: str = "") -> str: - """Auto-detect a diff from git. - - Strategy: - 1. If there are staged changes, use ``git diff --cached``. - 2. If there are unstaged changes, use ``git diff``. - 3. Otherwise, diff the current branch against *base* (or auto-detected - main/master branch). - """ - import subprocess as _sp - - def _run_git(*args: str) -> str: - try: - return _sp.check_output(["git", *args], text=True, stderr=_sp.DEVNULL) - except Exception: - return "" - - # 1. Staged changes - staged = _run_git("diff", "--cached") - if staged.strip(): - console.print("[dim]Using staged changes (git diff --cached)[/dim]") - return staged - - # 2. Unstaged changes - unstaged = _run_git("diff") - if unstaged.strip(): - console.print("[dim]Using unstaged changes (git diff)[/dim]") - return unstaged - - # 3. Branch diff against base - if not base: - # Auto-detect default branch - for candidate in ("main", "master", "develop"): - check = _run_git("rev-parse", "--verify", f"refs/heads/{candidate}") - if check.strip(): - base = candidate - break - if not base: - # Fallback: use HEAD~1 - base = "HEAD~1" - - branch_diff = _run_git("diff", f"{base}...HEAD") - if branch_diff.strip(): - console.print(f"[dim]Using branch diff ({base}...HEAD)[/dim]") - return branch_diff - - return "" - - -@guardrail_app.command("check") -def guardrail_check( - diff: str = typer.Option( - "", "--diff", "-d", - help="Path to diff file, '-' for stdin, or empty for auto-detect from git", - ), - base: str = typer.Option( - "", "--base", "-b", - help="Base ref for git diff (e.g. main, origin/main). Default: auto-detect", - ), - rules: Path = typer.Option( - Path("mimir-rules.yaml"), "--rules", "-r", - help="Path to rules YAML file", - ), - output: str = typer.Option( - "text", "--output", "-o", - help="Output format: text, json, github-pr-comment", - ), - report_file: Optional[Path] = typer.Option( - None, "--report-file", - help="Write the formatted report to a file (in addition to stdout)", - ), - no_approvals: bool = typer.Option( - False, "--no-approvals", - help="Ignore HEAD commit trailers (show raw BLOCK violations)", - ), - head: str = typer.Option( - "HEAD", "--head", - help=( - "Git ref whose commit message is scanned for Mimir-Approved " - "trailers. Defaults to HEAD. In GitHub Actions on pull_request " - "events, pass ${{ github.event.pull_request.head.sha }} because " - "the default checkout is a merge commit without the trailer." - ), - ), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Validate a diff against architectural rules. - - When no --diff is given, automatically detects changes from git: - \b - - Staged changes (git diff --cached) - - Unstaged changes (git diff) - - Branch diff against --base (or auto-detected main/master) - - BLOCK violations are cleared only when the HEAD commit carries a - matching ``Mimir-Approved:`` trailer. Exit codes: 0 = passed, - 1 = errors or unapproved blocks. - """ - _setup_logging(verbose) - - from mimir.domain.guardrails_config import load_rules - from mimir.services.guardrail import apply_approvals - from mimir.services.guardrail_report import GuardrailReporter - from mimir.services.guardrail_trailers import read_head_approval - - # Load rules (fail-closed) - try: - rule_list = load_rules(rules) - except Exception as exc: - console.print(f"[red bold]Rule loading error:[/] {exc}") - raise typer.Exit(1) from exc - - # Read diff - if diff == "-": - diff_text = sys.stdin.read() - elif diff: - diff_path = Path(diff) - if not diff_path.exists(): - console.print(f"[red bold]Diff file not found:[/] {diff}") - raise typer.Exit(1) - diff_text = diff_path.read_text() - else: - # Auto-detect from git - diff_text = _git_auto_diff(base) - - if not diff_text.strip(): - console.print("[yellow]Empty diff — nothing to check.[/]") - raise typer.Exit(0) - - # Load config and container - try: - cfg, ws_name = _load_config(config, workspace) - except SystemExit: - raise - except Exception as exc: - console.print(f"[red bold]Config error:[/] {exc}") - raise typer.Exit(1) from exc - - from mimir.container import Container - container = Container(cfg) - graph = container.load_graph() - - # Evaluate - result = asyncio.run(container.guardrail.evaluate(graph, diff_text, rule_list)) - - # Read approval trailer from HEAD and apply to BLOCK violations - if not no_approvals: - block_present = any( - v.severity.value == "block" for v in result.violations - ) - if block_present: - head_approval = read_head_approval(head) - if head_approval is None: - approved_ids: frozenset[str] = frozenset() - reason = "" - else: - approved_ids = head_approval.rule_ids - reason = head_approval.reason - result = apply_approvals( - result, - approved_rule_ids=approved_ids, - reason=reason, - ) - - # Format output - reporter = GuardrailReporter() - if output == "json": - formatted = json.dumps(result.to_dict(), indent=2) - console.print_json(formatted) - elif output == "github-pr-comment": - formatted = reporter.format_github_pr_comment(result) - console.print(formatted) - else: - formatted = reporter.format_text(result) - console.print(formatted) - - # Write report file if requested - if report_file: - report_file.parent.mkdir(parents=True, exist_ok=True) - report_file.write_text(formatted + "\n", encoding="utf-8") - - if not result.passed: - raise typer.Exit(1) - - -@guardrail_app.command("init") -def guardrail_init( - force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing files"), -) -> None: - """Generate example mimir-rules.yaml and mimir-agent-policy.yaml.""" - import shutil - - examples = { - "mimir-rules.yaml": Path(__file__).parent.parent.parent / "mimir-rules.yaml", - "mimir-agent-policy.yaml": Path(__file__).parent.parent.parent / "mimir-agent-policy.yaml", - } - - for name, source in examples.items(): - target = Path(name) - if target.exists() and not force: - console.print(f"[yellow]Skipping {name} (already exists, use --force to overwrite)[/]") - continue - if source.exists(): - shutil.copy2(source, target) - console.print(f"[green]Created {name}[/]") - else: - console.print(f"[yellow]Template {name} not found in package[/]") - - console.print("\n[bold]Next steps:[/]") - console.print(" 1. Edit mimir-rules.yaml to match your architecture") - console.print(" 2. Run: git diff | mimir guardrail check --diff -") - - -@guardrail_app.command("test") -def guardrail_test( - rules: Path = typer.Option( - Path("mimir-rules.yaml"), "--rules", "-r", - help="Path to rules YAML file", - ), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Dry-run: validate rule syntax and report current metric values.""" - _setup_logging(verbose) - from mimir.domain.guardrails_config import load_rules - - # Validate rules - try: - rule_list = load_rules(rules) - except Exception as exc: - console.print(f"[red bold]Rule loading error:[/] {exc}") - raise typer.Exit(1) from exc - - console.print(f"[green]Loaded {len(rule_list)} rules from {rules}[/]") - for r in rule_list: - console.print(f" [{r.severity.value}] {r.id}: {r.description}") - - # Optionally check against graph - try: - cfg, ws_name = _load_config(config, workspace) - except Exception: - console.print("\n[yellow]No config found — skipping graph analysis.[/]") - return - - from mimir.container import Container - container = Container(cfg) - graph = container.load_graph() - console.print(f"\n[bold]Graph:[/] {graph.node_count} nodes, {graph.edge_count} edges") - console.print("[green]Rules syntax OK. Ready for guardrail checks.[/]") - - -@guardrail_app.command("approve") -def guardrail_approve( - rule_ids: list[str] = typer.Argument( - ..., help="Rule IDs to approve (space-separated)", - ), - reason: str = typer.Option( - ..., "--reason", - help="Reason for approving (becomes the Mimir-Approved-Reason trailer)", - ), -) -> None: - """Approve BLOCK violations by committing an approval trailer on HEAD. - - Creates an empty commit whose message carries ``Mimir-Approved:`` and - ``Mimir-Approved-Reason:`` trailers. The next ``mimir guardrail check`` - run on this branch will clear the matching BLOCK violations. - - Any subsequent commit that does not re-add the trailer automatically - invalidates the approval (HEAD has moved). There is no self-approval - guard — whoever commits the trailer is trusted; the audit trail is - the git log. - """ - import subprocess - - if not reason.strip(): - console.print("[red bold]--reason must not be empty[/]") - raise typer.Exit(1) - - ids = [rid.strip() for rid in rule_ids if rid.strip()] - if not ids: - console.print("[red bold]At least one rule id is required[/]") - raise typer.Exit(1) - - subject = f"approval: {', '.join(ids)}" - body = ( - f"{subject}\n" - "\n" - f"Mimir-Approved: {', '.join(ids)}\n" - f"Mimir-Approved-Reason: {reason.strip()}\n" - ) - - try: - subprocess.run( - ["git", "commit", "--allow-empty", "-m", body], - check=True, - ) - except subprocess.CalledProcessError as exc: - console.print(f"[red bold]git commit failed:[/] {exc}") - raise typer.Exit(1) from exc - - console.print(f"[green]Approval commit created for:[/] {', '.join(ids)}") - console.print(f" Reason: {reason}") - console.print("") - console.print("[bold]Don't forget to push:[/] git push") - - -# ------------------------------------------------------------------ -# index -# ------------------------------------------------------------------ - -def _kill_serve_processes() -> int: - """Find and SIGTERM any running ``mimir serve`` processes, including - Docker containers that bind-mount the current project directory. - - Returns the number of processes/containers stopped. - """ - import os - import signal - import subprocess - - current_pid = os.getpid() - killed = 0 - - # 1. Kill local (non-Docker) mimir serve processes - try: - result = subprocess.run( - ["pgrep", "-f", "mimir.*serve"], - capture_output=True, - text=True, - ) - pids = [int(p) for p in result.stdout.strip().splitlines() if p.strip()] - - for pid in pids: - if pid == current_pid: - continue - try: - os.kill(pid, signal.SIGTERM) - killed += 1 - except ProcessLookupError: - pass # already gone - except PermissionError: - pass # not ours to kill - except FileNotFoundError: - pass # pgrep not available (Windows?) - - # 2. Stop Docker containers running mimir that mount this project directory. - # A running container with a bind-mount holds open SQLite file handles; - # if we delete chroma files while those handles are live, SQLite shifts - # into readonly mode (error code 1032). - try: - cwd = os.getcwd() - # List running containers whose command contains "mimir" - result = subprocess.run( - ["docker", "ps", "--filter", "status=running", - "--format", "{{.ID}}"], - capture_output=True, text=True, timeout=5, - ) - if result.returncode == 0: - for container_id in result.stdout.strip().splitlines(): - if not container_id.strip(): - continue - # Inspect the container's bind mounts - inspect = subprocess.run( - ["docker", "inspect", "--format", - '{{range .Mounts}}{{.Source}}::{{.Destination}} {{end}}', - container_id.strip()], - capture_output=True, text=True, timeout=5, - ) - if inspect.returncode == 0 and cwd in inspect.stdout: - subprocess.run( - ["docker", "stop", container_id.strip()], - capture_output=True, text=True, timeout=15, - ) - killed += 1 - except (FileNotFoundError, subprocess.TimeoutExpired): - pass # docker not installed or timed out - - return killed - -@app.command() -def index( - mode: Optional[str] = typer.Option(None, help="Summary mode: none, heuristic"), - clean: bool = typer.Option(False, "--clean", help="Force a full re-index (wipes existing data)"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c", help="Config file path"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Index all configured repositories. Uses incremental indexing by default.""" - _setup_logging(verbose) - - if mode == "llm": - console.print( - "[red bold]Error:[/] summary_mode 'llm' has been removed. " - "Use 'heuristic' (default) or 'none'." - ) - raise typer.Exit(1) - - # Stop any running `mimir serve` instances to release database locks. - killed = _kill_serve_processes() - if killed: - import time - console.print( - f"[yellow]⚠ Stopped {killed} running 'mimir serve' process(es) to release " - f"database locks. Re-run [bold]mimir serve[/] after indexing completes.[/]" - ) - time.sleep(0.5) # brief pause so processes can flush & release file handles - - cfg, _ = _load_config(config, workspace) - - # For --clean, we must wipe the ChromaDB directory BEFORE Container() is created. - # If we delete chroma files while a live ChromaDB client holds open handles, sqlite - # shifts into readonly mode and all subsequent writes fail with code 1032. - if clean: - import shutil - chroma_dir = cfg.vector_db.persist_directory or str(cfg.session_dir / "chroma") - chroma_path = Path(chroma_dir) - if chroma_path.exists() and cfg.vector_db.backend == "chroma": - shutil.rmtree(chroma_path) - chroma_path.mkdir(parents=True, exist_ok=True) - - from mimir.container import Container - container = Container(cfg) - - try: - if clean: - # Wipe only the SQLite graph (chroma already wiped above) - container.graph_store.clear() - container._graph = None - console.print("[dim]Wiped graph + vector store.[/]") - graph = asyncio.run(container.indexing.index_all(mode_override=mode)) - stats = graph.stats() - console.print(f"[green]✓ Clean full index complete[/]") - console.print(f" Nodes: {stats['total_nodes']}") - console.print(f" Edges: {stats['total_edges']}") - console.print(f" Repos: {', '.join(stats['repos'])}") - else: - graph, report = asyncio.run(container.indexing.index_incremental(mode_override=mode)) - if report.get("mode") == "full_fallback": - stats = graph.stats() - console.print(f"[green]✓ Initial full index complete[/]") - console.print(f" Nodes: {stats['total_nodes']}") - console.print(f" Edges: {stats['total_edges']}") - console.print(f" Repos: {', '.join(stats['repos'])}") - else: - _display_incremental_report(report) - except Exception as exc: - console.print(f"[red bold]Indexing failed:[/] {exc}") - raise typer.Exit(1) from exc - finally: - container.close() - - -def _display_incremental_report(report: dict) -> None: - """Pretty-print the incremental indexing report.""" - - console.print("[green]✓ Incremental index complete[/]") - - for repo_name, info in report.get("repos", {}).items(): - status = info.get("status", "unknown") - - if status == "up_to_date": - console.print(f" [dim]{repo_name}:[/] [green]up to date[/] ({info.get('commit', '')})") - elif status == "updated": - console.print(f" [cyan]{repo_name}:[/] [yellow]updated[/] ({info.get('commit', '')})") - console.print(f" Files: +{info.get('files_added', 0)} added, ~{info.get('files_modified', 0)} modified, -{info.get('files_deleted', 0)} deleted") - console.print(f" Parsed: {info.get('files_parsed', 0)} files, {info.get('symbols_parsed', 0)} symbols") - console.print(f" Nodes: -{info.get('nodes_removed', 0)} removed") - elif status == "full_index": - console.print(f" [cyan]{repo_name}:[/] [yellow]full index[/] ({info.get('reason', '')})") - elif status == "skipped": - console.print(f" [dim]{repo_name}:[/] [red]skipped[/] ({info.get('reason', '')})") - - console.print(f"\n [bold]Total:[/] -{report.get('total_removed', 0)} removed, +{report.get('total_added', 0)} added") - console.print(f" [bold]Graph:[/] {report.get('graph_nodes', 0)} nodes, {report.get('graph_edges', 0)} edges") - - - -# ------------------------------------------------------------------ -# search -# ------------------------------------------------------------------ - -@app.command() -def search( - query: str = typer.Argument(..., help="Natural language query"), - budget: int = typer.Option(8000, "--budget", "-b", help="Token budget"), - repos: Optional[str] = typer.Option(None, "--repos", "-r", help="Comma-separated repo filter"), - flat: bool = typer.Option(False, "--flat", help="Force flat search"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Search the indexed codebase and assemble context.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - graph = container.load_graph() - repo_list = repos.split(",") if repos else None - - bundle = asyncio.run(container.retrieval.search( - query=query, - graph=graph, - token_budget=budget, - repos=repo_list, - flat=flat, - )) - - # Display results - console.print(f"\n[bold]{bundle.summary}[/]") - if bundle.session_note: - console.print(f"[dim]{bundle.session_note}[/]") - console.print(f"[dim]Tokens: {bundle.token_count}[/]\n") - - console.print(bundle.format_for_llm()) - except Exception as exc: - console.print(f"[red bold]Search failed:[/] {exc}") - raise typer.Exit(1) from exc - finally: - container.close() - - - -# ------------------------------------------------------------------ -# graph -# ------------------------------------------------------------------ - -@app.command("graph") -def graph_cmd( - stats: bool = typer.Option(False, "--stats", help="Show graph statistics"), - show: Optional[str] = typer.Option(None, "--show", help="Show node details"), - cross_repo: bool = typer.Option(False, "--cross-repo", help="Show cross-repo edges"), - path_from: Optional[str] = typer.Option(None, "--path-from", help="Find path from"), - path_to: Optional[str] = typer.Option(None, "--path-to", help="Find path to"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Explore the code graph.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - graph = container.load_graph() - - if stats: - s = graph.stats() - table = Table(title="Graph Statistics") - table.add_column("Metric", style="cyan") - table.add_column("Value", style="green") - table.add_row("Total Nodes", str(s["total_nodes"])) - table.add_row("Total Edges", str(s["total_edges"])) - table.add_row("Repos", ", ".join(s["repos"])) - for kind, count in sorted(s["nodes_by_kind"].items()): - table.add_row(f" {kind}", str(count)) - console.print(table) - - elif show: - node = graph.get_node(show) - if not node: - console.print(f"[red]Node not found: {show}[/]") - raise typer.Exit(1) - console.print(f"[bold]{node.id}[/]") - console.print(f" Kind: {node.kind.value}") - console.print(f" Repo: {node.repo}") - console.print(f" Path: {node.path}") - if node.signature: - console.print(f" Signature: {node.signature}") - if node.summary: - console.print(f" Summary: {node.summary[:200]}") - out_edges = graph.get_outgoing_edges(show) - if out_edges: - console.print(f"\n Outgoing ({len(out_edges)}):") - for e in out_edges[:20]: - console.print(f" → {e.kind.value} → {e.target}") - in_edges = graph.get_incoming_edges(show) - if in_edges: - console.print(f"\n Incoming ({len(in_edges)}):") - for e in in_edges[:20]: - console.print(f" ← {e.kind.value} ← {e.source}") - - elif cross_repo: - edges = graph.cross_repo_edges() - table = Table(title=f"Cross-Repo Edges ({len(edges)})") - table.add_column("Source", style="cyan") - table.add_column("Kind", style="yellow") - table.add_column("Target", style="green") - for e in edges: - table.add_row(e.source, e.kind.value, e.target) - console.print(table) - - elif path_from and path_to: - edges = graph.shortest_path(path_from, path_to) - if not edges: - console.print("[yellow]No path found[/]") - else: - console.print(f"[bold]Path ({len(edges)} hops):[/]") - for e in edges: - console.print(f" {e.source} --{e.kind.value}--> {e.target}") - else: - console.print("[yellow]Use --stats, --show, --cross-repo, or --path-from/--path-to[/]") - - finally: - container.close() - - -# ------------------------------------------------------------------ -# hotspots -# ------------------------------------------------------------------ - -@app.command() -def hotspots( - top: int = typer.Option(20, "--top", "-n", help="Number of hotspots"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Show recently and frequently changed code.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - graph = container.load_graph() - results = container.temporal.get_hotspots(graph, top_n=top) - - table = Table(title=f"Top {top} Hotspots") - table.add_column("Node", style="cyan") - table.add_column("Score", style="green") - table.add_column("Changes", style="yellow") - for node, score in results: - table.add_row(node.id, f"{score:.3f}", str(node.modification_count)) - console.print(table) - finally: - container.close() - - - -# ------------------------------------------------------------------ -# quality -# ------------------------------------------------------------------ - -@app.command() -def quality( - threshold: float = typer.Option(0.3, "--threshold", "-t", help="Quality score threshold for gap detection"), - top: int = typer.Option(50, "--top", "-n", help="Maximum number of gaps to show"), - repos: Optional[str] = typer.Option(None, "--repos", help="Comma-separated repo names to filter"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Analyze graph quality and detect gaps in symbol resolution.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - graph = container.load_graph() - repo_list = repos.split(",") if repos else None - overview = container.quality.detect_gaps( - graph, repos=repo_list, threshold=threshold, top_n=top, - ) - - # Overview table - table = Table(title="Graph Quality Overview") - table.add_column("Metric", style="cyan") - table.add_column("Value", style="green") - table.add_row("Total Nodes", str(overview.total_nodes)) - table.add_row("Scored Nodes", str(overview.scored_nodes)) - table.add_row("Average Quality", f"{overview.avg_quality:.3f}") - table.add_row("Gaps Detected", str(overview.gap_count)) - for bucket, count in sorted(overview.quality_distribution.items()): - table.add_row(f" {bucket}", str(count)) - console.print(table) - - # Gaps table - if overview.gaps: - console.print() - gap_table = Table(title=f"Top {len(overview.gaps)} Gaps (quality < {threshold})") - gap_table.add_column("Node", style="cyan", max_width=60) - gap_table.add_column("Kind", style="yellow") - gap_table.add_column("Score", style="red") - gap_table.add_column("Reason", style="dim") - for gap in overview.gaps: - gap_table.add_row( - gap.node_id, gap.node_kind, - f"{gap.quality_score:.3f}", gap.reason, - ) - console.print(gap_table) - else: - console.print("[green]No gaps detected — graph looks healthy![/]") - finally: - container.close() - - -# ------------------------------------------------------------------ -# serve (MCP) -# ------------------------------------------------------------------ - -@app.command() -def serve( - http: bool = typer.Option(False, "--http", help="Start as shared HTTP server (for team access)"), - http_port: int = typer.Option(8421, "--http-port", help="Port for the HTTP server (only with --http)"), - http_host: str = typer.Option("0.0.0.0", "--http-host", help="Host to bind the HTTP server to"), - remote: Optional[str] = typer.Option(None, "--remote", "-r", help="URL of a remote Mimir HTTP server to proxy (e.g. http://team-server:8421)"), - watch: bool = typer.Option(False, "--watch", help="Enable file watcher for live re-indexing (heuristic summaries only, no LLM)"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Start the MCP server. - - Three modes: - - \b - mimir serve stdio MCP (default, for local IDE) - mimir serve --http shared HTTP server (team runs this) - mimir serve --remote proxy to a remote shared server (IDE connects here) - """ - # Validate mutual exclusivity - if http and remote: - console.print("[red bold]Error:[/] --http and --remote are mutually exclusive.") - raise typer.Exit(1) - - # Force logging to stderr so stdout is strictly for JSON-RPC - level = logging.DEBUG if verbose else logging.INFO - logging.basicConfig( - level=level, - format="%(asctime)s %(levelname)-8s %(name)s — %(message)s", - datefmt="%H:%M:%S", - stream=sys.stderr, - ) - - err_console = Console(stderr=True) - - if remote: - # Remote proxy mode — no config/workspace needed - err_console.print(f"[green]Connecting to remote Mimir server at {remote}[/]") - from mimir.adapters.remote_mcp import run_remote_mcp - run_remote_mcp(remote) - elif http: - # Shared HTTP server mode - cfg, ws_name = _load_config(config, workspace) - if watch: - cfg.watcher = _enable_watcher(cfg.watcher) - err_console.print( - f"[green]Starting shared Mimir HTTP server on http://{http_host}:{http_port}[/]", - ) - err_console.print( - f"[dim]Mobile/frontend devs connect with: mimir serve --remote http://:{http_port}[/]", - ) - from mimir.adapters.http_server import run_http_server - run_http_server(cfg, host=http_host, port=http_port, workspace_name=ws_name) - else: - # Default stdio MCP mode - cfg, ws_name = _load_config(config, workspace) - if watch: - cfg.watcher = _enable_watcher(cfg.watcher) - from mimir.adapters.mcp_server import run_mcp_server - run_mcp_server(cfg, workspace_name=ws_name) - - -# ------------------------------------------------------------------ -# ui -# ------------------------------------------------------------------ - -@app.command() -def ui( - port: int = typer.Option(8420, "--port", "-p", help="HTTP port"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Launch the web inspector UI.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.adapters.web.server import run_web_server - console.print(f"[green]Starting Mimir Inspector at http://localhost:{port}[/]") - run_web_server(cfg, port=port) - - -# ------------------------------------------------------------------ -# clear -# ------------------------------------------------------------------ - -@app.command() -def clear( - graph: bool = typer.Option(True, help="Clear the code graph and embeddings"), - sessions: bool = typer.Option(True, help="Clear all conversation sessions"), - yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation prompt"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Delete locally stored index data.""" - _setup_logging(verbose) - - targets: list[str] = [] - if graph: - targets.append("code graph + embeddings") - if sessions: - targets.append("sessions") - - if not targets: - console.print("[yellow]Nothing to clear — use --graph and/or --sessions[/]") - raise typer.Exit(0) - - if not yes: - console.print(f"[red bold]This will permanently delete:[/] {', '.join(targets)}") - confirmed = typer.confirm("Continue?") - if not confirmed: - console.print("[yellow]Aborted[/]") - raise typer.Exit(0) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - result = container.clear_data(graph=graph, sessions=sessions) - console.print(f"[green]✓ Cleared:[/] {', '.join(result['cleared'])}") - except Exception as exc: - console.print(f"[red bold]Clear failed:[/] {exc}") - raise typer.Exit(1) from exc - finally: - container.close() - - - -# ------------------------------------------------------------------ -# vacuum -# ------------------------------------------------------------------ - -@app.command() -def vacuum( - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Compact the SQLite graph database to reclaim unused file space.""" - _setup_logging(verbose) - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - try: - container.graph_store.vacuum() - console.print("[green]✓ Database vacuumed successfully[/]") - except Exception as exc: - console.print(f"[red bold]Vacuum failed:[/] {exc}") - raise typer.Exit(1) from exc - finally: - container.close() - - -# ------------------------------------------------------------------ -# ask -# ------------------------------------------------------------------ - -@app.command() -def ask( - query: str = typer.Argument(..., help="Natural language query"), - budget: int = typer.Option(8000, "--budget", "-b", help="Token budget"), - repos: Optional[str] = typer.Option(None, "--repos", "-r", help="Comma-separated repo filter"), - flat: bool = typer.Option(False, "--flat", help="Force flat search"), - workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), - config: Path = typer.Option(_DEFAULT_CONFIG, "--config", "-c", help="Config file path"), - verbose: bool = typer.Option(False, "--verbose", "-v"), -) -> None: - """Interactive semantic search CLI — retrieves context and answers via LLM.""" - _setup_logging(verbose) - - cfg, _ = _load_config(config, workspace) - from mimir.container import Container - container = Container(cfg) - - if not container.llm_client: - console.print("[red bold]Error:[/] LLM Client not configured. Add an [llm] section to mimir.toml.") - raise typer.Exit(1) - - try: - repo_list = [r.strip() for r in repos.split(",")] if repos else None - graph = container.load_graph() - - bundle = asyncio.run(container.retrieval.search( - query=query, - graph=graph, - token_budget=budget, - beam_width=cfg.retrieval.default_beam_width, - repos=repo_list, - flat=flat, - )) - - context = bundle.format_for_llm() - prompt = f"Context:\n{context}\n\nQuestion:\n{query}" - - from rich.markdown import Markdown - from rich.panel import Panel - - console.print(Panel( - f"Assembling context from [cyan]{len(bundle.nodes)} nodes[/] across [cyan]{len(bundle.repos_involved)} repos[/]...", - title="Mimir Semantic Search", - border_style="blue", - )) - - response = asyncio.run(container.llm_client.complete(prompt)) - - console.print("\n") - console.print(Markdown(response)) - console.print("\n") - console.print(f"[dim]Sources referenced: {', '.join({n.repo + '/' + (n.path or '') for n in bundle.nodes})}[/]") - - except Exception as exc: - console.print(f"[red bold]Search failed:[/] {exc}") - raise typer.Exit(1) from exc - finally: - container.close() - - -# ------------------------------------------------------------------ -# init -# ------------------------------------------------------------------ - -@app.command() -def init( - path: Path = typer.Option(Path("."), "--path", help="Directory to initialise"), -) -> None: - """Create a mimir.toml configuration file.""" - config_path = path / "mimir.toml" - if config_path.exists(): - console.print(f"[yellow]Config already exists: {config_path}[/]") - raise typer.Exit(0) - - template = '''# Mimir v1 Configuration - -[[repos]] -name = "my-project" -path = "." -language_hint = "python" - -[indexing] -summary_mode = "heuristic" -excluded_patterns = ["__pycache__", "node_modules", ".git", "venv", ".venv"] -max_file_size_kb = 500 - -[embeddings] -model = "local:all-MiniLM-L6-v2" - -[vector_db] -backend = "chroma" - -[retrieval] -default_beam_width = 3 -default_token_budget = 8000 -expansion_hops = 2 - -[temporal] -recency_lambda = 0.02 -co_retrieval_enabled = true -''' - config_path.write_text(template) - console.print(f"[green]✓ Created {config_path}[/]") - console.print(" Edit the [[repos]] section to point to your code repositories.") +__all__ = ["app"] if __name__ == "__main__": diff --git a/mimir/adapters/cli_support/__init__.py b/mimir/adapters/cli_support/__init__.py new file mode 100644 index 0000000..edee32e --- /dev/null +++ b/mimir/adapters/cli_support/__init__.py @@ -0,0 +1,5 @@ +"""CLI adapter support package.""" + +from mimir.adapters.cli_support.app import app + +__all__ = ["app"] diff --git a/mimir/adapters/cli_support/app.py b/mimir/adapters/cli_support/app.py new file mode 100644 index 0000000..53ada5c --- /dev/null +++ b/mimir/adapters/cli_support/app.py @@ -0,0 +1,59 @@ +"""CLI application bootstrap.""" + +from __future__ import annotations + +from pathlib import Path + +import typer + +from mimir.adapters.cli_support.common import console +from mimir.adapters.cli_support.commands.guardrail import guardrail_app +from mimir.adapters.cli_support.commands.indexer import indexer_app +from mimir.adapters.cli_support.commands.query import query_app +from mimir.adapters.cli_support.commands.workspace import workspace_app + +app = typer.Typer( + name="mimir", + help="Mimir — Context Server v1 — Context Engine for Large-Scale Codebases", + no_args_is_help=True, +) + +app.add_typer(workspace_app, name="workspace") +app.add_typer(guardrail_app, name="guardrail") +app.add_typer(indexer_app, name="indexer") +app.add_typer(query_app, name="query") + + +@app.command() +def init( + path: Path = typer.Option(Path("."), "--path", help="Directory to initialise"), +) -> None: + """Create a mimir.toml configuration file.""" + config_path = path / "mimir.toml" + if config_path.exists(): + console.print(f"[yellow]Config already exists: {config_path}[/]") + raise typer.Exit(0) + + template = '''# Mimir v1 Configuration + +[[repos]] +name = "my-project" +path = "." +language_hint = "python" + +[indexing] +summary_mode = "heuristic" +excluded_patterns = ["__pycache__", "node_modules", ".git", "venv", ".venv"] +max_file_size_kb = 500 + +[embeddings] +model = "local:all-MiniLM-L6-v2" + +[retrieval] +default_beam_width = 3 +default_token_budget = 8000 +expansion_hops = 2 +''' + config_path.write_text(template) + console.print(f"[green]Created {config_path}[/]") + console.print(" Edit the [[repos]] section to point to your code repositories.") diff --git a/mimir/adapters/cli_support/commands/__init__.py b/mimir/adapters/cli_support/commands/__init__.py new file mode 100644 index 0000000..cb5739a --- /dev/null +++ b/mimir/adapters/cli_support/commands/__init__.py @@ -0,0 +1 @@ +"""CLI command groups.""" diff --git a/mimir/adapters/cli_support/commands/guardrail.py b/mimir/adapters/cli_support/commands/guardrail.py new file mode 100644 index 0000000..205f217 --- /dev/null +++ b/mimir/adapters/cli_support/commands/guardrail.py @@ -0,0 +1,241 @@ +"""Guardrail-related CLI commands.""" + +from __future__ import annotations + +import asyncio +import json +import subprocess +import sys +from pathlib import Path +from typing import Optional + +import typer + +from mimir.adapters.cli_support.common import DEFAULT_CONFIG, console, load_config, setup_logging + +guardrail_app = typer.Typer( + name="guardrail", + help="Architectural guardrails — validate changes against structural rules.", + no_args_is_help=True, +) + + +def git_auto_diff(base: str = "") -> str: + """Auto-detect a diff from git.""" + + def run_git(*args: str) -> str: + try: + return subprocess.check_output(["git", *args], text=True, stderr=subprocess.DEVNULL) + except Exception: + return "" + + staged = run_git("diff", "--cached") + if staged.strip(): + console.print("[dim]Using staged changes (git diff --cached)[/dim]") + return staged + + unstaged = run_git("diff") + if unstaged.strip(): + console.print("[dim]Using unstaged changes (git diff)[/dim]") + return unstaged + + if not base: + for candidate in ("main", "master", "develop"): + if run_git("rev-parse", "--verify", f"refs/heads/{candidate}").strip(): + base = candidate + break + if not base: + base = "HEAD~1" + + branch_diff = run_git("diff", f"{base}...HEAD") + if branch_diff.strip(): + console.print(f"[dim]Using branch diff ({base}...HEAD)[/dim]") + return branch_diff + return "" + + +@guardrail_app.command("check") +def guardrail_check( + diff: str = typer.Option("", "--diff", "-d", help="Path to diff file, '-' for stdin, or empty for auto-detect from git"), + base: str = typer.Option("", "--base", "-b", help="Base ref for git diff (e.g. main, origin/main). Default: auto-detect"), + rules: Path = typer.Option(Path("mimir-rules.yaml"), "--rules", "-r", help="Path to rules YAML file"), + output: str = typer.Option("text", "--output", "-o", help="Output format: text, json, github-pr-comment"), + report_file: Optional[Path] = typer.Option(None, "--report-file", help="Write the formatted report to a file (in addition to stdout)"), + no_approvals: bool = typer.Option(False, "--no-approvals", help="Ignore HEAD commit trailers (show raw BLOCK violations)"), + head: str = typer.Option( + "HEAD", "--head", + help="Git ref whose commit message is scanned for Mimir-Approved trailers.", + ), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Validate a diff against architectural rules.""" + setup_logging(verbose) + + from mimir.domain.guardrails_config import load_rules + from mimir.services.guardrail import apply_approvals + from mimir.services.guardrail.report import GuardrailReporter + from mimir.services.guardrail.trailers import read_head_approval + from mimir.domain.errors import NoActiveIndexError + from mimir.runtime import RuntimeFactory + + try: + rule_list = load_rules(rules) + except Exception as exc: + console.print(f"[red bold]Rule loading error:[/] {exc}") + raise typer.Exit(1) from exc + + if diff == "-": + diff_text = sys.stdin.read() + elif diff: + diff_path = Path(diff) + if not diff_path.exists(): + console.print(f"[red bold]Diff file not found:[/] {diff}") + raise typer.Exit(1) + diff_text = diff_path.read_text() + else: + diff_text = git_auto_diff(base) + + if not diff_text.strip(): + console.print("[yellow]Empty diff — nothing to check.[/]") + raise typer.Exit(0) + + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).query() + try: + graph = runtime.require_graph() + result = asyncio.run(runtime.guardrail.evaluate(graph, diff_text, rule_list)) + + if not no_approvals and any(v.severity.value == "block" for v in result.violations): + head_approval = read_head_approval(head) + result = apply_approvals( + result, + approved_rule_ids=head_approval.rule_ids if head_approval else frozenset(), + reason=head_approval.reason if head_approval else "", + ) + + reporter = GuardrailReporter() + if output == "json": + formatted = json.dumps(result.to_dict(), indent=2) + console.print_json(formatted) + elif output == "github-pr-comment": + formatted = reporter.format_github_pr_comment(result) + console.print(formatted) + else: + formatted = reporter.format_text(result) + console.print(formatted) + + if report_file: + report_file.parent.mkdir(parents=True, exist_ok=True) + report_file.write_text(formatted + "\n", encoding="utf-8") + + if not result.passed: + raise typer.Exit(1) + except NoActiveIndexError as exc: + console.print(f"[red bold]{exc}.[/] Run: mimir indexer run") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@guardrail_app.command("init") +def guardrail_init( + force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing files"), +) -> None: + """Generate example mimir-rules.yaml and mimir-agent-policy.yaml.""" + import shutil + + examples = { + "mimir-rules.yaml": Path(__file__).parent.parent.parent.parent.parent / "mimir-rules.yaml", + "mimir-agent-policy.yaml": Path(__file__).parent.parent.parent.parent.parent / "mimir-agent-policy.yaml", + } + for name, source in examples.items(): + target = Path(name) + if target.exists() and not force: + console.print(f"[yellow]Skipping {name} (already exists, use --force to overwrite)[/]") + continue + if source.exists(): + shutil.copy2(source, target) + console.print(f"[green]Created {name}[/]") + else: + console.print(f"[yellow]Template {name} not found in package[/]") + + console.print("\n[bold]Next steps:[/]") + console.print(" 1. Edit mimir-rules.yaml to match your architecture") + console.print(" 2. Run: git diff | mimir guardrail check --diff -") + + +@guardrail_app.command("test") +def guardrail_test( + rules: Path = typer.Option(Path("mimir-rules.yaml"), "--rules", "-r", help="Path to rules YAML file"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Dry-run: validate rule syntax and report current metric values.""" + setup_logging(verbose) + + from mimir.domain.guardrails_config import load_rules + from mimir.domain.errors import NoActiveIndexError + from mimir.runtime import RuntimeFactory + + try: + rule_list = load_rules(rules) + except Exception as exc: + console.print(f"[red bold]Rule loading error:[/] {exc}") + raise typer.Exit(1) from exc + + console.print(f"[green]Loaded {len(rule_list)} rules from {rules}[/]") + for rule in rule_list: + console.print(f" [{rule.severity.value}] {rule.id}: {rule.description}") + + try: + cfg, _ = load_config(config, workspace) + except Exception: + console.print("\n[yellow]No config found — skipping graph analysis.[/]") + return + + runtime = RuntimeFactory(cfg).query() + try: + graph = runtime.require_graph() + console.print(f"\n[bold]Graph:[/] {graph.node_count} nodes, {graph.edge_count} edges") + console.print("[green]Rules syntax OK. Ready for guardrail checks.[/]") + except NoActiveIndexError as exc: + console.print(f"[red bold]{exc}.[/] Run: mimir indexer run") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@guardrail_app.command("approve") +def guardrail_approve( + rule_ids: list[str] = typer.Argument(..., help="Rule IDs to approve (space-separated)"), + reason: str = typer.Option(..., "--reason", help="Reason for approving"), +) -> None: + """Approve BLOCK violations by committing an approval trailer on HEAD.""" + if not reason.strip(): + console.print("[red bold]--reason must not be empty[/]") + raise typer.Exit(1) + + ids = [rule_id.strip() for rule_id in rule_ids if rule_id.strip()] + if not ids: + console.print("[red bold]At least one rule id is required[/]") + raise typer.Exit(1) + + body = ( + f"approval: {', '.join(ids)}\n" + "\n" + f"Mimir-Approved: {', '.join(ids)}\n" + f"Mimir-Approved-Reason: {reason.strip()}\n" + ) + try: + subprocess.run(["git", "commit", "--allow-empty", "-m", body], check=True) + except subprocess.CalledProcessError as exc: + console.print(f"[red bold]git commit failed:[/] {exc}") + raise typer.Exit(1) from exc + + console.print(f"[green]Approval commit created for:[/] {', '.join(ids)}") + console.print(f" Reason: {reason}") + console.print("") + console.print("[bold]Don't forget to push:[/] git push") diff --git a/mimir/adapters/cli_support/commands/indexer.py b/mimir/adapters/cli_support/commands/indexer.py new file mode 100644 index 0000000..6cc57c1 --- /dev/null +++ b/mimir/adapters/cli_support/commands/indexer.py @@ -0,0 +1,192 @@ +"""Indexer runtime CLI commands.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Optional + +import typer + +from mimir.adapters.cli_support.common import DEFAULT_CONFIG, console, load_config, setup_logging +from mimir.domain.index_state import IndexJobKind +from mimir.runtime import RuntimeFactory + +indexer_app = typer.Typer( + name="indexer", + help="Build, publish, and maintain central Mimir indexes.", + no_args_is_help=True, +) + + +@indexer_app.command("run") +def run_index( + mode: Optional[str] = typer.Option(None, help="Summary mode: none, heuristic"), + clean: bool = typer.Option(False, "--clean", help="Force a full re-index"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Build and publish an index version.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + version = asyncio.run(runtime.run_index(clean=clean, mode_override=mode)) + console.print(f"[green]Published index version:[/] {version.version}") + console.print(f" Nodes: {version.node_count}") + console.print(f" Edges: {version.edge_count}") + console.print(f" Graph: {version.graph_path}") + except Exception as exc: + console.print(f"[red bold]Index failed:[/] {exc}") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@indexer_app.command("sync") +def sync_repo( + repo: str = typer.Argument(..., help="Configured repo name to sync and re-index"), + commit_sha: Optional[str] = typer.Option(None, "--commit-sha", help="Specific commit to check out"), + mode: Optional[str] = typer.Option(None, help="Summary mode: none, heuristic"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Mirror one repo, refresh it in the graph, and publish a new index version.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + version = asyncio.run(runtime.sync_repo(repo, commit_sha=commit_sha, mode_override=mode)) + console.print(f"[green]Published index version:[/] {version.version}") + console.print(f" Repo: {repo}") + console.print(f" Graph: {version.graph_path}") + except Exception as exc: + console.print(f"[red bold]Sync failed:[/] {exc}") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@indexer_app.command("versions") +def versions( + limit: int = typer.Option(20, "--limit", help="Maximum versions to show"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """List published index versions.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + for version in runtime.list_versions(limit=limit): + marker = "*" if version.active else " " + console.print( + f"{marker} {version.version} " + f"nodes={version.node_count} edges={version.edge_count} " + f"model={version.embedding_model or '-'} dim={version.embedding_dim or '-'}" + ) + finally: + runtime.close() + + +@indexer_app.command("activate") +def activate( + version: str = typer.Argument(..., help="Published index version to activate"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Activate a previously published index version.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + activated = runtime.activate_version(version) + console.print(f"[green]Activated index version:[/] {activated.version}") + except Exception as exc: + console.print(f"[red bold]Activate failed:[/] {exc}") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@indexer_app.command("prune") +def prune( + keep: int = typer.Option(5, "--keep", help="Newest versions to retain, active is always retained"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Delete old inactive published index versions.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + removed = runtime.prune_versions(keep=keep) + if removed: + console.print(f"[green]Pruned {len(removed)} index version(s)[/]") + for version in removed: + console.print(f" {version}") + else: + console.print("[yellow]No index versions pruned[/]") + except Exception as exc: + console.print(f"[red bold]Prune failed:[/] {exc}") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@indexer_app.command("enqueue") +def enqueue( + kind: IndexJobKind = typer.Argument(..., help="Job kind"), + repo: Optional[str] = typer.Option(None, "--repo", help="Repo name for sync jobs"), + commit_sha: Optional[str] = typer.Option(None, "--commit-sha", help="Specific commit for sync jobs"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Create a durable indexer job.""" + setup_logging(verbose) + if kind is IndexJobKind.SYNC and not repo: + console.print("[red bold]Error:[/] sync jobs require --repo") + raise typer.Exit(1) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + job = runtime.enqueue(kind, repo=repo, commit_sha=commit_sha) + console.print(f"[green]Queued index job:[/] {job.id}") + console.print(f" Kind: {job.kind.value}") + console.print(f" Status: {job.status.value}") + finally: + runtime.close() + + +@indexer_app.command("worker") +def worker( + once: bool = typer.Option(False, "--once", help="Process at most one queued job and exit"), + poll_interval: float = typer.Option(5.0, "--poll-interval", help="Idle polling interval in seconds"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c", help="Config file path"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Run the durable indexer worker.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).indexer() + try: + if once: + job = asyncio.run(runtime.worker_once()) + if job is None: + console.print("[yellow]No queued jobs[/]") + else: + console.print(f"[green]Processed job:[/] {job.id} ({job.status.value})") + else: + console.print("[green]Indexer worker running[/]") + asyncio.run(runtime.worker_loop(poll_interval=poll_interval)) + except KeyboardInterrupt: + console.print("[yellow]Worker stopped[/]") + finally: + runtime.close() diff --git a/mimir/adapters/cli_support/commands/query.py b/mimir/adapters/cli_support/commands/query.py new file mode 100644 index 0000000..5690323 --- /dev/null +++ b/mimir/adapters/cli_support/commands/query.py @@ -0,0 +1,137 @@ +"""Query runtime CLI commands.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Optional + +import typer + +from mimir.adapters.cli_support.common import ( + DEFAULT_CONFIG, + console, + load_config, + setup_logging, + setup_stdio_logging, + stderr_console, +) +from mimir.domain.errors import NoActiveIndexError +from mimir.runtime import RuntimeFactory + +query_app = typer.Typer( + name="query", + help="Serve and query published Mimir indexes.", + no_args_is_help=True, +) + + +@query_app.command() +def search( + query: str = typer.Argument(..., help="Natural language query"), + budget: int = typer.Option(8000, "--budget", "-b", help="Token budget"), + repos: Optional[str] = typer.Option(None, "--repos", "-r", help="Comma-separated repo filter"), + flat: bool = typer.Option(False, "--flat", help="Force flat search"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Search the active published index.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).query() + try: + graph = runtime.require_graph() + bundle = asyncio.run(runtime.retrieval.search( + query=query, + graph=graph, + token_budget=budget, + repos=repos.split(",") if repos else None, + flat=flat, + )) + console.print(f"\n[bold]{bundle.summary}[/]") + if bundle.session_note: + console.print(f"[dim]{bundle.session_note}[/]") + console.print(f"[dim]Tokens: {bundle.token_count}[/]\n") + console.print(bundle.format_for_llm()) + except NoActiveIndexError as exc: + console.print(f"[red bold]{exc}.[/] Run: mimir indexer run") + raise typer.Exit(1) from exc + except Exception as exc: + console.print(f"[red bold]Search failed:[/] {exc}") + raise typer.Exit(1) from exc + finally: + runtime.close() + + +@query_app.command() +def status( + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Show the active published index.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + runtime = RuntimeFactory(cfg).query() + try: + status_data = runtime.status() + console.print(f"Active version: {status_data['active_version'] or '-'}") + console.print(f"Nodes: {status_data['graph_nodes']}") + console.print(f"Edges: {status_data['graph_edges']}") + if status_data["activated_at"]: + console.print(f"Activated: {status_data['activated_at']}") + finally: + runtime.close() + + +@query_app.command() +def serve( + http: bool = typer.Option(False, "--http", help="Start query HTTP server"), + http_port: int = typer.Option(8421, "--http-port", help="Port for the HTTP server"), + http_host: str = typer.Option("0.0.0.0", "--http-host", help="Host to bind"), + remote: Optional[str] = typer.Option(None, "--remote", "-r", help="URL of a remote Mimir HTTP server to proxy"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Start query serving locally or proxy to a remote query server.""" + if http and remote: + console.print("[red bold]Error:[/] --http and --remote are mutually exclusive.") + raise typer.Exit(1) + + setup_stdio_logging(verbose) + if remote: + stderr_console.print(f"[green]Connecting to remote Mimir server at {remote}[/]") + from mimir.adapters.mcp.remote import run_remote_mcp + + run_remote_mcp(remote) + return + + cfg, workspace_name = load_config(config, workspace) + if http: + stderr_console.print(f"[green]Starting Mimir query HTTP server on http://{http_host}:{http_port}[/]") + from mimir.adapters.http import run_http_server + + run_http_server(cfg, host=http_host, port=http_port, workspace_name=workspace_name) + return + + from mimir.adapters.mcp.server import run_mcp_server + + run_mcp_server(cfg, workspace_name=workspace_name) + + +@query_app.command() +def ui( + port: int = typer.Option(8420, "--port", "-p", help="HTTP port"), + workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Named workspace from registry"), + config: Path = typer.Option(DEFAULT_CONFIG, "--config", "-c"), + verbose: bool = typer.Option(False, "--verbose", "-v"), +) -> None: + """Launch the read-only web inspector over the active index.""" + setup_logging(verbose) + cfg, _ = load_config(config, workspace) + from mimir.adapters.web.server import run_web_server + + console.print(f"[green]Starting Mimir Inspector at http://localhost:{port}[/]") + run_web_server(cfg, port=port) diff --git a/mimir/adapters/cli_support/commands/workspace.py b/mimir/adapters/cli_support/commands/workspace.py new file mode 100644 index 0000000..10e37b6 --- /dev/null +++ b/mimir/adapters/cli_support/commands/workspace.py @@ -0,0 +1,78 @@ +"""Workspace management CLI commands.""" + +from __future__ import annotations + +from pathlib import Path + +import typer + +from mimir.adapters.cli_support.common import DEFAULT_CONFIG, console +from mimir.domain.config import ConfigError + +workspace_app = typer.Typer( + name="workspace", + help="Manage named Mimir workspaces (~/.mimir/workspaces.toml).", + no_args_is_help=True, +) + + +@workspace_app.command("add") +def workspace_add( + name: str = typer.Argument(..., help="Workspace name (letters, digits, hyphens, underscores)"), + config: Path = typer.Option( + DEFAULT_CONFIG, "--config", "-c", + help="Path to mimir.toml (default: ./mimir.toml)", + ), +) -> None: + """Register a workspace in the global registry.""" + from mimir.domain.workspace import WorkspaceRegistry + + registry = WorkspaceRegistry() + try: + registry.add(name, config) + console.print(f"[green]✓ Registered workspace:[/] {name} → {config.resolve()}") + console.print(f" Registry: {registry._path}") + except ConfigError as exc: + console.print(f"[red bold]Error:[/] {exc}") + raise typer.Exit(1) from exc + + +@workspace_app.command("list") +def workspace_list() -> None: + """List all registered workspaces.""" + from rich.table import Table + from mimir.domain.workspace import WorkspaceRegistry + + registry = WorkspaceRegistry() + workspaces = registry.list() + if not workspaces: + console.print("[yellow]No workspaces registered.[/] Use [bold]mimir workspace add[/] to register one.") + return + + table = Table(title=f"Registered Workspaces ({registry._path})") + table.add_column("Name", style="cyan bold") + table.add_column("Config Path", style="green") + table.add_column("Exists?", style="yellow") + for name, path in sorted(workspaces.items()): + table.add_row(name, str(path), "✓" if path.is_file() else "✗ missing") + console.print(table) + + +@workspace_app.command("remove") +def workspace_remove( + name: str = typer.Argument(..., help="Workspace name to remove"), + yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), +) -> None: + """Unregister a workspace from the global registry.""" + from mimir.domain.workspace import WorkspaceRegistry + + registry = WorkspaceRegistry() + if not yes and not typer.confirm(f"Remove workspace '{name}' from registry?"): + console.print("[yellow]Aborted[/]") + raise typer.Exit(0) + try: + registry.remove(name) + console.print(f"[green]✓ Removed workspace:[/] {name}") + except ConfigError as exc: + console.print(f"[red bold]Error:[/] {exc}") + raise typer.Exit(1) from exc diff --git a/mimir/adapters/cli_support/common.py b/mimir/adapters/cli_support/common.py new file mode 100644 index 0000000..74acb0e --- /dev/null +++ b/mimir/adapters/cli_support/common.py @@ -0,0 +1,87 @@ +"""Shared CLI adapter helpers.""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path +from typing import Optional + +import typer +from rich.console import Console + +from mimir.domain.config import ConfigError, MimirConfig + +console = Console() +stderr_console = Console(stderr=True) + +DEFAULT_CONFIG = Path("mimir.toml") + + +def resolve_config_path( + config: Path, + workspace: Optional[str] = None, +) -> tuple[Path, Optional[str]]: + """Resolve the config path and workspace name, enforcing mutual exclusivity.""" + resolved_workspace = workspace or os.environ.get("MIMIR_WORKSPACE") or None + explicit_config = config != DEFAULT_CONFIG + + if resolved_workspace and explicit_config: + stderr_console.print( + "[red bold]Error:[/] --workspace and --config are mutually exclusive. " + "Use one or the other." + ) + raise typer.Exit(1) + + if resolved_workspace: + from mimir.domain.workspace import WorkspaceRegistry + + try: + registry = WorkspaceRegistry() + config_path = registry.resolve(resolved_workspace) + except ConfigError as exc: + stderr_console.print(f"[red bold]Workspace error:[/] {exc}") + raise typer.Exit(1) from exc + return config_path, resolved_workspace + + return config, None + + +def load_config( + config: Path, + workspace: Optional[str] = None, +) -> tuple[MimirConfig, Optional[str]]: + """Load and validate config with user-friendly error messages.""" + config_path, workspace_name = resolve_config_path(config, workspace) + try: + return MimirConfig.load(config_path), workspace_name + except ConfigError as exc: + stderr_console.print(f"[red bold]Config error:[/] {exc}") + raise typer.Exit(1) from exc + + +def setup_logging(verbose: bool) -> None: + """Configure Rich logging for standard CLI commands.""" + from rich.logging import RichHandler + + level = logging.DEBUG if verbose else logging.INFO + handler = RichHandler(rich_tracebacks=True, console=console, markup=False, show_path=False) + handler.setFormatter(logging.Formatter("%(name)s — %(message)s", datefmt="[%X]")) + root = logging.getLogger() + root.setLevel(level) + root.handlers.clear() + root.addHandler(handler) + logging.getLogger("aiohttp.access").setLevel(logging.ERROR) + + +def setup_stdio_logging(verbose: bool) -> None: + """Force logging to stderr so stdout is reserved for JSON-RPC.""" + import sys + + level = logging.DEBUG if verbose else logging.INFO + logging.basicConfig( + level=level, + format="%(asctime)s %(levelname)-8s %(name)s — %(message)s", + datefmt="%H:%M:%S", + stream=sys.stderr, + ) diff --git a/mimir/adapters/http/__init__.py b/mimir/adapters/http/__init__.py new file mode 100644 index 0000000..c4484b8 --- /dev/null +++ b/mimir/adapters/http/__init__.py @@ -0,0 +1,5 @@ +"""HTTP server adapter package.""" + +from mimir.adapters.http.app import run_http_server + +__all__ = ["run_http_server"] diff --git a/mimir/adapters/http/admin_auth.py b/mimir/adapters/http/admin_auth.py new file mode 100644 index 0000000..f22033a --- /dev/null +++ b/mimir/adapters/http/admin_auth.py @@ -0,0 +1,46 @@ +"""Admin endpoint authentication helpers.""" + +from __future__ import annotations + +import hmac +import os + +from aiohttp import web + +from mimir.domain.config import MimirConfig + + +def require_admin_token(request: web.Request, config: MimirConfig) -> None: + """Enforce bearer-token auth for admin-only HTTP endpoints.""" + expected = _resolve_admin_token(config) + if not expected: + raise web.HTTPServiceUnavailable( + text='{"error":"Admin authentication is not configured"}', + content_type="application/json", + ) + + provided = _extract_token(request) + if not provided or not hmac.compare_digest(provided, expected): + raise web.HTTPUnauthorized( + text='{"error":"Invalid admin token"}', + content_type="application/json", + ) + + +def _resolve_admin_token(config: MimirConfig) -> str | None: + for env_name in (config.admin.admin_token_env, config.admin.webhook_secret_env): + if not env_name: + continue + value = os.environ.get(env_name) + if value: + return value + return None + + +def _extract_token(request: web.Request) -> str | None: + header = request.headers.get("Authorization", "").strip() + if header.lower().startswith("bearer "): + token = header[7:].strip() + return token or None + token = request.headers.get("X-Mimir-Admin-Token", "").strip() + return token or None diff --git a/mimir/adapters/http/app.py b/mimir/adapters/http/app.py new file mode 100644 index 0000000..2babc53 --- /dev/null +++ b/mimir/adapters/http/app.py @@ -0,0 +1,81 @@ +"""HTTP server bootstrap.""" + +from __future__ import annotations + +import logging + +from aiohttp import web + +from mimir.domain.config import MimirConfig +from mimir.runtime import RuntimeFactory + +from .routes_api import register_api_routes +from .routes_mcp import register_mcp_routes +from .state import HttpServerState + +logger = logging.getLogger(__name__) + + +def run_http_server( + config: MimirConfig, + host: str = "0.0.0.0", + port: int = 8421, + workspace_name: str | None = None, +) -> None: + runtime = RuntimeFactory(config).query() + state = HttpServerState( + runtime=runtime, + workspace_name=workspace_name or "default", + ) + + logger.info( + "HTTP server starting — workspace=%s, host=%s, port=%d, graph=%d nodes", + state.workspace_name, + host, + port, + state.current_graph().node_count, + ) + + app = _build_app(state) + + logger.info("Mimir query HTTP server listening on http://%s:%d", host, port) + web.run_app(app, host=host, port=port, print=lambda _: None, access_log=None) + + +def _build_app(state: HttpServerState) -> web.Application: + routes = web.RouteTableDef() + register_api_routes(routes, state) + register_mcp_routes(routes, state) + + app = web.Application(middlewares=[_cors_middleware]) + app.router.add_routes(routes) + app.on_startup.append(_startup_factory(state)) + app.on_cleanup.append(_cleanup_factory(state)) + return app + + +def _startup_factory(state: HttpServerState): + async def on_startup(app: web.Application) -> None: + state.runtime.start_polling() + + return on_startup + + +def _cleanup_factory(state: HttpServerState): + async def on_cleanup(app: web.Application) -> None: + await state.runtime.stop_polling() + state.runtime.close() + + return on_cleanup + + +@web.middleware +async def _cors_middleware(request: web.Request, handler): + if request.method == "OPTIONS": + response = web.Response(status=200) + else: + response = await handler(request) + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS" + response.headers["Access-Control-Allow-Headers"] = "Content-Type" + return response diff --git a/mimir/adapters/http/routes_api.py b/mimir/adapters/http/routes_api.py new file mode 100644 index 0000000..2ca4701 --- /dev/null +++ b/mimir/adapters/http/routes_api.py @@ -0,0 +1,278 @@ +"""Primary HTTP JSON endpoints.""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from aiohttp import web + +from mimir.adapters.shared.session_context import apply_session_context +from mimir.adapters.http.state import HttpServerState +from mimir.domain.errors import NoActiveIndexError +from mimir.domain.feedback import FeedbackOutcome +from mimir.domain.guardrails_config import load_rules + +logger = logging.getLogger(__name__) + + +def no_active_index_response() -> web.Response: + return web.json_response( + {"error": "No active index", "hint": "Run `mimir indexer run` first."}, + status=503, + ) + + +def register_api_routes(routes: web.RouteTableDef, state: HttpServerState) -> None: + @routes.get("/api/v1/health") + async def health(request: web.Request) -> web.Response: + graph = state.current_graph() + return web.json_response({ + "status": "ok", + "workspace": state.workspace_name, + "active_version": state.runtime.active_version.version if state.runtime.active_version else None, + "graph_nodes": graph.node_count, + "graph_edges": graph.edge_count, + }) + + @routes.get("/api/v1/index/status") + async def index_status(request: web.Request) -> web.Response: + status = state.runtime.status() + status["workspace"] = state.workspace_name + return web.json_response(status) + + @routes.post("/api/v1/context") + async def api_context(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + + query = body.get("query") + if not query: + return web.json_response({"error": "Missing 'query' field"}, status=400) + + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + try: + bundle = await state.runtime.retrieval.search( + query=query, + graph=graph, + token_budget=body.get("budget"), + repos=body.get("repos"), + ) + apply_session_context( + state.runtime, + bundle, + query=query, + session_id=body.get("session_id"), + budget=body.get("budget"), + ) + return web.json_response({ + "summary": bundle.summary, + "token_count": bundle.token_count, + "repos": bundle.repos_involved, + "session_note": bundle.session_note, + "formatted": bundle.format_for_llm(), + "nodes": [n.to_dict() for n in bundle.nodes], + }) + except Exception as exc: + logger.error("Context query failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.get("/api/v1/stats") + async def api_stats(request: web.Request) -> web.Response: + try: + stats = state.runtime.require_graph().stats() + except NoActiveIndexError: + return no_active_index_response() + stats["workspace"] = state.workspace_name + return web.json_response(stats) + + @routes.get("/api/v1/hotspots") + async def api_hotspots(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + top_n = int(request.query.get("top", "20")) + results = state.runtime.temporal.get_hotspots(graph, top_n=top_n) + return web.json_response([ + {"node": n.id, "score": round(s, 4), "changes": n.modification_count} + for n, s in results + ]) + + @routes.post("/api/v1/write_context") + async def api_write_context(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + file_path = body.get("file_path") + if not file_path: + return web.json_response({"error": "Missing 'file_path' field"}, status=400) + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + bundle = state.runtime.write_context.assemble(file_path=file_path, graph=graph) + return web.json_response({"formatted": bundle.format_for_llm()}) + + @routes.post("/api/v1/impact") + async def api_impact(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + result = state.runtime.impact.analyze( + graph, + node_id=body.get("node_id"), + file_path=body.get("file_path"), + symbol_name=body.get("symbol_name"), + max_hops=body.get("max_hops", 3), + ) + if result is None: + return web.json_response({"error": "No matching symbol or file found"}, status=404) + return web.json_response({"formatted": result.format_for_llm()}) + + @routes.get("/api/v1/quality") + async def api_quality(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + repos_param = request.query.get("repos") + overview = state.runtime.quality.detect_gaps( + graph, + repos=repos_param.split(",") if repos_param else None, + threshold=float(request.query.get("threshold", "0.3")), + top_n=int(request.query.get("top_n", "50")), + ) + return web.json_response(overview.to_dict()) + + @routes.get("/api/v1/catalog") + async def api_catalog(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + try: + repos_param = request.query.get("repos") + response = state.runtime.catalog.generate_catalog( + graph, + repos=repos_param.split(",") if repos_param else None, + ) + return web.json_response(response.to_dict()) + except Exception as exc: + logger.error("Catalog generation failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.get("/api/v1/catalog/{repo}") + async def api_catalog_service(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + repo = request.match_info["repo"] + try: + response = state.runtime.catalog.generate_catalog(graph, repos=[repo]) + if not response.services: + return web.json_response({"error": f"Repo '{repo}' not found in graph"}, status=404) + return web.json_response(response.services[0].to_dict()) + except Exception as exc: + logger.error("Catalog single-service failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.post("/api/v1/catalog/drift") + async def api_catalog_drift(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + + repo = body.get("repo") + if not repo: + return web.json_response({"error": "Missing 'repo' field"}, status=400) + + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + try: + report = state.runtime.catalog.detect_drift( + graph, + repo, + body.get("declared_dependencies", []), + ) + return web.json_response(report.to_dict()) + except Exception as exc: + logger.error("Drift detection failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.post("/api/v1/guardrails/check") + async def api_guardrails_check(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + diff = body.get("diff") + if not diff: + return web.json_response({"error": "Missing 'diff' field"}, status=400) + try: + graph = state.runtime.require_graph() + rules = load_rules(Path(body.get("rules_path", "mimir-rules.yaml"))) + result = await state.runtime.guardrail.evaluate(graph, diff, rules) + return web.json_response(result.to_dict()) + except NoActiveIndexError: + return no_active_index_response() + except Exception as exc: + logger.error("Guardrail check failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.post("/api/v1/feedback") + async def api_feedback(request: web.Request) -> web.Response: + try: + body = await request.json() + except Exception: + return web.json_response({"error": "Invalid JSON body"}, status=400) + + node_ids = body.get("node_ids") + outcome_raw = body.get("outcome") + try: + outcome = FeedbackOutcome(outcome_raw) if outcome_raw else None + except ValueError: + outcome = None + if not node_ids or outcome is None: + return web.json_response( + {"error": "Missing 'node_ids' (list) or invalid 'outcome' (positive|negative)"}, + status=400, + ) + + try: + signal = state.runtime.feedback.record_explicit( + node_ids=node_ids, + outcome=outcome, + session_id=body.get("session_id"), + query=body.get("query"), + ) + return web.json_response(signal.to_dict()) + except Exception as exc: + logger.error("Feedback recording failed: %s", exc, exc_info=True) + return web.json_response({"error": str(exc)}, status=500) + + @routes.get("/api/v1/feedback/stats") + async def api_feedback_stats(request: web.Request) -> web.Response: + node_id = request.query.get("node_id") + if not node_id: + return web.json_response({"error": "Missing 'node_id' query param"}, status=400) + + score = state.runtime.feedback.get_node_score(node_id) + if score is None: + return web.json_response({"node_id": node_id, "score": 0.5, "status": "no_data"}) + return web.json_response(score.to_dict()) diff --git a/mimir/adapters/http/routes_mcp.py b/mimir/adapters/http/routes_mcp.py new file mode 100644 index 0000000..28eb24e --- /dev/null +++ b/mimir/adapters/http/routes_mcp.py @@ -0,0 +1,159 @@ +"""MCP-over-HTTP routes.""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path + +from aiohttp import web + +from mimir.adapters.http.state import HttpServerState +from mimir.adapters.http.tooling import rpc_error, rpc_ok, tool_definitions +from mimir.adapters.shared.session_context import apply_session_context +from mimir.domain.errors import NoActiveIndexError +from mimir.domain.guardrails_config import load_agent_policy, load_rules +from mimir.services.agent_policy import AgentPolicy + +logger = logging.getLogger(__name__) + + +def register_mcp_routes(routes: web.RouteTableDef, state: HttpServerState) -> None: + @routes.post("/api/v1/mcp") + async def mcp_passthrough(request: web.Request) -> web.Response: + try: + rpc_request = await request.json() + except Exception: + return web.json_response(rpc_error(None, -32700, "Parse error"), status=400) + + method = rpc_request.get("method", "") + params = rpc_request.get("params", {}) + request_id = rpc_request.get("id") + + try: + if method == "initialize": + return web.json_response(rpc_ok(request_id, { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": { + "name": "mimir", + "version": "1.0.0", + "workspace": state.workspace_name, + "transport": "http", + }, + })) + if method == "tools/list": + return web.json_response(rpc_ok(request_id, {"tools": tool_definitions()})) + if method == "notifications/initialized": + return web.json_response({}) + if method != "tools/call": + return web.json_response(rpc_error(request_id, -32601, f"Unknown method: {method}")) + + tool_name = params.get("name") + tool_args = params.get("arguments", {}) + return await _handle_tool_call(state, request_id, tool_name, tool_args) + except Exception as exc: + logger.error("MCP-over-HTTP error: %s", exc, exc_info=True) + return web.json_response(rpc_error(request_id, -32000, str(exc))) + + +async def _handle_tool_call( + state: HttpServerState, + request_id, + tool_name: str | None, + tool_args: dict, +) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return web.json_response( + rpc_error(request_id, -32000, "No active index. Run: mimir indexer run"), + status=503, + ) + if tool_name == "get_context": + bundle = await state.runtime.retrieval.search( + query=tool_args["query"], + graph=graph, + token_budget=tool_args.get("budget"), + repos=tool_args.get("repos"), + ) + apply_session_context( + state.runtime, + bundle, + query=tool_args["query"], + session_id=tool_args.get("session_id"), + budget=tool_args.get("budget"), + ) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": bundle.format_for_llm()}]})) + + if tool_name == "get_graph_stats": + stats = graph.stats() + stats["workspace"] = state.workspace_name + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": json.dumps(stats, indent=2)}]})) + + if tool_name == "get_hotspots": + results = state.runtime.temporal.get_hotspots(graph, top_n=tool_args.get("top_n", 20)) + hotspots = [{"node": node.id, "score": f"{score:.3f}", "changes": node.modification_count} for node, score in results] + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": json.dumps(hotspots, indent=2)}]})) + + if tool_name == "get_write_context": + write_context = state.runtime.write_context.assemble(file_path=tool_args["file_path"], graph=graph) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": write_context.format_for_llm()}]})) + + if tool_name == "get_impact": + result = state.runtime.impact.analyze( + graph, + node_id=tool_args.get("node_id"), + file_path=tool_args.get("file_path"), + symbol_name=tool_args.get("symbol_name"), + max_hops=tool_args.get("max_hops", 3), + ) + text = "No matching symbol or file found for impact analysis." if result is None else result.format_for_llm() + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": text}]})) + + if tool_name == "get_quality": + overview = state.runtime.quality.detect_gaps( + graph, + repos=tool_args.get("repos"), + threshold=tool_args.get("threshold"), + top_n=tool_args.get("top_n", 50), + ) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": overview.format_for_llm()}]})) + + if tool_name == "get_catalog": + response = state.runtime.catalog.generate_catalog(graph, repos=tool_args.get("repos")) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": response.format_for_llm()}]})) + + if tool_name == "get_catalog_drift": + report = state.runtime.catalog.detect_drift( + graph, + repo=tool_args["repo"], + declared_deps=tool_args.get("declared_dependencies", []), + ) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": report.format_for_llm()}]})) + + if tool_name == "validate_change": + rules = load_rules(Path(tool_args.get("rules_path", "mimir-rules.yaml"))) + result = await state.runtime.guardrail.evaluate(graph, tool_args["diff"], rules) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": result.format_for_llm()}]})) + + if tool_name == "can_i_modify": + policy_path = Path(tool_args.get("policy_path", "mimir-agent-policy.yaml")) + try: + raw_policies = load_agent_policy(policy_path) + policy = AgentPolicy.from_dict(raw_policies[0]) if raw_policies else None + except Exception: + policy = None + file_path = tool_args["file_path"] + if policy is None: + text = f"File: {file_path}\nNo agent policy found - allowed by default." + else: + allowed = state.runtime.agent_policy.check_file_access(policy, file_path) + text = ( + f"File: {file_path}\n" + f"Policy: {policy.name}\n" + f"Allowed: {'yes' if allowed else 'NO - outside agent scope'}" + ) + return web.json_response(rpc_ok(request_id, {"content": [{"type": "text", "text": text}]})) + + return web.json_response(rpc_error(request_id, -32601, f"Unknown tool: {tool_name}")) diff --git a/mimir/adapters/http/state.py b/mimir/adapters/http/state.py new file mode 100644 index 0000000..77b88ef --- /dev/null +++ b/mimir/adapters/http/state.py @@ -0,0 +1,18 @@ +"""Shared request/application state for the query HTTP adapter.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from mimir.runtime import QueryRuntime + + +@dataclass +class HttpServerState: + """Mutable server state shared across route modules.""" + + runtime: QueryRuntime + workspace_name: str + + def current_graph(self): + return self.runtime.graph diff --git a/mimir/adapters/http/tooling.py b/mimir/adapters/http/tooling.py new file mode 100644 index 0000000..02ed5b9 --- /dev/null +++ b/mimir/adapters/http/tooling.py @@ -0,0 +1,165 @@ +"""Shared MCP helpers for the HTTP adapter.""" + +from __future__ import annotations + +from typing import Any + + +def rpc_ok(request_id: Any, result: Any) -> dict: + return {"jsonrpc": "2.0", "id": request_id, "result": result} + + +def rpc_error(request_id: Any, code: int, message: str) -> dict: + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": code, "message": message}, + } + + +def tool_definitions() -> list[dict]: + """Return the MCP tools list (same as stdio MCP server).""" + return [ + { + "name": "get_context", + "description": ( + "Retrieve relevant source code context for a natural language query. " + "Call this BEFORE answering any question about how the codebase works, " + "what a function does, where a feature is implemented, or how components interact. " + "Returns a minimal, connected, token-budget-aware context bundle assembled from " + "the code graph. Use `session_id` to enable cross-turn deduplication. " + "Use `repos` to restrict results to specific repositories. " + "Use `budget` to control the maximum token count (default 8000)." + ), + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Natural language question or task description"}, + "budget": {"type": "integer", "description": "Maximum tokens in the context bundle. Default: 8000."}, + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo names to restrict search to.", + }, + "session_id": {"type": "string", "description": "Conversation session ID for deduplication."}, + }, + "required": ["query"], + }, + }, + { + "name": "get_graph_stats", + "description": "Return statistics about the indexed code graph: node count, edge count, breakdown by kind, and repos indexed.", + "inputSchema": {"type": "object", "properties": {}}, + }, + { + "name": "get_hotspots", + "description": "Return the most recently and frequently modified code nodes.", + "inputSchema": { + "type": "object", + "properties": { + "top_n": {"type": "integer", "description": "Number of hotspots to return. Default: 20."}, + }, + }, + }, + { + "name": "get_write_context", + "description": "Collect edit-time context for a target file.", + "inputSchema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "File path or suffix to inspect."}, + }, + "required": ["file_path"], + }, + }, + { + "name": "get_impact", + "description": "Analyze the blast radius of a file or symbol change.", + "inputSchema": { + "type": "object", + "properties": { + "node_id": {"type": "string", "description": "Target node ID when available."}, + "file_path": {"type": "string", "description": "File path to narrow the target."}, + "symbol_name": {"type": "string", "description": "Symbol name to analyze."}, + "max_hops": {"type": "integer", "description": "Maximum transitive depth. Default: 3."}, + }, + }, + }, + { + "name": "get_quality", + "description": "Analyze graph connectivity quality and detect gaps — nodes with missing connections.", + "inputSchema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo names to restrict analysis to.", + }, + "threshold": {"type": "number", "description": "Quality threshold for gap detection. Default: 0.3."}, + "top_n": {"type": "integer", "description": "Max gap nodes to return. Default: 50."}, + }, + }, + }, + { + "name": "get_catalog", + "description": "Generate a Backstage-compatible service catalog from the code graph. Returns services with APIs, dependencies, tech stack, ownership, and quality.", + "inputSchema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo names to include. Omit for all repos.", + }, + }, + }, + }, + { + "name": "get_catalog_drift", + "description": "Compare declared dependencies against code-analyzed reality. Returns drift score and categorized findings.", + "inputSchema": { + "type": "object", + "properties": { + "repo": {"type": "string", "description": "Repository name to check."}, + "declared_dependencies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "type": {"type": "string"}, + }, + "required": ["name"], + }, + "description": "Declared dependencies to compare against.", + }, + }, + "required": ["repo", "declared_dependencies"], + }, + }, + { + "name": "validate_change", + "description": "Validate a diff against architectural guardrails.", + "inputSchema": { + "type": "object", + "properties": { + "diff": {"type": "string", "description": "Unified diff text."}, + "rules_path": {"type": "string", "description": "Path to guardrail rules."}, + }, + "required": ["diff"], + }, + }, + { + "name": "can_i_modify", + "description": "Check whether a file is within the current agent policy.", + "inputSchema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "Path to check."}, + "policy_path": {"type": "string", "description": "Path to mimir-agent-policy.yaml."}, + }, + "required": ["file_path"], + }, + }, + ] diff --git a/mimir/adapters/http_server.py b/mimir/adapters/http_server.py deleted file mode 100644 index a10ff75..0000000 --- a/mimir/adapters/http_server.py +++ /dev/null @@ -1,616 +0,0 @@ -"""HTTP API server — shared remote Mimir server for team access. - -Exposes the same query tools as the MCP server over HTTP JSON endpoints, -so developers who don't have repos cloned locally can query a centrally -indexed codebase. - -Endpoints ---------- -POST /api/v1/context — get_context (primary search tool) -GET /api/v1/stats — get_graph_stats -GET /api/v1/hotspots — get_hotspots -GET /api/v1/quality — get_quality -GET /api/v1/catalog — Backstage-compatible service catalog -GET /api/v1/catalog/{repo} — single-service catalog entry -POST /api/v1/catalog/drift — dependency drift detection -POST /api/v1/clear — clear_data (admin only, not exposed via MCP) -GET /api/v1/health — health check - -POST /api/v1/mcp — raw MCP JSON-RPC (for MCP-over-HTTP proxy clients) -""" - -from __future__ import annotations - -import json -import logging -from typing import Any - -from aiohttp import web - -from mimir.container import Container -from mimir.domain.config import MimirConfig - -logger = logging.getLogger(__name__) - - -def run_http_server( - config: MimirConfig, - host: str = "0.0.0.0", - port: int = 8421, - workspace_name: str | None = None, -) -> None: - """Start the shared HTTP API server. - - This is the server that the *team* runs centrally. Mobile developers - (or any consumer who doesn't have the repos locally) connect to it - via ``mimir serve --remote http://:``. - """ - container = Container(config) - graph = container.load_graph() - _ws_label = workspace_name or "default" - - logger.info( - "HTTP server starting — workspace=%s, host=%s, port=%d, graph=%d nodes", - _ws_label, host, port, graph.node_count, - ) - - routes = web.RouteTableDef() - - # ------------------------------------------------------------------ - # Health - # ------------------------------------------------------------------ - - @routes.get("/api/v1/health") - async def health(request: web.Request) -> web.Response: - return web.json_response({ - "status": "ok", - "workspace": _ws_label, - "graph_nodes": graph.node_count, - "graph_edges": graph.edge_count, - }) - - # ------------------------------------------------------------------ - # Core API - # ------------------------------------------------------------------ - - @routes.post("/api/v1/context") - async def api_context(request: web.Request) -> web.Response: - """Search the code graph and return a context bundle.""" - try: - body = await request.json() - except Exception: - return web.json_response({"error": "Invalid JSON body"}, status=400) - - query = body.get("query") - if not query: - return web.json_response({"error": "Missing 'query' field"}, status=400) - - budget = body.get("budget") - repos = body.get("repos") - session_id = body.get("session_id") - - try: - bundle = await container.retrieval.search( - query=query, - graph=graph, - token_budget=budget, - repos=repos, - ) - - # Session handling - if session_id: - session = container.session.get_or_create(session_id) - sg = _bundle_to_subgraph(bundle) - container.session.session_dedup( - sg, session, query_embedding=bundle.query_embedding, - ) - # Re-fit to budget after dedup may have changed node set - effective_budget = budget or container.retrieval._config.retrieval.default_token_budget - container.retrieval._fit_to_budget(sg, effective_budget, seed_ids=set()) - bundle.nodes = list(sg.nodes.values()) - bundle.edges = sg.edges - bundle.token_count = sg.token_estimate - if sg.notes: - bundle.session_note = ( - "Previously seen chunks omitted: " + str(len(sg.notes)) - ) - container.session.record_retrieval( - session, - query, - bundle.nodes, - {n.id: 1.0 for n in bundle.nodes}, - query_embedding=bundle.query_embedding, - ) - - return web.json_response({ - "summary": bundle.summary, - "token_count": bundle.token_count, - "repos": bundle.repos_involved, - "session_note": bundle.session_note, - "formatted": bundle.format_for_llm(), - "nodes": [n.to_dict() for n in bundle.nodes], - }) - except Exception as exc: - logger.error("Context query failed: %s", exc, exc_info=True) - return web.json_response({"error": str(exc)}, status=500) - - @routes.get("/api/v1/stats") - async def api_stats(request: web.Request) -> web.Response: - stats = graph.stats() - stats["workspace"] = _ws_label - return web.json_response(stats) - - @routes.get("/api/v1/hotspots") - async def api_hotspots(request: web.Request) -> web.Response: - top_n = int(request.query.get("top", "20")) - results = container.temporal.get_hotspots(graph, top_n=top_n) - return web.json_response([ - {"node": n.id, "score": round(s, 4), "changes": n.modification_count} - for n, s in results - ]) - - @routes.get("/api/v1/quality") - async def api_quality(request: web.Request) -> web.Response: - """Analyze graph quality and detect gaps.""" - repos_param = request.query.get("repos") - repos = repos_param.split(",") if repos_param else None - threshold = float(request.query.get("threshold", "0.3")) - top_n = int(request.query.get("top_n", "50")) - overview = container.quality.detect_gaps( - graph, repos=repos, threshold=threshold, top_n=top_n, - ) - return web.json_response(overview.to_dict()) - - # ------------------------------------------------------------------ - # Catalog API (Backstage integration) - # ------------------------------------------------------------------ - - @routes.get("/api/v1/catalog") - async def api_catalog(request: web.Request) -> web.Response: - """Generate Backstage-compatible service catalog from the code graph.""" - try: - repos_param = request.query.get("repos") - repos = repos_param.split(",") if repos_param else None - response = container.catalog.generate_catalog(graph, repos=repos) - return web.json_response(response.to_dict()) - except Exception as exc: - logger.error("Catalog generation failed: %s", exc, exc_info=True) - return web.json_response({"error": str(exc)}, status=500) - - @routes.get("/api/v1/catalog/{repo}") - async def api_catalog_service(request: web.Request) -> web.Response: - """Get catalog entry for a single service/repo.""" - repo = request.match_info["repo"] - try: - response = container.catalog.generate_catalog(graph, repos=[repo]) - if not response.services: - return web.json_response( - {"error": f"Repo '{repo}' not found in graph"}, status=404, - ) - return web.json_response(response.services[0].to_dict()) - except Exception as exc: - logger.error("Catalog single-service failed: %s", exc, exc_info=True) - return web.json_response({"error": str(exc)}, status=500) - - @routes.post("/api/v1/catalog/drift") - async def api_catalog_drift(request: web.Request) -> web.Response: - """Compare declared dependencies against code-analyzed reality.""" - try: - body = await request.json() - except Exception: - return web.json_response({"error": "Invalid JSON body"}, status=400) - - repo = body.get("repo") - if not repo: - return web.json_response({"error": "Missing 'repo' field"}, status=400) - - declared_deps = body.get("declared_dependencies", []) - try: - report = container.catalog.detect_drift( - graph, repo, declared_deps, - ) - return web.json_response(report.to_dict()) - except Exception as exc: - logger.error("Drift detection failed: %s", exc, exc_info=True) - return web.json_response({"error": str(exc)}, status=500) - - # ------------------------------------------------------------------ - # Guardrails API - # ------------------------------------------------------------------ - - @routes.post("/api/v1/guardrails/check") - async def api_guardrails_check(request: web.Request) -> web.Response: - """Validate a diff against architectural rules.""" - try: - body = await request.json() - except Exception: - return web.json_response({"error": "Invalid JSON body"}, status=400) - - diff = body.get("diff") - if not diff: - return web.json_response({"error": "Missing 'diff' field"}, status=400) - - from pathlib import Path - from mimir.domain.guardrails_config import load_rules - - rules_path = Path(body.get("rules_path", "mimir-rules.yaml")) - try: - rules = load_rules(rules_path) - except Exception as exc: - return web.json_response({"error": f"Rule loading failed: {exc}"}, status=400) - - try: - result = await container.guardrail.evaluate(graph, diff, rules) - return web.json_response(result.to_dict()) - except Exception as exc: - logger.error("Guardrail check failed: %s", exc, exc_info=True) - return web.json_response({"error": str(exc)}, status=500) - - # ------------------------------------------------------------------ - # Admin - # ------------------------------------------------------------------ - - @routes.post("/api/v1/clear") - async def api_clear(request: web.Request) -> web.Response: - nonlocal graph - try: - body = await request.json() - except Exception: - body = {} - result = container.clear_data( - graph=body.get("graph", True), - sessions=body.get("sessions", True), - ) - if body.get("graph", True): - graph = container.load_graph() - return web.json_response(result) - - # ------------------------------------------------------------------ - # MCP-over-HTTP (JSON-RPC passthrough) - # ------------------------------------------------------------------ - - @routes.post("/api/v1/mcp") - async def mcp_passthrough(request: web.Request) -> web.Response: - """Accept a raw MCP JSON-RPC request and return the response. - - This is how ``mimir serve --remote`` connects: it wraps each - stdio JSON-RPC message in an HTTP POST to this endpoint. - """ - try: - rpc_request = await request.json() - except Exception: - return web.json_response( - _rpc_error(None, -32700, "Parse error"), status=400, - ) - - method = rpc_request.get("method", "") - params = rpc_request.get("params", {}) - request_id = rpc_request.get("id") - - try: - if method == "initialize": - result = { - "protocolVersion": "2024-11-05", - "capabilities": {"tools": {"listChanged": False}}, - "serverInfo": { - "name": "mimir", - "version": "1.0.0", - "workspace": _ws_label, - "transport": "http", - }, - } - return web.json_response(_rpc_ok(request_id, result)) - - elif method == "tools/list": - tools = _tool_definitions() - return web.json_response(_rpc_ok(request_id, {"tools": tools})) - - elif method == "tools/call": - tool_name = params.get("name") - tool_args = params.get("arguments", {}) - - if tool_name == "get_context": - bundle = await container.retrieval.search( - query=tool_args["query"], - graph=graph, - token_budget=tool_args.get("budget"), - repos=tool_args.get("repos"), - ) - session_id = tool_args.get("session_id") - if session_id: - session = container.session.get_or_create(session_id) - sg = _bundle_to_subgraph(bundle) - container.session.session_dedup( - sg, session, query_embedding=bundle.query_embedding, - ) - bundle.nodes = list(sg.nodes.values()) - bundle.edges = sg.edges - bundle.token_count = sg.token_estimate - if sg.notes: - bundle.session_note = ( - "Previously seen chunks omitted: " - + str(len(sg.notes)) - ) - container.session.record_retrieval( - session, - tool_args["query"], - bundle.nodes, - {n.id: 1.0 for n in bundle.nodes}, - query_embedding=bundle.query_embedding, - ) - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": bundle.format_for_llm(), - }], - })) - - elif tool_name == "get_graph_stats": - stats = graph.stats() - stats["workspace"] = _ws_label - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": json.dumps(stats, indent=2), - }], - })) - - elif tool_name == "get_hotspots": - top_n = tool_args.get("top_n", 20) - results = container.temporal.get_hotspots(graph, top_n=top_n) - hotspots = [ - {"node": n.id, "score": f"{s:.3f}", "changes": n.modification_count} - for n, s in results - ] - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": json.dumps(hotspots, indent=2), - }], - })) - - elif tool_name == "get_quality": - overview = container.quality.detect_gaps( - graph, - repos=tool_args.get("repos"), - threshold=tool_args.get("threshold"), - top_n=tool_args.get("top_n", 50), - ) - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": overview.format_for_llm(), - }], - })) - - elif tool_name == "get_catalog": - cat_response = container.catalog.generate_catalog( - graph, repos=tool_args.get("repos"), - ) - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": cat_response.format_for_llm(), - }], - })) - - elif tool_name == "get_catalog_drift": - drift_report = container.catalog.detect_drift( - graph, - repo=tool_args["repo"], - declared_deps=tool_args.get("declared_dependencies", []), - ) - return web.json_response(_rpc_ok(request_id, { - "content": [{ - "type": "text", - "text": drift_report.format_for_llm(), - }], - })) - - else: - return web.json_response( - _rpc_error(request_id, -32601, f"Unknown tool: {tool_name}"), - ) - - elif method == "notifications/initialized": - return web.json_response({}) - - else: - return web.json_response( - _rpc_error(request_id, -32601, f"Unknown method: {method}"), - ) - - except Exception as exc: - logger.error("MCP-over-HTTP error: %s", exc, exc_info=True) - return web.json_response( - _rpc_error(request_id, -32000, str(exc)), - ) - - # ------------------------------------------------------------------ - # CORS - # ------------------------------------------------------------------ - - @web.middleware - async def cors_middleware(request: web.Request, handler): - if request.method == "OPTIONS": - response = web.Response(status=200) - else: - response = await handler(request) - response.headers["Access-Control-Allow-Origin"] = "*" - response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS" - response.headers["Access-Control-Allow-Headers"] = "Content-Type" - return response - - # ------------------------------------------------------------------ - # Run - # ------------------------------------------------------------------ - - app = web.Application(middlewares=[cors_middleware]) - app.router.add_routes(routes) - - # Eagerly load embedding model so first query is instant - container.warmup() - - logger.info("Shared Mimir HTTP server listening on http://%s:%d", host, port) - web.run_app(app, host=host, port=port, print=lambda _: None, access_log=None) - - -# ------------------------------------------------------------------ -# Helpers -# ------------------------------------------------------------------ - -def _rpc_ok(request_id: Any, result: Any) -> dict: - return {"jsonrpc": "2.0", "id": request_id, "result": result} - - -def _rpc_error(request_id: Any, code: int, message: str) -> dict: - return { - "jsonrpc": "2.0", - "id": request_id, - "error": {"code": code, "message": message}, - } - - -def _bundle_to_subgraph(bundle): - from mimir.domain.subgraph import SubGraph - sg = SubGraph() - for n in bundle.nodes: - sg.add_node(n) - for e in bundle.edges: - sg.add_edge(e) - return sg - - -def _tool_definitions() -> list[dict]: - """Return the MCP tools list (same as stdio MCP server).""" - return [ - { - "name": "get_context", - "description": ( - "Retrieve relevant source code context for a natural language query. " - "Call this BEFORE answering any question about how the codebase works, " - "what a function does, where a feature is implemented, or how components interact. " - "Returns a minimal, connected, token-budget-aware context bundle assembled from " - "the code graph. " - "Use `session_id` to enable cross-turn deduplication. " - "Use `repos` to restrict results to specific repositories. " - "Use `budget` to control the maximum token count (default 8000)." - ), - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Natural language question or task description", - }, - "budget": { - "type": "integer", - "description": "Maximum tokens in the context bundle. Default: 8000.", - }, - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional repo names to restrict search to.", - }, - "session_id": { - "type": "string", - "description": "Conversation session ID for deduplication.", - }, - }, - "required": ["query"], - }, - }, - { - "name": "get_graph_stats", - "description": ( - "Return statistics about the indexed code graph: node count, edge count, " - "breakdown by kind, and repos indexed." - ), - "inputSchema": {"type": "object", "properties": {}}, - }, - { - "name": "get_hotspots", - "description": ( - "Return the most recently and frequently modified code nodes." - ), - "inputSchema": { - "type": "object", - "properties": { - "top_n": { - "type": "integer", - "description": "Number of hotspots to return. Default: 20.", - }, - }, - }, - }, - { - "name": "get_quality", - "description": ( - "Analyze graph connectivity quality and detect gaps — nodes with missing connections." - ), - "inputSchema": { - "type": "object", - "properties": { - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional repo names to restrict analysis to.", - }, - "threshold": { - "type": "number", - "description": "Quality threshold for gap detection. Default: 0.3.", - }, - "top_n": { - "type": "integer", - "description": "Max gap nodes to return. Default: 50.", - }, - }, - }, - }, - { - "name": "get_catalog", - "description": ( - "Generate a Backstage-compatible service catalog from the code graph. " - "Returns services with APIs, dependencies, tech stack, ownership, and quality." - ), - "inputSchema": { - "type": "object", - "properties": { - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional repo names to include. Omit for all repos.", - }, - }, - }, - }, - { - "name": "get_catalog_drift", - "description": ( - "Compare declared dependencies against code-analyzed reality. " - "Returns drift score and categorized findings." - ), - "inputSchema": { - "type": "object", - "properties": { - "repo": { - "type": "string", - "description": "Repository name to check.", - }, - "declared_dependencies": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": {"type": "string"}, - "type": {"type": "string"}, - }, - "required": ["name"], - }, - "description": "Declared dependencies to compare against.", - }, - }, - "required": ["repo", "declared_dependencies"], - }, - }, - ] diff --git a/mimir/adapters/mcp/__init__.py b/mimir/adapters/mcp/__init__.py new file mode 100644 index 0000000..34de68a --- /dev/null +++ b/mimir/adapters/mcp/__init__.py @@ -0,0 +1,6 @@ +"""MCP adapter sub-package — stdio and remote MCP transports.""" + +from mimir.adapters.mcp.server import run_mcp_server +from mimir.adapters.mcp.remote import run_remote_mcp + +__all__ = ["run_mcp_server", "run_remote_mcp"] diff --git a/mimir/adapters/remote_mcp.py b/mimir/adapters/mcp/remote.py similarity index 100% rename from mimir/adapters/remote_mcp.py rename to mimir/adapters/mcp/remote.py diff --git a/mimir/adapters/mcp/server.py b/mimir/adapters/mcp/server.py new file mode 100644 index 0000000..433069e --- /dev/null +++ b/mimir/adapters/mcp/server.py @@ -0,0 +1,73 @@ +"""MCP server adapter — stdio transport bootstrap.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import sys + +from mimir.adapters.mcp.stdio_dispatch import handle_request +from mimir.domain.config import MimirConfig +from mimir.runtime import RuntimeFactory + +logger = logging.getLogger(__name__) + + +def run_mcp_server(config: MimirConfig, workspace_name: str | None = None) -> None: + """Start the MCP stdio server.""" + ws_label = workspace_name or "default" + runtime = RuntimeFactory(config).query() + graph = runtime.graph + logger.info("MCP server starting — workspace=%s, graph has %d nodes", ws_label, graph.node_count) + + try: + asyncio.run(_main_loop(runtime, ws_label)) + finally: + runtime.close() + + +async def _main_loop( + runtime, + workspace_name: str, +) -> None: + """Read JSON-RPC messages from stdin and write responses to stdout.""" + reader = asyncio.StreamReader() + protocol = asyncio.StreamReaderProtocol(reader) + loop = asyncio.get_event_loop() + await loop.connect_read_pipe(lambda: protocol, sys.stdin) + + write_transport, _ = await loop.connect_write_pipe(asyncio.streams.FlowControlMixin, sys.stdout) + + buffer = b"" + while True: + try: + data = await reader.read(4096) + if not data: + break + buffer += data + buffer = await _drain_messages( + buffer, + write_transport, + lambda request: handle_request(runtime, workspace_name, request), + ) + except asyncio.CancelledError: + break + except Exception as exc: + logger.error("MCP loop error: %s", exc, exc_info=True) + + +async def _drain_messages(buffer: bytes, write_transport, request_handler) -> bytes: + while b"\n" in buffer: + line, buffer = buffer.split(b"\n", 1) + line = line.strip() + if not line: + continue + try: + request = json.loads(line) + except json.JSONDecodeError: + continue + response = await request_handler(request) + if response and response.get("id") is not None: + write_transport.write((json.dumps(response) + "\n").encode()) + return buffer diff --git a/mimir/adapters/mcp/stdio_dispatch.py b/mimir/adapters/mcp/stdio_dispatch.py new file mode 100644 index 0000000..410cc56 --- /dev/null +++ b/mimir/adapters/mcp/stdio_dispatch.py @@ -0,0 +1,147 @@ +"""Request dispatch for stdio MCP.""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path + +from mimir.adapters.mcp.stdio_protocol import error_response, initialize_result, response, tool_definitions +from mimir.adapters.shared.session_context import apply_session_context +from mimir.domain.errors import NoActiveIndexError +from mimir.domain.guardrails_config import load_agent_policy, load_rules +from mimir.services.agent_policy import AgentPolicy + +logger = logging.getLogger(__name__) + + +async def handle_request(runtime, workspace_name: str, request: dict) -> dict: + method = request.get("method", "") + params = request.get("params", {}) + request_id = request.get("id") + + try: + if method == "initialize": + return response(request_id, initialize_result(workspace_name)) + + if method == "tools/list": + return response(request_id, {"tools": tool_definitions()}) + + if method == "notifications/initialized": + return {} + + if method != "tools/call": + return error_response(request_id, -32601, f"Unknown method: {method}") + + tool_name = params.get("name") + tool_args = params.get("arguments", {}) + return await _handle_tool_call(runtime, request_id, tool_name, tool_args, workspace_name) + except Exception as exc: + logger.error("MCP request failed: %s", exc, exc_info=True) + return error_response(request_id, -32000, str(exc)) + + +async def _handle_tool_call(runtime, request_id, tool_name: str | None, tool_args: dict, workspace_name: str) -> dict: + try: + graph = runtime.require_graph() + except NoActiveIndexError: + return error_response(request_id, -32000, "No active index. Run: mimir indexer run") + if tool_name == "get_context": + bundle = await runtime.retrieval.search( + query=tool_args["query"], + graph=graph, + token_budget=tool_args.get("budget"), + repos=tool_args.get("repos"), + ) + apply_session_context( + runtime, + bundle, + query=tool_args["query"], + session_id=tool_args.get("session_id"), + budget=tool_args.get("budget"), + ) + return response(request_id, {"content": [{"type": "text", "text": bundle.format_for_llm()}]}) + + if tool_name == "get_graph_stats": + stats = graph.stats() + stats["workspace"] = workspace_name + return response(request_id, {"content": [{"type": "text", "text": json.dumps(stats, indent=2)}]}) + + if tool_name == "get_hotspots": + results = runtime.temporal.get_hotspots(graph, top_n=tool_args.get("top_n", 20)) + payload = [{"node": node.id, "score": f"{score:.3f}", "changes": node.modification_count} for node, score in results] + return response(request_id, {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}]}) + + if tool_name == "get_write_context": + write_context = runtime.write_context.assemble(file_path=tool_args["file_path"], graph=graph) + return response(request_id, {"content": [{"type": "text", "text": write_context.format_for_llm()}]}) + + if tool_name == "get_impact": + result = runtime.impact.analyze( + graph, + node_id=tool_args.get("node_id"), + file_path=tool_args.get("file_path"), + symbol_name=tool_args.get("symbol_name"), + max_hops=tool_args.get("max_hops", 3), + ) + text = "No matching symbol or file found for impact analysis." if result is None else result.format_for_llm() + return response(request_id, {"content": [{"type": "text", "text": text}]}) + + if tool_name == "get_quality": + overview = runtime.quality.detect_gaps( + graph, + repos=tool_args.get("repos"), + threshold=tool_args.get("threshold"), + top_n=tool_args.get("top_n", 50), + ) + return response(request_id, {"content": [{"type": "text", "text": overview.format_for_llm()}]}) + + if tool_name == "get_catalog": + catalog = runtime.catalog.generate_catalog(graph, repos=tool_args.get("repos")) + return response(request_id, {"content": [{"type": "text", "text": catalog.format_for_llm()}]}) + + if tool_name == "get_catalog_drift": + report = runtime.catalog.detect_drift( + graph, + repo=tool_args["repo"], + declared_deps=tool_args.get("declared_dependencies", []), + ) + return response(request_id, {"content": [{"type": "text", "text": report.format_for_llm()}]}) + + if tool_name == "validate_change": + rules_path = Path(tool_args.get("rules_path", "mimir-rules.yaml")) + rules = load_rules(rules_path) + result = await runtime.guardrail.evaluate(graph, tool_args["diff"], rules) + return response(request_id, {"content": [{"type": "text", "text": result.format_for_llm()}]}) + + if tool_name == "can_i_modify": + policy_path = Path(tool_args.get("policy_path", "mimir-agent-policy.yaml")) + try: + raw_policies = load_agent_policy(policy_path) + policy = AgentPolicy.from_dict(raw_policies[0]) if raw_policies else None + except Exception: + policy = None + + file_path = tool_args["file_path"] + if policy is None: + text = f"File: {file_path}\nNo agent policy found - allowed by default." + else: + allowed = runtime.agent_policy.check_file_access(policy, file_path) + text = ( + f"File: {file_path}\n" + f"Policy: {policy.name}\n" + f"Allowed: {'yes' if allowed else 'NO - outside agent scope'}" + ) + return response(request_id, {"content": [{"type": "text", "text": text}]}) + + if tool_name == "report_feedback": + signal = runtime.feedback.record_explicit( + node_ids=tool_args["node_ids"], + outcome=tool_args["outcome"], + session_id=tool_args.get("session_id"), + query=tool_args.get("query"), + ) + text = f"Feedback recorded: {signal.outcome} for {len(signal.node_ids)} nodes." + return response(request_id, {"content": [{"type": "text", "text": text}]}) + + return error_response(request_id, -32601, f"Unknown tool: {tool_name}") diff --git a/mimir/adapters/mcp/stdio_protocol.py b/mimir/adapters/mcp/stdio_protocol.py new file mode 100644 index 0000000..b80f474 --- /dev/null +++ b/mimir/adapters/mcp/stdio_protocol.py @@ -0,0 +1,195 @@ +"""Protocol helpers and tool metadata for stdio MCP.""" + +from __future__ import annotations + +from typing import Any + + +def response(request_id: Any, result: Any) -> dict: + return {"jsonrpc": "2.0", "id": request_id, "result": result} + + +def error_response(request_id: Any, code: int, message: str) -> dict: + return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} + + +def initialize_result(workspace_name: str) -> dict: + return { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": { + "name": "mimir", + "version": "1.0.0", + "workspace": workspace_name, + }, + } + + +def tool_definitions() -> list[dict]: + return [ + { + "name": "get_context", + "description": "Retrieve relevant code context for a natural language query.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Natural language question or task."}, + "budget": {"type": "integer", "description": "Maximum token count. Default: 8000."}, + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo filter.", + }, + "session_id": { + "type": "string", + "description": "Conversation session ID for deduplication.", + }, + }, + "required": ["query"], + }, + }, + { + "name": "get_graph_stats", + "description": "Return graph statistics and indexed repositories.", + "inputSchema": {"type": "object", "properties": {}}, + }, + { + "name": "get_hotspots", + "description": "Return the most active or recently changed code nodes.", + "inputSchema": { + "type": "object", + "properties": { + "top_n": {"type": "integer", "description": "Number of hotspots to return. Default: 20."}, + }, + }, + }, + { + "name": "get_write_context", + "description": "Collect edit-time context for a target file.", + "inputSchema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "File path or suffix to inspect."}, + }, + "required": ["file_path"], + }, + }, + { + "name": "get_impact", + "description": "Analyze the blast radius of a file or symbol change.", + "inputSchema": { + "type": "object", + "properties": { + "node_id": {"type": "string", "description": "Target node ID when available."}, + "file_path": {"type": "string", "description": "File path to narrow the target."}, + "symbol_name": {"type": "string", "description": "Symbol name to analyze."}, + "max_hops": {"type": "integer", "description": "Maximum transitive depth. Default: 3."}, + }, + }, + }, + { + "name": "get_quality", + "description": "Analyze graph connectivity quality and gap nodes.", + "inputSchema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo filter.", + }, + "threshold": {"type": "number", "description": "Gap threshold. Default: 0.3."}, + "top_n": {"type": "integer", "description": "Max gap nodes to return. Default: 50."}, + }, + }, + }, + { + "name": "get_catalog", + "description": "Generate a catalog view from the code graph.", + "inputSchema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional repo filter.", + }, + }, + }, + }, + { + "name": "get_catalog_drift", + "description": "Compare declared dependencies against graph-derived dependencies.", + "inputSchema": { + "type": "object", + "properties": { + "repo": {"type": "string", "description": "Repository name."}, + "declared_dependencies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "type": {"type": "string"}, + }, + "required": ["name"], + }, + "description": "Declared dependencies to compare.", + }, + }, + "required": ["repo", "declared_dependencies"], + }, + }, + { + "name": "validate_change", + "description": "Validate a diff against architectural guardrails.", + "inputSchema": { + "type": "object", + "properties": { + "diff": {"type": "string", "description": "Unified diff text."}, + "rules_path": {"type": "string", "description": "Path to guardrail rules."}, + }, + "required": ["diff"], + }, + }, + { + "name": "can_i_modify", + "description": "Check whether a file is within the current agent policy.", + "inputSchema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "Path to check."}, + "policy_path": {"type": "string", "description": "Path to mimir-agent-policy.yaml."}, + }, + "required": ["file_path"], + }, + }, + { + "name": "report_feedback", + "description": "Report whether retrieved context was helpful (positive) or not (negative).", + "inputSchema": { + "type": "object", + "properties": { + "node_ids": { + "type": "array", + "items": {"type": "string"}, + "description": "Node IDs from the retrieved context.", + }, + "outcome": { + "type": "string", + "enum": ["positive", "negative"], + "description": "Whether the context was helpful.", + }, + "session_id": { + "type": "string", + "description": "Optional session ID for context.", + }, + "query": { + "type": "string", + "description": "The original query that produced this context.", + }, + }, + "required": ["node_ids", "outcome"], + }, + }, + ] diff --git a/mimir/adapters/mcp_server.py b/mimir/adapters/mcp_server.py deleted file mode 100644 index c188a71..0000000 --- a/mimir/adapters/mcp_server.py +++ /dev/null @@ -1,576 +0,0 @@ -"""MCP server adapter — stdio transport for IDE integration.""" - -from __future__ import annotations - -import asyncio -import json -import logging -import sys -from typing import Any - -from mimir.container import Container -from mimir.domain.config import MimirConfig - -logger = logging.getLogger(__name__) - - -def run_mcp_server(config: MimirConfig, workspace_name: str | None = None) -> None: - """Start the MCP server on stdio. - - Parameters - ---------- - config: - Validated Mimir configuration. - workspace_name: - The workspace name this server is locked to (for informational purposes only). - If None, the server is running against a bare --config file. - """ - _ws_label = workspace_name or "default" - container = Container(config) - graph = container.load_graph() - container.warmup() - logger.info( - "MCP server starting — workspace=%s, graph has %d nodes", - _ws_label, graph.node_count, - ) - - # File watcher (started later, after the event loop is available) - _watcher_enabled = config.watcher.enabled - - async def handle_request(request: dict) -> dict: - """Route MCP JSON-RPC requests.""" - method = request.get("method", "") - params = request.get("params", {}) - request_id = request.get("id") - - try: - if method == "initialize": - return _response(request_id, { - "protocolVersion": "2024-11-05", - "capabilities": { - "tools": {"listChanged": False}, - }, - "serverInfo": { - "name": "mimir", - "version": "1.0.0", - "workspace": _ws_label, - }, - }) - - elif method == "tools/list": - return _response(request_id, { - "tools": [ - { - "name": "get_context", - "description": ( - "Retrieve relevant source code context for a natural language query. " - "Call this BEFORE answering any question about how the codebase works, " - "what a function does, where a feature is implemented, or how components interact. " - "Returns a minimal, connected, token-budget-aware context bundle assembled from " - "the code graph — including the most relevant functions, classes, and their " - "dependencies. " - "Use `session_id` to enable cross-turn deduplication: pass the same ID on every " - "turn of a conversation so that code already seen by the LLM is summarized or " - "omitted in subsequent responses, reducing token usage. " - "Use `repos` to restrict results to specific repositories when working in a " - "multi-repo workspace. " - "Use `budget` to control the maximum token count of the returned context " - "(default 8000)." - ), - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Natural language question or task description, e.g. 'how does authentication work' or 'where is the retry logic for API calls'", - }, - "budget": { - "type": "integer", - "description": "Maximum tokens to include in the context bundle. Default: 8000. Reduce for faster responses or when only a summary is needed.", - }, - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional list of repo names to restrict the search to. Omit to search all indexed repos.", - }, - "session_id": { - "type": "string", - "description": "Conversation session ID. Pass the same value on every turn to enable deduplication — code sent in a previous turn will be summarized or omitted, reducing repeated context.", - }, - }, - "required": ["query"], - }, - }, - { - "name": "get_graph_stats", - "description": ( - "Return statistics about the indexed code graph: total node count, edge count, " - "breakdown by node kind (functions, classes, files, modules), and repos indexed. " - "Call this when the user asks what has been indexed, how large the codebase is, " - "or to confirm that indexing completed successfully before proceeding with queries." - ), - "inputSchema": {"type": "object", "properties": {}}, - }, - { - "name": "get_hotspots", - "description": ( - "Return the most recently and frequently modified code nodes, ranked by a " - "combined recency + change-frequency score. " - "Call this when the user asks about active development areas, what has changed " - "recently, where bugs are most likely introduced, or what to focus a code review on. " - "Results include node ID, hotspot score, and commit count." - ), - "inputSchema": { - "type": "object", - "properties": { - "top_n": { - "type": "integer", - "description": "Number of hotspots to return. Default: 20.", - }, - }, - }, - }, - { - "name": "get_write_context", - "description": ( - "Get everything you need to know before editing a file: the symbols it contains, " - "interfaces and base classes those symbols implement or extend, sibling implementations, " - "the associated test file, DI/factory registrations, and import relationships. " - "Call this BEFORE modifying a file so you understand the contracts, tests, and " - "dependents you need to satisfy." - ), - "inputSchema": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to the file you intend to edit, e.g. 'src/auth/login.py' or 'LoginView.swift'. Suffix matching is supported.", - }, - }, - "required": ["file_path"], - }, - }, - { - "name": "get_impact", - "description": ( - "Analyze what would be affected if you change a symbol or file. " - "Returns direct callers, type users, implementors/subclasses, associated test files, " - "and transitive dependencies up to N hops. " - "Call this before refactoring, renaming, or removing code to understand the blast radius." - ), - "inputSchema": { - "type": "object", - "properties": { - "node_id": { - "type": "string", - "description": "Node ID from a previous get_context result. Preferred if available.", - }, - "file_path": { - "type": "string", - "description": "File path to narrow down the search. Used with symbol_name.", - }, - "symbol_name": { - "type": "string", - "description": "Name of the function, class, or method to analyze.", - }, - "max_hops": { - "type": "integer", - "description": "Maximum transitive dependency depth. Default: 3.", - }, - }, - }, - }, - { - "name": "get_quality", - "description": ( - "Analyze the connectivity quality of the code graph and detect gaps — nodes " - "with missing or weak connections that may indicate under-indexed or poorly-resolved " - "areas of the codebase. Returns a quality overview with average scores, distribution, " - "and a list of the worst-connected nodes with diagnostic reasons. " - "Call this to assess index health, find areas that need re-indexing, or understand " - "which parts of the codebase have incomplete symbol resolution." - ), - "inputSchema": { - "type": "object", - "properties": { - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional list of repo names to restrict analysis to.", - }, - "threshold": { - "type": "number", - "description": "Quality score threshold below which nodes are flagged as gaps. Default: 0.3.", - }, - "top_n": { - "type": "integer", - "description": "Maximum number of gap nodes to return. Default: 50.", - }, - }, - }, - }, - { - "name": "get_catalog", - "description": ( - "Generate a Backstage-compatible service catalog from the code graph. " - "Returns discovered services with their APIs, cross-repo dependencies, " - "tech stack, ownership, and quality scores. " - "Use `repos` to restrict to specific repositories." - ), - "inputSchema": { - "type": "object", - "properties": { - "repos": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional list of repo names to include. Omit for all repos.", - }, - }, - }, - }, - { - "name": "get_catalog_drift", - "description": ( - "Compare declared service dependencies against what the code graph actually shows. " - "Detects undeclared dependencies (in code but not in catalog) and missing dependencies " - "(declared but no code evidence). Returns a drift score from 0 (perfect) to 1 (fully mismatched)." - ), - "inputSchema": { - "type": "object", - "properties": { - "repo": { - "type": "string", - "description": "Repository name to check drift for.", - }, - "declared_dependencies": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": {"type": "string"}, - "type": {"type": "string"}, - }, - "required": ["name"], - }, - "description": "List of declared dependencies, each with a 'name' and optional 'type'.", - }, - }, - "required": ["repo", "declared_dependencies"], - }, - }, - { - "name": "validate_change", - "description": ( - "Validate a code change against architectural rules before committing. " - "Pass a unified diff (from `git diff`) and receive a list of violations " - "if any architectural rules are broken. Use this BEFORE committing changes " - "to catch layer violations, circular dependencies, coupling threshold " - "breaches, and high-impact API changes." - ), - "inputSchema": { - "type": "object", - "properties": { - "diff": { - "type": "string", - "description": "Unified diff text (output of `git diff` or `git diff --cached`)", - }, - "rules_path": { - "type": "string", - "description": "Path to mimir-rules.yaml. Default: ./mimir-rules.yaml", - }, - }, - "required": ["diff"], - }, - }, - { - "name": "can_i_modify", - "description": ( - "Check if you are allowed to modify a file per the agent policy. " - "Returns whether the file is within the agent's allowed scope " - "and whether human review would be required." - ), - "inputSchema": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to the file you want to modify.", - }, - "policy_path": { - "type": "string", - "description": "Path to mimir-agent-policy.yaml. Default: ./mimir-agent-policy.yaml", - }, - }, - "required": ["file_path"], - }, - }, - ], - }) - - elif method == "tools/call": - tool_name = params.get("name") - tool_args = params.get("arguments", {}) - - if tool_name == "get_context": - bundle = await container.retrieval.search( - query=tool_args["query"], - graph=graph, - token_budget=tool_args.get("budget"), - repos=tool_args.get("repos"), - ) - - # Session handling - session_id = tool_args.get("session_id") - if session_id: - session = container.session.get_or_create(session_id) - sg = _bundle_to_subgraph(bundle) - container.session.session_dedup( - sg, session, query_embedding=bundle.query_embedding, - ) - - # Re-fit to budget after dedup may have changed node set - effective_budget = tool_args.get("budget") or container.retrieval._config.retrieval.default_token_budget - container.retrieval._fit_to_budget(sg, effective_budget, seed_ids=set()) - - # Apply deduplication back to the bundle - bundle.nodes = list(sg.nodes.values()) - bundle.edges = sg.edges - bundle.token_count = sg.token_estimate - if sg.notes: - bundle.session_note = "Previously seen chunks omitted: " + str(len(sg.notes)) - - container.session.record_retrieval( - session, - tool_args["query"], - bundle.nodes, - {n.id: 1.0 for n in bundle.nodes}, - query_embedding=bundle.query_embedding, - ) - - return _response(request_id, { - "content": [{ - "type": "text", - "text": bundle.format_for_llm(), - }], - }) - - elif tool_name == "get_graph_stats": - stats = graph.stats() - stats["workspace"] = _ws_label - return _response(request_id, { - "content": [{ - "type": "text", - "text": json.dumps(stats, indent=2), - }], - }) - - elif tool_name == "get_hotspots": - top_n = tool_args.get("top_n", 20) - results = container.temporal.get_hotspots(graph, top_n=top_n) - hotspots = [ - {"node": n.id, "score": f"{s:.3f}", "changes": n.modification_count} - for n, s in results - ] - return _response(request_id, { - "content": [{ - "type": "text", - "text": json.dumps(hotspots, indent=2), - }], - }) - - elif tool_name == "get_write_context": - wc = container.write_context.assemble( - file_path=tool_args["file_path"], - graph=graph, - ) - return _response(request_id, { - "content": [{ - "type": "text", - "text": wc.format_for_llm(), - }], - }) - - elif tool_name == "get_impact": - result = container.impact.analyze( - graph, - node_id=tool_args.get("node_id"), - file_path=tool_args.get("file_path"), - symbol_name=tool_args.get("symbol_name"), - max_hops=tool_args.get("max_hops", 3), - ) - if result is None: - text = "No matching symbol or file found for impact analysis." - else: - text = result.format_for_llm() - return _response(request_id, { - "content": [{ - "type": "text", - "text": text, - }], - }) - - elif tool_name == "get_quality": - overview = container.quality.detect_gaps( - graph, - repos=tool_args.get("repos"), - threshold=tool_args.get("threshold"), - top_n=tool_args.get("top_n", 50), - ) - return _response(request_id, { - "content": [{ - "type": "text", - "text": overview.format_for_llm(), - }], - }) - - elif tool_name == "get_catalog": - response = container.catalog.generate_catalog( - graph, repos=tool_args.get("repos"), - ) - return _response(request_id, { - "content": [{ - "type": "text", - "text": response.format_for_llm(), - }], - }) - - elif tool_name == "get_catalog_drift": - report = container.catalog.detect_drift( - graph, - repo=tool_args["repo"], - declared_deps=tool_args.get("declared_dependencies", []), - ) - return _response(request_id, { - "content": [{ - "type": "text", - "text": report.format_for_llm(), - }], - }) - - elif tool_name == "validate_change": - from pathlib import Path - from mimir.domain.guardrails_config import load_rules - - rules_path = Path(tool_args.get("rules_path", "mimir-rules.yaml")) - rules = load_rules(rules_path) - result = await container.guardrail.evaluate( - graph, tool_args["diff"], rules, - ) - return _response(request_id, { - "content": [{ - "type": "text", - "text": result.format_for_llm(), - }], - }) - - elif tool_name == "can_i_modify": - from pathlib import Path - from mimir.domain.guardrails_config import load_agent_policy - from mimir.services.agent_policy import AgentPolicy - - policy_path = Path(tool_args.get("policy_path", "mimir-agent-policy.yaml")) - try: - raw_policies = load_agent_policy(policy_path) - policy = AgentPolicy.from_dict(raw_policies[0]) if raw_policies else None - except Exception: - policy = None - - file_path = tool_args["file_path"] - if policy: - allowed = container.agent_policy.check_file_access(policy, file_path) - text = ( - f"File: {file_path}\n" - f"Policy: {policy.name}\n" - f"Allowed: {'yes' if allowed else 'NO — outside agent scope'}" - ) - else: - text = f"File: {file_path}\nNo agent policy found — allowed by default." - - return _response(request_id, { - "content": [{ - "type": "text", - "text": text, - }], - }) - - else: - return _error_response(request_id, -32601, f"Unknown tool: {tool_name}") - - elif method == "notifications/initialized": - return {} # Acknowledgement, no response needed - - else: - return _error_response(request_id, -32601, f"Unknown method: {method}") - - except Exception as exc: - logger.error("MCP request failed: %s", exc, exc_info=True) - return _error_response(request_id, -32000, str(exc)) - - async def main_loop(): - """Read JSON-RPC messages from stdin, write responses to stdout.""" - reader = asyncio.StreamReader() - protocol = asyncio.StreamReaderProtocol(reader) - await asyncio.get_event_loop().connect_read_pipe(lambda: protocol, sys.stdin) - - loop = asyncio.get_event_loop() - - # Start file watcher if enabled - if _watcher_enabled: - try: - container.watcher.start(loop) - except Exception as exc: - logger.error("Failed to start file watcher: %s", exc) - write_transport, _ = await loop.connect_write_pipe( - asyncio.streams.FlowControlMixin, sys.stdout - ) - - buffer = b"" - while True: - try: - data = await reader.read(4096) - if not data: - break - buffer += data - - # Try to parse JSON-RPC messages - while b"\n" in buffer: - line, buffer = buffer.split(b"\n", 1) - line = line.strip() - if not line: - continue - try: - request = json.loads(line) - response = await handle_request(request) - if response and response.get("id") is not None: - out = json.dumps(response) + "\n" - write_transport.write(out.encode()) - except json.JSONDecodeError: - continue - except asyncio.CancelledError: - break - except Exception as exc: - logger.error("MCP loop error: %s", exc, exc_info=True) - - try: - asyncio.run(main_loop()) - finally: - container.close() - - -def _response(request_id: Any, result: Any) -> dict: - return {"jsonrpc": "2.0", "id": request_id, "result": result} - - -def _error_response(request_id: Any, code: int, message: str) -> dict: - return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} - - -def _bundle_to_subgraph(bundle): - """Convert a ContextBundle back to a SubGraph for session dedup.""" - from mimir.domain.subgraph import SubGraph - sg = SubGraph() - for n in bundle.nodes: - sg.add_node(n) - for e in bundle.edges: - sg.add_edge(e) - return sg diff --git a/mimir/adapters/shared/__init__.py b/mimir/adapters/shared/__init__.py new file mode 100644 index 0000000..1a01f72 --- /dev/null +++ b/mimir/adapters/shared/__init__.py @@ -0,0 +1 @@ +"""Shared helpers for transport adapters.""" diff --git a/mimir/adapters/shared/session_context.py b/mimir/adapters/shared/session_context.py new file mode 100644 index 0000000..4d931ce --- /dev/null +++ b/mimir/adapters/shared/session_context.py @@ -0,0 +1,56 @@ +"""Shared session-aware bundle post-processing for transport adapters.""" + +from __future__ import annotations + +from mimir.domain.subgraph import SubGraph + + +def apply_session_context( + container, + bundle, + *, + query: str, + session_id: str | None, + budget: int | None, +) -> None: + """Apply session deduplication, budget fit, and retrieval tracking.""" + if not session_id: + return + + session = container.session.get_or_create(session_id) + subgraph = _bundle_to_subgraph(bundle) + container.session.session_dedup( + subgraph, + session, + query_embedding=bundle.query_embedding, + ) + + effective_budget = budget or container.retrieval.default_token_budget + container.retrieval.fit_subgraph_to_budget( + subgraph, + effective_budget, + seed_ids=set(), + ) + + bundle.nodes = list(subgraph.nodes.values()) + bundle.edges = subgraph.edges + bundle.token_count = subgraph.token_estimate + if subgraph.notes: + bundle.session_note = "Previously seen chunks omitted: " + str(len(subgraph.notes)) + + container.session.record_retrieval( + session, + query, + bundle.nodes, + {node.id: 1.0 for node in bundle.nodes}, + query_embedding=bundle.query_embedding, + ) + + +def _bundle_to_subgraph(bundle) -> SubGraph: + subgraph = SubGraph() + for node in bundle.nodes: + subgraph.add_node(node.clone()) + for edge in bundle.edges: + subgraph.add_edge(edge) + return subgraph diff --git a/mimir/adapters/web/app.py b/mimir/adapters/web/app.py new file mode 100644 index 0000000..0a87d6a --- /dev/null +++ b/mimir/adapters/web/app.py @@ -0,0 +1,38 @@ +"""Web inspector bootstrap.""" + +from __future__ import annotations + +import logging + +from aiohttp import web + +from mimir.domain.config import MimirConfig +from mimir.runtime import RuntimeFactory + +from .routes import cors_middleware, register_routes +from .state import WebServerState + +logger = logging.getLogger(__name__) + + +def run_web_server(config: MimirConfig, port: int = 8420) -> None: + """Start the aiohttp web inspector.""" + runtime = RuntimeFactory(config).query() + state = WebServerState(runtime=runtime) + + routes = web.RouteTableDef() + register_routes(routes, state) + + app = web.Application(middlewares=[cors_middleware()]) + app.router.add_routes(routes) + app.on_cleanup.append(_cleanup_factory(state)) + + logger.info("Starting web inspector on port %d", port) + web.run_app(app, host="0.0.0.0", port=port, print=lambda _: None, access_log=None) + + +def _cleanup_factory(state: WebServerState): + async def on_cleanup(app: web.Application) -> None: + state.runtime.close() + + return on_cleanup diff --git a/mimir/adapters/web/routes.py b/mimir/adapters/web/routes.py new file mode 100644 index 0000000..e700718 --- /dev/null +++ b/mimir/adapters/web/routes.py @@ -0,0 +1,188 @@ +"""Route registration for the web inspector adapter.""" + +from __future__ import annotations + +from pathlib import Path + +from aiohttp import web + +from mimir.adapters.http.routes_api import no_active_index_response +from mimir.adapters.web.state import WebServerState +from mimir.domain.errors import NoActiveIndexError + +_STATIC_DIR = Path(__file__).parent / "static" + + +def register_routes(routes: web.RouteTableDef, state: WebServerState) -> None: + @routes.get("/api/stats") + async def api_stats(request: web.Request) -> web.Response: + try: + return web.json_response(state.runtime.require_graph().stats()) + except NoActiveIndexError: + return no_active_index_response() + + @routes.get("/api/index/status") + async def api_index_status(request: web.Request) -> web.Response: + return web.json_response(state.runtime.status()) + + @routes.get("/api/nodes") + async def api_nodes(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + kind = request.query.get("kind") + repo = request.query.get("repo") + limit = int(request.query.get("limit", "100")) + offset = int(request.query.get("offset", "0")) + + nodes = list(graph.all_nodes()) + if kind: + nodes = [node for node in nodes if node.kind.value == kind] + if repo: + nodes = [node for node in nodes if node.repo == repo] + + total = len(nodes) + nodes = nodes[offset : offset + limit] + return web.json_response({ + "total": total, + "offset": offset, + "limit": limit, + "nodes": [node.to_dict() for node in nodes], + }) + + @routes.get("/api/node-detail") + async def api_node_detail_query(request: web.Request) -> web.Response: + node_id = request.query.get("id", "") + if not node_id: + return web.json_response({"error": "Missing 'id' parameter"}, status=400) + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + return _node_detail_response(graph, node_id, include_embedding=True) + + @routes.get("/api/nodes/{node_id:.*}") + async def api_node_detail(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + return _node_detail_response(graph, request.match_info["node_id"]) + + @routes.get("/api/graph-data") + async def api_graph_data(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + repo = request.query.get("repo") + max_nodes = int(request.query.get("max", "200")) + + nodes = list(graph.all_nodes()) + if repo: + nodes = [node for node in nodes if node.repo == repo] + nodes = nodes[:max_nodes] + node_ids = {node.id for node in nodes} + edges = [ + edge + for edge in graph.all_edges() + if edge.source in node_ids and edge.target in node_ids + ] + + return web.json_response({ + "nodes": [{"id": node.id, "name": node.name, "kind": node.kind.value, "repo": node.repo} for node in nodes], + "links": [{"source": edge.source, "target": edge.target, "kind": edge.kind.value} for edge in edges], + }) + + @routes.get("/api/search") + async def api_search(request: web.Request) -> web.Response: + query = request.query.get("q", "") + if not query: + return web.json_response({"error": "Missing query parameter 'q'"}, status=400) + + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + budget = int(request.query.get("budget", "4000")) + repo_filter = request.query.get("repo") + repos = [repo_filter] if repo_filter else None + bundle = await state.runtime.retrieval.search( + query=query, + graph=graph, + token_budget=budget, + repos=repos, + ) + return web.json_response({ + "summary": bundle.summary, + "token_count": bundle.token_count, + "repos": bundle.repos_involved, + "nodes": [node.to_dict() for node in bundle.nodes], + "formatted": bundle.format_for_llm(), + }) + + @routes.get("/api/hotspots") + async def api_hotspots(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + top_n = int(request.query.get("top", "20")) + results = state.runtime.temporal.get_hotspots(graph, top_n=top_n) + return web.json_response([{"node": node.to_dict(), "score": round(score, 4)} for node, score in results]) + + @routes.get("/api/quality") + async def api_quality(request: web.Request) -> web.Response: + try: + graph = state.runtime.require_graph() + except NoActiveIndexError: + return no_active_index_response() + repos_param = request.query.get("repos") + overview = state.runtime.quality.detect_gaps( + graph, + repos=repos_param.split(",") if repos_param else None, + threshold=float(request.query.get("threshold", "0.3")), + top_n=int(request.query.get("top_n", "50")), + ) + return web.json_response(overview.to_dict()) + + @routes.get("/") + async def index(request: web.Request) -> web.FileResponse: + return web.FileResponse(_STATIC_DIR / "index.html") + + routes.static("/static", _STATIC_DIR, append_version=True) + + +def cors_middleware(): + @web.middleware + async def middleware(request: web.Request, handler): + if request.method == "OPTIONS": + response = web.Response(status=200) + else: + response = await handler(request) + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS" + response.headers["Access-Control-Allow-Headers"] = "Content-Type" + return response + + return middleware + + +def _node_detail_response(graph, node_id: str, *, include_embedding: bool = False) -> web.Response: + node = graph.get_node(node_id) + if not node: + raise web.HTTPNotFound(text=f"Node not found: {node_id}") + + node_data = node.to_dict() + if include_embedding: + node_data["has_embedding"] = node.embedding is not None + node_data["embedding_dim"] = len(node.embedding) if node.embedding else 0 + + return web.json_response({ + "node": node_data, + "outgoing_edges": [edge.to_dict() for edge in graph.get_outgoing_edges(node_id)], + "incoming_edges": [edge.to_dict() for edge in graph.get_incoming_edges(node_id)], + "children": [child.to_dict() for child in graph.get_children(node_id)], + "parent": graph.get_parent(node_id).to_dict() if graph.get_parent(node_id) else None, + }) diff --git a/mimir/adapters/web/server.py b/mimir/adapters/web/server.py index 6554498..bdcdb16 100644 --- a/mimir/adapters/web/server.py +++ b/mimir/adapters/web/server.py @@ -1,240 +1,7 @@ -"""Web inspector server — aiohttp API for the frontend UI.""" +"""Compatibility shim for the web inspector bootstrap.""" from __future__ import annotations -import json -import logging -from pathlib import Path +from mimir.adapters.web.app import run_web_server -from aiohttp import web - -from mimir.container import Container -from mimir.domain.config import MimirConfig - -logger = logging.getLogger(__name__) - -_STATIC_DIR = Path(__file__).parent / "static" - - -def run_web_server(config: MimirConfig, port: int = 8420) -> None: - """Start the aiohttp web server.""" - container = Container(config) - graph = container.load_graph() - - routes = web.RouteTableDef() - - # ------------------------------------------------------------------ - # API endpoints - # ------------------------------------------------------------------ - - @routes.get("/api/stats") - async def api_stats(request: web.Request) -> web.Response: - return web.json_response(graph.stats()) - - @routes.get("/api/nodes") - async def api_nodes(request: web.Request) -> web.Response: - kind = request.query.get("kind") - repo = request.query.get("repo") - limit = int(request.query.get("limit", "100")) - offset = int(request.query.get("offset", "0")) - - nodes = list(graph.all_nodes()) - if kind: - nodes = [n for n in nodes if n.kind.value == kind] - if repo: - nodes = [n for n in nodes if n.repo == repo] - - total = len(nodes) - nodes = nodes[offset : offset + limit] - - return web.json_response({ - "total": total, - "offset": offset, - "limit": limit, - "nodes": [n.to_dict() for n in nodes], - }) - - @routes.get("/api/node-detail") - async def api_node_detail_query(request: web.Request) -> web.Response: - """Node detail using query param to avoid URL encoding issues.""" - node_id = request.query.get("id", "") - if not node_id: - return web.json_response({"error": "Missing 'id' parameter"}, status=400) - - node = graph.get_node(node_id) - if not node: - raise web.HTTPNotFound(text=f"Node not found: {node_id}") - - outgoing = graph.get_outgoing_edges(node_id) - incoming = graph.get_incoming_edges(node_id) - children = graph.get_children(node_id) - parent = graph.get_parent(node_id) - - node_data = node.to_dict() - node_data["has_embedding"] = node.embedding is not None - node_data["embedding_dim"] = len(node.embedding) if node.embedding else 0 - - return web.json_response({ - "node": node_data, - "outgoing_edges": [e.to_dict() for e in outgoing], - "incoming_edges": [e.to_dict() for e in incoming], - "children": [c.to_dict() for c in children], - "parent": parent.to_dict() if parent else None, - }) - - @routes.get("/api/nodes/{node_id:.*}") - async def api_node_detail(request: web.Request) -> web.Response: - node_id = request.match_info["node_id"] - node = graph.get_node(node_id) - if not node: - raise web.HTTPNotFound(text=f"Node not found: {node_id}") - - outgoing = graph.get_outgoing_edges(node_id) - incoming = graph.get_incoming_edges(node_id) - children = graph.get_children(node_id) - parent = graph.get_parent(node_id) - - return web.json_response({ - "node": node.to_dict(), - "outgoing_edges": [e.to_dict() for e in outgoing], - "incoming_edges": [e.to_dict() for e in incoming], - "children": [c.to_dict() for c in children], - "parent": parent.to_dict() if parent else None, - }) - - @routes.get("/api/graph-data") - async def api_graph_data(request: web.Request) -> web.Response: - """Return D3-compatible graph data.""" - repo = request.query.get("repo") - max_nodes = int(request.query.get("max", "200")) - - nodes = list(graph.all_nodes()) - if repo: - nodes = [n for n in nodes if n.repo == repo] - nodes = nodes[:max_nodes] - - node_ids = {n.id for n in nodes} - edges = [ - e for e in graph.all_edges() - if e.source in node_ids and e.target in node_ids - ] - - return web.json_response({ - "nodes": [ - {"id": n.id, "name": n.name, "kind": n.kind.value, "repo": n.repo} - for n in nodes - ], - "links": [ - {"source": e.source, "target": e.target, "kind": e.kind.value} - for e in edges - ], - }) - - @routes.get("/api/search") - async def api_search(request: web.Request) -> web.Response: - query = request.query.get("q", "") - if not query: - return web.json_response({"error": "Missing query parameter 'q'"}, status=400) - - budget = int(request.query.get("budget", "4000")) - repo_filter = request.query.get("repo") - repos = [repo_filter] if repo_filter else None - - bundle = await container.retrieval.search( - query=query, - graph=graph, - token_budget=budget, - repos=repos, - ) - - return web.json_response({ - "summary": bundle.summary, - "token_count": bundle.token_count, - "repos": bundle.repos_involved, - "nodes": [n.to_dict() for n in bundle.nodes], - "formatted": bundle.format_for_llm(), - }) - - @routes.get("/api/hotspots") - async def api_hotspots(request: web.Request) -> web.Response: - top_n = int(request.query.get("top", "20")) - results = container.temporal.get_hotspots(graph, top_n=top_n) - return web.json_response([ - { - "node": n.to_dict(), - "score": round(s, 4), - } - for n, s in results - ]) - - @routes.get("/api/quality") - async def api_quality(request: web.Request) -> web.Response: - repos_param = request.query.get("repos") - repo_list = repos_param.split(",") if repos_param else None - threshold = float(request.query.get("threshold", "0.3")) - top_n = int(request.query.get("top_n", "50")) - overview = container.quality.detect_gaps( - graph, repos=repo_list, threshold=threshold, top_n=top_n, - ) - return web.json_response(overview.to_dict()) - - @routes.delete("/api/clear") - async def api_clear(request: web.Request) -> web.Response: - """Delete all locally stored index data. - - Accepts an optional JSON body to control what is cleared: - {"graph": true, "sessions": true} - - Both default to true if omitted. - """ - nonlocal graph - try: - body = await request.json() - except Exception: - body = {} - - clear_graph = body.get("graph", True) - clear_sessions = body.get("sessions", True) - - result = container.clear_data(graph=clear_graph, sessions=clear_sessions) - - # Reload graph in-place so the server stays functional for new indexing - if clear_graph: - graph = container.load_graph() - - return web.json_response(result) - - # ------------------------------------------------------------------ - # Static files - # ------------------------------------------------------------------ - - @routes.get("/") - async def index(request: web.Request) -> web.FileResponse: - return web.FileResponse(_STATIC_DIR / "index.html") - - routes.static("/static", _STATIC_DIR, append_version=True) - - # ------------------------------------------------------------------ - # CORS middleware - # ------------------------------------------------------------------ - - @web.middleware - async def cors_middleware(request: web.Request, handler): - if request.method == "OPTIONS": - response = web.Response(status=200) - else: - response = await handler(request) - response.headers["Access-Control-Allow-Origin"] = "*" - response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS" - response.headers["Access-Control-Allow-Headers"] = "Content-Type" - return response - - # ------------------------------------------------------------------ - # Assemble and run - # ------------------------------------------------------------------ - - app = web.Application(middlewares=[cors_middleware]) - app.router.add_routes(routes) - - logger.info("Starting web inspector on port %d", port) - web.run_app(app, host="0.0.0.0", port=port, print=lambda _: None, access_log=None) +__all__ = ["run_web_server"] diff --git a/mimir/adapters/web/state.py b/mimir/adapters/web/state.py new file mode 100644 index 0000000..cd94da5 --- /dev/null +++ b/mimir/adapters/web/state.py @@ -0,0 +1,15 @@ +"""State for the read-only web inspector adapter.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from mimir.runtime import QueryRuntime + + +@dataclass +class WebServerState: + runtime: QueryRuntime + + def current_graph(self): + return self.runtime.graph diff --git a/mimir/container.py b/mimir/container.py index eeac665..4a7b9f0 100644 --- a/mimir/container.py +++ b/mimir/container.py @@ -21,6 +21,7 @@ def __init__(self, config: MimirConfig) -> None: self.config = config self._graph = None # lazy loaded self._watcher = None # lazy, created on demand + self._repo_sync = None # Infrastructure ------------------------------------------------ @@ -42,8 +43,12 @@ def __init__(self, config: MimirConfig) -> None: from mimir.infra.stores.sqlite_session import SqliteSessionStore self.session_store = SqliteSessionStore(config.session_dir / "sessions.db") - # LLM client (used by the `ask` CLI command for interactive Q&A) - self.llm_client = self._build_llm_client() + # Feedback store — lives in the ignored session/ folder + from mimir.infra.stores.sqlite_feedback import SqliteFeedbackStore + self.feedback_store = SqliteFeedbackStore( + config.session_dir / "feedback.db", + smoothing=config.feedback.score_smoothing, + ) # Services ------------------------------------------------------ @@ -88,7 +93,7 @@ def __init__(self, config: MimirConfig) -> None: self.catalog = CatalogService(quality_service=self.quality, config=config) # Guardrails - from mimir.services.diff_analyzer import DiffAnalyzer + from mimir.services.guardrail import DiffAnalyzer self.diff_analyzer = DiffAnalyzer(parser=self.parser) from mimir.services.guardrail import GuardrailService @@ -101,7 +106,15 @@ def __init__(self, config: MimirConfig) -> None: from mimir.services.agent_policy import AgentPolicyService self.agent_policy = AgentPolicyService(impact_service=self.impact) + from mimir.services.feedback import FeedbackService + self.feedback = FeedbackService( + config=config, + feedback_store=self.feedback_store, + ) + self.temporal.set_quality_service(self.quality) + self.temporal.set_feedback_service(self.feedback) + self.session.set_feedback_service(self.feedback) def _build_embedder(self): model = self.config.embeddings.model @@ -117,14 +130,14 @@ def _build_embedder(self): ) except Exception as exc: logger.warning("Jina API embedder init failed (%s), falling back to local", exc) - # Default: run locally via sentence-transformers + # Default: run locally via ONNX Runtime from mimir.infra.embedders.local import LocalEmbedder model_name = model.removeprefix("local:") if model.startswith("local:") else model cache_dir = self.config.embeddings.cache_dir or str(self.config.session_dir / "models") logger.info("Using local embedder: %s (cache: %s)", model_name, cache_dir) return LocalEmbedder(model_name=model_name, cache_dir=cache_dir) else: - # Default: run locally via sentence-transformers + # Default: run locally via ONNX Runtime from mimir.infra.embedders.local import LocalEmbedder model_name = model.removeprefix("local:") if model.startswith("local:") else model cache_dir = self.config.embeddings.cache_dir or str(self.config.session_dir / "models") @@ -132,84 +145,24 @@ def _build_embedder(self): return LocalEmbedder(model_name=model_name, cache_dir=cache_dir) def _build_vector_store(self): - backend = self.config.vector_db.backend - if backend == "chroma": - from mimir.infra.vector_stores.chroma import ChromaVectorStore - return ChromaVectorStore( - persist_directory=self.config.vector_db.persist_directory - or str(self.config.session_dir / "chroma"), - ) - else: - from mimir.infra.vector_stores.numpy_store import NumpyVectorStore - return NumpyVectorStore() - - def _build_llm_client(self): - from mimir.infra.llm.litellm_client import LiteLlmClient - return LiteLlmClient( - model=self.config.llm.model, - max_concurrent=self.config.indexing.concurrency, - api_base=self.config.llm.api_base, - ) + from mimir.infra.vector_stores.numpy_store import NumpyVectorStore + return NumpyVectorStore() - def load_graph(self): + def load_graph(self, *, force_reload: bool = False): """Load the persisted graph and hydrate the vector store.""" - if self._graph is None: + if self._graph is None or force_reload: self._graph = self.graph_store.load() self._hydrate_vector_store(self._graph) return self._graph - def _hydrate_vector_store(self, graph) -> None: - """Populate the vector store from graph node embeddings. + def replace_graph(self, graph) -> None: + """Swap the in-memory graph cache for a fully built graph.""" + self._graph = graph - Upserts only the delta: ids present in the graph but missing from the - store. Persistent backends (Chroma) that already hold the HNSW index - on disk skip the work entirely on warm starts. ``upsert`` is - idempotent in every backend, so the delta optimization is purely a - speedup — correctness does not depend on it. - """ - from mimir.services.indexing import IndexingService - - ids: list[str] = [] - embeddings: list[list[float]] = [] - metadatas: list[dict] = [] - documents: list[str] = [] - - for node in graph.all_nodes(): - if node.embedding: - ids.append(node.id) - embeddings.append(node.embedding) - metadatas.append({ - "repo": node.repo, - "kind": node.kind.value, - "path": node.path or "", - "last_modified": node.last_modified or "", - "http_method": node.http_method or "", - "route_path": node.route_path or "", - }) - documents.append(IndexingService._embedding_text(node, graph)) - - if not ids: - return - - existing = self.vector_store.get_existing_ids(ids) - if len(existing) == len(ids): - logger.info( - "Vector store up to date (%d embeddings) — skipping hydrate", len(ids), - ) - return - - missing_indices = [i for i, vec_id in enumerate(ids) if vec_id not in existing] - self.vector_store.upsert( - ids=[ids[i] for i in missing_indices], - embeddings=[embeddings[i] for i in missing_indices], - metadatas=[metadatas[i] for i in missing_indices], - documents=[documents[i] for i in missing_indices], - ) - logger.info( - "Hydrated vector store with %d new embeddings (%d already present)", - len(missing_indices), - len(existing), - ) + def _hydrate_vector_store(self, graph) -> None: + """Populate the vector store from graph node embeddings.""" + from mimir.services.hydration import hydrate_vector_store + hydrate_vector_store(graph, self.vector_store) def clear_data(self, *, graph: bool = True, sessions: bool = True) -> dict: """Delete all locally stored data. @@ -233,9 +186,6 @@ def clear_data(self, *, graph: bool = True, sessions: bool = True) -> dict: self._graph = None # invalidate in-memory cache cleared.append("graph") - # Reset the vector store through its live client so file handles stay valid. - # We must NOT use shutil.rmtree() here while the store's SQLite client is open, - # because deleting chroma files under an active handle puts SQLite into readonly mode. self.vector_store.reset() cleared.append("vector_store") @@ -261,6 +211,14 @@ def watcher(self): ) return self._watcher + @property + def repo_sync(self): + """Lazy-create the repo sync service.""" + if self._repo_sync is None: + from mimir.services.repo_sync import RepoSyncService + self._repo_sync = RepoSyncService(self.config) + return self._repo_sync + def warmup(self) -> None: """Eagerly load the embedding model so the first query is fast.""" if hasattr(self.embedder, '_ensure_model'): @@ -274,3 +232,4 @@ def close(self) -> None: self._watcher.stop() self.graph_store.close() self.session_store.close() + self.feedback_store.close() diff --git a/mimir/domain/catalog.py b/mimir/domain/catalog.py index 7a6b278..1105585 100644 --- a/mimir/domain/catalog.py +++ b/mimir/domain/catalog.py @@ -8,9 +8,19 @@ from __future__ import annotations from dataclasses import dataclass, field +from enum import Enum, unique from typing import Any +@unique +class DriftStatus(str, Enum): + """Status of a dependency drift entry.""" + + CONFIRMED = "confirmed" + MISSING_IN_CODE = "missing_in_code" + UNDECLARED_IN_CATALOG = "undeclared_in_catalog" + + @dataclass(frozen=True) class CatalogApi: """A discovered API endpoint in the code graph.""" @@ -154,13 +164,13 @@ class DriftEntry: """A single dependency drift finding.""" dependency: str - status: str # "confirmed" | "missing_in_code" | "undeclared_in_catalog" + status: DriftStatus evidence: tuple[dict[str, str], ...] = () def to_dict(self) -> dict[str, Any]: return { "dependency": self.dependency, - "status": self.status, + "status": self.status.value, "evidence": list(self.evidence), } diff --git a/mimir/domain/config.py b/mimir/domain/config.py index 6e0ef82..6bee28b 100644 --- a/mimir/domain/config.py +++ b/mimir/domain/config.py @@ -8,14 +8,23 @@ import logging from dataclasses import dataclass, field +from enum import Enum, unique from pathlib import Path -from typing import Literal, Optional +from typing import Optional from mimir.domain.errors import ConfigError logger = logging.getLogger(__name__) +@unique +class SummaryMode(str, Enum): + """How Mimir generates per-node summaries during indexing.""" + + NONE = "none" + HEURISTIC = "heuristic" + + # --------------------------------------------------------------------------- # Sub-configs # --------------------------------------------------------------------------- @@ -25,12 +34,34 @@ class RepoConfig: name: str path: Path language_hint: Optional[str] = None + clone_url: Optional[str] = None + branch: str = "main" + webhook_repo: Optional[str] = None def __post_init__(self) -> None: - if not self.path.is_dir(): + if not self.path.is_dir() and not self.clone_url: raise ConfigError( f"Repo '{self.name}' path does not exist or is not a directory: {self.path}" ) + if not self.branch.strip(): + raise ConfigError(f"Repo '{self.name}' branch must not be empty") + + +@dataclass(frozen=True) +class AdminConfig: + webhook_secret_env: Optional[str] = None + admin_token_env: Optional[str] = None + mirrors_dir: Optional[str] = None + enable_repo_sync: bool = False + job_history_limit: int = 200 + + def __post_init__(self) -> None: + if self.enable_repo_sync and not self.webhook_secret_env: + raise ConfigError("admin.webhook_secret_env is required when enable_repo_sync = true") + if self.admin_token_env is not None and not self.admin_token_env.strip(): + raise ConfigError("admin.admin_token_env must not be empty") + if self.job_history_limit <= 0: + raise ConfigError("admin.job_history_limit must be positive") @dataclass(frozen=True) @@ -42,7 +73,7 @@ class CrossRepoConfig: @dataclass(frozen=True) class IndexingConfig: - summary_mode: Literal["none", "heuristic"] = "heuristic" + summary_mode: SummaryMode = SummaryMode.HEURISTIC excluded_patterns: list[str] = field(default_factory=lambda: [ "*.test.*", "*.spec.*", "__pycache__", "node_modules", ".git", "venv", ".venv", "dist", "build", ".tox", ".mypy_cache", ".pytest_cache", @@ -51,21 +82,18 @@ class IndexingConfig: concurrency: int = 10 def __post_init__(self) -> None: - if self.summary_mode not in ("none", "heuristic"): - raise ConfigError(f"Invalid summary_mode: {self.summary_mode!r}") + # Coerce string input (e.g. from TOML) into SummaryMode enum + if not isinstance(self.summary_mode, SummaryMode): + try: + object.__setattr__(self, "summary_mode", SummaryMode(self.summary_mode)) + except ValueError as exc: + raise ConfigError(f"Invalid summary_mode: {self.summary_mode!r}") from exc if self.max_file_size_kb <= 0: raise ConfigError("max_file_size_kb must be positive") if self.concurrency <= 0: raise ConfigError("concurrency must be positive") -@dataclass(frozen=True) -class LlmConfig: - model: str = "claude-haiku-4-5-20251001" - api_key_env: Optional[str] = None - api_base: Optional[str] = None - - @dataclass(frozen=True) class EmbeddingConfig: model: str = "jina-embeddings-v2-base-code" @@ -81,12 +109,6 @@ def __post_init__(self) -> None: raise ConfigError("embedding max_concurrent_batches must be >= 1") -@dataclass(frozen=True) -class VectorDbConfig: - backend: Literal["chroma", "numpy"] = "chroma" - persist_directory: Optional[str] = None - - @dataclass(frozen=True) class RetrievalConfig: default_beam_width: int = 3 @@ -117,6 +139,25 @@ class SessionConfig: topic_tracking_alpha: float = 0.3 +@dataclass(frozen=True) +class FeedbackConfig: + """Configuration for the retrieval feedback loop.""" + + enabled: bool = True + implicit_signals: bool = True + implicit_positive_weight: float = 0.3 + implicit_negative_weight: float = 0.5 + score_smoothing: int = 2 + + def __post_init__(self) -> None: + if self.score_smoothing < 1: + raise ConfigError("feedback.score_smoothing must be >= 1") + if not 0.0 <= self.implicit_positive_weight <= 1.0: + raise ConfigError("feedback.implicit_positive_weight must be between 0.0 and 1.0") + if not 0.0 <= self.implicit_negative_weight <= 1.0: + raise ConfigError("feedback.implicit_negative_weight must be between 0.0 and 1.0") + + @dataclass(frozen=True) class WatcherConfig: """File watcher configuration for live re-indexing.""" @@ -145,13 +186,13 @@ class MimirConfig: cross_repo: CrossRepoConfig = field(default_factory=CrossRepoConfig) indexing: IndexingConfig = field(default_factory=IndexingConfig) - llm: LlmConfig = field(default_factory=LlmConfig) embeddings: EmbeddingConfig = field(default_factory=EmbeddingConfig) - vector_db: VectorDbConfig = field(default_factory=VectorDbConfig) retrieval: RetrievalConfig = field(default_factory=RetrievalConfig) temporal: TemporalConfig = field(default_factory=TemporalConfig) session: SessionConfig = field(default_factory=SessionConfig) + feedback: FeedbackConfig = field(default_factory=FeedbackConfig) watcher: WatcherConfig = field(default_factory=WatcherConfig) + admin: AdminConfig = field(default_factory=AdminConfig) def __post_init__(self) -> None: if not self.repos: @@ -164,7 +205,7 @@ def __post_init__(self) -> None: # Layout: .mimir/ is split into two subfolders # project/ — shared data tracked in git (graph.db) # session/ — personal / derived data ignored by git - # (sessions.db, embedding model cache, chroma store) + # (sessions.db, embedding model cache) # ------------------------------------------------------------------ @property @@ -180,13 +221,13 @@ def session_dir(self) -> Path: @classmethod def load(cls, path: Path) -> MimirConfig: """Parse a ``mimir.toml`` file into a validated config.""" - import tomli + import tomllib if not path.is_file(): raise ConfigError(f"Config file not found: {path}") with open(path, "rb") as f: - raw = tomli.load(f) + raw = tomllib.load(f) try: repos = [ @@ -194,6 +235,9 @@ def load(cls, path: Path) -> MimirConfig: name=r["name"], path=path.parent.joinpath(Path(r["path"]).expanduser()).resolve(), language_hint=r.get("language_hint"), + clone_url=r.get("clone_url"), + branch=r.get("branch", "main"), + webhook_repo=r.get("webhook_repo"), ) for r in raw.get("repos", []) ] @@ -203,13 +247,6 @@ def load(cls, path: Path) -> MimirConfig: # Resolve relative paths in sub-configs against config file dir config_dir = path.parent - vector_db = _parse_section(VectorDbConfig, raw.get("vector_db", {})) - if vector_db.persist_directory and not Path(vector_db.persist_directory).is_absolute(): - object.__setattr__( - vector_db, "persist_directory", - str(config_dir.joinpath(vector_db.persist_directory).resolve()), - ) - embeddings = _parse_section(EmbeddingConfig, raw.get("embeddings", {})) if embeddings.cache_dir and not Path(embeddings.cache_dir).is_absolute(): object.__setattr__( @@ -217,18 +254,25 @@ def load(cls, path: Path) -> MimirConfig: str(config_dir.joinpath(embeddings.cache_dir).resolve()), ) + admin = _parse_section(AdminConfig, raw.get("admin", {})) + if admin.mirrors_dir and not Path(admin.mirrors_dir).is_absolute(): + object.__setattr__( + admin, "mirrors_dir", + str(config_dir.joinpath(admin.mirrors_dir).resolve()), + ) + return cls( repos=repos, data_dir=data_dir, cross_repo=_parse_section(CrossRepoConfig, raw.get("cross_repo", {})), indexing=_parse_section(IndexingConfig, raw.get("indexing", {})), - llm=_parse_section(LlmConfig, raw.get("llm", {})), embeddings=embeddings, - vector_db=vector_db, retrieval=_parse_section(RetrievalConfig, raw.get("retrieval", {})), temporal=_parse_section(TemporalConfig, raw.get("temporal", {})), session=_parse_section(SessionConfig, raw.get("session", {})), + feedback=_parse_section(FeedbackConfig, raw.get("feedback", {})), watcher=_parse_section(WatcherConfig, raw.get("watcher", {})), + admin=admin, ) except (KeyError, TypeError, ValueError) as exc: raise ConfigError(f"Invalid config: {exc}") from exc diff --git a/mimir/domain/errors.py b/mimir/domain/errors.py index a7496a5..08ab5b6 100644 --- a/mimir/domain/errors.py +++ b/mimir/domain/errors.py @@ -2,7 +2,7 @@ Every infrastructure adapter catches library-specific exceptions and re-raises as the appropriate Mimir error with context. The application layer never sees -``chromadb.errors.*`` or ``sqlite3.OperationalError``. +``sqlite3.OperationalError`` or library-specific errors. """ from __future__ import annotations @@ -33,13 +33,22 @@ class EmbeddingError(IndexingError): class StorageError(MimirError): - """Database read/write failure (SQLite, ChromaDB, etc.).""" + """Database read/write failure (SQLite, etc.).""" class RetrievalError(MimirError): """Failure during context assembly / search.""" +class NoActiveIndexError(RetrievalError): + """No published index version is active for query-serving operations.""" + + hint = "Run `mimir indexer run` first." + + def __init__(self) -> None: + super().__init__("No active index") + + class SessionError(MimirError): """Failure in session management.""" diff --git a/mimir/domain/feedback.py b/mimir/domain/feedback.py new file mode 100644 index 0000000..d12d828 --- /dev/null +++ b/mimir/domain/feedback.py @@ -0,0 +1,108 @@ +"""Feedback domain models — signals and aggregated scores for retrieval learning.""" + +from __future__ import annotations + +import uuid +from dataclasses import dataclass, field +from datetime import datetime, timezone +from enum import Enum +from typing import Optional + + +class FeedbackOutcome(str, Enum): + """Whether the retrieved context was helpful.""" + + POSITIVE = "positive" + NEGATIVE = "negative" + + +class FeedbackSource(str, Enum): + """How the feedback signal was generated.""" + + EXPLICIT = "explicit" + IMPLICIT = "implicit" + + +@dataclass +class FeedbackSignal: + """A single feedback event recorded against a set of retrieved nodes.""" + + id: str + node_ids: list[str] + outcome: FeedbackOutcome + source: FeedbackSource + session_id: Optional[str] = None + query: Optional[str] = None + weight: float = 1.0 + timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + + @staticmethod + def new( + node_ids: list[str], + outcome: FeedbackOutcome | str, + source: FeedbackSource | str, + *, + session_id: Optional[str] = None, + query: Optional[str] = None, + weight: float = 1.0, + ) -> FeedbackSignal: + return FeedbackSignal( + id=str(uuid.uuid4()), + node_ids=node_ids, + outcome=FeedbackOutcome(outcome), + source=FeedbackSource(source), + session_id=session_id, + query=query, + weight=weight, + ) + + def to_dict(self) -> dict: + return { + "id": self.id, + "node_ids": self.node_ids, + "outcome": self.outcome.value, + "source": self.source.value, + "session_id": self.session_id, + "query": self.query, + "weight": self.weight, + "timestamp": self.timestamp.isoformat(), + } + + @classmethod + def from_dict(cls, data: dict) -> FeedbackSignal: + return cls( + id=data["id"], + node_ids=data["node_ids"], + outcome=FeedbackOutcome(data["outcome"]), + source=FeedbackSource(data["source"]), + session_id=data.get("session_id"), + query=data.get("query"), + weight=data.get("weight", 1.0), + timestamp=datetime.fromisoformat(data["timestamp"]), + ) + + +@dataclass +class NodeFeedbackScore: + """Aggregated feedback score for a single node.""" + + node_id: str + positive_count: int = 0 + negative_count: int = 0 + score: float = 0.5 + + @staticmethod + def compute_score(positive: int, negative: int, smoothing: int = 2) -> float: + """Laplace-smoothed score: (pos + k) / (pos + neg + 2k). + + Starts at 0.5 (neutral), converges with evidence. + """ + return (positive + smoothing) / (positive + negative + 2 * smoothing) + + def to_dict(self) -> dict: + return { + "node_id": self.node_id, + "positive_count": self.positive_count, + "negative_count": self.negative_count, + "score": round(self.score, 4), + } diff --git a/mimir/domain/guardrails.py b/mimir/domain/guardrails.py index 9c794db..7b32dbd 100644 --- a/mimir/domain/guardrails.py +++ b/mimir/domain/guardrails.py @@ -37,6 +37,31 @@ class Severity(Enum): BLOCK = "block" # block + require human approval (via HEAD commit trailer) +@unique +class ApprovalStatus(str, Enum): + """Approval state for BLOCK-severity violations.""" + + APPROVED = "approved" + PENDING = "pending" + + +@unique +class CycleScope(str, Enum): + """Scope for cycle-detection rules.""" + + CROSS_REPO = "cross_repo" + INTRA_REPO = "intra_repo" + + +@unique +class CouplingMetric(str, Enum): + """Coupling metrics for metric-threshold rules.""" + + AFFERENT_COUPLING = "afferent_coupling" + EFFERENT_COUPLING = "efferent_coupling" + INSTABILITY = "instability" + + # --------------------------------------------------------------------------- # Rule # --------------------------------------------------------------------------- @@ -86,7 +111,12 @@ class Violation: evidence: tuple[str, ...] = () file_path: str | None = None suggested_fix: str | None = None - approval_status: str | None = None # "approved", "pending", or None + approval_status: ApprovalStatus | None = None + + def __post_init__(self) -> None: + # Coerce string input into ApprovalStatus enum + if self.approval_status is not None and not isinstance(self.approval_status, ApprovalStatus): + object.__setattr__(self, "approval_status", ApprovalStatus(self.approval_status)) def to_dict(self) -> dict[str, Any]: d: dict[str, Any] = { @@ -99,7 +129,7 @@ def to_dict(self) -> dict[str, Any]: "suggested_fix": self.suggested_fix, } if self.approval_status is not None: - d["approval_status"] = self.approval_status + d["approval_status"] = self.approval_status.value return d @@ -144,9 +174,9 @@ def format_for_llm(self) -> str: parts.append("") for v in self.violations: sev_label = v.severity.value.upper() - if v.approval_status == "approved": + if v.approval_status is ApprovalStatus.APPROVED: sev_label = "BLOCK - APPROVED" - elif v.approval_status == "pending": + elif v.approval_status is ApprovalStatus.PENDING: sev_label = "BLOCK - PENDING" parts.append(f"### [{sev_label}] {v.rule_id}") parts.append(f"**Rule:** {v.rule_description}") diff --git a/mimir/domain/index_state.py b/mimir/domain/index_state.py new file mode 100644 index 0000000..1632d41 --- /dev/null +++ b/mimir/domain/index_state.py @@ -0,0 +1,57 @@ +"""Domain records for published index versions and indexer jobs.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone +from enum import Enum, unique +from typing import Optional + + +def utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +@unique +class IndexJobKind(str, Enum): + FULL = "full" + INCREMENTAL = "incremental" + SYNC = "sync" + + +@unique +class IndexJobStatus(str, Enum): + QUEUED = "queued" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + + +@dataclass(frozen=True) +class IndexVersion: + version: str + graph_path: str + active: bool = False + node_count: int = 0 + edge_count: int = 0 + repo_commits: dict[str, str] = field(default_factory=dict) + schema_version: int = 1 + embedding_model: Optional[str] = None + embedding_dim: Optional[int] = None + config_hash: Optional[str] = None + created_by: Optional[str] = None + created_at: str = field(default_factory=utc_now_iso) + activated_at: Optional[str] = None + + +@dataclass +class IndexJob: + id: str + kind: IndexJobKind + status: IndexJobStatus = IndexJobStatus.QUEUED + repo: Optional[str] = None + commit_sha: Optional[str] = None + error: Optional[str] = None + result: dict = field(default_factory=dict) + created_at: str = field(default_factory=utc_now_iso) + updated_at: str = field(default_factory=utc_now_iso) diff --git a/mimir/domain/models.py b/mimir/domain/models.py index 9444257..a9895b6 100644 --- a/mimir/domain/models.py +++ b/mimir/domain/models.py @@ -8,7 +8,7 @@ from __future__ import annotations import json -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from enum import Enum, unique from typing import Any, Optional @@ -202,6 +202,14 @@ def to_dict(self) -> dict[str, Any]: "co_retrieved_with": self.co_retrieved_with, } + def clone(self) -> Node: + """Return a detached copy safe for request-scoped mutations.""" + return replace( + self, + embedding=list(self.embedding) if self.embedding is not None else None, + co_retrieved_with=dict(self.co_retrieved_with), + ) + @classmethod def from_dict(cls, data: dict[str, Any]) -> Node: """Deserialise from a dictionary.""" diff --git a/mimir/domain/workspace.py b/mimir/domain/workspace.py index 751d5a9..e94a63f 100644 --- a/mimir/domain/workspace.py +++ b/mimir/domain/workspace.py @@ -32,9 +32,9 @@ def _load_raw(self) -> dict: """Load and return the raw TOML dict, or an empty dict if not found.""" if not self._path.exists(): return {} - import tomli + import tomllib with open(self._path, "rb") as f: - return tomli.load(f) + return tomllib.load(f) def list(self) -> dict[str, Path]: """Return all registered workspaces as {name: config_path}.""" diff --git a/mimir/infra/embedders/local.py b/mimir/infra/embedders/local.py index e54da6d..a44aaaa 100644 --- a/mimir/infra/embedders/local.py +++ b/mimir/infra/embedders/local.py @@ -1,84 +1,180 @@ -"""Local embedder using sentence-transformers (zero-cost, offline).""" +"""Local embedder running sentence-transformers models via ONNX Runtime (zero-cost, offline). + +Loads the ONNX export that sentence-transformers model repos ship under +``onnx/model.onnx`` and reproduces the sentence-transformers pipeline +(tokenize → transformer → pooling → optional normalize) from the repo's own +``modules.json`` / ``1_Pooling/config.json``. No torch required. +""" from __future__ import annotations import asyncio +import json import logging import os +from pathlib import Path from typing import Optional +import numpy as np + from mimir.domain.errors import EmbeddingError logger = logging.getLogger(__name__) os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") -os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") -# HF_HUB_OFFLINE is set dynamically in _ensure_model after first download -for _noisy in ( - "sentence_transformers", - "sentence_transformers.models.transformer", - "huggingface_hub", - "huggingface_hub.utils._http", - "transformers", - "transformers.utils.loading_report", - "httpx", -): +for _noisy in ("huggingface_hub", "huggingface_hub.utils._http", "httpx"): logging.getLogger(_noisy).setLevel(logging.ERROR) +_MODEL_FILES = [ + "onnx/model.onnx", + "onnx/model.onnx_data", + "tokenizer.json", + "config.json", + "modules.json", + "sentence_bert_config.json", + "1_Pooling/config.json", +] + +# Texts per ONNX forward pass. Texts are length-sorted first so each chunk +# pads to a similar length. +_CHUNK_SIZE = 32 + + +def _repo_id(model_name: str) -> str: + """Map short names (``all-MiniLM-L6-v2``, ``jina-embeddings-v2-base-code``) to repo ids.""" + if "/" in model_name: + return model_name + owner = "jinaai" if model_name.startswith("jina-") else "sentence-transformers" + return f"{owner}/{model_name}" + class LocalEmbedder: - """Embedder backed by sentence-transformers, runs fully offline. + """Embedder for sentence-transformers models, runs fully offline on CPU. - Default model: ``all-MiniLM-L6-v2`` (384 dimensions, ~80MB). + Default model: ``all-MiniLM-L6-v2`` (384 dimensions, ~90MB). """ def __init__(self, model_name: str = "all-MiniLM-L6-v2", cache_dir: Optional[str] = None) -> None: self._model_name = model_name self._cache_dir = cache_dir - self._model: Optional[object] = None + self._session = None + self._tokenizer = None + self._input_names: set[str] = set() + self._pooling = "mean" + self._normalize = False self._dim: Optional[int] = None + def _download(self) -> Path: + from huggingface_hub import snapshot_download + + repo = _repo_id(self._model_name) + # Prefer local copies: the configured cache, then the default HF cache + # (where the Docker image pre-bakes the model). Download only if neither has it. + for cache_dir in dict.fromkeys([self._cache_dir, None]): + try: + path = Path(snapshot_download( + repo, allow_patterns=_MODEL_FILES, cache_dir=cache_dir, local_files_only=True, + )) + if (path / "onnx" / "model.onnx").is_file(): + return path + except Exception: + continue + logger.info("Model '%s' not cached — downloading for the first time...", repo) + path = Path(snapshot_download(repo, allow_patterns=_MODEL_FILES, cache_dir=self._cache_dir)) + if not (path / "onnx" / "model.onnx").is_file(): + raise EmbeddingError(f"Model '{repo}' has no ONNX export (onnx/model.onnx)") + return path + def _ensure_model(self) -> None: - if self._model is not None: + if self._session is not None: return try: - from sentence_transformers import SentenceTransformer + import onnxruntime as ort + from tokenizers import Tokenizer - # Allow first download, then enforce offline mode for subsequent loads - try: - os.environ["HF_HUB_OFFLINE"] = "1" - self._model = SentenceTransformer(self._model_name, cache_folder=self._cache_dir) - except OSError: - logger.info("Model '%s' not cached — downloading for the first time...", self._model_name) - os.environ.pop("HF_HUB_OFFLINE", None) - self._model = SentenceTransformer(self._model_name, cache_folder=self._cache_dir) - os.environ["HF_HUB_OFFLINE"] = "1" - - # Probe dimension quietly - test = self._model.encode(["test"], show_progress_bar=False) - self._dim = len(test[0]) - logger.info("Loaded local embedding model: %s (dim=%d)", self._model_name, self._dim) - except ImportError: - raise EmbeddingError( - "sentence-transformers not installed. " - "Install with: pip install sentence-transformers" + path = self._download() + + def _read(name: str) -> dict: + f = path / name + return json.loads(f.read_text()) if f.is_file() else {} + + modules = _read("modules.json") + pooling_cfg = _read("1_Pooling/config.json") + max_len = _read("sentence_bert_config.json").get("max_seq_length") or 512 + max_len = min(max_len, _read("config.json").get("max_position_embeddings") or max_len) + + if pooling_cfg.get("pooling_mode_cls_token"): + self._pooling = "cls" + elif pooling_cfg.get("pooling_mode_max_tokens"): + self._pooling = "max" + else: + self._pooling = "mean" + self._normalize = any(m.get("type", "").endswith("Normalize") for m in modules) + + tokenizer = Tokenizer.from_file(str(path / "tokenizer.json")) + tokenizer.enable_truncation(max_length=max_len) + pad = tokenizer.padding or {} + tokenizer.enable_padding( + pad_id=pad.get("pad_id", 0), pad_token=pad.get("pad_token", "[PAD]"), ) + self._tokenizer = tokenizer + + opts = ort.SessionOptions() + opts.log_severity_level = 3 + self._session = ort.InferenceSession( + str(path / "onnx" / "model.onnx"), opts, providers=["CPUExecutionProvider"], + ) + self._input_names = {i.name for i in self._session.get_inputs()} + + self._dim = len(self._encode(["test"])[0]) + logger.info("Loaded local embedding model: %s (dim=%d)", self._model_name, self._dim) + except EmbeddingError: + raise except Exception as exc: + self._session = None raise EmbeddingError(f"Failed to load model '{self._model_name}': {exc}") from exc + def _encode(self, texts: list[str]) -> np.ndarray: + order = sorted(range(len(texts)), key=lambda i: len(texts[i])) + out = np.empty((len(texts), 0), dtype=np.float32) + for start in range(0, len(order), _CHUNK_SIZE): + idx = order[start:start + _CHUNK_SIZE] + encs = self._tokenizer.encode_batch([texts[i] for i in idx]) # type: ignore[union-attr] + mask = np.array([e.attention_mask for e in encs], dtype=np.int64) + feeds = { + "input_ids": np.array([e.ids for e in encs], dtype=np.int64), + "attention_mask": mask, + "token_type_ids": np.array([e.type_ids for e in encs], dtype=np.int64), + } + feeds = {k: v for k, v in feeds.items() if k in self._input_names} + tokens = self._session.run(None, feeds)[0] # type: ignore[union-attr] # (batch, seq, dim) + + if self._pooling == "cls": + pooled = tokens[:, 0] + elif self._pooling == "max": + pooled = np.where(mask[..., None] > 0, tokens, -1e9).max(axis=1) + else: + m = mask[..., None].astype(np.float32) + pooled = (tokens * m).sum(axis=1) / np.clip(m.sum(axis=1), 1e-9, None) + if self._normalize: + pooled = pooled / np.clip(np.linalg.norm(pooled, axis=1, keepdims=True), 1e-12, None) + + if out.shape[1] == 0: + out = np.empty((len(texts), pooled.shape[1]), dtype=np.float32) + out[idx] = pooled + return out + async def embed_batch(self, texts: list[str]) -> list[list[float]]: self._ensure_model() + if not texts: + return [] try: - # sentence-transformers' encode() is synchronous and CPU/GPU bound. - # Offload to a worker thread so callers (HTTP/MCP handlers running - # on the same loop) stay responsive during indexing. - embeddings = await asyncio.to_thread( - self._model.encode, # type: ignore[union-attr] - texts, - show_progress_bar=False, - ) - return [emb.tolist() for emb in embeddings] + # ONNX inference is synchronous and CPU bound. Offload to a worker + # thread so callers (HTTP/MCP handlers running on the same loop) + # stay responsive during indexing. + embeddings = await asyncio.to_thread(self._encode, texts) + return embeddings.tolist() except Exception as exc: raise EmbeddingError(f"Local embedding failed: {exc}") from exc diff --git a/mimir/infra/llm/litellm_client.py b/mimir/infra/llm/litellm_client.py deleted file mode 100644 index 5a99951..0000000 --- a/mimir/infra/llm/litellm_client.py +++ /dev/null @@ -1,82 +0,0 @@ -"""LiteLLM-based LLM client for summarization (llm mode only).""" - -from __future__ import annotations - -import asyncio -import logging -from typing import Optional - -from mimir.domain.errors import MimirError - -logger = logging.getLogger(__name__) - - -class LlmError(MimirError): - """LLM API call failed.""" - - -class LiteLlmClient: - """LLM client wrapping litellm for model-agnostic completions. - - Supports Claude, OpenAI, Ollama, and any OpenAI-compatible API. - """ - - def __init__( - self, - model: str = "claude-haiku-4-5-20251001", - max_concurrent: int = 10, - api_base: Optional[str] = None, - ) -> None: - self._model = model - self._api_base = api_base - self._semaphore = asyncio.Semaphore(max_concurrent) - - async def complete(self, prompt: str) -> str: - async with self._semaphore: - try: - import litellm - litellm.suppress_debug_info = True # STFU litellm - import logging - logging.getLogger("LiteLLM").setLevel(logging.WARNING) - - kwargs = { - "model": self._model, - "messages": [{"role": "user", "content": prompt}], - "max_tokens": 1024, - "temperature": 0.0, - } - if self._api_base: - kwargs["api_base"] = self._api_base - - response = await litellm.acompletion(**kwargs) - return response.choices[0].message.content or "" - except ImportError: - raise LlmError("litellm not installed. Install with: pip install litellm") - except Exception as exc: - raise LlmError(f"LLM completion failed: {exc}") from exc - - async def batch_complete( - self, - prompts: list[str], - *, - concurrency: int = 10, - ) -> list[str]: - """Send multiple prompts with concurrency control.""" - sem = asyncio.Semaphore(concurrency) - - async def _call(prompt: str) -> str: - async with sem: - return await self.complete(prompt) - - tasks = [_call(p) for p in prompts] - results = await asyncio.gather(*tasks, return_exceptions=True) - - output: list[str] = [] - for i, result in enumerate(results): - if isinstance(result, Exception): - logger.error("LLM call %d failed: %s", i, result) - output.append("") # graceful degradation - else: - output.append(result) - - return output diff --git a/mimir/infra/stores/sqlite_feedback.py b/mimir/infra/stores/sqlite_feedback.py new file mode 100644 index 0000000..a8667f4 --- /dev/null +++ b/mimir/infra/stores/sqlite_feedback.py @@ -0,0 +1,276 @@ +"""SQLite-backed feedback persistence.""" + +from __future__ import annotations + +import json +import logging +import sqlite3 +from itertools import combinations +from pathlib import Path +from typing import Optional + +from mimir.domain.errors import StorageError +from mimir.domain.feedback import FeedbackOutcome, FeedbackSignal, NodeFeedbackScore + +logger = logging.getLogger(__name__) + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS feedback_signals ( + id TEXT PRIMARY KEY, + session_id TEXT, + query TEXT, + node_ids TEXT NOT NULL, + outcome TEXT NOT NULL, + source TEXT NOT NULL, + weight REAL DEFAULT 1.0, + created_at TEXT DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS node_feedback_agg ( + node_id TEXT PRIMARY KEY, + positive_count INTEGER DEFAULT 0, + negative_count INTEGER DEFAULT 0, + score REAL DEFAULT 0.5, + updated_at TEXT +); + +CREATE TABLE IF NOT EXISTS pair_feedback_agg ( + node_a TEXT NOT NULL, + node_b TEXT NOT NULL, + co_positive INTEGER DEFAULT 0, + co_negative INTEGER DEFAULT 0, + score REAL DEFAULT 0.5, + PRIMARY KEY (node_a, node_b) +); + +CREATE INDEX IF NOT EXISTS idx_feedback_session ON feedback_signals(session_id); +CREATE INDEX IF NOT EXISTS idx_feedback_created ON feedback_signals(created_at); +CREATE INDEX IF NOT EXISTS idx_pair_node_a ON pair_feedback_agg(node_a); +""" + +#: Signals older than this many days are purged on startup. +_EXPIRY_DAYS = 90 + +#: Laplace smoothing parameter for score computation. +_DEFAULT_SMOOTHING = 2 + + +class SqliteFeedbackStore: + """SQLite persistence for retrieval feedback signals and aggregated scores.""" + + def __init__(self, db_path: Path, *, smoothing: int = _DEFAULT_SMOOTHING) -> None: + self._db_path = db_path + self._smoothing = smoothing + db_path.parent.mkdir(parents=True, exist_ok=True) + try: + self._conn = sqlite3.connect(str(db_path)) + self._conn.execute("PRAGMA journal_mode=WAL") + self._conn.executescript(_SCHEMA) + self._conn.commit() + self._purge_expired() + except sqlite3.Error as exc: + raise StorageError(f"Failed to init feedback store: {exc}") from exc + logger.info("Feedback store initialised at %s", db_path) + + def _purge_expired(self) -> None: + try: + cur = self._conn.execute( + "DELETE FROM feedback_signals WHERE created_at < datetime('now', ?)", + (f"-{_EXPIRY_DAYS} days",), + ) + if cur.rowcount > 0: + self._conn.commit() + logger.info( + "Purged %d expired feedback signals (older than %d days)", + cur.rowcount, + _EXPIRY_DAYS, + ) + except sqlite3.Error: + pass + + def record(self, signal: FeedbackSignal) -> None: + """Persist a feedback signal and incrementally update aggregated scores.""" + try: + self._conn.execute( + "INSERT OR REPLACE INTO feedback_signals " + "(id, session_id, query, node_ids, outcome, source, weight, created_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ( + signal.id, + signal.session_id, + signal.query, + json.dumps(signal.node_ids), + signal.outcome, + signal.source, + signal.weight, + signal.timestamp.isoformat(), + ), + ) + self._update_node_aggregates(signal) + self._update_pair_aggregates(signal) + self._conn.commit() + except sqlite3.Error as exc: + raise StorageError(f"Failed to record feedback: {exc}") from exc + + def _update_node_aggregates(self, signal: FeedbackSignal) -> None: + is_positive = signal.outcome is FeedbackOutcome.POSITIVE + for node_id in signal.node_ids: + self._conn.execute( + "INSERT INTO node_feedback_agg (node_id, positive_count, negative_count, score, updated_at) " + "VALUES (?, ?, ?, ?, datetime('now')) " + "ON CONFLICT(node_id) DO UPDATE SET " + "positive_count = positive_count + ?, " + "negative_count = negative_count + ?, " + "updated_at = datetime('now')", + ( + node_id, + 1 if is_positive else 0, + 0 if is_positive else 1, + NodeFeedbackScore.compute_score( + 1 if is_positive else 0, + 0 if is_positive else 1, + self._smoothing, + ), + 1 if is_positive else 0, + 0 if is_positive else 1, + ), + ) + # Recompute score from actual counts + cur = self._conn.execute( + "SELECT positive_count, negative_count FROM node_feedback_agg WHERE node_id = ?", + (node_id,), + ) + row = cur.fetchone() + if row: + score = NodeFeedbackScore.compute_score(row[0], row[1], self._smoothing) + self._conn.execute( + "UPDATE node_feedback_agg SET score = ? WHERE node_id = ?", + (score, node_id), + ) + + def _update_pair_aggregates(self, signal: FeedbackSignal) -> None: + if len(signal.node_ids) < 2: + return + is_positive = signal.outcome is FeedbackOutcome.POSITIVE + for a, b in combinations(sorted(signal.node_ids), 2): + self._conn.execute( + "INSERT INTO pair_feedback_agg (node_a, node_b, co_positive, co_negative, score) " + "VALUES (?, ?, ?, ?, ?) " + "ON CONFLICT(node_a, node_b) DO UPDATE SET " + "co_positive = co_positive + ?, " + "co_negative = co_negative + ?", + ( + a, b, + 1 if is_positive else 0, + 0 if is_positive else 1, + NodeFeedbackScore.compute_score( + 1 if is_positive else 0, + 0 if is_positive else 1, + self._smoothing, + ), + 1 if is_positive else 0, + 0 if is_positive else 1, + ), + ) + # Recompute pair score + cur = self._conn.execute( + "SELECT co_positive, co_negative FROM pair_feedback_agg " + "WHERE node_a = ? AND node_b = ?", + (a, b), + ) + row = cur.fetchone() + if row: + score = NodeFeedbackScore.compute_score(row[0], row[1], self._smoothing) + self._conn.execute( + "UPDATE pair_feedback_agg SET score = ? WHERE node_a = ? AND node_b = ?", + (score, a, b), + ) + + def get_node_scores(self, node_ids: list[str]) -> dict[str, NodeFeedbackScore]: + if not node_ids: + return {} + placeholders = ",".join("?" for _ in node_ids) + try: + cur = self._conn.execute( + f"SELECT node_id, positive_count, negative_count, score " + f"FROM node_feedback_agg WHERE node_id IN ({placeholders})", + node_ids, + ) + return { + row[0]: NodeFeedbackScore( + node_id=row[0], + positive_count=row[1], + negative_count=row[2], + score=row[3], + ) + for row in cur.fetchall() + } + except sqlite3.Error as exc: + raise StorageError(f"Failed to get node scores: {exc}") from exc + + def get_pair_scores(self, node_id: str, candidate_ids: list[str]) -> dict[str, float]: + if not candidate_ids: + return {} + results: dict[str, float] = {} + try: + for cid in candidate_ids: + a, b = sorted([node_id, cid]) + cur = self._conn.execute( + "SELECT score FROM pair_feedback_agg WHERE node_a = ? AND node_b = ?", + (a, b), + ) + row = cur.fetchone() + if row: + results[cid] = row[0] + return results + except sqlite3.Error as exc: + raise StorageError(f"Failed to get pair scores: {exc}") from exc + + def list_signals( + self, + session_id: Optional[str] = None, + limit: int = 100, + ) -> list[FeedbackSignal]: + try: + if session_id: + cur = self._conn.execute( + "SELECT id, session_id, query, node_ids, outcome, source, weight, created_at " + "FROM feedback_signals WHERE session_id = ? " + "ORDER BY created_at DESC LIMIT ?", + (session_id, limit), + ) + else: + cur = self._conn.execute( + "SELECT id, session_id, query, node_ids, outcome, source, weight, created_at " + "FROM feedback_signals ORDER BY created_at DESC LIMIT ?", + (limit,), + ) + return [ + FeedbackSignal.from_dict({ + "id": row[0], + "session_id": row[1], + "query": row[2], + "node_ids": json.loads(row[3]), + "outcome": row[4], + "source": row[5], + "weight": row[6], + "timestamp": row[7], + }) + for row in cur.fetchall() + ] + except sqlite3.Error as exc: + raise StorageError(f"Failed to list signals: {exc}") from exc + + def clear(self) -> None: + """Delete all feedback data.""" + try: + self._conn.execute("DELETE FROM feedback_signals") + self._conn.execute("DELETE FROM node_feedback_agg") + self._conn.execute("DELETE FROM pair_feedback_agg") + self._conn.commit() + logger.info("Feedback store cleared") + except sqlite3.Error as exc: + raise StorageError(f"Failed to clear feedback store: {exc}") from exc + + def close(self) -> None: + self._conn.close() diff --git a/mimir/infra/stores/sqlite_index_jobs.py b/mimir/infra/stores/sqlite_index_jobs.py new file mode 100644 index 0000000..455939d --- /dev/null +++ b/mimir/infra/stores/sqlite_index_jobs.py @@ -0,0 +1,196 @@ +"""SQLite-backed durable indexer jobs.""" + +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path +from typing import Optional +from uuid import uuid4 + +from mimir.domain.errors import StorageError +from mimir.domain.index_state import IndexJob, IndexJobKind, IndexJobStatus, utc_now_iso + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS index_jobs ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + repo TEXT, + commit_sha TEXT, + status TEXT NOT NULL, + error TEXT, + result TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_index_jobs_status ON index_jobs(status); +CREATE INDEX IF NOT EXISTS idx_index_jobs_created ON index_jobs(created_at); +""" + + +class SqliteIndexJobStore: + def __init__(self, db_path: Path) -> None: + self._db_path = db_path + db_path.parent.mkdir(parents=True, exist_ok=True) + try: + self._conn = sqlite3.connect(str(db_path)) + self._conn.execute("PRAGMA journal_mode=WAL") + self._conn.executescript(_SCHEMA) + self._conn.commit() + except sqlite3.Error as exc: + raise StorageError(f"Failed to initialise index job store: {exc}") from exc + + def enqueue(self, kind: IndexJobKind, *, repo: str | None = None, commit_sha: str | None = None) -> IndexJob: + existing = self._find_queued(kind, repo) + if existing is not None: + if commit_sha: + existing.commit_sha = commit_sha + self._update(existing) + return existing + + now = utc_now_iso() + job = IndexJob( + id=f"job-{uuid4().hex[:12]}", + kind=kind, + repo=repo, + commit_sha=commit_sha, + created_at=now, + updated_at=now, + ) + try: + self._conn.execute( + "INSERT INTO index_jobs " + "(id, kind, repo, commit_sha, status, error, result, created_at, updated_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + job.id, + job.kind.value, + job.repo, + job.commit_sha, + job.status.value, + job.error, + json.dumps(job.result), + job.created_at, + job.updated_at, + ), + ) + self._conn.commit() + return job + except sqlite3.Error as exc: + raise StorageError(f"Failed to enqueue index job: {exc}") from exc + + def claim_next(self) -> Optional[IndexJob]: + try: + cur = self._conn.execute( + "SELECT id, kind, repo, commit_sha, status, error, result, created_at, updated_at " + "FROM index_jobs WHERE status = ? ORDER BY created_at ASC LIMIT 1", + (IndexJobStatus.QUEUED.value,), + ) + row = cur.fetchone() + if row is None: + return None + job = self._row_to_job(row) + job.status = IndexJobStatus.RUNNING + job.updated_at = utc_now_iso() + self._update(job) + return job + except sqlite3.Error as exc: + raise StorageError(f"Failed to claim index job: {exc}") from exc + + def complete(self, job_id: str, result: dict) -> None: + self._set_terminal(job_id, IndexJobStatus.COMPLETED, result=result, error=None) + + def fail(self, job_id: str, error: str) -> None: + self._set_terminal(job_id, IndexJobStatus.FAILED, result={}, error=error) + + def get(self, job_id: str) -> Optional[IndexJob]: + try: + cur = self._conn.execute( + "SELECT id, kind, repo, commit_sha, status, error, result, created_at, updated_at " + "FROM index_jobs WHERE id = ?", + (job_id,), + ) + row = cur.fetchone() + return self._row_to_job(row) if row else None + except sqlite3.Error as exc: + raise StorageError(f"Failed to read index job: {exc}") from exc + + def list_jobs(self, status: IndexJobStatus | None = None, limit: int = 100) -> list[IndexJob]: + try: + if status is None: + cur = self._conn.execute( + "SELECT id, kind, repo, commit_sha, status, error, result, created_at, updated_at " + "FROM index_jobs ORDER BY created_at DESC LIMIT ?", + (limit,), + ) + else: + cur = self._conn.execute( + "SELECT id, kind, repo, commit_sha, status, error, result, created_at, updated_at " + "FROM index_jobs WHERE status = ? ORDER BY created_at DESC LIMIT ?", + (status.value, limit), + ) + return [self._row_to_job(row) for row in cur.fetchall()] + except sqlite3.Error as exc: + raise StorageError(f"Failed to list index jobs: {exc}") from exc + + def _find_queued(self, kind: IndexJobKind, repo: str | None) -> Optional[IndexJob]: + cur = self._conn.execute( + "SELECT id, kind, repo, commit_sha, status, error, result, created_at, updated_at " + "FROM index_jobs WHERE kind = ? AND status = ? AND (repo IS ? OR repo = ?) " + "ORDER BY created_at DESC LIMIT 1", + (kind.value, IndexJobStatus.QUEUED.value, repo, repo), + ) + row = cur.fetchone() + return self._row_to_job(row) if row else None + + def _set_terminal( + self, + job_id: str, + status: IndexJobStatus, + *, + result: dict, + error: str | None, + ) -> None: + try: + self._conn.execute( + "UPDATE index_jobs SET status = ?, result = ?, error = ?, updated_at = ? WHERE id = ?", + (status.value, json.dumps(result), error, utc_now_iso(), job_id), + ) + self._conn.commit() + except sqlite3.Error as exc: + raise StorageError(f"Failed to update index job: {exc}") from exc + + def _update(self, job: IndexJob) -> None: + self._conn.execute( + "UPDATE index_jobs SET kind = ?, repo = ?, commit_sha = ?, status = ?, error = ?, " + "result = ?, updated_at = ? WHERE id = ?", + ( + job.kind.value, + job.repo, + job.commit_sha, + job.status.value, + job.error, + json.dumps(job.result), + job.updated_at, + job.id, + ), + ) + self._conn.commit() + + @staticmethod + def _row_to_job(row) -> IndexJob: + return IndexJob( + id=row[0], + kind=IndexJobKind(row[1]), + repo=row[2], + commit_sha=row[3], + status=IndexJobStatus(row[4]), + error=row[5], + result=json.loads(row[6] or "{}"), + created_at=row[7], + updated_at=row[8], + ) + + def close(self) -> None: + self._conn.close() diff --git a/mimir/infra/stores/sqlite_index_metadata.py b/mimir/infra/stores/sqlite_index_metadata.py new file mode 100644 index 0000000..0dde17a --- /dev/null +++ b/mimir/infra/stores/sqlite_index_metadata.py @@ -0,0 +1,181 @@ +"""SQLite-backed metadata for published index versions.""" + +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path +from typing import Optional + +from mimir.domain.errors import StorageError +from mimir.domain.index_state import IndexVersion, utc_now_iso + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS index_versions ( + version TEXT PRIMARY KEY, + graph_path TEXT NOT NULL, + active INTEGER NOT NULL DEFAULT 0, + node_count INTEGER NOT NULL DEFAULT 0, + edge_count INTEGER NOT NULL DEFAULT 0, + repo_commits TEXT NOT NULL DEFAULT '{}', + schema_version INTEGER NOT NULL DEFAULT 1, + embedding_model TEXT, + config_hash TEXT, + embedding_dim INTEGER, + created_by TEXT, + created_at TEXT NOT NULL, + activated_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_index_versions_active ON index_versions(active); +CREATE INDEX IF NOT EXISTS idx_index_versions_created ON index_versions(created_at); +""" + + +class SqliteIndexMetadataStore: + def __init__(self, db_path: Path) -> None: + self._db_path = db_path + db_path.parent.mkdir(parents=True, exist_ok=True) + try: + self._conn = sqlite3.connect(str(db_path)) + self._conn.execute("PRAGMA journal_mode=WAL") + self._conn.executescript(_SCHEMA) + self._conn.commit() + self._ensure_columns() + except sqlite3.Error as exc: + raise StorageError(f"Failed to initialise index metadata store: {exc}") from exc + + def _ensure_columns(self) -> None: + cur = self._conn.execute("PRAGMA table_info(index_versions)") + existing = {row[1] for row in cur.fetchall()} + for col, defn in [ + ("schema_version", "INTEGER NOT NULL DEFAULT 1"), + ("embedding_model", "TEXT"), + ("embedding_dim", "INTEGER"), + ("config_hash", "TEXT"), + ("created_by", "TEXT"), + ]: + if col not in existing: + self._conn.execute(f"ALTER TABLE index_versions ADD COLUMN {col} {defn}") + self._conn.commit() + + def publish(self, version: IndexVersion, *, activate: bool = True) -> None: + try: + active = 1 if activate else int(version.active) + activated_at = utc_now_iso() if activate else version.activated_at + cur = self._conn.cursor() + if activate: + cur.execute("UPDATE index_versions SET active = 0") + cur.execute( + "INSERT OR REPLACE INTO index_versions " + "(version, graph_path, active, node_count, edge_count, repo_commits, " + "schema_version, embedding_model, embedding_dim, config_hash, created_by, " + "created_at, activated_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + version.version, + version.graph_path, + active, + version.node_count, + version.edge_count, + json.dumps(version.repo_commits), + version.schema_version, + version.embedding_model, + version.embedding_dim, + version.config_hash, + version.created_by, + version.created_at, + activated_at, + ), + ) + self._conn.commit() + except sqlite3.Error as exc: + self._conn.rollback() + raise StorageError(f"Failed to publish index version: {exc}") from exc + + def get_active(self) -> Optional[IndexVersion]: + try: + cur = self._conn.execute( + "SELECT version, graph_path, active, node_count, edge_count, repo_commits, " + "schema_version, embedding_model, embedding_dim, config_hash, created_by, " + "created_at, activated_at " + "FROM index_versions WHERE active = 1 ORDER BY activated_at DESC LIMIT 1" + ) + row = cur.fetchone() + return self._row_to_version(row) if row else None + except sqlite3.Error as exc: + raise StorageError(f"Failed to read active index version: {exc}") from exc + + def get(self, version: str) -> Optional[IndexVersion]: + try: + cur = self._conn.execute( + "SELECT version, graph_path, active, node_count, edge_count, repo_commits, " + "schema_version, embedding_model, embedding_dim, config_hash, created_by, " + "created_at, activated_at " + "FROM index_versions WHERE version = ?", + (version,), + ) + row = cur.fetchone() + return self._row_to_version(row) if row else None + except sqlite3.Error as exc: + raise StorageError(f"Failed to read index version: {exc}") from exc + + def list_versions(self, limit: int = 20) -> list[IndexVersion]: + try: + cur = self._conn.execute( + "SELECT version, graph_path, active, node_count, edge_count, repo_commits, " + "schema_version, embedding_model, embedding_dim, config_hash, created_by, " + "created_at, activated_at " + "FROM index_versions ORDER BY created_at DESC LIMIT ?", + (limit,), + ) + return [self._row_to_version(row) for row in cur.fetchall()] + except sqlite3.Error as exc: + raise StorageError(f"Failed to list index versions: {exc}") from exc + + def activate(self, version: str) -> Optional[IndexVersion]: + try: + existing = self.get(version) + if existing is None: + return None + activated_at = utc_now_iso() + cur = self._conn.cursor() + cur.execute("UPDATE index_versions SET active = 0") + cur.execute( + "UPDATE index_versions SET active = 1, activated_at = ? WHERE version = ?", + (activated_at, version), + ) + self._conn.commit() + return self.get(version) + except sqlite3.Error as exc: + self._conn.rollback() + raise StorageError(f"Failed to activate index version: {exc}") from exc + + def delete(self, version: str) -> None: + try: + self._conn.execute("DELETE FROM index_versions WHERE version = ?", (version,)) + self._conn.commit() + except sqlite3.Error as exc: + self._conn.rollback() + raise StorageError(f"Failed to delete index version: {exc}") from exc + + @staticmethod + def _row_to_version(row) -> IndexVersion: + return IndexVersion( + version=row[0], + graph_path=row[1], + active=bool(row[2]), + node_count=row[3], + edge_count=row[4], + repo_commits=json.loads(row[5] or "{}"), + schema_version=row[6], + embedding_model=row[7], + embedding_dim=row[8], + config_hash=row[9], + created_by=row[10], + created_at=row[11], + activated_at=row[12], + ) + + def close(self) -> None: + self._conn.close() diff --git a/mimir/infra/vector_stores/chroma.py b/mimir/infra/vector_stores/chroma.py deleted file mode 100644 index 85bc17a..0000000 --- a/mimir/infra/vector_stores/chroma.py +++ /dev/null @@ -1,124 +0,0 @@ -"""ChromaDB-backed vector store for production use.""" - -from __future__ import annotations - -import logging -from typing import Any, Optional - -from mimir.domain.errors import StorageError -from mimir.ports.vector_store import VectorSearchResult - -logger = logging.getLogger(__name__) - - -class ChromaVectorStore: - """ChromaDB vector store with HNSW indexing and metadata filtering.""" - - def __init__(self, persist_directory: Optional[str] = None, collection_name: str = "mimir") -> None: - try: - import chromadb - except ImportError: - raise StorageError( - "ChromaDB is not installed. Install with: pip install chromadb" - ) - - try: - if persist_directory: - self._client = chromadb.PersistentClient(path=persist_directory) - else: - self._client = chromadb.Client() - - self._collection = self._client.get_or_create_collection( - name=collection_name, - metadata={"hnsw:space": "cosine"}, - ) - logger.info( - "ChromaDB collection '%s' ready (%d vectors)", - collection_name, - self._collection.count(), - ) - except Exception as exc: - raise StorageError(f"Failed to initialise ChromaDB: {exc}") from exc - - def upsert( - self, - ids: list[str], - embeddings: list[list[float]], - metadatas: Optional[list[dict[str, Any]]] = None, - documents: Optional[list[str]] = None, - ) -> None: - try: - kwargs: dict[str, Any] = {"ids": ids, "embeddings": embeddings} - if metadatas: - # ChromaDB requires that all metadata values are str, int, float, or bool - kwargs["metadatas"] = [ - {k: v for k, v in m.items() if isinstance(v, (str, int, float, bool))} - for m in metadatas - ] - if documents: - kwargs["documents"] = documents - self._collection.upsert(**kwargs) - except Exception as exc: - raise StorageError(f"ChromaDB upsert failed: {exc}") from exc - - def search( - self, - query_embedding: list[float], - top_k: int = 10, - where: Optional[dict[str, Any]] = None, - ) -> list[VectorSearchResult]: - try: - kwargs: dict[str, Any] = { - "query_embeddings": [query_embedding], - "n_results": top_k, - } - if where: - kwargs["where"] = where - - results = self._collection.query(**kwargs) - - output: list[VectorSearchResult] = [] - if results["ids"] and results["ids"][0]: - ids = results["ids"][0] - distances = results["distances"][0] if results["distances"] else [0.0] * len(ids) - metadatas = results["metadatas"][0] if results["metadatas"] else [{}] * len(ids) - - for vec_id, dist, meta in zip(ids, distances, metadatas): - # ChromaDB cosine space returns distances in [0, 2]. - # Convert to similarity in [0, 1]: sim = 1 - (dist / 2) - score = max(0.0, 1.0 - dist / 2.0) - output.append(VectorSearchResult(id=vec_id, score=score, metadata=meta or {})) - - return output - except Exception as exc: - raise StorageError(f"ChromaDB search failed: {exc}") from exc - - def delete(self, ids: list[str]) -> None: - try: - self._collection.delete(ids=ids) - except Exception as exc: - raise StorageError(f"ChromaDB delete failed: {exc}") from exc - - def get_existing_ids(self, ids: list[str]) -> set[str]: - if not ids: - return set() - try: - # include=[] skips embeddings/metadata/documents — we only need the ids back. - result = self._collection.get(ids=ids, include=[]) - existing = result.get("ids") if isinstance(result, dict) else None - return set(existing) if existing else set() - except Exception as exc: - raise StorageError(f"ChromaDB get_existing_ids failed: {exc}") from exc - - def count(self) -> int: - return self._collection.count() - - def reset(self) -> None: - try: - self._client.delete_collection(self._collection.name) - self._collection = self._client.get_or_create_collection( - name=self._collection.name, - metadata={"hnsw:space": "cosine"}, - ) - except Exception as exc: - raise StorageError(f"ChromaDB reset failed: {exc}") from exc diff --git a/mimir/infra/vector_stores/numpy_store.py b/mimir/infra/vector_stores/numpy_store.py index 180362d..ef86bbe 100644 --- a/mimir/infra/vector_stores/numpy_store.py +++ b/mimir/infra/vector_stores/numpy_store.py @@ -1,8 +1,8 @@ """NumPy-based in-memory vector store. -Lightweight alternative to ChromaDB for development and small codebases. -Stores all vectors in memory using NumPy arrays. Supports metadata -filtering and cosine similarity search. +Stores all vectors in memory using NumPy arrays and is rebuilt from the +embeddings in graph.db on startup. Supports metadata filtering and exact +(brute-force) cosine similarity search. """ from __future__ import annotations @@ -27,6 +27,13 @@ def __init__(self) -> None: self._metadatas: list[dict[str, Any]] = [] self._documents: list[Optional[str]] = [] self._id_to_idx: dict[str, int] = {} + # Derived caches, invalidated on every mutation + self._unit: Optional[np.ndarray] = None # row-normalized embeddings + self._columns: dict[str, np.ndarray] = {} # metadata key -> values per row + + def _invalidate(self) -> None: + self._unit = None + self._columns.clear() def upsert( self, @@ -39,34 +46,57 @@ def upsert( raise StorageError( f"ids ({len(ids)}) and embeddings ({len(embeddings)}) length mismatch" ) + if not ids: + return metas = metadatas or [{}] * len(ids) docs = documents or [None] * len(ids) - new_vecs = np.array(embeddings, dtype=np.float32) + new_vecs = np.asarray(embeddings, dtype=np.float32) + # Updates are written in place; appends are collected and stacked once + # (row-by-row vstack would make bulk loads quadratic). + update_rows: list[int] = [] + update_idx: list[int] = [] + append_rows: list[int] = [] for i, vec_id in enumerate(ids): - if vec_id in self._id_to_idx: - # Update in-place - idx = self._id_to_idx[vec_id] - if self._embeddings is not None: - self._embeddings[idx] = new_vecs[i] - self._metadatas[idx] = metas[i] - self._documents[idx] = docs[i] - else: - # Append + idx = self._id_to_idx.get(vec_id) + if idx is None: idx = len(self._ids) self._ids.append(vec_id) self._metadatas.append(metas[i]) self._documents.append(docs[i]) self._id_to_idx[vec_id] = idx - - if self._embeddings is None: - self._embeddings = new_vecs[i : i + 1] + append_rows.append(i) + else: + self._metadatas[idx] = metas[i] + self._documents[idx] = docs[i] + if idx < self._stored_rows(): + update_idx.append(idx) + update_rows.append(i) else: - self._embeddings = np.vstack([self._embeddings, new_vecs[i : i + 1]]) + # Duplicate id earlier in this same batch — last write wins + append_rows[idx - self._stored_rows()] = i + + if update_idx: + self._embeddings[update_idx] = new_vecs[update_rows] # type: ignore[index] + if append_rows: + added = new_vecs[append_rows] + self._embeddings = added if self._embeddings is None else np.vstack([self._embeddings, added]) + self._invalidate() logger.debug("Upserted %d vectors (total: %d)", len(ids), len(self._ids)) + def _stored_rows(self) -> int: + return 0 if self._embeddings is None else len(self._embeddings) + + def _column(self, key: str) -> np.ndarray: + col = self._columns.get(key) + if col is None: + col = np.empty(len(self._metadatas), dtype=object) + col[:] = [m.get(key) for m in self._metadatas] + self._columns[key] = col + return col + def search( self, query_embedding: list[float], @@ -76,23 +106,22 @@ def search( if self._embeddings is None or len(self._ids) == 0: return [] - query = np.array(query_embedding, dtype=np.float32) - - # Cosine similarity - norms = np.linalg.norm(self._embeddings, axis=1) + query = np.asarray(query_embedding, dtype=np.float32) query_norm = np.linalg.norm(query) if query_norm == 0: return [] - similarities = self._embeddings @ query / (norms * query_norm + 1e-10) + # Cosine similarity against cached unit vectors + if self._unit is None: + norms = np.linalg.norm(self._embeddings, axis=1, keepdims=True) + self._unit = self._embeddings / (norms + 1e-10) + similarities = self._unit @ (query / query_norm) # Apply metadata filter if where: mask = np.ones(len(self._ids), dtype=bool) for key, value in where.items(): - for i, meta in enumerate(self._metadatas): - if meta.get(key) != value: - mask[i] = False + mask &= self._column(key) == value similarities = np.where(mask, similarities, -np.inf) # Top-k @@ -132,6 +161,7 @@ def delete(self, ids: list[str]) -> None: # Rebuild index self._id_to_idx = {vid: i for i, vid in enumerate(self._ids)} + self._invalidate() def get_existing_ids(self, ids: list[str]) -> set[str]: return {i for i in ids if i in self._id_to_idx} @@ -145,3 +175,4 @@ def reset(self) -> None: self._metadatas.clear() self._documents.clear() self._id_to_idx.clear() + self._invalidate() diff --git a/mimir/ports/__init__.py b/mimir/ports/__init__.py index 1fcf469..f318ee6 100644 --- a/mimir/ports/__init__.py +++ b/mimir/ports/__init__.py @@ -8,7 +8,6 @@ from mimir.ports.embedder import Embedder from mimir.ports.vector_store import VectorStore, VectorSearchResult from mimir.ports.graph_store import GraphStore -from mimir.ports.llm_client import LlmClient from mimir.ports.session_store import SessionStore __all__ = [ @@ -18,6 +17,5 @@ "VectorStore", "VectorSearchResult", "GraphStore", - "LlmClient", "SessionStore", ] diff --git a/mimir/ports/feedback_store.py b/mimir/ports/feedback_store.py new file mode 100644 index 0000000..bfea81a --- /dev/null +++ b/mimir/ports/feedback_store.py @@ -0,0 +1,39 @@ +"""FeedbackStore port — interface for persisting retrieval feedback.""" + +from __future__ import annotations + +from typing import Optional, Protocol, runtime_checkable + +from mimir.domain.feedback import FeedbackSignal, NodeFeedbackScore + + +@runtime_checkable +class FeedbackStore(Protocol): + """Interface for durable feedback storage. + + Implementation: ``SqliteFeedbackStore``. + """ + + def record(self, signal: FeedbackSignal) -> None: + """Persist a feedback signal and update aggregated scores.""" + ... + + def get_node_scores(self, node_ids: list[str]) -> dict[str, NodeFeedbackScore]: + """Return aggregated feedback scores for the given node IDs.""" + ... + + def get_pair_scores(self, node_id: str, candidate_ids: list[str]) -> dict[str, float]: + """Return co-success affinity scores between *node_id* and each candidate.""" + ... + + def list_signals( + self, + session_id: Optional[str] = None, + limit: int = 100, + ) -> list[FeedbackSignal]: + """Return recent feedback signals, optionally filtered by session.""" + ... + + def close(self) -> None: + """Release resources.""" + ... diff --git a/mimir/ports/index_job_store.py b/mimir/ports/index_job_store.py new file mode 100644 index 0000000..968e065 --- /dev/null +++ b/mimir/ports/index_job_store.py @@ -0,0 +1,38 @@ +"""IndexJobStore port for durable indexer work.""" + +from __future__ import annotations + +from typing import Optional, Protocol, runtime_checkable + +from mimir.domain.index_state import IndexJob, IndexJobKind, IndexJobStatus + + +@runtime_checkable +class IndexJobStore(Protocol): + def enqueue(self, kind: IndexJobKind, *, repo: str | None = None, commit_sha: str | None = None) -> IndexJob: + """Create or coalesce queued indexer work.""" + ... + + def claim_next(self) -> Optional[IndexJob]: + """Mark and return the next queued job as running.""" + ... + + def complete(self, job_id: str, result: dict) -> None: + """Mark a job as completed.""" + ... + + def fail(self, job_id: str, error: str) -> None: + """Mark a job as failed.""" + ... + + def get(self, job_id: str) -> Optional[IndexJob]: + """Return a job by id.""" + ... + + def list_jobs(self, status: IndexJobStatus | None = None, limit: int = 100) -> list[IndexJob]: + """Return recent jobs, optionally filtered by status.""" + ... + + def close(self) -> None: + """Release resources.""" + ... diff --git a/mimir/ports/index_metadata_store.py b/mimir/ports/index_metadata_store.py new file mode 100644 index 0000000..b77e2b8 --- /dev/null +++ b/mimir/ports/index_metadata_store.py @@ -0,0 +1,38 @@ +"""IndexMetadataStore port for published index versions.""" + +from __future__ import annotations + +from typing import Optional, Protocol, runtime_checkable + +from mimir.domain.index_state import IndexVersion + + +@runtime_checkable +class IndexMetadataStore(Protocol): + def publish(self, version: IndexVersion, *, activate: bool = True) -> None: + """Record a published index version and optionally make it active.""" + ... + + def get_active(self) -> Optional[IndexVersion]: + """Return the active published index version, if any.""" + ... + + def get(self, version: str) -> Optional[IndexVersion]: + """Return a published index version by id.""" + ... + + def list_versions(self, limit: int = 20) -> list[IndexVersion]: + """Return recently published index versions.""" + ... + + def activate(self, version: str) -> Optional[IndexVersion]: + """Make an existing published index version active.""" + ... + + def delete(self, version: str) -> None: + """Delete a published index version metadata row.""" + ... + + def close(self) -> None: + """Release resources.""" + ... diff --git a/mimir/ports/llm_client.py b/mimir/ports/llm_client.py deleted file mode 100644 index 01a4b1a..0000000 --- a/mimir/ports/llm_client.py +++ /dev/null @@ -1,46 +0,0 @@ -"""LlmClient port — interface for LLM completions (used in llm mode only).""" - -from __future__ import annotations - -from typing import Protocol, runtime_checkable - - -@runtime_checkable -class LlmClient(Protocol): - """Interface for LLM text completions. - - Implementation: ``LiteLlmClient``. - Only instantiated when ``summary_mode == "llm"``. - """ - - async def complete(self, prompt: str) -> str: - """Send a single completion request. - - Returns - ------- - str - The model's text response. - """ - ... - - async def batch_complete( - self, - prompts: list[str], - *, - concurrency: int = 10, - ) -> list[str]: - """Send multiple completion requests with concurrency control. - - Parameters - ---------- - prompts - List of prompt strings. - concurrency - Maximum number of concurrent API calls. - - Returns - ------- - list[str] - One response per prompt, in corresponding order. - """ - ... diff --git a/mimir/ports/vector_store.py b/mimir/ports/vector_store.py index 0de7ef9..79a77d2 100644 --- a/mimir/ports/vector_store.py +++ b/mimir/ports/vector_store.py @@ -19,7 +19,7 @@ class VectorSearchResult: class VectorStore(Protocol): """Interface for vector similarity search. - Implementations: ``ChromaVectorStore``, ``NumpyVectorStore``. + Implementation: ``NumpyVectorStore``. """ def upsert( @@ -76,7 +76,7 @@ def get_existing_ids(self, ids: list[str]) -> set[str]: """Return the subset of ``ids`` that already exist in the store. Used by the container's hydration path to skip re-upserting vectors - that persistent backends (e.g. Chroma) already hold on disk. + the store already holds. Implementations should probe only the given ids, not scan the whole store. """ diff --git a/mimir/runtime.py b/mimir/runtime.py new file mode 100644 index 0000000..507cc4f --- /dev/null +++ b/mimir/runtime.py @@ -0,0 +1,443 @@ +"""Runtime builders for indexing and query serving.""" + +from __future__ import annotations + +import asyncio +import hashlib +import logging +import shutil +from dataclasses import dataclass +from dataclasses import asdict, is_dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional + +from mimir.domain.config import MimirConfig, SummaryMode +from mimir.domain.errors import NoActiveIndexError, StorageError +from mimir.domain.graph import CodeGraph +from mimir.domain.index_state import IndexJob, IndexJobKind, IndexVersion +from mimir.infra.stores.sqlite_feedback import SqliteFeedbackStore +from mimir.infra.stores.sqlite_graph import SqliteGraphStore +from mimir.infra.stores.sqlite_index_jobs import SqliteIndexJobStore +from mimir.infra.stores.sqlite_index_metadata import SqliteIndexMetadataStore +from mimir.infra.stores.sqlite_session import SqliteSessionStore +from mimir.infra.vector_stores.numpy_store import NumpyVectorStore +from mimir.services.catalog import CatalogService +from mimir.services.feedback import FeedbackService +from mimir.services.agent_policy import AgentPolicyService +from mimir.services.guardrail import DiffAnalyzer, GuardrailService +from mimir.services.impact import ImpactService +from mimir.services.indexing import IndexingService +from mimir.services.quality import QualityService +from mimir.services.repo_sync import RepoSyncService +from mimir.services.retrieval import RetrievalService +from mimir.services.session import SessionService +from mimir.services.temporal import TemporalService +from mimir.services.write_context import WriteContextService + +logger = logging.getLogger(__name__) + + +def _version_id() -> str: + return datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S%f") + + +def _index_root(config: MimirConfig) -> Path: + return config.data_dir / "indexes" + + +def _config_hash(config: MimirConfig) -> str: + def normalize(value): + if is_dataclass(value): + return {k: normalize(v) for k, v in asdict(value).items()} + if isinstance(value, Path): + return str(value) + if isinstance(value, dict): + return {str(k): normalize(v) for k, v in sorted(value.items())} + if isinstance(value, list): + return [normalize(v) for v in value] + return value + + import json + + payload = json.dumps(normalize(config), sort_keys=True, default=str) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def _build_embedder(config: MimirConfig): + from mimir.infra.embedders.local import LocalEmbedder + from mimir.infra.embedders.jina import JinaEmbedder + + model = config.embeddings.model + if model.startswith("api:"): + return JinaEmbedder( + model=model.removeprefix("api:"), + api_key_env=config.embeddings.api_key_env, + batch_size=config.embeddings.batch_size, + ) + model_name = model.removeprefix("local:") if model.startswith("local:") else model + cache_dir = config.embeddings.cache_dir or str(config.session_dir / "models") + return LocalEmbedder(model_name=model_name, cache_dir=cache_dir) + + +def _build_vector_store(config: MimirConfig): + return NumpyVectorStore() + + +def _embedding_dim(graph: CodeGraph) -> Optional[int]: + for node in graph.all_nodes(): + if node.embedding: + return len(node.embedding) + return None + + +def _validate_graph_embeddings(graph: CodeGraph, expected_dim: Optional[int]) -> None: + if expected_dim is None: + return + for node in graph.all_nodes(): + if node.embedding and len(node.embedding) != expected_dim: + raise StorageError( + f"Index embedding dimension mismatch for {node.id}: " + f"expected {expected_dim}, got {len(node.embedding)}" + ) + + +@dataclass +class QueryView: + version: IndexVersion + graph: CodeGraph + vector_store: NumpyVectorStore + + +class RuntimeFactory: + """Build focused runtimes from a single config.""" + + def __init__(self, config: MimirConfig) -> None: + self.config = config + + def indexer(self) -> "IndexerRuntime": + return IndexerRuntime(self.config) + + def query(self) -> "QueryRuntime": + return QueryRuntime(self.config) + + +class IndexerRuntime: + """Owns repo sync, parsing, embedding, and index publication.""" + + def __init__(self, config: MimirConfig) -> None: + self.config = config + self.metadata_store = SqliteIndexMetadataStore(config.project_dir / "index_metadata.db") + self.job_store = SqliteIndexJobStore(config.project_dir / "index_jobs.db") + from mimir.infra.parsers.tree_sitter import TreeSitterParser + + self.parser = TreeSitterParser() + self.embedder = _build_embedder(config) + self.vector_store = _build_vector_store(config) + self.graph_store = SqliteGraphStore(config.project_dir / "graph.db") + self.indexing = IndexingService( + config=config, + parser=self.parser, + embedder=self.embedder, + vector_store=self.vector_store, + graph_store=self.graph_store, + ) + self.repo_sync = RepoSyncService(config) + + async def run_index( + self, + *, + clean: bool = False, + mode_override: Optional[SummaryMode | str] = None, + ) -> IndexVersion: + if clean: + self.graph_store.clear() + self.vector_store.reset() + graph = await self.indexing.index_all(mode_override=mode_override) + else: + graph, _ = await self.indexing.index_incremental(mode_override=mode_override) + return self.publish_graph(graph) + + async def sync_repo( + self, + repo_name: str, + *, + commit_sha: Optional[str] = None, + mode_override: Optional[SummaryMode | str] = None, + ) -> IndexVersion: + await self.repo_sync.sync_repo(repo_name, commit_sha=commit_sha) + graph = self._load_active_or_working_graph() + self.graph_store.save(graph) + await self.indexing.refresh_repo( + graph, + repo_name, + mode_override=mode_override, + ) + return self.publish_graph(graph) + + def enqueue(self, kind: IndexJobKind, *, repo: str | None = None, commit_sha: str | None = None) -> IndexJob: + return self.job_store.enqueue(kind, repo=repo, commit_sha=commit_sha) + + async def worker_once(self) -> Optional[IndexJob]: + job = self.job_store.claim_next() + if job is None: + return None + try: + if job.kind is IndexJobKind.FULL: + version = await self.run_index(clean=True) + elif job.kind is IndexJobKind.INCREMENTAL: + version = await self.run_index(clean=False) + elif job.kind is IndexJobKind.SYNC: + if not job.repo: + raise ValueError("sync job requires repo") + version = await self.sync_repo(job.repo, commit_sha=job.commit_sha) + else: + raise ValueError(f"Unknown index job kind: {job.kind}") + self.job_store.complete(job.id, {"version": version.version}) + except Exception as exc: + logger.exception("Index job failed: %s", job.id) + self.job_store.fail(job.id, str(exc)) + return self.job_store.get(job.id) + + async def worker_loop(self, *, poll_interval: float = 5.0) -> None: + while True: + job = await self.worker_once() + if job is None: + await asyncio.sleep(poll_interval) + + def publish_graph(self, graph: CodeGraph) -> IndexVersion: + version = _version_id() + version_dir = _index_root(self.config) / version + version_dir.mkdir(parents=True, exist_ok=True) + graph_path = version_dir / "graph.db" + store = SqliteGraphStore(graph_path) + try: + store.save(graph) + finally: + store.close() + + repo_commits = self.graph_store.get_all_repo_states() + index_version = IndexVersion( + version=version, + graph_path=str(graph_path), + node_count=graph.node_count, + edge_count=graph.edge_count, + repo_commits=repo_commits, + embedding_model=self.config.embeddings.model, + embedding_dim=_embedding_dim(graph), + config_hash=_config_hash(self.config), + created_by="mimir-indexer", + ) + self.metadata_store.publish(index_version, activate=True) + return self.metadata_store.get(version) or index_version + + def list_versions(self, *, limit: int = 20) -> list[IndexVersion]: + return self.metadata_store.list_versions(limit=limit) + + def activate_version(self, version: str) -> IndexVersion: + selected = self.metadata_store.get(version) + if selected is None: + raise ValueError(f"Unknown index version: {version}") + graph_path = Path(selected.graph_path) + if not graph_path.is_file(): + raise StorageError(f"Index graph not found: {graph_path}") + activated = self.metadata_store.activate(version) + if activated is None: + raise ValueError(f"Unknown index version: {version}") + return activated + + def prune_versions(self, *, keep: int = 5) -> list[str]: + if keep <= 0: + raise ValueError("keep must be positive") + versions = self.metadata_store.list_versions(limit=10_000) + active = self.metadata_store.get_active() + active_id = active.version if active else None + retained = {version.version for version in versions[:keep]} + if active_id: + retained.add(active_id) + + removed: list[str] = [] + for version in versions: + if version.version in retained: + continue + graph_path = Path(version.graph_path) + version_dir = graph_path.parent + if version_dir.is_dir() and version_dir.parent == _index_root(self.config): + shutil.rmtree(version_dir) + self.metadata_store.delete(version.version) + removed.append(version.version) + return removed + + def _load_active_or_working_graph(self) -> CodeGraph: + active = self.metadata_store.get_active() + if active is not None: + store = SqliteGraphStore(Path(active.graph_path)) + try: + return store.load() + finally: + store.close() + return self.graph_store.load() + + def close(self) -> None: + self.graph_store.close() + self.metadata_store.close() + self.job_store.close() + + +class QueryRuntime: + """Owns read-oriented query serving over the active published index.""" + + def __init__(self, config: MimirConfig) -> None: + self.config = config + self.metadata_store = SqliteIndexMetadataStore(config.project_dir / "index_metadata.db") + self.session_store = SqliteSessionStore(config.session_dir / "sessions.db") + self.feedback_store = SqliteFeedbackStore( + config.session_dir / "feedback.db", + smoothing=config.feedback.score_smoothing, + ) + self.quality = QualityService() + self.temporal = TemporalService(config=config) + self.write_context = WriteContextService() + self.impact = ImpactService() + from mimir.infra.parsers.tree_sitter import TreeSitterParser + self.parser = TreeSitterParser() + self.diff_analyzer = DiffAnalyzer(parser=self.parser) + self.guardrail = GuardrailService( + impact_service=self.impact, + quality_service=self.quality, + diff_analyzer=self.diff_analyzer, + ) + self.agent_policy = AgentPolicyService(impact_service=self.impact) + self.feedback = FeedbackService(config=config, feedback_store=self.feedback_store) + self.session = SessionService(config=config, session_store=self.session_store) + self.session.set_feedback_service(self.feedback) + self.temporal.set_quality_service(self.quality) + self.temporal.set_feedback_service(self.feedback) + self.catalog = CatalogService(quality_service=self.quality, config=config) + self._view: Optional[QueryView] = None + self._poll_task: Optional[asyncio.Task] = None + self._embedder = None + self._retrieval: Optional[RetrievalService] = None + self._active_vector_store = NumpyVectorStore() + self._load_active() + + @property + def active_version(self) -> Optional[IndexVersion]: + return self._view.version if self._view is not None else None + + @property + def graph(self) -> CodeGraph: + if self._view is None: + return CodeGraph() + return self._view.graph + + def require_active_version(self) -> IndexVersion: + if self._view is None: + raise NoActiveIndexError() + return self._view.version + + def require_graph(self) -> CodeGraph: + self.require_active_version() + return self.graph + + @property + def retrieval(self) -> RetrievalService: + self.require_active_version() + if self._retrieval is None: + self._retrieval = self._build_retrieval(self._active_vector_store) + return self._retrieval + + def _build_retrieval(self, vector_store: NumpyVectorStore) -> RetrievalService: + if self._embedder is None: + self._embedder = _build_embedder(self.config) + return RetrievalService( + config=self.config, + embedder=self._embedder, + vector_store=vector_store, + quality_service=self.quality, + temporal_service=self.temporal, + graph_store=None, + record_retrieval_metadata=False, + ) + + async def reload_if_changed(self) -> bool: + active = self.metadata_store.get_active() + current = self.active_version.version if self.active_version else None + if active is None or active.version == current: + return False + self._load_version(active) + return True + + def start_polling(self, *, interval: float = 10.0) -> None: + if self._poll_task is not None: + return + + async def _poll() -> None: + while True: + try: + await self.reload_if_changed() + except Exception: + logger.warning("Index version polling failed", exc_info=True) + await asyncio.sleep(interval) + + self._poll_task = asyncio.create_task(_poll()) + + async def stop_polling(self) -> None: + if self._poll_task is None: + return + self._poll_task.cancel() + try: + await self._poll_task + except asyncio.CancelledError: + pass + self._poll_task = None + + def status(self) -> dict: + version = self.active_version + return { + "active_version": version.version if version else None, + "graph_nodes": self.graph.node_count, + "graph_edges": self.graph.edge_count, + "repo_commits": version.repo_commits if version else {}, + "schema_version": version.schema_version if version else None, + "embedding_model": version.embedding_model if version else None, + "embedding_dim": version.embedding_dim if version else None, + "config_hash": version.config_hash if version else None, + "created_by": version.created_by if version else None, + "activated_at": version.activated_at if version else None, + } + + def _load_active(self) -> None: + active = self.metadata_store.get_active() + if active is not None: + self._load_version(active) + + def _load_version(self, version: IndexVersion) -> None: + graph_path = Path(version.graph_path) + if not graph_path.is_file(): + raise StorageError(f"Active index graph not found: {graph_path}") + if version.schema_version != 1: + raise StorageError(f"Unsupported index schema version: {version.schema_version}") + if version.embedding_model and version.embedding_model != self.config.embeddings.model: + raise StorageError( + f"Active index embedding model mismatch: expected " + f"{self.config.embeddings.model}, got {version.embedding_model}" + ) + store = SqliteGraphStore(Path(version.graph_path)) + try: + graph = store.load() + finally: + store.close() + _validate_graph_embeddings(graph, version.embedding_dim) + vector_store = NumpyVectorStore() + from mimir.services.hydration import hydrate_vector_store + + hydrate_vector_store(graph, vector_store) + self._view = QueryView(version=version, graph=graph, vector_store=vector_store) + self._active_vector_store = vector_store + self._retrieval = None + + def close(self) -> None: + self.metadata_store.close() + self.session_store.close() + self.feedback_store.close() diff --git a/mimir/services/agent_policy.py b/mimir/services/agent_policy.py index b1e96b2..1ec5deb 100644 --- a/mimir/services/agent_policy.py +++ b/mimir/services/agent_policy.py @@ -7,7 +7,9 @@ from __future__ import annotations import fnmatch +import logging from dataclasses import dataclass +from enum import Enum, unique from typing import Any, Optional from mimir.domain.graph import CodeGraph @@ -15,18 +17,34 @@ from mimir.domain.models import NodeKind from mimir.services.impact import ImpactService +logger = logging.getLogger(__name__) + # --------------------------------------------------------------------------- # Domain types (kept here to avoid circular imports with guardrails_config) # --------------------------------------------------------------------------- +@unique +class ReviewConditionType(str, Enum): + """Trigger kinds for agent-policy review conditions.""" + + IMPACT_COUNT = "impact_count" + CROSS_REPO = "cross_repo" + MODIFIES_API = "modifies_api" + + @dataclass(frozen=True) class ReviewCondition: """Condition that triggers human review requirement.""" - type: str # "impact_count", "cross_repo", "modifies_api" + type: ReviewConditionType threshold: Any = None + def __post_init__(self) -> None: + # Coerce string input into ReviewConditionType enum + if not isinstance(self.type, ReviewConditionType): + object.__setattr__(self, "type", ReviewConditionType(self.type)) + @dataclass(frozen=True) class AgentPolicy: @@ -42,8 +60,14 @@ def from_dict(cls, data: dict[str, Any]) -> AgentPolicy: """Create from a parsed YAML policy dict.""" conditions: list[ReviewCondition] = [] for rc in data.get("require_review_when", []): + raw_type = rc.get("type", "") + try: + condition_type = ReviewConditionType(raw_type) + except ValueError: + logger.warning("Unknown review condition type %r, skipping", raw_type) + continue conditions.append(ReviewCondition( - type=rc.get("type", ""), + type=condition_type, threshold=rc.get("threshold"), )) return cls( @@ -93,7 +117,7 @@ def check_review_required( reasons: list[str] = [] for condition in policy.require_review_conditions: - if condition.type == "impact_count": + if condition.type is ReviewConditionType.IMPACT_COUNT: threshold = condition.threshold or 15 for node_id in change.modified_nodes: result = self._impact.analyze(graph, node_id=node_id) @@ -104,13 +128,13 @@ def check_review_required( ) break - elif condition.type == "cross_repo": + elif condition.type is ReviewConditionType.CROSS_REPO: for edge in change.new_edges: if edge.is_cross_repo: reasons.append("Change introduces cross-repo dependencies") break - elif condition.type == "modifies_api": + elif condition.type is ReviewConditionType.MODIFIES_API: for node_id in change.modified_nodes: node = graph.get_node(node_id) if node and node.kind == NodeKind.API_ENDPOINT: diff --git a/mimir/services/catalog.py b/mimir/services/catalog.py index a0f7f50..8e766ea 100644 --- a/mimir/services/catalog.py +++ b/mimir/services/catalog.py @@ -23,6 +23,7 @@ CatalogServiceEntry, DriftEntry, DriftReport, + DriftStatus, ServiceDependency, TechStack, ) @@ -135,20 +136,20 @@ def detect_drift( for name in declared_names & actual_names: confirmed.append(DriftEntry( dependency=name, - status="confirmed", + status=DriftStatus.CONFIRMED, evidence=tuple(actual_deps[name]), )) for name in declared_names - actual_names: missing_in_code.append(DriftEntry( dependency=name, - status="missing_in_code", + status=DriftStatus.MISSING_IN_CODE, )) for name in actual_names - declared_names: undeclared.append(DriftEntry( dependency=name, - status="undeclared_in_catalog", + status=DriftStatus.UNDECLARED_IN_CATALOG, evidence=tuple(actual_deps[name]), )) diff --git a/mimir/services/feedback.py b/mimir/services/feedback.py new file mode 100644 index 0000000..0be91f1 --- /dev/null +++ b/mimir/services/feedback.py @@ -0,0 +1,143 @@ +"""Feedback service — explicit and implicit retrieval feedback loop. + +Records feedback signals against retrieved node sets and exposes +aggregated scores that feed into temporal reranking. +""" + +from __future__ import annotations + +import logging +import math +from typing import Optional + +from mimir.domain.config import MimirConfig +from mimir.domain.feedback import ( + FeedbackOutcome, + FeedbackSignal, + FeedbackSource, + NodeFeedbackScore, +) +from mimir.domain.session import Session +from mimir.ports.feedback_store import FeedbackStore + +logger = logging.getLogger(__name__) + + +class FeedbackService: + """Manages the retrieval feedback loop.""" + + def __init__(self, config: MimirConfig, feedback_store: FeedbackStore) -> None: + self._config = config + self._store = feedback_store + self._enabled = config.feedback.enabled + self._implicit_enabled = config.feedback.implicit_signals + self._implicit_pos_weight = config.feedback.implicit_positive_weight + self._implicit_neg_weight = config.feedback.implicit_negative_weight + + @property + def enabled(self) -> bool: + return self._enabled + + def record_explicit( + self, + node_ids: list[str], + outcome: FeedbackOutcome | str, + *, + session_id: Optional[str] = None, + query: Optional[str] = None, + ) -> FeedbackSignal: + """Record explicit feedback from an agent or user.""" + signal = FeedbackSignal.new( + node_ids=node_ids, outcome=outcome, source=FeedbackSource.EXPLICIT, + session_id=session_id, query=query, weight=1.0, + ) + if not self._enabled: + logger.debug("Feedback disabled, skipping explicit signal") + return signal + self._store.record(signal) + logger.info( + "Recorded explicit %s feedback for %d nodes (session=%s)", + outcome, len(node_ids), session_id, + ) + return signal + + def record_implicit(self, session: Session) -> Optional[FeedbackSignal]: + """Analyze session history and emit implicit feedback. + + Heuristics: + - Consecutive queries with high topic similarity (cosine > 0.7): + prior retrieval was insufficient -> negative signal. + - Topic shift (cosine < 0.3): prior retrieval resolved the + question -> positive signal. + """ + if not self._enabled or not self._implicit_enabled: + return None + history = session.query_history + if len(history) < 2: + return None + prev, curr = history[-2], history[-1] + if not prev.retrieved_node_ids: + return None + similarity = self._query_similarity(prev, curr) + if similarity is None: + return None + + if similarity > 0.7: + signal = FeedbackSignal.new( + node_ids=prev.retrieved_node_ids, + outcome=FeedbackOutcome.NEGATIVE, + source=FeedbackSource.IMPLICIT, + session_id=session.session_id, + query=prev.query, weight=self._implicit_neg_weight, + ) + self._store.record(signal) + logger.debug("Implicit negative: follow-up (sim=%.2f)", similarity) + return signal + + if similarity < 0.3: + signal = FeedbackSignal.new( + node_ids=prev.retrieved_node_ids, + outcome=FeedbackOutcome.POSITIVE, + source=FeedbackSource.IMPLICIT, + session_id=session.session_id, + query=prev.query, weight=self._implicit_pos_weight, + ) + self._store.record(signal) + logger.debug("Implicit positive: topic shift (sim=%.2f)", similarity) + return signal + + return None + + @staticmethod + def _query_similarity(prev, curr) -> Optional[float]: + """Cosine similarity between two query records' embeddings.""" + a, b = prev.query_embedding, curr.query_embedding + if a is None or b is None: + return None + dot = sum(x * y for x, y in zip(a, b)) + na = math.sqrt(sum(x * x for x in a)) + nb = math.sqrt(sum(x * x for x in b)) + if na == 0 or nb == 0: + return 0.0 + return dot / (na * nb) + + def get_feedback_weight(self, node_id: str) -> float: + """Return the feedback score for a single node (0.0-1.0, neutral=0.5).""" + if not self._enabled: + return 0.5 + scores = self._store.get_node_scores([node_id]) + return scores[node_id].score if node_id in scores else 0.5 + + def get_feedback_weights(self, node_ids: list[str]) -> dict[str, float]: + """Return feedback scores for multiple nodes. Missing nodes get 0.5.""" + if not self._enabled: + return {nid: 0.5 for nid in node_ids} + scores = self._store.get_node_scores(node_ids) + return {nid: scores[nid].score if nid in scores else 0.5 for nid in node_ids} + + def get_node_score(self, node_id: str) -> Optional[NodeFeedbackScore]: + """Return the full feedback score object for a node, or None.""" + if not self._enabled: + return None + scores = self._store.get_node_scores([node_id]) + return scores.get(node_id) diff --git a/mimir/services/guardrail/__init__.py b/mimir/services/guardrail/__init__.py new file mode 100644 index 0000000..ed5dce7 --- /dev/null +++ b/mimir/services/guardrail/__init__.py @@ -0,0 +1,16 @@ +"""Guardrail sub-package — architectural rule evaluation and reporting.""" + +from mimir.services.guardrail.service import GuardrailService, apply_approvals +from mimir.services.guardrail.diff_analyzer import DiffAnalyzer +from mimir.services.guardrail.report import GuardrailReporter, append_audit_entry +from mimir.services.guardrail.trailers import parse_approval_trailers, read_head_approval + +__all__ = [ + "GuardrailService", + "apply_approvals", + "DiffAnalyzer", + "GuardrailReporter", + "append_audit_entry", + "parse_approval_trailers", + "read_head_approval", +] diff --git a/mimir/services/diff_analyzer.py b/mimir/services/guardrail/diff_analyzer.py similarity index 94% rename from mimir/services/diff_analyzer.py rename to mimir/services/guardrail/diff_analyzer.py index 5e9601b..ef00635 100644 --- a/mimir/services/diff_analyzer.py +++ b/mimir/services/guardrail/diff_analyzer.py @@ -11,6 +11,7 @@ import re import tempfile from dataclasses import dataclass, field +from enum import Enum, unique from typing import Optional from mimir.domain.graph import CodeGraph @@ -25,13 +26,23 @@ # Internal types # --------------------------------------------------------------------------- +@unique +class FileDiffStatus(str, Enum): + """Change status for a file in a unified diff.""" + + ADDED = "added" + MODIFIED = "modified" + DELETED = "deleted" + RENAMED = "renamed" + + @dataclass class _FileDiff: """Parsed representation of changes to a single file.""" old_path: str new_path: str - status: str # "added", "modified", "deleted", "renamed" + status: FileDiffStatus = FileDiffStatus.MODIFIED hunks: list[tuple[int, int]] = field(default_factory=list) # (start, end) in new file added_lines: list[str] = field(default_factory=list) removed_lines: list[str] = field(default_factory=list) @@ -73,16 +84,16 @@ async def analyze(self, graph: CodeGraph, diff_text: str) -> ChangeSet: affected_files: list[str] = [] for fd in file_diffs: - path = fd.new_path if fd.status != "deleted" else fd.old_path + path = fd.new_path if fd.status is not FileDiffStatus.DELETED else fd.old_path affected_files.append(path) - if fd.status == "deleted": + if fd.status is FileDiffStatus.DELETED: # Find nodes in the deleted file and mark as modified file_nodes = self._find_nodes_in_file(graph, fd.old_path) modified_nodes.extend(n.id for n in file_nodes) continue - if fd.status == "added": + if fd.status is FileDiffStatus.ADDED: # Extract new symbols from added files extracted = await self._extract_new_symbols( fd.new_path, fd.added_lines, graph, @@ -131,7 +142,7 @@ def _parse_unified_diff(self, diff_text: str) -> list[_FileDiff]: current = _FileDiff( old_path=m.group(1), new_path=m.group(2), - status="modified", + status=FileDiffStatus.MODIFIED, ) current_line = 0 hunk_start = 0 @@ -142,18 +153,18 @@ def _parse_unified_diff(self, diff_text: str) -> list[_FileDiff]: # Binary file — skip if _BINARY_PATCH.match(line): - current.status = "modified" + current.status = FileDiffStatus.MODIFIED continue # New/deleted file markers if _NEW_FILE.match(line): - current.status = "added" + current.status = FileDiffStatus.ADDED continue if _DELETED_FILE.match(line): - current.status = "deleted" + current.status = FileDiffStatus.DELETED continue if _RENAME_FROM.match(line): - current.status = "renamed" + current.status = FileDiffStatus.RENAMED continue # Hunk header diff --git a/mimir/services/guardrail_report.py b/mimir/services/guardrail/report.py similarity index 96% rename from mimir/services/guardrail_report.py rename to mimir/services/guardrail/report.py index a5a0818..95875f4 100644 --- a/mimir/services/guardrail_report.py +++ b/mimir/services/guardrail/report.py @@ -11,7 +11,7 @@ from pathlib import Path from typing import Any, Optional -from mimir.domain.guardrails import GuardrailResult, Severity +from mimir.domain.guardrails import ApprovalStatus, GuardrailResult, Severity def _pending_rule_ids(result: GuardrailResult) -> list[str]: @@ -20,7 +20,7 @@ def _pending_rule_ids(result: GuardrailResult) -> list[str]: for v in result.violations: if ( v.severity == Severity.BLOCK - and v.approval_status == "pending" + and v.approval_status is ApprovalStatus.PENDING and v.rule_id not in seen ): seen.append(v.rule_id) @@ -58,9 +58,9 @@ def format_text(self, result: GuardrailResult) -> str: if result.violations: parts.append("") for v in result.violations: - if v.severity == Severity.BLOCK and v.approval_status == "approved": + if v.severity == Severity.BLOCK and v.approval_status is ApprovalStatus.APPROVED: severity_style = "[green]BLOCK (approved)[/green]" - elif v.severity == Severity.BLOCK and v.approval_status == "pending": + elif v.severity == Severity.BLOCK and v.approval_status is ApprovalStatus.PENDING: severity_style = "[yellow bold]BLOCK (pending approval)[/yellow bold]" else: severity_style = { @@ -110,9 +110,9 @@ def format_github_pr_comment(self, result: GuardrailResult) -> str: parts.append("|----------|------|---------|------|") for v in result.violations: - if v.severity == Severity.BLOCK and v.approval_status == "approved": + if v.severity == Severity.BLOCK and v.approval_status is ApprovalStatus.APPROVED: severity_badge = "✅ block (approved)" - elif v.severity == Severity.BLOCK and v.approval_status == "pending": + elif v.severity == Severity.BLOCK and v.approval_status is ApprovalStatus.PENDING: severity_badge = "⏳ block (pending)" else: severity_badge = { diff --git a/mimir/services/guardrail.py b/mimir/services/guardrail/service.py similarity index 93% rename from mimir/services/guardrail.py rename to mimir/services/guardrail/service.py index 44cd377..8fc7017 100644 --- a/mimir/services/guardrail.py +++ b/mimir/services/guardrail/service.py @@ -15,7 +15,10 @@ from mimir.domain.graph import CodeGraph from mimir.domain.guardrails import ( + ApprovalStatus, ChangeSet, + CouplingMetric, + CycleScope, GuardrailResult, Rule, RuleType, @@ -23,7 +26,7 @@ Violation, ) from mimir.domain.models import EdgeKind, NodeKind -from mimir.services.diff_analyzer import DiffAnalyzer +from mimir.services.guardrail.diff_analyzer import DiffAnalyzer from mimir.services.impact import ImpactService from mimir.services.quality import QualityService @@ -198,7 +201,11 @@ def _check_cycle_detection( self, graph: CodeGraph, change: ChangeSet, rule: Rule, ) -> list[Violation]: """Detect cycles introduced by the change.""" - scope = rule.config["scope"] + try: + scope = CycleScope(rule.config["scope"]) + except (KeyError, ValueError): + logger.warning("Rule %s has invalid cycle scope %r", rule.id, rule.config.get("scope")) + return [] edge_kinds_config = rule.config.get("edge_kinds", []) # Determine which edge kinds to include @@ -210,10 +217,10 @@ def _check_cycle_detection( except ValueError: pass else: - if scope == "cross_repo": - filter_kinds = set(EdgeKind.API_CALLS.value and { + if scope is CycleScope.CROSS_REPO: + filter_kinds = { EdgeKind.API_CALLS, EdgeKind.SHARED_LIB, EdgeKind.PROTO_DEFINES, - }) + } else: filter_kinds = {EdgeKind.IMPORTS} @@ -273,7 +280,11 @@ def _check_metric_threshold( self, graph: CodeGraph, change: ChangeSet, rule: Rule, ) -> list[Violation]: """Check coupling metrics against thresholds.""" - metric = rule.config["metric"] + try: + metric = CouplingMetric(rule.config["metric"]) + except (KeyError, ValueError): + logger.warning("Rule %s has invalid coupling metric %r", rule.id, rule.config.get("metric")) + return [] threshold = rule.config["threshold"] target_pattern = rule.config.get("target_pattern") @@ -302,11 +313,11 @@ def _check_metric_threshold( ca = len(incoming) # afferent coupling ce = len(outgoing) # efferent coupling - if metric == "afferent_coupling": + if metric is CouplingMetric.AFFERENT_COUPLING: value = ca - elif metric == "efferent_coupling": + elif metric is CouplingMetric.EFFERENT_COUPLING: value = ce - elif metric == "instability": + elif metric is CouplingMetric.INSTABILITY: value = ce / (ca + ce) if (ca + ce) > 0 else 0.0 else: continue @@ -317,7 +328,7 @@ def _check_metric_threshold( rule_description=rule.description, severity=rule.severity, message=( - f"{metric} for {node.name} is {value} " + f"{metric.value} for {node.name} is {value} " f"(threshold: {threshold})" ), evidence=( @@ -326,7 +337,7 @@ def _check_metric_threshold( f"efferent_coupling: {ce}", ), file_path=node.path, - suggested_fix=f"Reduce {metric} below {threshold} by refactoring dependencies.", + suggested_fix=f"Reduce {metric.value} below {threshold} by refactoring dependencies.", )) return violations @@ -454,11 +465,11 @@ def apply_approvals( if v.rule_id in effective_approved: new_violations.append( - dataclasses.replace(v, approval_status="approved") + dataclasses.replace(v, approval_status=ApprovalStatus.APPROVED) ) else: new_violations.append( - dataclasses.replace(v, approval_status="pending") + dataclasses.replace(v, approval_status=ApprovalStatus.PENDING) ) pending_count += 1 @@ -471,7 +482,7 @@ def apply_approvals( warning_count = sum(1 for v in new_violations if v.severity == Severity.WARNING) approved_count = sum( 1 for v in new_violations - if v.severity == Severity.BLOCK and v.approval_status == "approved" + if v.severity == Severity.BLOCK and v.approval_status is ApprovalStatus.APPROVED ) parts: list[str] = [] diff --git a/mimir/services/guardrail_trailers.py b/mimir/services/guardrail/trailers.py similarity index 100% rename from mimir/services/guardrail_trailers.py rename to mimir/services/guardrail/trailers.py diff --git a/mimir/services/hydration.py b/mimir/services/hydration.py new file mode 100644 index 0000000..967783a --- /dev/null +++ b/mimir/services/hydration.py @@ -0,0 +1,62 @@ +"""Vector store hydration — populates the vector store from graph node embeddings. + +Upserts only the delta: ids present in the graph but missing from the +store, so repeated calls (e.g. after a reload) skip vectors already +held. ``upsert`` is idempotent, so the delta optimization is purely a +speedup — correctness does not depend on it. +""" + +from __future__ import annotations + +import logging + +from mimir.ports.vector_store import VectorStore + +logger = logging.getLogger(__name__) + + +def hydrate_vector_store(graph, vector_store: VectorStore) -> None: + """Populate the vector store from graph node embeddings.""" + from mimir.services.indexing import IndexingService + + ids: list[str] = [] + embeddings: list[list[float]] = [] + metadatas: list[dict] = [] + documents: list[str] = [] + + for node in graph.all_nodes(): + if node.embedding: + ids.append(node.id) + embeddings.append(node.embedding) + metadatas.append({ + "repo": node.repo, + "kind": node.kind.value, + "path": node.path or "", + "last_modified": node.last_modified or "", + "http_method": node.http_method or "", + "route_path": node.route_path or "", + }) + documents.append(IndexingService._embedding_text(node, graph)) + + if not ids: + return + + existing = vector_store.get_existing_ids(ids) + if len(existing) == len(ids): + logger.info( + "Vector store up to date (%d embeddings) — skipping hydrate", len(ids), + ) + return + + missing_indices = [i for i, vec_id in enumerate(ids) if vec_id not in existing] + vector_store.upsert( + ids=[ids[i] for i in missing_indices], + embeddings=[embeddings[i] for i in missing_indices], + metadatas=[metadatas[i] for i in missing_indices], + documents=[documents[i] for i in missing_indices], + ) + logger.info( + "Hydrated vector store with %d new embeddings (%d already present)", + len(missing_indices), + len(existing), + ) diff --git a/mimir/services/indexing.py b/mimir/services/indexing.py deleted file mode 100644 index f1956a4..0000000 --- a/mimir/services/indexing.py +++ /dev/null @@ -1,1054 +0,0 @@ -"""Indexing service — orchestrates parsing, graph building, summarization, and embedding. - -This is the primary application service for Milestone 1+2. -It receives all infrastructure dependencies via constructor injection. -""" - -from __future__ import annotations - -import asyncio -import fnmatch -import logging -import os -import re -from datetime import datetime, timezone -from pathlib import Path -from typing import Callable, Optional - -from mimir.domain.config import MimirConfig -from mimir.domain.errors import ParsingError -from mimir.domain.graph import CodeGraph -from mimir.domain.models import Edge, EdgeKind, Node, NodeKind -from mimir.ports.embedder import Embedder -from mimir.ports.graph_store import GraphStore -from mimir.domain.lang import detect_language -from mimir.ports.parser import Parser, Symbol -from mimir.ports.vector_store import VectorStore -from mimir.services.graph_linker import ( - detect_api_contracts, - detect_inheritance, - detect_shared_imports, - normalize_route, - resolve_cross_file_refs, -) -from mimir.services.summarizer import generate_heuristic_summaries, heuristic_summary - -logger = logging.getLogger(__name__) - - -class IndexingService: - """Orchestrates the full indexing pipeline.""" - - def __init__( - self, - config: MimirConfig, - parser: Parser, - embedder: Embedder, - vector_store: VectorStore, - graph_store: GraphStore, - ) -> None: - self._config = config - self._parser = parser - self._embedder = embedder - self._vector_store = vector_store - self._graph_store = graph_store - - async def index_all(self, *, mode_override: Optional[str] = None) -> CodeGraph: - """Run the full indexing pipeline. - - 1. Parse all repos → build CodeGraph - 2. Cross-file symbol resolution (CALLS, USES_TYPE, INHERITS edges) - 3. Cross-repo link detection (API contracts, shared imports) - 4. Generate summaries (based on mode) - 5. Embed nodes - 6. Store in vector DB and SQLite - """ - mode = mode_override or self._config.indexing.summary_mode - logger.info("Starting full index — mode=%s, repos=%d", mode, len(self._config.repos)) - - graph = CodeGraph() - - # Phase 1: Parse all repos - for repo_config in self._config.repos: - logger.info("Indexing repo: %s (%s)", repo_config.name, repo_config.path) - await self._index_repo(graph, repo_config) - - # Phase 2: Cross-file symbol resolution - resolve_cross_file_refs(graph, self._parser) - - # Phase 3: Cross-repo link detection - if self._config.cross_repo.detect_api_contracts: - detect_api_contracts(graph) - if self._config.cross_repo.detect_shared_imports: - detect_shared_imports(graph) - - logger.info("Graph built: %s", graph.stats()) - - # Phase 4: Summarization - if mode == "heuristic": - generate_heuristic_summaries(graph) - - # Phase 5: Embedding - await self._embed_and_upsert(graph, mode, show_progress=True) - - # Phase 6: Persist - self._graph_store.save(graph) - - # Save commit hashes for incremental updates - for repo_config in self._config.repos: - try: - import git - repo = git.Repo(str(repo_config.path)) - commit_hash = repo.head.commit.hexsha - self._graph_store.save_repo_state(repo_config.name, commit_hash) - except Exception: - logger.debug("Could not read git commit for %s", repo_config.name) - - logger.info("Indexing complete: %d nodes, %d edges", graph.node_count, graph.edge_count) - return graph - - async def index_incremental(self, *, mode_override: Optional[str] = None) -> tuple[CodeGraph, dict]: - """Incremental index — only re-process files changed since the last commit. - - Flow: - 1. Load existing graph from storage - 2. For each repo, compute git diff against last-indexed commit - 3. Remove stale nodes (deleted & modified files) - 4. Re-parse only changed/added files - 5. Regenerate summaries & embeddings for affected nodes - 6. Persist delta to storage - - Returns (graph, report) where report is a dict summarising the changes. - """ - mode = mode_override or self._config.indexing.summary_mode - logger.info("Starting incremental index — mode=%s, repos=%d", mode, len(self._config.repos)) - - # Load existing graph - graph = self._graph_store.load() - if graph.node_count == 0: - logger.info("No existing graph found — falling back to full index") - return await self.index_all(mode_override=mode_override), { - "mode": "full_fallback", - "reason": "no existing graph", - } - - # Get stored commit hashes - stored_states = self._graph_store.get_all_repo_states() - - report: dict = { - "mode": "incremental", - "repos": {}, - } - - all_new_nodes: list[Node] = [] - all_new_edges: list[Edge] = [] - all_stale_ids: list[str] = [] - repos_needing_full: list = [] - - for repo_config in self._config.repos: - repo_name = repo_config.name - repo_path = Path(repo_config.path) - last_commit = stored_states.get(repo_name) - - if not last_commit: - logger.info("Repo %s: no previous commit — will full-index", repo_name) - repos_needing_full.append(repo_config) - report["repos"][repo_name] = {"status": "full_index", "reason": "first time"} - continue - - # Compute diff - try: - import git as gitmodule - repo = gitmodule.Repo(str(repo_path)) - current_commit = repo.head.commit.hexsha - except Exception as exc: - logger.warning("Cannot read git for %s: %s — skipping", repo_name, exc) - report["repos"][repo_name] = {"status": "skipped", "reason": str(exc)} - continue - - if current_commit == last_commit: - logger.info("Repo %s: no changes (still at %s)", repo_name, current_commit[:8]) - report["repos"][repo_name] = {"status": "up_to_date", "commit": current_commit[:8]} - continue - - # Get the actual diff - try: - diff = repo.commit(last_commit).diff(current_commit) - except Exception as exc: - logger.warning( - "Repo %s: diff failed (%s) — falling back to full index for this repo", - repo_name, exc, - ) - repos_needing_full.append(repo_config) - report["repos"][repo_name] = {"status": "full_index", "reason": f"diff failed: {exc}"} - continue - - # Categorise changed files - added_files: set[str] = set() - modified_files: set[str] = set() - deleted_files: set[str] = set() - - for d in diff: - if d.new_file: - if d.b_path: - added_files.add(d.b_path) - elif d.deleted_file: - if d.a_path: - deleted_files.add(d.a_path) - elif d.renamed_file: - if d.a_path: - deleted_files.add(d.a_path) - if d.b_path: - added_files.add(d.b_path) - else: - # Modified - if d.b_path: - modified_files.add(d.b_path) - - # Filter to only parseable files (skip binary, excluded, etc.) - files_to_remove = deleted_files | modified_files - files_to_parse = added_files | modified_files - - logger.info( - "Repo %s: %d added, %d modified, %d deleted (commit %s → %s)", - repo_name, - len(added_files), - len(modified_files), - len(deleted_files), - last_commit[:8], - current_commit[:8], - ) - - # Phase 1: Remove stale nodes from graph & store - if files_to_remove: - removed_ids = graph.remove_nodes_by_paths(repo_name, files_to_remove) - all_stale_ids.extend(removed_ids) - logger.info("Repo %s: removed %d stale nodes", repo_name, len(removed_ids)) - - # Phase 2: Re-parse changed/added files into the graph - files_parsed = 0 - symbols_parsed = 0 - for rel_path in sorted(files_to_parse): - file_path = str(repo_path / rel_path) - - # Skip excluded files - if self._is_excluded(os.path.basename(rel_path)): - continue - - # Skip files that don't exist (could be in gitignore or binary) - if not os.path.isfile(file_path): - continue - - # Check file size - try: - size_kb = os.path.getsize(file_path) / 1024 - if size_kb > self._config.indexing.max_file_size_kb: - continue - except OSError: - continue - - # Parse file - try: - symbols = await self._parser.parse_file( - file_path, repo_config.language_hint, - ) - except Exception as exc: - logger.warning("Parse failed for %s: %s", rel_path, exc) - continue - - if not symbols: - continue - - # Create file node - file_id = f"{repo_name}:{rel_path}" - file_node = Node( - id=file_id, - repo=repo_name, - kind=NodeKind.FILE, - name=os.path.basename(rel_path), - path=rel_path, - ) - graph.add_node(file_node) - all_new_nodes.append(file_node) - files_parsed += 1 - - # Link file to parent module/repo - rel_dir = os.path.dirname(rel_path) - parent_id = f"{repo_name}:{rel_dir}/" if rel_dir else f"{repo_name}:" - if graph.has_node(parent_id): - edge = Edge(source=parent_id, target=file_id, kind=EdgeKind.CONTAINS) - graph.add_edge(edge) - all_new_edges.append(edge) - - # Add symbol nodes - for sym in symbols: - node, edges = self._add_symbol_to_graph( - graph, sym, repo_name, rel_path, file_id, repo_path, - ) - all_new_nodes.append(node) - all_new_edges.extend(edges) - symbols_parsed += 1 - - # Update commit state - self._graph_store.save_repo_state(repo_name, current_commit) - - report["repos"][repo_name] = { - "status": "updated", - "commit": f"{last_commit[:8]} → {current_commit[:8]}", - "files_added": len(added_files), - "files_modified": len(modified_files), - "files_deleted": len(deleted_files), - "nodes_removed": len([i for i in all_stale_ids if i.startswith(repo_name + ":")]), - "files_parsed": files_parsed, - "symbols_parsed": symbols_parsed, - } - - # Phase 3: Full-index repos that had no prior commit - for repo_config in repos_needing_full: - # Remove existing nodes for this repo (if any orphans) - removed = graph.remove_nodes_by_repo(repo_config.name) - all_stale_ids.extend(removed) - # Re-index fully - await self._index_repo(graph, repo_config) - try: - import git as gitmodule - repo = gitmodule.Repo(str(repo_config.path)) - self._graph_store.save_repo_state(repo_config.name, repo.head.commit.hexsha) - except Exception: - pass - - # Phase 4: Re-resolve cross-file refs (on full graph) - resolve_cross_file_refs(graph, self._parser) - - # Phase 5: Re-detect cross-repo links (on full graph) - if self._config.cross_repo.detect_api_contracts: - detect_api_contracts(graph) - if self._config.cross_repo.detect_shared_imports: - detect_shared_imports(graph) - - # Phase 6: Summarisation for new/changed nodes only - if mode == "heuristic": - for node in all_new_nodes: - node.summary = heuristic_summary(node, graph) - - # Phase 7: Embed new/changed nodes only - if all_new_nodes: - await self._embed_and_upsert(graph, mode, nodes_to_embed=all_new_nodes) - - # Phase 8: Persist delta - if all_stale_ids: - self._graph_store.delete_nodes_by_ids(all_stale_ids) - self._vector_store.delete(all_stale_ids) - - if all_new_nodes or all_new_edges: - self._graph_store.save_partial(all_new_nodes, all_new_edges) - - # Also persist nodes from full-indexed repos - if repos_needing_full: - full_nodes = [] - full_edges = [] - for repo_config in repos_needing_full: - for n in graph.nodes_by_repo(repo_config.name): - full_nodes.append(n) - for e in graph.all_edges(): - src = graph.get_node(e.source) - tgt = graph.get_node(e.target) - if src and tgt and (src.repo == repo_config.name or tgt.repo == repo_config.name): - full_edges.append(e) - if full_nodes: - await self._embed_and_upsert(graph, mode, nodes_to_embed=full_nodes) - self._graph_store.save_partial(full_nodes, full_edges) - - total_removed = len(all_stale_ids) - total_added = len(all_new_nodes) - logger.info( - "Incremental index complete: -%d stale, +%d new nodes (graph total: %d nodes, %d edges)", - total_removed, total_added, graph.node_count, graph.edge_count, - ) - report["total_removed"] = total_removed - report["total_added"] = total_added - report["graph_nodes"] = graph.node_count - report["graph_edges"] = graph.edge_count - - return graph, report - - async def _index_repo(self, graph: CodeGraph, repo_config) -> None: - """Parse a single repository and add nodes/edges to the graph.""" - repo_name = repo_config.name - repo_path = Path(repo_config.path) - language = repo_config.language_hint - - # Create repo-level node - repo_node = Node( - id=f"{repo_name}:", - repo=repo_name, - kind=NodeKind.REPOSITORY, - name=repo_name, - path=str(repo_path), - ) - graph.add_node(repo_node) - - # Walk files — module nodes are created lazily so directories - # that contain no parseable code never appear in the graph. - modules_seen: dict[str, str] = {} # module path → node id - files_indexed = 0 - symbols_indexed = 0 - - def _ensure_module(rel_dir: str) -> str: - """Create module node (and ancestors) on demand, return its id.""" - if not rel_dir: - return f"{repo_name}:" - if rel_dir in modules_seen: - return modules_seen[rel_dir] - - # Ensure parent exists first - parent_dir = os.path.dirname(rel_dir) - parent_id = _ensure_module(parent_dir) - - module_id = f"{repo_name}:{rel_dir}/" - module_node = Node( - id=module_id, - repo=repo_name, - kind=NodeKind.MODULE, - name=os.path.basename(rel_dir), - path=rel_dir, - ) - graph.add_node(module_node) - modules_seen[rel_dir] = module_id - graph.add_edge(Edge( - source=parent_id, - target=module_id, - kind=EdgeKind.CONTAINS, - )) - return module_id - - for root, dirs, files in os.walk(str(repo_path)): - # Filter excluded directories - dirs[:] = [ - d for d in dirs - if not self._is_excluded(d) - ] - - rel_dir = os.path.relpath(root, str(repo_path)) - if rel_dir == ".": - rel_dir = "" - - for filename in files: - if self._is_excluded(filename): - continue - - file_path = os.path.join(root, filename) - rel_path = os.path.relpath(file_path, str(repo_path)) - - # Check file size - try: - size_kb = os.path.getsize(file_path) / 1024 - if size_kb > self._config.indexing.max_file_size_kb: - logger.debug("Skipping large file: %s (%.0f KB)", rel_path, size_kb) - continue - except OSError: - continue - - # Parse file - try: - symbols = await self._parser.parse_file(file_path, language) - except ParsingError as exc: - logger.warning("Parse failed: %s", exc) - continue - except Exception as exc: - logger.warning("Unexpected parse error for %s: %s", rel_path, exc) - continue - - if not symbols: - continue - - # Create file node - file_id = f"{repo_name}:{rel_path}" - file_node = Node( - id=file_id, - repo=repo_name, - kind=NodeKind.FILE, - name=filename, - path=rel_path, - ) - graph.add_node(file_node) - files_indexed += 1 - - # Link file to module/repo (creates module node if needed) - parent_id = _ensure_module(rel_dir) - graph.add_edge(Edge( - source=parent_id, - target=file_id, - kind=EdgeKind.CONTAINS, - )) - - # Add symbol nodes - for sym in symbols: - self._add_symbol_to_graph( - graph, sym, repo_name, rel_path, file_id, repo_path, - ) - symbols_indexed += 1 - - logger.info( - "Repo %s: %d files, %d symbols", - repo_name, files_indexed, symbols_indexed, - ) - - async def index_files( - self, - graph: CodeGraph, - repo_name: str, - repo_path: Path, - changed_files: set[str], - deleted_files: set[str], - language_hint: Optional[str] = None, - ) -> tuple[list[str], list[Node], list[Edge]]: - """Re-index specific files within a loaded graph (used by file watcher). - - This is a lightweight alternative to ``index_incremental`` that - operates on individual files without git diff. It never calls - the LLM — only heuristic summaries are used. - - Returns ``(removed_ids, new_nodes, new_edges)``. - """ - removed_ids: list[str] = [] - new_nodes: list[Node] = [] - new_edges: list[Edge] = [] - - # 1. Remove stale nodes for deleted + changed files - files_to_remove = deleted_files | changed_files - if files_to_remove: - removed_ids = graph.remove_nodes_by_paths(repo_name, files_to_remove) - - # 2. Re-parse changed files - for rel_path in sorted(changed_files): - file_path = str(repo_path / rel_path) - - if self._is_excluded(os.path.basename(rel_path)): - continue - if not os.path.isfile(file_path): - continue - - try: - size_kb = os.path.getsize(file_path) / 1024 - if size_kb > self._config.indexing.max_file_size_kb: - continue - except OSError: - continue - - try: - symbols = await self._parser.parse_file(file_path, language_hint) - except Exception as exc: - logger.warning("Watcher parse failed for %s: %s", rel_path, exc) - continue - - if not symbols: - continue - - # Create file node - file_id = f"{repo_name}:{rel_path}" - file_node = Node( - id=file_id, - repo=repo_name, - kind=NodeKind.FILE, - name=os.path.basename(rel_path), - path=rel_path, - ) - graph.add_node(file_node) - new_nodes.append(file_node) - - # Link file to parent module/repo - rel_dir = os.path.dirname(rel_path) - parent_id = f"{repo_name}:{rel_dir}/" if rel_dir else f"{repo_name}:" - if graph.has_node(parent_id): - edge = Edge(source=parent_id, target=file_id, kind=EdgeKind.CONTAINS) - graph.add_edge(edge) - new_edges.append(edge) - - # Add symbol nodes (lightweight — no CALLS/IMPORTS/API resolution) - for sym in symbols: - node, edges = self._add_symbol_to_graph( - graph, sym, repo_name, rel_path, file_id, repo_path, - resolve_edges=False, - ) - new_nodes.append(node) - new_edges.extend(edges) - - # 3. Affected-set cross-file resolution (only for new symbols) - new_symbol_nodes = [n for n in new_nodes if n.is_symbol] - if new_symbol_nodes and hasattr(self._parser, 'extract_identifiers'): - xref_edges = self._resolve_affected_refs(graph, new_symbol_nodes) - new_edges.extend(xref_edges) - - # 4. Heuristic summaries (never LLM) - for node in new_nodes: - node.summary = heuristic_summary(node, graph) - - # 5. Embed new nodes - if new_nodes: - await self._embed_and_upsert(graph, "heuristic", nodes_to_embed=new_nodes) - - logger.info( - "index_files: -%d removed, +%d nodes, +%d edges", - len(removed_ids), len(new_nodes), len(new_edges), - ) - return removed_ids, new_nodes, new_edges - - def _resolve_affected_refs( - self, graph: CodeGraph, new_symbols: list[Node], - ) -> list[Edge]: - """Cross-file resolution for only the affected symbols. - - Scans new symbols' code for references to existing symbols, - and scans existing symbols' code for references to new symbol names. - Much faster than full ``_resolve_cross_file_refs`` for single-file changes. - """ - from mimir.domain.lang import detect_language - - # Build full name → [node] index - name_index: dict[str, list[Node]] = {} - for node in graph.all_nodes(): - if node.is_symbol: - name_index.setdefault(node.name, []).append(node) - - ambiguous_names = { - name for name, nodes in name_index.items() - if len(nodes) > 20 - } - - new_edges: list[Edge] = [] - seen_edges: set[tuple[str, str, str]] = set() - - # Collect existing non-CONTAINS edges to avoid duplicates - for edge in graph.all_edges(): - if edge.kind != EdgeKind.CONTAINS: - seen_edges.add((edge.source, edge.target, edge.kind.value)) - - new_symbol_ids = {n.id for n in new_symbols} - new_symbol_names = {n.name for n in new_symbols} - - def _try_add_edge(source_id: str, target: Node, ident: str, inherits_names: set[str]) -> None: - if target.id == source_id: - return - if ident in inherits_names: - edge_kind = EdgeKind.INHERITS - elif target.kind in (NodeKind.CLASS, NodeKind.TYPE): - edge_kind = EdgeKind.USES_TYPE - else: - edge_kind = EdgeKind.CALLS - - edge_key = (source_id, target.id, edge_kind.value) - if edge_key in seen_edges: - return - seen_edges.add(edge_key) - - edge = Edge(source=source_id, target=target.id, kind=edge_kind) - graph.add_edge(edge) - new_edges.append(edge) - - # A. Scan new symbols → find what they reference - for node in new_symbols: - if not node.raw_code: - continue - lang = detect_language(node.path) if node.path else None - identifiers = self._parser.extract_identifiers( - node.raw_code, language=lang, file_path=node.path, - ) - inherits_names = detect_inheritance(node) - - for ident in identifiers: - if ident == node.name or ident in ambiguous_names: - continue - targets = name_index.get(ident) - if not targets: - continue - for target in targets: - _try_add_edge(node.id, target, ident, inherits_names) - - # B. Scan existing symbols → find references TO new symbol names - for node in graph.all_nodes(): - if not node.is_symbol or not node.raw_code: - continue - if node.id in new_symbol_ids: - continue # already handled above - - # Quick pre-filter: does raw_code contain any new symbol name? - if not any(name in node.raw_code for name in new_symbol_names if name not in ambiguous_names): - continue - - lang = detect_language(node.path) if node.path else None - identifiers = self._parser.extract_identifiers( - node.raw_code, language=lang, file_path=node.path, - ) - inherits_names = detect_inheritance(node) - - for ident in identifiers: - if ident not in new_symbol_names or ident in ambiguous_names: - continue - targets = name_index.get(ident) - if not targets: - continue - for target in targets: - if target.id not in new_symbol_ids: - continue # only add edges TO new symbols - _try_add_edge(node.id, target, ident, inherits_names) - - logger.info("Affected cross-file resolution: %d new edges", len(new_edges)) - return new_edges - - def _is_excluded(self, name: str) -> bool: - """Check if a file/dir name matches any exclusion pattern.""" - return any( - fnmatch.fnmatch(name, pattern) - for pattern in self._config.indexing.excluded_patterns - ) - - @staticmethod - def _map_symbol_kind(kind_str: str) -> NodeKind: - mapping = { - "function": NodeKind.FUNCTION, - "method": NodeKind.METHOD, - "class": NodeKind.CLASS, - "type": NodeKind.TYPE, - "constant": NodeKind.CONSTANT, - } - return mapping.get(kind_str, NodeKind.FUNCTION) - - def _add_symbol_to_graph( - self, - graph: CodeGraph, - sym: "Symbol", - repo_name: str, - rel_path: str, - file_id: str, - repo_path: Path, - *, - resolve_edges: bool = True, - ) -> tuple[Node, list[Edge]]: - """Create a symbol node, add it to *graph*, and return ``(node, edges)``. - - Handles ID deduplication, git metadata, CONTAINS edge, and optionally - CALLS/IMPORTS/API-endpoint detection. Set *resolve_edges* to ``False`` - for lightweight paths (file watcher) that skip cross-symbol linking. - """ - base_id = f"{repo_name}:{rel_path}::{sym.name}" - sym_id = base_id - suffix = 2 - while graph.has_node(sym_id): - sym_id = f"{base_id}_{suffix}" - suffix += 1 - - node_kind = self._map_symbol_kind(sym.kind) - sym_node = Node( - id=sym_id, - repo=repo_name, - kind=node_kind, - name=sym.name, - path=rel_path, - start_line=sym.start_line, - end_line=sym.end_line, - raw_code=sym.code, - signature=sym.signature, - docstring=sym.docstring, - ) - self._populate_git_metadata(sym_node, repo_path) - graph.add_node(sym_node) - - edges: list[Edge] = [] - - # CONTAINS edge - contains = Edge(source=file_id, target=sym_id, kind=EdgeKind.CONTAINS) - graph.add_edge(contains) - edges.append(contains) - - if resolve_edges: - # CALLS edges - for callee_name in sym.calls: - callee_id = self._resolve_symbol(callee_name, repo_name, rel_path, graph) - if callee_id: - e = Edge(source=sym_id, target=callee_id, kind=EdgeKind.CALLS) - graph.add_edge(e) - edges.append(e) - - # IMPORTS edges - for import_name in sym.imports: - import_id = self._resolve_symbol(import_name, repo_name, rel_path, graph) - if import_id: - e = Edge(source=sym_id, target=import_id, kind=EdgeKind.IMPORTS) - graph.add_edge(e) - edges.append(e) - - # API endpoint detection - for dec in sym.decorators: - endpoint_info = self._parse_endpoint_decorator(dec) - if endpoint_info: - current = graph.get_node(sym_id) - if current: - api_node = Node( - id=sym_id, - repo=repo_name, - kind=NodeKind.API_ENDPOINT, - name=sym.name, - path=rel_path, - start_line=sym.start_line, - end_line=sym.end_line, - raw_code=sym.code, - signature=sym.signature, - docstring=sym.docstring, - last_modified=current.last_modified, - modification_count=current.modification_count, - http_method=endpoint_info["method"], - route_path=endpoint_info["endpoint"], - ) - graph.add_node(api_node) # overwrite - sym_node = api_node - - return sym_node, edges - - @staticmethod - def _resolve_symbol( - name: str, - repo_name: str, - current_path: str, - graph: CodeGraph, - ) -> Optional[str]: - """Try to resolve a symbol name to a node ID in the graph.""" - # Exact match within repo - for node in graph.nodes_by_repo(repo_name): - if node.name == name and node.is_symbol: - return node.id - return None - - @staticmethod - def _populate_git_metadata(node: Node, repo_path: Path) -> None: - """Populate git metadata for a node — lightweight, no blame.""" - # Git blame is too slow for large repos. Use git log per-file instead, - # cached at the class level to avoid repeated calls. - if not hasattr(IndexingService, '_git_file_cache'): - IndexingService._git_file_cache = {} - - cache_key = f"{repo_path}:{node.path}" - if cache_key in IndexingService._git_file_cache: - cached = IndexingService._git_file_cache[cache_key] - node.last_modified = cached.get('last_modified') - node.modification_count = cached.get('modification_count', 0) - return - - try: - import git - repo = git.Repo(str(repo_path)) - if node.path: - commits = list(repo.iter_commits(paths=str(node.path), max_count=50)) - if commits: - info = { - 'last_modified': commits[0].committed_datetime.isoformat(), - 'modification_count': len(commits), - } - IndexingService._git_file_cache[cache_key] = info - node.last_modified = info['last_modified'] - node.modification_count = info['modification_count'] - else: - IndexingService._git_file_cache[cache_key] = {} - except Exception: - IndexingService._git_file_cache[cache_key] = {} - - @staticmethod - def _parse_endpoint_decorator(decorator: str) -> Optional[dict]: - """Parse a decorator to detect API endpoint info.""" - patterns = [ - r'@\w+\.(get|post|put|delete|patch)\s*\(\s*["\']([^"\']+)', - r'@app\.route\s*\(\s*["\']([^"\']+)', - ] - for pattern in patterns: - match = re.search(pattern, decorator, re.IGNORECASE) - if match: - groups = match.groups() - if len(groups) == 2: - return {"method": groups[0].upper(), "endpoint": groups[1]} - return {"method": "GET", "endpoint": groups[0]} - return None - - # ------------------------------------------------------------------ - # Embedding - # ------------------------------------------------------------------ - - @staticmethod - def _embedding_text(node: Node, graph: CodeGraph) -> str: - """Build grounded text for embedding a node. - - Symbols use their raw code augmented with structural context - (docstring, callers, callees, type relationships). - Containers use path + children signatures + heuristic summary. - """ - if node.is_symbol: - code = node.raw_code or node.signature or node.name - - # Augment with structural metadata - context_parts: list[str] = [] - if node.path: - context_parts.append(f"File: {node.path}") - if node.http_method and node.route_path: - context_parts.append(f"Route: {node.http_method} {node.route_path}") - if node.docstring: - context_parts.append(f"Doc: {node.docstring[:200]}") - - callees = graph.get_callees(node.id) - if callees: - names = [c.name for c in callees[:10]] - context_parts.append(f"Calls: {', '.join(names)}") - - callers = graph.get_callers(node.id) - if callers: - names = [c.name for c in callers[:10]] - context_parts.append(f"Called by: {', '.join(names)}") - - for edge_kind, label in [ - (EdgeKind.INHERITS, "Inherits"), - (EdgeKind.IMPLEMENTS, "Implements"), - ]: - edges = graph.get_outgoing_edges(node.id, edge_kind) - if edges: - targets = [] - for e in edges[:5]: - t = graph.get_node(e.target) - if t: - targets.append(t.name) - if targets: - context_parts.append(f"{label}: {', '.join(targets)}") - - if context_parts: - return code + "\n\n# Context\n" + "\n".join(context_parts) - return code - - # Container: build from grounded content - parts: list[str] = [] - - # Path carries semantic signal (e.g. "Features/Home/HomeView.swift") - if node.path: - parts.append(node.path) - - # Children's signatures / names - children = graph.get_children(node.id) - for child in children[:30]: - sig = child.signature or child.name - parts.append(sig) - - # Append summary as minority signal (not dominant) - if node.summary and len(parts) > 0: - parts.append(node.summary[:500]) - - return "\n".join(parts) if parts else node.name - - async def _embed_texts_batched( - self, - texts: list[str], - on_batch_done: Optional[Callable[[], None]] = None, - ) -> list[list[float]]: - """Embed ``texts`` in batches with bounded concurrency. - - Batches are dispatched via ``asyncio.gather`` and capped by a - semaphore of size ``embeddings.max_concurrent_batches``. Input order - is preserved in the returned list (``gather`` returns results in - submission order). - - ``on_batch_done`` is called once per completed batch and can be used - by callers (e.g. ``_embed_and_upsert``) to drive a progress bar. - """ - batch_size = self._config.embeddings.batch_size - max_concurrent = max(1, self._config.embeddings.max_concurrent_batches) - sem = asyncio.Semaphore(max_concurrent) - - async def run_batch(chunk: list[str]) -> list[list[float]]: - async with sem: - result = await self._embedder.embed_batch(chunk) - if on_batch_done is not None: - on_batch_done() - return result - - chunks = [texts[i : i + batch_size] for i in range(0, len(texts), batch_size)] - results = await asyncio.gather(*(run_batch(chunk) for chunk in chunks)) - - flat: list[list[float]] = [] - for r in results: - flat.extend(r) - return flat - - async def _embed_and_upsert( - self, - graph: CodeGraph, - mode: str, - *, - nodes_to_embed: Optional[list[Node]] = None, - show_progress: bool = False, - ) -> None: - """Embed nodes and upsert into the vector store. - - When *nodes_to_embed* is ``None`` (full-graph mode) every node in - *graph* is processed. Otherwise only the given list is embedded. - *show_progress* enables a Rich progress bar (used by the full-index - path). - """ - source = nodes_to_embed if nodes_to_embed is not None else list(graph.all_nodes()) - - texts: list[str] = [] - nodes: list[Node] = [] - - for node in source: - if mode == "none" and not node.is_symbol: - continue - text = self._embedding_text(node, graph) if graph else (node.raw_code or node.summary or node.name) - if text: - texts.append(text[:4000]) - nodes.append(node) - - if not texts: - if nodes_to_embed is None: - logger.warning("No texts to embed") - return - - logger.info("Embedding %d nodes...", len(texts)) - - if show_progress: - from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn - - batch_size = self._config.embeddings.batch_size - total_batches = (len(texts) + batch_size - 1) // batch_size - - with Progress( - SpinnerColumn(), - TextColumn("[progress.description]{task.description}"), - BarColumn(), - TaskProgressColumn(), - TextColumn("{task.completed}/{task.total} batches"), - transient=True, - ) as progress: - task_id = progress.add_task("[green]Embedding nodes...", total=total_batches) - all_embeddings = await self._embed_texts_batched( - texts, - on_batch_done=lambda: progress.update(task_id, advance=1), - ) - else: - all_embeddings = await self._embed_texts_batched(texts) - - # Assign to nodes and upsert to vector store - ids: list[str] = [] - metadatas: list[dict] = [] - for node, embedding in zip(nodes, all_embeddings): - node.embedding = embedding - ids.append(node.id) - metadatas.append({ - "repo": node.repo, - "kind": node.kind.value, - "path": node.path or "", - "last_modified": node.last_modified or "", - }) - - self._vector_store.upsert( - ids=ids, - embeddings=all_embeddings, - metadatas=metadatas, - documents=texts, - ) - - logger.info("Embedded and stored %d vectors", len(ids)) - diff --git a/mimir/services/indexing/__init__.py b/mimir/services/indexing/__init__.py new file mode 100644 index 0000000..bf84202 --- /dev/null +++ b/mimir/services/indexing/__init__.py @@ -0,0 +1,5 @@ +"""Indexing sub-package — parsing, graph building, summarization, and embedding.""" + +from mimir.services.indexing.service import IndexingService + +__all__ = ["IndexingService"] diff --git a/mimir/services/indexing/builder.py b/mimir/services/indexing/builder.py new file mode 100644 index 0000000..be36263 --- /dev/null +++ b/mimir/services/indexing/builder.py @@ -0,0 +1,405 @@ +"""Graph-construction helpers for the indexing pipeline.""" + +from __future__ import annotations + +import fnmatch +import logging +import os +import re +from pathlib import Path +from typing import Optional + +from mimir.domain.config import MimirConfig +from mimir.domain.errors import ParsingError +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Edge, EdgeKind, Node, NodeKind +from mimir.ports.parser import Parser, Symbol +from mimir.services.indexing.refs import resolve_affected_refs +from mimir.services.summarizer import heuristic_summary + +logger = logging.getLogger(__name__) + + +class IndexingGraphBuilder: + """Owns repository/file parsing and graph construction details.""" + + _git_file_cache: dict[str, dict] = {} + + def __init__(self, config: MimirConfig, parser: Parser) -> None: + self._config = config + self._parser = parser + + async def index_repo(self, graph: CodeGraph, repo_config) -> None: + repo_name = repo_config.name + repo_path = Path(repo_config.path) + language = repo_config.language_hint + + repo_node = Node( + id=f"{repo_name}:", + repo=repo_name, + kind=NodeKind.REPOSITORY, + name=repo_name, + path=str(repo_path), + ) + graph.add_node(repo_node) + + files_indexed = 0 + symbols_indexed = 0 + + for root, dirs, files in os.walk(str(repo_path)): + dirs[:] = [d for d in dirs if not self.is_excluded(d)] + + rel_dir = os.path.relpath(root, str(repo_path)) + if rel_dir == ".": + rel_dir = "" + + for filename in files: + if self.is_excluded(filename): + continue + + file_path = os.path.join(root, filename) + rel_path = os.path.relpath(file_path, str(repo_path)) + + try: + size_kb = os.path.getsize(file_path) / 1024 + if size_kb > self._config.indexing.max_file_size_kb: + logger.debug("Skipping large file: %s (%.0f KB)", rel_path, size_kb) + continue + except OSError: + continue + + try: + symbols = await self._parser.parse_file(file_path, language) + except ParsingError as exc: + logger.warning("Parse failed: %s", exc) + continue + except Exception as exc: + logger.warning("Unexpected parse error for %s: %s", rel_path, exc) + continue + + if not symbols: + continue + + file_id = f"{repo_name}:{rel_path}" + file_node = Node( + id=file_id, + repo=repo_name, + kind=NodeKind.FILE, + name=filename, + path=rel_path, + ) + graph.add_node(file_node) + files_indexed += 1 + + parent_id, _, _ = self.ensure_module_hierarchy( + graph, + repo_name, + rel_dir, + repo_root_path=repo_path, + ) + graph.add_edge(Edge( + source=parent_id, + target=file_id, + kind=EdgeKind.CONTAINS, + )) + + for sym in symbols: + self.add_symbol_to_graph( + graph, + sym, + repo_name, + rel_path, + file_id, + repo_path, + ) + symbols_indexed += 1 + + logger.info("Repo %s: %d files, %d symbols", repo_name, files_indexed, symbols_indexed) + + async def index_files( + self, + graph: CodeGraph, + repo_name: str, + repo_path: Path, + changed_files: set[str], + deleted_files: set[str], + *, + language_hint: Optional[str] = None, + ) -> tuple[list[str], list[Node], list[Edge]]: + removed_ids: list[str] = [] + new_nodes: list[Node] = [] + new_edges: list[Edge] = [] + + files_to_remove = deleted_files | changed_files + if files_to_remove: + removed_ids = graph.remove_nodes_by_paths(repo_name, files_to_remove) + + for rel_path in sorted(changed_files): + file_path = str(repo_path / rel_path) + + if self.is_excluded(os.path.basename(rel_path)): + continue + if not os.path.isfile(file_path): + continue + + try: + size_kb = os.path.getsize(file_path) / 1024 + if size_kb > self._config.indexing.max_file_size_kb: + continue + except OSError: + continue + + try: + symbols = await self._parser.parse_file(file_path, language_hint) + except Exception as exc: + logger.warning("Watcher parse failed for %s: %s", rel_path, exc) + continue + + if not symbols: + continue + + file_id = f"{repo_name}:{rel_path}" + file_node = Node( + id=file_id, + repo=repo_name, + kind=NodeKind.FILE, + name=os.path.basename(rel_path), + path=rel_path, + ) + graph.add_node(file_node) + new_nodes.append(file_node) + + rel_dir = os.path.dirname(rel_path) + parent_id, module_nodes, module_edges = self.ensure_module_hierarchy( + graph, + repo_name, + rel_dir, + repo_root_path=repo_path, + ) + new_nodes.extend(module_nodes) + new_edges.extend(module_edges) + edge = Edge(source=parent_id, target=file_id, kind=EdgeKind.CONTAINS) + graph.add_edge(edge) + new_edges.append(edge) + + for sym in symbols: + node, edges = self.add_symbol_to_graph( + graph, + sym, + repo_name, + rel_path, + file_id, + repo_path, + resolve_edges=False, + ) + new_nodes.append(node) + new_edges.extend(edges) + + new_symbol_nodes = [node for node in new_nodes if node.is_symbol] + if new_symbol_nodes and hasattr(self._parser, "extract_identifiers"): + xref_edges = resolve_affected_refs(graph, new_symbol_nodes, self._parser) + new_edges.extend(xref_edges) + + for node in new_nodes: + node.summary = heuristic_summary(node, graph) + + logger.info( + "index_files: -%d removed, +%d nodes, +%d edges", + len(removed_ids), + len(new_nodes), + len(new_edges), + ) + return removed_ids, new_nodes, new_edges + + def is_excluded(self, name: str) -> bool: + return any(fnmatch.fnmatch(name, pattern) for pattern in self._config.indexing.excluded_patterns) + + @staticmethod + def map_symbol_kind(kind_str: str) -> NodeKind: + mapping = { + "function": NodeKind.FUNCTION, + "method": NodeKind.METHOD, + "class": NodeKind.CLASS, + "type": NodeKind.TYPE, + "constant": NodeKind.CONSTANT, + } + return mapping.get(kind_str, NodeKind.FUNCTION) + + def ensure_module_hierarchy( + self, + graph: CodeGraph, + repo_name: str, + rel_dir: str, + *, + repo_root_path: Optional[Path] = None, + ) -> tuple[str, list[Node], list[Edge]]: + created_nodes: list[Node] = [] + created_edges: list[Edge] = [] + repo_id = f"{repo_name}:" + if not graph.has_node(repo_id): + repo_node = Node( + id=repo_id, + repo=repo_name, + kind=NodeKind.REPOSITORY, + name=repo_name, + path=str(repo_root_path) if repo_root_path is not None else None, + ) + graph.add_node(repo_node) + created_nodes.append(repo_node) + + if not rel_dir: + return repo_id, created_nodes, created_edges + + current_parent = repo_id + current_parts: list[str] = [] + for part in Path(rel_dir).parts: + current_parts.append(part) + module_path = "/".join(current_parts) + module_id = f"{repo_name}:{module_path}/" + if not graph.has_node(module_id): + module_node = Node( + id=module_id, + repo=repo_name, + kind=NodeKind.MODULE, + name=part, + path=module_path, + ) + graph.add_node(module_node) + created_nodes.append(module_node) + edge = Edge(source=current_parent, target=module_id, kind=EdgeKind.CONTAINS) + graph.add_edge(edge) + created_edges.append(edge) + current_parent = module_id + + return current_parent, created_nodes, created_edges + + def add_symbol_to_graph( + self, + graph: CodeGraph, + sym: Symbol, + repo_name: str, + rel_path: str, + file_id: str, + repo_path: Path, + *, + resolve_edges: bool = True, + ) -> tuple[Node, list[Edge]]: + base_id = f"{repo_name}:{rel_path}::{sym.name}" + sym_id = base_id + suffix = 2 + while graph.has_node(sym_id): + sym_id = f"{base_id}_{suffix}" + suffix += 1 + + sym_node = Node( + id=sym_id, + repo=repo_name, + kind=self.map_symbol_kind(sym.kind), + name=sym.name, + path=rel_path, + start_line=sym.start_line, + end_line=sym.end_line, + raw_code=sym.code, + signature=sym.signature, + docstring=sym.docstring, + ) + self.populate_git_metadata(sym_node, repo_path) + graph.add_node(sym_node) + + edges: list[Edge] = [] + contains = Edge(source=file_id, target=sym_id, kind=EdgeKind.CONTAINS) + graph.add_edge(contains) + edges.append(contains) + + if resolve_edges: + for callee_name in sym.calls: + callee_id = self.resolve_symbol(callee_name, repo_name, graph) + if callee_id: + edge = Edge(source=sym_id, target=callee_id, kind=EdgeKind.CALLS) + graph.add_edge(edge) + edges.append(edge) + + for import_name in sym.imports: + import_id = self.resolve_symbol(import_name, repo_name, graph) + if import_id: + edge = Edge(source=sym_id, target=import_id, kind=EdgeKind.IMPORTS) + graph.add_edge(edge) + edges.append(edge) + + for decorator in sym.decorators: + endpoint_info = self.parse_endpoint_decorator(decorator) + if endpoint_info: + current = graph.get_node(sym_id) + if current: + api_node = Node( + id=sym_id, + repo=repo_name, + kind=NodeKind.API_ENDPOINT, + name=sym.name, + path=rel_path, + start_line=sym.start_line, + end_line=sym.end_line, + raw_code=sym.code, + signature=sym.signature, + docstring=sym.docstring, + last_modified=current.last_modified, + modification_count=current.modification_count, + http_method=endpoint_info["method"], + route_path=endpoint_info["endpoint"], + ) + graph.add_node(api_node) + sym_node = api_node + + return sym_node, edges + + @staticmethod + def resolve_symbol(name: str, repo_name: str, graph: CodeGraph) -> Optional[str]: + for node in graph.nodes_by_repo(repo_name): + if node.name == name and node.is_symbol: + return node.id + return None + + @classmethod + def populate_git_metadata(cls, node: Node, repo_path: Path) -> None: + cache_key = f"{repo_path}:{node.path}" + cached = cls._git_file_cache.get(cache_key) + if cached is not None: + node.last_modified = cached.get("last_modified") + node.modification_count = cached.get("modification_count", 0) + return + + try: + import git + + repo = git.Repo(str(repo_path)) + if node.path: + commits = list(repo.iter_commits(paths=str(node.path), max_count=50)) + if commits: + info = { + "last_modified": commits[0].committed_datetime.isoformat(), + "modification_count": len(commits), + } + cls._git_file_cache[cache_key] = info + node.last_modified = info["last_modified"] + node.modification_count = info["modification_count"] + return + except Exception: + pass + + cls._git_file_cache[cache_key] = {} + + @staticmethod + def parse_endpoint_decorator(decorator: str) -> Optional[dict]: + patterns = [ + r'@\w+\.(get|post|put|delete|patch)\s*\(\s*["\']([^"\']+)', + r'@app\.route\s*\(\s*["\']([^"\']+)', + ] + for pattern in patterns: + match = re.search(pattern, decorator, re.IGNORECASE) + if not match: + continue + groups = match.groups() + if len(groups) == 2: + return {"method": groups[0].upper(), "endpoint": groups[1]} + return {"method": "GET", "endpoint": groups[0]} + return None diff --git a/mimir/services/indexing/embedding_pipeline.py b/mimir/services/indexing/embedding_pipeline.py new file mode 100644 index 0000000..d2e34d8 --- /dev/null +++ b/mimir/services/indexing/embedding_pipeline.py @@ -0,0 +1,171 @@ +"""Embedding helpers for the indexing pipeline.""" + +from __future__ import annotations + +import asyncio +import logging +from typing import Callable, Optional + +from mimir.domain.config import MimirConfig, SummaryMode +from mimir.domain.graph import CodeGraph +from mimir.domain.models import EdgeKind, Node +from mimir.ports.embedder import Embedder +from mimir.ports.vector_store import VectorStore + +logger = logging.getLogger(__name__) + + +class IndexingEmbeddingPipeline: + """Owns embedding text generation, batching, and vector upserts.""" + + def __init__( + self, + config: MimirConfig, + embedder: Embedder, + vector_store: VectorStore | None, + ) -> None: + self._config = config + self._embedder = embedder + self._vector_store = vector_store + + @staticmethod + def embedding_text(node: Node, graph: CodeGraph) -> str: + if node.is_symbol: + code = node.raw_code or node.signature or node.name + + context_parts: list[str] = [] + if node.path: + context_parts.append(f"File: {node.path}") + if node.http_method and node.route_path: + context_parts.append(f"Route: {node.http_method} {node.route_path}") + if node.docstring: + context_parts.append(f"Doc: {node.docstring[:200]}") + + callees = graph.get_callees(node.id) + if callees: + context_parts.append(f"Calls: {', '.join(callee.name for callee in callees[:10])}") + + callers = graph.get_callers(node.id) + if callers: + context_parts.append(f"Called by: {', '.join(caller.name for caller in callers[:10])}") + + for edge_kind, label in ( + (EdgeKind.INHERITS, "Inherits"), + (EdgeKind.IMPLEMENTS, "Implements"), + ): + edges = graph.get_outgoing_edges(node.id, edge_kind) + targets = [ + target.name + for edge in edges[:5] + if (target := graph.get_node(edge.target)) is not None + ] + if targets: + context_parts.append(f"{label}: {', '.join(targets)}") + + if context_parts: + return code + "\n\n# Context\n" + "\n".join(context_parts) + return code + + parts: list[str] = [] + if node.path: + parts.append(node.path) + + for child in graph.get_children(node.id)[:30]: + parts.append(child.signature or child.name) + + if node.summary and parts: + parts.append(node.summary[:500]) + + return "\n".join(parts) if parts else node.name + + async def embed_texts_batched( + self, + texts: list[str], + on_batch_done: Optional[Callable[[], None]] = None, + ) -> list[list[float]]: + batch_size = self._config.embeddings.batch_size + max_concurrent = max(1, self._config.embeddings.max_concurrent_batches) + sem = asyncio.Semaphore(max_concurrent) + + async def run_batch(chunk: list[str]) -> list[list[float]]: + async with sem: + result = await self._embedder.embed_batch(chunk) + if on_batch_done is not None: + on_batch_done() + return result + + chunks = [texts[i : i + batch_size] for i in range(0, len(texts), batch_size)] + results = await asyncio.gather(*(run_batch(chunk) for chunk in chunks)) + return [embedding for batch in results for embedding in batch] + + async def embed_and_upsert( + self, + graph: CodeGraph, + mode: SummaryMode, + *, + nodes_to_embed: Optional[list[Node]] = None, + show_progress: bool = False, + ) -> None: + source = nodes_to_embed if nodes_to_embed is not None else list(graph.all_nodes()) + + texts: list[str] = [] + nodes: list[Node] = [] + for node in source: + if mode is SummaryMode.NONE and not node.is_symbol: + continue + text = self.embedding_text(node, graph) if graph else (node.raw_code or node.summary or node.name) + if text: + texts.append(text[:4000]) + nodes.append(node) + + if not texts: + if nodes_to_embed is None: + logger.warning("No texts to embed") + return + + logger.info("Embedding %d nodes...", len(texts)) + + if show_progress: + from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn + + batch_size = self._config.embeddings.batch_size + total_batches = (len(texts) + batch_size - 1) // batch_size + with Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + BarColumn(), + TaskProgressColumn(), + TextColumn("{task.completed}/{task.total} batches"), + transient=True, + ) as progress: + task_id = progress.add_task("[green]Embedding nodes...", total=total_batches) + all_embeddings = await self.embed_texts_batched( + texts, + on_batch_done=lambda: progress.update(task_id, advance=1), + ) + else: + all_embeddings = await self.embed_texts_batched(texts) + + ids: list[str] = [] + metadatas: list[dict] = [] + for node, embedding in zip(nodes, all_embeddings): + node.embedding = embedding + ids.append(node.id) + metadatas.append({ + "repo": node.repo, + "kind": node.kind.value, + "path": node.path or "", + "last_modified": node.last_modified or "", + }) + + if self._vector_store is None: + raise RuntimeError("Vector store is required for embed_and_upsert") + + self._vector_store.upsert( + ids=ids, + embeddings=all_embeddings, + metadatas=metadatas, + documents=texts, + ) + + logger.info("Embedded and stored %d vectors", len(ids)) diff --git a/mimir/services/indexing/refs.py b/mimir/services/indexing/refs.py new file mode 100644 index 0000000..65c5d95 --- /dev/null +++ b/mimir/services/indexing/refs.py @@ -0,0 +1,99 @@ +"""Cross-file reference resolution helpers for indexing flows.""" + +from __future__ import annotations + +import logging + +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Edge, EdgeKind, Node, NodeKind +from mimir.services.graph_linker import detect_inheritance + +logger = logging.getLogger(__name__) + + +def resolve_affected_refs( + graph: CodeGraph, + new_symbols: list[Node], + parser: object, +) -> list[Edge]: + """Resolve cross-file references for new/changed symbols only.""" + from mimir.domain.lang import detect_language + + name_index: dict[str, list[Node]] = {} + for node in graph.all_nodes(): + if node.is_symbol: + name_index.setdefault(node.name, []).append(node) + + ambiguous_names = {name for name, nodes in name_index.items() if len(nodes) > 20} + + new_edges: list[Edge] = [] + seen_edges: set[tuple[str, str, str]] = set() + + for edge in graph.all_edges(): + if edge.kind != EdgeKind.CONTAINS: + seen_edges.add((edge.source, edge.target, edge.kind.value)) + + new_symbol_ids = {node.id for node in new_symbols} + new_symbol_names = {node.name for node in new_symbols} + + def try_add_edge(source_id: str, target: Node, ident: str, inherits_names: set[str]) -> None: + if target.id == source_id: + return + if ident in inherits_names: + edge_kind = EdgeKind.INHERITS + elif target.kind in (NodeKind.CLASS, NodeKind.TYPE): + edge_kind = EdgeKind.USES_TYPE + else: + edge_kind = EdgeKind.CALLS + + edge_key = (source_id, target.id, edge_kind.value) + if edge_key in seen_edges: + return + seen_edges.add(edge_key) + + edge = Edge(source=source_id, target=target.id, kind=edge_kind) + graph.add_edge(edge) + new_edges.append(edge) + + for node in new_symbols: + if not node.raw_code: + continue + lang = detect_language(node.path) if node.path else None + identifiers = parser.extract_identifiers(node.raw_code, language=lang, file_path=node.path) + inherits_names = detect_inheritance(node) + + for ident in identifiers: + if ident == node.name or ident in ambiguous_names: + continue + targets = name_index.get(ident) + if not targets: + continue + for target in targets: + try_add_edge(node.id, target, ident, inherits_names) + + for node in graph.all_nodes(): + if not node.is_symbol or not node.raw_code: + continue + if node.id in new_symbol_ids: + continue + + if not any(name in node.raw_code for name in new_symbol_names if name not in ambiguous_names): + continue + + lang = detect_language(node.path) if node.path else None + identifiers = parser.extract_identifiers(node.raw_code, language=lang, file_path=node.path) + inherits_names = detect_inheritance(node) + + for ident in identifiers: + if ident not in new_symbol_names or ident in ambiguous_names: + continue + targets = name_index.get(ident) + if not targets: + continue + for target in targets: + if target.id not in new_symbol_ids: + continue + try_add_edge(node.id, target, ident, inherits_names) + + logger.info("Affected cross-file resolution: %d new edges", len(new_edges)) + return new_edges diff --git a/mimir/services/indexing/service.py b/mimir/services/indexing/service.py new file mode 100644 index 0000000..e5629c3 --- /dev/null +++ b/mimir/services/indexing/service.py @@ -0,0 +1,604 @@ +"""Indexing service — orchestrates parsing, graph building, summarization, and embedding. + +This is the primary application service for Milestone 1+2. +It receives all infrastructure dependencies via constructor injection. +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +from mimir.domain.config import MimirConfig, SummaryMode +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Edge, EdgeKind, Node, NodeKind +from mimir.ports.embedder import Embedder +from mimir.ports.graph_store import GraphStore +from mimir.ports.parser import Parser +from mimir.ports.vector_store import VectorStore +from mimir.services.graph_linker import ( + detect_api_contracts, + detect_shared_imports, + resolve_cross_file_refs, +) +from mimir.services.indexing.builder import IndexingGraphBuilder +from mimir.services.indexing.embedding_pipeline import IndexingEmbeddingPipeline +from mimir.services.summarizer import generate_heuristic_summaries + +logger = logging.getLogger(__name__) + + +class IndexingService: + """Orchestrates the full indexing pipeline.""" + + def __init__( + self, + config: MimirConfig, + parser: Parser, + embedder: Embedder, + vector_store: VectorStore, + graph_store: GraphStore, + ) -> None: + self._config = config + self._parser = parser + self._embedder = embedder + self._vector_store = vector_store + self._graph_store = graph_store + self._graph_builder = IndexingGraphBuilder(config, parser) + self._embedding_pipeline = IndexingEmbeddingPipeline(config, embedder, vector_store) + + async def index_all(self, *, mode_override: Optional[SummaryMode | str] = None) -> CodeGraph: + """Run the full indexing pipeline. + + 1. Parse all repos → build CodeGraph + 2. Cross-file symbol resolution (CALLS, USES_TYPE, INHERITS edges) + 3. Cross-repo link detection (API contracts, shared imports) + 4. Generate summaries (based on mode) + 5. Embed nodes + 6. Store in vector DB and SQLite + """ + mode = SummaryMode(mode_override) if mode_override else self._config.indexing.summary_mode + logger.info("Starting full index — mode=%s, repos=%d", mode.value, len(self._config.repos)) + + graph = CodeGraph() + + # Phase 1: Parse all repos + for repo_config in self._config.repos: + logger.info("Indexing repo: %s (%s)", repo_config.name, repo_config.path) + await self._index_repo(graph, repo_config) + + # Phase 2: Cross-file symbol resolution + resolve_cross_file_refs(graph, self._parser) + + # Phase 3: Cross-repo link detection + if self._config.cross_repo.detect_api_contracts: + detect_api_contracts(graph) + if self._config.cross_repo.detect_shared_imports: + detect_shared_imports(graph) + + logger.info("Graph built: %s", graph.stats()) + + # Phase 4: Summarization + if mode is SummaryMode.HEURISTIC: + generate_heuristic_summaries(graph) + + # Phase 5: Embedding + await self._embed_and_upsert(graph, mode, show_progress=True) + + # Phase 6: Persist + self._graph_store.save(graph) + + # Save commit hashes for incremental updates + for repo_config in self._config.repos: + try: + import git + repo = git.Repo(str(repo_config.path)) + commit_hash = repo.head.commit.hexsha + self._graph_store.save_repo_state(repo_config.name, commit_hash) + except Exception: + logger.debug("Could not read git commit for %s", repo_config.name) + + logger.info("Indexing complete: %d nodes, %d edges", graph.node_count, graph.edge_count) + return graph + + async def index_incremental(self, *, mode_override: Optional[SummaryMode | str] = None) -> tuple[CodeGraph, dict]: + """Incremental index — only re-process files changed since the last commit. + + Flow: + 1. Load existing graph from storage + 2. For each repo, compute git diff against last-indexed commit + 3. Remove stale nodes (deleted & modified files) + 4. Re-parse only changed/added files + 5. Regenerate summaries & embeddings for affected nodes + 6. Persist delta to storage + + Returns (graph, report) where report is a dict summarising the changes. + """ + mode = SummaryMode(mode_override) if mode_override else self._config.indexing.summary_mode + logger.info("Starting incremental index — mode=%s, repos=%d", mode.value, len(self._config.repos)) + + # Load existing graph + graph = self._graph_store.load() + if graph.node_count == 0: + logger.info("No existing graph found — falling back to full index") + return await self.index_all(mode_override=mode_override), { + "mode": "full_fallback", + "reason": "no existing graph", + } + + # Get stored commit hashes + stored_states = self._graph_store.get_all_repo_states() + + report: dict = { + "mode": "incremental", + "repos": {}, + } + + all_new_nodes: list[Node] = [] + all_new_edges: list[Edge] = [] + all_stale_ids: list[str] = [] + repos_needing_full: list = [] + + for repo_config in self._config.repos: + repo_name = repo_config.name + repo_path = Path(repo_config.path) + last_commit = stored_states.get(repo_name) + + if not last_commit: + logger.info("Repo %s: no previous commit — will full-index", repo_name) + repos_needing_full.append(repo_config) + report["repos"][repo_name] = {"status": "full_index", "reason": "first time"} + continue + + # Compute diff + try: + import git as gitmodule + repo = gitmodule.Repo(str(repo_path)) + current_commit = repo.head.commit.hexsha + except Exception as exc: + logger.warning("Cannot read git for %s: %s — skipping", repo_name, exc) + report["repos"][repo_name] = {"status": "skipped", "reason": str(exc)} + continue + + if current_commit == last_commit: + logger.info("Repo %s: no changes (still at %s)", repo_name, current_commit[:8]) + report["repos"][repo_name] = {"status": "up_to_date", "commit": current_commit[:8]} + continue + + # Get the actual diff + try: + diff = repo.commit(last_commit).diff(current_commit) + except Exception as exc: + logger.warning( + "Repo %s: diff failed (%s) — falling back to full index for this repo", + repo_name, exc, + ) + repos_needing_full.append(repo_config) + report["repos"][repo_name] = {"status": "full_index", "reason": f"diff failed: {exc}"} + continue + + # Categorise changed files + added_files: set[str] = set() + modified_files: set[str] = set() + deleted_files: set[str] = set() + + for d in diff: + if d.new_file: + if d.b_path: + added_files.add(d.b_path) + elif d.deleted_file: + if d.a_path: + deleted_files.add(d.a_path) + elif d.renamed_file: + if d.a_path: + deleted_files.add(d.a_path) + if d.b_path: + added_files.add(d.b_path) + else: + # Modified + if d.b_path: + modified_files.add(d.b_path) + + # Filter to only parseable files (skip binary, excluded, etc.) + files_to_remove = deleted_files | modified_files + files_to_parse = added_files | modified_files + + logger.info( + "Repo %s: %d added, %d modified, %d deleted (commit %s → %s)", + repo_name, + len(added_files), + len(modified_files), + len(deleted_files), + last_commit[:8], + current_commit[:8], + ) + + # Phase 1: Remove stale nodes from graph & store + if files_to_remove: + removed_ids = graph.remove_nodes_by_paths(repo_name, files_to_remove) + all_stale_ids.extend(removed_ids) + logger.info("Repo %s: removed %d stale nodes", repo_name, len(removed_ids)) + + # Phase 2: Re-parse changed/added files into the graph + files_parsed = 0 + symbols_parsed = 0 + for rel_path in sorted(files_to_parse): + file_path = str(repo_path / rel_path) + + # Skip excluded files + if self._is_excluded(os.path.basename(rel_path)): + continue + + # Skip files that don't exist (could be in gitignore or binary) + if not os.path.isfile(file_path): + continue + + # Check file size + try: + size_kb = os.path.getsize(file_path) / 1024 + if size_kb > self._config.indexing.max_file_size_kb: + continue + except OSError: + continue + + # Parse file + try: + symbols = await self._parser.parse_file( + file_path, repo_config.language_hint, + ) + except Exception as exc: + logger.warning("Parse failed for %s: %s", rel_path, exc) + continue + + if not symbols: + continue + + # Create file node + file_id = f"{repo_name}:{rel_path}" + file_node = Node( + id=file_id, + repo=repo_name, + kind=NodeKind.FILE, + name=os.path.basename(rel_path), + path=rel_path, + ) + graph.add_node(file_node) + all_new_nodes.append(file_node) + files_parsed += 1 + + # Link file to parent module/repo + rel_dir = os.path.dirname(rel_path) + parent_id, module_nodes, module_edges = self._ensure_module_hierarchy( + graph, + repo_name, + rel_dir, + repo_root_path=repo_path, + ) + all_new_nodes.extend(module_nodes) + all_new_edges.extend(module_edges) + edge = Edge(source=parent_id, target=file_id, kind=EdgeKind.CONTAINS) + graph.add_edge(edge) + all_new_edges.append(edge) + + # Add symbol nodes + for sym in symbols: + node, edges = self._add_symbol_to_graph( + graph, sym, repo_name, rel_path, file_id, repo_path, + ) + all_new_nodes.append(node) + all_new_edges.extend(edges) + symbols_parsed += 1 + + # Update commit state + self._graph_store.save_repo_state(repo_name, current_commit) + + report["repos"][repo_name] = { + "status": "updated", + "commit": f"{last_commit[:8]} → {current_commit[:8]}", + "files_added": len(added_files), + "files_modified": len(modified_files), + "files_deleted": len(deleted_files), + "nodes_removed": len([i for i in all_stale_ids if i.startswith(repo_name + ":")]), + "files_parsed": files_parsed, + "symbols_parsed": symbols_parsed, + } + + # Phase 3: Full-index repos that had no prior commit + for repo_config in repos_needing_full: + # Remove existing nodes for this repo (if any orphans) + removed = graph.remove_nodes_by_repo(repo_config.name) + all_stale_ids.extend(removed) + # Re-index fully + await self._index_repo(graph, repo_config) + try: + import git as gitmodule + repo = gitmodule.Repo(str(repo_config.path)) + self._graph_store.save_repo_state(repo_config.name, repo.head.commit.hexsha) + except Exception: + pass + + # Phase 4: Re-resolve cross-file refs (on full graph) + resolve_cross_file_refs(graph, self._parser) + + # Phase 5: Re-detect cross-repo links (on full graph) + if self._config.cross_repo.detect_api_contracts: + detect_api_contracts(graph) + if self._config.cross_repo.detect_shared_imports: + detect_shared_imports(graph) + + # Phase 6: Summarisation for new/changed nodes only + if mode is SummaryMode.HEURISTIC: + for node in all_new_nodes: + node.summary = heuristic_summary(node, graph) + + # Phase 7: Embed new/changed nodes only + if all_new_nodes: + await self._embed_and_upsert(graph, mode, nodes_to_embed=all_new_nodes) + + # Phase 8: Persist delta + if all_stale_ids: + self._graph_store.delete_nodes_by_ids(all_stale_ids) + self._vector_store.delete(all_stale_ids) + + if all_new_nodes or all_new_edges: + self._graph_store.save_partial(all_new_nodes, all_new_edges) + + # Also persist nodes from full-indexed repos + if repos_needing_full: + full_nodes = [] + full_edges = [] + for repo_config in repos_needing_full: + for n in graph.nodes_by_repo(repo_config.name): + full_nodes.append(n) + for e in graph.all_edges(): + src = graph.get_node(e.source) + tgt = graph.get_node(e.target) + if src and tgt and (src.repo == repo_config.name or tgt.repo == repo_config.name): + full_edges.append(e) + if full_nodes: + await self._embed_and_upsert(graph, mode, nodes_to_embed=full_nodes) + self._graph_store.save_partial(full_nodes, full_edges) + + total_removed = len(all_stale_ids) + total_added = len(all_new_nodes) + logger.info( + "Incremental index complete: -%d stale, +%d new nodes (graph total: %d nodes, %d edges)", + total_removed, total_added, graph.node_count, graph.edge_count, + ) + report["total_removed"] = total_removed + report["total_added"] = total_added + report["graph_nodes"] = graph.node_count + report["graph_edges"] = graph.edge_count + + return graph, report + + async def refresh_repo( + self, + graph: CodeGraph, + repo_name: str, + *, + mode_override: Optional[SummaryMode | str] = None, + ) -> dict: + """Re-index one configured repo into the unified graph. + + This path is intended for centrally mirrored repos updated by webhook + or other admin sync flows. It keeps the unified multi-repo graph model + intact by removing the repo, rebuilding it from disk, then rerunning + the global linkers over the assembled graph. + """ + mode = SummaryMode(mode_override) if mode_override else self._config.indexing.summary_mode + repo_config = next((r for r in self._config.repos if r.name == repo_name), None) + if repo_config is None: + raise ValueError(f"Unknown repo: {repo_name}") + + external_edges_before = self._edge_keys_excluding_repo(graph, repo_name) + removed_ids = graph.remove_nodes_by_repo(repo_name) + if removed_ids: + self._vector_store.delete(removed_ids) + + await self._index_repo(graph, repo_config) + + resolve_cross_file_refs(graph, self._parser) + if self._config.cross_repo.detect_api_contracts: + detect_api_contracts(graph) + if self._config.cross_repo.detect_shared_imports: + detect_shared_imports(graph) + + if mode is SummaryMode.HEURISTIC: + generate_heuristic_summaries(graph) + + repo_nodes = list(graph.nodes_by_repo(repo_name)) + if repo_nodes: + await self._embed_and_upsert(graph, mode, nodes_to_embed=repo_nodes) + + external_edges_after = self._edge_keys_excluding_repo(graph, repo_name) + full_save_required = external_edges_before != external_edges_after + + if full_save_required: + self._graph_store.save(graph) + else: + if removed_ids: + self._graph_store.delete_nodes_by_ids(removed_ids) + repo_edges = self._edges_touching_repo(graph, repo_name) + if repo_nodes or repo_edges: + self._graph_store.save_partial(repo_nodes, repo_edges) + + try: + import git + + repo = git.Repo(str(repo_config.path)) + commit_hash = repo.head.commit.hexsha + self._graph_store.save_repo_state(repo_name, commit_hash) + except Exception: + logger.debug("Could not read git commit for %s", repo_name) + commit_hash = None + + return { + "repo": repo_name, + "removed_nodes": len(removed_ids), + "repo_nodes": len(repo_nodes), + "graph_nodes": graph.node_count, + "graph_edges": graph.edge_count, + "commit": commit_hash, + "persist_mode": "full" if full_save_required else "partial", + } + + @staticmethod + def _edge_keys_excluding_repo(graph: CodeGraph, repo_name: str) -> set[tuple[str, str, str]]: + """Return edge identity keys where both endpoints are outside *repo_name*.""" + keys: set[tuple[str, str, str]] = set() + for edge in graph.all_edges(): + src = graph.get_node(edge.source) + tgt = graph.get_node(edge.target) + if src is None or tgt is None: + continue + if src.repo == repo_name or tgt.repo == repo_name: + continue + keys.add((edge.source, edge.target, edge.kind.value)) + return keys + + @staticmethod + def _edges_touching_repo(graph: CodeGraph, repo_name: str) -> list[Edge]: + """Collect edges where either endpoint belongs to *repo_name*.""" + edges: list[Edge] = [] + for edge in graph.all_edges(): + src = graph.get_node(edge.source) + tgt = graph.get_node(edge.target) + if src is None or tgt is None: + continue + if src.repo == repo_name or tgt.repo == repo_name: + edges.append(edge) + return edges + + def _graph_builder_component(self) -> IndexingGraphBuilder: + builder = getattr(self, "_graph_builder", None) + if builder is None: + builder = IndexingGraphBuilder(self._config, self._parser) + self._graph_builder = builder + return builder + + def _embedding_pipeline_component(self) -> IndexingEmbeddingPipeline: + pipeline = getattr(self, "_embedding_pipeline", None) + if pipeline is None: + pipeline = IndexingEmbeddingPipeline( + self._config, + self._embedder, + getattr(self, "_vector_store", None), + ) + self._embedding_pipeline = pipeline + return pipeline + + async def _index_repo(self, graph: CodeGraph, repo_config) -> None: + await self._graph_builder_component().index_repo(graph, repo_config) + + async def index_files( + self, + graph: CodeGraph, + repo_name: str, + repo_path: Path, + changed_files: set[str], + deleted_files: set[str], + language_hint: Optional[str] = None, + ) -> tuple[list[str], list[Node], list[Edge]]: + removed_ids, new_nodes, new_edges = await self._graph_builder_component().index_files( + graph, + repo_name, + repo_path, + changed_files, + deleted_files, + language_hint=language_hint, + ) + if new_nodes: + await self._embed_and_upsert(graph, "heuristic", nodes_to_embed=new_nodes) + return removed_ids, new_nodes, new_edges + + def _is_excluded(self, name: str) -> bool: + return self._graph_builder_component().is_excluded(name) + + @staticmethod + def _map_symbol_kind(kind_str: str) -> NodeKind: + return IndexingGraphBuilder.map_symbol_kind(kind_str) + + def _ensure_module_hierarchy( + self, + graph: CodeGraph, + repo_name: str, + rel_dir: str, + *, + repo_root_path: Optional[Path] = None, + ) -> tuple[str, list[Node], list[Edge]]: + return self._graph_builder_component().ensure_module_hierarchy( + graph, + repo_name, + rel_dir, + repo_root_path=repo_root_path, + ) + + def _add_symbol_to_graph( + self, + graph: CodeGraph, + sym: "Symbol", + repo_name: str, + rel_path: str, + file_id: str, + repo_path: Path, + *, + resolve_edges: bool = True, + ) -> tuple[Node, list[Edge]]: + return self._graph_builder_component().add_symbol_to_graph( + graph, + sym, + repo_name, + rel_path, + file_id, + repo_path, + resolve_edges=resolve_edges, + ) + + @staticmethod + def _resolve_symbol( + name: str, + repo_name: str, + current_path: str, + graph: CodeGraph, + ) -> Optional[str]: + del current_path + return IndexingGraphBuilder.resolve_symbol(name, repo_name, graph) + + @staticmethod + def _populate_git_metadata(node: Node, repo_path: Path) -> None: + IndexingGraphBuilder.populate_git_metadata(node, repo_path) + + @staticmethod + def _parse_endpoint_decorator(decorator: str) -> Optional[dict]: + return IndexingGraphBuilder.parse_endpoint_decorator(decorator) + + @staticmethod + def _embedding_text(node: Node, graph: CodeGraph) -> str: + return IndexingEmbeddingPipeline.embedding_text(node, graph) + + async def _embed_texts_batched( + self, + texts: list[str], + on_batch_done: Optional[Callable[[], None]] = None, + ) -> list[list[float]]: + return await self._embedding_pipeline_component().embed_texts_batched( + texts, + on_batch_done=on_batch_done, + ) + + async def _embed_and_upsert( + self, + graph: CodeGraph, + mode: str, + *, + nodes_to_embed: Optional[list[Node]] = None, + show_progress: bool = False, + ) -> None: + await self._embedding_pipeline_component().embed_and_upsert( + graph, + mode, + nodes_to_embed=nodes_to_embed, + show_progress=show_progress, + ) diff --git a/mimir/services/repo_sync.py b/mimir/services/repo_sync.py new file mode 100644 index 0000000..ceb6255 --- /dev/null +++ b/mimir/services/repo_sync.py @@ -0,0 +1,139 @@ +"""Central repo mirroring and webhook-driven sync helpers.""" + +from __future__ import annotations + +import asyncio +import hmac +import json +import os +from hashlib import sha256 +from pathlib import Path +from typing import Optional + +from mimir.domain.config import MimirConfig, RepoConfig + + +class RepoSyncService: + """Owns git mirror/worktree management for centrally indexed repos.""" + + def __init__(self, config: MimirConfig) -> None: + self._config = config + self._repos_by_name = {repo.name: repo for repo in config.repos} + self._repos_by_webhook = { + (repo.webhook_repo or repo.name): repo for repo in config.repos + } + + def is_enabled(self) -> bool: + return self._config.admin.enable_repo_sync + + def resolve_webhook_repo(self, repo_name: str) -> RepoConfig: + repo = self._repos_by_webhook.get(repo_name) + if repo is None: + raise ValueError(f"Unknown webhook repo: {repo_name}") + return repo + + def verify_signature(self, body: bytes, signature_header: str | None) -> bool: + secret = self._secret() + if not secret: + return False + if not signature_header: + return False + provided = signature_header.strip() + if "=" in provided: + _, provided = provided.split("=", 1) + expected = hmac.new(secret.encode("utf-8"), body, sha256).hexdigest() + return hmac.compare_digest(provided, expected) + + async def sync_repo(self, repo_name: str, *, commit_sha: Optional[str] = None) -> dict: + repo = self._repos_by_name.get(repo_name) + if repo is None: + raise ValueError(f"Unknown repo: {repo_name}") + if not repo.clone_url: + raise ValueError(f"Repo '{repo_name}' is not configured for central sync") + + mirror_dir = self._mirror_dir(repo) + worktree_dir = Path(repo.path) + + await asyncio.to_thread(self._ensure_checkout, repo, mirror_dir, worktree_dir, commit_sha) + return { + "repo": repo.name, + "branch": repo.branch, + "commit": self.current_commit(repo.name), + "path": str(worktree_dir), + } + + def current_commit(self, repo_name: str) -> Optional[str]: + try: + import git + + repo = git.Repo(str(self._repos_by_name[repo_name].path)) + return repo.head.commit.hexsha + except Exception: + return None + + def _secret(self) -> Optional[str]: + env = self._config.admin.webhook_secret_env + if not env: + return None + return os.environ.get(env) + + def _mirror_dir(self, repo: RepoConfig) -> Path: + root = self._config.admin.mirrors_dir or str(self._config.session_dir / "mirrors") + root_path = Path(root) + root_path.mkdir(parents=True, exist_ok=True) + return root_path / f"{repo.name}.git" + + def _ensure_checkout( + self, + repo: RepoConfig, + mirror_dir: Path, + worktree_dir: Path, + commit_sha: Optional[str], + ) -> None: + import git + + if mirror_dir.exists(): + git.Repo(str(mirror_dir)).remote().fetch(prune=True) + mirror = git.Repo(str(mirror_dir)) + else: + mirror = git.Repo.clone_from(repo.clone_url, str(mirror_dir), mirror=True) + + target_ref = commit_sha or f"origin/{repo.branch}" + if commit_sha: + try: + mirror.commit(commit_sha) + except Exception as exc: + raise ValueError(f"Commit {commit_sha} not found in mirror for {repo.name}") from exc + + worktree_dir.parent.mkdir(parents=True, exist_ok=True) + if not worktree_dir.exists(): + checkout_repo = git.Repo.clone_from(str(mirror_dir), str(worktree_dir)) + else: + checkout_repo = git.Repo(str(worktree_dir)) + + checkout_repo.remote().fetch(prune=True) + checkout_repo.git.checkout("-B", repo.branch, f"origin/{repo.branch}") + checkout_repo.git.reset("--hard", target_ref) + + +def parse_webhook_payload(body: bytes) -> dict: + payload = json.loads(body.decode("utf-8")) + repository = payload.get("repository") + repo_from_repository = None + if isinstance(repository, dict): + repo_from_repository = repository.get("name") + elif isinstance(repository, str): + repo_from_repository = repository + repo = ( + payload.get("repo") + or repo_from_repository + ) + branch = payload.get("branch") or payload.get("ref") + commit_sha = ( + payload.get("commit_sha") + or payload.get("after") + or payload.get("checkout_sha") + ) + if isinstance(branch, str) and branch.startswith("refs/heads/"): + branch = branch.removeprefix("refs/heads/") + return {"repo": repo, "branch": branch, "commit_sha": commit_sha, "raw": payload} diff --git a/mimir/services/retrieval/__init__.py b/mimir/services/retrieval/__init__.py new file mode 100644 index 0000000..70c8aeb --- /dev/null +++ b/mimir/services/retrieval/__init__.py @@ -0,0 +1,5 @@ +"""Retrieval sub-package — context assembly engine.""" + +from mimir.services.retrieval.service import RetrievalService + +__all__ = ["RetrievalService"] diff --git a/mimir/services/retrieval/graph_ops.py b/mimir/services/retrieval/graph_ops.py new file mode 100644 index 0000000..eb1ece7 --- /dev/null +++ b/mimir/services/retrieval/graph_ops.py @@ -0,0 +1,204 @@ +"""Subgraph assembly and metadata helpers for retrieval.""" + +from __future__ import annotations + +import math +from datetime import datetime, timezone +from typing import Optional + +from mimir.domain.config import MimirConfig +from mimir.domain.graph import CodeGraph +from mimir.domain.models import EDGE_EXPANSION_WEIGHTS, EdgeKind, Node, NodeKind +from mimir.domain.subgraph import SubGraph + + +class RetrievalGraphOps: + """Owns subgraph expansion, pruning, ordering, and metadata updates.""" + + def __init__( + self, + config: MimirConfig, + *, + quality_service=None, + temporal_service=None, + graph_store=None, + ) -> None: + self._config = config + self._quality_service = quality_service + self._temporal_service = temporal_service + self._graph_store = graph_store + + def expand_subgraph( + self, + seeds: list[Node], + seed_scores: dict[str, float], + query_embedding: list[float], + graph: CodeGraph, + *, + hops: Optional[int] = None, + gate: Optional[float] = None, + ) -> SubGraph: + hops = hops if hops is not None else self._config.retrieval.expansion_hops + gate = gate if gate is not None else self._config.retrieval.relevance_gate + + subgraph = SubGraph() + for seed in seeds: + subgraph.add_node(seed.clone(), score=seed_scores.get(seed.id, 1.0)) + + frontier = {seed.id for seed in seeds} + visited: set[str] = set() + for _ in range(hops): + next_frontier: set[str] = set() + for node_id in frontier: + if node_id in visited: + continue + visited.add(node_id) + + for edge in graph.get_all_edges_for(node_id): + target_id = edge.target if edge.source == node_id else edge.source + if target_id in visited or target_id in subgraph.node_ids: + if subgraph.has_node(target_id): + subgraph.add_edge(edge) + continue + + target = graph.get_node(target_id) + if target is None: + continue + + if target.embedding and query_embedding: + similarity = self.cosine_similarity(query_embedding, target.embedding) + if similarity < gate: + continue + else: + similarity = 0.5 + + score = similarity * EDGE_EXPANSION_WEIGHTS.get(edge.kind, 0.5) + subgraph.add_node(target.clone(), score=score) + subgraph.add_edge(edge) + next_frontier.add(target_id) + + frontier = next_frontier + + return subgraph + + @staticmethod + def add_type_context(subgraph: SubGraph, graph: CodeGraph) -> None: + for node in list(subgraph.nodes.values()): + for edge in graph.get_outgoing_edges(node.id, EdgeKind.USES_TYPE): + type_node = graph.get_node(edge.target) + if type_node is not None and not subgraph.has_node(type_node.id): + subgraph.add_node(type_node.clone(), score=0.3) + subgraph.add_edge(edge) + + @staticmethod + def add_config_context(subgraph: SubGraph, graph: CodeGraph) -> None: + for node in list(subgraph.nodes.values()): + for edge in graph.get_outgoing_edges(node.id, EdgeKind.READS_CONFIG): + cfg_node = graph.get_node(edge.target) + if cfg_node is not None and not subgraph.has_node(cfg_node.id): + subgraph.add_node(cfg_node.clone(), score=0.2) + subgraph.add_edge(edge) + + def fit_to_budget(self, subgraph: SubGraph, budget: int, seed_ids: set[str]) -> None: + while subgraph.token_estimate > budget: + candidate = self.find_least_important_leaf(subgraph, seed_ids) + if candidate is None: + break + if candidate.raw_code and candidate.summary: + candidate.raw_code = None + if subgraph.token_estimate <= budget: + break + subgraph.remove_node(candidate.id) + + @staticmethod + def find_least_important_leaf(subgraph: SubGraph, seed_ids: set[str]) -> Optional[Node]: + targets = {edge.target for edge in subgraph.edges} + leaves = [ + node + for node in subgraph.nodes.values() + if node.id not in seed_ids and node.id not in targets + ] + if not leaves: + leaves = [node for node in subgraph.nodes.values() if node.id not in seed_ids] + if not leaves: + return None + return min(leaves, key=lambda node: subgraph.scores.get(node.id, 0.0)) + + @staticmethod + def topological_order(subgraph: SubGraph) -> list[Node]: + nodes = list(subgraph.nodes.values()) + types: list[Node] = [] + configs: list[Node] = [] + leaves: list[Node] = [] + others: list[Node] = [] + callee_ids = {edge.target for edge in subgraph.edges} + + for node in nodes: + if node.kind == NodeKind.TYPE: + types.append(node) + elif node.kind in (NodeKind.CONFIG, NodeKind.CONSTANT): + configs.append(node) + elif node.id not in callee_ids: + leaves.append(node) + else: + others.append(node) + + key = lambda node: subgraph.scores.get(node.id, 0.0) + types.sort(key=key, reverse=True) + configs.sort(key=key, reverse=True) + others.sort(key=key, reverse=True) + leaves.sort(key=key, reverse=True) + return types + configs + others + leaves + + def update_retrieval_metadata( + self, + nodes: list[Node], + *, + graph: Optional[CodeGraph] = None, + ) -> None: + now = datetime.now(timezone.utc).isoformat() + persisted_nodes: list[Node] = [] + seen_ids: set[str] = set() + for node in nodes: + target = graph.get_node(node.id) if graph is not None else node + if target is None or target.id in seen_ids: + continue + target.retrieval_count += 1 + target.last_retrieved = now + node.retrieval_count = target.retrieval_count + node.last_retrieved = target.last_retrieved + persisted_nodes.append(target) + seen_ids.add(target.id) + + if self._temporal_service is not None and persisted_nodes: + self._temporal_service.update_co_retrieval(persisted_nodes) + for node in nodes: + target = graph.get_node(node.id) if graph is not None else node + if target is not None: + node.co_retrieved_with = dict(target.co_retrieved_with) + + if self._graph_store is not None and persisted_nodes: + self._graph_store.update_retrieval_metadata(persisted_nodes) + + def apply_quality_adjustment(self, subgraph: SubGraph, graph: CodeGraph) -> None: + if self._quality_service is None: + return + for node_id, node in subgraph.nodes.items(): + original = subgraph.scores.get(node_id, 0.5) + quality = self._quality_service.compute_quality_score(node, graph) + subgraph.scores[node_id] = 0.85 * original + 0.15 * quality + + @staticmethod + def cosine_similarity(a: list[float], b: list[float]) -> float: + dot = sum(x * y for x, y in zip(a, b)) + norm_a = math.sqrt(sum(x * x for x in a)) + norm_b = math.sqrt(sum(x * x for x in b)) + if norm_a == 0 or norm_b == 0: + return 0.0 + return dot / (norm_a * norm_b) + + @staticmethod + def generate_summary(subgraph: SubGraph, query: str) -> str: + repos = subgraph.repos_involved + node_count = len(subgraph.nodes) + return f"Context for: \"{query}\" — {node_count} nodes from {', '.join(repos) if repos else 'unknown'}" diff --git a/mimir/services/retrieval/matching.py b/mimir/services/retrieval/matching.py new file mode 100644 index 0000000..b677da0 --- /dev/null +++ b/mimir/services/retrieval/matching.py @@ -0,0 +1,179 @@ +"""Search and matching helpers for retrieval.""" + +from __future__ import annotations + +import re +from typing import Optional + +from mimir.domain.config import MimirConfig +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Node, NodeKind +from mimir.ports.vector_store import VectorStore + + +class RetrievalMatchingOps: + """Owns vector, name, and route seed-selection logic.""" + + _STOPWORDS = frozenset({ + "the", "a", "an", "is", "are", "was", "were", "be", "been", + "do", "does", "did", "has", "have", "had", "in", "on", "at", + "to", "for", "of", "with", "by", "from", "and", "or", "not", + "it", "its", "this", "that", "how", "what", "where", "when", + "why", "who", "which", "all", "each", "every", "any", "my", + "your", "our", "use", "get", "set", "can", "will", "should", + "about", "into", "out", "up", "down", "code", "function", + "class", "method", "file", "does", "work", "show", "find", + }) + _ROUTE_PATTERN = re.compile( + r""" + (?:(?PGET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s+)? + (?P/[^\s]*) + """, + re.VERBOSE | re.IGNORECASE, + ) + + def __init__(self, config: MimirConfig, vector_store: VectorStore | None) -> None: + self._config = config + self._vector_store = vector_store + + def flat_search( + self, + query_embedding: list[float], + graph: CodeGraph, + *, + top_k: int = 20, + where: Optional[dict] = None, + ) -> list[tuple[Node, float]]: + if self._vector_store is None: + raise RuntimeError("Vector store is required for flat_search") + results = self._vector_store.search(query_embedding, top_k=top_k, where=where) + return [ + (node, result.score) + for result in results + if (node := graph.get_node(result.id)) is not None + ] + + def hierarchical_beam_search( + self, + query_embedding: list[float], + graph: CodeGraph, + beam_width: int, + *, + where: Optional[dict] = None, + ) -> list[tuple[Node, float]]: + if self._vector_store is None: + raise RuntimeError("Vector store is required for hierarchical_beam_search") + candidates: list[tuple[Node, float]] = [] + + for level_kind in (NodeKind.REPOSITORY, NodeKind.MODULE, NodeKind.FILE): + level_filter = {"kind": level_kind.value} if not where else {**where, "kind": level_kind.value} + level_results = self._vector_store.search( + query_embedding, + top_k=beam_width, + where=level_filter, + ) + for result in level_results[:beam_width]: + node = graph.get_node(result.id) + if node is not None: + candidates.append((node, result.score)) + + symbol_results = self._vector_store.search( + query_embedding, + top_k=beam_width * 3, + where=where, + ) + for result in symbol_results: + node = graph.get_node(result.id) + if node is not None and node.is_symbol: + candidates.append((node, result.score)) + + seen: set[str] = set() + unique: list[tuple[Node, float]] = [] + for node, score in sorted(candidates, key=lambda item: item[1], reverse=True): + if node.id in seen: + continue + seen.add(node.id) + unique.append((node, score)) + return unique[: beam_width * 3] + + @classmethod + def split_name(cls, name: str) -> set[str]: + parts = re.sub(r"([a-z])([A-Z])", r"\1 \2", name) + parts = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", parts) + tokens = re.split(r"[^a-zA-Z0-9]+", parts) + return {token.lower() for token in tokens if len(token) > 1} + + def name_match_seeds( + self, + query: str, + graph: CodeGraph, + repos: Optional[list[str]] = None, + ) -> list[tuple[Node, float]]: + query_words = set() + for word in query.split(): + query_words |= self.split_name(word) + query_words = {word for word in query_words if len(word) > 2 and word not in self._STOPWORDS} + if not query_words: + return [] + + boost = self._config.retrieval.hybrid_alpha + matches: list[tuple[Node, float]] = [] + for node in graph.all_nodes(): + if repos and node.repo not in repos: + continue + + overlap = query_words & self.split_name(node.name) + if overlap: + ratio = len(overlap) / len(query_words) + matches.append((node, boost * (0.5 + 0.5 * ratio))) + continue + + if node.path: + path_lower = node.path.lower() + if any(word in path_lower for word in query_words): + matches.append((node, boost * 0.4)) + + matches.sort(key=lambda item: item[1], reverse=True) + return matches[:30] + + @classmethod + def route_match_seeds( + cls, + query: str, + graph: CodeGraph, + repos: Optional[list[str]] = None, + ) -> list[tuple[Node, float]]: + match = cls._ROUTE_PATTERN.search(query) + if not match: + return [] + + query_method = (match.group("method") or "").upper() + query_path = match.group("path").rstrip("/").lower() or "/" + query_path_collapsed = re.sub(r"\{[^}]+\}", "{_}", query_path) + + matches: list[tuple[Node, float]] = [] + for node in graph.all_nodes(): + if node.kind != NodeKind.API_ENDPOINT or not node.route_path: + continue + if repos and node.repo not in repos: + continue + + node_path = node.route_path.rstrip("/").lower() or "/" + node_path_collapsed = re.sub(r"\{[^}]+\}", "{_}", node_path) + if node_path_collapsed != query_path_collapsed: + if not ( + node_path_collapsed.endswith(query_path_collapsed) + and ( + len(node_path_collapsed) == len(query_path_collapsed) + or node_path_collapsed[-len(query_path_collapsed) - 1] == "/" + ) + ): + continue + + score = 1.0 + if query_method and node.http_method: + score = 1.2 if query_method == node.http_method.upper() else 0.6 + matches.append((node, score)) + + matches.sort(key=lambda item: item[1], reverse=True) + return matches diff --git a/mimir/services/retrieval.py b/mimir/services/retrieval/service.py similarity index 50% rename from mimir/services/retrieval.py rename to mimir/services/retrieval/service.py index da3bd08..a172ab7 100644 --- a/mimir/services/retrieval.py +++ b/mimir/services/retrieval/service.py @@ -7,19 +7,18 @@ from __future__ import annotations import logging -import math import re -from collections import defaultdict -from datetime import datetime, timezone from typing import TYPE_CHECKING, Optional from mimir.domain.config import MimirConfig from mimir.domain.graph import CodeGraph -from mimir.domain.models import SYMBOL_KINDS, Edge, EdgeKind, Node, NodeKind, EDGE_EXPANSION_WEIGHTS +from mimir.domain.models import Node, NodeKind from mimir.domain.subgraph import ContextBundle, SubGraph from mimir.ports.embedder import Embedder from mimir.ports.vector_store import VectorStore from mimir.services.intent import classify_intent, INTENT_PROFILES +from mimir.services.retrieval.graph_ops import RetrievalGraphOps +from mimir.services.retrieval.matching import RetrievalMatchingOps from mimir.ports.graph_store import GraphStore @@ -41,6 +40,7 @@ def __init__( quality_service: Optional[QualityService] = None, temporal_service: Optional[TemporalService] = None, graph_store: Optional[GraphStore] = None, + record_retrieval_metadata: bool = True, ) -> None: self._config = config self._embedder = embedder @@ -48,6 +48,33 @@ def __init__( self._quality_service = quality_service self._temporal_service = temporal_service self._graph_store = graph_store + self._record_retrieval_metadata = record_retrieval_metadata + self._matching_ops = RetrievalMatchingOps(config, vector_store) + self._graph_ops = RetrievalGraphOps( + config, + quality_service=quality_service, + temporal_service=temporal_service, + graph_store=graph_store, + ) + + def _matching_component(self) -> RetrievalMatchingOps: + component = getattr(self, "_matching_ops", None) + if component is None: + component = RetrievalMatchingOps(self._config, getattr(self, "_vector_store", None)) + self._matching_ops = component + return component + + def _graph_component(self) -> RetrievalGraphOps: + component = getattr(self, "_graph_ops", None) + if component is None: + component = RetrievalGraphOps( + self._config, + quality_service=getattr(self, "_quality_service", None), + temporal_service=getattr(self, "_temporal_service", None), + graph_store=getattr(self, "_graph_store", None), + ) + self._graph_ops = component + return component async def search( self, @@ -195,7 +222,7 @@ async def search( self._fit_to_budget(subgraph, budget, seed_ids={n.id for n in seed_nodes}) # Step 6: Update retrieval metadata on retrieved nodes - self._update_retrieval_metadata(list(subgraph.nodes.values())) + self._update_retrieval_metadata(list(subgraph.nodes.values()), graph=graph) # Step 7: Topological ordering ordered = self._topological_order(subgraph) @@ -218,6 +245,11 @@ async def search( _bm25_index = None _bm25_node_ids: list[str] = [] + @property + def default_token_budget(self) -> int: + """Configured default token budget used when none is supplied.""" + return self._config.retrieval.default_token_budget + def invalidate_bm25(self) -> None: """Reset the cached BM25 index, forcing rebuild on next search.""" self._bm25_index = None @@ -305,14 +337,12 @@ def _flat_search( top_k: int = 20, where: Optional[dict] = None, ) -> list[tuple[Node, float]]: - """Flat vector search (none mode).""" - results = self._vector_store.search(query_embedding, top_k=top_k, where=where) - out: list[tuple[Node, float]] = [] - for r in results: - node = graph.get_node(r.id) - if node: - out.append((node, r.score)) - return out + return self._matching_component().flat_search( + query_embedding, + graph, + top_k=top_k, + where=where, + ) def _hierarchical_beam_search( self, @@ -321,73 +351,20 @@ def _hierarchical_beam_search( beam_width: int, where: Optional[dict] = None, ) -> list[tuple[Node, float]]: - """Top-down beam search: repo → module → file → symbol.""" - candidates: list[tuple[Node, float]] = [] - - # Search at each hierarchy level, keeping top-k at each stage - for level_kind in [NodeKind.REPOSITORY, NodeKind.MODULE, NodeKind.FILE]: - level_results = self._vector_store.search( - query_embedding, - top_k=beam_width, - where={"kind": level_kind.value} if not where else {**(where or {}), "kind": level_kind.value}, - ) - # Keep beam_width candidates for next level - for r in level_results[:beam_width]: - node = graph.get_node(r.id) - if node: - candidates.append((node, r.score)) - - # Final search at symbol level - symbol_results = self._vector_store.search( + return self._matching_component().hierarchical_beam_search( query_embedding, - top_k=beam_width * 3, + graph, + beam_width, where=where, ) - for r in symbol_results: - node = graph.get_node(r.id) - if node and node.is_symbol: - candidates.append((node, r.score)) - - # Sort by score, deduplicate - seen: set[str] = set() - unique: list[tuple[Node, float]] = [] - for node, score in sorted(candidates, key=lambda x: x[1], reverse=True): - if node.id not in seen: - seen.add(node.id) - unique.append((node, score)) - - return unique[:beam_width * 3] # ------------------------------------------------------------------ # Name matching # ------------------------------------------------------------------ - _STOPWORDS = frozenset({ - "the", "a", "an", "is", "are", "was", "were", "be", "been", - "do", "does", "did", "has", "have", "had", "in", "on", "at", - "to", "for", "of", "with", "by", "from", "and", "or", "not", - "it", "its", "this", "that", "how", "what", "where", "when", - "why", "who", "which", "all", "each", "every", "any", "my", - "your", "our", "use", "get", "set", "can", "will", "should", - "about", "into", "out", "up", "down", "code", "function", - "class", "method", "file", "does", "work", "show", "find", - }) - @staticmethod def _split_name(name: str) -> set[str]: - """Split a symbol name into lowercase words. - - Handles camelCase, PascalCase, snake_case, and kebab-case. - e.g. "HomeView" → {"home", "view"} - "get_user_name" → {"get", "user", "name"} - """ - # Insert boundary before uppercase runs: "HomeView" → "Home View" - parts = re.sub(r"([a-z])([A-Z])", r"\1 \2", name) - # Split acronym runs: "XMLParser" → "XML Parser" - parts = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", parts) - # Split on non-alphanumeric - tokens = re.split(r"[^a-zA-Z0-9]+", parts) - return {t.lower() for t in tokens if len(t) > 1} + return RetrievalMatchingOps.split_name(name) def _name_match_seeds( self, @@ -395,115 +372,19 @@ def _name_match_seeds( graph: CodeGraph, repos: Optional[list[str]] = None, ) -> list[tuple[Node, float]]: - """Find nodes whose name or path matches words in the query.""" - # Extract significant words from query - query_words = set() - for w in query.split(): - # Also split query words by camelCase in case user writes "HomeView" - query_words |= self._split_name(w) - query_words = {w for w in query_words if len(w) > 2 and w not in self._STOPWORDS} - - if not query_words: - return [] - - boost = self._config.retrieval.hybrid_alpha - matches: list[tuple[Node, float]] = [] - - for node in graph.all_nodes(): - if repos and node.repo not in repos: - continue - - # Split node name into words for matching - name_words = self._split_name(node.name) - overlap = query_words & name_words - - if overlap: - # Score based on fraction of query words matched - ratio = len(overlap) / len(query_words) - score = boost * (0.5 + 0.5 * ratio) # range: 0.5*boost → boost - matches.append((node, score)) - continue - - # Path matching: check if query words appear in the file path - if node.path: - path_lower = node.path.lower() - for word in query_words: - if word in path_lower: - matches.append((node, boost * 0.4)) - break - - # Sort by score desc, cap results - matches.sort(key=lambda x: x[1], reverse=True) - return matches[:30] + return self._matching_component().name_match_seeds(query, graph, repos) # ------------------------------------------------------------------ # Route matching # ------------------------------------------------------------------ - _HTTP_METHODS = frozenset({"get", "post", "put", "delete", "patch", "head", "options"}) - - _ROUTE_PATTERN = re.compile( - r""" - (?:(?PGET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s+)? # optional HTTP method - (?P/[^\s]*) # path starting with / - """, - re.VERBOSE | re.IGNORECASE, - ) - def _route_match_seeds( self, query: str, graph: CodeGraph, repos: Optional[list[str]] = None, ) -> list[tuple[Node, float]]: - """Find API_ENDPOINT nodes whose route matches a path in the query. - - Detects route-shaped patterns like ``/orders``, ``POST /users/{id}``, - or ``GET /api/health`` in the query text and matches them against - stored ``route_path`` / ``http_method`` on API_ENDPOINT nodes. - """ - match = self._ROUTE_PATTERN.search(query) - if not match: - return [] - - query_method = (match.group("method") or "").upper() - query_path = match.group("path").rstrip("/").lower() or "/" - - matches: list[tuple[Node, float]] = [] - for node in graph.all_nodes(): - if node.kind != NodeKind.API_ENDPOINT or not node.route_path: - continue - if repos and node.repo not in repos: - continue - - node_path = node.route_path.rstrip("/").lower() or "/" - # Strip path params for comparison: /orders/{id} → /orders/ - node_path_collapsed = re.sub(r'\{[^}]+\}', '{_}', node_path) - query_path_collapsed = re.sub(r'\{[^}]+\}', '{_}', query_path) - - if node_path_collapsed != query_path_collapsed: - # Also try suffix match: query /orders matches node /api/v1/orders - if not ( - node_path_collapsed.endswith(query_path_collapsed) - and ( - len(node_path_collapsed) == len(query_path_collapsed) - or node_path_collapsed[-len(query_path_collapsed) - 1] == "/" - ) - ): - continue - - # Path matches — compute score - score = 1.0 # high base score for exact route match - if query_method and node.http_method: - if query_method == node.http_method.upper(): - score = 1.2 # method + path match → highest priority - else: - score = 0.6 # path matches but wrong method → still relevant - - matches.append((node, score)) - - matches.sort(key=lambda x: x[1], reverse=True) - return matches + return self._matching_component().route_match_seeds(query, graph, repos) # ------------------------------------------------------------------ # Subgraph expansion @@ -519,74 +400,20 @@ def _expand_subgraph( hops: Optional[int] = None, gate: Optional[float] = None, ) -> SubGraph: - """BFS expansion from seeds, following dependency edges.""" - hops = hops if hops is not None else self._config.retrieval.expansion_hops - gate = gate if gate is not None else self._config.retrieval.relevance_gate - - subgraph = SubGraph() - for seed in seeds: - subgraph.add_node(seed, score=seed_scores.get(seed.id, 1.0)) - - frontier = {s.id for s in seeds} - visited: set[str] = set() - - for hop in range(hops): - next_frontier: set[str] = set() - for node_id in frontier: - if node_id in visited: - continue - visited.add(node_id) - - for edge in graph.get_all_edges_for(node_id): - target_id = edge.target if edge.source == node_id else edge.source - if target_id in visited or target_id in subgraph.node_ids: - # Still add the edge for connectivity - if subgraph.has_node(target_id): - subgraph.add_edge(edge) - continue - - target = graph.get_node(target_id) - if target is None: - continue - - # Relevance gate: check if target is related to query - if target.embedding and query_embedding: - sim = self._cosine_similarity(query_embedding, target.embedding) - if sim < gate: - continue - else: - sim = 0.5 # unknown, moderate weight - - edge_weight = EDGE_EXPANSION_WEIGHTS.get(edge.kind, 0.5) - score = sim * edge_weight - - subgraph.add_node(target, score=score) - subgraph.add_edge(edge) - next_frontier.add(target_id) - - frontier = next_frontier - - return subgraph + return self._graph_component().expand_subgraph( + seeds, + seed_scores, + query_embedding, + graph, + hops=hops, + gate=gate, + ) def _add_type_context(self, subgraph: SubGraph, graph: CodeGraph) -> None: - """Add type definitions used by nodes in the subgraph.""" - for node in list(subgraph.nodes.values()): - type_edges = graph.get_outgoing_edges(node.id, EdgeKind.USES_TYPE) - for edge in type_edges: - type_node = graph.get_node(edge.target) - if type_node and not subgraph.has_node(type_node.id): - subgraph.add_node(type_node, score=0.3) - subgraph.add_edge(edge) + self._graph_component().add_type_context(subgraph, graph) def _add_config_context(self, subgraph: SubGraph, graph: CodeGraph) -> None: - """Add config nodes read by nodes in the subgraph.""" - for node in list(subgraph.nodes.values()): - config_edges = graph.get_outgoing_edges(node.id, EdgeKind.READS_CONFIG) - for edge in config_edges: - cfg_node = graph.get_node(edge.target) - if cfg_node and not subgraph.has_node(cfg_node.id): - subgraph.add_node(cfg_node, score=0.2) - subgraph.add_edge(edge) + self._graph_component().add_config_context(subgraph, graph) # ------------------------------------------------------------------ # Budget fitting @@ -598,39 +425,24 @@ def _fit_to_budget( budget: int, seed_ids: set[str], ) -> None: - """Prune least important nodes until subgraph fits in token budget.""" - while subgraph.token_estimate > budget: - # Find least important non-seed leaf - candidate = self._find_least_important_leaf(subgraph, seed_ids) - if candidate is None: - break - - # First try: replace code with summary - if candidate.raw_code and candidate.summary: - candidate.raw_code = None # keep summary only - if subgraph.token_estimate <= budget: - break + self._graph_component().fit_to_budget(subgraph, budget, seed_ids) - # Still over: remove entirely - subgraph.remove_node(candidate.id) + def fit_subgraph_to_budget( + self, + subgraph: SubGraph, + budget: int, + *, + seed_ids: Optional[set[str]] = None, + ) -> None: + """Public budget-fit wrapper used by transport adapters.""" + self._fit_to_budget(subgraph, budget, seed_ids=seed_ids or set()) @staticmethod def _find_least_important_leaf( subgraph: SubGraph, seed_ids: set[str], ) -> Optional[Node]: - """Find the least important non-seed leaf node.""" - targets = {e.target for e in subgraph.edges} - leaves = [ - n for n in subgraph.nodes.values() - if n.id not in seed_ids and n.id not in targets - ] - if not leaves: - # Try non-seed nodes - leaves = [n for n in subgraph.nodes.values() if n.id not in seed_ids] - if not leaves: - return None - return min(leaves, key=lambda n: subgraph.scores.get(n.id, 0.0)) + return RetrievalGraphOps.find_least_important_leaf(subgraph, seed_ids) # ------------------------------------------------------------------ # Ordering @@ -638,69 +450,28 @@ def _find_least_important_leaf( @staticmethod def _topological_order(subgraph: SubGraph) -> list[Node]: - """Order nodes for LLM comprehension: types → configs → leaves → callers.""" - nodes = list(subgraph.nodes.values()) - - # Group by category - types: list[Node] = [] - configs: list[Node] = [] - leaves: list[Node] = [] - others: list[Node] = [] - - callee_ids = {e.target for e in subgraph.edges} - - for node in nodes: - if node.kind == NodeKind.TYPE: - types.append(node) - elif node.kind in (NodeKind.CONFIG, NodeKind.CONSTANT): - configs.append(node) - elif node.id not in callee_ids: - leaves.append(node) - else: - others.append(node) - - # Sort each group by score (most relevant first) - key = lambda n: subgraph.scores.get(n.id, 0.0) - types.sort(key=key, reverse=True) - configs.sort(key=key, reverse=True) - others.sort(key=key, reverse=True) - leaves.sort(key=key, reverse=True) - - return types + configs + others + leaves + return RetrievalGraphOps.topological_order(subgraph) # ------------------------------------------------------------------ # Retrieval metadata # ------------------------------------------------------------------ - def _update_retrieval_metadata(self, nodes: list[Node]) -> None: - """Update retrieval_count, last_retrieved, and co-retrieval on nodes.""" - now = datetime.now(timezone.utc).isoformat() - for node in nodes: - node.retrieval_count += 1 - node.last_retrieved = now - - # Update co-retrieval counts - if self._temporal_service is not None: - self._temporal_service.update_co_retrieval(nodes) - - # Persist to graph store - if self._graph_store is not None: - self._graph_store.update_retrieval_metadata(nodes) + def _update_retrieval_metadata( + self, + nodes: list[Node], + *, + graph: Optional[CodeGraph] = None, + ) -> None: + if not self._record_retrieval_metadata: + return + self._graph_component().update_retrieval_metadata(nodes, graph=graph) # ------------------------------------------------------------------ # Quality adjustment # ------------------------------------------------------------------ def _apply_quality_adjustment(self, subgraph: SubGraph, graph: CodeGraph) -> None: - """Blend connectivity quality into subgraph scores. - - Adjusts each node's score by blending in its quality score: - adjusted = 0.85 * original + 0.15 * quality - """ - for node_id, node in subgraph.nodes.items(): - original = subgraph.scores.get(node_id, 0.5) - quality = self._quality_service.compute_quality_score(node, graph) - subgraph.scores[node_id] = 0.85 * original + 0.15 * quality + self._graph_component().apply_quality_adjustment(subgraph, graph) # ------------------------------------------------------------------ # Utilities @@ -708,20 +479,8 @@ def _apply_quality_adjustment(self, subgraph: SubGraph, graph: CodeGraph) -> Non @staticmethod def _cosine_similarity(a: list[float], b: list[float]) -> float: - dot = sum(x * y for x, y in zip(a, b)) - norm_a = math.sqrt(sum(x * x for x in a)) - norm_b = math.sqrt(sum(x * x for x in b)) - if norm_a == 0 or norm_b == 0: - return 0.0 - return dot / (norm_a * norm_b) + return RetrievalGraphOps.cosine_similarity(a, b) @staticmethod def _generate_summary(subgraph: SubGraph, query: str) -> str: - repos = subgraph.repos_involved - node_count = len(subgraph.nodes) - return ( - f"Context for: \"{query}\" — {node_count} nodes " - f"from {', '.join(repos) if repos else 'unknown'}" - ) - - + return RetrievalGraphOps.generate_summary(subgraph, query) diff --git a/mimir/services/session.py b/mimir/services/session.py index d36060d..4279822 100644 --- a/mimir/services/session.py +++ b/mimir/services/session.py @@ -6,7 +6,7 @@ import math import uuid from datetime import datetime, timezone -from typing import Optional +from typing import TYPE_CHECKING, Optional from mimir.domain.config import MimirConfig from mimir.domain.models import Node @@ -14,6 +14,9 @@ from mimir.domain.subgraph import SubGraph from mimir.ports.session_store import SessionStore +if TYPE_CHECKING: + from mimir.services.feedback import FeedbackService + logger = logging.getLogger(__name__) @@ -29,6 +32,11 @@ def __init__( self._store = session_store self._decay_turns = config.session.context_decay_turns self._topic_alpha = config.session.topic_tracking_alpha + self._feedback_service: Optional[FeedbackService] = None + + def set_feedback_service(self, feedback_service: FeedbackService) -> None: + """Inject the feedback service for implicit signal recording.""" + self._feedback_service = feedback_service def get_or_create(self, session_id: Optional[str] = None) -> Session: """Load an existing session or create a new one.""" @@ -136,6 +144,12 @@ def record_retrieval( ) if query_embedding: self.update_topic(session, query_embedding) + # Record implicit feedback before pruning + if self._feedback_service is not None: + try: + self._feedback_service.record_implicit(session) + except Exception: + logger.warning("Implicit feedback recording failed", exc_info=True) # Prune to prevent unbounded growth before persisting session.prune() self._store.save(session) diff --git a/mimir/services/temporal.py b/mimir/services/temporal.py index 7c1b379..c0628ff 100644 --- a/mimir/services/temporal.py +++ b/mimir/services/temporal.py @@ -13,6 +13,7 @@ from mimir.domain.subgraph import SubGraph if TYPE_CHECKING: + from mimir.services.feedback import FeedbackService from mimir.services.quality import QualityService logger = logging.getLogger(__name__) @@ -26,11 +27,16 @@ def __init__(self, config: MimirConfig) -> None: self._change_window = config.temporal.change_window_commits self._co_retrieval_enabled = config.temporal.co_retrieval_enabled self._quality_service: Optional[QualityService] = None + self._feedback_service: Optional[FeedbackService] = None def set_quality_service(self, quality_service: QualityService) -> None: """Inject the quality service for connectivity-aware reranking.""" self._quality_service = quality_service + def set_feedback_service(self, feedback_service: FeedbackService) -> None: + """Inject the feedback service for learned retrieval weights.""" + self._feedback_service = feedback_service + def temporal_weight(self, node: Node, now: Optional[datetime] = None) -> float: """Exponential decay based on last modification time. @@ -53,18 +59,36 @@ def temporal_weight(self, node: Node, now: Optional[datetime] = None) -> float: def apply_temporal_weights( self, subgraph: SubGraph, graph: Optional[CodeGraph] = None, ) -> None: - """Rerank nodes in a subgraph using temporal and quality signals. + """Rerank nodes in a subgraph using temporal, quality, and feedback signals. + + With quality + feedback: + final = 0.40*retrieval + 0.16*recency + 0.10*change_freq + + 0.10*co_retrieval + 0.12*quality + 0.12*feedback - When a quality service is available and a graph is provided: + With quality only: final = 0.45*retrieval + 0.18*recency + 0.12*change_freq + 0.12*co_retrieval + 0.13*quality - Without quality: + With feedback only: + final = 0.45*retrieval + 0.18*recency + 0.12*change_freq + + 0.12*co_retrieval + 0.13*feedback + + Without quality or feedback: final = 0.50*retrieval + 0.20*recency + 0.15*change_freq + 0.15*co_retrieval """ now = datetime.now(timezone.utc) use_quality = self._quality_service is not None and graph is not None + use_feedback = ( + self._feedback_service is not None + and self._feedback_service.enabled + ) + + # Pre-fetch feedback weights in bulk if available + feedback_weights: dict[str, float] = {} + if use_feedback: + node_ids = list(subgraph.nodes.keys()) + feedback_weights = self._feedback_service.get_feedback_weights(node_ids) for node_id, node in subgraph.nodes.items(): retrieval_score = subgraph.scores.get(node_id, 0.5) @@ -72,7 +96,18 @@ def apply_temporal_weights( change_freq = self._change_frequency_weight(node) co_ret = self._co_retrieval_weight(node, subgraph) if self._co_retrieval_enabled else 0.0 - if use_quality: + if use_quality and use_feedback: + quality = self._quality_service.compute_quality_score(node, graph) + feedback = feedback_weights.get(node_id, 0.5) + final = ( + 0.40 * retrieval_score + + 0.16 * recency + + 0.10 * change_freq + + 0.10 * co_ret + + 0.12 * quality + + 0.12 * feedback + ) + elif use_quality: quality = self._quality_service.compute_quality_score(node, graph) final = ( 0.45 * retrieval_score @@ -81,6 +116,15 @@ def apply_temporal_weights( + 0.12 * co_ret + 0.13 * quality ) + elif use_feedback: + feedback = feedback_weights.get(node_id, 0.5) + final = ( + 0.45 * retrieval_score + + 0.18 * recency + + 0.12 * change_freq + + 0.12 * co_ret + + 0.13 * feedback + ) else: final = ( 0.5 * retrieval_score diff --git a/pyproject.toml b/pyproject.toml index d7c78e0..b0f4438 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=68.0", "wheel>=0.46", "setuptools-scm>=8"] +requires = ["setuptools>=84.0", "wheel>=0.48", "setuptools-scm>=10.3"] build-backend = "setuptools.build_meta" [project] @@ -8,13 +8,12 @@ dynamic = ["version"] description = "Mimir — Context Server: intelligent code context engine for LLMs working with large, multi-repo codebases" readme = "README.md" requires-python = ">=3.11" -license = {text = "MIT"} +license = "MIT" keywords = ["mcp", "context", "code", "llm", "rag", "code-graph", "embeddings", "mimir"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -25,34 +24,26 @@ classifiers = [ ] dependencies = [ - "networkx>=3.5", - "gitpython>=3.1", - "typer>=0.15", - "tomli>=2.2", - "chromadb>=1.5", - "pydantic-settings>=2.0", - "sentence-transformers>=4.1", - "litellm>=1.68", - "mcp>=1.26", - "numpy>=2.2", - "tree-sitter>=0.25", - "tree-sitter-language-pack>=0.9", - "aiohttp>=3.11", - "tiktoken>=0.9", - "rank-bm25>=0.2", - "rich>=14.0", - "watchdog>=6.0", - "pyyaml>=6.0", + "networkx>=3.6.1", + "gitpython>=3.2.0", + "typer>=0.27.2", + "onnxruntime>=1.30.0", + "tokenizers>=0.23.2", + "huggingface-hub>=1.33.0", + "numpy>=2.4.6", + "tree-sitter-language-pack>=1.20.0", + "aiohttp>=3.14.3", + "rank-bm25>=0.2.2", + "rich>=15.0.0", + "watchdog>=6.0.0", + "pyyaml>=6.0.3", ] [project.optional-dependencies] dev = [ - "pytest>=9.0", - "pytest-asyncio>=1.3", - "pytest-cov>=7.0", -] -lsp = [ - "multilspy>=0.2", + "pytest>=9.1.1", + "pytest-asyncio>=1.4.0", + "pytest-cov>=7.1.0", ] [project.urls] diff --git a/mimir/infra/llm/__init__.py b/tests/adapters/__init__.py similarity index 100% rename from mimir/infra/llm/__init__.py rename to tests/adapters/__init__.py diff --git a/tests/adapters/http/__init__.py b/tests/adapters/http/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/adapters/http/test_http_admin_auth.py b/tests/adapters/http/test_http_admin_auth.py new file mode 100644 index 0000000..fbfde00 --- /dev/null +++ b/tests/adapters/http/test_http_admin_auth.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from aiohttp import web + +from mimir.adapters.http.admin_auth import require_admin_token + + +def _request(**headers): + return SimpleNamespace(headers=headers) + + +def _config(*, admin_env: str | None = None, webhook_env: str | None = None): + return SimpleNamespace( + admin=SimpleNamespace( + admin_token_env=admin_env, + webhook_secret_env=webhook_env, + ), + ) + + +def test_require_admin_token_accepts_bearer_token(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MIMIR_ADMIN_TOKEN", "secret") + + require_admin_token( + _request(Authorization="Bearer secret"), + _config(admin_env="MIMIR_ADMIN_TOKEN"), + ) + + +def test_require_admin_token_falls_back_to_webhook_secret(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MIMIR_WEBHOOK_SECRET", "secret") + + require_admin_token( + _request(**{"X-Mimir-Admin-Token": "secret"}), + _config(webhook_env="MIMIR_WEBHOOK_SECRET"), + ) + + +def test_require_admin_token_rejects_missing_or_invalid_token(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MIMIR_ADMIN_TOKEN", "secret") + + with pytest.raises(web.HTTPUnauthorized): + require_admin_token( + _request(Authorization="Bearer wrong"), + _config(admin_env="MIMIR_ADMIN_TOKEN"), + ) + + +def test_require_admin_token_fails_closed_when_not_configured() -> None: + with pytest.raises(web.HTTPServiceUnavailable): + require_admin_token(_request(), _config()) diff --git a/tests/adapters/http/test_http_state.py b/tests/adapters/http/test_http_state.py new file mode 100644 index 0000000..7b3e134 --- /dev/null +++ b/tests/adapters/http/test_http_state.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from types import SimpleNamespace + +from mimir.adapters.http.state import HttpServerState +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Node, NodeKind + + +def test_http_state_reads_graph_from_query_runtime() -> None: + graph = CodeGraph() + graph.add_node(Node( + id="repo:", + repo="repo", + kind=NodeKind.REPOSITORY, + name="repo", + )) + state = HttpServerState( + runtime=SimpleNamespace(graph=graph), + workspace_name="default", + ) + + assert state.current_graph() is graph diff --git a/tests/adapters/mcp/test_stdio_dispatch.py b/tests/adapters/mcp/test_stdio_dispatch.py new file mode 100644 index 0000000..42ab6f7 --- /dev/null +++ b/tests/adapters/mcp/test_stdio_dispatch.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from mimir.adapters.mcp.stdio_dispatch import handle_request +from mimir.adapters.mcp.stdio_protocol import tool_definitions +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Node, NodeKind +from mimir.services.impact import ImpactService +from mimir.services.write_context import WriteContextService + + +def _runtime() -> SimpleNamespace: + graph = CodeGraph() + file_node = Node( + id="repo:src/service.py", + repo="repo", + kind=NodeKind.FILE, + name="service.py", + path="src/service.py", + ) + func_node = Node( + id="repo:src/service.py::handle", + repo="repo", + kind=NodeKind.FUNCTION, + name="handle", + path="src/service.py", + raw_code="def handle():\n return 1\n", + ) + graph.add_node(file_node) + graph.add_node(func_node) + return SimpleNamespace( + graph=graph, + require_graph=lambda: graph, + write_context=WriteContextService(), + impact=ImpactService(), + ) + + +def test_stdio_tool_definitions_include_core_agent_tools() -> None: + names = {tool["name"] for tool in tool_definitions()} + + assert "get_write_context" in names + assert "get_impact" in names + assert "validate_change" in names + assert "can_i_modify" in names + + +@pytest.mark.asyncio +async def test_stdio_get_write_context_uses_query_runtime_graph() -> None: + result = await handle_request( + _runtime(), + "default", + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "get_write_context", + "arguments": {"file_path": "service.py"}, + }, + }, + ) + + text = result["result"]["content"][0]["text"] + assert "Write context" in text + assert "service.py" in text + + +@pytest.mark.asyncio +async def test_stdio_get_impact_uses_query_runtime_graph() -> None: + result = await handle_request( + _runtime(), + "default", + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "get_impact", + "arguments": {"file_path": "service.py"}, + }, + }, + ) + + text = result["result"]["content"][0]["text"] + assert "Impact analysis" in text + assert "service.py" in text diff --git a/tests/adapters/shared/__init__.py b/tests/adapters/shared/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/adapters/shared/test_session_context.py b/tests/adapters/shared/test_session_context.py new file mode 100644 index 0000000..9d2932f --- /dev/null +++ b/tests/adapters/shared/test_session_context.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from datetime import datetime, timezone +from types import SimpleNamespace + +from mimir.adapters.shared.session_context import apply_session_context +from mimir.domain.models import Node, NodeKind +from mimir.domain.session import ContextEntry, QueryRecord, Session +from mimir.domain.subgraph import ContextBundle +from mimir.services.session import SessionService + + +class _MemorySessionStore: + def __init__(self) -> None: + self._sessions: dict[str, Session] = {} + + def save(self, session: Session) -> None: + self._sessions[session.session_id] = session + + def load(self, session_id: str) -> Session | None: + return self._sessions.get(session_id) + + def list_sessions(self) -> list[str]: + return sorted(self._sessions) + + def delete(self, session_id: str) -> None: + self._sessions.pop(session_id, None) + + def close(self) -> None: + return None + + +class _FakeRetrieval: + default_token_budget = 8000 + + def fit_subgraph_to_budget(self, subgraph, budget: int, *, seed_ids=None) -> None: + return None + + +def test_apply_session_context_does_not_mutate_canonical_node() -> None: + canonical = Node( + id="repo:service.py::handle", + repo="repo", + kind=NodeKind.FUNCTION, + name="handle", + path="service.py", + raw_code="def handle():\n return 1\n", + summary="Handle the request.", + ) + bundle = ContextBundle( + nodes=[canonical], + edges=[], + summary="context", + token_count=canonical.token_estimate, + repos_involved=["repo"], + query_embedding=None, + ) + + store = _MemorySessionStore() + session = Session(session_id="s-1") + session.query_history.append(QueryRecord( + query="older", + turn_number=3, + retrieved_node_ids=[canonical.id], + timestamp=datetime.now(timezone.utc), + query_embedding=None, + )) + session.context_window[canonical.id] = ContextEntry( + node_id=canonical.id, + added_at=datetime.now(timezone.utc), + turn_number=1, + relevance_at_addition=1.0, + query_embedding_at_addition=None, + ) + store.save(session) + + container = SimpleNamespace( + session=SessionService( + config=SimpleNamespace(session=SimpleNamespace(context_decay_turns=5, topic_tracking_alpha=0.3)), + session_store=store, + ), + retrieval=_FakeRetrieval(), + ) + + apply_session_context( + container, + bundle, + query="current", + session_id="s-1", + budget=None, + ) + + assert canonical.raw_code == "def handle():\n return 1\n" + assert len(bundle.nodes) == 1 + assert bundle.nodes[0].id == canonical.id + assert bundle.nodes[0].raw_code is None diff --git a/tests/adapters/test_cli_adapter.py b/tests/adapters/test_cli_adapter.py new file mode 100644 index 0000000..668ddbe --- /dev/null +++ b/tests/adapters/test_cli_adapter.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +from textwrap import dedent + +from typer.testing import CliRunner + +from mimir.adapters.cli import app as shim_app +from mimir.adapters.cli_support import app as package_app + +runner = CliRunner() + + +def test_cli_shim_exports_same_app_instance() -> None: + assert shim_app is package_app + + +def test_root_help_lists_expected_commands() -> None: + result = runner.invoke(shim_app, ["--help"]) + assert result.exit_code == 0 + for command in ("init", "workspace", "guardrail", "indexer", "query"): + assert command in result.stdout + + +def test_indexer_and_query_help_render() -> None: + indexer = runner.invoke(shim_app, ["indexer", "--help"]) + query = runner.invoke(shim_app, ["query", "--help"]) + + assert indexer.exit_code == 0 + assert "run" in indexer.stdout + assert "sync" in indexer.stdout + assert "versions" in indexer.stdout + assert "activate" in indexer.stdout + assert "prune" in indexer.stdout + assert "worker" in indexer.stdout + assert query.exit_code == 0 + assert "search" in query.stdout + assert "serve" in query.stdout + assert "status" in query.stdout + assert "ui" in query.stdout + + +def test_workspace_help_renders() -> None: + result = runner.invoke(shim_app, ["workspace", "--help"]) + assert result.exit_code == 0 + assert "add" in result.stdout + assert "list" in result.stdout + assert "remove" in result.stdout + + +def test_guardrail_help_renders() -> None: + result = runner.invoke(shim_app, ["guardrail", "--help"]) + assert result.exit_code == 0 + assert "check" in result.stdout + assert "init" in result.stdout + assert "test" in result.stdout + assert "approve" in result.stdout + + +def test_query_status_succeeds_without_active_index(tmp_path) -> None: + config_path = _write_config(tmp_path) + + result = runner.invoke(shim_app, ["query", "status", "--config", str(config_path)]) + + assert result.exit_code == 0 + assert "Active version: -" in result.stdout + + +def test_query_search_fails_without_active_index(tmp_path) -> None: + config_path = _write_config(tmp_path) + + result = runner.invoke(shim_app, ["query", "search", "auth", "--config", str(config_path)]) + + assert result.exit_code == 1 + assert "No active index" in result.stdout + assert "mimir indexer run" in result.stdout + + +def test_guardrail_check_fails_without_active_index(tmp_path) -> None: + config_path = _write_config(tmp_path) + rules_path = tmp_path / "rules.yaml" + rules_path.write_text(dedent(""" + rules: + - id: no-adapters + type: dependency_ban + description: "Adapters are blocked" + severity: error + config: + source_pattern: "*.py" + target_pattern: "*/adapters/*" + """)) + diff = dedent(""" + diff --git a/repo/app.py b/repo/app.py + index 1111111..2222222 100644 + --- a/repo/app.py + +++ b/repo/app.py + @@ -1 +1,2 @@ + print("ok") + +import mimir.adapters.http + """) + + result = runner.invoke( + shim_app, + ["guardrail", "check", "--diff", "-", "--rules", str(rules_path), "--config", str(config_path)], + input=diff, + ) + + assert result.exit_code == 1 + assert "No active index" in result.stdout + assert "mimir indexer run" in result.stdout + + +def _write_config(tmp_path): + repo = tmp_path / "repo" + repo.mkdir() + config_path = tmp_path / "mimir.toml" + config_path.write_text(dedent(f""" + data_dir = "{tmp_path / '.mimir'}" + + [[repos]] + name = "repo" + path = "{repo}" + language_hint = "python" + + [embeddings] + model = "local:test" + """)) + return config_path diff --git a/tests/domain/__init__.py b/tests/domain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_guardrails_domain.py b/tests/domain/test_guardrails_domain.py similarity index 99% rename from tests/test_guardrails_domain.py rename to tests/domain/test_guardrails_domain.py index a6c7527..94f8084 100644 --- a/tests/test_guardrails_domain.py +++ b/tests/domain/test_guardrails_domain.py @@ -283,7 +283,7 @@ def test_invalid_scope(self, tmp_path: Path): def test_load_example_rules_file(self): """Ensure the shipped mimir-rules.yaml parses successfully.""" - rules_path = Path(__file__).parent.parent / "mimir-rules.yaml" + rules_path = Path(__file__).parent.parent.parent / "mimir-rules.yaml" if rules_path.exists(): rules = load_rules(rules_path) assert len(rules) > 0 diff --git a/tests/infra/__init__.py b/tests/infra/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_hydration.py b/tests/infra/test_hydration.py similarity index 100% rename from tests/test_hydration.py rename to tests/infra/test_hydration.py diff --git a/tests/infra/test_index_runtime_stores.py b/tests/infra/test_index_runtime_stores.py new file mode 100644 index 0000000..664bf01 --- /dev/null +++ b/tests/infra/test_index_runtime_stores.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from pathlib import Path + +from mimir.domain.index_state import IndexJobKind, IndexJobStatus, IndexVersion +from mimir.infra.stores.sqlite_index_jobs import SqliteIndexJobStore +from mimir.infra.stores.sqlite_index_metadata import SqliteIndexMetadataStore + + +def test_index_metadata_store_publishes_active_version(tmp_path: Path) -> None: + store = SqliteIndexMetadataStore(tmp_path / "metadata.db") + try: + first = IndexVersion(version="v1", graph_path="/tmp/v1/graph.db", node_count=1) + second = IndexVersion( + version="v2", + graph_path="/tmp/v2/graph.db", + node_count=2, + schema_version=3, + embedding_model="local:test", + embedding_dim=3, + config_hash="abc123", + created_by="test", + ) + + store.publish(first) + store.publish(second) + + active = store.get_active() + assert active is not None + assert active.version == "v2" + assert active.node_count == 2 + assert active.schema_version == 3 + assert active.embedding_model == "local:test" + assert active.embedding_dim == 3 + assert active.config_hash == "abc123" + assert active.created_by == "test" + assert store.get("v1").active is False + finally: + store.close() + + +def test_index_metadata_store_activates_and_deletes_versions(tmp_path: Path) -> None: + store = SqliteIndexMetadataStore(tmp_path / "metadata.db") + try: + store.publish(IndexVersion(version="v1", graph_path="/tmp/v1/graph.db"), activate=True) + store.publish(IndexVersion(version="v2", graph_path="/tmp/v2/graph.db"), activate=True) + + activated = store.activate("v1") + + assert activated is not None + assert activated.active is True + assert store.get_active().version == "v1" + assert store.get("v2").active is False + + store.delete("v2") + assert store.get("v2") is None + finally: + store.close() + + +def test_index_job_store_claims_and_completes_jobs(tmp_path: Path) -> None: + store = SqliteIndexJobStore(tmp_path / "jobs.db") + try: + queued = store.enqueue(IndexJobKind.SYNC, repo="api", commit_sha="abc") + + claimed = store.claim_next() + assert claimed is not None + assert claimed.id == queued.id + assert claimed.kind is IndexJobKind.SYNC + assert claimed.status is IndexJobStatus.RUNNING + + store.complete(claimed.id, {"version": "v1"}) + completed = store.get(claimed.id) + assert completed is not None + assert completed.status is IndexJobStatus.COMPLETED + assert completed.result == {"version": "v1"} + finally: + store.close() + + +def test_index_job_store_coalesces_queued_jobs_by_kind_and_repo(tmp_path: Path) -> None: + store = SqliteIndexJobStore(tmp_path / "jobs.db") + try: + first = store.enqueue(IndexJobKind.SYNC, repo="api", commit_sha="abc") + second = store.enqueue(IndexJobKind.SYNC, repo="api", commit_sha="def") + + assert second.id == first.id + assert second.commit_sha == "def" + assert len(store.list_jobs()) == 1 + finally: + store.close() diff --git a/tests/infra/test_sqlite_feedback.py b/tests/infra/test_sqlite_feedback.py new file mode 100644 index 0000000..80b32c6 --- /dev/null +++ b/tests/infra/test_sqlite_feedback.py @@ -0,0 +1,117 @@ +"""Tests for SqliteFeedbackStore — CRUD, aggregation, and pair scoring.""" + +from __future__ import annotations + +import pytest +from pathlib import Path + +from mimir.domain.feedback import FeedbackSignal, NodeFeedbackScore +from mimir.infra.stores.sqlite_feedback import SqliteFeedbackStore + + +@pytest.fixture +def store(tmp_path: Path) -> SqliteFeedbackStore: + return SqliteFeedbackStore(tmp_path / "feedback.db") + + +class TestRecord: + def test_record_stores_signal(self, store: SqliteFeedbackStore) -> None: + signal = FeedbackSignal.new( + node_ids=["a", "b"], outcome="positive", source="explicit", + ) + store.record(signal) + signals = store.list_signals() + assert len(signals) == 1 + assert signals[0].id == signal.id + assert signals[0].outcome == "positive" + assert set(signals[0].node_ids) == {"a", "b"} + + def test_record_updates_node_aggregates(self, store: SqliteFeedbackStore) -> None: + store.record(FeedbackSignal.new(["n1"], "positive", "explicit")) + store.record(FeedbackSignal.new(["n1"], "positive", "explicit")) + store.record(FeedbackSignal.new(["n1"], "negative", "explicit")) + + scores = store.get_node_scores(["n1"]) + assert "n1" in scores + s = scores["n1"] + assert s.positive_count == 2 + assert s.negative_count == 1 + # Laplace(2): (2+2)/(2+1+4) = 4/7 ≈ 0.571 + assert abs(s.score - 4 / 7) < 0.01 + + def test_node_score_missing_returns_empty(self, store: SqliteFeedbackStore) -> None: + scores = store.get_node_scores(["nonexistent"]) + assert scores == {} + + +class TestPairScores: + def test_pair_aggregation(self, store: SqliteFeedbackStore) -> None: + store.record(FeedbackSignal.new(["a", "b"], "positive", "explicit")) + store.record(FeedbackSignal.new(["a", "b"], "positive", "explicit")) + store.record(FeedbackSignal.new(["a", "b"], "negative", "explicit")) + + pair_scores = store.get_pair_scores("a", ["b"]) + assert "b" in pair_scores + # Same Laplace as node: (2+2)/(2+1+4) = 4/7 + assert abs(pair_scores["b"] - 4 / 7) < 0.01 + + def test_pair_score_missing(self, store: SqliteFeedbackStore) -> None: + scores = store.get_pair_scores("x", ["y"]) + assert scores == {} + + def test_pair_order_independent(self, store: SqliteFeedbackStore) -> None: + store.record(FeedbackSignal.new(["b", "a"], "positive", "explicit")) + # Should be stored as (a, b) regardless of input order + scores_ab = store.get_pair_scores("a", ["b"]) + scores_ba = store.get_pair_scores("b", ["a"]) + assert scores_ab.get("b") == scores_ba.get("a") + + +class TestListSignals: + def test_list_all(self, store: SqliteFeedbackStore) -> None: + for i in range(5): + store.record(FeedbackSignal.new([f"n{i}"], "positive", "explicit")) + assert len(store.list_signals()) == 5 + + def test_list_by_session(self, store: SqliteFeedbackStore) -> None: + store.record(FeedbackSignal.new(["a"], "positive", "explicit", session_id="s1")) + store.record(FeedbackSignal.new(["b"], "negative", "explicit", session_id="s2")) + store.record(FeedbackSignal.new(["c"], "positive", "explicit", session_id="s1")) + + s1_signals = store.list_signals(session_id="s1") + assert len(s1_signals) == 2 + assert all(s.session_id == "s1" for s in s1_signals) + + def test_list_limit(self, store: SqliteFeedbackStore) -> None: + for i in range(10): + store.record(FeedbackSignal.new([f"n{i}"], "positive", "explicit")) + assert len(store.list_signals(limit=3)) == 3 + + +class TestClear: + def test_clear_removes_all(self, store: SqliteFeedbackStore) -> None: + store.record(FeedbackSignal.new(["a", "b"], "positive", "explicit")) + store.clear() + assert store.list_signals() == [] + assert store.get_node_scores(["a"]) == {} + assert store.get_pair_scores("a", ["b"]) == {} + + +class TestLaplaceSmoothing: + def test_neutral_start(self) -> None: + assert NodeFeedbackScore.compute_score(0, 0, smoothing=2) == 0.5 + + def test_all_positive(self) -> None: + score = NodeFeedbackScore.compute_score(10, 0, smoothing=2) + # (10+2)/(10+0+4) = 12/14 ≈ 0.857 + assert abs(score - 12 / 14) < 0.001 + + def test_all_negative(self) -> None: + score = NodeFeedbackScore.compute_score(0, 10, smoothing=2) + # (0+2)/(0+10+4) = 2/14 ≈ 0.143 + assert abs(score - 2 / 14) < 0.001 + + def test_custom_smoothing(self) -> None: + score = NodeFeedbackScore.compute_score(5, 5, smoothing=1) + # (5+1)/(5+5+2) = 6/12 = 0.5 + assert score == 0.5 diff --git a/tests/test_vector_stores.py b/tests/infra/test_vector_stores.py similarity index 73% rename from tests/test_vector_stores.py rename to tests/infra/test_vector_stores.py index 06939b2..7a66320 100644 --- a/tests/test_vector_stores.py +++ b/tests/infra/test_vector_stores.py @@ -1,19 +1,12 @@ -"""Parity tests for VectorStore implementations. +"""Contract tests for the VectorStore implementation. -Exercises NumpyVectorStore and ChromaVectorStore against the same fixtures to -ensure they agree on upsert/search/delete/count/reset/get_existing_ids. -Metadata is intentionally scalar-only — ChromaVectorStore silently drops -non-scalar metadata values (see ``chroma.py``), which would masquerade as a -parity failure otherwise. +Exercises NumpyVectorStore's upsert/search/delete/count/reset/get_existing_ids. """ from __future__ import annotations -from pathlib import Path - import pytest -from mimir.infra.vector_stores.chroma import ChromaVectorStore from mimir.infra.vector_stores.numpy_store import NumpyVectorStore from mimir.ports.vector_store import VectorStore @@ -23,22 +16,11 @@ # --------------------------------------------------------------------------- -def _numpy_store() -> VectorStore: +@pytest.fixture +def store() -> VectorStore: return NumpyVectorStore() -def _chroma_store(tmp_path: Path) -> VectorStore: - # Use a unique sub-path so parallel test runs don't collide. - return ChromaVectorStore(persist_directory=str(tmp_path / "chroma")) - - -@pytest.fixture(params=["numpy", "chroma"]) -def store(request, tmp_path: Path) -> VectorStore: - if request.param == "numpy": - return _numpy_store() - return _chroma_store(tmp_path) - - def _sample_vectors() -> tuple[list[str], list[list[float]], list[dict]]: ids = ["a", "b", "c"] # 4-D vectors along distinct axes so ranking is unambiguous. @@ -117,6 +99,45 @@ def test_upsert_updates_existing_id(store: VectorStore) -> None: assert store.count() == 1 +def test_upsert_duplicate_id_in_one_batch_last_write_wins(store: VectorStore) -> None: + store.upsert( + ids=["x", "y", "x"], + embeddings=[[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]], + metadatas=[{"repo": "alpha"}, {"repo": "beta"}, {"repo": "gamma"}], + ) + + assert store.count() == 2 + results = store.search(query_embedding=[1.0, 0.0], top_k=5, where={"repo": "gamma"}) + assert [r.id for r in results] == ["x"] + assert store.search(query_embedding=[1.0, 0.0], top_k=5, where={"repo": "alpha"}) == [] + + +def test_upsert_mixed_update_and_append(store: VectorStore) -> None: + ids, embeddings, metadatas = _sample_vectors() + store.upsert(ids=ids, embeddings=embeddings, metadatas=metadatas) + + store.upsert( + ids=["c", "d"], + embeddings=[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0]], + metadatas=[{"repo": "alpha"}, {"repo": "alpha"}], + ) + + assert store.count() == 4 + assert store.search(query_embedding=[0.0, 0.0, 0.0, 1.0], top_k=1)[0].id == "c" + assert store.search(query_embedding=[0.0, 0.0, 1.0, 0.0], top_k=1)[0].id == "d" + + +def test_filtered_search_after_delete(store: VectorStore) -> None: + ids, embeddings, metadatas = _sample_vectors() + store.upsert(ids=ids, embeddings=embeddings, metadatas=metadatas) + store.search(query_embedding=[1.0, 0.0, 0.0, 0.0], top_k=5, where={"repo": "alpha"}) + + store.delete(ids=["a"]) + + results = store.search(query_embedding=[1.0, 0.0, 0.0, 0.0], top_k=5, where={"repo": "alpha"}) + assert [r.id for r in results] == ["c"] + + # --------------------------------------------------------------------------- # delete / count / reset # --------------------------------------------------------------------------- @@ -168,6 +189,5 @@ def test_get_existing_ids_all_present(store: VectorStore) -> None: def test_get_existing_ids_empty_input(store: VectorStore) -> None: # Edge case: callers may pass an empty id list when the graph has no - # embedded nodes. Both backends must handle this without hitting the - # underlying collection. + # embedded nodes. assert store.get_existing_ids([]) == set() diff --git a/tests/services/__init__.py b/tests/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/services/guardrail/__init__.py b/tests/services/guardrail/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_diff_analyzer.py b/tests/services/guardrail/test_diff_analyzer.py similarity index 99% rename from tests/test_diff_analyzer.py rename to tests/services/guardrail/test_diff_analyzer.py index 358d41a..4bf511d 100644 --- a/tests/test_diff_analyzer.py +++ b/tests/services/guardrail/test_diff_analyzer.py @@ -10,7 +10,7 @@ from mimir.domain.graph import CodeGraph from mimir.domain.guardrails import ChangeSet from mimir.domain.models import Edge, EdgeKind, Node, NodeKind -from mimir.services.diff_analyzer import DiffAnalyzer +from mimir.services.guardrail.diff_analyzer import DiffAnalyzer # --------------------------------------------------------------------------- diff --git a/tests/test_guardrail_report.py b/tests/services/guardrail/test_guardrail_report.py similarity index 99% rename from tests/test_guardrail_report.py rename to tests/services/guardrail/test_guardrail_report.py index bfa08de..db68303 100644 --- a/tests/test_guardrail_report.py +++ b/tests/services/guardrail/test_guardrail_report.py @@ -8,7 +8,7 @@ import pytest from mimir.domain.guardrails import ChangeSet, GuardrailResult, Severity, Violation -from mimir.services.guardrail_report import ( +from mimir.services.guardrail.report import ( GuardrailReporter, append_audit_entry, ) diff --git a/tests/test_guardrail_service.py b/tests/services/guardrail/test_guardrail_service.py similarity index 99% rename from tests/test_guardrail_service.py rename to tests/services/guardrail/test_guardrail_service.py index f3c8a69..30f3be1 100644 --- a/tests/test_guardrail_service.py +++ b/tests/services/guardrail/test_guardrail_service.py @@ -9,7 +9,7 @@ from mimir.domain.graph import CodeGraph from mimir.domain.guardrails import ChangeSet, GuardrailResult, Rule, RuleType, Severity, Violation from mimir.domain.models import Edge, EdgeKind, Node, NodeKind -from mimir.services.guardrail import GuardrailService, apply_approvals +from mimir.services.guardrail.service import GuardrailService, apply_approvals from mimir.services.impact import ImpactResult, ImpactService from mimir.services.quality import QualityService diff --git a/tests/test_guardrail_trailers.py b/tests/services/guardrail/test_guardrail_trailers.py similarity index 97% rename from tests/test_guardrail_trailers.py rename to tests/services/guardrail/test_guardrail_trailers.py index cf0668b..e15d01c 100644 --- a/tests/test_guardrail_trailers.py +++ b/tests/services/guardrail/test_guardrail_trailers.py @@ -2,7 +2,7 @@ from __future__ import annotations -from mimir.services.guardrail_trailers import parse_approval_trailers +from mimir.services.guardrail.trailers import parse_approval_trailers class TestParseApprovalTrailers: diff --git a/tests/services/indexing/__init__.py b/tests/services/indexing/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_api_endpoint.py b/tests/services/indexing/test_api_endpoint.py similarity index 100% rename from tests/test_api_endpoint.py rename to tests/services/indexing/test_api_endpoint.py diff --git a/tests/test_indexing_embedding.py b/tests/services/indexing/test_indexing_embedding.py similarity index 100% rename from tests/test_indexing_embedding.py rename to tests/services/indexing/test_indexing_embedding.py diff --git a/tests/services/indexing/test_indexing_incremental.py b/tests/services/indexing/test_indexing_incremental.py new file mode 100644 index 0000000..562cf4c --- /dev/null +++ b/tests/services/indexing/test_indexing_incremental.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Node, NodeKind +from mimir.ports.parser import Symbol +from mimir.services.indexing import IndexingService + + +class _ParserStub: + async def parse_file(self, file_path: str, language: str | None = None) -> list[Symbol]: + return [ + Symbol( + name="handle", + kind="function", + relative_path="src/features/service.py", + start_line=1, + end_line=2, + code="def handle():\n return 1\n", + ) + ] + + def extract_identifiers(self, code: str, language: str | None = None, file_path: str | None = None) -> set[str]: + return set() + + +@pytest.mark.asyncio +async def test_index_files_creates_missing_module_hierarchy(tmp_path) -> None: + repo_path = tmp_path / "repo" + file_path = repo_path / "src" / "features" / "service.py" + file_path.parent.mkdir(parents=True) + file_path.write_text("def handle():\n return 1\n") + + service = IndexingService.__new__(IndexingService) + service._config = SimpleNamespace( + indexing=SimpleNamespace( + max_file_size_kb=500, + excluded_patterns=[], + ), + ) + service._parser = _ParserStub() + + async def _no_embed(graph, mode, *, nodes_to_embed=None, show_progress=False) -> None: + return None + + service._embed_and_upsert = _no_embed + + graph = CodeGraph() + removed_ids, new_nodes, new_edges = await service.index_files( + graph=graph, + repo_name="repo", + repo_path=repo_path, + changed_files={"src/features/service.py"}, + deleted_files=set(), + language_hint="python", + ) + + assert removed_ids == [] + assert graph.has_node("repo:") + assert graph.has_node("repo:src/") + assert graph.has_node("repo:src/features/") + assert graph.has_node("repo:src/features/service.py") + assert any(node.id == "repo:src/" for node in new_nodes) + assert any(node.id == "repo:src/features/" for node in new_nodes) + assert any(edge.source == "repo:" and edge.target == "repo:src/" for edge in new_edges) + assert any(edge.source == "repo:src/" and edge.target == "repo:src/features/" for edge in new_edges) diff --git a/tests/services/indexing/test_indexing_integration.py b/tests/services/indexing/test_indexing_integration.py new file mode 100644 index 0000000..177ef8f --- /dev/null +++ b/tests/services/indexing/test_indexing_integration.py @@ -0,0 +1,406 @@ +"""Integration test for the core indexing pipeline. + +Exercises the real end-to-end flow: + temp Python repo on disk → TreeSitter parser → graph builder → + cross-file resolution → summarisation → embedding → vector upsert → + graph persistence → reload. + +Uses real infra (TreeSitter, NumpyVectorStore, SqliteGraphStore) and a +lightweight embedder stub to avoid heavy model downloads. +""" + +from __future__ import annotations + +import textwrap +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Optional + +import pytest + +from mimir.domain.config import ( + CrossRepoConfig, + EmbeddingConfig, + IndexingConfig, + MimirConfig, + RepoConfig, +) +from mimir.domain.graph import CodeGraph +from mimir.domain.models import EdgeKind, NodeKind, SYMBOL_KINDS +from mimir.infra.stores.sqlite_graph import SqliteGraphStore +from mimir.infra.vector_stores.numpy_store import NumpyVectorStore +from mimir.services.indexing import IndexingService + + +# --------------------------------------------------------------------------- +# Lightweight embedder stub — deterministic, no model download +# --------------------------------------------------------------------------- + +_EMBED_DIM = 8 + + +class _DeterministicEmbedder: + """Produces deterministic vectors from text hashes. No model needed.""" + + @property + def dimension(self) -> int: + return _EMBED_DIM + + async def embed_batch(self, texts: list[str]) -> list[list[float]]: + import hashlib + + result: list[list[float]] = [] + for text in texts: + digest = hashlib.sha256(text.encode()).digest() + vec = [float(b) / 255.0 for b in digest[:_EMBED_DIM]] + result.append(vec) + return result + + +# --------------------------------------------------------------------------- +# Fixture: create a mini Python repo on disk +# --------------------------------------------------------------------------- + +_MODELS_PY = textwrap.dedent("""\ + class User: + \"\"\"Domain model for a user.\"\"\" + + def __init__(self, name: str, email: str): + self.name = name + self.email = email + + def display_name(self) -> str: + return self.name.title() + + + class UserNotFoundError(Exception): + pass +""") + +_SERVICE_PY = textwrap.dedent("""\ + from models import User, UserNotFoundError + + + class UserService: + \"\"\"Application service for user operations.\"\"\" + + def __init__(self, repo): + self.repo = repo + + def get_user(self, user_id: int) -> User: + user = self.repo.find(user_id) + if user is None: + raise UserNotFoundError(f"User {user_id} not found") + return user + + def list_users(self) -> list: + return self.repo.all() +""") + +_ROUTES_PY = textwrap.dedent("""\ + from service import UserService + + + def get_user_handler(request): + svc = UserService(request.app["repo"]) + user = svc.get_user(request.match_info["id"]) + return {"name": user.display_name()} + + def list_users_handler(request): + svc = UserService(request.app["repo"]) + return [u.display_name() for u in svc.list_users()] +""") + + +@pytest.fixture() +def repo_on_disk(tmp_path: Path) -> Path: + """Write a small Python project to a temp directory.""" + repo = tmp_path / "my_app" + repo.mkdir() + (repo / "models.py").write_text(_MODELS_PY) + (repo / "service.py").write_text(_SERVICE_PY) + (repo / "routes.py").write_text(_ROUTES_PY) + return repo + + +@pytest.fixture() +def mimir_config(tmp_path: Path, repo_on_disk: Path) -> MimirConfig: + data_dir = tmp_path / ".mimir" + return MimirConfig( + repos=[ + RepoConfig(name="my_app", path=repo_on_disk, language_hint="python"), + ], + data_dir=data_dir, + indexing=IndexingConfig( + summary_mode="heuristic", + excluded_patterns=["__pycache__", "*.pyc"], + max_file_size_kb=500, + ), + cross_repo=CrossRepoConfig( + detect_api_contracts=True, + detect_shared_imports=True, + ), + embeddings=EmbeddingConfig(batch_size=64), + ) + + +@pytest.fixture() +def graph_store(mimir_config: MimirConfig) -> SqliteGraphStore: + store = SqliteGraphStore(mimir_config.project_dir / "graph.db") + yield store + store.close() + + +@pytest.fixture() +def vector_store() -> NumpyVectorStore: + return NumpyVectorStore() + + +@pytest.fixture() +def indexing_service( + mimir_config: MimirConfig, + graph_store: SqliteGraphStore, + vector_store: NumpyVectorStore, +) -> IndexingService: + from mimir.infra.parsers.tree_sitter import TreeSitterParser + + return IndexingService( + config=mimir_config, + parser=TreeSitterParser(), + embedder=_DeterministicEmbedder(), + vector_store=vector_store, + graph_store=graph_store, + ) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + +class TestFullIndexPipeline: + """End-to-end: index_all → graph assertions.""" + + @pytest.mark.asyncio + async def test_index_builds_complete_graph( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + + # Repository root node exists + assert graph.has_node("my_app:") + repo_node = graph.get_node("my_app:") + assert repo_node.kind == NodeKind.REPOSITORY + + # File nodes exist + assert graph.has_node("my_app:models.py") + assert graph.has_node("my_app:service.py") + assert graph.has_node("my_app:routes.py") + for file_id in ("my_app:models.py", "my_app:service.py", "my_app:routes.py"): + assert graph.get_node(file_id).kind == NodeKind.FILE + + @pytest.mark.asyncio + async def test_index_extracts_symbols( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + + # Class symbols + class_nodes = [n for n in graph.all_nodes() if n.kind == NodeKind.CLASS] + class_names = {n.name for n in class_nodes} + assert "User" in class_names + assert "UserService" in class_names + assert "UserNotFoundError" in class_names + + # Function/method symbols + func_names = { + n.name + for n in graph.all_nodes() + if n.kind in (NodeKind.FUNCTION, NodeKind.METHOD) + } + assert "get_user" in func_names or "get_user_handler" in func_names + + @pytest.mark.asyncio + async def test_index_creates_containment_edges( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + + # Repo → file containment + repo_children = graph.get_children("my_app:") + child_ids = {c.id for c in repo_children} + assert "my_app:models.py" in child_ids + + # File → symbol containment + models_children = graph.get_children("my_app:models.py") + child_names = {c.name for c in models_children} + assert "User" in child_names + + @pytest.mark.asyncio + async def test_index_resolves_cross_file_refs( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + + # Service references User — there should be a CALLS or USES_TYPE edge + cross_file_edge_kinds = {EdgeKind.CALLS, EdgeKind.USES_TYPE, EdgeKind.INHERITS} + cross_file_edges = [ + e for e in graph.all_edges() if e.kind in cross_file_edge_kinds + ] + # At minimum, the cross-file linker should have found some references + # between service.py and models.py + assert len(cross_file_edges) > 0, ( + "Expected cross-file reference edges between service.py and models.py" + ) + + @pytest.mark.asyncio + async def test_index_generates_summaries( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + + # In heuristic mode, file-level nodes should get summaries + files_with_summaries = [ + n for n in graph.all_nodes() + if n.kind == NodeKind.FILE and n.summary + ] + assert len(files_with_summaries) > 0 + + @pytest.mark.asyncio + async def test_index_embeds_all_eligible_nodes( + self, indexing_service: IndexingService, vector_store: NumpyVectorStore, + ) -> None: + graph = await indexing_service.index_all() + + # Every symbol node should have an embedding + symbol_nodes = [n for n in graph.all_nodes() if n.kind in SYMBOL_KINDS] + assert len(symbol_nodes) > 0 + for node in symbol_nodes: + assert node.embedding is not None, f"Symbol {node.id} has no embedding" + assert len(node.embedding) == _EMBED_DIM + + # Vector store should contain all embedded nodes + stored_count = vector_store.count() + embedded_count = sum(1 for n in graph.all_nodes() if n.embedding) + assert stored_count == embedded_count + + +class TestGraphPersistence: + """Index → persist → reload → verify round-trip.""" + + @pytest.mark.asyncio + async def test_graph_survives_save_load_cycle( + self, + indexing_service: IndexingService, + graph_store: SqliteGraphStore, + ) -> None: + original = await indexing_service.index_all() + + # Graph was saved by index_all — reload from store + reloaded = graph_store.load() + + assert reloaded.node_count == original.node_count + assert reloaded.edge_count == original.edge_count + + # Spot-check a few nodes + for node_id in ("my_app:", "my_app:models.py"): + orig_node = original.get_node(node_id) + reload_node = reloaded.get_node(node_id) + assert reload_node is not None, f"Node {node_id} missing after reload" + assert reload_node.kind == orig_node.kind + assert reload_node.name == orig_node.name + + @pytest.mark.asyncio + async def test_embeddings_survive_save_load( + self, + indexing_service: IndexingService, + graph_store: SqliteGraphStore, + ) -> None: + original = await indexing_service.index_all() + reloaded = graph_store.load() + + original_embedded = { + n.id: n.embedding for n in original.all_nodes() if n.embedding + } + for node_id, orig_emb in original_embedded.items(): + reload_node = reloaded.get_node(node_id) + assert reload_node is not None + assert reload_node.embedding is not None, ( + f"Embedding lost for {node_id} after reload" + ) + assert reload_node.embedding == pytest.approx(orig_emb, abs=1e-5) + + +class TestIncrementalIndex: + """Index → modify file → incremental re-index → verify delta.""" + + @pytest.mark.asyncio + async def test_incremental_after_file_change( + self, + indexing_service: IndexingService, + repo_on_disk: Path, + vector_store: NumpyVectorStore, + ) -> None: + # Full index first + original = await indexing_service.index_all() + original_node_count = original.node_count + + # Simulate an incremental update via index_files + new_content = textwrap.dedent("""\ + class AdminService: + def ban_user(self, user_id: int) -> bool: + return True + """) + new_file = repo_on_disk / "admin.py" + new_file.write_text(new_content) + + removed_ids, new_nodes, new_edges = await indexing_service.index_files( + graph=original, + repo_name="my_app", + repo_path=repo_on_disk, + changed_files={"admin.py"}, + deleted_files=set(), + language_hint="python", + ) + + assert removed_ids == [] + assert any(n.name == "AdminService" for n in new_nodes) + assert original.has_node("my_app:admin.py") + assert original.node_count > original_node_count + + @pytest.mark.asyncio + async def test_incremental_delete_removes_nodes( + self, + indexing_service: IndexingService, + repo_on_disk: Path, + ) -> None: + original = await indexing_service.index_all() + assert original.has_node("my_app:routes.py") + + # Delete routes.py from disk and run incremental + (repo_on_disk / "routes.py").unlink() + + removed_ids, new_nodes, new_edges = await indexing_service.index_files( + graph=original, + repo_name="my_app", + repo_path=repo_on_disk, + changed_files=set(), + deleted_files={"routes.py"}, + ) + + assert "my_app:routes.py" in removed_ids + assert not original.has_node("my_app:routes.py") + + +class TestGraphStats: + """Verify graph statistics after indexing.""" + + @pytest.mark.asyncio + async def test_stats_are_populated( + self, indexing_service: IndexingService, + ) -> None: + graph = await indexing_service.index_all() + stats = graph.stats() + + assert stats["total_nodes"] > 0 + assert stats["total_edges"] > 0 + assert "my_app" in stats.get("repos", []) diff --git a/tests/services/retrieval/__init__.py b/tests/services/retrieval/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_route_search.py b/tests/services/retrieval/test_route_search.py similarity index 100% rename from tests/test_route_search.py rename to tests/services/retrieval/test_route_search.py diff --git a/tests/test_agent_policy.py b/tests/services/test_agent_policy.py similarity index 100% rename from tests/test_agent_policy.py rename to tests/services/test_agent_policy.py diff --git a/tests/test_catalog_service.py b/tests/services/test_catalog_service.py similarity index 100% rename from tests/test_catalog_service.py rename to tests/services/test_catalog_service.py diff --git a/tests/services/test_feedback.py b/tests/services/test_feedback.py new file mode 100644 index 0000000..65b3ce5 --- /dev/null +++ b/tests/services/test_feedback.py @@ -0,0 +1,162 @@ +"""Tests for FeedbackService — explicit recording, implicit heuristics, weight retrieval.""" + +from __future__ import annotations + +import pytest +from pathlib import Path +from datetime import datetime, timezone + +from mimir.domain.config import MimirConfig, RepoConfig, FeedbackConfig +from mimir.domain.feedback import FeedbackOutcome, FeedbackSignal, FeedbackSource +from mimir.domain.session import Session, QueryRecord +from mimir.infra.stores.sqlite_feedback import SqliteFeedbackStore +from mimir.services.feedback import FeedbackService + + +def _make_config(tmp_path: Path, **feedback_kw) -> MimirConfig: + repo_dir = tmp_path / "repo" + repo_dir.mkdir() + return MimirConfig( + repos=[RepoConfig(name="test", path=repo_dir)], + data_dir=tmp_path / ".mimir", + feedback=FeedbackConfig(**feedback_kw), + ) + + +@pytest.fixture +def feedback_env(tmp_path: Path): + config = _make_config(tmp_path) + store = SqliteFeedbackStore(tmp_path / "feedback.db") + service = FeedbackService(config=config, feedback_store=store) + return service, store + + +class TestExplicitFeedback: + def test_record_positive(self, feedback_env) -> None: + service, store = feedback_env + signal = service.record_explicit(["n1", "n2"], "positive", session_id="s1") + assert signal.outcome is FeedbackOutcome.POSITIVE + assert signal.source is FeedbackSource.EXPLICIT + assert store.list_signals() != [] + + def test_record_negative(self, feedback_env) -> None: + service, store = feedback_env + signal = service.record_explicit(["n1"], "negative") + assert signal.outcome is FeedbackOutcome.NEGATIVE + + def test_disabled_skips_store(self, tmp_path: Path) -> None: + config = _make_config(tmp_path, enabled=False) + store = SqliteFeedbackStore(tmp_path / "feedback.db") + service = FeedbackService(config=config, feedback_store=store) + service.record_explicit(["n1"], "positive") + assert store.list_signals() == [] + + +class TestImplicitFeedback: + @staticmethod + def _make_session_with_queries( + embeddings: list[list[float]], + node_ids: list[list[str]], + ) -> Session: + session = Session(session_id="test-session") + for i, (emb, nids) in enumerate(zip(embeddings, node_ids)): + session.record_query( + query=f"query {i}", + retrieved_ids=nids, + relevance_scores={nid: 1.0 for nid in nids}, + query_embedding=emb, + ) + return session + + def test_similar_queries_negative(self, feedback_env) -> None: + """Follow-up with high similarity → negative signal.""" + service, store = feedback_env + # Two nearly identical embeddings (cosine > 0.7) + emb1 = [1.0, 0.0, 0.0] + emb2 = [0.99, 0.1, 0.0] + session = self._make_session_with_queries( + [emb1, emb2], [["n1", "n2"], ["n3"]], + ) + signal = service.record_implicit(session) + assert signal is not None + assert signal.outcome is FeedbackOutcome.NEGATIVE + assert set(signal.node_ids) == {"n1", "n2"} + + def test_different_queries_positive(self, feedback_env) -> None: + """Topic shift → positive signal.""" + service, store = feedback_env + emb1 = [1.0, 0.0, 0.0] + emb2 = [0.0, 1.0, 0.0] # orthogonal → cosine ≈ 0 + session = self._make_session_with_queries( + [emb1, emb2], [["n1"], ["n2"]], + ) + signal = service.record_implicit(session) + assert signal is not None + assert signal.outcome is FeedbackOutcome.POSITIVE + assert signal.node_ids == ["n1"] + + def test_medium_similarity_no_signal(self, feedback_env) -> None: + """Mid-range similarity → no signal emitted.""" + service, store = feedback_env + emb1 = [1.0, 0.0, 0.0] + emb2 = [0.5, 0.866, 0.0] # cosine ≈ 0.5 + session = self._make_session_with_queries( + [emb1, emb2], [["n1"], ["n2"]], + ) + signal = service.record_implicit(session) + assert signal is None + + def test_single_query_no_signal(self, feedback_env) -> None: + """Only one query → not enough history.""" + service, _ = feedback_env + session = self._make_session_with_queries( + [[1.0, 0.0]], [["n1"]], + ) + signal = service.record_implicit(session) + assert signal is None + + def test_disabled_implicit(self, tmp_path: Path) -> None: + config = _make_config(tmp_path, implicit_signals=False) + store = SqliteFeedbackStore(tmp_path / "feedback.db") + service = FeedbackService(config=config, feedback_store=store) + session = self._make_session_with_queries( + [[1.0, 0.0], [1.0, 0.0]], [["n1"], ["n2"]], + ) + assert service.record_implicit(session) is None + + def test_no_embeddings_no_signal(self, feedback_env) -> None: + """Queries without embeddings → can't compute similarity.""" + service, _ = feedback_env + session = Session(session_id="s") + session.record_query("q1", ["n1"], {"n1": 1.0}) + session.record_query("q2", ["n2"], {"n2": 1.0}) + assert service.record_implicit(session) is None + + +class TestWeightRetrieval: + def test_get_weight_with_data(self, feedback_env) -> None: + service, store = feedback_env + service.record_explicit(["n1"], "positive") + service.record_explicit(["n1"], "positive") + w = service.get_feedback_weight("n1") + assert w > 0.5 + + def test_get_weight_no_data(self, feedback_env) -> None: + service, _ = feedback_env + assert service.get_feedback_weight("unknown") == 0.5 + + def test_get_weights_batch(self, feedback_env) -> None: + service, _ = feedback_env + service.record_explicit(["n1"], "positive") + service.record_explicit(["n2"], "negative") + weights = service.get_feedback_weights(["n1", "n2", "n3"]) + assert weights["n1"] > 0.5 + assert weights["n2"] < 0.5 + assert weights["n3"] == 0.5 + + def test_disabled_returns_neutral(self, tmp_path: Path) -> None: + config = _make_config(tmp_path, enabled=False) + store = SqliteFeedbackStore(tmp_path / "feedback.db") + service = FeedbackService(config=config, feedback_store=store) + assert service.get_feedback_weight("n1") == 0.5 + assert service.get_feedback_weights(["n1", "n2"]) == {"n1": 0.5, "n2": 0.5} diff --git a/tests/services/test_feedback_integration.py b/tests/services/test_feedback_integration.py new file mode 100644 index 0000000..ae0290c --- /dev/null +++ b/tests/services/test_feedback_integration.py @@ -0,0 +1,106 @@ +"""Integration test: feedback signals flow through to temporal reranking weights.""" + +from __future__ import annotations + +import pytest +from pathlib import Path + +from mimir.domain.config import MimirConfig, RepoConfig, FeedbackConfig, TemporalConfig +from mimir.domain.models import Node, NodeKind +from mimir.domain.subgraph import SubGraph +from mimir.infra.stores.sqlite_feedback import SqliteFeedbackStore +from mimir.services.feedback import FeedbackService +from mimir.services.temporal import TemporalService + + +def _make_config(tmp_path: Path) -> MimirConfig: + repo_dir = tmp_path / "repo" + repo_dir.mkdir() + return MimirConfig( + repos=[RepoConfig(name="test", path=repo_dir)], + data_dir=tmp_path / ".mimir", + feedback=FeedbackConfig(enabled=True), + temporal=TemporalConfig(co_retrieval_enabled=False), + ) + + +def _make_node(node_id: str) -> Node: + return Node(id=node_id, repo="test", kind=NodeKind.FUNCTION, name=node_id) + + +@pytest.fixture +def env(tmp_path: Path): + config = _make_config(tmp_path) + store = SqliteFeedbackStore(tmp_path / "feedback.db") + feedback = FeedbackService(config=config, feedback_store=store) + temporal = TemporalService(config=config) + temporal.set_feedback_service(feedback) + return feedback, temporal + + +class TestFeedbackTemporalIntegration: + def test_positive_feedback_boosts_score(self, env) -> None: + feedback, temporal = env + # Record positive feedback for node_a + for _ in range(5): + feedback.record_explicit(["node_a"], "positive") + + subgraph = SubGraph() + node_a = _make_node("node_a") + node_b = _make_node("node_b") + subgraph.add_node(node_a, score=0.5) + subgraph.add_node(node_b, score=0.5) + + temporal.apply_temporal_weights(subgraph) + + # node_a should score higher than node_b (which has no feedback) + assert subgraph.scores["node_a"] > subgraph.scores["node_b"] + + def test_negative_feedback_lowers_score(self, env) -> None: + feedback, temporal = env + for _ in range(5): + feedback.record_explicit(["node_a"], "negative") + + subgraph = SubGraph() + node_a = _make_node("node_a") + node_b = _make_node("node_b") + subgraph.add_node(node_a, score=0.5) + subgraph.add_node(node_b, score=0.5) + + temporal.apply_temporal_weights(subgraph) + + assert subgraph.scores["node_a"] < subgraph.scores["node_b"] + + def test_no_feedback_is_neutral(self, env) -> None: + _, temporal = env + subgraph = SubGraph() + node_a = _make_node("node_a") + node_b = _make_node("node_b") + subgraph.add_node(node_a, score=0.5) + subgraph.add_node(node_b, score=0.5) + + temporal.apply_temporal_weights(subgraph) + + # Without any feedback data, both should be equal + assert abs(subgraph.scores["node_a"] - subgraph.scores["node_b"]) < 0.001 + + def test_backward_compat_without_feedback_service(self, tmp_path: Path) -> None: + """Temporal weights work correctly without feedback service.""" + repo_dir = tmp_path / "repo" + repo_dir.mkdir() + config = MimirConfig( + repos=[RepoConfig(name="test", path=repo_dir)], + data_dir=tmp_path / ".mimir", + temporal=TemporalConfig(co_retrieval_enabled=False), + ) + temporal = TemporalService(config=config) + # Deliberately NOT setting feedback service + + subgraph = SubGraph() + subgraph.add_node(_make_node("node_a"), score=0.8) + subgraph.add_node(_make_node("node_b"), score=0.3) + + temporal.apply_temporal_weights(subgraph) + + # Should use the 4-term formula, higher initial score → higher final + assert subgraph.scores["node_a"] > subgraph.scores["node_b"] diff --git a/tests/services/test_repo_sync.py b/tests/services/test_repo_sync.py new file mode 100644 index 0000000..b828942 --- /dev/null +++ b/tests/services/test_repo_sync.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import hmac +from textwrap import dedent +from hashlib import sha256 +from pathlib import Path + +import pytest + +from mimir.domain.config import AdminConfig, MimirConfig, RepoConfig +from mimir.services.repo_sync import RepoSyncService, parse_webhook_payload + + +def _config(tmp_path: Path) -> MimirConfig: + return MimirConfig( + repos=[ + RepoConfig( + name="payments", + path=tmp_path / "repos" / "payments", + clone_url="git@github.com:acme/payments.git", + branch="main", + webhook_repo="payments-service", + ), + ], + data_dir=tmp_path / ".mimir", + admin=AdminConfig( + webhook_secret_env="MIMIR_WEBHOOK_SECRET", + mirrors_dir=str(tmp_path / "mirrors"), + enable_repo_sync=True, + ), + ) + + +def test_config_allows_missing_repo_path_when_clone_url_is_configured(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MIMIR_WEBHOOK_SECRET", "topsecret") + cfg = _config(tmp_path) + + assert cfg.repos[0].clone_url == "git@github.com:acme/payments.git" + assert cfg.repos[0].branch == "main" + assert cfg.admin.enable_repo_sync is True + + +def test_config_load_preserves_repo_sync_fields(tmp_path: Path) -> None: + config_path = tmp_path / "mimir.toml" + config_path.write_text(dedent(""" + [admin] + webhook_secret_env = "MIMIR_WEBHOOK_SECRET" + admin_token_env = "MIMIR_ADMIN_TOKEN" + enable_repo_sync = true + job_history_limit = 17 + + [[repos]] + name = "payments" + path = "repos/payments" + clone_url = "git@github.com:acme/payments.git" + branch = "release" + webhook_repo = "payments-service" + """)) + + cfg = MimirConfig.load(config_path) + + assert cfg.repos[0].clone_url == "git@github.com:acme/payments.git" + assert cfg.repos[0].branch == "release" + assert cfg.repos[0].webhook_repo == "payments-service" + assert cfg.admin.admin_token_env == "MIMIR_ADMIN_TOKEN" + assert cfg.admin.job_history_limit == 17 + + +def test_verify_signature_accepts_sha256_hex_header(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MIMIR_WEBHOOK_SECRET", "topsecret") + svc = RepoSyncService(_config(tmp_path)) + body = b'{"repo":"payments-service","branch":"main","commit_sha":"abc123"}' + digest = hmac.new(b"topsecret", body, sha256).hexdigest() + + assert svc.verify_signature(body, f"sha256={digest}") is True + assert svc.verify_signature(body, digest) is True + assert svc.verify_signature(body, "sha256=wrong") is False + + +def test_parse_webhook_payload_normalizes_branch() -> None: + payload = parse_webhook_payload( + b'{"repository":{"name":"payments-service"},"ref":"refs/heads/main","after":"abc123"}' + ) + + assert payload["repo"] == "payments-service" + assert payload["branch"] == "main" + assert payload["commit_sha"] == "abc123" diff --git a/tests/test_url_normalization.py b/tests/services/test_url_normalization.py similarity index 100% rename from tests/test_url_normalization.py rename to tests/services/test_url_normalization.py diff --git a/tests/test_runtime_publish_query.py b/tests/test_runtime_publish_query.py new file mode 100644 index 0000000..93050d1 --- /dev/null +++ b/tests/test_runtime_publish_query.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +from unittest.mock import Mock + +import pytest +from aiohttp.test_utils import make_mocked_request + +from mimir.adapters.http.app import _build_app +from mimir.adapters.http.state import HttpServerState +from mimir.adapters.web.routes import register_routes as register_web_routes +from mimir.adapters.web.state import WebServerState +from mimir.domain.config import EmbeddingConfig, MimirConfig, RepoConfig +from mimir.domain.errors import NoActiveIndexError +from mimir.domain.graph import CodeGraph +from mimir.domain.models import Node, NodeKind +import mimir.runtime as runtime_module +from mimir.runtime import IndexerRuntime, QueryRuntime + + +class _FakeEmbedder: + async def embed_batch(self, texts: list[str]) -> list[list[float]]: + return [[1.0, 0.0, 0.0] for _ in texts] + + +def _config(tmp_path) -> MimirConfig: + repo = tmp_path / "repo" + repo.mkdir() + return MimirConfig( + repos=[RepoConfig(name="repo", path=repo, language_hint="python")], + data_dir=tmp_path / ".mimir", + embeddings=EmbeddingConfig(model="local:test"), + ) + + +def _graph(node_id: str, *, raw_code: str = "def handle():\n return 1\n") -> CodeGraph: + graph = CodeGraph() + graph.add_node(Node( + id="repo:", + repo="repo", + kind=NodeKind.REPOSITORY, + name="repo", + )) + graph.add_node(Node( + id="repo:service.py", + repo="repo", + kind=NodeKind.FILE, + name="service.py", + path="service.py", + raw_code=raw_code, + )) + graph.add_node(Node( + id=node_id, + repo="repo", + kind=NodeKind.FUNCTION, + name="handle", + path="service.py", + raw_code=raw_code, + embedding=[1.0, 0.0, 0.0], + )) + return graph + + +def test_query_runtime_status_without_active_index_and_require_graph_fails(tmp_path) -> None: + runtime = QueryRuntime(_config(tmp_path)) + try: + status = runtime.status() + assert status["active_version"] is None + assert status["graph_nodes"] == 0 + with pytest.raises(NoActiveIndexError): + runtime.require_graph() + finally: + runtime.close() + + +def test_publish_graph_then_query_runtime_loads_and_reloads_active_version(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + cfg = _config(tmp_path) + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + indexer = IndexerRuntime(cfg) + try: + first = indexer.publish_graph(_graph("repo:service.py::handle")) + query = QueryRuntime(cfg) + try: + assert query.active_version.version == first.version + assert query.require_graph().has_node("repo:service.py::handle") + assert query.status()["embedding_model"] == "local:test" + assert query.status()["embedding_dim"] == 3 + + second = indexer.publish_graph(_graph("repo:service.py::handle_v2", raw_code="def handle_v2():\n return 2\n")) + assert second.version != first.version + assert query.active_version.version == first.version + finally: + query.close() + finally: + indexer.close() + + +@pytest.mark.asyncio +async def test_query_runtime_reload_if_changed_swaps_graph(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + cfg = _config(tmp_path) + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + indexer = IndexerRuntime(cfg) + try: + indexer.publish_graph(_graph("repo:service.py::handle")) + query = QueryRuntime(cfg) + try: + second = indexer.publish_graph(_graph("repo:service.py::handle_v2", raw_code="def handle_v2():\n return 2\n")) + assert await query.reload_if_changed() is True + assert query.active_version.version == second.version + assert query.require_graph().has_node("repo:service.py::handle_v2") + assert not query.require_graph().has_node("repo:service.py::handle") + finally: + query.close() + finally: + indexer.close() + + +@pytest.mark.asyncio +async def test_http_status_without_active_index_and_context_503(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + runtime = QueryRuntime(_config(tmp_path)) + app = _build_app(HttpServerState(runtime=runtime, workspace_name="default")) + try: + health = await _request(app, "GET", "/api/v1/health") + assert health.status == 200 + assert health.json["active_version"] is None + + status = await _request(app, "GET", "/api/v1/index/status") + assert status.status == 200 + assert status.json["active_version"] is None + + context = await _request(app, "POST", "/api/v1/context", json_body={"query": "handle"}) + assert context.status == 503 + assert context.json["error"] == "No active index" + finally: + await app.cleanup() + + +@pytest.mark.asyncio +async def test_http_index_status_reports_active_version(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + cfg = _config(tmp_path) + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + indexer = IndexerRuntime(cfg) + try: + version = indexer.publish_graph(_graph("repo:service.py::handle")) + runtime = QueryRuntime(cfg) + app = _build_app(HttpServerState(runtime=runtime, workspace_name="default")) + try: + response = await _request(app, "GET", "/api/v1/index/status") + assert response.status == 200 + payload = response.json + assert payload["active_version"] == version.version + assert payload["graph_nodes"] == 3 + assert payload["embedding_model"] == "local:test" + finally: + await app.cleanup() + finally: + indexer.close() + + +def test_indexer_lifecycle_can_activate_and_prune_versions(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + cfg = _config(tmp_path) + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + indexer = IndexerRuntime(cfg) + try: + first = indexer.publish_graph(_graph("repo:service.py::handle")) + second = indexer.publish_graph(_graph("repo:service.py::handle_v2")) + third = indexer.publish_graph(_graph("repo:service.py::handle_v3")) + + activated = indexer.activate_version(first.version) + removed = indexer.prune_versions(keep=1) + + assert activated.version == first.version + assert first.version not in removed + assert second.version in removed + assert third.version not in removed + finally: + indexer.close() + + +def test_query_runtime_rejects_embedding_model_mismatch(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + cfg = _config(tmp_path) + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + indexer = IndexerRuntime(cfg) + try: + indexer.publish_graph(_graph("repo:service.py::handle")) + finally: + indexer.close() + + mismatched = MimirConfig( + repos=cfg.repos, + data_dir=cfg.data_dir, + embeddings=EmbeddingConfig(model="local:other"), + ) + with pytest.raises(Exception, match="embedding model mismatch"): + QueryRuntime(mismatched) + + +@pytest.mark.asyncio +async def test_mcp_over_http_without_active_index_returns_503(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + runtime = QueryRuntime(_config(tmp_path)) + app = _build_app(HttpServerState(runtime=runtime, workspace_name="default")) + try: + response = await _request(app, "POST", "/api/v1/mcp", json_body={ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "get_graph_stats", "arguments": {}}, + }) + + assert response.status == 503 + assert response.json["error"]["message"].startswith("No active index") + finally: + await app.cleanup() + + +@pytest.mark.asyncio +async def test_web_inspector_without_active_index_returns_503(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(runtime_module, "_build_embedder", lambda config: _FakeEmbedder()) + runtime = QueryRuntime(_config(tmp_path)) + app = _build_web_app(runtime) + try: + response = await _request(app, "GET", "/api/stats") + + assert response.status == 503 + assert response.json["error"] == "No active index" + finally: + await app.cleanup() + + +class _Response: + def __init__(self, response) -> None: + import json + + self.status = response.status + self.json = json.loads(response.text) + + +async def _request(app, method: str, path: str, *, json_body: dict | None = None) -> _Response: + import json + from aiohttp import streams + + # Mock protocol: aiohttp>=3.14 calls flow-control hooks (e.g. resume_reading) on it. + payload = streams.StreamReader(protocol=Mock(_reading_paused=False), limit=2**16) + if json_body is not None: + payload.feed_data(json.dumps(json_body).encode("utf-8")) + payload.feed_eof() + request = make_mocked_request( + method, + path, + headers={"Content-Type": "application/json"}, + app=app, + payload=payload, + ) + match = await app.router.resolve(request) + request._match_info = match + response = await match.handler(request) + return _Response(response) + + +def _build_web_app(runtime: QueryRuntime): + from aiohttp import web + + routes = web.RouteTableDef() + register_web_routes(routes, WebServerState(runtime=runtime)) + app = web.Application() + app.router.add_routes(routes) + return app