cairn-ai 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.agents/workflows/cairn-doctor.md +4 -1
  2. package/.agents/workflows/cairn-install.md +3 -1
  3. package/.agents/workflows/cairn-memory.md +2 -2
  4. package/.agents/workflows/cairn-plan.md +2 -2
  5. package/.agents/workflows/cairn-review.md +1 -1
  6. package/.agents/workflows/cairn-uninstall.md +3 -1
  7. package/.agents/workflows/cairn-upgrade.md +3 -1
  8. package/.agents/workflows/cairn-work.md +2 -2
  9. package/.claude/agents/explorer.md +1 -1
  10. package/.claude/agents/worker.md +1 -1
  11. package/.codex-plugin/plugin.json +2 -2
  12. package/README.de.md +46 -8
  13. package/README.es.md +46 -8
  14. package/README.fr.md +46 -8
  15. package/README.ja.md +46 -8
  16. package/README.ko.md +51 -15
  17. package/README.md +51 -15
  18. package/README.pt.md +46 -8
  19. package/README.zh.md +46 -8
  20. package/agents/explorer.md +1 -1
  21. package/agents/worker.md +1 -1
  22. package/commands/cairn-doctor.md +4 -1
  23. package/commands/cairn-install.md +11 -5
  24. package/commands/cairn-memory.md +2 -2
  25. package/commands/cairn-plan.md +2 -2
  26. package/commands/cairn-review.md +1 -1
  27. package/commands/cairn-uninstall.md +9 -4
  28. package/commands/cairn-upgrade.md +8 -1
  29. package/commands/cairn-work.md +2 -2
  30. package/package.json +2 -2
  31. package/scripts/cairn-auto-upgrade.mjs +334 -0
  32. package/scripts/cairn-cleanup.mjs +142 -15
  33. package/scripts/cairn-goal-cli.mjs +50 -4
  34. package/scripts/cairn-goal-history.mjs +316 -0
  35. package/scripts/cairn-goal-operations-evidence.mjs +2 -2
  36. package/scripts/cairn-goal-operations.mjs +11 -3
  37. package/scripts/cairn-goal.mjs +3 -0
  38. package/scripts/cairn-index.mjs +1052 -0
  39. package/scripts/cairn-lifecycle-claude.mjs +64 -18
  40. package/scripts/cairn-lifecycle-commands.mjs +355 -79
  41. package/scripts/cairn-lifecycle-hosts.mjs +98 -0
  42. package/scripts/cairn-lifecycle-integrity.mjs +106 -33
  43. package/scripts/cairn-lifecycle-layout.mjs +69 -0
  44. package/scripts/cairn-lifecycle-staging.mjs +45 -30
  45. package/scripts/cairn-lifecycle-transaction-journal.mjs +50 -7
  46. package/scripts/cairn-lifecycle.mjs +148 -45
  47. package/scripts/cairn-paths.mjs +12 -0
  48. package/scripts/cairn-safe-fs.mjs +7 -2
  49. package/scripts/cairn-state-context.mjs +126 -10
  50. package/scripts/cairn-state-init.mjs +11 -68
  51. package/scripts/cairn-state.mjs +63 -19
  52. package/scripts/cairn-update-state.mjs +219 -0
  53. package/scripts/cairn.mjs +68 -26
  54. package/skills/cairn-memory/SKILL.md +4 -4
  55. package/skills/cairn-plan/SKILL.md +2 -2
  56. package/skills/cairn-plan/delegation.md +2 -1
  57. package/skills/cairn-plan/planning-rules.md +10 -0
  58. package/skills/cairn-review/SKILL.md +3 -1
  59. package/skills/cairn-work/SKILL.md +1 -1
  60. package/skills/cairn-work/delegation.md +2 -1
  61. package/skills/cairn-work/verification.md +15 -1
  62. package/templates/MEMORY.md +4 -6
  63. package/templates/PLAN.md +2 -15
  64. package/templates/domain-memory.md +2 -0
  65. package/templates/work-plan.md +3 -1
