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,122 @@
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 { HARNESS_COMPACT_PERCENT_MAX, HARNESS_COMPACT_PERCENT_MIN } from './harness-compact-threshold-config.js';
18
+ import { HARNESS_WINDOW_MAX_TOKENS, HARNESS_WINDOW_MIN_TOKENS } from './harness-window-config.js';
19
+ /** The band sentence, in one place, so no two notices can disagree about it. */
20
+ function percentBand() {
21
+ return `${HARNESS_COMPACT_PERCENT_MIN}..${HARNESS_COMPACT_PERCENT_MAX}`;
22
+ }
23
+ /**
24
+ * Why the percent half was not written, in words — one clause per `reason`.
25
+ *
26
+ * Every reason gets its own sentence rather than falling through to
27
+ * `(${reason})`. The default clause is unreachable for the reasons this module
28
+ * produces today; it exists so a future reason cannot silently degrade to a
29
+ * token.
30
+ *
31
+ * `out-of-range` and `not-peaks-owned` each have TWO shapes, told apart by the
32
+ * file's RAW value — see `describeFileValueRefusal`.
33
+ */
34
+ export function describePercentRefusal(result) {
35
+ switch (result.percent.reason) {
36
+ case 'opted-out':
37
+ return 'Harness threshold not managed (opted-out) — `peaks compact harness-window --reenable` re-enables both knobs.';
38
+ case 'unsafe-project-root':
39
+ return `Harness threshold not managed: ${result.settingsPath} sits directly in the user's home directory rather than in a project, so it is the harness's settings for every project at once and peaks-loop left it alone. Run init from inside a project.`;
40
+ case 'out-of-range':
41
+ case 'unreadable-percent':
42
+ case 'not-peaks-owned':
43
+ return describeFileValueRefusal(result);
44
+ case 'unreadable-settings':
45
+ return `Harness threshold not managed: ${result.settingsPath} is not a JSON object peaks-loop can safely edit.`;
46
+ case 'symlinked-settings':
47
+ return `Harness threshold not managed: ${result.settingsPath} is a symlink (or a Windows junction), or the directory holding it is, so writing the percent would follow the link and overwrite the file it points at. Replace the link with a real file (or directory) and the percent lands here.`;
48
+ default:
49
+ return `Harness threshold not managed (${String(result.percent.reason)}).`;
50
+ }
51
+ }
52
+ /**
53
+ * The WINDOW refusal alone — the init warning's other half.
54
+ *
55
+ * A window can be refused while the percent writes or is unchanged (an
56
+ * out-of-band `50000`, an opt-out that covers both, an unreadable file), and
57
+ * the combined describer only mentions a window that WROTE. A caller routing a
58
+ * refusal needs the window's own reason in words, for the same no-bare-token
59
+ * reason the percent's has.
60
+ */
61
+ export function describeWindowRefusal(result) {
62
+ const { window, settingsPath } = result;
63
+ const band = `${HARNESS_WINDOW_MIN_TOKENS}..${HARNESS_WINDOW_MAX_TOKENS}`;
64
+ switch (window.reason) {
65
+ case 'opted-out':
66
+ return 'the project opted out of harness management — `peaks compact harness-window --reenable` covers both knobs.';
67
+ case 'unsafe-project-root':
68
+ return `${settingsPath} sits directly in the user's home directory rather than in a project, so peaks-loop left it alone. Run init from inside a project.`;
69
+ case 'no-window-resolved':
70
+ return 'this call carried no token window, so peaks-loop did not invent one.';
71
+ case 'out-of-harness-range':
72
+ return `${window.key}: a window of ${String(window.requestedTokens)} is outside the ${band} band the harness accepts, so ${settingsPath} was not given a number it does not compact on.`;
73
+ case 'not-peaks-owned':
74
+ return `${window.key}: ${settingsPath} already carries a window peaks-loop did not write (${window.previousRawNote ?? 'a value'}), and peaks-loop never overwrites such a value.`;
75
+ case 'symlinked-settings':
76
+ return `${settingsPath} is a symlink (or a Windows junction), or the directory holding it is, so a write would follow the link and overwrite the file it points at.`;
77
+ case 'unreadable-settings':
78
+ return `${settingsPath} is not a JSON object peaks-loop can safely edit.`;
79
+ default:
80
+ return `the window was not managed (${String(window.reason)}).`;
81
+ }
82
+ }
83
+ /**
84
+ * The refusals decided by WHAT the file holds, in one place because they share
85
+ * the sentence frame:
86
+ *
87
+ * - `out-of-range` with a value on disk — a whole number outside 1..100. The
88
+ * old wording called `150` "not a percentage", which is false and points at
89
+ * the wrong remedy; it IS a percentage, just not one the harness accepts.
90
+ * - `out-of-range` with an empty slot — the caller's own number was out of band.
91
+ * - `unreadable-percent` — a typo (`eighty`), which is not a percentage at all.
92
+ * - `not-peaks-owned` — a human's pin, or a typo peaks-loop did not write.
93
+ *
94
+ * The FRAME is chosen by the value's shape; the REMEDY by who owns it. The two
95
+ * are independent: `eighty` with no marker is both "not a percentage" and a
96
+ * human's value, so it needs the human remedy inside the parse frame.
97
+ */
98
+ function describeFileValueRefusal(result) {
99
+ const { percent, settingsPath } = result;
100
+ const onDisk = percent.previousRawNote !== undefined;
101
+ const quoted = `${settingsPath} carries ${percent.previousRawNote ?? 'a value'} as ${percent.key}`;
102
+ const remedy = remedyClause(percent.ownership === 'human', result);
103
+ if (percent.reason === 'out-of-range') {
104
+ return !onDisk
105
+ ? `Harness threshold not managed: ${String(percent.requestedPercent)} is outside the ${percentBand()} percent the harness accepts.`
106
+ : `Harness threshold not managed: ${quoted}, which is outside the ${percentBand()} percent the harness accepts, so peaks-loop will not rewrite it. ${remedy}`;
107
+ }
108
+ if (percent.previousPercent !== null || !onDisk) {
109
+ return `Harness threshold not managed: ${settingsPath} already carries a percent that peaks-loop did not write, and peaks-loop never overwrites such a value. ${remedy}`;
110
+ }
111
+ return `Harness threshold not managed: ${quoted}, which is not a percentage. ${remedy}`;
112
+ }
113
+ /**
114
+ * The next step for a file-held percent, chosen by WHO owns it — see the module
115
+ * header for why the two branches exist.
116
+ */
117
+ function remedyClause(human, result) {
118
+ if (human) {
119
+ return `This value is yours, not peaks-loop's, so peaks-loop leaves it for you to fix: set ${result.percent.key} to a whole number in the ${percentBand()} band in ${result.settingsPath}.`;
120
+ }
121
+ return `Set ${result.percent.key} to a whole number in the ${percentBand()} band, or \`peaks compact harness-window --reset\` to clear what peaks-loop wrote.`;
122
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The SHAPES a `peaks compact harness-window --reset` reports.
3
+ *
4
+ * WHY A FILE OF ITS OWN. `harness-compact-threshold-reset.ts` sat at the 300-raw-
5
+ * line cap, and this interface plus its three companion types is the largest
6
+ * block that can move out without carrying a copy of the rollback's logic: types
7
+ * only, so a consumer of the result shape never pulls in the fs work.
8
+ */
9
+ import type { HarnessPercentOwnership } from './harness-compact-threshold-config.js';
10
+ import type { HarnessWindowOwnership } from './harness-window-ownership.js';
11
+ /** Re-exported from the config module, where the five states are named. */
12
+ export type { HarnessPercentOwnership } from './harness-compact-threshold-config.js';
13
+ /** Re-exported from the window ownership module, where its five states are named. */
14
+ export type { HarnessWindowOwnership } from './harness-window-ownership.js';
15
+ /** What became of one knob. `absent` = nothing of peaks-loop's was there. */
16
+ export type HarnessThresholdResetKnobAction = 'removed' | 'kept-human' | 'absent';
17
+ /**
18
+ * WHY the rollback wrote nothing, present only when it wrote nothing:
19
+ * `unreadable-settings` (not a JSON object we can edit) or `symlinked-settings`
20
+ * (a link, so a write would follow it into its target — its own reason, since
21
+ * the file may parse perfectly and where the bytes LAND is the problem).
22
+ */
23
+ export type HarnessThresholdResetRefusal = 'unreadable-settings' | 'symlinked-settings';
24
+ export interface HarnessThresholdResetResult {
25
+ readonly settingsPath: string;
26
+ readonly window: {
27
+ readonly key: string;
28
+ readonly action: HarnessThresholdResetKnobAction;
29
+ /** Who the window value belonged to; drives `action`. */
30
+ readonly ownership: HarnessWindowOwnership;
31
+ readonly previousTokens: number | null;
32
+ /**
33
+ * A BOUNDED description of the file's value — never the raw string, not a
34
+ * prefix of it (MED-2). `keptClause` renders this, so a secret mis-parked
35
+ * at the key cannot reach stdout or a log. Present only when the key was.
36
+ */
37
+ readonly previousRawNote?: string;
38
+ };
39
+ readonly percent: {
40
+ readonly key: string;
41
+ readonly action: HarnessThresholdResetKnobAction;
42
+ readonly ownership: HarnessPercentOwnership;
43
+ readonly previousPercent: number | null;
44
+ /** See `window.previousRawNote`. */
45
+ readonly previousRawNote?: string;
46
+ };
47
+ /** True when the opt-out row is on disk after the call. */
48
+ readonly optedOut: boolean;
49
+ /**
50
+ * True only when THIS call wrote the file. The sentence needs it: a stale
51
+ * percent marker leaves both knobs `absent` (no value to name) while the
52
+ * rollback still wrote, so the removals alone cannot tell that apart from a
53
+ * genuine no-op — which is how the sentence came to say "nothing was written"
54
+ * about a file that changed.
55
+ */
56
+ readonly wrote: boolean;
57
+ /** Present only when the rollback declined to write; see `…Refusal`. */
58
+ readonly refusal?: HarnessThresholdResetRefusal;
59
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The SHAPES a `peaks compact harness-window --reset` reports.
3
+ *
4
+ * WHY A FILE OF ITS OWN. `harness-compact-threshold-reset.ts` sat at the 300-raw-
5
+ * line cap, and this interface plus its three companion types is the largest
6
+ * block that can move out without carrying a copy of the rollback's logic: types
7
+ * only, so a consumer of the result shape never pulls in the fs work.
8
+ */
9
+ export {};
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the ROLLBACK half.
3
+ *
4
+ * `peaks compact harness-window --reset` must undo the PAIR: removing only the
5
+ * window left `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` (and its marker) behind, moving
6
+ * the trigger EARLIER while the opt-out row claimed nothing was managed.
7
+ * It is NOT a second call to `resetHarnessWindow`, whose no-op guard fires when
8
+ * the file holds no WINDOW row — exactly the state a percent can be left in
9
+ * alone. One read-modify-write deciding BOTH ownership questions is the only
10
+ * shape in which "removed the window but not the percent" cannot exist on disk.
11
+ *
12
+ * BOTH HALVES OBEY AN OWNERSHIP RULE, and it is the rollback's WIDER one
13
+ * (`percentOwnershipOf` / `windowOwnershipOf`): the init notice for a peaks-owned
14
+ * typo says "`--reset` to clear it", and a rule requiring both sides to parse
15
+ * would refuse exactly that value — a VALID numeric marker beside an unreadable
16
+ * value is peaks-loop's own write corrupted afterwards. A value with NO marker,
17
+ * or with an UNPARSEABLE marker (peaks-loop never writes one), is the user's own
18
+ * pin, and `--reset` undoes what peaks-loop wrote, never the user's own config.
19
+ */
20
+ import { type HarnessCompactThresholdLocation } from './harness-compact-threshold-config.js';
21
+ import type { HarnessThresholdResetResult } from './harness-compact-threshold-reset-types.js';
22
+ export type { HarnessPercentOwnership, HarnessThresholdResetKnobAction, HarnessThresholdResetRefusal, HarnessThresholdResetResult, HarnessWindowOwnership } from './harness-compact-threshold-reset-types.js';
23
+ /**
24
+ * Remove what peaks-loop wrote for BOTH knobs and record the opt-out, in one
25
+ * read-modify-write.
26
+ *
27
+ * A file with no peaks row of any kind is left byte-identical (the `$HOME`
28
+ * litter guard): there is nothing to roll back and nothing to make durable.
29
+ * A file whose only peak is a HUMAN window pin or a HUMAN percent still gets the
30
+ * opt-out row written, because those values ARE the harness threshold's content
31
+ * — the rollback's job is to stop peaks-loop managing it, and the sync would
32
+ * otherwise overwrite/fill the other knob on the next probe. The human's own
33
+ * value is never touched; only its ownership of it is left to the user.
34
+ *
35
+ * No `env` parameter, deliberately — mirrors `syncHarnessPercent`. Ownership is
36
+ * a property of the FILE against its own marker; the process env is frozen at
37
+ * session start and would be a second, silently-ignored input.
38
+ */
39
+ export declare function resetHarnessThreshold(input: {
40
+ readonly thresholdLocation: HarnessCompactThresholdLocation;
41
+ }): HarnessThresholdResetResult;
42
+ /**
43
+ * What the rollback did, in one sentence — the half it deliberately KEPT
44
+ * included ("Removed the threshold" would be false when a human's percent
45
+ * survived). A CORRUPTED peaks-owned value (`peaks-corrupt`) is reported as
46
+ * REMOVED, never `kept-human`: the user did not set it.
47
+ */
48
+ export declare function describeHarnessThresholdReset(result: HarnessThresholdResetResult): string;
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the ROLLBACK half.
3
+ *
4
+ * `peaks compact harness-window --reset` must undo the PAIR: removing only the
5
+ * window left `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` (and its marker) behind, moving
6
+ * the trigger EARLIER while the opt-out row claimed nothing was managed.
7
+ * It is NOT a second call to `resetHarnessWindow`, whose no-op guard fires when
8
+ * the file holds no WINDOW row — exactly the state a percent can be left in
9
+ * alone. One read-modify-write deciding BOTH ownership questions is the only
10
+ * shape in which "removed the window but not the percent" cannot exist on disk.
11
+ *
12
+ * BOTH HALVES OBEY AN OWNERSHIP RULE, and it is the rollback's WIDER one
13
+ * (`percentOwnershipOf` / `windowOwnershipOf`): the init notice for a peaks-owned
14
+ * typo says "`--reset` to clear it", and a rule requiring both sides to parse
15
+ * would refuse exactly that value — a VALID numeric marker beside an unreadable
16
+ * value is peaks-loop's own write corrupted afterwards. A value with NO marker,
17
+ * or with an UNPARSEABLE marker (peaks-loop never writes one), is the user's own
18
+ * pin, and `--reset` undoes what peaks-loop wrote, never the user's own config.
19
+ */
20
+ import { existsSync, writeFileSync } from 'node:fs';
21
+ import { envBlock, parseHarnessCompactPercent, percentOwnershipOf, readSettingsObject, HARNESS_PERCENT_WRITTEN_KEY } from './harness-compact-threshold-config.js';
22
+ // The TYPES live in their own module; see .
23
+ import { HARNESS_WINDOW_SYNC_OPTOUT_KEY, HARNESS_WINDOW_SYNC_OPTOUT_VALUE, HARNESS_WINDOW_WRITTEN_KEY, isLinkedSettingsFile, parseHarnessWindowTokens } from './harness-window-config.js';
24
+ import { windowOwnershipOf } from './harness-window-ownership.js';
25
+ import { boundedRawNote, nothingToRemoveSentence, percentClause, wasValue } from './harness-settings-file.js';
26
+ /** The action a given ownership state produces. */
27
+ function actionOf(ownership) {
28
+ if (ownership === 'peaks' || ownership === 'peaks-corrupt')
29
+ return 'removed';
30
+ return ownership === 'human' ? 'kept-human' : 'absent';
31
+ }
32
+ function snapshotOf(location) {
33
+ const settingsPath = location.settingsPath;
34
+ const settings = existsSync(settingsPath) ? readSettingsObject(settingsPath) : null;
35
+ const env = envBlock(settings);
36
+ const windowRaw = env[location.envVar];
37
+ const windowMarkerRaw = env[HARNESS_WINDOW_WRITTEN_KEY];
38
+ const percentRaw = env[location.percentEnvVar];
39
+ return {
40
+ settingsPath,
41
+ windowKey: location.envVar,
42
+ percentKey: location.percentEnvVar,
43
+ settings,
44
+ env,
45
+ previousTokens: parseHarnessWindowTokens(windowRaw),
46
+ windowRaw,
47
+ filePercent: parseHarnessCompactPercent(percentRaw),
48
+ ownership: percentOwnershipOf({
49
+ fileRaw: percentRaw,
50
+ markerRaw: env[HARNESS_PERCENT_WRITTEN_KEY]
51
+ }),
52
+ // The SAME rule the percent half uses, asked of the window pair: a value
53
+ // with no marker is the user's own pin, so the rollback keeps it.
54
+ windowOwnership: windowOwnershipOf({ fileRaw: windowRaw, markerRaw: windowMarkerRaw })
55
+ };
56
+ }
57
+ /** True when the file's opt-out row is already in place. */
58
+ function readsOptedOut(env) {
59
+ return env[HARNESS_WINDOW_SYNC_OPTOUT_KEY] === HARNESS_WINDOW_SYNC_OPTOUT_VALUE;
60
+ }
61
+ /**
62
+ * Remove what peaks-loop wrote for BOTH knobs and record the opt-out, in one
63
+ * read-modify-write.
64
+ *
65
+ * A file with no peaks row of any kind is left byte-identical (the `$HOME`
66
+ * litter guard): there is nothing to roll back and nothing to make durable.
67
+ * A file whose only peak is a HUMAN window pin or a HUMAN percent still gets the
68
+ * opt-out row written, because those values ARE the harness threshold's content
69
+ * — the rollback's job is to stop peaks-loop managing it, and the sync would
70
+ * otherwise overwrite/fill the other knob on the next probe. The human's own
71
+ * value is never touched; only its ownership of it is left to the user.
72
+ *
73
+ * No `env` parameter, deliberately — mirrors `syncHarnessPercent`. Ownership is
74
+ * a property of the FILE against its own marker; the process env is frozen at
75
+ * session start and would be a second, silently-ignored input.
76
+ */
77
+ export function resetHarnessThreshold(input) {
78
+ const snap = snapshotOf(input.thresholdLocation);
79
+ // Refused in order: a LINK must not be written through, then an EXISTING file
80
+ // that will not parse cannot be edited. Both are REPORTED, never thrown — an
81
+ // init or probe that reaches this must learn why nothing happened, not crash.
82
+ // An ABSENT file is neither: it carries nothing of peaks-loop's, so it falls
83
+ // through to the no-op below with the literal (absent, no opt-out) result.
84
+ if (isLinkedSettingsFile(snap.settingsPath))
85
+ return resultOf(snap, false, 'symlinked-settings');
86
+ if (snap.settings === null && existsSync(snap.settingsPath)) {
87
+ return resultOf(snap, false, 'unreadable-settings');
88
+ }
89
+ // Nothing of peaks-loop's to remove → write nothing. A stale marker (of either
90
+ // knob) IS peaks content and falls through, so it gets cleaned up. A HUMAN
91
+ // value alone also falls through: the opt-out must cover the knobs the user
92
+ // genuinely set, or the next probe fills the other one behind their back.
93
+ if (nothingToRemove(snap))
94
+ return resultOf(snap, readsOptedOut(snap.env));
95
+ writeThresholdReset(snap, input.thresholdLocation);
96
+ return resultOf(snap, true, undefined, true);
97
+ }
98
+ /** True when neither knob holds a value at all — the pure no-op. */
99
+ function nothingToRemove(snap) {
100
+ return snap.windowOwnership === 'none' && snap.ownership === 'none';
101
+ }
102
+ /**
103
+ * The single write. Each knob's rows are deleted only when the value is
104
+ * peaks-loop's own; a human's value and its (mismatching) marker stay together,
105
+ * because a marker that no longer matches its value IS the evidence of takeover.
106
+ */
107
+ function writeThresholdReset(snap, location) {
108
+ const nextEnv = { ...snap.env };
109
+ // A `stale-marker` window has no value to delete, only the marker to clean.
110
+ if (snap.windowOwnership === 'peaks' || snap.windowOwnership === 'peaks-corrupt') {
111
+ delete nextEnv[location.envVar];
112
+ delete nextEnv[HARNESS_WINDOW_WRITTEN_KEY];
113
+ }
114
+ else if (snap.windowOwnership === 'stale-marker') {
115
+ delete nextEnv[HARNESS_WINDOW_WRITTEN_KEY];
116
+ }
117
+ const removable = snap.ownership === 'peaks' || snap.ownership === 'peaks-corrupt';
118
+ if (removable || snap.ownership === 'stale-marker')
119
+ delete nextEnv[HARNESS_PERCENT_WRITTEN_KEY];
120
+ if (removable)
121
+ delete nextEnv[location.percentEnvVar];
122
+ nextEnv[HARNESS_WINDOW_SYNC_OPTOUT_KEY] = HARNESS_WINDOW_SYNC_OPTOUT_VALUE;
123
+ writeFileSync(snap.settingsPath, `${JSON.stringify({ ...(snap.settings ?? {}), env: nextEnv }, null, 2)}\n`, 'utf8');
124
+ }
125
+ /** The result shape, built from the PRE-write snapshot plus the opt-out after. */
126
+ function resultOf(snap, optedOut, refusal, wrote = false) {
127
+ const base = {
128
+ settingsPath: snap.settingsPath,
129
+ window: {
130
+ key: snap.windowKey,
131
+ action: actionOf(snap.windowOwnership),
132
+ ownership: snap.windowOwnership,
133
+ previousTokens: snap.previousTokens,
134
+ // Bounded at the source (MED-2).
135
+ ...(snap.windowRaw === undefined ? {} : { previousRawNote: boundedRawNote(snap.windowRaw) })
136
+ },
137
+ percent: {
138
+ key: snap.percentKey,
139
+ action: actionOf(snap.ownership),
140
+ ownership: snap.ownership,
141
+ previousPercent: snap.filePercent,
142
+ ...(snap.env[snap.percentKey] === undefined
143
+ ? {}
144
+ : { previousRawNote: boundedRawNote(snap.env[snap.percentKey]) })
145
+ },
146
+ optedOut,
147
+ wrote
148
+ };
149
+ // Spread rather than `refusal: undefined`, so `exactOptionalPropertyTypes`
150
+ // keeps the property ABSENT on the ordinary (wrote / nothing-to-remove) paths.
151
+ return refusal === undefined ? base : { ...base, refusal };
152
+ }
153
+ /**
154
+ * What the rollback did, in one sentence — the half it deliberately KEPT
155
+ * included ("Removed the threshold" would be false when a human's percent
156
+ * survived). A CORRUPTED peaks-owned value (`peaks-corrupt`) is reported as
157
+ * REMOVED, never `kept-human`: the user did not set it.
158
+ */
159
+ export function describeHarnessThresholdReset(result) {
160
+ const { window, percent, settingsPath } = result;
161
+ // A REFUSAL IS ITS OWN SENTENCE, so no other branch can be printed about a
162
+ // file this call declined to touch.
163
+ if (result.refusal !== undefined) {
164
+ return describeResetRefusal(result.refusal, settingsPath, window.key, percent.key);
165
+ }
166
+ const kept = [keptClause(window), keptClause(percent, true)].filter(Boolean).join('');
167
+ // A GENUINE NO-OP IS DECIDED BY `wrote`, NOT BY THE REMOVALS: a stale percent
168
+ // marker leaves nothing to name while the file DID change. A HUMAN pin is
169
+ // still named — "nothing to remove" about the user's own window must not read
170
+ // as "there was no setting here".
171
+ if (!result.wrote) {
172
+ return `${nothingToRemoveSentence(settingsPath, window.key, percent.key)}${kept}`;
173
+ }
174
+ const removed = [
175
+ ...(window.action === 'removed' ? [`${window.key}${wasValue(window.previousTokens)}`] : []),
176
+ ...(percent.action === 'removed' ? [percentClause(percent)] : [])
177
+ ];
178
+ // Three write shapes, and the sentence names the RIGHT one: removals → name
179
+ // them; only a stale marker cleaned → say THAT; neither → only HUMAN values
180
+ // were found and the write is the opt-out row itself.
181
+ const what = removed.length > 0
182
+ ? `Removed ${removed.join(' and ')} from ${settingsPath}`
183
+ : staleMarkerCleaned(window, percent)
184
+ ? `Cleaned the stale peaks-loop provenance marker from ${settingsPath}`
185
+ : `Peaks-loop now leaves ${window.key} and ${percent.key} alone in ${settingsPath}`;
186
+ return `${what} and opted this project out, so later probes and installs stop writing either knob.${kept} Undo with \`peaks compact harness-window --reenable\`.`;
187
+ }
188
+ /** True when the ONLY thing this call cleaned was a marker with no value. */
189
+ function staleMarkerCleaned(window, percent) {
190
+ return window.ownership === 'stale-marker' || percent.ownership === 'stale-marker';
191
+ }
192
+ /**
193
+ * The `Kept …` clause for one knob whose value survived because it is the
194
+ * user's own. Empty for every other action, so the two halves share one wording
195
+ * and a kept window cannot go unreported while a kept percent is announced.
196
+ */
197
+ function keptClause(knob, percent = false) {
198
+ if (knob.action !== 'kept-human')
199
+ return '';
200
+ const what = percent
201
+ ? 'which is your own setting rather than a value peaks-loop wrote'
202
+ : 'which is your own value rather than one peaks-loop wrote';
203
+ // The note is bounded at its source (MED-2) — this reaches stdout and logs.
204
+ return ` Kept ${knob.key}=${knob.previousRawNote ?? 'a value'}, ${what}.`;
205
+ }
206
+ /**
207
+ * The sentence for a rollback that declined to write — one clause per reason, so
208
+ * a refusal never degrades to a bare token and never claims a write.
209
+ */
210
+ function describeResetRefusal(refusal, settingsPath, windowKey, percentKey) {
211
+ if (refusal === 'symlinked-settings') {
212
+ return `Nothing written — ${settingsPath} is a symlink (or a Windows junction), or the directory holding it is, so removing ${windowKey} or ${percentKey} would follow the link and overwrite the file it points at. Replace the link with a real file (or directory) and re-run.`;
213
+ }
214
+ return `Nothing written — ${settingsPath} is not a JSON object peaks-loop can safely edit, so ${windowKey} and ${percentKey} were left exactly as found.`;
215
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the READ/VERDICT half.
3
+ *
4
+ * The harness reads `CLAUDE_CODE_AUTO_COMPACT_WINDOW` and
5
+ * `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` (as declared by the active adapter) ONCE
6
+ * at process start — measured 2026-11-20. So after peaks-loop writes the
7
+ * project's settings file, the session already running keeps the old trigger,
8
+ * and "the settings are configured" and "the settings are in force" are two
9
+ * different facts. This module compares them and says so; it writes nothing.
10
+ *
11
+ * The write half (the percent sync, the defaults, the band) lives in
12
+ * `harness-compact-threshold-config.ts`, which is also where
13
+ * `HarnessCompactThresholdLocation` is declared — re-exported below so both
14
+ * halves are reachable from this module, which is the import path the CLI uses.
15
+ */
16
+ import { type HarnessCompactThresholdLocation } from './harness-compact-threshold-config.js';
17
+ export type { HarnessCompactThresholdLocation };
18
+ /**
19
+ * What one threshold read found, as BOUNDED notes rather than raw values.
20
+ *
21
+ * Each field is `boundedRawNote`'s fixed phrase, never the text the settings
22
+ * file holds, and is present only when that side carried the key (MED-2). The
23
+ * facts a reader needs survive: PRESENCE (is there a configuration on disk, and
24
+ * did this session have one) and whether a value does not parse — not what it
25
+ * said.
26
+ */
27
+ export interface HarnessCompactThresholdRawValues {
28
+ readonly windowRawNote?: string;
29
+ readonly percentRawNote?: string;
30
+ readonly envWindowRawNote?: string;
31
+ readonly envPercentRawNote?: string;
32
+ }
33
+ /** One threshold read: the file's pair, the session's pair, and the verdict. */
34
+ export interface HarnessCompactThresholdReadResult {
35
+ readonly settingsPath: string;
36
+ readonly windowKey: string;
37
+ readonly percentKey: string;
38
+ readonly configured: {
39
+ readonly windowTokens: number | null;
40
+ readonly percent: number | null;
41
+ };
42
+ readonly inForce: {
43
+ readonly windowTokens: number | null;
44
+ readonly percent: number | null;
45
+ };
46
+ readonly matches: boolean;
47
+ /** See `HarnessCompactThresholdRawValues`; absent means "no raw comparison". */
48
+ readonly raw?: HarnessCompactThresholdRawValues;
49
+ }
50
+ /** Read both knobs, file vs process env, and say whether they agree. */
51
+ export declare function readHarnessCompactThreshold(input: {
52
+ readonly location: HarnessCompactThresholdLocation;
53
+ readonly env?: NodeJS.ProcessEnv | undefined;
54
+ }): HarnessCompactThresholdReadResult;
55
+ /**
56
+ * The machine-readable verdict `peaks code context-now` puts on the envelope.
57
+ *
58
+ * Top-level `windowTokens`/`percent` are the CONFIGURED pair — the field
59
+ * reports "what the project says" — and `inForce` is what this session uses,
60
+ * so `matches` needs no second read. Built from parsed numbers, never from
61
+ * raw strings.
62
+ */
63
+ export interface HarnessThresholdVerdict {
64
+ readonly windowTokens: number | null;
65
+ readonly percent: number | null;
66
+ readonly configured: HarnessCompactThresholdReadResult['configured'];
67
+ readonly inForce: HarnessCompactThresholdReadResult['inForce'];
68
+ readonly matches: boolean;
69
+ }
70
+ export declare function buildHarnessThresholdVerdict(read: HarnessCompactThresholdReadResult): HarnessThresholdVerdict;
71
+ export declare function describeHarnessThresholdRestart(read: HarnessCompactThresholdReadResult): string | null;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Harness auto-compact THRESHOLD — the READ/VERDICT half.
3
+ *
4
+ * The harness reads `CLAUDE_CODE_AUTO_COMPACT_WINDOW` and
5
+ * `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` (as declared by the active adapter) ONCE
6
+ * at process start — measured 2026-11-20. So after peaks-loop writes the
7
+ * project's settings file, the session already running keeps the old trigger,
8
+ * and "the settings are configured" and "the settings are in force" are two
9
+ * different facts. This module compares them and says so; it writes nothing.
10
+ *
11
+ * The write half (the percent sync, the defaults, the band) lives in
12
+ * `harness-compact-threshold-config.ts`, which is also where
13
+ * `HarnessCompactThresholdLocation` is declared — re-exported below so both
14
+ * halves are reachable from this module, which is the import path the CLI uses.
15
+ */
16
+ import { parseHarnessCompactPercent, readSettingsObject, settingsEnvValue } from './harness-compact-threshold-config.js';
17
+ import { parseHarnessWindowTokens } from './harness-window-config.js';
18
+ import { boundedRawNote } from './harness-settings-file.js';
19
+ function agrees(configured, fileRaw, inForce) {
20
+ if (fileRaw === undefined)
21
+ return true;
22
+ return configured !== null && configured === inForce;
23
+ }
24
+ /** Read both knobs, file vs process env, and say whether they agree. */
25
+ export function readHarnessCompactThreshold(input) {
26
+ const env = input.env ?? process.env;
27
+ const settings = readSettingsObject(input.location.settingsPath);
28
+ const windowRaw = settingsEnvValue(settings, input.location.envVar);
29
+ const percentRaw = settingsEnvValue(settings, input.location.percentEnvVar);
30
+ const envWindowRaw = env[input.location.envVar];
31
+ const envPercentRaw = env[input.location.percentEnvVar];
32
+ const configured = {
33
+ windowTokens: parseHarnessWindowTokens(windowRaw),
34
+ percent: parseHarnessCompactPercent(percentRaw)
35
+ };
36
+ const inForce = {
37
+ windowTokens: parseHarnessWindowTokens(envWindowRaw),
38
+ percent: parseHarnessCompactPercent(envPercentRaw)
39
+ };
40
+ return {
41
+ settingsPath: input.location.settingsPath,
42
+ windowKey: input.location.envVar,
43
+ percentKey: input.location.percentEnvVar,
44
+ configured,
45
+ inForce,
46
+ matches: agrees(configured.windowTokens, windowRaw, inForce.windowTokens) &&
47
+ agrees(configured.percent, percentRaw, inForce.percent),
48
+ // Each side is bounded HERE, at the source (MED-2): this result is folded
49
+ // into envelope data that reaches logs. Presence survives as note presence.
50
+ raw: {
51
+ ...(windowRaw === undefined ? {} : { windowRawNote: boundedRawNote(windowRaw) }),
52
+ ...(percentRaw === undefined ? {} : { percentRawNote: boundedRawNote(percentRaw) }),
53
+ ...(envWindowRaw === undefined ? {} : { envWindowRawNote: boundedRawNote(envWindowRaw) }),
54
+ ...(envPercentRaw === undefined ? {} : { envPercentRawNote: boundedRawNote(envPercentRaw) })
55
+ }
56
+ };
57
+ }
58
+ export function buildHarnessThresholdVerdict(read) {
59
+ return {
60
+ windowTokens: read.configured.windowTokens,
61
+ percent: read.configured.percent,
62
+ configured: read.configured,
63
+ inForce: read.inForce,
64
+ matches: read.matches
65
+ };
66
+ }
67
+ /**
68
+ * One half of the pair, with the three states kept apart: a number, ABSENT
69
+ * (`unset`), and PRESENT BUT UNUSABLE — `a value that is not a number (N chars,
70
+ * not echoed here) (not a percentage)`. The third used to collapse into
71
+ * `unset`, which made a typo render as both sides agreeing on nothing and still
72
+ * demanding a restart.
73
+ */
74
+ function describeHalf(parsed, rawNote, unit, unusable) {
75
+ if (parsed !== null)
76
+ return `${String(parsed)}${unit}`;
77
+ // The note is already bounded at its source (MED-2); this line reaches stdout
78
+ // and the nextActions a consumer logs, so it never carries the raw text.
79
+ if (rawNote !== undefined)
80
+ return `${rawNote} (${unusable})`;
81
+ return `unset${unit}`;
82
+ }
83
+ /** One pair in the `N tokens × P%` form both halves of the restart line use. */
84
+ function describePair(pair, raw) {
85
+ const window = describeHalf(pair.windowTokens, raw?.windowRawNote, '', 'not a token count');
86
+ const percent = describeHalf(pair.percent, raw?.percentRawNote, '%', 'not a percentage');
87
+ return `${window} tokens × ${percent}`;
88
+ }
89
+ export function describeHarnessThresholdRestart(read) {
90
+ if (read.matches)
91
+ return null;
92
+ const fileRaw = read.raw === undefined
93
+ ? undefined
94
+ : { windowRawNote: read.raw.windowRawNote, percentRawNote: read.raw.percentRawNote };
95
+ const envRaw = read.raw === undefined
96
+ ? undefined
97
+ : {
98
+ windowRawNote: read.raw.envWindowRawNote,
99
+ percentRawNote: read.raw.envPercentRawNote
100
+ };
101
+ const halves = halvesConfiguredBy(read.configured, fileRaw);
102
+ const fileHalf = describeSide(halves, read.configured, fileRaw);
103
+ const sessionHalf = describeSide(halves, read.inForce, envRaw);
104
+ return (`Harness threshold NOT in force in this session: ${read.settingsPath} configures ` +
105
+ `${fileHalf}, but the running session uses ${sessionHalf} — the harness reads these ` +
106
+ 'variables once, at process start. Restart the session (or the window) so the new configuration applies.');
107
+ }
108
+ /** Which halves the FILE configures: a parsed value or a present note, either counts. */
109
+ function halvesConfiguredBy(configured, raw) {
110
+ return {
111
+ window: configured.windowTokens !== null || raw?.windowRawNote !== undefined,
112
+ percent: configured.percent !== null || raw?.percentRawNote !== undefined
113
+ };
114
+ }
115
+ /** One side of the restart line, in exactly the halves the FILE configures. */
116
+ function describeSide(halves, pair, raw) {
117
+ if (halves.window && halves.percent)
118
+ return describePair(pair, raw);
119
+ if (halves.percent)
120
+ return describeHalf(pair.percent, raw?.percentRawNote, '%', 'not a percentage');
121
+ if (halves.window)
122
+ return `${describeHalf(pair.windowTokens, raw?.windowRawNote, '', 'not a token count')} tokens`;
123
+ return 'no harness threshold';
124
+ }