@kenkaiiii/ggcoder 7.3.1 → 7.4.1

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 (54) hide show
  1. package/dist/app-sidecar/app-settings.d.ts +0 -3
  2. package/dist/app-sidecar/app-settings.js +3 -3
  3. package/dist/app-sidecar/app-settings.js.map +1 -1
  4. package/dist/app-sidecar/autopilot-runner.d.ts +2 -1
  5. package/dist/app-sidecar/autopilot-runner.js +1 -1
  6. package/dist/app-sidecar/autopilot-runner.js.map +1 -1
  7. package/dist/app-sidecar/feature-map-watch.d.ts +2 -0
  8. package/dist/app-sidecar/feature-map-watch.js +11 -0
  9. package/dist/app-sidecar/feature-map-watch.js.map +1 -1
  10. package/dist/app-sidecar/fix-all-checkout.d.ts +45 -0
  11. package/dist/app-sidecar/fix-all-checkout.js +100 -0
  12. package/dist/app-sidecar/fix-all-checkout.js.map +1 -0
  13. package/dist/app-sidecar/fix-all-checks.d.ts +58 -0
  14. package/dist/app-sidecar/fix-all-checks.js +426 -0
  15. package/dist/app-sidecar/fix-all-checks.js.map +1 -0
  16. package/dist/app-sidecar/fix-all-git.d.ts +81 -0
  17. package/dist/app-sidecar/fix-all-git.js +271 -0
  18. package/dist/app-sidecar/fix-all-git.js.map +1 -0
  19. package/dist/app-sidecar/fix-all-journal.d.ts +56 -0
  20. package/dist/app-sidecar/fix-all-journal.js +68 -0
  21. package/dist/app-sidecar/fix-all-journal.js.map +1 -0
  22. package/dist/app-sidecar/fix-all-launch.d.ts +23 -0
  23. package/dist/app-sidecar/fix-all-launch.js +77 -0
  24. package/dist/app-sidecar/fix-all-launch.js.map +1 -0
  25. package/dist/app-sidecar/fix-all-routes.d.ts +10 -0
  26. package/dist/app-sidecar/fix-all-routes.js +100 -0
  27. package/dist/app-sidecar/fix-all-routes.js.map +1 -0
  28. package/dist/app-sidecar/fix-all-runner.d.ts +163 -0
  29. package/dist/app-sidecar/fix-all-runner.js +1012 -0
  30. package/dist/app-sidecar/fix-all-runner.js.map +1 -0
  31. package/dist/app-sidecar/prompt-routes.js +6 -0
  32. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  33. package/dist/app-sidecar/route-context.d.ts +7 -0
  34. package/dist/app-sidecar/run-control-routes.js +1 -0
  35. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  36. package/dist/app-sidecar/run-progress.d.ts +7 -0
  37. package/dist/app-sidecar/run-progress.js +56 -0
  38. package/dist/app-sidecar/run-progress.js.map +1 -0
  39. package/dist/app-sidecar/session-broadcast.d.ts +11 -0
  40. package/dist/app-sidecar/session-broadcast.js +11 -0
  41. package/dist/app-sidecar/session-broadcast.js.map +1 -0
  42. package/dist/app-sidecar/session-routes.d.ts +1 -0
  43. package/dist/app-sidecar/session-routes.js +1 -0
  44. package/dist/app-sidecar/session-routes.js.map +1 -1
  45. package/dist/app-sidecar/session-types.d.ts +3 -0
  46. package/dist/app-sidecar/session-types.js.map +1 -1
  47. package/dist/app-sidecar/shell-routes.js +6 -0
  48. package/dist/app-sidecar/shell-routes.js.map +1 -1
  49. package/dist/app-sidecar/worktrees.d.ts +2 -0
  50. package/dist/app-sidecar/worktrees.js +5 -1
  51. package/dist/app-sidecar/worktrees.js.map +1 -1
  52. package/dist/app-sidecar.js +226 -17
  53. package/dist/app-sidecar.js.map +1 -1
  54. package/package.json +6 -6
