From 3881b1c0a382f5a93542b4c6fa4c73618365341a Mon Sep 17 00:00:00 2001 From: Fan Kai Date: Thu, 29 Oct 2026 11:31:56 +0800 Subject: [PATCH 01/26] docs: add the project-scoped memory spec Assemble the decision map (fktpp2022/pi-memory#1) into a self-contained spec: docs/spec/project-scoped-memory.md plus the qmd spike transcript and the pi cwd/session-lifecycle research it cites. Doc-only: no code changes. --- docs/research/pi-cwd-and-session-lifecycle.md | 226 ++++++++ docs/spec/appendix-qmd-scope-layout-spike.md | 110 ++++ docs/spec/project-scoped-memory.md | 493 ++++++++++++++++++ 3 files changed, 829 insertions(+) create mode 100644 docs/research/pi-cwd-and-session-lifecycle.md create mode 100644 docs/spec/appendix-qmd-scope-layout-spike.md create mode 100644 docs/spec/project-scoped-memory.md diff --git a/docs/research/pi-cwd-and-session-lifecycle.md b/docs/research/pi-cwd-and-session-lifecycle.md new file mode 100644 index 0000000..1557a03 --- /dev/null +++ b/docs/research/pi-cwd-and-session-lifecycle.md @@ -0,0 +1,226 @@ +# Research: pi's cwd and session-lifecycle guarantees + +Ticket: [#8 "Research: pi's cwd and session-lifecycle guarantees"](https://github.com/fktpp2022/pi-memory/issues/8) + +All citations are to the installed pi runtime: + +``` +PI = C:\Users\Lenovo\.pi\agent\install\releases\1.4.0\node_modules\@earendil-works\pi-coding-agent +``` + +Paths below are relative to `PI/`. Where the source and `PI/docs/` disagree, the source is cited and the disagreement is noted. + +## Summary + +- pi does **not** hand the session working directory to an extension at load time. `ExtensionFactory` receives only `ExtensionAPI` (`dist/core/extensions/types.d.ts:1518`), and `ExtensionAPI` has no `cwd` member (`dist/core/extensions/types.d.ts:1186-1420`). The cwd is only observable from an event-handler context (`ctx.cwd`, `dist/core/extensions/types.d.ts:221`), or indirectly through `pi.exec`'s default cwd (`dist/core/extensions/loader.js:331`). +- `ctx.cwd` is **not live**: it is a getter over a value captured when the extension runner was constructed (`dist/core/extensions/runner.js:630-633`, `dist/core/extensions/runner.js:200-206`), which in turn comes from `AgentSession._cwd`, assigned once at session construction and never reassigned (`dist/core/agent-session.js:182`). +- The cwd therefore only changes by **replacing the session runtime**, not by mutating the context. A `/resume` (or session import) of a session recorded in another directory creates a whole new runtime with a new cwd; `/new`, `/fork`, and `/reload` keep the same cwd. pi has no cwd-changing command and never calls `process.chdir`. +- `session_start` fires on the **new** runtime with the new cwd, and `session_shutdown` fires on the old runtime before the replacement. `session_before_switch` fires on the **old** runtime (old cwd). +- The extension factory is re-invoked on every runtime replacement, so module-level state in a pi-memory extension resets at each session start. +- Project trust gates which project resources **pi** loads (project settings, `.pi/extensions`, `.pi/SYSTEM.md`, …). It does **not** sandbox extension code: an extension can read any file the process can read. + +--- + +## 1. Can an extension obtain the session's working directory at extension-load time? + +**No — not through the extension API. Only inside an event handler.** + +The factory signature carries no context: + +> `export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise;` +> — `dist/core/extensions/types.d.ts:1518` + +`ExtensionAPI` (`dist/core/extensions/types.d.ts:1186`) exposes `on`, `registerCommand`, `registerTool`, `exec`, settings/model accessors, etc. — no `cwd` property. + +The cwd is nonetheless known internally at load time; it is threaded into the API object but only used as a default: + +> `return execCommand(command, args, options?.cwd ?? cwd, options);` +> — `dist/core/extensions/loader.js:331` (inside `createExtensionAPI(extension, runtime, cwd, eventBus)`, `dist/core/extensions/loader.js:192`; the cwd argument originates at `dist/core/extensions/loader.js:513-535`) + +Event-handler contexts do carry it: + +> `/** Current working directory */` +> `cwd: string;` +> — `dist/core/extensions/types.d.ts:221` (in `ExtensionContext`, `dist/core/extensions/types.d.ts:213`) + +So an extension can read the cwd as `ctx.cwd` in any event handler. + +The one value an extension can read without a context is `process.cwd()`. That is the **launch** directory, not necessarily the session cwd: + +> `const cwd = process.cwd();` +> — `dist/main.js:467` (pi has no `--cwd` flag; `dist/core/cli-args*` exposes none) + +pi never changes `process.cwd()` for the session (no `process.chdir` in `dist/core/**`; the only `process.chdir` occurrences are inside the bundled `cross-spawn` helper, which chdirs temporarily and restores). If a session recorded in `/other/project` is resumed, the effective session cwd is `/other/project` while `process.cwd()` still returns the launch directory. `process.cwd()` is therefore not a safe substitute for `ctx.cwd`. + +**Answer:** the session cwd is obtainable only from an event-handler context (`ctx.cwd`), or from `pi.exec`'s implicit default cwd. At load time the extension has no API-level way to read it. + +## 2. Does `ctx.cwd` reflect a directory change within a session, and can the extension notice? + +**`ctx.cwd` is a snapshot for the lifetime of one session runtime, and the cwd never changes inside a session runtime. A change of cwd happens only by replacing the runtime, and the extension is notified of that replacement.** + +The context getter returns a stored value: + +> `get cwd() { runner.assertActive(); return runner.cwd; }` +> — `dist/core/extensions/runner.js:630-633` + +and the runner stores it once: + +> `constructor(extensions, runtime, cwd, sessionManager, modelRegistry) { ... this.cwd = cwd; ... }` +> — `dist/core/extensions/runner.js:200-206` + +The runner's cwd is the session's cwd, assigned once and never reassigned: + +> `this._cwd = config.cwd;` +> — `dist/core/agent-session.js:182` (a grep of `dist/core/agent-session.js` shows `_cwd` only read at `:608`, `:1302`, `:2688`, `:2972`, `:2983` — never written again) + +> `this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, ...)` +> — `dist/core/agent-session.js:2983` + +Consequences: + +- **No in-session cwd change.** pi has no `/cd`-style command (full command list: `dist/core/slash-commands.js:3-26`), and the effective cwd is fixed per `AgentSession`. +- **A session switch replaces the runtime, it does not mutate the context.** Resuming another directory's session tears the old runtime down and builds a new one: + +> `const sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);` +> `...` +> `this.apply(await this.createRuntime({ cwd: sessionManager.getCwd(), ... sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile }, ... }));` +> — `dist/core/agent-session-runtime.js:128-143` (cwd at `:138`, event at `:141`) + +> `const cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd();` +> — `dist/core/session-manager.js:1344` (a resumed session's cwd comes from its stored session header) + + Each replacement builds fresh cwd-bound services and a fresh `AgentSession` (hence a fresh runner, hence a fresh `ctx.cwd`): + +> `cwd: options.services.cwd,` +> — `dist/core/agent-session-services.js:131` + +- **Events that let the extension notice:** + - `session_shutdown` on the **old** runtime, before the new one exists — `dist/core/agent-session-runtime.js:102-112` (`teardownCurrent` → `emitSessionShutdownEvent`), type at `dist/core/extensions/types.d.ts:637-643`. + - `session_start` on the **new** runtime, with the new cwd in `ctx` — `dist/core/agent-session.js:2680` (`await this._extensionRunner.emit(this._sessionStartEvent);`). + - `session_before_switch` on the **old** runtime (so its `ctx.cwd` is the *old* cwd) — `dist/core/agent-session-runtime.js:78-90` (emitted via `this.session.extensionRunner`). + - `project_trust` can fire **again** when the replacement enters a different working directory — `docs/extensions.md:145` ("`project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory"), implemented by resolving trust per cwd in `dist/main.js:590-635` (per-cwd cache `projectTrustByCwd`). + + The documented lifecycle confirms the shape: + +> `Switch["/new or /resume"] --> BeforeSwitch["session_before_switch"] ... Shutdown["session_shutdown"] --> Replacement["load replacement extension runtime"] --> SessionStart` +> — `docs/extensions.md:130-141` + +**Answer:** `ctx.cwd` never changes in place. A cwd change implies a new session runtime, announced by `session_shutdown` (old) followed by `session_start` (new, carrying the new cwd); `project_trust` may re-fire for the new directory. + +## 3. What do `session_start`'s `reason` values imply for re-resolution? + +The type: + +> `reason: "startup" | "reload" | "new" | "resume" | "fork";` +> `/** Previously active session file. Present for "new", "resume", and "fork". */` +> — `dist/core/extensions/types.d.ts:575-580` + +| reason | emitted at | cwd source | can the project change? | +|---|---|---|---| +| `startup` | `dist/core/agent-session.js:199` (default), emitted at `:2680` | launch cwd `dist/main.js:467` | No (first session of the process). | +| `reload` | `dist/core/agent-session.js:3028` (after `_buildRuntime`, same `AgentSession`, same `this._cwd`) | unchanged | **No.** `/reload` rebuilds the extension runtime in place; `this._cwd` is untouched (`dist/core/agent-session.js:2999-3028`). | +| `new` | `dist/core/agent-session-runtime.js:147-166` | `cwd: this.cwd` (`:162`) | **No.** `/new` keeps the current cwd. | +| `resume` | `dist/core/agent-session-runtime.js:128-142` | `cwd: sessionManager.getCwd()` (`:138`) — the resumed session's own cwd | **Yes.** This is the only in-process path that moves the session to another project directory. | +| `fork` | `dist/core/agent-session-runtime.js:211`, `:229`, `:246` | `cwd: this.cwd` (`:208`, `:243`) and `cwd: sessionManager.getCwd()` (`:226`) where `sessionManager = SessionManager.open(currentSessionFile, ...)` (`:224`) — the *current* session's header | **No** in practice: a fork branches the current session, whose header cwd is the current cwd. | + +Session import (`/import`) uses the `resume` path and therefore the `resume` semantics: + +> `sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },` +> — `dist/core/agent-session-runtime.js:291`, with `cwd: sessionManager.getCwd()` at `:288` + +**Answer:** only `resume` (which includes JSONL import) can change the project. `startup`, `reload`, `new`, and `fork` cannot. `previousSessionFile` is present for `new`, `resume`, and `fork` (`dist/core/extensions/types.d.ts:579`), so it is not a reliable "project changed" signal by itself — `new` also carries it. + +## 4. Does a `before_agent_start` context always carry the *current* cwd? + +**It carries the cwd of the current session runtime, which is captured when that runtime was created — i.e. the same value `session_start` reported for this session, and it cannot change during the session.** + +`before_agent_start` handlers receive the standard `ExtensionContext` (`dist/core/extensions/types.d.ts:1207` → `ExtensionHandler`; event type at `dist/core/extensions/types.d.ts:718-741`). The context's `cwd` is the runner getter: + +> `get cwd() { runner.assertActive(); return runner.cwd; }` +> — `dist/core/extensions/runner.js:630-633` + +The runner is built with the session's `_cwd` (`dist/core/agent-session.js:2983`), which was assigned once at construction (`dist/core/agent-session.js:182`). On `/reload` the runner is rebuilt from the *same* `_cwd` (`_buildRuntime` at `dist/core/agent-session.js:2999`, `:2983`). + +So `before_agent_start`'s `ctx.cwd` is "current" in the sense of *this session's* cwd, and identical to the `session_start` `ctx.cwd` for that session — it is **not** re-read from the process or the filesystem at handler time. + +**Answer:** it is a session-start capture, stable for the session, and only a new session runtime (`session_start` with `reason: "resume"`) changes it. + +## 5. Is the extension re-instantiated per project, and do project-local extensions change that? + +**Yes, on both counts.** + +- **Per project (different launch directory).** A different directory means a different process, so the factory runs again with that directory's cwd. Extension discovery is cwd-relative: + +> `// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/` +> `const localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, "extensions");` +> — `dist/core/extensions/loader.js:680-682` (entry point `discoverAndLoadExtensions(configuredPaths, cwd, ...)` at `dist/core/extensions/loader.js:666`) + + A user-level extension (e.g. `~/.pi/agent/extensions/memory.ts`) is loaded in every project; a project-local extension in `/.pi/extensions/` exists only for that project. + +- **Per session replacement inside one process.** The whole cwd-bound stack is rebuilt: + +> `* These services are recreated whenever the effective session cwd changes.` +> — `dist/core/agent-session-services.d.ts:20-24` + +> `Each operation replaces the active `AgentSession` and recreates services for the target working directory.` +> — `docs/sdk.md:58` + + Concretely, the resource loader is reloaded (`dist/core/agent-session-services.js:63-71` creates `DefaultResourceLoader` with the cwd; `dist/core/resource-loader.js:356-366` reloads it), the extension module cache is dropped (`clearExtensionCache()`, `dist/core/extensions/loader.js:92-96`; and `useExtensionCacheCwd` invalidates it whenever the cwd differs, `dist/core/extensions/loader.js:97-104`), and the extension file is re-imported with `jiti` configured with `moduleCache: false` (`dist/core/extensions/loader.js:472-487`). The factory is then invoked again (`await factory(load.api);`, `dist/core/extensions/loader.js:517`). + + **Practical consequence:** module-level state in a pi-memory extension does **not** survive a session replacement — the module is re-evaluated and the factory re-runs. Any scope resolution cached at module level must be re-computed on `session_start`. + +- **Project-local extensions.** They are loaded only for their own project, and only when the project is trusted: + +> `if (projectTrusted) {` +> ` // Project extensions from .pi/` +> ` addResources("extensions", collectAutoExtensionEntries(projectDirs.extensions), projectMetadata, projectOverrides.extensions, projectBaseDir);` +> — `dist/core/package-manager.js:2034-2038` + + (the project dir is `/extensions`, `dist/core/package-manager.js:2017-2019`, where `projectBaseDir` is `/.pi`). + +**Answer:** yes. The extension is instantiated once per runtime, and a runtime is created per effective cwd; project-local extensions simply narrow this to "only for that project, and only when trusted". + +## 6. Does the project trust gate affect extension behaviour when reading a project-local config file? + +**The trust gate governs what *pi* loads from a project directory. It does not restrict what an *extension* can read.** + +Protected resources (require a trust decision): + +> - `.pi/settings.json` +> - `.pi/mcp.json` +> - `.pi/extensions`, `.pi/skills`, `.pi/prompts`, or `.pi/themes` +> - `.pi/SYSTEM.md` or `.pi/APPEND_SYSTEM.md` +> - project `.agents/skills` in the current directory or an ancestor directory +> — `docs/security.md:37-45` + +Enforcement in source: + +> `static loadFromStorage(storage, scope, projectTrusted = true) { if (scope === "project" && !projectTrusted) { return {}; } ... }` +> — `dist/core/settings-manager.js:257-260` + +> `if (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) { ... }` (×2, for `.pi/SYSTEM.md` and `.pi/APPEND_SYSTEM.md`) +> — `dist/core/resource-loader.js:946`, `:957` + +> `if (projectTrusted) { // Project extensions from .pi/ ... }` +> — `dist/core/package-manager.js:2034-2038` + +Explicitly *not* a sandbox: + +> `Project trust does not limit what tool calls can access or affect. After Pi starts, enabled tools still use the operating-system permissions of the Pi process.` +> — `docs/security.md:33` + +> `An extension runs inside the Pi process with the same operating-system permissions. It can inspect prompts, tool calls, files, credentials, and session history, so load extensions only from sources you trust.` +> — `docs/extensions.md:7` + +Also relevant: only user-level and command-line extensions can answer the `project_trust` event (it runs *before* project extensions load), so a project-local extension cannot influence its own project's trust decision: + +> `Only personal and explicit command-line extensions can participate in the `project_trust` event that runs before project extensions load.` +> — `docs/extensions.md:50` + +**Answer:** trust does not stop pi-memory from *reading* a project-local config file (no sandbox), but it does mean that (a) project-scoped pi settings (`/.pi/settings.json`) are empty when trust is declined, so a config read through pi's settings API would be missing, and (b) a pi-memory-owned config file in an untrusted project is still readable, and its contents should be treated as untrusted input (`docs/security.md:5`, `:57`). If pi-memory needs the trust state, it can read `ctx.isProjectTrusted()` (`dist/core/extensions/types.d.ts:236-237`, wired at `dist/core/extensions/runner.js:658-661`) and can handle the `project_trust` event itself (`dist/core/extensions/types.d.ts:535-551`). + +--- + +## Conclusion — where pi-memory must hook, and when it must re-resolve + +pi-memory must resolve its scope **inside a `session_start` handler, from `ctx.cwd`** — never at module import, never from `process.cwd()`, and never from `pi.exec`'s implicit default cwd, because the extension factory receives no cwd (`types.d.ts:1518`) and `process.cwd()` is the launch directory, which differs from the session cwd whenever a session recorded elsewhere is resumed (`main.js:467` vs `session-manager.js:1344`). `session_start` is the one event that fires on **every** runtime — startup, `/reload`, `/new`, `/resume`, `/fork` — and it always runs against the runtime that owns the current cwd (`agent-session.js:2680`, runner cwd at `agent-session.js:2983`), so `ctx.cwd` there is the authoritative session cwd. Because the extension factory is re-invoked and the module re-evaluated on every runtime replacement (`resource-loader.js:356-366`, `loader.js:92-104`, `:472-487`, `:517`), scope resolution must be re-done from scratch on each `session_start` rather than cached at module level. The only reason that can change the *project* is `session_start` with `reason: "resume"` (including JSONL import, `agent-session-runtime.js:137-142`, `:287-292`); `startup`, `reload`, `new`, and `fork` keep the same cwd, so a conservative implementation may re-resolve on every `session_start` and only *rebuild* project-scoped state (qmd collections, injected context) when the resolved cwd or the scope set actually differs from the previous one. `session_shutdown` (`types.d.ts:637`) is the correct place to release session-bound resources such as qmd handles or caches, and `session_before_switch` (`types.d.ts:589`) sees the **old** cwd, so it must not be used as the source of the new scope. Finally, if pi-memory reads a project-local config file, it must read it directly from disk (trust does not sandbox extension reads, `docs/security.md:33`) and must treat its contents as untrusted input when the project is not trusted (`ctx.isProjectTrusted()`, `types.d.ts:237`); project-scoped *pi settings* (`/.pi/settings.json`) are simply unavailable in that state (`settings-manager.js:257-260`). diff --git a/docs/spec/appendix-qmd-scope-layout-spike.md b/docs/spec/appendix-qmd-scope-layout-spike.md new file mode 100644 index 0000000..647ac73 --- /dev/null +++ b/docs/spec/appendix-qmd-scope-layout-spike.md @@ -0,0 +1,110 @@ +# Spike: sibling layout + one qmd collection per scope (2026-10-28) + +Throwaway spike for [issue #7](https://github.com/fktpp2022/pi-memory/issues/7). Real `qmd` CLI (2.8.3, `facd35e`), real user-level qmd config, real embedding model (`embeddinggemma-300M-Q8_0.gguf` already local). Everything ran under `~/pi-memory-spike/`, outside the repo. Spike collections were removed afterwards. + +## The script + +```bash +S=~/pi-memory-spike; rm -rf $S +mkdir -p $S/global/daily $S/projects/alpha/daily $S/projects/beta/daily $S/projects/gamma/daily + +printf '# Global memory\n\n- globalfact: the lighthouse keeper prefers herbal tea\n' > $S/global/MEMORY.md +printf '# 2026-10-28\n\n- globaldailyentry: harbour lights rotate at dusk\n' > $S/global/daily/2026-10-28.md +printf '# Project alpha memory\n\n- alphafact: alpha keeps its lighthouse log in the attic\n' > $S/projects/alpha/MEMORY.md +printf '# 2026-10-28\n\n- alphadailyentry: alpha inspected the north tower\n' > $S/projects/alpha/daily/2026-10-28.md +printf '# Project beta memory\n\n- betafact: beta replaces its beacon bulb every spring\n' > $S/projects/beta/MEMORY.md +printf '# 2026-10-28\n\n- betadailyentry: beta repainted the boathouse\n' > $S/projects/beta/daily/2026-10-28.md +printf '# Project gamma memory\n\n- gammafact: gamma counts the foghorn blasts each evening\n' > $S/projects/gamma/MEMORY.md +for i in 1 2 3 4 5 6 7; do + printf '# 2026-10-28\n\n- gammaentry%s: gamma log line about the harbour%s\n' $i $i > $S/projects/gamma/daily/2026-10-2$i.md +done + +qmd collection add $S/global --name spike-global +qmd collection add $S/projects/alpha --name spike-alpha +qmd collection add $S/projects/beta --name spike-beta +qmd collection add $S/projects/gamma --name spike-gamma +``` + +## 1–2. Sibling directories, one collection each + +``` +$ qmd collection list +Collections (4): + +pi-memory (qmd://pi-memory/) Files: 1 +spike-global (qmd://spike-global/) Files: 2 +spike-alpha (qmd://spike-alpha/) Files: 2 +spike-beta (qmd://spike-beta/) Files: 2 +spike-gamma (qmd://spike-gamma/) Files: 8 + +$ qmd collection show spike-alpha +Collection: spike-alpha + Path: C:\Users\Lenovo\pi-memory-spike\projects\alpha + Pattern: **/*.md + Include: yes (default) + +$ qmd ls spike-alpha +81 B qmd://spike-alpha/MEMORY.md +65 B qmd://spike-alpha/daily/2026-10-28.md +``` + +No file appears under two collections. Siblings do **not** double-index: each collection owns exactly its own subtree (`global/` is not a parent of `projects/`). + +## 3–4. Isolation and union + +``` +$ qmd search -c spike-alpha "lighthouse" → qmd://spike-alpha/MEMORY.md +$ qmd search -c spike-global "lighthouse" → qmd://spike-global/MEMORY.md +$ qmd search -c spike-beta "lighthouse" → [] (alpha's fact does not leak) +$ qmd search -c spike-alpha "beacon" → [] (beta's fact does not leak) +$ qmd search -c spike-beta "beacon" → qmd://spike-beta/MEMORY.md +$ qmd vsearch -c spike-alpha "lighthouse attic" → qmd://spike-alpha/MEMORY.md +$ qmd vsearch -c spike-beta "lighthouse attic" → [] (vector path isolates too) +``` + +## 5. `update` and `embed` cover every collection + +``` +$ qmd update # no -c +[4/5] spike-beta (**/*.md) Indexed: 0 new, 0 updated, 2 unchanged, 0 removed +[5/5] spike-gamma (**/*.md) Indexed: 0 new, 0 updated, 8 unchanged, 0 removed +✓ All collections updated. + +$ qmd embed # no -c +Model: C:/Users/Lenovo/qmd-models/embeddinggemma-300M-Q8_0.gguf +✓ Done! Embedded 14 chunks from 14 documents in 17s +``` + +One `qmd update` and one `qmd embed` cover every scope — no per-scope loop needed. + +## 6. `-n` is applied globally, after the merge + +With `gamma` matching 8 documents and `alpha` matching none: + +``` +$ qmd search -c spike-alpha -c spike-gamma "gamma" -n 5 → 5 results, all from spike-gamma +$ qmd search -c spike-alpha -c spike-gamma "gamma" -n 3 → 3 results, all from spike-gamma +``` + +Results are **not interleaved per collection**: the limit is global, and one collection can take every slot. A scope set searched as one union can therefore be starved by one noisy scope. + +## 7. `qmd context add` needs the `qmd://collection/path` form + +``` +$ qmd context add "qmd://spike-alpha/MEMORY.md" "Alpha project scope memory file" +✓ Added context for: qmd://spike-alpha/MEMORY.md + +$ qmd context list +spike-alpha + MEMORY.md + Alpha project scope memory file +``` + +There is no `-c` flag; the collection is part of the path, and the context lands under the right collection. + +## Other observations + +- **Collection names are global.** qmd collections live in the user-level config, not per project. Two projects with the same basename would collide on collection name — the uniqueness hash in collection names (already a map decision) is *required*, not cosmetic. +- `qmd search -c nope "x"` → `Collection not found: nope` (a clean, catchable error). +- After adding and removing collections, `qmd update` warned `15 orphaned embedding chunks (83% of vectors) — run 'qmd cleanup' to reclaim space`. Scopes that come and go will leak embedding chunks until `qmd cleanup` runs. +- `qmd ls` and `qmd collection list` give per-collection file counts — enough for `memory_status` without opening the files. diff --git a/docs/spec/project-scoped-memory.md b/docs/spec/project-scoped-memory.md new file mode 100644 index 0000000..e784920 --- /dev/null +++ b/docs/spec/project-scoped-memory.md @@ -0,0 +1,493 @@ +# Project-scoped and global memory + +**Status:** proposed. A design under discussion, not a frozen contract. Source: the decision tracker map ([fktpp2022/pi-memory#1](https://github.com/fktpp2022/pi-memory/issues/1)), whose tickets #2–#11 this document assembles. Targeted at [jayzeng/pi-memory](https://github.com/jayzeng/pi-memory). + +**One-line summary:** a session's memory is the union of one *own scope* (derived from the project it runs in), zero or more *extra scopes* the user configures, and — last, opt-in — the `global` scope; each scope is a sibling directory on disk, one qmd collection per scope, and a single one-time migration moves today's flat memory into that layout. + +| Chapter | Decides | From | +|---|---|---| +| [1. Scope model](#1-scope-model) | ids, own scope, ambiguity, display form | [#2](https://github.com/fktpp2022/pi-memory/issues/2) | +| [2. Storage layout](#2-storage-layout) | `global/` + `projects/-`, hash rule | [#2](https://github.com/fktpp2022/pi-memory/issues/2) [#6](https://github.com/fktpp2022/pi-memory/issues/6) | +| [3. Configuration surface](#3-configuration-surface) | config file, env var, command, precedence | [#2](https://github.com/fktpp2022/pi-memory/issues/2) | +| [4. Tool surface](#4-tool-surface) | scope params on the seven tools, error shapes | [#3](https://github.com/fktpp2022/pi-memory/issues/3) | +| [5. Injected context](#5-injected-context) | per-scope blocks, budget, search merge, snapshot | [#5](https://github.com/fktpp2022/pi-memory/issues/5) | +| [6. qmd collection lifecycle](#6-qmd-collection-lifecycle) | naming, discovery, creation, re-point, pruning | [#4](https://github.com/fktpp2022/pi-memory/issues/4) | +| [7. The migration command](#7-the-migration-command) | plan/apply/undo, exit codes, idempotency | [#6](https://github.com/fktpp2022/pi-memory/issues/6) | +| [8. Retiring the memory-scope extension](#8-retiring-the-memory-scope-extension) | rename-don't-delete, PI_MEMORY_DIR warning | [#9](https://github.com/fktpp2022/pi-memory/issues/9) | +| [9. Test plan](#9-test-plan) | what proves what, isolation proof, case matrix | [#10](https://github.com/fktpp2022/pi-memory/issues/10) | +| [10. Appendix](#10-appendix) | qmd facts, corrections log, omissions, open questions | all | + +--- + +# 1. Scope model + +A **scope** is a unit of memory: one `MEMORY.md`, one `daily/` tree, one scratchpad, one qmd collection. A session sees a **scope set**: the union of an *own scope* and zero or more *extra scopes*. + +**Scope id grammar (one grammar, everywhere):** + +``` +global | project: | project:# +``` + +- `global` — the global scope. A full scope like any other: its own `MEMORY.md`, `daily/` and scratchpad. It is **opt-in per session** — never auto-included. +- `project:` — a project scope. `` is the basename of the project root, lowercased, restricted to `[a-z0-9._-]`, overridable by the config file's `project` key. +- `project:#` — the same scope with its uniqueness hash made explicit. The hash suffix is **optional in references only**; it exists to disambiguate (below). + +**Own scope (always, implicitly, never excludable).** A session's own scope is `project:` where the slug comes from the project root. Writes land in the session's own project identity, so a scope set that excluded the own scope would mean writing to a scope you cannot read. Every configuration layer therefore supplies only *extra* scopes. + +**Outside any repo** there is no project scope: the own scope is `global`, extras are empty, and there is no project config file. + +**Display form is always the bare id.** Tool parameters, injected-context headings, status output and messages all use `project:chezmoi`, never the hash. One form to copy-paste; the hash appears only in directory names, collection names, diagnostics, and the `#` reference form. + +**Ambiguity is an error, never a silent pick.** A bare `project:` that matches more than one project (same basename, different roots) is rejected: the message lists the candidate directories, each carrying its hash, and suggests the `project:#` form. Bare references work fine whenever the basename is unique, which is the common case. + +**Scope identity is path-bound.** Moving or renaming a repo changes its scope id and its collection name. Accepted: the absolute path is predictable; a remote URL is not an identity (absent, forked, mirrored). The escape hatch is the `project` key in `.pi/memory.json` (chapter 3), which sets the slug explicitly. + +**Scope resolution happens in `session_start` from `ctx.cwd`** — never at import and never from `process.cwd()` (which is the launch dir, not the session dir). `ctx.cwd` is a snapshot refreshed only by a runtime replacement (`/resume` of a session recorded elsewhere), which re-runs the factory and re-evaluates module state anyway. Re-resolve on every `session_start`; rebuild project-scoped state (qmd collections, injected context) only when the resolved cwd or scope set actually changes; release session-bound resources in `session_shutdown`. Evidence: [docs/research/pi-cwd-and-session-lifecycle.md](../research/pi-cwd-and-session-lifecycle.md) (fork only) and appendix A. + +--- + +# 2. Storage layout + +The memory root is `~/.pi/agent/memory` (overridable by `PI_MEMORY_DIR`, chapter 8) holding exactly two categories of child: + +``` +~/.pi/agent/memory/ + global/ ← the global scope + MEMORY.md + SCRATCHPAD.md + daily/YYYY-MM-DD.md + recovery/ + .migration-manifest.json + projects/ + -/ ← one directory per project scope + MEMORY.md + SCRATCHPAD.md + daily/ + recovery/ +``` + +- `global/` and `projects/` are **siblings**, never nested: a collection over `~/.pi/agent/memory` would double-index everything in `projects/` (verified, appendix A). +- The directory name is `-`; the display id never carries the hash. **The hash is the first 8 hex characters of `sha1` over the lowercased, forward-slash-normalised absolute project path.** Lowercasing and slash-normalisation mean different spellings of the same path on one machine agree. +- The four directories the memory-scope extension already created (`chezmoi-d24458d5`, `gkd-cc779eb9`, `Lenovo-94672f7c`, `pi-memory-fd22b830`) are **already compliant** under this rule — adopted as-is, no rename. See [Corrections](#corrections). +- `PI_MEMORY_DIR` is the memory **root**, not a scope directory: pointing it at a directory containing `MEMORY.md` directly is a warned misconfiguration (chapter 8). + +**Filenames and contents are unchanged from pi-memory today** — `MEMORY.md`, `SCRATCHPAD.md`, `daily/YYYY-MM-DD.md`, `recovery/`, `#tags` and `[[links]]` in the files. Scoping is a layout change, not a format change. + +--- + +# 3. Configuration surface + +The surface by which a session's scope set is configured. One grammar (chapter 1), four layers, strict precedence. + +## 3.1 Config file: `.pi/memory.json` + +Location: `/.pi/memory.json`, where **project-root** = the git root if the session is inside a repo, otherwise the session's cwd. Read only for trusted projects (pi loads project resources after trust); an untrusted project contributes no config. Skipping the file (missing, unreadable, malformed JSON) is silent — the session falls back to defaults. + +Both keys optional; unknown keys ignored with a warning: + +```json +{ + "project": "chezmoi", + "scopes": ["global", "project:dotfiles"] +} +``` + +- `project` — overrides the slug of the session's own project scope. Default: basename of project-root. +- `scopes` — the extra scope ids beyond the session's own scope. + +## 3.2 Env var: `PI_MEMORY_SCOPES` + +Comma-separated extra scope ids: `PI_MEMORY_SCOPES=global,project:dotfiles`. Entries are trimmed, de-duplicated (first wins), order preserved. Colon is not a separator, so `project:x` needs no escaping; scope ids cannot contain commas (charset `[a-z0-9._-]`), so **no escaping rule exists at all**. + +An unknown env id is an error naming the offending id and listing the scopes that exist; the env layer is then **ignored entirely** (extras = empty, session continues with its own project scope only). + +## 3.3 Command: `/memory` + +One registered command (`pi`'s `registerCommand` takes a single name, so verbs are parsed from the argument string): + +| Invocation | Effect | +|---|---| +| `/memory` | Print: the active set (own scope marked), which layer won, and the config file in play. | +| `/memory scope` | Reset the extras to the next layer down (config, else default). | +| `/memory scope …` | Set the extras for this session, replacing any previous value. | +| `/memory migrate …` | The migration command (chapter 7) — same verb namespace. | + +Example print: + +``` +Scopes: project:chezmoi (own), global +Source: command +Config: /home/me/src/chezmoi/.pi/memory.json +``` + +`/memory scope` is **session-only**: the command layer is not persisted, and `.pi/memory.json` is the durable record. An invalid id is an error naming the unknown id and listing the scopes that exist; the set is left unchanged and the session continues with its previous set. Argument completion offers the scope ids that exist, so the user never types a hash unless disambiguating. + +## 3.4 Precedence + +**command > env var > project config > default.** Each layer supplies the extra-scope list; the first layer that is *present* wins — a layer is present if it supplied a value, **even an empty list** (an explicitly empty list clears the extras). + +The default layer: extras = empty. `global` is never auto-included; it is opt-in, in any layer. + +--- + +# 4. Tool surface + +Seven tools (the ticket said six — `scratchpad` is a tool like the rest and is scoped with the others). **No existing parameter is renamed**; only two new optional parameters appear. + +| Tool | Scope parameter | Default | On a bad scope id | +|---|---|---|---| +| `memory_write` | `scope` (string, optional) | the session's own scope | id outside `{own, global}` → "not writable"; unknown id → error listing valid ids | +| `scratchpad` | `scope` (string, optional) | own scope | same as `memory_write` | +| `memory_forget` | `scope` (string, optional) | own scope | same as `memory_write` | +| `memory_restore` | **none** | — | n/a; the recovery id identifies the record, and the record knows its scope | +| `memory_read` | `scopes` (string array, optional) | the whole active set | unknown id → error listing the known ids and the active set; an existing out-of-set id is allowed (widening) | +| `memory_search` | `scopes` (string array, optional) | whole active set | same as `memory_read` | +| `memory_status` | **none** | — | n/a | + +Existing parameters untouched (`target`, `mode`, `date`, `query`, `limit`, `action`, `text`). + +## 4.1 The write-side rule + +`memory_write`, `scratchpad` and `memory_forget` accept **only** the session's own scope and `global`. Anything else is an error, even if the scope exists on disk. Writes land in the session's own project identity; `global` is the one documented exception. + +## 4.2 The read-side rule + +`memory_read` and `memory_search` default to the whole active set (own scope plus the configured extras) and may **widen**: a scope that exists on disk but isn't active can be read explicitly. Reads spanning several scopes return results **grouped per scope**, each group headed by the scope's display form, so the agent can tell which project a fact came from. + +## 4.3 Error message shape + +One line, naming the offending id and the alternatives: + +``` +unknown scope id "project:chezmoi"; known scopes: global, project:dotfiles (active: global, project:chezmoi) +``` + +Two distinct failures, two distinct messages: + +- **Unknown id** (no such scope on disk) → "unknown scope id …". +- **Existing but not writable** → `scope 'project:other' is not writable; writes target your own scope or global`. + +## 4.4 No auto-creation, anywhere + +A scope id naming a scope that doesn't exist is **never** auto-created — not the directory, not the qmd collection. A typo must not leave a permanent junk scope behind (this is the failure mode that silently corrupts a user's memory, and it is tested: chapter 9). + +--- + +# 5. Injected context + +## 5.1 The shape + +The injected block for the active scope set — own scope first, then the extra project scopes **in the order the set lists them**, then `global` last, always: + +``` +# Memory + +## Scope: project:chezmoi + +### SCRATCHPAD.md (working context) +- [ ] open item + +### Daily log: 2026-10-28 (today) +… + +### MEMORY.md (long-term) +… + +### Daily log: 2026-10-27 (yesterday) +… + +--- + +## Scope: global + +### MEMORY.md (long-term) +… + +--- + +## Relevant memories (auto-retrieved) + +[project:chezmoi] …the attic lighthouse log… +[global] …the lighthouse keeper prefers herbal tea… +``` + +- Each scope is one `## Scope: ` block containing **its own** files as `###` sub-sections. The heading is the literal display form — the same string the tool parameters accept. No "(own)" marker: position (first) says which scope is yours. +- Within a scope, the order is fixed: **scratchpad → today's daily → MEMORY.md → yesterday's daily**. (The auto-retrieved results used to sit between today's log and `MEMORY.md`; they are cross-scope now, so they leave the scope block.) +- A scope with no content contributes **no block at all** — no empty heading. +- Scope blocks are separated by `---`, and the search section is separated the same way. The `# Memory` preamble and its how-to-use lines are unchanged. + +## 5.2 The auto-retrieved search section + +One shared section after all scope blocks; hits prefixed with their scope id (`[project:chezmoi]`). + +Searching runs **per scope**, then merges: the pool is all hits from all scope searches, each tagged with its scope, merged **round-robin over the scopes in set order**, each scope contributing its next-best hit in turn, until the overall limit is reached. Every active scope's best hit lands in the first pass (as long as there are slots); each scope's internal order stays score-ranked. When there are more scopes than slots, the earliest scopes in set order take them. + +The round-robin is **load-bearing**, not cosmetic: a single union search applies its limit globally after the merge, and one noisy scope can take every slot (verified, appendix A, §3.6). + +In `stable` snapshot mode the section is absent, exactly as today (the snapshot is taken without search results); it appears in `per-turn` mode. + +## 5.3 Token budget + +Total budget stays `CONTEXT_MAX_CHARS` = 16 000 chars. + +1. The search section reserves its existing cap (2 500 chars). +2. The remainder is split **equally among the scopes**: `floor((16000 − searchReserve) / N)`. +3. If the search section comes back empty, its unused share is redistributed equally to the scopes. +4. Inside a scope the existing per-section caps still apply (scratchpad 2 000 / 120 lines, daily 3 000 / 120, long-term 4 000 / 150). A scope exceeding its share is truncated **from the lowest-priority end** — yesterday's daily first, then `MEMORY.md`, then today's daily, the scratchpad last (working context is the most valuable). +5. A truncated scope says so: `[truncated: showing X/Y chars of scope project:chezmoi]`. The existing overall-truncation note stays as the outermost guard. + +No scope is ever dropped: the equal share guarantees every scope in the set is present, and truncation is visible rather than silent. + +## 5.4 Snapshot behaviour + +**A scope-set change mid-session (`/memory scope`) invalidates and refreshes the frozen `stable` snapshot**, with reason `scope_change` — the same path as a long-term write. The agent must not keep reading a snapshot describing scopes it can no longer see. The refresh costs the prefix cache once, on an event the user explicitly caused. In `per-turn` mode the next turn simply uses the new set; in `refresh` mode a scope change counts as a stale event alongside `long_term_write` and `day_rollover`. + +--- + +# 6. qmd collection lifecycle + +## 6.1 Naming + +One pure function computes the collection name from the scope: + +| Scope | Collection name | Collection path | +|---|---|---| +| `global` | `pi-memory` | `/global` | +| `project:` | `-` | `/projects/-` | + +The hash is chapter 2's, so two projects sharing a basename never collide. qmd collection names are **global** in the user's config (not per project), which makes the hash load-bearing. The global collection keeps the name `pi-memory` — its directory is `global/`, so the name is the one deliberate exception to "name == directory basename". **No mapping file is stored**: the rule is the whole mapping, and a collection's path must equal the scope's directory. Collections the user created for their own purposes are never touched — pi-memory manages only the collections its own rule produces. + +## 6.2 Discovery + +`qmd collection list --json` **ignores `--json`** in qmd 2.8.3 (it prints human text), so JSON parsing always fails. The reliable read is **`qmd collection show `**, which prints the collection's `Path:` (and `Collection not found: ` when absent). Compare that path against the scope's directory: not found → create; matches → nothing to do; differs → re-point. + +## 6.3 Creation + +- At session start, for every scope in the active set **whose directory exists**. +- Lazily the first time a scope is used: a write to `global`, or a mid-session widening of the set. +- **Order matters: create the directory first, then the collection** — `qmd collection add` on a nonexistent path fails. A scope with no directory gets no collection, and `memory_status` reports "no directory"; an empty collection is noise in the user's `qmd collection list`. + +## 6.4 Re-pointing + +`qmd collection add` refuses an existing name, so a re-point is: + +``` +qmd collection remove +qmd collection add --name +qmd context add "qmd:///daily" "Daily append-only work logs organized by date" +qmd context add "qmd:///" "Curated long-term memory: decisions, preferences, facts, lessons" +``` + +**Removing a collection deletes its contexts** (verified), so the contexts are re-added in the same operation. Every scope collection gets the same two contexts, added at creation — contexts are per-collection, so project collections need their own. Note the path form: there is **no `-c` flag**; the collection is part of the `qmd://` path (this is the fix for an existing call in `index.ts` today that passes `-c pi-memory` and has never worked — appendix B). + +**The migration owns the global re-point**, at chapter 7's step. Not now: the legacy `pi-memory` collection points at ``, whose `**/*.md` covers `global/` and `projects/*` alike; re-pointing it before the files move would point the index at an empty directory and make the user's memory vanish from search. A collection whose path differs for any other reason (the user moved a scope directory) is re-pointed the same way, at the next session start. + +## 6.5 Pruning: never automatic + +- pi-memory **never deletes a collection on its own** — removing an index can delete the only copy of memory the user hasn't migrated. +- `memory_status` reports **orphan collections** (name, path, "scope directory missing") and gives the user the command to remove them. +- After a removal, `qmd cleanup` reclaims the orphaned embedding chunks (the spike saw 83% of vectors orphaned). pi-memory **never runs `qmd cleanup` itself**: it is a global, user-level operation touching every collection the user has. `memory_status` reports when chunks are orphaned and prints the command. + +`memory_status` gains two sections: per-scope collection state (exists / path / file count — `qmd ls` gives counts without opening files) and orphan collections with the orphan-chunk warning. + +--- + +# 7. The migration command + +A one-time migration from today's flat layout to chapter 2's. **Dry run is the default** — this is the only destructive operation in the feature, and the printed plan doubles as the bug report. + +| Command | Effect | +|---|---| +| `/memory migrate` | **Plans.** Prints the plan, changes nothing. Exit 0. | +| `/memory migrate --apply` | Executes the plan. | +| `/memory migrate --undo` | Plans the undo of a completed migration (prints, changes nothing). | +| `/memory migrate --undo --apply` | Executes the undo. | + +## 7.1 Preconditions + +1. **The memory-scope extension must be gone.** If `~/.pi/agent/extensions/memory-scope.ts` exists, the command **refuses** (exit 2) and says: rename that file, then run `/reload`. It re-points the `pi-memory` collection at the current project dir at module load, so it would immediately undo the migration's re-point. +2. qmd is optional: if the binary is unavailable, the file moves still happen, the qmd steps are reported as skipped, and the collections are created by the next session start. + +## 7.2 What moves + +Source: the legacy top level of ``. Target: `/global/`. An entry moves **iff** it exists at the source and not at the target: `MEMORY.md`, `SCRATCHPAD.md`, `daily/`, `recovery/` (renames, atomic within the same tree; `EXDEV` falls back to copy → verify → delete; **no backup copy** — the moves are renames and the manifest makes them reversible). + +Everything else at the legacy top level is **unrecognised**: it stays where it is and is reported in the plan (`keep notes.txt (unrecognised, left in place)`). It will not be indexed by any collection — a visible, reported gap rather than silent loss. + +`projects//` is **adopted as-is**: nothing moves, nothing is renamed. Under chapter 2's hash rule the existing names are already the right ones. + +## 7.3 The qmd operations + +Run **after** the file moves, so the global collection points at a populated directory: + +1. `qmd collection remove pi-memory` (if present) — drops its documents and its contexts; the legacy documents are re-indexed under the new layout. +2. `qmd collection add /global --name pi-memory` +3. The two contexts from §6.4 on `pi-memory`. +4. For every `projects/`: `qmd collection add --name ` (if absent) + the same two contexts. +5. `qmd update` once (`update` and `embed` with no `-c` cover **every** collection — verified, appendix A §A.4; no per-scope loop needed). +6. Report that the old vectors are now orphaned and that `qmd cleanup` reclaims them — never run automatically. + +## 7.4 The plan output + +``` +plan: + move MEMORY.md -> global/MEMORY.md (2.1 KB) + move daily/ -> global/daily/ (3 files) + move recovery/ -> global/recovery/ (0 files) + keep notes.txt (unrecognised, left in place) + remove collection pi-memory (points at memory/) + add collection pi-memory -> memory/global/ + add collection gkd-cc779eb9 -> memory/projects/gkd-cc779eb9 + context pi-memory/daily, pi-memory/ + update qmd index +summary: 5 file operations, 3 collection operations, 0 changes made +``` + +One line per action, then a summary. `--apply` executes exactly this list. + +## 7.5 Idempotency, partial runs, conflicts + +- Every file operation is decided **independently** — a crashed migration is completed by re-running it. +- An entry existing at **both** ends is a **conflict**: skipped, reported, the other operations still run, exit non-zero. One stray file must not block the migration. +- Re-running after success reports `already migrated: nothing to do`, exit 0. +- A failed rename: that entry is reported as failed, the rest continue, exit non-zero. +- qmd failures are reported; the file moves are **not** rolled back (the migration is re-runnable), exit non-zero. + +| Code | Meaning | +|---|---| +| 0 | plan printed, or applied with no conflicts | +| 1 | conflicts or failed operations (everything else still ran) | +| 2 | precondition refused (the memory-scope extension is still installed) | + +## 7.6 Undo + +The migration writes `/.migration-manifest.json`: + +```json +{ + "version": 1, + "timestamp": "…", + "moves": [{ "from": "MEMORY.md", "to": "global/MEMORY.md" }], + "collections": [{ "name": "pi-memory", "action": "repoint", "path": "…" }, + { "name": "gkd-cc779eb9", "action": "create", "path": "…" }], + "contexts": [{ "collection": "pi-memory", "path": "/daily" }] +} +``` + +`--undo` replays it in reverse: moves the files back, removes the collections the migration created, restores the legacy `pi-memory` collection pointing at the legacy directory, re-adds its contexts. Like the migration itself, `--undo` plans first and only `--undo --apply` acts. + +--- + +# 8. Retiring the memory-scope extension + +Users who want per-project isolation today run a small extension at `~/.pi/agent/extensions/memory-scope.ts` that sets `PI_MEMORY_DIR` and re-points the `pi-memory` collection. Native scoping replaces it. + +## 8.1 When + +**At implementation time**, in the same change that ships native scoping — not before. Deleting it now would leave pi-memory with a single global directory and project facts leaking into each other for a feature that isn't written yet. + +## 8.2 The instruction + +1. **Rename** `memory-scope.ts` → `memory-scope.ts.disabled`. pi loads only direct `.ts`/`.js` files from the extensions directory, so the renamed file is inert. Renaming, not deleting: the artefact stays on disk, the change is reversible, the filename says what it was. +2. **Report it** at session start: the old path, the new path, one line saying per-project scoping now comes from pi-memory itself, and that `/reload` is needed for the running session to pick the change up. +3. **Leave the file to the user** to delete when satisfied. pi-memory never deletes files in the user's extensions directory. + +## 8.3 Compatibility: the derivation is preserved verbatim + +The native implementation keeps the extension's derivation exactly — `-<8 hex>`, sha1 of the lowercased, forward-slash-normalised absolute path. The four existing directories are adopted **without renaming**, and their scope ids and collection names follow unchanged. No user's project scope changes identity when the native feature replaces the extension. + +## 8.4 `PI_MEMORY_DIR`: honoured, but warned + +`PI_MEMORY_DIR` is resolved at import (`index.ts` today) and silently overrides everything downstream — that is the extension's whole trick, and anyone can do it by hand. In the new layout `PI_MEMORY_DIR` is the **memory root** (the directory holding `global/` and `projects/`), not a scope directory. Therefore: + +- **Warn once at session start** when `PI_MEMORY_DIR` is set and points somewhere other than the resolved memory root. If the target directory contains `MEMORY.md` directly — the shape of a scope directory, and exactly what the old extension did — the warning says: "this looks like a scope directory; `PI_MEMORY_DIR` now points at the memory root". +- **Show the same conflict** in `memory_status` and `/memory`, both of which already report where the scope came from. +- **Keep honouring it** as an explicit override. It is a warning, not an error: `PI_MEMORY_DIR` remains a legitimate escape hatch for "put my memory somewhere else". + +Consequence for the implementation: the memory directory is **per scope**, derived from the scope set, not one module-level `MEMORY_DIR` resolved at import; and nothing may set `PI_MEMORY_DIR` at import time — the extension did it precisely because that runs before pi-memory knows the cwd. + +--- + +# 9. Test plan + +## 9.1 Levels + +| Level | Proves | +|---|---| +| **unit** (`npm test` → `bun test test/unit.test.ts`, no key, no qmd) | pure logic: scope-id parsing, config/env resolution, precedence, the injected-layout builder, budget split, search merge, migration planning, the collection-name rule, the exact qmd argv sequences (mocked) | +| **e2e** (`npm run test:e2e`, `pi` as a subprocess) | only what needs a live pi, a real project dir and real qmd: the injected context in a real session, cross-project isolation, migration apply | + +Unit tests are the **assertions of record**: fast, keyless, able to assert *absence* deterministically. The context builder is directly drivable (`index.ts` exports `buildMemoryContext`), so the injected layout is unit-tested without a model. The e2e suite confirms the wiring. + +## 9.2 Fixtures + +Every scope test points the extension at a **temp memory root** (a temp directory, never `~/.pi/agent/memory`) and uses **two temp git repos** as the two projects — a git root is the default project identity — each with its own `.pi/memory.json`. Nothing is written into the user's real memory except by the user's own manual testing; the e2e's existing `backupFile`/`restoreFile` helpers stay in use for anything real. + +## 9.3 How isolation is proven + +Write a **unique marker token** into project A, then assert the token is **absent** from B's built context and from B's search output — on the builder's output and on qmd's raw JSON, **never** on model prose (models paraphrase and occasionally hallucinate; a marker token in raw output is deterministic). Exactly **one** API-backed e2e additionally asks the model in B for the token and asserts it doesn't answer it — a smoke test of the wiring, not the assertion of record. + +**Cases live in the existing files**: scope unit cases appended to `test/unit.test.ts`, scope e2e cases to `test/e2e.ts`. No new files, no package-script change (`npm test` names one file explicitly; the suites are organised by kind, not feature). API cost in CI stays at one new key-gated case; the suite skips it when no key is configured, as it already does. **Real qmd vs mocked qmd:** the lifecycle and migration are unit-tested against a mocked qmd asserting the exact argv sequence (§6.4) — the argv sequence is the contract, and asserting it needs no binary; one real-qmd e2e runs only when qmd is present; the migration-apply test always asserts the file moves and asserts the qmd steps only when qmd is available — **skipped, never failed**. One **guard test** asserts the resolved memory dir is under the temp root and fails loudly if it isn't. + +## 9.4 Case matrix + +| Area | Cases | +|---|---| +| Scope ids | `global`; `project:`; `project:#`; ambiguous bare slug → error | +| Configuration | config read; `project` override; extras list; untrusted project → ignored; env parsing (trim / de-dupe / order); unknown env id → error + extras ignored; precedence command > env > config > default, including "present but empty" clearing the extras | +| Tools | own scope always in the set; writes to own/`global` only; a write to another scope → error; reads widen to an existing out-of-set scope; unknown id → error **and no directory and no qmd collection created** | +| Injected context | one block per scope with the literal id heading; order own → extras → `global`; empty scope contributes no block; per-scope budget split; truncation drops lowest-priority first with a visible marker; scope-set change invalidates the snapshot (`scope_change`) | +| Search | one query per scope; round-robin merge in set order; each scope's best hit present; `[scope-id]` prefixes | +| qmd lifecycle | collection-name rule; missing → create (directory before collection); path differs → re-point (`collection remove`, `collection add`, two `context add`s); contexts in `qmd:///` form | +| Migration | planner's per-item decisions; conflict skipped and reported; unrecognised files kept; plan text; `--undo` manifest round-trip; refuses while the extension is installed | +| Warnings | `PI_MEMORY_DIR` pointing at a scope directory → warning | + +The two cases worth defending hardest: **"unknown id creates nothing"** and **"the migration refuses while the extension is installed"**, because both are the failure modes that silently corrupt a user's memory. + +## 9.5 Deliberate omission + +No case asserts the hash agreeing across Windows and POSIX. **Memory storage is never shared across platforms**, so the hash only has to be stable on the machine that created it; the derivation still lowercases and normalises separators, so different spellings of the same path on one machine agree. + +--- + +# 10. Appendix + +## A. qmd facts (verified against qmd 2.8.3, real embedding model) + +Full transcript: [appendix-qmd-scope-layout-spike.md](appendix-qmd-scope-layout-spike.md). + +- **Siblings do not double-index.** One collection per scope; each collection owns exactly its own subtree (`global/` is not a parent of `projects/`). +- **Isolation holds on both paths.** `qmd search -c spike-beta "lighthouse"` → `[]`, `qmd vsearch -c spike-beta "lighthouse attic"` → `[]`. +- **Union works** (`search -c a -c b`), **but results are not interleaved**: `-n` is global after the merge, and one noisy scope can take every slot (appendix A §A.6 of the spike). Hence §5.2's per-scope search + round-robin merge. +- **`qmd update` and `qmd embed` with no `-c` cover every collection** — one call each, no per-scope loop. +- **`qmd context add "qmd:///" "…"` works and attaches to the right collection**; there is no `-c` flag. +- **Collection names are global** (user-level config), so the uniqueness hash in collection names is required, not cosmetic. +- **`qmd collection list --json` ignores `--json`** in 2.8.3 — use `qmd collection show ` instead. +- **Removing a collection deletes its contexts**; orphaned embedding chunks persist until `qmd cleanup` (the spike saw 83% of vectors orphaned). +- `qmd search -c nope "x"` → `Collection not found: nope` — a clean, catchable error. + +## B. Corrections log + +Decisions made during the map that **supersede** an earlier statement: + +1. **Hash algorithm (#2 → #6).** The hash is the first 8 hex chars of **sha1** over the lowercased, forward-slash-normalised absolute project path — not "4 hex chars of sha256" as #2 first said. Reason: the four existing project directories were named by the memory-scope extension with exactly that algorithm, so adopting it lets them be reused untouched. +2. **`PI_MEMORY_DIR` semantics (#9 → #10).** It is the memory **root** (holding `global/` and `projects/`), not a scope directory. Pointing it at a scope-shaped directory is a warned misconfiguration, not a supported way to select a scope. +3. **Seven tools, not six (#3).** `scratchpad` is a tool and is scoped with the others. +4. **The upstream route (#11).** Community best practice overrode the recommendation: an **issue precedes the PR**. + +## C. Deliberate omissions + +- **No cross-platform hash-equality case** (§9.5) — memory storage never crosses platforms. +- **No auto-creation, no auto-pruning** anywhere in the design (§4.4, §6.5) — a typo must never create a junk scope; a removal must never be the only copy of unmigrated memory. +- **No qmd maintainer conversation** before the upstream issue — every qmd operation the design needs works as documented; one is opened only if the implementation hits a limitation. + +## D. Open questions for the maintainer + +- The **name `pi-memory` for the global collection** is back-compatible but is the one place where collection name ≠ directory basename (`global/`). Alternative: rename it `pi-memory-global` and let the migration re-point it — cleaner rule, worse back-compat. +- **Scope of trust:** `.pi/memory.json` is read only for trusted projects (pi's rule). Worth confirming that matches the maintainer's intent for a file that changes search behaviour. +- Whether `/memory scope` should gain a `--persist` flag to write the config file, or stays strictly session-only as specified (§3.3). + +## E. Beyond this spec + +Implementation, extension retirement and the code PR are the work this spec enables, and are deliberately out of scope here. From ce017f6241574667ef32710f96dd60d4e10b18f7 Mon Sep 17 00:00:00 2001 From: Fan Kai Date: Thu, 29 Oct 2026 11:36:32 +0800 Subject: [PATCH 02/26] docs: tighten the spec's evidence links and record the pre-existing qmd context bug --- docs/spec/project-scoped-memory.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/spec/project-scoped-memory.md b/docs/spec/project-scoped-memory.md index e784920..0a2f16f 100644 --- a/docs/spec/project-scoped-memory.md +++ b/docs/spec/project-scoped-memory.md @@ -43,7 +43,7 @@ global | project: | project:# **Scope identity is path-bound.** Moving or renaming a repo changes its scope id and its collection name. Accepted: the absolute path is predictable; a remote URL is not an identity (absent, forked, mirrored). The escape hatch is the `project` key in `.pi/memory.json` (chapter 3), which sets the slug explicitly. -**Scope resolution happens in `session_start` from `ctx.cwd`** — never at import and never from `process.cwd()` (which is the launch dir, not the session dir). `ctx.cwd` is a snapshot refreshed only by a runtime replacement (`/resume` of a session recorded elsewhere), which re-runs the factory and re-evaluates module state anyway. Re-resolve on every `session_start`; rebuild project-scoped state (qmd collections, injected context) only when the resolved cwd or scope set actually changes; release session-bound resources in `session_shutdown`. Evidence: [docs/research/pi-cwd-and-session-lifecycle.md](../research/pi-cwd-and-session-lifecycle.md) (fork only) and appendix A. +**Scope resolution happens in `session_start` from `ctx.cwd`** — never at import and never from `process.cwd()` (which is the launch dir, not the session dir). `ctx.cwd` is a snapshot refreshed only by a runtime replacement (`/resume` of a session recorded elsewhere), which re-runs the factory and re-evaluates module state anyway. Re-resolve on every `session_start`; rebuild project-scoped state (qmd collections, injected context) only when the resolved cwd or scope set actually changes; release session-bound resources in `session_shutdown`. Evidence: [pi-cwd-and-session-lifecycle.md](../research/pi-cwd-and-session-lifecycle.md) (shipped with this spec) and appendix A. --- @@ -279,7 +279,7 @@ qmd context add "qmd:///daily" "Daily append-only work logs organized by d qmd context add "qmd:///" "Curated long-term memory: decisions, preferences, facts, lessons" ``` -**Removing a collection deletes its contexts** (verified), so the contexts are re-added in the same operation. Every scope collection gets the same two contexts, added at creation — contexts are per-collection, so project collections need their own. Note the path form: there is **no `-c` flag**; the collection is part of the `qmd://` path (this is the fix for an existing call in `index.ts` today that passes `-c pi-memory` and has never worked — appendix B). +**Removing a collection deletes its contexts** (verified), so the contexts are re-added in the same operation. Every scope collection gets the same two contexts, added at creation — contexts are per-collection, so project collections need their own. Note the path form: there is **no `-c` flag**; the collection is part of the `qmd://` path (this is the fix for an existing call in `index.ts` today — `qmd context add /daily "…" -c pi-memory` — that passes `-c` and has never worked, appendix B). **The migration owns the global re-point**, at chapter 7's step. Not now: the legacy `pi-memory` collection points at ``, whose `**/*.md` covers `global/` and `projects/*` alike; re-pointing it before the files move would point the index at an empty directory and make the user's memory vanish from search. A collection whose path differs for any other reason (the user moved a scope directory) is re-pointed the same way, at the next session start. @@ -476,6 +476,12 @@ Decisions made during the map that **supersede** an earlier statement: 3. **Seven tools, not six (#3).** `scratchpad` is a tool and is scoped with the others. 4. **The upstream route (#11).** Community best practice overrode the recommendation: an **issue precedes the PR**. +**Defect found (pre-existing, fixed by this spec):** `index.ts` calls +`qmd context add /daily "…" -c pi-memory` when creating a collection. `-c` is not a +flag on `qmd context add` and the collection must be part of the path, so that call has +never succeeded — it throws and is swallowed by the surrounding `catch`. §6.4 gives the +working form. No test covers it today; the case matrix's context case (§9.4) would have caught it. + ## C. Deliberate omissions - **No cross-platform hash-equality case** (§9.5) — memory storage never crosses platforms. From d5400876dcd85cab311e6b6fb25f6a13ba9f684d Mon Sep 17 00:00:00 2001 From: Fan Kai Date: Thu, 29 Oct 2026 17:55:15 +0800 Subject: [PATCH 03/26] chore: add agent skills, glossary, and issue-tracker docs Signed-off-by: Fan Kai --- .agents/skills/ask-matt/PHASE-BOUNDARIES.md | 55 +++++ .agents/skills/ask-matt/SKILL.md | 97 ++++++++ .agents/skills/ask-matt/agents/openai.yaml | 5 + .agents/skills/chief-of-staff/SKILL.md | 68 +++++ .../skills/chief-of-staff/agents/openai.yaml | 5 + .agents/skills/claude-handoff/SKILL.md | 18 ++ .../skills/claude-handoff/agents/openai.yaml | 5 + .agents/skills/code-review/SKILL.md | 89 +++++++ .agents/skills/code-review/agents/openai.yaml | 3 + .agents/skills/codebase-design/DEEPENING.md | 37 +++ .../skills/codebase-design/DESIGN-IT-TWICE.md | 44 ++++ .agents/skills/codebase-design/SKILL.md | 114 +++++++++ .../skills/codebase-design/agents/openai.yaml | 3 + .agents/skills/diagnosing-bugs/SKILL.md | 138 +++++++++++ .../skills/diagnosing-bugs/agents/openai.yaml | 3 + .../scripts/hitl-loop.template.sh | 44 ++++ .agents/skills/domain-modeling/ADR-FORMAT.md | 47 ++++ .../skills/domain-modeling/GLOSSARY-FORMAT.md | 60 +++++ .agents/skills/domain-modeling/SKILL.md | 74 ++++++ .../skills/domain-modeling/agents/openai.yaml | 3 + .../git-guardrails-claude-code/SKILL.md | 95 +++++++ .../agents/openai.yaml | 3 + .../scripts/block-dangerous-git.sh | 25 ++ .agents/skills/grill-me/SKILL.md | 7 + .agents/skills/grill-me/agents/openai.yaml | 5 + .agents/skills/grill-with-docs/SKILL.md | 7 + .../skills/grill-with-docs/agents/openai.yaml | 5 + .agents/skills/grilling/SKILL.md | 30 +++ .agents/skills/grilling/agents/openai.yaml | 3 + .agents/skills/handoff/SKILL.md | 16 ++ .agents/skills/handoff/agents/openai.yaml | 5 + .agents/skills/implement-spec/SKILL.md | 40 +++ .../skills/implement-spec/agents/openai.yaml | 5 + .agents/skills/implement/SKILL.md | 17 ++ .agents/skills/implement/agents/openai.yaml | 5 + .../HTML-REPORT.md | 123 +++++++++ .../improve-codebase-architecture/SKILL.md | 71 ++++++ .../agents/openai.yaml | 5 + .agents/skills/loop-me/SKILL.md | 32 +++ .agents/skills/loop-me/agents/openai.yaml | 5 + .agents/skills/migrate-to-shoehorn/SKILL.md | 118 +++++++++ .../migrate-to-shoehorn/agents/openai.yaml | 3 + .agents/skills/pr/CREDITS.md | 3 + .agents/skills/pr/SKILL.md | 170 +++++++++++++ .agents/skills/pr/agents/openai.yaml | 3 + .agents/skills/prototype/LOGIC.md | 67 +++++ .agents/skills/prototype/SKILL.md | 26 ++ .agents/skills/prototype/UI.md | 112 +++++++++ .agents/skills/prototype/agents/openai.yaml | 3 + .agents/skills/research/SKILL.md | 12 + .agents/skills/research/agents/openai.yaml | 3 + .agents/skills/retro/SKILL.md | 44 ++++ .agents/skills/retro/agents/openai.yaml | 5 + .agents/skills/scaffold-exercises/SKILL.md | 106 ++++++++ .../scaffold-exercises/agents/openai.yaml | 3 + .../skills/setup-matt-pocock-skills/SKILL.md | 120 +++++++++ .../agents/openai.yaml | 5 + .../skills/setup-matt-pocock-skills/domain.md | 51 ++++ .../issue-tracker-github.md | 50 ++++ .../issue-tracker-gitlab.md | 46 ++++ .../issue-tracker-local.md | 30 +++ .../setup-matt-pocock-skills/triage-labels.md | 15 ++ .agents/skills/setup-pre-commit/SKILL.md | 91 +++++++ .../setup-pre-commit/agents/openai.yaml | 3 + .agents/skills/setup-ts-deep-modules/SKILL.md | 102 ++++++++ .../setup-ts-deep-modules/agents/openai.yaml | 5 + .../dependency-cruiser.config.cjs | 95 +++++++ .agents/skills/tdd/SKILL.md | 38 +++ .agents/skills/tdd/agents/openai.yaml | 3 + .agents/skills/tdd/mocking.md | 59 +++++ .agents/skills/tdd/tests.md | 77 ++++++ .agents/skills/teach/GLOSSARY-FORMAT.md | 35 +++ .../skills/teach/LEARNING-RECORD-FORMAT.md | 46 ++++ .agents/skills/teach/MISSION-FORMAT.md | 31 +++ .agents/skills/teach/RESOURCES-FORMAT.md | 32 +++ .agents/skills/teach/SKILL.md | 140 +++++++++++ .agents/skills/teach/agents/openai.yaml | 5 + .agents/skills/to-questionnaire/SKILL.md | 54 ++++ .../to-questionnaire/agents/openai.yaml | 5 + .agents/skills/to-spec/SKILL.md | 75 ++++++ .agents/skills/to-spec/agents/openai.yaml | 5 + .agents/skills/to-tickets/SKILL.md | 105 ++++++++ .agents/skills/to-tickets/agents/openai.yaml | 5 + .agents/skills/triage/AGENT-BRIEF.md | 207 ++++++++++++++++ .agents/skills/triage/OUT-OF-SCOPE.md | 105 ++++++++ .agents/skills/triage/SKILL.md | 112 +++++++++ .agents/skills/triage/agents/openai.yaml | 5 + .agents/skills/wait-what/SKILL.md | 7 + .agents/skills/wait-what/agents/openai.yaml | 5 + .agents/skills/wayfinder/SKILL.md | 128 ++++++++++ .agents/skills/wayfinder/agents/openai.yaml | 5 + .agents/skills/wizard/SKILL.md | 44 ++++ .agents/skills/wizard/agents/openai.yaml | 3 + .agents/skills/wizard/template.sh | 223 +++++++++++++++++ .agents/skills/writing-beats/SKILL.md | 67 +++++ .../skills/writing-beats/agents/openai.yaml | 5 + .../writing-for-agents/SKILL-MECHANICS.md | 22 ++ .agents/skills/writing-for-agents/SKILL.md | 81 ++++++ .../writing-for-agents/agents/openai.yaml | 3 + .agents/skills/writing-fragments/SKILL.md | 79 ++++++ .../writing-fragments/agents/openai.yaml | 5 + .agents/skills/writing-shape/SKILL.md | 79 ++++++ .../skills/writing-shape/agents/openai.yaml | 5 + .gitignore | 3 + CLAUDE.md | 14 ++ GLOSSARY.md | 43 ++++ biome.json | 2 +- docs/agents/domain.md | 53 ++++ docs/agents/issue-tracker.md | 48 ++++ docs/agents/triage-labels.md | 15 ++ skills-lock.json | 233 ++++++++++++++++++ 111 files changed, 5022 insertions(+), 1 deletion(-) create mode 100644 .agents/skills/ask-matt/PHASE-BOUNDARIES.md create mode 100644 .agents/skills/ask-matt/SKILL.md create mode 100644 .agents/skills/ask-matt/agents/openai.yaml create mode 100644 .agents/skills/chief-of-staff/SKILL.md create mode 100644 .agents/skills/chief-of-staff/agents/openai.yaml create mode 100644 .agents/skills/claude-handoff/SKILL.md create mode 100644 .agents/skills/claude-handoff/agents/openai.yaml create mode 100644 .agents/skills/code-review/SKILL.md create mode 100644 .agents/skills/code-review/agents/openai.yaml create mode 100644 .agents/skills/codebase-design/DEEPENING.md create mode 100644 .agents/skills/codebase-design/DESIGN-IT-TWICE.md create mode 100644 .agents/skills/codebase-design/SKILL.md create mode 100644 .agents/skills/codebase-design/agents/openai.yaml create mode 100644 .agents/skills/diagnosing-bugs/SKILL.md create mode 100644 .agents/skills/diagnosing-bugs/agents/openai.yaml create mode 100644 .agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh create mode 100644 .agents/skills/domain-modeling/ADR-FORMAT.md create mode 100644 .agents/skills/domain-modeling/GLOSSARY-FORMAT.md create mode 100644 .agents/skills/domain-modeling/SKILL.md create mode 100644 .agents/skills/domain-modeling/agents/openai.yaml create mode 100644 .agents/skills/git-guardrails-claude-code/SKILL.md create mode 100644 .agents/skills/git-guardrails-claude-code/agents/openai.yaml create mode 100644 .agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh create mode 100644 .agents/skills/grill-me/SKILL.md create mode 100644 .agents/skills/grill-me/agents/openai.yaml create mode 100644 .agents/skills/grill-with-docs/SKILL.md create mode 100644 .agents/skills/grill-with-docs/agents/openai.yaml create mode 100644 .agents/skills/grilling/SKILL.md create mode 100644 .agents/skills/grilling/agents/openai.yaml create mode 100644 .agents/skills/handoff/SKILL.md create mode 100644 .agents/skills/handoff/agents/openai.yaml create mode 100644 .agents/skills/implement-spec/SKILL.md create mode 100644 .agents/skills/implement-spec/agents/openai.yaml create mode 100644 .agents/skills/implement/SKILL.md create mode 100644 .agents/skills/implement/agents/openai.yaml create mode 100644 .agents/skills/improve-codebase-architecture/HTML-REPORT.md create mode 100644 .agents/skills/improve-codebase-architecture/SKILL.md create mode 100644 .agents/skills/improve-codebase-architecture/agents/openai.yaml create mode 100644 .agents/skills/loop-me/SKILL.md create mode 100644 .agents/skills/loop-me/agents/openai.yaml create mode 100644 .agents/skills/migrate-to-shoehorn/SKILL.md create mode 100644 .agents/skills/migrate-to-shoehorn/agents/openai.yaml create mode 100644 .agents/skills/pr/CREDITS.md create mode 100644 .agents/skills/pr/SKILL.md create mode 100644 .agents/skills/pr/agents/openai.yaml create mode 100644 .agents/skills/prototype/LOGIC.md create mode 100644 .agents/skills/prototype/SKILL.md create mode 100644 .agents/skills/prototype/UI.md create mode 100644 .agents/skills/prototype/agents/openai.yaml create mode 100644 .agents/skills/research/SKILL.md create mode 100644 .agents/skills/research/agents/openai.yaml create mode 100644 .agents/skills/retro/SKILL.md create mode 100644 .agents/skills/retro/agents/openai.yaml create mode 100644 .agents/skills/scaffold-exercises/SKILL.md create mode 100644 .agents/skills/scaffold-exercises/agents/openai.yaml create mode 100644 .agents/skills/setup-matt-pocock-skills/SKILL.md create mode 100644 .agents/skills/setup-matt-pocock-skills/agents/openai.yaml create mode 100644 .agents/skills/setup-matt-pocock-skills/domain.md create mode 100644 .agents/skills/setup-matt-pocock-skills/issue-tracker-github.md create mode 100644 .agents/skills/setup-matt-pocock-skills/issue-tracker-gitlab.md create mode 100644 .agents/skills/setup-matt-pocock-skills/issue-tracker-local.md create mode 100644 .agents/skills/setup-matt-pocock-skills/triage-labels.md create mode 100644 .agents/skills/setup-pre-commit/SKILL.md create mode 100644 .agents/skills/setup-pre-commit/agents/openai.yaml create mode 100644 .agents/skills/setup-ts-deep-modules/SKILL.md create mode 100644 .agents/skills/setup-ts-deep-modules/agents/openai.yaml create mode 100644 .agents/skills/setup-ts-deep-modules/dependency-cruiser.config.cjs create mode 100644 .agents/skills/tdd/SKILL.md create mode 100644 .agents/skills/tdd/agents/openai.yaml create mode 100644 .agents/skills/tdd/mocking.md create mode 100644 .agents/skills/tdd/tests.md create mode 100644 .agents/skills/teach/GLOSSARY-FORMAT.md create mode 100644 .agents/skills/teach/LEARNING-RECORD-FORMAT.md create mode 100644 .agents/skills/teach/MISSION-FORMAT.md create mode 100644 .agents/skills/teach/RESOURCES-FORMAT.md create mode 100644 .agents/skills/teach/SKILL.md create mode 100644 .agents/skills/teach/agents/openai.yaml create mode 100644 .agents/skills/to-questionnaire/SKILL.md create mode 100644 .agents/skills/to-questionnaire/agents/openai.yaml create mode 100644 .agents/skills/to-spec/SKILL.md create mode 100644 .agents/skills/to-spec/agents/openai.yaml create mode 100644 .agents/skills/to-tickets/SKILL.md create mode 100644 .agents/skills/to-tickets/agents/openai.yaml create mode 100644 .agents/skills/triage/AGENT-BRIEF.md create mode 100644 .agents/skills/triage/OUT-OF-SCOPE.md create mode 100644 .agents/skills/triage/SKILL.md create mode 100644 .agents/skills/triage/agents/openai.yaml create mode 100644 .agents/skills/wait-what/SKILL.md create mode 100644 .agents/skills/wait-what/agents/openai.yaml create mode 100644 .agents/skills/wayfinder/SKILL.md create mode 100644 .agents/skills/wayfinder/agents/openai.yaml create mode 100644 .agents/skills/wizard/SKILL.md create mode 100644 .agents/skills/wizard/agents/openai.yaml create mode 100644 .agents/skills/wizard/template.sh create mode 100644 .agents/skills/writing-beats/SKILL.md create mode 100644 .agents/skills/writing-beats/agents/openai.yaml create mode 100644 .agents/skills/writing-for-agents/SKILL-MECHANICS.md create mode 100644 .agents/skills/writing-for-agents/SKILL.md create mode 100644 .agents/skills/writing-for-agents/agents/openai.yaml create mode 100644 .agents/skills/writing-fragments/SKILL.md create mode 100644 .agents/skills/writing-fragments/agents/openai.yaml create mode 100644 .agents/skills/writing-shape/SKILL.md create mode 100644 .agents/skills/writing-shape/agents/openai.yaml create mode 100644 GLOSSARY.md create mode 100644 docs/agents/domain.md create mode 100644 docs/agents/issue-tracker.md create mode 100644 docs/agents/triage-labels.md create mode 100644 skills-lock.json diff --git a/.agents/skills/ask-matt/PHASE-BOUNDARIES.md b/.agents/skills/ask-matt/PHASE-BOUNDARIES.md new file mode 100644 index 0000000..fb58ef9 --- /dev/null +++ b/.agents/skills/ask-matt/PHASE-BOUNDARIES.md @@ -0,0 +1,55 @@ +# Phase boundaries + +A **phase** is a chunk of work inside a session: the grilling, the implementation, the QA. The definition is fuzzy on purpose: a phase ends when you think *"ok, we're done with that"*. + +The **phase boundary** is the gap between two phases, and it is the only place this decision belongs. Mid-phase there is no decision to make: continue, or split the work that's left into subagents. Compacting mid-phase makes the agent lose the thread. + +## The five options + +| Option | What it does | +| ------------ | --------------------------------------------------------------- | +| **Continue** | Stay in the session. No context switch at all. | +| **`/clear`** | Empty the context window and start from nothing. | +| **`/handoff`** | Write a portable markdown file and seed a session anywhere with it. | +| **Subagent** | Send the task to its own context window and get a report back. | +| **`/compact`** | Compress this context and seed a fresh session with the summary. | + +## The tree + +Work top to bottom at the boundary. The first **yes** wins. + +**1. Can you continue in this session?** Two things make the answer yes: the next phase needs this phase as a **primary source**, or you have enough [smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone) left (~150k tokens) for the next phase to fit. Grilling → implementation is the standard yes: the implementation wants the reasoning verbatim, not a summary of it. Continue costs nothing and loses nothing, so rule it out before anything else. + +**2. Is the context irrelevant to what comes next?** Is everything in this session (the exploration, the decisions, the dead ends) disposable? If so, **`/clear`**. It is the cheapest move on the board: it takes no time and hands back the whole window. `/clear` also isn't terminal: the old session stays resumable. + +The cost of getting this wrong is one-way. Clear a *relevant* context and you lose the **why** behind what you built, and no amount of reading the diff back gets it returned. + +**3. Do you need to hand off?** `/handoff` is narrow. You need it only when you are: + +- swapping to a **new harness** (Claude → Codex), +- moving to a **new directory** or repo, +- sending the work to a **colleague**, +- or forking a side task you found **mid-phase** without derailing what you're doing. + +That list is the whole clause. What `/handoff` buys is **portability**: a file that travels. If nothing is travelling, you don't need it. + +**4. Can the task be done AFK?** Is it scoped tightly enough to run with you away from the keyboard, no steering? Then send it to a **subagent** and leave this session untouched. Automated review is the standard case: the agent reads the diff and reports, and you aren't needed while it does. + +**5. Otherwise, `/compact`.** Relevant context, same harness, same directory, and you need to stay in the loop: this is where the tree lands, and it lands here often. Pass it an instruction (`/compact we're going to QA this area`) so the summary keeps what the next phase needs. + +`/compact` is the **default, not the first reach**. It sits at the bottom because the four questions above it are all cheaper or more precise. The failure mode when people start here is a fresh session that is confidently wrong about a decision the summary flattened. + +## Primary and secondary sources + +Every move except **Continue** turns a **primary source** into a **secondary source**: the session as it happened, replaced by a summary of it. The trade is always the same shape: + +| Source | Information | Noise | Room to move | +| --------------------------------- | ----------- | ----- | ------------ | +| Primary (Continue) | Full | Lots | Little | +| Secondary (`/compact`, `/handoff`) | Lossy | Less | Lots | + +This is why question 1 comes first. You only pay the lossiness when staying costs more than it saves. + +## These are judgement calls + +The questions are not objective: each has taste in it, and the same boundary can go two ways on two days. The value is in asking them **in order**, at the boundary rather than in the middle of the work. diff --git a/.agents/skills/ask-matt/SKILL.md b/.agents/skills/ask-matt/SKILL.md new file mode 100644 index 0000000..4bfeeb6 --- /dev/null +++ b/.agents/skills/ask-matt/SKILL.md @@ -0,0 +1,97 @@ +--- +name: ask-matt +description: Ask which skill or flow fits your situation. A router over the skills in this repo. +disable-model-invocation: true +--- + +# Ask Matt + +You don't remember every skill, so ask. + +Before stating what a skill does or recommending a step be skipped, read that skill's SKILL.md: the summaries here are for orientation only. + +A **flow** is a path through the skills. Most paths run along one **main flow**, and two **on-ramps** merge onto it. Everything else is standalone, or a vocabulary layer that runs underneath. + +## The main flow: idea → ship + +The route most work travels. You have an idea and want it built. + +1. **`/grill-with-docs`** sharpens the idea by interview. Start here whenever you are **working in a working directory**: it's stateful, retaining what it learns in `GLOSSARY.md` and ADRs. (No working directory? Use `/grill-me` instead, covered under Standalone. Both run the same `/grilling` primitive; `grill-with-docs` is the one that leaves a paper trail, which makes it the better of the two whenever a repo is there to leave it in.) +2. **Branch: can you settle every question in conversation?** If a question needs a runnable answer (state, business logic, a UI you have to see), detour through a prototype, bridged by **`/handoff`** in both directions (a prototype lives in its own directory, which is exactly what `/handoff` is for; see Phase boundaries): + - **`/handoff`** out, then open a fresh session against that file, + - **`/prototype`** to answer the question with throwaway code, + - **`/handoff`** back what you learned, and reference it from the original idea thread. +3. **Branch: is this a multi-session build?** + - **Yes** → **`/to-spec`** (turn the thread into a spec), then **`/to-tickets`** to split it into tracer-bullet tickets, each declaring its **blocking edges**. Then work the tickets one of two ways: + - **`/implement`** per ticket, **`/clear`ing context between each one**. On a local tracker that's one file per ticket under `.scratch//issues/`, worked blockers-first by hand; on a real tracker the edges become native blocking links, so any ticket whose blockers are done can be grabbed. Each ticket is self-contained, so the last one's context is disposable. + - **`/implement-spec`** for the whole spec in one run. It reads the tickets as a **task graph**, runs implementer subagents across the ready **frontier** in parallel, and lands everything on one **integration branch**. Reach for it when you'd rather orchestrate the build than drive each ticket yourself. + - **No** → **`/implement`** right here, in the same context window. + + Either way, the code gets built by driving **`/tdd`** (one red-green slice at a time) and closes out with **`/code-review`**, a two-axis review (Standards + Spec) of the diff. `/implement` runs both per ticket; `/implement-spec`'s implementers each drive `/tdd`, and it runs one `/code-review` over the integration branch. Reach for **`/tdd`** on its own when you just want to build a concrete behaviour test-first without a full spec, and **`/code-review`** on its own whenever you want to review a branch or PR against a fixed point. + + When the work goes up as a pull request, **`/pr`** shapes the body: the smallest visual that shows the change, before/after evidence that it works, and a one-way or two-way door call. It's model-invoked, so the agent reaches for it whenever it writes a PR. + +4. **`/retro`** closes the loop. After a build, and especially one that went sideways, it looks back over the session and suggests changes to the agent's **environment**, not the code: navigation pointers, automated checks, the coding standards `/code-review` enforces, steering files, tooling. Mechanical mistakes become deterministic checks; judgement calls become coding standards. The next build then starts from a better environment. + +### Context hygiene + +Keep steps 1–3 in **one unbroken context window** (don't compact or clear until after `/to-tickets`) so the grilling, spec, and tickets all build on the same thinking. Each `/implement` then starts fresh, working from the ticket. Run `/retro` in the session it's looking back on, before you clear; after clearing, point it at that session's log instead. + +The limit on this is the **[smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone)**: the window (~150k tokens on state-of-the-art models) within which the model still reasons sharply. If a session approaches it before `/to-tickets`, don't push on degraded; `/compact` at the nearest phase boundary and carry on (see Phase boundaries). + +## On-ramps + +A starting situation that generates work, then merges onto the main flow. + +- **Bugs and requests piling up** → **`/triage`**. It moves issues through triage roles and produces agent-ready issues, which **`/implement`** later picks up. + + Triage is only for issues **you didn't create**: bug reports, incoming feature requests, anything that arrives raw. Tickets that `/to-tickets` produced are already agent-ready, so **don't triage them**. + +- **Something's broken** → **`/diagnosing-bugs`**. For the hard ones: the bug that resists a first glance, the intermittent flake, the regression that crept in between two known-good states. It refuses to theorise until it has a **tight feedback loop** (one command that already goes red on *this* bug), then fixes with a regression test. Once the fix is in, run **`/retro`** in the same session to ask what would have prevented the bug; where the real finding is that there's no good seam to lock it down, that's a job for **`/improve-codebase-architecture`**. + +- **A huge, foggy effort: a greenfield project or a huge feature build, too big for one session** → **`/wayfinder`**, the most cognitively demanding flow here. When the way from here to the destination isn't visible yet, it charts a **shared map** of **decision tickets** on the issue tracker and resolves them one at a time, producing **decisions, not deliverables**, until the fog is pushed back and the way is clear. Where **`/grill-with-docs`** sharpens an idea you can hold in one session, wayfinder is for the idea you can't, and it's slower and denser, so save it for exactly that, never a well-scoped feature. + + When the map clears, **it hands off, it doesn't build**: merge onto the main flow at **`/to-spec`**, which collapses the map's linked decisions into a buildable plan, then `/to-tickets` and `/implement` as usual. Looping the map straight into `/implement` skips that collapse and throws the linked detail away, so go straight to `/implement` only when the effort turned out genuinely small. + +## Codebase health + +Not feature work, just upkeep. + +- **`/improve-codebase-architecture`** runs whenever you have a spare moment to keep the codebase good for agents to operate in. It surfaces **deepening opportunities**; picking one _generates an idea_ you can take into the main flow at `/grill-with-docs`. It's the survey that finds the candidates; **`/codebase-design`** (below) is the bench you design the chosen one on. + +## Vocabulary underneath + +Two model-invoked references that run *beneath* the other skills, each the single source of truth for its vocabulary. Reach for them directly when the **words**, not the process, are the problem; or let the skills above pull them in. + +- **`/domain-modeling`**: sharpen the project's *domain* language: challenge a fuzzy term, resolve an overloaded word ("account" doing three jobs), record a hard-to-reverse decision as an ADR. It's the active discipline `/grill-with-docs` drives to keep `GLOSSARY.md` a clean glossary. +- **`/codebase-design`** is the deep-module vocabulary (module, interface, depth, seam, adapter, leverage, locality) for designing a module's *shape*: a lot of behaviour behind a small interface at a clean seam. `/tdd` and `/improve-codebase-architecture` both speak it. + +## Phase boundaries + +A **phase** is a chunk of work inside a session: the grilling, the implementation, the QA. At the **boundary** between two of them you have five options, and picking between them is the fuzziest decision in this whole map: + +- **Continue**: stay put. Costs nothing, loses nothing. +- **`/clear`**: empty the window, when nothing here matters to what's next. +- **`/handoff`** writes a portable markdown file. Narrow: only for a **new harness**, a **new directory**, a **colleague**, or forking a side task **mid-phase**. What it buys is portability. +- **Subagent**: send a tightly-scoped task to its own window and get a report back. +- **`/compact`** compresses this context and seeds a fresh session with it. The **default**, at the bottom of the tree rather than the first reach. + +Read [PHASE-BOUNDARIES.md](PHASE-BOUNDARIES.md) for the ordered tree: the five questions, the reasoning behind each branch, and why the primary-source cost makes **Continue** the one to rule out first. Make the decision **at** a boundary; mid-phase, continue or split the rest into subagents. + +## Standalone + +Off the main flow entirely. + +- **`/grill-me`**: the same relentless interview as `/grill-with-docs`, but **stateless**: it saves nothing locally and builds no `GLOSSARY.md`. Reach for it when you are **not working in a working directory** (sharpening a plan, a design, a piece of writing, anything with no repo under it). If you are in a working directory, use `/grill-with-docs` instead: it runs the same interview and leaves a paper trail, so it is strictly the better one. +- **`/grilling`** is the interview primitive itself: rounds, the frontier, facts are the agent's job and decisions are yours. `/grill-me` and `/grill-with-docs` are the two named ways in, and `/triage`, `/wayfinder` and `/improve-codebase-architecture` all run it internally. Reach for it directly only when you want the interview with no wrapper around it. +- **`/prototype`** is a small, throwaway program that answers one design question: does this state model feel right, or what should this UI look like. Throwaway is a constraint on how the code is written, not a promise to destroy it: the answer folds into the real code, and the prototype itself is kept as a **primary source** on a `prototype/` branch out of main, pointed at from the implementation issue. It's the detour in step 2 of the main flow, but reach for it any time a design question is hard to settle on paper. +- **`/research`**: delegate reading legwork to a **background agent**: it investigates a question against **primary sources**, then leaves a cited Markdown file in the repo. Keep working while it reads. The file it produces is something to take *into* the main flow at `/grill-with-docs`, since research feeds the thinking rather than replacing it. +- **`/to-questionnaire`** comes in when the thing blocking you isn't in your head or the codebase but in **someone else's**, and it writes them a questionnaire to fill in. It's the inverse of `/grill-me`: instead of interviewing you about the subject, it interviews you about the **send** (who it's going to, what you need back) and aims the questions at the gap. What comes back is material for `/grill-with-docs` or `/to-spec`. +- **`/wizard`** is for the steps only a **human** can take: provisioning infrastructure, setting up credentials or CI secrets, clicking through an unfamiliar third-party dashboard, running a one-off migration or cutover. It generates an interactive bash script that opens each URL, captures each value, and writes it into `.env` and GitHub secrets, so the procedure stops being something you re-explain to an agent every time. Model-invoked, so the agent reaches for it the moment it hits a wall only you can pass. If the agent could just do it itself, it should; this is for where a human is genuinely in the loop. +- **`/wait-what`** is the corrective for a message that didn't land. Use it mid-conversation, inside any other skill, and the agent re-pitches what it just said with the context you were missing, in plain English, using the `GLOSSARY.md` vocabulary. It works after the fact; `/grill-with-docs` is the upfront cure, because a shared language agreed early is what stops the jargon arriving at all. +- **`/teach`**: learn a concept over multiple sessions, using the current directory as a stateful workspace. +- **`/writing-for-agents`** is the reference for writing documents agents consume: skills, AGENTS.md, pointed-at docs. + +## Precondition + +**`/setup-matt-pocock-skills`**: run before your first engineering flow to configure the issue tracker, triage labels, and doc layout the other skills assume. Custom issue trackers also work. diff --git a/.agents/skills/ask-matt/agents/openai.yaml b/.agents/skills/ask-matt/agents/openai.yaml new file mode 100644 index 0000000..5c60d51 --- /dev/null +++ b/.agents/skills/ask-matt/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Ask Matt" + short_description: "Find the right skill or workflow" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/chief-of-staff/SKILL.md b/.agents/skills/chief-of-staff/SKILL.md new file mode 100644 index 0000000..6dbdd4d --- /dev/null +++ b/.agents/skills/chief-of-staff/SKILL.md @@ -0,0 +1,68 @@ +--- +name: chief-of-staff +description: Pursue a long-running goal in a single session by co-ordinating subagents. +disable-model-invocation: true +--- + +You are a chief of staff, co-ordinating subagents and schedules to pursue a long-running goal. This session will run for a long time, accruing tribal knowledge and helping you make long-term strategic decisions. + +You are the Directly Responsible Individual for this goal. You are empowered to think much longer-term than you're used to. You must think on two tracks simultaneously: + +- Tactical: how do I complete the immediate task? +- Strategic: how do I modify the environment to improve the outcomes of the _next_ task? + +## Schedules + +Harness-permitting, you will suggest recurring schedules which can help in achieving the goal. + +## Subagents + +All work should be done in subagents. Protect your context window. + +Use background agents so you can stay in active dialogue with the user. + +Communication to and from subagents should be sparse. Communicate primarily through **context pointers**: research notes, previous commits, wiki pages, and others. Don't duplicate information already available via pointers. + +## Wiki + +Keep your memory in a **wiki**: a folder of interlinked markdown pages that outlives this session. Tribal knowledge that lives only in your context is lost at compaction; the wiki is how it reaches the next session. If the goal has no wiki yet, agree its location with the user before the first write. + +- `index.md` lists every page with a link and a one-line summary, grouped by category. +- Each other page covers one thing: a decision, a recurring problem, a subsystem, a user preference. Link related pages to each other. +- Sources (issues, PRs, transcripts, subagent reports) are never copied in or edited. Pages cite them. + +Three operations keep it alive: + +- **Ingest.** When you learn something durable (a decision, a user correction, a subagent's finding), update every page it touches and the index, not only a new page. +- **Query.** Before a decision, read `index.md` and the pages it points to. If the answer you build is worth keeping, file it as a page. +- **Lint.** Periodically look for contradictions, orphan pages, missing links and claims newer sources have overtaken. Suggest this as a schedule. + +### Write history, not the present + +The wiki is a historical record. It never claims to describe how things are now, because it cannot keep up with the code. + +- Date every claim: "On 2026-10-13, Matt decided..." +- When a claim concerns code, cite the commit it was true at, with its repo: "As of `mattpocock/skills@abc1234`, `retro` loads `writing-for-agents` in step 1." +- Never write "currently", "now" or "is" about code without a date or commit beside it. +- When something changes, add a new dated claim and mark the old one superseded. Don't rewrite the old one. + +## Strategic View + +As part of any and all work, FIRST consider how the environment the agents operate in might be improved. Agents thrive in the **pit of success**: + +- API's and functions which are extremely constrained and limited +- Lint rules which force correctness +- CODING_STANDARDS.md files which let code reviewers enforce best practices + +They also need relevant **data sources** to succeed: + +- Logs from critical running processes, like dev servers (or production logs) +- Access to test environment databases +- Access to the browser (when necessary) for clicking around and taking screenshots + +Finally, create environments (and codebases) that obey the **"no workarounds"** rule: + +- No one-off workarounds, or hacks that bypass established processes +- Any deviations from conventions must be fixed proactively, before feature work is done + +Be relentless in improving the environment. Use every user message as an excuse to search for these improvements. diff --git a/.agents/skills/chief-of-staff/agents/openai.yaml b/.agents/skills/chief-of-staff/agents/openai.yaml new file mode 100644 index 0000000..080598b --- /dev/null +++ b/.agents/skills/chief-of-staff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Chief Of Staff" + short_description: "Pursue a long-running goal in a single session by co-ordinating subagents" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/claude-handoff/SKILL.md b/.agents/skills/claude-handoff/SKILL.md new file mode 100644 index 0000000..77f82fc --- /dev/null +++ b/.agents/skills/claude-handoff/SKILL.md @@ -0,0 +1,18 @@ +--- +name: claude-handoff +description: Hand the current conversation off to a fresh background agent that picks up the work immediately. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff summary of the current conversation so a fresh agent can continue the work. Save it to the temporary directory of the user's OS, then launch a background agent seeded with it as its prompt: `claude --bg --name "" -- "$(cat )"`. Passing the file keeps the shell from running backticks or expanding `$` in the summary. It starts in the current working directory and returns immediately; the user manages it with `claude agents`. + +Always pass `-n`/`--name` with a descriptive name (e.g. `--name "Fix login bug"`); it sets the display name shown in the job list, session picker, and terminal title. + +Include a "suggested skills" section in the summary, naming which skills the next agent should call the Skill tool for. + +Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. + +Redact any sensitive information, such as API keys, passwords, or personally identifiable information, since the summary becomes the agent's prompt. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the summary accordingly. diff --git a/.agents/skills/claude-handoff/agents/openai.yaml b/.agents/skills/claude-handoff/agents/openai.yaml new file mode 100644 index 0000000..0a7aa5d --- /dev/null +++ b/.agents/skills/claude-handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Claude Handoff" + short_description: "Hand off to a background agent" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..373a4f2 --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,89 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in the tracker doc. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Search the repo for every file that documents how code should be written. When `CODING_STANDARDS.md` or `CONTRIBUTING.md` exists, it must be on the list. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +Issue both sub-agent calls together, in the foreground, and aggregate the reports they return. + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..d099013 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/diagnosing-bugs/SKILL.md b/.agents/skills/diagnosing-bugs/SKILL.md new file mode 100644 index 0000000..d039541 --- /dev/null +++ b/.agents/skills/diagnosing-bugs/SKILL.md @@ -0,0 +1,138 @@ +--- +name: diagnosing-bugs +description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow. +--- + +# Diagnosing Bugs + +A discipline for hard bugs. Skip phases only when explicitly justified. + +When exploring the codebase, read `GLOSSARY.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. + +## Redact + +This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal. + +If the redacted output is not enough to diagnose the bug, say so and ask the user. + +## Phase 1: Build a feedback loop + +**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you. + +Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** + +### Ways to construct one, in roughly this order + +1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e. +2. **Curl / HTTP script** against a running dev server. +3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot. +4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network. +5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation. +6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call. +7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode. +8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it. +9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs. +10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you. + +Build the right feedback loop, and the bug is 90% fixed. + +### Tighten the loop + +Treat the loop as a product. Once you have _a_ loop, **tighten** it: + +- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.) +- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".) +- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.) + +A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower. + +### Non-deterministic bugs + +The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable. + +### When you genuinely cannot build a loop + +Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop. + +### Completion criterion: a tight loop that goes red + +Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is: + +- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_. +- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above). +- [ ] **Fast**: seconds, not minutes. +- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`. + +If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2. + +## Phase 2: Reproduce + minimise + +Run the loop. Watch it go red as the bug appears. + +Confirm: + +- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix. +- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against). +- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it. + +### Minimise + +Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure. + +Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5. + +Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green. + +Do not proceed until you have reproduced **and** minimised. + +## Phase 3: Hypothesise + +Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea. + +Each hypothesis must be **falsifiable**: state the prediction it makes. + +> Format: "If is the cause, then will make the bug disappear / will make it worse." + +If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it. + +**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK. + +## Phase 4: Instrument + +Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.** + +Tool preference: + +1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs. +2. **Targeted logs** at the boundaries that distinguish hypotheses. +3. Never "log everything and grep". + +**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die. + +**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second. + +## Phase 5: Fix + regression test + +Write the regression test **before the fix**, but only if there is a **correct seam** for it. + +A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence. + +**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase. + +If a correct seam exists: + +1. Turn the minimised repro into a failing test at that seam. +2. Watch it fail. If you forced the red by mutating code or a fixture, `diff` against a pristine copy to prove the mutation landed before you trust it. +3. Apply the fix. +4. Watch it pass. +5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario. + +## Phase 6: Cleanup + +Required before declaring done: + +- [ ] Original repro no longer reproduces (re-run the Phase 1 loop) +- [ ] Regression test passes (or absence of seam is documented) +- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix) +- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location) +- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns diff --git a/.agents/skills/diagnosing-bugs/agents/openai.yaml b/.agents/skills/diagnosing-bugs/agents/openai.yaml new file mode 100644 index 0000000..a13a755 --- /dev/null +++ b/.agents/skills/diagnosing-bugs/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Diagnosing Bugs" + short_description: "Diagnose hard bugs and regressions" diff --git a/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh new file mode 100644 index 0000000..2431984 --- /dev/null +++ b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Human-in-the-loop reproduction loop. +# Copy this file, edit the steps below, and run it. +# The agent runs the script; the user follows prompts in their terminal. +# +# Usage: +# bash hitl-loop.template.sh +# +# Two helpers: +# step "" → show instruction, wait for Enter +# capture VAR "" → show question, read response into VAR +# +# At the end, captured values are printed as KEY=VALUE for the agent to parse. +# +# `capture` prints its value back to the terminal, where the agent reads it, +# so capture observations, and leave signing in to the user as a `step`. + +set -euo pipefail + +step() { + printf '\n>>> %s\n' "$1" + read -r -p " [Enter when done] " _ +} + +capture() { + local var="$1" question="$2" answer + printf '\n>>> %s\n' "$question" + read -r -p " > " answer + printf -v "$var" '%s' "$answer" +} + +# --- edit below --------------------------------------------------------- + +step "Open the app at http://localhost:3000 and sign in." + +capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)" + +capture ERROR_MSG "Paste the error message (or 'none'):" + +# --- edit above --------------------------------------------------------- + +printf '\n--- Captured ---\n' +printf 'ERRORED=%s\n' "$ERRORED" +printf 'ERROR_MSG=%s\n' "$ERROR_MSG" diff --git a/.agents/skills/domain-modeling/ADR-FORMAT.md b/.agents/skills/domain-modeling/ADR-FORMAT.md new file mode 100644 index 0000000..d7e61f3 --- /dev/null +++ b/.agents/skills/domain-modeling/ADR-FORMAT.md @@ -0,0 +1,47 @@ +# ADR Format + +ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. + +Create the `docs/adr/` directory lazily: only when the first ADR is needed. + +## Template + +```md +# {Short title of the decision} + +{1-3 sentences: what's the context, what did we decide, and why.} +``` + +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. + +## Optional sections + +Only include these when they add genuine value. Most ADRs won't need them. + +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out + +## Numbering + +Scan `docs/adr/` for the highest existing number and increment by one. + +## When to offer an ADR + +All three of these must be true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." + +### What qualifies + +- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." +- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. +- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. +- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. +- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md new file mode 100644 index 0000000..9c0b4c7 --- /dev/null +++ b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md @@ -0,0 +1,60 @@ +# GLOSSARY.md Format + +## Structure + +```md +# {Context Name} + +{One or two sentence description of what this context is and why it exists.} + +## Language + +**Order**: +{A one or two sentence description of the term} +_Avoid_: Purchase, transaction + +**Invoice**: +A request for payment sent to a customer after delivery. +_Avoid_: Bill, payment request + +**Customer**: +A person or organization that places orders. +_Avoid_: Client, buyer, account +``` + +## Rules + +- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`. +- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does. +- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs. +- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine. + +## Single vs multi-context repos + +**Single context (most repos):** One `GLOSSARY.md` at the repo root. + +**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: + +```md +# Glossary Map + +## Contexts + +- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders +- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping + +## Relationships + +- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking +- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices +- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money` +``` + +The skill infers which structure applies: + +- If `GLOSSARY-MAP.md` exists, read it to find contexts +- If only a root `GLOSSARY.md` exists, single context +- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved + +When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/.agents/skills/domain-modeling/SKILL.md b/.agents/skills/domain-modeling/SKILL.md new file mode 100644 index 0000000..a4438c6 --- /dev/null +++ b/.agents/skills/domain-modeling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: domain-modeling +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR. +--- + +# Domain Modeling + +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) + +## File structure + +Most repos have a single context: + +``` +/ +├── GLOSSARY.md +├── docs/ +│ └── adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: + +``` +/ +├── GLOSSARY-MAP.md +├── docs/ +│ └── adr/ ← system-wide decisions +├── src/ +│ ├── ordering/ +│ │ ├── GLOSSARY.md +│ │ └── docs/adr/ ← context-specific decisions +│ └── billing/ +│ ├── GLOSSARY.md +│ └── docs/adr/ +``` + +Create files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. + +## During the session + +### Challenge against the glossary + +When the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" + +### Sharpen fuzzy language + +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." + +### Discuss concrete scenarios + +When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. + +### Cross-reference with code + +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" + +### Update GLOSSARY.md inline + +When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md). + +`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. + +### Offer ADRs sparingly + +Only offer to create an ADR when all three are true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/.agents/skills/domain-modeling/agents/openai.yaml b/.agents/skills/domain-modeling/agents/openai.yaml new file mode 100644 index 0000000..7f1522d --- /dev/null +++ b/.agents/skills/domain-modeling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Domain Modeling" + short_description: "Build and sharpen a domain model" diff --git a/.agents/skills/git-guardrails-claude-code/SKILL.md b/.agents/skills/git-guardrails-claude-code/SKILL.md new file mode 100644 index 0000000..58bcdd8 --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/SKILL.md @@ -0,0 +1,95 @@ +--- +name: git-guardrails-claude-code +description: Set up Claude Code hooks to block dangerous git commands (push, reset --hard, clean, branch -D, etc.) before they execute. Use when user wants to prevent destructive git operations, add git safety hooks, or block git push/reset in Claude Code. +--- + +# Setup Git Guardrails + +Sets up a PreToolUse hook that intercepts and blocks dangerous git commands before Claude executes them. + +## What Gets Blocked + +- `git push` (all variants including `--force`) +- `git reset --hard` +- `git clean -f` / `git clean -fd` +- `git branch -D` +- `git checkout .` / `git restore .` + +When blocked, Claude sees a message telling it that it does not have authority to access these commands. + +## Steps + +### 1. Ask scope + +Ask the user: install for **this project only** (`.claude/settings.json`) or **all projects** (`~/.claude/settings.json`)? + +### 2. Copy the hook script + +The bundled script is at: [scripts/block-dangerous-git.sh](scripts/block-dangerous-git.sh) + +Copy it to the target location based on scope: + +- **Project**: `.claude/hooks/block-dangerous-git.sh` +- **Global**: `~/.claude/hooks/block-dangerous-git.sh` + +Make it executable with `chmod +x`. + +### 3. Add hook to settings + +Add to the appropriate settings file: + +**Project** (`.claude/settings.json`): + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous-git.sh" + } + ] + } + ] + } +} +``` + +**Global** (`~/.claude/settings.json`): + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "~/.claude/hooks/block-dangerous-git.sh" + } + ] + } + ] + } +} +``` + +If the settings file already exists, merge the hook into the existing `hooks.PreToolUse` array. Don't overwrite other settings. + +### 4. Ask about customization + +Ask if user wants to add or remove any patterns from the blocked list. Edit the copied script accordingly. + +### 5. Verify + +Run a quick test: + +```bash +echo '{"tool_input":{"command":"git push origin main"}}' | +``` + +Should exit with code 2 and print a BLOCKED message to stderr. diff --git a/.agents/skills/git-guardrails-claude-code/agents/openai.yaml b/.agents/skills/git-guardrails-claude-code/agents/openai.yaml new file mode 100644 index 0000000..3f5d756 --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Git Guardrails for Claude Code" + short_description: "Block dangerous git commands" diff --git a/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh b/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh new file mode 100644 index 0000000..c40b59c --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command') + +DANGEROUS_PATTERNS=( + "git push" + "git reset --hard" + "git clean -fd" + "git clean -f" + "git branch -D" + "git checkout \." + "git restore \." + "push --force" + "reset --hard" +) + +for pattern in "${DANGEROUS_PATTERNS[@]}"; do + if echo "$COMMAND" | grep -qE "$pattern"; then + echo "BLOCKED: '$COMMAND' matches dangerous pattern '$pattern'. The user has prevented you from doing this." >&2 + exit 2 + fi +done + +exit 0 diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md new file mode 100644 index 0000000..3947ff9 --- /dev/null +++ b/.agents/skills/grill-me/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-me +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true +--- + +Call the Skill tool with "grilling". diff --git a/.agents/skills/grill-me/agents/openai.yaml b/.agents/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/.agents/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/grill-with-docs/SKILL.md b/.agents/skills/grill-with-docs/SKILL.md new file mode 100644 index 0000000..62b9efb --- /dev/null +++ b/.agents/skills/grill-with-docs/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-with-docs +description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go. +disable-model-invocation: true +--- + +Call the Skill tool twice, for "grilling" and "domain-modeling". diff --git a/.agents/skills/grill-with-docs/agents/openai.yaml b/.agents/skills/grill-with-docs/agents/openai.yaml new file mode 100644 index 0000000..5dbe278 --- /dev/null +++ b/.agents/skills/grill-with-docs/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill with Docs" + short_description: "Grill a design and write its docs" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/grilling/SKILL.md b/.agents/skills/grilling/SKILL.md new file mode 100644 index 0000000..df69d99 --- /dev/null +++ b/.agents/skills/grilling/SKILL.md @@ -0,0 +1,30 @@ +--- +name: grilling +description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases. +--- + +Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. + +Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. + +Format a round like so: + +``` +❓ **Q1** - ****: + +➡️ + +--- + +❓ **Q2** - ****: + +➡️ +``` + +Word each question so "yes" accepts your recommended answer. + +Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. + +Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait. + +The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding. diff --git a/.agents/skills/grilling/agents/openai.yaml b/.agents/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..ddbdb96 --- /dev/null +++ b/.agents/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking a round of questions at a time" diff --git a/.agents/skills/handoff/SKILL.md b/.agents/skills/handoff/SKILL.md new file mode 100644 index 0000000..a224edc --- /dev/null +++ b/.agents/skills/handoff/SKILL.md @@ -0,0 +1,16 @@ +--- +name: handoff +description: Compact the current conversation into a handoff document for another agent to pick up. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS (`$TMPDIR`, else `/tmp`; `%TEMP%` on Windows) - not the current workspace. + +Include a "suggested skills" section in the document, naming which skills the next agent should call the Skill tool for. + +Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. + +Redact any sensitive information, such as API keys, passwords, or personally identifiable information. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the doc accordingly. diff --git a/.agents/skills/handoff/agents/openai.yaml b/.agents/skills/handoff/agents/openai.yaml new file mode 100644 index 0000000..6e1d8da --- /dev/null +++ b/.agents/skills/handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Handoff" + short_description: "Compact a conversation into a handoff" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement-spec/SKILL.md b/.agents/skills/implement-spec/SKILL.md new file mode 100644 index 0000000..1839237 --- /dev/null +++ b/.agents/skills/implement-spec/SKILL.md @@ -0,0 +1,40 @@ +--- +name: implement-spec +description: "Implement the result of /to-spec and /to-tickets in code." +disable-model-invocation: true +--- + +You have been provided a spec. This spec should have tickets associated with it, describing how to implement the spec. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +The goal is the entire spec implemented on a single **integration branch**, with every ticket resolved the way the issue tracker closes work. + +The tickets are not a list of steps. They are a **task graph** with blocking relationships between them. This means there is always a **frontier** of tickets which are ready to be grabbed. + +Communication to and from subagents should be sparse. Communicate primarily through **context pointers**: to the spec, tickets, research notes, and previous commits. Don't duplicate information already available via pointers. + +**Implementer subagents** should be run in the background where possible for maximum concurrency. + +## Steps + +1. Read the spec and tickets to understand the task graph. + +2. (optional) Use an **exploration subagent** to conduct any exploration required by the tickets - relevant codebase files or external documentation. Ensure the exploration subagent can save files - it should save its markdown notes in a directory outside the repo, accessible by all future subagents. This lets **implementer subagents** focus on implementation rather than exploration. + +3. Create the integration branch. If the issue tracker closes work through PRs, or the user asks for one, open a draft PR after the first merge in step 5 (a branch with no commits ahead of main can't open one), marked as closing the spec and tickets. + +4. Use **implementer subagents** to implement each ticket, each in its own worktree on its own branch. Each implementer subagent: + - confirms its worktree is based on the integration branch before starting, and resets onto it if not; + - calls the Skill tool with `tdd` to build the ticket; + - merges the integration branch tip into its own branch before reporting done + +5. Once an **implementer subagent** completes, merge its work to the integration branch with a **merger subagent**. + +6. If this changes the **frontier** of available tickets, kick off more **implementer subagents** to work on the new tickets. This allows for maximum concurrency. + +7. Once all tickets are complete, call the Skill tool with `code-review` on the integration branch. Fix all issues raised by the code review in a single **implementer subagent**. + +8. If a draft PR exists, mark it ready for review. Otherwise, resolve each ticket the way the issue tracker closes work, and report the integration branch. + +9. Clean up all **implementer subagent** worktrees. diff --git a/.agents/skills/implement-spec/agents/openai.yaml b/.agents/skills/implement-spec/agents/openai.yaml new file mode 100644 index 0000000..f5e91af --- /dev/null +++ b/.agents/skills/implement-spec/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement Spec" + short_description: "Implement the result of /to-spec and /to-tickets in code." +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement/SKILL.md b/.agents/skills/implement/SKILL.md new file mode 100644 index 0000000..bd49e47 --- /dev/null +++ b/.agents/skills/implement/SKILL.md @@ -0,0 +1,17 @@ +--- +name: implement +description: "Implement a piece of work based on a spec or set of tickets." +disable-model-invocation: true +--- + +Implement the work described by the user in the spec or tickets. + +If the user passes a ticket reference, fetch it from the issue tracker and state its title before starting. If the reference is ambiguous, ask. + +Call the Skill tool with "tdd" where possible, at pre-agreed seams. + +Run typechecking regularly, single test files regularly, and the full test suite once at the end. + +Once done, call the Skill tool with "code-review" to review the work. + +Commit your work to the current branch. diff --git a/.agents/skills/implement/agents/openai.yaml b/.agents/skills/implement/agents/openai.yaml new file mode 100644 index 0000000..f8794dc --- /dev/null +++ b/.agents/skills/implement/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement" + short_description: "Build work from a spec or tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..44cc7d3 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use GLOSSARY.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/loop-me/SKILL.md b/.agents/skills/loop-me/SKILL.md new file mode 100644 index 0000000..e58a474 --- /dev/null +++ b/.agents/skills/loop-me/SKILL.md @@ -0,0 +1,32 @@ +--- +name: loop-me +description: Grill me about specs for the workflows I want to build, within this workspace. +disable-model-invocation: true +argument-hint: "A workflow to design, or nothing to go find one" +--- + +Run a stateful `/grilling` session whose only output is **workflow** specs. Use the grilling discipline (relentless, a round of questions at a time, a recommended answer attached to each) aimed at the vocabulary and goal below. Create, edit, and delete specs as the grilling resolves things. + +## The loop lens + +A **loop** is a recurring pattern in the user's life: their career, their week, their morning, a single repeated activity. Picturing a life as loops within loops reveals how predictable its activities really are, which is what makes them worth **delegating**. Use the lens to find loops worth specifying, and propose ones the user hasn't noticed. + +A **workflow** is the spec of one loop, made real. You run a workflow on a loop: the loop is its running instantiation. Workflows live in `workflows/*.md` and are the source of truth. + +## Vocabulary + +A shared language, reached for only when a workflow calls for it: never a checklist. **Mandate nothing structural**: a workflow needs no AI, no checkpoint, and no schedule unless the grilling shows it does. + +- **Trigger**: what fires each run, an **event** (a new email, a new issue) or a **schedule** (every morning). Event-triggering is usually the more efficient. +- **Checkpoint**: a human-in-the-loop point where the user is asked to verify or decide. Some workflows have none and run autonomously; some use no AI at all. +- **Push right**: defer the checkpoint as far as it will go. Do maximal work before involving the human, so they are asked once, late, with everything prepared. +- **Brief**: what a checkpoint presents, a tight, decision-ready summary (what was produced, why, and a link down to the asset itself), never the raw output. The user reads a brief, not a draft. Speed of review is imperative. + +## Definition of done + +A workflow spec is done when an implementer agent could build it without asking a single question. Grill until then; nothing is done while a question remains. + +## The workspace + +- `workflows/*.md`: one spec per workflow. +- `NOTES.md`: raw notes on the user's world, the tools they use, the channels they process, and their own terminology for both. When it is empty or thin, interview them about their world before specifying anything. Sharpen fuzzy terms into canonical ones as they surface, and record them here. diff --git a/.agents/skills/loop-me/agents/openai.yaml b/.agents/skills/loop-me/agents/openai.yaml new file mode 100644 index 0000000..1a4f411 --- /dev/null +++ b/.agents/skills/loop-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Loop Me" + short_description: "Spec the workflows you want to build" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/migrate-to-shoehorn/SKILL.md b/.agents/skills/migrate-to-shoehorn/SKILL.md new file mode 100644 index 0000000..ae4f965 --- /dev/null +++ b/.agents/skills/migrate-to-shoehorn/SKILL.md @@ -0,0 +1,118 @@ +--- +name: migrate-to-shoehorn +description: Migrate test files from `as` type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace `as` in tests, or needs partial test data. +--- + +# Migrate to Shoehorn + +## Why shoehorn? + +`shoehorn` lets you pass partial data in tests while keeping TypeScript happy. It replaces `as` assertions with type-safe alternatives. + +**Test code only.** Never use shoehorn in production code. + +Problems with `as` in tests: + +- Trained not to use it +- Must manually specify target type +- Double-as (`as unknown as Type`) for intentionally wrong data + +## Install + +```bash +npm i @total-typescript/shoehorn +``` + +## Migration patterns + +### Large objects with few needed properties + +Before: + +```ts +type Request = { + body: { id: string }; + headers: Record; + cookies: Record; + // ...20 more properties +}; + +it("gets user by id", () => { + // Only care about body.id but must fake entire Request + getUser({ + body: { id: "123" }, + headers: {}, + cookies: {}, + // ...fake all 20 properties + }); +}); +``` + +After: + +```ts +import { fromPartial } from "@total-typescript/shoehorn"; + +it("gets user by id", () => { + getUser( + fromPartial({ + body: { id: "123" }, + }), + ); +}); +``` + +### `as Type` → `fromPartial()` + +Before: + +```ts +getUser({ body: { id: "123" } } as Request); +``` + +After: + +```ts +import { fromPartial } from "@total-typescript/shoehorn"; + +getUser(fromPartial({ body: { id: "123" } })); +``` + +### `as unknown as Type` → `fromAny()` + +Before: + +```ts +getUser({ body: { id: 123 } } as unknown as Request); // wrong type on purpose +``` + +After: + +```ts +import { fromAny } from "@total-typescript/shoehorn"; + +getUser(fromAny({ body: { id: 123 } })); +``` + +## When to use each + +| Function | Use case | +| --------------- | -------------------------------------------------- | +| `fromPartial()` | Pass partial data that still type-checks | +| `fromAny()` | Pass intentionally wrong data (keeps autocomplete) | +| `fromExact()` | Force full object (swap with fromPartial later) | + +## Workflow + +1. **Gather requirements** - ask user: + - What test files have `as` assertions causing problems? + - Are they dealing with large objects where only some properties matter? + - Do they need to pass intentionally wrong data for error testing? + +2. **Install and migrate**: + - [ ] Install: `npm i @total-typescript/shoehorn` + - [ ] Find test files with `as` assertions: `grep -r " as [A-Z]" --include="*.test.ts" --include="*.spec.ts"` + - [ ] Replace `as Type` with `fromPartial()` + - [ ] Replace `as unknown as Type` with `fromAny()` + - [ ] Add imports from `@total-typescript/shoehorn` + - [ ] Run type check to verify diff --git a/.agents/skills/migrate-to-shoehorn/agents/openai.yaml b/.agents/skills/migrate-to-shoehorn/agents/openai.yaml new file mode 100644 index 0000000..3bd79ee --- /dev/null +++ b/.agents/skills/migrate-to-shoehorn/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Migrate to Shoehorn" + short_description: "Replace test assertions with shoehorn" diff --git a/.agents/skills/pr/CREDITS.md b/.agents/skills/pr/CREDITS.md new file mode 100644 index 0000000..5314bda --- /dev/null +++ b/.agents/skills/pr/CREDITS.md @@ -0,0 +1,3 @@ +# Credits + +The **Summary** section's menu of visuals (pseudocode, call trees, component trees, file trees, Mermaid, diffs) and its placement guidance come from [Dex Horthy](https://github.com/dexhorthy)'s [`show-me`](https://github.com/humanlayer/humanlayer) skill, reproduced almost word for word and aimed at a diff instead of a live conversation. `pr` does not depend on `show-me` as a skill (it isn't part of this repo, and a hard dependency would break standalone installs), so the content is copied in rather than pointed at; this file is the attribution a dependency would otherwise have carried. diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md new file mode 100644 index 0000000..84dd4fb --- /dev/null +++ b/.agents/skills/pr/SKILL.md @@ -0,0 +1,170 @@ +--- +name: pr +description: "Use when writing a PR body." +metadata: + credits: + skill: show-me + author: Dex Horthy + organisation: Humanlayer + url: "https://github.com/humanlayer/skills/blob/main/plugins/show-me/skills/show-me/SKILL.md" +--- + +Use this template for writing the PR body: + +```markdown +## Summary + + + +## Evidence + +- **Before:** + **After:** + +## Merge Danger + +**Door:** + + + +**Blast Radius:** + + +``` + +## Sections + +Skip all preambles and keep prose brief. Use the user's domain language from `GLOSSARY.md`. + +### Summary + +Pick the smallest view that makes the key point clear. + +- Show logic or an algorithm as pseudocode: + +```text +on(save) + if content is unchanged + return cached result + write new content + return fresh result +``` + +- Show runtime control flow as a call tree: + +```text +submitForm + createSession + persistPrompt + launchAgent + navigateToSession +``` + +- Show UI structure as a component tree, including state and module boundaries that matter: + +```text + (apps/example/src/routes/session.tsx) + useSessionEvents() + + (packages/ui) +``` + +- Show file responsibility or a broad refactor as a shallow file tree: + +```text +src/ +├── commands/ # parses user actions +├── sessions/ # owns session state +└── transport/ # sends API requests +``` + +- Show component interaction, control flow, or data flow with Mermaid: + +```mermaid +sequenceDiagram + participant User + participant UI + participant Daemon + User->>UI: choose command + UI->>Daemon: send expanded prompt + Daemon-->>UI: stream result +``` + +- Use `diff` when the point is what changes and the surrounding shape already exists. Match the diff shape to the topic. + +For a component change: + +```diff + + useSessionEvents() + ++ + ++ +``` + +For a file-layout change: + +```diff + src/ + ├── commands/ ++│ └── show-me.ts # expands the slash command + ├── sessions/ +-└── transport.ts ++└── transport/ ++ ├── client.ts ++ └── stream.ts +``` + +For a call-tree or call-stack change: + +```diff + submitForm + createSession + persistPrompt ++ expandSkillMention + launchAgent +- navigateToSession ++ navigateToSession ++ subscribeToEvents +``` + +For a state or control-flow change: + +```diff + on(save) +- write content ++ if content is unchanged ++ return cached result ++ write new content ++ invalidate cache +``` + +- Show the whole block when most of it is new, when omitted context would hide ownership or order, or when the user needs a copyable target shape: + +```ts +function expandSkill(command: string): string { + const skillName = command.slice(1); + return `use the ${skillName} skill`; +} +``` + +#### Guidance + +Place each visual next to the short text it supports. Keep only the calls, files, props, states, and boundaries needed to answer the user's current question or the options to resolve the current discussion point. + +You may use one of these, you may use several, it is unlikely you will use all of them. Use your judgement and don't overwhelm the user. + +### Evidence + +Concrete evidence that the change works. Show a before and after. + +Screenshots are S-tier - when the environment is set up for it and the change is visual. + +Execution-based evidence is A-tier. Test results, console output. Show the exact test that now fails and passes, using pseudocode. + +### Merge Danger + +Describe whether it's a one-way or two-way door. You can walk back through two-way doors, but not one-way doors. A PR that is cheap to roll back is lower risk. Changes that involve destructive actions or hard-to-reverse decisions are one-way doors. + +The blast radius is the potential impact or scope of the changes introduced by this PR. Consider all possibilities. Examples are layout shift, breakages for consumers, mobile responsiveness, etc. diff --git a/.agents/skills/pr/agents/openai.yaml b/.agents/skills/pr/agents/openai.yaml new file mode 100644 index 0000000..48286f4 --- /dev/null +++ b/.agents/skills/pr/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "PR" + short_description: "Write a PR body that's fast to review" diff --git a/.agents/skills/prototype/LOGIC.md b/.agents/skills/prototype/LOGIC.md new file mode 100644 index 0000000..32be86a --- /dev/null +++ b/.agents/skills/prototype/LOGIC.md @@ -0,0 +1,67 @@ +# Logic Prototype + +A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases. + +Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's. + +## When this is the right shape + +- "I'm not sure if this state machine handles the edge case where X then Y." +- "Does this data model actually let me represent the case where..." +- "I want to feel out what the API should look like before writing it." +- Anything where someone wants to **press buttons and watch state change**. + +If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md). + +## Process + +### 1. State the question + +Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK. + +### 2. Isolate the logic in a portable module + +Put the actual logic (the bit that's answering the question) in a single `