Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat!: keep the shared record on git refs, not in commits

Eren4fe11f273838
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 547d0f6..1ca58d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Changed
+- **Breaking:** the record no longer enters commits. Each session sits on its own ref in your repository, outside every branch, so pull requests, `git status` and `git grep` show only code and a normal clone stays small. If you shared your record before, run `git rm -r --cached .cogit/sessions` once and commit; `cogit doctor` reminds you. Old commits keep the files they had.
+- **Breaking:** the record is private unless you say otherwise. `cogit init` asks one question, "Share the session records with your team?", and no answer means no. `cogit init --git` and `cogit config git` take `share` or `ignore`.
+- `git push` sends the record of a project that shares it, in the background: it prints how many, never slows or fails the push, and only goes to `origin` or your only remote. What cannot be sent stays queued and `cogit doctor` says why.
+- The first time cogit runs in a clone of a shared project it downloads the team's records, and from then on a plain `git pull` brings them. An empty map says whether the download failed.
+- A linked worktree always uses the main checkout's record, so a session outlives its worktree.
+
+### Added
+- `cogit prune --older-than <age>` deletes old sessions here and in the repository, after listing them and asking. Your own by default, `--all` for everyone's.
+- `git clean -fdx` no longer loses a shared project's sessions: cogit puts the files back from their refs.
+
+### Removed
+- **Breaking:** the `gitPolicy` and `recordCommit` settings, the commit policy, the `pre-commit` hook and the record commit. An old `pre-commit` block is removed on its own.
## [0.31.1] - 2026-11-04
### Fixed
diff --git a/README.md b/README.md
index 375f517..5c2830f 100644
--- a/README.md
+++ b/README.md
@@ -91,9 +91,10 @@ including the option that was rejected.*
map too, with who ran them and what changed most.
- **Cheap by default**: a small side model records in the background; in our sessions it
cost about 1–2% of a session's tokens.
-- **No server, no account**: it runs on your machine. Your chats are not committed. The record
- (titles, decisions and reasons) is, so it travels with your branch; `cogit init` lets you keep
- it local instead. Key and token patterns are redacted.
+- **No server, no account**: it runs on your machine. Nothing leaves it unless you say so: `cogit
+ init` asks whether to share the record (titles, decisions and reasons) with your team. If you
+ do, `git push` sends it to your own repository, outside your branches, so it never shows up in
+ a pull request or `git status`. Your chats stay local. Key and token patterns are redacted.
- **The agent gets the context too**: a new session starts where the last one left off, and
before editing a file the agent hears what was already tried and rejected there. It works
alongside memory tools; it doesn't replace them.
@@ -139,7 +140,7 @@ cogit open .
- [Reading the lineage](docs/guide/reading-the-lineage.md): `log`, `show`, `blame`, `why`,
`search`
- [Pull requests](docs/guide/pull-requests.md): `cogit pr`
-- [Teams and git](docs/guide/teams-and-git.md): what is committed, the trailer, the hooks
+- [Teams and git](docs/guide/teams-and-git.md): what is shared, the trailer, the hooks
- [Recording and cost](docs/guide/recording-and-cost.md): who writes the record, what it
costs
- [Privacy](docs/guide/privacy.md): what is recorded and what never leaves your machine
diff --git a/docs/format.md b/docs/format.md
index fa3ea75..89fa64c 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -14,15 +14,15 @@ fails when a file and the code disagree.
```
<project>/.cogit/
- project.json # name, 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)
+ project.json # name, schema version (committed when shared)
+ sessions/<session-id>.json # one file per session, the notes
+ sessions/<session-id>.events.jsonl # append-only structure facts
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
+ .gitignore # keeps all but the marker out of commits
map.html # generated map (local)
~/.config/cogit/ # or $COGIT_HOME / $XDG_CONFIG_HOME/cogit
@@ -35,23 +35,38 @@ fails when a file and the code disagree.
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
+### What travels, and how
-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:
+In a project that shares its record the root `.gitignore` says nothing about `.cogit/`;
+`.cogit/.gitignore` keeps everything but the marker out of commits:
```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.
+The sessions travel on refs instead, one per session, in the same repository:
+
+```
+refs/cogit/sessions/<session-id> # what this clone wrote
+refs/cogit-remote/sessions/<session-id> # what the remote last said (local name)
+refs/cogit/projects/<hash>/sessions/<session-id> # a project in a repository subdirectory
+```
+
+Each ref names a tree, not a commit, so no history builds up and `git log --all` stays
+clean. The tree holds `session.json`, `events.jsonl` when it exists, and, with
+`shareConversations: true`, `conversation.jsonl.gz`. A clone receives them through one
+fetch line, `+refs/cogit/*:refs/cogit-remote/*`, which cogit adds the first time it runs
+there. To read a session without cogit:
+
+```bash
+git fetch origin '+refs/cogit/*:refs/cogit-remote/*'
+git show refs/cogit-remote/sessions/<session-id>:session.json
+```
+
+Everything else (`state/`, `locks/`, `inbox/`, `map.html`, `HEAD`, backups) stays local.
+In a private project the root `.gitignore` holds `/.cogit/` and nothing travels.
## Versioning
@@ -216,12 +231,14 @@ holds one or more JSON lines:
- `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.
+`conversations/` is **local** unless `shareConversations` is on, which adds it to the session's ref.
## state, locks, inbox, HEAD
- `state/<id>.json`: `{schema, turns, turnsSinceUpdate, recordUpdatedAt}`. Derived
and machine-local; losing it only restarts the turn count.
+- `state/record-sync.json`: what waits to be sent, what the last download or send said, and
+ each session's file stamps. Derived and machine-local; losing it costs a re-hash.
- `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
@@ -264,11 +281,9 @@ 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.
+The git `pre-push` hook queues the sessions the remote does not have yet and sends them in the
+background, with `--no-verify` so that push does not set off the hook again. A code commit
+carries only the trailer; the record never enters a commit.
## Reading a branch for a pull request
diff --git a/docs/guide/README.md b/docs/guide/README.md
index 788635e..3a41932 100644
--- a/docs/guide/README.md
+++ b/docs/guide/README.md
@@ -9,7 +9,7 @@ part in detail.
| [The map](map.md) | Sessions, branches, the "Your turn" inbox, files, search, resuming or forking a session, the people filter |
| [Reading the lineage](reading-the-lineage.md) | `log`, `show`, `blame`, `why`, `search` in the terminal, and how the agent uses them |
| [Pull requests](pull-requests.md) | `cogit pr`: a review-ready description with the decisions behind the code |
-| [Teams and git](teams-and-git.md) | What is committed, the `Thought:` trailer, the git hooks, teammates' records |
+| [Teams and git](teams-and-git.md) | What is shared, the `Thought:` trailer, the git hooks, teammates' records |
| [Recording and cost](recording-and-cost.md) | Who writes the record, the side model, what it costs |
| [Privacy](privacy.md) | What is recorded, what never is, what leaves your machine |
| [Settings](settings.md) | Every setting with a plain-language explanation |
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
index 592d41f..84906fc 100644
--- a/docs/guide/getting-started.md
+++ b/docs/guide/getting-started.md
@@ -49,13 +49,12 @@ so `cogit init --yes` runs without asking.
| Question | Default | Flag |
|---|---|---|
-| Where should the session records live? | in the repository | `--git commit\|ignore` |
+| Share the session records with your team? | no | `--git share\|ignore` |
| Keep Claude Code transcripts longer? Claude Code deletes them after 30 days by default. | keep as is | `--retention <days\|keep>` |
-The record holds your messages' titles, branch summaries, decisions and open items, so
-committing `.cogit/` shares all of that with anyone who clones the repository; keep it local
-for a public repository or private sessions. The project is named after its directory;
-`--name` overrides it.
+The record holds your messages' titles, branch summaries, decisions and open items. Sharing
+sends all of that with every `git push` to anyone who can read the repository; if the repository
+is public, that means everyone. So it stays on your machine unless you say yes.
Without asking, `init` lets the agent run the cogit skill without a permission prompt (so it
updates the record as it works), turns the plugin on for the project (writes
@@ -104,8 +103,8 @@ If you agreed to turn the plugin on for the repository, `init` wrote the project
Each teammate runs `npm install -g @cogit/cli` and `cogit init` once on their machine; `init` sees
the project is already set up, registers it on their machine and installs the git hooks in
-their clone. With the default commit policy,
-everyone's records travel with the branch. See [Teams and git](teams-and-git.md).
+their clone. In a project that shares its record, everyone's sessions then arrive with `git pull`.
+See [Teams and git](teams-and-git.md).
## Stop recording
diff --git a/docs/guide/privacy.md b/docs/guide/privacy.md
index cfc7f6e..1c6c2ce 100644
--- a/docs/guide/privacy.md
+++ b/docs/guide/privacy.md
@@ -13,22 +13,33 @@ and a redaction pass for key and token patterns runs over everything the map wri
## What stays on your machine
- **The raw conversation.** `.cogit/conversations/` keeps a copy of each transcript so the map
- still works after Claude Code deletes it. It stays out of git unless you turn
- `shareConversations` on. Turn it on only if everyone who can read the repository may read
- your chats, and never in a public repository.
-- **The map** (`.cogit/map.html`) shows the conversation, so it is never committed.
+ still works after Claude Code deletes it. It is never sent unless you turn
+ `shareConversations` on in a project that shares its record. Turn it on only if everyone who
+ can read the repository may read your chats, and never in a public repository.
+- **The map** (`.cogit/map.html`) shows the conversation, so it is never committed or sent.
- **Local state:** the inbox, the map view, locks.
+- **The record itself**, unless you choose to share it. `cogit init` asks, and no answer means
+ no. Private is the default for public and private repositories alike.
-## What git carries
+## What sharing sends
-Under the default commit policy, the record travels with your branch. Anyone who can read the
-repository can read the titles, decisions and reasons. If the repository is public, so is the
-record. Choose the ignore policy for a project where that is not wanted; see
-[Teams and git](teams-and-git.md).
+If you share the record, `git push` also sends it to your own repository, on refs outside your
+branches (`refs/cogit/`). It does not appear in the file tree, in pull requests or on GitHub's
+pages, but **hidden is not private**: anyone who can read the repository can download the titles,
+decisions and reasons with one command. If the repository is public, so is the record. Each push
+prints how many session records it sends. A repository you share in while it is private shows
+that record to everyone if it later goes public.
`cogit pr` reads only the record, never the conversation, so its output is safe to paste into
a public pull request.
+## Deleting
+
+`cogit prune --older-than 1y` deletes your old sessions here and in the repository. Use it to
+keep the record small, not to take back a secret: copies already on teammates' machines stay
+until they delete them, and a host can keep deleted data for a while. To remove a secret, treat
+it as leaked and rotate it.
+
## Transcripts
Claude Code deletes transcripts after `cleanupPeriodDays` (30 days by default). `init` offers
diff --git a/docs/guide/pull-requests.md b/docs/guide/pull-requests.md
index 7782254..9192e0f 100644
--- a/docs/guide/pull-requests.md
+++ b/docs/guide/pull-requests.md
@@ -47,7 +47,7 @@ Commits:
## Dig deeper
- `cogit show <message-hash>` opens a thought: its decisions, the options it rejected, and the conversation turn for whoever has it locally.
- `cogit show <sha>` opens the thought behind a commit.
-- This branch commits its record, so a reviewer who checks it out gets the same `cogit show` output.
+- This project shares its record, so a reviewer with cogit in their clone gets the same `cogit show` output once the author has pushed.
```
## Safe on a public pull request
@@ -57,10 +57,10 @@ text or your prompts as written.
## For the reviewer
-Under the default commit policy the record travels with the branch, so a reviewer who checks
-it out and has cogit installed can run `cogit show <hash>` or open the map on the same
-messages. Under the ignore policy the description says the hashes resolve only on the author's
-machine.
+In a project that shares its record, a reviewer with cogit installed can run `cogit show <hash>`
+or open the map on the same messages once the author has pushed. A pull request from a fork is
+the exception: the record went to the fork, so its hashes resolve only there. In a project that
+keeps its record private, the description says the hashes resolve only on the author's machine.
cogit does not promise a faster review; nothing has measured that yet. It hands the reviewer
the intent they would otherwise have to ask for in comments.
diff --git a/docs/guide/settings.md b/docs/guide/settings.md
index 3750219..b924ca5 100644
--- a/docs/guide/settings.md
+++ b/docs/guide/settings.md
@@ -76,17 +76,9 @@ The language the record is written in. With auto, it follows the language of the
`shareConversations` · default `false`
-**Commit the raw chat text too, not only the session record (off: chat stays local).**
+**Send the raw chat text too, not only the session record (off: chat stays local).**
-Also commit the raw chat text, not only the record. Leave it off to keep conversations on your machine while the record still travels with the branch.
-
-### Commit the record
-
-`recordCommit` · default `ask`
-
-**ask, auto or off: what to do with the last messages after the last code commit.**
-
-What happens to record changes made after your last code commit: ask you next time, commit them automatically, or leave them for you to commit.
+In a project that shares its record, also send the raw chat text. Leave it off to keep conversations on your machine while teammates still see titles, decisions and reasons.
## Only through `cogit config`
@@ -124,14 +116,6 @@ When a session ends, the side model records whatever nobody got to, then reads t
The small model behind every side record: every few turns in mixed mode, all the time in side mode, and at session end. Haiku is cheap and good enough for titles, parents and short decisions.
-### Git policy
-
-`gitPolicy` · default `commit`
-
-**What `cogit init` offers a new project: commit the record to git, or ignore it.**
-
-Only the default for new projects: each project answers it during `cogit init`. `cogit config git` shows the current project's policy and `cogit config git commit` or `ignore` switches it.
-
### Agents
`agents` · default `claude-code`
diff --git a/docs/guide/teams-and-git.md b/docs/guide/teams-and-git.md
index 338cc9a..1aab0af 100644
--- a/docs/guide/teams-and-git.md
+++ b/docs/guide/teams-and-git.md
@@ -1,39 +1,90 @@
# Teams and git
-cogit keeps its record in `.cogit/` next to your code and ties it to your commits.
+cogit keeps its record in `.cogit/` on your machine and ties it to your commits. The record never
+enters a commit, so your branches, pull requests and `git status` show only code.
-## What is committed
+## What is shared
-`init` asks whether to commit the record. The answer is per project.
+`init` asks whether to share the record with your team. The answer is per project, and no answer
+means no.
-| | Commit (default) | Ignore |
+| | Shared | Private (default) |
|---|---|---|
-| `.cogit/sessions/`, `.cogit/project.json` (the record) | committed | ignored |
-| `.cogit/conversations/` (raw chat) | ignored, unless `shareConversations` is on | ignored |
+| `.cogit/sessions/` (the record) | sent with `git push`, outside your branches | stays here |
+| `.cogit/conversations/` (raw chat) | stays here, unless `shareConversations` is on | stays here |
+| `.cogit/project.json`, `.cogit/.gitignore` | committed: they mark the project for a clone | ignored |
| Local state: map, inbox, locks, `HEAD` | ignored | ignored |
-Under the commit policy, `.cogit/.gitignore` decides what stays local. Under the ignore policy,
-one `/.cogit/` line in the root `.gitignore` hides all of it.
+In a private project, one `/.cogit/` line in the root `.gitignore` hides all of it.
```bash
-cogit config git # this project's policy
-cogit config git commit # switch it
+cogit config git # this project's setting
+cogit config git share # switch it
cogit config git ignore
```
-Switching never deletes a record; switching to ignore leaves what git already tracks alone.
+Switching never deletes a record. Switching to `ignore` stops sending; what the repository already
+holds stays there until you `cogit prune` it.
+
+### Where it goes
+
+Each session sits on its own ref in your repository: `refs/cogit/sessions/<id>`. A normal clone
+does not download them, so someone without cogit gets a clone of the usual size and never sees
+them. They do not appear in `git log --all` or `git branch`, nor in a pull request or on GitHub's
+pages, which also means the record cannot be read there: reading it takes cogit.
+
+- **Sending:** `git push` to `origin` (or your only remote) prints how many records it sends and
+ sends them in the background. It never slows the push, never asks for anything and never fails
+ it. What could not be sent stays queued, the next session start tries again, and `cogit doctor`
+ tells you why. Pushing to any other remote, such as a deploy target, sends nothing.
+- **Receiving:** the first time cogit runs in a clone, it adds one fetch line to that clone's
+ `.git/config` and downloads the team's records, showing progress in a terminal. After that a
+ plain `git pull` brings them, even when no code changed. Each new record adds a line to its
+ output.
+- **Your own unsent work:** a pull never overwrites a session you have changed and not sent. A
+ `git clean -fdx` does not lose anything either: the refs hold a copy and cogit puts the files back.
+- **Only your own sessions go out:** a session is sent by the person it is stamped with.
+
+Records follow the repository, not the branch: a session stays on the map after its branch is
+deleted, and shows which branch it ran on.
+
+A pull request from a fork brings the code but not the record, which went to the fork.
+
+### Deleting old sessions
+
+```bash
+cogit prune --older-than 1y --dry-run # what would go
+cogit prune --older-than 1y # lists them, asks, then deletes
+```
+
+It deletes your own sessions here and in the repository, and only when you run it; add `--all` to
+include teammates'. It cannot be undone. Copies already on teammates' machines stay until they
+delete them. If the repository cannot be reached, nothing is deleted.
+
+### Coming from a version that committed the record
+
+Older versions committed `.cogit/sessions/`. After upgrading, your files stay put and the next
+`git push` sends them. Stop tracking them once, in one clone, or they keep showing in `git status`:
+
+```bash
+git rm -r --cached .cogit/sessions
+git commit -m "chore: stop tracking the cogit record"
+```
+
+Old commits keep the files they had, so the repository's size does not shrink. `cogit doctor`
+reminds you until this is done.
## The git hooks
-`init` adds a block to two git hooks in your clone (and follows `core.hooksPath`, so Husky
-setups work). The block never fails a commit.
+`init` adds a block to three git hooks in your clone (and follows `core.hooksPath`, so Husky
+setups work). The block never fails a commit or a push.
- **`prepare-commit-msg`** adds a `Thought: h<id>` trailer naming the message the commit came
from: the newest message of the current session. It is skipped for merges and squashes, while
a rebase or cherry-pick replays old commits, and when the last message is older than
`trailerMaxAgeHours` (6 hours), since such a commit is probably not about that message.
-- **`pre-commit`** stages the current session's record with your code commit. It never creates
- a record-only commit.
+- **`post-commit`** starts the commit's Shape in the background.
+- **`pre-push`** sends the session records of a project that shares them.
### Rebase and squash
@@ -47,9 +98,6 @@ The link names a message, not a commit hash, so it follows the commit message:
details" in the repository's settings. A squash that keeps only the title has no link to read;
the messages stay in the record, and `cogit search` still finds them.
-`recordCommit` decides what happens to messages recorded after your last code commit: `ask`
-(the next session start offers to commit them), `auto`, or `off`.
-
```bash
cogit hooks install # add or refresh the block
cogit hooks uninstall # remove only the cogit block
@@ -57,11 +105,11 @@ cogit hooks uninstall # remove only the cogit block
## Working as a team
-1. One person runs `cogit init` with the team setup and commits `.cogit/` and
- `.claude/settings.json`.
+1. One person runs `cogit init`, answers yes to sharing, and commits `.cogit/.gitignore`,
+ `.cogit/project.json` and `.claude/settings.json`.
2. Everyone installs the CLI and runs `cogit init` once in their clone. It sees the project is
set up, registers it on their machine and installs the git hooks.
-3. Each person's sessions are committed with their code. After a pull, teammates' sessions
+3. Each person's sessions go out with their `git push`. After a pull, teammates' sessions
appear on the map with their author, most recent first.
A session belongs to the person who recorded it: cogit stamps it with their git `user.name`
@@ -77,6 +125,5 @@ teammates see the record (titles, decisions, reasons) but not the chat itself.
## Worktrees
-Sessions in a linked git worktree (`claude -w`) record into the main checkout's `.cogit/`
-under the ignore policy, and into the worktree's own copy under the commit policy. The
-details show which worktree and branch a session ran in.
+Sessions in a linked git worktree (`claude -w`) record into the main checkout's `.cogit/`, so
+they outlive the worktree. The details show which worktree and branch a session ran in.
diff --git a/docs/schema/config.json b/docs/schema/config.json
index 6d2a5d3..0e5dd7e 100644
--- a/docs/schema/config.json
+++ b/docs/schema/config.json
@@ -74,27 +74,10 @@
"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",
@@ -150,9 +133,7 @@
"startupContext",
"recordHeadless",
"serverPort",
- "gitPolicy",
"shareConversations",
- "recordCommit",
"trailerMaxAgeHours",
"bigChangeLines",
"tryBeforeNotes",
diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.ts
index 5b60c9a..e2931d6 100644
--- a/packages/cli/src/commands/backfill.ts
+++ b/packages/cli/src/commands/backfill.ts
@@ -3,7 +3,6 @@ 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 { LineageNodeInput, type Session, Status } from "../schema/session.js";
-import { maybeAutoCommit } from "../session-git.js";
import { applyEvents, readEvents } from "../store/events.js";
import { LockBusyError, withLock } from "../store/lock.js";
import { projectPaths } from "../store/paths.js";
@@ -357,8 +356,6 @@ export async function backfillTail(
if (turns.length === 0) {
io.out(`session ${sessionId} has nothing left to record`);
if (opts.close === true) await closeSession(root, sessionId, io);
- // Story 9.3: `recordCommit: auto` still commits what an earlier update wrote.
- await maybeAutoCommit(root, sessionId, io.env);
return;
}
@@ -388,5 +385,4 @@ export async function backfillTail(
if (opts.close === true) await closeSession(root, sessionId, io);
// The session end wrote the last messages after the last code commit; auto
// mode commits exactly those record files now (Story 9.3).
- await maybeAutoCommit(root, sessionId, io.env);
}
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 42d44c0..f09a81c 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -19,6 +19,7 @@ import {
storedMessages,
upgradeSessionIds,
} from "../messages.js";
+import { reconcileRecords, recordSyncStatus } from "../record-sync.js";
import { redactDeep } from "../redact.js";
import { Slug } from "../schema/common.js";
import { SESSION_SCHEMA, type Session } from "../schema/session.js";
@@ -297,12 +298,14 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
const paths = projectPaths(root);
const config = await loadConfig(io.env);
- // Projects initialized before the conversation store get the privacy rules on
- // their next build; an unwritable record must never fail the map.
+ // Projects set up by an older version get the current rules on their next build,
+ // and every build keeps the refs and the files in step. An unwritable record or
+ // a failing git must never fail the map.
try {
- await refreshCogitGitignore(root, config.shareConversations);
+ await refreshCogitGitignore(root);
+ await reconcileRecords(root, io.env);
} catch (err) {
- io.warn(`could not update .cogit/.gitignore: ${(err as Error).message}`);
+ io.warn(`could not update the shared record: ${(err as Error).message}`);
}
// The map's switcher (8.12) and the panel read the same project list; collect
// it once. A broken registry is a warning: it must never fail the map.
@@ -336,6 +339,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
// Story 10.3: each message carries the numstat totals of its linked
// commits. A project outside git simply has no numbers to show.
const withChanges = attachChanges(withThoughts, commits.changes);
+ const sync = await recordSyncStatus(root, io.env).catch(() => undefined);
const built = buildViewModel({
project: project.data,
sessions: withChanges,
@@ -355,6 +359,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
unrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,
});
built.switcher = switcher;
+ if (sync?.downloadError !== undefined && !sync.downloaded) built.recordDownloadFailed = true;
const view = await readMapView(root);
built.rowWidths = view.rowWidths;
built.openSessions = view.open;
diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.ts
index 874e9d2..1de511c 100644
--- a/packages/cli/src/commands/config.ts
+++ b/packages/cli/src/commands/config.ts
@@ -7,8 +7,8 @@ import {
} from "../git.js";
import { installGitHooks } from "../git-hooks.js";
import { CliError, type Io } from "../io.js";
+import { addRecordRefspec } from "../record-sync.js";
import { Config, type RegistryEntry } from "../schema/config.js";
-import { refreshShareConversations } from "../share.js";
import { isDirectory } from "../store/fs.js";
import { resolveProjectRoot } from "../store/root.js";
import {
@@ -73,9 +73,6 @@ export async function configSet(key: string, raw: string, io: Io): Promise<void>
}
const name = canonicalKey(key);
await updateConfig((c) => ({ ...c, [name]: next.data[key] }), io.env);
- // Sharing the raw chat changes the project ignore files, not just the config.
- if (name === "shareConversations")
- await refreshShareConversations(io.env, next.data.shareConversations);
io.out(`${name} = ${JSON.stringify(next.data[key])}`);
}
@@ -85,14 +82,14 @@ export async function configGitShow(dir: string, io: Io): Promise<void> {
const project = await loadProject(root);
if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);
if (!project.ok) throw new CliError(project.error);
- const policy: GitPolicy = (await cogitIgnored(root)) ? "ignore" : "commit";
+ const policy: GitPolicy = (await cogitIgnored(root)) ? "ignore" : "share";
io.out(`Git policy for ${project.data.name}: ${policy}`);
}
/**
- * `cogit config git commit|ignore` (Story 9.3): switches an existing project.
- * Both ignore files are edited; no record file is ever deleted, so switching to
- * `ignore` leaves what git already tracks alone.
+ * `cogit config git share|ignore`: switches an existing project. Both ignore files
+ * are edited and no record file is ever deleted. Switching to `ignore` stops
+ * sending; what the remote already holds stays there until `cogit prune`.
*/
export async function configGit(dir: string, policy: GitPolicy, io: Io): Promise<void> {
const { root } = await resolveProjectRoot(dir);
@@ -103,9 +100,9 @@ export async function configGit(dir: string, policy: GitPolicy, io: Io): Promise
throw new CliError(`${root} is not in a git repository`);
const added = await ensureGitignore(root, policy);
- const config = await loadConfig(io.env);
- await ensureCogitGitignore(root, policy, config.shareConversations);
+ await ensureCogitGitignore(root, policy);
await installGitHooks(root);
+ if (policy === "share") await addRecordRefspec(root, io.env);
io.out(`Git policy for ${project.data.name}: ${policy}`);
if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);
}
diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts
index 7e07700..3904c06 100644
--- a/packages/cli/src/commands/doctor.ts
+++ b/packages/cli/src/commands/doctor.ts
@@ -5,9 +5,10 @@ import type { AgentAdapter } from "../agents/index.js";
import { defaultAgent } from "../agents/index.js";
import { compareVersions, versionNotice } from "../cli-version.js";
import { cogitIgnored, findGitRoot, gitHooksDir, gitUserEmail, gitUserName } from "../git.js";
-import { BLOCK_START, hookBlock } from "../git-hooks.js";
+import { BLOCK_START, GIT_HOOK_EVENTS, hookBlock } from "../git-hooks.js";
import type { Io } from "../io.js";
import { hashTurns, isRecorded, upgradeSessionIds } from "../messages.js";
+import { recordSyncStatus, trackedRecordFiles } from "../record-sync.js";
import type { Session } from "../schema/session.js";
import { checkHealth } from "../server.js";
import { applyEvents, readEvents } from "../store/events.js";
@@ -300,6 +301,45 @@ const CHECK_SPECS: CheckSpec[] = [
},
},
+ {
+ id: "record",
+ run: async (ctx) => {
+ const tracked = await trackedRecordFiles(ctx.root, ctx.env);
+ if (tracked > 0)
+ return {
+ id: "record",
+ status: "warn",
+ message: `git still tracks ${tracked} session file${tracked === 1 ? "" : "s"} an older version committed`,
+ fix: "git rm -r --cached .cogit/sessions, then commit",
+ };
+ const sync = await recordSyncStatus(ctx.root, ctx.env);
+ if (!sync.sharing)
+ return { id: "record", status: "ok", message: "the record stays on this machine" };
+ if (sync.sendError !== undefined)
+ return {
+ id: "record",
+ status: "warn",
+ message: `${sync.pending} session record${sync.pending === 1 ? "" : "s"} could not be sent: ${sync.sendError}`,
+ fix: "check your access to the remote; the next session start tries again",
+ };
+ if (sync.downloadError !== undefined && !sync.downloaded)
+ return {
+ id: "record",
+ status: "warn",
+ message: `the team's records could not be downloaded: ${sync.downloadError}`,
+ fix: "cogit open",
+ };
+ return {
+ id: "record",
+ status: "ok",
+ message:
+ sync.remote === undefined
+ ? "the record is shared, but this repository has no remote yet"
+ : `the record is shared through ${sync.remote}`,
+ };
+ },
+ },
+
{
id: "skill",
run: async (ctx) => {
@@ -455,7 +495,7 @@ async function hookProblems(ctx: DoctorContext): Promise<string[]> {
const dir = await gitHooksDir(gitRoot);
if (dir === undefined) return ["the git hooks directory could not be found"];
const problems: string[] = [];
- for (const event of ["prepare-commit-msg", "pre-commit", "post-commit"] as const) {
+ for (const event of GIT_HOOK_EVENTS) {
const text = await readFile(join(dir, event), "utf8").catch(() => undefined);
if (text === undefined || !text.includes(BLOCK_START)) {
problems.push(`the ${event} hook is missing`);
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 2993e6d..c2cd72f 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -13,6 +13,7 @@ import {
} from "../git.js";
import { installGitHooks } from "../git-hooks.js";
import { CliError, type Io } from "../io.js";
+import { addRecordRefspec } from "../record-sync.js";
import { readJson } from "../store/fs.js";
import { migrateProject } from "../store/migrate.js";
import { globalPaths, projectPaths } from "../store/paths.js";
@@ -52,25 +53,26 @@ async function bestEffort(io: Io, what: string, fn: () => Promise<unknown>): Pro
}
/**
- * Where the record lives. This one changes what a clone contains — the record
- * holds titles, summaries, decisions and open items — so it is asked with a
- * note, in a colour that stands apart from the routine questions.
+ * Whether the team sees the record. This one decides what leaves the machine — the
+ * record holds titles, summaries, decisions and open items — so it is asked with a
+ * note, in a colour that stands apart from the routine questions. No answer keeps
+ * the record here: nothing is ever published by default.
*/
-async function askGitPolicy(io: Io, fallback: GitPolicy): Promise<GitPolicy> {
+async function askGitPolicy(io: Io): Promise<GitPolicy> {
const paint = (text: string): string =>
process.stdout.isTTY === true ? styleText("yellow", text) : text;
io.out(
paint("⚠ Session records carry your messages' titles, summaries, decisions and open items."),
);
- io.out(paint(" Committing .cogit/ shares all of that with anyone who clones this repository."));
- io.out(paint(" Keep it local if the repository is public or the sessions are private."));
+ io.out(paint(" Sharing sends them with every `git push` to anyone who can read this"));
+ io.out(paint(" repository. If it is public, that means everyone."));
return io.prompt.select<GitPolicy>(
- "Where should the session records live?",
+ "Share the session records with your team?",
[
- { value: "commit", name: "In the repository — shared with whoever clones it" },
- { value: "ignore", name: "Only on this machine — private" },
+ { value: "ignore", name: "No — keep them on this machine" },
+ { value: "share", name: "Yes — send them with `git push`" },
],
- fallback,
+ "ignore",
);
}
@@ -160,40 +162,40 @@ export async function register(io: Io, root: string, name: string): Promise<void
}
/**
- * Applies a policy to the two ignore files and, under `commit`, installs the git
- * hooks that carry the current session's record and link it to the commit
- * (Stories 9.3, 9.4). Each step is best-effort: a read-only `.gitignore` or a
- * repository git will not report hooks for must never fail setup.
+ * Applies a policy to the two ignore files and installs the git hooks that link
+ * commits to messages and send the record (Stories 9.3, 9.4). Each step is
+ * best-effort: a read-only `.gitignore` or a repository git will not report hooks
+ * for must never fail setup.
*/
-async function applyGitPolicy(
- io: Io,
- root: string,
- policy: GitPolicy,
- shareConversations: boolean,
-): Promise<void> {
+async function applyGitPolicy(io: Io, root: string, policy: GitPolicy): Promise<void> {
const added: string[] = [];
await bestEffort(io, "could not update .gitignore", async () => {
added.push(...(await ensureGitignore(root, policy)));
});
if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);
await bestEffort(io, "could not write .cogit/.gitignore", () =>
- ensureCogitGitignore(root, policy, shareConversations),
+ ensureCogitGitignore(root, policy),
);
- // Every policy: the trailer links commits locally; staging follows the policy.
+ // Every policy: the trailer links commits locally; sending follows the policy.
await bestEffort(io, "could not install the git hooks", () => installGitHooks(root));
+ if (policy === "share")
+ await bestEffort(io, "could not set up fetching the records", () =>
+ addRecordRefspec(root, io.env),
+ );
}
/**
* Brings an already initialized project up to date: every repository gets the
- * hooks, one that commits its records also the new `.cogit/.gitignore`, without
- * changing the policy the user chose at setup.
+ * hooks, a shared one also the current `.cogit/.gitignore`, without changing the
+ * policy the project chose at setup. A teammate's first `init` in a clone lands here.
*/
async function refreshGitIntegration(io: Io, root: string): Promise<void> {
if ((await findGitRoot(root)) === undefined) return;
await bestEffort(io, "could not refresh the git integration", async () => {
- if (!(await cogitIgnored(root)))
- await refreshCogitGitignore(root, (await loadConfig(io.env)).shareConversations);
await installGitHooks(root);
+ if (await cogitIgnored(root)) return;
+ await refreshCogitGitignore(root);
+ await addRecordRefspec(root, io.env);
});
}
@@ -238,8 +240,7 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<void
const name = opts.name ?? basename(root);
const config = await loadConfig(io.env);
- // Story 9.3: the record travels with the repository by default.
- const policy: GitPolicy = opts.git ?? (await askGitPolicy(io, config.gitPolicy));
+ const policy: GitPolicy = opts.git ?? (await askGitPolicy(io));
await askRetention(io, opts);
await askSkillPermission(io, opts);
@@ -248,13 +249,19 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<void
await updateProject(root, (cur) => cur ?? { schema: 1, name });
await mkdir(projectPaths(root).sessions, { recursive: true });
- await applyGitPolicy(io, root, policy, config.shareConversations);
+ await applyGitPolicy(io, root, policy);
await register(io, root, name);
+ if (policy === "share") {
+ io.out("Session records will be sent with `git push` to whoever can read this repository.");
+ io.out(
+ "Commit .cogit/.gitignore and .cogit/project.json so your team's clones share them too.",
+ );
+ }
io.out(
- config.shareConversations
- ? "Conversations are stored in .cogit/conversations/ (shared through git: shareConversations is on)."
- : "Conversations are stored in .cogit/conversations/ (kept out of git; turn on shareConversations to share them).",
+ policy === "share" && config.shareConversations
+ ? "Conversations are stored in .cogit/conversations/ (sent too: shareConversations is on)."
+ : "Conversations are stored in .cogit/conversations/ and stay on this machine.",
);
io.out(`Initialized ${name} in ${projectPaths(root).base}`);
const installed = await agent.readPluginInstalled(io.env).catch(() => undefined);
diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts
index 5048c56..14ad02b 100644
--- a/packages/cli/src/commands/open.ts
+++ b/packages/cli/src/commands/open.ts
@@ -1,5 +1,6 @@
import { type SpawnOptions, spawn } from "node:child_process";
import type { Io } from "../io.js";
+import { prepareRecords } from "../record-prepare.js";
import { ensureServer, mapPageUrl } from "../server.js";
import { globalPaths, projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
@@ -87,6 +88,7 @@ async function openTarget(target: string, opts: OpenOptions): Promise<void> {
export async function openProject(opts: OpenProjectOptions): Promise<void> {
const { io } = opts;
const { root } = await resolveProjectRoot(opts.dir);
+ await prepareRecords(root, io.env, io.warn);
await buildProject({
dir: root,
io,
diff --git a/packages/cli/src/commands/pr.ts b/packages/cli/src/commands/pr.ts
index 5ae2297..3f86dba 100644
--- a/packages/cli/src/commands/pr.ts
+++ b/packages/cli/src/commands/pr.ts
@@ -98,7 +98,7 @@ export interface PrModel {
base: PrBase;
head: string;
/** What the project does with its record: it travels, or it stays local. */
- policy: "commit" | "ignore";
+ policy: "share" | "ignore";
goals: PrGoal[];
sessions: PrSessionLine[];
thoughts: PrThought[];
@@ -204,7 +204,7 @@ export interface BuildPrInput {
head: string;
commits: readonly PrCommit[];
sessions: readonly EffectiveSession[];
- policy: "commit" | "ignore";
+ policy: "share" | "ignore";
}
/**
@@ -414,8 +414,8 @@ export function formatPr(model: PrModel, opts: PrFormatOptions): string {
model.policy === "ignore"
? "- This project keeps its record out of git, so these hashes resolve only on the " +
"author's machine; ask the author to run `cogit show`."
- : "- This branch commits its record, so a reviewer who checks it out gets the same " +
- "`cogit show` output.",
+ : "- This project shares its record, so a reviewer with cogit in their clone gets the " +
+ "same `cogit show` output once the author has pushed.",
);
const dropped = opts.dropped ?? [];
@@ -546,7 +546,7 @@ export async function pr(opts: PrOptions): Promise<PrModel> {
const model = buildPrModel({
base,
head,
- policy: (await cogitIgnored(root)) ? "ignore" : "commit",
+ policy: (await cogitIgnored(root)) ? "ignore" : "share",
sessions,
commits: commits.map((commit) => {
const thoughts = trailers.get(commit.full);
diff --git a/packages/cli/src/commands/prune.ts b/packages/cli/src/commands/prune.ts
new file mode 100644
index 0000000..406b5a6
--- /dev/null
+++ b/packages/cli/src/commands/prune.ts
@@ -0,0 +1,100 @@
+import { gitUserEmail } from "../git.js";
+import { CliError, type Io } from "../io.js";
+import { deleteRecords, isSharing } from "../record-sync.js";
+import { resolveProjectRoot } from "../store/root.js";
+import { loadAllSessions, loadProject } from "../store/stores.js";
+import { buildProject } from "./build.js";
+
+export interface PruneRecordOptions {
+ dir: string;
+ /** `30d`, `2w`, `6m`, `1y`. */
+ olderThan: string;
+ /** Teammates' sessions too; the default leaves them alone. */
+ all?: boolean;
+ yes?: boolean;
+ dryRun?: boolean;
+ io: Io;
+ /** Tests inject a minimal page instead of the bundled template. */
+ templateHtml?: string;
+}
+
+const DAYS_PER_UNIT: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 };
+
+/** The moment before which a session counts as older than `age`. */
+export function pruneCutoff(age: string, now: string): string {
+ const match = /^(\d+)([dwmy])$/.exec(age.trim());
+ if (match === null) throw new CliError(`invalid age "${age}"; use a number and d, w, m or y: 6m`);
+ const days = Number(match[1]) * (DAYS_PER_UNIT[match[2] as string] as number);
+ return new Date(Date.parse(now) - days * 86_400_000).toISOString();
+}
+
+/**
+ * `cogit prune`: deletes old sessions for good, on this machine and, in a shared
+ * project, in the repository. It only ever runs when asked, shows what it will
+ * delete and needs a yes: unlike the rest of cogit, this cannot be undone.
+ */
+export async function pruneRecords(opts: PruneRecordOptions): Promise<void> {
+ const { io } = opts;
+ const { root } = await resolveProjectRoot(opts.dir);
+ const project = await loadProject(root);
+ if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);
+ if (!project.ok) throw new CliError(project.error);
+
+ const cutoff = pruneCutoff(opts.olderThan, io.now());
+ const me = await gitUserEmail(root, io.env);
+ const sessions = (await loadAllSessions(root, io.warn)).filter(
+ (session) =>
+ session.updatedAt < cutoff &&
+ (opts.all === true || session.authorEmail === undefined || session.authorEmail === me),
+ );
+ if (sessions.length === 0) {
+ io.out(`No sessions older than ${opts.olderThan}.`);
+ return;
+ }
+
+ const count = `${sessions.length} session${sessions.length === 1 ? "" : "s"}`;
+ for (const session of sessions) {
+ const author =
+ session.authorEmail !== undefined && session.authorEmail !== me
+ ? ` ${session.author ?? session.authorEmail}`
+ : "";
+ const title = session.title.trim() === "" ? session.sessionId : session.title.trim();
+ io.out(` ${session.updatedAt.slice(0, 10)} ${title}${author}`);
+ }
+ const sharing = await isSharing(root);
+ if (opts.dryRun === true) {
+ io.out(`Would delete ${count}.`);
+ return;
+ }
+ if (opts.yes !== true) {
+ const where = sharing ? "from this machine and the repository" : "from this machine";
+ const agreed = await io.prompt.confirm(
+ `Delete ${count} ${where}? This cannot be undone.`,
+ false,
+ );
+ if (!agreed) {
+ io.out("Nothing deleted.");
+ return;
+ }
+ }
+
+ try {
+ await deleteRecords(
+ root,
+ sessions.map((session) => session.sessionId),
+ io.env,
+ );
+ } catch (err) {
+ throw new CliError(
+ `could not delete from the repository, so nothing was deleted: ${(err as Error).message}`,
+ );
+ }
+ io.out(`Deleted ${count}.`);
+ if (sharing)
+ io.out("Copies already on teammates' machines stay until they delete them themselves.");
+ await buildProject({
+ dir: root,
+ io,
+ ...(opts.templateHtml === undefined ? {} : { templateHtml: opts.templateHtml }),
+ });
+}
diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.ts
index b56491e..2425e00 100644
--- a/packages/cli/src/git-hooks.ts
+++ b/packages/cli/src/git-hooks.ts
@@ -3,7 +3,7 @@ import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";
import { join } from "node:path";
import { findGitRoot, gitHooksDir, resolveCommit } from "./git.js";
import { spawnDetachedProcess } from "./hooks/run.js";
-import { stageSessionFiles } from "./session-git.js";
+import { queueRecords } from "./record-sync.js";
import { atomicWrite } from "./store/fs.js";
import { captureDisabled, projectPaths } from "./store/paths.js";
import { loadConfig } from "./store/stores.js";
@@ -114,11 +114,14 @@ export async function installGitHook(root: string, event: string): Promise<boole
/**
* The git-side events cogit answers (Stories 9.3, 9.4, 13.6). A git hook's stdin
* is not the Claude Code hook JSON, so these never go through `runHook`.
- * `pre-commit` carries the session record with a code commit; `prepare-commit-msg`
+ * `pre-push` sends the session records along with the code; `prepare-commit-msg`
* adds the `Thought:` trailer that names the message behind it; `post-commit`
* queues the Shape of a message that landed commits, outside the commit.
*/
-export const GIT_HOOK_EVENTS = ["pre-commit", "prepare-commit-msg", "post-commit"] as const;
+export const GIT_HOOK_EVENTS = ["prepare-commit-msg", "post-commit", "pre-push"] as const;
+
+/** Hooks older versions installed: their block is removed on the next refresh. */
+const RETIRED_GIT_HOOK_EVENTS = ["pre-commit"] as const;
export type GitHookEvent = (typeof GIT_HOOK_EVENTS)[number];
export function isGitHookEvent(event: string): event is GitHookEvent {
@@ -144,11 +147,15 @@ export async function refreshGitHooks(root: string): Promise<GitHookEvent[]> {
const dir = await gitHooksDir(gitRoot);
if (dir === undefined) return [];
const refreshed: GitHookEvent[] = [];
+ const hasBlock = async (event: string): Promise<boolean> =>
+ ((await readFile(join(dir, event), "utf8").catch(() => undefined)) ?? "").includes(BLOCK_START);
+ // A hook this version added reaches a clone that already has cogit's others.
+ const installed = await hasBlock("prepare-commit-msg");
for (const event of GIT_HOOK_EVENTS) {
- const current = await readFile(join(dir, event), "utf8").catch(() => undefined);
- if (current === undefined || !current.includes(BLOCK_START)) continue;
+ if (!installed && !(await hasBlock(event))) continue;
if (await installGitHook(root, event)) refreshed.push(event);
}
+ await removeHookBlocks(dir, RETIRED_GIT_HOOK_EVENTS);
return refreshed;
}
@@ -162,8 +169,17 @@ export async function uninstallGitHooks(root: string): Promise<GitHookEvent[]> {
if (gitRoot === undefined) return [];
const dir = await gitHooksDir(gitRoot);
if (dir === undefined) return [];
- const removed: GitHookEvent[] = [];
- for (const event of GIT_HOOK_EVENTS) {
+ await removeHookBlocks(dir, RETIRED_GIT_HOOK_EVENTS);
+ return removeHookBlocks(dir, GIT_HOOK_EVENTS);
+}
+
+/** Takes cogit's block out of these hooks; returns the ones that had one. */
+async function removeHookBlocks<Event extends string>(
+ dir: string,
+ events: readonly Event[],
+): Promise<Event[]> {
+ const removed: Event[] = [];
+ for (const event of events) {
const file = join(dir, event);
const current = await readFile(file, "utf8").catch(() => undefined);
if (current === undefined || !current.includes(BLOCK_START)) continue;
@@ -175,6 +191,29 @@ export async function uninstallGitHooks(root: string): Promise<GitHookEvent[]> {
return removed;
}
+/**
+ * The `pre-push` hook: queues the records and sends them in the background, so
+ * the user's push never waits for the network, never meets a second SSH prompt and
+ * never fails because of a record. The line is the only sign that something else
+ * is leaving the machine, so it goes out even though the push itself is quiet.
+ */
+async function sendWithPush(
+ dir: string,
+ env: NodeJS.ProcessEnv,
+ pushedRemote: string | undefined,
+ spawn: typeof spawnDetachedProcess,
+): Promise<void> {
+ if (captureDisabled(env)) return;
+ const queued = await queueRecords(dir, env, pushedRemote);
+ if (queued === 0) return;
+ const cli = currentCliPath();
+ if (cli === undefined) return;
+ process.stderr.write(
+ `cogit: sending ${queued} session record${queued === 1 ? "" : "s"} to ${pushedRemote ?? "the remote"}\n`,
+ );
+ spawn(cli, ["record-sync", "send", "-C", dir], env, projectPaths(dir).detachedLog);
+}
+
/**
* Starts the Shape of the commit that just landed (Story 13.6). The commit's
* `Thought:` trailer, read by the shape run, names the message, so the Shape
@@ -214,8 +253,8 @@ export async function runGitHook(
now: Date = new Date(),
spawn: typeof spawnDetachedProcess = spawnDetachedProcess,
): Promise<void> {
- if (event === "pre-commit") {
- await stageSessionFiles(dir, env);
+ if (event === "pre-push") {
+ await sendWithPush(dir, env, args[0], spawn);
return;
}
if (event === "post-commit") {
diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts
index 945ea09..7763245 100644
--- a/packages/cli/src/git.ts
+++ b/packages/cli/src/git.ts
@@ -6,7 +6,8 @@ import { atomicWrite } from "./store/fs.js";
const exec = promisify(execFile);
-export type GitPolicy = "ignore" | "commit";
+/** Shared with the team through the repository, or kept on this machine. */
+export type GitPolicy = "ignore" | "share";
/** Walks up from `dir` looking for `.git` (a directory, or a file in worktrees). */
export async function findGitRoot(dir: string): Promise<string | undefined> {
@@ -46,23 +47,24 @@ const HEADER = "# cogit";
const IGNORE_ALL = "/.cogit/";
/**
- * What the root `.gitignore` needs for a policy (Story 9.3). Under `commit` the
- * root lists nothing: the project's own `.cogit/.gitignore` keeps local state out
- * and lets the session records travel. Under `ignore` a single line hides it all.
+ * What the root `.gitignore` needs for a policy. A shared project lists nothing:
+ * the project's own `.cogit/.gitignore` keeps everything but the project marker
+ * out. Under `ignore` a single line hides it all, and that line is what later
+ * commands read the policy from.
*/
export function gitignoreLines(policy: GitPolicy): string[] {
return policy === "ignore" ? [IGNORE_ALL] : [];
}
/**
- * Applies the policy to `<root>/.gitignore`: adds the ignore line, or removes the
- * one an older init wrote when the project switches to `commit`. User lines are
- * never touched. Returns the lines added (none when switching to commit).
+ * Applies the policy to `<root>/.gitignore`: adds the ignore line, or removes it
+ * when the project starts sharing. User lines are never touched. Returns the
+ * lines added (none when sharing).
*/
export async function ensureGitignore(root: string, policy: GitPolicy): Promise<string[]> {
const file = join(root, ".gitignore");
const text = await readFile(file, "utf8").catch(() => "");
- if (policy === "commit") {
+ if (policy === "share") {
const lines = text.split(/\r?\n/);
const kept = lines.filter((line) => line.trim() !== IGNORE_ALL);
if (kept.length !== lines.length) await atomicWrite(file, kept.join("\n"));
@@ -84,56 +86,37 @@ export async function cogitIgnored(root: string): Promise<boolean> {
}
/**
- * The `.cogit/.gitignore` the commit policy writes (Story 9.3): everything in the
- * directory stays local except the session records, `project.json` and these
- * rules themselves. The file has to travel: without it a clone would not ignore
- * the conversation store and one `git add -A` would publish the raw chat. The
- * list has no timestamps and a stable order, so switching a setting rewrites it
- * once and later builds leave it alone.
+ * The `.cogit/.gitignore` of a shared project: only the marker that tells a clone
+ * this project uses cogit is tracked. The sessions travel on their own refs
+ * (record-sync.ts), and the file has to travel too: without it a clone would not
+ * ignore the record, and one `git add -A` would commit it.
*/
-export function cogitGitignore(shareConversations: boolean): string {
- return [
- HEADER,
- "*",
- "!.gitignore",
- "!sessions/",
- "!sessions/**",
- "!project.json",
- ...(shareConversations ? ["!conversations/", "!conversations/**"] : []),
- "",
- ].join("\n");
+export function cogitGitignore(): string {
+ return [HEADER, "*", "!.gitignore", "!project.json", ""].join("\n");
}
/**
- * Writes `.cogit/.gitignore` for the commit policy; a no-op under `ignore`
- * (the root already hides everything). Returns true when the file changed.
+ * Writes `.cogit/.gitignore` for a shared project; a no-op under `ignore` (the
+ * root already hides everything). Returns true when the file changed.
*/
-export async function ensureCogitGitignore(
- root: string,
- policy: GitPolicy,
- shareConversations: boolean,
-): Promise<boolean> {
- if (policy !== "commit") return false;
+export async function ensureCogitGitignore(root: string, policy: GitPolicy): Promise<boolean> {
+ if (policy !== "share") return false;
const file = join(root, ".cogit", ".gitignore");
- const content = cogitGitignore(shareConversations);
- const current = await readFile(file, "utf8").catch(() => undefined);
- if (current === content) return false;
+ const content = cogitGitignore();
+ if ((await readFile(file, "utf8").catch(() => undefined)) === content) return false;
await atomicWrite(file, content);
return true;
}
/**
- * Keeps an existing project's `.cogit/.gitignore` in step with the settings
- * (Story 9.3): reads the policy from the root ignore file, so a project that
- * committed its records before this story gets the new rules on its next build.
+ * Keeps an existing project's `.cogit/.gitignore` current: reads the policy from
+ * the root ignore file, so a project set up by an older version gets the new rules
+ * on its next build.
*/
-export async function refreshCogitGitignore(
- root: string,
- shareConversations: boolean,
-): Promise<boolean> {
+export async function refreshCogitGitignore(root: string): Promise<boolean> {
if ((await findGitRoot(root)) === undefined) return false;
if (await cogitIgnored(root)) return false;
- return ensureCogitGitignore(root, "commit", shareConversations);
+ return ensureCogitGitignore(root, "share");
}
interface CommitLine {
diff --git a/packages/cli/src/hooks/sessionend.ts b/packages/cli/src/hooks/sessionend.ts
index 642dd9f..23f20d9 100644
--- a/packages/cli/src/hooks/sessionend.ts
+++ b/packages/cli/src/hooks/sessionend.ts
@@ -12,27 +12,13 @@ import type { HookContext } from "./run.js";
* where the session left off) over the whole session, so it starts even when
* every message already has a node. Nothing waits for it: when it never
* finishes, the next session start in the project runs it again (close-retry.ts).
- *
- * With `recordCommit: auto` (Story 9.3) the last record is committed detached as
- * well; the catch-up does that itself once it has written, so this only starts a
- * commit when there is nothing to catch up (or the catch-up is off).
*/
export async function onSessionEnd(ctx: HookContext): Promise<undefined> {
if (!ctx.initialized) return undefined;
const config = await loadConfig(ctx.env);
- const commitOnly = (): void => {
- if (config.recordCommit === "auto")
- ctx.spawnDetached(["record-commit", ctx.sessionId, "-C", ctx.root]);
- };
- if (!config.sessionEndCatchUp) {
- commitOnly();
- return undefined;
- }
+ if (!config.sessionEndCatchUp) return undefined;
const messages = await readSessionMessages(ctx.root, ctx.sessionId, ctx.env);
- if (!messages || messages.length === 0) {
- commitOnly();
- return undefined;
- }
+ if (!messages || messages.length === 0) return undefined;
ctx.spawnDetached(["backfill", ctx.sessionId, "--tail", "--close", "-C", ctx.root]);
return undefined;
}
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index a8de0d6..5016d2e 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -4,8 +4,9 @@ import { installedCliVersion, versionNotice } from "../cli-version.js";
import { branchesOf, type LogBranch } from "../commands/log.js";
import { findGitRoot } from "../git.js";
import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";
+import { setUpClone } from "../record-prepare.js";
+import { isSharing, reconcileRecords, recordSyncStatus } from "../record-sync.js";
import type { Session } from "../schema/session.js";
-import { uncommittedSession } from "../session-git.js";
import { applyEvents, readEvents } from "../store/events.js";
import { loadAllSessions, loadConfig, loadSession } from "../store/stores.js";
import { buildMessages } from "../view/lineage.js";
@@ -94,10 +95,28 @@ async function sessionStartOutput(ctx: HookContext): Promise<HookOutput | undefi
// Sessions whose closing pass never finished get it now, detached (a failure
// here must not cost the handoff).
await retryUnclosed(ctx).catch(() => undefined);
+ await syncRecordsAtStart(ctx).catch(() => undefined);
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(ctx, await startupContext(ctx, config.recordCommit));
+ return additionalContext(ctx, await startupContext(ctx));
+}
+
+/**
+ * A clone's first session sets it up and downloads the team's records in the
+ * background; later ones read what a pull brought, and retry what the user's last
+ * push could not send. Nothing new goes out here: only what that push queued.
+ */
+async function syncRecordsAtStart(ctx: HookContext): Promise<void> {
+ if (!(await isSharing(ctx.root))) return;
+ await setUpClone(ctx.root, ctx.env);
+ const status = await recordSyncStatus(ctx.root, ctx.env);
+ if (status.remote !== undefined && !status.downloaded) {
+ ctx.spawnDetached(["record-sync", "download", "-C", ctx.root]);
+ return;
+ }
+ await reconcileRecords(ctx.root, ctx.env);
+ if (status.pending > 0) ctx.spawnDetached(["record-sync", "send", "-C", ctx.root]);
}
function additionalContext(ctx: HookContext, text: string): HookOutput {
@@ -130,11 +149,9 @@ function clip(text: string, max: number): string {
/**
* What the agent needs to continue the project: where the lineage lives, how to
- * read it, and the compressed view of the last session before this one. Under
- * `recordCommit: ask` (Story 9.3) it also says when that session's record is
- * still uncommitted, so the agent can offer to commit it.
+ * read it, and the compressed view of the last session before this one.
*/
-async function startupContext(ctx: HookContext, recordCommit: string): Promise<string> {
+async function startupContext(ctx: HookContext): Promise<string> {
const command = cli(ctx);
const header =
`cogit records this project's lineage (one node per user message, hanging from the ` +
@@ -151,26 +168,7 @@ async function startupContext(ctx: HookContext, recordCommit: string): Promise<s
const events = await readEvents(ctx.root, previous.sessionId);
const messages = buildMessages(applyEvents(previous.nodes, events));
- const recordLine =
- recordCommit === "ask" && (await uncommittedSession(ctx.root, previous.sessionId, ctx.env))
- ? recordCommitLine(previous)
- : "";
- return composeStartupContext(
- header,
- previous,
- branchesOf(previous.sessionId, messages),
- recordLine,
- );
-}
-
-/** The offer the agent makes for a record the last code commit did not carry. */
-export function recordCommitLine(session: Session): string {
- const title = session.title.trim() === "" ? session.sessionId : clip(oneLine(session.title), 120);
- return (
- "The last session's record is not committed. Offer to commit it with the message " +
- `\`chore(cogit): record ${title}\`, only the .cogit/sessions/ paths (never other staged ` +
- "changes), and run it only if the user agrees."
- );
+ return composeStartupContext(header, previous, branchesOf(previous.sessionId, messages));
}
/** The session with the newest activity, ignoring this one. */
@@ -193,14 +191,8 @@ export function composeStartupContext(
header: string,
session: Session,
branches: readonly LogBranch[],
- recordLine = "",
): string {
- const head = [
- header,
- ...(recordLine === "" ? [] : ["", recordLine]),
- "",
- ...statusLines(session),
- ];
+ const head = [header, "", ...statusLines(session)];
const blocks = branches.map(branchLines);
const cutNote = (cut: number): string[] =>
cut === 0
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index af89fcc..d7b9da0 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -1,3 +1,5 @@
+import { existsSync } from "node:fs";
+import { dirname, resolve } from "node:path";
import { Command, InvalidArgumentError, Option } from "commander";
import pkg from "../package.json" with { type: "json" };
import { backfillTail } from "./commands/backfill.js";
@@ -20,6 +22,7 @@ import { formatShow, log, logFile, show } from "./commands/log.js";
import { migrateIds } from "./commands/migrate.js";
import { openPanel, openProject } from "./commands/open.js";
import { pr } from "./commands/pr.js";
+import { pruneRecords } from "./commands/prune.js";
import { search } from "./commands/search.js";
import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";
import { shapeMessage } from "./commands/shape.js";
@@ -27,9 +30,12 @@ import { why } from "./commands/why.js";
import { isGitHookEvent, runGitHook } from "./git-hooks.js";
import { runHook } from "./hooks/run.js";
import { CliError, type Io, processIo } from "./io.js";
+import { prepareRecords } from "./record-prepare.js";
+import { downloadRecords, reconcileRecords, sendRecords } from "./record-sync.js";
import { startMapServer } from "./server.js";
-import { maybeAutoCommit } from "./session-git.js";
import { takeMigrationWarnings } from "./store/migrate.js";
+import { projectPaths } from "./store/paths.js";
+import { resolveProjectRoot } from "./store/root.js";
import { loadConfig } from "./store/stores.js";
import { configHelpLines } from "./view/settings.js";
@@ -66,6 +72,22 @@ function examples(...commands: string[]): string {
return `\nExamples:\n${commands.map((command) => ` $ ${command}`).join("\n")}\n`;
}
+/**
+ * Before a command reads the record: in a clone of a shared project this is what
+ * brings the team's sessions in. Walks up like `why` does, since a command may run
+ * from a subfolder; outside a project it does nothing and the command reports that.
+ */
+async function readyToRead(dir: string, io: Io): Promise<void> {
+ for (let cur = resolve(dir); ; cur = dirname(cur)) {
+ const { root } = await resolveProjectRoot(cur);
+ if (existsSync(projectPaths(root).project)) {
+ await prepareRecords(root, io.env, io.warn);
+ return;
+ }
+ if (dirname(cur) === cur) return;
+ }
+}
+
export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps = {}): Command {
const program = new Command().name("cogit").description(pkg.description).version(pkg.version);
@@ -94,7 +116,9 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.addHelpText("after", examples("cogit blame src/auth.ts:42", "cogit blame src/auth.ts"))
.action(
run(async (target: string, dir: string, opts: { dir?: string }) => {
- await blame({ dir: opts.dir ?? dir, target, io: makeIo(false) });
+ const io = makeIo(false);
+ await readyToRead(opts.dir ?? dir, io);
+ await blame({ dir: opts.dir ?? dir, target, io });
}),
);
@@ -117,11 +141,13 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.action(
run(async (file: string, dir: string | undefined, opts: { dir?: string; line?: number }) => {
const project = opts.dir ?? dir;
+ const io = makeIo(false);
+ await readyToRead(project ?? process.cwd(), io);
await why({
...(project === undefined ? { cwd: process.cwd() } : { dir: project }),
file,
...(opts.line === undefined ? {} : { line: opts.line }),
- io: makeIo(false),
+ io,
});
}),
);
@@ -152,18 +178,20 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
},
) => {
const target = opts.dir ?? dir;
+ const io = makeIo(false);
+ await readyToRead(target, io);
if (opts.file !== undefined) {
await logFile({
dir: target,
file: opts.file,
- io: makeIo(false),
+ io,
json: opts.json === true,
});
return;
}
await log({
dir: target,
- io: makeIo(false),
+ io,
session: opts.session,
limit: opts.number,
branchesOnly: opts.branches === true,
@@ -191,6 +219,7 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
opts: { dir?: string; chat?: boolean; json?: boolean },
) => {
const io = makeIo(false);
+ await readyToRead(opts.dir ?? dir, io);
const model = await show({ dir: opts.dir ?? dir, ref, io, chat: opts.chat !== false });
if (opts.json === true) io.out(JSON.stringify(model, null, 2));
else for (const line of formatShow(model)) io.out(line);
@@ -291,9 +320,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
dir: string,
opts: { dir?: string; session?: string; number?: number; json?: boolean },
) => {
+ const io = makeIo(false);
+ await readyToRead(opts.dir ?? dir, io);
await search({
dir: opts.dir ?? dir,
- io: makeIo(false),
+ io,
text,
session: opts.session,
limit: opts.number,
@@ -323,10 +354,12 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.action(
run(
async (base: string | undefined, opts: { dir: string; json?: boolean; copy?: boolean }) => {
+ const io = makeIo(false);
+ await readyToRead(opts.dir, io);
await pr({
dir: opts.dir,
base,
- io: makeIo(false),
+ io,
json: opts.json === true,
copy: opts.copy === true,
});
@@ -360,7 +393,10 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.argument("[dir]", "project directory", ".")
.option("--name <name>", "project name")
.addOption(
- new Option("--git <policy>", "commit or ignore .cogit/").choices(["ignore", "commit"]),
+ new Option(
+ "--git <policy>",
+ "share the session records with `git push`, or keep them here",
+ ).choices(["ignore", "share"]),
)
.option("--language <lang>", 'summary language: "auto" or a language')
.option("--retention <days>", 'Claude Code transcript retention, or "keep"', retention)
@@ -445,13 +481,13 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
config
.command("git")
.description("show, or switch to commit or ignore, this project's session records (story 9.3)")
- .argument("[policy]", "commit or ignore; without it, shows the current policy")
+ .argument("[policy]", "share or ignore; without it, shows the current policy")
.argument("[dir]", "project directory", ".")
.action(
run(async (policy: string | undefined, dir: string) => {
if (policy === undefined) return configGitShow(dir, makeIo(false));
- if (policy !== "commit" && policy !== "ignore")
- throw new CliError(`invalid git policy "${policy}"; use commit or ignore`);
+ if (policy !== "share" && policy !== "ignore")
+ throw new CliError(`invalid git policy "${policy}"; use share or ignore`);
await configGit(dir, policy, makeIo(false));
}),
);
@@ -480,6 +516,40 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
),
);
+ program
+ .command("prune")
+ .description("delete old sessions for good, here and in the repository")
+ .helpGroup("Map:")
+ .requiredOption("--older-than <age>", "how old a session must be: 30d, 2w, 6m, 1y")
+ .option("--all", "teammates' sessions too, not only your own")
+ .option("--dry-run", "list what would be deleted without deleting")
+ .option("-y, --yes", "do not ask for confirmation")
+ .option("-C, --dir <dir>", "project directory", ".")
+ .addHelpText(
+ "after",
+ examples("cogit prune --older-than 1y --dry-run", "cogit prune --older-than 6m"),
+ )
+ .action(
+ run(
+ async (opts: {
+ olderThan: string;
+ all?: boolean;
+ dryRun?: boolean;
+ yes?: boolean;
+ dir: string;
+ }) => {
+ await pruneRecords({
+ dir: opts.dir,
+ olderThan: opts.olderThan,
+ all: opts.all === true,
+ dryRun: opts.dryRun === true,
+ yes: opts.yes === true,
+ io: makeIo(process.stdin.isTTY === true),
+ });
+ },
+ ),
+ );
+
program
.command("shape")
.description("write the Shape of the newest message that landed commits (side model)")
@@ -591,9 +661,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.argument("[args...]", "arguments git passed to its hook: $1, $2, …")
.option("-C, --dir <dir>", "project directory (git hooks pass theirs)")
.allowExcessArguments(true)
- .addHelpText("after", examples("cogit hook stop", "cogit hook pre-commit --dir ../my-app"))
+ .addHelpText("after", examples("cogit hook stop", "cogit hook pre-push --dir ../my-app"))
.action(async (event: string, args: string[], opts: { dir?: string }) => {
const io = makeIo(false);
+ // A block a past version left in a hook it has since retired: quiet until refreshed.
+ if (event === "pre-commit") return;
if (isGitHookEvent(event)) {
try {
await runGitHook(event, opts.dir ?? process.cwd(), io.env, args, new Date(io.now()));
@@ -645,15 +717,21 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
}),
);
- // Started detached by the SessionEnd hook when `recordCommit` is `auto`.
+ // Started detached by the pre-push hook and by SessionStart.
program
- .command("record-commit", { hidden: true })
- .description("commit the session record files without touching other staged changes")
- .argument("<session-id>", "session id")
+ .command("record-sync", { hidden: true })
+ .description("send the queued session records, or download the team's")
+ .argument("<action>", "send or download")
.option("-C, --dir <dir>", "project directory", ".")
.action(
- run(async (sessionId: string, opts: { dir: string }) => {
- await maybeAutoCommit(opts.dir, sessionId, makeIo(false).env);
+ run(async (action: string, opts: { dir: string }) => {
+ const io = makeIo(false);
+ const { root } = await resolveProjectRoot(opts.dir);
+ if (action === "send") await sendRecords(root, io.env);
+ else if (action === "download") {
+ await downloadRecords(root, io.env);
+ await reconcileRecords(root, io.env);
+ } else throw new CliError(`unknown record-sync action "${action}"`);
}),
);
diff --git a/packages/cli/src/record-prepare.ts b/packages/cli/src/record-prepare.ts
new file mode 100644
index 0000000..a77c24e
--- /dev/null
+++ b/packages/cli/src/record-prepare.ts
@@ -0,0 +1,44 @@
+import { installGitHooks } from "./git-hooks.js";
+import {
+ addRecordRefspec,
+ downloadRecords,
+ isSharing,
+ reconcileRecords,
+ recordSyncStatus,
+} from "./record-sync.js";
+
+/**
+ * What cogit does the first time it runs in a clone of a shared project: `git
+ * clone` cannot carry either of these. Afterwards `git pull` brings the records
+ * and `git push` sends them.
+ */
+export async function setUpClone(root: string, env: NodeJS.ProcessEnv): Promise<void> {
+ if (await addRecordRefspec(root, env)) await installGitHooks(root);
+}
+
+/**
+ * Runs before a command reads the record, so a person who has just cloned sees the
+ * team's sessions and never an empty map. Only the first run touches the network;
+ * from then on this costs a local look at the refs. A failed download is a warning:
+ * the command goes on with what is here.
+ */
+export async function prepareRecords(
+ root: string,
+ env: NodeJS.ProcessEnv,
+ warn: (line: string) => void,
+): Promise<void> {
+ try {
+ if (!(await isSharing(root))) return;
+ await setUpClone(root, env);
+ const status = await recordSyncStatus(root, env);
+ if (status.remote !== undefined && !status.downloaded) {
+ const showProgress = process.stderr.isTTY === true;
+ if (showProgress) process.stderr.write("Downloading your team's session records...\n");
+ if (!(await downloadRecords(root, env, showProgress)))
+ warn("could not download your team's session records; check your connection and try again");
+ }
+ await reconcileRecords(root, env);
+ } catch (err) {
+ warn(`could not update the session records: ${(err as Error).message}`);
+ }
+}
diff --git a/packages/cli/src/record-sync.ts b/packages/cli/src/record-sync.ts
new file mode 100644
index 0000000..5f6badf
--- /dev/null
+++ b/packages/cli/src/record-sync.ts
@@ -0,0 +1,571 @@
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync } from "node:fs";
+import { rm, stat } from "node:fs/promises";
+import { relative, sep } from "node:path";
+import { z } from "zod";
+import { cogitIgnored, findGitRoot, gitUserEmail } from "./git.js";
+import { atomicWrite, atomicWriteJson, readJson } from "./store/fs.js";
+import { withLock } from "./store/lock.js";
+import { projectPaths } from "./store/paths.js";
+import { listSessionIds, loadConfig } from "./store/stores.js";
+
+/**
+ * The shared record: each session lives on its own ref in the project's own
+ * repository, outside every branch, so a clone, a pull request and `git grep` see
+ * only the code. The working files in `.cogit/` stay what cogit reads; these refs
+ * are how they travel, and how an ignored file survives `git clean`.
+ *
+ * - `refs/cogit/…` is what this clone wrote; a remote holds the same names.
+ * - `refs/cogit-remote/…` is what the remote last said, so a fetch never moves a
+ * ref this clone has not sent yet.
+ *
+ * One ref per session keeps two people's pushes from ever rejecting each other, and
+ * each ref names a tree rather than a commit, so `git log --all` shows only code.
+ */
+const LOCAL = "refs/cogit";
+const TRACKING = "refs/cogit-remote";
+export const RECORD_REFSPEC = `+${LOCAL}/*:${TRACKING}/*`;
+
+/** GitHub took 5,000 refs in one push; smaller parts lose less when a network drops. */
+const PUSH_BATCH = 2000;
+const IMPORT_BATCH = 500;
+
+/** Session ids become file names, so a ref from a remote must look like one. */
+const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+const SESSION_FILE = "session.json";
+const EVENTS_FILE = "events.jsonl";
+const CONVERSATION_FILE = "conversation.jsonl.gz";
+
+const SyncState = z.object({
+ /** When the records were first downloaded into this clone. */
+ downloadedAt: z.string().optional(),
+ downloadError: z.string().optional(),
+ sendError: z.string().optional(),
+ /** Refs the user's last push asked to send, with the tree each should reach. */
+ pending: z.record(z.string(), z.string()).default({}),
+ /** Each session's files as last seen, so an unchanged session costs one stat. */
+ stamps: z.record(z.string(), z.string()).default({}),
+ /** The remote tree each session's files were last written from. */
+ imported: z.record(z.string(), z.string()).default({}),
+});
+type SyncState = z.infer<typeof SyncState>;
+
+interface GitResult {
+ code: number;
+ stdout: Buffer;
+ stderr: string;
+}
+
+function runGit(
+ root: string,
+ args: string[],
+ env: NodeJS.ProcessEnv,
+ input?: string,
+): Promise<GitResult> {
+ return new Promise((done) => {
+ const child = spawn("git", ["-C", root, ...args], {
+ env,
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
+ });
+ const out: Buffer[] = [];
+ const err: Buffer[] = [];
+ child.stdout?.on("data", (chunk: Buffer) => out.push(chunk));
+ child.stderr?.on("data", (chunk: Buffer) => err.push(chunk));
+ child.on("error", (error) => done({ code: 1, stdout: Buffer.alloc(0), stderr: error.message }));
+ child.on("close", (code) =>
+ done({
+ code: code ?? 1,
+ stdout: Buffer.concat(out),
+ stderr: Buffer.concat(err).toString("utf8"),
+ }),
+ );
+ if (input !== undefined) {
+ child.stdin?.on("error", () => undefined);
+ child.stdin?.end(input);
+ }
+ });
+}
+
+/** Git with the prompts off: nothing here runs where a person could answer one. */
+function quietEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ return { ...env, GIT_TERMINAL_PROMPT: "0", SSH_ASKPASS_REQUIRE: "never" };
+}
+
+function gitError(text: string): string {
+ const lines = text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line !== "");
+ // Git ends with advice; the reason is the line it marks as fatal.
+ const reason = lines.find((line) => line.startsWith("fatal:")) ?? lines.at(-1) ?? "git failed";
+ return reason.slice(0, 300);
+}
+
+/** True when this project's record is shared: in a repository, and not kept private. */
+export async function isSharing(root: string): Promise<boolean> {
+ if (!existsSync(projectPaths(root).project)) return false;
+ if ((await findGitRoot(root)) === undefined) return false;
+ return !(await cogitIgnored(root));
+}
+
+/** `origin`, or the only remote there is. With several and no origin, none is assumed. */
+export async function syncRemote(
+ root: string,
+ env: NodeJS.ProcessEnv,
+): Promise<string | undefined> {
+ const result = await runGit(root, ["remote"], env);
+ if (result.code !== 0) return undefined;
+ const remotes = result.stdout.toString("utf8").split("\n").filter(Boolean);
+ if (remotes.includes("origin")) return "origin";
+ return remotes.length === 1 ? remotes[0] : undefined;
+}
+
+/**
+ * A project inside a repository subdirectory gets its own part of the namespace,
+ * so two projects in one monorepo never read each other's sessions.
+ */
+async function sessionScope(root: string): Promise<string> {
+ const gitRoot = await findGitRoot(root);
+ const prefix = gitRoot === undefined ? "" : relative(gitRoot, root).split(sep).join("/");
+ if (prefix === "") return "sessions";
+ return `projects/${createHash("sha256").update(prefix).digest("hex").slice(0, 16)}/sessions`;
+}
+
+async function listRefs(
+ root: string,
+ base: string,
+ scope: string,
+ env: NodeJS.ProcessEnv,
+): Promise<Map<string, string>> {
+ const result = await runGit(
+ root,
+ ["for-each-ref", "--format=%(objectname) %(refname)", `${base}/${scope}/`],
+ env,
+ );
+ const refs = new Map<string, string>();
+ if (result.code !== 0) return refs;
+ const start = `${base}/${scope}/`.length;
+ for (const line of result.stdout.toString("utf8").split("\n")) {
+ const space = line.indexOf(" ");
+ if (space < 0) continue;
+ const id = line.slice(space + 1 + start);
+ if (SESSION_ID.test(id)) refs.set(id, line.slice(0, space));
+ }
+ return refs;
+}
+
+async function readState(root: string): Promise<SyncState> {
+ const read = await readJson(projectPaths(root).recordSync).catch(() => ({
+ found: false as const,
+ }));
+ if (read.found && "value" in read) {
+ const parsed = SyncState.safeParse(read.value);
+ if (parsed.success) return parsed.data;
+ }
+ return SyncState.parse({});
+}
+
+/** The state is derived: losing it costs a re-hash, never a record. */
+async function updateState(
+ root: string,
+ fn: (state: SyncState) => SyncState | Promise<SyncState>,
+): Promise<SyncState> {
+ const paths = projectPaths(root);
+ return withLock(paths.lock("record-sync"), async () => {
+ const current = await readState(root);
+ const next = await fn(current);
+ // Most looks change nothing; every turn's build should not rewrite the file.
+ if (next !== current) await atomicWriteJson(paths.recordSync, next);
+ return next;
+ });
+}
+
+async function sessionFiles(
+ root: string,
+ id: string,
+ conversations: boolean,
+): Promise<[name: string, path: string][]> {
+ const paths = projectPaths(root);
+ const all: [string, string][] = [
+ [SESSION_FILE, paths.session(id)],
+ [EVENTS_FILE, paths.events(id)],
+ ...(conversations ? ([[CONVERSATION_FILE, paths.conversation(id)]] as [string, string][]) : []),
+ ];
+ return all.filter(([, path]) => existsSync(path));
+}
+
+async function stampOf(files: [string, string][], conversations: boolean): Promise<string> {
+ const parts = [conversations ? "c" : "-"];
+ for (const [name, path] of files) {
+ const info = await stat(path);
+ parts.push(`${name}:${info.mtimeMs}:${info.size}`);
+ }
+ return parts.join("|");
+}
+
+/** A session stamped with someone else's email is theirs to send, never this clone's. */
+async function isOwnSession(root: string, id: string, me: string | undefined): Promise<boolean> {
+ const read = await readJson(projectPaths(root).session(id));
+ if (!read.found || !("value" in read)) return false;
+ const author = (read.value as { authorEmail?: unknown }).authorEmail;
+ return typeof author !== "string" || me === undefined || author === me;
+}
+
+/**
+ * Writes the sessions that changed since the last look onto their local refs,
+ * without touching the index or the working tree. Nothing leaves the machine.
+ * Returns how many refs moved.
+ */
+export async function snapshotRecords(root: string, env: NodeJS.ProcessEnv): Promise<number> {
+ if (!(await isSharing(root))) return 0;
+ const conversations = (await loadConfig(env)).shareConversations;
+ const me = await gitUserEmail(root, env);
+ const scope = await sessionScope(root);
+ let moved = 0;
+ await updateState(root, async (state) => {
+ const stamps = { ...state.stamps };
+ let touched = false;
+ const changed: { id: string; files: [string, string][] }[] = [];
+ for (const id of await listSessionIds(projectPaths(root).sessions)) {
+ if (!SESSION_ID.test(id)) continue;
+ const files = await sessionFiles(root, id, conversations);
+ const stamp = await stampOf(files, conversations);
+ if (stamps[id] === stamp) continue;
+ stamps[id] = stamp;
+ touched = true;
+ if (await isOwnSession(root, id, me)) changed.push({ id, files });
+ }
+ if (!touched) return state;
+ if (changed.length === 0) return { ...state, stamps };
+
+ const paths = changed.flatMap(({ files }) => files.map(([, path]) => path));
+ const hashed = await runGit(
+ root,
+ ["hash-object", "-w", "--stdin-paths"],
+ env,
+ `${paths.join("\n")}\n`,
+ );
+ if (hashed.code !== 0) throw new Error(gitError(hashed.stderr));
+ const blobs = hashed.stdout.toString("utf8").trim().split("\n");
+ let next = 0;
+ const listing = changed
+ .map(({ files }) =>
+ files.map(([name]) => `100644 blob ${blobs[next++] as string}\t${name}\n`).join(""),
+ )
+ .join("\n");
+ const made = await runGit(root, ["mktree", "--batch"], env, `${listing}\n`);
+ if (made.code !== 0) throw new Error(gitError(made.stderr));
+ const trees = made.stdout.toString("utf8").trim().split("\n");
+
+ const local = await listRefs(root, LOCAL, scope, env);
+ const tracking = await listRefs(root, TRACKING, scope, env);
+ const commands: string[] = [];
+ changed.forEach(({ id }, index) => {
+ const tree = trees[index] as string;
+ if (local.get(id) === tree) return;
+ // Already what the remote holds and never changed here: not this clone's to send.
+ if (!local.has(id) && tracking.get(id) === tree) return;
+ commands.push(`update ${LOCAL}/${scope}/${id} ${tree}\n`);
+ });
+ if (commands.length > 0) {
+ const updated = await runGit(root, ["update-ref", "--stdin"], env, commands.join(""));
+ if (updated.code !== 0) throw new Error(gitError(updated.stderr));
+ moved = commands.length;
+ }
+ return { ...state, stamps };
+ });
+ return moved;
+}
+
+/** Reads many blobs in one process; `<tree>:<name>` that does not exist comes back absent. */
+async function readBlobs(
+ root: string,
+ specs: string[],
+ env: NodeJS.ProcessEnv,
+): Promise<Map<string, Buffer>> {
+ const result = await runGit(root, ["cat-file", "--batch"], env, `${specs.join("\n")}\n`);
+ const blobs = new Map<string, Buffer>();
+ if (result.code !== 0) throw new Error(gitError(result.stderr));
+ const out = result.stdout;
+ let at = 0;
+ for (const spec of specs) {
+ const end = out.indexOf(0x0a, at);
+ if (end < 0) break;
+ const header = out.subarray(at, end).toString("utf8");
+ at = end + 1;
+ const match = /^[0-9a-f]+ blob (\d+)$/.exec(header);
+ if (match === null) continue;
+ const size = Number(match[1]);
+ blobs.set(spec, out.subarray(at, at + size));
+ at += size + 1;
+ }
+ return blobs;
+}
+
+/**
+ * Brings the working files up to date with the refs: what a pull brought in, and
+ * whatever `git clean` removed. A session with changes this clone has not sent
+ * keeps them. Returns how many sessions were written.
+ */
+export async function importRecords(root: string, env: NodeJS.ProcessEnv): Promise<number> {
+ if (!(await isSharing(root))) return 0;
+ const scope = await sessionScope(root);
+ const local = await listRefs(root, LOCAL, scope, env);
+ const tracking = await listRefs(root, TRACKING, scope, env);
+ if (local.size === 0 && tracking.size === 0) return 0;
+ const paths = projectPaths(root);
+ const conversations = (await loadConfig(env)).shareConversations;
+ let written = 0;
+ await updateState(root, async (state) => {
+ const imported = { ...state.imported };
+ const stamps = { ...state.stamps };
+ const wanted = new Map<string, string>();
+ for (const [id, tree] of tracking) {
+ const mine = local.get(id);
+ const missing = !existsSync(paths.session(id));
+ if (missing) wanted.set(id, mine ?? tree);
+ else if (mine !== undefined) {
+ // The local ref is the newer word; once sent, the two simply agree.
+ if (mine === tree) imported[id] = tree;
+ } else if (imported[id] !== tree) wanted.set(id, tree);
+ }
+ for (const [id, tree] of local) {
+ if (!tracking.has(id) && !existsSync(paths.session(id))) wanted.set(id, tree);
+ }
+
+ const ids = [...wanted.keys()];
+ const agreed = Object.keys(imported).length !== Object.keys(state.imported).length;
+ if (ids.length === 0 && !agreed) return state;
+ for (let start = 0; start < ids.length; start += IMPORT_BATCH) {
+ const part = ids.slice(start, start + IMPORT_BATCH);
+ const specs = part.flatMap((id) => {
+ const tree = wanted.get(id) as string;
+ return [SESSION_FILE, EVENTS_FILE, CONVERSATION_FILE].map((name) => `${tree}:${name}`);
+ });
+ const blobs = await readBlobs(root, specs, env);
+ for (const id of part) {
+ const tree = wanted.get(id) as string;
+ const session = blobs.get(`${tree}:${SESSION_FILE}`);
+ if (session === undefined) continue;
+ await atomicWrite(paths.session(id), session);
+ const events = blobs.get(`${tree}:${EVENTS_FILE}`);
+ if (events !== undefined) await atomicWrite(paths.events(id), events);
+ const conversation = blobs.get(`${tree}:${CONVERSATION_FILE}`);
+ if (conversation !== undefined) await atomicWrite(paths.conversation(id), conversation);
+ if (tracking.get(id) === tree) imported[id] = tree;
+ stamps[id] = await stampOf(await sessionFiles(root, id, conversations), conversations);
+ written++;
+ }
+ }
+ return { ...state, imported, stamps };
+ });
+ return written;
+}
+
+/** Local writes first, so a session this clone just changed is never overwritten. */
+export async function reconcileRecords(root: string, env: NodeJS.ProcessEnv): Promise<void> {
+ await snapshotRecords(root, env);
+ await importRecords(root, env);
+}
+
+/**
+ * The refspec that makes a plain `git fetch` and `git pull` bring the records,
+ * in this clone's config only. Git never applies a repository's settings on clone,
+ * so cogit's first run here has to add it. Returns true when it was added.
+ */
+export async function addRecordRefspec(root: string, env: NodeJS.ProcessEnv): Promise<boolean> {
+ const remote = await syncRemote(root, env);
+ if (remote === undefined) return false;
+ const key = `remote.${remote}.fetch`;
+ const current = await runGit(root, ["config", "--get-all", key], env);
+ if (current.stdout.toString("utf8").split("\n").includes(RECORD_REFSPEC)) return false;
+ return (await runGit(root, ["config", "--add", key, RECORD_REFSPEC], env)).code === 0;
+}
+
+/**
+ * Downloads the records. Only the record refs move: the user's remote-tracking
+ * branches stay where their last fetch left them. With `showProgress` git's own
+ * progress goes to the terminal, and a person can answer an SSH passphrase.
+ */
+export async function downloadRecords(
+ root: string,
+ env: NodeJS.ProcessEnv,
+ showProgress = false,
+): Promise<boolean> {
+ const remote = await syncRemote(root, env);
+ if (remote === undefined) return false;
+ const args = ["fetch", "--no-tags", "--no-write-fetch-head", remote, RECORD_REFSPEC];
+ const result = showProgress
+ ? await new Promise<GitResult>((done) => {
+ const child = spawn("git", ["-C", root, ...args], { env, stdio: "inherit" });
+ const failed = (code: number): void =>
+ done({ code, stdout: Buffer.alloc(0), stderr: "the download failed" });
+ child.on("error", () => failed(1));
+ child.on("close", (code) => failed(code ?? 1));
+ })
+ : await runGit(root, [...args.slice(0, 1), "--quiet", ...args.slice(1)], quietEnv(env));
+ await updateState(root, (state) => {
+ if (result.code === 0) {
+ const { downloadError: _cleared, ...rest } = state;
+ return { ...rest, downloadedAt: new Date().toISOString() };
+ }
+ return { ...state, downloadError: gitError(result.stderr) };
+ });
+ return result.code === 0;
+}
+
+/**
+ * The `pre-push` step: writes what changed and queues every session the remote
+ * does not have yet, without any network. Pushes to other remotes queue nothing,
+ * so a deploy remote or a fork never receives the record. Returns the queue's size.
+ */
+export async function queueRecords(
+ root: string,
+ env: NodeJS.ProcessEnv,
+ pushedRemote?: string,
+): Promise<number> {
+ if (!(await isSharing(root))) return 0;
+ const remote = await syncRemote(root, env);
+ if (remote === undefined) return 0;
+ if (pushedRemote !== undefined && pushedRemote !== remote) return 0;
+ await snapshotRecords(root, env);
+ const scope = await sessionScope(root);
+ const local = await listRefs(root, LOCAL, scope, env);
+ const tracking = await listRefs(root, TRACKING, scope, env);
+ const state = await updateState(root, (cur) => {
+ const pending = { ...cur.pending };
+ for (const [id, tree] of local) {
+ const ref = `${LOCAL}/${scope}/${id}`;
+ if (tracking.get(id) === tree) delete pending[ref];
+ else pending[ref] = tree;
+ }
+ return { ...cur, pending };
+ });
+ return Object.keys(state.pending).length;
+}
+
+/**
+ * Sends the queue, in the background of the user's push: no prompt can appear
+ * and nothing here reaches their exit code. What fails stays queued; the next
+ * session start tries it again. `--no-verify` keeps this push from firing the
+ * hook that started it. Returns how many were sent.
+ */
+export async function sendRecords(root: string, env: NodeJS.ProcessEnv): Promise<number> {
+ const remote = await syncRemote(root, env);
+ if (remote === undefined) return 0;
+ const queue = Object.entries((await readState(root)).pending);
+ let sent = 0;
+ for (let start = 0; start < queue.length; start += PUSH_BATCH) {
+ const part = queue.slice(start, start + PUSH_BATCH);
+ const specs = part.map(([ref, tree]) => `+${tree}:${ref}`);
+ const pushed = await runGit(
+ root,
+ ["push", "--no-verify", "--quiet", remote, ...specs],
+ quietEnv(env),
+ );
+ if (pushed.code !== 0) {
+ const error = gitError(pushed.stderr);
+ await updateState(root, (state) => ({ ...state, sendError: error }));
+ return sent;
+ }
+ const commands = part
+ .map(([ref, tree]) => `update ${TRACKING}${ref.slice(LOCAL.length)} ${tree}\n`)
+ .join("");
+ await runGit(root, ["update-ref", "--stdin"], env, commands);
+ await updateState(root, (state) => {
+ const pending = { ...state.pending };
+ for (const [ref, tree] of part) if (pending[ref] === tree) delete pending[ref];
+ const { sendError: _cleared, ...rest } = state;
+ return { ...rest, pending };
+ });
+ sent += part.length;
+ }
+ return sent;
+}
+
+/** Session files an older version committed; they stay tracked until the user removes them. */
+export async function trackedRecordFiles(root: string, env: NodeJS.ProcessEnv): Promise<number> {
+ const result = await runGit(root, ["ls-files", "--", ".cogit/sessions"], env);
+ return result.stdout.toString("utf8").split("\n").filter(Boolean).length;
+}
+
+export interface RecordSyncStatus {
+ sharing: boolean;
+ remote?: string;
+ downloaded: boolean;
+ downloadError?: string;
+ pending: number;
+ sendError?: string;
+}
+
+export async function recordSyncStatus(
+ root: string,
+ env: NodeJS.ProcessEnv,
+): Promise<RecordSyncStatus> {
+ const sharing = await isSharing(root);
+ if (!sharing) return { sharing, downloaded: false, pending: 0 };
+ const remote = await syncRemote(root, env);
+ const state = await readState(root);
+ return {
+ sharing,
+ ...(remote === undefined ? {} : { remote }),
+ downloaded: state.downloadedAt !== undefined,
+ ...(state.downloadError === undefined ? {} : { downloadError: state.downloadError }),
+ pending: Object.keys(state.pending).length,
+ ...(state.sendError === undefined ? {} : { sendError: state.sendError }),
+ };
+}
+
+/**
+ * Deletes sessions from the remote first and only then from this machine: a
+ * failed push leaves everything in place instead of a local copy the next import
+ * would bring back. Throws the reason. The caller has already asked the user.
+ */
+export async function deleteRecords(
+ root: string,
+ ids: readonly string[],
+ env: NodeJS.ProcessEnv,
+): Promise<void> {
+ const paths = projectPaths(root);
+ if (await isSharing(root)) {
+ const scope = await sessionScope(root);
+ const tracking = await listRefs(root, TRACKING, scope, env);
+ const remote = await syncRemote(root, env);
+ const published = ids.filter((id) => tracking.has(id));
+ if (remote !== undefined) {
+ for (let start = 0; start < published.length; start += PUSH_BATCH) {
+ const part = published.slice(start, start + PUSH_BATCH);
+ const specs = part.map((id) => `:${LOCAL}/${scope}/${id}`);
+ const pushed = await runGit(
+ root,
+ ["push", "--no-verify", "--quiet", remote, ...specs],
+ quietEnv(env),
+ );
+ if (pushed.code !== 0) throw new Error(gitError(pushed.stderr));
+ }
+ }
+ const commands = ids
+ .flatMap((id) => [`delete ${LOCAL}/${scope}/${id}\n`, `delete ${TRACKING}/${scope}/${id}\n`])
+ .join("");
+ await runGit(root, ["update-ref", "--stdin"], env, commands);
+ await updateState(root, (state) => {
+ const pending = { ...state.pending };
+ const imported = { ...state.imported };
+ const stamps = { ...state.stamps };
+ for (const id of ids) {
+ delete pending[`${LOCAL}/${scope}/${id}`];
+ delete imported[id];
+ delete stamps[id];
+ }
+ return { ...state, pending, imported, stamps };
+ });
+ }
+ for (const id of ids) {
+ await rm(paths.session(id), { force: true });
+ await rm(paths.events(id), { force: true });
+ await rm(paths.conversation(id), { force: true });
+ await rm(paths.state(id), { force: true });
+ }
+}
diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.ts
index 967931f..47c5a17 100644
--- a/packages/cli/src/schema/config.ts
+++ b/packages/cli/src/schema/config.ts
@@ -60,18 +60,11 @@ export const Config = z.object({
recordHeadless: z.boolean().default(false),
/** Port the local map server binds on `127.0.0.1`. */
serverPort: z.int().min(1).max(65535).default(4747),
- /** Default for new projects; `init` asks per repo. Story 9.3: the record travels. */
- gitPolicy: z.enum(["ignore", "commit"]).default("commit"),
/**
* Whether `.cogit/conversations/` (the raw chat text) travels too. Off by
- * default: the session record can be committed while the chat stays local.
+ * default: the session record can be shared while the chat stays local.
*/
shareConversations: z.boolean().default(false),
- /**
- * What happens to the session files the last code commit left behind: ask the
- * user at the next session start, commit them at session end, or do nothing.
- */
- recordCommit: z.enum(["ask", "auto", "off"]).default("ask"),
/**
* How long `.cogit/HEAD` stays fresh for the `Thought:` trailer (Story 9.4).
* A commit made hours after the last message is probably not that message.
diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.ts
index 5e75f4b..73c9ff2 100644
--- a/packages/cli/src/server.ts
+++ b/packages/cli/src/server.ts
@@ -18,7 +18,6 @@ import { regenerateShape } from "./commands/shape.js";
import { diffTooLarge, isDiffSha, readCommitDiff } from "./diff.js";
import { defaultsPrompter, type Io } from "./io.js";
import { Config } from "./schema/config.js";
-import { refreshShareConversations } from "./share.js";
import {
CAPTURE_ID,
CaptureTransitionError,
@@ -597,8 +596,6 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
return;
}
// Story 9.3: un-ignore (or hide) the conversation store in every project.
- if (key === "shareConversations")
- await refreshShareConversations(env, next.data.shareConversations);
res.writeHead(200, {
"content-type": "application/json",
"cache-control": "no-store",
diff --git a/packages/cli/src/session-git.ts b/packages/cli/src/session-git.ts
index b91bbea..3b937d4 100644
--- a/packages/cli/src/session-git.ts
+++ b/packages/cli/src/session-git.ts
@@ -1,19 +1,11 @@
-import { execFile } from "node:child_process";
-import { existsSync } from "node:fs";
-import { relative, sep } from "node:path";
-import { promisify } from "node:util";
import { z } from "zod";
-import { findGitRoot } from "./git.js";
import { Slug } from "./schema/common.js";
import { readJson } from "./store/fs.js";
import { projectPaths } from "./store/paths.js";
-import { loadConfig, loadSession } from "./store/stores.js";
-
-const exec = promisify(execFile);
/**
* What the UserPromptSubmit hook leaves in `.cogit/HEAD` (Story 9.3): the session
- * a code commit in this working tree carries, and where its transcript is.
+ * a code commit in this working tree belongs to, and where its transcript is.
*/
export const SessionHead = z.object({
sessionId: Slug,
@@ -28,139 +20,3 @@ export async function readSessionHead(root: string): Promise<SessionHead | undef
const parsed = SessionHead.safeParse(read.value);
return parsed.success ? parsed.data : undefined;
}
-
-interface GitResult {
- code: number;
- stdout: string;
-}
-
-/** Git with `-C`, never throwing: the exit code and stdout are what callers need. */
-async function git(
- root: string,
- args: string[],
- env: NodeJS.ProcessEnv = process.env,
-): Promise<GitResult> {
- try {
- const { stdout } = await exec("git", ["-C", root, ...args], { env });
- return { code: 0, stdout };
- } catch (err) {
- const failure = err as { code?: number | string; stdout?: string };
- return {
- code: typeof failure.code === "number" ? failure.code : 1,
- stdout: failure.stdout ?? "",
- };
- }
-}
-
-/**
- * The current session's files as paths git understands, relative to the git
- * root. A project inside a repository subdirectory keeps its own prefix, so the
- * hook stages what it actually wrote. Missing files are left out: a session that
- * recorded nothing has nothing to carry.
- */
-async function sessionPaths(gitRoot: string, root: string, sessionId: string): Promise<string[]> {
- const paths = projectPaths(root);
- const session = [paths.session(sessionId), paths.events(sessionId)].filter((file) =>
- existsSync(file),
- );
- if (session.length === 0) return [];
- // The project file and the ignore rules travel with the first record: a clone
- // without them has sessions but no project, and no rules for the local state.
- const shared = [paths.project, paths.gitignore].filter((file) => existsSync(file));
- return [...session, ...shared]
- .map((file) => relative(gitRoot, file).split(sep).join("/"))
- .filter((file) => file !== "" && !file.startsWith(".."));
-}
-
-/** True when the ignore policy keeps these paths out of git: staging would fail. */
-async function ignored(gitRoot: string, path: string, env: NodeJS.ProcessEnv): Promise<boolean> {
- return (await git(gitRoot, ["check-ignore", "-q", "--", path], env)).code === 0;
-}
-
-/**
- * Something other than the session files is already staged. The pre-commit hook
- * must never create a record-only commit, so with an empty index it does nothing.
- * An initial commit (no HEAD yet) counts as staged: the user is committing.
- */
-async function hasStagedChanges(gitRoot: string, env: NodeJS.ProcessEnv): Promise<boolean> {
- return (await git(gitRoot, ["diff", "--cached", "--quiet", "--exit-code"], env)).code !== 0;
-}
-
-/** True when this session's files differ from HEAD (or are untracked). */
-export async function uncommittedSession(
- root: string,
- sessionId: string,
- env: NodeJS.ProcessEnv = process.env,
-): Promise<boolean> {
- const gitRoot = await findGitRoot(root);
- if (gitRoot === undefined) return false;
- const paths = await sessionPaths(gitRoot, root, sessionId);
- if (paths.length === 0) return false;
- if (await ignored(gitRoot, paths[0] as string, env)) return false;
- return (await git(gitRoot, ["status", "--porcelain", "--", ...paths], env)).stdout.trim() !== "";
-}
-
-/**
- * Git pre-commit hook (Story 9.3): stage the current session's record so a code
- * commit carries its "why". The session comes from `.cogit/HEAD`, written by the
- * UserPromptSubmit hook. Everything is best-effort: a missing HEAD, an ignored
- * project, an empty index or a failing git all end quietly and the commit runs.
- */
-export async function stageSessionFiles(
- root: string,
- env: NodeJS.ProcessEnv = process.env,
-): Promise<boolean> {
- const head = await readSessionHead(root);
- if (head === undefined) return false;
- const gitRoot = await findGitRoot(root);
- if (gitRoot === undefined) return false;
- const paths = await sessionPaths(gitRoot, root, head.sessionId);
- if (paths.length === 0) return false;
- if (await ignored(gitRoot, paths[0] as string, env)) return false;
- if (!(await hasStagedChanges(gitRoot, env))) return false;
- return (await git(gitRoot, ["add", "--", ...paths], env)).code === 0;
-}
-
-/** The message an `auto` record commit carries; the title is kept to one short line. */
-export function recordMessage(title: string, sessionId: string): string {
- const clean = title.replace(/\s+/g, " ").trim() || sessionId;
- return `chore(cogit): record ${clean.length > 120 ? `${clean.slice(0, 119)}…` : clean}`;
-}
-
-/**
- * Commits exactly this session's record files (Story 9.3, `recordCommit: auto`).
- * Other staged changes stay staged: the commit is restricted to these paths. A
- * missing git, an ignored project or nothing to commit is not an error.
- */
-export async function commitSessionFiles(
- root: string,
- sessionId: string,
- title: string,
- env: NodeJS.ProcessEnv = process.env,
-): Promise<boolean> {
- const gitRoot = await findGitRoot(root);
- if (gitRoot === undefined) return false;
- const paths = await sessionPaths(gitRoot, root, sessionId);
- if (paths.length === 0) return false;
- if (await ignored(gitRoot, paths[0] as string, env)) return false;
- if ((await git(gitRoot, ["status", "--porcelain", "--", ...paths], env)).stdout.trim() === "")
- return false;
- if ((await git(gitRoot, ["add", "--", ...paths], env)).code !== 0) return false;
- // --no-verify: the record commit must not set off the hooks it is part of.
- const message = recordMessage(title, sessionId);
- return (
- (await git(gitRoot, ["commit", "--no-verify", "-m", message, "--", ...paths], env)).code === 0
- );
-}
-
-/** The `recordCommit` setting applied at session end: only `auto` commits here. */
-export async function maybeAutoCommit(
- root: string,
- sessionId: string,
- env: NodeJS.ProcessEnv,
-): Promise<boolean> {
- if ((await loadConfig(env)).recordCommit !== "auto") return false;
- const loaded = await loadSession(root, sessionId);
- const title = loaded.found && loaded.ok ? loaded.data.title : "";
- return commitSessionFiles(root, sessionId, title, env);
-}
diff --git a/packages/cli/src/share.ts b/packages/cli/src/share.ts
deleted file mode 100644
index b5ab1a7..0000000
--- a/packages/cli/src/share.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { refreshCogitGitignore } from "./git.js";
-import { isDirectory } from "./store/fs.js";
-import { loadRegistry } from "./store/stores.js";
-
-/**
- * Applies a change of `shareConversations` to every registered project (Story
- * 9.3): a project that commits its records gets `conversations/` un-ignored (or
- * hidden again) right away, not only on its next build. Missing directories and
- * unwritable ignore files are skipped in silence; this is derived state.
- */
-export async function refreshShareConversations(
- env: NodeJS.ProcessEnv,
- share: boolean,
-): Promise<void> {
- const registry = await loadRegistry(env);
- if (!registry.found || !registry.ok) return;
- for (const entry of registry.data.projects) {
- if (!(await isDirectory(entry.path))) continue;
- try {
- await refreshCogitGitignore(entry.path, share);
- } catch {
- // A read-only project keeps its previous rules; the next build retries.
- }
- }
-}
diff --git a/packages/cli/src/store/fs.ts b/packages/cli/src/store/fs.ts
index 99987c9..88c6bbb 100644
--- a/packages/cli/src/store/fs.ts
+++ b/packages/cli/src/store/fs.ts
@@ -12,7 +12,7 @@ export async function isDirectory(path: string): Promise<boolean> {
}
/** Writes via a temp file in the same directory and renames it into place. */
-export async function atomicWrite(file: string, data: string): Promise<void> {
+export async function atomicWrite(file: string, data: string | Uint8Array): Promise<void> {
const dir = dirname(file);
await mkdir(dir, { recursive: true });
const tmp = join(dir, `.${basename(file)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.ts
index 4927cbe..c68bfcd 100644
--- a/packages/cli/src/store/paths.ts
+++ b/packages/cli/src/store/paths.ts
@@ -40,6 +40,8 @@ export function projectPaths(root: string) {
captures: join(base, "state", "captures.json"),
/** What the detached hook children (build, side run) printed; local, capped. */
detachedLog: join(base, "state", "detached.log"),
+ /** What the record refs last looked like, and what waits to be sent; local. */
+ recordSync: join(base, "state", "record-sync.json"),
/** Commits waiting for their message's record before a Shape; local. */
shapeQueue: join(base, "state", "shape-queue"),
locks: join(base, "locks"),
diff --git a/packages/cli/src/store/root.ts b/packages/cli/src/store/root.ts
index 3bc2b44..fdeddc2 100644
--- a/packages/cli/src/store/root.ts
+++ b/packages/cli/src/store/root.ts
@@ -44,11 +44,12 @@ async function readBranch(gitdir: string): Promise<string | null> {
}
/**
- * Finds the `.cogit/` for a directory. A linked git worktree has no copy of
- * a git-ignored `.cogit/`, so it shares the main checkout's, the same way
- * Claude Code keeps worktree state in the main checkout. With `.cogit/`
- * committed, the worktree has its own copy and keeps it. Only files are read
- * (`.git` → `gitdir` → `commondir`), so git itself is never needed.
+ * Finds the `.cogit/` for a directory. The record is ignored by git, so a linked
+ * worktree shares the main checkout's, the same way Claude Code keeps worktree
+ * state there: a session must not vanish with its worktree. A shared project's
+ * marker is tracked and so appears in the worktree too, which is why the main
+ * checkout is asked first. Only files are read (`.git` → `gitdir` → `commondir`),
+ * so git itself is never needed.
*/
export async function resolveProjectRoot(dir: string): Promise<ProjectRoot> {
const start = resolve(dir);
@@ -60,11 +61,12 @@ export async function resolveProjectRoot(dir: string): Promise<ProjectRoot> {
}
const worktree = { path: linked.top, branch: await readBranch(linked.gitdir) };
await migrateProject(start);
- if (existsSync(projectPaths(start).project)) return { root: start, worktree };
const common = (await readFile(join(linked.gitdir, "commondir"), "utf8")).trim();
const mainTop = dirname(resolve(linked.gitdir, common));
const root = join(mainTop, relative(linked.top, start));
await migrateProject(root);
+ if (!existsSync(projectPaths(root).project) && existsSync(projectPaths(start).project))
+ return { root: start, worktree };
return { root, worktree };
} catch {
// An unreadable or odd `.git` layout falls back to the directory itself.
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index 91d300f..1501528 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -42,7 +42,6 @@ export const PANEL_EDITABLE_KEYS = [
"captures",
"language",
"shareConversations",
- "recordCommit",
] as const;
export type PanelEditableKey = (typeof PANEL_EDITABLE_KEYS)[number];
@@ -299,6 +298,8 @@ export interface ViewInboxRow {
}
export interface LineageViewModel {
+ /** A shared project's first download failed, so an empty map does not mean an empty record. */
+ recordDownloadFailed?: boolean;
kind: "lineage";
schema: typeof VIEW_SCHEMA;
project: {
@@ -430,7 +431,7 @@ export interface PanelProject {
}
/**
- * Global settings on the panel. `gitPolicy` and `agents` are shown read-only;
+ * Global settings on the panel. `agents` is shown read-only;
* the keys in `PANEL_EDITABLE_KEYS` are editable when the page comes from the
* local server (over `file://` everything stays read-only).
*/
@@ -464,8 +465,6 @@ export interface PanelSettings {
*/
captures: boolean;
shareConversations: boolean;
- recordCommit: "ask" | "auto" | "off";
- gitPolicy: "ignore" | "commit";
agents: string[];
/** A message whose linked commits crossed this many lines counts as big (10.3). */
bigChangeLines: number;
diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.ts
index a56378d..9046c86 100644
--- a/packages/cli/src/view/panel.ts
+++ b/packages/cli/src/view/panel.ts
@@ -68,8 +68,6 @@ export function panelSettings(config: Config): PanelSettings {
shapes: config.shapes,
captures: config.captures,
shareConversations: config.shareConversations,
- recordCommit: config.recordCommit,
- gitPolicy: config.gitPolicy,
agents: config.agents,
bigChangeLines: config.bigChangeLines,
};
diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.ts
index fb9ba9e..e42e02c 100644
--- a/packages/cli/src/view/settings.ts
+++ b/packages/cli/src/view/settings.ts
@@ -142,21 +142,12 @@ const EDITABLE: FieldSpec[] = [
{
key: "shareConversations",
label: "Share conversations",
- help: "Commit the raw chat text too, not only the session record (off: chat stays local).",
+ help: "Send the raw chat text too, not only the session record (off: chat stays local).",
details:
- "Also commit the raw chat text, not only the record. Leave it off to keep conversations " +
- "on your machine while the record still travels with the branch.",
+ "In a project that shares its record, also send the raw chat text. Leave it off to keep " +
+ "conversations on your machine while teammates still see titles, decisions and reasons.",
kind: "boolean",
},
- {
- key: "recordCommit",
- label: "Commit the record",
- help: "ask, auto or off: what to do with the last messages after the last code commit.",
- details:
- "What happens to record changes made after your last code commit: ask you next time, " +
- "commit them automatically, or leave them for you to commit.",
- kind: "text",
- },
];
/** A setting only `cogit config` changes: per project, set up once, or rarely touched. */
@@ -203,15 +194,6 @@ export const CLI_ONLY: CliSetting[] = [
"time in side mode, and at session end. Haiku is cheap and good enough for titles, " +
"parents and short decisions.",
},
- {
- key: "gitPolicy",
- label: "Git policy",
- help: "What `cogit init` offers a new project: commit the record to git, or ignore it.",
- details:
- "Only the default for new projects: each project answers it during `cogit init`. " +
- "`cogit config git` shows the current project's policy and `cogit config git commit` " +
- "or `ignore` switches it.",
- },
{
key: "agents",
label: "Agents",
@@ -297,8 +279,6 @@ export const DEFAULT_SETTINGS: PanelSettings = {
shapes: true,
captures: true,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "commit",
agents: ["claude-code"],
bigChangeLines: 300,
};
@@ -319,7 +299,6 @@ export function editableSettings(settings: PanelSettings): PanelEditableSettings
captures: settings.captures,
language: settings.language,
shareConversations: settings.shareConversations,
- recordCommit: settings.recordCommit,
};
}
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index 3533a71..5a3d5f7 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -581,8 +581,6 @@ describe("cogit build", () => {
recorder: "side",
updateEveryTurns: 15,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "commit",
agents: ["claude-code"],
});
expect(embedded(await readFile(paths().html, "utf8"))).toEqual(model);
@@ -834,13 +832,14 @@ describe("cogit build", () => {
it("writes the project ignore rules once, also in an existing project", async () => {
const ignore = join(paths().base, ".gitignore");
- // A commit-policy project: a git dir and no root rule hiding .cogit/.
+ // A shared project: a git dir and no root rule hiding .cogit/.
await mkdir(join(root, ".git"));
+ await rm(join(root, ".gitignore"), { force: true });
await rm(ignore, { force: true });
await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
- expect(await readFile(ignore, "utf8")).toBe(cogitGitignore(false));
+ expect(await readFile(ignore, "utf8")).toBe(cogitGitignore());
await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
- expect(await readFile(ignore, "utf8")).toBe(cogitGitignore(false));
+ expect(await readFile(ignore, "utf8")).toBe(cogitGitignore());
});
it("keeps the map when the conversation store cannot be written", async () => {
@@ -869,12 +868,13 @@ describe("cogit build", () => {
it("warns but still builds when the inner gitignore cannot be written", async () => {
const ignore = join(paths().base, ".gitignore");
await mkdir(join(root, ".git"));
+ await rm(join(root, ".gitignore"), { force: true });
await rm(ignore, { force: true });
await mkdir(ignore);
const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
expect(model.sessions).toEqual([]);
expect(io.warnings).toEqual(
- expect.arrayContaining([expect.stringMatching(/^could not update \.cogit\/\.gitignore: /)]),
+ expect.arrayContaining([expect.stringMatching(/^could not update the shared record: /)]),
);
});
diff --git a/packages/cli/test/config-epoch.test.ts b/packages/cli/test/config-epoch.test.ts
index 18f933a..22575b5 100644
--- a/packages/cli/test/config-epoch.test.ts
+++ b/packages/cli/test/config-epoch.test.ts
@@ -27,8 +27,6 @@ describe("config", () => {
expect(io.lines.some((line) => line.startsWith("catchUpModel"))).toBe(false);
expect(io.lines).toContain("messageSummaries = false");
expect(io.lines).toContain("startupContext = true");
- await configGet("gitPolicy", io);
- expect(io.lines.at(-1)).toBe('"commit"');
// The old name reads as the new one (Story 12.1).
await configGet("catchUpModel", io);
expect(io.lines.at(-1)).toBe('"haiku"');
@@ -85,7 +83,7 @@ describe("config", () => {
await expect(configSet("schema", "2", fakeIo(env))).rejects.toThrow(/unknown key/);
await expect(configGet("nope", fakeIo(env))).rejects.toBeInstanceOf(CliError);
await expect(configSet("updateEveryTurns", "0", fakeIo(env))).rejects.toThrow(/invalid value/);
- await expect(configSet("gitPolicy", "maybe", fakeIo(env))).rejects.toThrow(/invalid value/);
+ await expect(configSet("gitPolicy", "share", fakeIo(env))).rejects.toThrow(/unknown key/);
});
});
diff --git a/packages/cli/test/doctor.test.ts b/packages/cli/test/doctor.test.ts
index 4953466..dfe8e55 100644
--- a/packages/cli/test/doctor.test.ts
+++ b/packages/cli/test/doctor.test.ts
@@ -45,7 +45,7 @@ async function project(name = "proj"): Promise<string> {
root,
{
name,
- git: "commit",
+ git: "share",
retention: "keep",
allowSkill: false,
projectSettings: false,
@@ -390,6 +390,7 @@ describe("doctor", () => {
"plugin",
"git",
"project",
+ "record",
"skill",
"transcripts",
"sessions",
diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.ts
index a6a961c..336fa8f 100644
--- a/packages/cli/test/helpers.ts
+++ b/packages/cli/test/helpers.ts
@@ -23,7 +23,7 @@ export async function noGitDir(): Promise<string> {
export async function noGitProject(env: NodeJS.ProcessEnv, name = "plain"): Promise<string> {
const dir = join(await noGitDir(), name);
await mkdir(join(dir, ".git"), { recursive: true });
- const options = { name, git: "commit", retention: "keep", language: "auto" } as const;
+ const options = { name, git: "share", retention: "keep", language: "auto" } as const;
await init(dir, { ...options, allowSkill: false, projectSettings: false }, fakeIo(env));
await rm(join(dir, ".git"), { recursive: true, force: true });
return dir;
diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.ts
index 01e2012..7d0a70d 100644
--- a/packages/cli/test/hooks.test.ts
+++ b/packages/cli/test/hooks.test.ts
@@ -533,20 +533,6 @@ describe("runHook", () => {
expect(spawned).toEqual([]);
});
- it("commits the record at session end in auto mode, even with the catch-up off", async () => {
- await initialized(2);
- await configSet("recordCommit", "auto", fakeIo(env));
- // Nothing to catch up: the last update still leaves files to commit.
- expect(await sessionEnd()).toBeUndefined();
- expect(spawned).toEqual([["/plugin/dist/cli.js", "record-commit", "s1", "-C", root]]);
-
- spawned = [];
- await transcript([typed("first", 1)]);
- await configSet("sessionEndCatchUp", "false", fakeIo(env));
- expect(await sessionEnd()).toBeUndefined();
- expect(spawned).toEqual([["/plugin/dist/cli.js", "record-commit", "s1", "-C", root]]);
- });
-
it("records the current session for the next code commit", async () => {
await initialized(2);
await runHook(
@@ -578,8 +564,8 @@ describe("runHook", () => {
it("points an existing git hook block at the CLI running now", async () => {
await initialized(2);
await promisify(execFile)("git", ["-C", root, "init", "-q"]);
- const hook = join(root, ".git", "hooks", "pre-commit");
- await writeFile(hook, "#!/bin/sh\n# >>> cogit\ncogit hook pre-commit || true\n# <<< cogit\n");
+ const hook = join(root, ".git", "hooks", "post-commit");
+ await writeFile(hook, "#!/bin/sh\n# >>> cogit\ncogit hook post-commit || true\n# <<< cogit\n");
await runHook(
"promptsubmit",
JSON.stringify({ session_id: "s1", cwd: root }),
@@ -587,7 +573,7 @@ describe("runHook", () => {
T0,
() => {},
);
- expect(await readFile(hook, "utf8")).toContain(hookBlock("pre-commit", root));
+ expect(await readFile(hook, "utf8")).toContain(hookBlock("post-commit", root));
});
it("stays quiet at session end without a readable transcript or before init", async () => {
diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.ts
index 1dcc60f..3c6b03e 100644
--- a/packages/cli/test/init.test.ts
+++ b/packages/cli/test/init.test.ts
@@ -84,10 +84,11 @@ describe("init", () => {
expect(io.lines.at(-2)).toMatch(/^Initialized proj/);
// No plugin list in this Claude Code config: the last line says how to install it.
expect(io.lines.at(-1)).toContain("claude plugin install cogit --marketplace erensrtky/cogit");
- // The default commit policy writes the project's own ignore rules.
- expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));
+ // No answer shares nothing: the root rule hides the whole folder.
+ expect(await readText(join(root, ".gitignore"))).toContain("/.cogit/");
+ expect(existsSync(join(root, ".cogit", ".gitignore"))).toBe(false);
expect(io.lines).toContain(
- "Conversations are stored in .cogit/conversations/ (kept out of git; turn on shareConversations to share them).",
+ "Conversations are stored in .cogit/conversations/ and stay on this machine.",
);
});
@@ -116,14 +117,13 @@ describe("init", () => {
expect(await readPluginInstalled({ CLAUDE_CONFIG_DIR: join(dir, "nowhere") })).toBeUndefined();
});
- it("writes the project ignore file once for the commit policy", async () => {
+ it("writes the project ignore file once for a shared project", async () => {
await mkdir(join(root, ".cogit"));
- expect(await ensureCogitGitignore(root, "commit", false)).toBe(true);
- expect(await ensureCogitGitignore(root, "commit", false)).toBe(false);
- expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));
- // Sharing the conversation store un-ignores it in the same file.
- expect(await ensureCogitGitignore(root, "commit", true)).toBe(true);
- expect(await readText(join(root, ".cogit", ".gitignore"))).toContain("!conversations/");
+ expect(await ensureCogitGitignore(root, "share")).toBe(true);
+ expect(await ensureCogitGitignore(root, "share")).toBe(false);
+ expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore());
+ // Only the marker travels through commits; the sessions have their own refs.
+ expect(await readText(join(root, ".cogit", ".gitignore"))).not.toContain("sessions");
});
it("asks nothing when every answer is given as an option", async () => {
@@ -133,7 +133,7 @@ describe("init", () => {
root,
{
name: "P",
- git: "commit",
+ git: "share",
retention: "keep",
allowSkill: false,
projectSettings: false,
@@ -144,7 +144,7 @@ describe("init", () => {
expect((await loadConfig(env)).language).toBe("Turkish");
// Commit policy: the root file stays untouched, the project writes its own rules.
expect(existsSync(join(root, ".gitignore"))).toBe(false);
- expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));
+ expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore());
});
it("asks for the git policy in a repo and writes .gitignore", async () => {
@@ -158,7 +158,7 @@ describe("init", () => {
it("raises transcript retention when asked, keeping other settings", async () => {
await mkdir(join(dir, "claude"));
await writeFile(settingsFile(), JSON.stringify({ model: "x" }));
- const io = fakeIo(env, ["commit", "365"]);
+ const io = fakeIo(env, ["share", "365"]);
await init(root, {}, io);
expect(JSON.parse(await readText(settingsFile()))).toEqual({
model: "x",
@@ -190,7 +190,7 @@ describe("init", () => {
root,
{
name: "p",
- git: "commit",
+ git: "share",
retention: 90,
allowSkill: false,
projectSettings: false,
@@ -204,7 +204,7 @@ describe("init", () => {
const io = fakeIo(env, [], true);
await init(
again,
- { name: "o", git: "commit", retention: 90, allowSkill: false, projectSettings: false },
+ { name: "o", git: "share", retention: 90, allowSkill: false, projectSettings: false },
io,
);
expect(io.lines.some((l) => l.includes("cleanupPeriodDays"))).toBe(false);
@@ -213,7 +213,7 @@ describe("init", () => {
it("applies a retention option to a project that is already set up", async () => {
const options = {
name: "p",
- git: "commit",
+ git: "share",
allowSkill: false,
projectSettings: false,
language: "auto",
@@ -234,7 +234,7 @@ describe("init", () => {
});
it("takes the conversation's language without asking, and the option when given", async () => {
- const io = fakeIo(env, ["commit", "keep"]);
+ const io = fakeIo(env, ["share", "keep"]);
await init(root, {}, io);
expect((await loadConfig(env)).language).toBe("auto");
expect(io.asked.some((q) => q.startsWith("Language"))).toBe(false);
@@ -250,7 +250,7 @@ describe("init", () => {
settingsFile(),
JSON.stringify({ permissions: { allow: ["Bash(ls)"], deny: [] } }),
);
- const io = fakeIo(env, ["commit", "keep", "yes"]);
+ const io = fakeIo(env, ["share", "keep", "yes"]);
await init(root, {}, io);
expect(JSON.parse(await readText(settingsFile())).permissions).toEqual({
allow: ["Bash(ls)", SKILL_RULE],
@@ -265,7 +265,7 @@ describe("init", () => {
});
it("leaves permissions alone when declined with the flag", async () => {
- const io = fakeIo(env, ["commit", "keep"]);
+ const io = fakeIo(env, ["share", "keep"]);
await init(root, { allowSkill: false }, io);
expect(await readSkillAllowed(env)).toBe(false);
expect(io.lines).toContain(
@@ -329,7 +329,7 @@ describe("git helpers", () => {
it("adds the ignore line under the ignore policy and removes it when switching", async () => {
const gi = join(root, ".gitignore");
await writeFile(gi, "node_modules/");
- expect(await ensureGitignore(root, "commit")).toEqual([]);
+ expect(await ensureGitignore(root, "share")).toEqual([]);
expect(await readText(gi)).toBe("node_modules/");
expect(await ensureGitignore(root, "ignore")).toEqual(["/.cogit/"]);
expect(await ensureGitignore(root, "ignore")).toEqual([]);
@@ -337,7 +337,7 @@ describe("git helpers", () => {
expect(text).toBe("node_modules/\n# cogit\n/.cogit/\n");
expect(text.match(/# cogit/g)).toHaveLength(1);
// Switching back removes only our line, never the user's.
- expect(await ensureGitignore(root, "commit")).toEqual([]);
+ expect(await ensureGitignore(root, "share")).toEqual([]);
expect(await readText(gi)).toBe("node_modules/\n# cogit\n");
expect(basename(gi)).toBe(".gitignore");
});
@@ -373,7 +373,7 @@ describe("git helpers", () => {
expect(set.warnings.join("\n")).not.toMatch(/user\.email/);
});
- it("restores the record hook when init runs again on a commit project", async () => {
+ it("restores the send hook when init runs again on a shared project", async () => {
const run = promisify(execFile);
const git = (...args: string[]) => run("git", ["-C", root, ...args]);
await git("init", "-q");
@@ -381,10 +381,10 @@ describe("git helpers", () => {
await git("config", "user.name", "Tester");
await init(
root,
- { name: "P", git: "commit", retention: "keep", allowSkill: false, language: "auto" },
+ { name: "P", git: "share", retention: "keep", allowSkill: false, language: "auto" },
fakeIo(env),
);
- const hook = join(root, ".git", "hooks", "pre-commit");
+ const hook = join(root, ".git", "hooks", "pre-push");
expect(existsSync(hook)).toBe(true);
await rm(hook);
const io = fakeIo(env);
diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.ts
index 29a9f1a..13af06d 100644
--- a/packages/cli/test/panel.test.ts
+++ b/packages/cli/test/panel.test.ts
@@ -94,8 +94,6 @@ describe("buildPanel", () => {
shapes: true,
captures: true,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "commit",
agents: ["claude-code"],
bigChangeLines: 300,
},
diff --git a/packages/cli/test/pr.test.ts b/packages/cli/test/pr.test.ts
index 77024fc..92a0741 100644
--- a/packages/cli/test/pr.test.ts
+++ b/packages/cli/test/pr.test.ts
@@ -136,7 +136,7 @@ describe("cogit pr (Story 10.1)", () => {
await git("branch", "main");
await init(
root,
- { name: "proj", git: "commit", retention: "keep", language: "auto" },
+ { name: "proj", git: "share", retention: "keep", language: "auto" },
fakeIo(env),
);
await writeFile(projectPaths(root).session("s1"), JSON.stringify(session()));
@@ -225,7 +225,7 @@ describe("cogit pr (Story 10.1)", () => {
`- \`${commitHashes[3]?.slice(0, 7)}\` docs: describe the parser — thought \`${C}\` not recorded yet`,
);
expect(text).toContain("## Dig deeper");
- expect(text).toContain("a reviewer who checks it out");
+ expect(text).toContain("a reviewer with cogit in their clone");
expect(text).not.toContain(SECRET);
expect(text).not.toContain("Conversation:");
});
@@ -280,7 +280,7 @@ describe("cogit pr (Story 10.1)", () => {
await run("git", ["-C", empty, "init", "-q"], { env });
await init(
empty,
- { name: "empty", git: "commit", retention: "keep", language: "auto" },
+ { name: "empty", git: "share", retention: "keep", language: "auto" },
fakeIo(env),
);
await expect(pr({ dir: empty, io })).rejects.toThrow(/HEAD has no commits yet/);
@@ -310,7 +310,7 @@ describe("cogit pr (Story 10.1)", () => {
const model: PrModel = {
base: { ref: "main", commit: "0".repeat(40) },
head: "1".repeat(40),
- policy: "commit",
+ policy: "share",
goals: [{ text: "A goal", sessionId: "s1", sessionTitle: "Session" }],
sessions: [
{
diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.ts
index 259cf45..10234fe 100644
--- a/packages/cli/test/program-commands.test.ts
+++ b/packages/cli/test/program-commands.test.ts
@@ -279,7 +279,7 @@ describe("commands through the CLI", () => {
expect(io.lines.at(-1)).toMatch(new RegExp(`^Removed .+ \\(${gone}\\)$`));
});
- it("runs the git hook and the detached record commit through the CLI", async () => {
+ it("runs the git hooks through the CLI", async () => {
const run = promisify(execFile);
const git = async (...args: string[]): Promise<string> =>
(await run("git", ["-C", root, ...args])).stdout;
@@ -295,7 +295,7 @@ describe("commands through the CLI", () => {
root,
"--yes",
"--git",
- "commit",
+ "share",
"--name",
"P",
"--retention",
@@ -303,8 +303,8 @@ describe("commands through the CLI", () => {
"--language",
"auto",
);
- expect(await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8")).toContain(
- "cogit hook pre-commit",
+ expect(await readFile(join(root, ".git", "hooks", "pre-push"), "utf8")).toContain(
+ "cogit hook pre-push",
);
await cli("hooks", "install", root);
expect(io.lines.at(-1)).toBe("The cogit hook blocks are already current.");
@@ -324,25 +324,29 @@ describe("commands through the CLI", () => {
await writeFile(join(root, ".cogit", "HEAD"), JSON.stringify({ sessionId: "s1", at: T0 }));
await writeFile(join(root, "a.txt"), "two\n");
await git("add", "a.txt");
+ // A block a past version left behind stays quiet and stages nothing.
+ await git("add", "a.txt");
await cli("hook", "pre-commit", "--dir", root);
- expect(await git("diff", "--cached", "--name-only")).toContain(".cogit/sessions/s1.json");
-
- await cli("config", "set", "recordCommit", "auto");
- await cli("record-commit", "s1", "-C", root);
- expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record CLI session");
-
- expect(await cli("config", "git", "nope")).toMatch(/^error: invalid git policy "nope"/);
- // Without a policy it reports the current one instead of refusing.
- expect(await cli("config", "git")).not.toMatch(/invalid git policy/);
- expect(await cli("config", "git", "ignore", root)).toBe("");
- expect(await readFile(join(root, ".gitignore"), "utf8")).toBe("# cogit\n/.cogit/\n");
+ expect(await git("diff", "--cached", "--name-only")).not.toContain(".cogit/sessions");
+ // No remote to send to: the hook is silent.
+ await cli("hook", "pre-push", "--dir", root, "origin", "nowhere");
+ await cli("record-sync", "send", "-C", root);
+ await cli("record-sync", "download", "-C", root);
+ expect(await cli("record-sync", "elsewhere", "-C", root)).toMatch(/unknown record-sync action/);
+ await cli("config", "git", "share", root);
+ expect(io.lines.at(-1)).toBe("Git policy for P: share");
+ expect(await cli("config", "git", "commit", root)).toMatch(/invalid git policy/);
+ await cli("prune", "--older-than", "1y", "--dry-run", "-C", root);
+ expect(io.lines.at(-1)).toBe("No sessions older than 1y.");
+ // Outside any project the read command reports it, after looking all the way up.
+ expect(await cli("log", await noGitDir())).toMatch(/not initialized/);
});
it("refuses init and config git outside a git repository", async () => {
const outside = await noGitDir();
expect(await cli("init", outside, "--yes")).toMatch(/not in a git repository.*git init/);
const plain = await noGitProject(envFor(dir));
- expect(await cli("config", "git", "commit", plain)).toMatch(/not in a git repository/);
+ expect(await cli("config", "git", "share", plain)).toMatch(/not in a git repository/);
});
it("prints user errors as one line", async () => {
diff --git a/packages/cli/test/record-sync.test.ts b/packages/cli/test/record-sync.test.ts
new file mode 100644
index 0000000..261851a
--- /dev/null
+++ b/packages/cli/test/record-sync.test.ts
@@ -0,0 +1,601 @@
+import { execFile } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { beforeEach, describe, expect, it } from "vitest";
+import { doctor } from "../src/commands/doctor.js";
+import { init } from "../src/commands/init.js";
+import { pruneCutoff, pruneRecords } from "../src/commands/prune.js";
+import { installGitHooks, runGitHook } from "../src/git-hooks.js";
+import { runHook } from "../src/hooks/run.js";
+import { prepareRecords } from "../src/record-prepare.js";
+import {
+ addRecordRefspec,
+ deleteRecords,
+ downloadRecords,
+ importRecords,
+ isSharing,
+ queueRecords,
+ RECORD_REFSPEC,
+ reconcileRecords,
+ recordSyncStatus,
+ sendRecords,
+ snapshotRecords,
+ syncRemote,
+ trackedRecordFiles,
+} from "../src/record-sync.js";
+import type { Session } from "../src/schema/session.js";
+import { projectPaths } from "../src/store/paths.js";
+import { resolveProjectRoot } from "../src/store/root.js";
+import { loadSession, updateConfig } from "../src/store/stores.js";
+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";
+
+const run = promisify(execFile);
+const TEMPLATE =
+ '<!doctype html><html><head><script id="cogit-data" type="application/json"></script></head></html>';
+
+describe("the record on its own refs", () => {
+ let dir: string;
+ let remote: string;
+ let alice: string;
+ let env: NodeJS.ProcessEnv;
+ let gitEnv: NodeJS.ProcessEnv;
+
+ const git = async (cwd: string, ...args: string[]): Promise<string> => {
+ const { stdout } = await run("git", ["-C", cwd, ...args], { env: gitEnv });
+ return stdout;
+ };
+
+ const session = (id: string, title: string, email: string, updatedAt = T0): Session => ({
+ schema: 1,
+ sessionId: id,
+ agent: "claude-code",
+ title,
+ startedAt: T0,
+ updatedAt,
+ authorEmail: email,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [],
+ });
+
+ const record = async (root: string, id: string, title: string, email: string): Promise<void> => {
+ const paths = projectPaths(root);
+ await mkdir(paths.sessions, { recursive: true });
+ await writeFile(paths.session(id), JSON.stringify(session(id, title, email)));
+ await writeFile(paths.events(id), `{"event":"${title}"}\n`);
+ };
+
+ const title = async (root: string, id: string): Promise<string | undefined> => {
+ const loaded = await loadSession(root, id);
+ return loaded.found && loaded.ok ? loaded.data.title : undefined;
+ };
+
+ const refs = async (cwd: string, base = "refs/cogit"): Promise<string[]> =>
+ (await git(cwd, "for-each-ref", "--format=%(refname)", base)).split("\n").filter(Boolean);
+
+ /** A second person's clone, as `git clone` leaves it: no refspec, no hooks, no record. */
+ const cloneAs = async (name: string): Promise<string> => {
+ const target = join(dir, name);
+ await run("git", ["clone", "-q", remote, target], { env: gitEnv });
+ await git(target, "config", "user.email", `${name}@example.com`);
+ await git(target, "config", "user.name", name);
+ return target;
+ };
+
+ const initShared = async (root: string): Promise<void> => {
+ await init(
+ root,
+ { name: "proj", git: "share", retention: "keep", allowSkill: false, projectSettings: false },
+ fakeIo(env),
+ );
+ };
+
+ const push = async (root: string): Promise<number> => {
+ const queued = await queueRecords(root, env, "origin");
+ if (queued > 0) await sendRecords(root, env);
+ return queued;
+ };
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ env = envFor(dir);
+ gitEnv = { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir };
+ env = { ...env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir };
+ remote = join(dir, "remote.git");
+ await run("git", ["init", "-q", "--bare", "-b", "main", remote], { env: gitEnv });
+ alice = join(dir, "alice");
+ await mkdir(alice);
+ await git(alice, "init", "-q", "-b", "main");
+ await git(alice, "config", "user.email", "[email protected]");
+ await git(alice, "config", "user.name", "alice");
+ await git(alice, "remote", "add", "origin", remote);
+ await writeFile(join(alice, "a.txt"), "one\n");
+ await initShared(alice);
+ await git(alice, "add", "-A");
+ await git(alice, "commit", "-q", "-m", "feat: base");
+ await git(alice, "push", "-q", "-u", "origin", "main");
+ });
+
+ it("keeps the record out of git: only the marker is tracked", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ const tracked = (await git(alice, "ls-files")).split("\n").filter(Boolean);
+ expect(tracked).toEqual(
+ expect.arrayContaining([".cogit/.gitignore", ".cogit/project.json", "a.txt"]),
+ );
+ expect(tracked.some((file) => file.includes("sessions"))).toBe(false);
+ expect(await git(alice, "status", "--short")).toBe("");
+ });
+
+ it("carries a session between two clones without a new command", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ expect(await push(alice)).toBe(1);
+ expect(await git(alice, "status", "--short")).toBe("");
+
+ const bob = await cloneAs("bob");
+ expect(existsSync(projectPaths(bob).session("s1"))).toBe(false);
+ expect(await git(bob, "for-each-ref", "refs/cogit", "refs/cogit-remote")).toBe("");
+
+ await prepareRecords(bob, env, () => {});
+ expect(await title(bob, "s1")).toBe("First");
+ expect(await readFile(projectPaths(bob).events("s1"), "utf8")).toContain("First");
+
+ // From now on a plain `git pull` brings records, even with no new code.
+ await record(alice, "s2", "Second", "[email protected]");
+ await push(alice);
+ await git(bob, "pull", "-q");
+ await reconcileRecords(bob, env);
+ expect(await title(bob, "s2")).toBe("Second");
+ expect(await git(bob, "status", "--short")).toBe("");
+ });
+
+ it("stays out of branches and git log --all", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ expect((await git(alice, "log", "--all", "--oneline")).trim().split("\n")).toHaveLength(1);
+ expect(await git(alice, "branch", "-a")).not.toContain("cogit");
+ });
+
+ it("sends only when the person pushes, and only to the sync remote", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await snapshotRecords(alice, env);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toBe("");
+ expect(await queueRecords(alice, env, "deploy")).toBe(0);
+ expect(await sendRecords(alice, env)).toBe(0);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toBe("");
+ await push(alice);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toContain("s1");
+ });
+
+ it("lets a session update reach a teammate, and keeps two people's refs apart", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const bob = await cloneAs("bob");
+ await prepareRecords(bob, env, () => {});
+
+ await record(alice, "s1", "First, longer", "[email protected]");
+ await record(bob, "b1", "Bob's", "[email protected]");
+ await Promise.all([push(alice), push(bob)]);
+ await git(alice, "pull", "-q");
+ await git(bob, "pull", "-q");
+ await reconcileRecords(alice, env);
+ await reconcileRecords(bob, env);
+ expect(await title(bob, "s1")).toBe("First, longer");
+ expect(await title(alice, "b1")).toBe("Bob's");
+ });
+
+ it("never lets a fetch overwrite what this clone has not sent", async () => {
+ await record(alice, "s1", "Sent", "[email protected]");
+ await push(alice);
+ await record(alice, "s1", "Not sent yet", "[email protected]");
+ await snapshotRecords(alice, env);
+ await downloadRecords(alice, env);
+ await importRecords(alice, env);
+ expect(await title(alice, "s1")).toBe("Not sent yet");
+ expect(await git(alice, "rev-parse", "refs/cogit/sessions/s1")).not.toBe(
+ await git(alice, "rev-parse", "refs/cogit-remote/sessions/s1"),
+ );
+ });
+
+ it("does not send a teammate's session as its own", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const bob = await cloneAs("bob");
+ await prepareRecords(bob, env, () => {});
+ expect(await queueRecords(bob, env, "origin")).toBe(0);
+ // A stale or hand-edited copy of Alice's session is still hers to send.
+ await record(bob, "s1", "Edited by accident", "[email protected]");
+ expect(await queueRecords(bob, env, "origin")).toBe(0);
+ expect(await refs(bob)).toEqual([]);
+ });
+
+ it("brings the files back after git clean", async () => {
+ await record(alice, "s1", "Survives", "[email protected]");
+ await snapshotRecords(alice, env);
+ await git(alice, "clean", "-fdxq");
+ expect(existsSync(projectPaths(alice).session("s1"))).toBe(false);
+ await reconcileRecords(alice, env);
+ expect(await title(alice, "s1")).toBe("Survives");
+ expect(await readFile(projectPaths(alice).events("s1"), "utf8")).toContain("Survives");
+ });
+
+ it("keeps the raw chat local unless shareConversations is on", async () => {
+ const conversation = projectPaths(alice).conversation("s1");
+ await mkdir(join(alice, ".cogit", "conversations"), { recursive: true });
+ await writeFile(conversation, "chat");
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const names = async (): Promise<string> =>
+ git(alice, "ls-tree", "--name-only", "refs/cogit/sessions/s1");
+ expect(await names()).not.toContain("conversation");
+
+ await updateConfig((config) => ({ ...config, shareConversations: true }), env);
+ await push(alice);
+ expect(await names()).toContain("conversation");
+ const bob = await cloneAs("bob");
+ await prepareRecords(bob, env, () => {});
+ expect(await readFile(projectPaths(bob).conversation("s1"), "utf8")).toBe("chat");
+ });
+
+ it("does nothing at all for a project that keeps its record private", async () => {
+ await init(
+ alice,
+ { name: "proj", retention: "keep", allowSkill: false, projectSettings: false },
+ fakeIo(env),
+ );
+ const privateRoot = join(dir, "private");
+ await mkdir(privateRoot);
+ await git(privateRoot, "init", "-q", "-b", "main");
+ await git(privateRoot, "remote", "add", "origin", remote);
+ const io = fakeIo(env);
+ await init(privateRoot, { name: "p", retention: "keep", allowSkill: false }, io);
+ expect(io.asked[0]).toMatch(/Share the session records/);
+ expect(await isSharing(privateRoot)).toBe(false);
+ await record(privateRoot, "s1", "Private", "[email protected]");
+ expect(await snapshotRecords(privateRoot, env)).toBe(0);
+ expect(await queueRecords(privateRoot, env, "origin")).toBe(0);
+ expect(await refs(privateRoot)).toEqual([]);
+ expect(await git(privateRoot, "config", "--get-all", "remote.origin.fetch")).not.toContain(
+ "cogit",
+ );
+ });
+
+ it("works with no remote, and with an unusable one reports it", async () => {
+ await git(alice, "remote", "remove", "origin");
+ await record(alice, "s1", "First", "[email protected]");
+ expect(await syncRemote(alice, env)).toBeUndefined();
+ expect(await addRecordRefspec(alice, env)).toBe(false);
+ expect(await queueRecords(alice, env)).toBe(0);
+ expect(await sendRecords(alice, env)).toBe(0);
+ expect(await downloadRecords(alice, env)).toBe(false);
+ expect((await recordSyncStatus(alice, env)).remote).toBeUndefined();
+
+ await git(alice, "remote", "add", "upstream", join(dir, "nowhere.git"));
+ expect(await syncRemote(alice, env)).toBe("upstream");
+ await queueRecords(alice, env, "upstream");
+ expect(await sendRecords(alice, env)).toBe(0);
+ const failed = await recordSyncStatus(alice, env);
+ expect(failed.pending).toBe(1);
+ expect(failed.sendError).toBeTruthy();
+
+ // Kept for the next try, and sent once the remote works.
+ await git(alice, "remote", "set-url", "upstream", remote);
+ expect(await sendRecords(alice, env)).toBe(1);
+ const sent = await recordSyncStatus(alice, env);
+ expect(sent.pending).toBe(0);
+ expect(sent.sendError).toBeUndefined();
+ });
+
+ it("says why when the first download fails", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const bob = await cloneAs("bob");
+ await git(bob, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ const warnings: string[] = [];
+ await prepareRecords(bob, env, (line) => warnings.push(line));
+ expect(warnings.join()).toMatch(/could not download/);
+ const status = await recordSyncStatus(bob, env);
+ expect(status.downloaded).toBe(false);
+ expect(status.downloadError).toBeTruthy();
+
+ await git(bob, "remote", "set-url", "origin", remote);
+ await prepareRecords(bob, env, () => {});
+ expect(await title(bob, "s1")).toBe("First");
+ expect((await recordSyncStatus(bob, env)).downloadError).toBeUndefined();
+ });
+
+ it("adds the refspec once, in this clone's config only", async () => {
+ const bob = await cloneAs("bob");
+ expect(await addRecordRefspec(bob, env)).toBe(true);
+ expect(await addRecordRefspec(bob, env)).toBe(false);
+ expect(await git(bob, "config", "--local", "--get-all", "remote.origin.fetch")).toContain(
+ RECORD_REFSPEC,
+ );
+ await expect(
+ run("git", ["config", "--global", "--get-all", "remote.origin.fetch"], { env: gitEnv }),
+ ).rejects.toThrow();
+ });
+
+ it("sets up hooks in a clone on cogit's first run", async () => {
+ const bob = await cloneAs("bob");
+ expect(existsSync(join(bob, ".git", "hooks", "pre-push"))).toBe(false);
+ await prepareRecords(bob, env, () => {});
+ expect(await readFile(join(bob, ".git", "hooks", "pre-push"), "utf8")).toContain(
+ "cogit hook pre-push",
+ );
+ });
+
+ it("queues in the pre-push hook and starts the send in the background", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ const started: string[][] = [];
+ const spawned = ((_cli: string, args: string[]) => {
+ started.push(args);
+ }) as never;
+ const stderr = process.stderr.write;
+ const printed: string[] = [];
+ process.stderr.write = ((text: string) => {
+ printed.push(text);
+ return true;
+ }) as typeof process.stderr.write;
+ try {
+ await runGitHook("pre-push", alice, env, ["origin", remote], new Date(T0), spawned);
+ await runGitHook("pre-push", alice, env, ["deploy", remote], new Date(T0), spawned);
+ } finally {
+ process.stderr.write = stderr;
+ }
+ expect(started).toHaveLength(1);
+ expect(started[0]?.slice(0, 2)).toEqual(["record-sync", "send"]);
+ expect(printed.join("")).toContain("sending 1 session record to origin");
+ });
+
+ it("a real git push fires the hook and never fails because of it", async () => {
+ await installGitHooks(alice);
+ await record(alice, "s1", "First", "[email protected]");
+ await writeFile(join(alice, "a.txt"), "two\n");
+ await git(alice, "commit", "-qam", "feat: more");
+ await git(alice, "remote", "set-url", "--push", "origin", remote);
+ await expect(git(alice, "push", "-q", "origin", "main")).resolves.toBe("");
+ expect(await git(alice, "ls-remote", remote, "refs/heads/main")).toContain("main");
+ });
+
+ it("deletes from the remote first, and from nowhere when that fails", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ await git(alice, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ await expect(deleteRecords(alice, ["s1"], env)).rejects.toThrow();
+ expect(existsSync(projectPaths(alice).session("s1"))).toBe(true);
+ expect(await refs(alice)).toHaveLength(1);
+
+ await git(alice, "remote", "set-url", "origin", remote);
+ await deleteRecords(alice, ["s1"], env);
+ expect(existsSync(projectPaths(alice).session("s1"))).toBe(false);
+ expect(await refs(alice)).toEqual([]);
+ expect(await refs(alice, "refs/cogit-remote")).toEqual([]);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toBe("");
+ // Nothing comes back on the next look.
+ await reconcileRecords(alice, env);
+ expect(existsSync(projectPaths(alice).session("s1"))).toBe(false);
+ });
+
+ it("gives a monorepo's projects separate namespaces", async () => {
+ const sub = join(alice, "packages", "app");
+ await mkdir(sub, { recursive: true });
+ await initShared(sub);
+ await record(sub, "app1", "App session", "[email protected]");
+ await record(alice, "root1", "Root session", "[email protected]");
+ await snapshotRecords(sub, env);
+ await snapshotRecords(alice, env);
+ const names = await refs(alice);
+ expect(names).toContain("refs/cogit/sessions/root1");
+ expect(
+ names.some((name) => /refs\/cogit\/projects\/[0-9a-f]+\/sessions\/app1/.test(name)),
+ ).toBe(true);
+ });
+
+ it("ignores a ref whose name could not be a session file", async () => {
+ const tree = (
+ await run("sh", ["-c", `git -C "${alice}" mktree </dev/null`], { env: gitEnv })
+ ).stdout.trim();
+ await git(alice, "update-ref", "refs/cogit-remote/sessions/nested/evil", tree);
+ expect(await importRecords(alice, env)).toBe(0);
+ expect(existsSync(join(alice, ".cogit", "sessions", "nested"))).toBe(false);
+ });
+
+ it("uses the main checkout's record from a worktree, though the marker is tracked", async () => {
+ const worktree = join(dir, "wt");
+ await git(alice, "worktree", "add", "-q", "-b", "wt", worktree);
+ expect(existsSync(projectPaths(worktree).project)).toBe(true);
+ const resolved = await resolveProjectRoot(worktree);
+ expect(resolved.root).toBe(alice);
+ });
+
+ it("tells an old project what to do about its tracked sessions", async () => {
+ await git(alice, "config", "user.name", "alice");
+ await record(alice, "old", "Old", "[email protected]");
+ await git(alice, "add", "-f", projectPaths(alice).session("old"));
+ expect(await trackedRecordFiles(alice, env)).toBe(1);
+ const report = await doctor({ dir: alice, io: fakeIo(env), json: false } as never);
+ const check = report.checks.find((item) => item.id === "record");
+ expect(check?.status).toBe("warn");
+ expect(check?.fix).toContain("git rm -r --cached .cogit/sessions");
+ });
+
+ it("reports a failed send and a failed download in doctor", async () => {
+ const check = async (root: string) => {
+ const report = await doctor({ dir: root, io: fakeIo(env), json: false } as never);
+ return report.checks.find((item) => item.id === "record");
+ };
+ expect((await check(alice))?.message).toContain("shared through origin");
+
+ await record(alice, "s1", "First", "[email protected]");
+ await queueRecords(alice, env, "origin");
+ await git(alice, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ await sendRecords(alice, env);
+ expect((await check(alice))?.message).toMatch(/1 session record could not be sent/);
+
+ await git(alice, "remote", "set-url", "origin", remote);
+ await sendRecords(alice, env);
+ const bob = await cloneAs("bob");
+ await git(bob, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ await downloadRecords(bob, env);
+ const failed = await check(bob);
+ expect(failed?.message).toMatch(/could not be downloaded/);
+ expect(failed?.message).toContain("fatal:");
+
+ await git(alice, "remote", "remove", "origin");
+ expect((await check(alice))?.message).toContain("no remote yet");
+ });
+
+ it("shows git's own progress to a person, and says when it failed", async () => {
+ expect(await downloadRecords(alice, env, true)).toBe(true);
+ await git(alice, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ expect(await downloadRecords(alice, env, true)).toBe(false);
+ expect((await recordSyncStatus(alice, env)).downloaded).toBe(true);
+ });
+
+ it("warns instead of failing the command when the record cannot be updated", async () => {
+ await rm(join(alice, ".cogit", "state"), { recursive: true, force: true });
+ await writeFile(join(alice, ".cogit", "state"), "in the way");
+ const warnings: string[] = [];
+ await prepareRecords(alice, env, (line) => warnings.push(line));
+ expect(warnings.join()).toMatch(/could not update the session records/);
+ });
+
+ describe("at session start", () => {
+ const start = async (root: string): Promise<string[][]> => {
+ const spawned: string[][] = [];
+ await runHook(
+ "sessionstart",
+ JSON.stringify({ session_id: "live", cwd: root, source: "startup" }),
+ env,
+ T0,
+ () => {},
+ { spawnDetached: (_cli, args) => spawned.push(args) },
+ );
+ return spawned;
+ };
+
+ it("sets a new clone up and downloads in the background", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const bob = await cloneAs("bob");
+ const started = await start(bob);
+ expect(started.some((args) => args.join(" ").startsWith("record-sync download"))).toBe(true);
+ expect(await git(bob, "config", "--get-all", "remote.origin.fetch")).toContain(
+ RECORD_REFSPEC,
+ );
+ expect(existsSync(join(bob, ".git", "hooks", "pre-push"))).toBe(true);
+ });
+
+ it("reads what a pull brought, and retries only what a push queued", async () => {
+ await record(alice, "s1", "First", "[email protected]");
+ await push(alice);
+ const bob = await cloneAs("bob");
+ await prepareRecords(bob, env, () => {});
+ await record(alice, "s2", "Second", "[email protected]");
+ await push(alice);
+ await git(bob, "pull", "-q");
+ const quiet = await start(bob);
+ expect(await title(bob, "s2")).toBe("Second");
+ expect(quiet.some((args) => args[0] === "record-sync")).toBe(false);
+
+ // A session nobody pushed stays home: starting a chat sends nothing new.
+ await record(bob, "b1", "Unpushed", "[email protected]");
+ expect((await start(bob)).some((args) => args[0] === "record-sync")).toBe(false);
+
+ await queueRecords(bob, env, "origin");
+ const retried = await start(bob);
+ expect(retried.some((args) => args.join(" ").startsWith("record-sync send"))).toBe(true);
+ });
+
+ it("leaves a private project alone", async () => {
+ await rm(join(alice, ".cogit", ".gitignore"), { force: true });
+ await writeFile(join(alice, ".gitignore"), "/.cogit/\n");
+ expect((await start(alice)).some((args) => args[0] === "record-sync")).toBe(false);
+ });
+ });
+
+ describe("cogit prune", () => {
+ const old = "2020-01-01T00:00:00.000Z";
+ const write = async (id: string, email: string, updatedAt: string): Promise<void> => {
+ const paths = projectPaths(alice);
+ await mkdir(paths.sessions, { recursive: true });
+ await writeFile(paths.session(id), JSON.stringify(session(id, id, email, updatedAt)));
+ };
+ const template = TEMPLATE;
+
+ it("reads an age or refuses it", () => {
+ expect(pruneCutoff("1y", T0).slice(0, 4)).toBe("2025");
+ expect(pruneCutoff("30d", T0).slice(0, 10)).toBe("2026-09-21");
+ expect(pruneCutoff("2w", T0).slice(0, 10)).toBe("2026-10-07");
+ expect(pruneCutoff("6m", T0).slice(0, 7)).toBe("2026-04");
+ expect(() => pruneCutoff("soon", T0)).toThrow(/invalid age/);
+ });
+
+ it("deletes only your own old sessions, after asking", async () => {
+ await write("mine", "[email protected]", old);
+ await write("theirs", "[email protected]", old);
+ await write("fresh", "[email protected]", "2100-01-01T00:00:00.000Z");
+ await push(alice);
+
+ const declined = fakeIo(env);
+ await pruneRecords({ dir: alice, olderThan: "1y", io: declined, templateHtml: template });
+ expect(declined.asked[0]).toMatch(/Delete 1 session from this machine and the repository/);
+ expect(declined.lines).toContain("Nothing deleted.");
+ expect(existsSync(projectPaths(alice).session("mine"))).toBe(true);
+
+ const io = fakeIo(env, ["true"]);
+ io.prompt.confirm = async (): Promise<boolean> => true;
+ await pruneRecords({ dir: alice, olderThan: "1y", io, templateHtml: template });
+ expect(existsSync(projectPaths(alice).session("mine"))).toBe(false);
+ expect(existsSync(projectPaths(alice).session("theirs"))).toBe(true);
+ expect(existsSync(projectPaths(alice).session("fresh"))).toBe(true);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/sessions/mine")).toBe("");
+ });
+
+ it("lists without deleting on a dry run, and includes teammates with --all", async () => {
+ await write("mine", "[email protected]", old);
+ await write("theirs", "[email protected]", old);
+ const io = fakeIo(env, [], true);
+ await pruneRecords({ dir: alice, olderThan: "1y", all: true, dryRun: true, io });
+ expect(io.lines.at(-1)).toBe("Would delete 2 sessions.");
+ expect(existsSync(projectPaths(alice).session("theirs"))).toBe(true);
+
+ await pruneRecords({
+ dir: alice,
+ olderThan: "1y",
+ all: true,
+ yes: true,
+ io,
+ templateHtml: template,
+ });
+ expect(existsSync(projectPaths(alice).session("theirs"))).toBe(false);
+ });
+
+ it("reports nothing to do, an uninitialized directory and a failed remote", async () => {
+ const io = fakeIo(env, [], true);
+ await pruneRecords({ dir: alice, olderThan: "1y", io });
+ expect(io.lines).toContain("No sessions older than 1y.");
+ await expect(
+ pruneRecords({ dir: join(dir, "nowhere"), olderThan: "1y", io }),
+ ).rejects.toThrow(/not initialized/);
+
+ await write("mine", "[email protected]", old);
+ await push(alice);
+ await git(alice, "remote", "set-url", "origin", join(dir, "nowhere.git"));
+ await expect(pruneRecords({ dir: alice, olderThan: "1y", yes: true, io })).rejects.toThrow(
+ /nothing was deleted/,
+ );
+ expect(existsSync(projectPaths(alice).session("mine"))).toBe(true);
+ });
+
+ it("works without a repository remote in a private project", async () => {
+ await rm(join(alice, ".cogit", ".gitignore"), { force: true });
+ await writeFile(join(alice, ".gitignore"), "/.cogit/\n");
+ await write("mine", "[email protected]", old);
+ const io = fakeIo(env, [], true);
+ await pruneRecords({ dir: alice, olderThan: "1y", yes: true, io, templateHtml: template });
+ expect(existsSync(projectPaths(alice).session("mine"))).toBe(false);
+ });
+ });
+});
diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.ts
index 9f4196f..6d45241 100644
--- a/packages/cli/test/schema.test.ts
+++ b/packages/cli/test/schema.test.ts
@@ -147,9 +147,7 @@ describe("Project and Config schemas", () => {
sideModel: "haiku",
sideEveryTurns: 5,
sessionEndCatchUp: true,
- gitPolicy: "commit",
shareConversations: false,
- recordCommit: "ask",
inboxMaxAgeDays: 1,
});
});
diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.ts
index 94c59e6..8297fe4 100644
--- a/packages/cli/test/server.test.ts
+++ b/packages/cli/test/server.test.ts
@@ -438,14 +438,7 @@ describe("settings write", () => {
expect(
(await configWrite(server, token, { key: "shareConversations", value: true })).status,
).toBe(200);
- expect((await configWrite(server, token, { key: "recordCommit", value: "auto" })).status).toBe(
- 200,
- );
expect((await loadConfig(env)).shareConversations).toBe(true);
- expect((await loadConfig(env)).recordCommit).toBe("auto");
- expect(
- (await configWrite(server, token, { key: "recordCommit", value: "sometimes" })).status,
- ).toBe(400);
});
it("rebuilds an open map so the page picks the new setting up", async () => {
@@ -508,7 +501,7 @@ describe("settings write", () => {
it("rejects a read-only key, an unknown key and a bad value type", async () => {
const server = await start();
const token = await panelToken(server);
- expect((await configWrite(server, token, { key: "gitPolicy", value: "commit" })).status).toBe(
+ expect((await configWrite(server, token, { key: "gitPolicy", value: "share" })).status).toBe(
400,
);
expect((await configWrite(server, token, { key: "nope", value: 1 })).status).toBe(400);
@@ -518,7 +511,6 @@ describe("settings write", () => {
expect(
(await configWrite(server, token, { key: "messageSummaries", value: "true" })).status,
).toBe(400);
- expect((await loadConfig(env)).gitPolicy).toBe("commit");
expect((await loadConfig(env)).messageSummaries).toBe(false);
});
@@ -591,7 +583,6 @@ describe("settings read", () => {
captures: true,
language: "auto",
shareConversations: false,
- recordCommit: "ask",
},
});
});
diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.ts
index 1903c9d..15d4f0a 100644
--- a/packages/cli/test/session-git.test.ts
+++ b/packages/cli/test/session-git.test.ts
@@ -4,7 +4,7 @@ import { userInfo } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { beforeEach, describe, expect, it } from "vitest";
-import { configGit, configGitShow, configSet } from "../src/commands/config.js";
+import { configGit, configGitShow } from "../src/commands/config.js";
import { hooksInstall, hooksUninstall } from "../src/commands/hooks.js";
import { sessionAuthor, sessionWrite } from "../src/commands/session.js";
import {
@@ -20,23 +20,15 @@ import {
refreshGitHooks,
withHookBlock,
} from "../src/git-hooks.js";
-import { runHook } from "../src/hooks/run.js";
import type { Session } from "../src/schema/session.js";
-import {
- commitSessionFiles,
- maybeAutoCommit,
- readSessionHead,
- recordMessage,
- stageSessionFiles,
- uncommittedSession,
-} from "../src/session-git.js";
+import { readSessionHead } from "../src/session-git.js";
import { projectPaths } from "../src/store/paths.js";
import { loadSession, projectJson } from "../src/store/stores.js";
import { envFor, fakeIo, noGitDir, T0, tempDir } from "./helpers.js";
const run = promisify(execFile);
-describe("the record travels with the repo (Story 9.3)", () => {
+describe("the session HEAD and author (Story 9.3)", () => {
let dir: string;
let root: string;
let env: NodeJS.ProcessEnv;
@@ -101,85 +93,6 @@ describe("the record travels with the repo (Story 9.3)", () => {
expect(await readSessionHead(root)).toBeUndefined();
});
- it("stages the current session only when something else is already staged", async () => {
- await makeProject();
- await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));
- // Nothing staged: the hook must not create a record-only commit.
- expect(await stageSessionFiles(root)).toBe(false);
- expect((await git("diff", "--cached", "--name-only")).trim()).toBe("");
-
- await writeFile(join(root, "a.txt"), "two\n");
- await git("add", "a.txt");
- expect(await stageSessionFiles(root)).toBe(true);
- const staged = (await git("diff", "--cached", "--name-only")).trim().split("\n");
- expect(staged).toContain(".cogit/sessions/s1.json");
- expect(staged).toContain(".cogit/sessions/s1.events.jsonl");
- });
-
- it("stages into the temporary index of git commit <paths>", async () => {
- await makeProject();
- await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));
- // git commit <paths> builds a temporary index; its path arrives as GIT_INDEX_FILE.
- const tempEnv = { GIT_INDEX_FILE: join(dir, "temp-index") };
- await gitEnv(tempEnv, "read-tree", "HEAD");
- expect(await stageSessionFiles(root, { ...process.env, ...tempEnv })).toBe(false);
- await writeFile(join(root, "a.txt"), "three\n");
- await gitEnv(tempEnv, "add", "a.txt");
- expect(await stageSessionFiles(root, { ...process.env, ...tempEnv })).toBe(true);
- const temp = (await gitEnv(tempEnv, "diff", "--cached", "--name-only")).trim();
- expect(temp).toContain(".cogit/sessions/s1.json");
- // The real index is untouched by the temporary one.
- expect((await git("diff", "--cached", "--name-only")).trim()).toBe("");
- });
-
- it("does nothing when the ignore policy hides the record", async () => {
- await makeProject();
- await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));
- await writeFile(join(root, ".gitignore"), "/.cogit/\n");
- await writeFile(join(root, "a.txt"), "two\n");
- await git("add", "a.txt");
- expect(await stageSessionFiles(root)).toBe(false);
- expect(await uncommittedSession(root, "s1")).toBe(false);
- expect((await git("diff", "--cached", "--name-only")).trim()).toBe("a.txt");
- });
-
- it("commits exactly the record files, leaving other staged changes alone", async () => {
- await makeProject();
- await writeFile(join(root, "a.txt"), "two\n");
- await git("add", "a.txt");
- expect(await commitSessionFiles(root, "s1", "My session")).toBe(true);
- expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record My session");
- const files = (await git("show", "--name-only", "--format=")).trim().split("\n");
- expect(files).toContain(".cogit/sessions/s1.json");
- expect(files).not.toContain("a.txt");
- expect((await git("diff", "--cached", "--name-only")).trim()).toBe("a.txt");
- expect(await uncommittedSession(root, "s1")).toBe(false);
- });
-
- it("commits at session end only in auto mode", async () => {
- await makeProject();
- const io = fakeIo(env);
- await configSet("recordCommit", "off", io);
- expect(await maybeAutoCommit(root, "s1", env)).toBe(false);
- expect((await git("log", "--format=%s")).trim().split("\n")).toEqual(["feat: base"]);
-
- await configSet("recordCommit", "auto", io);
- expect(await maybeAutoCommit(root, "s1", env)).toBe(true);
- expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record My session");
- // Nothing left to commit is a quiet no-op, not an error.
- expect(await commitSessionFiles(root, "s1", "My session")).toBe(false);
- // Changing the sharing setting also walks the registry's ignore files.
- await configSet("shareConversations", "true", io);
- });
-
- it("keeps the record commit message to one short line", () => {
- expect(recordMessage(" Multi\nline title ", "s1")).toBe(
- "chore(cogit): record Multi line title",
- );
- expect(recordMessage("", "s1")).toBe("chore(cogit): record s1");
- expect(recordMessage("x".repeat(200), "s1")).toHaveLength("chore(cogit): record ".length + 120);
- });
-
it("stamps the author from git on the first write, else the OS user", async () => {
await makeProject();
expect(await sessionAuthor(root, env)).toBe("Tester");
@@ -233,25 +146,21 @@ describe("ignore files and git hooks", () => {
it("adds and removes the root ignore line with the policy", async () => {
await ensureGitignore(root, "ignore");
await expect(readFile(join(root, ".gitignore"), "utf8")).resolves.toBe("# cogit\n/.cogit/\n");
- await ensureGitignore(root, "commit");
- await expect(refreshCogitGitignore(root, false)).resolves.toBe(true);
- await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(
- cogitGitignore(false),
- );
+ await ensureGitignore(root, "share");
+ await expect(refreshCogitGitignore(root)).resolves.toBe(true);
+ await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(cogitGitignore());
// A project that still ignores .cogit/ keeps no inner file.
await ensureGitignore(root, "ignore");
- await expect(refreshCogitGitignore(root, true)).resolves.toBe(false);
+ await expect(refreshCogitGitignore(root)).resolves.toBe(false);
});
- it("switches an existing project between commit and ignore", async () => {
+ it("switches an existing project between share and ignore", async () => {
const io = fakeIo(env);
- await configGit(root, "commit", io);
- await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(
- cogitGitignore(false),
- );
- const hook = await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8");
+ await configGit(root, "share", io);
+ await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(cogitGitignore());
+ const hook = await readFile(join(root, ".git", "hooks", "pre-push"), "utf8");
expect(hook).toContain("# >>> cogit");
- expect(hook).toContain("cogit hook pre-commit --dir");
+ expect(hook).toContain("cogit hook pre-push --dir");
expect(await readFile(projectPaths(root).project, "utf8")).toContain('"proj"');
await configGitShow(root, io);
@@ -259,8 +168,8 @@ describe("ignore files and git hooks", () => {
await expect(readFile(join(root, ".gitignore"), "utf8")).resolves.toBe("# cogit\n/.cogit/\n");
await configGitShow(root, io);
expect(io.lines.filter((line) => line.startsWith("Git policy"))).toEqual([
- "Git policy for proj: commit",
- "Git policy for proj: commit",
+ "Git policy for proj: share",
+ "Git policy for proj: share",
"Git policy for proj: ignore",
"Git policy for proj: ignore",
]);
@@ -295,25 +204,6 @@ describe("ignore files and git hooks", () => {
expect(next).toContain("--dir '/p'");
});
- it("carries project.json and the inner ignore file with the first record", async () => {
- await mkdir(projectPaths(root).sessions, { recursive: true });
- await writeFile(projectPaths(root).session("s1"), "{}\n");
- await writeFile(projectPaths(root).gitignore, cogitGitignore(false));
- await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));
- await writeFile(join(root, "a.txt"), "two\n");
- await git("add", "a.txt");
- expect(await stageSessionFiles(root)).toBe(true);
- const staged = (await git("diff", "--cached", "--name-only")).trim().split("\n");
- expect(staged).toEqual(
- expect.arrayContaining([
- "a.txt",
- ".cogit/sessions/s1.json",
- ".cogit/project.json",
- ".cogit/.gitignore",
- ]),
- );
- });
-
it("falls back to the installing CLI under node, else does nothing", () => {
const withCli = hookBlock("pre-commit", "/p", "/opt/cogit/cli.js");
expect(withCli).toContain("if command -v cogit >/dev/null 2>&1; then");
@@ -365,13 +255,13 @@ describe("ignore files and git hooks", () => {
it("refreshes only the hooks that already carry a cogit block", async () => {
const hooks = join(root, ".git", "hooks");
await writeFile(
- join(hooks, "pre-commit"),
- "#!/bin/sh\n# >>> cogit\ncogit hook pre-commit || true\n# <<< cogit\n",
+ join(hooks, "post-commit"),
+ "#!/bin/sh\n# >>> cogit\ncogit hook post-commit || true\n# <<< cogit\n",
);
await writeFile(join(hooks, "prepare-commit-msg"), "#!/bin/sh\necho mine\n");
- expect(await refreshGitHooks(root)).toEqual(["pre-commit"]);
- expect(await readFile(join(hooks, "pre-commit"), "utf8")).toContain(
- hookBlock("pre-commit", root),
+ expect(await refreshGitHooks(root)).toEqual(["post-commit"]);
+ expect(await readFile(join(hooks, "post-commit"), "utf8")).toContain(
+ hookBlock("post-commit", root),
);
expect(await readFile(join(hooks, "prepare-commit-msg"), "utf8")).toBe(
"#!/bin/sh\necho mine\n",
@@ -380,6 +270,20 @@ describe("ignore files and git hooks", () => {
expect(await refreshGitHooks(await noGitDir())).toEqual([]);
});
+ it("adds pre-push to an installed clone and retires an old pre-commit block", async () => {
+ const hooks = join(root, ".git", "hooks");
+ const block = (event: string): string =>
+ `#!/bin/sh\n# >>> cogit\ncogit hook ${event} || true\n# <<< cogit\n`;
+ await writeFile(join(hooks, "prepare-commit-msg"), block("prepare-commit-msg"));
+ await writeFile(
+ join(hooks, "pre-commit"),
+ `#!/bin/sh\necho mine\n${block("pre-commit").slice(10)}`,
+ );
+ await refreshGitHooks(root);
+ expect(await readFile(join(hooks, "pre-push"), "utf8")).toContain("cogit hook pre-push");
+ expect(await readFile(join(hooks, "pre-commit"), "utf8")).toBe("#!/bin/sh\necho mine\n");
+ });
+
it("installs the hooks on request and with the ignore policy", async () => {
const io = fakeIo(env);
const other = join(dir, "other");
@@ -388,7 +292,7 @@ describe("ignore files and git hooks", () => {
await hooksInstall(root, io);
await hooksInstall(root, io);
expect(io.lines).toEqual([
- "Added the cogit block to: pre-commit, prepare-commit-msg, post-commit",
+ "Added the cogit block to: prepare-commit-msg, post-commit, pre-push",
"The cogit hook blocks are already current.",
]);
await hooksUninstall(root, io);
@@ -396,50 +300,4 @@ describe("ignore files and git hooks", () => {
const hook = await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8");
expect(hook).toContain("hook prepare-commit-msg --dir");
});
-
- it("offers the uncommitted record at session start only in ask mode", async () => {
- const paths = projectPaths(root);
- await mkdir(paths.sessions, { recursive: true });
- const earlier: Session = {
- schema: 1,
- sessionId: "s0",
- agent: "claude-code",
- title: "Earlier work",
- startedAt: T0,
- updatedAt: T0,
- status: { goal: "", done: [], pending: [], next: "" },
- nodes: [],
- };
- await writeFile(paths.session("s0"), JSON.stringify(earlier));
- await writeFile(paths.events("s0"), "");
- const io = fakeIo(env);
- await configSet("recordCommit", "ask", io);
-
- const start = async (): Promise<string> => {
- const out = await runHook(
- "sessionstart",
- JSON.stringify({ session_id: "s1", cwd: root, source: "startup" }),
- env,
- T0,
- () => {},
- );
- return (
- (JSON.parse(out ?? "{}") as { hookSpecificOutput?: { additionalContext?: string } })
- .hookSpecificOutput?.additionalContext ?? ""
- );
- };
-
- expect(await start()).toContain("The last session's record is not committed");
- expect(await start()).toContain("chore(cogit): record Earlier work");
-
- await git("add", "-A");
- await git("commit", "-q", "-m", "chore(cogit): record Earlier work");
- expect(await start()).not.toContain("The last session's record is not committed");
-
- // `off` and `auto` never ask the agent.
- await configSet("recordCommit", "auto", io);
- await writeFile(paths.head, JSON.stringify({ sessionId: "s0", at: T0 }));
- await writeFile(paths.session("s0"), JSON.stringify({ ...earlier, title: "Changed" }));
- expect(await start()).not.toContain("The last session's record is not committed");
- });
});
diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.ts
index 9c80b83..b083336 100644
--- a/packages/cli/test/settings.test.ts
+++ b/packages/cli/test/settings.test.ts
@@ -28,8 +28,6 @@ describe("settings model", () => {
shapes: parsed.shapes,
captures: parsed.captures,
shareConversations: parsed.shareConversations,
- recordCommit: parsed.recordCommit,
- gitPolicy: parsed.gitPolicy,
agents: parsed.agents,
bigChangeLines: parsed.bigChangeLines,
});
@@ -37,10 +35,9 @@ describe("settings model", () => {
it("lets the embedded values override the defaults", () => {
expect(withDefaults(undefined)).toEqual(DEFAULT_SETTINGS);
- expect(withDefaults({ updateEveryTurns: 9, gitPolicy: "commit" })).toEqual({
+ expect(withDefaults({ updateEveryTurns: 9 })).toEqual({
...DEFAULT_SETTINGS,
updateEveryTurns: 9,
- gitPolicy: "commit",
});
});
@@ -76,7 +73,6 @@ describe("settings model", () => {
captures: true,
language: "tr",
shareConversations: false,
- recordCommit: "ask",
});
expect(Object.keys(editableSettings(settings)).sort()).toEqual([...PANEL_EDITABLE_KEYS].sort());
});
diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.ts
index e01d2a9..fa5b849 100644
--- a/packages/cli/test/thought.test.ts
+++ b/packages/cli/test/thought.test.ts
@@ -503,16 +503,16 @@ describe("the thought behind a commit (Story 9.4)", () => {
const userHook = "#!/bin/sh\necho user-hook\n";
it("installs both events, keeps the user's lines, and uninstalls only its block", async () => {
- const preCommit = join(root, ".git", "hooks", "pre-commit");
+ const preCommit = join(root, ".git", "hooks", "pre-push");
await writeFile(preCommit, userHook);
await chmod(preCommit, 0o755);
expect(await installGitHooks(root)).toEqual([
- "pre-commit",
"prepare-commit-msg",
"post-commit",
+ "pre-push",
]);
expect(await readFile(preCommit, "utf8")).toBe(
- `${userHook}\n${hookBlock("pre-commit", root)}\n`,
+ `${userHook}\n${hookBlock("pre-push", root)}\n`,
);
expect(await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8")).toContain(
"cogit hook prepare-commit-msg",
@@ -520,9 +520,9 @@ describe("the thought behind a commit (Story 9.4)", () => {
expect(await installGitHooks(root)).toEqual([]);
expect(await uninstallGitHooks(root)).toEqual([
- "pre-commit",
"prepare-commit-msg",
"post-commit",
+ "pre-push",
]);
expect(await readFile(preCommit, "utf8")).toBe(userHook);
// The file held nothing but cogit's shebang and block, so it is gone.
@@ -533,17 +533,17 @@ describe("the thought behind a commit (Story 9.4)", () => {
it("follows core.hooksPath and leaves a hook without the block alone", async () => {
await git("config", "core.hooksPath", ".husky");
await mkdir(join(root, ".husky"), { recursive: true });
- await writeFile(join(root, ".husky", "pre-commit"), userHook);
+ await writeFile(join(root, ".husky", "pre-push"), userHook);
await installGitHooks(root);
expect(await readFile(join(root, ".husky", "prepare-commit-msg"), "utf8")).toContain(
"cogit hook prepare-commit-msg",
);
expect(await uninstallGitHooks(root)).toEqual([
- "pre-commit",
"prepare-commit-msg",
"post-commit",
+ "pre-push",
]);
- expect(await readFile(join(root, ".husky", "pre-commit"), "utf8")).toBe(userHook);
+ expect(await readFile(join(root, ".husky", "pre-push"), "utf8")).toBe(userHook);
// No repository and no block: nothing to do.
expect(await uninstallGitHooks(await noGitDir())).toEqual([]);
@@ -573,7 +573,7 @@ describe("the thought behind a commit (Story 9.4)", () => {
program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });
await program.parseAsync(["hooks", "uninstall", root], { from: "user" });
expect(io.lines.at(-1)).toBe(
- "Removed the cogit block from: pre-commit, prepare-commit-msg, post-commit",
+ "Removed the cogit block from: prepare-commit-msg, post-commit, pre-push",
);
await program.parseAsync(["hooks", "uninstall", root], { from: "user" });
@@ -584,14 +584,14 @@ describe("the thought behind a commit (Story 9.4)", () => {
});
});
- it("init installs both hooks under the commit policy", async () => {
+ it("init installs the hooks for a shared project", async () => {
await init(
root,
- { name: "proj", retention: "keep", language: "auto", git: "commit" },
+ { name: "proj", retention: "keep", language: "auto", git: "share" },
fakeIo(env),
);
- expect(await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8")).toContain(
- "cogit hook pre-commit",
+ expect(await readFile(join(root, ".git", "hooks", "pre-push"), "utf8")).toContain(
+ "cogit hook pre-push",
);
expect(await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8")).toContain(
"cogit hook prepare-commit-msg",
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index 14d0b13..aaa75d2 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -891,7 +891,11 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchSta
) : null}
<div className="graph-canvas">
{sessionGraph.git.rows.length === 0 ? (
- <p className="graph-status empty">No sessions recorded yet.</p>
+ <p className="graph-status empty">
+ {model.recordDownloadFailed === true
+ ? "Your team's session records could not be downloaded. Check your connection and run cogit open again."
+ : "No sessions recorded yet. They appear here as you work with Claude Code."}
+ </p>
) : (
<MapCanvas
nodes={nodes}
diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.ts
index dae945c..61d237b 100644
--- a/packages/template/src/fixture.ts
+++ b/packages/template/src/fixture.ts
@@ -63,8 +63,6 @@ export const fixture: LineageViewModel = {
shapes: true,
captures: true,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "ignore",
agents: ["claude-code"],
bigChangeLines: 300,
},
diff --git a/packages/template/test/map-changes.test.tsx b/packages/template/test/map-changes.test.tsx
index 81f3567..2165712 100644
--- a/packages/template/test/map-changes.test.tsx
+++ b/packages/template/test/map-changes.test.tsx
@@ -55,8 +55,6 @@ function modelOf(current: ViewSession): LineageViewModel {
messageSummaries: false,
startupContext: true,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "ignore",
agents: ["claude-code"],
bigChangeLines: 300,
},
diff --git a/packages/template/test/panel.test.ts b/packages/template/test/panel.test.ts
index 66a1c21..0386665 100644
--- a/packages/template/test/panel.test.ts
+++ b/packages/template/test/panel.test.ts
@@ -18,8 +18,6 @@ const model: PanelViewModel = {
messageSummaries: false,
startupContext: true,
shareConversations: false,
- recordCommit: "ask",
- gitPolicy: "ignore",
agents: ["claude-code"],
},
projects: [],