peaks-loop 4.2.3 → 4.2.4

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 (51) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +47 -0
  3. package/dist/cli/commands/code-context-now-command.js +8 -3
  4. package/dist/cli/commands/code-context-now-envelope.d.ts +27 -2
  5. package/dist/cli/commands/code-context-now-envelope.js +47 -2
  6. package/dist/cli/commands/compact-harness-window-command.js +19 -111
  7. package/dist/cli/commands/compact-harness-window-opt-out.d.ts +4 -0
  8. package/dist/cli/commands/compact-harness-window-opt-out.js +76 -0
  9. package/dist/cli/commands/compact-harness-window-percent.d.ts +39 -0
  10. package/dist/cli/commands/compact-harness-window-percent.js +78 -0
  11. package/dist/cli/commands/compact-harness-window-reports.d.ts +8 -0
  12. package/dist/cli/commands/compact-harness-window-reports.js +149 -0
  13. package/dist/cli/commands/workspace/init-actions.d.ts +2 -0
  14. package/dist/cli/commands/workspace/init-actions.js +15 -1
  15. package/dist/cli/commands/workspace/init-command.js +1 -1
  16. package/dist/cli/commands/workspace/init-envelope.d.ts +2 -1
  17. package/dist/cli/commands/workspace/init-envelope.js +18 -1
  18. package/dist/cli/commands/workspace/init-harness-threshold.d.ts +30 -0
  19. package/dist/cli/commands/workspace/init-harness-threshold.js +134 -0
  20. package/dist/services/context/auto-compact-reader.d.ts +6 -5
  21. package/dist/services/context/auto-compact-reader.js +24 -27
  22. package/dist/services/context/harness-compact-threshold-config.d.ts +178 -0
  23. package/dist/services/context/harness-compact-threshold-config.js +166 -0
  24. package/dist/services/context/harness-compact-threshold-ensure.d.ts +90 -0
  25. package/dist/services/context/harness-compact-threshold-ensure.js +158 -0
  26. package/dist/services/context/harness-compact-threshold-refusal.d.ts +39 -0
  27. package/dist/services/context/harness-compact-threshold-refusal.js +122 -0
  28. package/dist/services/context/harness-compact-threshold-reset-types.d.ts +59 -0
  29. package/dist/services/context/harness-compact-threshold-reset-types.js +9 -0
  30. package/dist/services/context/harness-compact-threshold-reset.d.ts +48 -0
  31. package/dist/services/context/harness-compact-threshold-reset.js +215 -0
  32. package/dist/services/context/harness-compact-threshold-verdict.d.ts +71 -0
  33. package/dist/services/context/harness-compact-threshold-verdict.js +124 -0
  34. package/dist/services/context/harness-percent-gates.d.ts +35 -0
  35. package/dist/services/context/harness-percent-gates.js +102 -0
  36. package/dist/services/context/harness-percent-ownership.d.ts +126 -0
  37. package/dist/services/context/harness-percent-ownership.js +200 -0
  38. package/dist/services/context/harness-settings-file.d.ts +70 -0
  39. package/dist/services/context/harness-settings-file.js +83 -0
  40. package/dist/services/context/harness-window-config.d.ts +53 -141
  41. package/dist/services/context/harness-window-config.js +58 -296
  42. package/dist/services/context/harness-window-opt-out.d.ts +67 -0
  43. package/dist/services/context/harness-window-opt-out.js +241 -0
  44. package/dist/services/context/harness-window-ownership.d.ts +49 -0
  45. package/dist/services/context/harness-window-ownership.js +130 -0
  46. package/dist/services/ide/adapters/claude-code-adapter.d.ts +9 -9
  47. package/dist/services/ide/adapters/claude-code-adapter.js +5 -5
  48. package/dist/services/ide/ide-compact-types.d.ts +23 -4
  49. package/dist/services/ide/shared/safe-path.d.ts +18 -0
  50. package/dist/services/ide/shared/safe-path.js +34 -1
  51. package/package.json +6 -6
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD percent ownership — the WRITE half.
3
+ *
4
+ * The window module next door answers "how big is the window the harness
5
+ * compacts against". This module answers the other half of when it fires: the
6
+ * harness's own percentage knob (`IdeCompactProfile.autoCompactPercentEnvVar`,
7
+ * declared per adapter — no IDE names here). The read-only verdict lives in
8
+ * `harness-compact-threshold-verdict.ts`.
9
+ *
10
+ * WHY A PERCENT IS NEEDED AT ALL. Measured on Claude Code 2.1.314 (2026-11-20):
11
+ * with no percent set, the harness compacts at `window − 13_000` (≈98.7% of a
12
+ * 1M window) or `window − 20_000` below 200K — after the point long-running
13
+ * sessions already die. With the percent set it compacts at `window × PCT%`.
14
+ * Writing the window alone therefore does NOT make early compaction happen;
15
+ * the pair is the feature.
16
+ *
17
+ * WHAT IS DELIBERATELY SHARED, NOT RE-IMPLEMENTED. The window half is written
18
+ * by `syncHarnessWindow` itself — the only implementation of its provenance
19
+ * guard, its band check, its opt-out and its home-directory guard. A second copy
20
+ * here would eventually disagree with the first about some file, so this module
21
+ * calls it and reports its result. What IS new is the percent key: its parse,
22
+ * its band, its own provenance marker, and one read-modify-write that touches
23
+ * nothing else in the file.
24
+ *
25
+ * THE PAIR IS TWO SEPARATE WRITES, AND THE FIRST ONE CAN OUTLIVE THE SECOND. A
26
+ * failure between them does NOT restore "the pre-slice state" — the window half
27
+ * has already been written by then, and only the percent half is missing. That
28
+ * is deliberate: each half is idempotent and independently owned, so a later
29
+ * init (or probe) fills the percent without re-deriving the window, and a percent
30
+ * refusal never rolls back a window that was correct on its own.
31
+ */
32
+ import type { HarnessWindowLocation } from './harness-window-config.js';
33
+ import { type HarnessPercentOwnership } from './harness-percent-ownership.js';
34
+ /**
35
+ * The window peaks-loop configures when nobody has said otherwise.
36
+ *
37
+ * 250_000 is the value the user calibrated on 2026-11-20
38
+ * (`CLAUDE_CODE_AUTO_COMPACT_WINDOW=250000` + 80% → a 200_000-token trigger),
39
+ * and it is the one the harness accepts as a plain token count inside its
40
+ * documented 100_000..1_000_000 band. A fresh downstream project gets THIS
41
+ * rather than an unset slot, because an unset slot means "no early compaction
42
+ * at all" — the state this slice exists to end.
43
+ */
44
+ export declare const DEFAULT_HARNESS_COMPACT_WINDOW_TOKENS = 250000;
45
+ /**
46
+ * The percent peaks-loop configures when nobody has said otherwise — 80% of
47
+ * the window above, i.e. a 200_000-token trigger on a 250_000 window.
48
+ *
49
+ * The single named default, exported here and nowhere else.
50
+ */
51
+ export declare const DEFAULT_HARNESS_COMPACT_PERCENT = 80;
52
+ /**
53
+ * The ownership half — parse, band, marker predicate, five-state classifier and
54
+ * the state read — lives in `harness-percent-ownership.ts` and is RE-EXPORTED
55
+ * here so every existing import path in this slice keeps working. It is its own
56
+ * module so the writer, the rollback and the state report cannot grow three
57
+ * spellings of "is this value peaks-loop's", and so both of those files stay
58
+ * under the file-size cap.
59
+ */
60
+ export type { HarnessPercentOwnership, HarnessPercentState } from './harness-percent-ownership.js';
61
+ export { HARNESS_COMPACT_PERCENT_MAX, HARNESS_COMPACT_PERCENT_MIN, HARNESS_PERCENT_WRITTEN_KEY, isHarnessPercentPeaksOwned, isHarnessPercentRemovable, parseHarnessCompactPercent, percentOwnershipOf, readHarnessPercentState } from './harness-percent-ownership.js';
62
+ /** A location that carries BOTH adapter-declared keys. */
63
+ export interface HarnessCompactThresholdLocation extends HarnessWindowLocation {
64
+ /** Env var / settings key the harness reads its auto-compact percent from. */
65
+ readonly percentEnvVar: string;
66
+ }
67
+ /**
68
+ * Resolve where the pair lives, for the IDE the env selects. `null` when any
69
+ * half is undeclared — the adapter names both keys and the file, never this
70
+ * module.
71
+ *
72
+ * It repeats the three-line adapter lookup rather than importing
73
+ * `resolveHarnessWindowLocation` (whose result it would only widen with the
74
+ * percent key) for one reason: that helper lives next door in
75
+ * `auto-compact-reader.ts`, which is the probe entry point and pulls in the
76
+ * statusline / transcript fallbacks. Keeping the write half off that import
77
+ * keeps a settings write from loading the whole probe stack — it is a
78
+ * dependency-weight decision, not a correctness one, and there is no import
79
+ * cycle either way.
80
+ */
81
+ export declare function resolveHarnessCompactThresholdLocation(input: {
82
+ readonly projectRoot: string;
83
+ readonly env?: NodeJS.ProcessEnv | undefined;
84
+ }): HarnessCompactThresholdLocation | null;
85
+ /**
86
+ * The shared settings-file read layer, re-exported so every existing import
87
+ * path in this slice's own modules keeps working. The implementation lives in
88
+ * `harness-settings-file.ts`; see its header for why it is one copy.
89
+ */
90
+ export type { SettingsFileShape } from './harness-settings-file.js';
91
+ export { envBlock, isEditableSettingsFile, isLinkedSettingsFile, readSettingsObject, settingsEnvValue } from './harness-settings-file.js';
92
+ export type HarnessPercentSyncAction = 'written' | 'unchanged' | 'skipped';
93
+ export interface HarnessPercentSyncResult {
94
+ readonly settingsPath: string;
95
+ readonly key: string;
96
+ readonly action: HarnessPercentSyncAction;
97
+ /**
98
+ * Why nothing was written, present only for `skipped`:
99
+ * - `opted-out` — the project's rollback flag is set (it covers
100
+ * both knobs: "remove it" must not be undone by a
101
+ * percent row appearing later)
102
+ * - `unsafe-project-root` — the root IS the user's home directory
103
+ * - `no-percent-resolved` — the caller passed `null` explicitly
104
+ * - `unreadable-percent` — the FILE's value is not a percentage at all,
105
+ * so no threshold can be read from it
106
+ * - `out-of-range` — not a whole 1..100, refused rather than clamped
107
+ * - `unreadable-settings` — the file is not a JSON object we can edit
108
+ * - `symlinked-settings` — the file, or the `.claude` directory holding it,
109
+ * is a symlink or junction, so writing would
110
+ * follow it into whatever it points at.
111
+ * Its own reason rather than `unreadable-settings`:
112
+ * the file may parse perfectly, and telling the
113
+ * user it is "not a JSON object" would point at
114
+ * the wrong remedy.
115
+ * - `not-peaks-owned` — the file holds a percent peaks-loop did not
116
+ * write (a human's pin), never overwritten
117
+ */
118
+ readonly reason?: string;
119
+ /**
120
+ * True only on the `written` action.
121
+ *
122
+ * Why it travels: the RESET sentence cannot tell "wrote (cleaned a stale
123
+ * marker)" from "wrote nothing" by looking at what was removed — a stale
124
+ * percent marker leaves nothing to name while the rollback still wrote the
125
+ * opt-out. A result that says whether THIS call wrote is the one fact that
126
+ * distinguishes them, so it is reported rather than re-derived.
127
+ */
128
+ readonly wrote: boolean;
129
+ readonly percent: number | null;
130
+ /**
131
+ * The percent the caller ASKED for, on every branch — mirroring
132
+ * `requestedTokens` on the window result.
133
+ *
134
+ * Why it is carried rather than left at the call site: on the skip path
135
+ * `percent` is the value the FILE holds, so an out-of-band refusal rendered
136
+ * `null is outside the 1..100 percent` — a sentence naming nothing. A refusal
137
+ * takes two values (what was asked, what the band is) and only the result can
138
+ * name the first.
139
+ */
140
+ readonly requestedPercent: number | null;
141
+ readonly previousPercent: number | null;
142
+ /**
143
+ * A BOUNDED description of the file's value before the call (MED-2), present
144
+ * only when the file carried the key — never the raw string, not a prefix.
145
+ *
146
+ * `previousPercent` cannot express the case that matters: a hand-typed
147
+ * `eighty` parses to `null`, exactly like an absent key, yet the two need
148
+ * opposite notices. The note's presence is that distinction, without putting
149
+ * user-writable text on a result that reaches logs.
150
+ */
151
+ readonly previousRawNote?: string;
152
+ /**
153
+ * WHO the file's percent belongs to — the same five-state classifier
154
+ * `--reset` uses. Carried because the refusal notice picks its REMEDY from it:
155
+ * a peaks-owned typo is cleared by `--reset`, while a human's `150` is the
156
+ * user's to change and `--reset` deliberately keeps it, so pointing at that
157
+ * command would be advice the rollback refuses to carry out.
158
+ */
159
+ readonly ownership: HarnessPercentOwnership;
160
+ readonly peakWritten: boolean;
161
+ }
162
+ /**
163
+ * Write `percent` as the harness's auto-compact threshold percentage.
164
+ * Idempotent: a re-run with the same value performs no write.
165
+ *
166
+ * Everything else in the file is preserved verbatim — this is a
167
+ * read-modify-write of the `env` block only, and only of its two peaks rows.
168
+ *
169
+ * No `env` parameter, deliberately: unlike the WINDOW (whose env copy is what a
170
+ * running session captured and therefore a legitimate source), the percent write
171
+ * has nothing to learn from the process env — it writes the number it was given
172
+ * and judges ownership from the FILE. Accepting an env it never read would be a
173
+ * second, silently-ignored input.
174
+ */
175
+ export declare function syncHarnessPercent(input: {
176
+ readonly location: HarnessCompactThresholdLocation;
177
+ readonly percent: number | null;
178
+ }): HarnessPercentSyncResult;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD percent ownership — the WRITE half.
3
+ *
4
+ * The window module next door answers "how big is the window the harness
5
+ * compacts against". This module answers the other half of when it fires: the
6
+ * harness's own percentage knob (`IdeCompactProfile.autoCompactPercentEnvVar`,
7
+ * declared per adapter — no IDE names here). The read-only verdict lives in
8
+ * `harness-compact-threshold-verdict.ts`.
9
+ *
10
+ * WHY A PERCENT IS NEEDED AT ALL. Measured on Claude Code 2.1.314 (2026-11-20):
11
+ * with no percent set, the harness compacts at `window − 13_000` (≈98.7% of a
12
+ * 1M window) or `window − 20_000` below 200K — after the point long-running
13
+ * sessions already die. With the percent set it compacts at `window × PCT%`.
14
+ * Writing the window alone therefore does NOT make early compaction happen;
15
+ * the pair is the feature.
16
+ *
17
+ * WHAT IS DELIBERATELY SHARED, NOT RE-IMPLEMENTED. The window half is written
18
+ * by `syncHarnessWindow` itself — the only implementation of its provenance
19
+ * guard, its band check, its opt-out and its home-directory guard. A second copy
20
+ * here would eventually disagree with the first about some file, so this module
21
+ * calls it and reports its result. What IS new is the percent key: its parse,
22
+ * its band, its own provenance marker, and one read-modify-write that touches
23
+ * nothing else in the file.
24
+ *
25
+ * THE PAIR IS TWO SEPARATE WRITES, AND THE FIRST ONE CAN OUTLIVE THE SECOND. A
26
+ * failure between them does NOT restore "the pre-slice state" — the window half
27
+ * has already been written by then, and only the percent half is missing. That
28
+ * is deliberate: each half is idempotent and independently owned, so a later
29
+ * init (or probe) fills the percent without re-deriving the window, and a percent
30
+ * refusal never rolls back a window that was correct on its own.
31
+ */
32
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
33
+ import { dirname, join } from 'node:path';
34
+ import { getAdapter } from '../ide/ide-registry.js';
35
+ import { detectIdeFromEnv } from './ide-detect.js';
36
+ import { envBlock, readSettingsObject, settingsEnvValue } from './harness-settings-file.js';
37
+ import { percentSkipReason, SKIP_UNCHANGED } from './harness-percent-gates.js';
38
+ import { HARNESS_PERCENT_WRITTEN_KEY, boundedRawNote, isHarnessPercentPeaksOwned, parseHarnessCompactPercent, percentOwnershipOf } from './harness-percent-ownership.js';
39
+ /**
40
+ * The window peaks-loop configures when nobody has said otherwise.
41
+ *
42
+ * 250_000 is the value the user calibrated on 2026-11-20
43
+ * (`CLAUDE_CODE_AUTO_COMPACT_WINDOW=250000` + 80% → a 200_000-token trigger),
44
+ * and it is the one the harness accepts as a plain token count inside its
45
+ * documented 100_000..1_000_000 band. A fresh downstream project gets THIS
46
+ * rather than an unset slot, because an unset slot means "no early compaction
47
+ * at all" — the state this slice exists to end.
48
+ */
49
+ export const DEFAULT_HARNESS_COMPACT_WINDOW_TOKENS = 250_000;
50
+ /**
51
+ * The percent peaks-loop configures when nobody has said otherwise — 80% of
52
+ * the window above, i.e. a 200_000-token trigger on a 250_000 window.
53
+ *
54
+ * The single named default, exported here and nowhere else.
55
+ */
56
+ export const DEFAULT_HARNESS_COMPACT_PERCENT = 80;
57
+ export { HARNESS_COMPACT_PERCENT_MAX, HARNESS_COMPACT_PERCENT_MIN, HARNESS_PERCENT_WRITTEN_KEY, isHarnessPercentPeaksOwned, isHarnessPercentRemovable, parseHarnessCompactPercent, percentOwnershipOf, readHarnessPercentState } from './harness-percent-ownership.js';
58
+ /**
59
+ * Resolve where the pair lives, for the IDE the env selects. `null` when any
60
+ * half is undeclared — the adapter names both keys and the file, never this
61
+ * module.
62
+ *
63
+ * It repeats the three-line adapter lookup rather than importing
64
+ * `resolveHarnessWindowLocation` (whose result it would only widen with the
65
+ * percent key) for one reason: that helper lives next door in
66
+ * `auto-compact-reader.ts`, which is the probe entry point and pulls in the
67
+ * statusline / transcript fallbacks. Keeping the write half off that import
68
+ * keeps a settings write from loading the whole probe stack — it is a
69
+ * dependency-weight decision, not a correctness one, and there is no import
70
+ * cycle either way.
71
+ */
72
+ export function resolveHarnessCompactThresholdLocation(input) {
73
+ const env = input.env ?? process.env;
74
+ const detected = detectIdeFromEnv(env);
75
+ const ideId = (detected === 'unknown' ? 'claude-code' : detected);
76
+ const adapter = getAdapter(ideId);
77
+ const windowEnvVar = adapter.compact?.autoCompactWindowEnvVar;
78
+ const percentEnvVar = adapter.compact?.autoCompactPercentEnvVar;
79
+ const fileName = adapter.settings.localSettingsFileName ?? adapter.settings.settingsFileName;
80
+ if (windowEnvVar === undefined || percentEnvVar === undefined || fileName === undefined)
81
+ return null;
82
+ return {
83
+ settingsPath: join(input.projectRoot, adapter.settings.dirName, fileName),
84
+ envVar: windowEnvVar,
85
+ percentEnvVar,
86
+ projectRoot: input.projectRoot
87
+ };
88
+ }
89
+ export { envBlock, isEditableSettingsFile, isLinkedSettingsFile, readSettingsObject, settingsEnvValue } from './harness-settings-file.js';
90
+ /**
91
+ * Write `percent` as the harness's auto-compact threshold percentage.
92
+ * Idempotent: a re-run with the same value performs no write.
93
+ *
94
+ * Everything else in the file is preserved verbatim — this is a
95
+ * read-modify-write of the `env` block only, and only of its two peaks rows.
96
+ *
97
+ * No `env` parameter, deliberately: unlike the WINDOW (whose env copy is what a
98
+ * running session captured and therefore a legitimate source), the percent write
99
+ * has nothing to learn from the process env — it writes the number it was given
100
+ * and judges ownership from the FILE. Accepting an env it never read would be a
101
+ * second, silently-ignored input.
102
+ */
103
+ export function syncHarnessPercent(input) {
104
+ const settingsPath = input.location.settingsPath;
105
+ const settings = readSettingsObject(settingsPath);
106
+ const fileRaw = settingsEnvValue(settings, input.location.percentEnvVar);
107
+ const markerRaw = settingsEnvValue(settings, HARNESS_PERCENT_WRITTEN_KEY);
108
+ const filePercent = parseHarnessCompactPercent(fileRaw);
109
+ // THE writer's (strict) predicate. NOT the rollback's wider one: a probe may
110
+ // overwrite only a value that still parses to its own marker, so a human's
111
+ // unreadable pin is never silently replaced. See `isHarnessPercentRemovable`.
112
+ const peakWritten = isHarnessPercentPeaksOwned({ fileRaw, markerRaw });
113
+ const ownership = percentOwnershipOf({ fileRaw, markerRaw });
114
+ const base = {
115
+ settingsPath,
116
+ key: input.location.percentEnvVar,
117
+ requestedPercent: input.percent,
118
+ previousPercent: filePercent,
119
+ // Bounded at the source (MED-2): the raw text never leaves this module,
120
+ // and the note's presence is what says the slot was not empty.
121
+ ...(fileRaw === undefined ? {} : { previousRawNote: boundedRawNote(fileRaw) }),
122
+ ownership,
123
+ peakWritten,
124
+ wrote: false
125
+ };
126
+ const skip = percentSkipReason({
127
+ location: input.location,
128
+ percent: input.percent,
129
+ settings,
130
+ fileRaw,
131
+ filePercent,
132
+ peakWritten
133
+ });
134
+ if (skip === SKIP_UNCHANGED) {
135
+ return { ...base, action: 'unchanged', percent: input.percent };
136
+ }
137
+ if (skip !== null) {
138
+ return { ...base, action: 'skipped', reason: skip, percent: filePercent };
139
+ }
140
+ // N8 — A NON-OBJECT `env` BLOCK IS REPLACED, NOT PRESERVED. `envBlock` yields
141
+ // `{}` for a `env` that is absent, `null`, an array or a string, so a file
142
+ // carrying `"env": "oops"` comes out of this write with a fresh object holding
143
+ // only the two peaks rows. That is deliberate: there is no peaks row to find in
144
+ // a value that is not an object, so the alternative is refusing every percent
145
+ // write on that file forever — and the harness itself cannot read a non-object
146
+ // `env`, so no user setting is destroyed by replacing it. The rest of the file
147
+ // (every other top-level key) is still carried over verbatim.
148
+ const next = {
149
+ ...(settings ?? {}),
150
+ env: {
151
+ ...envBlock(settings),
152
+ // A JSON env block is string-valued. `String(percent)` is the plain
153
+ // decimal the parser reads back (`PLAIN_PERCENT_SPELLING`), never `80.0`
154
+ // or `8e1`. The provenance marker travels in the SAME object, so value and
155
+ // provenance can never be split across two writes.
156
+ [input.location.percentEnvVar]: String(input.percent),
157
+ [HARNESS_PERCENT_WRITTEN_KEY]: String(input.percent)
158
+ }
159
+ };
160
+ const dir = dirname(settingsPath);
161
+ if (!existsSync(dir))
162
+ mkdirSync(dir, { recursive: true });
163
+ // 2-space JSON + trailing newline, the same convention as the window writer.
164
+ writeFileSync(settingsPath, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
165
+ return { ...base, action: 'written', percent: input.percent, peakWritten: true, wrote: true };
166
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the RECONCILE half (`peaks workspace init`).
3
+ *
4
+ * `ensureHarnessCompactThreshold` makes BOTH knobs configured in one project's
5
+ * machine-local settings file: the window through `syncHarnessWindow` (the one
6
+ * implementation of its provenance/band/home guards) and the percent through
7
+ * `syncHarnessPercent`. The two knobs' own rules live in
8
+ * `harness-compact-threshold-config.ts`; the read/verdict half lives in
9
+ * `harness-compact-threshold-verdict.ts`.
10
+ *
11
+ * This module exists so neither of those grows past the file-size cap for the
12
+ * sake of one orchestration function and its wording.
13
+ */
14
+ import { type HarnessCompactThresholdLocation, type HarnessPercentSyncResult } from './harness-compact-threshold-config.js';
15
+ import { type HarnessWindowSyncResult } from './harness-window-config.js';
16
+ /** The pair a reconcile returns: the window half and the percent half. */
17
+ export interface HarnessCompactThresholdResult {
18
+ readonly settingsPath: string;
19
+ /** The window half, decided by `syncHarnessWindow` (one implementation). */
20
+ readonly window: HarnessWindowSyncResult;
21
+ /** The percent half, decided by `syncHarnessPercent`. */
22
+ readonly percent: HarnessPercentSyncResult;
23
+ }
24
+ /**
25
+ * Ensure BOTH knobs are configured in the project's machine-local settings —
26
+ * the "install → early compaction works" path (`peaks workspace init`).
27
+ *
28
+ * A DEFAULT FILLS AN EMPTY SLOT; IT DOES NOT OVERRIDE A VALUE. An omitted
29
+ * argument (`undefined`) means "make sure this knob is configured", which
30
+ * resolves to the value already in the file when there is one and to the
31
+ * default only when the slot is empty. Init carries no new MEASUREMENT, so
32
+ * rewriting an existing value from it would be peaks-loop overruling its own
33
+ * probe with a policy constant — this repository's own file holds a
34
+ * peaks-written 1M window that a 250_000 default must not cut down on every
35
+ * init. An explicit argument (`number`), or `null` for "do not manage this one
36
+ * on this call", is passed through as given (the provenance and band gates
37
+ * still apply).
38
+ *
39
+ * Fail-soft by construction: every refusal returns a result, nothing throws,
40
+ * and an unreadable settings file is reported (reason `unreadable-settings`)
41
+ * rather than raised — an init must not abort because a third-party file
42
+ * cannot be parsed.
43
+ *
44
+ * A WRITE THAT THROWS IS CONTAINED. `.claude` existing as a regular FILE makes
45
+ * `mkdirSync(dirname(...), { recursive: true })` throw EEXIST, and a read-only
46
+ * directory throws EACCES — neither is a "nothing to do" the syncs report, so a
47
+ * throw there would escape init. Each half's write is caught and its sync is
48
+ * re-run against the UNCHANGED file rather than reported as written, which is
49
+ * what keeps the failure honest: the result says whatever the sync would say if
50
+ * no write had been attempted.
51
+ */
52
+ export declare function ensureHarnessCompactThreshold(input: {
53
+ readonly location: HarnessCompactThresholdLocation;
54
+ readonly env?: NodeJS.ProcessEnv | undefined;
55
+ readonly windowTokens?: number | null | undefined;
56
+ readonly percent?: number | null | undefined;
57
+ }): HarnessCompactThresholdResult;
58
+ /**
59
+ * The WINDOW write announcement alone — no percent clause.
60
+ *
61
+ * For a caller that routes a write and a refusal into DIFFERENT channels: the
62
+ * combined sentence opens with the write, so forwarding it as the refusal's
63
+ * warning would deliver `WROTE …` under a warning label. Same words as the
64
+ * combined sentence's window clause, so the two cannot read differently.
65
+ */
66
+ export declare function describeWindowOnly(result: HarnessCompactThresholdResult): string;
67
+ /**
68
+ * The PERCENT refusal alone — no window clause, and never a write announcement.
69
+ *
70
+ * A refusal means the project is NOT configured, which is a warning. See
71
+ * `describeWindowOnly` for why the combined describer cannot be split by
72
+ * substring at the call site. The sentences themselves live in
73
+ * `harness-compact-threshold-refusal.ts`, beside the window half's.
74
+ */
75
+ export { describePercentRefusal, describeWindowRefusal } from './harness-compact-threshold-refusal.js';
76
+ export declare function describeHarnessThresholdRefusal(result: HarnessCompactThresholdResult): string;
77
+ export declare function describeHarnessThresholdWindowRefusal(result: HarnessCompactThresholdResult): string;
78
+ /**
79
+ * One sentence for a reconcile, in the same "tell the user what was written"
80
+ * spirit as `describeHarnessWindowSync`: a write names the key, the value, the
81
+ * file and the previous value, and a refusal names why AND the way back.
82
+ *
83
+ * THE WINDOW HALF IS NAMED WHENEVER IT IS NEWS, INDEPENDENTLY OF THE PERCENT
84
+ * HALF. The two knobs are two separate read-modify-writes, so the window can be
85
+ * written while the percent reports `unchanged` (a hand-set pin) or a refusal.
86
+ * Describing only the percent then announced nothing about a write that DID
87
+ * happen — measured: a 250000 window was written and the only sentence named
88
+ * `… carries "150" …`.
89
+ */
90
+ export declare function describeHarnessCompactThreshold(result: HarnessCompactThresholdResult): string;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the RECONCILE half (`peaks workspace init`).
3
+ *
4
+ * `ensureHarnessCompactThreshold` makes BOTH knobs configured in one project's
5
+ * machine-local settings file: the window through `syncHarnessWindow` (the one
6
+ * implementation of its provenance/band/home guards) and the percent through
7
+ * `syncHarnessPercent`. The two knobs' own rules live in
8
+ * `harness-compact-threshold-config.ts`; the read/verdict half lives in
9
+ * `harness-compact-threshold-verdict.ts`.
10
+ *
11
+ * This module exists so neither of those grows past the file-size cap for the
12
+ * sake of one orchestration function and its wording.
13
+ */
14
+ import { DEFAULT_HARNESS_COMPACT_PERCENT, DEFAULT_HARNESS_COMPACT_WINDOW_TOKENS, parseHarnessCompactPercent, readSettingsObject, settingsEnvValue, syncHarnessPercent } from './harness-compact-threshold-config.js';
15
+ import { parseHarnessWindowTokens, syncHarnessWindow } from './harness-window-config.js';
16
+ import { describePercentRefusal, describeWindowRefusal } from './harness-compact-threshold-refusal.js';
17
+ /**
18
+ * The value to hand a sync when the caller passed `undefined`:
19
+ * - the caller's own number / `null` wins outright;
20
+ * - an existing on-disk value wins over the default (init carries no
21
+ * measurement — see `ensureHarnessCompactThreshold`);
22
+ * - otherwise the default.
23
+ *
24
+ * A present-but-unparseable on-disk value resolves to `null`, so the sync
25
+ * refuses and REPORTS rather than replacing a value nobody could read.
26
+ */
27
+ function resolveEnsured(arg, fileRaw, parse, fallback) {
28
+ if (arg !== undefined)
29
+ return arg;
30
+ if (fileRaw !== undefined)
31
+ return parse(fileRaw);
32
+ return fallback;
33
+ }
34
+ /**
35
+ * Ensure BOTH knobs are configured in the project's machine-local settings —
36
+ * the "install → early compaction works" path (`peaks workspace init`).
37
+ *
38
+ * A DEFAULT FILLS AN EMPTY SLOT; IT DOES NOT OVERRIDE A VALUE. An omitted
39
+ * argument (`undefined`) means "make sure this knob is configured", which
40
+ * resolves to the value already in the file when there is one and to the
41
+ * default only when the slot is empty. Init carries no new MEASUREMENT, so
42
+ * rewriting an existing value from it would be peaks-loop overruling its own
43
+ * probe with a policy constant — this repository's own file holds a
44
+ * peaks-written 1M window that a 250_000 default must not cut down on every
45
+ * init. An explicit argument (`number`), or `null` for "do not manage this one
46
+ * on this call", is passed through as given (the provenance and band gates
47
+ * still apply).
48
+ *
49
+ * Fail-soft by construction: every refusal returns a result, nothing throws,
50
+ * and an unreadable settings file is reported (reason `unreadable-settings`)
51
+ * rather than raised — an init must not abort because a third-party file
52
+ * cannot be parsed.
53
+ *
54
+ * A WRITE THAT THROWS IS CONTAINED. `.claude` existing as a regular FILE makes
55
+ * `mkdirSync(dirname(...), { recursive: true })` throw EEXIST, and a read-only
56
+ * directory throws EACCES — neither is a "nothing to do" the syncs report, so a
57
+ * throw there would escape init. Each half's write is caught and its sync is
58
+ * re-run against the UNCHANGED file rather than reported as written, which is
59
+ * what keeps the failure honest: the result says whatever the sync would say if
60
+ * no write had been attempted.
61
+ */
62
+ export function ensureHarnessCompactThreshold(input) {
63
+ const settings = readSettingsObject(input.location.settingsPath);
64
+ const windowTokens = resolveEnsured(input.windowTokens, settingsEnvValue(settings, input.location.envVar), parseHarnessWindowTokens, DEFAULT_HARNESS_COMPACT_WINDOW_TOKENS);
65
+ const percent = resolveEnsured(input.percent, settingsEnvValue(settings, input.location.percentEnvVar), parseHarnessCompactPercent, DEFAULT_HARNESS_COMPACT_PERCENT);
66
+ const window = containWriteFailure(() => syncHarnessWindow({
67
+ location: input.location,
68
+ tokens: windowTokens,
69
+ env: input.env
70
+ }));
71
+ const percentResult = containWriteFailure(() => syncHarnessPercent({ location: input.location, percent }));
72
+ return {
73
+ settingsPath: input.location.settingsPath,
74
+ window,
75
+ percent: percentResult
76
+ };
77
+ }
78
+ /**
79
+ * Run one sync, and on a THROWN write report `unreadable-settings` instead of
80
+ * letting the error escape init.
81
+ *
82
+ * There is deliberately NO retry: the only throw path is a write that cannot
83
+ * land (`mkdirSync` meeting `.claude` as a regular file, a read-only directory),
84
+ * and the sync has already REPORTED that state — its `skipped` branch was the
85
+ * one that tried to write. Re-running it would repeat the same side effects.
86
+ * Only `action`/`reason` are replaced, because "skipped" is the truth of a call
87
+ * that changed nothing.
88
+ */
89
+ function containWriteFailure(run) {
90
+ try {
91
+ return run();
92
+ }
93
+ catch {
94
+ return {
95
+ settingsPath: '',
96
+ key: '',
97
+ action: 'skipped',
98
+ reason: 'unreadable-settings'
99
+ };
100
+ }
101
+ }
102
+ /**
103
+ * The WINDOW write announcement alone — no percent clause.
104
+ *
105
+ * For a caller that routes a write and a refusal into DIFFERENT channels: the
106
+ * combined sentence opens with the write, so forwarding it as the refusal's
107
+ * warning would deliver `WROTE …` under a warning label. Same words as the
108
+ * combined sentence's window clause, so the two cannot read differently.
109
+ */
110
+ export function describeWindowOnly(result) {
111
+ const { window } = result;
112
+ return `WROTE ${window.key}=${String(window.tokens)} to ${result.settingsPath} (was ${window.previousTokens === null ? 'unset' : String(window.previousTokens)}) so the harness compacts against that window.`;
113
+ }
114
+ /**
115
+ * The PERCENT refusal alone — no window clause, and never a write announcement.
116
+ *
117
+ * A refusal means the project is NOT configured, which is a warning. See
118
+ * `describeWindowOnly` for why the combined describer cannot be split by
119
+ * substring at the call site. The sentences themselves live in
120
+ * `harness-compact-threshold-refusal.ts`, beside the window half's.
121
+ */
122
+ export { describePercentRefusal, describeWindowRefusal } from './harness-compact-threshold-refusal.js';
123
+ export function describeHarnessThresholdRefusal(result) {
124
+ return describePercentRefusal(result);
125
+ }
126
+ export function describeHarnessThresholdWindowRefusal(result) {
127
+ return describeWindowRefusal(result);
128
+ }
129
+ /**
130
+ * One sentence for a reconcile, in the same "tell the user what was written"
131
+ * spirit as `describeHarnessWindowSync`: a write names the key, the value, the
132
+ * file and the previous value, and a refusal names why AND the way back.
133
+ *
134
+ * THE WINDOW HALF IS NAMED WHENEVER IT IS NEWS, INDEPENDENTLY OF THE PERCENT
135
+ * HALF. The two knobs are two separate read-modify-writes, so the window can be
136
+ * written while the percent reports `unchanged` (a hand-set pin) or a refusal.
137
+ * Describing only the percent then announced nothing about a write that DID
138
+ * happen — measured: a 250000 window was written and the only sentence named
139
+ * `… carries "150" …`.
140
+ */
141
+ export function describeHarnessCompactThreshold(result) {
142
+ const { percent } = result;
143
+ // Two separate read-modify-writes produce two separate NEWS ITEMS, so the
144
+ // separator is load-bearing: without it the window sentence ran straight into
145
+ // the percent sentence ("…against that window.Harness threshold not
146
+ // managed…") and an operator reading the notice got one run-on line.
147
+ const windowNews = result.window.action === 'written' ? `${describeWindowOnly(result)} ` : '';
148
+ if (percent.action === 'written') {
149
+ return `${windowNews}WROTE ${percent.key}=${String(percent.percent)} to ${result.settingsPath} (was ${percent.previousPercent === null ? 'unset' : String(percent.previousPercent)}) so the harness compacts at that share of its window.`;
150
+ }
151
+ if (percent.action === 'unchanged') {
152
+ // A quiet percent is news only when the OTHER half just wrote.
153
+ return (windowNews.trimEnd() ||
154
+ `Harness threshold ${percent.key}=${String(percent.percent)} already in force.`);
155
+ }
156
+ // A refusal: the window write, if any, comes first so it is never swallowed.
157
+ return `${windowNews}${describePercentRefusal(result)}`;
158
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the REFUSAL sentences.
3
+ *
4
+ * Split out of `harness-compact-threshold-ensure.ts` so that file — which is at
5
+ * the 300-raw-line cap — can keep the reconcile and its write announcements.
6
+ * Every sentence here names a value, a file and a next step, because the bare
7
+ * reason token (`(out-of-harness-range)`) names none of the three.
8
+ *
9
+ * THE REMEDY IS CHOSEN BY OWNERSHIP, NOT BY THE REASON. `--reset` removes only
10
+ * what peaks-loop wrote (`percentOwnershipOf`); pointing it at a HUMAN value
11
+ * would be advice the command refuses to carry out — measured: a no-marker
12
+ * `150` was classified `human`, and `--reset` answered "Kept … your own
13
+ * setting". A peaks-owned shape still gets the `--reset` advice, which is what
14
+ * makes the documented recovery from a corrupted peaks write work; a human's
15
+ * value gets the only remedy that exists for it — the user setting it.
16
+ */
17
+ import type { HarnessCompactThresholdResult } from './harness-compact-threshold-ensure.js';
18
+ /**
19
+ * Why the percent half was not written, in words — one clause per `reason`.
20
+ *
21
+ * Every reason gets its own sentence rather than falling through to
22
+ * `(${reason})`. The default clause is unreachable for the reasons this module
23
+ * produces today; it exists so a future reason cannot silently degrade to a
24
+ * token.
25
+ *
26
+ * `out-of-range` and `not-peaks-owned` each have TWO shapes, told apart by the
27
+ * file's RAW value — see `describeFileValueRefusal`.
28
+ */
29
+ export declare function describePercentRefusal(result: HarnessCompactThresholdResult): string;
30
+ /**
31
+ * The WINDOW refusal alone — the init warning's other half.
32
+ *
33
+ * A window can be refused while the percent writes or is unchanged (an
34
+ * out-of-band `50000`, an opt-out that covers both, an unreadable file), and
35
+ * the combined describer only mentions a window that WROTE. A caller routing a
36
+ * refusal needs the window's own reason in words, for the same no-bare-token
37
+ * reason the percent's has.
38
+ */
39
+ export declare function describeWindowRefusal(result: HarnessCompactThresholdResult): string;