peaks-loop 4.2.0 → 4.2.1

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 (42) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +108 -0
  3. package/contracts/readonly-argv-whitelist.json +116 -0
  4. package/dist/cli/commands/code-auto-compact-command.js +15 -3
  5. package/dist/cli/commands/core/skill-presence-housekeeping-commands.js +7 -1
  6. package/dist/cli/commands/mut-commands-helpers.js +42 -36
  7. package/dist/cli/commands/project-context-command.js +7 -2
  8. package/dist/cli/commands/workspace/init-actions.js +5 -0
  9. package/dist/cli/commands/workspace/init-context.js +1 -0
  10. package/dist/services/code/auto-compact-artifacts.js +42 -10
  11. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  12. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  13. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  14. package/dist/services/code/auto-compact-envelopes.js +18 -4
  15. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  16. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  17. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  18. package/dist/services/mcp/context-tool.d.ts +3 -0
  19. package/dist/services/mcp/context-tool.js +135 -0
  20. package/dist/services/mcp/surface.js +7 -1
  21. package/dist/services/mcp/tools.js +3 -1
  22. package/dist/services/memory/project-context-service.d.ts +10 -1
  23. package/dist/services/memory/project-context-service.js +13 -6
  24. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  25. package/dist/services/prd/project-scan-body-tables.js +185 -0
  26. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  27. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  28. package/dist/services/prd/project-scan-content.d.ts +24 -0
  29. package/dist/services/prd/project-scan-content.js +207 -0
  30. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  31. package/dist/services/prd/project-scan-existing-state.js +61 -0
  32. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  33. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  34. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  35. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  36. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  37. package/dist/services/prd/project-scan-library-versions.js +135 -0
  38. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  39. package/dist/services/prd/project-scan-techstack.js +167 -0
  40. package/package.json +6 -6
  41. package/skills/peaks-code/SKILL.md +1 -1
  42. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "metadata": {
3
3
  "pluginRoot": ".",
4
- "version": "4.2.0"
4
+ "version": "4.2.1"
5
5
  },
