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,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-
@@ -110,6 +110,12 @@ export function evaluateAutoCompactDecision(input) {
110
110
  }
111
111
  // pre-compact zone (0.85 ≤ ratio < 0.95): honor D6.e in-flight deferral.
112
112
  if (probe?.hasInFlightBatch === true) {
113
+ // A phase boundary is the batch's BEST compaction point, not a reason to
114
+ // wait: the stage's agents are done, its results are on disk, and the
115
+ // window is heaviest right there. So the deferral does not apply.
116
+ if (input.atPhaseBoundary === true) {
117
+ return { shouldCompact: true, reason: 'pre-compact', trigger, action: 'auto-compact-now' };
118
+ }
113
119
  return { shouldCompact: false, reason: 'in-flight-batch', trigger, action: 'defer' };
114
120
  }
115
121
  if (input.force) {
@@ -26,6 +26,7 @@
26
26
  * and the envelopes in `auto-compact-envelopes.js`.
27
27
  */
28
28
  import { getSessionIdCanonical } from '../session/session-manager.js';
29
+ import { resolveBatchCompactionBoundary } from '../batch/batch-active-batch.js';
29
30
  import { resolveOuterSessionId } from '../session/binding-status-service.js';
30
31
  import { resolveCanonicalProjectRoot } from '../config/config-service.js';
31
32
  import { thresholdFor } from './auto-compact-modes.js';
@@ -182,6 +183,11 @@ async function openRun(input, sessionId, mode) {
182
183
  force: input.force,
183
184
  bypassRedLine: input.bypassRedLine,
184
185
  mode,
186
+ // A batch at a compaction boundary is the batch's BEST compaction
187
+ // point: the stage's agents are done and its results are on disk, so
188
+ // the in-flight deferral must not apply there. Absent a batch, this
189
+ // is `false` and the behaviour is exactly what it was.
190
+ atPhaseBoundary: resolveBatchCompactionBoundary(input.projectRoot, sessionId),
185
191
  // Tagged through so the decision can apply the source-aware carve-out for Mac's
186
192
  // `transcript-estimate` signal.
187
193
  source: probe.source
@@ -0,0 +1,45 @@
1
+ import type { BatchPhase } from '../batch/batch-progress-types.js';
2
+ import type { AutoCompactMode } from './auto-compact-modes.js';
3
+ /** Which rule decided the compaction point. */
4
+ export type BatchCompactionKind = 'silent' | 'ratio' | 'phase-boundary' | 'red-line';
5
+ /**
6
+ * The decision, in the shape the caller acts on.
7
+ *
8
+ * `action` uses the same vocabulary as `evaluateAutoCompactDecision`, so a
9
+ * caller that already handles that action handles this one.
10
+ */
11
+ export interface BatchCompactionPoint {
12
+ readonly kind: BatchCompactionKind;
13
+ readonly shouldCompact: boolean;
14
+ readonly action: 'ok' | 'soft-warn' | 'auto-compact-now' | 'red-line';
15
+ readonly ratio: number;
16
+ /** Whether the batch is crossing one of the two compaction boundaries. */
17
+ readonly atBoundary: boolean;
18
+ }
19
+ /**
20
+ * The two phase transitions that are a compaction boundary.
21
+ *
22
+ * ①→② is the diagnosis giving way to the topology, ③→④ the fix giving
23
+ * way to the verification. The other two transitions (②→③, ④→done) are
24
+ * not boundaries: neither of them is followed by a stage that reads the
25
+ * stage before it back.
26
+ *
27
+ * @param fromPhase - The phase the batch was in.
28
+ * @param toPhase - The phase the batch is in now.
29
+ */
30
+ export declare function isBatchPhaseBoundary(fromPhase: BatchPhase, toPhase: BatchPhase): boolean;
31
+ /**
32
+ * Decide the batch's compaction point.
33
+ *
34
+ * @param input.ratio - The context ratio, 0..1.
35
+ * @param input.fromPhase - The phase the batch was in.
36
+ * @param input.toPhase - The phase the batch is in now; the same value as
37
+ * `fromPhase` when no transition happened.
38
+ * @param input.mode - The auto-compact mode; the thresholds come from it.
39
+ */
40
+ export declare function decideBatchCompactionPoint(input: {
41
+ readonly ratio: number;
42
+ readonly fromPhase: BatchPhase;
43
+ readonly toPhase: BatchPhase;
44
+ readonly mode?: AutoCompactMode;
45
+ }): BatchCompactionPoint;
@@ -0,0 +1,99 @@
1
+ // src/services/code/batch-compaction-point.ts
2
+ //
3
+ // WHEN a batch compacts. The compaction thresholds are not this file's to
4
+ // set: `evaluateCompactTrigger` already owns 0.80 / 0.85 / 0.95, and this
5
+ // file reads them.
6
+ //
7
+ // WHY THE COMPACTION POINT IS A PHASE BOUNDARY AND A RATIO. The batch's
8
+ // four phases end in two boundaries that are the cheapest moments to
9
+ // compact at: ①→② (diagnosis → topology) and ③→④ (fix → verify). At ①→②
10
+ // the N diagnosis reports have just been produced; at ③→④ the N fixes
11
+ // have just landed. Both are moments where the batch's own state is on
12
+ // disk (the progress record) and the window is at its heaviest — which is
13
+ // exactly why compacting there costs least and buys most. §7A.4 of the
14
+ // design calls the boundary the preferred compaction point; this file is
15
+ // how that preference is decided.
16
+ //
17
+ // THE THREE CASES, AND WHAT IS NOT CHANGED.
18
+ // - ratio ≥ red line (0.95): the red line. Unchanged, and the boundary
19
+ // does not defer it — at the red line the harness is asked NOW,
20
+ // because waiting for a boundary is how a window overflows.
21
+ // - ratio ≥ auto-fire (0.80) at a boundary: the boundary. This is the
22
+ // best point, so the compaction is attributed to it.
23
+ // - ratio ≥ auto-fire (0.80) away from a boundary: the existing
24
+ // auto-compact contract, unchanged. It compresses by itself; it never
25
+ // asks the user.
26
+ //
27
+ // WHY NOTHING IS DEFERRED. Deferring a compaction to the next boundary is
28
+ // what the existing in-flight-batch deferral did, and it is why a batch's
29
+ // window was systematically compressed too late: the reports arrive
30
+ // together, so the window is already at its worst before the boundary
31
+ // arrives. This file never says "wait" — it says where the compaction
32
+ // happens.
33
+ import { evaluateCompactTrigger } from './auto-compact-decision.js';
34
+ /**
35
+ * The two phase transitions that are a compaction boundary.
36
+ *
37
+ * ①→② is the diagnosis giving way to the topology, ③→④ the fix giving
38
+ * way to the verification. The other two transitions (②→③, ④→done) are
39
+ * not boundaries: neither of them is followed by a stage that reads the
40
+ * stage before it back.
41
+ *
42
+ * @param fromPhase - The phase the batch was in.
43
+ * @param toPhase - The phase the batch is in now.
44
+ */
45
+ export function isBatchPhaseBoundary(fromPhase, toPhase) {
46
+ return ((fromPhase === 'diagnosis' && toPhase === 'topology') ||
47
+ (fromPhase === 'fix' && toPhase === 'verify'));
48
+ }
49
+ /**
50
+ * Decide the batch's compaction point.
51
+ *
52
+ * @param input.ratio - The context ratio, 0..1.
53
+ * @param input.fromPhase - The phase the batch was in.
54
+ * @param input.toPhase - The phase the batch is in now; the same value as
55
+ * `fromPhase` when no transition happened.
56
+ * @param input.mode - The auto-compact mode; the thresholds come from it.
57
+ */
58
+ export function decideBatchCompactionPoint(input) {
59
+ const mode = input.mode ?? 'standard';
60
+ const atBoundary = isBatchPhaseBoundary(input.fromPhase, input.toPhase);
61
+ // The trigger owns the thresholds. This file only asks which zone the
62
+ // ratio is in and whether the batch is at a boundary.
63
+ const trigger = evaluateCompactTrigger(input.ratio, mode);
64
+ const inAutoZone = trigger.kind === 'auto-fire' || trigger.kind === 'pre-compact';
65
+ if (trigger.kind === 'red-line') {
66
+ return {
67
+ kind: 'red-line',
68
+ shouldCompact: true,
69
+ action: 'red-line',
70
+ ratio: input.ratio,
71
+ atBoundary
72
+ };
73
+ }
74
+ if (atBoundary && inAutoZone) {
75
+ return {
76
+ kind: 'phase-boundary',
77
+ shouldCompact: true,
78
+ action: 'auto-compact-now',
79
+ ratio: input.ratio,
80
+ atBoundary
81
+ };
82
+ }
83
+ if (inAutoZone) {
84
+ return {
85
+ kind: 'ratio',
86
+ shouldCompact: true,
87
+ action: 'auto-compact-now',
88
+ ratio: input.ratio,
89
+ atBoundary
90
+ };
91
+ }
92
+ return {
93
+ kind: 'silent',
94
+ shouldCompact: false,
95
+ action: trigger.kind === 'soft-warn' ? 'soft-warn' : 'ok',
96
+ ratio: input.ratio,
97
+ atBoundary
98
+ };
99
+ }
@@ -14,8 +14,8 @@ export declare const ContextJsonSchema: z.ZodObject<{
14
14
  kind: z.ZodEnum<{
15
15
  doc: "doc";
16
16
  source: "source";
17
- config: "config";
18
17
  test: "test";
18
+ config: "config";
19
19
  }>;
20
20
  lines: z.ZodNumber;
21
21
  hash: z.ZodString;