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(init): set a project up for a team and stop sessions without the plugin

Eren5a1df952d886
diff --git a/CHANGELOG.md b/CHANGELOG.md
index daf7d78..66640fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- A logo: the c of cogito drawn as a git lane with commits, with a branch that leaves and merges back (`docs/images/cogit-mark.svg`). It heads the README and is the browser tab icon of the map and the panel, which used to ask the server for a missing `favicon.ico`. Under the slogan the README shows Descartes, after the Frans Hals portrait, with git branches running through his hair.
+- `cogit init` can set the project up for a team (`--project-settings`): it enables the plugin in the project's `.claude/settings.json` and adds a hook that stops the first message of an interactive session that started without the plugin, once per session, with the install command. Headless `claude -p` runs pass through.
+- The README states what recording costs: about 3–7% of a session's tokens in measured sessions.
+
### Changed
- The "Your turn" inbox: each row closes with an × in its top-right corner (hidden until the agent writes in that session again), rows of different projects carry their own lane colour on the left, and on a project's map the inbox starts folded to one "Your turn" line so it no longer pushes the map off the page.
diff --git a/README.md b/README.md
index 7aa9fe4..a056548 100644
--- a/README.md
+++ b/README.md
@@ -58,15 +58,25 @@ The Claude Code plugin adds the skill that keeps the record and the hooks that m
```bash
cd your-project
-cogit init # asks about git, transcript retention and summary language
+cogit init # asks about git, transcript retention, team setup and summary language
cogit open # builds the map and serves it on 127.0.0.1
```
Then work as usual. The skill updates the record every few turns (`updateEveryTurns`, default
5) and at session end; the hooks write `.cogit/HEAD`, rebuild the map and, if `recordCommit`
-is `auto`, commit the record. Nothing cogit installs can block a prompt or a commit: every
+is `auto`, commit the record. Nothing in the plugin can block a prompt or a commit: every
hook failure is silent and exits 0.
+The record is written by the session's own agent, so it costs tokens: in our sessions it added
+about 3–7% to a session's token cost, more in short ones. Raise `updateEveryTurns` to record
+less often.
+
+If you agree to the team setup, `init` also writes the project's `.claude/settings.json`
+(commit it to share): it turns the plugin on for everyone who opens the repository, and adds a
+small hook that stops the first message of a session that started without the plugin, once,
+with the install command, since such a session records nothing. Send the message again to go
+on without recording. Headless runs (`claude -p`) are never stopped.
+
## Read the lineage
```bash
diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.ts
index 568a1aa..7eae1e7 100644
--- a/packages/cli/src/agents/claude/index.ts
+++ b/packages/cli/src/agents/claude/index.ts
@@ -3,10 +3,13 @@ import { additionalContext, parseHookInput } from "./hooks.js";
import {
allowSkill,
CLAUDE_DEFAULT_RETENTION,
+ markLive,
+ readProjectSetup,
readRetention,
readSkillAllowed,
SKILL_RULE,
setRetention,
+ writeProjectSetup,
} from "./settings.js";
import {
claudeConfigDir,
@@ -54,4 +57,7 @@ export const claude: AgentAdapter = {
readSkillAllowed,
setRetention,
allowSkill,
+ readProjectSetup,
+ writeProjectSetup,
+ markLive,
};
diff --git a/packages/cli/src/agents/claude/settings.ts b/packages/cli/src/agents/claude/settings.ts
index c6d74ea..839ddb0 100644
--- a/packages/cli/src/agents/claude/settings.ts
+++ b/packages/cli/src/agents/claude/settings.ts
@@ -1,5 +1,5 @@
-import { constants, copyFile } from "node:fs/promises";
-import { homedir } from "node:os";
+import { constants, copyFile, mkdir, writeFile } from "node:fs/promises";
+import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { atomicWriteJson, readJson } from "../../store/fs.js";
import type { FileChange } from "../types.js";
@@ -98,3 +98,113 @@ export async function allowSkill(env: NodeJS.ProcessEnv, stamp: string): Promise
return { ...s, permissions: { ...permissions, allow: [...allow, SKILL_RULE] } };
});
}
+
+/**
+ * Team setup in the project's shared `.claude/settings.json`: the plugin is
+ * enabled for everyone who opens the repository, and a guard hook that does not
+ * need the plugin stops the first message of an attended session that started
+ * without it. The plugin's SessionStart hook leaves {@link liveMarker}; the
+ * guard blocks once per session when it is missing, so a second send goes
+ * through. Headless runs (`claude -p`, loops) are never blocked.
+ */
+export const PLUGIN_ID = "cogit@cogit";
+export const MARKETPLACE = "cogit";
+export const MARKETPLACE_REPO = "sainthardrock/cogit";
+export const INSTALL_COMMAND = `claude plugin install cogit --marketplace ${MARKETPLACE_REPO}`;
+
+/** Where a session's SessionStart leaves its mark; the guard reads the same path. */
+export function liveDir(): string {
+ return join(tmpdir(), "cogit-live");
+}
+
+/** Marks a session as started with the plugin loaded. */
+export async function markLive(sessionId: string): Promise<void> {
+ if (!/^[\w-]+$/.test(sessionId)) return;
+ await mkdir(liveDir(), { recursive: true });
+ await writeFile(join(liveDir(), sessionId), "");
+}
+
+export const GUARD_REASON =
+ "cogit: this session started without the cogit plugin, so nothing in it is recorded. " +
+ `Install it once with \`${INSTALL_COMMAND}\` (or start claude with --plugin-dir), ` +
+ "then open a new session. Send the message again to continue without recording.";
+
+/**
+ * The guard as one `node -e` command: no cogit install needed, no single quotes
+ * inside, so `sh` passes it through unchanged. Keep in step with {@link markLive}.
+ */
+export const GUARD_COMMAND =
+ "node -e '" +
+ [
+ 'const fs=require("fs"),os=require("os"),path=require("path");',
+ 'if(process.env.CLAUDE_CODE_SESSION_ATTENDED!=="1"||process.env.COGIT_DISABLE)process.exit(0);',
+ 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{',
+ "const id=JSON.parse(s).session_id;if(!/^[\\w-]+$/.test(id))return;",
+ 'const dir=path.join(os.tmpdir(),"cogit-live");if(fs.existsSync(path.join(dir,id)))return;',
+ 'const warned=path.join(dir,id+".warned");if(fs.existsSync(warned))return;',
+ 'fs.mkdirSync(dir,{recursive:true});fs.writeFileSync(warned,"");',
+ `process.stdout.write(JSON.stringify({decision:"block",reason:${JSON.stringify(GUARD_REASON)}}))`,
+ "}catch{}});",
+ ].join("") +
+ "' # cogit:guard";
+
+const GUARD_TAG = "# cogit:guard";
+
+export function projectSettingsPath(root: string): string {
+ return join(root, ".claude", "settings.json");
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+function hasGuard(settings: Record<string, unknown>): boolean {
+ const hooks = isObject(settings.hooks) ? settings.hooks.UserPromptSubmit : undefined;
+ return JSON.stringify(hooks ?? []).includes(GUARD_TAG);
+}
+
+/** Whether the project's shared settings already carry the team setup; undefined if unreadable. */
+export async function readProjectSetup(root: string): Promise<boolean | undefined> {
+ const settings = await readSettings(projectSettingsPath(root));
+ if (!settings) return undefined;
+ const plugins = isObject(settings.enabledPlugins) ? settings.enabledPlugins : {};
+ return plugins[PLUGIN_ID] === true && hasGuard(settings);
+}
+
+/**
+ * Writes the team setup into the project's `.claude/settings.json`, keeping every
+ * other key and hook. The file is meant to be committed, so no backup is left
+ * beside it; an unparseable file is never touched.
+ */
+export async function writeProjectSetup(root: string): Promise<FileChange> {
+ const file = projectSettingsPath(root);
+ const settings = await readSettings(file);
+ if (!settings) throw new Error(`${file} is not a valid JSON object; not changing it`);
+ for (const key of ["enabledPlugins", "extraKnownMarketplaces", "hooks"])
+ if (settings[key] !== undefined && !isObject(settings[key]))
+ throw new Error(`${file} has an unexpected ${key}; not changing it`);
+ const hooks = (settings.hooks ?? {}) as Record<string, unknown>;
+ const submit = hooks.UserPromptSubmit ?? [];
+ if (!Array.isArray(submit))
+ throw new Error(`${file} has an unexpected hooks.UserPromptSubmit; not changing it`);
+ const next: Record<string, unknown> = {
+ ...settings,
+ enabledPlugins: { ...(settings.enabledPlugins as object), [PLUGIN_ID]: true },
+ extraKnownMarketplaces: {
+ ...(settings.extraKnownMarketplaces as object),
+ [MARKETPLACE]: { source: { source: "github", repo: MARKETPLACE_REPO } },
+ },
+ hooks: hasGuard(settings)
+ ? hooks
+ : {
+ ...hooks,
+ UserPromptSubmit: [
+ ...submit,
+ { hooks: [{ type: "command", command: GUARD_COMMAND, timeout: 5 }] },
+ ],
+ },
+ };
+ await mkdir(join(root, ".claude"), { recursive: true });
+ await atomicWriteJson(file, next);
+ return { file };
+}
diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.ts
index 0da80bd..759abc0 100644
--- a/packages/cli/src/agents/types.ts
+++ b/packages/cli/src/agents/types.ts
@@ -143,4 +143,10 @@ export interface AgentAdapter {
setRetention(days: number, env: NodeJS.ProcessEnv, stamp: string): Promise<FileChange>;
/** Allows the record skill in the agent's settings. */
allowSkill(env: NodeJS.ProcessEnv, stamp: string): Promise<FileChange>;
+ /** Whether the project's shared settings enable the plugin and guard; undefined when unreadable. */
+ readProjectSetup(root: string): Promise<boolean | undefined>;
+ /** Enables the plugin for the whole project and adds the guard against sessions without it. */
+ writeProjectSetup(root: string): Promise<FileChange>;
+ /** Records that this session started with the plugin loaded; the guard looks for it. */
+ markLive(sessionId: string): Promise<void>;
}
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 7e94556..fab4100 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -32,6 +32,8 @@ export interface InitOptions {
retention?: number | "keep";
/** Allow the lineage skill in Claude Code's user settings; undefined asks. */
allowSkill?: boolean;
+ /** Enable the plugin and the guard in the project's shared settings; undefined asks. */
+ projectSettings?: boolean;
}
/** Below this, init offers to raise Claude Code's transcript retention. */
@@ -103,6 +105,27 @@ async function askSkillPermission(io: Io, opts: InitOptions): Promise<void> {
io.out(`Allowed ${agent.skillRule} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);
}
+async function askProjectSettings(io: Io, root: string, opts: InitOptions): Promise<void> {
+ const done = await agent.readProjectSetup(root);
+ if (done === undefined) {
+ io.warn("could not read the project's Claude Code settings; leaving them unchanged");
+ return;
+ }
+ if (done) return;
+ const add =
+ opts.projectSettings ??
+ (await io.prompt.confirm(
+ "Turn the plugin on for everyone who opens this project, and stop a session that " +
+ "started without it? (writes .claude/settings.json; commit it to share)",
+ true,
+ ));
+ if (!add) return;
+ await bestEffort(io, "could not update the project's Claude Code settings", async () => {
+ const { file } = await agent.writeProjectSetup(root);
+ io.out(`Enabled the plugin and the missing-plugin guard in ${file}.`);
+ });
+}
+
async function askLanguage(io: Io, opts: InitOptions): Promise<void> {
const firstRun = !(await readJson(globalPaths(io.env).config)).found;
if (!firstRun && opts.language === undefined) return;
@@ -184,6 +207,7 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<void
if (!existing.ok) throw new CliError(`${projectPaths(root).project}: ${existing.error}`);
await register(io, root, existing.data.name);
if (opts.allowSkill !== undefined) await askSkillPermission(io, opts);
+ if (opts.projectSettings !== undefined) await askProjectSettings(io, root, opts);
await refreshGitIntegration(io, root);
io.out(`Already initialized: ${existing.data.name} (${root})`);
return;
@@ -210,6 +234,7 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<void
await askRetention(io, opts);
await askSkillPermission(io, opts);
+ await askProjectSettings(io, root, opts);
await askLanguage(io, opts);
await updateProject(root, (cur) => cur ?? { schema: 1, name, epochs: [] });
diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.ts
index e8d7249..5181a39 100644
--- a/packages/cli/src/hooks/run.ts
+++ b/packages/cli/src/hooks/run.ts
@@ -82,6 +82,11 @@ export async function runHook(
return undefined;
}
if (!Slug.safeParse(input.session_id).success) return undefined;
+ // The project's guard hook looks for this mark (agents/claude/settings.ts).
+ if (handler === onSessionStart)
+ await agent
+ .markLive(input.session_id)
+ .catch((err: Error) => debug(`cogit mark: ${err.message}`));
// In a linked worktree both point at the worktree; the record lives in the main checkout.
const { root } = await resolveProjectRoot(env[agent.projectDirEnv] ?? input.cwd ?? ".");
const initialized = existsSync(projectPaths(root).project);
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index 5650863..4cc0320 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -48,9 +48,10 @@ export function setupHint(ctx: HookContext): string {
"Say this once, in one line, and do not repeat it in later turns. If the user asks " +
"you to set it up, ask the install questions in the chat (whether to commit " +
".cogit/, whether to keep transcripts longer, whether the lineage skill may run " +
- "without asking, and the summary language), then run " +
+ "without asking, whether to turn the plugin on for the whole project and stop " +
+ "sessions that start without it, and the summary language), then run " +
`${cli(ctx)} init --yes --git <ignore|commit> --retention <days|keep> --language <lang>` +
- " (add --allow-skill when the user agreed). Never run init or register the project on " +
+ " (add --allow-skill and --project-settings for what the user agreed to). Never run init or register the project on " +
`your own. If the user wants no more hints here, run ${cli(ctx)} config hint-off. ` +
"A plugin update reaches a running session only after /reload-plugins or a new chat."
);
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index eaf0c06..5e10793 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -283,6 +283,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.option("--retention <days>", 'Claude Code transcript retention, or "keep"', retention)
.option("--allow-skill", "let the agent run the lineage skill without asking")
.option("--no-allow-skill", "leave Claude Code's permissions unchanged")
+ .option(
+ "--project-settings",
+ "enable the plugin for this project and stop sessions that start without it",
+ )
+ .option("--no-project-settings", "leave the project's .claude/settings.json unchanged")
.option("-y, --yes", "accept defaults for every question")
.addHelpText("after", examples("cogit init", "cogit init ../my-app --git commit --yes"))
.action(
@@ -290,6 +295,8 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
const { yes, ...rest } = opts;
// --yes never changes Claude Code's permissions on its own
if (yes) rest.allowSkill ??= false;
+ // nor the project's shared settings
+ if (yes) rest.projectSettings ??= false;
await init(dir, rest, makeIo(!yes && process.stdin.isTTY === true));
}),
);
diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.ts
index 8dc82a4..964bfcd 100644
--- a/packages/cli/test/init.test.ts
+++ b/packages/cli/test/init.test.ts
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
import { beforeEach, describe, expect, it } from "vitest";
import {
allowSkill,
+ readProjectSetup,
readRetention,
readSkillAllowed,
SKILL_RULE,
@@ -30,6 +31,15 @@ const settingsFile = () => join(dir, "claude", "settings.json");
const readText = (f: string) => readFile(f, "utf8");
describe("init", () => {
+ it("leaves project settings it cannot read alone and says so", async () => {
+ await mkdir(join(root, ".claude"));
+ await writeFile(join(root, ".claude", "settings.json"), "{ not json");
+ const io = fakeIo(env);
+ await init(root, { name: "p", retention: "keep", allowSkill: false, language: "auto" }, io);
+ expect(io.warnings.join("\n")).toMatch(/could not read the project's Claude Code settings/);
+ expect(await readText(join(root, ".claude", "settings.json"))).toBe("{ not json");
+ });
+
it("recognizes a pre-rename .codelineage project and renames it", async () => {
await mkdir(join(root, ".codelineage"), { recursive: true });
await writeFile(
@@ -55,8 +65,9 @@ describe("init", () => {
data: { projects: [{ path: root, name: "proj" }] },
});
expect((await loadConfig(env)).language).toBe("auto");
- // not a git repo: name, retention, skill permission and language were asked
- expect(io.asked).toHaveLength(4);
+ // not a git repo: name, retention, skill permission, project settings and language
+ expect(io.asked).toHaveLength(5);
+ expect(await readProjectSetup(root)).toBe(true);
expect(await readSkillAllowed(env)).toBe(true);
expect(io.lines.at(-2)).toMatch(/^Initialized proj/);
// Outside a git repository there is nothing to ignore and no hook to install.
@@ -81,7 +92,14 @@ describe("init", () => {
const io = fakeIo(env, [], true);
await init(
root,
- { name: "P", git: "commit", retention: "keep", allowSkill: false, language: "Turkish" },
+ {
+ name: "P",
+ git: "commit",
+ retention: "keep",
+ allowSkill: false,
+ projectSettings: false,
+ language: "Turkish",
+ },
io,
);
expect((await loadConfig(env)).language).toBe("Turkish");
@@ -125,20 +143,20 @@ describe("init", () => {
const io = fakeIo(env);
await init(root, {}, io);
expect(io.lines).toContain("Claude Code keeps transcripts for 365 days.");
- expect(io.asked).toHaveLength(3);
+ expect(io.asked).toHaveLength(4);
});
it("applies a retention option without asking, and skips an unchanged one", async () => {
await init(
root,
- { name: "p", retention: 90, allowSkill: false, language: "auto" },
+ { name: "p", retention: 90, allowSkill: false, projectSettings: false, language: "auto" },
fakeIo(env, [], true),
);
expect(await readRetention(env)).toBe(90);
const again = join(dir, "other");
await mkdir(again);
const io = fakeIo(env, [], true);
- await init(again, { name: "o", retention: 90, allowSkill: false }, io);
+ await init(again, { name: "o", retention: 90, allowSkill: false, projectSettings: false }, io);
expect(io.lines.some((l) => l.includes("cleanupPeriodDays"))).toBe(false);
});
@@ -153,7 +171,7 @@ describe("init", () => {
});
it("asks which fixed language on the first run only", async () => {
- await init(root, {}, fakeIo(env, ["proj", "keep", "yes", "fixed", "Turkish"]));
+ await init(root, {}, fakeIo(env, ["proj", "keep", "yes", "yes", "fixed", "Turkish"]));
expect((await loadConfig(env)).language).toBe("Turkish");
const second = join(dir, "second");
await mkdir(second);
diff --git a/packages/cli/test/project-setup.test.ts b/packages/cli/test/project-setup.test.ts
new file mode 100644
index 0000000..ee07f61
--- /dev/null
+++ b/packages/cli/test/project-setup.test.ts
@@ -0,0 +1,138 @@
+import { execFile } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ GUARD_COMMAND,
+ GUARD_REASON,
+ markLive,
+ PLUGIN_ID,
+ projectSettingsPath,
+ readProjectSetup,
+ writeProjectSetup,
+} from "../src/agents/claude/settings.js";
+import { runHook } from "../src/hooks/run.js";
+import { envFor, T0, tempDir } from "./helpers.js";
+
+let root: string;
+let tmp: string;
+beforeEach(async () => {
+ root = await tempDir();
+ tmp = await tempDir();
+});
+
+const readSettings = async () =>
+ JSON.parse(await readFile(projectSettingsPath(root), "utf8")) as Record<string, any>;
+
+/** Runs the guard the way Claude Code would: through `sh`, the payload on stdin. */
+function guard(sessionId: string, attended: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = execFile(
+ "sh",
+ ["-c", GUARD_COMMAND],
+ { env: { PATH: process.env.PATH, TMPDIR: tmp, CLAUDE_CODE_SESSION_ATTENDED: attended } },
+ (err, stdout) => (err ? reject(err) : resolve(stdout)),
+ );
+ child.stdin?.end(JSON.stringify({ session_id: sessionId, prompt: "hi" }));
+ });
+}
+
+/** Runs `fn` with the process temp dir pointed at the test's own. */
+async function withTmp<T>(fn: () => Promise<T>): Promise<T> {
+ const saved = process.env.TMPDIR;
+ process.env.TMPDIR = tmp;
+ try {
+ return await fn();
+ } finally {
+ // assigning undefined would store the string "undefined"
+ if (saved === undefined) delete process.env.TMPDIR;
+ else process.env.TMPDIR = saved;
+ }
+}
+
+describe("project setup", () => {
+ it("enables the plugin and adds the guard, keeping what was there", async () => {
+ await mkdir(join(root, ".claude"));
+ const other = { hooks: [{ type: "command", command: "echo other" }] };
+ await writeFile(
+ projectSettingsPath(root),
+ JSON.stringify({
+ model: "x",
+ enabledPlugins: { "a@b": true },
+ hooks: { UserPromptSubmit: [other], Stop: [other] },
+ }),
+ );
+ expect(await readProjectSetup(root)).toBe(false);
+
+ await writeProjectSetup(root);
+ await writeProjectSetup(root);
+
+ const s = await readSettings();
+ expect(s.model).toBe("x");
+ expect(s.enabledPlugins).toEqual({ "a@b": true, [PLUGIN_ID]: true });
+ expect(s.extraKnownMarketplaces.cogit.source).toEqual({
+ source: "github",
+ repo: "sainthardrock/cogit",
+ });
+ expect(s.hooks.Stop).toEqual([other]);
+ // the guard is added once, after the hooks that were there
+ expect(s.hooks.UserPromptSubmit).toHaveLength(2);
+ expect(s.hooks.UserPromptSubmit[0]).toEqual(other);
+ expect(await readProjectSetup(root)).toBe(true);
+ });
+
+ it("creates the file when there is none and refuses one it cannot parse", async () => {
+ await writeProjectSetup(root);
+ expect(await readProjectSetup(root)).toBe(true);
+
+ await writeFile(projectSettingsPath(root), "{ not json");
+ expect(await readProjectSetup(root)).toBeUndefined();
+ await expect(writeProjectSetup(root)).rejects.toThrow(/not a valid JSON object/);
+
+ await writeFile(projectSettingsPath(root), JSON.stringify({ enabledPlugins: [] }));
+ await expect(writeProjectSetup(root)).rejects.toThrow(/unexpected enabledPlugins/);
+ await writeFile(projectSettingsPath(root), JSON.stringify({ hooks: { UserPromptSubmit: {} } }));
+ await expect(writeProjectSetup(root)).rejects.toThrow(/unexpected hooks.UserPromptSubmit/);
+ });
+
+ it("blocks an attended session without the plugin once, then lets it through", async () => {
+ const first = await guard("s-1", "1");
+ expect(JSON.parse(first)).toEqual({ decision: "block", reason: GUARD_REASON });
+ expect(await guard("s-1", "1")).toBe("");
+ // another session is warned on its own
+ expect(await guard("s-2", "1")).not.toBe("");
+ });
+
+ it("never blocks a headless run or a session the plugin marked", async () => {
+ expect(await guard("s-3", "0")).toBe("");
+ expect(existsSync(join(tmp, "cogit-live", "s-3.warned"))).toBe(false);
+
+ await withTmp(() => markLive("s-4"));
+ expect(await guard("s-4", "1")).toBe("");
+ });
+
+ it("marks the session live from the plugin's SessionStart hook", async () => {
+ const env = { ...envFor(await tempDir()), TMPDIR: tmp };
+ const input = JSON.stringify({ session_id: "s-5", cwd: root });
+ await withTmp(() => runHook("sessionstart", input, env, T0, () => {}));
+ expect(existsSync(join(tmp, "cogit-live", "s-5"))).toBe(true);
+ expect(await guard("s-5", "1")).toBe("");
+ });
+
+ it("keeps the hook going when the mark cannot be written", async () => {
+ const env = envFor(await tempDir());
+ const notADir = join(tmp, "file");
+ await writeFile(notADir, "");
+ const lines: string[] = [];
+ const saved = tmp;
+ tmp = notADir;
+ try {
+ const input = JSON.stringify({ session_id: "s-6", cwd: root });
+ await withTmp(() => runHook("sessionstart", input, env, T0, (l) => lines.push(l)));
+ } finally {
+ tmp = saved;
+ }
+ expect(lines.some((l) => l.startsWith("cogit mark:"))).toBe(true);
+ });
+});