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,358 @@
|
|
|
1
|
+
/** dev-flow runtime — Dev deploy, health probes, tier-1 checks and branch facts. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
|
+
import { existsSync, readFileSync, statfsSync } from "node:fs";
|
|
3
|
+
import { createServer } from "node:net";
|
|
4
|
+
import { freemem } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { checkFingerprint, DEFAULTS, freshenChecks, healthProbe, listFiles, needsOperator, newestTaggedVersion, parseVersion, sq, validSlug, formatSize, sideBySide, type BranchState, type Config, type DevSlot, type FlowState, type StageCheck } from "../core.ts";
|
|
7
|
+
import { loadProject } from "../projectmd.ts";
|
|
8
|
+
import { agentText, presentGate, type GateView, type StageFacts } from "../present.ts";
|
|
9
|
+
import { atomicWrite, boundFeature, dfDir, featDir, featureEnv, flagValue, gateCwd, initiated, mergeBase, now, originUrl, readState, runHealthProbe, sh, tail, worktreeAbs, writeState } from "./base.ts";
|
|
10
|
+
import { type GateCtx } from "./gates.ts";
|
|
11
|
+
|
|
12
|
+
/** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
|
|
13
|
+
export const devPortOf = (state: FlowState, cfg: Config): number | undefined => state.devPort ?? cfg.devPort;
|
|
14
|
+
|
|
15
|
+
/** featureEnv plus where this flow's dev instance lives: $DEV_FLOW_PORT, $DEV_FLOW_INSTANCE (the slug) and
|
|
16
|
+
* $DEV_FLOW_SUFFIX — "" on the default port, "-<slug>" on another — for a compose project name or container
|
|
17
|
+
* prefix that must not collide with the instance already running. */
|
|
18
|
+
export function devEnv(root: string, state: FlowState, cfg: Config): Record<string, string> {
|
|
19
|
+
const port = devPortOf(state, cfg);
|
|
20
|
+
const side = state.devPort !== undefined && state.devPort !== cfg.devPort;
|
|
21
|
+
return { ...featureEnv(root, state), ...(port !== undefined ? { DEV_FLOW_PORT: String(port) } : {}), DEV_FLOW_INSTANCE: state.slug, DEV_FLOW_SUFFIX: side ? `-${state.slug}` : "" };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------- dev stack registry
|
|
25
|
+
// One machine, one dev port, several flows: who deployed last is what decides whether a verify may
|
|
26
|
+
// redeploy there or must ask first. Keyed by port ("default" when the playbook names none).
|
|
27
|
+
export const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.json");
|
|
28
|
+
export const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
|
|
29
|
+
|
|
30
|
+
/** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
|
|
31
|
+
export function readDevPorts(root: string): Record<string, DevSlot> {
|
|
32
|
+
let raw: Record<string, DevSlot>;
|
|
33
|
+
try {
|
|
34
|
+
raw = JSON.parse(readFileSync(devPortsFile(root), "utf8")) as Record<string, DevSlot>;
|
|
35
|
+
} catch {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
return Object.fromEntries(
|
|
39
|
+
Object.entries(raw).filter(([, v]) => {
|
|
40
|
+
const st = v?.slug ? readState(root, v.slug) : null;
|
|
41
|
+
return !!st && !st.aborted;
|
|
42
|
+
}),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function writeDevPorts(root: string, reg: Record<string, DevSlot>): void {
|
|
47
|
+
atomicWrite(devPortsFile(root), `${JSON.stringify(reg, null, "\t")}\n`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function portFree(port: number): Promise<boolean> {
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
const srv = createServer();
|
|
53
|
+
srv.once("error", () => resolve(false));
|
|
54
|
+
srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function nextFreePort(from: number, taken: Set<number>): Promise<number | null> {
|
|
59
|
+
for (let p = from + 1; p < Math.min(from + 50, 65536); p++) if (!taken.has(p) && (await portFree(p))) return p;
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** MemAvailable (what a new process can really get) where Linux reports it, else the OS free figure. */
|
|
64
|
+
export function memAvailable(): number | null {
|
|
65
|
+
try {
|
|
66
|
+
const m = readFileSync("/proc/meminfo", "utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);
|
|
67
|
+
if (m) return Number(m[1]) * 1024;
|
|
68
|
+
} catch {
|
|
69
|
+
/* not Linux */
|
|
70
|
+
}
|
|
71
|
+
const f = freemem();
|
|
72
|
+
return Number.isFinite(f) ? f : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function diskFreeAt(dir: string): number | null {
|
|
76
|
+
try {
|
|
77
|
+
const st = statfsSync(dir);
|
|
78
|
+
return Number(st.bavail) * Number(st.bsize);
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function ago(iso: string): string {
|
|
85
|
+
const min = Math.round((Date.now() - Date.parse(iso)) / 60_000);
|
|
86
|
+
if (!Number.isFinite(min)) return "at an unknown time";
|
|
87
|
+
return min < 1 ? "just now" : min < 90 ? `${min} min ago` : `${Math.round(min / 60)} h ago`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const portLabel = (port: number | undefined) => (port === undefined ? "the dev stack" : `port ${port}`);
|
|
91
|
+
|
|
92
|
+
/** Before a verify deploys: is the stack it would replace held by another live flow? Applies the
|
|
93
|
+
* operator's `--port=<n>` / `--replace` answer, or asks — with the measured resources — which to do. */
|
|
94
|
+
export async function devSlotCheck(o: GateCtx, state: FlowState): Promise<RunResult | { note: string }> {
|
|
95
|
+
const { root, cfg, flag, rest } = o;
|
|
96
|
+
const portArg = flagValue(rest, "port");
|
|
97
|
+
if (portArg !== null) {
|
|
98
|
+
const n = Number(portArg);
|
|
99
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) return { text: `--port=${portArg} is not a port`, isError: true };
|
|
100
|
+
if (cfg.devPort === undefined) return { text: "--port needs a default `port` in the playbook's ## implement flow block — dev-flow exports the chosen one to dev/health as $DEV_FLOW_PORT", isError: true };
|
|
101
|
+
if (n === cfg.devPort) delete state.devPort;
|
|
102
|
+
else state.devPort = n;
|
|
103
|
+
writeState(root, state);
|
|
104
|
+
}
|
|
105
|
+
const port = devPortOf(state, cfg);
|
|
106
|
+
const reg = readDevPorts(root);
|
|
107
|
+
const slot = reg[slotKey(port)];
|
|
108
|
+
if (!slot || slot.slug === state.slug) return { note: "" };
|
|
109
|
+
if (flag("replace")) return { note: `dev: replaced ${slot.slug}'s deploy on ${portLabel(port)} (operator's answer)` };
|
|
110
|
+
const other = readState(root, slot.slug);
|
|
111
|
+
const taken = new Set(Object.keys(reg).map(Number).filter(Number.isFinite));
|
|
112
|
+
const nextPort = port !== undefined ? await nextFreePort(port, taken) : null;
|
|
113
|
+
const mem = memAvailable();
|
|
114
|
+
const disk = diskFreeAt(root);
|
|
115
|
+
const side = sideBySide({ cfg, nextPort, memAvail: mem, diskFree: disk });
|
|
116
|
+
const res = [
|
|
117
|
+
`RAM available ${mem !== null ? formatSize(mem) : "unknown"}${cfg.instanceMem !== undefined ? ` (one instance needs ${formatSize(cfg.instanceMem)})` : ""}`,
|
|
118
|
+
`disk free ${disk !== null ? formatSize(disk) : "unknown"}${cfg.instanceDisk !== undefined ? ` (one instance needs ${formatSize(cfg.instanceDisk)})` : ""}`,
|
|
119
|
+
].join(", ");
|
|
120
|
+
const caveat = side.ok
|
|
121
|
+
? cfg.parallelDev === undefined
|
|
122
|
+
? " The playbook does not say whether two instances can share this machine (parallelDev = yes|no) — tell the operator that when you ask."
|
|
123
|
+
: ""
|
|
124
|
+
: ` Running alongside is not offered: ${side.why.join("; ")}.`;
|
|
125
|
+
const opts = [
|
|
126
|
+
...(side.ok ? [`run alongside on port ${nextPort}: flow verify --port=${nextPort}`] : []),
|
|
127
|
+
`replace ${slot.slug}'s deploy: flow verify --replace`,
|
|
128
|
+
`wait until ${slot.slug} is done with it`,
|
|
129
|
+
];
|
|
130
|
+
const held = `${portLabel(port)} is serving ${slot.slug} (stage ${other?.stage ?? "?"}${other?.pendingAsk ? `, waiting on ${other.pendingAsk}` : ""}, ${slot.head.slice(0, 7)}, deployed ${ago(slot.at)})`;
|
|
131
|
+
return { text: needsOperator(`${held} — this verify would replace it. Resources: ${res}.${caveat} Ask the operator which: ${opts.join(" | ")} — nothing was built or deployed yet.`, "Dev port?"), isError: true };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Before a review deploy: bring the branch up to date with the default branch, so the operator reviews
|
|
135
|
+
* the tree that will ship. Rebases a clean branch that is behind; refuses on a conflict (aborted, branch
|
|
136
|
+
* untouched) or on uncommitted work. With the operator's answer in hand (--confirmed) it never rewrites
|
|
137
|
+
* history: a default branch that moved since the review deploy sends the flow back to `flow verify`. */
|
|
138
|
+
export async function catchUp(root: string, state: FlowState, cfg: Config, confirmed: boolean): Promise<RunResult | { note: string }> {
|
|
139
|
+
const cwd = gateCwd(root, state);
|
|
140
|
+
if (cwd === root) return { note: "" };
|
|
141
|
+
const d = cfg.defaultBranch;
|
|
142
|
+
const hasOrigin = !!(await originUrl(root));
|
|
143
|
+
let fetchNote = "";
|
|
144
|
+
if (hasOrigin && !(await sh(`git fetch -q origin ${sq(d)}`, cwd, 60_000)).ok) fetchNote = ` (fetch of origin/${d} failed — compared with the last fetched state)`;
|
|
145
|
+
const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
|
|
146
|
+
const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
|
|
147
|
+
const behind = Number.parseInt(r.out.trim(), 10);
|
|
148
|
+
if (!r.ok || !Number.isFinite(behind)) return { note: `behind ${base}: unknown${fetchNote}` };
|
|
149
|
+
if (behind === 0) return { note: fetchNote ? `up to date with ${base}${fetchNote}` : "" };
|
|
150
|
+
if (confirmed)
|
|
151
|
+
return { text: `verify gate FAILED:\n- ${base} moved ${behind} commit(s) past this branch — the operator's answer would cover a tree that is not the one that ships. Run flow verify (it rebases and redeploys for review), then ask Verified? again`, isError: true };
|
|
152
|
+
// untracked build output (a deploy's artifacts) does not stop a rebase; uncommitted tracked edits do
|
|
153
|
+
const dirty = await sh("git status --porcelain --untracked-files=no", cwd);
|
|
154
|
+
if (dirty.ok && dirty.out.trim()) return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and has uncommitted changes — commit them, then re-run flow verify (it rebases before the review deploy)`, isError: true };
|
|
155
|
+
const rb = await sh(`git rebase ${sq(base)}`, cwd, 120_000);
|
|
156
|
+
if (!rb.ok) {
|
|
157
|
+
const conflicts = (await sh("git diff --name-only --diff-filter=U", cwd)).out.split("\n").filter(Boolean);
|
|
158
|
+
await sh("git rebase --abort", cwd);
|
|
159
|
+
return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and the rebase stopped on conflicts${conflicts.length ? ` (${conflicts.join(", ")})` : ""} — aborted, the branch is as it was. Rebase by hand in ${state.worktree} (git rebase ${base}), resolve, then re-run flow verify\n${tail(rb.out)}`, isError: true };
|
|
160
|
+
}
|
|
161
|
+
const pushed = hasOrigin && state.branch && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${state.branch}`)}`, cwd)).ok;
|
|
162
|
+
return { note: `rebased onto ${base} (was ${behind} commit(s) behind)${fetchNote}${pushed ? ` — origin/${state.branch} now differs: the next push needs --force-with-lease (dev-flow asks the operator)` : ""}` };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
|
|
166
|
+
* clears the records, so "run flow check first" cost three round trips to say what one could (#84).
|
|
167
|
+
* `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
|
|
168
|
+
export function pendingChecks(state: FlowState, cfg: Config): StageCheck[] {
|
|
169
|
+
if (state.docs) return [];
|
|
170
|
+
return cfg.checkList.filter((c) => !state.checks[c.name]?.ok && !(c.name === "health" && healthRerunsAfterDeploy(cfg)));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Run tier-1 checks in the feature cwd and record each result (health seeds first, as `flow health` does). */
|
|
174
|
+
export async function runChecks(root: string, state: FlowState, cfg: Config, checks: StageCheck[]): Promise<{ lines: string[]; failed: boolean }> {
|
|
175
|
+
const lines: string[] = [];
|
|
176
|
+
let failed = false;
|
|
177
|
+
const ran: string[] = [];
|
|
178
|
+
for (const c of checks) {
|
|
179
|
+
// health is the same probe `flow health` runs: seeded first, retried within healthWait
|
|
180
|
+
const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state), undefined, featureEnv(root, state));
|
|
181
|
+
if ("seedFail" in res) {
|
|
182
|
+
lines.push(res.seedFail.text);
|
|
183
|
+
failed = true;
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
state.checks[c.name] = { ok: res.ok, at: now() };
|
|
187
|
+
ran.push(c.name);
|
|
188
|
+
const tried = triedNote((res as { attempts?: number }).attempts ?? 1);
|
|
189
|
+
lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd}${tried})${res.ok ? "" : `\n${tail(res.out)}`}`);
|
|
190
|
+
if (!res.ok) failed = true;
|
|
191
|
+
}
|
|
192
|
+
await stampChecks(root, state, ran);
|
|
193
|
+
writeState(root, state);
|
|
194
|
+
return { lines, failed };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Which health record a verify may leave stale on purpose: the post-deploy probe re-runs it, so
|
|
198
|
+
* the pre-deploy record must survive the gate that schedules the deploy. */
|
|
199
|
+
export const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthProbe(cfg);
|
|
200
|
+
|
|
201
|
+
/** Seed pre-existing data before a health probe, recording the step (`flow health` and the verify
|
|
202
|
+
* deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
|
|
203
|
+
export async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
|
|
204
|
+
if (!cfg.commands.seedData) return null;
|
|
205
|
+
const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, devEnv(root, state, cfg));
|
|
206
|
+
state.checks.seedData = { ok: seed.ok, at: now() };
|
|
207
|
+
writeState(root, state);
|
|
208
|
+
return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: RunResult };
|
|
212
|
+
|
|
213
|
+
/** Seed (when configured), then run the health probe within the playbook's wait budget. */
|
|
214
|
+
export async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
|
|
215
|
+
const seedFail = await seedStep(root, state, cfg);
|
|
216
|
+
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, devEnv(root, state, cfg));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
|
|
220
|
+
export async function probeHealth(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
|
|
221
|
+
const res = await seededProbe(root, state, cfg, probe);
|
|
222
|
+
if ("seedFail" in res) return res;
|
|
223
|
+
state.checks.health = { ok: res.ok, at: now() };
|
|
224
|
+
await stampChecks(root, state, ["health"]);
|
|
225
|
+
writeState(root, state);
|
|
226
|
+
return res;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** A probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42). */
|
|
230
|
+
export const triedNote = (attempts: number) => (attempts > 1 ? `, ${attempts} attempts` : "");
|
|
231
|
+
|
|
232
|
+
/** Fingerprint of the working-tree state the checks ran against: paths (`status --porcelain`),
|
|
233
|
+
* tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
|
|
234
|
+
* measurement failure must never mark a green record stale (see freshenChecks). */
|
|
235
|
+
export async function worktreeFingerprint(cwd: string): Promise<string | null> {
|
|
236
|
+
const st = await sh("git status --porcelain", cwd);
|
|
237
|
+
if (!st.ok) return null;
|
|
238
|
+
const diff = await sh("git diff HEAD --no-color | git hash-object --stdin", cwd);
|
|
239
|
+
const head = await sh("git rev-parse HEAD", cwd);
|
|
240
|
+
if (!diff.ok || !head.ok) return null;
|
|
241
|
+
return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
|
|
245
|
+
* that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
|
|
246
|
+
export async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
|
|
247
|
+
const fp = await worktreeFingerprint(gateCwd(root, state));
|
|
248
|
+
if (!fp) return;
|
|
249
|
+
for (const n of names) if (state.checks[n]) state.checks[n].wt = fp;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Commits the feature branch holds over its merge base with the default branch, plus how many
|
|
253
|
+
* paths sit uncommitted: verify's proof that there is a committed state behind the operator's
|
|
254
|
+
* question. Local refs only — same offline-safe stance as the changelog proof — and an
|
|
255
|
+
* unanswerable merge base reports null instead of refusing on a measurement failure. */
|
|
256
|
+
export async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
|
|
257
|
+
const base = await mergeBase(cwd, defaultBranch);
|
|
258
|
+
if (!base) return { commitsAhead: null, uncommitted: 0 };
|
|
259
|
+
const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
|
|
260
|
+
const n = Number.parseInt(ahead.out.trim(), 10);
|
|
261
|
+
const dirty = await sh("git status --porcelain", cwd);
|
|
262
|
+
return {
|
|
263
|
+
commitsAhead: Number.isFinite(n) ? n : null,
|
|
264
|
+
uncommitted: dirty.ok ? dirty.out.split("\n").filter((l) => l.trim()).length : 0,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Commits HEAD carries since the newest local version tag (all of them before the first release) —
|
|
269
|
+
* local refs only, so the probe stays offline-safe. HEAD is the default branch's tip on an empty branch. */
|
|
270
|
+
export async function unreleasedOnMain(cwd: string, pattern: string): Promise<{ count: number | null; since: string | null }> {
|
|
271
|
+
const tags = await sh("git tag --list", cwd);
|
|
272
|
+
const newest = tags.ok ? newestTaggedVersion(pattern, tags.out.split("\n").map((t) => t.trim()).filter(Boolean)) : null;
|
|
273
|
+
const since = newest ? pattern.replace("{version}", newest) : null;
|
|
274
|
+
const r = await sh(since ? `git rev-list --count ${sq(since)}..HEAD` : "git rev-list --count HEAD", cwd);
|
|
275
|
+
const n = Number.parseInt(r.out.trim(), 10);
|
|
276
|
+
return { count: r.ok && Number.isFinite(n) ? n : null, since };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Gates whose result carries the feature's stage line (the rest answer about the repo, not one feature). */
|
|
280
|
+
export const STAGE_LINE_GATES = new Set(["start", "use", "approve", "check", "test", "verify", "release", "release-done", "finish"]);
|
|
281
|
+
|
|
282
|
+
/** Cheap facts for the stage line: the plan file and mockups at plan, commit counts and HEAD once a
|
|
283
|
+
* worktree exists, the manifest version at pre-release. Measurement failures leave a field out. */
|
|
284
|
+
export async function stageFacts(root: string, state: FlowState, cfg: Config): Promise<StageFacts> {
|
|
285
|
+
const f: StageFacts = {};
|
|
286
|
+
if (state.stage === "plan") {
|
|
287
|
+
const planDir = path.join(featDir(root, state.slug), "plan");
|
|
288
|
+
const planMd = path.join(planDir, "plan.md");
|
|
289
|
+
f.plan = existsSync(planMd) ? (/\bdraft\b/i.test(readFileSync(planMd, "utf8").slice(0, 400)) ? "draft" : "written") : "missing";
|
|
290
|
+
if (state.ui) {
|
|
291
|
+
const files = listFiles(planDir);
|
|
292
|
+
const html = files.filter((x) => x.startsWith("mockups/") && x.endsWith(".html"));
|
|
293
|
+
const rendered = html.filter((h) => files.some((x) => x.startsWith(h.replace(/\.html$/, "-")) && x.endsWith(".png"))).length;
|
|
294
|
+
f.mockups = { rendered, total: html.length };
|
|
295
|
+
}
|
|
296
|
+
return f;
|
|
297
|
+
}
|
|
298
|
+
const wt = worktreeAbs(root, state);
|
|
299
|
+
if (wt && existsSync(wt) && (state.stage === "implement" || state.stage === "pre-release")) {
|
|
300
|
+
const b = await branchState(wt, cfg.defaultBranch);
|
|
301
|
+
if (b.commitsAhead !== null) {
|
|
302
|
+
f.ahead = b.commitsAhead;
|
|
303
|
+
f.uncommitted = b.uncommitted;
|
|
304
|
+
}
|
|
305
|
+
const head = await sh("git rev-parse HEAD", wt, 10_000);
|
|
306
|
+
if (head.ok) f.head = head.out.trim();
|
|
307
|
+
if (state.stage === "pre-release" && cfg.versioning.file && existsSync(path.join(wt, cfg.versioning.file))) {
|
|
308
|
+
try {
|
|
309
|
+
f.manifest = parseVersion(cfg.versioning.file, readFileSync(path.join(wt, cfg.versioning.file), "utf8"));
|
|
310
|
+
} catch {
|
|
311
|
+
/* the version field stays pending */
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return f;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** A gate result as both readers need it: the agent's text (with its stage line) and the operator's view. */
|
|
319
|
+
export async function presentRun(args: string[], root: string, key: string, res: RunResult): Promise<{ agent: string; view: GateView }> {
|
|
320
|
+
const sub = args[0] ?? "status";
|
|
321
|
+
const cfg = initiated(root) ? loadProject(dfDir(root)).cfg : DEFAULTS;
|
|
322
|
+
let state: FlowState | null = null;
|
|
323
|
+
if (STAGE_LINE_GATES.has(sub) && initiated(root)) {
|
|
324
|
+
const slugArg = args.slice(1).find((a) => !a.startsWith("--"));
|
|
325
|
+
state = boundFeature(root, key) ?? (slugArg && validSlug(slugArg) ? readState(root, slugArg) : null);
|
|
326
|
+
}
|
|
327
|
+
let facts: StageFacts | undefined;
|
|
328
|
+
try {
|
|
329
|
+
facts = state ? await stageFacts(root, state, cfg) : undefined;
|
|
330
|
+
} catch {
|
|
331
|
+
facts = undefined;
|
|
332
|
+
}
|
|
333
|
+
const view = presentGate(sub, res.text, !!res.isError, state, cfg, facts);
|
|
334
|
+
return { agent: agentText(res.text, view), view };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function describeBranchState(b: BranchState, defaultBranch: string): string {
|
|
338
|
+
if (b.commitsAhead === null) return `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`;
|
|
339
|
+
const line = `commits: ${b.commitsAhead} ahead of ${defaultBranch}, ${b.uncommitted} uncommitted path(s)`;
|
|
340
|
+
return b.commitsAhead === 0 && (b.unreleased?.count ?? 0) > 0
|
|
341
|
+
? `${line} — release-only flow: ${b.unreleased!.count} unreleased commit(s) on ${defaultBranch}${b.unreleased!.since ? ` since ${b.unreleased!.since}` : " (nothing tagged yet)"}; verify proves that tree, the version bump is the pre-release commit`
|
|
342
|
+
: line;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ---------------------------------------------------------------- gate runner
|
|
346
|
+
|
|
347
|
+
export interface RunResult {
|
|
348
|
+
text: string;
|
|
349
|
+
isError?: boolean;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export interface Session {
|
|
353
|
+
slug: string | null;
|
|
354
|
+
key: string;
|
|
355
|
+
bind: (slug: string | null) => void;
|
|
356
|
+
/** Name the pi session after a slug (one session = one feature: the picker shows the feature). */
|
|
357
|
+
rename: (slug: string) => void;
|
|
358
|
+
}
|