Metadata-Version: 2.5
Name: learning-loop-mcp
Version: 0.4.1
Summary: MCP server (stdio) to query and validate lessons learned across projects, closing the learning loop.
Project-URL: Homepage, https://github.com/tiempor3al/learning-loop-mcp
Project-URL: Repository, https://github.com/tiempor3al/learning-loop-mcp
Project-URL: Issues, https://github.com/tiempor3al/learning-loop-mcp/issues
License: MIT License
        
        Copyright (c) 2026 Manuel Martínez (tiempor3al)
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Requires-Dist: fastembed>=0.8.0
Requires-Dist: fastmcp>=4.0.2
Requires-Dist: mcp>=2.1.1
Requires-Dist: pyyaml>=6
Requires-Dist: sqlite-vec>=0.1.9
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.9; extra == 'dev'
Description-Content-Type: text/markdown

# learning-loop-mcp

A **portable learning-loop kit** for AI-agent projects: an MCP server (stdio)
plus a thin CLI that index, search and validate **lessons learned** across
project repositories, closing the loop — read lessons when a task starts,
record verified solutions while working, consolidate on close — **without
loading full files into every conversation**.

The source of truth stays each project's git-tracked `docs/lessons.md` and
`docs/metrics/errors.yaml` (Markdown/YAML). This server builds a local SQLite
index (FTS5 + sqlite-vec) over them and validates format/conventions.
Verified solutions are appended to `docs/metrics/solutions.yaml`
(git-tracked, write-through) and mirrored into the derived index.

## How the kit is layered

```
learning-loop-mcp repo (single source)        [kit root]
├── src/learning_loop_mcp/     MCP server + CLI + loop orchestration
├── skills/learning-loop/      the ritual, one skill (auto-loads by relevance)
├── templates/                 canonical seeds (lessons.md, errors.yaml,
│                              solutions.yaml, AGENTS ritual block)
├── scripts/install.sh         idempotent installer (Hermes MCP registration)
├── scripts/init-project.sh    per-project bootstrap
└── docs/lessons-format.md     canonical format (also served as a resource)
```

- The **canonical files and format** are served by the MCP server as
  `learning-loop://` resources — the agent reads them by URI, it never needs
  to know where the kit lives.
- The **ritual** is one skill (`learning-loop`), not duplicated text in every
  repo. Project `AGENTS.md` files reference the skill in a single line.
- **No absolute host paths** anywhere: the projects root comes from an env
  var, the kit locates itself by `__file__`, docs live under
  `<PROJECTS_ROOT>/<project>/docs/`.

## Features

- **Parser + validator** of the canonical `docs/lessons.md` format
  (areas, bullets, `Error class:` / `Check:` / `Task:` markers) crossed with
  `docs/metrics/errors.yaml` (error classes, checks, dedup).
- **Hybrid search**: SQLite FTS5 (lexical, citable snippets with file:line) +
  sqlite-vec KNN (semantic) fused with RRF, per-project isolation.
- **Local embeddings** via fastembed (small EN models), offline fallback to
  FTS5; no external APIs.
- **Verified-solution registry**: append-only `solutions` table (immutable
  events, incremental revisions, forward-only states with per-state gates) +
  durable per-project YAML write-through + drift detection in `status`.
- **Typed durable memory sources**: canonical ADRs in `docs/adr/` and
  operational runbooks in `docs/runbooks/` are discovered safely, indexed with
  kind/status/citations, and reported in status counts; the source files remain
  authoritative.
- **Portable project root**: `LEARNING_LOOP_PROJECTS_ROOT` resolves per call,
  so one install serves repos anywhere on disk (a fresh Hermes with different
  paths only sets this env).

## Requirements

