pi-dev-flow 0.85.0 → 0.86.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 +27 -0
- package/README.md +2 -1
- package/docs/development.md +10 -0
- package/docs/gates.md +1 -1
- package/docs/guardrails.md +2 -2
- package/docs/playbook.md +17 -2
- package/extensions/dev-flow.ts +120 -2655
- package/package.json +4 -2
- package/skills/dev-flow/SKILL.md +52 -74
- package/skills/dev-flow/references/finish.md +41 -58
- package/skills/dev-flow/references/implement.md +62 -152
- package/skills/dev-flow/references/plan.md +40 -68
- package/skills/dev-flow/references/pre-release.md +39 -50
- package/skills/dev-flow/references/reflect.md +51 -85
- package/skills/dev-flow/references/release.md +31 -64
- package/skills/dev-flow/references/start.md +50 -69
- package/src/core.ts +24 -20
- package/src/present.ts +224 -0
- package/src/projectmd.ts +6 -1
- package/src/runtime/base.ts +554 -0
- package/src/runtime/checks.ts +358 -0
- package/src/runtime/gates.ts +719 -0
- package/src/runtime/reflect.ts +160 -0
- package/src/runtime/setup.ts +85 -0
- package/src/runtime/ship.ts +629 -0
- package/src/runtime/workers.ts +170 -0
- package/src/timeouts.ts +52 -17
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/** dev-flow runtime — Fresh-session workers (flow_stage): transcripts, pi-web metadata, spawning. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
|
+
import { closeSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, type AgentSession } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { digestTranscript, sq, featureTmpDir, type SessionHeaderInfo, type WorkerOp } from "../core.ts";
|
|
6
|
+
import { dfDir, now, sh } from "./base.ts";
|
|
7
|
+
|
|
8
|
+
/** Sessions spawned by flow_stage in this process: they get no [dev-flow] driver context injected
|
|
9
|
+
* (their brief is their whole context) — the guards still judge them like any session. */
|
|
10
|
+
export const workerSessions = new Set<string>();
|
|
11
|
+
|
|
12
|
+
/** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
|
|
13
|
+
export const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"], reflect: ["read", "bash"] };
|
|
14
|
+
|
|
15
|
+
/** Test-only timer override: the smoke suite drives the steer, the hard cut and the salvage grace in ms. */
|
|
16
|
+
export const workerTiming: { softMs?: number; hardMs?: number; graceMs?: number } = {};
|
|
17
|
+
|
|
18
|
+
/** The upstream dev-flow repo's issues in every state, for the reflect brief's dedupe — prefetched so
|
|
19
|
+
* the worker reads a list instead of looping gh searches. null = gh could not answer (the brief then
|
|
20
|
+
* falls back to the search recipe). */
|
|
21
|
+
export async function upstreamIssueList(root: string, repo: string): Promise<{ number: number; title: string; state: string }[] | null> {
|
|
22
|
+
if (!repo || process.env.DEV_FLOW_NO_ISSUES) return null;
|
|
23
|
+
const r = await sh(`gh issue list --repo ${sq(repo)} --state all --json number,title,state --limit 200`, root, 15_000);
|
|
24
|
+
if (!r.ok) return null;
|
|
25
|
+
try {
|
|
26
|
+
const a = JSON.parse(r.out) as { number?: unknown; title?: unknown; state?: unknown }[];
|
|
27
|
+
return Array.isArray(a) ? a.filter((i) => Number.isInteger(i?.number)).map((i) => ({ number: Number(i.number), title: String(i.title ?? ""), state: String(i.state ?? "") })) : null;
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Seam: the smoke suite stubs the prefetch instead of calling gh against the real upstream. */
|
|
34
|
+
export const reflectSeams = { upstreamIssues: upstreamIssueList };
|
|
35
|
+
|
|
36
|
+
/** Build the reflect worker's transcript digests in the feature's scratch dir (driver first). A
|
|
37
|
+
* transcript that cannot be read is skipped — the brief still names the raw file. */
|
|
38
|
+
export function writeTranscriptDigests(root: string, slug: string, files: string[]): { transcript: string; digest: string }[] {
|
|
39
|
+
const dir = path.join(featureTmpDir(dfDir(root), slug), "reflect");
|
|
40
|
+
const out: { transcript: string; digest: string }[] = [];
|
|
41
|
+
for (const f of files) {
|
|
42
|
+
try {
|
|
43
|
+
mkdirSync(dir, { recursive: true });
|
|
44
|
+
const digest = path.join(dir, `${path.basename(f, ".jsonl")}.digest.txt`);
|
|
45
|
+
writeFileSync(digest, digestTranscript(readFileSync(f, "utf8")));
|
|
46
|
+
out.push({ transcript: f, digest });
|
|
47
|
+
} catch { /* unreadable transcript: the raw path stays in the brief */ }
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Line 1 of every pi session file in `dir` — the header that names a worker's parent session. A
|
|
53
|
+
* file is read up to its first newline only (transcripts grow large); unreadable files are skipped. */
|
|
54
|
+
export function sessionHeaders(dir: string | undefined): SessionHeaderInfo[] {
|
|
55
|
+
if (!dir) return [];
|
|
56
|
+
let names: string[];
|
|
57
|
+
try { names = readdirSync(dir).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
|
|
58
|
+
const out: SessionHeaderInfo[] = [];
|
|
59
|
+
for (const n of names) {
|
|
60
|
+
const file = path.join(dir, n);
|
|
61
|
+
try {
|
|
62
|
+
const fd = openSync(file, "r");
|
|
63
|
+
try {
|
|
64
|
+
const buf = Buffer.alloc(16_384);
|
|
65
|
+
const len = readSync(fd, buf, 0, buf.length, 0);
|
|
66
|
+
const first = buf.subarray(0, len).toString("utf8").split("\n")[0];
|
|
67
|
+
const h = JSON.parse(first) as { type?: unknown; parentSession?: unknown };
|
|
68
|
+
if (h?.type === "session") out.push({ file, parentSession: typeof h.parentSession === "string" ? h.parentSession : undefined });
|
|
69
|
+
} finally { closeSync(fd); }
|
|
70
|
+
} catch { /* not a session file, or a header past the read window: skip */ }
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What makes a worker show up in pi-web's Agents menu: pi-web classifies a subagent from the
|
|
76
|
+
* custom entries its own runtime writes into the child's session file (pi-web lib/subagents.ts
|
|
77
|
+
* readSubagentRun, fed by lib/session-reader.ts). Two placement rules the reader enforces:
|
|
78
|
+
* the meta entry must be the file's FIRST data entry (the scanner reads header + one line and
|
|
79
|
+
* calls anything else a fork), and a persisted `running` the host cannot prove live displays as
|
|
80
|
+
* `interrupted` — so while a worker runs it also claims a slot in pi-web's live run map
|
|
81
|
+
* (piwebLiveClaim), and the final result entry settles the row after.
|
|
82
|
+
* Unknown entry types are inert in plain pi, so stamping is unconditional. */
|
|
83
|
+
export const PIWEB_SUBAGENT = { meta: "pi-web:subagent", status: "pi-web:subagent-status", result: "pi-web:subagent-result" } as const;
|
|
84
|
+
|
|
85
|
+
export interface WorkerSubagentMeta {
|
|
86
|
+
parentId: string;
|
|
87
|
+
parentFile: string;
|
|
88
|
+
toolCallId: string;
|
|
89
|
+
profile: string;
|
|
90
|
+
description: string;
|
|
91
|
+
task: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Only version 1 + the two lineage strings are hard-validated by pi-web's reader; the rest is
|
|
95
|
+
* display. resourceSnapshot is deliberately absent: its presence pins the tool set strictly when
|
|
96
|
+
* pi-web reopens the child, and these workers are never resumed by pi-web. */
|
|
97
|
+
export function piwebWorkerMeta(m: WorkerSubagentMeta): Record<string, unknown> {
|
|
98
|
+
return {
|
|
99
|
+
version: 1,
|
|
100
|
+
parentSessionId: m.parentId,
|
|
101
|
+
parentSessionPath: m.parentFile,
|
|
102
|
+
parentToolCallId: m.toolCallId,
|
|
103
|
+
profile: m.profile,
|
|
104
|
+
description: m.description,
|
|
105
|
+
task: m.task,
|
|
106
|
+
runInBackground: false,
|
|
107
|
+
createdAt: now(),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Best-effort by contract: a stamp that will not write must never break the worker run —
|
|
112
|
+
* visibility, not function (same rule as the worker's setSessionName renames). */
|
|
113
|
+
export function piwebStamp(target: { appendCustomEntry?(customType: string, data?: unknown): unknown } | undefined, customType: string, data: unknown): void {
|
|
114
|
+
try { target?.appendCustomEntry?.(customType, data); } catch { /* visibility only */ }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** pi-web proves a subagent live only from its own in-process tables (rpc-manager.ts
|
|
118
|
+
* subagentDisplayStatus: its session registry, or globalThis.__piSubagentRuns); anything else with
|
|
119
|
+
* a persisted `running` reads `interrupted`. pi-web hosts extensions in its server process, so the
|
|
120
|
+
* worker claims a slot in that map for the run — pi-web's private global, used only when pi-web
|
|
121
|
+
* created it (never created here: plain pi stays untouched, and a pi-web without it keeps the old
|
|
122
|
+
* mid-run `interrupted`). Side effects: the driver counts as having an unsettled subagent while the
|
|
123
|
+
* tool call runs (it is mid-call anyway); Stop/steer from the Agents menu still answer "not running",
|
|
124
|
+
* since pi-web holds no wrapper for this child — the driver's Stop aborts it. Returns an idempotent
|
|
125
|
+
* release that drops the slot only if it still holds this claim (pi-web's dropSubagentRun rule). */
|
|
126
|
+
export function piwebLiveClaim(sm: { getSessionId?(): string; getSessionFile?(): string | undefined } | undefined, m: WorkerSubagentMeta): (status: string) => void {
|
|
127
|
+
try {
|
|
128
|
+
const runs = (globalThis as { __piSubagentRuns?: unknown }).__piSubagentRuns;
|
|
129
|
+
const sessionId = sm?.getSessionId?.();
|
|
130
|
+
if (!(runs instanceof Map) || !sessionId) return () => {};
|
|
131
|
+
let settle: (run: unknown) => void = () => {};
|
|
132
|
+
const run = { sessionId, sessionPath: sm?.getSessionFile?.() ?? "", parentSessionId: m.parentId, parentToolCallId: m.toolCallId, profile: m.profile, description: m.description, task: m.task, runInBackground: false, status: "running", createdAt: now() };
|
|
133
|
+
const stored = { run, completion: new Promise((resolve) => { settle = resolve; }), abortRequested: false, dispatchedAt: Date.now() };
|
|
134
|
+
runs.set(sessionId, stored);
|
|
135
|
+
let released = false;
|
|
136
|
+
return (status) => {
|
|
137
|
+
if (released) return;
|
|
138
|
+
released = true;
|
|
139
|
+
try { if (runs.get(sessionId) === stored) runs.delete(sessionId); settle({ ...run, status, completedAt: now() }); } catch { /* visibility only */ }
|
|
140
|
+
};
|
|
141
|
+
} catch { return () => {}; }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The worker's display name — the Agents row and the session name: `<glyph> <slug> <what>`. The
|
|
145
|
+
* model's label often repeats the slug ("flow-list-widget review"), so the slug and stray separators
|
|
146
|
+
* are cut from it; with nothing left the op names the run. */
|
|
147
|
+
export function workerName(glyph: string, slug: string, op: string, label: unknown): string {
|
|
148
|
+
const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
149
|
+
const what = String(label ?? "").replace(/[\r\n]+/g, " ").replace(new RegExp(esc, "gi"), " ")
|
|
150
|
+
.replace(/^[\s·:|/,-]+|[\s·:|/,-]+$/g, "").replace(/\s{2,}/g, " ").slice(0, 40).trim();
|
|
151
|
+
return `${glyph} ${slug} ${what || op}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
|
|
155
|
+
* file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
|
|
156
|
+
* picker nests it under the driver, and the pi-web meta lands as the file's first data entry. */
|
|
157
|
+
export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string; subagent?: WorkerSubagentMeta }) => Promise<AgentSession> } = {
|
|
158
|
+
run: async ({ work, model, name, tools, parent, dir, subagent }) => {
|
|
159
|
+
const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
|
|
160
|
+
await loader.reload();
|
|
161
|
+
const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
|
|
162
|
+
// The meta must be stamped here — before createAgentSession appends model_change/session_info,
|
|
163
|
+
// because pi-web's scanner classifies the child only from the first data entry after the header.
|
|
164
|
+
if (sessionManager && subagent) piwebStamp(sessionManager, PIWEB_SUBAGENT.meta, piwebWorkerMeta(subagent));
|
|
165
|
+
const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
|
|
166
|
+
try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
|
|
167
|
+
try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
|
|
168
|
+
return session;
|
|
169
|
+
},
|
|
170
|
+
};
|
package/src/timeouts.ts
CHANGED
|
@@ -31,28 +31,65 @@ const GIT_NETWORK = new Set(["push", "pull", "fetch", "clone", "ls-remote", "sub
|
|
|
31
31
|
// wrappers/prefixes that never decide the class of a segment
|
|
32
32
|
const SKIP_HEADS = new Set(["cd", "export", "source", ".", "set", "unset", "if", "then", "else", "fi", "do", "done", "while", "for", "case", "esac", "{", "}", "(", "!", "test", "[[", "time", "nohup", "env", "command", "sudo"]);
|
|
33
33
|
|
|
34
|
-
/**
|
|
35
|
-
|
|
34
|
+
/** Margin over a command's own `timeout N`: the shell's timer fires first, with its own message;
|
|
35
|
+
* dev-flow's kill stays the backstop. */
|
|
36
|
+
export const WRAPPER_MARGIN_S = 15;
|
|
37
|
+
|
|
38
|
+
/** `timeout`'s options that take a value as the next token (`-s KILL`, `-k 5`). */
|
|
39
|
+
const TIMEOUT_VALUE_OPTS = new Set(["-s", "--signal", "-k", "--kill-after"]);
|
|
40
|
+
|
|
41
|
+
/** A coreutils duration (`600`, `90s`, `2m`, `1.5h`, `1d`) in seconds; null when unreadable or 0 (= no limit). */
|
|
42
|
+
function parseDuration(tok: string): number | null {
|
|
43
|
+
const m = tok.match(/^(\d+(?:\.\d+)?)([smhd]?)$/);
|
|
44
|
+
if (!m) return null;
|
|
45
|
+
const n = Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2] as "" | "s" | "m" | "h" | "d"];
|
|
46
|
+
return n > 0 ? Math.ceil(n) : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Class of one command segment: its ceiling in seconds and the class name the timeout note reports;
|
|
50
|
+
* 0 = contributes nothing (a wrapper like `cd x`). */
|
|
51
|
+
function segClass(seg: string): { s: number; cls: string } {
|
|
36
52
|
// watchers run by design until done — they get their own ceiling no matter what head they carry
|
|
37
|
-
if (/\bgh\s+run\s+watch\b/.test(seg)) return WATCH_S;
|
|
38
|
-
if (/(logs?|tail|journalctl)/.test(seg) && /(^|\s)(-f|--follow)(\s|$)/.test(seg)) return WATCH_S;
|
|
39
|
-
if (/\bcompose\b.*\bup\b/.test(seg) && !/(^|\s)(-d|--detach)(\s|$)/.test(seg)) return WATCH_S;
|
|
53
|
+
if (/\bgh\s+run\s+watch\b/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
54
|
+
if (/(logs?|tail|journalctl)/.test(seg) && /(^|\s)(-f|--follow)(\s|$)/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
55
|
+
if (/\bcompose\b.*\bup\b/.test(seg) && !/(^|\s)(-d|--detach)(\s|$)/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
40
56
|
const tok = seg.trim().split(/\s+/);
|
|
41
57
|
let i = 0;
|
|
42
58
|
while (i < tok.length && (/^[\w.]+=/.test(tok[i]) || SKIP_HEADS.has(tok[i]))) i++;
|
|
43
59
|
const base = (tok[i] ?? "").split("/").pop() ?? "";
|
|
44
|
-
if (SKIP_HEADS.has(base) || !base) return 0;
|
|
60
|
+
if (SKIP_HEADS.has(base) || !base) return { s: 0, cls: "" };
|
|
61
|
+
// `timeout N cmd`: the command already says how long it may run — honour that, plus a margin, instead
|
|
62
|
+
// of judging the segment by the head `timeout` (which fell to the 120s default and killed a
|
|
63
|
+
// `timeout 600 bun test` at two minutes). An unreadable duration falls back to the wrapped command.
|
|
64
|
+
if (base === "timeout" || base === "gtimeout") {
|
|
65
|
+
let j = i + 1;
|
|
66
|
+
while (j < tok.length && tok[j].startsWith("-")) j += TIMEOUT_VALUE_OPTS.has(tok[j]) ? 2 : 1;
|
|
67
|
+
const n = parseDuration(tok[j] ?? "");
|
|
68
|
+
if (n !== null) return { s: Math.min(n + WRAPPER_MARGIN_S, CLAMP_S), cls: `its own timeout ${tok[j]}` };
|
|
69
|
+
const inner = segClass(tok.slice(j + 1).join(" "));
|
|
70
|
+
return inner.s ? inner : { s: DEFAULT_S, cls: "default" };
|
|
71
|
+
}
|
|
45
72
|
if (base === "git") {
|
|
46
73
|
const sub = tok[i + 1] ?? "";
|
|
47
|
-
if (GIT_QUICK.has(sub)) return QUICK_S;
|
|
48
|
-
if (GIT_NETWORK.has(sub)) return NETWORK_S;
|
|
49
|
-
return LOCAL_GIT_S;
|
|
74
|
+
if (GIT_QUICK.has(sub)) return { s: QUICK_S, cls: "quick" };
|
|
75
|
+
if (GIT_NETWORK.has(sub)) return { s: NETWORK_S, cls: "network" };
|
|
76
|
+
return { s: LOCAL_GIT_S, cls: "local git" };
|
|
77
|
+
}
|
|
78
|
+
if (NETWORK.has(base)) return { s: NETWORK_S, cls: "network" };
|
|
79
|
+
if (SERVICE.has(base)) return /\bbuild\b/.test(seg) ? { s: BUILD_S, cls: "build" } : { s: SERVICE_S, cls: "service" }; // docker/compose build is an image build, not a service poke
|
|
80
|
+
if (BUILD.has(base)) return { s: BUILD_S, cls: "build" };
|
|
81
|
+
if (QUICK.has(base)) return { s: QUICK_S, cls: "quick" };
|
|
82
|
+
return { s: DEFAULT_S, cls: "default" };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The slowest segment's class — what decides a command's default timeout, and what the kill note names. */
|
|
86
|
+
export function timeoutClass(command: string): { s: number; cls: string } {
|
|
87
|
+
let best = { s: 0, cls: "" };
|
|
88
|
+
for (const seg of bashSegments(command)) {
|
|
89
|
+
const c = segClass(seg);
|
|
90
|
+
if (c.s > best.s) best = c;
|
|
50
91
|
}
|
|
51
|
-
|
|
52
|
-
if (SERVICE.has(base)) return /\bbuild\b/.test(seg) ? BUILD_S : SERVICE_S; // docker/compose build is an image build, not a service poke
|
|
53
|
-
if (BUILD.has(base)) return BUILD_S;
|
|
54
|
-
if (QUICK.has(base)) return QUICK_S;
|
|
55
|
-
return DEFAULT_S;
|
|
92
|
+
return best.s ? best : { s: DEFAULT_S, cls: "default" };
|
|
56
93
|
}
|
|
57
94
|
|
|
58
95
|
/**
|
|
@@ -61,9 +98,7 @@ function segTimeout(seg: string): number {
|
|
|
61
98
|
*/
|
|
62
99
|
export function bashTimeout(command: string, explicit?: number): number {
|
|
63
100
|
if (typeof explicit === "number" && Number.isFinite(explicit) && explicit > 0) return Math.min(explicit, CLAMP_S);
|
|
64
|
-
|
|
65
|
-
for (const seg of bashSegments(command)) t = Math.max(t, segTimeout(seg));
|
|
66
|
-
return t || DEFAULT_S;
|
|
101
|
+
return timeoutClass(command).s;
|
|
67
102
|
}
|
|
68
103
|
|
|
69
104
|
/**
|