6
6
  "plugins": [
7
7
  {
8
8
  "name": "peaks-loop",
9
9
  "description": "Loop Engineering CLI — workflow primitive / loop guards / evaluators / slice orchestration",
10
- "version": "4.2.0",
10
+ "version": "4.2.1",
11
11
  "author": {
12
12
  "name": "SquabbyZ"
13
13
  },
package/CHANGELOG.md CHANGED
@@ -1,5 +1,113 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.2.1 — 2026-11-17(auto-compact 真正接上恢复;project-scan 不再冻结)
4
+
5
+ **版本级别**:**patch**(三个缺陷修复 + 一个 MCP 工具;无门禁阈值放宽,无 schema 变更)。
6
+ 门禁天花板只降不升:`fileSizeExcessLines` 21801 → 21715。
7
+
8
+ **一句话:这一版让 `.peaks/project-scan/project-scan.md` 不再装完就冻结,让 auto-compact 在子目录下
9
+ 不再静默失效,并让压缩后的恢复真的拿到内容,而不是一个空壳。**
10
+
11
+ ### 1. `project-scan.md` 从「写一次就冻结」改成「机器字段就地刷新」
12
+
13
+ `bootstrapProjectScan` 过去写完一次就永远跳过:盘上只要有 `schemaVersion: 1`,之后每次运行都报
14
+ `skipped: true`,`libraryVersions` 冻结在装机当天的版本。而该文件是**消费方契约**——peaks-rd 读它的
15
+ `## Library versions` 去比对 `schemas/library-breaking-changes.data.json`,它同时被声明为 Gate C 证据,
16
+ 所以一份冻结的版本表会让破坏性变更检查**在过期输入上通过**。
17
+
18
+ 死选项 `force`(声明了、读了、但没有任何调用方传 `true`)替换为只重写 `capturedAt` / `techStack` /
19
+ `libraryVersions` 三个字段的就地刷新,其余字节原样保留。`peaks project context` 默认刷新,
20
+ `--no-project-scan-refresh` 关闭。
21
+
22
+ 同批修掉的、每个都由一次复现发现的:
23
+
24
+ - **CRLF**。`core.autocrlf=true` 是 Windows 默认,版本探测和 frontmatter 切分都改成 `\r?\n` 锚定。
25
+ 此前 CRLF 文件会落到 CREATE 分支,**销毁**手写架构说明、锁定版本注释和 memory 块。
26
+ - 文件**存在但无法归类**时刷新,绝不重建。
27
+ - `libraryVersions` 的 specifier 读**根 manifest**。取扫描首行时,除 `packages/*` 外的 workspace glob
28
+ (`apps/*`、`libs/*`)会把工作区的 `^5.4.0` 记成项目版本,覆盖根上的 `^5.7.2`。
29
+ - 正文 `## Library versions` 表跟随 frontmatter(改版本单元格、补缺行、保留 Notes 列)。
30
+ 修复前实测:frontmatter 32 个包,正文表 21 行。
31
+ - **正文散文永不覆盖**:`## Tech stack` 表只填空单元格,截断的派生 `buildTool` 不得替换更完整的作者行。
32
+ - 源码探测覆盖 `app/`、`server/` 和扁平根目录,这些布局不再被误判为 0-1 而永远陈旧。
33
+ - 读到坏的 `package.json` 时降级,不再让 `peaks project context` 失败。
34
+
35
+ ### 2. `AUTO_COMPACT_NO_SESSION`:hook 在子目录下静默失效
36
+
37
+ `peaks code auto-compact` 由 PreToolUse hook 在每次 Bash/Task 调用时触发,参数是 `--project .`。
38
+ `.` 相对**hook 的工作目录**解析,所以在子目录里跑的工具调用会让它去子目录找
39
+ `.peaks/_runtime/session.json`,找不到就返回 `AUTO_COMPACT_NO_SESSION`。
40
+
41
+ 比报错更糟的是:**hook 忽略退出码**,所以从那一刻起整个会话的 auto-compact 静默失效。
42
+ 2026-11-16 实测:同一条命令在仓库根成功(ratio 31.8%),在 `./src` 失败。
43
+
44
+ 命令构造 input 时直接用了 `opts.project`,从未做规范化,而该文件自己的注释声称 `.` 会被
45
+ `resolveCanonicalProjectRoot` 提升到 git 根——**注释描述的调用根本不存在**。现在真正调用了。
46
+
47
+ 曾尝试把 hook 改成 `${CLAUDE_PROJECT_DIR:-.}` 并回退:本项目的 Windows hook 由 PowerShell 承载,
48
+ 变量不展开,`--project` 收到字面文本、运行器试图 `mkdir` 同名目录。CLI 侧修复不依赖任何展开。
49
+
50
+ ### 3. 压缩后的 checkpoint 从空壳变成可用
51
+
52
+ `writePreCompactCheckpoint` 把 post-compact 探测器要读的字段全部写空:`openQuestions` /
53
+ `recentDecisions` / `recentArtifactPaths` 是 `[]`,`gitStatus` 是 `''`,`currentPlan` 只有一句
54
+ "resume from auto-decisions.md"。于是恢复时**无从恢复**。
55
+
56
+ 实测:一个有活跃 request、且 `txt/auto-decisions.md` 有内容的会话,checkpoint 仍带 7 个空字段。
57
+ 修复后只剩 1 个(`todoState`,无可信数据源,保持为空而不是编造)。
58
+
59
+ 数据一直都在盘上,只是没被读:决策日志给出 resume hint 与 next actions,会话的 request 产物给出
60
+ 恢复时先开的路径,`git status --porcelain -b` 给出工作树状态。
61
+
62
+ ### 4. 新增 MCP 工具 `peaks_context_compress`
63
+
64
+ 在可选 rid/role 下返回工作流当前状态的事实摘要——活跃技能、gate、上下文占比、request 状态与产物路径
65
+ ——供模型在把旧轮次移出工作集**之前**取用。
66
+
67
+ **它不是压缩。** MCP 工具返回的是一个**值**,这里的值是文本。billion-context 的压缩靠坐在网络路径上
68
+ 改写出站请求体,peaks-loop 不在那个位置(其 `writeMainSessionCompactIntent` 的头注释写明:
69
+ hook 只能观察或否决,不能发起)。它不减少任何 token 账单,也不替代 `/compact`;收益在「不必重读」。
70
+
71
+ 它**按组合方式保持只读**:只运行已为 `peaks_status` 白名单化的 argv,不新增 CLI 命令,不新增 argv,
72
+ `validateSurface` 仍在漂移时拒绝启动。
73
+
74
+ ### 5. `peaks mut` 从「完全不可用」修成「可跑」
75
+
76
+ 两处独立的工具链缺陷,都让变异测试在任何项目上都无法启动:
77
+
78
+ - **沙箱复制 `.peaks/` 撞上 Windows junction**。Stryker 把项目整树复制进
79
+ `.stryker-tmp/sandbox-*`,而 `.peaks/_runtime/` 里存着往期会话的 scratch fixture,
80
+ 含 junction/符号链接,复制以 `EPERM: operation not permitted, copyfile` 失败——一次都没跑起来,
81
+ 而它的失败与待测代码毫无关系。`.peaks` 现加入 `alwaysIgnoredPatterns`(与 `.stryker-tmp` 同级):
82
+ 运行时产物树不进沙箱,既避开链接,也不必为每个变异体复制整个会话档案。
83
+ - **`--test-files` 被项目的 `include` 过滤成 0 个测试**。`stryker.conf.js` 把
84
+ `vitest.configFile` 指向 `stryker.vitest.config.mjs`,后者的 `include` 是**两个硬编码文件**;
85
+ vitest 会用 `--test-files` 去过滤这个 `include`,于是任何别的文件都选不中,dry run 以
86
+ "No tests were executed" 中止。**新写的测试根本无法进入变异测试。**
87
+ 现在每次运行生成一份临时 config,`include` 就是调用方给的文件。
88
+
89
+ 顺带修掉的:
90
+
91
+ - `sessionId` 在 CLI → runner → invoker → options builder 这条链上断了三处,逐个接上。
92
+ - 生成的 config 用**相对路径**且**不设 `root`**:Stryker 在沙箱内求值该 config,
93
+ 绝对路径会指向原始树(在沙箱 `root` 之外),vitest 全部过滤掉——实测正是 0 tests。
94
+ - `.stryker-tmp` 之前**不在 `.gitignore`**:崩溃的 run 会留下整树副本,
95
+ 门禁把它当作「未声明的可执行代码」。已忽略,并清掉残留。
96
+
97
+ **首次实测**:152 变异体 / 92 杀 / kill rate **60.5%**(阈值 80%)。
98
+ 这说明新代码的断言仍偏弱——是变异测试**应该**告诉我们的信息,已单独记录待补。
99
+
100
+ ### 6. 已知未修
101
+
102
+ - `scanLibraries` 仍为每个 workspace 各返回一行,同一包名重复。本次只在消费端修正了 specifier 来源;
103
+ 改 scan service 会影响 `peaks scan libraries` 的输出契约与集成测试断言。
104
+ - **kill rate 60.5% < 80% 阈值**:52 个变异体存活,断言覆盖不足,待补。
105
+ - **全局安装的 `peaks` 找不到 `typescript`**:全局 `node_modules` 没有这个 devDependency。
106
+ 用项目本地命令可绕过,且全局安装本就不宜跑变异测试。
107
+ - **依赖运行时状态的测试不能做变异目标**:`context-tool.test.ts` 在沙箱内失败(它读 `.peaks/`,
108
+ 而该树已被忽略)。应给出明确前置提示,而不是让 Stryker 报 "failed tests in initial run"。
109
+ - `todoState` 保持空:会话树里尚无可信的待办来源。
110
+
3
111
  ## 4.2.0 — 2026-11-06(运行态接缝收口)
4
112
 
5
113
  **版本级别**:**minor**(新增 `peaks mut run --ignore` 能力,并把一个新的 workspace 包发到 registry)。
@@ -206,6 +206,122 @@
206
206
  ],
207
207
  "positionalCount": 1
208
208
  }
