@zhuxixi/pi-agent-board 0.13.0 → 0.14.0

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 (91) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +37 -12
  3. package/docs/SECTION_FOLDING.md +53 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-222-attach-ready.md +290 -0
  5. package/docs/superpowers/plans/2026-10-26-issue-245-key-hints-doc-sync.md +244 -0
  6. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  7. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  8. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  9. package/docs/superpowers/plans/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup.md +256 -0
  10. package/docs/superpowers/plans/2026-11-03-cwd-favorites-full-pool.md +266 -0
  11. package/docs/superpowers/plans/2026-11-03-issue-266-alt-h-detach.md +467 -0
  12. package/docs/superpowers/plans/2026-11-04-issue-270-scenario-stdout-flush.md +584 -0
  13. package/docs/superpowers/plans/2026-11-05-issue-278-ctrl-g-external-editor.md +381 -0
  14. package/docs/superpowers/plans/2026-11-06-issue-280-frame-witness-delivery.md +430 -0
  15. package/docs/superpowers/plans/2026-11-07-issue-284-attach-recovery.md +115 -0
  16. package/docs/superpowers/plans/2026-11-07-issue-284-u1-u2-trial-guide.md +39 -0
  17. package/docs/superpowers/plans/2026-11-08-host-restart-model-override.md +894 -0
  18. package/docs/superpowers/plans/2026-11-08-issue-288-cap-floor.md +51 -0
  19. package/docs/superpowers/plans/2026-11-09-dashboard-fold-flake.md +166 -0
  20. package/docs/superpowers/plans/2026-11-09-issue-273-harness-console-log-exit.md +369 -0
  21. package/docs/superpowers/plans/2026-11-10-issue-258-board-selection-settle.md +760 -0
  22. package/docs/superpowers/plans/2026-11-13-issue-294-snapshot-resize-intent.md +590 -0
  23. package/docs/superpowers/plans/2026-11-16-greeting-title-poll.md +838 -0
  24. package/docs/superpowers/plans/2026-11-22-issue-297-compaction-mirror.md +797 -0
  25. package/docs/superpowers/plans/2026-11-23-issue-254-cursor-keep-position.md +663 -0
  26. package/docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md +320 -0
  27. package/docs/superpowers/specs/2026-10-23-issue-222-attach-ready-design.md +204 -0
  28. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  29. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  31. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-257-legacy-pty-runner-endpoint-cleanup-design.md +197 -0
  33. package/docs/superpowers/specs/2026-11-03-cwd-favorites-full-pool-design.md +106 -0
  34. package/docs/superpowers/specs/2026-11-03-issue-266-alt-h-detach-design.md +185 -0
  35. package/docs/superpowers/specs/2026-11-04-issue-270-scenario-stdout-flush-design.md +176 -0
  36. package/docs/superpowers/specs/2026-11-05-issue-278-ctrl-g-external-editor-design.md +185 -0
  37. package/docs/superpowers/specs/2026-11-07-issue-284-attach-recovery-design.md +166 -0
  38. package/docs/superpowers/specs/2026-11-08-host-restart-model-override-design.md +115 -0
  39. package/docs/superpowers/specs/2026-11-08-issue-288-cap-floor-design.md +86 -0
  40. package/docs/superpowers/specs/2026-11-09-dashboard-fold-flake-design.md +109 -0
  41. package/docs/superpowers/specs/2026-11-09-issue-273-harness-console-log-exit-design.md +182 -0
  42. package/docs/superpowers/specs/2026-11-10-issue-258-board-selection-settle-design.md +109 -0
  43. package/docs/superpowers/specs/2026-11-13-issue-294-snapshot-resize-intent-design.md +141 -0
  44. package/docs/superpowers/specs/2026-11-16-greeting-title-poll-design.md +174 -0
  45. package/docs/superpowers/specs/2026-11-22-issue-297-compaction-mirror-design.md +158 -0
  46. package/docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md +209 -0
  47. package/docs/superpowers/specs/2026-11-23-issue-254-cursor-keep-position-design.md +201 -0
  48. package/package.json +1 -1
  49. package/runner/pty-runner.mjs +526 -63
  50. package/runner/state-coordinator.mjs +62 -5
  51. package/runner/title-runner.mjs +33 -24
  52. package/src/commands/agent-board.ts +5 -1
  53. package/src/core/attach-detach.mjs +27 -0
  54. package/src/core/attach-frame-proof.mjs +897 -0
  55. package/src/core/attach-frame-reporter.mjs +738 -0
  56. package/src/core/attach-frame-stream.mjs +266 -0
  57. package/src/core/attach-pr-label.mjs +12 -0
  58. package/src/core/attach-recovery.mjs +239 -0
  59. package/src/core/attach-screen-owner.mjs +55 -0
  60. package/src/core/attach-view-proof.mjs +709 -0
  61. package/src/core/auto-state.mjs +6 -1
  62. package/src/core/cwd-stats.mjs +3 -1
  63. package/src/core/dashboard-prefs.mjs +31 -0
  64. package/src/core/derive.mjs +8 -1
  65. package/src/core/events.mjs +127 -1
  66. package/src/core/foreground-projection-cache.mjs +1 -0
  67. package/src/core/frame-witness-update.mjs +35 -0
  68. package/src/core/fullscreen-selection.mjs +60 -0
  69. package/src/core/host-coordination.mjs +48 -0
  70. package/src/core/host-protocol.mjs +13 -2
  71. package/src/core/hosted-frame-witness.mjs +60 -0
  72. package/src/core/paths.mjs +10 -3
  73. package/src/core/pty-attach-render.mjs +239 -0
  74. package/src/core/pty-kitty-images.mjs +237 -0
  75. package/src/core/pty-scroll.mjs +8 -8
  76. package/src/core/rows.mjs +43 -7
  77. package/src/core/session-entries.mjs +82 -0
  78. package/src/core/session-launch-prefs.mjs +45 -0
  79. package/src/core/session-view.mjs +3 -63
  80. package/src/core/store.mjs +1 -0
  81. package/src/core/terminal-attach-client.mjs +199 -20
  82. package/src/core/terminal-attach-protocol.mjs +221 -7
  83. package/src/core/terminal-model.mjs +24 -3
  84. package/src/core/terminal-snapshot.mjs +10 -0
  85. package/src/core/title-flow.mjs +66 -0
  86. package/src/core/title.mjs +101 -0
  87. package/src/core/types.mjs +17 -0
  88. package/src/index.ts +85 -0
  89. package/src/runtime/service.mjs +87 -18
  90. package/src/ui/dashboard.ts +206 -49
  91. package/src/ui/pty-attach.ts +1472 -99
