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
@@ -3,6 +3,7 @@
3
3
  // renders the advisory `nextActions`; it never compacts.
4
4
  import { readContextPercent } from '../../../services/context/auto-compact-reader.js';
5
5
  import { evaluateCompactTrigger } from '../../../services/code/auto-compact-orchestrator.js';
6
+ import { resolveBatchPresenceReminder } from '../../../services/batch/batch-context-reminder.js';
6
7
  import { resolveAutoCompactProfile } from '../../../services/mode/mode-status-service.js';
7
8
  import { getSessionId } from '../../../services/session/session-manager.js';
8
9
  import { resolveOuterSessionId } from '../../../services/session/binding-status-service.js';
@@ -24,23 +25,41 @@ import { resolveOuterSessionId } from '../../../services/session/binding-status-
24
25
  * Executing `peaks code auto-compact` stays the skill's own action — a
25
26
  * side effect here would fire on every single turn.
26
27
  *
28
+ * THE ONE WRITE. The batch reminder records the phase it last spoke in,
29
+ * so the batch says its reminder once per phase instead of once per turn.
30
+ * That marker is written only when the phase changed or when the batch
31
+ * spoke, and it lives in the batch's own directory under the session —
32
+ * never in the presence marker itself.
33
+ *
27
34
  * Failure swallows to `null`: the hygiene verdict is advisory and must
28
35
  * never be able to break the presence read itself.
36
+ *
37
+ * THE BATCH REMINDER IS CARRIED HERE TOO. A batch's context reminder (the
38
+ * ratio zone, the phase boundary) is another statement about the window,
39
+ * and it reaches the model through the same carrier — so a batch sentence
40
+ * cannot bypass the zero-pause contract by living somewhere else. The
41
+ * sentence itself is built by the batch module (it owns the wording); it
42
+ * is APPENDED here, and it states a fact rather than asking anybody to do
43
+ * anything.
29
44
  */