209
+ },
210
+ {
211
+ "id": "ctx-skill-presence",
212
+ "tool": "peaks_context_compress",
213
+ "commandPath": [
214
+ "skill",
215
+ "presence"
216
+ ],
217
+ "argv": [
218
+ {
219
+ "kind": "literal",
220
+ "value": "skill"
221
+ },
222
+ {
223
+ "kind": "literal",
224
+ "value": "presence"
225
+ },
226
+ {
227
+ "kind": "literal",
228
+ "value": "--json"
229
+ }
230
+ ],
231
+ "params": {},
232
+ "introspection": {
233
+ "optionTokens": [
234
+ "--json"
235
+ ],
236
+ "positionalCount": 0
237
+ }
238
+ },
239
+ {
240
+ "id": "ctx-request-show",
241
+ "tool": "peaks_context_compress",
242
+ "commandPath": [
243
+ "request",
244
+ "show"
245
+ ],
246
+ "argv": [
247
+ {
248
+ "kind": "literal",
249
+ "value": "request"
250
+ },
251
+ {
252
+ "kind": "literal",
253
+ "value": "show"
254
+ },
255
+ {
256
+ "kind": "param",
257
+ "name": "rid"
258
+ },
259
+ {
260
+ "kind": "literal",
261
+ "value": "--role"
262
+ },
263
+ {
264
+ "kind": "param",
265
+ "name": "role"
266
+ },
267
+ {
268
+ "kind": "literal",
269
+ "value": "--json"
270
+ },
271
+ {
272
+ "kind": "literal",
273
+ "value": "--project"
274
+ },
275
+ {
276
+ "kind": "param",
277
+ "name": "project"
278
+ }
279
+ ],
280
+ "params": {
281
+ "rid": {
282
+ "type": "slug",
283
+ "pattern": "^[a-z0-9][a-z0-9-]*$",
284
+ "binding": {
285
+ "kind": "positional",
286
+ "token": "request-id",
287
+ "required": true
288
+ },
289
+ "constraintSource": "handwritten"
290
+ },
291
+ "role": {
292
+ "type": "enum",
293
+ "values": [
294
+ "prd",
295
+ "ui",
296
+ "rd",
297
+ "qa",
298
+ "sc"
299
+ ],
300
+ "binding": {
301
+ "kind": "option",
302
+ "token": "--role",
303
+ "required": true
304
+ },
305
+ "constraintSource": "handwritten"
306
+ },
307
+ "project": {
308
+ "type": "path",
309
+ "binding": {
310
+ "kind": "option",
311
+ "token": "--project",
312
+ "required": true
313
+ },
314
+ "constraintSource": "handwritten"
315
+ }
316
+ },
317
+ "introspection": {
318
+ "optionTokens": [
319
+ "--role",
320
+ "--json",
321
+ "--project"
322
+ ],
323
+ "positionalCount": 1
324
+ }
209
325
  }
