peaks-loop 4.1.12 → 4.1.13

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 (72) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +53 -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/core/skill-context-verdict.d.ts +16 -1
  17. package/dist/cli/commands/core/skill-context-verdict.js +38 -8
  18. package/dist/cli/commands/lint-commands.js +8 -0
  19. package/dist/cli/commands/lint-rules-command.d.ts +14 -0
  20. package/dist/cli/commands/lint-rules-command.js +44 -0
  21. package/dist/services/batch/batch-active-batch.d.ts +55 -0
  22. package/dist/services/batch/batch-active-batch.js +127 -0
  23. package/dist/services/batch/batch-context-reminder.d.ts +85 -0
  24. package/dist/services/batch/batch-context-reminder.js +201 -0
  25. package/dist/services/batch/batch-diagnosis-finding.d.ts +25 -0
  26. package/dist/services/batch/batch-diagnosis-finding.js +227 -0
  27. package/dist/services/batch/batch-diagnosis-report-store.d.ts +49 -0
  28. package/dist/services/batch/batch-diagnosis-report-store.js +133 -0
  29. package/dist/services/batch/batch-diagnosis-summary.d.ts +31 -0
  30. package/dist/services/batch/batch-diagnosis-summary.js +129 -0
  31. package/dist/services/batch/batch-diagnosis.d.ts +36 -0
  32. package/dist/services/batch/batch-diagnosis.js +107 -0
  33. package/dist/services/batch/batch-entry.d.ts +22 -0
  34. package/dist/services/batch/batch-entry.js +42 -0
  35. package/dist/services/batch/batch-fix-agent.d.ts +39 -0
  36. package/dist/services/batch/batch-fix-agent.js +126 -0
  37. package/dist/services/batch/batch-fix-types.d.ts +85 -0
  38. package/dist/services/batch/batch-fix-types.js +11 -0
  39. package/dist/services/batch/batch-fix.d.ts +15 -0
  40. package/dist/services/batch/batch-fix.js +229 -0
  41. package/dist/services/batch/batch-phase-advance.d.ts +45 -0
  42. package/dist/services/batch/batch-phase-advance.js +105 -0
  43. package/dist/services/batch/batch-progress-store.d.ts +52 -0
  44. package/dist/services/batch/batch-progress-store.js +219 -0
  45. package/dist/services/batch/batch-progress-types.d.ts +79 -0
  46. package/dist/services/batch/batch-progress-types.js +10 -0
  47. package/dist/services/batch/batch-recovery.d.ts +5 -0
  48. package/dist/services/batch/batch-recovery.js +24 -0
  49. package/dist/services/batch/batch-verify.d.ts +93 -0
  50. package/dist/services/batch/batch-verify.js +216 -0
  51. package/dist/services/code/auto-compact-decision.d.ts +17 -0
  52. package/dist/services/code/auto-compact-decision.js +6 -0
  53. package/dist/services/code/auto-compact-orchestrator.js +6 -0
  54. package/dist/services/code/batch-compaction-point.d.ts +45 -0
  55. package/dist/services/code/batch-compaction-point.js +99 -0
  56. package/dist/services/context/context-schema.d.ts +1 -1
  57. package/dist/services/lint/curated-rule-reader.d.ts +37 -0
  58. package/dist/services/lint/curated-rule-reader.js +179 -0
  59. package/dist/services/lint/project-lint-declarations.d.ts +27 -0
  60. package/dist/services/lint/project-lint-declarations.js +217 -0
  61. package/dist/services/lint/project-lint-tool-detection.d.ts +14 -0
  62. package/dist/services/lint/project-lint-tool-detection.js +208 -0
  63. package/dist/services/lint/project-lint-tool-rules.d.ts +19 -0
  64. package/dist/services/lint/project-lint-tool-rules.js +199 -0
  65. package/dist/services/lint/rule-pre-read-types.d.ts +66 -0
  66. package/dist/services/lint/rule-pre-read-types.js +22 -0
  67. package/dist/services/lint/rule-pre-read.d.ts +20 -0
  68. package/dist/services/lint/rule-pre-read.js +145 -0
  69. package/dist/services/skill/skill-search-service.d.ts +3 -3
  70. package/package.json +5 -5
  71. package/skills/peaks-code/references/micro-cycle.md +13 -1
  72. package/skills/peaks-race-code/SKILL.md +40 -1
