@andares/pi-toolkits 0.14.0 → 1.0.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.
- package/CHANGELOG.md +13 -0
- package/README.md +87 -21
- package/README.zh-CN.md +52 -17
- package/package.json +8 -2
- package/src/features/ask/index.test.ts +15 -0
- package/src/features/ask/index.ts +17 -0
- package/src/features/init/audit.test.ts +19 -2
- package/src/features/init/audit.ts +117 -15
- package/src/features/init/index.test.ts +123 -1
- package/src/features/init/index.ts +156 -46
- package/src/features/init/parity.test.ts +176 -0
- package/src/features/init/parity.ts +229 -0
- package/src/features/init/plan.ts +25 -3
- package/src/features/init/refresh.test.ts +88 -1
- package/src/features/init/refresh.ts +43 -64
- package/src/features/init/spec.ts +11 -0
- package/src/features/init/templates/memory-readme.md +9 -2
- package/src/features/init/test-helpers.ts +1 -0
- package/src/features/init/workflow.ts +159 -0
- package/src/features/plan/index.test.ts +51 -0
- package/src/features/plan/index.ts +24 -4
- package/src/features/quit-guard/constants.ts +18 -5
- package/src/features/quit-guard/index.ts +75 -29
- package/src/features/quit-guard/killer.test.ts +77 -0
- package/src/features/quit-guard/killer.ts +215 -0
- package/src/features/review/index.ts +14 -0
- package/src/features/review/review.test.ts +34 -2
- package/src/features/uat/index.test.ts +15 -0
- package/src/features/uat/index.ts +10 -7
- package/src/features/uat/record-tool.ts +3 -2
- package/src/features/uat/state.ts +13 -5
- package/src/lib/phases.ts +37 -0
|
@@ -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
|
-
//
|
|
87
|
-
//
|
|
88
|
-
//
|
|
89
|
-
// bracketed paste on and the cursor hidden.
|
|
90
|
-
//
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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 (
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
|
|
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:
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
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
|
-
|
|
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
|
+
}
|
|
@@ -32,6 +32,8 @@ import type {
|
|
|
32
32
|
SessionStartEvent,
|
|
33
33
|
Theme,
|
|
34
34
|
} from "@earendil-works/pi-coding-agent";
|
|
35
|
+
import { getAskControl } from "../../lib/ask-control.js";
|
|
36
|
+
import { PLAN_PHASE_TOOL } from "../../lib/phases.js";
|
|
35
37
|
import {
|
|
36
38
|
modelKey,
|
|
37
39
|
resolveConfiguredModel,
|
|
@@ -138,6 +140,13 @@ export function createReviewRunner(
|
|
|
138
140
|
);
|
|
139
141
|
return;
|
|
140
142
|
}
|
|
143
|
+
if (pi.getActiveTools?.().includes(PLAN_PHASE_TOOL)) {
|
|
144
|
+
ctx.ui.notify(
|
|
145
|
+
`${REVIEW_COMMAND}: ask-plan is active — approve or /ask-plan off first; a review needs write access.`,
|
|
146
|
+
"warning",
|
|
147
|
+
);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
141
150
|
running = true;
|
|
142
151
|
try {
|
|
143
152
|
const store = getReviewStore();
|
|
@@ -172,6 +181,11 @@ export function createReviewRunner(
|
|
|
172
181
|
`${REVIEW_COMMAND}: switched to the review model "${model.name}" for this review (check + fix); the session stays on it afterwards.`,
|
|
173
182
|
"info",
|
|
174
183
|
);
|
|
184
|
+
// A review promises check AND fix, so it needs the full tool set. Ask
|
|
185
|
+
// mode's read-only surface is restored on every before_agent_start; exit
|
|
186
|
+
// it here rather than silently running a review that cannot edit.
|
|
187
|
+
const ask = getAskControl();
|
|
188
|
+
if (ask?.isActive()) ask.exit(ctx);
|
|
175
189
|
pi.sendUserMessage(REVIEW_PROMPT);
|
|
176
190
|
} finally {
|
|
177
191
|
running = false;
|
|
@@ -45,6 +45,7 @@ import {
|
|
|
45
45
|
type AvailableModel,
|
|
46
46
|
} from "../../lib/model-config.js";
|
|
47
47
|
import { REVIEW_PROMPT } from "./prompt.js";
|
|
48
|
+
import { setAskControl } from "../../lib/ask-control.js";
|
|
48
49
|
import {
|
|
49
50
|
ReviewStore,
|
|
50
51
|
getReviewStore,
|
|
@@ -122,10 +123,14 @@ function fakeCtx(
|
|
|
122
123
|
return { ctx, notify, custom, select };
|
|
123
124
|
}
|
|
124
125
|
|
|
125
|
-
function fakePi(switched = true) {
|
|
126
|
+
function fakePi(switched = true, tools: string[] = []) {
|
|
126
127
|
const setModel = vi.fn(async () => switched);
|
|
127
128
|
const sendUserMessage = vi.fn();
|
|
128
|
-
const pi = {
|
|
129
|
+
const pi = {
|
|
130
|
+
setModel,
|
|
131
|
+
sendUserMessage,
|
|
132
|
+
getActiveTools: () => tools,
|
|
133
|
+
} as unknown as ExtensionAPI;
|
|
129
134
|
return { pi, setModel, sendUserMessage };
|
|
130
135
|
}
|
|
131
136
|
|
|
@@ -410,6 +415,33 @@ describe("createReviewRunner", () => {
|
|
|
410
415
|
expect(getReviewStore().getModel()).toBeUndefined();
|
|
411
416
|
});
|
|
412
417
|
|
|
418
|
+
it("refuses to review while a plan is under review", async () => {
|
|
419
|
+
getReviewStore().setModel("anthropic/claude-sonnet-4");
|
|
420
|
+
const { pi, sendUserMessage } = fakePi(true, ["read", "plan_submit"]);
|
|
421
|
+
const { ctx, notify, custom } = fakeCtx({ customResult: MODELS[0] });
|
|
422
|
+
await createReviewRunner(pi)(ctx);
|
|
423
|
+
expect(custom).not.toHaveBeenCalled();
|
|
424
|
+
expect(sendUserMessage).not.toHaveBeenCalled();
|
|
425
|
+
expect(notify).toHaveBeenCalledWith(
|
|
426
|
+
expect.stringContaining("ask-plan"),
|
|
427
|
+
"warning",
|
|
428
|
+
);
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
it("exits read-only ask mode before a check-and-fix review", async () => {
|
|
432
|
+
const exit = vi.fn();
|
|
433
|
+
setAskControl({ isActive: () => true, exit });
|
|
434
|
+
try {
|
|
435
|
+
const { pi, sendUserMessage } = fakePi(true, ["read", "write"]);
|
|
436
|
+
const { ctx } = fakeCtx({ customResult: MODELS[0] });
|
|
437
|
+
await createReviewRunner(pi)(ctx);
|
|
438
|
+
expect(exit).toHaveBeenCalledWith(ctx);
|
|
439
|
+
expect(sendUserMessage).toHaveBeenCalledWith(REVIEW_PROMPT);
|
|
440
|
+
} finally {
|
|
441
|
+
setAskControl(undefined);
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
|
|
413
445
|
it("reports and aborts when switching to the review model fails", async () => {
|
|
414
446
|
getReviewStore().setModel("anthropic/claude-sonnet-4");
|
|
415
447
|
const { pi, setModel, sendUserMessage } = fakePi(false); // setModel → false
|
|
@@ -31,6 +31,10 @@ beforeEach(() => {
|
|
|
31
31
|
sessionId = `s-${Math.random().toString(36).slice(2, 8)}`;
|
|
32
32
|
mkdirSync(join(root, ".agents/framework"), { recursive: true });
|
|
33
33
|
writeFileSync(join(root, ".agents/framework/state.toml"), 'version = 1\ntool = "test"\n', "utf8");
|
|
34
|
+
writeFileSync(join(root, "AGENTS.md"), "# demo\n", "utf8");
|
|
35
|
+
mkdirSync(join(root, ".agents/memory"), { recursive: true });
|
|
36
|
+
writeFileSync(join(root, ".agents/memory/README.md"), "# contract\n", "utf8");
|
|
37
|
+
mkdirSync(join(root, ".agents/implementations"), { recursive: true });
|
|
34
38
|
});
|
|
35
39
|
|
|
36
40
|
afterEach(() => {
|
|
@@ -168,6 +172,17 @@ describe("ask-uat command", () => {
|
|
|
168
172
|
expect(h.openBrowser).not.toHaveBeenCalled();
|
|
169
173
|
});
|
|
170
174
|
|
|
175
|
+
it("refuses a half-installed framework and names the missing piece", async () => {
|
|
176
|
+
rmSync(join(root, ".agents/memory/README.md"));
|
|
177
|
+
const h = harness();
|
|
178
|
+
await h.commands.get(UAT_COMMAND)!.handler("", h.ctx);
|
|
179
|
+
expect(h.notify).toHaveBeenCalledWith(
|
|
180
|
+
expect.stringContaining(".agents/memory/README.md"),
|
|
181
|
+
"error",
|
|
182
|
+
);
|
|
183
|
+
expect(h.openBrowser).not.toHaveBeenCalled();
|
|
184
|
+
});
|
|
185
|
+
|
|
171
186
|
it("opens the page and dispatches clustering only when records are pending", async () => {
|
|
172
187
|
createRecord(root, { title: "alpha change", body: "body", now: new Date(2026, 10, 12, 9, 0) });
|
|
173
188
|
const h = harness();
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
21
21
|
import { getAskControl } from "../../lib/ask-control.js";
|
|
22
|
+
import { PLAN_PHASE_TOOL } from "../../lib/phases.js";
|
|
22
23
|
import { openInBrowser } from "../../lib/opener.js";
|
|
23
24
|
import {
|
|
24
25
|
MAX_CANDIDATES_PER_RUN,
|
|
@@ -26,6 +27,7 @@ import {
|
|
|
26
27
|
RECORD_CHANGE_TOOL,
|
|
27
28
|
UAT_COMMAND,
|
|
28
29
|
UAT_IDLE_CLOSE_MS,
|
|
30
|
+
UAT_ITEM_TOOL,
|
|
29
31
|
} from "./constants.js";
|
|
30
32
|
import { registerUatItemTool } from "./item-tool.js";
|
|
31
33
|
import { deriveState, ledgerPath, readEvents, appendEvent, newEventId } from "./ledger.js";
|
|
@@ -33,7 +35,7 @@ import { listRecords } from "./records.js";
|
|
|
33
35
|
import { buildUatKickoff, describeCounts, UAT_MODE_BANNER } from "./prompt.js";
|
|
34
36
|
import { registerRecordTool } from "./record-tool.js";
|
|
35
37
|
import { startUatServer, type UatServerHandle } from "./server.js";
|
|
36
|
-
import { frameworkInstalled, loadSnapshot, resolveProjectRoot } from "./state.js";
|
|
38
|
+
import { frameworkInstalled, frameworkMissing, loadSnapshot, resolveProjectRoot } from "./state.js";
|
|
37
39
|
|
|
38
40
|
export interface UatOptions {
|
|
39
41
|
/** Opening the browser is injectable so tests never spawn one. */
|
|
@@ -75,7 +77,7 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
75
77
|
// `plan_submit` is the owning feature's phase marker. Detecting the active
|
|
76
78
|
// tool avoids a second global control registry while still keeping the two
|
|
77
79
|
// phases' write surfaces disjoint.
|
|
78
|
-
const planningTool =
|
|
80
|
+
const planningTool = PLAN_PHASE_TOOL;
|
|
79
81
|
|
|
80
82
|
function recordChangeAllowed(tools: readonly string[] = pi.getActiveTools()): boolean {
|
|
81
83
|
return !getAskControl()?.isActive() && !tools.includes(planningTool);
|
|
@@ -129,7 +131,7 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
129
131
|
batch = undefined;
|
|
130
132
|
clearIdle();
|
|
131
133
|
closeServer();
|
|
132
|
-
pi.setActiveTools(toolsWith([], [
|
|
134
|
+
pi.setActiveTools(toolsWith([], [UAT_ITEM_TOOL]));
|
|
133
135
|
ctx.ui.notify(`ask-uat: ${reason}`, "info");
|
|
134
136
|
}
|
|
135
137
|
|
|
@@ -186,8 +188,9 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
186
188
|
async function start(ctx: ExtensionContext): Promise<void> {
|
|
187
189
|
const projectRoot = rootOf(ctx.cwd || process.cwd());
|
|
188
190
|
if (!frameworkInstalled(projectRoot)) {
|
|
191
|
+
const missing = frameworkMissing(projectRoot);
|
|
189
192
|
ctx.ui.notify(
|
|
190
|
-
|
|
193
|
+
`ask-uat: the agent framework is incomplete (missing: ${missing.join(", ")}) — run /ask-init first.`,
|
|
191
194
|
"error",
|
|
192
195
|
);
|
|
193
196
|
return;
|
|
@@ -234,7 +237,7 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
234
237
|
startIdleTimer();
|
|
235
238
|
// The framework is installed here, so both tools belong in the request:
|
|
236
239
|
// clustering writes items, and the same turn may need to record a change.
|
|
237
|
-
pi.setActiveTools(toolsWith(["record_change",
|
|
240
|
+
pi.setActiveTools(toolsWith(["record_change", UAT_ITEM_TOOL]));
|
|
238
241
|
open(server.url);
|
|
239
242
|
|
|
240
243
|
const pending = snapshot.state.pending;
|
|
@@ -292,7 +295,7 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
292
295
|
syncRecordTool(frameworkInstalled(projectRoot));
|
|
293
296
|
if (active) {
|
|
294
297
|
const current = pi.getActiveTools();
|
|
295
|
-
if (!current.includes(
|
|
298
|
+
if (!current.includes(UAT_ITEM_TOOL)) pi.setActiveTools([...current, UAT_ITEM_TOOL]);
|
|
296
299
|
}
|
|
297
300
|
if (!active) return undefined;
|
|
298
301
|
return { systemPrompt: `${event.systemPrompt}\n\n${UAT_MODE_BANNER}` };
|
|
@@ -310,7 +313,7 @@ export function registerUat(pi: ExtensionAPI, options: UatOptions = {}): void {
|
|
|
310
313
|
closeServer();
|
|
311
314
|
// Session state never leaks: remove the phase tool unconditionally, then
|
|
312
315
|
// recompute the record tool from the new project's framework and phase.
|
|
313
|
-
pi.setActiveTools(toolsWith([], [
|
|
316
|
+
pi.setActiveTools(toolsWith([], [UAT_ITEM_TOOL]));
|
|
314
317
|
root = rootOf(ctx.cwd || process.cwd());
|
|
315
318
|
syncRecordTool(frameworkInstalled(root));
|
|
316
319
|
});
|
|
@@ -22,7 +22,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
|
|
|
22
22
|
import { RECORD_CHANGE_TOOL } from "./constants.js";
|
|
23
23
|
import { appendEvent, ledgerPath, newEventId } from "./ledger.js";
|
|
24
24
|
import { createRecord } from "./records.js";
|
|
25
|
-
import { frameworkInstalled, resolveProjectRoot } from "./state.js";
|
|
25
|
+
import { frameworkInstalled, frameworkMissing, resolveProjectRoot } from "./state.js";
|
|
26
26
|
|
|
27
27
|
const PARAMS = Type.Object({
|
|
28
28
|
title: Type.String({
|
|
@@ -109,8 +109,9 @@ export function registerRecordTool(pi: ExtensionAPI, options: RecordToolOptions
|
|
|
109
109
|
}
|
|
110
110
|
const root = rootOf(ctx.cwd || process.cwd());
|
|
111
111
|
if (!frameworkInstalled(root)) {
|
|
112
|
+
const missing = frameworkMissing(root);
|
|
112
113
|
return errorResult(
|
|
113
|
-
|
|
114
|
+
`record_change: the agent framework is incomplete (missing: ${missing.join(", ")}). Run /ask-init first, or write the record by hand.`,
|
|
114
115
|
);
|
|
115
116
|
}
|
|
116
117
|
const title = params.title.trim();
|