peaks-loop 4.0.36 → 4.0.37

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 (88) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README-en.md +1 -1
  3. package/README.md +1 -1
  4. package/bin/peaks.js +71 -1
  5. package/dist/cli/cli-helpers.js +7 -0
  6. package/dist/cli/commands/_register.js +2 -0
  7. package/dist/cli/commands/best-practice-scan-command.d.ts +14 -1
  8. package/dist/cli/commands/best-practice-scan-command.js +67 -9
  9. package/dist/cli/commands/code-runtime-commands.js +21 -5
  10. package/dist/cli/commands/hooks-commands.js +10 -1
  11. package/dist/cli/commands/job-commands.js +107 -25
  12. package/dist/cli/commands/scan-commands.js +1 -1
  13. package/dist/cli/commands/web-commands.d.ts +28 -0
  14. package/dist/cli/commands/web-commands.js +327 -0
  15. package/dist/cli/commands/web-lifecycle-commands.d.ts +49 -0
  16. package/dist/cli/commands/web-lifecycle-commands.js +321 -0
  17. package/dist/services/best-practice/scan-orchestrator.d.ts +22 -0
  18. package/dist/services/best-practice/scan-orchestrator.js +14 -5
  19. package/dist/services/code/orchestrator-can-do.js +27 -4
  20. package/dist/services/context/context-audit-hint.d.ts +79 -0
  21. package/dist/services/context/context-audit-hint.js +150 -0
  22. package/dist/services/hooks/auto-compact-hook-install.js +10 -1
  23. package/dist/services/hooks/write-gate.js +88 -0
  24. package/dist/services/lint/detect-eslint.d.ts +2 -0
  25. package/dist/services/lint/detect-eslint.js +23 -9
  26. package/dist/services/lint/npx-resolver.d.ts +6 -0
  27. package/dist/services/lint/npx-resolver.js +38 -14
  28. package/dist/services/release/version-precheck-service.js +9 -2
  29. package/dist/services/scan/file-size-scan.d.ts +29 -0
  30. package/dist/services/scan/file-size-scan.js +63 -0
  31. package/dist/services/session/caller-binding-service.d.ts +24 -0
  32. package/dist/services/session/caller-binding-service.js +34 -0
  33. package/dist/services/session/getSessionDir.js +15 -10
  34. package/dist/services/skills/hooks-codegate-superpowers.d.ts +33 -0
  35. package/dist/services/skills/hooks-codegate-superpowers.js +34 -3
  36. package/dist/services/skills/hooks-settings-service.d.ts +10 -0
  37. package/dist/services/skills/hooks-settings-service.js +152 -61
  38. package/dist/services/slice/slice-check-service.d.ts +14 -0
  39. package/dist/services/slice/slice-check-service.js +110 -50
  40. package/dist/services/slice/slice-check-types.d.ts +12 -7
  41. package/dist/services/slice/slice-check-types.js +8 -3
  42. package/dist/services/slice/slice-decompose-runners.js +24 -21
  43. package/dist/services/sop/sop-check-service.js +12 -1
  44. package/dist/services/web/bounded-output.d.ts +34 -0
  45. package/dist/services/web/bounded-output.js +68 -0
  46. package/dist/services/web/browser-acquire.d.ts +14 -0
  47. package/dist/services/web/browser-acquire.js +84 -0
  48. package/dist/services/web/browser-session-manager.d.ts +111 -0
  49. package/dist/services/web/browser-session-manager.js +413 -0
  50. package/dist/services/web/daemon-entry.d.ts +1 -0
  51. package/dist/services/web/daemon-entry.js +65 -0
  52. package/dist/services/web/daemon-registry.d.ts +42 -0
  53. package/dist/services/web/daemon-registry.js +164 -0
  54. package/dist/services/web/daemon-supervisor.d.ts +144 -0
  55. package/dist/services/web/daemon-supervisor.js +455 -0
  56. package/dist/services/web/playwright-loader.d.ts +89 -0
  57. package/dist/services/web/playwright-loader.js +253 -0
  58. package/dist/services/web/snapshot-pruner.d.ts +48 -0
  59. package/dist/services/web/snapshot-pruner.js +241 -0
  60. package/dist/services/web/untrusted-envelope.d.ts +27 -0
  61. package/dist/services/web/untrusted-envelope.js +44 -0
  62. package/dist/services/web/web-artifact-paths.d.ts +79 -0
  63. package/dist/services/web/web-artifact-paths.js +163 -0
  64. package/dist/services/web/web-client.d.ts +19 -0
  65. package/dist/services/web/web-client.js +55 -0
  66. package/dist/services/web/web-daemon-service.d.ts +38 -0
  67. package/dist/services/web/web-daemon-service.js +416 -0
  68. package/dist/services/web/web-fallback.d.ts +70 -0
  69. package/dist/services/web/web-fallback.js +121 -0
  70. package/dist/services/web/web-install-service.d.ts +91 -0
  71. package/dist/services/web/web-install-service.js +346 -0
  72. package/dist/services/web/web-login-profile.d.ts +89 -0
  73. package/dist/services/web/web-login-profile.js +612 -0
  74. package/dist/services/web/web-login-staging.d.ts +27 -0
  75. package/dist/services/web/web-login-staging.js +173 -0
  76. package/dist/services/web/web-protocol.d.ts +58 -0
  77. package/dist/services/web/web-protocol.js +58 -0
  78. package/dist/services/web/web-status-report.d.ts +33 -0
  79. package/dist/services/web/web-status-report.js +47 -0
  80. package/dist/services/workspace/claude-settings-template.d.ts +41 -5
  81. package/dist/services/workspace/claude-settings-template.js +116 -64
  82. package/dist/services/workspace/workspace-claude-settings-materializer.js +5 -1
  83. package/dist/services/workspace/workspace-service.js +33 -0
  84. package/package.json +5 -5
  85. package/scripts/copy-templates.mjs +12 -0
  86. package/scripts/sync-version.mjs +20 -0
  87. package/skills/peaks-code/SKILL.md +10 -0
  88. package/skills/peaks-code/references/browser-workflow.md +10 -1
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `peaks web status|stop|install|login` — the daemon-lifecycle, acquisition and
3
+ * persistent-login verbs (slice S2, file 13; S3 adds `install`; S4 adds `login`).
4
+ *
5
+ * Attaches to the `web` parent handed in by `web-commands.ts` rather than
6
+ * looking it up: the lookup needs a fallback branch for "parent not registered
7
+ * yet" that cannot happen here, and one less branch is one less path to test.
8
+ *
9
+ * None of the four goes through the daemon. `status` must work when the daemon
10
+ * is dead or wedged — that IS its job (AC6) — and `stop` must work when the
11
+ * daemon answers nothing at all. Both therefore read the filesystem and the
12
+ * loopback port directly, and both keep working under S3's
13
+ * `PEAKS_WEB_DISABLED` gate (decision C2). `install` is a local download, so it
14
+ * needs no daemon either, and `login` opens its own headed browser (the daemon's
15
+ * is headless) for a user-level profile that is deliberately cross-project
16
+ * (design §10.2) — which is why it needs no session binding.
17
+ */
18
+ import type { Command } from 'commander';
19
+ import { type ProgramIO } from '../cli-helpers.js';
20
+ export declare function registerWebLifecycleCommands(web: Command, io: ProgramIO): void;
21
+ export declare function runWebStatus(io: ProgramIO, asJson: boolean): Promise<void>;
22
+ /**
23
+ * Stop the daemon and clear its records. `stopped` counts the daemons whose
24
+ * process is confirmed GONE by return — not merely the ones we signalled — so a
25
+ * caller that checks the process table right after this returns is not racing
26
+ * the teardown (AC6).
27
+ */
28
+ export declare function runWebStop(io: ProgramIO, asJson: boolean): Promise<void>;
29
+ /**
30
+ * `peaks web install` — the explicit form of the lazy download, plus R6's
31
+ * recovery path (`--force`).
32
+ *
33
+ * The gate is step 1 of the ordered gate (tech-doc §5.1): checked BEFORE the
34
+ * session lookup, before any lock and before anything that could touch the
35
+ * browser cache, so this verb cannot download under `PEAKS_WEB_DISABLED=1` even
36
+ * if every later step is broken (C2's matrix).
37
+ */
38
+ export declare function runWebInstall(io: ProgramIO, asJson: boolean, force: boolean): Promise<void>;
39
+ /**
40
+ * `peaks web login --profile <name>` — the only path that persists a login
41
+ * (design §2/§5, PRD R7).
42
+ *
43
+ * `--profile` is enforced HERE rather than with commander's `requiredOption`,
44
+ * because `requiredOption` refuses before this handler runs — and then the
45
+ * `PEAKS_WEB_DISABLED` gate would no longer be statement #1 (tech-doc §5.1,
46
+ * AC5). A profile-less login refuses without touching the profile root: no
47
+ * directory, no storage state, no browser.
48
+ */
49
+ export declare function runWebLogin(io: ProgramIO, asJson: boolean, rawProfile: string | undefined): Promise<void>;
@@ -0,0 +1,321 @@
1
+ import { fail, getErrorMessage, ok } from 'peaks-loop-shared/result';
2
+ import { resolveCanonicalProjectRoot } from '../../services/config/config-service.js';
3
+ import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
4
+ import { stopDaemon } from '../../services/web/daemon-supervisor.js';
5
+ import { degradedEnvelope } from '../../services/web/web-fallback.js';
6
+ import { INSTALL_SIZE_WARNING, installChromium, isWebDisabled, probeBrowserInstalled } from '../../services/web/web-install-service.js';
7
+ import { buildStatusReport } from '../../services/web/web-status-report.js';
8
+ import { cappedEcho, loginStorageStatePath, resolveProfileName, runHeadedLogin } from '../../services/web/web-login-profile.js';
9
+ import { addJsonOption, printResult } from '../cli-helpers.js';
10
+ export function registerWebLifecycleCommands(web, io) {
11
+ addJsonOption(web
12
+ .command('status')
13
+ .description('Report this session\'s web daemon instances (live / orphaned / stale). Works with no ' +
14
+ 'daemon running and never starts one.')).action(async (options) => {
15
+ await runWebStatus(io, options.json === true);
16
+ });
17
+ addJsonOption(web
18
+ .command('stop')
19
+ .description("Stop this session's web daemon and close its browser. Scoped to this project root and " +
20
+ 'session; another worktree is untouched, and a process that cannot be proven to be this ' +
21
+ "session's daemon is left running rather than signalled.")).action(async (options) => {
22
+ await runWebStop(io, options.json === true);
23
+ });
24
+ addJsonOption(web
25
+ .command('install')
26
+ .description('Download the pinned chromium for `peaks web` (one time, ~700 MB on disk). Needed only ' +
27
+ 'before the first browser op — a read-only verb never downloads. Refuses while ' +
28
+ 'PEAKS_WEB_DISABLED=1.')
29
+ .option('--force', "reinstall even if the browser is already present (Playwright's own recovery path)")).action(async (options) => {
30
+ await runWebInstall(io, options.json === true, options.force === true);
31
+ });
32
+ addJsonOption(web
33
+ .command('login')
34
+ .description('Open a HEADED browser so the user can log in themselves, then persist that session to ' +
35
+ '~/.peaks/web-profiles/<name>/storageState.json. Run it only when the user asks for a ' +
36
+ 'persistent login: it writes live session cookies to disk. --profile is required, and ' +
37
+ 'without it nothing is persisted.')
38
+ .option('--profile <name>', 'the login profile to persist (required; [a-z0-9._-], 1-64 chars — upper case folds to lower)')).action(async (options) => {
39
+ await runWebLogin(io, options.json === true, options.profile);
40
+ });
41
+ }
42
+ /** Resolve this project's session, or report `NO_SESSION` exactly once. */
43
+ function resolveSession() {
44
+ const projectRoot = resolveCanonicalProjectRoot(process.cwd());
45
+ const sessionId = getCurrentSessionId(projectRoot);
46
+ return sessionId === null ? null : { projectRoot, sessionId };
47
+ }
48
+ /** The shared `NO_SESSION` envelope for both lifecycle verbs. */
49
+ function noSession(command) {
50
+ return fail(command, 'NO_SESSION', 'No peaks session is bound to this project root', {}, [
51
+ 'Bind a session first (the LLM runs `peaks workspace init` on your behalf)'
52
+ ]);
53
+ }
54
+ /** Everything `stop` did NOT clean, said out loud rather than left implicit. */
55
+ function stopWarnings(result) {
56
+ const warnings = [];
57
+ const stuck = result.pids.length - result.stopped;
58
+ if (stuck > 0) {
59
+ warnings.push(`${String(stuck)} daemon process(es) did not exit after the stop request; they are recorded, ` +
60
+ 'so a later `peaks web stop` can try again');
61
+ }
62
+ if (result.orphanedPids.length > 0) {
63
+ warnings.push(`${String(result.orphanedPids.length)} daemon instance(s) are alive but could not be proven ` +
64
+ 'to be this session\'s daemon (no authenticated identity); the processes were left running, ' +
65
+ 'because a pid that cannot be proven is never signalled, and their records are kept so ' +
66
+ '`peaks web status` and a later `stop` still see them');
67
+ }
68
+ return warnings;
69
+ }
70
+ export async function runWebStatus(io, asJson) {
71
+ const command = 'peaks.web.status';
72
+ try {
73
+ const session = resolveSession();
74
+ if (session === null) {
75
+ printResult(io, noSession(command), asJson);
76
+ process.exitCode = 1;
77
+ return;
78
+ }
79
+ printResult(io, ok(command, await buildStatusReport(session.projectRoot, session.sessionId)), asJson);
80
+ }
81
+ catch (error) {
82
+ printResult(io, fail(command, 'WEB_STATUS_FAILED', `peaks web status failed: ${getErrorMessage(error)}`, {}, []), asJson);
83
+ process.exitCode = 1;
84
+ }
85
+ }
86
+ /**
87
+ * Stop the daemon and clear its records. `stopped` counts the daemons whose
88
+ * process is confirmed GONE by return — not merely the ones we signalled — so a
89
+ * caller that checks the process table right after this returns is not racing
90
+ * the teardown (AC6).
91
+ */
92
+ export async function runWebStop(io, asJson) {
93
+ const command = 'peaks.web.stop';
94
+ try {
95
+ const session = resolveSession();
96
+ if (session === null) {
97
+ printResult(io, noSession(command), asJson);
98
+ process.exitCode = 1;
99
+ return;
100
+ }
101
+ const result = await stopDaemon(session.projectRoot, session.sessionId);
102
+ printResult(io, ok(command, {
103
+ stopped: result.stopped,
104
+ pids: [...result.pids],
105
+ orphanedPids: [...result.orphanedPids]
106
+ }, stopWarnings(result)), asJson);
107
+ }
108
+ catch (error) {
109
+ printResult(io, fail(command, 'WEB_STOP_FAILED', `peaks web stop failed: ${getErrorMessage(error)}`, {}, []), asJson);
110
+ process.exitCode = 1;
111
+ }
112
+ }
113
+ /** The MCP fallback for `install`, named so the LLM can act on it (decision C3). */
114
+ const WEB_DISABLED_ACTIONS = [
115
+ 'Unset PEAKS_WEB_DISABLED to install locally',
116
+ 'Or call mcp__playwright__browser_install instead'
117
+ ];
118
+ /** The same fallback, minus the gate, for a download that failed on its own. */
119
+ const INSTALL_FAILED_ACTIONS = [
120
+ 'Retry `peaks web install`, or `peaks web install --force` after a partial download',
121
+ 'Or call mcp__playwright__browser_install instead'
122
+ ];
123
+ /**
124
+ * `peaks web install` — the explicit form of the lazy download, plus R6's
125
+ * recovery path (`--force`).
126
+ *
127
+ * The gate is step 1 of the ordered gate (tech-doc §5.1): checked BEFORE the
128
+ * session lookup, before any lock and before anything that could touch the
129
+ * browser cache, so this verb cannot download under `PEAKS_WEB_DISABLED=1` even
130
+ * if every later step is broken (C2's matrix).
131
+ */
132
+ export async function runWebInstall(io, asJson, force) {
133
+ const command = 'peaks.web.install';
134
+ try {
135
+ if (isWebDisabled(process.env)) {
136
+ printResult(io, fail(command, 'WEB_DISABLED', '`peaks web install` will not download anything while PEAKS_WEB_DISABLED=1', {}, WEB_DISABLED_ACTIONS), asJson);
137
+ process.exitCode = 1;
138
+ return;
139
+ }
140
+ const session = resolveSession();
141
+ if (session === null) {
142
+ printResult(io, noSession(command), asJson);
143
+ process.exitCode = 1;
144
+ return;
145
+ }
146
+ // R6's other half: a missing executable is the only reason to download, so
147
+ // an already-complete install is reported without spawning anything. The
148
+ // shortcut still names `--force`, because it is the only escape if a browser
149
+ // op keeps failing against a probe that says otherwise (R7).
150
+ const before = await probeBrowserInstalled();
151
+ if (before.installed && !force) {
152
+ printResult(io, ok(command, {
153
+ installed: true,
154
+ downloaded: false,
155
+ version: before.version,
156
+ executablePath: before.executablePath
157
+ }, [], ['If browser ops still fail, re-run `peaks web install --force`']), asJson);
158
+ return;
159
+ }
160
+ // R2: name the size on the human channel BEFORE the blocking download —
161
+ // this is the only point at which "before" is still available.
162
+ io.stderr(`warning: ${INSTALL_SIZE_WARNING}`);
163
+ const outcome = await installChromium({ force });
164
+ if (!outcome.ok) {
165
+ // R2: a failed download is a structured tier-3 envelope, never a stack.
166
+ printResult(io, degradedEnvelope('install', `${outcome.code}: ${outcome.message}`), asJson);
167
+ process.exitCode = 1;
168
+ return;
169
+ }
170
+ // `after.installed` is CONSULTED, not merely carried (R7). An installer
171
+ // that exits 0 without landing the browser — a proxy that filters the CDN, a
172
+ // pinned npx resolving into a different cache root, a partial install — used
173
+ // to report `ok: true, downloaded: true, installed: false` with exit 0 and
174
+ // nothing to do next.
175
+ const after = await probeBrowserInstalled();
176
+ if (!after.installed) {
177
+ printResult(io, degradedEnvelope('install', 'WEB_INSTALL_INCOMPLETE: `playwright install chromium` exited 0 but the browser it ' +
178
+ 'names is still missing'), asJson);
179
+ process.exitCode = 1;
180
+ return;
181
+ }
182
+ printResult(io, ok(command, {
183
+ installed: true,
184
+ downloaded: true,
185
+ version: after.version,
186
+ executablePath: after.executablePath
187
+ }, [...outcome.warnings]), asJson);
188
+ }
189
+ catch (error) {
190
+ printResult(io, fail(command, 'WEB_INSTALL_FAILED', `peaks web install failed: ${getErrorMessage(error)}`, {}, INSTALL_FAILED_ACTIONS), asJson);
191
+ process.exitCode = 1;
192
+ }
193
+ }
194
+ /** What a caller can actually do after a refusal or an unclosed login. */
195
+ const LOGIN_NEXT_ACTIONS = [
196
+ 'Re-run `peaks web login --profile <name>` when the user is ready to log in',
197
+ 'Close the headed browser window when the login is finished — closing it is what saves the session'
198
+ ];
199
+ /**
200
+ * The fold, said out loud on the one path that CANNOT fold (S4 repair, code F5 /
201
+ * security S5).
202
+ *
203
+ * The gate is statement #1 (tech-doc §5.1), so on this path the name was never
204
+ * validated and never folded — which is exactly why this refusal must not look
205
+ * like it disagrees with a live run about the profile. It reports what happened
206
+ * (nothing was folded, this is what was typed) rather than implying a canonical
207
+ * name was used, and it claims nothing about whether the name would be accepted.
208
+ * The echo is capped by the same helper the guard uses.
209
+ */
210
+ function gateFoldNotice(rawProfile) {
211
+ if (rawProfile === undefined || rawProfile === rawProfile.toLowerCase()) {
212
+ return [];
213
+ }
214
+ return [
215
+ `--profile ${JSON.stringify(cappedEcho(rawProfile))} was NOT folded: PEAKS_WEB_DISABLED is ` +
216
+ 'checked before the profile name, so this refusal echoes what was typed, not a canonical ' +
217
+ 'profile. A run that gets past the gate lower-cases the name first.'
218
+ ];
219
+ }
220
+ /**
221
+ * `peaks web login --profile <name>` — the only path that persists a login
222
+ * (design §2/§5, PRD R7).
223
+ *
224
+ * `--profile` is enforced HERE rather than with commander's `requiredOption`,
225
+ * because `requiredOption` refuses before this handler runs — and then the
226
+ * `PEAKS_WEB_DISABLED` gate would no longer be statement #1 (tech-doc §5.1,
227
+ * AC5). A profile-less login refuses without touching the profile root: no
228
+ * directory, no storage state, no browser.
229
+ */
230
+ export async function runWebLogin(io, asJson, rawProfile) {
231
+ const command = 'peaks.web.login';
232
+ // Declared out here so the CATCH can report it too (S4 repair, security S5 /
233
+ // code F3): a launch failure happens AFTER the name was resolved, so a run
234
+ // that dies on `WEB_LAUNCH_FAILED` knows the canonical name just as well as
235
+ // one that succeeds, and must not be the one path where the fold is silent.
236
+ let foldWarnings = [];
237
+ try {
238
+ if (isWebDisabled(process.env)) {
239
+ const gateEnvelope = degradedEnvelope('login', 'PEAKS_WEB_DISABLED=1', 3, rawProfile === undefined ? {} : { profile: cappedEcho(rawProfile) });
240
+ printResult(io, { ...gateEnvelope, warnings: [...gateEnvelope.warnings, ...gateFoldNotice(rawProfile)] }, asJson);
241
+ process.exitCode = 1;
242
+ return;
243
+ }
244
+ if (rawProfile === undefined || rawProfile === '') {
245
+ printResult(io, fail(command, 'WEB_PROFILE_REQUIRED', '`peaks web login` requires --profile <name>: it is the only verb that persists a login, ' +
246
+ 'and there is no default profile — without a name nothing is written', {}, LOGIN_NEXT_ACTIONS), asJson);
247
+ process.exitCode = 1;
248
+ return;
249
+ }
250
+ let profile;
251
+ try {
252
+ profile = resolveProfileName(rawProfile);
253
+ }
254
+ catch (error) {
255
+ // The helper's own message already begins with the code, and `fail()`
256
+ // puts the code in front of the message again — strip it, so human output
257
+ // does not read `WEB_PROFILE_NAME_INVALID: WEB_PROFILE_NAME_INVALID: …`.
258
+ const detail = getErrorMessage(error).replace(/^WEB_PROFILE_NAME_INVALID:\s*/, '');
259
+ printResult(io, fail(command, 'WEB_PROFILE_NAME_INVALID', detail, {}, LOGIN_NEXT_ACTIONS), asJson);
260
+ process.exitCode = 1;
261
+ return;
262
+ }
263
+ // The fold (see `resolveProfileName`) is never silent: `--profile Work` and
264
+ // `--profile work` are one profile, and the caller is told which name was
265
+ // used. The two sides are deliberately not the same value — the left is what
266
+ // the caller TYPED (echoed through `cappedEcho`, since it is still caller
267
+ // input), the right is the canonical name the run uses from here on.
268
+ foldWarnings =
269
+ rawProfile === profile
270
+ ? []
271
+ : [`--profile ${JSON.stringify(cappedEcho(rawProfile))} resolved to the profile "${profile}"`];
272
+ const outcome = await runHeadedLogin({
273
+ profile,
274
+ announce: () => {
275
+ io.stderr([
276
+ `peaks web login: a headed browser is open for profile "${profile}" — log in there yourself.`,
277
+ 'Close the browser window when you are done: that is what saves the session, to ' +
278
+ `${loginStorageStatePath(profile)}.`,
279
+ 'The session is captured while the window is open, so the saved state can be up to a ' +
280
+ 'second older than what you see — finish logging in before you close it.'
281
+ ].join('\n'));
282
+ }
283
+ });
284
+ if (!outcome.ok) {
285
+ // S1's F1. This is the ONLY path on which the runner returns `ok: false`
286
+ // AND a warning (a login whose context never opened and whose headed
287
+ // browser then refused to close — a browser nothing can then stop,
288
+ // because `stop` is daemon-scoped). `fail()` hard-codes `warnings: []`, so
289
+ // the warning is spread back over it, the shape `degradedEnvelope` uses.
290
+ printResult(io, {
291
+ ...fail(command, outcome.code, outcome.message, {}, LOGIN_NEXT_ACTIONS),
292
+ warnings: [...foldWarnings, ...outcome.warnings]
293
+ }, asJson);
294
+ process.exitCode = 1;
295
+ return;
296
+ }
297
+ // Counts, never the values: the file holds live session cookies and this
298
+ // envelope reaches a terminal (and a transcript).
299
+ const envelope = ok(command, {
300
+ profile: outcome.profile,
301
+ storageStatePath: outcome.storageStatePath,
302
+ bytes: outcome.bytes,
303
+ cookies: outcome.cookies,
304
+ origins: outcome.origins
305
+ }, [...foldWarnings, ...outcome.warnings]);
306
+ // R5: a capture that was written but could not be read back is `ok` — the
307
+ // file did land, so it is not a failure — but it is not a clean success
308
+ // either. The code is what an ok-only consumer cannot miss.
309
+ printResult(io, outcome.code === '' ? envelope : { ...envelope, code: outcome.code }, asJson);
310
+ }
311
+ catch (error) {
312
+ printResult(io, {
313
+ ...fail(command, 'WEB_LOGIN_FAILED', `peaks web login failed: ${getErrorMessage(error)}`, {}, LOGIN_NEXT_ACTIONS),
314
+ // A run that reached `resolveProfileName` knows the canonical name, so a
315
+ // failure before the browser was even up reports the fold like every
316
+ // other path (S4 repair, code F5 / security S5).
317
+ warnings: foldWarnings
318
+ }, asJson);
319
+ process.exitCode = 1;
320
+ }
321
+ }
@@ -12,6 +12,14 @@
12
12
  * the orchestrator's source-priority logic is testable end-to-end.
