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(close): retry an unfinished closing pass at the next session start

Erenb1251222fe4a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d8625b..7e24ed4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- The session-end pass writes each thread's outcome, what is still open and where the session left off as things stood at the end: a problem a later message fixed no longer shows as open.
### Fixed
+- A session whose closing pass never finished (the machine was shut down within a minute or two of leaving, the terminal was closed, or the model run failed) is closed at the next session start in the project, in the background; before, it kept no "where it left off" line and no branch summaries. Each session is retried at most twice, and only sessions from the last three days that have been idle for ten minutes are touched.
+- A side-model run that hangs is stopped after five minutes and logged as such (`COGIT_CLAUDE_TIMEOUT_MS` changes the limit); before, it waited silently until the machine shut down.
- A new session shows on the map from its first message. Before, it appeared only once its first record was written, a few turns in.
## [0.21.0] - 2026-10-29
diff --git a/docs/schema/hook-state.json b/docs/schema/hook-state.json
index 69eb8cd..7a0f3ec 100644
--- a/docs/schema/hook-state.json
+++ b/docs/schema/hook-state.json
@@ -45,6 +45,11 @@
"minLength": 1,
"maxLength": 500
}
+ },
+ "closeRetries": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
}
},
"required": [
diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.ts
index 95d2dcc..b3cba03 100644
--- a/packages/cli/src/commands/backfill.ts
+++ b/packages/cli/src/commands/backfill.ts
@@ -185,11 +185,17 @@ function claudeBin(): string {
return process.platform === "win32" ? "claude.cmd" : "claude";
}
+/** How long one headless run may take; a closing pass usually needs under two minutes. */
+export const CLAUDE_TIMEOUT_MS = 5 * 60_000;
+
/**
* Runs the agent once, headless and without session persistence, with the prompt
- * on stdin. Resolves with stdout; a missing binary or a failed run rejects.
+ * on stdin. Resolves with stdout; a missing binary, a failed run or one that
+ * outlives the time limit rejects, so a hung run lands in the log instead of
+ * waiting until the machine shuts down. `COGIT_CLAUDE_TIMEOUT_MS` overrides the limit.
*/
export function runClaude(prompt: string, model: string, env: NodeJS.ProcessEnv): Promise<string> {
+ const limit = Number(env.COGIT_CLAUDE_TIMEOUT_MS) || CLAUDE_TIMEOUT_MS;
return new Promise((resolve, reject) => {
const child = spawn(
claudeBin(),
@@ -206,6 +212,11 @@ export function runClaude(prompt: string, model: string, env: NodeJS.ProcessEnv)
);
let out = "";
let err = "";
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child.kill("SIGKILL");
+ }, limit);
// The child may exit before reading the prompt; that write error is not ours.
child.stdin.on("error", () => {});
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
@@ -215,10 +226,14 @@ export function runClaude(prompt: string, model: string, env: NodeJS.ProcessEnv)
err += chunk;
});
child.on("error", (error) => {
+ clearTimeout(timer);
reject(new CliError(`could not run claude: ${error.message}`));
});
child.on("close", (code) => {
- if (code === 0) resolve(out);
+ clearTimeout(timer);
+ if (timedOut)
+ reject(new CliError(`claude did not answer within ${Math.round(limit / 1000)} s`));
+ else if (code === 0) resolve(out);
else reject(new CliError(`claude exited with ${code}: ${err.trim() || "no output"}`));
});
child.stdin.end(prompt);
diff --git a/packages/cli/src/hooks/close-retry.ts b/packages/cli/src/hooks/close-retry.ts
new file mode 100644
index 0000000..cfac87e
--- /dev/null
+++ b/packages/cli/src/hooks/close-retry.ts
@@ -0,0 +1,73 @@
+import { statSync } from "node:fs";
+import type { Session } from "../schema/session.js";
+import { type HookState, STATE_SCHEMA } from "../schema/state.js";
+import { loadAllSessions, loadConfig, updateState } from "../store/stores.js";
+import type { HookContext } from "./run.js";
+
+/** A session written to this recently may still be open in another terminal. */
+export const CLOSE_RETRY_IDLE_MS = 10 * 60_000;
+/** Older sessions are left alone, so an upgrade does not close a whole history at once. */
+export const CLOSE_RETRY_WINDOW_MS = 3 * 24 * 60 * 60_000;
+/** Retries per session, so one that never yields a `leftOff` is not closed forever. */
+export const CLOSE_RETRY_LIMIT = 2;
+/** Closing passes one session start may begin. */
+export const CLOSE_RETRY_BATCH = 3;
+
+/**
+ * The session-end pass runs detached when a session ends, and nothing waits for
+ * it: a machine shut down within the next minute, a closed terminal that never
+ * fired SessionEnd, or a hung or failed model run leaves the record without
+ * where it left off and without its branch summaries. The next session start in
+ * the project closes those sessions instead, with the same detached catch-up.
+ * Closing one that is in fact still open is harmless: its own session end runs
+ * the pass again and rewrites what this one wrote.
+ */
+export async function retryUnclosed(ctx: HookContext): Promise<void> {
+ const config = await loadConfig(ctx.env);
+ if (!config.sessionEndCatchUp) return;
+ const now = Date.parse(ctx.now);
+ const sessions = await loadAllSessions(ctx.root, () => {});
+ const candidates = sessions
+ .filter((session) => session.sessionId !== ctx.sessionId && unclosed(session, now))
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ let started = 0;
+ for (const session of candidates) {
+ if (started >= CLOSE_RETRY_BATCH) break;
+ const id = session.sessionId;
+ const transcript = await ctx.agent.findTranscript(id, ctx.env);
+ // No transcript (Claude Code deleted it) means nobody is writing to it either.
+ const written = transcript
+ ? statSync(transcript, { throwIfNoEntry: false })?.mtimeMs
+ : undefined;
+ if (written !== undefined && now - written < CLOSE_RETRY_IDLE_MS) continue;
+ let allowed = false;
+ await updateState(ctx.root, id, (cur) => {
+ const tries = cur?.closeRetries ?? 0;
+ if (tries >= CLOSE_RETRY_LIMIT) return cur ?? emptyState();
+ allowed = true;
+ return { ...(cur ?? emptyState()), closeRetries: tries + 1 };
+ });
+ if (!allowed) continue;
+ ctx.spawnDetached(["backfill", id, "--tail", "--close", "-C", ctx.root]);
+ started += 1;
+ }
+}
+
+/** Recorded messages, no `leftOff`, idle long enough and recent enough. */
+function unclosed(session: Session, now: number): boolean {
+ if (session.leftOff !== undefined) return false;
+ if (!session.nodes.some((node) => node.kind === "message")) return false;
+ const age = now - Date.parse(session.updatedAt);
+ return age >= CLOSE_RETRY_IDLE_MS && age <= CLOSE_RETRY_WINDOW_MS;
+}
+
+function emptyState(): HookState {
+ return {
+ schema: STATE_SCHEMA,
+ turns: 0,
+ turnsSinceUpdate: 0,
+ recordUpdatedAt: null,
+ turnsSinceSide: 0,
+ notedFiles: [],
+ };
+}
diff --git a/packages/cli/src/hooks/sessionend.ts b/packages/cli/src/hooks/sessionend.ts
index 592dc30..642dd9f 100644
--- a/packages/cli/src/hooks/sessionend.ts
+++ b/packages/cli/src/hooks/sessionend.ts
@@ -10,7 +10,8 @@ import type { HookContext } from "./run.js";
*
* The catch-up then runs the closing pass (threads, parents, branch summaries,
* where the session left off) over the whole session, so it starts even when
- * every message already has a node.
+ * 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
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index 87b19d4..a8de0d6 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -9,6 +9,7 @@ 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";
+import { retryUnclosed } from "./close-retry.js";
import type { HookContext, HookOutput } from "./run.js";
/** The compaction request, naming the skill the way the agent spells it. */
@@ -90,6 +91,9 @@ async function sessionStartOutput(ctx: HookContext): Promise<HookOutput | undefi
if ((await findGitRoot(ctx.root)) === undefined) return undefined;
return additionalContext(ctx, setupHint(ctx));
}
+ // Sessions whose closing pass never finished get it now, detached (a failure
+ // here must not cost the handoff).
+ await retryUnclosed(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;
diff --git a/packages/cli/src/schema/state.ts b/packages/cli/src/schema/state.ts
index 7f42a67..bf37e4a 100644
--- a/packages/cli/src/schema/state.ts
+++ b/packages/cli/src/schema/state.ts
@@ -24,6 +24,11 @@ export const HookState = z.object({
* walk the history again.
*/
notedFiles: z.array(z.string().min(1).max(500)).default([]),
+ /**
+ * Closing passes a later session started for this one because its own, at
+ * the session end, never finished (machine shut down, run hung or failed).
+ */
+ closeRetries: z.number().int().min(0).optional(),
});
export type HookState = z.infer<typeof HookState>;
diff --git a/packages/cli/test/backfill.test.ts b/packages/cli/test/backfill.test.ts
index 6e95bf2..30186d1 100644
--- a/packages/cli/test/backfill.test.ts
+++ b/packages/cli/test/backfill.test.ts
@@ -262,6 +262,19 @@ describe("backfill --tail", () => {
expect(await record()).toBeUndefined();
});
+ it("stops a headless run that outlives the time limit and says so", async () => {
+ const env = {
+ ...(await fakeClaude("setTimeout(() => {}, 60_000);", dir)),
+ COGIT_CLAUDE_TIMEOUT_MS: "300",
+ };
+ await initialized(env);
+ await transcript([typed("first", 1)]);
+ await expect(backfillTail(root, "s1", fakeIo(env))).rejects.toThrow(
+ /claude did not answer within 0 s/,
+ );
+ expect(await record()).toBeUndefined();
+ });
+
it("reports a missing claude binary", async () => {
const empty = join(dir, "empty");
await mkdir(empty);
diff --git a/packages/cli/test/close-retry.test.ts b/packages/cli/test/close-retry.test.ts
new file mode 100644
index 0000000..c43d9a4
--- /dev/null
+++ b/packages/cli/test/close-retry.test.ts
@@ -0,0 +1,112 @@
+import { mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { defaultAgent } from "../src/agents/index.js";
+import { configSet } from "../src/commands/config.js";
+import { init } from "../src/commands/init.js";
+import { sessionWrite } from "../src/commands/session.js";
+import { CLOSE_RETRY_LIMIT, retryUnclosed } from "../src/hooks/close-retry.js";
+import type { HookContext } from "../src/hooks/run.js";
+import { projectPaths } from "../src/store/paths.js";
+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";
+
+let dir: string;
+let root: string;
+let env: NodeJS.ProcessEnv;
+let spawned: string[][];
+
+const HOUR = 60 * 60_000;
+// Records written in these tests carry the frozen clock, T0.
+const at = (ms: number) => new Date(Date.parse(T0) + ms);
+const later = (ms: number) => at(ms).toISOString();
+
+beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ env = envFor(dir);
+ spawned = [];
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(env));
+});
+
+function ctx(now: string, sessionId = "current"): HookContext {
+ return {
+ agent: defaultAgent(),
+ input: { session_id: sessionId, cwd: root, source: "startup" },
+ sessionId,
+ root,
+ initialized: true,
+ env,
+ now,
+ spawnDetached: (args) => spawned.push(args),
+ };
+}
+
+function transcriptPath(id: string): string {
+ return join(env.CLAUDE_CONFIG_DIR ?? "", "projects", "proj", `${id}.jsonl`);
+}
+
+/** A recorded session with one message and its transcript, both written at T0. */
+async function recorded(id: string, extra: Record<string, unknown> = {}): Promise<void> {
+ await mkdir(join(env.CLAUDE_CONFIG_DIR ?? "", "projects", "proj"), { recursive: true });
+ const line = { type: "user", timestamp: T0, message: { content: "Hi" } };
+ await writeFile(transcriptPath(id), `${JSON.stringify(line)}\n`);
+ await utimes(transcriptPath(id), at(0), at(0));
+ await sessionWrite({ dir: root, by: "side" }, fakeIo(env), async () =>
+ JSON.stringify({
+ sessionId: id,
+ nodes: [{ id: "m1", kind: "message", title: "Hi" }],
+ ...extra,
+ }),
+ );
+}
+
+const closing = (id: string) => ["backfill", id, "--tail", "--close", "-C", root];
+
+describe("retryUnclosed", () => {
+ it("closes an idle session that has no leftOff, up to the retry limit", async () => {
+ await recorded("s1");
+ for (let i = 0; i < CLOSE_RETRY_LIMIT + 1; i += 1) await retryUnclosed(ctx(later(HOUR)));
+ expect(spawned).toEqual(Array(CLOSE_RETRY_LIMIT).fill(closing("s1")));
+ const state = JSON.parse(await readFile(projectPaths(root).state("s1"), "utf8"));
+ expect(state.closeRetries).toBe(CLOSE_RETRY_LIMIT);
+ });
+
+ it("leaves closed, current, recent, old and message-less sessions alone", async () => {
+ await recorded("closed", { leftOff: "Done." });
+ await recorded("current");
+ await recorded("busy");
+ // Its transcript was written five minutes before the start: maybe still open.
+ const recent = at(HOUR - 5 * 60_000);
+ await utimes(transcriptPath("busy"), recent, recent);
+ await sessionWrite({ dir: root, by: "side" }, fakeIo(env), async () =>
+ JSON.stringify({ sessionId: "steps", nodes: [{ id: "a", kind: "step", title: "Step" }] }),
+ );
+ await retryUnclosed(ctx(later(HOUR)));
+ expect(spawned).toEqual([]);
+
+ await recorded("old");
+ await retryUnclosed(ctx(later(4 * 24 * HOUR), "none"));
+ expect(spawned).toEqual([]);
+ });
+
+ it("closes a session whose transcript is gone", async () => {
+ await recorded("s1");
+ await rm(transcriptPath("s1"));
+ await retryUnclosed(ctx(later(HOUR)));
+ expect(spawned).toEqual([closing("s1")]);
+ });
+
+ it("starts at most three closing passes per session start", async () => {
+ for (const id of ["a", "b", "c", "d"]) await recorded(id);
+ await retryUnclosed(ctx(later(HOUR)));
+ expect(spawned).toHaveLength(3);
+ });
+
+ it("does nothing when the session-end catch-up is off", async () => {
+ await recorded("s1");
+ await configSet("sessionEndCatchUp", "false", fakeIo(env));
+ await retryUnclosed(ctx(later(HOUR)));
+ expect(spawned).toEqual([]);
+ });
+});