# Memory Governance Specification v1.0

**Status:** Active
**Version:** 1.0
**Scope:** abi-template and all adopted repositories

---

## 1. Purpose

This document defines the Memory Governance Protocol for abi-template: the rules, structures, and automated checks that govern how long-running session state and governance knowledge are maintained, verified, and exported across AI-assisted development sessions.

Memory governance ensures that:
- Context handed to AI agents is accurate and verifiable.
- Session state does not silently drift from repository reality.
- Humans can resume any session from a known, authoritative state.
- Generated context bundles are deterministic and auditable.

---

## 2. Context Surface Boundaries

abi-template maintains three orthogonal context surfaces. Memory governance does **not** duplicate them.

| Surface | Path | Owner | Purpose |
|---------|------|-------|---------|
| **Agent-bootstrap context** | `context/` | AI infra | Runtime context packs served to agents at task start. Governed by `context/CONTEXT_MANIFEST.json` and validated by `script/context-gate`. |
| **Generated artifacts** | `artifacts/context/` | CI | Machine-generated CONTEXT_MAP and JSON summaries. Read-only for humans. |
| **Session memory** | `memory/` | Human maintainers | Long-running human-maintained state: task queues, decisions, risk register, interface ledger, glossary, and resume prompts. |

### Boundary rules

1. `context/current/` contains **runtime agent orientation files** — what AI reads at task start.
2. `memory/` contains **human-maintained governance state** — what humans write and curate across sessions.
3. `memory/` files are inputs to `script/context-export`, which assembles them (alongside `context/` files) into `context_bundle/` for portable session resumption.
4. Neither `memory/` nor `context_bundle/` replaces the other. They serve different lifecycle stages.

---

## 3. Memory Directory Structure

```
memory/
  README.md                 # This protocol overview (human-readable)
  templates/
    STATE.md                # Template: current system state snapshot
    TASKS.md                # Template: task queue and backlog
    DECISIONS.md            # Template: architectural decision log
    RISKS.md                # Template: risk register
    INTERFACES.md           # Template: interface and contract ledger
    GLOSSARY.md             # Template: domain terminology
    RESUME_PROMPT.md        # Template: AI session resume prompt scaffold
```

Adopted repositories populate the templates with actual content. The templates define required sections and field markers; `script/memory-drift-check` verifies that deployed files satisfy the template contract.

---

## 4. Memory File Lifecycle

```
Create (from template)
  → Populate (human edits)
    → Verify (script/memory-drift-check)
      → Bundle (script/context-export → context_bundle/)
        → Archive (memory/archive/<date>/ on major state change)
```

### 4.1 Create

Copy the relevant template from `memory/templates/` into `memory/` (at the root or a named subdirectory). Templates contain `<!-- REQUIRED: <field_name> -->` markers that must be replaced with actual content before passing verification.

### 4.2 Populate

Humans edit memory files between sessions. Fields map to required sections defined in `MEMORY_VERIFIER_ALGORITHM.md`.

### 4.3 Verify

`script/memory-drift-check` runs the verification algorithm (see `docs/governance/MEMORY_VERIFIER_ALGORITHM.md`) and produces a PASS / WARN / FAIL verdict. Default mode is WARN: findings are reported but do not block CI.

### 4.4 Bundle

`script/context-export` assembles a `context_bundle/` snapshot:
- `context_bundle/BUNDLE.md` — Human-readable summary of the bundle contents.
- `context_bundle/pointers.json` — Machine-readable list of contributing files with SHA-256 digests.

Bundles are **deterministic**: identical inputs produce byte-identical outputs. No timestamps, no random elements.

### 4.5 Archive

Before a major state transition (new phase, milestone release), copy the current `memory/` snapshot to `memory/archive/<YYYY-MM-DD>-<label>/`. The drift checker ignores `memory/archive/`.

---

## 5. Policy Reference

Runtime policy for memory governance lives in `.abi/memory_policy.yml`. Editable without a code review unless the change affects:
- Required template sections (triggers `template` check category)
- Bundle output paths (requires updating `script/context-export`)
- Enforcement mode (`warn` → `block`)

See `.abi/memory_policy.yml` for current values.

