ceulen 0.15.2 → 0.16.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.
- package/CHANGELOG.md +41 -0
- package/README.md +1 -1
- package/extensions/lib/registry.ts +2 -1
- package/extensions/modules/classifier/index.ts +29 -12
- package/extensions/modules/classifier/lib/settings.ts +20 -3
- package/extensions/modules/classifier/test/classifier.test.ts +12 -4
- package/extensions/modules/config/defaultTools.ts +7 -3
- package/extensions/modules/config/test/defaultTools.test.ts +16 -0
- package/extensions/modules/gh/lib/ops.ts +22 -4
- package/extensions/modules/gh/test/gh.test.ts +64 -1
- package/extensions/modules/plan/index.ts +116 -4
- package/extensions/modules/plan/lib/settings.ts +5 -7
- package/extensions/modules/plan/test/module.test.ts +104 -1
- package/extensions/modules/plan/test/settings.test.ts +7 -0
- package/extensions/modules/repair/configPanel.ts +3 -1
- package/extensions/modules/repair/index.ts +21 -16
- package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
- package/extensions/modules/repair/test/freshness.test.ts +30 -0
- package/extensions/modules/repair/test/hardening.test.ts +46 -1
- package/extensions/modules/repair/test/readers.test.ts +11 -5
- package/extensions/modules/repair/test/settings.test.ts +7 -2
- package/extensions/modules/rtk/configPanel.ts +67 -0
- package/extensions/modules/rtk/index.ts +76 -9
- package/extensions/modules/rtk/lib/settings.ts +65 -0
- package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
- package/extensions/modules/rtk/test/index.test.js +120 -2
- package/extensions/modules/rules/index.ts +4 -1
- package/extensions/modules/rules/lib/rules.ts +6 -3
- package/extensions/modules/rules/test/lib.test.ts +24 -0
- package/extensions/modules/rules/test/module.test.ts +29 -0
- package/extensions/modules/shells/lib/sessions.ts +40 -12
- package/extensions/modules/shells/test/sessions.test.ts +60 -2
- package/extensions/modules/steering/index.ts +12 -1
- package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
- package/extensions/modules/subagent/index.ts +19 -3
- package/extensions/modules/subagent/lib/herdr.ts +141 -1
- package/extensions/modules/subagent/lib/runner.ts +88 -22
- package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
- package/extensions/modules/subagent/test/worktree.test.ts +156 -1
- package/extensions/modules/todo/index.ts +4 -0
- package/extensions/modules/todo/test/todo.test.ts +9 -0
- package/extensions/modules/web/index.ts +1 -1
- package/extensions/modules/web/lib/a11y.ts +30 -15
- package/extensions/modules/web/lib/cdp.ts +11 -2
- package/extensions/modules/web/lib/chrome.ts +12 -3
- package/extensions/modules/web/lib/content.ts +32 -9
- package/extensions/modules/web/lib/search.ts +111 -3
- package/extensions/modules/web/test/a11y.test.ts +100 -2
- package/extensions/modules/web/test/cdp.test.ts +48 -0
- package/extensions/modules/web/test/chrome.test.ts +32 -0
- package/extensions/modules/web/test/content.test.ts +92 -0
- package/extensions/modules/web/test/search.test.ts +75 -0
- package/package.json +1 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// ds-anchor × plan mode: the bootstrap DEFERS while plan mode is active.
|
|
2
|
+
// Plan mode strips the mutator tools (str_replace_editor is in plan's
|
|
3
|
+
// BLOCKED_TOOLS), so the DSH pair can never reach the payload — previously
|
|
4
|
+
// the anchor fail-opened PERMANENTLY there: warning + anchorPromoted latch +
|
|
5
|
+
// request #1 shipped with the minimal persona and NO plan-mode contract.
|
|
6
|
+
// Deferral keeps the session anchorable and the warning silent.
|
|
7
|
+
|
|
8
|
+
import assert from "node:assert";
|
|
9
|
+
import { after, before, describe, it } from "node:test";
|
|
10
|
+
import { createFakePi, isolateAgentDir } from "./harness.js";
|
|
11
|
+
import { setPlanActive } from "../../../lib/plan-bridge.ts";
|
|
12
|
+
|
|
13
|
+
const MINIMAL = "You are a helpful software engineer assistant.";
|
|
14
|
+
const PRO = "deepseek-v4-pro";
|
|
15
|
+
// Plan-mode-shaped catalog: reads + plan tools, NO mutator pair.
|
|
16
|
+
const PLAN_TOOLS = ["read", "bash", "grep", "find", "ls", "write_plan", "ask_user_question"];
|
|
17
|
+
|
|
18
|
+
describe("ds-anchor × plan mode", () => {
|
|
19
|
+
let restoreAgentDir: () => void;
|
|
20
|
+
before(() => { restoreAgentDir = isolateAgentDir("ceulen-steering-plan-").restore; });
|
|
21
|
+
after(() => { setPlanActive(false); restoreAgentDir(); });
|
|
22
|
+
|
|
23
|
+
it("defers while plan mode is active: no minimal prompt, no tool filter, no fail-open warning", () => {
|
|
24
|
+
setPlanActive(true);
|
|
25
|
+
const h = createFakePi(PLAN_TOOLS);
|
|
26
|
+
h.setEntries([]);
|
|
27
|
+
h.fire("session_start", {}, h.ctx(PRO));
|
|
28
|
+
|
|
29
|
+
const r = h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
|
|
30
|
+
assert.notEqual(r?.systemPrompt, MINIMAL, "no minimal prompt while planning");
|
|
31
|
+
assert.ok(r?.systemPrompt === undefined || r.systemPrompt.includes("FULL PI PROMPT"), "composed prompt preserved (plan contract survives)");
|
|
32
|
+
|
|
33
|
+
// The payload that triggered the live bug: plan-filtered catalog without str_replace_editor.
|
|
34
|
+
const out = h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
|
|
35
|
+
assert.equal(out?.tools, undefined, "no tool substitution while planning");
|
|
36
|
+
assert.equal(out?.max_tokens, undefined, "no budget pin while planning");
|
|
37
|
+
assert.equal(h.notifications.length, 0, "no fail-open warning");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("bootstrap engages on the first post-exit turn when no assistant reply landed", () => {
|
|
41
|
+
setPlanActive(true);
|
|
42
|
+
const h = createFakePi(PLAN_TOOLS);
|
|
43
|
+
h.setEntries([]);
|
|
44
|
+
h.fire("session_start", {}, h.ctx(PRO));
|
|
45
|
+
h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
|
|
46
|
+
h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
|
|
47
|
+
assert.equal(h.notifications.length, 0, "still no warning after exit");
|
|
48
|
+
|
|
49
|
+
setPlanActive(false);
|
|
50
|
+
const r2 = h.fire("before_agent_start", { prompt: "now do it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
|
|
51
|
+
assert.equal(r2?.systemPrompt, MINIMAL, "plan exit with no durable reply → bootstrap fires");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("plan-mode assistant replies promote naturally (no post-exit re-anchor)", () => {
|
|
55
|
+
setPlanActive(true);
|
|
56
|
+
const h = createFakePi(PLAN_TOOLS);
|
|
57
|
+
h.setEntries([]);
|
|
58
|
+
h.fire("session_start", {}, h.ctx(PRO));
|
|
59
|
+
h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "text" }] } }]);
|
|
60
|
+
|
|
61
|
+
setPlanActive(false);
|
|
62
|
+
const r = h.fire("before_agent_start", { prompt: "execute", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
|
|
63
|
+
assert.notEqual(r?.systemPrompt, MINIMAL, "history diverged from DSH distribution — no re-anchor");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("/steering status discloses the deferral", () => {
|
|
67
|
+
setPlanActive(true);
|
|
68
|
+
const h = createFakePi(PLAN_TOOLS);
|
|
69
|
+
h.setEntries([]);
|
|
70
|
+
h.fire("session_start", {}, h.ctx(PRO));
|
|
71
|
+
assert.ok(h.status(h.ctx(PRO)).includes("deferred (plan mode)"));
|
|
72
|
+
});
|
|
73
|
+
});
|
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
getResultOutput,
|
|
43
43
|
isFailedResult,
|
|
44
44
|
mapWithConcurrencyLimit,
|
|
45
|
+
OWNER_SUFFIX,
|
|
45
46
|
pidAlive,
|
|
46
47
|
runSubAgent,
|
|
47
48
|
startHeartbeat,
|
|
@@ -108,6 +109,7 @@ import {
|
|
|
108
109
|
MAX_HERDR_TASK_BYTES,
|
|
109
110
|
MAX_REPORT_BYTES,
|
|
110
111
|
prepareHerdrTask,
|
|
112
|
+
captureEvidenceStamp,
|
|
111
113
|
promptAndWait,
|
|
112
114
|
resolveEffectiveRunner,
|
|
113
115
|
truncateHerdrTask,
|
|
@@ -421,7 +423,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
421
423
|
const ownerLabel = async (): Promise<string> => {
|
|
422
424
|
const base = path.join(path.resolve(ctx.cwd), WORKTREE_DIR_NAME);
|
|
423
425
|
let entries: string[] = [];
|
|
424
|
-
try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore"); } catch { return "No worktree sandboxes."; }
|
|
426
|
+
try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore" && !e.endsWith(OWNER_SUFFIX)); } catch { return "No worktree sandboxes."; }
|
|
425
427
|
if (entries.length === 0) return "No worktree sandboxes.";
|
|
426
428
|
const lines = await Promise.all(entries.map(async (entry) => {
|
|
427
429
|
let owner: WorktreeOwner | undefined;
|
|
@@ -434,7 +436,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
434
436
|
return `Worktree sandboxes (${entries.length}):
|
|
435
437
|
${lines.join("\n")}`;
|
|
436
438
|
};
|
|
437
|
-
const result = force ? await sweepStaleWorktrees(ctx.cwd) : null;
|
|
439
|
+
const result = force ? await sweepStaleWorktrees(ctx.cwd, undefined, { force: true }) : null;
|
|
438
440
|
const listing = await ownerLabel();
|
|
439
441
|
const sweepLine = result ? `\n\nSwept ${result.removed.length} stale sandbox(es): ${result.removed.map((r) => path.basename(r)).join(", ") || "none"}.` : "\n\n(/subagent worktrees clean to sweep stale entries)";
|
|
440
442
|
pi.sendMessage({ customType: "ceulen-subagent", content: `${listing}${sweepLine}`, display: true });
|
|
@@ -2156,6 +2158,8 @@ ${lines.join("\n")}`;
|
|
|
2156
2158
|
const fileStampBefore = entry
|
|
2157
2159
|
? await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
|
|
2158
2160
|
: "";
|
|
2161
|
+
// Stalled-turn recovery evidence (same baseline as the runner path).
|
|
2162
|
+
const stamp = entry ? await captureEvidenceStamp(entry, name, herdrCli.exec) : undefined;
|
|
2159
2163
|
// Abortable: an aborted tool call interrupts the wait (esc to the
|
|
2160
2164
|
// child) instead of blocking until the CLI timeout.
|
|
2161
2165
|
const outcome = await new Promise<PromptOutcome>((resolve) => {
|
|
@@ -2168,7 +2172,19 @@ ${lines.join("\n")}`;
|
|
|
2168
2172
|
resolve({ state: "unknown", delivered: false, error: "aborted: tool call cancelled" });
|
|
2169
2173
|
};
|
|
2170
2174
|
_signal?.addEventListener("abort", onAbort, { once: true });
|
|
2171
|
-
promptAndWait({
|
|
2175
|
+
promptAndWait({
|
|
2176
|
+
name,
|
|
2177
|
+
text,
|
|
2178
|
+
timeoutMs,
|
|
2179
|
+
exec: herdrCli.exec,
|
|
2180
|
+
evidence: entry
|
|
2181
|
+
? {
|
|
2182
|
+
resultFile: entry.resultFile,
|
|
2183
|
+
readOnly: entry.readOnly,
|
|
2184
|
+
stamp: stamp!,
|
|
2185
|
+
}
|
|
2186
|
+
: undefined,
|
|
2187
|
+
}).then((o) => {
|
|
2172
2188
|
if (settled) return;
|
|
2173
2189
|
settled = true;
|
|
2174
2190
|
_signal?.removeEventListener("abort", onAbort);
|
|
@@ -42,6 +42,93 @@ export const herdrCli: { exec: HerdrExec } = { exec: defaultExec };
|
|
|
42
42
|
export const HERDR_OFF_ENV = "PI_SUBAGENT_HERDR";
|
|
43
43
|
|
|
44
44
|
const HERDR_NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
45
|
+
/**
|
|
46
|
+
* Grace window after herdr's `agent_prompt_stalled` (its built-in allowance is
|
|
47
|
+
* a hard 5000ms): how long we additionally wait for OUTPUT evidence before
|
|
48
|
+
* declaring the dispatch dead. Covers cold-model first-token latency.
|
|
49
|
+
*/
|
|
50
|
+
const STALLED_GRACE_MS = 30_000;
|
|
51
|
+
|
|
52
|
+
/** Pre-submission snapshot used as the baseline for stalled-turn recovery. */
|
|
53
|
+
export interface OutputEvidenceStamp {
|
|
54
|
+
/** `${size}:${mtimeMs}` of the report file ("" when absent) — same format the herdr tool's follow-up compare uses. */
|
|
55
|
+
fileStamp: string;
|
|
56
|
+
/** Read-only children only: pane tail before submission (inline replies are the only evidence channel). */
|
|
57
|
+
paneTail?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* herdr 0.9.3's status watcher never observes `working` for pi panes —
|
|
62
|
+
* `state_change_seq` stays frozen across live turns (live-probed 2026-10-10) —
|
|
63
|
+
* so `agent prompt --wait` stalls on dispatches that run fine and `agent
|
|
64
|
+
* wait --until working` never fires. State polling proves nothing; the only
|
|
65
|
+
* trustworthy completion evidence is OUTPUT. Capture the pre-submission
|
|
66
|
+
* baseline: report-file stamp (+ pane tail for read-only children).
|
|
67
|
+
*/
|
|
68
|
+
export async function captureEvidenceStamp(
|
|
69
|
+
handle: { resultFile: string; readOnly?: boolean },
|
|
70
|
+
name: string,
|
|
71
|
+
exec: HerdrExec,
|
|
72
|
+
): Promise<OutputEvidenceStamp> {
|
|
73
|
+
const fileStamp = await fs.stat(handle.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
74
|
+
let paneTail: string | undefined;
|
|
75
|
+
if (handle.readOnly) {
|
|
76
|
+
const read = await exec("herdr", ["agent", "read", name, "--source", "recent-unwrapped", "--lines", "40"], { timeout: 10_000 });
|
|
77
|
+
paneTail = read.code === 0 ? read.stdout : "";
|
|
78
|
+
}
|
|
79
|
+
return { fileStamp, paneTail };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Wait for output evidence that the stalled turn is (or already was) running:
|
|
84
|
+
* the report file's stamp changing (delivery contract), or — read-only
|
|
85
|
+
* children — the pane tail changing and then staying quiet. Returns true when
|
|
86
|
+
* evidence settled; false on deadline (genuinely silent pane).
|
|
87
|
+
*/
|
|
88
|
+
async function waitForOutputEvidence(opts: {
|
|
89
|
+
name: string;
|
|
90
|
+
resultFile: string;
|
|
91
|
+
readOnly?: boolean;
|
|
92
|
+
stamp: OutputEvidenceStamp;
|
|
93
|
+
deadlineMs: number;
|
|
94
|
+
pollMs?: number;
|
|
95
|
+
signal?: AbortSignal;
|
|
96
|
+
exec: HerdrExec;
|
|
97
|
+
}): Promise<boolean> {
|
|
98
|
+
const pollMs = opts.pollMs ?? 1_000;
|
|
99
|
+
const deadline = Date.now() + opts.deadlineMs;
|
|
100
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
101
|
+
const fileStampNow = () =>
|
|
102
|
+
fs.stat(opts.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
103
|
+
const readTail = async () => {
|
|
104
|
+
const read = await opts.exec("herdr", ["agent", "read", opts.name, "--source", "recent-unwrapped", "--lines", "40"], { timeout: 10_000 });
|
|
105
|
+
return read.code === 0 ? read.stdout : "";
|
|
106
|
+
};
|
|
107
|
+
let stableCount = 0;
|
|
108
|
+
let lastTail = "";
|
|
109
|
+
for (;;) {
|
|
110
|
+
if (opts.signal?.aborted) return false;
|
|
111
|
+
if (!opts.readOnly) {
|
|
112
|
+
const stamp = await fileStampNow();
|
|
113
|
+
// A changed stamp means the child (re)wrote its report — settled.
|
|
114
|
+
// "" → exists is the fast-child case (wrote before the stall fired).
|
|
115
|
+
if (stamp && stamp !== opts.stamp.fileStamp) return true;
|
|
116
|
+
} else {
|
|
117
|
+
const tail = await readTail();
|
|
118
|
+
if (tail !== opts.stamp.paneTail) {
|
|
119
|
+
// Changed from the baseline: require quiescence (3 identical polls)
|
|
120
|
+
// so a mid-stream snapshot is not collected as the final reply.
|
|
121
|
+
if (tail === lastTail) stableCount++;
|
|
122
|
+
else { stableCount = 1; lastTail = tail; }
|
|
123
|
+
if (stableCount >= 3) return true;
|
|
124
|
+
} else {
|
|
125
|
+
stableCount = 0;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (Date.now() >= deadline) return false;
|
|
129
|
+
await sleep(pollMs);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
45
132
|
/** Reject herdr tasks above this size — the prompt travels as a CLI argv element. */
|
|
46
133
|
export const MAX_HERDR_TASK_BYTES = 64 * 1024;
|
|
47
134
|
/**
|
|
@@ -565,6 +652,18 @@ export async function promptAndWait(opts: {
|
|
|
565
652
|
text: string;
|
|
566
653
|
timeoutMs: number;
|
|
567
654
|
exec: HerdrExec;
|
|
655
|
+
/** Output-evidence baseline + channels for stalled-turn recovery. Without
|
|
656
|
+
* it a stall is a hard failure (CLI-faithful behaviour). With it, the
|
|
657
|
+
* evidence wait spans the remaining dispatch budget — a long task is not
|
|
658
|
+
* a stalled task — and exhaustion reports TIMEOUT (the caller then
|
|
659
|
+
* interrupts the pane), never a phantom stall. */
|
|
660
|
+
evidence?: {
|
|
661
|
+
resultFile: string;
|
|
662
|
+
readOnly?: boolean;
|
|
663
|
+
stamp: OutputEvidenceStamp;
|
|
664
|
+
graceMs?: number;
|
|
665
|
+
signal?: AbortSignal;
|
|
666
|
+
};
|
|
568
667
|
}): Promise<PromptOutcome> {
|
|
569
668
|
const res = await opts.exec(
|
|
570
669
|
"herdr",
|
|
@@ -580,7 +679,37 @@ export async function promptAndWait(opts: {
|
|
|
580
679
|
return { state: "unknown", delivered: true, error: `timeout after ${opts.timeoutMs}ms` };
|
|
581
680
|
}
|
|
582
681
|
if (/stalled/i.test(errText)) {
|
|
583
|
-
|
|
682
|
+
// herdr's --wait requires an observed working/blocked state within
|
|
683
|
+
// 5000ms — but its status watcher NEVER reports `working` for pi panes
|
|
684
|
+
// (state_change_seq frozen across live turns, live probe 2026-10-10), so
|
|
685
|
+
// the stall fires on healthy dispatches and no state probe can recover
|
|
686
|
+
// it. The only trustworthy completion evidence is OUTPUT: a changed
|
|
687
|
+
// report-file stamp (delivery contract) or a changed-then-quiet pane
|
|
688
|
+
// tail (read-only inline replies). Without evidence channels, the
|
|
689
|
+
// stall stays a hard failure.
|
|
690
|
+
if (opts.evidence) {
|
|
691
|
+
const settled = await waitForOutputEvidence({
|
|
692
|
+
name: opts.name,
|
|
693
|
+
resultFile: opts.evidence.resultFile,
|
|
694
|
+
readOnly: opts.evidence.readOnly,
|
|
695
|
+
stamp: opts.evidence.stamp,
|
|
696
|
+
// The CLI consumed ~5s observing its stall window; the evidence
|
|
697
|
+
// wait gets the full dispatch budget (floored at the grace minimum
|
|
698
|
+
// so very short timeouts still get a fair window).
|
|
699
|
+
deadlineMs: opts.evidence.graceMs ?? Math.max(STALLED_GRACE_MS, opts.timeoutMs),
|
|
700
|
+
signal: opts.evidence.signal,
|
|
701
|
+
exec: opts.exec,
|
|
702
|
+
});
|
|
703
|
+
if (settled) {
|
|
704
|
+
return { state: await getAgentState(opts.name, opts.exec), delivered: true };
|
|
705
|
+
}
|
|
706
|
+
// Evidence window exhausted with the full budget spent: report
|
|
707
|
+
// timeout semantics (executeHerdrTask's timedOut branch interrupts
|
|
708
|
+
// the child and discloses the maybe-late write) — the dispatch was
|
|
709
|
+
// delivered and may STILL complete, so never a hard stall here.
|
|
710
|
+
return { state: "unknown", delivered: true, error: `timeout after ${opts.timeoutMs}ms (no output evidence — likely still working or blocked in its pane)` };
|
|
711
|
+
}
|
|
712
|
+
return { state: "unknown", delivered: false, error: "agent_prompt_stalled: no output evidence within the grace window — check the pane (a dialog can also look silent), then prompt again" };
|
|
584
713
|
}
|
|
585
714
|
// Unexpected error — still report the last known state.
|
|
586
715
|
const state = await getAgentState(opts.name, opts.exec);
|
|
@@ -964,6 +1093,11 @@ export async function executeHerdrTask(
|
|
|
964
1093
|
try {
|
|
965
1094
|
pollTimer = setInterval(() => { void poll(); }, 2_000);
|
|
966
1095
|
pollTimer.unref?.();
|
|
1096
|
+
// Pre-submission output baseline: herdr's stall fires on healthy pi
|
|
1097
|
+
// dispatches (its watcher never reports `working`), so recovery waits on
|
|
1098
|
+
// evidence, not state. Snapshot BEFORE the prompt so any change proves
|
|
1099
|
+
// the turn produced output.
|
|
1100
|
+
const stamp = await captureEvidenceStamp(handle, handle.name, exec);
|
|
967
1101
|
// A pre-aborted dispatch must not submit the task to the live child at
|
|
968
1102
|
// all (mirrors the SDK path's early return on an aborted signal).
|
|
969
1103
|
const prompt = opts.signal?.aborted
|
|
@@ -973,6 +1107,12 @@ export async function executeHerdrTask(
|
|
|
973
1107
|
text: wrapTaskPrompt(handle.task, handle.resultFile, handle.readOnly),
|
|
974
1108
|
timeoutMs: handle.timeoutMs,
|
|
975
1109
|
exec,
|
|
1110
|
+
evidence: {
|
|
1111
|
+
resultFile: handle.resultFile,
|
|
1112
|
+
readOnly: handle.readOnly,
|
|
1113
|
+
stamp,
|
|
1114
|
+
signal: opts.signal,
|
|
1115
|
+
},
|
|
976
1116
|
});
|
|
977
1117
|
let output = "";
|
|
978
1118
|
let outputSource: "file" | "pane" | "none" = "none";
|
|
@@ -460,13 +460,23 @@ export const WORKTREE_DIR_NAME = ".pi-worktrees";
|
|
|
460
460
|
|
|
461
461
|
/** A nested `.gitignore` (content `*`) inside the sandbox base keeps sandboxes
|
|
462
462
|
* out of the parent's `git status` AND out of untracked baseline capture —
|
|
463
|
-
* without touching the user's own .gitignore.
|
|
464
|
-
|
|
463
|
+
* without touching the user's own .gitignore. Returns an error note when the
|
|
464
|
+
* base is unusable (sandboxes would then be enumerable by the baseline
|
|
465
|
+
* capture), undefined on success. */
|
|
466
|
+
async function ensureWorktreeBaseGitignore(base: string): Promise<string | undefined> {
|
|
465
467
|
const ignoreFile = path.join(base, ".gitignore");
|
|
466
468
|
try {
|
|
467
469
|
await fs.mkdir(base, { recursive: true });
|
|
468
470
|
await fs.writeFile(ignoreFile, "*\n", { flag: "wx" });
|
|
469
|
-
} catch
|
|
471
|
+
} catch (error) {
|
|
472
|
+
if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") {
|
|
473
|
+
return `could not write ${WORKTREE_DIR_NAME}/.gitignore: ${(error as Error).message}`;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
// EEXIST is acceptable only if the thing at that path IS the ignore file.
|
|
477
|
+
const st = await fs.stat(ignoreFile).catch(() => undefined);
|
|
478
|
+
if (!st?.isFile()) return `${WORKTREE_DIR_NAME}/.gitignore is missing or not a file`;
|
|
479
|
+
return undefined;
|
|
470
480
|
}
|
|
471
481
|
|
|
472
482
|
/** Owner marker: a SIBLING file inside the (gitignored) sandbox base —
|
|
@@ -476,9 +486,14 @@ async function ensureWorktreeBaseGitignore(base: string): Promise<void> {
|
|
|
476
486
|
* concurrent-merge race test). */
|
|
477
487
|
export const OWNER_SUFFIX = ".owner.json";
|
|
478
488
|
|
|
489
|
+
/** Atomic write (tmp + rename) — a concurrent sweep reader must never see a
|
|
490
|
+
* partial marker and mistake a live sandbox for stale. */
|
|
479
491
|
async function writeOwnerMarker(base: string, id: string): Promise<void> {
|
|
480
492
|
const owner: WorktreeOwner = { pid: process.pid, id, createdAt: Date.now() };
|
|
481
|
-
|
|
493
|
+
const target = path.join(base, `${id}${OWNER_SUFFIX}`);
|
|
494
|
+
const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
|
|
495
|
+
await fs.writeFile(tmp, JSON.stringify(owner), { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
496
|
+
await fs.rename(tmp, target);
|
|
482
497
|
}
|
|
483
498
|
|
|
484
499
|
async function readOwnerMarker(base: string, entry: string): Promise<WorktreeOwner | undefined> {
|
|
@@ -510,10 +525,13 @@ export interface SweepResult {
|
|
|
510
525
|
/** Remove crashed runs' worktree sandboxes under <repoRoot>/.pi-worktrees.
|
|
511
526
|
* Source of truth is the DIRECTORY (covers both backends); the git
|
|
512
527
|
* registration check only decides HOW a stale dir is removed. Never removes
|
|
513
|
-
* a sandbox whose marker pid is alive
|
|
528
|
+
* a sandbox whose marker pid is alive — except under opts.force, which may
|
|
529
|
+
* also remove FOREIGN live-pid sandboxes (pid recycling can false-KEEP);
|
|
530
|
+
* this process's own live sandboxes stay protected. Best-effort throughout. */
|
|
514
531
|
export async function sweepStaleWorktrees(
|
|
515
532
|
cwd: string,
|
|
516
533
|
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
534
|
+
opts?: { force?: boolean },
|
|
517
535
|
): Promise<SweepResult> {
|
|
518
536
|
const removed: string[] = [];
|
|
519
537
|
try {
|
|
@@ -534,17 +552,35 @@ export async function sweepStaleWorktrees(
|
|
|
534
552
|
(list.ok ? list.stdout : "").split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice("worktree ".length).trim()),
|
|
535
553
|
);
|
|
536
554
|
for (const entry of entries) {
|
|
537
|
-
if (entry.endsWith(OWNER_SUFFIX))
|
|
555
|
+
if (entry.endsWith(OWNER_SUFFIX)) {
|
|
556
|
+
// Orphan marker (creation failed after the write, or the sandbox was
|
|
557
|
+
// already swept): the dir is gone, so drop the marker instead of
|
|
558
|
+
// skipping it forever — it would otherwise render as a phantom row
|
|
559
|
+
// in /subagent worktrees for the life of the checkout.
|
|
560
|
+
const orphanDir = path.join(base, entry.slice(0, -OWNER_SUFFIX.length));
|
|
561
|
+
if (!(await fs.stat(orphanDir).then((s) => s.isDirectory()).catch(() => false))) {
|
|
562
|
+
await fs.rm(path.join(base, entry), { force: true }).catch(() => { /* best effort */ });
|
|
563
|
+
}
|
|
564
|
+
continue; // marker files, not sandboxes
|
|
565
|
+
}
|
|
538
566
|
const dir = path.join(base, entry);
|
|
539
567
|
// The nested .gitignore is a FILE, not a sandbox — never scan/rm it.
|
|
540
568
|
if (!(await fs.stat(dir).then((s) => s.isDirectory()).catch(() => false))) continue;
|
|
541
569
|
const owner = await readOwnerMarker(base, entry);
|
|
542
|
-
if (owner && pidAlive(owner.pid)) { kept++; continue; }
|
|
570
|
+
if (owner && pidAlive(owner.pid) && (!opts?.force || owner.pid === process.pid)) { kept++; continue; }
|
|
543
571
|
// ponytail: pid recycling can false-KEEP a stale sandbox (safe
|
|
544
|
-
// direction); `/subagent worktrees clean`
|
|
572
|
+
// direction); `/subagent worktrees clean` passes force, which lifts
|
|
573
|
+
// the keep-gate for foreign live pids only.
|
|
545
574
|
try {
|
|
546
|
-
|
|
575
|
+
let removeFailed = false;
|
|
576
|
+
if (registered.has(dir)) {
|
|
577
|
+
const rmRes = await runGit(repoRoot, ["worktree", "remove", "--force", dir], exec);
|
|
578
|
+
removeFailed = !rmRes.ok;
|
|
579
|
+
}
|
|
547
580
|
await fs.rm(dir, { recursive: true, force: true });
|
|
581
|
+
// rm -rf alone leaves a stale .git/worktrees registration behind —
|
|
582
|
+
// prune it (after the dir is gone; prune only drops missing dirs).
|
|
583
|
+
if (removeFailed) await runGit(repoRoot, ["worktree", "prune"], exec);
|
|
548
584
|
await fs.rm(path.join(base, `${entry}${OWNER_SUFFIX}`), { force: true });
|
|
549
585
|
removed.push(dir);
|
|
550
586
|
} catch { /* best effort per dir */ }
|
|
@@ -648,7 +684,13 @@ async function createCowClone(
|
|
|
648
684
|
const entries = await fs.readdir(repoRoot, { withFileTypes: true });
|
|
649
685
|
for (const entry of entries) {
|
|
650
686
|
if (entry.name === WORKTREE_DIR_NAME) continue;
|
|
651
|
-
const
|
|
687
|
+
const args = ["-cR", path.join(repoRoot, entry.name), path.join(staging, entry.name)];
|
|
688
|
+
// The live .git mutates under us — copy it under the same per-repo lock
|
|
689
|
+
// the sibling mutators (worktree add/remove, git apply --3way) hold, or
|
|
690
|
+
// a concurrent mutation can tear the copy.
|
|
691
|
+
const res = entry.name === ".git"
|
|
692
|
+
? await withRepoLock(repoRoot, () => run("cp", args, { timeout: 300_000 }))
|
|
693
|
+
: await run("cp", args, { timeout: 300_000 });
|
|
652
694
|
if (res.code !== 0) return false;
|
|
653
695
|
}
|
|
654
696
|
await fs.mkdir(path.dirname(wtPath), { recursive: true });
|
|
@@ -740,19 +782,43 @@ export async function createWorktree(
|
|
|
740
782
|
const repoRoot = root.stdout.trim();
|
|
741
783
|
if (!repoRoot) return { ok: false, error: "empty git root" };
|
|
742
784
|
const id = `pi-subagent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
743
|
-
const
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
785
|
+
const base = path.join(repoRoot, WORKTREE_DIR_NAME);
|
|
786
|
+
const wtPath = path.join(base, id);
|
|
787
|
+
const ignoreError = await ensureWorktreeBaseGitignore(base);
|
|
788
|
+
if (ignoreError) return { ok: false, error: ignoreError };
|
|
789
|
+
// Owner marker BEFORE the sandbox becomes visible at wtPath (CoW rename /
|
|
790
|
+
// `worktree add`): the GC sweep treats a missing marker as stale and
|
|
791
|
+
// rm -rf's the dir, so a marker published late — or failing to publish —
|
|
792
|
+
// must never leave an unprotected live sandbox behind.
|
|
793
|
+
const markerError = await writeOwnerMarker(base, id).then(
|
|
794
|
+
() => undefined,
|
|
795
|
+
(error) => (error instanceof Error ? error.message : String(error)),
|
|
796
|
+
);
|
|
797
|
+
if (markerError) return { ok: false, error: `owner marker unwritable (${markerError}) — refusing to create an unprotected sandbox` };
|
|
798
|
+
let outcome: { ok: boolean; path?: string; repoRoot?: string; error?: string; cow?: boolean };
|
|
799
|
+
try {
|
|
800
|
+
if (await createCowClone(repoRoot, wtPath, exec)) {
|
|
801
|
+
outcome = { ok: true, path: wtPath, repoRoot };
|
|
802
|
+
} else {
|
|
803
|
+
// Fallback: detached git worktree (clean HEAD; the caller seeds the
|
|
804
|
+
// parent's WIP via applyBaselineToWorktree). worktree add mutates the
|
|
805
|
+
// parent's shared .git/worktrees registry. The marker already covers it.
|
|
806
|
+
const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
|
|
807
|
+
outcome = add.ok
|
|
808
|
+
? { ok: true, path: wtPath, repoRoot, cow: false }
|
|
809
|
+
: { ok: false, error: add.stderr.trim() || "git worktree add failed" };
|
|
810
|
+
}
|
|
811
|
+
} catch (error) {
|
|
812
|
+
// A rejecting exec (or any throw) after the marker write lands here.
|
|
813
|
+
outcome = { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
814
|
+
}
|
|
815
|
+
if (!outcome.ok) {
|
|
816
|
+
// No sandbox was published — drop the marker so it cannot litter the
|
|
817
|
+
// base as an orphan: the sweep skips marker entries and /subagent
|
|
818
|
+
// worktrees would render it as a phantom row forever.
|
|
819
|
+
await fs.rm(path.join(base, `${id}${OWNER_SUFFIX}`), { force: true }).catch(() => { /* best effort */ });
|
|
748
820
|
}
|
|
749
|
-
|
|
750
|
-
// parent's WIP via applyBaselineToWorktree). worktree add mutates the
|
|
751
|
-
// parent's shared .git/worktrees registry.
|
|
752
|
-
const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
|
|
753
|
-
if (!add.ok) return { ok: false, error: add.stderr.trim() || "git worktree add failed" };
|
|
754
|
-
await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
|
|
755
|
-
return { ok: true, path: wtPath, repoRoot, cow: false };
|
|
821
|
+
return outcome;
|
|
756
822
|
} catch (error) {
|
|
757
823
|
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
758
824
|
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// promptAndWait's agent_prompt_stalled recovery — OUTPUT-evidence based.
|
|
2
|
+
// herdr 0.9.3's status watcher never observes `working` for pi panes
|
|
3
|
+
// (state_change_seq frozen across live turns; live probe 2026-10-10), so its
|
|
4
|
+
// `agent prompt --wait` stalls on healthy dispatches and NO state probe can
|
|
5
|
+
// recover it. Recovery waits on evidence instead: a changed report-file stamp
|
|
6
|
+
// (delivery contract) or a changed-then-quiet pane tail (read-only inline
|
|
7
|
+
// replies). Silence through the grace window is a genuine stall.
|
|
8
|
+
|
|
9
|
+
import assert from "node:assert/strict";
|
|
10
|
+
import { mkdtempSync, writeFileSync, statSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { test } from "node:test";
|
|
14
|
+
|
|
15
|
+
import { captureEvidenceStamp, promptAndWait } from "../lib/herdr.ts";
|
|
16
|
+
|
|
17
|
+
type FakeRes = { code: number; stdout?: string; stderr?: string };
|
|
18
|
+
type Call = { args: string[]; res: { code: number; stdout: string; stderr: string } };
|
|
19
|
+
|
|
20
|
+
/** Scripted exec: args-signature (first 2 tokens, e.g. "agent read") → responses consumed in order. */
|
|
21
|
+
function fakeExec(script: Map<string, FakeRes[]>, calls: Call[]) {
|
|
22
|
+
return async (_cmd: string, args: string[]) => {
|
|
23
|
+
const key = args.slice(0, 2).join(" ");
|
|
24
|
+
const res = { code: 0, stdout: "", stderr: "", ...script.get(key)?.shift() };
|
|
25
|
+
calls.push({ args, res });
|
|
26
|
+
return res;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const idleInfo = JSON.stringify({ result: { agent: { name: "a1", agent_status: "idle" } } });
|
|
31
|
+
const STALLED = { code: 1, stderr: "error: agent_prompt_stalled: no working within 5000ms" };
|
|
32
|
+
|
|
33
|
+
function tmpResultFile(): string {
|
|
34
|
+
return join(mkdtempSync(join(tmpdir(), "ceulen-herdr-stalled-")), "report.md");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
test("captureEvidenceStamp: missing file → empty stamp; existing → size:mtime", async () => {
|
|
38
|
+
const missing = join(tmpdir(), "ceulen-herdr-stamped-", "nope.md");
|
|
39
|
+
const exec = fakeExec(new Map(), []);
|
|
40
|
+
assert.equal((await captureEvidenceStamp({ resultFile: missing }, "a1", exec)).fileStamp, "");
|
|
41
|
+
const f = tmpResultFile();
|
|
42
|
+
writeFileSync(f, "hello");
|
|
43
|
+
const st = statSync(f);
|
|
44
|
+
assert.equal((await captureEvidenceStamp({ resultFile: f }, "a1", exec)).fileStamp, `${st.size}:${st.mtimeMs}`);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("stalled recovery: report file appears during grace → success (fast-child case)", async () => {
|
|
48
|
+
const resultFile = tmpResultFile();
|
|
49
|
+
// Baseline taken BEFORE the file exists (like a first dispatch); the child
|
|
50
|
+
// writing its report is the settle evidence.
|
|
51
|
+
const stamp = await captureEvidenceStamp({ resultFile }, "a1", fakeExec(new Map(), []));
|
|
52
|
+
writeFileSync(resultFile, "# report\n");
|
|
53
|
+
const calls: Call[] = [];
|
|
54
|
+
const script = new Map<string, FakeRes[]>([
|
|
55
|
+
["agent prompt", [STALLED]],
|
|
56
|
+
["agent get", [{ code: 0, stdout: idleInfo }]],
|
|
57
|
+
]);
|
|
58
|
+
const outcome = await promptAndWait({
|
|
59
|
+
name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
|
|
60
|
+
evidence: { resultFile, stamp, graceMs: 5_000 },
|
|
61
|
+
});
|
|
62
|
+
assert.equal(outcome.delivered, true);
|
|
63
|
+
assert.equal(outcome.error, undefined);
|
|
64
|
+
assert.equal(outcome.state, "idle");
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("stalled recovery: read-only child's pane tail changed + stayed quiet → success", async () => {
|
|
68
|
+
const calls: Call[] = [];
|
|
69
|
+
const script = new Map<string, FakeRes[]>([
|
|
70
|
+
["agent prompt", [STALLED]],
|
|
71
|
+
["agent read", [{ code: 0, stdout: "REPLY-DONE" }]],
|
|
72
|
+
["agent get", [{ code: 0, stdout: idleInfo }]],
|
|
73
|
+
]);
|
|
74
|
+
const outcome = await promptAndWait({
|
|
75
|
+
name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
|
|
76
|
+
evidence: { resultFile: tmpResultFile(), readOnly: true, stamp: { fileStamp: "", paneTail: "PRE-PROMPT" }, graceMs: 15_000 },
|
|
77
|
+
});
|
|
78
|
+
assert.equal(outcome.delivered, true);
|
|
79
|
+
assert.equal(outcome.state, "idle");
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("stalled recovery: silence through the evidence window → timeout semantics (delivered, may still complete)", async () => {
|
|
83
|
+
const resultFile = tmpResultFile(); // never written
|
|
84
|
+
const calls: Call[] = [];
|
|
85
|
+
const script = new Map<string, FakeRes[]>([
|
|
86
|
+
["agent prompt", [STALLED]],
|
|
87
|
+
]);
|
|
88
|
+
const outcome = await promptAndWait({
|
|
89
|
+
name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
|
|
90
|
+
evidence: { resultFile, stamp: { fileStamp: "" }, graceMs: 200 },
|
|
91
|
+
});
|
|
92
|
+
// Exhausted evidence wait = spent budget: the caller interrupts the pane;
|
|
93
|
+
// the dispatch was delivered, so never a hard stall.
|
|
94
|
+
assert.equal(outcome.delivered, true);
|
|
95
|
+
assert.match(outcome.error ?? "", /timeout/);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("stalled without evidence channels → immediate hard fail (CLI-faithful, unchanged)", async () => {
|
|
99
|
+
const calls: Call[] = [];
|
|
100
|
+
const script = new Map<string, FakeRes[]>([["agent prompt", [STALLED]]]);
|
|
101
|
+
const outcome = await promptAndWait({ name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls) });
|
|
102
|
+
assert.equal(outcome.delivered, false);
|
|
103
|
+
assert.match(outcome.error ?? "", /agent_prompt_stalled/);
|
|
104
|
+
// No evidence polling happened (no `agent read` calls).
|
|
105
|
+
assert.equal(calls.filter((c) => c.args[1] === "read").length, 0);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("no regression: plain timeout still short-circuits before the stalled branch", async () => {
|
|
109
|
+
const calls: Call[] = [];
|
|
110
|
+
const script = new Map<string, FakeRes[]>([
|
|
111
|
+
["agent prompt", [{ code: 1, stderr: "error: timeout after 1000ms" }]],
|
|
112
|
+
]);
|
|
113
|
+
const outcome = await promptAndWait({ name: "a1", text: "t", timeoutMs: 1000, exec: fakeExec(script, calls) });
|
|
114
|
+
assert.equal(outcome.delivered, true);
|
|
115
|
+
assert.match(outcome.error ?? "", /timeout/);
|
|
116
|
+
assert.equal(calls.filter((c) => c.args[1] === "read").length, 0);
|
|
117
|
+
});
|