peaks-loop 4.1.12 → 4.1.14

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 (76) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +118 -0
  3. package/dist/cli/commands/_register.js +2 -0
  4. package/dist/cli/commands/batch-commands.d.ts +6 -0
  5. package/dist/cli/commands/batch-commands.js +70 -0
  6. package/dist/cli/commands/batch-diagnose-command.d.ts +10 -0
  7. package/dist/cli/commands/batch-diagnose-command.js +196 -0
  8. package/dist/cli/commands/batch-diagnose-envelope.d.ts +25 -0
  9. package/dist/cli/commands/batch-diagnose-envelope.js +60 -0
  10. package/dist/cli/commands/batch-diagnose-record.d.ts +21 -0
  11. package/dist/cli/commands/batch-diagnose-record.js +51 -0
  12. package/dist/cli/commands/batch-item-input.d.ts +59 -0
  13. package/dist/cli/commands/batch-item-input.js +113 -0
  14. package/dist/cli/commands/batch-report-command.d.ts +22 -0
  15. package/dist/cli/commands/batch-report-command.js +199 -0
  16. package/dist/cli/commands/code-gate-command.d.ts +18 -0
  17. package/dist/cli/commands/code-gate-command.js +95 -32
  18. package/dist/cli/commands/core/skill-context-verdict.d.ts +16 -1
  19. package/dist/cli/commands/core/skill-context-verdict.js +38 -8
  20. package/dist/cli/commands/lint-commands.js +8 -0
  21. package/dist/cli/commands/lint-rules-command.d.ts +14 -0
  22. package/dist/cli/commands/lint-rules-command.js +44 -0
  23. package/dist/services/batch/batch-active-batch.d.ts +55 -0
  24. package/dist/services/batch/batch-active-batch.js +127 -0
  25. package/dist/services/batch/batch-context-reminder.d.ts +85 -0
  26. package/dist/services/batch/batch-context-reminder.js +201 -0
  27. package/dist/services/batch/batch-diagnosis-finding.d.ts +25 -0
  28. package/dist/services/batch/batch-diagnosis-finding.js +227 -0
  29. package/dist/services/batch/batch-diagnosis-report-store.d.ts +49 -0
  30. package/dist/services/batch/batch-diagnosis-report-store.js +133 -0
  31. package/dist/services/batch/batch-diagnosis-summary.d.ts +31 -0
  32. package/dist/services/batch/batch-diagnosis-summary.js +129 -0
  33. package/dist/services/batch/batch-diagnosis.d.ts +36 -0
  34. package/dist/services/batch/batch-diagnosis.js +107 -0
  35. package/dist/services/batch/batch-entry.d.ts +22 -0
  36. package/dist/services/batch/batch-entry.js +42 -0
  37. package/dist/services/batch/batch-fix-agent.d.ts +39 -0
  38. package/dist/services/batch/batch-fix-agent.js +126 -0
  39. package/dist/services/batch/batch-fix-types.d.ts +85 -0
  40. package/dist/services/batch/batch-fix-types.js +11 -0
  41. package/dist/services/batch/batch-fix.d.ts +15 -0
  42. package/dist/services/batch/batch-fix.js +229 -0
  43. package/dist/services/batch/batch-phase-advance.d.ts +45 -0
  44. package/dist/services/batch/batch-phase-advance.js +105 -0
  45. package/dist/services/batch/batch-progress-store.d.ts +52 -0
  46. package/dist/services/batch/batch-progress-store.js +219 -0
  47. package/dist/services/batch/batch-progress-types.d.ts +79 -0
  48. package/dist/services/batch/batch-progress-types.js +10 -0
  49. package/dist/services/batch/batch-recovery.d.ts +5 -0
  50. package/dist/services/batch/batch-recovery.js +24 -0
  51. package/dist/services/batch/batch-verify.d.ts +93 -0
  52. package/dist/services/batch/batch-verify.js +216 -0
  53. package/dist/services/code/auto-compact-decision.d.ts +17 -0
  54. package/dist/services/code/auto-compact-decision.js +6 -0
  55. package/dist/services/code/auto-compact-orchestrator.js +6 -0
  56. package/dist/services/code/batch-compaction-point.d.ts +45 -0
  57. package/dist/services/code/batch-compaction-point.js +99 -0
  58. package/dist/services/context/context-schema.d.ts +1 -1
  59. package/dist/services/hooks/pre-tool-code-gate.d.ts +33 -1
  60. package/dist/services/hooks/pre-tool-code-gate.js +67 -6
  61. package/dist/services/lint/curated-rule-reader.d.ts +37 -0
  62. package/dist/services/lint/curated-rule-reader.js +179 -0
  63. package/dist/services/lint/project-lint-declarations.d.ts +27 -0
  64. package/dist/services/lint/project-lint-declarations.js +217 -0
  65. package/dist/services/lint/project-lint-tool-detection.d.ts +14 -0
  66. package/dist/services/lint/project-lint-tool-detection.js +208 -0
  67. package/dist/services/lint/project-lint-tool-rules.d.ts +19 -0
  68. package/dist/services/lint/project-lint-tool-rules.js +199 -0
  69. package/dist/services/lint/rule-pre-read-types.d.ts +66 -0
  70. package/dist/services/lint/rule-pre-read-types.js +22 -0
  71. package/dist/services/lint/rule-pre-read.d.ts +20 -0
  72. package/dist/services/lint/rule-pre-read.js +145 -0
  73. package/dist/services/skill/skill-search-service.d.ts +3 -3
  74. package/package.json +5 -5
  75. package/skills/peaks-code/references/micro-cycle.md +13 -1
  76. package/skills/peaks-race-code/SKILL.md +40 -1