@@ -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
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Where one item of the batch stands.
3
+ *
4
+ * `pending` is the only state that still needs work: an item that has been
5
+ * diagnosed, fixed or verified must never be diagnosed again.
6
+ */
7
+ export type BatchItemStatus = 'pending' | 'diagnosed' | 'fixed' | 'verified';
8
+ /**
9
+ * Which stage of the four-stage batch pipeline the record is in.
10
+ *
11
+ * `phase` is the only field that says "a batch is in flight": the
12
+ * workflow-graph probe cannot see a diagnosis fan-out, so this record is that
13
+ * signal (see the design's account of the compaction gap).
14
+ */
15
+ export type BatchPhase = 'diagnosis' | 'topology' | 'fix' | 'verify' | 'done';
16
+ /**
17
+ * One independent bug (or small requirement) inside the batch.
18
+ */
19
+ export interface BatchItem {
20
+ readonly id: string;
21
+ readonly label: string;
22
+ /**
23
+ * What the user reported, in the user's words.
24
+ *
25
+ * This is the item's INPUT, not a measurement: the diagnosis prompt is
26
+ * built from it, and the report the diagnostician produces is an answer
27
+ * to it. It is kept on the record so a batch that resumes after a
28
+ * compaction can still ask the question — a record that kept only the
29
+ * label would ask the wrong one.
30
+ */
31
+ readonly symptom?: string;
32
+ readonly status: BatchItemStatus;
33
+ /**
34
+ * The repo-relative paths this item is expected to touch.
35
+ *
36
+ * A consumer compares two sets to decide whether two items may run in the
37
+ * same wave, and that comparison is exact string equality — so the set has
38
+ * to be in one canonical form before it is compared. The store keeps
39
+ * whatever it is handed; `normalizeFileSet` in the store module is the
40
+ * normalizer a caller applies before comparing.
41
+ */
42
+ readonly files: readonly string[];
43
+ /** The risk surface this item was judged to hit, when one was recorded. */
44
+ readonly riskSurface?: number;
45
+ readonly diagnosedAt?: string;
46
+ readonly fixedAt?: string;
47
+ }
48
+ /**
49
+ * The whole record for one batch.
50
+ */
51
+ export interface BatchProgress {
52
+ readonly batchId: string;
53
+ readonly phase: BatchPhase;
54
+ readonly items: readonly BatchItem[];
55
+ /** The wave plan produced by the topology stage, when it exists. */
56
+ readonly topology?: unknown;
57
+ /**
58
+ * The notice the batch recorded when it crossed its last phase
59
+ * boundary.
60
+ *
61
+ * The WORDING belongs to the batch's verification stage
62
+ * (`buildPhaseBoundaryNotice`); this record only carries it. That is
63
+ * what lets a reader with no access to that stage — the presence read,
64
+ * for one — still say what happened at the boundary, without a second
65
+ * module writing a second sentence about the same moment.
66
+ *
67
+ * Optional: a batch that crossed a boundary without recording a notice
68
+ * simply has none, and the reader falls back to the ratio sentence.
69
+ */
70
+ readonly boundaryNotice?: string;
71
+ /**
72
+ * When the record was last written.
73
+ *
74
+ * Optional in the type because the writer stamps it: a caller that does
75
+ * not care about the timestamp need not invent one, and the value on disk
76
+ * is always the writer's, never the caller's.
77
+ */
78
+ readonly updatedAt?: string;
79
+ }
@@ -0,0 +1,10 @@
1
+ // src/services/batch/batch-progress-types.ts
2
+ //
3
+ // The shape of one batch's progress record, and the vocabulary the batch
4
+ // orchestrator drives it with.
5
+ //
6
+ // WHY A SEPARATE MODULE. The store below touches the filesystem; the
7
+ // recovery helpers are pure functions over a record. Keeping the names here
8
+ // means the recovery path can be used — and tested — without importing any
9
+ // I/O.
10
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { BatchItem, BatchProgress } from './batch-progress-types.js';
2
+ /** The items whose diagnosis is still outstanding. */
3
+ export declare function pendingItems(progress: BatchProgress): readonly BatchItem[];
4
+ /** The items whose diagnosis is already behind us. */
5
+ export declare function diagnosedItems(progress: BatchProgress): readonly BatchItem[];
@@ -0,0 +1,24 @@
1
+ // src/services/batch/batch-recovery.ts
2
+ //
3
+ // What a resumed batch is allowed to do next, given the record on disk.
4
+ //
5
+ // WHY THIS IS SEPARATE FROM THE STORE. The store answers "what is on disk";
6
+ // this answers "what does that mean for the work that is left". Keeping them
7
+ // apart means the recovery rule can be read, and changed, without touching
8
+ // the file format — and the rule is the whole point of the record.
9
+ //
10
+ // THE RULE. An item is diagnosed once. `pending` is the only status that still
11
+ // needs a diagnosis; `diagnosed`, `fixed` and `verified` all mean the
12
+ // diagnosis is behind us. A batch that resumes after a compaction therefore
13
+ // diagnoses exactly the items still marked `pending`, and never re-diagnoses
14
+ // an item it already knows the root cause of.
15
+ //
16
+ // The store's merge is by item id, so this is one filter over one field.
17
+ /** The items whose diagnosis is still outstanding. */
18
+ export function pendingItems(progress) {
19
+ return progress.items.filter((item) => item.status === 'pending');
20
+ }
21
+ /** The items whose diagnosis is already behind us. */
22
+ export function diagnosedItems(progress) {
23
+ return progress.items.filter((item) => item.status !== 'pending');
24
+ }
@@ -0,0 +1,93 @@
1
+ import { type AutoCompactMode } from '../code/auto-compact-modes.js';
2
+ /**
3
+ * The acceptance gate a batch runs, ONCE: the same three legs a single task
4
+ * runs, in the same order. The batch mode amortizes the runs; it does not
5
+ * choose a different gate.
6
+ */
7
+ export declare const BATCH_ACCEPTANCE_GATE: readonly ["test", "tsc", "lint"];
8
+ /** One leg of the gate. */
9
+ export type BatchAcceptanceCheck = (typeof BATCH_ACCEPTANCE_GATE)[number];
10
+ /**
11
+ * The command that produces the build artifacts two of the legs import.
12
+ * Named here because it is the remedy a blocked leg offers.
13
+ */
14
+ export declare const BATCH_GATE_BUILD_COMMAND = "pnpm build";
15
+ /** What one leg reported. */
16
+ export interface BatchCheckOutcome {
17
+ readonly ok: boolean;
18
+ /**
19
+ * The leg's own output, in full: the artifact detector reads it, and a tail
20
+ * of a failing `tsc` run can hold a genuine type error next to the
21
+ * module-resolution errors.
22
+ */
23
+ readonly output: string;
24
+ }
25
+ /** Runs one leg of the gate, injected so a test need not spend a suite's wall clock. */
26
+ export type BatchCheckRunner = (check: BatchAcceptanceCheck) => BatchCheckOutcome;
27
+ /** One leg's result, as the verdict reports it. */
28
+ export interface BatchCheckResult {
29
+ readonly name: BatchAcceptanceCheck;
30
+ readonly ok: boolean;
31
+ readonly detail: string;
32
+ }
33
+ /**
34
+ * Which kind of breakage a red gate points at: `integration` (the batch
35
+ * itself), `single-item` (one item, named in the failing detail), or
36
+ * `unknown` (no evidence to attribute with).
37
+ */
38
+ export type BatchAttribution = 'integration' | 'single-item' | 'unknown';
39
+ /** The verdict of the unified verification. */
40
+ export interface BatchVerificationResult {
41
+ readonly gate: 'pass' | 'fail' | 'blocked';
42
+ readonly checks: readonly BatchCheckResult[];
43
+ readonly attribution: BatchAttribution;
44
+ }
45
+ /**
46
+ * The shape of a failure that is an ARTIFACT problem, not a source problem.
47
+ */
48
+ export type BatchArtifactShape = 'missing-workspace-dist' | 'build-prerequisite-refused';
49
+ /** The seam a caller may replace: how one leg is run. */
50
+ export interface BatchVerificationOptions {
51
+ readonly runCheck?: BatchCheckRunner;
52
+ }
53
+ /**
54
+ * Verify the whole batch against the acceptance gate, once. A malformed
55
+ * progress record throws rather than reading as an empty batch: the record IS
56
+ * the attribution's evidence, so losing it would turn a verdict into a guess.
57
+ */
58
+ export declare function runBatchVerification(projectRoot: string, sessionId: string, batchId: string, options?: BatchVerificationOptions): BatchVerificationResult;
59
+ /**
60
+ * The notice shown when the batch reaches a phase boundary.
61
+ *
62
+ * The wording states what the SYSTEM is doing: compaction is running, this is
63
+ * the moment its recovery cost is lowest, and the progress is already on
64
+ * disk. It never asks the user for an action, because the zero-pause
65
+ * contract makes compaction the system's job. The context ratio comes from
66
+ * `buildContextVerdict` rather than from a second reading of the number, so
67
+ * the occupancy shown and the tier the system acts on cannot disagree.
68
+ */
69
+ export declare function buildPhaseBoundaryNotice(input: {
70
+ readonly done: number;
71
+ readonly total: number;
72
+ readonly ratio?: number;
73
+ readonly mode?: AutoCompactMode;
74
+ }): string;
75
+ /**
76
+ * Is this leg's failure an ARTIFACT problem rather than a source problem?
77
+ *
78
+ * TWO SHAPES, and both are the repository's own. `missing-workspace-dist` is
79
+ * the `tsc` leg's shape: every error it reported is a module-resolution
80
+ * failure (TS2307 or TS7016) naming an internal workspace package, because
81
+ * `tsc -p tsconfig.json` resolves the packages' subpath exports into their
82
+ * `dist/` output, which no commit contains. That is the repository gate's
83
+ * own rule (.husky/gate/repo.mjs), keyed on the PROPERTY rather than on one
84
+ * spelling of the symptom: an absent build output says TS2307 and a missing
85
+ * declaration file says TS7016, and both are the same problem.
86
+ *
87
+ * `build-prerequisite-refused` is the suite's shape: it refused to start
88
+ * because the workspace build is stale, which is what the repository's own
89
+ * test preflight does (tests/_global-setup/packages-build.ts). A run that
90
+ * refused produced no results of its own, so a run that DID report results
91
+ * is not this shape.
92
+ */
93
+ export declare function detectArtifactFailure(output: string): BatchArtifactShape | null;
@@ -0,0 +1,216 @@
1
+ // src/services/batch/batch-verify.ts
2
+ //
3
+ // The unified verification: ONE acceptance gate for the whole batch.
4
+ //
5
+ // THE GATE IS THE SINGLE-TASK GATE, VERBATIM. The fast-lane norm's §1 defines
6
+ // the acceptance gate a single task runs as `test pass + tsc pass + lint
7
+ // pass`. The batch mode runs THAT gate once for the whole batch instead of
8
+ // once per item: only the COUNT changes (N runs became 1), so the strictness
9
+ // does not drop by a notch.
10
+ //
11
+ // WHY ATTRIBUTION EXISTS. A red gate has two causes: an item's own breakage,
12
+ // which the fix phase's per-item scoped test catches at the moment it
13
+ // happens, and a breakage that only appears when the items are together. The
14
+ // gate tells them apart because the fix phase ran each item's scoped test
15
+ // right after that item's fix, so the per-item outcome IS the evidence: the
16
+ // progress record appends an item as `fixed` only once that item is green.
17
+ //
18
+ // THE BUILD DEPENDENCY IS EXPLICIT. Two legs import build output: `tsc`
19
+ // resolves the workspace packages' subpath exports into `packages/*/dist`,
20
+ // and the suite imports the same packages through node_modules. That output
21
+ // is in no commit, so it is a PREREQUISITE of the gate, and the gate says so
22
+ // rather than guessing: a leg whose failure has the artifact shape is
23
+ // BLOCKED, with the build command as its remedy, and no item is named. The
24
+ // gate does not run the build itself: a verification phase that writes to the
25
+ // tree is not a verification, and the repository's own gate takes that road.
26
+ //
27
+ // THE PHASE-BOUNDARY NOTICE states what the SYSTEM is doing at the batch's
28
+ // cheapest compaction moment, and routes through the same verdict channel the
29
+ // zero-pause contract lives in, so it cannot ask the user to compact.
30
+ import { spawnSync } from 'node:child_process';
31
+ import { buildContextVerdict } from '../../cli/commands/core/skill-context-verdict.js';
32
+ import { thresholdFor } from '../code/auto-compact-modes.js';
33
+ import { readBatchProgress } from './batch-progress-store.js';
34
+ /**
35
+ * The acceptance gate a batch runs, ONCE: the same three legs a single task
36
+ * runs, in the same order. The batch mode amortizes the runs; it does not
37
+ * choose a different gate.
38
+ */
39
+ export const BATCH_ACCEPTANCE_GATE = ['test', 'tsc', 'lint'];
40
+ /**
41
+ * The command that produces the build artifacts two of the legs import.
42
+ * Named here because it is the remedy a blocked leg offers.
43
+ */
44
+ export const BATCH_GATE_BUILD_COMMAND = 'pnpm build';
45
+ /** The command each leg runs, in the repository's own terms. */
46
+ const GATE_COMMANDS = {
47
+ test: 'pnpm test',
48
+ tsc: 'pnpm exec tsc -p tsconfig.json --noEmit',
49
+ lint: 'pnpm lint'
50
+ };
51
+ /** How many lines of a failing leg's output the detail carries. */
52
+ const FAILURE_DETAIL_LINES = 20;
53
+ /** How much output a leg may produce before the runner refuses to buffer it. */
54
+ // eslint-disable-next-line no-magic-numbers -- a byte count, not a policy number
55
+ const MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
56
+ /** The repository's own sentence for a suite that refused to start. */
57
+ const BUILD_PREREQUISITE_REFUSAL = 'Test suite refused to start:';
58
+ /**
59
+ * Verify the whole batch against the acceptance gate, once. A malformed
60
+ * progress record throws rather than reading as an empty batch: the record IS
61
+ * the attribution's evidence, so losing it would turn a verdict into a guess.
62
+ */
63
+ export function runBatchVerification(projectRoot, sessionId, batchId, options = {}) {
64
+ const runCheck = options.runCheck ?? ((check) => runLeg(check, projectRoot));
65
+ const checks = [];
66
+ let blocked = false;
67
+ for (const check of BATCH_ACCEPTANCE_GATE) {
68
+ let outcome;
69
+ try {
70
+ outcome = runCheck(check);
71
+ }
72
+ catch (error) {
73
+ // A leg that never produced a verdict is not a red leg: nothing is
74
+ // known about the leg at all.
75
+ blocked = true;
76
+ outcome = { ok: false, output: `could not run: ${describeError(error)}` };
77
+ }
78
+ const shape = outcome.ok ? null : detectArtifactFailure(outcome.output);
79
+ if (shape !== null)
80
+ blocked = true;
81
+ checks.push({
82
+ name: check,
83
+ ok: outcome.ok,
84
+ detail: shape === null ? tail(outcome.output) : blockedDetail(shape)
85
+ });
86
+ }
87
+ const gate = blocked ? 'blocked' : checks.every((check) => check.ok) ? 'pass' : 'fail';
88
+ const progress = readBatchProgress(projectRoot, sessionId, batchId);
89
+ const offenders = offendersOf(progress);
90
+ const attribution = decideAttribution(gate, progress, offenders);
91
+ return {
92
+ gate,
93
+ checks: nameOffenders(checks, offenders, attribution),
94
+ attribution
95
+ };
96
+ }
97
+ /**
98
+ * The notice shown when the batch reaches a phase boundary.
99
+ *
100
+ * The wording states what the SYSTEM is doing: compaction is running, this is
101
+ * the moment its recovery cost is lowest, and the progress is already on
102
+ * disk. It never asks the user for an action, because the zero-pause
103
+ * contract makes compaction the system's job. The context ratio comes from
104
+ * `buildContextVerdict` rather than from a second reading of the number, so
105
+ * the occupancy shown and the tier the system acts on cannot disagree.
106
+ */
107
+ export function buildPhaseBoundaryNotice(input) {
108
+ const mode = input.mode ?? 'standard';
109
+ const ratio = input.ratio ?? thresholdFor(mode, 'autoFire');
110
+ const verdict = buildContextVerdict(ratio, mode);
111
+ return `诊断完成(${input.done}/${input.total} 项);正在压缩 —— 恢复成本最低的时点,进度已落盘(上下文 ${verdict.context.ratioPct})`;
112
+ }
113
+ /**
114
+ * Is this leg's failure an ARTIFACT problem rather than a source problem?
115
+ *
116
+ * TWO SHAPES, and both are the repository's own. `missing-workspace-dist` is
117
+ * the `tsc` leg's shape: every error it reported is a module-resolution
118
+ * failure (TS2307 or TS7016) naming an internal workspace package, because
119
+ * `tsc -p tsconfig.json` resolves the packages' subpath exports into their
120
+ * `dist/` output, which no commit contains. That is the repository gate's
121
+ * own rule (.husky/gate/repo.mjs), keyed on the PROPERTY rather than on one
122
+ * spelling of the symptom: an absent build output says TS2307 and a missing
123
+ * declaration file says TS7016, and both are the same problem.
124
+ *
125
+ * `build-prerequisite-refused` is the suite's shape: it refused to start
126
+ * because the workspace build is stale, which is what the repository's own
127
+ * test preflight does (tests/_global-setup/packages-build.ts). A run that
128
+ * refused produced no results of its own, so a run that DID report results
129
+ * is not this shape.
130
+ */
131
+ export function detectArtifactFailure(output) {
132
+ const errors = output.split('\n').filter((line) => /error TS\d+/.test(line));
133
+ if (errors.length > 0 && errors.every(isMissingWorkspaceModule)) {
134
+ return 'missing-workspace-dist';
135
+ }
136
+ if (output.includes(BUILD_PREREQUISITE_REFUSAL) && !hasTestResults(output)) {
137
+ return 'build-prerequisite-refused';
138
+ }
139
+ return null;
140
+ }
141
+ /**
142
+ * Run one leg through the repository's own command. The command strings are
143
+ * constants and the working directory travels as the child's `cwd`, so
144
+ * nothing a caller supplies reaches a shell.
145
+ */
146
+ function runLeg(check, projectRoot) {
147
+ const result = spawnSync(GATE_COMMANDS[check], {
148
+ cwd: projectRoot,
149
+ shell: true,
150
+ encoding: 'utf8',
151
+ windowsHide: true,
152
+ maxBuffer: MAX_OUTPUT_BYTES
153
+ });
154
+ if (result.error !== undefined)
155
+ throw result.error;
156
+ if (result.status === 0)
157
+ return { ok: true, output: 'passed' };
158
+ return { ok: false, output: `${result.stdout ?? ''}${result.stderr ?? ''}` };
159
+ }
160
+ /** A module-resolution failure naming an internal workspace package. */
161
+ function isMissingWorkspaceModule(line) {
162
+ return /error TS(?:2307|7016)/.test(line) && /'peaks-loop-[^']*'/.test(line);
163
+ }
164
+ /** Did the suite report results of its own? A refused run reported none. */
165
+ function hasTestResults(output) {
166
+ return /Test Files\s+\d/.test(output);
167
+ }
168
+ /** What a blocked leg says: the reason, the remedy, and no item. */
169
+ function blockedDetail(shape) {
170
+ const why = shape === 'missing-workspace-dist'
171
+ ? 'every error is a module-resolution failure naming an internal workspace package, which resolves into untracked build output'
172
+ : 'the suite refused to start because the workspace build is stale';
173
+ return `blocked — ${why}. Run \`${BATCH_GATE_BUILD_COMMAND}\` first, then re-run.`;
174
+ }
175
+ /** The last lines of a leg's output: enough to see what failed. */
176
+ function tail(output) {
177
+ const lines = output.trim().split('\n');
178
+ return lines.slice(-FAILURE_DETAIL_LINES).join('\n');
179
+ }
180
+ /** The items whose own scoped test was not green. */
181
+ function offendersOf(progress) {
182
+ if (progress === null)
183
+ return [];
184
+ return progress.items.filter((item) => item.status !== 'fixed' && item.status !== 'verified');
185
+ }
186
+ /** Which kind of breakage the verdict points at. */
187
+ function decideAttribution(gate, progress, offenders) {
188
+ if (gate === 'pass')
189
+ return 'integration';
190
+ if (gate === 'blocked')
191
+ return 'unknown';
192
+ if (progress === null || progress.items.length === 0)
193
+ return 'unknown';
194
+ return offenders.length === 0 ? 'integration' : 'single-item';
195
+ }
196
+ /**
197
+ * Put the culprit's name into the failing legs' details: a red gate that
198
+ * does not say which item is at fault sends the reader back to the whole
199
+ * batch to find out. A BLOCKED gate never reaches here, because nothing is
200
+ * known about the leg and so nothing may be blamed on an item.
201
+ */
202
+ function nameOffenders(checks, offenders, attribution) {
203
+ if (attribution !== 'single-item' || offenders.length === 0)
204
+ return checks;
205
+ const names = offenders.map((item) => `${item.id} (${item.label})`).join(', ');
206
+ return checks.map((check) => check.ok
207
+ ? check
208
+ : {
209
+ ...check,
210
+ detail: `${check.detail} — item(s) not green at their own scoped test: ${names}`
211
+ });
212
+ }
213
+ /** An error's message, whatever it turned out to be. */
214
+ function describeError(error) {
215
+ return error instanceof Error ? error.message : String(error);
216
+ }
@@ -44,6 +44,23 @@ export declare function evaluateAutoCompactDecision(input: {
44
44
  /** Accepted and ignored — see `AutoCompactInput.bypassRedLine`. */
45
45
  bypassRedLine?: boolean | undefined;
46
46
  mode?: AutoCompactMode | undefined;
47
+ /**
48
+ * Whether the batch in flight has crossed a COMPACTION BOUNDARY — the
49
+ * ①→② or ③→④ transition of the batch's four stages.
50
+ *
51
+ * Why this exists. The in-flight-batch branch below DEFERS a compaction
52
+ * while a batch is running, because compacting in the middle of a fan-out
53
+ * interrupts the agents. But a batch is "in flight" for its whole life,
54
+ * so the deferral postpones the compaction for the whole batch — and the
55
+ * window is at its worst exactly then, because N reports arrive
56
+ * together. At a boundary that is false: the stage's agents are done, its
57
+ * results are on disk, and the recovery cost is the lowest it will be.
58
+ * So at a boundary the compaction happens NOW instead of being deferred.
59
+ *
60
+ * Absent (the default), the behaviour is EXACTLY what it was: a batch in
61
+ * flight defers, and nothing else changes.
62
+ */
63
+ atPhaseBoundary?: boolean | undefined;
47
64
  /**
48
65
  * Source tag from `readContextPercent.source`. Optional — when absent, the
49
66
  * function behaves exactly as pre-rid (ratio-only). Slice 2026-07-31-rid-