@@ -0,0 +1,1012 @@
1
+ import { collectFixFindings, FIX_PHASE, fixCommitMessage, fixGroupPrompt, fixPhaseCounts, fixRetryPrompt, fixStepCap, nextFixGroup, parseSetAside, planFixQueue, toFixAllGroup, toFixFinding, } from "@kenkaiiii/gg-engine/internal/core/feature-map-fix-plan.js";
2
+ import { checkLabel, fixChecksCover, uncheckedKinds, } from "./fix-all-checks.js";
3
+ import { FixAllGuardError } from "./fix-all-git.js";
4
+ import { fixAllJournalPath, markJournalLive, } from "./fix-all-journal.js";
5
+ // Fix all: the app, not the agent, owns the order, the checks, the commits and the rollbacks.
6
+ // A run works in a worktree of its own, driven by a background session there: Start in any session
7
+ // of the repository launches it (`deps.launch`), and that session's runner sets the folder up, runs
8
+ // the baseline checks and the loop. Each step is one group of findings in a fresh conversation; the
9
+ // queue is re-planned from a fresh map after every step. Everything outside is injected so the loop
10
+ // can be tested without a model.
11
+ const NEXT_SHOWN = 8;
12
+ /** Group failures in a row before the run pauses (a broken provider or toolchain). */
13
+ export const FAIL_STREAK_PAUSE = 3;
14
+ /** Passing fixes that left a finding flagged before it's set aside. */
15
+ const STILL_FLAGGED_TRIES = 2;
16
+ const IDLE = {
17
+ status: "idle",
18
+ step: null,
19
+ reason: null,
20
+ branch: null,
21
+ phase: null,
22
+ index: 0,
23
+ total: 0,
24
+ current: null,
25
+ done: [],
26
+ setAside: [],
27
+ needsYou: [],
28
+ next: [],
29
+ discard: [],
30
+ startedAt: null,
31
+ updatedAt: null,
32
+ preview: null,
33
+ };
34
+ const short = (sha) => sha.slice(0, 7);
35
+ const errText = (e) => (e instanceof Error ? e.message : String(e));
36
+ /** The reason while a pause takes effect; the app keys its "Pausing…" off it. */
37
+ export const PAUSING = "Pausing…";
38
+ const PAUSED_MID_FIX = "Paused. The unfinished fix was undone; it runs again when you resume.";
39
+ /** How long a fix's background agents may keep working before its checks run without them. */
40
+ export const FIX_ALL_SETTLE_MS = 10 * 60_000;
41
+ /** A typed prompt or `!` command while a run works the checkout: it would land in the fixes. */
42
+ export const FIX_ALL_HOLDS_CHAT = "Fix all is working in this folder, so a message or command now would get mixed into its fixes. Pause it first.";
43
+ /**
44
+ * Why a typed message or `!` command in a session on `dir` is held, or null: only while the
45
+ * repository's run is working, and only on the run's own folder (the project's folder and other
46
+ * worktrees stay free).
47
+ */
48
+ export async function fixAllHoldsAt(checkout, dir) {
49
+ const key = await checkout.keyOf(dir);
50
+ const run = key ? checkout.live(key) : null;
51
+ if (!run?.working())
52
+ return null;
53
+ const root = await checkout.rootOf(dir);
54
+ return root && root === run.folder() ? FIX_ALL_HOLDS_CHAT : null;
55
+ }
56
+ /** Fixes are checked scoped to what they touched; the full checks run after this many. */
57
+ export const FULL_CHECKS_EVERY = 10;
58
+ /** What each step is doing, until a finer part (a check command) says more. */
59
+ const STEP_ACTIVITY = {
60
+ fixing: "the agent is fixing it",
61
+ checking: "running your checks",
62
+ retrying: "the agent is fixing a failed check",
63
+ committing: "committing the fix",
64
+ "rolling-back": "undoing the unfinished fix",
65
+ picking: "re-reading the map",
66
+ };
67
+ export function createFixAllRunner(deps) {
68
+ const now = deps.now ?? (() => new Date());
69
+ let j = null;
70
+ let file = null;
71
+ let interrupted = false;
72
+ /** The repository's key, once known: where the run's state goes out to. */
73
+ let runKey = null;
74
+ const emit = (state) => deps.broadcast(state, runKey);
75
+ /** The run belongs to another session's runner. */
76
+ let foreign = false;
77
+ let loop = null;
78
+ let starting = false;
79
+ /** This runner took the repository's run; it keeps it until the run ends or is dismissed. */
80
+ let owner = false;
81
+ /** The run's folder while setting up, before the journal exists. */
82
+ let setupRoot = null;
83
+ /** Where this runner's run started, once its folder passed the first preflight. */
84
+ let runStart = null;
85
+ /** Setup and baseline checks before the journal exists: shown as running. */
86
+ let baseline = null;
87
+ let pauseRequested = false;
88
+ let stopRequested = false;
89
+ let checksAbort = new AbortController();
90
+ let commands = [];
91
+ /** Only findings the run's checks reach are fixed unattended. */
92
+ const checkedBy = (checks) => (f) => fixChecksCover(checks, f.files);
93
+ /** The last group committed: the next fresh map says whether it's really gone. */
94
+ let lastCommitted = null;
95
+ /**
96
+ * The journal is the truth whenever this runner isn't the one working: another session on the
97
+ * checkout may have paused, resumed or stopped the run since. A finished run's summary lives only
98
+ * in the runner that ran it (its journal is gone); a stopped one leaves nothing.
99
+ */
100
+ async function ensureLoaded() {
101
+ if (loop || starting)
102
+ return;
103
+ if (!file) {
104
+ const key = await deps.git.repoKey(deps.cwd).catch(() => null);
105
+ if (!key)
106
+ return;
107
+ runKey = key;
108
+ file = fixAllJournalPath(deps.stateDir, key);
109
+ }
110
+ await journalWrites;
111
+ const got = await deps.journal.load(file);
112
+ const status = got?.journal.status;
113
+ if (!got || status === "stopped" || status === "done") {
114
+ if (got)
115
+ await removeJournal(file);
116
+ if (j && j.status !== "done") {
117
+ j = null;
118
+ interrupted = false;
119
+ foreign = false;
120
+ }
121
+ return;
122
+ }
123
+ j = { ...got.journal };
124
+ interrupted = got.interrupted;
125
+ foreign = j.status === "running" && !got.interrupted;
126
+ }
127
+ /** The part in hand while running; shown only while the run is running. */
128
+ let activity = null;
129
+ const doing = (label, broadcast = true) => {
130
+ activity = { label, since: now().toISOString() };
131
+ if (broadcast)
132
+ emit(toState());
133
+ };
134
+ /** Each check command as it starts: "check 2 of 3 · pnpm test". */
135
+ const onCheck = (count) => (index, command) => doing(`check ${index + 1} of ${count} · ${checkLabel(command)}`);
136
+ /** Only the runner driving the run knows its conversation. */
137
+ const watch = () => (owner ? (deps.sessionPath?.() ?? null) : null);
138
+ /** The run's folder when it holds no fix (its branch never moved past where it started). */
139
+ const emptyRun = () => j
140
+ ? j.commits.length === 0
141
+ ? { root: j.root, branch: j.branch, head: j.base }
142
+ : null
143
+ : runStart;
144
+ /** Let the repository's run go: it ended, was dismissed, or never started. */
145
+ function disown(empty) {
146
+ if (owner && runKey)
147
+ deps.onLive?.(runKey, false);
148
+ owner = false;
149
+ runStart = null;
150
+ // Nothing to review on its branch: its worktree and branch go too, so they don't pile up.
151
+ if (empty)
152
+ deps.discardFolder?.(empty);
153
+ }
154
+ function toState(preview = null) {
155
+ if (baseline && !j) {
156
+ return {
157
+ ...IDLE,
158
+ status: baseline.failed ? "stopped" : "running",
159
+ step: baseline.failed ? null : "checking",
160
+ activity: baseline.failed ? null : activity,
161
+ reason: baseline.reason,
162
+ worktree: setupRoot,
163
+ sessionPath: watch(),
164
+ startedAt: baseline.startedAt,
165
+ updatedAt: now().toISOString(),
166
+ };
167
+ }
168
+ if (!j)
169
+ return { ...IDLE, preview };
170
+ const status = interrupted ? "interrupted" : j.status;
171
+ const finished = j.done.length + j.setAside.length;
172
+ const total = finished + (j.current ? 1 : 0) + j.queued;
173
+ return {
174
+ status,
175
+ step: status === "running" ? j.step : null,
176
+ activity: status === "running" ? activity : null,
177
+ reason: pauseRequested && status === "running" ? PAUSING : j.reason,
178
+ branch: j.branch,
179
+ worktree: j.root,
180
+ sessionPath: watch(),
181
+ phase: j.current?.phase ?? j.next[0]?.phase ?? null,
182
+ index: j.current ? finished + 1 : finished,
183
+ total,
184
+ current: j.current,
185
+ done: j.done,
186
+ setAside: j.setAside,
187
+ needsYou: j.needsYou,
188
+ next: j.next,
189
+ discard: j.discard,
190
+ startedAt: j.startedAt,
191
+ updatedAt: j.updatedAt,
192
+ preview: null,
193
+ unchecked: j.unchecked ?? null,
194
+ };
195
+ }
196
+ // One journal write at a time, in call order: a slow save (Windows renames retry) must never
197
+ // land after a later save or the removal, leaving a finished run's file saying "running".
198
+ let journalWrites = Promise.resolve();
199
+ const queueJournal = (write) => (journalWrites = journalWrites.then(write));
200
+ const removeJournal = (at) => queueJournal(() => deps.journal.remove(at).catch(() => { }));
201
+ async function persist() {
202
+ if (j && file) {
203
+ j.updatedAt = now().toISOString();
204
+ const at = file;
205
+ const snapshot = structuredClone(j);
206
+ await queueJournal(async () => {
207
+ try {
208
+ await deps.journal.save(at, snapshot);
209
+ }
210
+ catch (error) {
211
+ deps.log("WARN", "fix-all: could not save the journal", { error: errText(error) });
212
+ }
213
+ });
214
+ }
215
+ emit(toState());
216
+ }
217
+ async function setStep(step) {
218
+ if (!j)
219
+ return;
220
+ j.step = step;
221
+ doing(STEP_ACTIVITY[step], false);
222
+ await persist();
223
+ }
224
+ async function preview() {
225
+ const snap = await deps.map.snapshot();
226
+ const root = await deps.git.root(deps.cwd).catch(() => null);
227
+ const checks = root ? await deps.checks.resolve(root).catch(() => null) : null;
228
+ const plan = planFixQueue(snap, new Set(), checks ? checkedBy(checks) : undefined);
229
+ return {
230
+ fixable: plan.groups.reduce((n, g) => n + g.findings.length, 0),
231
+ phases: fixPhaseCounts(plan),
232
+ needsYou: plan.needsYou,
233
+ branch: await deps.git.proposeBranch(deps.cwd, now()),
234
+ unchecked: checks ? uncheckedNote(checks, snap, []) : null,
235
+ };
236
+ }
237
+ /** Checks the run won't run, and the fixes no check reaches, in a sentence (null: neither). */
238
+ function uncheckedNote(checks, snap, dropped) {
239
+ const parts = [];
240
+ if (dropped.length > 0) {
241
+ parts.push(`${dropped.map((d) => `\`${d}\``).join(", ")} already ${dropped.length === 1 ? "fails" : "fail"} before any fix, so ${dropped.length === 1 ? "it isn't" : "they aren't"} run.`);
242
+ }
243
+ const left = collectFixFindings(snap).filter((c) => FIX_PHASE[c.kind] !== "needs-you" && !fixChecksCover(checks, c.files));
244
+ if (left.length > 0) {
245
+ const kinds = uncheckedKinds(checks, left.flatMap((c) => c.files));
246
+ const where = kinds && kinds !== "other" ? `${kinds} code` : "files";
247
+ parts.push(`${left.length} ${left.length === 1 ? "fix is" : "fixes are"} in ${where} no check runs on, so ${left.length === 1 ? "it's" : "they're"} left for you.`);
248
+ }
249
+ return parts.length > 0 ? parts.join(" ") : null;
250
+ }
251
+ // ── start ──────────────────────────────────────────────────
252
+ /** Guards here, then the run goes to a background session in a new worktree of its own. */
253
+ async function start() {
254
+ if (starting || loop)
255
+ throw new FixAllGuardError("A Fix all run is already in progress.");
256
+ starting = true;
257
+ try {
258
+ await ensureLoaded();
259
+ if (j && (j.status === "running" || j.status === "paused" || j.status === "gate")) {
260
+ throw new FixAllGuardError(interrupted
261
+ ? "A Fix all run was interrupted. Resume or stop it first."
262
+ : "A Fix all run is already in progress.");
263
+ }
264
+ const busy = deps.busyReason();
265
+ if (busy)
266
+ throw new FixAllGuardError(busy);
267
+ // The cached map only re-checks after agent work; commits made elsewhere since must count.
268
+ const snap = await deps.map.refresh();
269
+ if (snap.state !== "ready")
270
+ throw new FixAllGuardError("The map isn't ready yet.");
271
+ if (planFixQueue(snap).groups.length === 0) {
272
+ throw new FixAllGuardError("Nothing on the map can be fixed unattended.");
273
+ }
274
+ const root = await deps.git.root(deps.cwd);
275
+ if (!root)
276
+ throw new FixAllGuardError("This folder isn't a Git repository.");
277
+ const key = (await deps.git.repoKey(root)) ?? root;
278
+ const checks = await deps.checks.resolve(root);
279
+ const plan = planFixQueue(snap, new Set(), checkedBy(checks));
280
+ if (plan.groups.length === 0) {
281
+ throw new FixAllGuardError("Nothing on the map can be fixed unattended: no check runs on the code its findings are in.");
282
+ }
283
+ // A finished run's record makes way for the new one.
284
+ j = null;
285
+ interrupted = false;
286
+ foreign = false;
287
+ baseline = null;
288
+ runKey = key;
289
+ file = fixAllJournalPath(deps.stateDir, key);
290
+ const startCount = plan.groups.reduce((n, g) => n + g.findings.length, 0);
291
+ const runner = await deps.launch({ kind: "start", from: root, key, startCount });
292
+ return await runner.state();
293
+ }
294
+ finally {
295
+ starting = false;
296
+ }
297
+ }
298
+ async function beginInWorktree(opts) {
299
+ if (starting || loop)
300
+ throw new FixAllGuardError("A Fix all run is already in progress.");
301
+ starting = true;
302
+ try {
303
+ const key = await deps.git.repoKey(deps.cwd);
304
+ if (!key)
305
+ throw new FixAllGuardError("This folder isn't a Git repository.");
306
+ runKey = key;
307
+ file = fixAllJournalPath(deps.stateDir, key);
308
+ if (!deps.claim())
309
+ throw new FixAllGuardError("The agent is busy. Try again when it's done.");
310
+ j = null;
311
+ interrupted = false;
312
+ foreign = false;
313
+ setupRoot = (await deps.git.root(deps.cwd).catch(() => null)) ?? deps.cwd;
314
+ runStart = null;
315
+ pauseRequested = false;
316
+ stopRequested = false;
317
+ checksAbort = new AbortController();
318
+ baseline = { startedAt: now().toISOString(), reason: null, failed: false };
319
+ owner = true;
320
+ deps.onLive?.(key, true);
321
+ loop = setUpThenLoop(opts).finally(async () => {
322
+ loop = null;
323
+ await clearIfStopped();
324
+ });
325
+ emit(toState());
326
+ return toState();
327
+ }
328
+ finally {
329
+ starting = false;
330
+ }
331
+ }
332
+ async function setUpThenLoop(opts) {
333
+ let claimed = true;
334
+ // Stopped before any fix (the dialog's Cancel): nothing happened, so back to idle.
335
+ const cancelled = () => {
336
+ baseline = null;
337
+ emit(toState());
338
+ disown(emptyRun());
339
+ };
340
+ const giveUp = (reason) => {
341
+ baseline = { ...(baseline ?? { startedAt: now().toISOString() }), reason, failed: true };
342
+ emit(toState());
343
+ };
344
+ const tail = (text) => text.split("\n").slice(-12).join("\n");
345
+ try {
346
+ let pre;
347
+ try {
348
+ pre = await deps.git.preflight(deps.cwd, { branch: opts.branch });
349
+ }
350
+ catch (error) {
351
+ return giveUp(errText(error));
352
+ }
353
+ setupRoot = pre.root;
354
+ runStart = { root: pre.root, branch: opts.branch, head: pre.head };
355
+ doing(STEP_ACTIVITY.picking);
356
+ const snap = await deps.map.refresh();
357
+ if (stopRequested)
358
+ return cancelled();
359
+ if (snap.state !== "ready") {
360
+ return giveUp("The map isn't ready in the run's folder, so nothing started.");
361
+ }
362
+ commands = await deps.checks.resolve(pre.root);
363
+ // A fresh folder has nothing installed: its setup runs first, like a check.
364
+ const unready = new Set();
365
+ for (const step of await deps.checks.setup(pre.root, commands)) {
366
+ doing(`setting up · ${checkLabel(step)}`);
367
+ const r = await deps.checks.run(pre.root, [step], checksAbort.signal);
368
+ if (stopRequested || (!r.ok && r.aborted))
369
+ return cancelled();
370
+ if (r.ok)
371
+ continue;
372
+ if (!step.dir) {
373
+ return giveUp(`Setting up the run's folder failed (\`${r.command}\`), so no check could run there. Fix that first.\n\n${tail(r.tail)}`);
374
+ }
375
+ unready.add(step.dir);
376
+ }
377
+ doing("running your checks");
378
+ const all = commands.length;
379
+ const r = await deps.checks.run(pre.root, commands.filter((c) => !c.dir), checksAbort.signal, onCheck(all));
380
+ if (stopRequested || (!r.ok && r.aborted))
381
+ return cancelled();
382
+ if (!r.ok) {
383
+ return giveUp(`The project's checks fail before any fix (\`${r.command}\`), so every fix would be rolled back. Fix that first.\n\n${tail(r.tail)}`);
384
+ }
385
+ // A subproject's check that already fails (or whose setup failed) is left out: what it
386
+ // alone covered is left for you.
387
+ const dropped = [];
388
+ const nested = commands.filter((c) => c.dir);
389
+ for (const [i, check] of nested.entries()) {
390
+ if (check.dir && unready.has(check.dir)) {
391
+ dropped.push(check);
392
+ continue;
393
+ }
394
+ const offset = all - nested.length + i;
395
+ const n = await deps.checks.run(pre.root, [check], checksAbort.signal, (_, c) => doing(`check ${offset + 1} of ${all} · ${checkLabel(c)}`));
396
+ if (stopRequested || (!n.ok && n.aborted))
397
+ return cancelled();
398
+ if (!n.ok)
399
+ dropped.push(check);
400
+ }
401
+ if (dropped.length > 0) {
402
+ commands = commands.filter((c) => !dropped.includes(c));
403
+ deps.log("INFO", "fix-all: left out checks that fail before any fix", {
404
+ checks: dropped.map(checkLabel).join(", "),
405
+ });
406
+ if (planFixQueue(snap, new Set(), checkedBy(commands)).groups.length === 0) {
407
+ return giveUp(`The checks for every fix fail before any fix (${dropped.map((c) => `\`${checkLabel(c)}\``).join(", ")}), so nothing could be checked. Fix those first.`);
408
+ }
409
+ }
410
+ const unchecked = uncheckedNote(commands, snap, dropped.map(checkLabel));
411
+ // Setup and checks must have left the folder clean and on the run's branch.
412
+ let ready;
413
+ try {
414
+ ready = await deps.git.preflight(deps.cwd, { branch: opts.branch });
415
+ }
416
+ catch (error) {
417
+ return giveUp(errText(error));
418
+ }
419
+ const at = now().toISOString();
420
+ j = {
421
+ version: 1,
422
+ status: "running",
423
+ step: "picking",
424
+ reason: null,
425
+ root: ready.root,
426
+ branch: opts.branch,
427
+ // The run's own start: a map commit carried over from the folder stays.
428
+ base: ready.head,
429
+ checkpoint: ready.head,
430
+ commits: [],
431
+ startCount: opts.startCount,
432
+ steps: 0,
433
+ failStreak: 0,
434
+ restructureConfirmed: false,
435
+ settled: [],
436
+ retried: {},
437
+ current: null,
438
+ done: [],
439
+ setAside: [],
440
+ needsYou: [],
441
+ next: [],
442
+ queued: 0,
443
+ discard: [],
444
+ checks: commands,
445
+ unchecked,
446
+ startedAt: baseline?.startedAt ?? at,
447
+ updatedAt: at,
448
+ };
449
+ baseline = null;
450
+ if (file)
451
+ markJournalLive(file, true);
452
+ await persist();
453
+ claimed = false;
454
+ await drive(true);
455
+ }
456
+ catch (error) {
457
+ deps.log("WARN", "fix-all: start failed", { error: errText(error) });
458
+ if (!j)
459
+ giveUp(`Couldn't start: ${errText(error)}`);
460
+ }
461
+ finally {
462
+ if (claimed)
463
+ deps.release();
464
+ }
465
+ }
466
+ // ── the loop ───────────────────────────────────────────────
467
+ /** Runs steps until done, paused, gated or stopped. Holds the run claim throughout. */
468
+ async function drive(alreadyClaimed) {
469
+ if (!j || !file)
470
+ return;
471
+ if (!alreadyClaimed && !deps.claim()) {
472
+ await pauseWith("The agent is busy. Resume when it's done.");
473
+ return;
474
+ }
475
+ markJournalLive(file, true);
476
+ try {
477
+ await steps();
478
+ }
479
+ catch (error) {
480
+ deps.log("WARN", "fix-all: run failed", { error: errText(error) });
481
+ if (j && j.status === "running")
482
+ await pauseWith(`Paused: ${errText(error)}`);
483
+ }
484
+ finally {
485
+ deps.release();
486
+ if (file && j?.status !== "running")
487
+ markJournalLive(file, false);
488
+ }
489
+ }
490
+ async function steps() {
491
+ for (;;) {
492
+ if (!j)
493
+ return;
494
+ if (stopRequested)
495
+ return finish("stopped", "Stopped.");
496
+ if (pauseRequested) {
497
+ pauseRequested = false;
498
+ return pauseWith("Paused.");
499
+ }
500
+ await setStep("picking");
501
+ const snap = await deps.map.refresh();
502
+ const settled = new Set(j.settled);
503
+ noteStillFlagged(snap, settled);
504
+ const plan = planFixQueue(snap, settled, checkedBy(commands));
505
+ j.needsYou = plan.needsYou.map(toFixFinding);
506
+ j.next = plan.groups.slice(0, NEXT_SHOWN).map(toFixAllGroup);
507
+ j.queued = plan.groups.length;
508
+ if (j.steps >= fixStepCap(j.startCount)) {
509
+ if (!(await fullChecks(true)))
510
+ return;
511
+ return finish("done", "Reached the step limit for this run.");
512
+ }
513
+ const next = nextFixGroup(snap, settled, j.restructureConfirmed, checkedBy(commands));
514
+ if (next.kind === "done") {
515
+ if (!(await fullChecks(true)))
516
+ return;
517
+ return finish("done", null);
518
+ }
519
+ if (next.kind === "gate") {
520
+ if (!(await fullChecks(true)))
521
+ return;
522
+ j.status = "gate";
523
+ j.step = null;
524
+ j.reason =
525
+ "Restructuring is next: bigger changes (splitting files, simplifying functions). Continue when you're ready.";
526
+ return persist();
527
+ }
528
+ // Guards before touching anything: still our branch, still our checkout.
529
+ const guard = await stepGuard();
530
+ if (guard)
531
+ return pauseWith(guard);
532
+ if (stopRequested)
533
+ return finish("stopped", "Stopped.");
534
+ if (pauseRequested)
535
+ return pauseWith("Paused.");
536
+ j.next = plan.groups.slice(1, NEXT_SHOWN + 1).map(toFixAllGroup);
537
+ j.queued = plan.groups.length - 1;
538
+ j.steps++;
539
+ const outcome = await runStep(next.group);
540
+ if (outcome === "halt")
541
+ return;
542
+ if (!(await fullChecks(false)))
543
+ return;
544
+ if (j.failStreak >= FAIL_STREAK_PAUSE) {
545
+ return pauseWith("Several fixes failed in a row, so the run paused. Check the provider and the project's checks, then resume.");
546
+ }
547
+ }
548
+ }
549
+ function noteStillFlagged(snap, settled) {
550
+ const group = lastCommitted;
551
+ lastCommitted = null;
552
+ if (!group || !j)
553
+ return;
554
+ const flagged = new Set(collectFixFindings(snap).map((c) => c.actionId));
555
+ for (const f of group.findings) {
556
+ if (!flagged.has(f.actionId))
557
+ continue;
558
+ const tries = (j.retried[f.actionId] ?? 0) + 1;
559
+ j.retried = { ...j.retried, [f.actionId]: tries };
560
+ if (tries >= STILL_FLAGGED_TRIES) {
561
+ settled.add(f.actionId);
562
+ j.settled = [...j.settled, f.actionId];
563
+ j.setAside = [
564
+ ...j.setAside,
565
+ {
566
+ group: {
567
+ id: f.actionId,
568
+ phase: group.phase,
569
+ title: f.label,
570
+ findings: [toFixFinding(f)],
571
+ },
572
+ reason: "The map still flags it after two passing fixes.",
573
+ },
574
+ ];
575
+ }
576
+ }
577
+ }
578
+ async function stepGuard() {
579
+ if (!j)
580
+ return null;
581
+ const branch = await deps.git.currentBranch(j.root);
582
+ if (branch !== j.branch) {
583
+ return `The checkout is on ${branch ?? "a detached HEAD"}, not the run's branch ${j.branch}. Switch back to resume; nothing was reset.`;
584
+ }
585
+ const others = await deps.othersOnCheckout(j.root);
586
+ if (others.busy) {
587
+ return "Another session started working in this checkout. Resume when it's done; nothing was reset.";
588
+ }
589
+ return null;
590
+ }
591
+ /**
592
+ * The full checks, when fixes were committed on scoped ones since they last passed: every
593
+ * FULL_CHECKS_EVERY fixes, or always with `force` (before the run ends or waits). False when the
594
+ * run paused or stopped instead; a failure pauses it with the output.
595
+ */
596
+ async function fullChecks(force) {
597
+ if (!j)
598
+ return false;
599
+ const since = j.done.length - (j.fullAt ?? 0);
600
+ if (since <= 0 || (!force && since < FULL_CHECKS_EVERY))
601
+ return true;
602
+ await setStep("checking");
603
+ doing(`full checks after ${since} ${since === 1 ? "fix" : "fixes"}`);
604
+ const r = await deps.checks.run(j.root, commands, checksAbort.signal, (i, c) => doing(`full check ${i + 1} of ${commands.length} · ${checkLabel(c)}`));
605
+ if (stopRequested) {
606
+ await finish("stopped", "Stopped.");
607
+ return false;
608
+ }
609
+ if (pauseRequested) {
610
+ await pauseWith("Paused.");
611
+ return false;
612
+ }
613
+ if (!r.ok) {
614
+ await pauseWith(`The full checks fail after the last ${since} ${since === 1 ? "fix" : "fixes"} (\`${r.command}\`). Each passed the checks for what it touched, so look over the branch's latest commits, fix it, then resume.\n\n${r.tail.split("\n").slice(-12).join("\n")}`);
615
+ return false;
616
+ }
617
+ j.fullAt = j.done.length;
618
+ await persist();
619
+ return true;
620
+ }
621
+ async function runStep(group) {
622
+ if (!j)
623
+ return "halt";
624
+ j.current = toFixAllGroup(group);
625
+ j.discard = [];
626
+ j.step = "fixing";
627
+ doing(STEP_ACTIVITY.fixing, false);
628
+ await persist();
629
+ const index = j.done.length + j.setAside.length + 1;
630
+ const total = index + j.queued;
631
+ await deps.session.begin(`Fix ${index} of ${total} · ${group.title}`);
632
+ // A fresh conversation: Open follows it.
633
+ emit(toState());
634
+ for (const f of group.findings)
635
+ await deps.map.act(f.featureId, f.actionId);
636
+ if (stopRequested || pauseRequested)
637
+ return halt();
638
+ let result = await deps.session.prompt(fixGroupPrompt(group), group.title);
639
+ for (let attempt = 1;; attempt++) {
640
+ if (stopRequested || pauseRequested)
641
+ return halt();
642
+ if (result.planSubmitted) {
643
+ return rollbackAnd(() => setAside(group, "It wanted to write a plan first, so it needs you."));
644
+ }
645
+ if (result.error) {
646
+ j.failStreak++;
647
+ return rollbackAnd(async () => {
648
+ j.reason = `The last fix stopped with an error: ${result.error}`;
649
+ });
650
+ }
651
+ const aside = parseSetAside(result.reply);
652
+ if (aside)
653
+ return rollbackAnd(() => setAside(group, aside));
654
+ // Background agents the fix started may still be editing: the checks wait for them.
655
+ const settled = await deps.session.settle(checksAbort.signal, (n) => doing(`waiting for ${n} background ${n === 1 ? "agent" : "agents"}`));
656
+ if (stopRequested || pauseRequested)
657
+ return halt();
658
+ if (!settled) {
659
+ j.failStreak++;
660
+ return rollbackAnd(() => setAside(group, "Its background agents were still working after the time limit."));
661
+ }
662
+ await setStep("checking");
663
+ let failure;
664
+ // Only what the fix touched (and what uses it); the full checks run every few fixes.
665
+ const scoped = deps.checks.scope(j.root, commands, await deps.git.changedPaths(j.root));
666
+ const fullSet = scoped.length === commands.length &&
667
+ scoped.every((c, i) => c.command === commands[i]?.command && c.dir === commands[i]?.dir);
668
+ const checked = await deps.checks.run(j.root, scoped, checksAbort.signal, onCheck(scoped.length));
669
+ if (stopRequested || pauseRequested)
670
+ return halt();
671
+ if (!checked.ok)
672
+ failure = { command: checked.command, tail: checked.tail };
673
+ else {
674
+ const guard = await stepGuard();
675
+ if (guard) {
676
+ await pauseWith(guard);
677
+ return "halt";
678
+ }
679
+ await setStep("committing");
680
+ try {
681
+ const sha = await deps.git.commit(j.root, j.branch, fixCommitMessage(group));
682
+ if (!sha)
683
+ return rollbackAnd(() => setAside(group, "The agent changed nothing."));
684
+ j.commits = [...j.commits, sha];
685
+ j.checkpoint = sha;
686
+ j.done = [...j.done, { group: toFixAllGroup(group), commit: short(sha) }];
687
+ // The full checks just passed on the whole tree, earlier fixes included.
688
+ if (fullSet)
689
+ j.fullAt = j.done.length;
690
+ j.current = null;
691
+ j.failStreak = 0;
692
+ j.reason = null;
693
+ lastCommitted = group;
694
+ await persist();
695
+ return "next";
696
+ }
697
+ catch (error) {
698
+ if (error instanceof FixAllGuardError) {
699
+ await pauseWith(error.message);
700
+ return "halt";
701
+ }
702
+ // A failing commit hook counts as a failing check.
703
+ failure = { command: "git commit (hooks)", tail: errText(error) };
704
+ }
705
+ }
706
+ if (attempt >= 2) {
707
+ j.failStreak++;
708
+ const f = failure;
709
+ return rollbackAnd(() => setAside(group, `The checks still failed after a retry (\`${f.command}\`).`));
710
+ }
711
+ await setStep("retrying");
712
+ result = await deps.session.prompt(fixRetryPrompt(failure.command, failure.tail), group.title);
713
+ }
714
+ }
715
+ async function setAside(group, reason) {
716
+ if (!j)
717
+ return;
718
+ const ids = group.findings.map((f) => f.actionId);
719
+ j.settled = [...j.settled, ...ids];
720
+ j.setAside = [...j.setAside, { group: toFixAllGroup(group), reason }];
721
+ }
722
+ /** Roll the unfinished step back to the checkpoint, then `after`; a refused rollback pauses. */
723
+ async function rollbackAnd(after) {
724
+ if (!j)
725
+ return "halt";
726
+ const ok = await rollbackUnfinished();
727
+ if (!ok)
728
+ return "halt";
729
+ await after();
730
+ if (j.status !== "running")
731
+ return "halt";
732
+ j.current = null;
733
+ await persist();
734
+ return stopRequested ? "halt" : "next";
735
+ }
736
+ async function rollbackUnfinished() {
737
+ if (!j)
738
+ return false;
739
+ await setStep("rolling-back");
740
+ const run = j;
741
+ try {
742
+ const files = await deps.git.rollback({
743
+ dir: run.root,
744
+ branch: run.branch,
745
+ checkpoint: run.checkpoint,
746
+ allowed: new Set([run.base, ...run.commits]),
747
+ othersOnCheckout: async () => ((await deps.othersOnCheckout(run.root)).busy ? 1 : 0),
748
+ onDiscard: async (list) => {
749
+ run.discard = [...list];
750
+ deps.log("INFO", "fix-all: rolling back", {
751
+ checkpoint: short(run.checkpoint),
752
+ files: list.join(", ").slice(0, 2_000),
753
+ });
754
+ await persist();
755
+ },
756
+ });
757
+ run.discard = files;
758
+ return true;
759
+ }
760
+ catch (error) {
761
+ await pauseWith(error instanceof FixAllGuardError
762
+ ? error.message
763
+ : `Couldn't undo the last fix: ${errText(error)}`);
764
+ return false;
765
+ }
766
+ }
767
+ async function pauseWith(reason) {
768
+ if (!j)
769
+ return;
770
+ j.status = "paused";
771
+ j.step = null;
772
+ j.reason = reason;
773
+ pauseRequested = false;
774
+ await persist();
775
+ }
776
+ async function finish(status, reason) {
777
+ if (!j)
778
+ return;
779
+ j.status = status;
780
+ j.step = null;
781
+ j.reason = reason;
782
+ j.current = null;
783
+ if (status === "done") {
784
+ j.next = [];
785
+ j.queued = 0;
786
+ }
787
+ await persist();
788
+ // Nothing to resume: the summary stays here until dismissed, not in the project's other sessions.
789
+ if (status === "done" && file) {
790
+ markJournalLive(file, false);
791
+ await removeJournal(file);
792
+ }
793
+ }
794
+ /** A stopped run leaves only its branch: no summary here or in the project's other sessions. */
795
+ async function clearIfStopped() {
796
+ if (j?.status !== "stopped")
797
+ return;
798
+ if (file) {
799
+ markJournalLive(file, false);
800
+ await removeJournal(file);
801
+ }
802
+ const empty = emptyRun();
803
+ j = null;
804
+ interrupted = false;
805
+ activity = null;
806
+ emit(toState());
807
+ disown(empty);
808
+ }
809
+ /** Stop or Pause mid-fix: undo its unfinished edits. A paused fix goes back in the queue. */
810
+ function halt() {
811
+ if (stopRequested)
812
+ return rollbackAnd(() => finish("stopped", "Stopped."));
813
+ return rollbackAnd(async () => {
814
+ if (!j)
815
+ return;
816
+ // Back in line, so the paused run still counts it and shows it next.
817
+ if (j.current) {
818
+ j.next = [j.current, ...j.next].slice(0, NEXT_SHOWN);
819
+ j.queued += 1;
820
+ }
821
+ j.current = null;
822
+ j.steps = Math.max(0, j.steps - 1);
823
+ await pauseWith(PAUSED_MID_FIX);
824
+ });
825
+ }
826
+ // ── controls ───────────────────────────────────────────────
827
+ function refuseForeign() {
828
+ if (foreign)
829
+ throw new FixAllGuardError("This run belongs to another GG Coder window.");
830
+ }
831
+ async function pause() {
832
+ await ensureLoaded();
833
+ refuseForeign();
834
+ if (!j || j.status !== "running" || !loop)
835
+ throw new FixAllGuardError("No run is working.");
836
+ pauseRequested = true;
837
+ // Now, not after the fix: the agent and checks stop, and the unfinished fix is undone. A commit
838
+ // already under way finishes first.
839
+ checksAbort.abort();
840
+ if (j.step === "fixing" || j.step === "retrying")
841
+ deps.session.abort();
842
+ emit(toState());
843
+ return toState();
844
+ }
845
+ async function resume(opts) {
846
+ await ensureLoaded();
847
+ refuseForeign();
848
+ if (loop || starting)
849
+ throw new FixAllGuardError("The run is already working.");
850
+ if (!j || !file)
851
+ throw new FixAllGuardError("There's no run to resume.");
852
+ const status = interrupted ? "interrupted" : j.status;
853
+ if (status !== "paused" && status !== "gate" && status !== "interrupted") {
854
+ throw new FixAllGuardError("There's no run to resume.");
855
+ }
856
+ if (status === "gate" && !opts.confirmRestructure) {
857
+ throw new FixAllGuardError("Confirm restructuring to continue.");
858
+ }
859
+ // Nobody drives it now (its session closed, or the app restarted): a background session in
860
+ // the run's folder takes it back.
861
+ const here = await deps.git.root(deps.cwd).catch(() => null);
862
+ if (here !== j.root) {
863
+ const runner = await deps.launch({
864
+ kind: "resume",
865
+ root: j.root,
866
+ key: runKey ?? j.root,
867
+ ...(opts.confirmRestructure ? { confirmRestructure: true } : {}),
868
+ });
869
+ return runner.state();
870
+ }
871
+ const busy = deps.busyReason();
872
+ if (busy)
873
+ throw new FixAllGuardError(busy);
874
+ const guard = await stepGuard();
875
+ if (guard)
876
+ throw new FixAllGuardError(guard);
877
+ const head = await deps.git.head(j.root);
878
+ if (!head || !(await deps.git.isAncestor(j.root, j.checkpoint))) {
879
+ throw new FixAllGuardError("The run's last commit is no longer behind this branch's tip. Stop the run instead.");
880
+ }
881
+ const unfinished = j.current !== null || status === "interrupted";
882
+ if (!unfinished) {
883
+ const changed = await deps.git.changedPaths(j.root);
884
+ if (changed.length > 0) {
885
+ throw new FixAllGuardError(`There are uncommitted changes (${changed.length} files). Commit or discard them, then resume.`);
886
+ }
887
+ // Commits made on the branch while paused are kept: later rollbacks never go behind them.
888
+ if (head !== j.checkpoint) {
889
+ j.commits = [...j.commits, head];
890
+ j.checkpoint = head;
891
+ }
892
+ }
893
+ // The checks it passed at its start: a run resumed after a restart, or by another session's
894
+ // runner, has no others.
895
+ commands = j.checks ? [...j.checks] : await deps.checks.resolve(j.root);
896
+ if (!deps.claim())
897
+ throw new FixAllGuardError("The agent is busy. Try again when it's done.");
898
+ if (opts.confirmRestructure)
899
+ j.restructureConfirmed = true;
900
+ j.status = "running";
901
+ j.reason = null;
902
+ j.failStreak = 0;
903
+ interrupted = false;
904
+ pauseRequested = false;
905
+ stopRequested = false;
906
+ checksAbort = new AbortController();
907
+ markJournalLive(file, true);
908
+ if (runKey) {
909
+ owner = true;
910
+ deps.onLive?.(runKey, true);
911
+ }
912
+ loop = (async () => {
913
+ if (unfinished) {
914
+ if (!(await rollbackUnfinished())) {
915
+ deps.release();
916
+ markJournalLive(file, false);
917
+ return;
918
+ }
919
+ j.current = null;
920
+ await persist();
921
+ }
922
+ await drive(true);
923
+ })()
924
+ .catch((error) => deps.log("WARN", "fix-all: resume failed", { error: errText(error) }))
925
+ .finally(async () => {
926
+ loop = null;
927
+ await clearIfStopped();
928
+ });
929
+ await persist();
930
+ return toState();
931
+ }
932
+ async function stop(fromCancel = false) {
933
+ await ensureLoaded();
934
+ if (baseline && !j) {
935
+ if (baseline.failed) {
936
+ if (fromCancel)
937
+ return toState();
938
+ baseline = null;
939
+ disown(emptyRun());
940
+ }
941
+ else {
942
+ stopRequested = true;
943
+ checksAbort.abort();
944
+ }
945
+ emit(toState());
946
+ return toState();
947
+ }
948
+ if (!j) {
949
+ if (fromCancel)
950
+ return toState();
951
+ throw new FixAllGuardError("There's no run to stop.");
952
+ }
953
+ if (foreign) {
954
+ if (fromCancel)
955
+ return toState();
956
+ refuseForeign();
957
+ }
958
+ if (loop) {
959
+ stopRequested = true;
960
+ checksAbort.abort();
961
+ if (!fromCancel)
962
+ deps.session.abort();
963
+ emit({ ...toState(), reason: "Stopping…" });
964
+ return toState();
965
+ }
966
+ if (fromCancel)
967
+ return toState();
968
+ if (j.status === "done" || j.status === "stopped") {
969
+ // Dismiss a finished run.
970
+ if (file)
971
+ await removeJournal(file);
972
+ const empty = emptyRun();
973
+ j = null;
974
+ interrupted = false;
975
+ baseline = null;
976
+ emit(toState());
977
+ disown(empty);
978
+ return toState();
979
+ }
980
+ // Paused, waiting or interrupted: end it, leaving the branch as it is.
981
+ interrupted = false;
982
+ await finish("stopped", "Stopped. The branch is left as it was.");
983
+ await clearIfStopped();
984
+ return toState();
985
+ }
986
+ return {
987
+ async state() {
988
+ await ensureLoaded();
989
+ if (!j && !baseline)
990
+ return toState(await preview().catch(() => null));
991
+ if (interrupted && j && j.discard.length === 0) {
992
+ j.discard = await deps.git.filesToDiscard(j.root, j.checkpoint).catch(() => []);
993
+ }
994
+ return toState();
995
+ },
996
+ start,
997
+ beginInWorktree,
998
+ pause,
999
+ resume,
1000
+ stop,
1001
+ active: () => loop !== null && !pauseRequested,
1002
+ working: () => loop !== null,
1003
+ owns: () => owner,
1004
+ folder: () => (owner ? (j?.root ?? setupRoot) : null),
1005
+ key: () => runKey,
1006
+ settled: async () => {
1007
+ while (loop)
1008
+ await loop;
1009
+ },
1010
+ };
1011
+ }
1012
+ //# sourceMappingURL=fix-all-runner.js.map