pi-dev-flow 0.85.1 → 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 +16 -0
- package/README.md +2 -1
- package/docs/development.md +10 -0
- package/docs/gates.md +1 -1
- package/docs/guardrails.md +1 -1
- package/docs/playbook.md +17 -2
- package/extensions/dev-flow.ts +82 -2652
- package/package.json +1 -1
- package/skills/dev-flow/SKILL.md +52 -75
- 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
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
/** dev-flow runtime — Shared runtime: shell, paths, flow state, sessions and claims, skill core, compaction pacing. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
|
+
import { exec } from "node:child_process";
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { compact, SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { checklistPending, claimBlocks, classifyMergeHistory, cmpVersions, detectForge, extractSkillCore, featureBranchPrefix, healthRetry, parseMergeStyle, parseLsRemoteTags, pluginVersion, reflectItems, sessionRunsOlderBuild, listFiles, shouldSelfCompact, sq, featureTmpDir, featureTmpEnv, mainCheckoutRoot, type ReflectItem, type Config, type FeatureRef, type FlowState, type SessionClaim } from "../core.ts";
|
|
8
|
+
import { loadProject, parseProjectMd, setPlaybookKey } from "../projectmd.ts";
|
|
9
|
+
import { bashTimeout } from "../timeouts.ts";
|
|
10
|
+
import { type RunResult, type Session } from "./checks.ts";
|
|
11
|
+
import { GIT_TRACK_NOTE, isSelfRepo } from "./setup.ts";
|
|
12
|
+
|
|
13
|
+
export const execAsync = promisify(exec);
|
|
14
|
+
|
|
15
|
+
/** This build's own identity, read once at load: it is what this session's code IS — an update that
|
|
16
|
+
* rewrites the package on disk later does not change the code already running. */
|
|
17
|
+
export const SELF_BUILD = pluginVersion(import.meta.dirname);
|
|
18
|
+
|
|
19
|
+
/** The dev-flow build this session actually loaded — see sessionRunsOlderBuild. The load-time
|
|
20
|
+
* manifest, never a fresh read: re-reading the package after an in-place update reported the NEW
|
|
21
|
+
* version as loaded and the stale one as shipped (lettuce rail-ui-fixes, 0.79.0 → 0.80.0).
|
|
22
|
+
* DEV_FLOW_LOADED_VERSION (read at call time) can stand in for it (the smoke suite runs gates
|
|
23
|
+
* in-process and needs to pretend it is an old session): the override can only ever make a gate more
|
|
24
|
+
* cautious — it never lifts a proof, it turns a release into a warn-and-ask. */
|
|
25
|
+
export function loadedVersion(): string | null {
|
|
26
|
+
return process.env.DEV_FLOW_LOADED_VERSION?.trim() || SELF_BUILD.version;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The dev-flow build this session *should* be running, as the disk describes it, and how to call it.
|
|
30
|
+
* In the dev-flow repo that is the checkout's own manifest: main moves ahead of the installed copy at
|
|
31
|
+
* every release, while `loadedVersion()` and the plugin's own package.json are the same file — so a
|
|
32
|
+
* session running 0.54.0 in a checkout already at 0.58.1 compared equal and nothing anywhere said so.
|
|
33
|
+
* In a normal project the only manifest is the installed package's, which a mid-session update moves. */
|
|
34
|
+
export function checkoutBuild(root: string): { version: string | null; dir: string; repo: string; label: string } {
|
|
35
|
+
return isSelfRepo(root)
|
|
36
|
+
? { ...pluginVersion(root), label: "this checkout" }
|
|
37
|
+
: { ...pluginVersion(import.meta.dirname), label: "the dev-flow install" }; // fresh: what the disk ships NOW
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The build this session runs vs the one the disk ships: `behind` is the loaded version when they differ
|
|
41
|
+
* ("" when current or unknown), `line` the one warning every surface prints for it. */
|
|
42
|
+
export function buildSkew(root: string): { disk: ReturnType<typeof checkoutBuild>; behind: string; line: string } {
|
|
43
|
+
const disk = checkoutBuild(root);
|
|
44
|
+
const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
|
|
45
|
+
return { disk, behind, line: behind ? `this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version ?? "?"} — /reload rebinds session state; only restarting the host swaps the code it runs` : "" };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Cross-copy registry: one process can register dev-flow more than once (the documented
|
|
49
|
+
* two-sources-at-once hazard: a project dogfood pointer plus an installed copy), and EVERY copy
|
|
50
|
+
* evaluates every guard hook. The flow-tool binding belongs to whichever copy served the call,
|
|
51
|
+
* so the other copy judges from a missing binding — claims on disk (see boundFeature) keep its
|
|
52
|
+
* verdict honest, and these entries let `flow version`, `status` and `start` name the duplicate
|
|
53
|
+
* instead of leaving a misattribution a mystery. Same-process only: it is a globalThis list. */
|
|
54
|
+
export interface CopyEntry {
|
|
55
|
+
dir: string;
|
|
56
|
+
version: string | null;
|
|
57
|
+
pid: number;
|
|
58
|
+
at: string;
|
|
59
|
+
}
|
|
60
|
+
export const COPIES: CopyEntry[] = ((globalThis as { __piDevFlowCopies?: CopyEntry[] }).__piDevFlowCopies ??= []);
|
|
61
|
+
export function registerCopy(): void {
|
|
62
|
+
const mine = COPIES.find((r) => r.dir === SELF_BUILD.dir && r.pid === process.pid);
|
|
63
|
+
if (mine) Object.assign(mine, { version: loadedVersion(), at: new Date().toISOString() });
|
|
64
|
+
else COPIES.push({ dir: SELF_BUILD.dir, version: loadedVersion(), pid: process.pid, at: new Date().toISOString() });
|
|
65
|
+
}
|
|
66
|
+
export function otherCopies(): CopyEntry[] {
|
|
67
|
+
return COPIES.filter((r) => r.pid === process.pid && r.dir !== SELF_BUILD.dir);
|
|
68
|
+
}
|
|
69
|
+
/** Election: when one process runs several dev-flow copies (the documented two-sources hazard, or a
|
|
70
|
+
* copy whose loaded code predates an update), only the highest-version copy may judge — stale code
|
|
71
|
+
* must not veto tool calls with a build nobody reviewed. Node cannot unload a loaded module and pi
|
|
72
|
+
* cannot unregister its hooks, so silence is the most removal can be from inside the package; only
|
|
73
|
+
* a host restart truly drops stale code. Equal versions both judge (same code, same verdicts); a
|
|
74
|
+
* copy whose version cannot be read is never outranked. Gate tool/command handlers stay live on
|
|
75
|
+
* every copy: the host dispatches a session's flow calls to whichever copy loaded that session,
|
|
76
|
+
* and staleness there is what the /reload warnings address. */
|
|
77
|
+
export function guardsAreMine(): boolean {
|
|
78
|
+
const mine = SELF_BUILD.version;
|
|
79
|
+
if (!mine) return true; // an unreadable version is never outranked
|
|
80
|
+
return !otherCopies().some((r) => r.version && cmpVersions(r.version, mine) > 0);
|
|
81
|
+
}
|
|
82
|
+
export function copyWarning(): string | null {
|
|
83
|
+
const dup = otherCopies();
|
|
84
|
+
if (!dup.length) return null;
|
|
85
|
+
const verdict = guardsAreMine() ? "this copy is the newest and judges the guards" : "this copy is older and stays silent \u2014 the newest copy judges";
|
|
86
|
+
return `warning: ${dup.length} other dev-flow cop${dup.length === 1 ? "y" : "ies"} registered in this process: ${dup.map((d) => `${d.dir} (${d.version ?? "?"})`).join(", ")} \u2014 this call served by ${SELF_BUILD.dir} (${SELF_BUILD.version ?? "?"}); ${verdict}. Keep only one source you intend; a host restart drops stale code (README: two sources at once)`;
|
|
87
|
+
}
|
|
88
|
+
/** Test seams the runtime reads; the entry file adds the worker ones and exports the whole set. */
|
|
89
|
+
export const baseSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined }, bashTimeout: { cap: undefined as number | undefined } };
|
|
90
|
+
|
|
91
|
+
export interface Ui {
|
|
92
|
+
hasUI: boolean;
|
|
93
|
+
confirm: (title: string, message: string) => Promise<boolean>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const now = () => new Date().toISOString();
|
|
97
|
+
|
|
98
|
+
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
99
|
+
|
|
100
|
+
export async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000, env?: Record<string, string>): Promise<{ ok: boolean; out: string }> {
|
|
101
|
+
try {
|
|
102
|
+
const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) });
|
|
103
|
+
return { ok: true, out: `${stdout}\n${stderr}`.trim() };
|
|
104
|
+
} catch (e) {
|
|
105
|
+
const err = e as { stdout?: string; stderr?: string; message?: string };
|
|
106
|
+
return { ok: false, out: `${err.stdout ?? ""}\n${err.stderr ?? ""}`.trim() || String(err.message) };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** origin's URL, or null when the repo has no origin. */
|
|
111
|
+
export async function originUrl(root: string): Promise<string | null> {
|
|
112
|
+
const r = await sh("git remote get-url origin", root, 10_000);
|
|
113
|
+
return r.ok && r.out.trim() ? r.out.trim() : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The forge the release machinery targets: the playbook's `forge`, else detected from origin ("self" without one). */
|
|
117
|
+
export const forgeOf = (cfg: Config, origin: string | null): string => cfg.forge || detectForge(origin ?? "");
|
|
118
|
+
|
|
119
|
+
/** The branch's merge base with the default branch (origin's when fetched), or "" when git cannot say. */
|
|
120
|
+
export async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
|
|
121
|
+
const mb = await sh(`git merge-base origin/${sq(defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(defaultBranch)} HEAD 2>/dev/null || true`, cwd);
|
|
122
|
+
return mb.ok ? mb.out.trim() : "";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The published pi-dev-flow version (`--check-upstream`), or "" when the registry cannot be asked. */
|
|
126
|
+
export async function publishedVersion(root: string): Promise<string> {
|
|
127
|
+
const pub = await sh("npm view pi-dev-flow version", root);
|
|
128
|
+
return pub.ok ? (pub.out.trim().split("\n").pop() ?? "") : "";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const dfDir = (root: string) => path.join(root, ".dev-flow");
|
|
132
|
+
/** dev-flow is initiated once the operator playbook exists: before flow init writes project.md the
|
|
133
|
+
* extension is silent in that folder — no injections, no guards (not even the no-playbook bash-timeout
|
|
134
|
+
* default), no footer. The flow tool itself stays registered so flow init remains callable. */
|
|
135
|
+
export const initiated = (root: string): boolean => existsSync(path.join(dfDir(root), "project.md"));
|
|
136
|
+
|
|
137
|
+
/** A `--merge=squash` style flag, or null when absent. Returned as the raw string: the caller validates it
|
|
138
|
+
* with parseMergeStyle so a typo is reported instead of ignored. */
|
|
139
|
+
export function flagValue(rest: string[], name: string): string | null {
|
|
140
|
+
for (const a of rest) {
|
|
141
|
+
const m = a.match(new RegExp(`^--${name}=([\\s\\S]+)$`)); // a --brief= value spans lines
|
|
142
|
+
if (m) return m[1];
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** One cheap first-parent log tells the operator what their repo actually does when a PR merges: merge
|
|
148
|
+
* commits or one squashed commit per PR. `flow init` and `flow start` ask with this evidence instead of
|
|
149
|
+
* asking blind; null when there is no default-branch log to read. */
|
|
150
|
+
export async function mergeHistoryEvidence(root: string, defaultBranch: string): Promise<{ note: string; recent: "squash" | "merge" | "rebase" | null } | null> {
|
|
151
|
+
const log = await sh(`git log --first-parent -n 40 --format=%p|%s ${sq(`origin/${defaultBranch}`)} 2>/dev/null || git log --first-parent -n 40 --format=%p|%s ${sq(defaultBranch)} 2>/dev/null`, root);
|
|
152
|
+
if (!log.ok || !log.out.trim()) return null;
|
|
153
|
+
const c = classifyMergeHistory(log.out.split("\n"));
|
|
154
|
+
return { note: c.note, recent: c.recent };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** How the forge says the PR landed, when it can be asked — the only way to tell a squash from a rebase,
|
|
158
|
+
* because both erase the branch's ancestry. null = unaskable (self-hosted, no CLI, no merged PR found). */
|
|
159
|
+
export async function forgeMergeStyle(root: string, forge: string, branch: string): Promise<"squash" | "merge" | "rebase" | null> {
|
|
160
|
+
if (!branch) return null;
|
|
161
|
+
// sh() folds stderr into stdout, so a CLI error can arrive where the JSON was expected: parse defensively
|
|
162
|
+
const json = (out: string): unknown | null => {
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(out);
|
|
165
|
+
} catch {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
if (forge === "github") {
|
|
170
|
+
const pr = await sh(`gh pr list --state merged --head ${sq(branch)} --json number,squashCommit,rebaseCommit,mergeCommit --jq '.[0]'`, root);
|
|
171
|
+
if (!pr.ok || !pr.out.trim() || pr.out.trim() === "null") return null;
|
|
172
|
+
const parsed = json(pr.out.trim()) as { squashCommit?: string | null; rebaseCommit?: string | null; mergeCommit?: string | null } | null;
|
|
173
|
+
return parsed?.squashCommit ? "squash" : parsed?.rebaseCommit ? "rebase" : parsed?.mergeCommit ? "merge" : null;
|
|
174
|
+
}
|
|
175
|
+
if (forge === "gitlab") {
|
|
176
|
+
const mr = await sh(`glab api ${sq(`projects/:id/merge_requests?source_branch=${branch}&state=merged&per_page=1`)}`, root);
|
|
177
|
+
if (!mr.ok || !mr.out.trim() || mr.out.trim() === "[]") return null;
|
|
178
|
+
const list = json(mr.out.trim()) as { squash_commit_sha?: string | null; merge_commit_sha?: string | null }[] | null;
|
|
179
|
+
const parsed = Array.isArray(list) ? list[0] : null;
|
|
180
|
+
return parsed?.squash_commit_sha ? "squash" : parsed?.merge_commit_sha ? "merge" : null;
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Write the merge policy into the playbook with a single-line insert — never a draft regeneration, which
|
|
187
|
+
* cannot reproduce hand-written prose and checklist items and would drop them. Validated before it is
|
|
188
|
+
* written and kept as `.bak`, exactly like `flow init --write`. The commit is the playbook chore the guard
|
|
189
|
+
* already blesses, and only when the playbook is the only dirty path: a gate never sweeps someone else's
|
|
190
|
+
* work into a chore commit.
|
|
191
|
+
*/
|
|
192
|
+
export async function writePlaybookMergePolicy(root: string, style: string): Promise<{ note: string } | { err: string }> {
|
|
193
|
+
const mdFile = path.join(dfDir(root), "project.md");
|
|
194
|
+
if (!existsSync(mdFile)) return { err: "no .dev-flow/project.md to write the policy into — run flow init first" };
|
|
195
|
+
const ins = setPlaybookKey(readFileSync(mdFile, "utf8"), "release", "merge", style);
|
|
196
|
+
if ("error" in ins) return { err: ins.error };
|
|
197
|
+
const parsed = parseProjectMd(ins.text);
|
|
198
|
+
if (parsed.hard.length) return { err: `refusing to write project.md — the result would not parse:\n- ${parsed.hard.join("\n- ")}` };
|
|
199
|
+
copyFileSync(mdFile, `${mdFile}.bak`);
|
|
200
|
+
writeFileSync(mdFile, ins.text);
|
|
201
|
+
const dirty = await sh("git status --porcelain", root);
|
|
202
|
+
const onlyPlaybook = dirty.ok && dirty.out.trim().split("\n").every((l) => l.trim().endsWith(" .dev-flow/project.md"));
|
|
203
|
+
const tracked = (await sh("git ls-files --error-unmatch .dev-flow/project.md", root)).ok;
|
|
204
|
+
let note = `merge = ${style} written to .dev-flow/project.md (${ins.where}; previous copy kept as project.md.bak)`;
|
|
205
|
+
if (tracked && onlyPlaybook) {
|
|
206
|
+
const commit = await sh(`git add .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(`playbook: merge policy = ${style}`)}`, root);
|
|
207
|
+
note += commit.ok ? " — committed as a playbook chore" : ` — commit failed (${tail(commit.out)}); commit it yourself`;
|
|
208
|
+
} else note += `. ${GIT_TRACK_NOTE}`;
|
|
209
|
+
return { note };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Run the health probe with the playbook's wait budget (#42). A service whose readiness lags its
|
|
214
|
+
* container start can never pass a single shot, and hand-writing a poll loop into every playbook was
|
|
215
|
+
* the workaround; the gate waits and says how long it tried. Attempts/schedule: core.healthRetry.
|
|
216
|
+
*/
|
|
217
|
+
export async function runHealthProbe(cmd: string, cwd: string, waitSec: number, env?: Record<string, string>): Promise<{ ok: boolean; out: string; attempts: number }> {
|
|
218
|
+
const { attempts, delayMs } = healthRetry(waitSec);
|
|
219
|
+
const deadline = Date.now() + waitSec * 1000; // the budget is wall time: a slow probe must not multiply it by its own duration
|
|
220
|
+
let res = { ok: false, out: "" };
|
|
221
|
+
for (let i = 1; ; i++) {
|
|
222
|
+
res = await sh(cmd, cwd, undefined, env);
|
|
223
|
+
if (res.ok || i >= attempts || Date.now() >= deadline) return { ...res, attempts: i };
|
|
224
|
+
await sleep(delayMs);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Tags to judge a release against: what origin holds — a clone that has not fetched must not get to
|
|
229
|
+
* decide what is already tagged (#52). Local tags only when there is no remote to ask; null when an
|
|
230
|
+
* origin exists but could not be asked (offline, no ssh agent) — then local tags must not stand in. */
|
|
231
|
+
export async function releaseTags(root: string): Promise<string[] | null> {
|
|
232
|
+
if (!(await originUrl(root))) return (await sh("git tag --sort=-creatordate", root)).out.split("\n").filter(Boolean);
|
|
233
|
+
const remote = await sh("git ls-remote --tags origin", root);
|
|
234
|
+
if (!remote.ok) return null;
|
|
235
|
+
return parseLsRemoteTags(remote.out);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export const GATE_HELP =
|
|
239
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
240
|
+
export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
241
|
+
export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
242
|
+
export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
243
|
+
|
|
244
|
+
export function readState(root: string, slug: string): FlowState | null {
|
|
245
|
+
try {
|
|
246
|
+
return JSON.parse(readFileSync(stateFile(root, slug), "utf8")) as FlowState;
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function writeState(root: string, state: FlowState): void {
|
|
253
|
+
atomicWrite(stateFile(root, state.slug), `${JSON.stringify(state, null, "\t")}\n`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Count one refusal or guard block against the session's bound feature (best effort, never throws). */
|
|
257
|
+
export function noteFriction(root: string, key: string): void {
|
|
258
|
+
try {
|
|
259
|
+
const st = boundFeature(root, key);
|
|
260
|
+
if (!st) return;
|
|
261
|
+
st.friction = (st.friction ?? 0) + 1;
|
|
262
|
+
writeState(root, st);
|
|
263
|
+
} catch {
|
|
264
|
+
/* a counter must never fail the call it watches */
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Replace a file in one move. Gates write state after every check, and a kill in the middle left a
|
|
269
|
+
* truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
|
|
270
|
+
* and every recorded check, with the folder gitignored so nothing else could restore it. */
|
|
271
|
+
export function atomicWrite(file: string, text: string): void {
|
|
272
|
+
const tmp = `${file}.tmp`;
|
|
273
|
+
writeFileSync(tmp, text);
|
|
274
|
+
renameSync(tmp, file);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Session bindings: one flow per pi session; persisted per session branch via appendEntry.
|
|
278
|
+
* Module-level means shared by every session in the process — pi runs many sessions inside one Node
|
|
279
|
+
* process (pi-web's agent lives in the server) — so every key here is a session identity and every
|
|
280
|
+
* entry is released when that session ends (see releaseSession). */
|
|
281
|
+
export const bindings = new Map<string, string | null>();
|
|
282
|
+
// Two identities are possible: pi's session id, or — when the host hands out none — the working
|
|
283
|
+
// directory. Both are prefixed, because a claim written under the directory identity is not a session:
|
|
284
|
+
// two pi sessions sharing one directory share that key, and `cwd:` in a claim file says so out loud
|
|
285
|
+
// instead of reading like a session that went missing.
|
|
286
|
+
export const sessionKey = (ctx: { cwd: string; sessionManager?: { getSessionId(): string } }): string =>
|
|
287
|
+
ctx.sessionManager?.getSessionId() ? `sid:${ctx.sessionManager.getSessionId()}` : `cwd:${ctx.cwd}`;
|
|
288
|
+
/** Sessions with a dev-flow-initiated compaction in flight (prevents stacked compactions). */
|
|
289
|
+
export const compacting = new Set<string>();
|
|
290
|
+
/** Sessions that already received the skill's always-on core this session. The `dev-flow-skill`
|
|
291
|
+
* entry records the injection in the session branch, so /reload, resume and fork restore the fact
|
|
292
|
+
* instead of paying ~1k tokens a second time. */
|
|
293
|
+
export const coreInjected = new Set<string>();
|
|
294
|
+
/** Sessions whose last compaction dropped the core out of context — the next run pays it once more. */
|
|
295
|
+
export const coreStale = new Set<string>();
|
|
296
|
+
/** The last stage context each session was handed. The context rides a hidden message on every run, and
|
|
297
|
+
* a long session at one stage used to carry the same ~200-word note dozens of times: an unchanged one
|
|
298
|
+
* is now one line. Cleared by a compaction (the summary may have dropped it) and by a reload. */
|
|
299
|
+
export const lastContext = new Map<string, string>();
|
|
300
|
+
/** The skill dir of THIS loaded copy: the copy a session runs and a development checkout can be
|
|
301
|
+
* different installs, so playbook paths resolve from the code actually loaded — never from cwd. */
|
|
302
|
+
export const SKILL_DIR = path.join(import.meta.dirname, "..", "..", "skills", "dev-flow");
|
|
303
|
+
export let skillCoreCache: string | null | undefined;
|
|
304
|
+
/** The core block between SKILL.md's markers, read once per process (/reload reloads the module
|
|
305
|
+
* and picks up edits). Null — no file, no markers, empty core — leaves every message exactly as it
|
|
306
|
+
* was: a copy shipped without its skill must not take the guards, or the run, down. */
|
|
307
|
+
export function skillCore(): string | null {
|
|
308
|
+
// Seam first: a test cannot ship a copy of the package with its skills/ directory deleted.
|
|
309
|
+
if (baseSeams.skillCore.value !== undefined) return baseSeams.skillCore.value;
|
|
310
|
+
if (skillCoreCache === undefined) {
|
|
311
|
+
try {
|
|
312
|
+
skillCoreCache = extractSkillCore(readFileSync(path.join(SKILL_DIR, "SKILL.md"), "utf8"));
|
|
313
|
+
} catch {
|
|
314
|
+
skillCoreCache = null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return skillCoreCache;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Seam for the takeover's summarize call (pi's own compact()); tests replace `.run` — mutable object stands in for ESM mocking. */
|
|
321
|
+
export const compactionTakeover: { run: typeof compact } = { run: compact };
|
|
322
|
+
|
|
323
|
+
/** Marks the before_agent_start pass that already wrote this run's [dev-flow] line — see the claim in that handler. */
|
|
324
|
+
export const CONTEXT_EMITTED = Symbol.for("pi-dev-flow.context-emitted");
|
|
325
|
+
|
|
326
|
+
/** Every feature with a state file — finish deletes the state, so whatever is on disk is unfinished. */
|
|
327
|
+
export function unfinishedStates(root: string): FlowState[] {
|
|
328
|
+
if (!existsSync(dfDir(root))) return [];
|
|
329
|
+
return readdirSync(dfDir(root), { withFileTypes: true })
|
|
330
|
+
.filter((d) => d.isDirectory())
|
|
331
|
+
.map((d) => readState(root, d.name))
|
|
332
|
+
.filter((s): s is FlowState => !!s);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Open items of the agent's suggestion queue (.dev-flow/reflections.md), each with its section. */
|
|
336
|
+
export const readReflections = (root: string): ReflectItem[] => {
|
|
337
|
+
const f = path.join(dfDir(root), "reflections.md");
|
|
338
|
+
return existsSync(f) ? reflectItems(readFileSync(f, "utf8")) : [];
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
/** Raw reflections.md content — the closed-item count needs the checked lines the open-only reader drops. */
|
|
342
|
+
export const readReflectionsText = (root: string): string => {
|
|
343
|
+
const f = path.join(dfDir(root), "reflections.md");
|
|
344
|
+
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
export const roadmapFile = (root: string) => path.join(dfDir(root), "roadmap.md");
|
|
348
|
+
export const readRoadmap = (root: string): string => {
|
|
349
|
+
const f = roadmapFile(root);
|
|
350
|
+
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
/** The session's feature — explicit bindings only: flow start/flow use bind, resume restores from session
|
|
354
|
+
* history. Never binds on its own: an unbound session stays unbound however few features are unfinished,
|
|
355
|
+
* and reading it must never claim anything. The claim on disk IS the persisted binding — bind() stamps the
|
|
356
|
+
* session key into claim.json — so trust the disk after the in-memory map: a second registered dev-flow
|
|
357
|
+
* copy (both copies evaluate the guard hooks) or a re-instantiated module then attributes the session's
|
|
358
|
+
* own feature from disk instead of misjudging with stage null. */
|
|
359
|
+
export function boundFeature(root: string, key: string): FlowState | null {
|
|
360
|
+
const bound = bindings.get(key);
|
|
361
|
+
if (bound) {
|
|
362
|
+
const s = readState(root, bound);
|
|
363
|
+
if (s) return s;
|
|
364
|
+
}
|
|
365
|
+
return unfinishedStates(root).find((s) => readClaim(root, s.slug)?.key === key) ?? null;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function readClaim(root: string, slug: string): SessionClaim | null {
|
|
369
|
+
try {
|
|
370
|
+
return JSON.parse(readFileSync(claimFile(root, slug), "utf8")) as SessionClaim;
|
|
371
|
+
} catch {
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const writeClaim = (root: string, slug: string, key: string) =>
|
|
377
|
+
atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
|
|
378
|
+
|
|
379
|
+
/** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
|
|
380
|
+
* never dies, so a claim left behind by a finished session keeps refusing every later session with
|
|
381
|
+
* "claimed by another live session" — the lock has to end with the session that wrote it. Idempotent:
|
|
382
|
+
* shutdown, reload and process exit can converge on this path. */
|
|
383
|
+
export function releaseSession(root: string, key: string): void {
|
|
384
|
+
bindings.delete(key);
|
|
385
|
+
compacting.delete(key);
|
|
386
|
+
coreInjected.delete(key);
|
|
387
|
+
coreStale.delete(key);
|
|
388
|
+
if (!existsSync(dfDir(root))) return;
|
|
389
|
+
for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
|
|
390
|
+
if (!d.isDirectory()) continue;
|
|
391
|
+
if (readClaim(root, d.name)?.key === key) rmSync(claimFile(root, d.name), { force: true });
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** A lone unfinished feature another live session holds — lets the unbound-context message name it and offer the explicit takeover. */
|
|
396
|
+
export function claimBlocker(root: string, key: string): { state: FlowState; claim: SessionClaim } | null {
|
|
397
|
+
const un = unfinishedStates(root);
|
|
398
|
+
if (un.length !== 1) return null;
|
|
399
|
+
const claim = readClaim(root, un[0].slug);
|
|
400
|
+
return claim && claimBlocks(claim, key) ? { state: un[0], claim } : null;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Flow-aware focus for any compaction dev-flow initiates — state lives on disk, the summary must not invent it. */
|
|
404
|
+
export const flowCompactInstructions = (st: FlowState) =>
|
|
405
|
+
`dev-flow feature "${st.slug}", stage "${st.stage}" — flow state is persisted on disk (state.json, plan/). Preserve verbatim: operator answers not yet recorded by a gate, reasons for uncommitted changes, and the exact next action from the last exchange.`;
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Flow-aware self-compaction at safe points: called after a successful gate (state just hit disk),
|
|
409
|
+
* at every turn_end and when a run settles. Only fires within COMPACT_MARGIN of pi's own threshold
|
|
410
|
+
* (computed with the *effective* reserveTokens — settings + model overrides, like pi does) and
|
|
411
|
+
* never while chat-only state is pending (open dialog, undigested plan) — see shouldSelfCompact.
|
|
412
|
+
*/
|
|
413
|
+
export function maybeCompactNow(ctx: ExtensionContext, root: string): void {
|
|
414
|
+
if (!initiated(root)) return;
|
|
415
|
+
const u = ctx.getContextUsage?.(); // minimal/fake contexts may lack usage info — treat as unknown
|
|
416
|
+
if (!u || u.tokens === null) return;
|
|
417
|
+
const key = sessionKey(ctx);
|
|
418
|
+
const st = boundFeature(root, key);
|
|
419
|
+
if (!st) return;
|
|
420
|
+
let reserve: number;
|
|
421
|
+
try {
|
|
422
|
+
const settings = SettingsManager.create(ctx.cwd); // throws on a malformed compaction setting — pi surfaces that itself; we just stay out
|
|
423
|
+
if (!settings.getCompactionEnabled()) return; // operator turned auto-compaction off — don't do it behind their back
|
|
424
|
+
reserve = settings.getCompactionReserveTokens(ctx.model);
|
|
425
|
+
} catch {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const cfg = loadProject(dfDir(root)).cfg;
|
|
429
|
+
const decision = {
|
|
430
|
+
tokens: u.tokens,
|
|
431
|
+
contextWindow: u.contextWindow,
|
|
432
|
+
stage: st.stage,
|
|
433
|
+
planFiles: listFiles(path.join(featDir(root, st.slug), "plan")).length,
|
|
434
|
+
checklistPending: checklistPending(cfg, st, st.stage),
|
|
435
|
+
compacting: compacting.has(key),
|
|
436
|
+
};
|
|
437
|
+
if (!shouldSelfCompact(decision, reserve)) return;
|
|
438
|
+
compacting.add(key);
|
|
439
|
+
const done = () => compacting.delete(key);
|
|
440
|
+
try {
|
|
441
|
+
ctx.compact({ customInstructions: flowCompactInstructions(st), onComplete: done, onError: done });
|
|
442
|
+
} catch {
|
|
443
|
+
done(); // a throw before the run started must not leave the flag set: that switched off self-compaction and the takeover for the rest of the session
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function featureRefs(root: string): FeatureRef[] {
|
|
448
|
+
return unfinishedStates(root).map((s) => ({ state: s, worktreeAbs: s.worktree ? path.resolve(root, s.worktree) : null }));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function worktreeAbs(root: string, state: FlowState): string | null {
|
|
452
|
+
return state.worktree ? path.resolve(root, state.worktree) : null;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Git-level consistency probes for the doctor: orphan worktrees/branches, features missing their worktree. */
|
|
456
|
+
export async function gitConsistency(root: string, cfg: Config): Promise<string[]> {
|
|
457
|
+
const feats = unfinishedStates(root);
|
|
458
|
+
const out: string[] = [];
|
|
459
|
+
const wtRoot = path.resolve(root, cfg.worktreeDir.split("{")[0]);
|
|
460
|
+
const owned = new Set(feats.map((f) => (f.worktree ? path.resolve(root, f.worktree) : "")));
|
|
461
|
+
const wtRaw = await sh("git worktree list --porcelain", root);
|
|
462
|
+
if (wtRaw.ok)
|
|
463
|
+
for (const line of wtRaw.out.split("\n")) {
|
|
464
|
+
if (!line.startsWith("worktree ")) continue;
|
|
465
|
+
const abs = path.resolve(line.slice(9).trim());
|
|
466
|
+
if (abs !== path.resolve(root) && abs.startsWith(wtRoot) && !owned.has(abs)) out.push(`orphan worktree ${path.relative(root, abs)} — no feature owns it (git worktree remove)`);
|
|
467
|
+
}
|
|
468
|
+
const ownedBr = new Set(feats.map((f) => f.branch));
|
|
469
|
+
const brRaw = await sh(`git branch --list ${sq(`${featureBranchPrefix(cfg)}*`)}`, root);
|
|
470
|
+
if (brRaw.ok)
|
|
471
|
+
// git marks the current branch with "* " and a worktree-checked-out one with "+ " — strip both, or an active feature's own branch never matches ownedBr
|
|
472
|
+
for (const b of brRaw.out.split("\n").map((x) => x.replace(/^[*+]?\s+/, "").trim()).filter(Boolean)) {
|
|
473
|
+
if (!ownedBr.has(b)) out.push(`orphan branch ${b} — no unfinished feature owns it (git branch -D ${b})`);
|
|
474
|
+
}
|
|
475
|
+
// an aborted feature is a designed state, not drift: the abort echo tells the operator to remove
|
|
476
|
+
// the worktree by hand, and the stamp keeps that cleanup from being re-reported forever (gh#138)
|
|
477
|
+
for (const f of feats) if (f.worktree && !f.aborted && !existsSync(path.resolve(root, f.worktree))) out.push(`feature ${f.slug} (${f.stage}) has no worktree at ${f.worktree}`);
|
|
478
|
+
// the playbook belongs in git — an untracked project.md is invisible to teammates and lost on machine changes
|
|
479
|
+
if (existsSync(path.join(root, ".dev-flow", "project.md")) && !(await sh("git ls-files --error-unmatch -- .dev-flow/project.md", root)).ok)
|
|
480
|
+
out.push('.dev-flow/project.md is not tracked in git — track it: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force: a root .gitignore may exclude .dev-flow/ wholesale; the env prefix is for the installed hook — dev-flow allows a main commit whose only change is the playbook)');
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Where feature commands run: the feature worktree once it exists (that is where the
|
|
485
|
+
* code under test lives), else the main checkout. Keeps gates off the main branch. */
|
|
486
|
+
export function gateCwd(root: string, state: FlowState): string {
|
|
487
|
+
const wt = worktreeAbs(root, state);
|
|
488
|
+
return wt && existsSync(wt) ? wt : root;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** TMPDIR for the project commands a gate runs: the feature's own scratch dir, removed at finish —
|
|
492
|
+
* a test suite's mkdtemp fixtures no longer pile up in the OS temp dir. */
|
|
493
|
+
export function featureEnv(root: string, state: FlowState): Record<string, string> {
|
|
494
|
+
const dir = featureTmpDir(dfDir(root), state.slug);
|
|
495
|
+
mkdirSync(dir, { recursive: true });
|
|
496
|
+
return featureTmpEnv(dir);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** Per-cwd cache of the main checkout a linked worktree belongs to (null = not a linked worktree) —
|
|
500
|
+
* every hook resolves its root through flowRoot, so git is asked once per directory. */
|
|
501
|
+
export const mainCheckoutCache = new Map<string, string | null>();
|
|
502
|
+
|
|
503
|
+
/** The root whose .dev-flow/ is the flow truth for a session cwd. A feature worktree is a linked git
|
|
504
|
+
* worktree whose tracked .dev-flow/ holds only project.md — state, claims and plans live in the main
|
|
505
|
+
* checkout. Judging a session by its own cwd found no features and every guard answered "no active
|
|
506
|
+
* flow". So a linked worktree resolves to its main checkout when that checkout is initiated. */
|
|
507
|
+
export async function flowRoot(cwd: string): Promise<string> {
|
|
508
|
+
if (!mainCheckoutCache.has(cwd)) {
|
|
509
|
+
const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", cwd);
|
|
510
|
+
const [gitDir, common] = r.ok ? r.out.split("\n").map((l) => l.trim()) : [];
|
|
511
|
+
const linked = !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
|
|
512
|
+
mainCheckoutCache.set(cwd, linked ? mainCheckoutRoot(cwd, common) : null);
|
|
513
|
+
}
|
|
514
|
+
const main = mainCheckoutCache.get(cwd);
|
|
515
|
+
return main && initiated(main) ? main : cwd;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export async function currentBranch(root: string): Promise<string> {
|
|
519
|
+
const r = await sh("git branch --show-current", root);
|
|
520
|
+
return r.ok ? r.out.split("\n")[0] : "";
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export function needState(root: string, sess: Session, slugArg?: string): { state: FlowState | null; err?: RunResult } {
|
|
524
|
+
// no implicit feature: gates run on this session's binding or an explicit slug — never on "the one
|
|
525
|
+
// feature left", which is how an unbound session would end up steering a flow it never took
|
|
526
|
+
const slug = slugArg ?? sess.slug;
|
|
527
|
+
if (!slug) {
|
|
528
|
+
const un = unfinishedStates(root);
|
|
529
|
+
if (!un.length) return { state: null, err: { text: "no unfinished features — flow start <slug> [--ui]", isError: true } };
|
|
530
|
+
return { state: null, err: { text: `nothing bound — flow use <slug> or pass an explicit slug (unfinished: ${un.map((s) => s.slug).join(", ")})`, isError: true } };
|
|
531
|
+
}
|
|
532
|
+
const state = readState(root, slug);
|
|
533
|
+
if (!state) return { state: null, err: { text: `no state for feature ${slug}`, isError: true } };
|
|
534
|
+
// passing a slug is not a takeover: a live session that holds the claim drives its gates, or the two
|
|
535
|
+
// sessions overwrite one state file (last write wins) while both believe they own the stage.
|
|
536
|
+
const claim = readClaim(root, slug);
|
|
537
|
+
if (sess.slug !== slug && claimBlocks(claim, sess.key))
|
|
538
|
+
return { state: null, err: { text: `${slug} is claimed by another live session (pid ${claim!.pid}) — flow use ${slug} takes it over explicitly`, isError: true } };
|
|
539
|
+
return { state };
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function tail(out: string, n = 15): string {
|
|
543
|
+
const lines = out.split("\n").filter(Boolean);
|
|
544
|
+
return lines.length > n ? `…(${lines.length - n} lines)…\n${lines.slice(-n).join("\n")}` : out;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ------------------------------------------------------------------ extension
|
|
548
|
+
|
|
549
|
+
/** The pi-web chip's current key, per session: the chip's label IS the widget key, so it changes with the
|
|
550
|
+
* footer text and the previous one must be cleared on every repaint. Per session, not per process — one
|
|
551
|
+
* pi-web server repaints many sessions (drivers, chats, workers), and a single shared slot let session B's
|
|
552
|
+
* repaint overwrite A's key, so A's next repaint cleared a key A never had and left its old chip beside
|
|
553
|
+
* the new one. On globalThis so a /reload or a duplicate copy still knows the chip already painted. */
|
|
554
|
+
export const WEB_CHIP_KEYS: Map<string, string> = ((globalThis as { __piDevFlowChipKeys?: Map<string, string> }).__piDevFlowChipKeys ??= new Map());
|