Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(agents): open the record format and add the agent adapter boundary
Eren5fe749b7a1d6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94d7b0d..4007fd1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- The record format is now an open contract: `docs/format.md` documents the `.cogit/` layout, the session file and events log, the canonical message id, parents/links/branches, the conversation store, `HEAD`, the `Thought:` trailer and schema versioning, with JSON Schemas generated from the zod schemas into `docs/schema/` (`npm run schemas`; a test fails when they drift). Everything Claude Code-specific — finding and reading transcripts, parsing hook payloads, the record skill's slash name and permission rule, transcript retention — now sits behind an `AgentAdapter` in `packages/cli/src/agents/` with one implementation, `claude`; no behaviour change.+## [0.11.0] - 2026-10-26### Added- npm readiness: the README now says what cogit is, shows the map, the four read verbs (`log`, `show`, `blame`, `search`), what git sees, privacy and every setting; the package carries `repository`, `homepage`, `bugs` and keywords, and `prepack` copies the repository README and LICENSE next to `package.json` so the registry page shows them. `npm pack` still ships only the bundled CLI, the plugin manifest, the skill, the hooks and those two files.diff --git a/README.md b/README.mdindex ea46561..5d63a0e 100644--- a/README.md+++ b/README.md@@ -96,6 +96,8 @@ hash with a `Thought:` trailer.## Docs and licence-The design, the data model and the full CLI surface are in+The record format — `.cogit/` layout, message ids, events, the `Thought:` trailer — is+[docs/format.md](docs/format.md), with generated JSON Schemas in+[docs/schema/](docs/schema/). The design and the full CLI surface are in[specs/codelineage-mvp.md](specs/codelineage-mvp.md), kept up to date with the code. MIT —see [LICENSE](LICENSE).diff --git a/docs/format.md b/docs/format.mdnew file mode 100644index 0000000..04145ce--- /dev/null+++ b/docs/format.md@@ -0,0 +1,283 @@+# The cogit record format++cogit stores the **why** next to git's **what**. This document is the contract for+that record: the files, their JSON shapes, the message id, and how the graph is+read. It is written for anyone who wants to read or write `.cogit/` without+running cogit — another agent, a viewer, an import/export tool.++The JSON Schemas in [`docs/schema/`](schema/) are generated from the zod schemas+in `packages/cli/src/schema/`; they are the machine-readable form of this page.+`npm run schemas` regenerates them, and `packages/cli/test/schema-export.test.ts`+fails when a file and the code disagree.++## Where the record lives++```+<project>/.cogit/+ project.json # name, epochs, schema version (shared, versioned)+ sessions/<session-id>.json # one file per session, the notes (versioned)+ sessions/<session-id>.events.jsonl # append-only structure facts (versioned)+ conversations/<session-id>.jsonl.gz # the conversation store (local by default)+ state/<session-id>.json # hook state: turn counter (local)+ locks/ # lock files (local)+ inbox/<session-id>.json # JSON the agent hands to `session write` (local)+ HEAD # the session the next commit carries (local)+ .gitignore # which local paths stay out of git+ map.html # generated map (local)++~/.config/cogit/ # or $COGIT_HOME / $XDG_CONFIG_HOME/cogit+ config.json # global settings+ projects.json # registry of project paths+ panel.html # generated project switcher (local)+```++`COGIT_HOME` overrides the config directory (`CODELINEAGE_HOME` is still read as+a fallback). A pre-rename `.codelineage/` is migrated to `.cogit/` silently on+the first command or hook in the project.++### What travels with a git clone++Under the default `gitPolicy: "commit"`, the root `.gitignore` says nothing about+`.cogit/`; instead `.cogit/.gitignore` ignores everything except the files that+make up the record:++```gitignore+*+!.gitignore+!sessions/+!sessions/**+!project.json+```++With `shareConversations: true` it also keeps `conversations/`. Everything else+(`state/`, `locks/`, `inbox/`, `map.html`, `HEAD`, backups) stays local. Under+`gitPolicy: "ignore"` the root `.gitignore` holds `/.cogit/` and nothing travels.++## Versioning++Every versioned document has an integer `schema` field, starting at `1`:++| File | Schema |+| --- | --- |+| `project.json` | `PROJECT_SCHEMA` = 1 |+| `sessions/<id>.json` | `SESSION_SCHEMA` = 1 |+| `sessions/<id>.events.jsonl` | event shape v1 (no per-line version) |+| `config.json` | `CONFIG_SCHEMA` = 1 |+| `projects.json` | `CONFIG_SCHEMA` = 1 |+| `state/<id>.json` | `STATE_SCHEMA` = 1 |++A reader must accept an older version by migrating it step by step+(`parseVersioned` in `packages/cli/src/schema/versioned.ts`). A newer version is+read best-effort with a warning, never rejected. A reader that changes the shape+of a document must do it in code (a migration), not by hand-editing old files.++## project.json++```json+{+ "epochs": [+ {"createdAt": "2026-10-26T12:00:00.000Z", "id": "e2e", "title": "End-to-end"}+ ],+ "name": "cogit",+ "schema": 1+}+```++An **epoch** is a named stretch of work (a feature, an epic); a session points at+one through the session file's `epoch` field. `project.json` is the only file two+people write; cogit writes it with sorted keys and one epoch per line so git+merges concurrent epoch additions line by line.++## sessions/<session-id>.json++One file per session, written only by that session's owner. The session id is a+slug (`[A-Za-z0-9][A-Za-z0-9_.-]{0,127}`), normally the agent's session id.++```json+{+ "schema": 1,+ "sessionId": "9c32…",+ "agent": "claude-code",+ "title": "e2e setup flow",+ "epoch": "e2e",+ "startedAt": "2026-10-26T10:00:00.000Z",+ "updatedAt": "2026-10-26T10:30:00.000Z",+ "status": {+ "goal": "…",+ "done": ["…"],+ "pending": [{"text": "…", "needsUser": true}],+ "next": "…"+ },+ "nodes": [+ {+ "id": "h3f9a2c1b0d4",+ "parent": null,+ "kind": "message",+ "title": "Set up the e2e flow",+ "at": "2026-10-26T10:01:00.000Z",+ "branch": {"title": "…", "asked": "…", "outcome": "…", "open": ""}+ }+ ],+ "author": "Eren",+ "worktree": {"path": "/…/wt/feature", "branch": "feature"}+}+```++- `agent` is the recording agent (`claude-code` today).+- `author` is git `user.name` (else the OS user), set on the first write. Older+ records have none.+- `worktree` is set by the CLI when the session ran in a linked worktree.+- `addedAt` and `touchedAt` on a node are stamped by `session write`, never taken+ from agent input. A resent node that changes nothing keeps `touchedAt`.++### Nodes++`kind` is one of `phase`, `message`, `step`, `decision`, `question`. New records+write `message` nodes only: one per user message. The other kinds are kept for+records written before messages became the nodes; they still render.++A node carries the notes: `title`, optional `summary`, `why`, `decidedBy`+(`user` | `agent` | `agreed`), `alternatives` (`{option, why}`), `work`,+`agentDecisions`, `commits` (7–40 hex), `files`, `links`. The first message of a+branch carries `branch` (`{title, asked, outcome, open}`).++### The message id++A message node id is **stable**: `h` plus the first 12 hex characters of the+SHA-256 of the canonical JSON:++```json+{"sessionId":"<session>","uuid":"<transcript uuid or ''>","at":"<ISO time>","text":"<the text the user sent>"}+```++The JSON has that exact key order, no whitespace, and UTF-8 bytes. `uuid` is the+transcript's uuid for the user line, or `""` when there is none. The parent is+**not** part of the hash: correcting a parent never renames a message, so notes+and links keep pointing at it. `messages.ts` computes it (`messageHash`).++`m1`, `m2`, … are **display labels** derived from send order, not ids. A reader+may accept a label where an id is expected (the CLI maps it), but a stored record+should use the stable id. A record written before stable ids (schema still 1; the+`mN` ids) is renamed on load and persisted on its next `session write`.++A cross-session reference has the form `<sessionId>:<id>`: a message of an+earlier session of the same project (never across projects).++### Parents, links, roots++`parent` is the earlier message a node reacts to, `null` for a new root. A parent+must be an earlier message of the session (or a checked cross-session reference);+anything else is repaired to the previous message with a warning.++`links` are up to five earlier messages a node builds on besides its parent. On+the map, a link from the left channel is drawn as a dashed return arrow.++Siblings are ordered by when their thread began (the earliest `at` in their+subtree; `addedAt` for non-message nodes). A branch starts at a root or where a+message gains a second child.++## sessions/<session-id>.events.jsonl++Notes live in the session JSON and may be updated freely (like `git notes`).+**Structure changes** are facts and are appended here, one JSON object per line:++```json+{"at":"2026-10-26T10:05:00.000Z","type":"parent","msg":"h3f9…","target":"h2b1…","by":"agent"}+{"at":"2026-10-26T10:06:00.000Z","type":"link","msg":"h3f9…","target":"h1aa…","by":"user"}+{"at":"2026-10-26T10:07:00.000Z","type":"unlink","msg":"h3f9…","target":"h1aa…","by":"agent"}+```++- `type` is `parent`, `link` or `unlink`.+- `msg` is the message whose structure changed; `target` is the parent (or+ `null` for a root) or the other message.+- `by` is `agent` or `user`.+- `at` is when the change was recorded.++Replay is the only read rule: the **last** `parent` event for a message wins,+`link` adds a return, `unlink` removes one. A message with no `parent` event is a+root. Lines are never edited or deleted. A session with no events file (an older+record) keeps rendering from its JSON `parent`/`links`; the first+`session write` that changes its structure seeds the existing facts first.++## conversations/<session-id>.jsonl.gz++The conversation as the drill-down shows it, so it survives the agent deleting+its transcript. The file is a sequence of gzip members, append-only; each member+holds one or more JSON lines:++```json+{"uuid":"…","hash":"h3f9…","at":"…","text":"…","replies":["…"],"tools":{"commands":1,"files":["src/a.ts"],"other":2}}+```++- `uuid` is the transcript's uuid and the idempotency key: a turn already stored+ is not stored again.+- `hash` is the stable message id; a later line with the same `uuid` may add it+ to a turn stored before stable ids.+- `text`, `replies` and `tools` are redacted before writing. Tool output is+ never stored, only counts and edited file paths.++`conversations/` is **local** unless `shareConversations` is on.++## state, locks, inbox, HEAD++- `state/<id>.json`: `{schema, turns, turnsSinceUpdate, recordUpdatedAt}`. Derived+ and machine-local; losing it only restarts the turn count.+- `locks/`: lock directories for the build and for one session's writes.+- `inbox/<id>.json`: where the record skill writes its JSON before+ `cogit session write --file … --consume`. The CLI validates, redacts, merges+ and deletes it.+- `HEAD`: written by the `UserPromptSubmit` hook, local and ignored:+ `{sessionId, transcriptPath?, at?}`. It names the session the next code commit+ carries (see the trailer below). A missing or stale `HEAD` means "no trailer".++## The `Thought:` trailer++A code commit can name the message that led to it with a git trailer:++```+feat(auth): add the login form++Thought: h3f9a2c1b0d4+```++The git `prepare-commit-msg` hook adds it with `git interpret-trailers` when+`.cogit/HEAD` is fresh (within `trailerMaxAgeHours`, default 6) and the+transcript is readable; it uses the newest user message of that session. It is+skipped for merge and squash commits, a local-only record (`gitPolicy: ignore`),+and when the trailer is already present (`--amend`). A failure never blocks the+commit.++Readers must not trust the trailer alone: at read time cogit reads the trailers+back from `git log` (`%(trailers:key=Thought,valueonly)`) and attaches those+commits to their message nodes. A trailer wins over a commit hash the agent also+listed on the node.++The git `pre-commit` hook stages the current session's record+(`sessions/<id>.json` and `.events.jsonl`) when they changed **and** something+else is already staged, so a code commit carries its why and the hook never+creates a record-only commit. `git commit -a`, `git commit <paths>` and a+temporary index (`GIT_INDEX_FILE`) all work.++## What the schemas describe++| File | Describes |+| --- | --- |+| `schema/session.json` | a stored session file |+| `schema/session-input.json` | the JSON the agent sends to `session write` |+| `schema/session-event.json` | one line of the events log |+| `schema/project.json` | `project.json` |+| `schema/config.json` | the global `config.json` |+| `schema/registry.json` | the global `projects.json` |+| `schema/hook-state.json` | `state/<id>.json` |++The schemas use JSON Schema 2020-12. `session-input.json` is generated in+**input** mode (fields with defaults are optional); the others in output mode+(what a written record contains).++Regenerate after a schema change:++```bash+npm run schemas # writes docs/schema/*.json+```++`./qa` runs the drift test, so a forgotten regeneration fails the gate.diff --git a/docs/schema/config.json b/docs/schema/config.jsonnew file mode 100644index 0000000..1962db2--- /dev/null+++ b/docs/schema/config.json@@ -0,0 +1,108 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "schema": {+ "type": "number",+ "const": 1+ },+ "language": {+ "default": "auto",+ "type": "string",+ "minLength": 1,+ "maxLength": 32+ },+ "updateEveryTurns": {+ "default": 5,+ "type": "integer",+ "minimum": 1,+ "maximum": 100+ },+ "sessionEndCatchUp": {+ "default": true,+ "type": "boolean"+ },+ "catchUpModel": {+ "default": "haiku",+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "messageSummaries": {+ "default": false,+ "type": "boolean"+ },+ "startupContext": {+ "default": true,+ "type": "boolean"+ },+ "serverPort": {+ "default": 4747,+ "type": "integer",+ "minimum": 1,+ "maximum": 65535+ },+ "gitPolicy": {+ "default": "commit",+ "type": "string",+ "enum": [+ "ignore",+ "commit"+ ]+ },+ "shareConversations": {+ "default": false,+ "type": "boolean"+ },+ "recordCommit": {+ "default": "ask",+ "type": "string",+ "enum": [+ "ask",+ "auto",+ "off"+ ]+ },+ "trailerMaxAgeHours": {+ "default": 6,+ "type": "integer",+ "minimum": 1,+ "maximum": 8760+ },+ "agents": {+ "default": [+ "claude-code"+ ],+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "setupHintOff": {+ "default": [],+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "required": [+ "schema",+ "language",+ "updateEveryTurns",+ "sessionEndCatchUp",+ "catchUpModel",+ "messageSummaries",+ "startupContext",+ "serverPort",+ "gitPolicy",+ "shareConversations",+ "recordCommit",+ "trailerMaxAgeHours",+ "agents",+ "setupHintOff"+ ],+ "additionalProperties": false+}diff --git a/docs/schema/hook-state.json b/docs/schema/hook-state.jsonnew file mode 100644index 0000000..ed9df2f--- /dev/null+++ b/docs/schema/hook-state.json@@ -0,0 +1,42 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "schema": {+ "type": "number",+ "const": 1+ },+ "turns": {+ "default": 0,+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "turnsSinceUpdate": {+ "default": 0,+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "recordUpdatedAt": {+ "default": null,+ "anyOf": [+ {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "schema",+ "turns",+ "turnsSinceUpdate",+ "recordUpdatedAt"+ ],+ "additionalProperties": false+}diff --git a/docs/schema/project.json b/docs/schema/project.jsonnew file mode 100644index 0000000..8c8935d--- /dev/null+++ b/docs/schema/project.json@@ -0,0 +1,50 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "schema": {+ "type": "number",+ "const": 1+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "epochs": {+ "default": [],+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ }+ },+ "required": [+ "id",+ "title",+ "createdAt"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "schema",+ "name",+ "epochs"+ ],+ "additionalProperties": false+}diff --git a/docs/schema/registry.json b/docs/schema/registry.jsonnew file mode 100644index 0000000..ed91131--- /dev/null+++ b/docs/schema/registry.json@@ -0,0 +1,44 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "schema": {+ "type": "number",+ "const": 1+ },+ "projects": {+ "default": [],+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "minLength": 1+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "addedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ }+ },+ "required": [+ "path",+ "name",+ "addedAt"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "schema",+ "projects"+ ],+ "additionalProperties": false+}diff --git a/docs/schema/session-event.json b/docs/schema/session-event.jsonnew file mode 100644index 0000000..1a6ee8a--- /dev/null+++ b/docs/schema/session-event.json@@ -0,0 +1,50 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "at": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "type": {+ "type": "string",+ "enum": [+ "parent",+ "link",+ "unlink"+ ]+ },+ "msg": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "target": {+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$"+ },+ {+ "type": "null"+ }+ ]+ },+ "by": {+ "default": "agent",+ "type": "string",+ "enum": [+ "agent",+ "user"+ ]+ }+ },+ "required": [+ "at",+ "type",+ "msg",+ "target",+ "by"+ ],+ "additionalProperties": false+}diff --git a/docs/schema/session-input.json b/docs/schema/session-input.jsonnew file mode 100644index 0000000..505137d--- /dev/null+++ b/docs/schema/session-input.json@@ -0,0 +1,272 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "agent": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "title": {+ "type": "string",+ "maxLength": 200+ },+ "epoch": {+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "status": {+ "type": "object",+ "properties": {+ "goal": {+ "default": "",+ "type": "string",+ "maxLength": 500+ },+ "done": {+ "default": [],+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 500+ }+ },+ "pending": {+ "default": [],+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "minLength": 1,+ "maxLength": 500+ },+ "needsUser": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "text"+ ]+ }+ },+ "next": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ }+ },+ "nodes": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "parent": {+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$"+ },+ {+ "type": "null"+ }+ ]+ },+ "kind": {+ "type": "string",+ "enum": [+ "phase",+ "message",+ "step",+ "decision",+ "question"+ ]+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "summary": {+ "type": "string",+ "maxLength": 2000+ },+ "why": {+ "type": "string",+ "maxLength": 2000+ },+ "at": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "decidedBy": {+ "type": "string",+ "enum": [+ "user",+ "agent",+ "agreed"+ ]+ },+ "alternatives": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "option": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "option"+ ]+ }+ },+ "commits": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[0-9a-f]{7,40}$"+ }+ },+ "files": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ }+ },+ "links": {+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$"+ }+ },+ "branch": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "asked": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ },+ "outcome": {+ "type": "string",+ "minLength": 1,+ "maxLength": 600+ },+ "open": {+ "default": "",+ "type": "string",+ "maxLength": 300+ }+ },+ "required": [+ "title",+ "asked",+ "outcome"+ ]+ },+ "work": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ }+ },+ "agentDecisions": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ },+ "alternatives": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "option": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "option"+ ]+ }+ }+ },+ "required": [+ "title"+ ]+ }+ }+ },+ "required": [+ "id",+ "kind",+ "title"+ ]+ }+ }+ },+ "required": [+ "sessionId"+ ]+}diff --git a/docs/schema/session.json b/docs/schema/session.jsonnew file mode 100644index 0000000..4fc4d45--- /dev/null+++ b/docs/schema/session.json@@ -0,0 +1,365 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "schema": {+ "type": "number",+ "const": 1+ },+ "sessionId": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "agent": {+ "default": "claude-code",+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "title": {+ "default": "",+ "type": "string",+ "maxLength": 200+ },+ "epoch": {+ "default": null,+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "startedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "status": {+ "default": {+ "goal": "",+ "done": [],+ "pending": [],+ "next": ""+ },+ "type": "object",+ "properties": {+ "goal": {+ "default": "",+ "type": "string",+ "maxLength": 500+ },+ "done": {+ "default": [],+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 500+ }+ },+ "pending": {+ "default": [],+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "minLength": 1,+ "maxLength": 500+ },+ "needsUser": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "text",+ "needsUser"+ ],+ "additionalProperties": false+ }+ },+ "next": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "goal",+ "done",+ "pending",+ "next"+ ],+ "additionalProperties": false+ },+ "nodes": {+ "default": [],+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$"+ },+ "parent": {+ "default": null,+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$"+ },+ {+ "type": "null"+ }+ ]+ },+ "kind": {+ "type": "string",+ "enum": [+ "phase",+ "message",+ "step",+ "decision",+ "question"+ ]+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "summary": {+ "type": "string",+ "maxLength": 2000+ },+ "why": {+ "type": "string",+ "maxLength": 2000+ },+ "at": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "decidedBy": {+ "type": "string",+ "enum": [+ "user",+ "agent",+ "agreed"+ ]+ },+ "alternatives": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "option": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "option",+ "why"+ ],+ "additionalProperties": false+ }+ },+ "commits": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[0-9a-f]{7,40}$"+ }+ },+ "files": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ }+ },+ "links": {+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$"+ }+ },+ "branch": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "asked": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ },+ "outcome": {+ "type": "string",+ "minLength": 1,+ "maxLength": 600+ },+ "open": {+ "default": "",+ "type": "string",+ "maxLength": 300+ }+ },+ "required": [+ "title",+ "asked",+ "outcome",+ "open"+ ],+ "additionalProperties": false+ },+ "work": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300+ }+ },+ "agentDecisions": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ },+ "alternatives": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "option": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "why": {+ "default": "",+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "option",+ "why"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "title",+ "why"+ ],+ "additionalProperties": false+ }+ },+ "addedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "touchedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ }+ },+ "required": [+ "id",+ "parent",+ "kind",+ "title"+ ],+ "additionalProperties": false+ }+ },+ "worktree": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "minLength": 1+ },+ "branch": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "path",+ "branch"+ ],+ "additionalProperties": false+ },+ "author": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ }+ },+ "required": [+ "schema",+ "sessionId",+ "agent",+ "title",+ "epoch",+ "startedAt",+ "updatedAt",+ "status",+ "nodes"+ ],+ "additionalProperties": false+}diff --git a/package.json b/package.jsonindex 8e46690..5d7878b 100644--- a/package.json+++ b/package.json@@ -14,7 +14,8 @@"lint": "biome check .","format": "biome check --write .","typecheck": "tsc -p packages/cli --noEmit && tsc -p packages/template --noEmit",- "test": "vitest run --coverage"+ "test": "vitest run --coverage",+ "schemas": "UPDATE_SCHEMAS=1 vitest run packages/cli/test/schema-export.test.ts"},"devDependencies": {"@biomejs/biome": "^2.6.2",diff --git a/packages/cli/src/agents/claude/hooks.ts b/packages/cli/src/agents/claude/hooks.tsnew file mode 100644index 0000000..ac08fcd--- /dev/null+++ b/packages/cli/src/agents/claude/hooks.ts@@ -0,0 +1,35 @@+import { z } from "zod";+import type { HookInput } from "../types.js";++/**+ * Claude Code's hook protocol: the payload arrives on stdin as JSON, and a hook+ * answers with `hookSpecificOutput.additionalContext` so the agent sees the text.+ */++/** The common fields of a Claude Code hook input we rely on; the rest is ignored. */+export const ClaudeHookInput = z.looseObject({+ session_id: z.string(),+ cwd: z.string().optional(),+ /** Where Claude Code keeps the session's transcript (UserPromptSubmit and friends). */+ transcript_path: z.string().optional(),+ stop_hook_active: z.boolean().optional(),+ /** SessionStart only: `startup`, `resume`, `clear` or `compact`. */+ source: z.string().optional(),+});++/** Parses a hook's stdin; undefined when it is not Claude Code's payload. */+export function parseHookInput(stdin: string): HookInput | undefined {+ let raw: unknown;+ try {+ raw = JSON.parse(stdin);+ } catch {+ return undefined;+ }+ const parsed = ClaudeHookInput.safeParse(raw);+ return parsed.success ? parsed.data : undefined;+}++/** One hook answer that adds text to the agent's context, in Claude Code's shape. */+export function additionalContext(event: string, text: string): Record<string, unknown> {+ return { hookSpecificOutput: { hookEventName: event, additionalContext: text } };+}diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsnew file mode 100644index 0000000..49c7e6c--- /dev/null+++ b/packages/cli/src/agents/claude/index.ts@@ -0,0 +1,54 @@+import { type AgentAdapter, DEFAULT_AGENT } from "../types.js";+import { additionalContext, parseHookInput } from "./hooks.js";+import {+ allowSkill,+ CLAUDE_DEFAULT_RETENTION,+ readRetention,+ readSkillAllowed,+ SKILL_RULE,+ setRetention,+} from "./settings.js";+import {+ claudeConfigDir,+ collectTranscriptIds,+ collectTranscripts,+ countUserLines,+ displayTurn,+ excerpt,+ findTranscript,+ readConversation,+ readsHandoff,+} from "./transcripts.js";++/**+ * Claude Code: transcripts under `~/.claude/projects`, hooks whose payload+ * arrives on stdin, and the `cogit:record` plugin skill. The only adapter today;+ * adding another agent means adding a sibling folder, not touching callers.+ */+export const claude: AgentAdapter = {+ name: DEFAULT_AGENT,+ skill: "/cogit:record",+ skillRule: SKILL_RULE,+ projectDirEnv: "CLAUDE_PROJECT_DIR",+ pluginRootEnv: "CLAUDE_PLUGIN_ROOT",+ sessionIdEnv: "CLAUDE_SESSION_ID",+ defaultRetention: CLAUDE_DEFAULT_RETENTION,++ configDir: claudeConfigDir,+ findTranscript,+ collectTranscripts,+ collectTranscriptIds,+ readConversation,+ readsHandoff,+ countUserLines,+ displayTurn,+ excerpt,++ parseHookInput,+ additionalContext,++ readRetention,+ readSkillAllowed,+ setRetention,+ allowSkill,+};diff --git a/packages/cli/src/claude-settings.ts b/packages/cli/src/agents/claude/settings.tssimilarity index 88%rename from packages/cli/src/claude-settings.tsrename to packages/cli/src/agents/claude/settings.tsindex 289eb36..c6d74ea 100644--- a/packages/cli/src/claude-settings.ts+++ b/packages/cli/src/agents/claude/settings.ts@@ -1,7 +1,13 @@import { constants, copyFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";-import { atomicWriteJson, readJson } from "./store/fs.js";+import { atomicWriteJson, readJson } from "../../store/fs.js";+import type { FileChange } from "../types.js";++/**+ * The parts of Claude Code's own settings cogit touches: transcript retention+ * and the permission that lets the agent run the record skill without asking.+ *//** Claude Code's own default, see the cleanupPeriodDays docs. */export const CLAUDE_DEFAULT_RETENTION = 30;@@ -28,7 +34,7 @@ export async function readRetention(env: NodeJS.ProcessEnv): Promise<number | unreturn typeof days === "number" ? days : CLAUDE_DEFAULT_RETENTION;}-/** Lets the agent run the lineage skill without a permission prompt each time. */+/** Lets the agent run the record skill without a permission prompt each time. */export const SKILL_RULE = "Skill(cogit:record)";function allowList(settings: Record<string, unknown>): unknown[] | undefined {@@ -55,7 +61,7 @@ async function updateSettings(env: NodeJS.ProcessEnv,stamp: string,fn: (settings: Record<string, unknown>, file: string) => Record<string, unknown>,-): Promise<{ file: string; backup?: string }> {+): Promise<FileChange> {const file = claudeSettingsPath(env);const settings = await readSettings(file);if (!settings) throw new Error(`${file} is not a valid JSON object; not changing it`);@@ -76,17 +82,14 @@ export async function setRetention(days: number,env: NodeJS.ProcessEnv,stamp: string,-): Promise<{ file: string; backup?: string }> {+): Promise<FileChange> {if (!Number.isInteger(days) || days < 1)throw new Error("retention must be a whole number of days, at least 1");return updateSettings(env, stamp, (s) => ({ ...s, cleanupPeriodDays: days }));}/** Adds {@link SKILL_RULE} to `permissions.allow` in the user's Claude Code settings. */-export async function allowSkill(- env: NodeJS.ProcessEnv,- stamp: string,-): Promise<{ file: string; backup?: string }> {+export async function allowSkill(env: NodeJS.ProcessEnv, stamp: string): Promise<FileChange> {return updateSettings(env, stamp, (s, file) => {const allow = allowList(s);if (!allow) throw new Error(`${file} has an unexpected permissions.allow; not changing it`);diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/agents/claude/transcripts.tssimilarity index 82%rename from packages/cli/src/transcript.tsrename to packages/cli/src/agents/claude/transcripts.tsindex 2df5f4a..73939d2 100644--- a/packages/cli/src/transcript.ts+++ b/packages/cli/src/agents/claude/transcripts.ts@@ -1,18 +1,19 @@import { createReadStream } from "node:fs";import { access, readdir } from "node:fs/promises";+import { homedir } from "node:os";import { join } from "node:path";import { createInterface } from "node:readline";-import { claudeConfigDir } from "./view/transcripts.js";+import type { ChatTurn, ToolUse, UserMessage } from "../types.js";-/** One message the user typed, numbered in transcript order. */-export interface UserMessage {- /** `m1`, `m2`, …: the node id the message gets on the map. */- id: string;- /** When the user sent it, from the transcript. */- at: string;- text: string;- /** A `/clear`, a resume or a new process came between this message and the previous one. */- resumed?: boolean;+/**+ * Reading Claude Code's transcripts. A session is one JSONL file under+ * `projects/<encoded cwd>/<id>.jsonl` in the Claude home; every line is an API+ * or harness record, and only some user lines are messages the user typed.+ */++/** Where Claude Code keeps its state: `$CLAUDE_CONFIG_DIR` or `~/.claude`. */+export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env): string {+ return env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");}/**@@ -42,6 +43,46 @@ export async function findTranscript(return null;}+/**+ * Every transcript under `projects/<encoded>/*.jsonl`, by session id.+ * Best effort: an unreadable Claude home means "none found", never a failed build.+ */+export async function collectTranscripts(+ env: NodeJS.ProcessEnv = process.env,+): Promise<Map<string, string>> {+ const found = new Map<string, string>();+ const projectsDir = join(claudeConfigDir(env), "projects");++ let projectDirs;+ try {+ projectDirs = await readdir(projectsDir, { withFileTypes: true });+ } catch {+ return found;+ }++ for (const entry of projectDirs) {+ if (!entry.isDirectory()) continue;+ const dir = join(projectsDir, entry.name);+ let files: string[];+ try {+ files = await readdir(dir);+ } catch {+ continue;+ }+ for (const file of files) {+ if (file.endsWith(".jsonl")) found.set(file.slice(0, -".jsonl".length), join(dir, file));+ }+ }+ return found;+}++/** Session ids that still have a transcript. */+export async function collectTranscriptIds(+ env: NodeJS.ProcessEnv = process.env,+): Promise<Set<string>> {+ return new Set((await collectTranscripts(env)).keys());+}+/** Lines Claude Code writes as user turns that the user did not type as a message. */const NOT_A_MESSAGE =/^\s*<(bash-input|bash-stdout|bash-stderr|local-command-[a-z]+|command-message)>/;@@ -85,29 +126,6 @@ export function messageText(line: Record<string, unknown>): string | null {return text.trim() === "" ? null : text;}-/** What the agent did with tools during one turn, without their output. */-export interface ToolUse {- /** Shell commands run. */- commands: number;- /** Files written or edited, as the agent named them. */- files: string[];- /** Any other tool calls (reads, searches, web, subagents…). */- other: number;-}--/** One user message and what the agent wrote back before the next one. */-export interface ChatTurn extends UserMessage {- /** The transcript's uuid for the user line; the key of the conversation store. */- uuid?: string;- /** The message's stable id (`h…`, Story 8.5); set once the session id is known. */- hash?: string;- /** The display label (`m1`, `m2`, …); set once the session id is known. */- label?: string;- /** The agent's written replies, in order; tool output never appears here. */- replies: string[];- tools: ToolUse;-}-/** The longest text one chat entry keeps on the map; the rest is cut with a note. */export const CHAT_TEXT_LIMIT = 20_000;@@ -116,14 +134,18 @@ function capped(text: string): string {return `${text.slice(0, CHAT_TEXT_LIMIT)}\n\n[… ${text.length - CHAT_TEXT_LIMIT} more characters not shown]`;}+/** Claude Code's injected reminders, dropped from the text the map shows. */+function withoutReminders(text: string): string {+ return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");+}+/*** A turn as the map shows it: reminders the harness injected are dropped, paste* markers become a plain label, very long text is cut, and edited files are shown* relative to the project (or the worktree the session ran in).*/export function displayTurn(turn: ChatTurn, roots: string[]): ChatTurn {- const text = turn.text- .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "")+ const text = withoutReminders(turn.text).replace(/<pasted_content[^>]*>([\s\S]*?)<\/pasted_content[^>]*>/g,"\n[Pasted]\n$1\n[/Pasted]\n",@@ -288,13 +310,13 @@ function oneLine(text: string): string {* message is nothing but pastes, which then show as far as the limit allows.*/export function excerpt(text: string, max = EXCERPT_LENGTH): string {- const withoutReminders = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, " ");- const own = oneLine(withoutReminders.replace(PASTE, " "));+ const without = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, " ");+ const own = oneLine(without.replace(PASTE, " "));const cleaned =own === ""- ? `[pasted] ${oneLine([...withoutReminders.matchAll(PASTE)].map((m) => m[1]).join(" "))}`+ ? `[pasted] ${oneLine([...without.matchAll(PASTE)].map((m) => m[1]).join(" "))}`: oneLine(- withoutReminders.replace(PASTE, (_, body: string) => {+ without.replace(PASTE, (_, body: string) => {const first = oneLine(body).slice(0, 80);return ` [pasted: ${first}…] `;}),diff --git a/packages/cli/src/agents/index.ts b/packages/cli/src/agents/index.tsnew file mode 100644index 0000000..2214cf0--- /dev/null+++ b/packages/cli/src/agents/index.ts@@ -0,0 +1,25 @@+import { claude } from "./claude/index.js";+import type { AgentAdapter } from "./types.js";++/**+ * The agents cogit can record. With one entry the default is always Claude Code;+ * choosing per project comes with the second adapter. Callers ask for the+ * default and never import an implementation directly.+ */+export const AGENTS: Readonly<Record<string, AgentAdapter>> = {+ "claude-code": claude,+};++export function defaultAgent(): AgentAdapter {+ return claude;+}++export type {+ AgentAdapter,+ ChatTurn,+ FileChange,+ HookInput,+ ToolUse,+ UserMessage,+} from "./types.js";+export { DEFAULT_AGENT } from "./types.js";diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsnew file mode 100644index 0000000..034f49c--- /dev/null+++ b/packages/cli/src/agents/types.ts@@ -0,0 +1,114 @@+/**+ * The boundary between cogit's own record format and the AI agent it records.+ * Everything here is agent-neutral; the only implementation today is Claude+ * Code (`agents/claude/`). A second agent adds a folder and an entry in+ * {@link AGENTS} (`agents/index.ts`), so no caller imports an implementation+ * directly.+ */++/** The agent recorded when nothing else is chosen; `session.agent` for new records. */+export const DEFAULT_AGENT = "claude-code";++/** One message the user typed, numbered in transcript order. */+export interface UserMessage {+ /** `m1`, `m2`, …: the node id the message gets on the map. */+ id: string;+ /** When the user sent it, from the transcript. */+ at: string;+ text: string;+ /** A `/clear`, a resume or a new process came between this message and the previous one. */+ resumed?: boolean;+}++/** What the agent did with tools during one turn, without their output. */+export interface ToolUse {+ /** Shell commands run. */+ commands: number;+ /** Files written or edited, as the agent named them. */+ files: string[];+ /** Any other tool calls (reads, searches, web, subagents…). */+ other: number;+}++/** One user message and what the agent wrote back before the next one. */+export interface ChatTurn extends UserMessage {+ /** The transcript's uuid for the user line; the key of the conversation store. */+ uuid?: string;+ /** The message's stable id (`h…`, Story 8.5); set once the session id is known. */+ hash?: string;+ /** The display label (`m1`, `m2`, …); set once the session id is known. */+ label?: string;+ /** The agent's written replies, in order; tool output never appears here. */+ replies: string[];+ tools: ToolUse;+}++/** The fields of a hook payload cogit relies on, however the agent names them. */+export interface HookInput {+ session_id: string;+ cwd?: string | undefined;+ /** Where the agent keeps the session's transcript (UserPromptSubmit and friends). */+ transcript_path?: string | undefined;+ stop_hook_active?: boolean | undefined;+ /** SessionStart only: `startup`, `resume`, `clear` or `compact`. */+ source?: string | undefined;+}++/** A file cogit changed and the backup it left first. */+export interface FileChange {+ file: string;+ backup?: string;+}++/**+ * What cogit needs from an agent: where its transcripts are and how to read+ * them, how its hooks deliver a payload and receive context, and how to let the+ * agent run the record skill without asking every time.+ */+export interface AgentAdapter {+ /** The value stored in a session record's `agent` field. */+ readonly name: string;+ /** How a message asks the agent to run the record skill, e.g. `/cogit:record`. */+ readonly skill: string;+ /** The permission rule that allows the skill without a prompt. */+ readonly skillRule: string;+ /** Env var the agent sets to the project directory for hooks. */+ readonly projectDirEnv: string;+ /** Env var that points at the installed plugin (skill text uses it). */+ readonly pluginRootEnv: string;+ /** Env var the skill and commands use for the current session id. */+ readonly sessionIdEnv: string;+ /** The agent's own default transcript retention, in days. */+ readonly defaultRetention: number;++ /** Where the agent keeps its state on this machine. */+ configDir(env: NodeJS.ProcessEnv): string;+ /** Locate one session's transcript; null when there is none. */+ findTranscript(sessionId: string, env: NodeJS.ProcessEnv): Promise<string | null>;+ /** Every transcript on this machine, by session id. */+ collectTranscripts(env: NodeJS.ProcessEnv): Promise<Map<string, string>>;+ /** Session ids that still have a transcript. */+ collectTranscriptIds(env: NodeJS.ProcessEnv): Promise<Set<string>>;+ /** Each message the user typed, in order, with the agent's replies and tool counts. */+ readConversation(file: string): Promise<ChatTurn[]>;+ /** Whether the transcript shows the agent reading a handoff file (Story 8.6). */+ readsHandoff(file: string): Promise<boolean>;+ /** Counts user-role lines, to tell "no messages" from "unreadable format". */+ countUserLines(file: string): Promise<number>;+ /** A turn as the map shows it: injected text removed, long text cut, paths relative. */+ displayTurn(turn: ChatTurn, roots: string[]): ChatTurn;+ /** A short, single-line view of a message for the agent to title it. */+ excerpt(text: string, max?: number): string;+ /** Parses a hook's stdin; undefined when it is not a payload cogit understands. */+ parseHookInput(stdin: string): HookInput | undefined;+ /** Hook output that adds context for the agent, in the agent's own protocol. */+ additionalContext(event: string, text: string): Record<string, unknown>;+ /** Days the agent keeps transcripts, undefined when the setting is unreadable. */+ readRetention(env: NodeJS.ProcessEnv): Promise<number | undefined>;+ /** Whether the record skill is already allowed; undefined when unreadable. */+ readSkillAllowed(env: NodeJS.ProcessEnv): Promise<boolean | undefined>;+ /** Sets the transcript retention in the agent's settings. */+ setRetention(days: number, env: NodeJS.ProcessEnv, stamp: string): Promise<FileChange>;+ /** Allows the record skill in the agent's settings. */+ allowSkill(env: NodeJS.ProcessEnv, stamp: string): Promise<FileChange>;+}diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.tsindex 720b1cb..cabb6f8 100644--- a/packages/cli/src/commands/backfill.ts+++ b/packages/cli/src/commands/backfill.ts@@ -1,4 +1,5 @@import { spawn } from "node:child_process";+import { type ChatTurn, defaultAgent } from "../agents/index.js";import { CliError, type Io } from "../io.js";import { hashTurns, isRecorded, type SessionMessage, upgradeSessionIds } from "../messages.js";import type { Session } from "../schema/session.js";@@ -8,7 +9,6 @@ import { LockBusyError, withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { loadConfig, loadProject, loadSession } from "../store/stores.js";-import { type ChatTurn, findTranscript, readConversation } from "../transcript.js";import { sessionWrite } from "./session.js";/** How much of one message or reply goes into the prompt. */@@ -172,9 +172,10 @@ async function missingTurns(sessionId: string,env: NodeJS.ProcessEnv,): Promise<SessionMessage[]> {- const file = await findTranscript(sessionId, env);+ const agent = defaultAgent();+ const file = await agent.findTranscript(sessionId, env);if (!file) return [];- const turns = hashTurns(sessionId, await readConversation(file));+ const turns = hashTurns(sessionId, await agent.readConversation(file));const loaded = await loadSession(root, sessionId);let recorded = new Set<string>();if (loaded.found && loaded.ok) {diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 192dab1..756cb16 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,3 +1,4 @@+import { type ChatTurn, defaultAgent } from "../agents/index.js";import {findGitRoot,projectFiles,@@ -27,7 +28,6 @@ import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";-import { type ChatTurn, displayTurn, excerpt, readConversation } from "../transcript.js";import { buildFileHistory, modelSessions } from "../view/files.js";import { buildViewModel, embedViewModel } from "../view/lineage.js";import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";@@ -39,7 +39,6 @@ import {} from "../view/panel.js";import { switcherEntries } from "../view/switcher.js";import { TEMPLATE_HTML } from "../view/template.js";-import { collectTranscripts } from "../view/transcripts.js";export interface BuildOptions {dir: string;@@ -92,6 +91,7 @@ async function readTranscriptViews(root: string,io: Io,): Promise<TranscriptViews> {+ const agent = defaultAgent();const chats = new Map<string, ViewChatTurn[]>();const pending = new Map<string, ViewPendingMessage[]>();const prepared: Session[] = [];@@ -105,7 +105,7 @@ async function readTranscriptViews(let transcript: ChatTurn[] | null = null;if (file) {try {- transcript = await readConversation(file);+ transcript = await agent.readConversation(file);} catch (err) {if (recordsMessages)io.warn(@@ -129,7 +129,7 @@ async function readTranscriptViews(await appendConversationTurns(root,session.sessionId,- fresh.map((turn) => displayTurn(turn, roots)),+ fresh.map((turn) => agent.displayTurn(turn, roots)),);// Turns stored before ids were stable get theirs now, before Claude Code// deletes the transcript this hash comes from.@@ -171,7 +171,7 @@ async function readTranscriptViews(replies: kept.replies,tools: kept.tools,})- : toViewTurn(displayTurn(turn, roots));+ : toViewTurn(agent.displayTurn(turn, roots));});} else if (stored.length > 0) {// No readable transcript: the store is all that is left. Its append-only@@ -189,7 +189,7 @@ async function readTranscriptViews(id: message.hash,label: message.label,at: message.at,- title: excerpt(message.text, PENDING_TITLE_LENGTH) || "(blank message)",+ title: agent.excerpt(message.text, PENDING_TITLE_LENGTH) || "(blank message)",})),);unrecorded.set(session.sessionId, missing.length);@@ -267,7 +267,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelpaths.lock("build"),async () => {const sessions = await loadAllSessions(root, io.warn);- const transcripts = await collectTranscripts(io.env);+ const transcripts = await defaultAgent().collectTranscripts(io.env);const views = await readTranscriptViews(sessions, transcripts, root, io);// The `Thought:` trailers git holds (Story 9.4) attach commits to the// message they carry out, so the map, the file history and `blame` agreediff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex c408cb8..ede846a 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -1,13 +1,6 @@import { mkdir } from "node:fs/promises";import { basename, resolve } from "node:path";-import {- allowSkill,- CLAUDE_DEFAULT_RETENTION,- readRetention,- readSkillAllowed,- SKILL_RULE,- setRetention,-} from "../claude-settings.js";+import { defaultAgent } from "../agents/index.js";import {cogitIgnored,ensureCogitGitignore,@@ -29,6 +22,8 @@ import {updateRegistry,} from "../store/stores.js";+const agent = defaultAgent();+export interface InitOptions {name?: string;git?: GitPolicy;@@ -53,7 +48,7 @@ async function bestEffort(io: Io, what: string, fn: () => Promise<unknown>): Pro}async function askRetention(io: Io, opts: InitOptions): Promise<void> {- const current = await readRetention(io.env);+ const current = await agent.readRetention(io.env);if (current === undefined) {io.warn("could not read Claude Code settings; transcript retention left unchanged");return;@@ -65,7 +60,7 @@ async function askRetention(io: Io, opts: InitOptions): Promise<void> {return;}const picked = await io.prompt.select(- `Claude Code deletes transcripts after ${current} days${current === CLAUDE_DEFAULT_RETENTION ? " (its default)" : ""}. ` ++ `Claude Code deletes transcripts after ${current} days${current === agent.defaultRetention ? " (its default)" : ""}. ` +"Older sessions can then no longer be resumed or backfilled. Keep them longer?",[{ value: "keep", name: `Keep ${current} days` },@@ -78,15 +73,15 @@ async function askRetention(io: Io, opts: InitOptions): Promise<void> {choice = picked === "keep" ? "keep" : Number(picked);}if (choice === "keep" || choice === current) return;- const { file, backup } = await setRetention(choice, io.env, io.now());+ const { file, backup } = await agent.setRetention(choice, io.env, io.now());io.out(`Set cleanupPeriodDays to ${choice} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);}async function askSkillPermission(io: Io, opts: InitOptions): Promise<void> {- const allowed = await readSkillAllowed(io.env);+ const allowed = await agent.readSkillAllowed(io.env);if (allowed === undefined) {io.warn(- `could not read Claude Code permissions; add ${SKILL_RULE} to permissions.allow yourself`,+ `could not read Claude Code permissions; add ${agent.skillRule} to permissions.allow yourself`,);return;}@@ -95,15 +90,17 @@ async function askSkillPermission(io: Io, opts: InitOptions): Promise<void> {opts.allowSkill ??(await io.prompt.confirm("Let the agent update the lineage record without asking each time? " +- `(adds ${SKILL_RULE} to your Claude Code permissions)`,+ `(adds ${agent.skillRule} to your Claude Code permissions)`,true,));if (!allow) {- io.out(`Claude Code will ask before each lineage update; allow ${SKILL_RULE} to stop that.`);+ io.out(+ `Claude Code will ask before each lineage update; allow ${agent.skillRule} to stop that.`,+ );return;}- const { file, backup } = await allowSkill(io.env, io.now());- io.out(`Allowed ${SKILL_RULE} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);+ const { file, backup } = await agent.allowSkill(io.env, io.now());+ io.out(`Allowed ${agent.skillRule} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);}async function askLanguage(io: Io, opts: InitOptions): Promise<void> {diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex 8f66f6d..bacc137 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -1,6 +1,7 @@import { readFile, rm } from "node:fs/promises";import { userInfo } from "node:os";import { resolve } from "node:path";+import { defaultAgent } from "../agents/index.js";import { commitBetween, findGitRoot, gitUserName } from "../git.js";import { CliError, type Io } from "../io.js";import {@@ -28,9 +29,10 @@ import {loadSession,updateSession,} from "../store/stores.js";-import { countUserLines, excerpt, findTranscript, readsHandoff } from "../transcript.js";import { buildProject } from "./build.js";+const agent = defaultAgent();+export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {const chunks: Buffer[] = [];for await (const c of stream) chunks.push(typeof c === "string" ? Buffer.from(c) : c);@@ -356,8 +358,8 @@ export async function sessionShow();// A format change would otherwise look like "nothing written yet" forever.if (messages && messages.length === 0) {- const file = await findTranscript(sessionId, io.env);- const userLines = file ? await countUserLines(file).catch(() => 0) : 0;+ const file = await agent.findTranscript(sessionId, io.env);+ const userLines = file ? await agent.countUserLines(file).catch(() => 0) : 0;if (userLines > 0)view.transcriptWarning =`the transcript has ${userLines} user line(s) but none read as a message; ` +@@ -424,7 +426,7 @@ async function newMessages(id: message.hash,label: labels.get(message.hash) ?? message.label,at: message.at,- text: excerpt(message.text),+ text: agent.excerpt(message.text),...(gapMinutes === undefined ? {} : { gapMinutes }),...(message.resumed ? { resumed: true } : {}),...(committed ? { commitBetween: true } : {}),@@ -496,8 +498,8 @@ async function parentCandidates(});if (others.length === CANDIDATE_SESSIONS) break;}- const file = await findTranscript(sessionId, io.env);- const handoff = file ? await readsHandoff(file).catch(() => false) : false;+ const file = await agent.findTranscript(sessionId, io.env);+ const handoff = file ? await agent.readsHandoff(file).catch(() => false) : false;return {forMessage: { id: first.hash, label: first.label },...(handoff || CONTINUES.test(first.text) ? { continuesHint: true } : {}),diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.tsindex 095be58..01d60f5 100644--- a/packages/cli/src/hooks/run.ts+++ b/packages/cli/src/hooks/run.ts@@ -1,7 +1,7 @@import { spawn } from "node:child_process";import { existsSync } from "node:fs";import { fileURLToPath } from "node:url";-import { z } from "zod";+import { type AgentAdapter, defaultAgent, type HookInput } from "../agents/index.js";import { Slug } from "../schema/common.js";import { captureDisabled, projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";@@ -10,19 +10,9 @@ import { onSessionEnd } from "./sessionend.js";import { onSessionStart } from "./sessionstart.js";import { onStop } from "./stop.js";-/** The common fields of a Claude Code hook input we rely on. */-export const HookInput = z.looseObject({- session_id: z.string(),- cwd: z.string().optional(),- /** Where Claude Code keeps the session's transcript (UserPromptSubmit and friends). */- transcript_path: z.string().optional(),- stop_hook_active: z.boolean().optional(),- /** SessionStart only: `startup`, `resume`, `clear` or `compact`. */- source: z.string().optional(),-});-export type HookInput = z.infer<typeof HookInput>;-export interface HookContext {+ /** The agent whose hook this is: its payload format and its record skill. */+ agent: AgentAdapter;input: HookInput;sessionId: string;/** Where `.cogit/` lives: `CLAUDE_PROJECT_DIR`, else the hook's `cwd`, mapped out of a worktree. */@@ -83,10 +73,15 @@ export async function runHook(if (captureDisabled(env)) return undefined;const handler = HANDLERS[event];if (!handler) return undefined;- const input = HookInput.parse(JSON.parse(stdin));+ const agent = defaultAgent();+ const input = agent.parseHookInput(stdin);+ if (input === undefined) {+ debug(`cogit ${event} hook: unreadable hook input`);+ return undefined;+ }if (!Slug.safeParse(input.session_id).success) return undefined;// In a linked worktree both point at the worktree; the record lives in the main checkout.- const { root } = await resolveProjectRoot(env.CLAUDE_PROJECT_DIR ?? input.cwd ?? ".");+ const { root } = await resolveProjectRoot(env[agent.projectDirEnv] ?? input.cwd ?? ".");const initialized = existsSync(projectPaths(root).project);// Before `init` every hook is a no-op except SessionStart, which offers setup;// projects are never registered here.@@ -95,6 +90,7 @@ export async function runHook(const startCatchUp = (args: string[]) =>(deps.spawnDetached ?? spawnDetachedProcess)(cli, args, env);const out = await handler({+ agent,input,sessionId: input.session_id,root,diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.tsindex 199c5f3..5650863 100644--- a/packages/cli/src/hooks/sessionstart.ts+++ b/packages/cli/src/hooks/sessionstart.ts@@ -1,3 +1,4 @@+import { defaultAgent } from "../agents/index.js";import { branchesOf, type LogBranch } from "../commands/log.js";import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";import type { Session } from "../schema/session.js";@@ -7,11 +8,17 @@ import { loadAllSessions, loadConfig, loadSession } from "../store/stores.js";import { buildMessages } from "../view/lineage.js";import type { HookContext, HookOutput } from "./run.js";-export const COMPACT_REQUEST =- "cogit: this session was compacted and some of its user messages are not in the " +- "lineage record yet. Run the /cogit:record skill now; `session show` lists the " +- "messages that have no node. It records only what is missing and replies " +- '"up to date" when nothing is; do not mention this request otherwise.';+/** The compaction request, naming the skill the way the agent spells it. */+export function compactRequestText(skill: string): string {+ return (+ "cogit: this session was compacted and some of its user messages are not in the " ++ `lineage record yet. Run the ${skill} skill now; \`session show\` lists the ` ++ "messages that have no node. It records only what is missing and replies " ++ '"up to date" when nothing is; do not mention this request otherwise.'+ );+}++export const COMPACT_REQUEST = compactRequestText(defaultAgent().skill);/*** Budget for the handoff context SessionStart injects. The record is meant to@@ -27,7 +34,8 @@ export function estimateTokens(text: string): number {/** The bundled CLI, as the agent should spell it in a project without `init`. */function cli(ctx: HookContext): string {- return `node "${ctx.env.CLAUDE_PLUGIN_ROOT ?? "${CLAUDE_PLUGIN_ROOT}"}/dist/cli.js"`;+ const root = ctx.env[ctx.agent.pluginRootEnv] ?? `\${${ctx.agent.pluginRootEnv}}`;+ return `node "${root}/dist/cli.js"`;}/**@@ -66,16 +74,16 @@ export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undconst config = await loadConfig(ctx.env);// "Don't ask again in this project" lives outside the project.if (config.setupHintOff.includes(ctx.root)) return undefined;- return additionalContext(setupHint(ctx));+ return additionalContext(ctx, setupHint(ctx));}const config = await loadConfig(ctx.env);// SessionStart runs inside the chat's startup budget: opt out and it is silent.if (!config.startupContext) return undefined;- return additionalContext(await startupContext(ctx, config.recordCommit));+ return additionalContext(ctx, await startupContext(ctx, config.recordCommit));}-function additionalContext(text: string): HookOutput {- return { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } };+function additionalContext(ctx: HookContext, text: string): HookOutput {+ return ctx.agent.additionalContext("SessionStart", text);}async function compactRequest(ctx: HookContext): Promise<HookOutput | undefined> {@@ -90,7 +98,7 @@ async function compactRequest(ctx: HookContext): Promise<HookOutput | undefined>recorded = new Set(applyEvents(upgraded.nodes, events).map((node) => node.id));}if (messages.every((message) => isRecorded(recorded, message))) return undefined;- return additionalContext(COMPACT_REQUEST);+ return additionalContext(ctx, COMPACT_REQUEST);}/** One line of prose, however the record stored it. */diff --git a/packages/cli/src/hooks/stop.ts b/packages/cli/src/hooks/stop.tsindex 3130cc1..fd6f8be 100644--- a/packages/cli/src/hooks/stop.ts+++ b/packages/cli/src/hooks/stop.ts@@ -1,3 +1,4 @@+import { defaultAgent } from "../agents/index.js";import type { HookState } from "../schema/state.js";import { STATE_SCHEMA } from "../schema/state.js";import { isLockHeld } from "../store/lock.js";@@ -5,10 +6,16 @@ import { projectPaths } from "../store/paths.js";import { loadConfig, loadSession, updateState } from "../store/stores.js";import type { HookContext, HookOutput } from "./run.js";-export const UPDATE_REQUEST =- "cogit: several turns have passed since this session's lineage record was last updated. " +- "Run the /cogit:record skill now. It records only what changed and replies " +- '"up to date" when nothing did; do not mention this request otherwise.';+/** The turn-count request, naming the skill the way the agent spells it. */+export function updateRequestText(skill: string): string {+ return (+ "cogit: several turns have passed since this session's lineage record was last updated. " ++ `Run the ${skill} skill now. It records only what changed and replies ` ++ '"up to date" when nothing did; do not mention this request otherwise.'+ );+}++export const UPDATE_REQUEST = updateRequestText(defaultAgent().skill);/** One Stop: count the turn and decide whether to ask for a record update. */export function countTurn(@@ -72,5 +79,5 @@ export async function onStop(ctx: HookContext): Promise<HookOutput | undefined>{ timeoutMs: 2000 },);if (!request) return undefined;- return { hookSpecificOutput: { hookEventName: "Stop", additionalContext: UPDATE_REQUEST } };+ return ctx.agent.additionalContext("Stop", UPDATE_REQUEST);}diff --git a/packages/cli/src/messages.ts b/packages/cli/src/messages.tsindex 1e6ce2e..7a9553f 100644--- a/packages/cli/src/messages.ts+++ b/packages/cli/src/messages.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";+import { type ChatTurn, defaultAgent } from "./agents/index.js";import type { LineageNode, Session } from "./schema/session.js";import { readConversationStore } from "./store/conversations.js";-import { type ChatTurn, findTranscript, readConversation } from "./transcript.js";/*** A user message's stable id: `h` plus the first 12 hex of the SHA-256 over the@@ -63,10 +63,11 @@ export async function readSessionMessages(sessionId: string,env: NodeJS.ProcessEnv = process.env,): Promise<SessionMessage[] | null> {- const file = await findTranscript(sessionId, env);+ const agent = defaultAgent();+ const file = await agent.findTranscript(sessionId, env);if (file) {try {- const turns = await readConversation(file);+ const turns = await agent.readConversation(file);if (turns.length > 0) return hashTurns(sessionId, turns);const stored = await readConversationStore(root, sessionId);if (stored.length > 0) return storedMessages(sessionId, stored);diff --git a/packages/cli/src/schema/export.ts b/packages/cli/src/schema/export.tsnew file mode 100644index 0000000..65528cb--- /dev/null+++ b/packages/cli/src/schema/export.ts@@ -0,0 +1,48 @@+import { z } from "zod";+import { Config, Registry } from "./config.js";+import { SessionEvent } from "./events.js";+import { Project } from "./project.js";+import { Session, SessionInput } from "./session.js";+import { HookState } from "./state.js";++/**+ * The record documents published as JSON Schema under `docs/schema/` (Story+ * 9.6): enough for a tool in another language to read and write `.cogit/`+ * without running cogit. Generated from the zod schemas here, never edited by+ * hand; `npm run schemas` regenerates them and a test fails when they drift.+ */+export const SCHEMA_DOCUMENTS = {+ "session.json": Session,+ "session-input.json": SessionInput,+ "session-event.json": SessionEvent,+ "project.json": Project,+ "config.json": Config,+ "registry.json": Registry,+ "hook-state.json": HookState,+} as const;++export type SchemaDocument = keyof typeof SCHEMA_DOCUMENTS;++/** A document's JSON Schema; `session-input.json` describes what the agent sends. */+export function jsonSchema(name: SchemaDocument): object {+ return z.toJSONSchema(+ SCHEMA_DOCUMENTS[name],+ name === "session-input.json" ? { io: "input" } : {},+ );+}++/** Every published schema, keyed by its file name in `docs/schema/`. */+export function jsonSchemas(): Record<string, object> {+ return Object.fromEntries(+ (Object.keys(SCHEMA_DOCUMENTS) as SchemaDocument[]).map((name) => [name, jsonSchema(name)]),+ );+}++/** The exact file contents: pretty JSON with a trailing newline. */+export function schemaText(+ schemas: Readonly<Record<string, object>> = jsonSchemas(),+): Map<string, string> {+ return new Map(+ Object.entries(schemas).map(([name, schema]) => [name, `${JSON.stringify(schema, null, 2)}\n`]),+ );+}diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 03a180a..698c1af 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -10,6 +10,7 @@ import {import type { AddressInfo } from "node:net";import { basename, join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { defaultAgent } from "./agents/index.js";import { buildProject } from "./commands/build.js";import { defaultsPrompter, type Io } from "./io.js";import { Config } from "./schema/config.js";@@ -20,7 +21,6 @@ import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";import { buildPanel, panelSettings } from "./view/panel.js";import { editableSettings } from "./view/settings.js";-import { claudeConfigDir } from "./view/transcripts.js";/** A page nobody is looking at is a dead server after this long. */export const DEFAULT_IDLE_MS = 30 * 60 * 1000;@@ -264,7 +264,7 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>*/function startTranscriptWatch(): void {if (transcriptWatcher !== undefined) return;- const dir = join(claudeConfigDir(env), "projects");+ const dir = join(defaultAgent().configDir(env), "projects");try {transcriptWatcher = watch(dir, { persistent: false, recursive: true }, (_event, name) => {if (name === null || !name.toString().endsWith(".jsonl")) return;diff --git a/packages/cli/src/store/conversations.ts b/packages/cli/src/store/conversations.tsindex d19b066..1fdc6d0 100644--- a/packages/cli/src/store/conversations.ts+++ b/packages/cli/src/store/conversations.ts@@ -1,8 +1,8 @@import { appendFile, mkdir, readFile } from "node:fs/promises";import { dirname } from "node:path";import { constants, gunzipSync, gzipSync } from "node:zlib";+import type { ChatTurn, ToolUse } from "../agents/types.js";import { redactDeep } from "../redact.js";-import type { ChatTurn, ToolUse } from "../transcript.js";import { projectPaths } from "./paths.js";/**diff --git a/packages/cli/src/thought.ts b/packages/cli/src/thought.tsindex 12a5484..d92e59a 100644--- a/packages/cli/src/thought.ts+++ b/packages/cli/src/thought.ts@@ -2,13 +2,13 @@ import { execFile } from "node:child_process";import { access } from "node:fs/promises";import { isAbsolute, resolve } from "node:path";import { promisify } from "node:util";+import { defaultAgent } from "./agents/index.js";import { cogitIgnored, findGitRoot } from "./git.js";import { messageHash } from "./messages.js";import type { Session } from "./schema/session.js";import { readSessionHead } from "./session-git.js";import { captureDisabled } from "./store/paths.js";import { loadConfig } from "./store/stores.js";-import { findTranscript, readConversation } from "./transcript.js";const exec = promisify(execFile);@@ -78,13 +78,14 @@ export async function addThoughtTrailer(opts: TrailerOptions): Promise<boolean>// A little clock skew is fine; a cutoff that passed (or a future date) is not.if (age > config.trailerMaxAgeHours * 3_600_000 || age < -5 * 60_000) return false;+ const agent = defaultAgent();const transcript =head.transcriptPath !== undefined && (await readable(head.transcriptPath))? head.transcriptPath- : await findTranscript(head.sessionId, env);+ : await agent.findTranscript(head.sessionId, env);if (transcript === null) return false;- const turns = await readConversation(transcript);+ const turns = await agent.readConversation(transcript);const newest = turns.at(-1);if (newest === undefined) return false;diff --git a/packages/cli/src/view/transcripts.ts b/packages/cli/src/view/transcripts.tsdeleted file mode 100644index 8a192bd..0000000--- a/packages/cli/src/view/transcripts.ts+++ /dev/null@@ -1,48 +0,0 @@-import { readdir } from "node:fs/promises";-import { homedir } from "node:os";-import { join } from "node:path";--/** Where Claude Code keeps its state: `$CLAUDE_CONFIG_DIR` or `~/.claude`. */-export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env): string {- return env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");-}--/**- * Every transcript under `projects/<encoded>/*.jsonl`, by session id.- * Best effort: an unreadable Claude home means "none found", never a failed build.- */-export async function collectTranscripts(- env: NodeJS.ProcessEnv = process.env,-): Promise<Map<string, string>> {- const found = new Map<string, string>();- const projectsDir = join(claudeConfigDir(env), "projects");-- let projectDirs;- try {- projectDirs = await readdir(projectsDir, { withFileTypes: true });- } catch {- return found;- }-- for (const entry of projectDirs) {- if (!entry.isDirectory()) continue;- const dir = join(projectsDir, entry.name);- let files: string[];- try {- files = await readdir(dir);- } catch {- continue;- }- for (const file of files) {- if (file.endsWith(".jsonl")) found.set(file.slice(0, -".jsonl".length), join(dir, file));- }- }- return found;-}--/** Session ids that still have a transcript. */-export async function collectTranscriptIds(- env: NodeJS.ProcessEnv = process.env,-): Promise<Set<string>> {- return new Set((await collectTranscripts(env)).keys());-}diff --git a/packages/cli/test/agents.test.ts b/packages/cli/test/agents.test.tsnew file mode 100644index 0000000..3e92ad0--- /dev/null+++ b/packages/cli/test/agents.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";+import { AGENTS, defaultAgent } from "../src/agents/index.js";++/**+ * The adapter is the only place that knows which agent cogit records. These+ * checks keep that boundary honest: a second agent should be a new folder, not a+ * change in a caller.+ */+describe("agent adapter", () => {+ it("exposes Claude Code as the only implementation", () => {+ const agent = defaultAgent();+ expect(agent).toBe(AGENTS["claude-code"]);+ expect(agent.name).toBe("claude-code");+ expect(agent.skill).toBe("/cogit:record");+ expect(agent.skillRule).toBe("Skill(cogit:record)");+ expect(agent.sessionIdEnv).toBe("CLAUDE_SESSION_ID");+ });++ it("parses a Claude Code hook payload and refuses anything else", () => {+ const agent = defaultAgent();+ expect(+ agent.parseHookInput(JSON.stringify({ session_id: "s1", cwd: "/p", source: "startup" })),+ ).toEqual({ session_id: "s1", cwd: "/p", source: "startup" });+ expect(agent.parseHookInput("not json")).toBeUndefined();+ expect(agent.parseHookInput(JSON.stringify({ cwd: "/p" }))).toBeUndefined();+ });++ it("builds additional context in the agent's own hook shape", () => {+ expect(defaultAgent().additionalContext("Stop", "hi")).toEqual({+ hookSpecificOutput: { hookEventName: "Stop", additionalContext: "hi" },+ });+ });++ it("reads its state directory from its own env var", () => {+ expect(defaultAgent().configDir({ CLAUDE_CONFIG_DIR: "/tmp/claude" })).toBe("/tmp/claude");+ });+});diff --git a/packages/cli/test/backfill.test.ts b/packages/cli/test/backfill.test.tsindex f0d012d..148c212 100644--- a/packages/cli/test/backfill.test.ts+++ b/packages/cli/test/backfill.test.ts@@ -1,6 +1,7 @@import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";+import type { ChatTurn } from "../src/agents/types.js";import {agentRecord,backfillTail,@@ -14,7 +15,6 @@ import { messageHash } from "../src/messages.js";import type { Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";import { loadSession } from "../src/store/stores.js";-import type { ChatTurn } from "../src/transcript.js";import { envFor, fakeIo, T0, tempDir } from "./helpers.js";let dir: string;diff --git a/packages/cli/test/conversations.test.ts b/packages/cli/test/conversations.test.tsindex 1d9bdb4..ecf1092 100644--- a/packages/cli/test/conversations.test.ts+++ b/packages/cli/test/conversations.test.ts@@ -1,8 +1,8 @@import { readFile, stat, truncate } from "node:fs/promises";import { describe, expect, it } from "vitest";+import type { ChatTurn } from "../src/agents/types.js";import { appendConversationTurns, readConversationStore } from "../src/store/conversations.js";import { projectPaths } from "../src/store/paths.js";-import type { ChatTurn } from "../src/transcript.js";import { tempDir } from "./helpers.js";function turn(uuid: string | undefined, text: string, replies: string[] = []): ChatTurn {diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.tsindex c27915b..c56ed5c 100644--- a/packages/cli/test/init.test.ts+++ b/packages/cli/test/init.test.ts@@ -10,7 +10,7 @@ import {readSkillAllowed,SKILL_RULE,setRetention,-} from "../src/claude-settings.js";+} from "../src/agents/claude/settings.js";import { init } from "../src/commands/init.js";import { cogitGitignore, ensureCogitGitignore, ensureGitignore, findGitRoot } from "../src/git.js";import { loadConfig, loadProject, loadRegistry } from "../src/store/stores.js";diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex c28ef5a..9c8fc8b 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -5,7 +5,7 @@ import { type AddressInfo, createServer as createNetServer } from "node:net";import { join } from "node:path";import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";-import { readSkillAllowed } from "../src/claude-settings.js";+import { readSkillAllowed } from "../src/agents/claude/settings.js";import { createProgram } from "../src/program.js";import { globalPaths } from "../src/store/paths.js";import { loadConfig, loadProject } from "../src/store/stores.js";diff --git a/packages/cli/test/resume.test.ts b/packages/cli/test/resume.test.tsindex 2595cc1..66c7c78 100644--- a/packages/cli/test/resume.test.ts+++ b/packages/cli/test/resume.test.ts@@ -1,13 +1,13 @@import { chmod, mkdir, writeFile } from "node:fs/promises";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";+import { claudeConfigDir, collectTranscriptIds } from "../src/agents/claude/transcripts.js";import { buildProject } from "../src/commands/build.js";import { epochAdd } from "../src/commands/epoch.js";import { init } from "../src/commands/init.js";import type { Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";import { resumeCommand, shellQuote } from "../src/view/resume.js";-import { claudeConfigDir, collectTranscriptIds } from "../src/view/transcripts.js";import { envFor, fakeIo, T0, tempDir } from "./helpers.js";function session(over: Partial<Session> & { sessionId: string }): Session {diff --git a/packages/cli/test/schema-export.test.ts b/packages/cli/test/schema-export.test.tsnew file mode 100644index 0000000..b16f542--- /dev/null+++ b/packages/cli/test/schema-export.test.ts@@ -0,0 +1,45 @@+import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { jsonSchemas, SCHEMA_DOCUMENTS, schemaText } from "../src/schema/export.js";++/**+ * The published JSON Schemas must be the zod schemas themselves, or a tool+ * reading `docs/format.md` would follow a format the code no longer has.+ * Regenerate after a schema change with `npm run schemas`.+ */+const schemaDir = join(dirname(fileURLToPath(import.meta.url)), "../../../docs/schema");+const update = process.env.UPDATE_SCHEMAS === "1";++describe("docs/schema", () => {+ it("matches the zod schemas, with no extra or missing file", async () => {+ const files = schemaText();+ if (update) {+ await mkdir(schemaDir, { recursive: true });+ for (const [name, text] of files) await writeFile(join(schemaDir, name), text);+ }+ expect((await readdir(schemaDir)).sort()).toEqual([...files.keys()].sort());+ for (const [name, text] of files) {+ expect(`${name}\n${await readFile(join(schemaDir, name), "utf8")}`).toBe(`${name}\n${text}`);+ }+ });++ it("publishes one document per record type", () => {+ expect(Object.keys(SCHEMA_DOCUMENTS)).toEqual([+ "session.json",+ "session-input.json",+ "session-event.json",+ "project.json",+ "config.json",+ "registry.json",+ "hook-state.json",+ ]);+ const schemas = jsonSchemas();+ for (const schema of Object.values(schemas)) expect(schema).toMatchObject({ type: "object" });+ expect(schemas["session-input.json"]).toMatchObject({+ type: "object",+ properties: { sessionId: { type: "string" } },+ });+ });+});diff --git a/packages/cli/test/transcript.test.ts b/packages/cli/test/transcript.test.tsindex 690f398..775dff6 100644--- a/packages/cli/test/transcript.test.ts+++ b/packages/cli/test/transcript.test.ts@@ -10,7 +10,7 @@ import {readConversation,readsHandoff,readUserMessages,-} from "../src/transcript.js";+} from "../src/agents/claude/transcripts.js";import { envFor, tempDir } from "./helpers.js";const at = (m: number) => `2026-10-23T10:${String(m).padStart(2, "0")}:00.000Z`;