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.

fix(record): send only after a push lands, and restore committed sessions

Eren3eb5631c6764
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ca58d2..39c074d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [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 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. Teammates' files come back from history on their next cogit run. 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.
+- `git push` sends the record of a project that shares it, in the background once the push has landed: it prints how many, never slows or fails the push, and only goes to `origin` or your only remote. A dry run or a rejected push sends nothing. 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.
diff --git a/docs/guide/privacy.md b/docs/guide/privacy.md
index 1c6c2ce..9ed2401 100644
--- a/docs/guide/privacy.md
+++ b/docs/guide/privacy.md
@@ -27,7 +27,7 @@ If you share the record, `git push` also sends it to your own repository, on ref
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
+prints how many session records will follow it. 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
diff --git a/docs/guide/teams-and-git.md b/docs/guide/teams-and-git.md
index 1aab0af..d1812b1 100644
--- a/docs/guide/teams-and-git.md
+++ b/docs/guide/teams-and-git.md
@@ -33,10 +33,11 @@ does not download them, so someone without cogit gets a clone of the usual size
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.
+- **Sending:** `git push` to `origin` (or your only remote) prints how many records will follow,
+ and they go in the background once the push has landed. It never slows the push, never asks
+ for anything and never fails it. A `--dry-run` or a rejected push sends nothing. 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
@@ -63,16 +64,18 @@ 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`:
+Older versions committed `.cogit/sessions/`. After upgrading, 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.
+That commit makes `git pull` delete the files from teammates' disks. cogit brings them back from
+history the next time it runs, for them and for new clones, so nothing is lost and nothing is
+sent again. Sessions recorded after the upgrade travel the new way. 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
diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.ts
index 2425e00..e7e6d3f 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 { queueRecords } from "./record-sync.js";
+import { countUnsentRecords } from "./record-sync.js";
import { atomicWrite } from "./store/fs.js";
import { captureDisabled, projectPaths } from "./store/paths.js";
import { loadConfig } from "./store/stores.js";
@@ -191,27 +191,42 @@ async function removeHookBlocks<Event extends string>(
return removed;
}
+const NO_OBJECT = /^0+$/;
+
/**
- * 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.
+ * The `pre-push` hook (`pushedRefs` is git's stdin: one `<ref> <sha> <remote ref> <sha>` a
+ * line): hands the records to a background run that waits for this
+ * push to land, so the user's push never waits for the network, never meets a second
+ * SSH prompt and never fails because of a record. A push that only deletes sends
+ * nothing. The line is the only sign that something else is leaving the machine.
*/
async function sendWithPush(
dir: string,
env: NodeJS.ProcessEnv,
pushedRemote: string | undefined,
+ pushedRefs: string,
spawn: typeof spawnDetachedProcess,
): Promise<void> {
if (captureDisabled(env)) return;
- const queued = await queueRecords(dir, env, pushedRemote);
- if (queued === 0) return;
+ const lines = pushedRefs.split("\n").filter(Boolean);
+ const going = lines
+ .map((line) => line.split(" "))
+ .find((part) => !NO_OBJECT.test(part[1] ?? "0"));
+ if (lines.length > 0 && going === undefined) return;
+ const unsent = await countUnsentRecords(dir, env, pushedRemote);
+ if (unsent === 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`,
+ `cogit: ${unsent} session record${unsent === 1 ? "" : "s"} will follow this push to ${pushedRemote}\n`,
+ );
+ const after = going === undefined ? [] : ["--after", `${going[2]}=${going[1]}`];
+ spawn(
+ cli,
+ ["record-sync", "send-pushed", ...after, "-C", dir],
+ env,
+ projectPaths(dir).detachedLog,
);
- spawn(cli, ["record-sync", "send", "-C", dir], env, projectPaths(dir).detachedLog);
}
/**
@@ -252,9 +267,10 @@ export async function runGitHook(
args: readonly string[] = [],
now: Date = new Date(),
spawn: typeof spawnDetachedProcess = spawnDetachedProcess,
+ pushedRefs: () => Promise<string> = async () => "",
): Promise<void> {
if (event === "pre-push") {
- await sendWithPush(dir, env, args[0], spawn);
+ await sendWithPush(dir, env, args[0], await pushedRefs(), spawn);
return;
}
if (event === "post-commit") {
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index 5016d2e..cea36ff 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -5,7 +5,12 @@ 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 {
+ isSharing,
+ reconcileRecords,
+ recordSyncStatus,
+ restoreCommittedRecords,
+} from "../record-sync.js";
import type { Session } from "../schema/session.js";
import { applyEvents, readEvents } from "../store/events.js";
import { loadAllSessions, loadConfig, loadSession } from "../store/stores.js";
@@ -115,6 +120,7 @@ async function syncRecordsAtStart(ctx: HookContext): Promise<void> {
ctx.spawnDetached(["record-sync", "download", "-C", ctx.root]);
return;
}
+ await restoreCommittedRecords(ctx.root, ctx.env);
await reconcileRecords(ctx.root, ctx.env);
if (status.pending > 0) ctx.spawnDetached(["record-sync", "send", "-C", ctx.root]);
}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index d7b9da0..ae77309 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -31,7 +31,7 @@ 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 { downloadRecords, reconcileRecords, sendAfterPush, sendRecords } from "./record-sync.js";
import { startMapServer } from "./server.js";
import { takeMigrationWarnings } from "./store/migrate.js";
import { projectPaths } from "./store/paths.js";
@@ -668,7 +668,15 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
if (event === "pre-commit") return;
if (isGitHookEvent(event)) {
try {
- await runGitHook(event, opts.dir ?? process.cwd(), io.env, args, new Date(io.now()));
+ await runGitHook(
+ event,
+ opts.dir ?? process.cwd(),
+ io.env,
+ args,
+ new Date(io.now()),
+ undefined,
+ deps.stdin ?? readStdin,
+ );
} catch {
// A hook must never block the commit or the session.
}
@@ -721,13 +729,15 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
program
.command("record-sync", { hidden: true })
.description("send the queued session records, or download the team's")
- .argument("<action>", "send or download")
+ .argument("<action>", "send, send-pushed or download")
+ .option("--after <ref=sha>", "with send-pushed: wait until the remote holds this")
.option("-C, --dir <dir>", "project directory", ".")
.action(
- run(async (action: string, opts: { dir: string }) => {
+ run(async (action: string, opts: { dir: string; after?: string }) => {
const io = makeIo(false);
const { root } = await resolveProjectRoot(opts.dir);
if (action === "send") await sendRecords(root, io.env);
+ else if (action === "send-pushed") await sendAfterPush(root, io.env, opts.after);
else if (action === "download") {
await downloadRecords(root, io.env);
await reconcileRecords(root, io.env);
diff --git a/packages/cli/src/record-prepare.ts b/packages/cli/src/record-prepare.ts
index a77c24e..0f99523 100644
--- a/packages/cli/src/record-prepare.ts
+++ b/packages/cli/src/record-prepare.ts
@@ -5,6 +5,7 @@ import {
isSharing,
reconcileRecords,
recordSyncStatus,
+ restoreCommittedRecords,
} from "./record-sync.js";
/**
@@ -37,6 +38,7 @@ export async function prepareRecords(
if (!(await downloadRecords(root, env, showProgress)))
warn("could not download your team's session records; check your connection and try again");
}
+ await restoreCommittedRecords(root, env);
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
index 5f6badf..b393c96 100644
--- a/packages/cli/src/record-sync.ts
+++ b/packages/cli/src/record-sync.ts
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { rm, stat } from "node:fs/promises";
import { relative, sep } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
import { z } from "zod";
import { cogitIgnored, findGitRoot, gitUserEmail } from "./git.js";
import { atomicWrite, atomicWriteJson, readJson } from "./store/fs.js";
@@ -49,6 +50,10 @@ const SyncState = z.object({
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({}),
+ /** The HEAD last searched for commits that stopped tracking the record. */
+ historyCheckedAt: z.string().optional(),
+ /** Those commits, once their sessions were brought back. */
+ restoredFrom: z.array(z.string()).default([]),
});
type SyncState = z.infer<typeof SyncState>;
@@ -364,6 +369,81 @@ export async function importRecords(root: string, env: NodeJS.ProcessEnv): Promi
return written;
}
+/**
+ * Older versions committed the record, so the commit that stopped tracking it makes
+ * every `git pull` delete those files from a teammate's disk, and a new clone never
+ * gets them. They are still in history: this brings back what such a commit
+ * removed. They count as seen, so old sessions are not sent again. A later prune
+ * stays a prune here, since a commit is only read once. Returns how many came back.
+ */
+export async function restoreCommittedRecords(
+ root: string,
+ env: NodeJS.ProcessEnv,
+): Promise<number> {
+ if (!(await isSharing(root))) return 0;
+ const head = (await runGit(root, ["rev-parse", "HEAD"], env)).stdout.toString("utf8").trim();
+ if (head === "" || (await readState(root)).historyCheckedAt === head) return 0;
+ const log = await runGit(
+ root,
+ [
+ "log",
+ "--diff-filter=D",
+ "--format=commit %H",
+ "--name-only",
+ "--relative",
+ "--",
+ ".cogit/sessions",
+ ],
+ env,
+ );
+ let restored = 0;
+ const conversations = (await loadConfig(env)).shareConversations;
+ await updateState(root, async (state) => {
+ const done = new Set(state.restoredFrom);
+ const newest = new Map<string, string>();
+ let commit = "";
+ for (const line of log.stdout.toString("utf8").split("\n")) {
+ if (line.startsWith("commit ")) commit = line.slice("commit ".length);
+ else if (line !== "" && !done.has(commit) && !newest.has(line)) newest.set(line, commit);
+ }
+ const paths = projectPaths(root);
+ const wanted = [...newest].flatMap(([file, from]) => {
+ const name = /^\.cogit\/sessions\/([^/]+?)(\.events\.jsonl|\.json)$/.exec(file);
+ if (name === null || !SESSION_ID.test(name[1] as string)) return [];
+ const id = name[1] as string;
+ const target = name[2] === ".json" ? paths.session(id) : paths.events(id);
+ return existsSync(target) ? [] : [{ id, target, spec: `${from}^:./${file}` }];
+ });
+ const blobs =
+ wanted.length === 0
+ ? new Map<string, Buffer>()
+ : await readBlobs(
+ root,
+ wanted.map((item) => item.spec),
+ env,
+ );
+ const stamps = { ...state.stamps };
+ const ids = new Set<string>();
+ for (const { id, target, spec } of wanted) {
+ const blob = blobs.get(spec);
+ if (blob === undefined) continue;
+ await atomicWrite(target, blob);
+ ids.add(id);
+ }
+ for (const id of ids) {
+ stamps[id] = await stampOf(await sessionFiles(root, id, conversations), conversations);
+ }
+ restored = ids.size;
+ return {
+ ...state,
+ stamps,
+ historyCheckedAt: head,
+ restoredFrom: [...done, ...new Set(newest.values())],
+ };
+ });
+ return restored;
+}
+
/** 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);
@@ -417,19 +497,77 @@ export async function downloadRecords(
}
/**
- * 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.
+ * What the `pre-push` hook announces: how many sessions this push would take along,
+ * without any network. Pushes to other remotes take none, so a deploy remote or a
+ * fork never receives the record.
*/
-export async function queueRecords(
+export async function countUnsentRecords(
root: string,
env: NodeJS.ProcessEnv,
- pushedRemote?: string,
+ pushedRemote: string | undefined,
): Promise<number> {
if (!(await isSharing(root))) return 0;
+ if (pushedRemote !== (await syncRemote(root, env))) 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);
+ return [...local].filter(([id, tree]) => tracking.get(id) !== tree).length;
+}
+
+/**
+ * Whether the remote now holds what the hook saw going out. `pre-push` runs before
+ * the push, and also for `--dry-run` and for a push the remote goes on to reject;
+ * git has no hook for "it worked", so this asks the remote.
+ */
+export async function pushLanded(
+ root: string,
+ env: NodeJS.ProcessEnv,
+ ref: string,
+ sha: string,
+ wait: { intervalMs: number; timeoutMs: number } = { intervalMs: 3000, timeoutMs: 600_000 },
+): Promise<boolean> {
const remote = await syncRemote(root, env);
- if (remote === undefined) return 0;
- if (pushedRemote !== undefined && pushedRemote !== remote) return 0;
+ if (remote === undefined) return false;
+ const deadline = Date.now() + wait.timeoutMs;
+ for (;;) {
+ const seen = await runGit(root, ["ls-remote", remote, ref], quietEnv(env));
+ if (
+ seen.stdout
+ .toString("utf8")
+ .split("\n")
+ .some((line) => line.startsWith(`${sha}\t`))
+ )
+ return true;
+ if (Date.now() >= deadline) return false;
+ await sleep(wait.intervalMs);
+ }
+}
+
+/**
+ * The background half of `git push`: once the code has landed (`after` names the
+ * ref and hash the hook saw; a push with nothing to send has none), queues what the
+ * remote does not have and sends it. A dry run or a rejected push queues nothing.
+ */
+export async function sendAfterPush(
+ root: string,
+ env: NodeJS.ProcessEnv,
+ after?: string,
+ wait?: { intervalMs: number; timeoutMs: number },
+): Promise<number> {
+ if (after !== undefined) {
+ const split = after.lastIndexOf("=");
+ if (!(await pushLanded(root, env, after.slice(0, split), after.slice(split + 1), wait)))
+ return 0;
+ }
+ await queueRecords(root, env);
+ return sendRecords(root, env);
+}
+
+/** Writes what changed and queues every session the remote does not have. Returns its size. */
+export async function queueRecords(root: string, env: NodeJS.ProcessEnv): Promise<number> {
+ if (!(await isSharing(root))) return 0;
+ if ((await syncRemote(root, env)) === undefined) return 0;
await snapshotRecords(root, env);
const scope = await sessionScope(root);
const local = await listRefs(root, LOCAL, scope, env);
diff --git a/packages/cli/test/record-sync.test.ts b/packages/cli/test/record-sync.test.ts
index 261851a..2ca1e24 100644
--- a/packages/cli/test/record-sync.test.ts
+++ b/packages/cli/test/record-sync.test.ts
@@ -12,14 +12,18 @@ import { runHook } from "../src/hooks/run.js";
import { prepareRecords } from "../src/record-prepare.js";
import {
addRecordRefspec,
+ countUnsentRecords,
deleteRecords,
downloadRecords,
importRecords,
isSharing,
+ pushLanded,
queueRecords,
RECORD_REFSPEC,
reconcileRecords,
recordSyncStatus,
+ restoreCommittedRecords,
+ sendAfterPush,
sendRecords,
snapshotRecords,
syncRemote,
@@ -92,7 +96,7 @@ describe("the record on its own refs", () => {
};
const push = async (root: string): Promise<number> => {
- const queued = await queueRecords(root, env, "origin");
+ const queued = await queueRecords(root, env);
if (queued > 0) await sendRecords(root, env);
return queued;
};
@@ -160,7 +164,8 @@ describe("the record on its own refs", () => {
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 countUnsentRecords(alice, env, "deploy")).toBe(0);
+ expect(await countUnsentRecords(alice, env, "origin")).toBe(1);
expect(await sendRecords(alice, env)).toBe(0);
expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toBe("");
await push(alice);
@@ -202,10 +207,10 @@ describe("the record on its own refs", () => {
await push(alice);
const bob = await cloneAs("bob");
await prepareRecords(bob, env, () => {});
- expect(await queueRecords(bob, env, "origin")).toBe(0);
+ expect(await queueRecords(bob, env)).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 queueRecords(bob, env)).toBe(0);
expect(await refs(bob)).toEqual([]);
});
@@ -253,7 +258,8 @@ describe("the record on its own refs", () => {
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 queueRecords(privateRoot, env)).toBe(0);
+ expect(await countUnsentRecords(privateRoot, env, "origin")).toBe(0);
expect(await refs(privateRoot)).toEqual([]);
expect(await git(privateRoot, "config", "--get-all", "remote.origin.fetch")).not.toContain(
"cogit",
@@ -272,7 +278,7 @@ describe("the record on its own refs", () => {
await git(alice, "remote", "add", "upstream", join(dir, "nowhere.git"));
expect(await syncRemote(alice, env)).toBe("upstream");
- await queueRecords(alice, env, "upstream");
+ await queueRecords(alice, env);
expect(await sendRecords(alice, env)).toBe(0);
const failed = await recordSyncStatus(alice, env);
expect(failed.pending).toBe(1);
@@ -325,7 +331,7 @@ describe("the record on its own refs", () => {
);
});
- it("queues in the pre-push hook and starts the send in the background", async () => {
+ it("announces in the pre-push hook and hands the send to the background", async () => {
await record(alice, "s1", "First", "[email protected]");
const started: string[][] = [];
const spawned = ((_cli: string, args: string[]) => {
@@ -337,15 +343,138 @@ describe("the record on its own refs", () => {
printed.push(text);
return true;
}) as typeof process.stderr.write;
+ const sha = "a".repeat(40);
+ const zero = "0".repeat(40);
+ const hook = (remoteName: string, refs: string): Promise<void> =>
+ runGitHook(
+ "pre-push",
+ alice,
+ env,
+ [remoteName, remote],
+ new Date(T0),
+ spawned,
+ async () => refs,
+ );
try {
- await runGitHook("pre-push", alice, env, ["origin", remote], new Date(T0), spawned);
+ await hook("origin", `refs/heads/main ${sha} refs/heads/main ${zero}\n`);
+ await hook("deploy", `refs/heads/main ${sha} refs/heads/main ${zero}\n`);
+ await hook("origin", `(delete) ${zero} refs/heads/old ${sha}\n`);
+ await hook("origin", "");
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");
+ expect(started).toHaveLength(2);
+ expect(started[0]?.slice(0, 4)).toEqual([
+ "record-sync",
+ "send-pushed",
+ "--after",
+ `refs/heads/main=${sha}`,
+ ]);
+ expect(started[1]?.slice(0, 3)).toEqual(["record-sync", "send-pushed", "-C"]);
+ expect(printed.join("")).toContain("1 session record will follow this push to origin");
+ // Nothing is queued until the push has landed.
+ expect((await recordSyncStatus(alice, env)).pending).toBe(0);
+ });
+
+ it("sends only after the code has landed", async () => {
+ const quick = { intervalMs: 1, timeoutMs: 30 };
+ await record(alice, "s1", "First", "[email protected]");
+ const head = (await git(alice, "rev-parse", "HEAD")).trim();
+ const unpushed = "b".repeat(40);
+
+ // A dry run or a rejected push: the remote never holds it, so nothing goes.
+ expect(await sendAfterPush(alice, env, `refs/heads/main=${unpushed}`, quick)).toBe(0);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toBe("");
+ expect((await recordSyncStatus(alice, env)).pending).toBe(0);
+
+ expect(await sendAfterPush(alice, env, `refs/heads/main=${head}`, quick)).toBe(1);
+ expect(await git(alice, "ls-remote", remote, "refs/cogit/*")).toContain("s1");
+
+ // Nothing to land: `git push` with the code already there still sends.
+ await record(alice, "s2", "Second", "[email protected]");
+ expect(await sendAfterPush(alice, env)).toBe(1);
+
+ await git(alice, "remote", "remove", "origin");
+ expect(await pushLanded(alice, env, "refs/heads/main", head, quick)).toBe(false);
+ });
+
+ describe("a project that used to commit its record", () => {
+ /** Alice committed sessions under an older version; Bob has them, and one of his own. */
+ const committed = async (): Promise<string> => {
+ await record(alice, "old1", "Alice old", "[email protected]");
+ await git(
+ alice,
+ "add",
+ "-f",
+ projectPaths(alice).session("old1"),
+ projectPaths(alice).events("old1"),
+ );
+ await git(alice, "commit", "-qm", "chore: record");
+ await git(alice, "push", "-q");
+ const bob = await cloneAs("bob");
+ await record(bob, "old2", "Bob old", "[email protected]");
+ await git(bob, "add", "-f", projectPaths(bob).session("old2"));
+ await git(bob, "commit", "-qm", "chore: record");
+ await git(bob, "push", "-q");
+ await git(alice, "pull", "-q");
+ await git(alice, "rm", "-rq", "--cached", ".cogit/sessions");
+ await git(alice, "commit", "-qm", "chore: stop tracking the cogit record");
+ await git(alice, "push", "-q");
+ return bob;
+ };
+
+ it("brings back what the pull deleted from a teammate's disk", async () => {
+ const bob = await committed();
+ await git(bob, "pull", "-q");
+ expect(existsSync(projectPaths(bob).session("old2"))).toBe(false);
+ await prepareRecords(bob, env, () => {});
+ expect(await title(bob, "old1")).toBe("Alice old");
+ expect(await title(bob, "old2")).toBe("Bob old");
+ expect(await readFile(projectPaths(bob).events("old1"), "utf8")).toContain("Alice old");
+ // Already public in history: nothing goes out again.
+ expect(await countUnsentRecords(bob, env, "origin")).toBe(0);
+ expect(await git(bob, "status", "--short")).toBe("");
+ });
+
+ it("gives a new clone the old sessions too", async () => {
+ await committed();
+ const carol = await cloneAs("carol");
+ await prepareRecords(carol, env, () => {});
+ expect(await title(carol, "old1")).toBe("Alice old");
+ expect(await title(carol, "old2")).toBe("Bob old");
+ });
+
+ it("reads a commit once, so a later prune stays deleted", async () => {
+ const bob = await committed();
+ await git(bob, "pull", "-q");
+ expect(await restoreCommittedRecords(bob, env)).toBe(2);
+ expect(await restoreCommittedRecords(bob, env)).toBe(0);
+ await deleteRecords(bob, ["old2"], env);
+ await writeFile(join(bob, "a.txt"), "new\n");
+ await git(bob, "commit", "-qam", "feat: later");
+ expect(await restoreCommittedRecords(bob, env)).toBe(0);
+ expect(existsSync(projectPaths(bob).session("old2"))).toBe(false);
+ });
+
+ it("ignores other deleted files, and does nothing without history or sharing", async () => {
+ await writeFile(join(alice, ".cogit", "sessions-note"), "x");
+ const empty = join(dir, "empty");
+ await mkdir(empty);
+ await git(empty, "init", "-q", "-b", "main");
+ await initShared(empty);
+ expect(await restoreCommittedRecords(empty, env)).toBe(0);
+ await mkdir(projectPaths(alice).sessions, { recursive: true });
+ await writeFile(join(alice, ".cogit", "sessions", "bad name.json"), "{}");
+ await git(alice, "add", "-f", join(alice, ".cogit", "sessions", "bad name.json"));
+ await git(alice, "commit", "-qm", "chore: odd file");
+ await git(alice, "rm", "-q", "--cached", join(alice, ".cogit", "sessions", "bad name.json"));
+ await git(alice, "commit", "-qm", "chore: drop it");
+ await rm(join(alice, ".cogit", "sessions", "bad name.json"));
+ expect(await restoreCommittedRecords(alice, env)).toBe(0);
+ await writeFile(join(alice, ".gitignore"), "/.cogit/\n");
+ expect(await restoreCommittedRecords(alice, env)).toBe(0);
+ });
});
it("a real git push fires the hook and never fails because of it", async () => {
@@ -428,7 +557,7 @@ describe("the record on its own refs", () => {
expect((await check(alice))?.message).toContain("shared through origin");
await record(alice, "s1", "First", "[email protected]");
- await queueRecords(alice, env, "origin");
+ await queueRecords(alice, env);
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/);
@@ -503,7 +632,7 @@ describe("the record on its own refs", () => {
await record(bob, "b1", "Unpushed", "[email protected]");
expect((await start(bob)).some((args) => args[0] === "record-sync")).toBe(false);
- await queueRecords(bob, env, "origin");
+ await queueRecords(bob, env);
const retried = await start(bob);
expect(retried.some((args) => args.join(" ").startsWith("record-sync send"))).toBe(true);
});