cairn-ai 0.1.10 → 0.2.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 (57) hide show
  1. package/.agents/workflows/cairn-doctor.md +2 -11
  2. package/.agents/workflows/cairn-install.md +1 -5
  3. package/.agents/workflows/cairn-memory.md +3 -1
  4. package/.agents/workflows/cairn-plan.md +6 -4
  5. package/.agents/workflows/cairn-review.md +3 -1
  6. package/.agents/workflows/cairn-toolcheck.md +2 -10
  7. package/.agents/workflows/cairn-uninstall.md +1 -11
  8. package/.agents/workflows/cairn-upgrade.md +1 -5
  9. package/.agents/workflows/cairn-work.md +4 -2
  10. package/.claude/agents/explorer.md +1 -1
  11. package/.claude/agents/worker.md +1 -1
  12. package/.claude/commands/cairn-doctor.md +1 -9
  13. package/.claude/commands/cairn-install.md +1 -5
  14. package/.claude/commands/cairn-memory.md +1 -1
  15. package/.claude/commands/cairn-plan.md +1 -1
  16. package/.claude/commands/cairn-review.md +1 -1
  17. package/.claude/commands/cairn-toolcheck.md +2 -5
  18. package/.claude/commands/cairn-uninstall.md +1 -9
  19. package/.claude/commands/cairn-upgrade.md +1 -5
  20. package/.claude/commands/cairn-work.md +1 -1
  21. package/.codex-plugin/plugin.json +6 -1
  22. package/README.de.md +5 -5
  23. package/README.es.md +5 -5
  24. package/README.fr.md +5 -5
  25. package/README.ja.md +5 -5
  26. package/README.ko.md +11 -8
  27. package/README.md +11 -8
  28. package/README.pt.md +5 -5
  29. package/README.zh.md +5 -5
  30. package/commands/cairn-doctor.md +2 -7
  31. package/commands/cairn-install.md +4 -7
  32. package/commands/cairn-memory.md +3 -3
  33. package/commands/cairn-plan.md +8 -7
  34. package/commands/cairn-review.md +3 -3
  35. package/commands/cairn-toolcheck.md +4 -6
  36. package/commands/cairn-uninstall.md +1 -7
  37. package/commands/cairn-upgrade.md +4 -7
  38. package/commands/cairn-work.md +10 -8
  39. package/docs/model-guidance/README.md +9 -6
  40. package/docs/model-guidance/claude.md +1 -1
  41. package/docs/model-guidance/codex.md +1 -1
  42. package/hooks/hooks.json +5 -5
  43. package/package.json +2 -2
  44. package/scripts/cairn-goal.mjs +539 -0
  45. package/scripts/cairn-lifecycle.mjs +140 -7
  46. package/scripts/cairn-paths.mjs +103 -0
  47. package/scripts/cairn-state.mjs +183 -131
  48. package/scripts/cairn-state.sh +68 -8
  49. package/scripts/cairn-toolcheck.mjs +312 -79
  50. package/scripts/cairn.mjs +54 -43
  51. package/skills/cairn-memory/SKILL.md +9 -3
  52. package/skills/cairn-plan/SKILL.md +26 -10
  53. package/skills/cairn-review/SKILL.md +5 -2
  54. package/skills/cairn-work/SKILL.md +34 -13
  55. package/templates/MEMORY.md +1 -1
  56. package/templates/PLAN.md +1 -0
  57. package/templates/work-plan.md +21 -4