30
- export function buildContextVerdict(ratio, mode) {
45
+ export function buildContextVerdict(ratio, mode, batch) {
31
46
  const trigger = evaluateCompactTrigger(ratio, mode);
32
47
  const ratioPct = `${(ratio * 100).toFixed(1)}%`;
33
48
  // `auto-fire` belongs in the in-zone set: it is the tier where
34
49
  // peaks-loop preempts rather than asking the LLM to decide.
35
50
  const inZone = trigger.kind === 'auto-fire' || trigger.kind === 'pre-compact' || trigger.kind === 'red-line';
51
+ const nextActions = inZone
52
+ ? [
53
+ `Context at ${ratioPct} is in the '${trigger.kind}' zone (mode=${mode}).`,
54
+ 'Run `peaks code auto-compact --project .` YOURSELF now, then continue. Do NOT ask the user to run /compact — that is the regression the zero-pause contract forbids.'
55
+ ]
56
+ : [];
57
+ if (batch !== null && batch !== undefined && batch.text.length > 0) {
58
+ nextActions.push(batch.text);
59
+ }
36
60
  return {
37
61
  context: { ratioPct, action: trigger.kind, mode },
38
- nextActions: inZone
39
- ? [
40
- `Context at ${ratioPct} is in the '${trigger.kind}' zone (mode=${mode}).`,
41
- 'Run `peaks code auto-compact --project .` YOURSELF now, then continue. Do NOT ask the user to run /compact — that is the regression the zero-pause contract forbids.'
42
- ]
43
- : []
62
+ nextActions
44
63
  };
45
64
  }
46
65
  export function contextVerdict(projectRoot) {
@@ -55,7 +74,18 @@ export function contextVerdict(projectRoot) {
55
74
  // any threshold. Same resolution order the orchestrator uses.
56
75
  const outerSessionId = resolveOuterSessionId(projectRoot, sessionId, process.env);
57
76
  const probe = readContextPercent({ projectRoot, sessionId, outerSessionId, env: process.env });
58
- return buildContextVerdict(probe.ratio, mode);
77
+ // The batch reminder rides the same carrier as the zone instruction:
78
+ // the batch in flight is found among the session's batch records, and
79
+ // its sentence is a statement about the window, not a request. It is
80
+ // resolved INSIDE this try — the batch lookup reads files, and a
81
+ // corrupt batch record must not be able to break the presence read.
82
+ const batch = resolveBatchPresenceReminder({
83
+ projectRoot,
84
+ sessionId,
85
+ ratio: probe.ratio,
86
+ mode
87
+ });
88
+ return buildContextVerdict(probe.ratio, mode, batch);
59
89
  }
60
90
  catch {
61
91
  return { context: null, nextActions: [] };
@@ -5,6 +5,7 @@ import { fail, ok } from 'peaks-loop-shared/result';
5
5
  import { detectEslint } from '../../services/lint/detect-eslint.js';
6
6
  import { runEslint } from '../../services/lint/eslint-runner.js';
7
7
  import { emitBaseline } from './lint-baseline-command.js';
8
+ import { emitRules } from './lint-rules-command.js';
8
9
  function parseTimeoutMs(value) {
9
10
  if (value === undefined)
10
11
  return undefined;
@@ -128,4 +129,11 @@ export function registerLintCommands(program, io) {
128
129
  }
129
130
  emitBaseline(io, options, timeoutMs);
130
131
  });
132
+ addJsonOption(lint
133
+ .command('rules')
134
+ .description("Read the rules in force for a file set: the project's own lint tooling, the language rule channel, and the curated rule sets.")
135
+ .option('--files <files...>', 'the files to read the rules for')
136
+ .option('--project <repo>', 'the project root (default: the current directory)')).action((options) => {
137
+ emitRules(io, options);
138
+ });
131
139
  }
@@ -0,0 +1,14 @@
1
+ import { type ProgramIO } from '../cli-helpers.js';
2
+ /** The `peaks lint rules` options. */
3
+ export type RulesOptions = {
4
+ files?: string[];
5
+ project?: string;
6
+ json?: boolean;
7
+ };
8
+ /**
9
+ * Read the rules in force for a file set and print them.
10
+ *
11
+ * The project root defaults to the current directory and is resolved against
12
+ * it, so a relative `--project` means what the user typed.
13
+ */
14
+ export declare function emitRules(io: ProgramIO, options: RulesOptions): void;
@@ -0,0 +1,44 @@
1
+ // src/cli/commands/lint-rules-command.ts
2
+ //
3
+ // `peaks lint rules` — the CLI surface of the rule pre-read.
4
+ //
5
+ // It answers one question for a given file set: what are the rules in force?
6
+ // The answer has three parts, and each rule names the layer it came from —
7
+ // the project's own lint tooling, the language rule channel, the curated rule
8
+ // sets. A reader that cannot tell the layers apart cannot act on them.
9
+ //
10
+ // THE REFUSAL IS THE POINT. A call with no files is REFUSED with a named
11
+ // code rather than answered with an empty rule set: "you named no files" and
12
+ // "there are no rules" are different answers, and only one of them is a
13
+ // finding about the code.
14
+ //
15
+ // The read itself lives in `src/services/lint/rule-pre-read.ts`; this file is
16
+ // the verb around it, nothing more.
17
+ import { resolve } from 'node:path';
18
+ import { printResult } from '../cli-helpers.js';
19
+ import { fail, ok } from 'peaks-loop-shared/result';
20
+ import { readEffectiveRules, RULES_RESOLVED_REASON } from '../../services/lint/rule-pre-read.js';
21
+ /**
22
+ * Read the rules in force for a file set and print them.
23
+ *
24
+ * The project root defaults to the current directory and is resolved against
25
+ * it, so a relative `--project` means what the user typed.
26
+ */
27
+ export function emitRules(io, options) {
28
+ const files = options.files ?? [];
29
+ if (files.length === 0) {
30
+ printResult(io, fail('code.lint.rules', 'NO_FILES', 'No files were given, so there is nothing to read the rules for.', { files: [] }, ['Pass the files to read: --files <file...>']), options.json);
31
+ process.exitCode = 1;
32
+ return;
33
+ }
34
+ const cwd = process.cwd();
35
+ const projectRoot = options.project === undefined ? cwd : resolve(cwd, options.project);
36
+ const ruleSet = readEffectiveRules(projectRoot, files);
37
+ // The reason names every layer that could not be read. A read that found
38
+ // nothing because a layer never ran must not read as a read that found
39
+ // nothing wrong.
40
+ const warnings = ruleSet.reason === RULES_RESOLVED_REASON ? [] : [ruleSet.reason];
41
+ printResult(io, ok('code.lint.rules', ruleSet, warnings, [
42
+ 'Each rule names the layer it came from: project, language, or curated.'
43
+ ]), options.json);
44
+ }
@@ -0,0 +1,55 @@
1
+ import type { BatchProgress } from './batch-progress-types.js';
2
+ /** The batch that is running, and the record that says so. */
3
+ export interface ActiveBatch {
4
+ readonly batchId: string;
5
+ readonly progress: BatchProgress;
6
+ }
7
+ /**
8
+ * The ids of the batches this session holds a record for.
9
+ *
10
+ * This function only READS a directory, so it does not throw. A session id
11
+ * that is not one safe path segment is refused by `getSessionDir` — and
12
+ * refusing to LOOK is the whole answer here: there are no batches to list.
13
+ * The refusal still stands for everything that WRITES under the session
14
+ * directory; this is a reader.
15
+ *
16
+ * @returns The ids, or an empty list when the session has no batches.
17
+ */
18
+ export declare function listBatchIds(projectRoot: string, sessionId: string): readonly string[];
19
+ /**
20
+ * The batch that is in flight, if one is.
21
+ *
22
+ * @returns The running batch, or `null` when the session holds no batch,
23
+ * only finished batches, or only records that cannot be read.
24
+ */
25
+ export declare function findActiveBatch(projectRoot: string, sessionId: string): ActiveBatch | null;
26
+ /**
27
+ * Whether a batch record is at a COMPACTION BOUNDARY.
28
+ *
29
+ * The batch's phase machine is linear — diagnosis → topology → fix → verify
30
+ * → done — so the phase alone says whether a boundary has been crossed: a
31
+ * batch in `topology` has just crossed ①→②, and a batch in `verify` has
32
+ * just crossed ③→④. In both cases the stage that just finished has its
33
+ * results on disk and its agents are done, which is exactly the moment
34
+ * compaction is cheapest: the recovery cost is the lowest it will be, and
35
+ * the window is at its heaviest.
36
+ *
37
+ * A batch in `diagnosis` or `fix` is mid-stage, with agents in flight: that
38
+ * is the case the existing in-flight deferral is for.
39
+ */
40
+ export declare function isBatchAtCompactionBoundary(progress: BatchProgress): boolean;
41
+ /**
42
+ * Whether a batch in this project is at a compaction boundary.
43
+ *
44
+ * THIS FUNCTION NEVER THROWS. It is called on EVERY auto-compact run, and
45
+ * the batch lookup is ADVISORY: a batch in flight is a hint about the
46
+ * cheapest moment to compact, never a precondition for compacting. So a
47
+ * failure to determine whether a batch is at a boundary means "assume not
48
+ * at a boundary" — the compaction path carries on exactly as it did before
49
+ * this lookup existed.
50
+ *
51
+ * Fail-safe: `false` when there is no batch in flight, when its record
52
+ * cannot be read, when the session id is not usable, and when the batch is
53
+ * mid-stage.
54
+ */
55
+ export declare function resolveBatchCompactionBoundary(projectRoot: string, sessionId: string): boolean;
@@ -0,0 +1,127 @@
1
+ // src/services/batch/batch-active-batch.ts
2
+ //
3
+ // WHICH BATCH is in flight, for a reader that has only a session.
4
+ //
5
+ // WHY THIS EXISTS. The context reminder (see `batch-context-reminder.ts`)
6
+ // has to be attached to a presence read, and a presence read knows the
7
+ // SESSION — not the batch. The batch's records live under the session, one
8
+ // directory per batch, so the batch in flight is found there.
9
+ //
10
+ // THE RULE. A batch that has reached the `done` phase is finished: it is
11
+ // not in flight, and a finished batch must never make the presence read
12
+ // report a reminder. Among the batches that are still running, the one
13
+ // written most recently is the one in flight — a session may hold several
14
+ // batches' records, and the newest record is the batch the orchestrator
15
+ // last touched.
16
+ //
17
+ // A RECORD THAT CANNOT BE READ IS NOT A BATCH IN FLIGHT. The progress
18
+ // store fails loud on a malformed record, and that is right for the
19
+ // batch's own recovery path — a batch that silently lost its history
20
+ // restarts work it had already done. Here the question is different: "is
21
+ // a batch running right now?" — and a record that cannot be read cannot
22
+ // answer it. Such a record is skipped, so a corrupt file cannot make the
23
+ // presence read report a reminder for a batch nobody can see.
24
+ import { readdirSync } from 'node:fs';
25
+ import { join } from 'node:path';
26
+ import { getSessionDir } from '../session/getSessionDir.js';
27
+ import { readBatchProgress } from './batch-progress-store.js';
28
+ const BATCH_DIR = 'batch';
29
+ /**
30
+ * The ids of the batches this session holds a record for.
31
+ *
32
+ * This function only READS a directory, so it does not throw. A session id
33
+ * that is not one safe path segment is refused by `getSessionDir` — and
34
+ * refusing to LOOK is the whole answer here: there are no batches to list.
35
+ * The refusal still stands for everything that WRITES under the session
36
+ * directory; this is a reader.
37
+ *
38
+ * @returns The ids, or an empty list when the session has no batches.
39
+ */
40
+ export function listBatchIds(projectRoot, sessionId) {
41
+ try {
42
+ const dir = join(getSessionDir(projectRoot, sessionId), BATCH_DIR);
43
+ return readdirSync(dir, { withFileTypes: true })
44
+ .filter((entry) => entry.isDirectory())
45
+ .map((entry) => entry.name);
46
+ }
47
+ catch {
48
+ // A session with no batch directory has no batches. That is an
49
+ // answer, not a failure.
50
+ return [];
51
+ }
52
+ }
53
+ /**
54
+ * The batch that is in flight, if one is.
55
+ *
56
+ * @returns The running batch, or `null` when the session holds no batch,
57
+ * only finished batches, or only records that cannot be read.
58
+ */
59
+ export function findActiveBatch(projectRoot, sessionId) {
60
+ const candidates = [];
61
+ for (const batchId of listBatchIds(projectRoot, sessionId)) {
62
+ let progress;
63
+ try {
64
+ progress = readBatchProgress(projectRoot, sessionId, batchId);
65
+ }
66
+ catch {
67
+ continue;
68
+ }
69
+ if (progress === null)
70
+ continue;
71
+ if (progress.phase === 'done')
72
+ continue;
73
+ candidates.push({ batchId, progress });
74
+ }
75
+ if (candidates.length === 0)
76
+ return null;
77
+ // The most recently written record is the batch the orchestrator last
78
+ // touched. The id breaks a tie, so the answer does not depend on the
79
+ // order the directory happened to be read in.
80
+ candidates.sort((left, right) => {
81
+ const byTime = (right.progress.updatedAt ?? '').localeCompare(left.progress.updatedAt ?? '');
82
+ if (byTime !== 0)
83
+ return byTime;
84
+ return left.batchId.localeCompare(right.batchId);
85
+ });
86
+ return candidates[0];
87
+ }
88
+ /**
89
+ * Whether a batch record is at a COMPACTION BOUNDARY.
90
+ *
91
+ * The batch's phase machine is linear — diagnosis → topology → fix → verify
92
+ * → done — so the phase alone says whether a boundary has been crossed: a
93
+ * batch in `topology` has just crossed ①→②, and a batch in `verify` has
94
+ * just crossed ③→④. In both cases the stage that just finished has its
95
+ * results on disk and its agents are done, which is exactly the moment
96
+ * compaction is cheapest: the recovery cost is the lowest it will be, and
97
+ * the window is at its heaviest.
98
+ *
99
+ * A batch in `diagnosis` or `fix` is mid-stage, with agents in flight: that
100
+ * is the case the existing in-flight deferral is for.
101
+ */
102
+ export function isBatchAtCompactionBoundary(progress) {
103
+ return progress.phase === 'topology' || progress.phase === 'verify';
104
+ }
105
+ /**
106
+ * Whether a batch in this project is at a compaction boundary.
107
+ *
108
+ * THIS FUNCTION NEVER THROWS. It is called on EVERY auto-compact run, and
109
+ * the batch lookup is ADVISORY: a batch in flight is a hint about the
110
+ * cheapest moment to compact, never a precondition for compacting. So a
111
+ * failure to determine whether a batch is at a boundary means "assume not
112
+ * at a boundary" — the compaction path carries on exactly as it did before
113
+ * this lookup existed.
114
+ *
115
+ * Fail-safe: `false` when there is no batch in flight, when its record
116
+ * cannot be read, when the session id is not usable, and when the batch is
117
+ * mid-stage.
118
+ */
119
+ export function resolveBatchCompactionBoundary(projectRoot, sessionId) {
120
+ try {
121
+ const active = findActiveBatch(projectRoot, sessionId);
122
+ return active !== null && isBatchAtCompactionBoundary(active.progress);
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ }
@@ -0,0 +1,85 @@
1
+ import type { AutoCompactMode } from '../code/auto-compact-modes.js';
2
+ /**
3
+ * The red-line sentence.
4
+ *
5
+ * It states what the system is doing and what is NOT blocked, so the
6
+ * reader does not read the red line as a stop. It asks for nothing.
7
+ */
8
+ export declare const BATCH_CONTEXT_RED_LINE_NOTICE = "\u5DF2\u8BF7\u6C42 harness \u538B\u7F29\uFF0C\u7B49\u5F85\u4E2D\uFF1B\u6D3E\u53D1\u672A\u963B\u585E";
9
+ /**
10
+ * The zone sentence for a ratio that has entered the auto-compact zone.
11
+ *
12
+ * @param ratio - The context ratio, 0..1.
13
+ */
14
+ export declare function batchContextRatioNotice(ratio: number): string;
15
+ /** What kind of reminder this is. */
16
+ export type BatchReminderKind = 'ratio' | 'phase-boundary' | 'red-line';
17
+ /** One reminder: what kind, and the sentence. */
18
+ export interface BatchContextReminder {
19
+ readonly kind: BatchReminderKind;
20
+ readonly text: string;
21
+ }
22
+ /**
23
+ * Build the reminder for this turn, from the ratio and the phase.
24
+ *
25
+ * Pure: the same inputs always give the same sentence, so the wording can
26
+ * be tested without a filesystem.
27
+ *
28
+ * @param input.ratio - The context ratio, 0..1.
29
+ * @param input.mode - The auto-compact mode; the thresholds come from it.
30
+ * @param input.atBoundary - Whether the batch is crossing a compaction
31
+ * boundary right now.
32
+ * @param input.boundaryNotice - The boundary notice, when the caller has
33
+ * one. Used verbatim; this module writes no boundary sentence of its own.
34
+ */
35
+ export declare function buildBatchContextReminder(input: {
36
+ readonly ratio: number;
37
+ readonly mode: AutoCompactMode;
38
+ readonly atBoundary: boolean;
39
+ readonly boundaryNotice?: string;
40
+ }): BatchContextReminder | null;
41
+ /**
42
+ * The reminder this turn, and the record that it was said.
43
+ *
44
+ * SIDE EFFECT: the phase the batch was seen in, and the phase it last
45
+ * said something in, are recorded. That is what makes the rule "once per
46
+ * phase" enforceable in code rather than left to the caller's discipline —
47
+ * a reminder on every turn is the noise the design's open question named.
48
+ * The write happens only when the phase changed or when the batch spoke,
49
+ * so a steady phase is not written on every turn.
50
+ *
51
+ * The phase comes from the batch's progress record, which is the one place
52
+ * that says which stage the batch is in.
53
+ *
54
+ * @param input.atBoundary - Whether the batch is crossing a compaction
55
+ * boundary right now. When it is not given, the boundary is derived
56
+ * from the recorded phase: a phase that differs from the one seen last
57
+ * time IS a crossing.
58
+ * @returns The reminder, or `null` when there is nothing to say.
59
+ */
60
+ export declare function resolveBatchContextReminder(input: {
61
+ readonly projectRoot: string;
62
+ readonly sessionId: string;
63
+ readonly batchId: string;
64
+ readonly ratio: number;
65
+ readonly mode: AutoCompactMode;
66
+ readonly atBoundary?: boolean;
67
+ readonly boundaryNotice?: string;
68
+ }): BatchContextReminder | null;
69
+ /**
70
+ * The reminder the PRESENCE read should carry, for the batch in flight.
71
+ *
72
+ * The presence read knows the session, not the batch, so the batch in
73
+ * flight is found among the session's batch records (see
74
+ * `findActiveBatch`), and the boundary notice is the one the batch
75
+ * recorded when it last crossed a boundary.
76
+ *
77
+ * @returns The reminder, or `null` when no batch is running, or when
78
+ * there is nothing to say.
79
+ */
80
+ export declare function resolveBatchPresenceReminder(input: {
81
+ readonly projectRoot: string;
82
+ readonly sessionId: string;
83
+ readonly ratio: number;
84
+ readonly mode: AutoCompactMode;
85
+ }): BatchContextReminder | null;
@@ -0,0 +1,201 @@
1
+ // src/services/batch/batch-context-reminder.ts
2
+ //
3
+ // WHAT the batch says about the context window, and HOW OFTEN.
4
+ //
5
+ // THE RULE IS "STATE, NEVER INSTRUCT". The zero-pause contract says the
6
+ // compaction is the system's own action, never the user's: any wording
7
+ // that asks the user to compact, to run `/compact`, or to manage their own
8
+ // context is a regression (`tests/unit/cli/skill-presence-loop-hygiene.test.ts`
9
+ // is the guard). So the sentences here only say what is true — the ratio,
10
+ // the zone, what the system is doing — and never ask anybody to do
11
+ // anything.
12
+ //
13
+ // THE FREQUENCY IS "ONCE PER PHASE", NOT "EVERY TURN". Below the
14
+ // auto-fire line nothing is said at all: the ratio is visible every turn
15
+ // in the presence read (`context.ratioPct`), so a reminder below the line
16
+ // only adds noise. Above the line the batch says something once per
17
+ // phase, and once per phase boundary — a reminder on every turn would be
18
+ // the "每轮说会吵" the design's open question named.
19
+ //
20
+ // THE PHASE BOUNDARY SENTENCE IS NOT HERE. The notice that says the
21
+ // diagnosis is done and the compression is running belongs to the batch's
22
+ // verification stage (`buildPhaseBoundaryNotice`). This module CONSUMES
23
+ // that notice — it is handed in as `boundaryNotice` — rather than writing
24
+ // a second, rival sentence about the same moment. When no notice is
25
+ // supplied, this module falls back to the ratio sentence, which states a
26
+ // fact about the zone and asks for nothing.
27
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
28
+ import { dirname, join } from 'node:path';
29
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
30
+ import { evaluateCompactTrigger } from '../code/auto-compact-decision.js';
31
+ import { getSessionDir } from '../session/getSessionDir.js';
32
+ import { findActiveBatch } from './batch-active-batch.js';
33
+ import { readBatchProgress } from './batch-progress-store.js';
34
+ const BATCH_DIR = 'batch';
35
+ const REMINDER_STATE_FILE = 'reminder.json';
36
+ /**
37
+ * The red-line sentence.
38
+ *
39
+ * It states what the system is doing and what is NOT blocked, so the
40
+ * reader does not read the red line as a stop. It asks for nothing.
41
+ */
42
+ export const BATCH_CONTEXT_RED_LINE_NOTICE = '已请求 harness 压缩,等待中;派发未阻塞';
43
+ /**
44
+ * The zone sentence for a ratio that has entered the auto-compact zone.
45
+ *
46
+ * @param ratio - The context ratio, 0..1.
47
+ */
48
+ export function batchContextRatioNotice(ratio) {
49
+ return `上下文 ${(ratio * 100).toFixed(1)}%,已进入自动压缩区`;
50
+ }
51
+ /**
52
+ * Build the reminder for this turn, from the ratio and the phase.
53
+ *
54
+ * Pure: the same inputs always give the same sentence, so the wording can
55
+ * be tested without a filesystem.
56
+ *
57
+ * @param input.ratio - The context ratio, 0..1.
58
+ * @param input.mode - The auto-compact mode; the thresholds come from it.
59
+ * @param input.atBoundary - Whether the batch is crossing a compaction
60
+ * boundary right now.
61
+ * @param input.boundaryNotice - The boundary notice, when the caller has
62
+ * one. Used verbatim; this module writes no boundary sentence of its own.
63
+ */
64
+ export function buildBatchContextReminder(input) {
65
+ const trigger = evaluateCompactTrigger(input.ratio, input.mode);
66
+ if (trigger.kind === 'red-line') {
67
+ return { kind: 'red-line', text: BATCH_CONTEXT_RED_LINE_NOTICE };
68
+ }
69
+ const inAutoZone = trigger.kind === 'auto-fire' || trigger.kind === 'pre-compact';
70
+ // Below the auto-fire line the batch says nothing at all — not about the
71
+ // zone, and not about the boundary.
72
+ if (!inAutoZone)
73
+ return null;
74
+ const notice = input.boundaryNotice;
75
+ if (input.atBoundary && typeof notice === 'string' && notice.length > 0) {
76
+ return { kind: 'phase-boundary', text: notice };
77
+ }
78
+ return { kind: 'ratio', text: batchContextRatioNotice(input.ratio) };
79
+ }
80
+ function statePath(projectRoot, sessionId, batchId) {
81
+ if (isUnsafePathInput(batchId) || batchId.includes('/') || batchId.includes('\\')) {
82
+ throw new Error(`Invalid batch id: ${batchId} (must be a single safe path segment)`);
83
+ }
84
+ return join(getSessionDir(projectRoot, sessionId), BATCH_DIR, batchId, REMINDER_STATE_FILE);
85
+ }
86
+ /**
87
+ * Read what the batch has already said.
88
+ *
89
+ * A missing state is "nothing said yet" — the first call in a batch
90
+ * speaks. A malformed state is ignored for the same reason: a reminder
91
+ * that repeats itself is a nuisance, and a reminder that never repeats
92
+ * itself is worse.
93
+ */
94
+ function readReminderState(projectRoot, sessionId, batchId) {
95
+ const path = statePath(projectRoot, sessionId, batchId);
96
+ if (!existsSync(path))
97
+ return {};
98
+ try {
99
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
100
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
101
+ return {};
102
+ const record = parsed;
103
+ const seen = record.lastSeenPhase;
104
+ const spoken = record.lastSpokenPhase;
105
+ return {
106
+ ...(typeof seen === 'string' ? { lastSeenPhase: seen } : {}),
107
+ ...(typeof spoken === 'string' ? { lastSpokenPhase: spoken } : {})
108
+ };
109
+ }
110
+ catch {
111
+ return {};
112
+ }
113
+ }
114
+ /** Record what the batch has seen and said. */
115
+ function writeReminderState(projectRoot, sessionId, batchId, state) {
116
+ const path = statePath(projectRoot, sessionId, batchId);
117
+ mkdirSync(dirname(path), { recursive: true });
118
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
119
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, 'utf8');
120
+ renameSync(tmp, path);
121
+ }
122
+ /** Whether the batch has crossed into the phase it is in now. */
123
+ function hasCrossedPhase(state, phase) {
124
+ return state.lastSeenPhase !== undefined && state.lastSeenPhase !== phase;
125
+ }
126
+ /** The state to record: the phase seen now, and the phase last spoken in. */
127
+ function nextReminderState(state, phase, spoke) {
128
+ const spokenPhase = spoke ? phase : state.lastSpokenPhase;
129
+ return {
130
+ lastSeenPhase: phase,
131
+ ...(spokenPhase === undefined ? {} : { lastSpokenPhase: spokenPhase })
132
+ };
133
+ }
134
+ /** Whether the recorded state changed, and so has to be written back. */
135
+ function stateChanged(left, right) {
136
+ return (left.lastSeenPhase !== right.lastSeenPhase || left.lastSpokenPhase !== right.lastSpokenPhase);
137
+ }
138
+ /**
139
+ * The reminder this turn, and the record that it was said.
140
+ *
141
+ * SIDE EFFECT: the phase the batch was seen in, and the phase it last
142
+ * said something in, are recorded. That is what makes the rule "once per
143
+ * phase" enforceable in code rather than left to the caller's discipline —
144
+ * a reminder on every turn is the noise the design's open question named.
145
+ * The write happens only when the phase changed or when the batch spoke,
146
+ * so a steady phase is not written on every turn.
147
+ *
148
+ * The phase comes from the batch's progress record, which is the one place
149
+ * that says which stage the batch is in.
150
+ *
151
+ * @param input.atBoundary - Whether the batch is crossing a compaction
152
+ * boundary right now. When it is not given, the boundary is derived
153
+ * from the recorded phase: a phase that differs from the one seen last
154
+ * time IS a crossing.
155
+ * @returns The reminder, or `null` when there is nothing to say.
156
+ */
157
+ export function resolveBatchContextReminder(input) {
158
+ const progress = readBatchProgress(input.projectRoot, input.sessionId, input.batchId);
159
+ if (progress === null)
160
+ return null;
161
+ const phase = progress.phase;
162
+ const state = readReminderState(input.projectRoot, input.sessionId, input.batchId);
163
+ const atBoundary = input.atBoundary ?? hasCrossedPhase(state, phase);
164
+ const reminder = buildBatchContextReminder({
165
+ ratio: input.ratio,
166
+ mode: input.mode,
167
+ atBoundary,
168
+ ...(input.boundaryNotice === undefined ? {} : { boundaryNotice: input.boundaryNotice })
169
+ });
170
+ const spoken = state.lastSpokenPhase === phase ? null : reminder;
171
+ const next = nextReminderState(state, phase, spoken !== null);
172
+ if (stateChanged(state, next)) {
173
+ writeReminderState(input.projectRoot, input.sessionId, input.batchId, next);
174
+ }
175
+ return spoken;
176
+ }
177
+ /**
178
+ * The reminder the PRESENCE read should carry, for the batch in flight.
179
+ *
180
+ * The presence read knows the session, not the batch, so the batch in
181
+ * flight is found among the session's batch records (see
182
+ * `findActiveBatch`), and the boundary notice is the one the batch
183
+ * recorded when it last crossed a boundary.
184
+ *
185
+ * @returns The reminder, or `null` when no batch is running, or when
186
+ * there is nothing to say.
187
+ */
188
+ export function resolveBatchPresenceReminder(input) {
189
+ const active = findActiveBatch(input.projectRoot, input.sessionId);
190
+ if (active === null)
191
+ return null;
192
+ const notice = active.progress.boundaryNotice;
193
+ return resolveBatchContextReminder({
194
+ projectRoot: input.projectRoot,
195
+ sessionId: input.sessionId,
196
+ batchId: active.batchId,
197
+ ratio: input.ratio,
198
+ mode: input.mode,
199
+ ...(notice === undefined ? {} : { boundaryNotice: notice })
200
+ });
201
+ }
@@ -0,0 +1,25 @@
1
+ /** What the summary is built from: the three things the orchestrator needs. */
2
+ export interface BatchDiagnosisFinding {
3
+ /** Why the symptom happens, in the diagnostician's own words. */
4
+ readonly rootCause: string;
5
+ /** The repo-relative paths a fix would touch, POSIX-normalized. */
6
+ readonly files: readonly string[];
7
+ /** The sketch of the fix, one line. */
8
+ readonly sketch: string;
9
+ }
10
+ /**
11
+ * Collapse a paragraph to one line.
12
+ *
13
+ * Exported because the summary renders the same fields, and two modules
14
+ * that shape the same text must shape it the same way.
15
+ */
16
+ export declare function collapse(text: string): string;
17
+ /**
18
+ * Read the finding out of a diagnosis report.
19
+ *
20
+ * @param report - The report the diagnostician produced, verbatim.
21
+ * @returns The finding, or `null` when the report carries no recognised
22
+ * section at all — a report in another shape, which the caller must
23
+ * read rather than summarise.
24
+ */
25
+ export declare function parseBatchDiagnosisFinding(report: string): BatchDiagnosisFinding | null;