13
13
  * Real MCP wiring is a future slice — the stubs are clearly marked.
14
14
  *
15
+ * Because a stub result is indistinguishable from a real one by shape,
16
+ * every result carries `synthetic`: true when the fragments came from a
17
+ * built-in stub rather than a caller-injected lookup (`context7Lookup` /
18
+ * `webSearchLookup`). Callers MUST NOT present a synthetic result as a
19
+ * scan result — `source` alone says which transport answered, not whether
20
+ * anything real was consulted. The stub seam stays injectable so the real
21
+ * wiring (and its tests) can replace it without touching this contract.
22
+ *
15
23
  * The orchestrator emits structured log lines via the injected `io`
16
24
  * (stdout for progress, stderr for warnings) so a CLI caller can see
17
25
  * which fallback path was taken.
@@ -28,6 +36,12 @@ export type ScanResult = {
28
36
  readonly fragments: readonly DocFragment[];
29
37
  readonly source: ScanSource;
30
38
  readonly elapsedMs: number;
39
+ /**
40
+ * `true` when the fragments came from the built-in stub lookups instead
41
+ * of a real documentation lookup. A synthetic result is not a scan
42
+ * result: it must never be rendered as one or gated on.
43
+ */
44
+ readonly synthetic: boolean;
31
45
  };