@@ -0,0 +1,174 @@
1
+ # Spec: #295 — greeting first message must not freeze the session title
2
+
3
+ Status: DRAFT (rev 4, post round-3 cross-review; 1 gap + 3 details accepted, 5 passes) — gate=design-only per `../authorization.md`: after convergence, PAUSE once for user design confirmation, then push/PR/CR-fix loop runs automatically until the merge decision.
4
+ Issue: https://github.com/zhuxixi/pi-agent-board/issues/295
5
+ Repo baseline: local main `750b854` (post-#293 merge). Pi 1.5.1 runtime. Implementation re-pins `origin/main` in the worktree and records the SHA.
6
+ Plan provenance: @SummerZuo's fix plan (issue comment) — endorsed by the maintainer; this spec turns it into a verifiable design.
7
+ Research artifacts: `~/.github-issue-driven/zhuxixi/pi-agent-board/issue-295/research/` (research-summary.md).
8
+
9
+ Drafted: zai-coding-cn/glm-5.3 (selected) · zai-coding-cn/glm-5.3 (physical) @ 2026-11-13T08:45:00+08:00
10
+ Revised: zai-coding-cn/glm-5.3 (selected) · zai-coding-cn/glm-5.3 (physical) @ 2026-11-13T09:05:00+08:00 — R1-G1 (greedy longest-match tokenizer so multi-word/multi-char greetings actually match; A1 explicit phrase cases), R1-G2 (unified `commitMeta` dep), R1-G3 (`resolveTitleSettings` pure resolver owning both env vars + precedence; flow is env-free; `enabled:false` exits before polling), R1-G4 (A4 failure branches: empty/null/fallback outputs, readMeta null, rename during pending one-shot, rejection propagation), R1-G5 (U1 deployment preconditions: loaded checkout, pull, SHA record, full restart, provider auth), R1-G6 (last-line extraction preserved in `generateOnce`; multiline cases in A4), R1-D1 (honest shell coverage + hermetic runner smoke test A6 with new fixture), R1-D2 (U1③ reordered to actually reach the guard)
11
+ Revised: zai-coding-cn/glm-5.3 (selected) · zai-coding-cn/glm-5.3 (physical) @ 2026-11-13T09:25:00+08:00 — R2-G1 (consume rule rewritten as whole-string greedy consumption without per-unit trailing boundary, so `你好呀`/`嗨嗨` match and the duplicate rule is subsumed; A1 gains no-separator negatives `helloX`/`你好请修复`), R2-D1 (U1 precondition now runs a one-shot with the explicit resolved title model/thinking instead of relying on VERIFY.md §2's default-model check)
12
+ Revised: zai-coding-cn/glm-5.3 (selected) · zai-coding-cn/glm-5.3 (physical) @ 2026-11-13T09:50:00+08:00 — R3-G1 (greeting-first grammar: the first consumed unit must be a GREETINGS entry; PARTICLES may only follow; A1 adds bare-particle and particle-first negatives), R3-D1 (U1① timing anchored to the substantive message send, ~30s window), R3-D2 (A6 spawns the fixture via `piCommand: process.execPath` + `piArgsPrefix: [fixture]` per the repo's hermetic pattern), R3-D3 (one-shot health judgment aligned with VERIFY.md: exit 0 + assistant `message_end` + `agent_end` + no auth errors)
13
+
14
+ ## Problem (root cause, verified on `750b854`)
15
+
16
+ A session whose first user message is a bare greeting (`hello` / `hi` / `你好`) keeps a useless title ("Simple greeting") forever:
17
+
18
+ 1. `queueGeneratedTitle(meta, prompt)` has a single call site — the dispatch path (`src/runtime/service.mjs:2083`); replies never re-trigger it.
19
+ 2. `runner/title-runner.mjs` generates the title **once**, from that first prompt, via a one-shot model call.
20
+ 3. The write-back guard `if (meta.name !== config.fallbackName) return;` (`runner/title-runner.mjs:40`) — intended as "manual rename wins" — then holds forever, because the generated title made `meta.name` differ from the fallback.
21
+
22
+ Feasibility notes from research (see research-summary.md): the referenced `feat/board-ux-title` retry machinery (`shouldRetryTitle` / `TITLE_RETRY_BACKOFF_MS`) does **not exist** on origin or in any commit; the design is therefore fully self-contained inside the runner. `contentText` is currently private in `src/core/session-view.mjs` and must be lifted. Nothing reaps a longer-lived title-runner (detached spawn, warm-host sweeper only targets PTY hosts and skips `AGENT_BOARD_NO_SWEEP=1` children).
23
+
24
+ ## Design
25
+
26
+ ### 1. `src/core/title.mjs` — greeting classifier (pure)
27
+
28
+ `isGreetingPrompt(text)` classifies a message as a greeting iff the **entire** message is greeting material.
29
+
30
+ Normalization: `String(text ?? "")` → trim → lowercase → collapse whitespace runs to a single space → strip leading/trailing characters from `PUNCT = "!!??。.,,、~~…;;::"`.
31
+
32
+ Matching is a **whole-string greedy longest-match consume** over the normalized string (multi-word English phrases and multi-character Chinese phrases are first-class vocabulary units; adjacent units need no separator, which is what makes `你好呀` and `嗨嗨` match):
33
+
34
+ - Vocabulary: `GREETINGS = { hello, hi, hey, hiya, yo, sup, howdy, greetings, morning, good morning, good afternoon, good evening, good day, 你好, 您好, 嗨, 哈喽, 哈啰, 在吗, 在么, 早上好, 上午好, 早安, 下午好, 晚上好, 晚安 }` and `PARTICLES = { there, 呀, 啊, 哦 }` (covers `hi there`, `你好呀`).
35
+ - Consume rule (**greeting-first**): starting at position 0, repeatedly (a) skip any run of separators (a space or any `PUNCT` char), then (b) consume the **longest** vocabulary unit matching at the current position — **no trailing-boundary requirement on individual units**. **The first consumed unit must belong to `GREETINGS`; units consumed after the first may be `GREETINGS` or `PARTICLES`.** There is no separate repetition rule: adjacent duplicates (``hello hello``, ``嗨嗨``) are naturally consumed because each unit is itself in the vocabulary.
36
+ - The message is a greeting iff the consume reaches the end of the string with **at least one `GREETINGS` unit consumed**. A stuck position — next characters match no vocabulary unit (``hello, please fix X`` stalls at ``please``; bare ``good`` stalls immediately since ``good`` alone is not in the vocabulary; no-separator real tasks like ``helloX`` / ``你好请修复`` stall at ``X`` / ``请修复``) → `false`; a string that never consumes a `GREETINGS` unit (bare ``there``, bare ``呀``, or particle-first ``there hello``) → `false`. Empty string → `false`.
37
+ - The vocabulary is intentionally small and fixed (denylist-style classifier, not NLP); extending it is a one-line change plus tests.
38
+
39
+ ### 2. `src/core/title.mjs` — env settings resolver (pure, new)
40
+
41
+ `resolveTitleSettings(env, configModel)` returns `{ enabled: boolean, model: string, thinking: string }`, owning **both** legacy and current env vars with today's exact precedence (currently inlined in `runner/title-runner.mjs:26-29`):
42
+
43
+ - `configured = env.AGENT_BOARD_TITLE_MODEL ?? env.AGENT_VIEW_TITLE_MODEL`
44
+ - `enabled = configured !== "off"` (off wins even when `configModel` is set — preserves today's early return)
45
+ - `model = configModel ?? configured ?? DEFAULT_TITLE_MODEL`
46
+ - `thinking = env.AGENT_BOARD_TITLE_THINKING_LEVEL ?? env.AGENT_VIEW_TITLE_THINKING_LEVEL ?? DEFAULT_TITLE_THINKING_LEVEL`
47
+
48
+ The flow module never reads `process.env`; the shell calls this resolver once and either exits (`enabled === false`, before any polling starts) or wires `runOneShot` with the resolved model/thinking.
49
+
50
+ ### 3. `src/core/session-entries.mjs` — lift `contentText`
51
+
52
+ Move `contentText(content)` verbatim from `src/core/session-view.mjs` into `src/core/session-entries.mjs` (both are structure/projection primitives; session-entries is the documented "single source" module and has no `node:fs` import). `session-view.mjs` imports it from there — no duplicate, no behavior change.
53
+
54
+ ### 4. `src/core/title.mjs` — substantive-prompt projection (pure)
55
+
56
+ `firstSubstantiveUserPrompt(sessionJsonlText)`:
57
+
58
+ - `parseSessionEntries` → `activeBranchEntries` (both from `src/core/session-entries.mjs`);
59
+ - iterate branch entries in order, keep `type === "message"` with `message.role === "user"`, project text via `contentText(message.content)` (only text blocks — tool-result user entries project to empty and are skipped);
60
+ - skip empty projections and entries where `isGreetingPrompt(text)` is true (the first entry **is** the greeting prompt that triggered polling);
61
+ - return the first remaining text; if none, `null`.
62
+
63
+ ### 5. `src/core/title-flow.mjs` — orchestration with injected I/O (new module)
64
+
65
+ Exported: `runTitleFlow(config, deps)` plus constants `TITLE_POLL_INTERVAL_MS = 15_000`, `TITLE_POLL_BUDGET_MS = 300_000`.
66
+
67
+ `deps` (all injected; the runner shell wires real implementations):
68
+ `{ now(): number, sleep(ms): Promise<void>, readMeta(root, viewId): object|null, commitMeta(meta): void, readSessionText(config): string|null, runOneShot(prompt): Promise<string|null> }`
69
+
70
+ `TitleConfig` (`src/core/types.mjs` JSDoc) gains optional `pollIntervalMs` / `pollBudgetMs`; when absent the constants above apply. The service never sets them — they exist so hermetic tests can shrink the poll window without touching production timing.
71
+
72
+ Flow (single source for both paths):
73
+
74
+ ```text
75
+ runTitleFlow(config, deps):
76
+ if !isGreetingPrompt(config.prompt):
77
+ return generateOnce(config, deps, config.prompt) // today's behavior, unchanged
78
+ deadline = deps.now() + (config.pollBudgetMs ?? TITLE_POLL_BUDGET_MS)
79
+ interval = config.pollIntervalMs ?? TITLE_POLL_INTERVAL_MS
80
+ loop while deps.now() < deadline:
81
+ await deps.sleep(interval) // sleep-first: t=15s, 30s, …
82
+ text = deps.readSessionText(config) // readMeta → meta.sessionFile → read if exists, else null
83
+ prompt = text ? firstSubstantiveUserPrompt(text) : null
84
+ if prompt: return generateOnce(config, deps, prompt)
85
+ return // budget exhausted → quiet exit, row keeps fallback slug
86
+
87
+ generateOnce(config, deps, prompt):
88
+ out = await deps.runOneShot(prompt) // rejection propagates to the caller (shell catches — best effort)
89
+ last = out?.trim().split("\n").slice(-1)[0]?.trim() ?? "" // LAST LINE ONLY — today's shell semantics, now owned by the flow
90
+ title = normalizeGeneratedTitle(last, config.fallbackName)
91
+ if !title || title === config.fallbackName: return
92
+ meta = deps.readMeta(config.root, config.viewId)
93
+ if !meta: return
94
+ if meta.name !== config.fallbackName: return // manual rename wins — re-checked at write time
95
+ meta.name = title
96
+ deps.commitMeta(meta)
97
+ ```
98
+
99
+ `readMeta` is re-read **inside** `generateOnce` right before the guard, so a manual rename at any point — during polling **or** while the one-shot model call is pending — still wins (this also keeps the runner safe against other `meta.name` writers such as the user-side `agent-board-name-sync` bridge). `runOneShot` rejections are **not** caught inside the flow: they propagate to the shell's existing `.catch(() => {})` best-effort handler. (Today's real `runOneShot` never rejects — it resolves `""` on spawn error and on timeout — but injected test doubles may.)
100
+
101
+ ### 6. `runner/title-runner.mjs` — thin shell
102
+
103
+ - Keep argv/config-file handling, `runOneShot` (spawn + JSON event scan + timeout), and the top-level best-effort catch.
104
+ - `main()`: read config → `const settings = resolveTitleSettings(process.env, config.model)` → `if (!settings.enabled) return` (before any polling) → wire real deps and `await runTitleFlow(config, deps)`:
105
+ - `now: Date.now`, `sleep: ms => new Promise(r => setTimeout(r, ms))`
106
+ - `readMeta` from `src/core/store.mjs`
107
+ - `commitMeta: meta => writeMeta(config.root, meta)` (`writeMeta` from `src/core/store.mjs`)
108
+ - `readSessionText: () => { const m = readMeta(config.root, config.viewId); if (!m?.sessionFile) return null; return existsSync(m.sessionFile) ? readFileSync(m.sessionFile, "utf8") : null; }`
109
+ - `runOneShot: prompt => runOneShot(config.piCommand, [...config.piArgsPrefix, "--mode", "json", "-p", "--no-session", "--model", settings.model, ...(settings.thinking && settings.thinking !== "off" ? ["--thinking", settings.thinking] : []), titlePrompt(prompt)], 15000)`
110
+ - `src/runtime/service.mjs` is **not touched** (single call site, same config shape, same fallback name).
111
+
112
+ ### Decision table
113
+
114
+ | Situation | Behavior |
115
+ |---|---|
116
+ | First prompt is substantive | Identical to today: generate once at dispatch, guarded write |
117
+ | First prompt is a greeting, later substantive user message within budget | Title generated from that first substantive message; guarded write |
118
+ | First prompt is a greeting, manual rename before the write (polling **or** one-shot pending) | Manual name kept (guard re-checks `meta.name` at write time) |
119
+ | First prompt is a greeting, no substantive message within budget | Runner exits quietly; row keeps fallback slug (today's failure mode, no worse) |
120
+ | Title settings resolve to off (`AGENT_BOARD_TITLE_MODEL` or legacy `AGENT_VIEW_TITLE_MODEL` = `off`) | Shell exits before flow and before polling; no generation |
121
+ | Session file never appears (child failed to start) | Poll misses every tick (readSessionText → null); quiet exit at budget |
122
+ | Model call returns empty / null / fallback-equal output | No commit (normalize + equality guard) |
123
+ | `readMeta` returns null at write time | No commit, quiet return |
124
+ | `runOneShot` rejects | Propagates to shell's `.catch(() => {})`; no commit |
125
+
126
+ ### Non-goals
127
+
128
+ - No retry/backoff machinery (the referenced `feat/board-ux-title` branch does not exist); no changes to `service.mjs` scheduling; no regeneration for rows that already carry a generated or manual title.
129
+ - No NLP greeting detection beyond the fixed vocabulary; no change to the title model, prompt, `normalizeGeneratedTitle`, or the last-line extraction semantics.
130
+ - No new env knobs (both legacy and current title env vars keep today's names and precedence).
131
+
132
+ ## Acceptance matrix
133
+
134
+ | ID | 功能点 | 验收方式 | 具体验证 | 通过标准 |
135
+ |----|--------|----------|----------|----------|
136
+ | A1 | `isGreetingPrompt` classification | 自动化验证(unit) | `node --test test/title.test.mjs` | 正例:`hello/hi/hey/hiya/yo/sup/howdy/greetings/morning`、**`good morning/good afternoon/good evening/good day`**、zh 全词表(`你好/您好/嗨/哈喽/哈啰/在吗/在么/早上好/上午好/早安/下午好/晚上好/晚安`)、大小写、首尾标点、重复(`hello hello`、`嗨嗨`)、语气词后缀(`hi there`、`你好呀`)→ `true`;反例:问候前缀实任务(`hello, please fix X`)、**无分隔符前缀任务(`helloX`、`你好请修复`)**、**裸语气词(`there`、`呀`)、语气词在前(`there hello`)**、裸 `good`、空串、非问候 → `false` |
137
+ | A2 | `firstSubstantiveUserPrompt` projection | 自动化验证(unit) | `node --test test/title.test.mjs` | fixture JSONL(问候首条、tool-result 用户条目、assistant 条目、非活动分支):返回活动分支第一条实质用户消息文本;全问候/空文件/无用户消息 → `null` |
138
+ | A3 | `contentText` lift regression | 自动化验证(unit) | `npm test`(既有 session-view/session-entries 测试不变更地通过) | 行为零变化 |
139
+ | A4 | greeting poll flow + guard + failure branches | 自动化验证(unit,注入 I/O + 假时钟) | `node --test test/title-flow.test.mjs` | ①问候→轮询命中→以实质消息调 `runOneShot`、守卫后 `commitMeta` 提交;②轮询期间手动改名→不提交;③预算耗尽→不调 `runOneShot`、不提交、安静返回;④非问候→立即生成、不轮询;⑤`runOneShot` 返回 null/空串/等于 fallback 的输出→不提交;⑥写前 `readMeta` 返回 null→不提交;⑦deferred `runOneShot` 挂起期间改名→恢复后仍不提交;⑧`runOneShot` reject→异常传播出 flow、不提交(由 shell catch 承接);⑨多行模型输出(两条路径各一例)→只用最后一行生成标题 |
140
+ | A5 | `resolveTitleSettings` env resolution | 自动化验证(unit) | `node --test test/title.test.mjs` | `AGENT_BOARD_TITLE_MODEL=off` → `enabled:false`;legacy `AGENT_VIEW_TITLE_MODEL=off` → `enabled:false`;两变量并存时 board 优先;`configModel` 覆盖 env model 但不覆盖 off;thinking 同名变量与默认值链路正确 |
141
+ | A6 | runner shell hermetic smoke | 自动化验证(integration) | `node --test test/title-runner-smoke.test.mjs`(新 fixture `test-support/fake-title-pi.mjs`:输出一行 `message_end` JSON 后退出;**按仓内 hermetic 模式配置 `piCommand: process.execPath`、`piArgsPrefix: [<fixture 绝对路径>]`**——不直接 spawn `.mjs`,Windows 亦可移植) | ①非问候:真实 spawn `node runner/title-runner.mjs <config>`,temp root meta → 进程退出、`meta.name` 更新为 fixture 标题;②问候:config 带 `pollIntervalMs: 50`、session 文件预置问候+实质消息 → 退出、`meta.name` 更新为实质消息标题;③`off`(board 与 legacy 各一)→ 退出且 `meta.name` 不变、无模型调用 |
142
+ | A7 | static/build | 自动化验证(static + build) | `npm run typecheck`;PR 前 `npm run verify`(worktree 内,node_modules 软链主 checkout) | typecheck 0 错误;verify 全绿且 coverage 阈值(lines 85 / funcs 80 / branches 70)达标 |
143
+ | A8 | full-suite regression | 自动化验证(integration) | `npm test` | 全绿 |
144
+ | U1 | real dispatch on deployed code | 用户实测(部署前置见下) | ①新会话首条发 `hello`,再发一条实任务消息,**从实任务消息发送时刻起约 30 秒内**(下一次轮询 tick ≤15s + 一次 one-shot ≤15s + 余量)标题更新为实任务标题;②对照:首条即实任务的会话标题照旧即时生成;③`hello` → 手动改名 → 发实任务 → 等待 ≥ 轮询间隔 + 一次 one-shot 窗口 → 手动名保持;④`hello` 后 5 分钟内不发实任务 → 行名保持 slug | ①–④ 全部符合观察预期 |
145
+
146
+ **U1 部署前置(必须先完成,否则在旧代码上验收)**:运行中的 Pi 通过扩展加载路径的 `import.meta.url` 解析 `TITLE_RUNNER_SCRIPT`(`src/index.ts:21`)——①对 Pi **当前实际加载**的 checkout(本机为 `~/.pi/agent/git/github.com/zhuxixi/pi-agent-board`,以 `pi` 会话内实际加载路径为准)执行 `git pull --ff-only` 并记录部署 SHA(PR 合并后);②完全退出并重启 Pi(dashboard/board 会话全部重开);③**title-model 专项检查**(VERIFY.md §2 的 one-shot 只验证默认模型,验不了 title-runner 实际使用的模型):用与本次部署相同的 title settings 显式跑一次 one-shot——`pi --mode json -p --no-session --model <resolved-title-model> [--thinking <resolved-thinking>] 'Reply with: ok'`(`<resolved-title-model>` 按 `resolveTitleSettings` 的优先级解析,未配置时为 `openai-codex/gpt-5.5`;thinking 为 off 时省略该参数);**健康判定与 VERIFY.md §2 对齐:进程退出码 0、出现 assistant 的 `message_end`、随后 `agent_end`、无认证错误**(可进一步确认回复包含 `ok`);④再执行①–④ 实测并回填结果。
147
+
148
+ **U1 rationale**: the poll window and one-shot model call involve a real detached runner + real title model on the user's machine; deterministic coverage of the same logic is achieved by A4/A6 with injected deps and hermetic fixtures, so U1 verifies deployment reality (spawn path, session-file timing, env resolution in a real process) rather than logic. **可执行时机**:PR 合并部署后(或明确将 `pi install` 指向被测 worktree 后),随时可执行。
149
+
150
+ ## Testability split (design constraint for implementation)
151
+
152
+ | Unit | Purity | Test boundary |
153
+ |------|--------|---------------|
154
+ | `isGreetingPrompt` (`src/core/title.mjs`) | pure | direct unit table tests (A1) |
155
+ | `resolveTitleSettings` (`src/core/title.mjs`) | pure (env passed as argument) | unit tests with plain objects (A5); nothing reads `process.env` outside the shell |
156
+ | `firstSubstantiveUserPrompt` (`src/core/title.mjs`) | pure (imports session-entries) | fixture-JSONL unit tests (A2) |
157
+ | `contentText` (`src/core/session-entries.mjs`, moved) | pure | exercised via A2 + existing session-view tests (A3) |
158
+ | `runTitleFlow` + constants (`src/core/title-flow.mjs`) | orchestration, **all** I/O injected (`now/sleep/readMeta/commitMeta/readSessionText/runOneShot`) | fake-clock unit tests drive ticks without real timers or spawns (A4); **no re-coupling allowed** — the shell must not regain decision logic, the flow must not read env |
159
+ | `runner/title-runner.mjs` shell | I/O only | hermetic spawn smoke via `test-support/fake-title-pi.mjs` + `pollIntervalMs` shrink (A6); real-pi behavior by U1 |
160
+
161
+ Implementation must keep these boundaries: the classifier, resolver, and projection stay pure; the flow module owns sequencing and guards with every effect injected; the shell only wires real deps.
162
+
163
+ ## Deployment / execution path
164
+
165
+ - Runner spawn path unchanged: `launchTitle` (`src/core/launch.mjs:97-105`) writes the title config and spawns the detached node script; poll mode only extends the runner's lifetime to ≤ ~5 min 15 s. Nothing in the repo reaps title-runners (sweeper targets warm PTY hosts only, `src/core/warm-host-sweeper.mjs:147-148`).
166
+ - Worktree (step 5, model B): branch `issue-295-greeting-title-poll` (≤64 chars, no prefixes); `npm run verify` in the worktree requires `node_modules` symlinked to the main checkout (known ENOENT otherwise — see research notes).
167
+ - U1 executes only after the deployed checkout (the one Pi actually loads) is updated and Pi is fully restarted — see the U1 preconditions block.
168
+
169
+ ## Alternatives considered (from the issue plan + research)
170
+
171
+ - **Skip generation for greetings, keep the slug forever**: trivial but leaves a useless name — rejected (does not satisfy the issue).
172
+ - **Re-queue title generation from the `reply()` path in `service.mjs`**: misses messages typed directly inside an attached session; the session JSONL observes every user message — rejected.
173
+ - **Revive a retry/backout machinery**: the referenced branch does not exist; would grow scope beyond the runner — rejected for this issue.
174
+ - **Let the flow read `process.env` directly**: rejected in round 1 (R1-G3) — breaks the fake-clock unit boundary and duplicates the legacy-alias precedence that already lives in the shell.
@@ -0,0 +1,158 @@
1
+ # Issue #297 根因报告与修复 Spec — 看板镜像 compaction 窗口
2
+
3
+ Drafted: deepseek/deepseek-flash (selected) · deepseek/deepseek-flash (physical) @ 2026-11-16T22:24:08+08:00
4
+ Revised: deepseek/deepseek-flash (selected) · deepseek/deepseek-flash (physical) @ 2026-11-16T22:43:40+08:00(round-1:接受 R1-G1/G2/G3 修订与 R1-D1–D6 细化,spec 升 v2)
5
+ Revised: deepseek/deepseek-flash (selected) · deepseek/deepseek-flash (physical) @ 2026-11-16T23:12:00+08:00(round-2:0 真缺口;吸收 R2-D1,U1 前置去掉不存在的 `npm run build`)
6
+ Base: main @ 608a22a(0.13.1)
7
+ Status: v2-final(round-2 收敛:0 真缺口、1 细化已吸收)
8
+
9
+ ## 0. 一句话结论
10
+
11
+ 给两条事件通路(interactive/hosted 扩展钩子、JSON runner 流)各加一个 compaction 窗口的**状态标记**:窗口内把行置为 `working` 并显示 `Compacting context…`,窗口结束时按「压缩前状态」恢复;标记里持久化压缩前快照(含 `processState`),因此两条通路共用同一套 reducer 语义,且 `isAgentBusy` 派生出的全部忙守卫自动恢复。
12
+
13
+ ## 1. 根因
14
+
15
+ 看板没有订阅 compaction 事件,不是镜像逻辑写错(证据与代码坐标见 issue #297 与本目录 `research/root-cause.md`):
16
+
17
+ - 扩展事件通路只注册了 8 个事件(`src/index.ts:238-244`),compaction 的扩展钩子 `session_before_compact` / `session_compact` / `session_compact_failed` 未被注册。
18
+ - JSON 通路 `reduceEvent`(`src/core/events.mjs:144`)没有 `compaction_start` / `compaction_end` 分支。
19
+ - `syncRowEvent`(`src/runtime/service.mjs:1849`)只在 `input | before_agent_start | agent_start` 时置 `working`。
20
+
21
+ 后果不只是标签:`isAgentBusy()`(`src/core/warm-host-sweeper.mjs:23`)只认 `queued/working`,压缩期间 mark-done / hold / follow-up drain / warm-host 驱逐保护 / header Running 计数全部把行当作空闲。
22
+
23
+ pi 侧事件时序(1.5.2 `dist/core/agent-session.js`):
24
+
25
+ - interactive 手动 `/compact`:`compaction_start` → `session_before_compact` → 摘要生成 → `session_compact`;失败时触发 `session_compact_failed`(`errorMessage` 已带 `Compaction failed: ` 前缀;`aborted` 表示取消)。
26
+ - interactive 自动压缩(threshold/overflow):同样先 `session_before_compact`,成功 `session_compact`,失败 `session_compact_failed`;`willRetry=true` 表示压缩后要重试被中断的 turn。
27
+ - JSON/RPC:只发 `compaction_start` / `compaction_end`(`{reason, result|undefined, aborted, willRetry, errorMessage?}`)。
28
+ - 手动压缩在 `prepareCompaction` 失败(如「Nothing to compact」)时**仍会**走 catch 分支发 `compaction_end` + `session_compact_failed`,因此不会留下「永远 Compacting」的悬空窗口——但这也意味着 begin 与 end 之间可能只隔毫秒级(R1-G2 的竞态来源)。
29
+
30
+ ## 2. 修复设计
31
+
32
+ ### D1 — 新增 compaction 窗口字段(ViewState + RunStatus)
33
+
34
+ ```js
35
+ /**
36
+ * @typedef {Object} CompactionWindow
37
+ * @property {"running"|"failed"} phase
38
+ * @property {"manual"|"threshold"|"overflow"} reason
39
+ * @property {number} startedAt
40
+ * @property {{semanticState:SemanticState, processState:ProcessState, summary:string,
41
+ * question:string|null, error:string|null}|null} previous
42
+ * 压缩前快照(含 processState,R1-G3)。failed 标记也保留它:重试成功后恢复压缩前的 error,
43
+ * 而不是把 `Compaction failed: …` 留在行上(CR round-1 advisory)。
44
+ * @property {string|null} error 仅 phase "failed":pi 的 errorMessage 原文。
45
+ */
46
+ ```
47
+
48
+ - `ViewState` 新增可选 `compaction`;`RunStatus` 新增 `compaction`。
49
+ - `createRunStatus` / `blankState` 初始化为 `null`;**`statusFromRow` 读穿现有值** `compaction: s.compaction ?? null`(R1-D1:这里不是「初始化 null」,否则 begin 落盘的 marker 在下一个事件重建时丢失)。
50
+ - `projectViewState` 透传 `compaction: status.compaction ?? null`。
51
+ - `src/core/foreground-projection-cache.mjs` 的 `CACHED_FIELDS` 白名单**必须加入 `"compaction"`**(R1-G2):前台通路 `syncRowEvent` 入口会 `adopt` 缓存覆盖白名单字段做 read-your-writes 纠正(issue #225 机制),白名单漏掉该字段会让「begin 写盘在途时 end 到达」的毫秒级失败路径丢掉 marker,随后落入 previous 缺失分支,idle 行卡在 working + `Compacting context…`。
52
+ - 旧行无该字段:读取时按 `?? null` 容忍,**不做迁移、不写版本号**。
53
+
54
+ ### D2 — 纯函数语义(events.mjs,两条通路共用)
55
+
56
+ `beginCompaction(status, { reason }, now)`:
57
+
58
+ - 已有 marker 且 `phase === "running"`(重复/嵌套 before_compact):**不覆盖** `previous`(I3),只刷新 `lastActivityAt`。
59
+ - 已有 marker 且 `phase === "failed"`(失败后用户立刻重试 `/compact`,或自动压缩失败后 pi 再次触发):**视为新窗口**——用当前(已恢复的)状态重拍快照,`phase` 置 `"running"`(R1-D2)。
60
+ - 无 marker:快照 `previous = { semanticState, processState, summary, question, error }`,`phase="running"`,`startedAt=now`。
61
+ - 统一置 `semanticState="working"`、`processState="alive"`、`lastActivityAt=now`,`summary = deriveSummary(status)`。
62
+ - 不动 `pendingQuestions`、`latestAssistantPreview`、`latestTool`、evidence。
63
+
64
+ `endCompaction(status, { willRetry, aborted, errorMessage }, now)`:
65
+
66
+ - `previous` 缺失(没等到 begin 落盘 / 迟到 end):清标记,保持 `working`,交给后续 `agent_end` 或 reconcile 收敛(这是唯一无法从快照恢复的分支,见 R1-G2 的缓存白名单消除主要来源)。
67
+ - `willRetry === true`:清标记、保持 `working`(run 会重试)。**有意丢弃 `errorMessage`**:重试会把该错误盖掉,写进行里只会误导(R1-D2,A2 有断言)。
68
+ - 否则 `previous.semanticState ∈ {queued, working}`:清标记、`semanticState="working"`、`processState="alive"`,summary 用 `deriveSummary`。
69
+ - 否则(resting 态):恢复 `semanticState / processState / question / error`,`summary = previous.summary || deriveSummary(status)`(R1-G3:`processState` 必须回到快照值,否则 idle 行会留下假 `alive`,导致 `row.alive`、reconcile 的 `looksActive`、dashboard stop 守卫全部误判)。
70
+ - `aborted === true`:按上面的恢复规则收尾,**不**写 `error`、**不**留 failed 标记(pi 的语义是「Compaction cancelled」)。
71
+ - `!aborted && errorMessage`:先按恢复规则回落,再写 `status.error = errorMessage`,留 `compaction = { phase:"failed", reason, startedAt:now, previous:null, error:errorMessage }`,**并在同一函数内 `status.summary = deriveSummary(status)`**(R1-G1:前台薄壳不经过 `reduceEvent` 的尾巴,失败文案只能由这里产出)。
72
+ - 所有分支清 `lastActivityAt = now`。
73
+
74
+ `finalizeRun`:清 `compaction = null`(终态不可能仍在压缩)。
75
+
76
+ ### D3 — summary 派生与归属(derive.mjs + events.mjs)
77
+
78
+ `deriveSummary` 的首个分支(**先于** currentTool / preview):
79
+
80
+ - `phase === "running"` → `"Compacting context…"`(对齐 pi 自己的状态文案)。
81
+ - `phase === "failed"` → `truncate(error, max)`(pi 的 `errorMessage` 已自带 `Compaction failed: ` 前缀,不再二次拼接)。
82
+
83
+ **summary 归属(R1-D3)**:compaction 窗口的两个 helper 是 summary 的唯一生产者。`reduceEvent` 末尾的 `if (meaningful) status.summary = deriveSummary(status)` 对 `compaction_start` / `compaction_end` 两个事件**跳过**(用局部标记),否则 JSON 通路会重派生、吃掉 `endCompaction` 刚恢复的 `previous.summary`,与前台通路行为分裂。
84
+
85
+ failed 标记的清除:`reduceEvent` 末尾计算 summary 之前(非 compaction 事件且 `meaningful`)清标记再派生;前台通路在 `syncRowEvent` 入口清除非 compaction 事件带来的残留标记。失败提示只活到下一次真实活动为止。
86
+
87
+ ### D4 — 扩展事件通路(src/index.ts + service.mjs)
88
+
89
+ - `src/index.ts` 追加三个注册,全部复用现有 `syncForeground`(hosted 走 `syncHostedEvent`,普通会话走 `syncForegroundEvent`):
90
+ `session_before_compact` / `session_compact` / `session_compact_failed`。
91
+ 处理器**不返回**任何值(不 cancel、不提供自定义 compaction)。
92
+ - `syncRowEvent` 追加三个分支,各 3–6 行薄壳:构造 facts → 调 D2 的纯函数 → `writeForegroundState` → `return true`:
93
+ - `session_before_compact` → `beginCompaction(status, { reason: event.reason }, now)`
94
+ - `session_compact` → `endCompaction(status, { willRetry: event.willRetry }, now)`
95
+ - `session_compact_failed` → `endCompaction(status, { willRetry: event.willRetry, aborted: event.aborted, errorMessage: event.errorMessage ?? null }, now)`
96
+ - 入口清理规则:`if (status.compaction && !COMPACTION_EVENTS.has(event.type)) status.compaction = null;`(COMPACTION_EVENTS = 上述三个),保证 abandon 的 running 标记/残留 failed 标记不会跨真实事件存活。
97
+ - `index.ts` 的注册名由 A6 静态断言覆盖(R1-D4:注册层不进 service harness,拼写错误不能只等用户实测发现)。
98
+
99
+ ### D5 — JSON 通路(events.mjs reduceEvent)
100
+
101
+ - `case "compaction_start"`:`beginCompaction(status, { reason: event.reason }, now)`,`meaningful = true`,标记「本次 summary 已由 helper 产出」。
102
+ - `case "compaction_end"`:`endCompaction(status, { willRetry, aborted, errorMessage }, now)`,`meaningful = true`,同样跳过尾巴重派生(D3)。
103
+
104
+ D2/D3 的语义在两条通路上完全相同;`runner/job-runner.mjs` 不需要改(beat 把整份 status 当作 patch,`applyStatusProjection` 泛型合并后由 `projectViewState` 投影)。
105
+
106
+ ### D6 — 不改动的层(明确排除)
107
+
108
+ - `isAgentBusy` 及其全部调用点:**读的是 semanticState,不是 compaction 字段**;本修复只通过置 `working` 生效。
109
+ - coordinator 决策层与 `PATCHABLE_FIELDS` 白名单:`sync_foreground` 是全量投影(`state-commands.mjs:612-618`),`run_progress` 是泛型 `diffFields` 合并,新字段无需白名单(R1-P1 已逐条核对)。
110
+ - evidence / session view / attach 通路:compaction 不产生 evidence 变化。
111
+
112
+ ## 3. 不变量
113
+
114
+ - **I1(窗口只动展示态)**:compaction 窗口内只允许改 `semanticState / processState / summary / lastActivityAt / compaction`;`pendingQuestions`、`latestAssistantPreview`、`latestTool`、evidence 保持原样。
115
+ - **I2(忙判据不扩语义)**:忙守卫仍只读 `semanticState ∈ {queued, working}`;`compaction` 字段不参与任何守卫判断。
116
+ - **I3(快照一次性)**:同一 running 窗口内重复 `before_compact`/`compaction_start` 不覆盖 `previous`;只有 failed 残留会被视为新窗口。
117
+ - **I4(恢复有条件)**:压缩前是 resting 态(`idle/needs_input/completed/failed/stopped/holding`)→ 恢复该态及其 `processState`;压缩前是 `queued/working` 或 `willRetry` → 保持 `working/alive`,交由后续 `agent_end` 收尾。
118
+ - **I5(失败不伪造终态)**:压缩失败只写 `error` 与失败 summary,不把行改成 `failed` 语义态(会话本身仍可用);`willRetry` 时连 error 也不写。
119
+ - **I6(终态不残留)**:`finalizeRun` 必清 `compaction`;任何真实活动事件都会清掉 failed 标记。
120
+ - **I7(旧行兼容)**:缺失字段按 `null` 解释,不迁移、不改 version。
121
+ - **I8(summary 单一生产者)**:窗口内 summary 只由 D2 helper 产出,两条通路的尾巴都不得重派生。
122
+
123
+ ## 4. 非目标
124
+
125
+ - 不显示压缩进度百分比、token 数、耗时、成本。
126
+ - 不处理 `summarization_retry_*`(pi 的重试提示不进看板),也不把压缩尝试渲染成独立行。
127
+ - 不改 mark-done / hold / follow-up / attach 的任何语义或文案。
128
+ - 不为 JSON runner 增加手动 `/compact` 能力(该通路本就没有斜杠命令)。
129
+ - 不改 dashboard 分组规则、header 计数公式、evidence 聚合。
130
+
131
+ ## 5. 验收矩阵
132
+
133
+ | ID | 功能点 | 验收方式 | 具体验证 | 通过标准 |
134
+ |----|--------|----------|----------|----------|
135
+ | A1 | `deriveSummary` 的 compaction 文案与优先级 | 自动化验证(unit) | `node --test test/derive.test.mjs` | running→`Compacting context…`;failed→`error` 原文(不二次加前缀);无标记时既有断言全过;优先级高于 currentTool/preview |
136
+ | A2 | D2/D3 reducer 语义(两条通路共用的纯函数) | 自动化验证(unit) | `node --test test/events.test.mjs` | `beginCompaction`:快照含 processState、running 幂等、failed 残留→新窗口;`endCompaction`:resting 恢复(含 `processState` 回到快照值)/ mid-run 保持 working+alive / `willRetry` 保持并**丢弃 errorMessage** / `aborted` 恢复且无 error / `errorMessage`→failed 标记 + `error` + summary=error 原文 / previous 缺失→保持 working;`finalizeRun` 清标记;`projectViewState` 透传、缺字段→null;`reduceEvent` 对 `compaction_start/end` 返回 meaningful、summary 不被尾巴重派生覆盖;下一个真实事件清掉 failed 标记 |
137
+ | A3 | 前台/hosted 镜像(`syncRowEvent` 三分支 + 忙守卫 + 在途竞态) | 自动化验证(integration,进程内) | `node --test test/service.test.mjs`(主断言用 coordinator off;另加一条 `startTrackedCoordinator` 的在途用例) | coordinator off:`session_before_compact`→`state.json`: working/alive/summary=`Compacting context…`/`compaction.previous.semanticState===idle`. 期间 `isAgentBusy(row)===true`、`markCompleted`/`holdView` 返回 busy 拒绝;`session_compact`→恢复 idle + 原 summary + `processState==="exited"` + `compaction===null`;failed(aborted)→恢复且无 error;failed(errorMessage)→恢复态 + `error` 原文 + **summary 为 `Compaction failed: …`**;重复 before 不覆盖 previous。tracked coordinator:back-to-back 触发 begin→end(不等待在途写)后轮询到恢复态,**不得**停在 working + Compacting |
138
+ | A4 | JSON runner 通路的端到端镜像 | 自动化验证(integration) | `node --test test/runner.integration.test.mjs`(fake-pi 新增 `compact` 模式,sleep 窗口 ≥1s) | 压缩窗口内用 `waitFor` 轮询到 `state.json` 为 working + `Compacting context…` 且 `status.json.compaction.phase==="running"`;`agent_end` 后行终态为 idle 且 `compaction===null`、`status.json` 同步清空 |
139
+ | A5 | 全量回归 | 自动化验证(build+static+test) | `npm run verify`(typecheck + perf gate + tests + coverage + pack:dry) | 全绿,覆盖率阈值(lines 85 / funcs 80 / branches 70)不下降 |
140
+ | A6 | `src/index.ts` 的三个钩子注册名(注册层不进 service harness) | 自动化验证(static) | 新增 `test/index-compaction-events.test.mjs`:读 `src/index.ts` 文本,断言包含 `pi.on("session_before_compact"`、`pi.on("session_compact"`、`pi.on("session_compact_failed"` 三处 | 三条注册都在;文件被改名/删除时测试失败(fail-closed) |
141
+ | U1 | 真实 `/compact` 观感与守卫 | 用户实测 | **前置**:切到 PR 分支并 `npm install`——**没有构建步骤**(`package.json` 的 `main`/`exports` 直接指向 `./index.ts`,pi 加载 TS 源;不存在 `build` script),或用隔离启动 `--extension <worktree 绝对 index.ts>`;随后重启 pi 或 `/reload` 扩展;JSON 通路需重新 dispatch 一个后台会话才会用新 runner。**时机**:A1–A6 全绿后、合并前。**步骤**:在 board 里对一个有历史的后台会话 attach → 执行 `/compact`(长历史会话最直观)。**观察**:(1) 行进入 Running 且 summary 为 `Compacting context…`;(2) 压缩期间在 dashboard 按 `d` 标记完成被拒(提示等待);(3) 压缩结束行回到压缩前状态(通常 Needs instructions),summary 不再是 Compacting;(4) 阈值压缩:用一个小上下文窗口模型(或超长历史)跑一个后台会话,压缩发生时行不显示为空闲 | 四项均符合;(3) 若压缩失败(用 `Nothing to compact` 的短历史触发),行显示 `Compaction failed: ...` 且不残留 Compacting |
142
+
143
+ ## 6. 可测性拆分设计(实现硬约束)
144
+
145
+ - **纯函数层(events.mjs)**:`beginCompaction` / `endCompaction` 不读盘、不取时钟(`now` 注入);`endCompaction` 的六种分支全部可由 A2 单测覆盖,`endCompaction` 是 summary 的唯一生产者(I8)。
146
+ - **派生层(derive.mjs)**:`deriveSummary` 的 compaction 分支是纯字符串决策,A1 直接断言;不引入新的 I/O。
147
+ - **薄壳层(service.mjs)**:`syncRowEvent` 三个分支只做「取字段 → 调纯函数 → 写盘」,不做判断;语义断言放在 A2,落盘断言放在 A3。**禁止**把 restore 规则复制进 service(否则两条通路会漂移)。
148
+ - **缓存层(foreground-projection-cache.mjs)**:只加白名单项,不改机制;A3 的在途用例是这个白名单的回归保护。
149
+ - **驱动层(test-support/fake-pi.mjs)**:新增 `compact` 模式(`agent_start` → `compaction_start` → sleep ≥1000ms → `compaction_end` → `message_end` → `agent_end`),只负责发事件。**sleep 下限的依据**:`runner/job-runner.mjs:37` 的 `WRITE_THROTTLE_MS = 250`,beat 节流后还要经协调器物化,窗口 <1s 会间歇性错过 running 相位(R1-D5);A4 用 `waitFor` 轮询,不做一次性读取。
150
+ - **静态层(A6)**:只读文本断言注册名,不 import TS(`src/index.ts` 不是可运行 ESM)。
151
+ - **测试边界**:A1 只碰 derive;A2 只碰 events;A3 只碰 service + 写盘(off / tracked coordinator 两种);A4 只碰 runner 子进程与 JSON 流;A6 只碰源文本。任何一层都不需要真实模型调用或真实 `/compact`(那是 U1 的职责)。
152
+
153
+ ## 7. 风险与回滚
154
+
155
+ - **风险 1(字段进入投影)**:`compaction` 进入 `state.json` 后,若有外部消费者做严格 schema 校验会报未知字段。仓内证据:`readState` 只做 JSON 解析、dashboard 按已知字段读取,无严格 schema;`patch_fields` 白名单只约束命令来源,不约束投影字段。
156
+ - **风险 2(typecheck 覆盖面,R1-D6)**:`tsconfig.json:9` 是 `checkJs: false`,本改动主体是 `.mjs`,`npm run verify` 的 typecheck 几乎不覆盖其函数体——**真正的把关者是 A1–A4 的测试与覆盖率阈值**,不要把 A5 当成类型级保护。
157
+ - **风险 3(summary 覆盖策略)**:写错会让行短暂显示错误文案。A1/A2 钉住 running/failed 两相位、恢复取值与清除时机;U1 覆盖真实观感。
158
+ - **回滚**:按层列文件——运行时 `src/index.ts`、`src/runtime/service.mjs`、`src/core/events.mjs`、`src/core/derive.mjs`、`src/core/types.mjs`(三个 typedef)、`src/core/foreground-projection-cache.mjs`(白名单);测试 `test/derive.test.mjs`、`test/events.test.mjs`、`test/service.test.mjs`、`test/runner.integration.test.mjs`、新增 `test/index-compaction-events.test.mjs`;夹具 `test-support/fake-pi.mjs`。revert 该 PR 即可;`state.json` 中的 `compaction` 字段对旧代码是未知字段(被忽略),无迁移负担。
@@ -0,0 +1,209 @@
1
+ # Spec — Issue #95 切片:临时隔离 `internal marker failure … (legacy main)` 并补 F3 现场
2
+
3
+ > 状态:**DRAFT 待用户确认**(`stepwise` 档,步 4 收敛后 ⏸)
4
+ > 认领:zhuxixi(2026-11-22)
5
+ > 调研:同目录 `research/01-red-state-and-scope.md`、`research/02-mechanism-evidence.md`(2026-09-25)、
6
+ > `research/03-legacy-quarantine-slice.md`(2026-11-22,本切片专属)
7
+ > 上游:issue #95(umbrella,本切片**不关闭**它)
8
+ > 基线 HEAD:`c1e39cd`(2026-11-23 main;目标相关文件与 `df083a5` 无差异;已完成的 run `43781526496` Node 22 Coverage 红在本切片目标用例)
9
+ > Drafted: kimi-coding/k3.1-pro (selected) · kimi-coding/k3.1-pro (physical) @ 2026-11-22T21:57:44+08:00
10
+ > Revised: kimi-coding/k3.1-pro (selected) · kimi-coding/k3.1-pro (physical) @ 2026-11-22T22:14:46+08:00(R1:接受 R1-G1 + R1-D1…D5 全部六条)
11
+
12
+ > Revised: kimi-coding/k3.1-pro (selected) · kimi-coding/k3.1-pro (physical) @ 2026-11-22T22:30:23+08:00(R2:收敛,接受 R2-D1…D3 三条细化;A7 预算改为有实测依据的 240s)
13
+
14
+ ## 1. 问题陈述
15
+
16
+ `test/attach-frame-witness.integration.test.mjs` 的
17
+ `internal marker failure revokes capability via onUnavailable (legacy main)` 是 main CI 的反复红源:
18
+ 11-16 run `43781526496` 上它烧满 15s 等待(`duration_ms 15263.9`),失败信息只有一句 `timed out waiting`;
19
+ 同一 run 的 owned 半边与 Node 24 双 job 全绿。issue 台账记录该签名近 6 次 main CI 有 5 次命中。
20
+
21
+ 这条红属于 #95 已定论的 B 类:**事件产生了,但没在墙钟窗口内到达**(并行争抢 + 默认文件级并发)。
22
+ 它**不是** A 类(事件根本没产生的生产缺陷)——没有证据指向 legacy runner 的降级链路本身坏了。
23
+
24
+ **本切片的定位是临时隔离,不是修复。** #95 的结构性病因(无串行化、墙钟预算)原样保留,
25
+ 恢复条件写死为「process 相位串行化落地后 revert」。
26
+
27
+ ## 2. 设计决策
28
+
29
+ ### D1:只跳 legacy 半边,owned 半边原样保留并继续跑
30
+
31
+ `for (const legacy of [false, true])` 生成的两个用例共享**同一段参数化 test 体**,因此隔离只能写成条件式:
32
+
33
+ ```js
34
+ { skip: legacy ? "issue #95: temporary quarantine … restore after process-phase serialization" : undefined }
35
+ ```
36
+
37
+ `legacy === false`(owned)时 `skip` 为 `undefined`,用例照常执行;`legacy === true` 时跳过并输出理由。
38
+ skip 理由是字符串而非 `true`,会原样出现在 TAP 输出里,让每次跳过都自证原因。
39
+
40
+ skip 文案须包含三要素:`issue #95`、临时性质(temporary quarantine)、恢复条件(restore after process-phase serialization)。
41
+
42
+ - **为什么不整条删**:它保护的跨进程降级链路(marker 写失败 → `onUnavailable` → `socket.destroy`
43
+ → runner 清理 → 广播 `enabled:false` → host.json 改写)只有本用例在测;
44
+ `attach-frame-reporter.test.mjs:557` 的单测只覆盖第一步。整条删 = 撤掉兜底保护。
45
+ - **为什么跳 legacy 而不是 owned**:owned 是现代默认路径(`attachMode==="protocol" && frameWitnessAvailable`),
46
+ 保护价值更高,且当前不是红源。
47
+ - **为什么不用 `--test-name-pattern` 隔离**:#178 D6 已实证 Node 24 下负向前瞻排除不掉测试(root 聚合条目名称为空、恒匹配)。
48
+
49
+ ### D2:保留的 owned 半边必须补 F3 现场快照
50
+
51
+ 本文件是 F3 纪律的漏网文件(同族 6 个文件已接 `test-support/flake-postmortem.mjs`,本文件零命中)。
52
+ 给 owned 半边的两处等待接上 capture thunk,使超时错误自带 **host / state / diagnosticsTail / journal / screenLog** 现场。
53
+ **`status` 恒为 `<absent>`,不是「可能缺失」**:`capturePostmortem` 只在 `runId` 非空时才读 status
54
+ (`test-support/flake-postmortem.mjs:87`),而本文件 fixture 直接 spawn `pty-runner`、不经协调器建 run,全文件无 `runId`。
55
+ 本切片不改这个行为——为拿到 status 而引入协调器属于范围扩张。
56
+
57
+ 实现走**本文件本地 `waitFor` 的可选参数**,与同族 `runner.integration.test.mjs:71` 的既有写法一致:
58
+
59
+ ```js
60
+ async function waitFor(predicate, timeoutMs = 15000, capture = null) {
61
+ return waitForWithPostmortem(predicate, { timeoutMs, intervalMs: 25, capture });
62
+ }
63
+ ```
64
+
65
+ - **默认值与轮询间隔不变**(15000 / 25ms),未传 capture 的既有 74 处 `await waitFor(` 调用行为字节级不变。
66
+ - 只在 owned 半边传 capture;legacy 半边已 skip,不接。
67
+ - **不做全文件迁移**:其余 18 个用例的等待不在本切片范围,避免 diff 膨胀。
68
+
69
+ ### D3:守卫必须钉「条件式 skip」这一具体形态,并给 TAP 面一个真归属
70
+
71
+ **前置事实(决定守卫怎么写)**:两个「半边」不是两段独立源码,而是**同一段参数化 test 体**——
72
+ `for (const legacy of [false, true])` + 模板串名(`test/attach-frame-witness.integration.test.mjs:1320-1321`)。
73
+ 所以「owned 段无 skip / legacy 段有 skip」在源码文本上互斥,**唯一可实现且防得住扩大化的守卫是钉住条件式形态**:
74
+
75
+ ```js
76
+ { skip: legacy ? "issue #95: temporary quarantine …" : undefined }
77
+ ```
78
+
79
+ 沿用 `test/wait-capture-wiring.test.mjs`(#178 A3/A7)的源码级手法,新增守卫断言五件事:
80
+
81
+ 1. 用例体匹配 `skip:\s*legacy\s*\?\s*"issue #95[^"]*"`,且 false 分支为 `undefined`
82
+ ——拍平成 `skip: "…"`(全跳)或删掉 skip(隔离失效)都会红;
83
+ 2. skip 文案含「temporary quarantine」与恢复条件关键词;
84
+ 3. 两条核心断言仍在,**以磁盘源文本为准**(`:1327` 与 `:1330`,含 `msg.` 前缀与可选链):
85
+ 广播断言 `msg.status?.frameWitness?.enabled === false`、host 断言 `readHost(root, viewId)?.frameWitness?.enabled === false`
86
+ ——删断言不是转绿的方式;守卫按真实文本写正则,不得按转述写;
87
+ 4. 用例体内每个 `await waitFor(` 都以裸 `capture` 收尾(复用既有正则 `/,\s*capture\s*$/`);
88
+ 5. 本地 `waitFor` 委托层的默认值文本仍为 `timeoutMs = 15000` 与 `intervalMs: 25`。
89
+
90
+ **TAP 面(「owned 半边真的在跑」)必须有自动归属,不能靠人眼扫**:新增一条用例 spawn
91
+ `node --test test/attach-frame-witness.integration.test.mjs`(预算见下),
92
+ 解析其 TAP 输出,断言:legacy 条目带 `# SKIP` 且理由含 `issue #95`;owned 条目为 `ok` 且**不含** `SKIP`。
93
+ 这条是本切片唯一会 spawn 进程的守卫,与纯文本守卫分文件存放(见 §3.2)。
94
+
95
+ **预算依据(实测,非拍脑袋)**:本机(8 核、Node v24.22.1)跑目标文件全量 29 条用例,墙钟 **45.08s**、
96
+ `duration_ms 45058`,29 pass / 0 fail / 0 skipped;目标用例单条约 0.51s(基线 TAP 留档见下)。
97
+ 取 `{ timeout: 240_000 }`(4 分钟 ≈ 5.3× 本机实测)以容纳 CI 慢机与 c8 插桩开销,
98
+ 并按 `scripts/budget-audit.mjs` 规则 (b) 附 `// budget: spawns the whole 29-case file; 4 min = 5.3x the 45.08s local measurement` 豁免。
99
+ 若实测 CI 上仍不够,改预算属于后续 PR 的事,不在本切片里反复加宽。
100
+
101
+ ### D4:范围与硬边界
102
+
103
+ - **只动测试**:不改 `runner/`、不改 `src/`、**`ci.yml` 零改动**、不加依赖、不改任何测试用例名称。
104
+ - **不改预算数值**:15s / 5s 等待与文件内既有的 `{ timeout: 20000 }`(`spawnSync` 选项,非 test 超时)原样保留。
105
+ 本切片不是预算调整,预算纪律由 #95 F2 的 `budget-audit` 门禁继续把守。
106
+ - **不动 #95 的其它签名**:`subscribe_terminal`、`A5 burst`、`attach-entry-22` B/Q、reporter 系列等一律不碰。
107
+ - **不关闭 #95**:PR 描述用 `Refs #95`,不用 `Fixes`。
108
+
109
+ ## 3. 组件契约
110
+
111
+ ### 3.1 `test/attach-frame-witness.integration.test.mjs`(改)
112
+
113
+ | 点 | 改动 |
114
+ |---|---|
115
+ | import | 新增 `capturePostmortem, formatPostmortem, waitForWithPostmortem`(来自 `../test-support/flake-postmortem.mjs`) |
116
+ | `waitFor` | 签名加第三个可选参数 `capture = null`,函数体改为委托 `waitForWithPostmortem`,默认 `timeoutMs = 15000`、`intervalMs = 25` 不变 |
117
+ | legacy 半边 | test 选项加 `{ skip: legacy ? "issue #95: temporary quarantine …" : undefined }`(条件式,见 D1) |
118
+ | owned 半边 | 用例体内先建命名绑定 `const capture = () => formatPostmortem(capturePostmortem(root, viewId, null));`,两处 `await waitFor(...)` 以裸 `capture` 收尾 |
119
+
120
+ capture 使用 `runId = null`:本文件的 fixture 直接 spawn `pty-runner`、不经协调器创建 run,因此现场里 `status` 恒为 `<absent>`
121
+ (见 D2);`capturePostmortem` 对其余缺失文件一律安全返回 `null`(`safe()` 包裹),不会二次抛错。
122
+
123
+ **形态必须与兄弟文件先例一致**:`control-reconcile.integration.test.mjs:343` 与 `pty-runner.integration.test.mjs:521`
124
+ 都是「命名 `capture` 绑定 + 裸标识符传参」,既有守卫正则 `/,\s*capture\s*$/`
125
+ (`test/wait-capture-wiring.test.mjs:120,127`)也只认这个形态。写内联 thunk 会让复用的守卫必红。
126
+
127
+ ### 3.2 `test-support/test-source-scan.mjs`(新,纯函数模块)
128
+
129
+ **为什么放 `test-support/` 而不是从守卫文件 import**:`test/wait-capture-wiring.test.mjs` 在 import 时即注册 5 个顶层 `test()`,
130
+ 跨测试文件 import 会在新守卫文件的 `node --test` 进程里把这 5 个用例**再跑一遍**(`node --test` 对每个测试文件各起一个子进程;`scripts/run-tests.mjs:331` 把全部文件交给单个 `node --test` 调用),
131
+ 红时失败归因翻倍。故把纯函数移到 `test-support/`,两个守卫文件都从那里 import——符合仓约定的「纯函数 + 薄 I/O 壳」分层。
132
+
133
+ 迁移内容(实现阶段不改其逻辑,只搬家):
134
+
135
+ - `testCaseBody(source, marker)` —— 从 `test/wait-capture-wiring.test.mjs:40` 迁入并 re-export,原文件改为 import;
136
+ - `waitForCalls(body)` —— 从 `:55` 迁入,同上;
137
+ - `indentedTestCaseBody(source, marker)` —— **新增**,处理本切片目标用例位于 `for` 循环内、**缩进一级**的情形:
138
+ 起始为行首 `\ttest(`,收尾为该缩进层级的 `\n\t});`;marker 不存在或找不到收尾都显式抛错(防空跑成绿)。
139
+
140
+ ### 3.3 `test/frame-witness-quarantine.test.mjs`(新,unit/static)
141
+
142
+ 纯文本守卫(D3 第 1/2/3/4/5 条)+ `indentedTestCaseBody` 的真值表单测。不 spawn 进程。
143
+
144
+ ### 3.4 `test/frame-witness-quarantine-tap.test.mjs`(新,integration)
145
+
146
+ 唯一 spawn 子进程的守卫:跑目标文件、解析 TAP、断言 legacy SKIP / owned 非 SKIP(D3 的 TAP 面)。
147
+ 与纯文本守卫分文件,避免「只想跑静态检查」时被迫跑一遍真实 runner 套件。
148
+
149
+ ### 3.5 非组件
150
+
151
+ 不新增 `src/` 模块、不改 `scripts/run-tests.mjs`、不动 `package.json` 脚本。
152
+ `test/wait-capture-wiring.test.mjs` 只改 import 来源,其 5 个用例的断言与行为不变。
153
+
154
+ ## 4. 可测性拆分设计(实现阶段硬约束)
155
+
156
+ | 单元 | 性质 | 怎么测 | 验收 |
157
+ |---|---|---|---|
158
+ | `indentedTestCaseBody(source, marker)` | **纯函数**(字符串处理,无 I/O) | 直接传字符串样本,断言:正确截取、不吞掉后续用例、marker 缺失抛错、收尾缺失抛错 | A1 |
159
+ | `waitFor` 委托层 | 薄壳,决策全在已测的 `waitForWithPostmortem` | 不新增单测;由 `test/flake-postmortem.test.mjs` 既有 11 个顶层用例覆盖核心逻辑;默认值由静态守卫钉住(A2) | A2 |
160
+ | capture thunk | 纯 I/O 读取 + 已测的 `formatPostmortem` | 由 `test/flake-postmortem.test.mjs` 覆盖渲染;本切片只保证接线形态 | A3 |
161
+ | 条件式 skip 接线 | 声明式 test 选项 | 静态守卫钉形态(A4)+ TAP 实证(A7) | A4 / A7 |
162
+ | 纯函数迁移 | 搬家不改逻辑 | `test/wait-capture-wiring.test.mjs` 既有 5 个用例原样通过即回归钉 | A6 |
163
+
164
+ 边界声明:**解析(纯)↔ 等待(已测共享件)↔ 断言(测试)三层不得合并**;
165
+ 不允许把 `indentedTestCaseBody` 内联进断言里,也不允许在目标文件里重写一份 postmortem 渲染。
166
+
167
+ ## 5. 验收矩阵
168
+
169
+ ### 自动化验证
170
+
171
+ | ID | 功能点 | 验收方式 | 具体验证 | 通过标准 |
172
+ |----|--------|----------|----------|----------|
173
+ | A1 | 缩进用例段解析 + 纯函数迁移 | 自动化(unit,`test/frame-witness-quarantine.test.mjs`) | `node --test test/frame-witness-quarantine.test.mjs` | 真值表通过;marker 缺失 / 收尾缺失均抛错(防空跑成绿);不吞后续用例 |
174
+ | A2 | 默认等待行为不变 | 自动化(static,同上) | 静态守卫断言委托层文本含 `timeoutMs = 15000` 与 `intervalMs: 25`;`node --test test/attach-frame-witness.integration.test.mjs` 退出码 0 | 默认值被改即红;`git diff` 复核为评审注记,不计入自动化 |
175
+ | A3 | owned 半边现场接线 | 自动化(static,同上) | 静态守卫断言用例体内每个 `await waitFor(` 以裸 `capture` 收尾(复用 `/,\s*capture\s*$/`) | 全部命中;漏接即红 |
176
+ | A4 | skip 是条件式且只落 legacy | 自动化(static,同上) | 断言用例体匹配 `skip:\s*legacy\s*\?\s*"issue #95[^"]*"` 且 false 分支为 `undefined` | 拍平成全跳、或删 skip,均红 |
177
+ | A5 | 降级断言未被削弱 | 自动化(static,同上) | 静态守卫按磁盘真实文本断言两条核心断言仍在用例体(`msg.status?.frameWitness?.enabled === false`、`readHost(root, viewId)?.frameWitness?.enabled === false`) | 均在;任一被删即红 |
178
+ | A6 | 既有套件与迁移回归 | 自动化(unit + integration + build) | `node --test test/wait-capture-wiring.test.mjs`;`npm run verify` | 既有 5 个守卫用例原样通过;verify exit 0(typecheck + perf gate + 全量测试 + 覆盖率阈值 85/80/70 + pack:dry) |
179
+ | A7 | TAP 面:owned 真的在跑、legacy 真的被跳 | 自动化(integration,`test/frame-witness-quarantine-tap.test.mjs`) | `node --test test/frame-witness-quarantine-tap.test.mjs`(该守卫内部 spawn `node --test test/attach-frame-witness.integration.test.mjs` 并解析 TAP) | legacy 条目带 `# SKIP` 且理由含 `issue #95`;owned 条目为 `ok` 且不含 `SKIP`。两版 Node 由 CI 矩阵各跑一次(A8) |
180
+ | A8 | CI 双矩阵 | 自动化(CI) | PR 的 `Test (Node 22)` / `Test (Node 24)` | 两个必需检查均绿;A7 的 TAP 守卫在两版 Node 上都执行并通过 |
181
+
182
+ ### 用户实测 / 合并后观测
183
+
184
+ | ID | 功能点 | 验收方式 | 步骤与观察 | 通过标准 |
185
+ |----|--------|----------|------------|----------|
186
+ | U1 | 该签名不再阻塞 main | 用户实测(合并后 CI 观测) | `gh run list --branch main --limit 8`,逐 run 记录失败点 | 合并后 ≥5 次 main run 中,`internal marker failure … (legacy main)` 零命中(它已 SKIP);若 owned 半边转红,失败信息**必须**自带 postmortem 现场 |
187
+ | U2 | 隔离可回退 | 用户实测(#95 串行化落地时) | revert 本切片 commit 后跑 `node --test test/attach-frame-witness.integration.test.mjs` | 静态守卫同步更新后,legacy 半边恢复执行;本条是恢复动作的 checklist,不在本 PR 执行 |
188
+
189
+ **诚实声明**:A6/A7 全绿不能证明 #95 痊愈。本切片只移除一条签名,
190
+ 同文件其余等待与其它 32 个真实进程文件的 flake 风险原样存在,U1 只对该签名负责。
191
+
192
+ ## 6. 非目标
193
+
194
+ - 不实现 #95 的 process 相位串行化(F5/D1),不新增 CI job,不改分支保护。
195
+ - 不做 `attach-entry-22` B/Q 的 c8 相位剔除(属另一条线)。
196
+ - 不迁移本文件其它 18 个用例的 postmortem 接线。
197
+ - 不清理 `/tmp/agentview-*` 夹具残留(#95 F6 / #211)。
198
+ - 不改 `enforce_admins`、不使用 `--admin` 绕过必需检查。
199
+
200
+ ## 7. 交付物清单
201
+
202
+ 1. `test/attach-frame-witness.integration.test.mjs`:skip + F3 接线(预计 ~20 行)
203
+ 2. `test-support/test-source-scan.mjs`:新纯函数模块(迁移 `testCaseBody` / `waitForCalls` + 新增 `indentedTestCaseBody`)
204
+ 3. `test/wait-capture-wiring.test.mjs`:改为从 `test-support/test-source-scan.mjs` import,断言不变
205
+ 4. `test/frame-witness-quarantine.test.mjs`:新纯文本守卫 + 解析真值表(预计 ~110 行)
206
+ 5. `test/frame-witness-quarantine-tap.test.mjs`:新 TAP 实证守卫(预计 ~60 行)
207
+ 6. spec 文档落 worktree `docs/superpowers/specs/2026-11-22-issue-95-legacy-quarantine-design.md`(首个 commit)
208
+ 7. plan 落 worktree `docs/superpowers/plans/2026-11-23-issue-95-legacy-quarantine.md`
209
+ 8. issue #95 评论:切片交付对账 + 「未结案」声明 + 恢复条件