@andares/pi-toolkits 0.14.0 → 1.0.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 (59) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +101 -34
  3. package/README.zh-CN.md +68 -32
  4. package/package.json +10 -3
  5. package/src/features/ask/index.test.ts +15 -0
  6. package/src/features/ask/index.ts +18 -1
  7. package/src/features/init/audit.test.ts +19 -2
  8. package/src/features/init/audit.ts +117 -15
  9. package/src/features/init/index.test.ts +123 -1
  10. package/src/features/init/index.ts +156 -46
  11. package/src/features/init/parity.test.ts +176 -0
  12. package/src/features/init/parity.ts +229 -0
  13. package/src/features/init/plan.ts +25 -3
  14. package/src/features/init/refresh.test.ts +88 -1
  15. package/src/features/init/refresh.ts +43 -64
  16. package/src/features/init/spec.ts +11 -0
  17. package/src/features/init/templates/memory-readme.md +9 -2
  18. package/src/features/init/templates/workflow-block.md +2 -2
  19. package/src/features/init/test-helpers.ts +1 -0
  20. package/src/features/init/workflow.ts +159 -0
  21. package/src/features/permission/index.ts +1 -1
  22. package/src/features/quit-guard/constants.ts +18 -5
  23. package/src/features/quit-guard/index.ts +75 -29
  24. package/src/features/quit-guard/killer.test.ts +77 -0
  25. package/src/features/quit-guard/killer.ts +215 -0
  26. package/src/features/review/index.ts +14 -0
  27. package/src/features/review/review.test.ts +34 -2
  28. package/src/features/spec/assets/index-CdTerMvN.css +1 -0
  29. package/src/features/spec/assets/index-Dv52AIjX.js +1 -0
  30. package/src/features/{plan → spec}/assets/index.html +3 -3
  31. package/src/features/{plan → spec}/assets.test.ts +5 -5
  32. package/src/features/{plan → spec}/blocks.ts +1 -1
  33. package/src/features/{plan → spec}/feedback.test.ts +26 -26
  34. package/src/features/{plan → spec}/feedback.ts +14 -14
  35. package/src/features/{plan → spec}/index.test.ts +148 -63
  36. package/src/features/{plan → spec}/index.ts +136 -105
  37. package/src/features/{plan → spec}/prompt.test.ts +20 -20
  38. package/src/features/{plan → spec}/prompt.ts +25 -25
  39. package/src/features/{plan → spec}/render.test.ts +2 -2
  40. package/src/features/{plan → spec}/server.test.ts +21 -21
  41. package/src/features/{plan → spec}/server.ts +22 -22
  42. package/src/features/{plan → spec}/store.test.ts +77 -35
  43. package/src/features/{plan → spec}/store.ts +80 -52
  44. package/src/features/uat/index.test.ts +20 -5
  45. package/src/features/uat/index.ts +16 -13
  46. package/src/features/uat/record-tool.ts +6 -5
  47. package/src/features/uat/records.test.ts +5 -5
  48. package/src/features/uat/state.ts +13 -5
  49. package/src/index.ts +6 -6
  50. package/src/lib/ask-control.ts +2 -2
  51. package/src/lib/permission-control.ts +4 -4
  52. package/src/lib/phases.ts +50 -0
  53. package/src/lib/web-review.ts +1 -1
  54. package/src/features/plan/assets/index-C1YLIi4I.js +0 -1
  55. package/src/features/plan/assets/index-DMEpYC3V.css +0 -1
  56. /package/src/features/{plan → spec}/blocks.test.ts +0 -0
  57. /package/src/features/{plan → spec}/diff.test.ts +0 -0
  58. /package/src/features/{plan → spec}/diff.ts +0 -0
  59. /package/src/features/{plan → spec}/render.ts +0 -0
@@ -6,7 +6,7 @@ This project uses the `@andares/pi-toolkits` ask workflow. The steps run in this
6
6
  | step | entry | what it does |
7
7
  | --- | --- | --- |
8
8
  | discuss | `/ask` | read-only consult; `scratchpad` is the only write channel |
9
- | plan | `/ask-plan <topic>` | research, ask questions, write `specs/<slug>.md`, review it block by block in the browser, implement only after approval |
9
+ | spec | `/ask-spec <topic>` | research, ask questions, write `specs/<slug>.md`, review it block by block in the browser, implement only after approval |
10
10
  | record | `record_change` | after the work: write the change record and one user-visible behaviour sentence |
11
11
  | review | `/ask-review` | optional third-party model cross-check (check + fix); it leaves no state behind |
12
12
  | accept | `/ask-uat` | cluster pending change records into acceptance items, verify them on the page, tick them off |