210
326
  ]
211
327
  }
@@ -6,6 +6,7 @@ import { resolveAutoCompactProfile } from '../../services/code/auto-compact-prof
6
6
  import { probeInFlightBatch } from '../../services/workflow/workflow-inflight-probe.js';
7
7
  import { readDispatchLedgerFacts } from '../../services/dispatch/dispatch-ledger-reader.js';
8
8
  import { readActiveSid } from './code-runtime-session.js';
9
+ import { resolveCanonicalProjectRoot } from '../../services/config/config-safety.js';
9
10
  import { emitResultDocument } from '../../services/hooks/output.js';
10
11
  import { buildAutoCompactEnvelope } from './code-auto-compact-envelope.js';
11
12
  import { describeDeferral, withDeferralDetail } from './code-auto-compact-deferral.js';
@@ -46,10 +47,18 @@ function buildAutoCompactInput(opts, modeName, capture) {
46
47
  // `workflow-inflight-probe.ts` service fed by the ledger reader, so the
47
48
  // production decision is ledger-backed.
48
49
  const isTestSeam = process.env.PEAKS_TEST_SEAM === '1';
49
- const projectRoot = opts.project;
50
+ // CANONICALISE. The hook fires on every Bash/Task call, and `--project .`
51
+ // resolves against the HOOK'S working directory, which is wherever the tool
52
+ // call happens to run — a `cd src && ...` puts it in a subdirectory, where
53
+ // `.peaks/_runtime/session.json` is not on the path and the run reported
54
+ // `AUTO_COMPACT_NO_SESSION` (non-blocking, so it failed silently). Promoting
55
+ // `.` to the git root is what makes the documented contract true; the
56
+ // previous version passed `opts.project` through untouched and the comment
57
+ // claiming otherwise was wrong. Measured 2026-11-16 from `./src`.
58
+ const projectRoot = resolveCanonicalProjectRoot(opts.project);
50
59
  return {
51
60
  projectRoot,
52
- sessionId: opts.sessionId ?? readActiveSid(opts.project) ?? undefined,
61
+ sessionId: opts.sessionId ?? readActiveSid(projectRoot) ?? undefined,
53
62
  ...(isTestSeam && opts.inFlightBatch === true
54
63
  ? { inFlightBatch: { hasInFlightBatch: true } }
55
64
  : {}),
@@ -113,7 +122,10 @@ async function runAutoCompactAction(opts, io) {
113
122
  reportInvalidAutoCompactMode(io, opts.mode, opts.json);
114
123
  return;
115
124
  }
116
- const selection = resolveAutoCompactProfile({ projectRoot: opts.project, cliMode });
125
+ const selection = resolveAutoCompactProfile({
126
+ projectRoot: resolveCanonicalProjectRoot(opts.project),
127
+ cliMode
128
+ });
117
129
  const capture = { last: null };
118
130
  const result = await runAutoCompact(buildAutoCompactInput(opts, selection.profile, capture));
119
131
  const code = result.code;
@@ -48,7 +48,13 @@ async function runPresenceClear(options, io) {
48
48
  // bootstraps `.peaks/project-scan/` (idempotent). Await the async
49
49
  // signature; failure is still non-fatal so we don't block the clear.
50
50
  try {
51
- await generateProjectContext(projectRoot);
51
+ // `refreshProjectScan: false` keeps this housekeeping path's semantics
52
+ // unchanged: it regenerates `.peaks/PROJECT.md` and does NOT refresh the
53
+ // scan's machine fields. (The bootstrap it calls still repairs a
54
+ // never-populated shell on any path — that arm does not consult this
55
+ // option. `peaks project context` is the surface that refreshes a populated
56
+ // scan's fields; this path leaves those alone.)
57
+ await generateProjectContext(projectRoot, { refreshProjectScan: false });
52
58
  }
53
59
  catch {
54
60
  // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
@@ -94,44 +94,49 @@ function assertMutTestFiles(a) {
94
94
  .requiredOption('--out <path>', 'output path for mut-report.json')
95
95
  .option('--json', 'machine-readable output', false)
96
96
  .action(async (a) => {
97
- try {
98
- assertMutTestFiles(a);
99
- const { mutation } = await runMutation({
100
- project: a.project,
101
- testFiles: a.testFiles,
102
- mutate: a.mutate ?? [],
103
- ignorePatterns: a.ignore ?? [],
104
- invokeStryker
105
- });
106
- const assertions = await scanAssertions({
107
- project: a.project,
108
- testFiles: a.testFiles
109
- });
110
- const report = await buildMutReport({
111
- inputSig: a.inputSig,
112
- out: a.out,
113
- mutation,
114
- assertions
115
- });
116
- emitSummary(io, a.json, {
117
- ok: true,
118
- sha256: report.sha256,
119
- passed: report.thresholds.passed,
120
- path: a.out
121
- });
122
- if (!report.thresholds.passed) {
123
- // H6: CLI裁决 — threshold breach is a non-zero exit so callers
124
- // (peaks-rd, peaks-qa, CI) can block on it without parsing stdout.
125
- process.exitCode = 1;
126
- }
127
- }
128
- catch (err) {
129
- // R7: a named code + actionable message + non-zero exit, never an
130
- // UNHANDLED_ERROR envelope with a bare "Cannot find package".
131
- emitMutError(io, err, mutationFailureLogPath(a.out));
132
- }
97
+ await runMutRunAction(a, invokeStryker, io);
133
98
  });
134
99
  }
100
+ /** The `run` action body, split out so the builder stays inside its line budget. */
101
+ async function runMutRunAction(a, invokeStryker, io) {
102
+ try {
103
+ assertMutTestFiles(a);
104
+ const { mutation } = await runMutation({
105
+ project: a.project,
106
+ testFiles: a.testFiles,
107
+ mutate: a.mutate ?? [],
108
+ ignorePatterns: a.ignore ?? [],
109
+ sessionId: a.sessionId,
110
+ invokeStryker
111
+ });
112
+ const assertions = await scanAssertions({
113
+ project: a.project,
114
+ testFiles: a.testFiles
115
+ });
116
+ const report = await buildMutReport({
117
+ inputSig: a.inputSig,
118
+ out: a.out,
119
+ mutation,
120
+ assertions
121
+ });
122
+ emitSummary(io, a.json, {
123
+ ok: true,
124
+ sha256: report.sha256,
125
+ passed: report.thresholds.passed,
126
+ path: a.out
127
+ });
128
+ if (!report.thresholds.passed) {
129
+ // H6: CLI裁决 — threshold breach is a non-zero exit so callers
130
+ // (peaks-rd, peaks-qa, CI) can block on it without parsing stdout.
131
+ process.exitCode = 1;
132
+ }
133
+ }
134
+ catch (err) {
135
+ // R7: a named code + actionable message + non-zero exit, never an
136
+ // UNHANDLED_ERROR envelope with a bare "Cannot find package".
137
+ emitMutError(io, err, mutationFailureLogPath(a.out));
138
+ }
139
+ }
135
140
  /**
136
141
  * `peaks mut mutants` — Stryker only; writes a stub-assertions
137
142
  * mut-report.json. One-axis: --session-id required.
@@ -155,6 +160,7 @@ export function buildMutMutantsCommand(invokeStryker, io) {
155
160
  testFiles: a.testFiles,
156
161
  mutate: a.mutate ?? [],
157
162
  ignorePatterns: a.ignore ?? [],
163
+ sessionId: a.sessionId,
158
164
  invokeStryker
159
165
  });
160
166
  const report = await buildMutReport({
@@ -19,7 +19,11 @@ async function runProjectContext(io, options) {
19
19
  printResult(io, ok('project.context', readContextData(options.project)), options.json);
20
20
  return;
21
21
  }
22
- const result = await generateProjectContext(options.project);
22
+ const result = await generateProjectContext(options.project, {
23
+ // `--no-project-scan-refresh` is the only way to turn the refresh off;
24
+ // absence leaves this `undefined`, which the service reads as "refresh".
25
+ refreshProjectScan: options.projectScanRefresh !== false
26
+ });
23
27
  printResult(io, ok('project.context', {
24
28
  path: result.path,
25
29
  sessionCount: result.sessionCount,
@@ -40,5 +44,6 @@ export function registerProjectContextCommand(project, io) {
40
44
  .command('context')
41
45
  .description('Generate or read persistent project context for cross-session Peaks understanding. Generates BOTH `.peaks/PROJECT.md` (session history) AND `.peaks/project-scan/project-scan.md` (tech stack + archetypes) — see `peaks workspace init` for the full 5-template boot (G4b/AC9).')
42
46
  .requiredOption('--project <path>', 'target project root')
43
- .option('--read', 'read existing PROJECT.md without regenerating')).action((options) => runProjectContext(io, options));
47
+ .option('--read', 'read existing PROJECT.md without regenerating')
48
+ .option('--no-project-scan-refresh', 'skip refreshing the machine fields (capturedAt / techStack / libraryVersions) of an existing project-scan.md')).action((options) => runProjectContext(io, options));
44
49
  }
@@ -157,6 +157,11 @@ function pushProjectScanActions(nextActions, warnings, ctx) {
157
157
  if (projectScanError !== null) {
158
158
  warnings.push(`project-scan bootstrap failed: ${projectScanError}`);
159
159
  }
160
+ else if (projectScanEnvelope !== null && projectScanEnvelope.refreshWarning !== undefined) {
161
+ // An unparseable or unreadable scan is REPORTED, not silently skipped: the
162
+ // machine fields stay stale and nothing else in this envelope would say so.
163
+ warnings.push(projectScanEnvelope.refreshWarning);
164
+ }
160
165
  else if (projectScanEnvelope !== null && projectScanEnvelope.created) {
161
166
  nextActions.push(`Bootstrapped .peaks/project-scan/ (project-scan.md + 4 audit/business templates) — ` +
162
167
  `${projectScanEnvelope.templatesBooted} file(s) written, ${projectScanEnvelope.templatesSkipped} preserved. ` +
@@ -97,6 +97,7 @@ export async function bootstrapProjectScanForInit(options, projectRoot) {
97
97
  envelope: {
98
98
  created: false,
99
99
  skipped: true,
100
+ refreshed: false,
100
101
  templatesBooted: 0,
101
102
  templatesSkipped: 0,
102
103
  projectScanPath: `${projectRoot}/.peaks/project-scan/project-scan.md`,
@@ -5,9 +5,11 @@
5
5
  * orchestrator re-exports every name declared here, so existing importers keep
6
6
  * using `./auto-compact-orchestrator.js` unchanged.
7
7
  */
8
+ import { spawnSync } from 'node:child_process';
8
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
10
  import { join } from 'node:path';
10
11
  import { getSessionDir } from '../session/getSessionDir.js';
12
+ import { buildCheckpointContent } from './auto-compact-checkpoint-content.js';
11
13
  import { describeHarnessWindowSync } from '../context/harness-window-config.js';
12
14
  /**
13
15
  * What the caller is told to do next. The harness-window notice rides along because
@@ -111,25 +113,55 @@ export function writePreCompactCheckpoint(input) {
111
113
  const prefix = input.redLine === true ? 'red-line-' : 'pre-compact-';
112
114
  const filename = `${prefix}${input.now.toISOString().replace(/[:.]/g, '-')}.json`;
113
115
  const path = join(dir, filename);
116
+ // D7 reads `mode`, `currentPlan`, `openQuestions`, `recentDecisions` out of
117
+ // this JSON. Until 2026-11-16 every one of those was seeded EMPTY, so the
118
+ // resume the detector enabled had nothing to restore — measured: a checkpoint
119
+ // written from a session with an active request and a populated decisions log
120
+ // still carried seven empty fields. `buildCheckpointContent` reads what the
121
+ // session already wrote to disk and renders it into the shape D7 expects.
122
+ const populated = buildCheckpointContent({
123
+ projectRoot: input.projectRoot,
124
+ sessionId: input.sessionId,
125
+ ...(input.redLine === true ? { redLine: true } : {})
126
+ });
114
127
  const content = {
115
128
  schemaVersion: 1,
116
129
  reason: input.redLine === true ? 'pre-compact-red-line' : PRE_COMPACT_REASON,
117
130
  sessionId: input.sessionId,
118
131
  createdAt: input.now.toISOString(),
119
- // D7 reads `mode`, `currentPlan`, `openQuestions`, `recentDecisions`
120
- // out of this JSON. We seed empty arrays; the post-compact LLM
121
- // rehydrates from the auto-decisions log + open question list.
122
132
  mode: 'full-auto',
123
- currentPlan: input.redLine === true
124
- ? 'RED-LINE compact REQUESTED from the harness (not executed by peaks-loop); work continues'
125
- : 'auto-compact in progress; resume from auto-decisions.md',
126
- openQuestions: [],
127
- recentDecisions: [],
128
- recentArtifactPaths: [],
129
- gitStatus: '',
133
+ currentPlan: populated.currentPlan,
134
+ openQuestions: populated.openQuestions,
135
+ recentDecisions: populated.recentDecisions,
136
+ recentArtifactPaths: populated.recentArtifactPaths,
137
+ gitStatus: readGitStatusQuietly(input.projectRoot),
130
138
  skillsActive: ['peaks-code'],
131
139
  todoState: []
132
140
  };
133
141
  writeFileSync(path, JSON.stringify(content, null, 2), 'utf8');
134
142
  return path;
135
143
  }
144
+ /** Cap on the working-tree lines a checkpoint carries; the rest stay in git. */
145
+ const MAX_GIT_STATUS_LINES = 20;
146
+ /**
147
+ * `git status --porcelain -b` for the checkpoint, or `''`.
148
+ *
149
+ * A checkpoint is written on the compact path, where a few hundred milliseconds
150
+ * spent on git is acceptable and a resume that knows the working tree was dirty
151
+ * is materially better than one that does not. Failure is not an error: a repo
152
+ * without git, or a locked index, simply leaves the field empty.
153
+ */
154
+ function readGitStatusQuietly(projectRoot) {
155
+ const result = spawnSync('git', ['status', '--porcelain', '-b'], {
156
+ cwd: projectRoot,
157
+ encoding: 'utf8',
158
+ timeout: 5_000,
159
+ // Windows: without this the console window flashes on every probe. The
160
+ // repo's spawn-hygiene ratchet requires it on EVERY call site.
161
+ windowsHide: true
162
+ });
163
+ if (result.error !== undefined || result.status !== 0 || typeof result.stdout !== 'string') {
164
+ return '';
165
+ }
166
+ return result.stdout.trim().split('\n').slice(0, MAX_GIT_STATUS_LINES).join('\n');
167
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Building a pre-compact checkpoint that carries enough to resume from.
3
+ *
4
+ * WHY THIS EXISTS. `writePreCompactCheckpoint` used to seed every field empty —
5
+ * `currentPlan` said only "resume from auto-decisions.md", and
6
+ * `openQuestions` / `recentDecisions` / `recentArtifactPaths` were `[]`. The
7
+ * post-compact detector reads exactly those fields, so the resume it enabled had
8
+ * nothing to restore. Measured 2026-11-16: a checkpoint written from a session
9
+ * with an active request and a populated decisions log still contained seven
10
+ * empty fields.
11
+ *
12
+ * The data was never missing — it was on disk and unread. This module reads it
13
+ * and renders it into the shape `post-compact-checkpoint.ts` expects.
14
+ *
15
+ * WHAT THIS DELIBERATELY DOES NOT DO. It does not compress, summarize with a
16
+ * model, or truncate conversation history. peaks-loop cannot read the request
17
+ * body and cannot initiate a compact (see the note on
18
+ * `writeMainSessionCompactIntent`); what it CAN do is leave a complete, truthful
19
+ * record of where the work stands, so the post-compact turn resumes instead of
20
+ * re-deriving.
21
+ */
22
+ /** One `## Auto-compact decision — <ts>` block from `txt/auto-decisions.md`. */
23
+ export type AutoDecisionEntry = {
24
+ readonly decidedAt: string;
25
+ readonly ratio: string | null;
26
+ readonly resumeHint: string | null;
27
+ readonly nextActions: readonly string[];
28
+ };
29
+ /** Read `txt/auto-decisions.md` and return its blocks, newest last. */
30
+ export declare function readAutoDecisions(projectRoot: string, sessionId: string): AutoDecisionEntry[];
31
+ /**
32
+ * The populated fields for a checkpoint.
33
+ *
34
+ * `currentPlan` is built from what the session actually recorded — the newest
35
+ * auto-compact decision's resume hint plus its next actions — and falls back to
36
+ * a sentence that still says something true (no decisions yet) rather than the
37
+ * old "resume from auto-decisions.md", which told a resumed turn to go read a
38
+ * file that this checkpoint is supposed to have already summarized.
39
+ */
40
+ export declare function buildCheckpointContent(input: {
41
+ readonly projectRoot: string;
42
+ readonly sessionId: string;
43
+ readonly redLine?: boolean;
44
+ }): {
45
+ readonly currentPlan: string;
46
+ readonly openQuestions: string[];
47
+ readonly recentDecisions: string[];
48
+ readonly recentArtifactPaths: string[];
49
+ };