@@ -1,4 +1,13 @@
1
- import { resolveRepoRoot } from "./cairn-paths.mjs";
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { memoryPromotionReminder } from "./cairn-goal-history.mjs";
4
+ import { resolvePluginRoot, resolveRepoRoot } from "./cairn-paths.mjs";
5
+
6
+ const GOAL_COMMANDS = ["start", "status", "ready", "stats", "task", "replan", "claim", "assign", "receipt", "verify", "finish", "pause", "resume", "block", "cancel", "complete"];
7
+ const GOAL_USAGE = [
8
+ `Usage: cairn goal <${GOAL_COMMANDS.join("|")}> [options] [--root PATH]`,
9
+ "Note: --criteria (completionCriteria) is advisory and is not enforced; completion is gated only by required evidence.",
10
+ ].join("\n");
2
11
 
3
12
  export async function runGoalCli(args, {
4
13
  stdout = console.log,
@@ -8,10 +17,31 @@ export async function runGoalCli(args, {
8
17
  }) {
9
18
  const [firstCommand = "help", ...remaining] = args;
10
19
  const [command = "help", ...rest] = firstCommand === "goal" ? remaining : [firstCommand, ...remaining];
20
+ // Help and version are answered before parsing options or touching state; arguments after -- are passed through.
21
+ const leading = [command, ...rest];
22
+ const separator = leading.indexOf("--");
23
+ const beforeSeparator = separator === -1 ? leading : leading.slice(0, separator);
24
+ const help = command === "help" || beforeSeparator.includes("--help");
25
+ const version = beforeSeparator.includes("--version");
26
+ if (help && version) throw new Error("--help and --version cannot be used together");
27
+ if (help) {
28
+ stdout(GOAL_USAGE);
29
+ return null;
30
+ }
31
+ if (version) {
32
+ stdout(`cairn ${JSON.parse(readFileSync(join(resolvePluginRoot(import.meta.url), "package.json"), "utf8")).version}`);
33
+ return null;
34
+ }
35
+ if (!GOAL_COMMANDS.includes(command)) throw new Error(unknownCommandMessage(command));
11
36
  const { options, positional, passthrough } = parseArgs(rest, command);
12
37
  // Without --root, resolve the repository (HARNESS_REPO_ROOT or the nearest .git ancestor), not a subdirectory cwd.
13
38
  const root = resolveRepoRoot({ explicitRoot: options.root ?? null });
14
39
  const emit = options.quiet ? () => {} : stdout;
40
+ // Terminal notices go to stderr only; stdout and the exit code stay those of the transition.
41
+ const onTerminal = (record, { historyError } = {}) => {
42
+ if (historyError) stderr(`Cairn warning: goal history was not recorded: ${firstLine(historyError)}`);
43
+ if (record?.status === "completed" && record.memoryPromotion === "missing") stderr(memoryPromotionReminder(record.planId));
44
+ };
15
45
  if (command === "start") {
16
46
  const tasks = parseTasks(options.tasks ?? positional.slice(0));
17
47
  const state = await operations.startGoal({
@@ -137,6 +167,7 @@ export async function runGoalCli(args, {
137
167
  if (command === "finish") {
138
168
  const state = await operations.finishGoal({
139
169
  root,
170
+ onTerminal,
140
171
  watchPaths: splitValues(options.watch),
141
172
  argv: passthrough,
142
173
  timeoutMs: options["timeout-ms"] === undefined
@@ -154,6 +185,12 @@ export async function runGoalCli(args, {
154
185
  return summary;
155
186
  }
156
187
  if (command === "stats") {
188
+ if (options.limit !== undefined && !options.history) throw new Error("--limit requires --history");
189
+ if (options.history) {
190
+ const history = await operations.goalHistoryStats({ root, limit: options.limit });
191
+ stdout(JSON.stringify(history));
192
+ return history;
193
+ }
157
194
  const stats = operations.goalStats(await operations.readGoalState({ root }), root);
158
195
  stdout(JSON.stringify(stats));
159
196
  return stats;
@@ -163,18 +200,23 @@ export async function runGoalCli(args, {
163
200
  root,
164
201
  status: { pause: "paused", resume: "active", block: "blocked", cancel: "cancelled", complete: "completed" }[command],
165
202
  blocker: options.reason,
203
+ onTerminal,
166
204
  });
167
205
  emit(JSON.stringify(state));
168
206
  return state;
169
207
  }
170
- throw new Error("Usage: cairn-goal start|status|ready|stats|task|replan|claim|assign|receipt|verify|finish|pause|resume|block|cancel|complete [--root PATH]");
208
+ throw new Error(unknownCommandMessage(command));
209
+ }
210
+
211
+ function unknownCommandMessage(command) {
212
+ return `unknown goal command: ${command} (run cairn goal --help)`;
171
213
  }
172
214
 
173
215
  function parseArgs(args, command) {
174
216
  const options = {};
175
217
  const positional = [];
176
218
  const passthrough = [];
177
- const booleanOptions = new Set(["quiet"]);
219
+ const booleanOptions = new Set(["quiet", "history"]);
178
220
  const allowed = allowedOptions(command);
179
221
  const seenCanonicalOptions = new Set();
180
222
  for (let index = 0; index < args.length; index += 1) {
@@ -232,7 +274,7 @@ function allowedOptions(command) {
232
274
  receipt: ["task", "kind", "scope", "command", "exitCode", "exit-code", "exit", "timestamp", "goalId", "goal-id", "plan"],
233
275
  verify: ["task", "kind", "scope", "watch", "timeout-ms"],
234
276
  finish: ["watch", "timeout-ms"],
235
- stats: [],
277
+ stats: ["history", "limit"],
236
278
  ready: [],
237
279
  pause: [],
238
280
  resume: [],
@@ -257,6 +299,10 @@ function parseTasks(value) {
257
299
  }
258
300
  }
259
301
 
302
+ function firstLine(error) {
303
+ return String(error?.message ?? error).split(/\r?\n/)[0];
304
+ }
305
+
260
306
  function splitValues(value) {
261
307
  if (!value) return [];
262
308
  return String(value).split("|").map((item) => item.trim()).filter(Boolean);
@@ -0,0 +1,316 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import { lstat, readFile, readdir, rename, rm } from "node:fs/promises";
4
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { cairnHome, goalStateDirectory, repositoryId } from "./cairn-paths.mjs";
6
+ import { assertNoSymlinkComponents, safeWriteFile } from "./cairn-safe-fs.mjs";
7
+
8
+ export const GOAL_HISTORY_SCHEMA_VERSION = 1;
9
+ export const GOAL_HISTORY_MAX_RECORDS = 200;
10
+ export const GOAL_HISTORY_LIMIT_MAX = 200;
11
+ const TITLE_MAX_LENGTH = 120;
12
+ const PLAN_FILE_MAX_BYTES = 512 * 1024;
13
+ const RECENT_MAX = 5;
14
+ const TREND_MIN_COMPLETED = 4;
15
+ const historyStatuses = new Set(["completed", "cancelled"]);
16
+ const memoryPromotionValues = ["note", "none", "missing", "unknown"];
17
+ const memoryPromotionLine = /^\s*(?:[-*]\s*)?Memory promotion\s*:\s*(.*)$/gim;
18
+
19
+ export function goalHistoryPath(root = process.cwd()) {
20
+ return join(goalStateDirectory(root), "history.jsonl");
21
+ }
22
+
23
+ export function memoryPromotionReminder(planId) {
24
+ return `Cairn memory: plan ${planId} has no "Memory promotion:" line. If this goal produced reusable repository knowledge, write it to docs/memory/<domain>.md and run cairn memory index; otherwise record "Memory promotion: none: <reason>" in the plan.`;
25
+ }
26
+
27
+ // Classifies the plan's memory promotion decision. Anything that is not a regular repository file of at most
28
+ // 512 KiB (an id such as plan-status, a symlink, a directory, a path outside root) is "unknown"; never throws.
29
+ export function memoryPromotionStatus(root, planId) {
30
+ try {
31
+ const workspaceRoot = resolve(root);
32
+ const target = resolve(workspaceRoot, String(planId));
33
+ const relation = relative(workspaceRoot, target);
34
+ if (relation === "" || relation === ".." || relation.startsWith(`..${sep}`) || isAbsolute(relation)) return "unknown";
35
+ let current = workspaceRoot;
36
+ for (const component of relation.split(sep)) {
37
+ current = join(current, component);
38
+ if (lstatSync(current).isSymbolicLink()) return "unknown";
39
+ }
40
+ const stat = lstatSync(target);
41
+ if (!stat.isFile() || stat.size > PLAN_FILE_MAX_BYTES) return "unknown";
42
+ const text = readFileSync(target, "utf8");
43
+ for (const match of text.matchAll(memoryPromotionLine)) {
44
+ const value = match[1].trim();
45
+ if (value.length === 0 || /^<.*>$/.test(value)) continue;
46
+ return /^(?:none|없음)/i.test(value) ? "none" : "note";
47
+ }
48
+ return "missing";
49
+ } catch {
50
+ return "unknown";
51
+ }
52
+ }
53
+
54
+ // Builds the schemaVersion 1 summary of a terminal goal. It carries ids and counts only, never absolute paths.
55
+ export function buildGoalHistoryRecord(state, { root = process.cwd(), recordedBy, endedAt = state.goal.updatedAt } = {}) {
56
+ const { goal, tasks, receipts } = state;
57
+ const createdMs = Date.parse(goal.createdAt);
58
+ const endedMs = Date.parse(endedAt);
59
+ const durationMs = Number.isFinite(createdMs) && Number.isFinite(endedMs) ? Math.max(0, endedMs - createdMs) : 0;
60
+ const byKind = {};
61
+ const latest = new Set();
62
+ let reruns = 0;
63
+ // Same rerun definition as goalStats: a later receipt for an already-seen scope, task, and kind.
64
+ for (const receipt of receipts) {
65
+ byKind[receipt.kind] = (byKind[receipt.kind] ?? 0) + 1;
66
+ const key = `${receipt.scope}\0${receipt.taskId ?? ""}\0${receipt.kind}`;
67
+ if (latest.has(key)) reruns += 1;
68
+ latest.add(key);
69
+ }
70
+ const models = {};
71
+ const efforts = {};
72
+ for (const task of tasks) {
73
+ if (task.model) models[task.model] = (models[task.model] ?? 0) + 1;
74
+ if (task.effort) efforts[task.effort] = (efforts[task.effort] ?? 0) + 1;
75
+ }
76
+ return {
77
+ schemaVersion: GOAL_HISTORY_SCHEMA_VERSION,
78
+ goalId: goal.id,
79
+ planId: goal.planId,
80
+ title: Array.from(goal.title).slice(0, TITLE_MAX_LENGTH).join(""),
81
+ status: goal.status,
82
+ worktreeId: goal.worktreeId ?? null,
83
+ createdAt: goal.createdAt,
84
+ endedAt,
85
+ durationMs,
86
+ revision: state.revision,
87
+ evidencePolicy: goal.evidencePolicy,
88
+ tasks: {
89
+ total: tasks.length,
90
+ completed: tasks.filter((task) => task.status === "completed").length,
91
+ heavy: tasks.filter((task) => task.route === "heavy").length,
92
+ light: tasks.filter((task) => task.route === "light").length,
93
+ delegated: tasks.filter((task) => task.assignedAgentId).length,
94
+ design: tasks.filter((task) => task.kind === "design").length,
95
+ },
96
+ receipts: {
97
+ total: receipts.length,
98
+ tool: receipts.filter((receipt) => receipt.source === "tool").length,
99
+ reruns,
100
+ byKind,
101
+ },
102
+ waivers: {
103
+ effort: tasks.filter((task) => task.effortWaiver).length,
104
+ design: tasks.filter((task) => task.designWaiver).length,
105
+ },
106
+ models,
107
+ efforts,
108
+ memoryPromotion: memoryPromotionStatus(root, goal.planId),
109
+ recordedBy,
110
+ };
111
+ }
112
+
113
+ // Records a terminal goal while the caller holds the goal state lock. History is best effort: it never throws, and
114
+ // the caller reports a returned error instead of blocking the transition.
115
+ export async function recordGoalHistoryUnlocked(root, state, options) {
116
+ let record = null;
117
+ try {
118
+ record = buildGoalHistoryRecord(state, { ...options, root });
119
+ await writeGoalHistoryRecordUnlocked(root, record);
120
+ return { record, error: null };
121
+ } catch (error) {
122
+ return { record, error };
123
+ }
124
+ }
125
+
126
+ // Keeps valid lines only, replaces a record with the same goalId, appends, and keeps the newest 200 records.
127
+ // The state lock serializes writers per worktree; temporary file + rename keeps readers on a whole file.
128
+ export async function writeGoalHistoryRecordUnlocked(root, record) {
129
+ const path = goalHistoryPath(root);
130
+ await assertNoSymlinkComponents(cairnHome(), path);
131
+ const { records } = await readHistoryFile(path);
132
+ const kept = records.filter((item) => item.goalId !== record.goalId);
133
+ kept.push(record);
134
+ const text = kept.slice(-GOAL_HISTORY_MAX_RECORDS).map((item) => JSON.stringify(item)).join("\n");
135
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
136
+ try {
137
+ await safeWriteFile(cairnHome(), temporaryPath, `${text}\n`, "utf8");
138
+ await rename(temporaryPath, path);
139
+ } catch (error) {
140
+ await rm(temporaryPath, { force: true }).catch(() => {});
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ async function readHistoryFile(path) {
146
+ let text;
147
+ try {
148
+ text = await readFile(path, "utf8");
149
+ } catch (error) {
150
+ if (error?.code === "ENOENT") return { records: [], skippedLines: 0 };
151
+ throw error;
152
+ }
153
+ const records = [];
154
+ let skippedLines = 0;
155
+ for (const line of text.split("\n")) {
156
+ if (line.trim().length === 0) continue;
157
+ let value;
158
+ try {
159
+ value = JSON.parse(line);
160
+ } catch {
161
+ value = null;
162
+ }
163
+ if (isHistoryRecord(value)) records.push(value);
164
+ else skippedLines += 1;
165
+ }
166
+ return { records, skippedLines };
167
+ }
168
+
169
+ function isHistoryRecord(value) {
170
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value)
171
+ && value.schemaVersion === GOAL_HISTORY_SCHEMA_VERSION
172
+ && typeof value.goalId === "string" && value.goalId.length > 0
173
+ && historyStatuses.has(value.status)
174
+ && typeof value.endedAt === "string" && Number.isFinite(Date.parse(value.endedAt));
175
+ }
176
+
177
+ // Reads every worktree history of this repository without taking locks or creating directories.
178
+ async function readRepositoryHistory(root) {
179
+ const worktreesDirectory = join(cairnHome(), "projects", repositoryId(root), "worktrees");
180
+ let entries;
181
+ try {
182
+ await assertNoSymlinkComponents(cairnHome(), worktreesDirectory);
183
+ entries = await readdir(worktreesDirectory, { withFileTypes: true });
184
+ } catch (error) {
185
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return { records: [], skippedLines: 0 };
186
+ throw error;
187
+ }
188
+ const byGoal = new Map();
189
+ let skippedLines = 0;
190
+ for (const entry of entries.filter((item) => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
191
+ const path = join(worktreesDirectory, entry.name, "history.jsonl");
192
+ try {
193
+ if (!(await lstat(path)).isFile()) continue;
194
+ } catch (error) {
195
+ if (error?.code === "ENOENT") continue;
196
+ throw error;
197
+ }
198
+ const file = await readHistoryFile(path);
199
+ skippedLines += file.skippedLines;
200
+ for (const record of file.records) {
201
+ const existing = byGoal.get(record.goalId);
202
+ if (!existing || Date.parse(record.endedAt) > Date.parse(existing.endedAt)) byGoal.set(record.goalId, record);
203
+ }
204
+ }
205
+ return { records: [...byGoal.values()], skippedLines };
206
+ }
207
+
208
+ export function validHistoryLimit(value) {
209
+ if (value === undefined || value === null) return null;
210
+ const text = String(value);
211
+ const result = Number(text);
212
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(result) || result < 1 || result > GOAL_HISTORY_LIMIT_MAX) {
213
+ throw new Error(`--limit must be an integer between 1 and ${GOAL_HISTORY_LIMIT_MAX}`);
214
+ }
215
+ return result;
216
+ }
217
+
218
+ // Repository-wide summary across goals. Medians, p90, rates, and trend use completed goals only; limit keeps the
219
+ // newest N records by endedAt.
220
+ export async function goalHistoryStats({ root = process.cwd(), limit } = {}) {
221
+ const normalizedLimit = validHistoryLimit(limit);
222
+ const history = await readRepositoryHistory(root);
223
+ const ordered = history.records.sort((a, b) => Date.parse(a.endedAt) - Date.parse(b.endedAt) || a.goalId.localeCompare(b.goalId));
224
+ const records = normalizedLimit === null ? ordered : ordered.slice(-normalizedLimit);
225
+ if (records.length === 0) {
226
+ return {
227
+ schemaVersion: GOAL_HISTORY_SCHEMA_VERSION,
228
+ scope: "repository",
229
+ goals: 0,
230
+ ...(history.skippedLines > 0 ? { skippedLines: history.skippedLines } : {}),
231
+ };
232
+ }
233
+ const completed = records.filter((record) => record.status === "completed");
234
+ const memoryPromotion = Object.fromEntries(memoryPromotionValues.map((value) => [value, 0]));
235
+ for (const record of records) {
236
+ const value = memoryPromotionValues.includes(record.memoryPromotion) ? record.memoryPromotion : "unknown";
237
+ memoryPromotion[value] += 1;
238
+ }
239
+ const durations = completed.map((record) => count(record.durationMs)).sort((a, b) => a - b);
240
+ const receiptTotals = completed.map((record) => count(record.receipts?.total));
241
+ return {
242
+ schemaVersion: GOAL_HISTORY_SCHEMA_VERSION,
243
+ scope: "repository",
244
+ goals: records.length,
245
+ completed: completed.length,
246
+ cancelled: records.length - completed.length,
247
+ skippedLines: history.skippedLines,
248
+ window: { from: records[0].endedAt, to: records.at(-1).endedAt },
249
+ durationMs: { median: median(durations), p90: durations.length === 0 ? 0 : durations[Math.ceil(0.9 * durations.length) - 1] },
250
+ tasks: {
251
+ total: sum(completed, (record) => record.tasks?.total),
252
+ median: median(completed.map((record) => count(record.tasks?.total))),
253
+ heavy: sum(completed, (record) => record.tasks?.heavy),
254
+ light: sum(completed, (record) => record.tasks?.light),
255
+ delegated: sum(completed, (record) => record.tasks?.delegated),
256
+ },
257
+ receipts: {
258
+ total: sum(completed, (record) => record.receipts?.total),
259
+ tool: sum(completed, (record) => record.receipts?.tool),
260
+ reruns: sum(completed, (record) => record.receipts?.reruns),
261
+ rerunRate: rerunRate(completed),
262
+ median: median(receiptTotals),
263
+ },
264
+ waivers: {
265
+ effort: sum(records, (record) => record.waivers?.effort),
266
+ design: sum(records, (record) => record.waivers?.design),
267
+ },
268
+ memoryPromotion,
269
+ trend: trend(completed),
270
+ recent: records.slice(-RECENT_MAX).reverse().map((record) => ({
271
+ goalId: record.goalId,
272
+ planId: record.planId,
273
+ status: record.status,
274
+ endedAt: record.endedAt,
275
+ durationMs: count(record.durationMs),
276
+ tasks: count(record.tasks?.total),
277
+ receipts: count(record.receipts?.total),
278
+ reruns: count(record.receipts?.reruns),
279
+ memoryPromotion: record.memoryPromotion,
280
+ })),
281
+ };
282
+ }
283
+
284
+ // Completed goals in endedAt order split in half; an odd count gives newer the extra goal.
285
+ function trend(completed) {
286
+ if (completed.length < TREND_MIN_COMPLETED) return null;
287
+ const middle = Math.floor(completed.length / 2);
288
+ const summarize = (records) => ({
289
+ goals: records.length,
290
+ durationMsMedian: median(records.map((record) => count(record.durationMs))),
291
+ receiptsMedian: median(records.map((record) => count(record.receipts?.total))),
292
+ rerunRate: rerunRate(records),
293
+ });
294
+ return { older: summarize(completed.slice(0, middle)), newer: summarize(completed.slice(middle)) };
295
+ }
296
+
297
+ function rerunRate(records) {
298
+ const total = sum(records, (record) => record.receipts?.total);
299
+ const reruns = sum(records, (record) => record.receipts?.reruns);
300
+ return Number((reruns / Math.max(1, total)).toFixed(3));
301
+ }
302
+
303
+ function median(values) {
304
+ if (values.length === 0) return 0;
305
+ const sorted = [...values].sort((a, b) => a - b);
306
+ const middle = Math.floor(sorted.length / 2);
307
+ return sorted.length % 2 === 1 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
308
+ }
309
+
310
+ function sum(records, pick) {
311
+ return records.reduce((total, record) => total + count(pick(record)), 0);
312
+ }
313
+
314
+ function count(value) {
315
+ return Number.isFinite(value) && value > 0 ? value : 0;
316
+ }
@@ -133,7 +133,7 @@ export async function verifyAndRecord({
133
133
 
134
134
  // Completes the active task, proves every goal-level evidence kind with one run, and completes the goal.
135
135
  export async function finishGoal({
136
- root = process.cwd(), argv = [], watchPaths = [], runner, timeoutMs = 600_000,
136
+ root = process.cwd(), argv = [], watchPaths = [], runner, timeoutMs = 600_000, onTerminal,
137
137
  } = {}) {
138
138
  const initialState = await readGoalState({ root });
139
139
  if (!initialState) throw new Error("No Cairn goal state exists; start a goal first");
@@ -149,7 +149,7 @@ export async function finishGoal({
149
149
  if (goalKinds.length > 0) {
150
150
  await verifyAndRecord({ root, scope: "goal", kind: goalKinds, argv, watchPaths, runner, timeoutMs });
151
151
  }
152
- return transitionGoal({ root, status: "completed" });
152
+ return transitionGoal({ root, status: "completed", onTerminal });
153
153
  }
154
154
 
155
155
  // Overhead measurement: how many verifications ran, how many were reruns, and which latest receipts are stale.
@@ -3,6 +3,7 @@ import { rm } from "node:fs/promises";
3
3
  import { cairnHome, worktreeId } from "./cairn-paths.mjs";
4
4
  import { assertNoSymlinkComponents } from "./cairn-safe-fs.mjs";
5
5
  import { goalStatePath, readGoalState, readGoalStateUnlocked, withGoalStateLock, writeGoalStateUnlocked } from "./cairn-goal-state.mjs";
6
+ import { recordGoalHistoryUnlocked } from "./cairn-goal-history.mjs";
6
7
  import {
7
8
  GOAL_STATE_VERSION, PLAN_ID_MAX_LENGTH, STRONGEST_MODEL_BY_HOST, assertRecoveryReferenceBudget, boundedRequiredText,
8
9
  assertCanBeActive, assertEffortRecord, assertModelRecord, assertTaskGraph,
@@ -44,6 +45,8 @@ export async function startGoal({ root = process.cwd(), goal, planId, tasks, com
44
45
  if (existing && !terminalGoalStatuses.has(existing.goal.status)) {
45
46
  throw new Error(`An unfinished Cairn goal already exists (${existing.goal.id}, ${existing.goal.status}); add the new work to it with goal replan (resume it first if paused or blocked), or cancel or complete it before starting another goal`);
46
47
  }
48
+ // A terminal state persisted by an older version is about to be overwritten; history failure never blocks start.
49
+ if (existing) await recordGoalHistoryUnlocked(root, existing, { recordedBy: "start", endedAt: existing.goal.updatedAt });
47
50
  const now = timestamp();
48
51
  const normalizedTasks = normalizeTaskList(tasks, []);
49
52
  assertTaskGraph(normalizedTasks);
@@ -88,20 +91,25 @@ export async function reconcileWorktreeState({ root = process.cwd() } = {}) {
88
91
  });
89
92
  }
90
93
 
91
- export async function transitionGoal({ root = process.cwd(), status, blocker } = {}) {
94
+ // onTerminal(record, { historyError }) runs after a terminal transition succeeds; a history failure never blocks it.
95
+ export async function transitionGoal({ root = process.cwd(), status, blocker, onTerminal = () => {} } = {}) {
92
96
  const nextStatus = validGoalStatus(status);
93
97
  if (terminalGoalStatuses.has(nextStatus)) {
94
- return withGoalStateLock(root, async () => {
98
+ const { next, history } = await withGoalStateLock(root, async () => {
95
99
  const state = await readGoalStateUnlocked(root);
96
100
  if (!state) throw new Error("No Cairn goal state exists; start a goal first");
97
101
  const next = applyGoalTransition(structuredClone(state), nextStatus, blocker, root);
98
102
  next.revision += 1;
99
103
  validateState(next);
104
+ // Recorded before deletion; a retry after a crash replaces the record for the same goalId.
105
+ const history = await recordGoalHistoryUnlocked(root, next, { recordedBy: "transition" });
100
106
  const path = goalStatePath(root);
101
107
  await assertNoSymlinkComponents(cairnHome(), path, { allowMissing: false });
102
108
  await rm(path);
103
- return next;
109
+ return { next, history };
104
110
  });
111
+ await onTerminal(history.record, { historyError: history.error });
112
+ return next;
105
113
  }
106
114
  return mutateGoal(root, (state) => applyGoalTransition(state, nextStatus, blocker, root));
107
115
  }
@@ -5,6 +5,7 @@ import { runGoalCli } from "./cairn-goal-cli.mjs";
5
5
  import { assignTask, claimGoal, replanGoal, setTaskStatus, startGoal, transitionGoal } from "./cairn-goal-operations.mjs";
6
6
  import { finishGoal, goalStats, recordReceipt, verifyAndRecord } from "./cairn-goal-operations-evidence.mjs";
7
7
  import { readGoalState } from "./cairn-goal-state.mjs";
8
+ import { goalHistoryStats } from "./cairn-goal-history.mjs";
8
9
  import { readyTasks } from "./cairn-goal-operations-mutations.mjs";
9
10
  import { defaultGoalEvidence } from "./cairn-goal-state-validation.mjs";
10
11
 
@@ -20,6 +21,7 @@ export {
20
21
  TASK_STATUSES,
21
22
  } from "./cairn-goal-state-validation.mjs";
22
23
  export { goalStatePath, readGoalState, writeGoalState } from "./cairn-goal-state.mjs";
24
+ export { GOAL_HISTORY_MAX_RECORDS, goalHistoryPath, goalHistoryStats, memoryPromotionStatus } from "./cairn-goal-history.mjs";
23
25
  export { assignTask, claimGoal, reconcileWorktreeState, replanGoal, setTaskStatus, startGoal, transitionGoal } from "./cairn-goal-operations.mjs";
24
26
  export { finishGoal, goalStats, recordReceipt, verifyAndRecord } from "./cairn-goal-operations-evidence.mjs";
25
27
  export { currentTask, evaluateStop, isGoalOwnedBySession } from "./cairn-goal-policy.mjs";
@@ -34,6 +36,7 @@ export async function handleGoalCli(args = process.argv.slice(2), { stdout = con
34
36
  assignTask,
35
37
  claimGoal,
36
38
  finishGoal,
39
+ goalHistoryStats,
37
40
  goalStats,
38
41
  readGoalState,
39
42
  readyTasks,