@dreki-gg/pi-plan-mode 0.13.0 → 0.14.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.
@@ -1,80 +1 @@
1
- /**
2
- * Plan disk I/O — save/load plans, exec-pending markers, and manifest updates.
3
- */
4
-
5
- import { mkdir, readFile, readdir, unlink, writeFile } from 'node:fs/promises';
6
- import { readPlansJson, serializePlansJson } from './plans-json.js';
7
- import type { PlanData, ExecPendingConfig } from './types.js';
8
- import { EXEC_PENDING_FILE } from './constants.js';
9
-
10
- export async function savePlanToDisk(planDir: string, plan: PlanData): Promise<void> {
11
- await mkdir(planDir, { recursive: true });
12
- await writeFile(`${planDir}/plan.json`, JSON.stringify(plan, null, 2) + '\n', 'utf-8');
13
- }
14
-
15
- export async function loadPlanFromDisk(dir: string): Promise<PlanData | undefined> {
16
- try {
17
- const text = await readFile(`${dir}/plan.json`, 'utf-8');
18
- return JSON.parse(text) as PlanData;
19
- } catch {
20
- return undefined;
21
- }
22
- }
23
-
24
- export async function writeExecPending(dir: string, config: ExecPendingConfig): Promise<void> {
25
- await mkdir(dir, { recursive: true });
26
- await writeFile(`${dir}/${EXEC_PENDING_FILE}`, JSON.stringify(config, null, 2) + '\n', 'utf-8');
27
- }
28
-
29
- export async function readAndClearExecPending(): Promise<{ planDir: string; config: ExecPendingConfig } | undefined> {
30
- try {
31
- const entries = await readdir('.plans', { withFileTypes: true });
32
- for (const entry of entries) {
33
- if (!entry.isDirectory()) continue;
34
- const dir = `.plans/${entry.name}`;
35
- const markerPath = `${dir}/${EXEC_PENDING_FILE}`;
36
- try {
37
- const text = await readFile(markerPath, 'utf-8');
38
- const config = JSON.parse(text) as ExecPendingConfig;
39
- await unlink(markerPath);
40
- return { planDir: dir, config };
41
- } catch {
42
- // No marker in this directory
43
- }
44
- }
45
- } catch {
46
- // .plans/ doesn't exist
47
- }
48
- return undefined;
49
- }
50
-
51
- export async function saveHandoff(planDir: string, content: string): Promise<void> {
52
- await mkdir(planDir, { recursive: true });
53
- await writeFile(`${planDir}/HANDOFF.md`, content, 'utf-8');
54
- }
55
-
56
- export async function loadHandoff(planDir: string): Promise<string | undefined> {
57
- try {
58
- return await readFile(`${planDir}/HANDOFF.md`, 'utf-8');
59
- } catch {
60
- return undefined;
61
- }
62
- }
63
-
64
- export async function updatePlansManifest(
65
- planName: string,
66
- status: 'in-progress' | 'done',
67
- title?: string,
68
- ): Promise<void> {
69
- const manifest = await readPlansJson();
70
- const existing = manifest[planName];
71
- const now = new Date().toISOString();
72
- manifest[planName] = {
73
- status,
74
- title: title ?? existing?.title ?? 'Untitled plan',
75
- created: existing?.created ?? now,
76
- completed: status === 'done' ? now : null,
77
- };
78
- await mkdir('.plans', { recursive: true });
79
- await writeFile('.plans/plans.json', serializePlansJson(manifest), 'utf-8');
80
- }
1
+ export { loadHandoff, readAndClearExecPending, saveHandoff, writeExecPending } from './storage/plan-storage.js';
@@ -7,66 +7,62 @@ import { PLAN_TOOLS } from './constants.js';
7
7
 
