Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(cli): add session write with secret redaction
Erenfe144b4ac134
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 080dcb5..2ec4a69 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,3 +10,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `codelineage` CLI skeleton (`--version`, `--help`), MIT license.- `codelineage init`: creates `.codelineage/`, registers the project, asks for git policy, Claude Code transcript retention (`cleanupPeriodDays`, with backup) and summary language; `--yes` and per-question flags for non-interactive use.- `codelineage config get/set` and `codelineage epoch add`.+- `codelineage session write`: validates agent JSON from stdin or `--file`, redacts secret-looking values, merges into the session file under a lock.diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsnew file mode 100644index 0000000..90180e0--- /dev/null+++ b/packages/cli/src/commands/session.ts@@ -0,0 +1,67 @@+import { readFile } from "node:fs/promises";+import { resolve } from "node:path";+import { CliError, type Io } from "../io.js";+import { redactDeep } from "../redact.js";+import { mergeSession } from "../schema/merge.js";+import { SessionInput } from "../schema/session.js";+import { loadProject, updateSession } from "../store/stores.js";++export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {+ const chunks: Buffer[] = [];+ for await (const c of stream) chunks.push(typeof c === "string" ? Buffer.from(c) : c);+ return Buffer.concat(chunks).toString("utf8");+}++export interface SessionWriteOptions {+ dir: string;+ /** Read JSON from this file instead of stdin. */+ file?: string;+}++/**+ * Validates agent JSON, redacts secrets and merges it into the session file under+ * the session lock.+ */+export async function sessionWrite(+ opts: SessionWriteOptions,+ io: Io,+ stdin: () => Promise<string> = readStdin,+): Promise<void> {+ const root = resolve(opts.dir);+ const project = await loadProject(root);+ if (!project.found)+ throw new CliError(`${root} is not initialized; run \`codelineage init\` first`);+ if (!project.ok) throw new CliError(project.error);++ const text = opts.file ? await readFile(opts.file, "utf8") : await stdin();+ let raw: unknown;+ try {+ raw = JSON.parse(text);+ } catch (err) {+ throw new CliError(`input is not valid JSON: ${(err as Error).message}`);+ }+ const parsed = SessionInput.safeParse(raw);+ if (!parsed.success) {+ const issues = parsed.error.issues+ .slice(0, 5)+ .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);+ throw new CliError(`input does not match the session schema: ${issues.join("; ")}`);+ }++ const { value: input, count } = redactDeep(parsed.data);+ if (count > 0) io.warn(`redacted ${count} secret-looking value(s)`);+ if (input.epoch && !project.data.epochs.some((e) => e.id === input.epoch)) {+ io.warn(+ `epoch "${input.epoch}" is not in project.json; the session shows as unassigned until you run \`codelineage epoch add ${input.epoch} <title>\``,+ );+ }++ let warnings: string[] = [];+ const saved = await updateSession(root, input.sessionId, (cur) => {+ const merged = mergeSession(cur, input, io.now());+ warnings = merged.warnings;+ return merged.session;+ });+ for (const w of warnings) io.warn(w);+ io.out(`Saved session ${saved.sessionId} (${saved.nodes.length} nodes)`);+}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex a8461c4..c2236d8 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -3,6 +3,7 @@ import pkg from "../package.json" with { type: "json" };import { configGet, configSet } from "./commands/config.js";import { epochAdd } from "./commands/epoch.js";import { type InitOptions, init } from "./commands/init.js";+import { sessionWrite } from "./commands/session.js";import { CliError, type Io, processIo } from "./io.js";export type IoFactory = (interactive: boolean) => Io;@@ -73,5 +74,15 @@ export function createProgram(makeIo: IoFactory = processIo): Command {),);+ const session = program+ .command("session")+ .description("session records (used by the agent skill)");+ session+ .command("write")+ .description("merge session JSON from stdin into .codelineage/sessions/")+ .option("-C, --dir <dir>", "project directory", ".")+ .option("-f, --file <file>", "read JSON from a file instead of stdin")+ .action(run(async (opts: { dir: string; file?: string }) => sessionWrite(opts, makeIo(false))));+return program;}diff --git a/packages/cli/src/redact.ts b/packages/cli/src/redact.tsnew file mode 100644index 0000000..df16218--- /dev/null+++ b/packages/cli/src/redact.ts@@ -0,0 +1,60 @@+/**+ * Best-effort secret redaction. The skill already tells the agent not to record+ * secrets; this is the safety net before anything is written or rendered.+ */+const MASK = "[REDACTED]";++const PATTERNS: RegExp[] = [+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,+ /\bsk-ant-[A-Za-z0-9_-]{20,}/g, // Anthropic+ /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}/g, // OpenAI-style+ /\bgh[pousr]_[A-Za-z0-9]{30,}/g, // GitHub tokens+ /\bgithub_pat_[A-Za-z0-9_]{22,}/g,+ /\bglpat-[A-Za-z0-9_-]{20,}/g, // GitLab+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, // AWS access key id+ /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, // Slack+ /\bAIza[0-9A-Za-z_-]{35}\b/g, // Google API key+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, // JWT+];++/**+ * Keeps the label, masks the value: `password=hunter2!x` → `password=[REDACTED]`.+ * The value must look like a credential (8+ chars with a digit or symbol), so+ * prose such as "token: refresh flow" is left alone.+ */+const ASSIGNMENT =+ /\b((?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret)\s*[:=]\s*)(["']?)(?=[^\s"',;]*[0-9_\-+/!@#$%^&*])[^\s"',;]{8,}\2/gi;+const BEARER = /\b(Bearer\s+)[A-Za-z0-9._~+/-]{16,}=*/g;+const URL_CREDENTIALS = /(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi;++export function redactText(text: string): { text: string; count: number } {+ let count = 0;+ const hit = () => {+ count++;+ return MASK;+ };+ let out = text;+ for (const re of PATTERNS) out = out.replace(re, hit);+ out = out.replace(ASSIGNMENT, (_m, label: string, q: string) => `${label}${q}${hit()}${q}`);+ out = out.replace(BEARER, (_m, label: string) => `${label}${hit()}`);+ out = out.replace(URL_CREDENTIALS, (_m, prefix: string) => `${prefix}${hit()}@`);+ return { text: out, count };+}++/** Redacts every string inside a JSON-like value. */+export function redactDeep<T>(value: T): { value: T; count: number } {+ let count = 0;+ const walk = (v: unknown): unknown => {+ if (typeof v === "string") {+ const r = redactText(v);+ count += r.count;+ return r.text;+ }+ if (Array.isArray(v)) return v.map(walk);+ if (v !== null && typeof v === "object") {+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));+ }+ return v;+ };+ return { value: walk(value) as T, count };+}diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 025a91b..12494b7 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -60,6 +60,14 @@ describe("commands through the CLI", () => {expect(io.lines.at(-1)).toBe("Added epoch e1: First");});+ it("runs session write from a file", async () => {+ await cli("init", root, "--yes", "--retention", "keep");+ const f = join(dir, "s.json");+ await writeFile(f, '{"sessionId":"s1"}');+ await cli("session", "write", "-C", root, "-f", f);+ expect(io.lines.at(-1)).toBe("Saved session s1 (0 nodes)");+ });+it("prints user errors as one line", async () => {expect(await cli("config", "get", "nope")).toMatch(/^error: unknown key "nope"/);});diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.tsnew file mode 100644index 0000000..5f41fc8--- /dev/null+++ b/packages/cli/test/session.test.ts@@ -0,0 +1,128 @@+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { Readable } from "node:stream";+import { beforeEach, describe, expect, it } from "vitest";+import { epochAdd } from "../src/commands/epoch.js";+import { init } from "../src/commands/init.js";+import { readStdin, sessionWrite } from "../src/commands/session.js";+import { redactDeep, redactText } from "../src/redact.js";+import { loadSession } from "../src/store/stores.js";+import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";++describe("redactText", () => {+ it.each([+ ["key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123", "key [REDACTED]"],+ ["sk-proj-abcdefghijklmnopqrstuvwx", "[REDACTED]"],+ ["ghp_abcdefghijklmnopqrstuvwxyz0123456789", "[REDACTED]"],+ ["github_pat_11ABCDEFG0123456789_abcdef", "[REDACTED]"],+ ["glpat-abcdefghijklmnopqrstu", "[REDACTED]"],+ ["AKIAABCDEFGHIJKLMNOP", "[REDACTED]"],+ ["xoxb-1234567890-abcdef", "[REDACTED]"],+ ["AIzaSyA-abcdefghijklmnopqrstuvwxyz01234", "[REDACTED]"],+ ["eyJhbGciOiJI.eyJzdWIiOiIx.SflKxwRJSMeK", "[REDACTED]"],+ ["password=hunter22!", "password=[REDACTED]"],+ ['api_key: "abc123def456"', 'api_key: "[REDACTED]"'],+ ["Authorization: Bearer abcdefghijklmnop1234", "Authorization: Bearer [REDACTED]"],+ ["postgres://admin:[email protected]/x", "postgres://admin:[REDACTED]@db.local/x"],+ ["-----BEGIN RSA PRIVATE KEY-----\nMIIE\n-----END RSA PRIVATE KEY-----", "[REDACTED]"],+ ])("masks %s", (input, expected) => {+ expect(redactText(input).text).toBe(expected);+ });++ it.each([+ "token: refresh flow",+ "password reset is out of scope",+ "decided to keep the secret in the OS keychain",+ "https://example.com/path@v2",+ "sk-short",+ ])("leaves prose alone: %s", (input) => {+ expect(redactText(input)).toEqual({ text: input, count: 0 });+ });++ it("walks nested values and counts hits", () => {+ const r = redactDeep({ a: ["password=hunter22!", 3, null], b: { c: "ok", d: true } });+ expect(r).toEqual({+ value: { a: ["password=[REDACTED]", 3, null], b: { c: "ok", d: true } },+ count: 1,+ });+ });+});++describe("session write", () => {+ let dir: string;+ let root: string;+ let io: FakeIo;+ const write = (json: unknown) =>+ sessionWrite({ dir: root }, io, async () =>+ typeof json === "string" ? json : JSON.stringify(json),+ );++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ io = fakeIo(envFor(dir));+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ await epochAdd(root, "e2e", "E2E", fakeIo(envFor(dir)));+ });++ it("creates and then merges a session", async () => {+ await write({+ sessionId: "s1",+ title: "setup",+ epoch: "e2e",+ nodes: [{ id: "n1", kind: "phase", title: "start" }],+ });+ await write({+ sessionId: "s1",+ nodes: [{ id: "n2", parent: "n1", kind: "decision", title: "use elk", why: "nesting" }],+ });+ const s = await loadSession(root, "s1");+ expect(s).toMatchObject({ ok: true, data: { title: "setup", epoch: "e2e" } });+ expect(s.found && s.ok && s.data.nodes.map((n) => n.id)).toEqual(["n1", "n2"]);+ expect(io.lines).toEqual(["Saved session s1 (1 nodes)", "Saved session s1 (2 nodes)"]);+ expect(io.warnings).toEqual([]);+ });++ it("redacts secrets before writing", async () => {+ await write({+ sessionId: "s1",+ status: { goal: "rotate ghp_abcdefghijklmnopqrstuvwxyz0123456789" },+ });+ const s = await loadSession(root, "s1");+ expect(s.found && s.ok && s.data.status.goal).toBe("rotate [REDACTED]");+ expect(io.warnings).toEqual(["redacted 1 secret-looking value(s)"]);+ });++ it("warns about unknown epochs and repaired trees but still saves", async () => {+ await write({+ sessionId: "s1",+ epoch: "nope",+ nodes: [{ id: "a", parent: "ghost", kind: "step", title: "x" }],+ });+ expect(io.warnings[0]).toMatch(/epoch "nope" is not in project.json/);+ expect(io.warnings[1]).toMatch(/parent ghost not found/);+ expect(await loadSession(root, "s1")).toMatchObject({ ok: true, data: { epoch: "nope" } });+ });++ it("rejects invalid JSON and schema mismatches", async () => {+ await expect(write("{nope")).rejects.toThrow(/not valid JSON/);+ await expect(write({ sessionId: "../x" })).rejects.toThrow(/sessionId:/);+ await expect(write([])).rejects.toThrow(/\(root\)/);+ });++ it("reads from a file and requires an initialized project", async () => {+ const f = join(dir, "in.json");+ await writeFile(f, JSON.stringify({ sessionId: "s2" }));+ await sessionWrite({ dir: root, file: f }, io);+ expect(io.lines).toEqual(["Saved session s2 (0 nodes)"]);+ await expect(sessionWrite({ dir: dir, file: f }, io)).rejects.toThrow(/not initialized/);+ await mkdir(join(dir, ".codelineage"));+ await writeFile(join(dir, ".codelineage", "project.json"), "{}");+ await expect(sessionWrite({ dir: dir, file: f }, io)).rejects.toThrow(/schema version/);+ });++ it("reads stdin as utf8", async () => {+ expect(await readStdin(Readable.from([Buffer.from('{"a":'), "1}"]))).toBe('{"a":1}');+ });+});