-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplan-state.ts
More file actions
203 lines (173 loc) · 5.8 KB
/
plan-state.ts
File metadata and controls
203 lines (173 loc) · 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import { join } from 'path';
import { z } from 'zod';
import { getDataDir } from './paths';
import { GitMutex } from './git-mutex';
import type { PlanSpec, JobSpec, CheckpointContext } from './plan-types';
import { isValidPlanTransition, isValidJobTransition } from './plan-types';
import { PlanSpecSchema } from './schemas';
import { atomicWrite } from './utils';
const PLAN_FILE = 'plan.json';
const planMutex = new GitMutex();
async function getPlanFilePath(): Promise<string> {
const dataDir = await getDataDir();
return join(dataDir, PLAN_FILE);
}
export async function loadPlan(): Promise<PlanSpec | null> {
const filePath = await getPlanFilePath();
const file = Bun.file(filePath);
const exists = await file.exists();
if (!exists) {
return null;
}
try {
const content = await file.text();
const parsed = JSON.parse(content);
return PlanSpecSchema.parse(parsed);
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(`Invalid plan state in ${filePath}: ${error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`);
}
throw new Error(`Failed to load plan state from ${filePath}: ${error}`);
}
}
export async function savePlan(plan: PlanSpec): Promise<void> {
await planMutex.withLock(async () => {
const existing = await loadPlan();
if (existing && existing.id !== plan.id) {
throw new Error('active plan already exists');
}
if (existing && existing.status !== plan.status) {
if (!isValidPlanTransition(existing.status, plan.status)) {
console.warn(`[MC] Invalid plan transition: ${existing.status} → ${plan.status} (plan: ${plan.name})`);
}
}
const ghAuthenticated = await validateGhAuth();
const planToSave = { ...plan, ghAuthenticated };
const filePath = await getPlanFilePath();
try {
const data = JSON.stringify(planToSave, null, 2);
await atomicWrite(filePath, data);
} catch (error) {
throw new Error(`Failed to save plan state to ${filePath}: ${error}`);
}
});
}
export async function getActivePlan(): Promise<PlanSpec | null> {
return loadPlan();
}
export async function updatePlanJob(
planId: string,
jobName: string,
updates: Partial<JobSpec>,
): Promise<void> {
await planMutex.withLock(async () => {
const plan = await loadPlan();
if (!plan) {
throw new Error('No active plan exists');
}
if (plan.id !== planId) {
throw new Error(
`Plan ID mismatch: expected ${planId}, got ${plan.id}`,
);
}
const jobIndex = plan.jobs.findIndex((j) => j.name === jobName);
if (jobIndex === -1) {
throw new Error(`Job "${jobName}" not found in plan "${plan.name}"`);
}
if (updates.status && updates.status !== plan.jobs[jobIndex].status) {
if (!isValidJobTransition(plan.jobs[jobIndex].status, updates.status)) {
console.warn(`[MC] Invalid job transition: ${plan.jobs[jobIndex].status} → ${updates.status} (job: ${jobName})`);
}
}
plan.jobs[jobIndex] = {
...plan.jobs[jobIndex],
...updates,
};
const filePath = await getPlanFilePath();
try {
const data = JSON.stringify(plan, null, 2);
await atomicWrite(filePath, data);
} catch (error) {
throw new Error(`Failed to save plan state to ${filePath}: ${error}`);
}
});
}
export interface PlanFieldUpdates {
status?: PlanSpec['status'];
checkpoint?: PlanSpec['checkpoint'];
checkpointContext?: CheckpointContext | null;
completedAt?: string;
prUrl?: string;
}
/**
* Atomically update plan-level fields without overwriting job states.
*
* Unlike savePlan(), this reads the current plan inside the mutex and merges
* only the specified fields. This prevents a stale plan snapshot from clobbering
* concurrent updatePlanJob() writes — the root cause of completed jobs appearing
* as "running" after a sibling job failed (see #63).
*/
export async function updatePlanFields(
planId: string,
updates: PlanFieldUpdates,
): Promise<void> {
await planMutex.withLock(async () => {
const plan = await loadPlan();
if (!plan) {
throw new Error('No active plan exists');
}
if (plan.id !== planId) {
throw new Error(
`Plan ID mismatch: expected ${planId}, got ${plan.id}`,
);
}
if (updates.status !== undefined && updates.status !== plan.status) {
if (!isValidPlanTransition(plan.status, updates.status)) {
console.warn(`[MC] Invalid plan transition: ${plan.status} → ${updates.status} (plan: ${plan.name})`);
}
plan.status = updates.status;
}
if (updates.checkpoint !== undefined) {
plan.checkpoint = updates.checkpoint;
}
if (updates.checkpointContext !== undefined) {
plan.checkpointContext = updates.checkpointContext;
}
if (updates.completedAt !== undefined) {
plan.completedAt = updates.completedAt;
}
if (updates.prUrl !== undefined) {
plan.prUrl = updates.prUrl;
}
const ghAuthenticated = await validateGhAuth();
const planToSave = { ...plan, ghAuthenticated };
const filePath = await getPlanFilePath();
try {
const data = JSON.stringify(planToSave, null, 2);
await atomicWrite(filePath, data);
} catch (error) {
throw new Error(`Failed to save plan state to ${filePath}: ${error}`);
}
});
}
export async function clearPlan(): Promise<void> {
await planMutex.withLock(async () => {
const filePath = await getPlanFilePath();
const fs = await import('fs');
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
});
}
export async function validateGhAuth(): Promise<boolean> {
try {
const proc = Bun.spawn(['gh', 'auth', 'status'], {
stdout: 'pipe',
stderr: 'pipe',
});
const exitCode = await proc.exited;
return exitCode === 0;
} catch {
return false;
}
}