8
8
  export function buildPlanModePrompt(): string {
9
9
  return `[PLAN MODE ACTIVE]
10
- You are in plan mode — a planning phase with strict bash restrictions.
10
+ You are in conversational plan mode — a planning dialogue with strict bash restrictions.
11
11
 
12
12
  Restrictions:
13
13
  - Available tools: ${PLAN_TOOLS.join(', ')}
14
14
  - Bash is restricted to read-only commands (ls, grep, git status, etc.)
15
+ - Do NOT make product code changes during planning.
15
16
 
16
- Your task:
17
- 1. Analyze the codebase thoroughly using the available read-only tools
18
- 2. Ask clarifying questions if needed (use the questionnaire tool)
19
- 3. Produce a detailed, concrete plan
17
+ Your job is to reach shared understanding before formalizing a plan:
18
+ 1. Understand the user's intent through dialogue. Push back on weak assumptions, name trade-offs, and ask clarifying questions when needed.
19
+ 2. Investigate the codebase with read-only tools. Use questionnaire when explicit choices are needed.
20
+ 3. Maintain .plans/<plan-name>/context.md with the write tool as the living planning context in caveman-lite style: professional, tight, no filler. Capture intent, decisions, constraints, open questions, and discarded options.
21
+ 4. Only call submit_plan after the user and agent have converged on the approach.
20
22
 
21
- When you are ready to finalize the plan, call the submit_plan tool with:
23
+ When you are ready to finalize the plan, call submit_plan with:
22
24
  - name: a short kebab-case name (e.g. "add-auth-middleware")
23
25
  - title: a human-readable plan title
24
- - handoff: a markdown document that explains:
25
- 1. **What** change is being made and **why** it matters
26
- 2. The approach and key design decisions
27
- 3. Relevant codebase context: file paths, APIs, patterns, constraints, and gotchas
28
- This document is saved as HANDOFF.md and must be clear to both human reviewers and executor agents.
29
- - steps: an array of steps, each with a short description (≤60 chars for display) and detailed implementation instructions
26
+ - handoff: a markdown document that explains what is changing, why it matters, approach, decisions, file paths, APIs, patterns, constraints, and gotchas
27
+ - tasks: an array of tasks with id (e.g. "t-001"), description (≤60 chars), details, and optional depends_on task IDs
28
+ - prototype: optional Pug markup for a creative prototype section in the generated plan.html
30
29
 
31
- Do NOT attempt to make product code changes only analyze and plan.
32
- Do NOT write files manually — use submit_plan to finalize the plan.
30
+ submit_plan is finalization, not the starting point. The generated plan.html is written but not opened automatically.
33
31
 
34
32
  When facing a significant technical decision with multiple viable approaches (architecture, API design, implementation strategy), use the technical-options skill: you generate the competing proposals yourself, then use the subagent tool to fan out voting agents for evaluation. Do not delegate the entire workflow to a subagent — you are the planner, you drive the process.`;
35
33
  }
36
34
 