32
46
  export type ScanOptions = {
33
47
  readonly intent: string;
@@ -35,5 +49,13 @@ export type ScanOptions = {
35
49
  readonly projectRoot: string;
36
50
  readonly io: ProgramIO;
37
51
  readonly context7TimeoutMs?: number;
52
+ /** Test / real-wiring seam: replaces the priority-1 Context7 stub. */
53
+ readonly context7Lookup?: LookupFn;
54
+ /** Test / real-wiring seam: replaces the priority-2 WebSearch stub. */
55
+ readonly webSearchLookup?: LookupFn;
38
56
  };
57
+ export type LookupFn = (intent: string, language: string) => Promise<{
58
+ readonly ok: boolean;
59
+ readonly results: readonly DocFragment[];
60
+ }>;
39
61
  export declare function scanBestPractice(opts: ScanOptions): Promise<ScanResult>;
@@ -35,11 +35,17 @@ const defaultWebSearchLookup = async (intent, language) => {
35
35
  export async function scanBestPractice(opts) {
36
36
  const timeoutMs = opts.context7TimeoutMs ?? DEFAULT_CONTEXT7_TIMEOUT_MS;
37
37
  const startedAt = Date.now();
38
+ const context7Lookup = opts.context7Lookup ?? defaultContext7Lookup;
39
+ const webSearchLookup = opts.webSearchLookup ?? defaultWebSearchLookup;
40
+ // A branch is synthetic when the lookup that answered it is a stub. The
41
+ // fallback branch counts as synthetic if ANY stub took part in the chain.
42
+ const context7Stub = opts.context7Lookup === undefined;
43
+ const webSearchStub = opts.webSearchLookup === undefined;
38
44
  opts.io.stdout(`[scan-orchestrator] querying context7 for "${opts.intent}" (${opts.language})`);
39
45
  let context7Outcome = null;
40
46
  let context7Error = null;
41
47
  try {
42
- const ctxPromise = defaultContext7Lookup(opts.intent, opts.language);
48
+ const ctxPromise = context7Lookup(opts.intent, opts.language);
43
49
  const ctxTimer = new Promise((_, reject) => {
44
50
  setTimeout(() => reject(new Error(`context7 timeout after ${timeoutMs}ms`)), timeoutMs).unref();
45
51
  });
@@ -54,14 +60,15 @@ export async function scanBestPractice(opts) {
54
60
  results: context7Outcome.results,
55
61
  fragments: context7Outcome.results,
56
62
  source: 'context7',
57
- elapsedMs: Date.now() - startedAt
63
+ elapsedMs: Date.now() - startedAt,
64
+ synthetic: context7Stub
58
65
  };
59
66
  }
60
67
  opts.io.stdout(`[scan-orchestrator] falling back to websearch for "${opts.intent}" (${opts.language})`);
61
68
  let webOutcome = null;
62
69
  let webError = null;
63
70
  try {
64
- webOutcome = await defaultWebSearchLookup(opts.intent, opts.language);
71
+ webOutcome = await webSearchLookup(opts.intent, opts.language);
65
72
  }
66
73
  catch (err) {
67
74
  webError = err instanceof Error ? err.message : String(err);
@@ -72,7 +79,8 @@ export async function scanBestPractice(opts) {
72
79
  results: webOutcome.results,
73
80
  fragments: webOutcome.results,
74
81
  source: 'websearch',
75
- elapsedMs: Date.now() - startedAt
82
+ elapsedMs: Date.now() - startedAt,
83
+ synthetic: webSearchStub
76
84
  };
77
85
  }
78
86
  opts.io.stderr('[scan-orchestrator] both sources empty; returning empty fallback');
@@ -80,6 +88,7 @@ export async function scanBestPractice(opts) {
80
88
  results: [],
81
89
  fragments: [],
82
90
  source: 'fallback',
83
- elapsedMs: Date.now() - startedAt
91
+ elapsedMs: Date.now() - startedAt,
92
+ synthetic: context7Stub || webSearchStub
84
93
  };
85
94
  }
@@ -35,7 +35,28 @@
35
35
  import { execFile } from 'node:child_process';
36
36
  import { promisify } from 'node:util';
37
37
  import { randomUUID } from 'node:crypto';
38
+ // 2026-09-10 D1: both probes used to spawn a bare `peaks`. On Windows that name
39
+ // resolves to a `.cmd` shim, which `execFile` cannot run: it does not apply
40
+ // PATHEXT, and Node >= 20 refuses to spawn `.cmd`/`.bat` at all without
41
+ // `shell: true` (CVE-2024-27980). So Q2 reported "sub-agent dispatch
42
+ // unavailable" and Q4 reported ratio 0 for every slice-spec on Windows —
43
+ // phantom blockers produced by the spawn, not by the CLI. Running this tree's
44
+ // own CLI entry through `process.execPath` needs no shell and no shim.
45
+ import { cliEntryPath, interpreterArgs } from '../web/daemon-supervisor.js';
38
46
  const execFileAsync = promisify(execFile);
47
+ /** Sentinel: no explicit binary was injected, so resolve this tree's own CLI. */
48
+ const DEFAULT_PEAKS_BIN = 'peaks';
49
+ /**
50
+ * Spawn argv for the peaks CLI. An explicitly injected `peaksBin` (the
51
+ * `--peaks-bin` test seam) is spawned verbatim; the default sentinel resolves
52
+ * to this tree's own CLI entry, interpreted by the running Node.
53
+ */
54
+ function peaksSpawn(peaksBin) {
55
+ if (peaksBin !== DEFAULT_PEAKS_BIN) {
56
+ return { command: peaksBin, args: [] };
57
+ }
58
+ return { command: process.execPath, args: interpreterArgs(cliEntryPath()) };
59
+ }
39
60
  /** Slice 2026-08-05-orchestrator-can-do-probe: red-line threshold. */
40
61
  export const ORCHESTRATOR_REDLINE_RATIO = 0.95;
41
62
  /** Slice 2026-08-05-orchestrator-can-do-probe: pre-compact threshold. */
@@ -126,9 +147,10 @@ export function detectRequiresUserDecision(sliceSpec) {
126
147
  * true when the subprocess exits 0. Resolves to false on spawn
127
148
  * failure or non-zero exit.
128
149
  */
129
- export async function probeSubAgentAvailable(projectRoot, peaksBin = 'peaks') {
150
+ export async function probeSubAgentAvailable(projectRoot, peaksBin = DEFAULT_PEAKS_BIN) {
130
151
  try {
131
- await execFileAsync(peaksBin, ['sub-agent', 'dispatch', '--role', 'rd', '--help'], {
152
+ const { command, args } = peaksSpawn(peaksBin);
153
+ await execFileAsync(command, [...args, 'sub-agent', 'dispatch', '--role', 'rd', '--help'], {
132
154
  cwd: projectRoot,
133
155
  timeout: 5000,
134
156
  });
@@ -143,9 +165,10 @@ export async function probeSubAgentAvailable(projectRoot, peaksBin = 'peaks') {
143
165
  * field. Falls back to {ratio: 0, source: 'unavailable'} when the
144
166
  * subprocess fails or returns malformed JSON.
145
167
  */
146
- export async function probeContextRatio(projectRoot, peaksBin = 'peaks') {
168
+ export async function probeContextRatio(projectRoot, peaksBin = DEFAULT_PEAKS_BIN) {
147
169
  try {
148
- const { stdout } = await execFileAsync(peaksBin, ['code', 'context-now', '--project', projectRoot, '--json'], {
170
+ const { command, args } = peaksSpawn(peaksBin);
171
+ const { stdout } = await execFileAsync(command, [...args, 'code', 'context-now', '--project', projectRoot, '--json'], {
149
172
  cwd: projectRoot,
150
173
  timeout: 10000,
151
174
  });
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Slice 2026-09-10-three-fixes (Slice 2) — proactive context-consumer hint.
3
+ *
4
+ * `peaks code context-audit` (Slice A, same day) already reports WHAT fills
5
+ * the window, but only when someone remembers to run it. The Step 0.8
6
+ * PreToolUse gate (`peaks code gate-step-08`) runs before every Bash call, so
7
+ * it is the natural place to surface the single largest consumer — provided
8
+ * that costs nothing measurable.
9
+ *
10
+ * Cost contract (the whole point of this module):
11
+ * - The ratio probe is the cheap, adapter-driven `readContextPercent`
12
+ * (env-var → statusline file read; the transcript fallback is a
13
+ * bounded backwards scan, never a whole-file read).
14
+ * - The expensive part — the transcript scan inside `auditContext` — runs
15
+ * at most ONCE per TTL window. Its result is cached under
16
+ * `.peaks/_runtime/<sid>/context-audit-hint.json`; a fresh entry
17
+ * short-circuits the scan entirely.
18
+ * - Every failure is fail-soft: a missing/corrupt cache, an unavailable
19
+ * transcript, an adapter that cannot locate one — all yield `null`
20
+ * (emit nothing). The gate never blocks and never gains more than ONE
21
+ * line.
22
+ *
23
+ * The cache deliberately records FAILED audits too (with `available:false`),
24
+ * so a broken transcript cannot turn every Bash call back into a scan.
25
+ */
26
+ import { type ContextAuditInput, type ContextAuditResult } from './context-audit.js';
27
+ /** Only surface a hint once the window is this full. */
28
+ export declare const CONTEXT_HINT_RATIO_THRESHOLD = 0.7;
29
+ /** Minimum cache TTL — a fresh entry must skip the transcript scan. */
30
+ export declare const CONTEXT_HINT_CACHE_TTL_MS: number;
31
+ /** Per-session cache file name (under `.peaks/_runtime/<sid>/`). */
32
+ export declare const CONTEXT_HINT_CACHE_FILE_NAME = "context-audit-hint.json";
33
+ /** Cached top-consumer snapshot — one audit result, no transcript content. */
34
+ export interface ContextHintCacheEntry {
35
+ /** Epoch ms when the audit ran (TTL anchor). */
36
+ readonly cachedAt: number;
37
+ /** False when the audit could not read the transcript. */
38
+ readonly available: boolean;
39
+ /** Ratio observed when the audit ran (informational). */
40
+ readonly ratio: number;
41
+ readonly tool: string | null;
42
+ readonly key: string | null;
43
+ readonly bytes: number;
44
+ readonly pctOfTotal: number;
45
+ readonly count: number;
46
+ }
47
+ export interface ContextAuditHintInput {
48
+ readonly projectRoot: string;
49
+ readonly sessionId: string;
50
+ readonly outerSessionId?: string | null | undefined;
51
+ readonly env?: NodeJS.ProcessEnv | undefined;
52
+ /** Clock override (test seam). */
53
+ readonly nowMs?: number | undefined;
54
+ /** Cache path override (test seam; default is per-session under `_runtime`). */
55
+ readonly cachePath?: string | undefined;
56
+ /** Ratio probe override (test seam). Returns null when unknown. */
57
+ readonly probeRatio?: (() => number | null) | undefined;
58
+ /** Audit runner override (test seam; lets a test count scans). */
59
+ readonly runAudit?: ((input: ContextAuditInput) => ContextAuditResult) | undefined;
60
+ }
61
+ /**
62
+ * `<projectRoot>/.peaks/_runtime/<sid>/context/context-audit-hint.json`
63
+ * (gitignored). The `context/` bucket mirrors the existing `<sid>/txt/`
64
+ * convention so session-id artifacts stay under `.peaks/_runtime/<sid>/`.
65
+ */
66
+ export declare function contextHintCachePath(projectRoot: string, sessionId: string): string;
67
+ /**
68
+ * The single line the gate may append. Names ONE consumer — the largest by
69
+ * tool-result bytes — plus the share and call count that justify the number.
70
+ */
71
+ export declare function formatContextHintLine(entry: ContextHintCacheEntry): string;
72
+ /**
73
+ * Build the ONE optional hint line for the Step 0.8 gate.
74
+ *
75
+ * Returns `null` when: the ratio is unknown or below 0.70, the cache (fresh)
76
+ * says the audit was unavailable, the fresh audit found no groups, or
77
+ * anything throws. Never throws, never blocks.
78
+ */
79
+ export declare function buildContextAuditHint(input: ContextAuditHintInput): string | null;