@@ -0,0 +1,539 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from "node:crypto";
3
+ import { realpathSync } from "node:fs";
4
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+
8
+ export const GOAL_STATE_VERSION = 1;
9
+ export const GOAL_STATUSES = new Set(["active", "paused", "blocked", "cancelled", "completed"]);
10
+ export const TASK_STATUSES = new Set(["pending", "active", "blocked", "completed"]);
11
+
12
+ const terminalGoalStatuses = new Set(["cancelled", "completed"]);
13
+ const defaultTaskEvidence = ["moduleAcceptance", "surfaceIntegration"];
14
+ const defaultGoalEvidence = ["finalReview"];
15
+ const goalTransitions = {
16
+ active: new Set(["paused", "blocked", "cancelled", "completed"]),
17
+ paused: new Set(["active", "blocked", "cancelled"]),
18
+ blocked: new Set(["active", "paused", "cancelled"]),
19
+ cancelled: new Set(),
20
+ completed: new Set(),
21
+ };
22
+ const taskTransitions = {
23
+ pending: new Set(["active", "blocked"]),
24
+ active: new Set(["pending", "blocked", "completed"]),
25
+ blocked: new Set(["pending", "active"]),
26
+ completed: new Set(),
27
+ };
28
+
29
+ export function goalStatePath(root = process.cwd()) {
30
+ return join(resolve(root), ".cairn", "state.json");
31
+ }
32
+
33
+ export async function readGoalState({ root = process.cwd() } = {}) {
34
+ try {
35
+ const text = await readFile(goalStatePath(root), "utf8");
36
+ return validateState(JSON.parse(text));
37
+ } catch (error) {
38
+ if (error?.code === "ENOENT") return null;
39
+ if (error instanceof SyntaxError) throw new Error(`Cairn goal state is invalid JSON: ${error.message}`);
40
+ throw error;
41
+ }
42
+ }
43
+
44
+ export async function startGoal({ root = process.cwd(), goal, planId, tasks, completionCriteria = [], requiredEvidence = defaultGoalEvidence, ownerSessionId = null } = {}) {
45
+ const normalizedGoal = requiredText(goal, "goal");
46
+ const normalizedPlanId = requiredText(planId, "planId");
47
+ if (!Array.isArray(tasks) || tasks.length === 0) throw new Error("tasks must contain at least one task");
48
+
49
+ const existing = await readGoalState({ root });
50
+ if (existing && !terminalGoalStatuses.has(existing.goal.status)) {
51
+ throw new Error(`An active Cairn goal already exists (${existing.goal.id}); pause, block, cancel, or complete it first`);
52
+ }
53
+
54
+ const now = timestamp();
55
+ const goalId = `goal-${randomUUID()}`;
56
+ const normalizedTasks = tasks.map((task, index) => normalizeTask(task, index, index === 0 ? "active" : "pending"));
57
+ const state = {
58
+ schemaVersion: GOAL_STATE_VERSION,
59
+ revision: 1,
60
+ goal: {
61
+ id: goalId,
62
+ title: normalizedGoal,
63
+ planId: normalizedPlanId,
64
+ status: "active",
65
+ completionCriteria: normalizeCriteria(completionCriteria),
66
+ requiredEvidence: normalizeCriteria(requiredEvidence),
67
+ ownerSessionId: optionalText(ownerSessionId, "ownerSessionId"),
68
+ blocker: null,
69
+ createdAt: now,
70
+ updatedAt: now,
71
+ },
72
+ tasks: normalizedTasks,
73
+ receipts: [],
74
+ };
75
+ await writeGoalState({ root, state });
76
+ return state;
77
+ }
78
+
79
+ export async function writeGoalState({ root = process.cwd(), state } = {}) {
80
+ const validated = validateState(state);
81
+ const path = goalStatePath(root);
82
+ await mkdir(dirname(path), { recursive: true });
83
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
84
+ try {
85
+ await writeFile(temporaryPath, `${JSON.stringify(validated, null, 2)}\n`, "utf8");
86
+ await rename(temporaryPath, path);
87
+ } catch (error) {
88
+ await rm(temporaryPath, { force: true }).catch(() => {});
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ export async function transitionGoal({ root = process.cwd(), status, blocker } = {}) {
94
+ const nextStatus = validGoalStatus(status);
95
+ return mutateGoal(root, (state) => {
96
+ const currentStatus = state.goal.status;
97
+ if (currentStatus === nextStatus) return state;
98
+ if (!goalTransitions[currentStatus].has(nextStatus)) {
99
+ throw new Error(`Cannot transition goal from ${currentStatus} to ${nextStatus}`);
100
+ }
101
+ if (nextStatus === "completed") ensureGoalCanComplete(state);
102
+ if (nextStatus === "blocked") state.goal.blocker = requiredText(blocker, "blocker");
103
+ if (nextStatus === "active") state.goal.blocker = null;
104
+ state.goal.status = nextStatus;
105
+ state.goal.updatedAt = timestamp();
106
+ return state;
107
+ });
108
+ }
109
+
110
+ export async function setTaskStatus({ root = process.cwd(), taskId, status, blocker } = {}) {
111
+ const nextStatus = validTaskStatus(status);
112
+ const normalizedTaskId = requiredText(taskId, "taskId");
113
+ return mutateGoal(root, (state) => {
114
+ assertGoalMutable(state);
115
+ const task = taskById(state, normalizedTaskId);
116
+ if (task.status === nextStatus) return state;
117
+ if (!taskTransitions[task.status].has(nextStatus)) {
118
+ throw new Error(`Cannot transition task ${task.id} from ${task.status} to ${nextStatus}`);
119
+ }
120
+ if (nextStatus === "active") {
121
+ const anotherActive = state.tasks.find((item) => item.id !== task.id && item.status === "active");
122
+ if (anotherActive) throw new Error(`Task ${anotherActive.id} is already active`);
123
+ }
124
+ if (nextStatus === "completed") ensureTaskCanComplete(state, task);
125
+ if (nextStatus === "blocked") task.blocker = requiredText(blocker, "blocker");
126
+ if (nextStatus === "active" || nextStatus === "pending") task.blocker = null;
127
+ task.status = nextStatus;
128
+ task.updatedAt = timestamp();
129
+ if (nextStatus === "completed") activateNextPendingTask(state);
130
+ if (nextStatus === "blocked" && !activateNextPendingTask(state)) {
131
+ state.goal.status = "blocked";
132
+ state.goal.blocker = task.blocker;
133
+ }
134
+ state.goal.updatedAt = timestamp();
135
+ return state;
136
+ });
137
+ }
138
+
139
+ export async function assignTask({ root = process.cwd(), taskId, agentId = null } = {}) {
140
+ const normalizedTaskId = requiredText(taskId, "taskId");
141
+ const normalizedAgentId = agentId === null ? null : requiredText(agentId, "agentId");
142
+ return mutateGoal(root, (state) => {
143
+ assertGoalMutable(state);
144
+ const task = taskById(state, normalizedTaskId);
145
+ task.assignedAgentId = normalizedAgentId;
146
+ task.updatedAt = timestamp();
147
+ state.goal.updatedAt = timestamp();
148
+ return state;
149
+ });
150
+ }
151
+
152
+ export async function recordReceipt({ root = process.cwd(), taskId, kind, scope = "task", command, exitCode, timestamp: receiptTimestamp, goalId, planId } = {}) {
153
+ const normalizedScope = validReceiptScope(scope);
154
+ const normalizedTaskId = normalizedScope === "task" ? requiredText(taskId, "taskId") : undefined;
155
+ const normalizedKind = requiredText(kind, "receipt kind");
156
+ const normalizedCommand = validReceiptCommand(command);
157
+ if (exitCode !== 0) throw new Error("receipt exitCode must be 0");
158
+ const normalizedTimestamp = validTimestamp(receiptTimestamp ?? timestamp());
159
+ return mutateGoal(root, (state) => {
160
+ assertGoalMutable(state);
161
+ const task = normalizedScope === "task" ? taskById(state, normalizedTaskId) : null;
162
+ if (goalId !== undefined && goalId !== state.goal.id) throw new Error("receipt goalId does not match the active goal");
163
+ if (planId !== undefined && planId !== state.goal.planId) throw new Error("receipt planId does not match the active goal");
164
+ const receipt = {
165
+ id: `receipt-${randomUUID()}`,
166
+ scope: normalizedScope,
167
+ kind: normalizedKind,
168
+ ...(task ? { taskId: task.id } : {}),
169
+ goalId: state.goal.id,
170
+ planId: state.goal.planId,
171
+ command: normalizedCommand,
172
+ exitCode: 0,
173
+ timestamp: normalizedTimestamp,
174
+ };
175
+ state.receipts.push(receipt);
176
+ if (task) task.updatedAt = timestamp();
177
+ state.goal.updatedAt = timestamp();
178
+ return state;
179
+ });
180
+ }
181
+
182
+ export function currentTask(state) {
183
+ if (!state) return null;
184
+ return state.tasks.find((task) => task.status === "active")
185
+ ?? state.tasks.find((task) => task.status === "pending")
186
+ ?? state.tasks.find((task) => task.status === "blocked")
187
+ ?? null;
188
+ }
189
+
190
+ export function isGoalOwnedBySession(state, sessionId) {
191
+ return !state?.goal?.ownerSessionId || state.goal.ownerSessionId === sessionId;
192
+ }
193
+
194
+ export function evaluateStop(state, { subagent = false, agentId } = {}) {
195
+ if (!state || state.goal.status !== "active") return { block: false };
196
+ const task = currentTask(state);
197
+ if (!task) {
198
+ return {
199
+ block: true,
200
+ reason: `Cairn goal "${state.goal.title}" has no incomplete task, but is still active. Verify completion criteria and explicitly mark the goal complete.`,
201
+ };
202
+ }
203
+ if (subagent) {
204
+ if (!agentId || task.assignedAgentId !== agentId) return { block: false };
205
+ return {
206
+ block: true,
207
+ reason: `Cairn task ${task.id} (${task.title}) is assigned to this subagent and is ${task.status}. Continue only this assigned task, record a successful receipt, then hand off.`,
208
+ };
209
+ }
210
+ return {
211
+ block: true,
212
+ reason: `Cairn goal "${state.goal.title}" is active. Continue current task ${task.id} (${task.title}); its status is ${task.status}. Record a successful receipt before marking it complete.`,
213
+ };
214
+ }
215
+
216
+ export async function handleGoalCli(args = process.argv.slice(2), { stdout = console.log } = {}) {
217
+ const [firstCommand = "help", ...remaining] = args;
218
+ const [command = "help", ...rest] = firstCommand === "goal" ? remaining : [firstCommand, ...remaining];
219
+ const { options, positional } = parseArgs(rest);
220
+ const root = options.root ?? process.cwd();
221
+ if (command === "start") {
222
+ const tasks = parseTasks(options.tasks ?? positional.slice(0));
223
+ const state = await startGoal({
224
+ root,
225
+ goal: options.goal,
226
+ planId: options.plan,
227
+ tasks,
228
+ completionCriteria: splitValues(options.criteria),
229
+ requiredEvidence: options.requiredEvidence ? splitValues(options.requiredEvidence) : defaultGoalEvidence,
230
+ ownerSessionId: options.session,
231
+ });
232
+ stdout(JSON.stringify(state));
233
+ return state;
234
+ }
235
+ if (command === "status") {
236
+ const state = await readGoalState({ root });
237
+ stdout(JSON.stringify(state));
238
+ return state;
239
+ }
240
+ if (command === "task") {
241
+ const taskAction = taskStatusFromAction(positional[0]);
242
+ const state = await setTaskStatus({
243
+ root,
244
+ taskId: options.task ?? (taskAction ? positional[1] : positional[0]),
245
+ status: options.status ?? taskAction ?? positional[1],
246
+ blocker: options.reason,
247
+ });
248
+ stdout(JSON.stringify(state));
249
+ return state;
250
+ }
251
+ if (command === "assign") {
252
+ const state = await assignTask({ root, taskId: options.task ?? positional[0], agentId: options.agent ?? positional[1] ?? null });
253
+ stdout(JSON.stringify(state));
254
+ return state;
255
+ }
256
+ if (command === "receipt") {
257
+ const state = await recordReceipt({
258
+ root,
259
+ taskId: options.task ?? positional[0],
260
+ kind: options.kind,
261
+ scope: options.scope,
262
+ command: options.command,
263
+ exitCode: numberOption(options.exitCode ?? options["exit-code"] ?? options.exit),
264
+ timestamp: options.timestamp,
265
+ goalId: options.goalId,
266
+ planId: options.plan,
267
+ });
268
+ stdout(JSON.stringify(state));
269
+ return state;
270
+ }
271
+ if (["pause", "resume", "block", "cancel", "complete"].includes(command)) {
272
+ const state = await transitionGoal({
273
+ root,
274
+ status: { pause: "paused", resume: "active", block: "blocked", cancel: "cancelled", complete: "completed" }[command],
275
+ blocker: options.reason,
276
+ });
277
+ stdout(JSON.stringify(state));
278
+ return state;
279
+ }
280
+ throw new Error("Usage: cairn-goal start|status|task|assign|receipt|pause|resume|block|cancel|complete [--root PATH]");
281
+ }
282
+
283
+ async function mutateGoal(root, mutate) {
284
+ const state = await readGoalState({ root });
285
+ if (!state) throw new Error("No Cairn goal state exists; start a goal first");
286
+ const next = await mutate(structuredClone(state));
287
+ next.revision += 1;
288
+ await writeGoalState({ root, state: next });
289
+ return next;
290
+ }
291
+
292
+ function normalizeTask(task, index, defaultStatus) {
293
+ const source = typeof task === "string" ? { title: task } : task;
294
+ if (!source || typeof source !== "object") throw new Error(`tasks[${index}] must be a string or object`);
295
+ const id = source.id === undefined ? `task-${index + 1}` : requiredText(source.id, `tasks[${index}].id`);
296
+ const title = requiredText(source.title, `tasks[${index}].title`);
297
+ return {
298
+ id,
299
+ title,
300
+ status: source.status === undefined ? defaultStatus : validTaskStatus(source.status),
301
+ assignedAgentId: source.assignedAgentId === undefined || source.assignedAgentId === null ? null : requiredText(source.assignedAgentId, `tasks[${index}].assignedAgentId`),
302
+ requiredEvidence: normalizeCriteria(source.requiredEvidence ?? defaultTaskEvidence),
303
+ blocker: null,
304
+ createdAt: timestamp(),
305
+ updatedAt: timestamp(),
306
+ };
307
+ }
308
+
309
+ function validateState(value) {
310
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Cairn goal state must be an object");
311
+ if (value.schemaVersion !== GOAL_STATE_VERSION) throw new Error(`Unsupported Cairn goal state schema version: ${value.schemaVersion}`);
312
+ if (!Number.isSafeInteger(value.revision) || value.revision < 1) throw new Error("Cairn goal state revision must be a positive integer");
313
+ if (!value.goal || typeof value.goal !== "object") throw new Error("Cairn goal state is missing goal");
314
+ const goal = value.goal;
315
+ requiredText(goal.id, "goal.id");
316
+ requiredText(goal.title, "goal.title");
317
+ requiredText(goal.planId, "goal.planId");
318
+ validGoalStatus(goal.status);
319
+ validTimestamp(goal.createdAt);
320
+ validTimestamp(goal.updatedAt);
321
+ if (!Array.isArray(goal.completionCriteria)) throw new Error("goal.completionCriteria must be an array");
322
+ if (!Array.isArray(goal.requiredEvidence) || goal.requiredEvidence.length === 0) throw new Error("goal.requiredEvidence must be a non-empty array");
323
+ goal.requiredEvidence.forEach((kind, index) => requiredText(kind, `goal.requiredEvidence[${index}]`));
324
+ if (goal.ownerSessionId !== null && goal.ownerSessionId !== undefined) requiredText(goal.ownerSessionId, "goal.ownerSessionId");
325
+ if (goal.blocker !== null && goal.blocker !== undefined) requiredText(goal.blocker, "goal.blocker");
326
+ if (!Array.isArray(value.tasks) || value.tasks.length === 0) throw new Error("Cairn goal state must contain tasks");
327
+ if (!Array.isArray(value.receipts)) throw new Error("Cairn goal state receipts must be an array");
328
+ const ids = new Set();
329
+ let activeTasks = 0;
330
+ for (const task of value.tasks) {
331
+ if (!task || typeof task !== "object") throw new Error("Each task must be an object");
332
+ requiredText(task.id, "task.id");
333
+ if (ids.has(task.id)) throw new Error(`Duplicate task id: ${task.id}`);
334
+ ids.add(task.id);
335
+ requiredText(task.title, "task.title");
336
+ validTaskStatus(task.status);
337
+ if (task.status === "active") activeTasks += 1;
338
+ if (task.assignedAgentId !== null && task.assignedAgentId !== undefined) requiredText(task.assignedAgentId, "task.assignedAgentId");
339
+ if (!Array.isArray(task.requiredEvidence) || task.requiredEvidence.length === 0) throw new Error(`task ${task.id} requiredEvidence must be a non-empty array`);
340
+ task.requiredEvidence.forEach((kind, index) => requiredText(kind, `task ${task.id} requiredEvidence[${index}]`));
341
+ if (task.blocker !== null && task.blocker !== undefined) requiredText(task.blocker, `task ${task.id} blocker`);
342
+ validTimestamp(task.createdAt);
343
+ validTimestamp(task.updatedAt);
344
+ }
345
+ if (activeTasks > 1) throw new Error("Only one task may be active");
346
+ for (const receipt of value.receipts) validateReceipt(receipt, value);
347
+ return value;
348
+ }
349
+
350
+ function validateReceipt(receipt, state) {
351
+ if (!receipt || typeof receipt !== "object") throw new Error("Each receipt must be an object");
352
+ requiredText(receipt.id, "receipt.id");
353
+ const scope = validReceiptScope(receipt.scope);
354
+ requiredText(receipt.kind, "receipt.kind");
355
+ if (scope === "task") {
356
+ requiredText(receipt.taskId, "receipt.taskId");
357
+ if (!state.tasks.some((task) => task.id === receipt.taskId)) throw new Error(`Receipt references unknown task: ${receipt.taskId}`);
358
+ } else if (receipt.taskId !== undefined && receipt.taskId !== null) {
359
+ throw new Error("goal-scope receipt must not contain taskId");
360
+ }
361
+ if (receipt.goalId !== state.goal.id) throw new Error("receipt goalId does not match goal");
362
+ if (receipt.planId !== state.goal.planId) throw new Error("receipt planId does not match goal");
363
+ validReceiptCommand(receipt.command);
364
+ if (receipt.exitCode !== 0) throw new Error("receipt exitCode must be 0");
365
+ validTimestamp(receipt.timestamp);
366
+ }
367
+
368
+ function ensureTaskCanComplete(state, task) {
369
+ const missingKinds = task.requiredEvidence.filter((kind) => !state.receipts.some((item) => (
370
+ item.scope === "task" && item.kind === kind && item.taskId === task.id && validReceiptForTask(item, state, task)
371
+ )));
372
+ if (missingKinds.length > 0) throw new Error(`Task ${task.id} cannot be completed without successful, bound receipts: ${missingKinds.join(", ")}`);
373
+ }
374
+
375
+ function ensureGoalCanComplete(state) {
376
+ const incomplete = state.tasks.filter((task) => task.status !== "completed");
377
+ if (incomplete.length > 0) throw new Error(`Goal cannot be completed while tasks remain: ${incomplete.map((task) => task.id).join(", ")}`);
378
+ for (const task of state.tasks) ensureTaskCanComplete(state, task);
379
+ const missingKinds = state.goal.requiredEvidence.filter((kind) => !state.receipts.some((receipt) => (
380
+ receipt.scope === "goal" && receipt.kind === kind && validReceiptForGoal(receipt, state)
381
+ )));
382
+ if (missingKinds.length > 0) throw new Error(`Goal cannot be completed without successful, bound receipts: ${missingKinds.join(", ")}`);
383
+ }
384
+
385
+ function validReceiptForTask(receipt, state, task) {
386
+ try {
387
+ validateReceipt(receipt, state);
388
+ return receipt.taskId === task.id;
389
+ } catch {
390
+ return false;
391
+ }
392
+ }
393
+
394
+ function validReceiptForGoal(receipt, state) {
395
+ try {
396
+ validateReceipt(receipt, state);
397
+ return receipt.scope === "goal";
398
+ } catch {
399
+ return false;
400
+ }
401
+ }
402
+
403
+ function activateNextPendingTask(state) {
404
+ if (state.tasks.some((task) => task.status === "active")) return true;
405
+ const next = state.tasks.find((task) => task.status === "pending");
406
+ if (next) {
407
+ next.status = "active";
408
+ next.updatedAt = timestamp();
409
+ return true;
410
+ }
411
+ return false;
412
+ }
413
+
414
+ function assertGoalMutable(state) {
415
+ if (terminalGoalStatuses.has(state.goal.status)) throw new Error(`Cannot change a ${state.goal.status} goal`);
416
+ }
417
+
418
+ function taskById(state, taskId) {
419
+ const task = state.tasks.find((item) => item.id === taskId);
420
+ if (!task) throw new Error(`Unknown task: ${taskId}`);
421
+ return task;
422
+ }
423
+
424
+ function requiredText(value, label) {
425
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`);
426
+ return value.trim();
427
+ }
428
+
429
+ function validGoalStatus(value) {
430
+ if (!GOAL_STATUSES.has(value)) throw new Error(`Invalid goal status: ${value}`);
431
+ return value;
432
+ }
433
+
434
+ function validTaskStatus(value) {
435
+ if (!TASK_STATUSES.has(value)) throw new Error(`Invalid task status: ${value}`);
436
+ return value;
437
+ }
438
+
439
+ function taskStatusFromAction(value) {
440
+ return {
441
+ start: "active",
442
+ activate: "active",
443
+ active: "active",
444
+ complete: "completed",
445
+ completed: "completed",
446
+ block: "blocked",
447
+ blocked: "blocked",
448
+ pending: "pending",
449
+ }[value] ?? null;
450
+ }
451
+
452
+ function validReceiptScope(value) {
453
+ if (value !== "task" && value !== "goal") throw new Error(`Invalid receipt scope: ${value}`);
454
+ return value;
455
+ }
456
+
457
+ function validReceiptCommand(value) {
458
+ const command = requiredText(value, "receipt command");
459
+ if (/\b(skip(?:ped)?|todo|tbd|n\/?a|not[ -]?run|not[ -]?applicable|placeholder)\b/i.test(command)) {
460
+ throw new Error("receipt command cannot be skipped, placeholder, or incomplete evidence");
461
+ }
462
+ return command;
463
+ }
464
+
465
+ function validTimestamp(value) {
466
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) throw new Error("timestamp must be an ISO-8601 date string");
467
+ return value;
468
+ }
469
+
470
+ function normalizeCriteria(criteria) {
471
+ if (!Array.isArray(criteria)) throw new Error("completionCriteria must be an array");
472
+ return criteria.map((item, index) => requiredText(item, `completionCriteria[${index}]`));
473
+ }
474
+
475
+ function optionalText(value, label) {
476
+ return value === undefined || value === null ? null : requiredText(value, label);
477
+ }
478
+
479
+ function timestamp() {
480
+ return new Date().toISOString();
481
+ }
482
+
483
+ function parseArgs(args) {
484
+ const options = {};
485
+ const positional = [];
486
+ for (let index = 0; index < args.length; index += 1) {
487
+ const value = args[index];
488
+ if (!value.startsWith("--")) {
489
+ positional.push(value);
490
+ continue;
491
+ }
492
+ const [key, inline] = value.slice(2).split("=", 2);
493
+ options[key] = inline ?? args[++index];
494
+ }
495
+ return { options, positional };
496
+ }
497
+
498
+ function parseTasks(value) {
499
+ if (Array.isArray(value)) return value;
500
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error("Provide tasks with --tasks JSON or positional task titles");
501
+ try {
502
+ const parsed = JSON.parse(value);
503
+ if (!Array.isArray(parsed)) throw new Error("--tasks JSON must be an array");
504
+ return parsed;
505
+ } catch (error) {
506
+ if (error instanceof SyntaxError) return value.split("|").map((item) => item.trim()).filter(Boolean);
507
+ throw error;
508
+ }
509
+ }
510
+
511
+ function splitValues(value) {
512
+ if (!value) return [];
513
+ return String(value).split("|").map((item) => item.trim()).filter(Boolean);
514
+ }
515
+
516
+ function numberOption(value) {
517
+ if (value === undefined) return undefined;
518
+ const result = Number(value);
519
+ if (!Number.isInteger(result)) throw new Error("exitCode must be an integer");
520
+ return result;
521
+ }
522
+
523
+ function isCliEntry() {
524
+ if (!process.argv[1]) return false;
525
+ try {
526
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
527
+ } catch {
528
+ return import.meta.url === pathToFileURL(process.argv[1]).href;
529
+ }
530
+ }
531
+
532
+ if (isCliEntry()) {
533
+ try {
534
+ await handleGoalCli();
535
+ } catch (error) {
536
+ console.error(`Cairn goal error: ${error.message}`);
537
+ process.exitCode = 1;
538
+ }
539
+ }