37
35
  export function buildExecutionPrompt(plan: PlanData): string | undefined {
38
- const remaining = plan.steps
39
- .map((s, i) => ({ ...s, num: i + 1 }))
40
- .filter((s) => s.status === 'pending');
36
+ const remaining = plan.tasks.filter((task) => task.status === 'pending');
41
37
 
42
38
  if (remaining.length === 0) return undefined;
43
39
 
44
- const stepList = remaining
45
- .map((s) => `${s.num}. ${s.description}\n Details: ${s.details}`)
40
+ const taskList = remaining
41
+ .map((task) => `${task.id}. ${task.description}\n Details: ${task.details}`)
46
42
  .join('\n\n');
47
43
 
48
- const currentStep = remaining[0];
44
+ const currentTask = remaining[0];
49
45
 
50
46
  return `[EXECUTING PLAN — FOLLOW THE PLAN EXACTLY]
51
47
 
52
- You are executing a structured plan. Your ONLY job is to implement the plan steps below, one at a time.
48
+ You are executing a structured plan. Your ONLY job is to implement the plan tasks below, one at a time.
53
49
 
54
50
  Rules:
55
- - Work on ONE step at a time, starting with step ${currentStep.num}
56
- - After completing each step, IMMEDIATELY call update_step to mark it done with notes summarizing what you changed (files modified, key decisions)
57
- - Do NOT run diagnostics, linters, test suites, or skills unless a step explicitly asks for it
58
- - Do NOT explore the codebase beyond what the current step requires
59
- - Do NOT deviate from the plan — if something seems wrong, call update_step with status "blocked"
51
+ - Work on ONE task at a time, starting with ${currentTask.id}
52
+ - After completing each task, IMMEDIATELY call update_task to mark it done with notes summarizing what you changed (files modified, key decisions)
53
+ - Do NOT run diagnostics, linters, test suites, or skills unless a task explicitly asks for it
54
+ - Do NOT explore the codebase beyond what the current task requires
55
+ - Do NOT deviate from the plan — if something seems wrong, call update_task with status "blocked"
60
56
 
61
- ## Current step
62
- Step ${currentStep.num}: ${currentStep.description}
63
- Details: ${currentStep.details}
57
+ ## Current task
58
+ ${currentTask.id}: ${currentTask.description}
59
+ Details: ${currentTask.details}
64
60
 
65
61
  ## Handoff
66
62
  ${plan.handoff}
67
63
 
68
- ## All remaining steps
69
- ${stepList}
64
+ ## All remaining tasks
65
+ ${taskList}
70
66
 
71
- Start with step ${currentStep.num} NOW. When done, call update_step(step=${currentStep.num}, status="done", notes="<brief summary of what you did>").`;
67
+ Start with ${currentTask.id} NOW. When done, call update_task(task_id="${currentTask.id}", status="done", notes="<brief summary of what you did>").`;
72
68
  }
@@ -0,0 +1,5 @@
1
+ declare module 'pug' {
2
+ export function render(template: string, options?: Record<string, unknown>): string;
3
+ const pug: { render: typeof render };
4
+ export default pug;
5
+ }
@@ -6,13 +6,12 @@ import type { ExtensionAPI, ExtensionContext, ExtensionCommandContext } from '@e
6
6
  import type { PlanModeState } from './state.js';
7
7
  import type { PlanData } from './types.js';
8
8
  import { EXEC_THINKING, EXEC_MODEL_OPTIONS } from './constants.js';
9
- import { readPlansJson } from './plans-json.js';
10
- import { loadPlanFromDisk, writeExecPending, savePlanToDisk } from './plan-storage.js';
9
+ import { readPlansManifest } from './storage/plans-manifest.js';
10
+ import { loadHandoff, writeExecPending } from './storage/plan-storage.js';
11
+ import { readTasksJsonl, writeTasksJsonl } from './storage/task-storage.js';
11
12
  import { enterPlanMode } from './phase-transitions.js';
12
13
 
13
- export async function pickExecutionModel(
14
- ctx: ExtensionContext,
15
- ): Promise<{ provider: string; id: string } | undefined> {
14
+ export async function pickExecutionModel(ctx: ExtensionContext): Promise<{ provider: string; id: string } | undefined> {
16
15
  const labels = EXEC_MODEL_OPTIONS.map((o) => o.label);
17
16
  const choice = await ctx.ui.select('Execute with:', labels);
18
17
  if (!choice) return undefined;
@@ -39,20 +38,16 @@ export async function executeInNewSession(
39
38
  });
40
39
  }
41
40
 
42
- export async function resumePlan(
43
- state: PlanModeState,
44
- pi: ExtensionAPI,
45
- ctx: ExtensionCommandContext,
46
- ): Promise<void> {
47
- const manifest = await readPlansJson();
48
- const inProgress = Object.entries(manifest).filter(([, e]) => e.status === 'in-progress');
41
+ export async function resumePlan(state: PlanModeState, pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
42
+ const manifest = await readPlansManifest();
43
+ const inProgress = manifest.filter((entry) => entry.status === 'in-progress');
49
44
 
50
45
  if (inProgress.length === 0) {
51
- ctx.ui.notify('No in-progress plans found in .plans/plans.json', 'info');
46
+ ctx.ui.notify('No in-progress plans found in .plans/plans.jsonl', 'info');
52
47
  return;
53
48
  }
54
49
 
55
- const options = inProgress.map(([name, entry]) => `${name} — ${entry.title}`);
50
+ const options = inProgress.map((entry) => `${entry.name} — ${entry.title}`);
56
51
  options.push('Cancel');
57
52
 
58
53
  const choice = await ctx.ui.select('Resume which plan?', options);
@@ -60,32 +55,38 @@ export async function resumePlan(
60
55
 
61
56
  const planName = choice.split(' — ')[0];
62
57
  const dir = `.plans/${planName}`;
63
- const loaded = await loadPlanFromDisk(dir);
58
+ const snapshot = await readTasksJsonl(dir);
64
59
 
65
- if (!loaded) {
66
- ctx.ui.notify(`Could not load ${dir}/plan.json`, 'error');
60
+ if (!snapshot) {
61
+ ctx.ui.notify(`Could not load ${dir}/tasks.jsonl`, 'error');
67
62
  return;
68
63
  }
69
64
 
70
65
  state.planDir = dir;
71
- state.plan = loaded;
66
+ state.plan = {
67
+ title: snapshot.meta.title,
68
+ planName: snapshot.meta.plan_name,
69
+ handoff: (await loadHandoff(dir)) ?? '',
70
+ tasks: snapshot.tasks,
71
+ };
72
72
 
73
- const doneCount = state.plan.steps.filter((s) => s.status === 'done' || s.status === 'skipped').length;
74
- const pendingCount = state.plan.steps.filter((s) => s.status === 'pending').length;
75
- const blockedCount = state.plan.steps.filter((s) => s.status === 'blocked').length;
73
+ const doneCount = state.plan.tasks.filter((task) => task.status === 'done' || task.status === 'skipped').length;
74
+ const pendingCount = state.plan.tasks.filter((task) => task.status === 'pending').length;
75
+ const blockedCount = state.plan.tasks.filter((task) => task.status === 'blocked').length;
76
76
 
77
77
  if (pendingCount === 0 && blockedCount === 0) {
78
- ctx.ui.notify(`Plan "${state.plan.title}" is already complete (${doneCount}/${state.plan.steps.length} done).`, 'info');
78
+ ctx.ui.notify(`Plan "${state.plan.title}" is already complete (${doneCount}/${state.plan.tasks.length} done).`, 'info');
79
79
  state.plan = undefined;
80
80
  state.planDir = undefined;
81
81
  return;
82
82
  }
83
83
 
84
- const summary = `${doneCount}/${state.plan.steps.length} done, ${pendingCount} pending${blockedCount ? `, ${blockedCount} blocked` : ''}`;
85
- const action = await ctx.ui.select(
86
- `Resume "${state.plan.title}" (${summary}) — what next?`,
87
- ['Continue execution', 'Re-plan from scratch', 'Cancel'],
88
- );
84
+ const summary = `${doneCount}/${state.plan.tasks.length} done, ${pendingCount} pending${blockedCount ? `, ${blockedCount} blocked` : ''}`;
85
+ const action = await ctx.ui.select(`Resume "${state.plan.title}" (${summary}) — what next?`, [
86
+ 'Continue execution',
87
+ 'Re-plan from scratch',
88
+ 'Cancel',
89
+ ]);
89
90
 
90
91
  if (!action || action === 'Cancel') {
91
92
  state.plan = undefined;
@@ -98,24 +99,24 @@ export async function resumePlan(
98
99
  const planDirPath = state.planDir;
99
100
  await enterPlanMode(state, pi, ctx);
100
101
  pi.sendUserMessage(
101
- `There is an existing plan "${planTitle}" at ${planDirPath}/plan.json. Review it and create a revised plan using submit_plan. Keep the same plan name ("${planName}").`,
102
+ `There is an existing plan "${planTitle}" at ${planDirPath}/tasks.jsonl. Review it and create a revised plan using submit_plan. Keep the same plan name ("${planName}").`,
102
103
  );
103
104
  return;
104
105
  }
105
106
 
106
- // Unblock any blocked steps
107
107
  if (blockedCount > 0) {
108
- for (const step of state.plan.steps) {
109
- if (step.status === 'blocked') step.status = 'pending';
108
+ for (const task of state.plan.tasks) {
109
+ if (task.status === 'blocked') {
110
+ task.status = 'pending';
111
+ task.updated_at = new Date().toISOString();
112
+ }
110
113
  }
111
- await savePlanToDisk(dir, state.plan);
114
+ await writeTasksJsonl(dir, snapshot.meta, state.plan.tasks);
112
115
  }
113
116
 
114
- const remaining = state.plan.steps
115
- .map((s, i) => ({ ...s, num: i + 1 }))
116
- .filter((s) => s.status === 'pending');
117
- const stepList = remaining.map((s) => `${s.num}. ${s.description}`).join('\n');
118
- const kickoff = `Resuming plan: "${state.plan.title}"\n\nCompleted: ${doneCount}/${state.plan.steps.length} steps\n\nRemaining steps:\n${stepList}\n\nContinue from step ${remaining[0].num}. Call update_step after completing each step.`;
117
+ const remaining = state.plan.tasks.filter((task) => task.status === 'pending');
118
+ const taskList = remaining.map((task) => `${task.id}. ${task.description}`).join('\n');
119
+ const kickoff = `Resuming plan: "${state.plan.title}"\n\nCompleted: ${doneCount}/${state.plan.tasks.length} tasks\n\nRemaining tasks:\n${taskList}\n\nContinue from ${remaining[0]?.id}. Call update_task after completing each task.`;
119
120
 
120
121
  await executeInNewSession(ctx, dir, state.plan, kickoff);
121
122
  }
@@ -0,0 +1,53 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { open, rename, rm } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ export interface AtomicWriteOptions {
7
+ /** Test seam: file mode for the temporary file. */
8
+ mode?: number;
9
+ }
10
+
11
+ export async function writeFileAtomic(path: string, data: string | Buffer, options: AtomicWriteOptions = {}): Promise<void> {
12
+ const dir = dirname(path);
13
+ const tempPath = join(dir, `.${process.pid}.${randomUUID()}.tmp`);
14
+ let completed = false;
15
+
16
+ try {
17
+ await writeAndSync(tempPath, data, options.mode);
18
+ await rename(tempPath, path);
19
+ completed = true;
20
+ await syncDirectory(dir);
21
+ } finally {
22
+ if (!completed) {
23
+ await rm(tempPath, { force: true }).catch(() => undefined);
24
+ }
25
+ }
26
+ }
27
+
28
+ async function writeAndSync(path: string, data: string | Buffer, mode?: number): Promise<void> {
29
+ await new Promise<void>((resolve, reject) => {
30
+ const stream = createWriteStream(path, { flags: 'wx', mode });
31
+ stream.once('error', reject);
32
+ stream.once('finish', resolve);
33
+ stream.end(data);
34
+ });
35
+
36
+ const handle = await open(path, 'r+');
37
+ try {
38
+ await handle.sync();
39
+ } finally {
40
+ await handle.close();
41
+ }
42
+ }
43
+
44
+ async function syncDirectory(dir: string): Promise<void> {
45
+ // Directory fsync is best-effort: supported on Unix, not always elsewhere.
46
+ const handle = await open(dir, 'r').catch(() => undefined);
47
+ if (!handle) return;
48
+ try {
49
+ await handle.sync().catch(() => undefined);
50
+ } finally {
51
+ await handle.close().catch(() => undefined);
52
+ }
53
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Plan disk I/O — exec-pending markers and handoff documents.
3
+ */
4
+
5
+ import { mkdir, readFile, readdir, unlink, writeFile } from 'node:fs/promises';
6
+ import type { ExecPendingConfig } from '../types.js';
7
+ import { EXEC_PENDING_FILE } from '../constants.js';
8
+
9
+ export async function writeExecPending(dir: string, config: ExecPendingConfig): Promise<void> {
10
+ await mkdir(dir, { recursive: true });
11
+ await writeFile(`${dir}/${EXEC_PENDING_FILE}`, JSON.stringify(config, null, 2) + '\n', 'utf-8');
12
+ }
13
+
14
+ export async function readAndClearExecPending(): Promise<{ planDir: string; config: ExecPendingConfig } | undefined> {
15
+ try {
16
+ const entries = await readdir('.plans', { withFileTypes: true });
17
+ for (const entry of entries) {
18
+ if (!entry.isDirectory()) continue;
19
+ const dir = `.plans/${entry.name}`;
20
+ const markerPath = `${dir}/${EXEC_PENDING_FILE}`;
21
+ try {
22
+ const text = await readFile(markerPath, 'utf-8');
23
+ const config = JSON.parse(text) as ExecPendingConfig;
24
+ await unlink(markerPath);
25
+ return { planDir: dir, config };
26
+ } catch {
27
+ // No marker in this directory
28
+ }
29
+ }
30
+ } catch {
31
+ // .plans/ doesn't exist
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ export async function saveHandoff(planDir: string, content: string): Promise<void> {
37
+ await mkdir(planDir, { recursive: true });
38
+ await writeFile(`${planDir}/HANDOFF.md`, content, 'utf-8');
39
+ }
40
+
41
+ export async function loadHandoff(planDir: string): Promise<string | undefined> {
42
+ try {
43
+ return await readFile(`${planDir}/HANDOFF.md`, 'utf-8');
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
@@ -0,0 +1,57 @@
1
+ import { mkdir, readFile } from 'node:fs/promises';
2
+ import { writeFileAtomic } from './atomic-write.js';
3
+
4
+ const MANIFEST_PATH = '.plans/plans.jsonl';
5
+
6
+ export interface PlanManifestEntry {
7
+ _type: 'plan';
8
+ name: string;
9
+ status: 'in-progress' | 'done';
10
+ title: string;
11
+ created_at: string;
12
+ completed_at: string | null;
13
+ }
14
+
15
+ export async function readPlansManifest(): Promise<PlanManifestEntry[]> {
16
+ let text: string;
17
+ try { text = await readFile(MANIFEST_PATH, 'utf8'); } catch { return []; }
18
+ const entries: PlanManifestEntry[] = [];
19
+ for (const [index, raw] of text.split(/\r?\n/).entries()) {
20
+ if (!raw.trim()) continue;
21
+ let parsed: unknown;
22
+ try { parsed = JSON.parse(raw); } catch (error) { throw new Error(`Invalid plans.jsonl at line ${index + 1}: ${(error as Error).message}`); }
23
+ if (!isPlanManifestEntry(parsed)) throw new Error(`Invalid plans.jsonl record at line ${index + 1}`);
24
+ entries.push(parsed);
25
+ }
26
+ return entries;
27
+ }
28
+
29
+ export async function writePlansManifest(entries: PlanManifestEntry[]): Promise<void> {
30
+ await mkdir('.plans', { recursive: true });
31
+ const content = entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length ? '\n' : '');
32
+ await writeFileAtomic(MANIFEST_PATH, content);
33
+ }
34
+
35
+ export async function upsertPlanEntry(name: string, updates: { status: 'in-progress' | 'done'; title?: string }): Promise<void> {
36
+ const entries = await readPlansManifest();
37
+ const now = new Date().toISOString();
38
+ const index = entries.findIndex((entry) => entry.name === name);
39
+ const existing = index === -1 ? undefined : entries[index];
40
+ const entry: PlanManifestEntry = {
41
+ _type: 'plan',
42
+ name,
43
+ status: updates.status,
44
+ title: updates.title ?? existing?.title ?? 'Untitled plan',
45
+ created_at: existing?.created_at ?? now,
46
+ completed_at: updates.status === 'done' ? now : null,
47
+ };
48
+ if (index === -1) entries.push(entry);
49
+ else entries[index] = entry;
50
+ await writePlansManifest(entries);
51
+ }
52
+
53
+ function isPlanManifestEntry(value: unknown): value is PlanManifestEntry {
54
+ if (typeof value !== 'object' || value === null) return false;
55
+ const record = value as Record<string, unknown>;
56
+ return record._type === 'plan' && typeof record.name === 'string' && (record.status === 'in-progress' || record.status === 'done') && typeof record.title === 'string' && typeof record.created_at === 'string' && (record.completed_at === null || typeof record.completed_at === 'string');
57
+ }
@@ -0,0 +1,44 @@
1
+ import { mkdir, readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { isTaskMeta, isTaskRecord, type TaskMeta, type TaskRecord } from '../types.js';
4
+ import { writeFileAtomic } from './atomic-write.js';
5
+
6
+ const TASKS_FILE = 'tasks.jsonl';
7
+
8
+ export interface TasksSnapshot { meta: TaskMeta; tasks: TaskRecord[] }
9
+
10
+ export async function readTasksJsonl(planDir: string): Promise<TasksSnapshot | undefined> {
11
+ let text: string;
12
+ try { text = await readFile(join(planDir, TASKS_FILE), 'utf8'); } catch { return undefined; }
13
+ if (!text.trim()) throw new Error('tasks.jsonl is missing meta record');
14
+
15
+ let meta: TaskMeta | undefined;
16
+ const tasks: TaskRecord[] = [];
17
+ for (const [index, raw] of text.split(/\r?\n/).entries()) {
18
+ if (!raw.trim()) continue;
19
+ let parsed: unknown;
20
+ try { parsed = JSON.parse(raw); } catch (error) { throw new Error(`Invalid JSONL at line ${index + 1}: ${(error as Error).message}`); }
21
+ if (isTaskMeta(parsed)) meta = parsed;
22
+ else if (isTaskRecord(parsed)) tasks.push(parsed);
23
+ else throw new Error(`Invalid tasks.jsonl record at line ${index + 1}`);
24
+ }
25
+ if (!meta) throw new Error('tasks.jsonl is missing meta record');
26
+ return { meta, tasks };
27
+ }
28
+
29
+ export async function writeTasksJsonl(planDir: string, meta: TaskMeta, tasks: TaskRecord[]): Promise<void> {
30
+ await mkdir(planDir, { recursive: true });
31
+ const content = [meta, ...tasks].map((record) => JSON.stringify(record)).join('\n') + '\n';
32
+ await writeFileAtomic(join(planDir, TASKS_FILE), content);
33
+ }
34
+
35
+ export async function updateTask(planDir: string, taskId: string, updates: Partial<Omit<TaskRecord, '_type' | 'id' | 'created_at'>>): Promise<TaskRecord> {
36
+ const snapshot = await readTasksJsonl(planDir);
37
+ if (!snapshot) throw new Error(`No tasks.jsonl found in ${planDir}`);
38
+ const index = snapshot.tasks.findIndex((task) => task.id === taskId);
39
+ if (index === -1) throw new Error(`Task not found: ${taskId}`);
40
+ const updated: TaskRecord = { ...snapshot.tasks[index], ...updates, updated_at: new Date().toISOString() };
41
+ snapshot.tasks[index] = updated;
42
+ await writeTasksJsonl(planDir, snapshot.meta, snapshot.tasks);
43
+ return updated;
44
+ }