- Python >= 3.11, [uv](https://docs.astral.sh/uv/).

## Install

```bash
uv sync --extra dev                 # creates .venv with deps + dev extras
uv run pytest                       # full suite
uv run ruff check src tests         # lint
```

### Install from PyPI

For a Hermes host where the repository is not being developed:

```bash
uv tool install learning-loop-mcp==0.4.1
hermes mcp add learning-loop-mcp \
  --command "$HOME/.local/bin/learning-loop-mcp-server" \
  --env LEARNING_LOOP_MCP_DB="$HOME/.local/share/learning-loop-mcp/index.db" \
  --env LEARNING_LOOP_PROJECTS_ROOT="$HOME/Proyectos"
hermes mcp test learning-loop-mcp
```

If `uv tool install` places the executable elsewhere, use the path printed by
`uv tool install` in `--command`. Restart Hermes after registration. The PyPI
wheel includes the MCP resources; `scripts/init-project.sh` and the optional
skill distribution remain available from a repository checkout.

### Secure PyPI publishing with GitHub OIDC

`.github/workflows/publish-pypi.yml` uses PyPI Trusted Publishing. Configure a
pending publisher in the PyPI account settings with:

```text
Project: learning-loop-mcp
Owner: tiempor3al
Repository: learning-loop-mcp
Workflow: publish-pypi.yml
Environment: pypi
```

Create the `pypi` GitHub Environment and require approval before deployment.
The workflow requests only `contents: read` and `id-token: write`; it stores no
PyPI token. After merging a release, publish a versioned tag:

```bash
git tag -a v0.4.1 -m "release: learning-loop-mcp 0.4.1"
git push origin v0.4.1
```

The first successful run converts the pending publisher into a normal PyPI
publisher. TestPyPI requires a separate pending publisher and environment.

### Install from a repository checkout

```bash
./scripts/install.sh                 # uv sync + register with Hermes + test
```

Idempotent: safe to re-run. If a legacy index exists at
`~/.cache/learning-loop-mcp/index.db` and the destination has no copy, it is
migrated to `~/.local/share/learning-loop-mcp/index.db` (XDG data home).
Useful overrides (env):

- `LEARNING_LOOP_MCP_DB` — explicit index path.
- `LEARNING_LOOP_PROJECTS_ROOT` — project repos root (default `~/Proyectos`).
- `LEARNING_LOOP_INSTALL_SKIP_HERMES=1` — sync + migration only.
- `LEARNING_LOOP_INSTALL_WITH_SKILLS=1` — also copy `skills/` to
  `$HERMES_HOME/skills`.
- `LEARNING_LOOP_INSTALL_DEV=0` — production host with a dedicated venv
  (skips dev extras).

After installing, restart the Hermes gateway so the server tools and
`learning-loop://` resources appear in new sessions.

### Enroll a project in the loop

```bash
scripts/init-project.sh /path/to/<project>
```

Creates `docs/lessons.md`, `docs/metrics/{errors,solutions}.yaml` (canonical
seeds), and appends the one-line ritual reference to the project's
`AGENTS.md`. Never overwrites existing files; safe to re-run.

## Usage

CLI (entry point `learning-loop-mcp`):

```bash
learning-loop-mcp index <project> [--lessons PATH] [--with-embeddings] [--db PATH]
learning-loop-mcp search "query" [--project P] [--with-embeddings] [--max-distance N] [--json]
learning-loop-mcp learning-context PROJECT TASK [--version 1|2] [--kanban-board BOARD] [--db PATH] [--json]
learning-loop-mcp capture-outcome PROJECT --draft PATH --output PATH [--projects-root PATH] [--json]
learning-loop-mcp amnesia-check PROJECT [--kanban-board BOARD] [--projects-root PATH] [--db PATH] [--json]
learning-loop-mcp amnesia-evaluate PROJECT [--evaluation PATH] [--ignore-evaluation]
                    [--kanban-board BOARD] [--projects-root PATH] [--db PATH] [--json]
learning-loop-mcp validate <project> [--errors PATH] [--tests-dir PATH] [--json]
learning-loop-mcp status <project> [--json]
learning-loop-mcp register-solution <project> --solution-id X --title T --status E [--db PATH] [--json]
learning-loop-mcp solutions <project> [--solution-id X] [--status E] [--db PATH] [--json]
learning-loop-mcp reindex-solutions <project> [--solutions-path PATH] [--db PATH] [--json]
learning-loop-mcp backup [--db PATH] [--out PATH]
learning-loop-mcp backup --recovery --kanban-board BOARD [--checkpoint PATH] [--project PROJECT] [--projects-root PATH] [--db PATH] [--out PATH] [--json]
learning-loop-mcp export PROJECT... [--out PATH] [--projects-root PATH] [--json]
learning-loop-mcp import BUNDLE [--projects-root PATH] [--db PATH] [--json]
learning-loop-mcp import-recovery BUNDLE [--projects-root PATH] [--db PATH] [--json]
learning-loop-mcp resume PROJECT [--checkpoint PATH] [--projects-root PATH] [--json]
```

`export` creates a versioned `.tar.gz` bundle containing only the canonical
`lessons.md`, `errors.yaml` and `solutions.yaml` files plus a checksum manifest.
`backup --recovery --kanban-board BOARD` additionally packages the online-safe
learning-loop SQLite snapshot and Hermes' native Kanban archive (exported via
`hermes kanban boards export`, without reading Hermes' private SQLite schema).
With `--checkpoint PATH`, it also includes a validated YAML restore point and
human-readable `recovery/resume.md` containing completed work, next actions,
blockers, and validation evidence. It includes no attachments by default.
with Hermes' native `hermes kanban boards import` plus the learning-loop import.
`import` validates every member and checksum, rejects conflicting existing files,
creates a SQLite backup when an index exists, writes only canonical files, and
reindexes the imported projects. The SQLite `backup` command remains a separate
technical snapshot and is not the portable data format.
timestamped file next to the index by default (e.g.
`~/.local/share/learning-loop-mcp/learning-loop-20260906-120000.db`) and runs
an integrity check before reporting success. To restore: stop the server and
copy the backup over the index path.

`capture-outcome` validates a task-local JSON draft and writes it to the explicit
project-local output path. It reports `promoted: false` and never edits canonical
lessons, ADRs, runbooks, or solutions. `amnesia-check` is a read-only continuity
check that returns cited pass/warn/error findings and `next_action: unknown` when
no owner-curated action exists.

`amnesia-evaluate` combines those deterministic facts with an explicit
`docs/amnesia-test.md` report when one is available. It reports the evaluated
commit, seven rubric areas, score, citations, next action, limitations, and
warnings. It returns `score: unknown` when the report is missing, stale,
self-authenticating, invalid, or explicitly bypassed with `--ignore-evaluation`.
It never infers semantic comprehensibility from document presence.

MCP server (stdio, entry point `learning-loop-mcp-server`): tools `search`,
`learning_context` (legacy list by default, `context_version=2` for the ADD
package), `capture_outcome`, `amnesia_check`, `amnesia_evaluate`, `learning_status`, `index`,
`register_solution`, `reindex_solutions`, `solutions`; resources
`learning-loop://format/...` and `learning-loop://templates/...`.

`learning_context` v2 can include read-only Kanban state when `--kanban-board`
is supplied (or `LEARNING_LOOP_KANBAN_BOARD` is set). It invokes only
`hermes kanban --board BOARD list --json`, filters cards by the project's
workspace, and never reads Hermes' private SQLite database or mutates cards.
Without a configured board/provider it returns `task-state-unavailable`
explicitly instead of guessing.

ADD continuity contract, requirements, and the documented evaluation are available in
[docs/add-contract.md](docs/add-contract.md), [docs/requirements.md](docs/requirements.md),
[docs/amnesia-test.md](docs/amnesia-test.md), and the rationale-preserving ADR
format in [docs/decision-format.md](docs/decision-format.md).

Defaults: docs live in `<PROJECTS_ROOT>/<project>/docs/`; the index lives in
`$LEARNING_LOOP_MCP_DB` or `$XDG_DATA_HOME/learning-loop-mcp/index.db`.
Exit codes: 0 ok, 1 error-severity findings, 2 usage/IO error.

Note for `mcp` SDK clients: `stdio_client` uses a curated environment by
default; pass `env=dict(os.environ)` in `StdioServerParameters` so the server
sees `LEARNING_LOOP_MCP_DB` / `LEARNING_LOOP_PROJECTS_ROOT`.

## Canonical lesson language

**English** (ADR-0001): canonical lessons and everything new (code, docs,
messages) are written in English, which keeps small local EN embedding models
discriminative.

## Architecture

```text
project repos (docs/lessons.md + docs/metrics/errors.yaml
               + docs/metrics/solutions.yaml)             [source of truth]
        ↓ parser / validator
local SQLite FTS5 + sqlite-vec + per-project metadata
        ↓ query domain (loop.py, single source CLI ↔ MCP)
CLI  ─  MCP stdio server  ─  learning-loop:// resources (kit files)
```

## Debugging

- FastMCP logs go to **stderr**; stdout is reserved for JSON-RPC (do not
  pollute it).
- Tests are offline and credential-free; embeddings use synthetic vectors or
  the cached model.

## CI

- `.github/workflows/ci.yml` runs tests + lint + compile on every PR and push
 to main — canonical toolchain only (official GitHub actions + pip, no
  third-party actions).
- Dependency updates are handled by native **Dependabot**
  (`.github/dependabot.yml`): ecosystems `uv` (pyproject + uv.lock) and
  `github-actions`, weekly. No secrets or configuration needed.

## License

MIT — see [LICENSE](LICENSE).
