# opencode-plugin-memory

[![npm version](https://img.shields.io/npm/v/@chncaesar/opencode-plugin-memory)](https://www.npmjs.com/package/@chncaesar/opencode-plugin-memory)

PR-gated, project-scoped persistent memory for [OpenCode](https://opencode.ai). The LLM proposes durable knowledge; a human approves it by merging a pull request before it becomes shared truth. No cloud dependency, no vector database.

## How it works

- Six tools (`memory_propose`, `memory_update`, `memory_delete`, `memory_read`, `memory_review`, `memory_publish`) are registered with OpenCode and available to the LLM during every session.
- The LLM **never writes shared truth directly**. It only writes a proposal file into a machine-local, git-ignored `.memory/staging/` folder.
- A local **bot** (a small CLI you run on your machine) watches staging, branches, commits each proposal into `memory/active/`, and opens a pull request.
- A **human** reviews the PR against a checklist and merges it. Merge is the only approval.
- On merge, a **CI** workflow regenerates the committed `memory/_summary.md` index, which is the only memory content injected into every session's system prompt (titles + IDs, never full bodies — full bodies load lazily via `memory_read`).

A memory is not valid until it is merged. Proposed, wrong, or harmful memories never silently become shared truth.

## Storage layout

State is positional — the folder a file lives in is its status:

```
.memory/staging/mem-*.md    machine-local drop folder, git-ignored, the agent writes here
memory/active/mem-*.md      merged truth; the only memories injected into context
memory/retired/mem-*.md     removed memories, with reason and provenance
memory/_summary.md          committed index, one line per active memory, regenerated by CI
```

Each file is self-describing via YAML frontmatter (`id`, `title`, `author`, `source`, `proposed_at`, `approved_at`, `approved_by`, `supersedes` / `superseded_by`, `retired_at`, `retired_reason`, `related_pr`, and — for staged files — `intent`). IDs are random and collision-free (`mem-` + 8 base64url chars), so multiple branches can add memories concurrently.

## Installation

Install the published package:

```bash
npm i @chncaesar/opencode-plugin-memory
```

Restart OpenCode afterwards: plugins are loaded per server process. Then add it to your OpenCode configuration:

```jsonc
// opencode.json or ~/.config/opencode/opencode.jsonc
"plugin": ["@chncaesar/opencode-plugin-memory"]

// from a local clone
"plugin": ["/path/to/opencode-plugin-memory"]

// with options
"plugin": [["@chncaesar/opencode-plugin-memory", { "maxSummaryChars": 10000 }]]
```

## The bot

The LLM can run the bot itself through the argument-less `memory_publish` tool. It needs no user approval because it only opens PRs (the merge is the gate), and all git work happens in a throwaway `git worktree`, so your checkout, branch and uncommitted files are never touched. A lock file (`.memory/bot.lock`) keeps a `watch` daemon and `memory_publish` from running at once.

The bot is the only component that holds repository credentials and runs git. It is a local daemon/CLI, not a GitHub Action — an Action runs remotely and can never see a local, git-ignored staging folder. It uses the `gh` CLI (already authenticated) to open PRs.

```bash
npx opencode-memory-bot once      # process staged proposals once, then exit
npx opencode-memory-bot watch     # poll staging forever (default every 2s)
```

Or from a clone: `node dist/bot.js once`. The bot:

- reads each staged file's `intent`;
- `propose` → branches `memory/<id>`, commits the file into `memory/active/` (moving any `supersedes` targets to `memory/retired/` with `superseded_by`), pushes, opens a PR, then removes the staged file;
- `retire` → moves `memory/active/<id>` to `memory/retired/` with the reason, opens a PR, removes the staged file.

The bot is idempotent: a proposal whose branch already exists is skipped, and a crash mid-run never double-commits. If opening a PR fails, the staged file is left in place and retried on the next poll — the bot never spins.

## CI

`.github/workflows/memory-summary.yml` runs on merge to the default branch and regenerates `memory/_summary.md` from `memory/active/`. It only commits when there is a diff, and tags the commit `[skip ci]` to avoid re-triggering itself. The bot never edits the index, so proposed memories stay invisible until merged.

## Configuration

- `maxSummaryChars` (number, default `10000`) — max characters used by the injected index of titles. The fixed writing policy is added separately.
- `enableLog` (boolean, default `true`) — write an operation log to `.memory/plugin.log`.
- `staleDays` (number, default `90`) — active memories older than this are listed as "aging" in `memory_review`. Informational only; nothing is retired on an age threshold.
- `auditIntervalMinutes` (number, default `1`) — minimum minutes between two background audits.
- `auditBatchChars` (number, default `400000`) — max characters of memory text per audit model call. The default assumes a ~1M-token model and about one token per character (Chinese); lower it if your audit model has a smaller context window, since an over-long prompt makes the audit fail. A larger store is split into batches of related entries, with a 3-entry overlap between batches; a memory is never cut in two, and a pair that lands in different batches can still be missed. Example: `["@chncaesar/opencode-plugin-memory", { "auditBatchChars": 100000 }]`.
- `backgroundAudit` (boolean, default `true`) — run the model-judged semantic audit after sessions go idle: a restricted `memory-audit` agent reads every active memory and reports duplicate / refinement / contradiction findings, each of which becomes a retirement proposal (turned into a PR by the bot).
- `auditModel` (string, V2 host only) — model for the audit, as `"providerID/modelID"`. Without it the host default is used (the V1 audit agent prefers `small_model`).

## When does the LLM propose a memory?

The system prompt and tool description guide the LLM to call `memory_propose` when:

- the user says "remember this" / "save this";
- a reusable coding rule or project convention is discovered;
- a recurring bug pattern is fixed and the lesson should persist;
- the user corrects how the LLM communicates, reasons, edits, tests, or collaborates;
- the user confirms a non-obvious approach worked and should be repeated;
- a memory needs correcting, replacing, or removing because it went stale or conflicts.

Unscoped corrections and preferences are durable by default — the user does not need to say "remember this". Instructions limited to the current answer, task, or file are not proposed. Duplicates are checked against active and staged memories before proposing.

## Migration from the legacy single-file store

On first run, the plugin migrates the legacy `.opencode/memory/MEMORY.md` (and `.agents/memory/MEMORY.md`) — the old `Active`/`Archived` + `MEM-NNN` + `nextSeq` format — into one file per memory under `memory/active/` and `memory/retired/`. A `memory/.migration.json` sidecar maps old IDs to new ones so `superseded_by` links resolve. Migration is idempotent, the legacy file is left in place as a backup, and it never blocks startup.

## Development

```bash
npm install
npm run typecheck   # type-check only, no emit
npm run build       # compile to dist/
npm test            # compile + run unit tests (Node built-in runner)
```

## Design notes

- **PR-gated** — a memory is valid only after merge; nothing proposed is trusted before a human approves it.
- **Credential-free agent** — the agent never holds repo credentials and never runs git; it only writes a local file.
- **Progressive loading** — the prompt sees a compact index of titles; full bodies load on demand.
- **Memory validity is independent of code reversibility** — a memory survives its own review lifecycle and is never bundled into a code change.
- **No automatic deletion** — nothing is retired on a timer; retirement always goes through a PR.
- **Zod version** — uses `tool.schema` from `@opencode-ai/plugin` (zod 4), never `import { z } from "zod"` directly.