@@ -16,6 +16,6 @@ Rules that are easy to break:
16
16
  - Change records live in `.agents/implementations/`; new ones carry the minute in the name (`YYYY-MM-DD_HHMM_slug.md`) and repeat it in the first line (`# YYYY-MM-DDTHH:MM±HH:MM — title`).
17
17
  - The acceptance ledger is `.agents/uat/ledger.jsonl`, append-only, committed to git, and belongs to the main checkout. Never edit it by hand: the tools and the page write it.
18
18
  - Acceptance items are created by clustering on the UAT side, never by an implementation session.
19
- - Plans go in `specs/`, memory in `.agents/memory/`, evidence in `.agents/implementations/`.
19
+ - Specs go in `specs`, memory in `.agents/memory/`, evidence in `.agents/implementations/`.
20
20
 
21
21
  <!-- ask-init:end workflow -->
@@ -65,6 +65,7 @@ export function installedProject(extra: Record<string, string> = {}): string {
65
65
  "| --- | --- | --- |",
66
66
  "| `specs/PLAN.md` | route | before work |",
67
67
  "| `.agents/memory/FINISHED.md` | closed work | closing |",
68
+ "| `.agents/implementations/` | change records | after work |",
68
69
  "",
69
70
  ].join("\n"),
70
71
  "specs/PLAN.md": "# Plan (open work)\n\n## Route\n\n_None._\n",