---

## 6. Governance Rules

1. **No secrets.** Memory files must never contain API keys, tokens, passwords, private keys, or PII. The memory drift checker enforces this via `disallowed_patterns` from `.abi/memory_policy.yml`.

2. **No stale unfilled markers.** A deployed memory file must not contain unfilled template markers (`<!-- REQUIRED: ... -->`). Any unfilled marker is a WARN finding.

3. **Required sections must be present.** Each memory file type has a mandatory set of sections (defined in `MEMORY_VERIFIER_ALGORITHM.md`). Missing sections are WARN findings (or FAIL in strict mode).

4. **Bundle determinism.** Running `script/context-export` twice on the same inputs must produce bit-for-bit identical `context_bundle/` output. The CI workflow (`memory-drift.yml`) validates this on every PR.

5. **Template freshness.** When `memory/templates/` changes, deployed memory files must be re-verified within `freshness_days` (default: 30, configurable in `.abi/memory_policy.yml`).

6. **Archive before wipe.** Before replacing deployed memory files during a major state change, archive the previous version under `memory/archive/`.

---

## 7. Integration Points

### 7.1 `script/context-gate`

The existing agent-bootstrap gate (`script/context-gate`) validates `context/CONTEXT_MANIFEST.json`. Memory governance does **not** modify `context/`. The two gates run independently.

### 7.2 `script/memory-drift-check`

The memory drift checker (new, this protocol) validates deployed memory files against their templates and the rules in Section 6. It is wired into `.github/workflows/memory-drift.yml`.

### 7.3 `script/context-export`

Assembles `context_bundle/` from live `memory/` + `context/current/` files. Called by humans at session start to produce a portable bundle for AI agents that cannot traverse the full repo.

### 7.4 TemplateSynch

When the upstream abi-template updates `memory/templates/`, adopted repositories receive the change through the normal TemplateSynch propagation workflow (see `docs/guides/MEMORY_PROTOCOL_QUICKSTART.md` — TemplateSynch section). Template version is recorded in `.abi/memory_policy.yml` under `template_version`.

---

## 8. Enforcement Levels

| Level | Behaviour | Default |
|-------|-----------|---------|
| `warn` | All findings reported; exit 0 always. | Yes |
| `block` | Exit 1 on any FAIL finding. WARN findings still exit 0. | No |
| `strict` | Exit 1 on any FAIL or WARN finding. | No |

Set via `enforcement_mode` in `.abi/memory_policy.yml` or `--strict` / `--block` flags on `script/memory-drift-check`.

---

## 9. Non-Goals

- Memory governance does **not** replace `context/CONTEXT_MANIFEST.json` or `script/context-gate`.
- Memory governance does **not** auto-populate memory files from code or commits.
- Memory governance does **not** enforce correctness of content — only structural completeness and policy compliance.
- Memory governance does **not** version-control the `context_bundle/` directory. Bundles are ephemeral; `memory/` is the source of truth.

---

## 10. References

- `docs/governance/MEMORY_VERIFIER_ALGORITHM.md` — Detailed verification algorithm
- `docs/guides/MEMORY_PROTOCOL_QUICKSTART.md` — Operational quick-start
- `memory/README.md` — Directory-level overview
- `.abi/memory_policy.yml` — Runtime policy configuration
- `script/memory-drift-check` — Drift checker CLI
- `script/context-export` — Bundle generator CLI
- `.github/workflows/memory-drift.yml` — CI integration

---

## 11. Update Trigger Matrix

This matrix defines which memory files must be updated for each category of repository change. CI will WARN if a PR modifies a listed path without a corresponding memory file update (unless the `memory:override` label is applied — see Section 13).