@@ -0,0 +1,229 @@
1
+ // src/services/batch/batch-fix.ts
2
+ //
3
+ // The batch's fix phase: one fix sub-agent per item, each carrying ONLY its
4
+ // own diagnosis, and a scoped test that decides whether the item counts as
5
+ // fixed.
6
+ //
7
+ // WHY THE SCOPED TEST IS A GATE AND NOT A REPORT. The batch's verification
8
+ // phase runs once, at the end, over the whole tree. When that gate goes red
9
+ // the question "which item broke it?" has no answer — unless every item was
10
+ // checked on its own, immediately after its own fix. So the scoped test runs
11
+ // BETWEEN the fix and the status flip: green ⇒ `appendBatchItem(status:
12
+ // 'fixed')`; red ⇒ the item stays `diagnosed` and the failure travels back
13
+ // in the result. Without that step the final gate cannot tell an integration
14
+ // failure from one broken item.
15
+ //
16
+ // WHY THE DISPATCH AND THE SCOPED TEST ARE INJECTED. Both are effects this
17
+ // library cannot perform on its own: a sub-agent is dispatched by an IDE
18
+ // tool call the LLM executes, and a scoped test is a test runner inside the
19
+ // target project. So `runBatchFix` takes both as dependencies, and the tests
20
+ // pass fakes. The contract that matters — own diagnosis, distinct rid,
21
+ // scoped test before the status flip — is then observable without spawning a
22
+ // real agent or running a real suite.
23
+ //
24
+ // The prompt and the rid live in `batch-fix-agent.ts`; the names live in
25
+ // `batch-fix-types.ts`. This file is the phase itself: the order of the
26
+ // steps, and the one rule that decides a status.
27
+ import { planBatchTopology } from './batch-diagnosis.js';
28
+ import { appendBatchItem, readBatchProgress } from './batch-progress-store.js';
29
+ import { advanceBatchPhase } from './batch-phase-advance.js';
30
+ import { buildFixPrompt, deriveAgentRid, FIX_ROLE } from './batch-fix-agent.js';
31
+ /**
32
+ * Fix every diagnosed item of a batch, one scoped test at a time.
33
+ *
34
+ * The waves are the unit of parallelism: the agents of one wave are
35
+ * dispatched together, and the wave after it starts only when the previous
36
+ * wave's items have been tested. The scoped test of an item runs before that
37
+ * item's status flips, and a red test leaves the item `diagnosed`.
38
+ *
39
+ * @param options - The batch, its items, their diagnoses and the rule list.
40
+ * @param deps - The dispatch and the scoped-test runner.
41
+ * @returns One result per fixed item, and the items that had no diagnosis.
42
+ */
43
+ export async function runBatchFix(options, deps) {
44
+ const { fixable, undiagnosable } = splitDiagnosed(options);
45
+ const plan = planBatchTopology(fixable);
46
+ const scheduled = scheduleFixes(fixable, plan, options.rid);
47
+ const frame = {
48
+ context: {
49
+ projectRoot: options.projectRoot,
50
+ sessionId: options.sessionId,
51
+ batchId: options.batchId
52
+ },
53
+ deps,
54
+ diagnoses: options.diagnoses,
55
+ rules: options.rules
56
+ };
57
+ stampFixPhase(frame.context, fixable, plan);
58
+ const results = [];
59
+ for (const wave of plan.waves) {
60
+ for (const result of await runWave(frame, wave.waveIndex, scheduled)) {
61
+ results.push(result);
62
+ }
63
+ }
64
+ // The ③→④ boundary: the fix stage is over, whether its scoped tests
65
+ // were green or not. A red test is the UNIFIED GATE's to attribute, and
66
+ // the attribution needs the batch to be in verification — so the advance
67
+ // happens either way, and it is the cheapest moment to compact.
68
+ advanceBatchPhase({
69
+ projectRoot: options.projectRoot,
70
+ sessionId: options.sessionId,
71
+ batchId: options.batchId,
72
+ toPhase: 'verify'
73
+ });
74
+ return { results, undiagnosable };
75
+ }
76
+ /**
77
+ * Split the batch's items into the ones a fix agent can be dispatched for and
78
+ * the ones whose diagnosis is missing.
79
+ *
80
+ * Only a `diagnosed` item is fixed: a `pending` one has no diagnosis to
81
+ * carry, and a `fixed` or `verified` one is already behind us.
82
+ */
83
+ function splitDiagnosed(options) {
84
+ const fixable = [];
85
+ const undiagnosable = [];
86
+ for (const item of options.items) {
87
+ if (item.status !== 'diagnosed')
88
+ continue;
89
+ if (options.diagnoses[item.id] === undefined)
90
+ undiagnosable.push(item.id);
91
+ else
92
+ fixable.push(item);
93
+ }
94
+ return { fixable, undiagnosable };
95
+ }
96
+ /**
97
+ * Give every scheduled item its wave and its own rid.
98
+ *
99
+ * The rid is derived from the batch's rid and the item's id, so two agents
100
+ * of one wave never ask for the same worktree branch.
101
+ */
102
+ function scheduleFixes(items, plan, baseRid) {
103
+ const byId = new Map(items.map((item) => [item.id, item]));
104
+ const usedRids = new Set();
105
+ const scheduled = [];
106
+ for (const wave of plan.waves) {
107
+ for (const itemId of wave.slices) {
108
+ const item = byId.get(itemId);
109
+ if (item === undefined)
110
+ continue;
111
+ scheduled.push({
112
+ item,
113
+ waveIndex: wave.waveIndex,
114
+ rid: deriveAgentRid(baseRid, itemId, usedRids)
115
+ });
116
+ }
117
+ }
118
+ return scheduled;
119
+ }
120
+ /**
121
+ * Run one wave: dispatch its agents together, then test each item and flip
122
+ * its status if the test was green.
123
+ */
124
+ async function runWave(frame, waveIndex, scheduled) {
125
+ const entries = scheduled.filter((entry) => entry.waveIndex === waveIndex);
126
+ const dispatched = await Promise.all(entries.map(async (entry) => ({ entry, outcome: await dispatchOne(frame, entry) })));
127
+ const results = [];
128
+ for (const { entry, outcome } of dispatched) {
129
+ results.push(await fixOne(frame, entry, outcome));
130
+ }
131
+ return results;
132
+ }
133
+ /**
134
+ * Dispatch one fix sub-agent.
135
+ *
136
+ * A dispatch that throws is a failed fix, not a failed batch: the item
137
+ * stays `diagnosed` and the batch's other items still run.
138
+ */
139
+ async function dispatchOne(frame, entry) {
140
+ const diagnosis = frame.diagnoses[entry.item.id];
141
+ if (diagnosis === undefined) {
142
+ return { ok: false, summary: `no diagnosis was recorded for item "${entry.item.id}"` };
143
+ }
144
+ const spec = {
145
+ rid: entry.rid,
146
+ role: FIX_ROLE,
147
+ itemId: entry.item.id,
148
+ waveIndex: entry.waveIndex,
149
+ purpose: `Batch fix: ${entry.item.label} (${entry.item.id})`,
150
+ prompt: buildFixPrompt(entry.item, diagnosis, frame.rules, entry.rid)
151
+ };
152
+ try {
153
+ return await frame.deps.dispatchFixAgent(spec);
154
+ }
155
+ catch (error) {
156
+ return { ok: false, summary: `the fix agent could not be dispatched: ${describe(error)}` };
157
+ }
158
+ }
159
+ /**
160
+ * Test one fixed item, and flip its status only if the test was green.
161
+ *
162
+ * The order is the whole point: the test runs while the item is still
163
+ * `diagnosed`, so a record read mid-run shows the item before the flip.
164
+ */
165
+ async function fixOne(frame, entry, outcome) {
166
+ const scopedTest = await runScopedTest(frame, entry.item, outcome);
167
+ const fixed = outcome.ok && scopedTest.ok;
168
+ if (fixed) {
169
+ appendBatchItem(frame.context.projectRoot, frame.context.sessionId, frame.context.batchId, {
170
+ ...entry.item,
171
+ status: 'fixed',
172
+ fixedAt: new Date().toISOString()
173
+ });
174
+ }
175
+ return {
176
+ itemId: entry.item.id,
177
+ waveIndex: entry.waveIndex,
178
+ rid: entry.rid,
179
+ status: fixed ? 'fixed' : 'diagnosed',
180
+ fix: outcome,
181
+ scopedTest
182
+ };
183
+ }
184
+ /**
185
+ * Run one item's scoped test.
186
+ *
187
+ * A runner that throws is a red test, not a crashed batch: the item keeps
188
+ * its `diagnosed` status and the failure text travels back in the result.
189
+ */
190
+ async function runScopedTest(frame, item, outcome) {
191
+ try {
192
+ return await frame.deps.runScopedTest({ item, outcome });
193
+ }
194
+ catch (error) {
195
+ return {
196
+ ok: false,
197
+ command: '',
198
+ detail: `the scoped test could not be run: ${describe(error)}`
199
+ };
200
+ }
201
+ }
202
+ /**
203
+ * Stamp the record with the fix phase and the wave plan.
204
+ *
205
+ * The record is what survives a compaction, and its `phase` is the only
206
+ * field that says a batch is in flight — so entering the fix phase is
207
+ * written down before any agent is dispatched. The items already in the
208
+ * record are kept: the record knows more than this call does.
209
+ */
210
+ function stampFixPhase(context, items, topology) {
211
+ const current = readBatchProgress(context.projectRoot, context.sessionId, context.batchId);
212
+ const recorded = [...(current?.items ?? [])];
213
+ for (const item of items) {
214
+ if (!recorded.some((candidate) => candidate.id === item.id))
215
+ recorded.push(item);
216
+ }
217
+ advanceBatchPhase({
218
+ projectRoot: context.projectRoot,
219
+ sessionId: context.sessionId,
220
+ batchId: context.batchId,
221
+ toPhase: 'fix',
222
+ items: recorded,
223
+ topology
224
+ });
225
+ }
226
+ /** An error's message, whether it is an `Error` or not. */
227
+ function describe(error) {
228
+ return error instanceof Error ? error.message : String(error);
229
+ }
@@ -0,0 +1,45 @@
1
+ import type { AutoCompactMode } from '../code/auto-compact-modes.js';
2
+ import { type BatchCompactionPoint } from '../code/batch-compaction-point.js';
3
+ import type { BatchItem, BatchPhase, BatchProgress } from './batch-progress-types.js';
4
+ /** What the caller knows about the advance. */
5
+ export interface BatchPhaseAdvanceInput {
6
+ readonly projectRoot: string;
7
+ readonly sessionId: string;
8
+ readonly batchId: string;
9
+ /** The phase the batch is moving INTO. */
10
+ readonly toPhase: BatchPhase;
11
+ /** The items to record; the record's own items when omitted. */
12
+ readonly items?: readonly BatchItem[];
13
+ /** The wave plan to record; the record's own when omitted. */
14
+ readonly topology?: unknown;
15
+ /** The auto-compact mode; the project's own profile when omitted. */
16
+ readonly mode?: AutoCompactMode;
17
+ }
18
+ /** What the advance did. */
19
+ export interface BatchPhaseAdvanceResult {
20
+ /** The record as it was written. */
21
+ readonly progress: BatchProgress;
22
+ /** The compaction point this advance chose. */
23
+ readonly compaction: BatchCompactionPoint;
24
+ /** The notice recorded, when one was. */
25
+ readonly boundaryNotice?: string;
26
+ }
27
+ /**
28
+ * Advance the batch's phase, and record the boundary notice when a boundary
29
+ * was crossed.
30
+ *
31
+ * The notice is recorded only when a compaction actually happens: it SAYS
32
+ * that a compaction is running, so writing it while the window is still at
33
+ * 40% would be a false fact.
34
+ *
35
+ * @param input - The batch, the phase it is moving into, and what to record.
36
+ */
37
+ export declare function advanceBatchPhase(input: BatchPhaseAdvanceInput): BatchPhaseAdvanceResult;
38
+ /**
39
+ * The context ratio the compaction point is judged against.
40
+ *
41
+ * The probe is the same one every other context read uses; when it cannot
42
+ * measure, it answers zero, which reads as "there is room" — the same
43
+ * answer today's conservative fallback gives.
44
+ */
45
+ export declare function readContextRatio(projectRoot: string, sessionId: string): number;
@@ -0,0 +1,105 @@
1
+ // src/services/batch/batch-phase-advance.ts
2
+ //
3
+ // ONE owner for "the batch changed phase".
4
+ //
5
+ // WHY THIS MODULE EXISTS. The batch's four stages end in two compaction
6
+ // boundaries — ①→② (diagnosis → topology) and ③→④ (fix → verify) — and
7
+ // each boundary is the cheapest moment to compact: the stage's results are
8
+ // on disk, its agents are done, and the window is at its heaviest. Both
9
+ // boundaries need the same three things: the phase written down, the
10
+ // compaction point chosen, and the boundary notice recorded. Two writers
11
+ // would drift, and a drifted boundary rule is a batch that compacts at the
12
+ // wrong moment — or never.
13
+ //
14
+ // WHY THE NOTICE IS NOT WRITTEN HERE. The wording belongs to the
15
+ // verification stage (`buildPhaseBoundaryNotice`), and this module CONSUMES
16
+ // it. A second sentence about the same moment would be a rival, and two
17
+ // rivals drift apart.
18
+ //
19
+ // WHY THE COUNTS IN THE NOTICE ARE THE DIAGNOSIS COUNTS. The notice says
20
+ // 诊断完成 — "the diagnosis is complete" — and that is Task 2's wording,
21
+ // which this module does not change. So the numbers it carries have to be
22
+ // the DIAGNOSIS counts at every boundary: a boundary after a red scoped
23
+ // test still reports the diagnosis's counts, because a notice claiming the
24
+ // diagnosis finished 1 of 2 items when it finished 2 of 2 would be a false
25
+ // fact. If the notice should name the stage that finished, that is a
26
+ // change to the producer's wording, and the producer owns it.
27
+ //
28
+ // WHY THE RATIO IS READ HERE. The compaction point and the notice both
29
+ // depend on the window's occupancy, and the two callers that advance a
30
+ // phase must not each read it differently. One read, one place.
31
+ import { readContextPercent } from '../context/auto-compact-reader.js';
32
+ import { resolveOuterSessionId } from '../session/binding-status-service.js';
33
+ import { resolveAutoCompactProfile } from '../mode/mode-status-service.js';
34
+ import { decideBatchCompactionPoint, isBatchPhaseBoundary } from '../code/batch-compaction-point.js';
35
+ import { buildPhaseBoundaryNotice } from './batch-verify.js';
36
+ import { readBatchProgress, writeBatchProgress } from './batch-progress-store.js';
37
+ /**
38
+ * Advance the batch's phase, and record the boundary notice when a boundary
39
+ * was crossed.
40
+ *
41
+ * The notice is recorded only when a compaction actually happens: it SAYS
42
+ * that a compaction is running, so writing it while the window is still at
43
+ * 40% would be a false fact.
44
+ *
45
+ * @param input - The batch, the phase it is moving into, and what to record.
46
+ */
47
+ export function advanceBatchPhase(input) {
48
+ const { projectRoot, sessionId, batchId, toPhase } = input;
49
+ const current = readBatchProgress(projectRoot, sessionId, batchId);
50
+ const items = input.items ?? current?.items ?? [];
51
+ const topology = input.topology ?? current?.topology;
52
+ const fromPhase = current?.phase ?? 'diagnosis';
53
+ const mode = input.mode ?? resolveAutoCompactProfile(projectRoot);
54
+ const ratio = readContextRatio(projectRoot, sessionId);
55
+ const compaction = decideBatchCompactionPoint({ ratio, fromPhase, toPhase, mode });
56
+ const boundaryNotice = resolveBoundaryNotice({ fromPhase, toPhase, items, ratio, mode, compaction }) ??
57
+ current?.boundaryNotice;
58
+ const progress = {
59
+ batchId,
60
+ phase: toPhase,
61
+ items,
62
+ ...(topology === undefined ? {} : { topology }),
63
+ ...(boundaryNotice === undefined ? {} : { boundaryNotice })
64
+ };
65
+ writeBatchProgress(projectRoot, sessionId, progress);
66
+ return {
67
+ progress,
68
+ compaction,
69
+ ...(boundaryNotice === undefined ? {} : { boundaryNotice })
70
+ };
71
+ }
72
+ /**
73
+ * The notice for this advance, when one is due.
74
+ *
75
+ * Three conditions, and each one is a refusal: the phase did not change,
76
+ * the change was not a boundary, or no compaction is actually running (the
77
+ * notice SAYS a compaction is running, so it may not be written when none
78
+ * is).
79
+ */
80
+ function resolveBoundaryNotice(input) {
81
+ if (input.fromPhase === input.toPhase)
82
+ return undefined;
83
+ if (!isBatchPhaseBoundary(input.fromPhase, input.toPhase))
84
+ return undefined;
85
+ if (!input.compaction.shouldCompact)
86
+ return undefined;
87
+ const diagnosed = input.items.filter((item) => item.status !== 'pending').length;
88
+ return buildPhaseBoundaryNotice({
89
+ done: diagnosed,
90
+ total: input.items.length,
91
+ ratio: input.ratio,
92
+ mode: input.mode
93
+ });
94
+ }
95
+ /**
96
+ * The context ratio the compaction point is judged against.
97
+ *
98
+ * The probe is the same one every other context read uses; when it cannot
99
+ * measure, it answers zero, which reads as "there is room" — the same
100
+ * answer today's conservative fallback gives.
101
+ */
102
+ export function readContextRatio(projectRoot, sessionId) {
103
+ const outerSessionId = resolveOuterSessionId(projectRoot, sessionId, process.env);
104
+ return readContextPercent({ projectRoot, sessionId, outerSessionId, env: process.env }).ratio;
105
+ }
@@ -0,0 +1,52 @@
1
+ import type { BatchItem, BatchProgress } from './batch-progress-types.js';
2
+ /**
3
+ * The record's path for one batch.
4
+ *
5
+ * `batchId` is caller-supplied and becomes a path segment, so it is checked
6
+ * before it is joined: `..` and an absolute path would otherwise let a caller
7
+ * write outside the session's batch directory, and a nested `a/b` would write
8
+ * outside the directory the batch owns.
9
+ */
10
+ export declare function batchProgressPath(projectRoot: string, sessionId: string, batchId: string): string;
11
+ /**
12
+ * The canonical form of a file set: POSIX separators, no leading `./`, no
13
+ * duplicates, sorted.
14
+ *
15
+ * Two callers that measured the same file differently — one agent on Windows
16
+ * reporting a backslash-spelled path, another reporting the same path with
17
+ * forward slashes — must end up with the same string, or the disjointness
18
+ * check that decides whether two items may run in parallel waves reads them as
19
+ * disjoint and two agents edit one file. Sorting makes the stored set
20
+ * comparable, not just its members.
21
+ */
22
+ export declare function normalizeFileSet(files: readonly string[]): readonly string[];
23
+ /**
24
+ * Read one batch's record. `null` when the batch has no record yet — the
25
+ * "no progress" answer, distinct from a record that exists but is unreadable.
26
+ *
27
+ * A malformed record throws rather than reading as `null`: the two answers
28
+ * mean opposite things to the caller, and a batch that silently loses its
29
+ * history restarts the work it had already done.
30
+ */
31
+ export declare function readBatchProgress(projectRoot: string, sessionId: string, batchId: string): BatchProgress | null;
32
+ /**
33
+ * Write one batch's record, atomically.
34
+ *
35
+ * The timestamp is the writer's, not the caller's: the record's value is
36
+ * "when this batch last moved", and a caller that supplied its own clock
37
+ * would make that unanswerable.
38
+ */
39
+ export declare function writeBatchProgress(projectRoot: string, sessionId: string, progress: BatchProgress): void;
40
+ /**
41
+ * Append one item to a batch's record and write it back.
42
+ *
43
+ * The append is read → merge → write, and the merge is by item id: an item
44
+ * that is already in the record is replaced by the new version, so an item
45
+ * that moves from `pending` to `diagnosed` to `fixed` is one row that changes
46
+ * status rather than three rows. That is what lets the recovery read "which
47
+ * items are still pending" by filtering one field.
48
+ *
49
+ * A batch with no record yet gets one, so the first append does not need a
50
+ * separate create step — the record is written as the batch runs, not before.
51
+ */
52
+ export declare function appendBatchItem(projectRoot: string, sessionId: string, batchId: string, item: BatchItem): void;
@@ -0,0 +1,219 @@
1
+ // src/services/batch/batch-progress-store.ts
2
+ //
3
+ // The on-disk batch progress record, and the file-set normalizer the whole
4
+ // batch mode depends on.
5
+ //
6
+ // WHY THIS FILE EXISTS (the compaction gap). The pre-compact checkpoint
7
+ // records empty lists for open questions, recent decisions and todo state, so
8
+ // a compaction in the middle of a batch loses everything the orchestrator knew
9
+ // about that batch: which items were already diagnosed, which file sets they
10
+ // would touch, which stage the batch had reached. The batch then restarts from
11
+ // the beginning. This record is what survives that: one file per batch, written
12
+ // as each item is diagnosed or fixed, so a resumed batch continues instead of
13
+ // re-running.
14
+ //
15
+ // WHERE IT LIVES. `<sessionDir>/batch/<batchId>/progress.json` — beside the
16
+ // other artifacts of the session, one directory per batch.
17
+ //
18
+ // WHY THE WRITE IS ATOMIC. A reader that sees a half-written file reads it as
19
+ // "no progress" and restarts the batch. The write goes to a temp file in the
20
+ // same directory and is renamed over the target, so a reader sees either the
21
+ // previous record or the new one — the same pattern the job progress mirror
22
+ // and the session checkpoint use.
23
+ //
24
+ // WHY THE FILE SET IS NORMALIZED. Two items may run in the same wave only if
25
+ // their file sets are disjoint, and that comparison is exact string equality.
26
+ // A backslash-spelled path and the same path spelled with forward slashes name
27
+ // one file on every platform this project runs on, so an unnormalized set makes
28
+ // two items look disjoint when they are not — and two agents then edit the same
29
+ // file at once. `normalizeFileSet` is the one place that decides what a file
30
+ // set is.
31
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
32
+ import { dirname, join } from 'node:path';
33
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
34
+ import { normalizePath } from '../../shared/path-utils.js';
35
+ import { getSessionDir } from '../session/getSessionDir.js';
36
+ const BATCH_DIR = 'batch';
37
+ const PROGRESS_FILE = 'progress.json';
38
+ const PHASES = ['diagnosis', 'topology', 'fix', 'verify', 'done'];
39
+ const STATUSES = ['pending', 'diagnosed', 'fixed', 'verified'];
40
+ /**
41
+ * The record's path for one batch.
42
+ *
43
+ * `batchId` is caller-supplied and becomes a path segment, so it is checked
44
+ * before it is joined: `..` and an absolute path would otherwise let a caller
45
+ * write outside the session's batch directory, and a nested `a/b` would write
46
+ * outside the directory the batch owns.
47
+ */
48
+ export function batchProgressPath(projectRoot, sessionId, batchId) {
49
+ if (isUnsafePathInput(batchId) || batchId.includes('/')) {
50
+ throw new Error(`Invalid batch id: ${batchId} (must be a single safe path segment)`);
51
+ }
52
+ return join(getSessionDir(projectRoot, sessionId), BATCH_DIR, batchId, PROGRESS_FILE);
53
+ }
54
+ /**
55
+ * The canonical form of a file set: POSIX separators, no leading `./`, no
56
+ * duplicates, sorted.
57
+ *
58
+ * Two callers that measured the same file differently — one agent on Windows
59
+ * reporting a backslash-spelled path, another reporting the same path with
60
+ * forward slashes — must end up with the same string, or the disjointness
61
+ * check that decides whether two items may run in parallel waves reads them as
62
+ * disjoint and two agents edit one file. Sorting makes the stored set
63
+ * comparable, not just its members.
64
+ */
65
+ export function normalizeFileSet(files) {
66
+ const seen = new Set();
67
+ for (const raw of files) {
68
+ if (typeof raw !== 'string')
69
+ continue;
70
+ const posix = normalizePath(raw).replace(/^\.\//, '');
71
+ if (posix.length > 0)
72
+ seen.add(posix);
73
+ }
74
+ return [...seen].sort();
75
+ }
76
+ /**
77
+ * Read one batch's record. `null` when the batch has no record yet — the
78
+ * "no progress" answer, distinct from a record that exists but is unreadable.
79
+ *
80
+ * A malformed record throws rather than reading as `null`: the two answers
81
+ * mean opposite things to the caller, and a batch that silently loses its
82
+ * history restarts the work it had already done.
83
+ */
84
+ export function readBatchProgress(projectRoot, sessionId, batchId) {
85
+ const path = batchProgressPath(projectRoot, sessionId, batchId);
86
+ if (!existsSync(path))
87
+ return null;
88
+ const raw = readFileSync(path, 'utf8');
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(raw);
92
+ }
93
+ catch (error) {
94
+ const detail = error instanceof Error ? error.message : String(error);
95
+ throw new Error(`Invalid batch progress at ${path}: ${detail}`);
96
+ }
97
+ return coerceProgress(parsed, path);
98
+ }
99
+ /**
100
+ * Write one batch's record, atomically.
101
+ *
102
+ * The timestamp is the writer's, not the caller's: the record's value is
103
+ * "when this batch last moved", and a caller that supplied its own clock
104
+ * would make that unanswerable.
105
+ */
106
+ export function writeBatchProgress(projectRoot, sessionId, progress) {
107
+ const path = batchProgressPath(projectRoot, sessionId, progress.batchId);
108
+ mkdirSync(dirname(path), { recursive: true });
109
+ const record = { ...progress, updatedAt: new Date().toISOString() };
110
+ // Temp file in the same directory, then rename: a write that fails halfway
111
+ // leaves the previous record intact rather than a truncated one.
112
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
113
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
114
+ renameSync(tmp, path);
115
+ }
116
+ /**
117
+ * Append one item to a batch's record and write it back.
118
+ *
119
+ * The append is read → merge → write, and the merge is by item id: an item
120
+ * that is already in the record is replaced by the new version, so an item
121
+ * that moves from `pending` to `diagnosed` to `fixed` is one row that changes
122
+ * status rather than three rows. That is what lets the recovery read "which
123
+ * items are still pending" by filtering one field.
124
+ *
125
+ * A batch with no record yet gets one, so the first append does not need a
126
+ * separate create step — the record is written as the batch runs, not before.
127
+ */
128
+ export function appendBatchItem(projectRoot, sessionId, batchId, item) {
129
+ const existing = readBatchProgress(projectRoot, sessionId, batchId);
130
+ const items = existing === null ? [] : existing.items;
131
+ const at = items.findIndex((candidate) => candidate.id === item.id);
132
+ const merged = at === -1
133
+ ? [...items, item]
134
+ : items.map((candidate, index) => (index === at ? item : candidate));
135
+ const next = {
136
+ ...(existing ?? {}),
137
+ batchId,
138
+ phase: existing?.phase ?? 'diagnosis',
139
+ items: merged
140
+ };
141
+ writeBatchProgress(projectRoot, sessionId, next);
142
+ }
143
+ /**
144
+ * Check a parsed record against the shape the rest of the batch mode reads.
145
+ *
146
+ * The record is written by this module and read by another process after a
147
+ * compaction, so it is external data at read time. The fields the recovery
148
+ * path depends on — the phase and the items — are checked; a mismatch throws
149
+ * with the path, so a wrong-shaped file is reported rather than read as a
150
+ * batch with no items (which would restart the batch's work).
151
+ */
152
+ function coerceProgress(raw, path) {
153
+ const record = requireObject(raw, path, 'root');
154
+ const batchId = requireText(record['batchId'], path, 'batchId');
155
+ const phase = requireEnum(record['phase'], PHASES, path, 'phase');
156
+ const rawItems = record['items'];
157
+ if (!Array.isArray(rawItems)) {
158
+ throw new Error(`Invalid batch progress at ${path}: items must be an array`);
159
+ }
160
+ const items = rawItems.map((entry, index) => coerceItem(entry, path, index));
161
+ const topology = record['topology'];
162
+ const updatedAt = record['updatedAt'];
163
+ const boundaryNotice = record['boundaryNotice'];
164
+ return {
165
+ batchId,
166
+ phase,
167
+ items,
168
+ ...(topology === undefined ? {} : { topology }),
169
+ ...(typeof boundaryNotice === 'string' ? { boundaryNotice } : {}),
170
+ ...(typeof updatedAt === 'string' ? { updatedAt } : {})
171
+ };
172
+ }
173
+ /** One item of the record, checked the same way as the record itself. */
174
+ function coerceItem(raw, path, index) {
175
+ const at = `items[${index}]`;
176
+ const entry = requireObject(raw, path, at);
177
+ const id = requireText(entry['id'], path, `${at}.id`);
178
+ const label = requireText(entry['label'], path, `${at}.label`);
179
+ const status = requireEnum(entry['status'], STATUSES, path, `${at}.status`);
180
+ const files = entry['files'];
181
+ if (!Array.isArray(files) || !files.every((file) => typeof file === 'string')) {
182
+ throw new Error(`Invalid batch progress at ${path}: ${at}.files must be an array of strings`);
183
+ }
184
+ const riskSurface = entry['riskSurface'];
185
+ const diagnosedAt = entry['diagnosedAt'];
186
+ const fixedAt = entry['fixedAt'];
187
+ const symptom = entry['symptom'];
188
+ return {
189
+ id,
190
+ label,
191
+ status,
192
+ files,
193
+ ...(typeof symptom === 'string' ? { symptom } : {}),
194
+ ...(typeof riskSurface === 'number' ? { riskSurface } : {}),
195
+ ...(typeof diagnosedAt === 'string' ? { diagnosedAt } : {}),
196
+ ...(typeof fixedAt === 'string' ? { fixedAt } : {})
197
+ };
198
+ }
199
+ /** A JSON object, or a refusal naming where it was expected. */
200
+ function requireObject(raw, path, what) {
201
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
202
+ throw new Error(`Invalid batch progress at ${path}: ${what} must be an object`);
203
+ }
204
+ return raw;
205
+ }
206
+ /** A non-empty string, or a refusal naming the field. */
207
+ function requireText(raw, path, what) {
208
+ if (typeof raw !== 'string' || raw.length === 0) {
209
+ throw new Error(`Invalid batch progress at ${path}: ${what} must be a non-empty string`);
210
+ }
211
+ return raw;
212
+ }
213
+ /** One of a fixed set of values, or a refusal naming the set. */
214
+ function requireEnum(raw, allowed, path, what) {
215
+ if (typeof raw !== 'string' || !allowed.includes(raw)) {
216
+ throw new Error(`Invalid batch progress at ${path}: ${what} must be one of ${allowed.join('|')}`);
217
+ }
218
+ return raw;
219
+ }