@@ -0,0 +1,159 @@
1
+ /**
2
+ * init feature — the one framework-owned region inside `AGENTS.md`.
3
+ *
4
+ * The workflow block is delimited by HTML comments. Matching must be strict:
5
+ * documentation often *shows* these markers as inline code, and a plain
6
+ * `indexOf` would treat such an example as the real block and replace the
7
+ * surrounding prose. Markers therefore have to occupy a whole line, sit outside
8
+ * a fenced code block, and come in exactly one matching pair.
9
+ */
10
+ import { WORKFLOW_BLOCK_BEGIN, WORKFLOW_BLOCK_END } from "./spec.js";
11
+
12
+ export type BlockStatus =
13
+ | "current"
14
+ | "updated"
15
+ | "inserted"
16
+ | "malformed"
17
+ | "hand-written"
18
+ | "missing-agents";
19
+
20
+ /** What an existing file looks like; `missing-agents` is a file-level fact. */
21
+ export type WorkflowStatus =
22
+ | "current"
23
+ | "stale"
24
+ | "missing"
25
+ | "malformed"
26
+ | "hand-written"
27
+ | "missing-agents";
28
+
29
+ interface LineSpan {
30
+ readonly start: number;
31
+ /** Offset just after the line's newline (or the end of the text). */
32
+ readonly end: number;
33
+ readonly text: string;
34
+ }
35
+
36
+ const BEGIN_RE = /^<!--\s*ask-init:begin workflow\b[^\n]*-->\s*$/;
37
+ const END_RE = /^<!--\s*ask-init:end workflow\s*-->\s*$/;
38
+ const FENCE_RE = /^\s*(```+|~~~+)/;
39
+
40
+ /**
41
+ * Lines outside fenced code blocks, with their byte offsets. The fence lines
42
+ * themselves are skipped; a marker cannot share a line with them.
43
+ */
44
+ function linesOutsideFences(text: string): LineSpan[] {
45
+ const out: LineSpan[] = [];
46
+ const raw = text.split("\n");
47
+ let offset = 0;
48
+ let fence: string | undefined;
49
+ for (let index = 0; index < raw.length; index += 1) {
50
+ const line = raw[index];
51
+ const start = offset;
52
+ const hasNewline = index < raw.length - 1;
53
+ const end = start + line.length + (hasNewline ? 1 : 0);
54
+ offset = end;
55
+ const visible = line.endsWith("\r") ? line.slice(0, -1) : line;
56
+ const fenceMatch = FENCE_RE.exec(visible);
57
+ if (fenceMatch) {
58
+ const marker = fenceMatch[1][0];
59
+ if (!fence) fence = marker;
60
+ else if (fence === marker) fence = undefined;
61
+ continue;
62
+ }
63
+ if (fence) continue;
64
+ out.push({ start, end, text: visible });
65
+ }
66
+ return out;
67
+ }
68
+
69
+ type Located =
70
+ | { kind: "none" }
71
+ | { kind: "malformed"; reason: string }
72
+ | { kind: "found"; begin: LineSpan; end: LineSpan };
73
+
74
+ /** Locate exactly one marker pair; anything ambiguous is malformed. */
75
+ export function locateWorkflowBlock(text: string): Located {
76
+ const lines = linesOutsideFences(text);
77
+ const begins = lines.filter((line) => BEGIN_RE.test(line.text));
78
+ const ends = lines.filter((line) => END_RE.test(line.text));
79
+ if (begins.length === 0 && ends.length === 0) return { kind: "none" };
80
+ if (begins.length === 0 || ends.length === 0) {
81
+ return {
82
+ kind: "malformed",
83
+ reason: begins.length === 0 ? "end marker without begin marker" : "begin marker without end marker",
84
+ };
85
+ }
86
+ if (begins.length > 1 || ends.length > 1) {
87
+ return { kind: "malformed", reason: "more than one workflow marker pair" };
88
+ }
89
+ const begin = begins[0];
90
+ const end = ends[0];
91
+ if (end.start < begin.start) {
92
+ return { kind: "malformed", reason: "end marker appears before the begin marker" };
93
+ }
94
+ return { kind: "found", begin, end };
95
+ }
96
+
97
+ /**
98
+ * Replace the block between a valid marker pair, or insert it. Any malformed
99
+ * marker layout returns the input untouched so prose can never be damaged.
100
+ */
101
+ export function applyWorkflowBlock(
102
+ text: string,
103
+ block: string,
104
+ ): { text: string; status: Exclude<BlockStatus, "missing-agents"> } {
105
+ const located = locateWorkflowBlock(text);
106
+ if (located.kind === "malformed") return { text, status: "malformed" };
107
+ if (located.kind === "found") {
108
+ const suffix = text.slice(located.end.end);
109
+ // Keep the final newline when the block is the last content: dropping it
110
+ // makes every second refresh look like an update.
111
+ const next = `${text.slice(0, located.begin.start)}${block.trimEnd()}${
112
+ suffix.length === 0 && text.endsWith("\n") ? "\n" : suffix
113
+ }`;
114
+ return { text: next, status: next === text ? "current" : "updated" };
115
+ }
116
+
117
+ const appendix = linesOutsideFences(text).find((line) =>
118
+ /^##[ \t]+(?:附录|appendix)(?:[ \t]|$)/i.test(line.text),
119
+ );
120
+ // A project may have written its own workflow section. Do not append a
121
+ // second one: report it and let the operator add markers or remove it.
122
+ const handWritten = linesOutsideFences(text).some((line) =>
123
+ /^##[ \t]+Ask workflow\b/i.test(line.text),
124
+ );
125
+ if (handWritten) return { text, status: "hand-written" };
126
+ if (appendix) {
127
+ return {
128
+ text: `${text.slice(0, appendix.start)}${block.trimEnd()}\n\n${text.slice(appendix.start)}`,
129
+ status: "inserted",
130
+ };
131
+ }
132
+ if (text.trim() === "") return { text: `${block.trimEnd()}\n`, status: "inserted" };
133
+ return { text: `${text.trimEnd()}\n\n${block.trimEnd()}\n`, status: "inserted" };
134
+ }
135
+
136
+ /** Inspect a present AGENTS.md without changing it. */
137
+ export function inspectWorkflowBlock(
138
+ text: string,
139
+ expected: string,
140
+ ): { status: Exclude<WorkflowStatus, "missing-agents">; reason?: string } {
141
+ const located = locateWorkflowBlock(text);
142
+ if (located.kind === "malformed") return { status: "malformed", reason: located.reason };
143
+ if (located.kind === "found") {
144
+ const actual = text.slice(located.begin.start, located.end.end).trimEnd();
145
+ return { status: actual === expected.trimEnd() ? "current" : "stale" };
146
+ }
147
+ const handWritten = linesOutsideFences(text).some((line) =>
148
+ /^##[ \t]+Ask workflow\b/i.test(line.text),
149
+ );
150
+ if (handWritten) {
151
+ return {
152
+ status: "hand-written",
153
+ reason: "a hand-written 'Ask workflow' section exists without the managed markers",
154
+ };
155
+ }
156
+ return { status: "missing" };
157
+ }
158
+
159
+ export { WORKFLOW_BLOCK_BEGIN, WORKFLOW_BLOCK_END };
@@ -406,7 +406,7 @@ export function registerPermission(
406
406
  });
407
407
 
408
408
  // ── Control surface for other features ─────────────────────────────────
409
- // `/ask-plan` needs to switch the checks on for the planning phase and put
409
+ // `/ask-spec` needs to switch the checks on for the spec-review phase and put
410
410
  // them back afterwards. It gets a handle, not a copy of the state: the
411
411
  // session's own `/ask-perm` command stays authoritative, so an operator who
412
412
  // changes the mode mid-plan wins over whatever we restore later.
@@ -73,13 +73,26 @@ export const TEARDOWN_MARKERS = ["\x1b[?2004l", "\x1b[?1049l"] as const;
73
73
  export const SHUTDOWN_EVENT_MARKER = "session_shutdown";
74
74
 
75
75
  /**
76
- * Terminal restore written before a forced exit that never reached
77
- * `ui.stop()`: leave the alternate screen, disable bracketed paste, show the
78
- * cursor, reset attributes. Harmless when the TUI already restored (the
79
- * marker-armed path never writes it) and the only thing that makes the shell
80
- * usable when it did not.
76
+ * Terminal restore written before every forced exit (writeSync(1, …), which
77
+ * bypasses our own stdout wrapper and cannot re-arm the guard).
78
+ *
79
+ * The shutdown-event path needs it because nothing restored the terminal:
80
+ * without it the prompt comes back on the alternate screen, with bracketed
81
+ * paste on and the cursor hidden. The marker path gets it too (since
82
+ * 2026-11-13): `ui.stop()` can also hang between its two sequences —
83
+ * `?2004l` written, `?1049l` never — and an already-restored terminal
84
+ * simply ignores the extra sequences. Idempotent, unlike a frozen screen.
81
85
  */
82
86
  export const TERMINAL_RESTORE = "\x1b[?2004l\x1b[?1049l\x1b[?25h\x1b[0m\r\n";
83
87
 
88
+ /**
89
+ * Grace period for the kill fallbacks that run AFTER the report is on disk
90
+ * and "forcing exit" has been printed: `process.exit(0)` first, then, in
91
+ * layers, a same-loop `setTimeout` SIGKILL and the independent-thread
92
+ * SIGKILL from killer.ts (see there for why the timer alone is not enough:
93
+ * the main thread can deadlock inside `process.exit`, where no timer runs).
94
+ */
95
+ export const HARD_KILL_DELAY_MS = 500;
96
+
84
97
  /** Sequences that mean a TUI is starting (mode switch or suspend/resume). */
85
98
  export const RESTART_MARKERS = ["\x1b[?2004h", "\x1b[?1049h"] as const;
@@ -36,14 +36,15 @@ import { join } from "node:path";
36
36
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
37
37
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
38
38
  import {
39
+ HARD_KILL_DELAY_MS,
39
40
  MAX_TIMEOUT_MS,
40
41
  MIN_TIMEOUT_MS,
41
42
  QUIT_GUARD_FILE,
42
43
  QUIT_GUARD_REPORT_DIR,
43
- SHUTDOWN_EVENT_MARKER,
44
44
  TERMINAL_RESTORE,
45
45
  } from "./constants.js";
46
46
  import { QuitGuard, type GuardFireInfo } from "./guard.js";
47
+ import { armThreadHardKill, armThreadWatchdog, type ThreadWatchdog } from "./killer.js";
47
48
  import {
48
49
  collectHangReport,
49
50
  formatHangReportSummary,
@@ -83,17 +84,19 @@ function storeSharedState(state: QuitGuardState): void {
83
84
  }
84
85
 
85
86
  function fire(state: QuitGuardState, info: GuardFireInfo): void {
86
- // Armed by `session_shutdown` (signal-triggered quit, or a shutdown that
87
- // hung before `ui.stop()`): nothing restored the terminal, so do it here
88
- // before exiting or the prompt comes back on the alternate screen, with
89
- // bracketed paste on and the cursor hidden. `writeSync(1, …)` bypasses our
90
- // own stdout wrapper, so these sequences cannot re-arm the guard.
91
- if (info.marker === SHUTDOWN_EVENT_MARKER) {
92
- try {
93
- writeSync(1, TERMINAL_RESTORE);
94
- } catch {
95
- // Dead terminal: the report and the exit still happen.
96
- }
87
+ // Restore the terminal on every path, not just the shutdown-event one.
88
+ // When the guard was armed by `session_shutdown` nothing restored the
89
+ // terminal at all: without this write the prompt comes back on the
90
+ // alternate screen, with bracketed paste on and the cursor hidden. When it
91
+ // was armed by a teardown marker the TUI usually already restored — but
92
+ // `ui.stop()` can also hang between its two sequences (`?2004l` written,
93
+ // `?1049l` never), and a terminal that is already healthy ignores the
94
+ // extra sequences. `writeSync(1, …)` bypasses our own stdout wrapper, so
95
+ // these sequences cannot re-arm the guard.
96
+ try {
97
+ writeSync(1, TERMINAL_RESTORE);
98
+ } catch {
99
+ // Dead terminal: the report and the exit still happen.
97
100
  }
98
101
  const timeoutMs = state.guard.getTimeoutMs();
99
102
  const elapsedMs = Math.round(info.elapsedMs);
@@ -125,18 +128,29 @@ function fire(state: QuitGuardState, info: GuardFireInfo): void {
125
128
  // The terminal is gone or blocked; the report (if any) still exists.
126
129
  }
127
130
  // `process.exit(0)` is normally immediate, but every step of it is host
128
- // code: an `exit` listener (or a patched `reallyExit`) can turn it into a
129
- // no-op or throw — one such case was observed while testing this feature.
130
- // The SIGKILL fallback guarantees the prompt comes back; the report is
131
- // already on disk and session entries are appended as they happen, so
132
- // nothing recoverable is lost.
133
- const hardKill = setTimeout(() => process.kill(process.pid, "SIGKILL"), 500);
131
+ // code: an `exit` listener (pi-tui's own `exitRestoreHandler`, the
132
+ // graceful-fs patches bundled with the host, stdio flushing) can deadlock
133
+ // it. Observed for real on 2026-11-13: the process sat in `futex_wait` for
134
+ // 18 minutes after this line, its pty already deleted, because the
135
+ // `setTimeout` SIGKILL below cannot fire while the main thread is blocked
136
+ // *inside* `process.exit`. Three layers now guarantee the prompt comes
137
+ // back: (1) `process.exit(0)`; (2) a same-loop SIGKILL timer for hangs
138
+ // where the loop still turns; (3) the independent-thread SIGKILL from
139
+ // killer.ts, which works even when the main thread never unblocks. The
140
+ // report is already on disk and session entries are appended as they
141
+ // happen, so nothing recoverable is lost.
142
+ const hardKill = setTimeout(
143
+ () => process.kill(process.pid, "SIGKILL"),
144
+ HARD_KILL_DELAY_MS,
145
+ );
146
+ const cancelThreadKill = armThreadHardKill(HARD_KILL_DELAY_MS);
134
147
  try {
135
148
  process.exit(0);
136
149
  } catch {
137
150
  // Fall through to the hard kill.
138
151
  }
139
152
  clearTimeout(hardKill);
153
+ cancelThreadKill();
140
154
  process.kill(process.pid, "SIGKILL");
141
155
  }
142
156
 
@@ -204,24 +218,56 @@ function buildState(agentDir: string): QuitGuardState {
204
218
  // arm/disarm/fire. It exists because the failure being debugged happens
205
219
  // after the TUI is gone: there is no other channel left to observe.
206
220
  const debugPath = process.env.PI_QUIT_GUARD_DEBUG;
221
+ // Arm-time layer of the independent-thread kill: a main thread that
222
+ // deadlocks synchronously (observed inside `process.exit` right after a
223
+ // fast dispose) never runs the fire timer, so the guard needs a watcher
224
+ // that does not live on the main event loop. The worker waits out the
225
+ // deadline, then samples this heartbeat: a beating loop means the fire
226
+ // timer owns the outcome (with its raw-mode probe and full report); a
227
+ // stopped loop can only be ended by the worker. Disarmed/fired guards
228
+ // cancel the worker — including every restart (mode switch, Ctrl+Z
229
+ // resume, /reload) so a returning TUI is never killed.
230
+ let watchdog: ThreadWatchdog | undefined;
231
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
232
+ const stopWatchdog = (): void => {
233
+ if (heartbeatTimer !== undefined) {
234
+ clearInterval(heartbeatTimer);
235
+ heartbeatTimer = undefined;
236
+ }
237
+ watchdog?.cancel();
238
+ watchdog = undefined;
239
+ };
207
240
  const guard = new QuitGuard(config.timeoutMs, {
208
241
  onFire: (info) => {
209
242
  if (state) fire(state, info);
210
243
  },
211
244
  // Raw mode is the independent "TUI still running" signal; see guard.ts.
212
245
  isTuiActive: () => process.stdin.isRaw === true,
213
- onEvent: debugPath
214
- ? (event, detail) => {
215
- try {
216
- appendFileSync(
217
- debugPath,
218
- `${new Date().toISOString()} ${event} ${detail}\n`,
219
- );
220
- } catch {
221
- // Debug output must never affect the guard.
222
- }
246
+ onEvent: (event, detail) => {
247
+ if (event === "arm") {
248
+ watchdog = armThreadWatchdog({
249
+ deadlineMs: guard.getTimeoutMs(),
250
+ restore: TERMINAL_RESTORE,
251
+ reportDir: join(agentDir, QUIT_GUARD_REPORT_DIR),
252
+ debugPath,
253
+ });
254
+ watchdog.heartbeat();
255
+ heartbeatTimer = setInterval(() => watchdog?.heartbeat(), 1_000);
256
+ heartbeatTimer?.unref?.();
257
+ } else if (event === "disarm" || event === "fire") {
258
+ stopWatchdog();
259
+ }
260
+ if (debugPath) {
261
+ try {
262
+ appendFileSync(
263
+ debugPath,
264
+ `${new Date().toISOString()} ${event} ${detail}\n`,
265
+ );
266
+ } catch {
267
+ // Debug output must never affect the guard.
223
268
  }
224
- : undefined,
269
+ }
270
+ },
225
271
  });
226
272
  state = {
227
273
  store,
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Unit tests for the independent-thread hard kill (killer.ts).
3
+ *
4
+ * What these tests deliberately do NOT cover: the worker actually SIGKILLing
5
+ * the process. A test that kills its own process cannot report results; the
6
+ * kill path is verified in real-pi smoke runs (an extension whose
7
+ * `process.on("exit")` listener deadlocks, /quit, and the pane returning to
8
+ * the shell — see .agents/implementations/2026-11-13). Here we pin the
9
+ * safety property instead: an armed kill that gets cancelled, or whose
10
+ * process simply keeps living, must never fire on its own or break the
11
+ * caller.
12
+ */
13
+ import { describe, expect, it } from "vitest";
14
+ import { armThreadHardKill, armThreadWatchdog } from "./killer.js";
15
+
16
+ function sleep(ms: number): Promise<void> {
17
+ return new Promise((resolve) => {
18
+ setTimeout(resolve, ms);
19
+ });
20
+ }
21
+
22
+ describe("armThreadWatchdog", () => {
23
+ it("never kills while the main loop keeps beating (deadline passes, loop alive)", async () => {
24
+ // A tiny deadline so the worker's sampling phases run within the test;
25
+ // the heartbeat below proves a live loop, which the worker must step
26
+ // aside for — the main-loop fire timer owns the outcome there.
27
+ const watchdog = armThreadWatchdog({
28
+ deadlineMs: 100,
29
+ headStartMs: 50,
30
+ sampleMs: 100,
31
+ restore: "",
32
+ reportDir: undefined,
33
+ });
34
+ const beat = setInterval(() => watchdog.heartbeat(), 50);
35
+ // Long past deadline + head start + sampling: the runner surviving is
36
+ // the assertion.
37
+ await sleep(700);
38
+ clearInterval(beat);
39
+ watchdog.cancel();
40
+ expect(process.pid).toBeGreaterThan(0);
41
+ });
42
+
43
+ it("is inert once cancelled, even with the deadline long past", async () => {
44
+ const watchdog = armThreadWatchdog({
45
+ deadlineMs: 50,
46
+ headStartMs: 25,
47
+ sampleMs: 50,
48
+ restore: "",
49
+ reportDir: undefined,
50
+ });
51
+ // No heartbeat at all: only the cancellation keeps this process alive,
52
+ // which is exactly the disarm contract (TUI restarted, /reload, ...).
53
+ watchdog.cancel();
54
+ watchdog.cancel();
55
+ await sleep(400);
56
+ expect(process.pid).toBeGreaterThan(0);
57
+ });
58
+ });
59
+
60
+ describe("armThreadHardKill", () => {
61
+ it("does not kill the process before its deadline passes", async () => {
62
+ const cancel = armThreadHardKill(60_000);
63
+ // Long enough for the worker thread to spin up, wait, and be bored;
64
+ // the test runner surviving this line IS the assertion.
65
+ await sleep(300);
66
+ expect(process.pid).toBeGreaterThan(0);
67
+ cancel();
68
+ });
69
+
70
+ it("tolerates being cancelled twice", async () => {
71
+ const cancel = armThreadHardKill(60_000);
72
+ cancel();
73
+ cancel();
74
+ await sleep(100);
75
+ expect(process.pid).toBeGreaterThan(0);
76
+ });
77
+ });
@@ -0,0 +1,215 @@
1
+ /**
2
+ * quit-guard feature — independent-thread hard kill.
3
+ *
4
+ * Why this exists (2026-11-13, real hang, pid 398960): the guard fired,
5
+ * wrote its report, printed "forcing exit" and called `process.exit(0)` —
6
+ * and the process stayed alive for 18+ minutes (`futex_wait`, PPID=1, its
7
+ * pty already deleted by the user closing the terminal window). The exit
8
+ * path runs host code (`process.on("exit")` listeners, graceful-fs patches,
9
+ * stdio flush) and can deadlock synchronously. Any fallback scheduled on
10
+ * the event loop (`setTimeout`) is dead the moment the main thread blocks:
11
+ * a timer cannot fire inside a dead loop.
12
+ *
13
+ * Two watchdogs, both on `worker_threads` (an independent OS thread that
14
+ * keeps running while the main thread is blocked):
15
+ *
16
+ * 1. `armThreadHardKill(delayMs)` — the last-resort layer of fire(): after
17
+ * the report is on disk and "forcing exit" has been printed, kill the
18
+ * process `delayMs` later no matter what `process.exit(0)` did.
19
+ *
20
+ * 2. `armThreadWatchdog({ deadlineMs, ... })` — armed when the guard arms
21
+ * (teardown marker / shutdown event), covering the blind spot the
22
+ * main-loop timer has: a main thread that deadlocks BEFORE the fire
23
+ * deadline (e.g. synchronously inside `process.exit` right after a fast
24
+ * dispose) never runs the fire timer at all. The main loop must prove
25
+ * liveness with a heartbeat (a 1 Hz counter in shared memory). The
26
+ * worker waits out `deadlineMs` (+ a head start for the main-loop fire
27
+ * timer, which handles the common hangs with full context: raw-mode
28
+ * probe, report, restore), then samples the heartbeat twice. Still
29
+ * beating → the event loop is alive → step aside (the fire timer owns
30
+ * the outcome, including its stray-marker protection). Stopped → the
31
+ * main loop can never fire → the worker restores the terminal, writes a
32
+ * minimal report and SIGKILLs. This kills exactly-and-only a main
33
+ * thread that is alive as a process but dead as an event loop.
34
+ *
35
+ * Failure policy: if a Worker cannot even be constructed, degrade to a
36
+ * no-op — the fire path still has its `setTimeout` fallback, and a killer
37
+ * that breaks the arm/fire sequence is worse than no extra killer.
38
+ */
39
+ import { Worker } from "node:worker_threads";
40
+
41
+ /**
42
+ * Start a watchdog thread that SIGKILLs this process after `delayMs`.
43
+ *
44
+ * Returns a `cancel()` that terminates the worker. Cancelling only matters
45
+ * on the "process.exit threw synchronously" path, where fire() recovers and
46
+ * performs its own synchronous kill; on every healthy path the process dies
47
+ * with the main thread and the worker is never heard from again.
48
+ */
49
+ export function armThreadHardKill(delayMs: number): () => void {
50
+ let worker: Worker;
51
+ try {
52
+ worker = new Worker(
53
+ `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${Math.max(
54
+ 0,
55
+ delayMs,
56
+ )});
57
+ process.kill(process.pid, "SIGKILL");`,
58
+ { eval: true },
59
+ );
60
+ } catch {
61
+ // Could not start the watchdog thread (resource exhaustion, ...):
62
+ // degrade to the setTimeout fallback instead of breaking the fire path.
63
+ return () => {};
64
+ }
65
+ // The worker must never keep the process alive on its own: its only job
66
+ // is to end it.
67
+ worker.unref();
68
+ return () => {
69
+ try {
70
+ void worker.terminate();
71
+ } catch {
72
+ // terminate() returns a promise that can only reject if the worker
73
+ // is already gone; either way this process is about to exit.
74
+ }
75
+ };
76
+ }
77
+
78
+ /** Handle returned by {@link armThreadWatchdog}. */
79
+ export interface ThreadWatchdog {
80
+ /** Record one main-loop heartbeat tick (idempotent per tick). */
81
+ heartbeat(): void;
82
+ /** Disarm: the main loop owns the outcome from here on. */
83
+ cancel(): void;
84
+ }
85
+
86
+ export interface ThreadWatchdogOptions {
87
+ /** Guard deadline (ms) the main-loop fire timer is armed with. */
88
+ readonly deadlineMs: number;
89
+ /**
90
+ * Grace after the deadline before the first heartbeat sample (ms), so
91
+ * the main-loop fire timer — which handles hangs with full context —
92
+ * always gets the first shot.
93
+ */
94
+ readonly headStartMs?: number;
95
+ /** Gap between the two heartbeat samples (ms). Default 1500. */
96
+ readonly sampleMs?: number;
97
+ /** Terminal restore written before the watchdog's kill. */
98
+ readonly restore?: string;
99
+ /** Directory for the minimal deadlock report; omit to skip the report. */
100
+ readonly reportDir?: string;
101
+ /** PI_QUIT_GUARD_DEBUG path, appended to from the worker on a kill. */
102
+ readonly debugPath?: string;
103
+ }
104
+
105
+ /**
106
+ * Cells of the shared heartbeat buffer: [0] = heartbeat ticks (written by
107
+ * the main loop, never waited on), [1] = signal (0 = armed, 1 = cancelled;
108
+ * the only cell the worker waits on — Atomics.wait's third argument is the
109
+ * EXPECTED value, so waiting on the heartbeat cell, which changes on every
110
+ * tick, would return "not-equal" immediately and fake a deadlock).
111
+ */
112
+ const CELL_HEARTBEAT = 0;
113
+ const CELL_SIGNAL = 1;
114
+
115
+ const WATCHDOG_SOURCE = `
116
+ (function () {
117
+ const { workerData } = require("node:worker_threads");
118
+ const { writeSync, writeFileSync, mkdirSync, appendFileSync } = require("node:fs");
119
+ const cells = workerData.cells;
120
+ const cancelFlag = () => Atomics.load(cells, ${CELL_SIGNAL}) === 1;
121
+ // Phase 1: wait out the deadline plus the main-loop timer's head start.
122
+ Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.deadlineMs + workerData.headStartMs);
123
+ if (cancelFlag()) return;
124
+ // Phase 2: sample the heartbeat twice. A loop that is merely slow still
125
+ // ticks; a loop that is blocked cannot.
126
+ const first = Atomics.load(cells, ${CELL_HEARTBEAT});
127
+ Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.sampleMs);
128
+ if (cancelFlag()) return;
129
+ if (Atomics.load(cells, ${CELL_HEARTBEAT}) !== first) return;
130
+ // Phase 3: deadlocked. Restore the terminal, leave a minimal trace, kill.
131
+ try { writeSync(1, workerData.restore); } catch {}
132
+ try {
133
+ mkdirSync(workerData.reportDir, { recursive: true });
134
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
135
+ writeFileSync(
136
+ workerData.reportDir + "/quit-hang-" + ts + "-" + process.pid + "-thread.json",
137
+ JSON.stringify(
138
+ {
139
+ version: 1,
140
+ kind: "quit-guard",
141
+ source: "thread-watchdog",
142
+ timestamp: new Date().toISOString(),
143
+ pid: process.pid,
144
+ timeoutMs: workerData.deadlineMs,
145
+ elapsedMs: workerData.deadlineMs + workerData.headStartMs + workerData.sampleMs,
146
+ marker: "heartbeat-stopped",
147
+ note: "main event loop stopped beating during shutdown; killed from the watchdog thread (main-loop fire timer could never run)",
148
+ },
149
+ null,
150
+ "\\t",
151
+ ) + "\\n",
152
+ );
153
+ } catch {}
154
+ try {
155
+ writeSync(2, "[pi-toolkits/quit-guard] main loop stopped during shutdown (no heartbeat for " + workerData.sampleMs + "ms after the " + (workerData.deadlineMs + workerData.headStartMs) + "ms deadline); killing from the watchdog thread.\\n");
156
+ } catch {}
157
+ try {
158
+ if (workerData.debugPath) appendFileSync(workerData.debugPath, new Date().toISOString() + " thread-kill heartbeat-stopped deadline=" + workerData.deadlineMs + "\\n");
159
+ } catch {}
160
+ process.kill(process.pid, "SIGKILL");
161
+ })();
162
+ `;
163
+
164
+ /**
165
+ * Arm the arm-time watchdog. See the module comment for the protocol.
166
+ *
167
+ * The returned handle is deliberately passive: an owner that forgets to
168
+ * cancel merely keeps one unref'd worker alive for the rest of the process
169
+ * — which the deadline then ends (heartbeat still beating → the worker
170
+ * steps aside; heartbeat stopped → the process was dead anyway).
171
+ */
172
+ export function armThreadWatchdog(
173
+ options: ThreadWatchdogOptions,
174
+ ): ThreadWatchdog {
175
+ const cells = new Int32Array(new SharedArrayBuffer(8));
176
+ let worker: Worker;
177
+ try {
178
+ worker = new Worker(WATCHDOG_SOURCE, {
179
+ eval: true,
180
+ workerData: {
181
+ cells,
182
+ deadlineMs: Math.max(0, options.deadlineMs),
183
+ headStartMs: Math.max(0, options.headStartMs ?? 500),
184
+ sampleMs: Math.max(0, options.sampleMs ?? 1_500),
185
+ restore: options.restore ?? "",
186
+ reportDir: options.reportDir ?? "",
187
+ debugPath: options.debugPath ?? "",
188
+ },
189
+ });
190
+ } catch {
191
+ // No watchdog thread: the guard degrades to its main-loop timer,
192
+ // exactly the behavior that existed before this layer.
193
+ return { heartbeat: () => {}, cancel: () => {} };
194
+ }
195
+ worker.unref();
196
+ let beats = 0;
197
+ return {
198
+ heartbeat: () => {
199
+ Atomics.store(cells, CELL_HEARTBEAT, ++beats);
200
+ },
201
+ cancel: () => {
202
+ // Flag first so a worker whose terminate() has not landed yet
203
+ // stops at its next check; notify so it wakes now (the signal cell
204
+ // is the only one the worker waits on); terminate so the thread
205
+ // goes away even mid-phase-1.
206
+ Atomics.store(cells, CELL_SIGNAL, 1);
207
+ Atomics.notify(cells, CELL_SIGNAL);
208
+ try {
209
+ void worker.terminate();
210
+ } catch {
211
+ // Already gone.
212
+ }
213
+ },
214
+ };
215
+ }