| Change type | Trigger condition | Required memory file updates |
|-------------|-------------------|------------------------------|
| `impl` | New or modified script, module, or CLI | `memory/STATE.md` (current phase/state); `memory/TASKS.md` (completed/new tasks); `memory/DECISIONS.md` (if an architectural decision was made) |
| `iface` | Interface or contract change (schema, API boundary, contract lock) | `memory/INTERFACES.md` (updated contract ledger); `memory/DECISIONS.md` (change rationale); `memory/STATE.md` |
| `runtime` | Runtime config change (`.abi/`, policy, CI workflow) | `memory/STATE.md`; `memory/DECISIONS.md` (enforcement rationale) |
| `tests` | Test changes only (no production code change) | `memory/TASKS.md` only (mark task complete) |
| `docs` | Documentation updates only | `memory/TASKS.md` (optional, if task-driven) |
| `major-phase` | Phase transition or milestone release | ALL files: archive previous state (`memory/archive/`), reset `STATE.md`/`TASKS.md`, update `DECISIONS.md`, update `RESUME_PROMPT.md` |

---

## 12. Definition of Done

A memory update is considered complete only when **all** of the following are satisfied:

- [ ] All `<!-- REQUIRED: ... -->` markers replaced with actual content in every deployed memory file.
- [ ] All required `## Section` headings present per file type (see `MEMORY_VERIFIER_ALGORITHM.md`).
- [ ] `script/memory-drift-check` reports PASS (no FAIL findings; no WARN findings in `--block` mode).
- [ ] Evidence pointer included: at least one `<!-- ref: <issue|PR|commit> -->` tag or inline link in the updated memory file(s).
- [ ] Context bundle regenerated: `script/context-export` run after all memory edits complete.
- [ ] `context_bundle/` changes committed in the same commit or PR as the `memory/` changes.
- [ ] No secrets in any `memory/*.md` file (verified automatically by the drift checker secret scan).

---

## 13. Override Policy

When a complete memory update cannot be finished before merging (e.g., exploratory branch, time-constrained release), the maintainer may apply an override.

### Required PR label

`memory:override`

### Required rationale block

The following block **must** appear in the PR description when the `memory:override` label is applied:

```
<!-- memory:override
reason: <why the memory update cannot be completed before merge>
follow-up: <issue number or task that will complete the update>
deadline: <date or milestone by which the update must be completed>
-->
```

### Verifier behavior under override

| Enforcement mode | With `memory:override` label | Without label |
|-----------------|------------------------------|---------------|
| `warn` | WARN findings reported; CI exits 0 (no change — warn never blocks) | Same |
| `block` | WARN findings downgraded to INFO; FAIL findings still exit 1 | WARN exits 0; FAIL exits 1 |
| `strict` | WARN findings downgraded to INFO; FAIL findings still exit 1 | WARN or FAIL exits 1 |

> **Note:** The `memory:override` label **never** suppresses `secret_scan` FAIL findings. Secrets must be removed unconditionally, regardless of any label.

---

## 14. WARN→FAIL Rollout Plan

The default enforcement mode is `warn`. This section defines the criteria and procedure for promoting to stricter enforcement on protected branches.

### Phase 1 — Warn-only (current default)

Success criteria that must be met before promoting to Phase 2:

1. **Zero-drift streak:** Ten consecutive PRs merged to the main branch with zero WARN findings from `script/memory-drift-check`.
2. **Clean deployed files:** All deployed `memory/*.md` files have no unfilled markers and no missing required sections.
3. **Sprint validation:** At least one full team sprint completed using the memory protocol without requiring a `memory:override` label.
4. **Drift resolved promptly:** Any `template_drift` WARN resolved within `max_drift_days` (default: 30 days) on its first occurrence.

### Promotion criteria (WARN → block)

1. Run `script/memory-drift-check --strict` locally on `main` HEAD and confirm PASS.
2. Update `.abi/memory_policy.yml`: set `enforcement_mode: block`.
3. Update `.github/workflows/memory-drift.yml`: remove `continue-on-error: true` from the `memory-drift` job.
4. Open a PR with these two file changes. All CI checks must pass before merging.

### Phase 2 — Block on protected branches

Enabling rules once Phase 1 criteria are met:

- `enforcement_mode: block` in `.abi/memory_policy.yml`.
- CI exits 1 on any FAIL finding (secret scan). WARN findings still exit 0.
- `--strict` mode reserved for pre-release gates only (passed as a CLI flag, not set in `memory_policy.yml`).
- WARN→FAIL findings (unfilled markers, missing sections) block the PR only when `--strict` is active.
