pi-dev-flow 0.97.0 → 0.99.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 +42 -0
- package/README.md +5 -0
- package/docs/gates.md +11 -4
- package/docs/guardrails.md +12 -4
- package/docs/jira.md +68 -0
- package/docs/playbook.md +10 -3
- package/extensions/dev-flow.ts +194 -31
- package/package.json +1 -1
- package/skills/dev-flow/references/start.md +33 -0
- package/src/core.ts +148 -5
- package/src/jira/client.ts +425 -0
- package/src/jira/config.ts +192 -0
- package/src/jira/creds.ts +57 -0
- package/src/jira/mcp.ts +176 -0
- package/src/jira/sync.ts +123 -0
- package/src/projectmd.ts +45 -3
- package/src/runtime/base.ts +1 -1
- package/src/runtime/checks.ts +2 -0
- package/src/runtime/gates.ts +78 -5
- package/src/runtime/grants.ts +28 -1
- package/src/runtime/jira-watch.ts +126 -0
- package/src/runtime/jira.ts +533 -0
- package/src/runtime/ship.ts +31 -6
package/src/jira/mcp.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal MCP client over Streamable HTTP — just enough to call the official Atlassian Rovo MCP server
|
|
3
|
+
* (https://mcp.atlassian.com/v2/mcp) from extension code, outside any model turn. pi's extension API can
|
|
4
|
+
* register an MCP server for the agent but offers no way for an extension to call one of its tools, and the
|
|
5
|
+
* Jira watch must poll without spending model turns — hence this ~150-line client instead of a dependency.
|
|
6
|
+
*
|
|
7
|
+
* Speaks JSON-RPC 2.0: `initialize` → `notifications/initialized` → `tools/list` / `tools/call`. A response
|
|
8
|
+
* may come back as `application/json` or as a `text/event-stream` carrying the JSON-RPC message(s); both are
|
|
9
|
+
* read. The server's `Mcp-Session-Id` is echoed on every later request.
|
|
10
|
+
*
|
|
11
|
+
* Pure of pi imports; `fetch` is injectable for tests.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{
|
|
15
|
+
ok: boolean;
|
|
16
|
+
status: number;
|
|
17
|
+
headers: { get(name: string): string | null };
|
|
18
|
+
text(): Promise<string>;
|
|
19
|
+
}>;
|
|
20
|
+
|
|
21
|
+
export interface McpTool {
|
|
22
|
+
name: string;
|
|
23
|
+
description?: string;
|
|
24
|
+
inputSchema?: { properties?: Record<string, unknown>; required?: string[] };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface McpCallResult {
|
|
28
|
+
content?: { type: string; text?: string; [k: string]: unknown }[];
|
|
29
|
+
structuredContent?: unknown;
|
|
30
|
+
isError?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class McpError extends Error {
|
|
34
|
+
readonly status?: number;
|
|
35
|
+
constructor(message: string, status?: number) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.status = status;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PROTOCOL = "2025-06-18";
|
|
42
|
+
|
|
43
|
+
/** The JSON-RPC message answering `id` in an SSE body (`data:` lines, events split by a blank line). */
|
|
44
|
+
export function parseSse(body: string, id: number): unknown {
|
|
45
|
+
for (const event of body.split(/\r?\n\r?\n/)) {
|
|
46
|
+
const data = event
|
|
47
|
+
.split(/\r?\n/)
|
|
48
|
+
.filter((l) => l.startsWith("data:"))
|
|
49
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
50
|
+
.join("\n");
|
|
51
|
+
if (!data) continue;
|
|
52
|
+
try {
|
|
53
|
+
const msg = JSON.parse(data) as { id?: number };
|
|
54
|
+
if (msg && msg.id === id) return msg;
|
|
55
|
+
} catch {
|
|
56
|
+
/* not JSON — keep looking */
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class McpClient {
|
|
63
|
+
private sessionId: string | undefined;
|
|
64
|
+
private nextId = 1;
|
|
65
|
+
private ready: Promise<void> | undefined;
|
|
66
|
+
private toolsCache: McpTool[] | undefined;
|
|
67
|
+
|
|
68
|
+
readonly url: string;
|
|
69
|
+
private readonly headers: Record<string, string>;
|
|
70
|
+
private readonly fetchFn: FetchLike;
|
|
71
|
+
private readonly timeoutMs: number;
|
|
72
|
+
|
|
73
|
+
constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, timeoutMs = 30_000) {
|
|
74
|
+
this.url = url;
|
|
75
|
+
this.headers = headers;
|
|
76
|
+
this.fetchFn = fetchFn;
|
|
77
|
+
this.timeoutMs = timeoutMs;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async post(body: unknown, id?: number): Promise<unknown> {
|
|
81
|
+
const headers: Record<string, string> = {
|
|
82
|
+
...this.headers,
|
|
83
|
+
"content-type": "application/json",
|
|
84
|
+
accept: "application/json, text/event-stream",
|
|
85
|
+
"mcp-protocol-version": PROTOCOL,
|
|
86
|
+
};
|
|
87
|
+
if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
|
|
88
|
+
const ctl = new AbortController();
|
|
89
|
+
const timer = setTimeout(() => ctl.abort(), this.timeoutMs);
|
|
90
|
+
let res: Awaited<ReturnType<FetchLike>>;
|
|
91
|
+
try {
|
|
92
|
+
res = await this.fetchFn(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: ctl.signal });
|
|
93
|
+
} catch (e) {
|
|
94
|
+
throw new McpError(ctl.signal.aborted ? `timed out after ${this.timeoutMs / 1000}s` : `request failed: ${(e as Error).message}`);
|
|
95
|
+
} finally {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
}
|
|
98
|
+
const sid = res.headers.get("mcp-session-id");
|
|
99
|
+
if (sid) this.sessionId = sid;
|
|
100
|
+
const text = await res.text();
|
|
101
|
+
if (!res.ok) {
|
|
102
|
+
const hint = res.status === 401 || res.status === 403 ? " — check the email and API token, and that an org admin enabled API-token auth for the Atlassian MCP server" : "";
|
|
103
|
+
throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status);
|
|
104
|
+
}
|
|
105
|
+
if (id === undefined) return undefined; // a notification: 202, no body
|
|
106
|
+
const type = res.headers.get("content-type") ?? "";
|
|
107
|
+
const msg = (type.includes("text/event-stream") ? parseSse(text, id) : text ? JSON.parse(text) : undefined) as
|
|
108
|
+
| { result?: unknown; error?: { code: number; message: string } }
|
|
109
|
+
| undefined;
|
|
110
|
+
if (!msg) throw new McpError("empty response");
|
|
111
|
+
if (msg.error) throw new McpError(`MCP error ${msg.error.code}: ${msg.error.message}`);
|
|
112
|
+
return msg.result;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private async request(method: string, params?: unknown): Promise<unknown> {
|
|
116
|
+
const id = this.nextId++;
|
|
117
|
+
return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Handshake once; a failed handshake is retried by the next call. */
|
|
121
|
+
init(): Promise<void> {
|
|
122
|
+
this.ready ??= (async () => {
|
|
123
|
+
await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } });
|
|
124
|
+
await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
125
|
+
})().catch((e) => {
|
|
126
|
+
this.ready = undefined;
|
|
127
|
+
this.sessionId = undefined;
|
|
128
|
+
throw e;
|
|
129
|
+
});
|
|
130
|
+
return this.ready;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async listTools(): Promise<McpTool[]> {
|
|
134
|
+
if (this.toolsCache) return this.toolsCache;
|
|
135
|
+
await this.init();
|
|
136
|
+
const out: McpTool[] = [];
|
|
137
|
+
let cursor: string | undefined;
|
|
138
|
+
do {
|
|
139
|
+
const r = (await this.request("tools/list", cursor ? { cursor } : {})) as { tools?: McpTool[]; nextCursor?: string };
|
|
140
|
+
out.push(...(r.tools ?? []));
|
|
141
|
+
cursor = r.nextCursor;
|
|
142
|
+
} while (cursor);
|
|
143
|
+
this.toolsCache = out;
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async callTool(name: string, args: Record<string, unknown>): Promise<McpCallResult> {
|
|
148
|
+
await this.init();
|
|
149
|
+
try {
|
|
150
|
+
return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
|
|
151
|
+
} catch (e) {
|
|
152
|
+
// an expired server session: start over once
|
|
153
|
+
if (e instanceof McpError && e.status === 404 && this.sessionId) {
|
|
154
|
+
this.ready = undefined;
|
|
155
|
+
this.sessionId = undefined;
|
|
156
|
+
await this.init();
|
|
157
|
+
return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
|
|
158
|
+
}
|
|
159
|
+
throw e;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A tool result's payload: structuredContent, else the text blocks parsed as JSON, else the joined text. */
|
|
165
|
+
export function resultValue(r: McpCallResult): unknown {
|
|
166
|
+
if (r.structuredContent !== undefined) return r.structuredContent;
|
|
167
|
+
const text = (r.content ?? []).filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
|
|
168
|
+
try {
|
|
169
|
+
return JSON.parse(text);
|
|
170
|
+
} catch {
|
|
171
|
+
return text;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The text of a tool result (error messages included). */
|
|
176
|
+
export const resultText = (r: McpCallResult) => (r.content ?? []).filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
|
package/src/jira/sync.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Jira sync decisions — pure, no I/O: what a mirrored comment says, which Jira activity is the operator's
|
|
3
|
+
* answer, and when the watch checks next.
|
|
4
|
+
*
|
|
5
|
+
* Who may answer: only the token owner's account (`link.accountId`) — you, replying in Jira. dev-flow posts
|
|
6
|
+
* as that same account, so its own comments are told apart by the ids it saved (`link.posted`) and by the
|
|
7
|
+
* footer marker. Anyone else's comment, and any status move that answers nothing, is relayed as information.
|
|
8
|
+
*/
|
|
9
|
+
import type { FlowState, JiraConfig, JiraLink, JiraStage } from "../core.ts";
|
|
10
|
+
import { stageOfStatus, statusForStage } from "./config.ts";
|
|
11
|
+
import type { JiraComment } from "./client.ts";
|
|
12
|
+
|
|
13
|
+
export const MARKER = "— dev-flow ·";
|
|
14
|
+
|
|
15
|
+
/** The checkpoint a status move answers: moving the issue into `stage` while dev-flow waits on `ask`. */
|
|
16
|
+
const MOVE_ANSWERS: Record<string, { stage: JiraStage; word: string }> = {
|
|
17
|
+
"Approve?": { stage: "implement", word: "Approved" },
|
|
18
|
+
"Verified?": { stage: "pre-release", word: "Verified" },
|
|
19
|
+
"Release?": { stage: "release", word: "Release" },
|
|
20
|
+
"Finish?": { stage: "done", word: "Finish" },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** The status a move to which answers `ask`, for the comment's hint; undefined when none is mapped. */
|
|
24
|
+
export function answeringStatus(cfg: JiraConfig, link: JiraLink, ask: string | undefined): string | undefined {
|
|
25
|
+
const a = ask ? MOVE_ANSWERS[ask] : undefined;
|
|
26
|
+
return a ? statusForStage(cfg, link.type, a.stage) : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A mirrored question (or closing message) as a Jira comment, in markdown. */
|
|
30
|
+
export function formatComment(o: { slug: string; ask?: string; text: string; attachments?: string[]; answerStatus?: string }): string {
|
|
31
|
+
const L: string[] = [];
|
|
32
|
+
if (o.ask) L.push(`**dev-flow is waiting on: ${o.ask}**`, "");
|
|
33
|
+
L.push(o.text.trim());
|
|
34
|
+
if (o.attachments?.length) L.push("", `Attached: ${o.attachments.join(", ")}`);
|
|
35
|
+
if (o.ask) L.push("", `_Answer with a comment here${o.answerStatus ? `, or move the issue to **${o.answerStatus}**` : ""}._`);
|
|
36
|
+
L.push("", `${MARKER} ${o.slug}`);
|
|
37
|
+
return L.join("\n");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Does this closing agent message get mirrored? `all`: always; `asks`: when a gate question is pending or the
|
|
41
|
+
* message asks something (a question mark outside code). */
|
|
42
|
+
export function shouldMirror(mode: JiraConfig["mirror"], pendingAsk: string | undefined, text: string): boolean {
|
|
43
|
+
if (!text.trim()) return false;
|
|
44
|
+
if (mode === "all" || pendingAsk) return true;
|
|
45
|
+
const prose = text.replace(/```[\s\S]*?```/g, "").replace(/`[^`]*`/g, "");
|
|
46
|
+
return /\?\s*(\*\*)?\s*$/m.test(prose);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Relay {
|
|
50
|
+
/** answer: delivered as an operator message (it may grant a gate); info: shown, no turn, no grant */
|
|
51
|
+
kind: "answer" | "info";
|
|
52
|
+
text: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Read new Jira activity against the link: the relays to deliver, and the link fields to store. */
|
|
56
|
+
export function classifyActivity(o: {
|
|
57
|
+
link: JiraLink;
|
|
58
|
+
cfg: JiraConfig;
|
|
59
|
+
state: Pick<FlowState, "slug" | "stage" | "pendingAsk">;
|
|
60
|
+
comments: JiraComment[];
|
|
61
|
+
status: string;
|
|
62
|
+
}): { relays: Relay[]; seenUntil?: string; seenCommentId?: string; lastStatus: string } {
|
|
63
|
+
const { link, cfg, state } = o;
|
|
64
|
+
const relays: Relay[] = [];
|
|
65
|
+
// comment ids grow and are exact; times are a fallback (Jira's are minute-precision through the MCP server)
|
|
66
|
+
const num = (id: string) => (/^\d+$/.test(id) ? Number(id) : NaN);
|
|
67
|
+
const sinceId = link.seenCommentId ? num(link.seenCommentId) : NaN;
|
|
68
|
+
const since = link.seenUntil ? Date.parse(link.seenUntil) : 0;
|
|
69
|
+
const isFresh = (c: JiraComment) => (!Number.isNaN(sinceId) && !Number.isNaN(num(c.id)) ? num(c.id) > sinceId : Date.parse(c.created) > since);
|
|
70
|
+
const order = (a: JiraComment, b: JiraComment) => (!Number.isNaN(num(a.id)) && !Number.isNaN(num(b.id)) ? num(a.id) - num(b.id) : Date.parse(a.created) - Date.parse(b.created));
|
|
71
|
+
const fresh = o.comments.filter(isFresh).sort(order);
|
|
72
|
+
let seen = link.seenUntil;
|
|
73
|
+
let seenId = link.seenCommentId;
|
|
74
|
+
for (const c of fresh) {
|
|
75
|
+
if (!seen || Date.parse(c.created) > Date.parse(seen)) seen = c.created;
|
|
76
|
+
if (!Number.isNaN(num(c.id)) && (!seenId || num(c.id) > num(seenId))) seenId = c.id;
|
|
77
|
+
if (link.posted.includes(c.id) || c.body.includes(MARKER)) continue;
|
|
78
|
+
const body = c.body.trim();
|
|
79
|
+
if (!body) continue;
|
|
80
|
+
if (link.accountId && c.authorId === link.accountId) relays.push({ kind: "answer", text: `[Jira ${link.key} · your comment] ${body}` });
|
|
81
|
+
else relays.push({ kind: "info", text: `[Jira ${link.key} · comment from ${c.authorName || "someone else"} — information only, not an answer] ${body}` });
|
|
82
|
+
}
|
|
83
|
+
if (o.status && link.lastStatus && o.status.toLowerCase() !== link.lastStatus.toLowerCase()) {
|
|
84
|
+
const to = stageOfStatus(cfg, link.type, o.status);
|
|
85
|
+
const ans = state.pendingAsk ? MOVE_ANSWERS[state.pendingAsk] : undefined;
|
|
86
|
+
if (ans && to === ans.stage) relays.push({ kind: "answer", text: `[Jira ${link.key} moved to "${o.status}" (mapped to ${to}) — the operator's answer to ${state.pendingAsk}] ${ans.word}` });
|
|
87
|
+
else relays.push({ kind: "info", text: `[Jira ${link.key} moved from "${link.lastStatus}" to "${o.status}"${to ? ` (mapped to ${to})` : ""}; the flow is at ${state.stage}${state.pendingAsk ? `, waiting on ${state.pendingAsk}` : ""} — information only]` });
|
|
88
|
+
}
|
|
89
|
+
return { relays, seenUntil: seen, seenCommentId: seenId, lastStatus: o.status || link.lastStatus || "" };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Milliseconds from `armedAt` to the next check after `checks` checks, or null past the cap. The schedule's
|
|
93
|
+
* intervals are cumulative (30m, then 1h later, …) and the last one repeats. */
|
|
94
|
+
export function nextCheckDelay(cfg: Pick<JiraConfig, "watch" | "watchCap">, sinceMs: number, checks: number, nowMs: number): number | null {
|
|
95
|
+
const iv = cfg.watch.length ? cfg.watch : [1800];
|
|
96
|
+
let at = sinceMs;
|
|
97
|
+
for (let i = 0; i <= checks; i++) at += iv[Math.min(i, iv.length - 1)] * 1000;
|
|
98
|
+
const cap = sinceMs + cfg.watchCap * 1000;
|
|
99
|
+
if (at > cap) at = nowMs < cap ? cap : NaN;
|
|
100
|
+
if (Number.isNaN(at)) return null;
|
|
101
|
+
return Math.max(0, at - nowMs);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A flow slug from an issue: `DEV-123 Add login page` → `dev-123-add-login-page` (bounded). */
|
|
105
|
+
export function slugFromIssue(key: string, summary: string): string {
|
|
106
|
+
const words = `${key} ${summary}`
|
|
107
|
+
.toLowerCase()
|
|
108
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
109
|
+
.trim()
|
|
110
|
+
.split(" ")
|
|
111
|
+
.filter(Boolean);
|
|
112
|
+
let out = "";
|
|
113
|
+
for (const w of words) {
|
|
114
|
+
if ((out ? out.length + 1 : 0) + w.length > 40) break;
|
|
115
|
+
out = out ? `${out}-${w}` : w;
|
|
116
|
+
}
|
|
117
|
+
return out || key.toLowerCase();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The plan brief seeded from an issue. */
|
|
121
|
+
export function issueBrief(i: { key: string; summary: string; description: string; url: string; type: string }): string {
|
|
122
|
+
return [`# ${i.summary}`, "", `Jira: [${i.key}](${i.url}) (${i.type})`, "", "## Brief (from the issue)", "", i.description.trim() || "_(the issue has no description)_", ""].join("\n");
|
|
123
|
+
}
|
package/src/projectmd.ts
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
* tier 3: every other line — prose injected to the agent when its stage begins
|
|
6
6
|
* Parsing is pure and never fatal: unknown stages/keys and odd syntax become warnings.
|
|
7
7
|
*/
|
|
8
|
-
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
8
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
|
-
import {
|
|
10
|
+
import { parseJiraBlock } from "./jira/config.ts";
|
|
11
|
+
import { applyAnswer, type JiraConfig, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
|
|
11
12
|
|
|
12
13
|
export const MD_STAGES = ["global", "plan", "implement", "pre-release", "release"] as const;
|
|
13
14
|
export type MdStage = (typeof MD_STAGES)[number];
|
|
@@ -25,6 +26,8 @@ export interface ParsedMd {
|
|
|
25
26
|
prose: Record<string, string>;
|
|
26
27
|
/** ## global `flow-worker` block lines — the setup every stage worker's brief carries (gh#201) */
|
|
27
28
|
workerPreamble: string[];
|
|
29
|
+
/** ## global `flow-jira` block — the opt-in Jira sync (src/jira/config.ts) */
|
|
30
|
+
jira?: JiraConfig;
|
|
28
31
|
}
|
|
29
32
|
|
|
30
33
|
// stage → flow-key → config dot-path (aliases); unknown keys warn
|
|
@@ -138,6 +141,8 @@ export function parseProjectMd(text: string): ParsedMd {
|
|
|
138
141
|
let checkName = "";
|
|
139
142
|
let checkBody: string[] = [];
|
|
140
143
|
let guardBody: { line: string; where: string }[] = [];
|
|
144
|
+
let jiraBody: { line: string; where: string }[] = [];
|
|
145
|
+
let jiraSeen = false;
|
|
141
146
|
let lastLine = ""; // for fence-start line numbers (1-based = index+1)
|
|
142
147
|
text.split("\n").forEach((line, i) => {
|
|
143
148
|
const where = `line ${i + 1}`;
|
|
@@ -155,6 +160,18 @@ export function parseProjectMd(text: string): ParsedMd {
|
|
|
155
160
|
if (guardBody.length) parseGuardRules(guardBody, stage, p);
|
|
156
161
|
guardBody = [];
|
|
157
162
|
}
|
|
163
|
+
if (inFence === "flow-jira") {
|
|
164
|
+
if (stage !== "global") p.warn.push(`${where}: flow-jira belongs to ## global — the block under ## ${stage ?? "(no stage)"} is ignored`);
|
|
165
|
+
else if (jiraSeen) p.warn.push(`${where}: a second flow-jira block — ignored (one per project)`);
|
|
166
|
+
else {
|
|
167
|
+
jiraSeen = true;
|
|
168
|
+
const r = parseJiraBlock(jiraBody);
|
|
169
|
+
p.hard.push(...r.hard);
|
|
170
|
+
p.warn.push(...r.warn);
|
|
171
|
+
if (r.cfg && !r.hard.length) p.jira = r.cfg;
|
|
172
|
+
}
|
|
173
|
+
jiraBody = [];
|
|
174
|
+
}
|
|
158
175
|
inFence = null;
|
|
159
176
|
checkName = "";
|
|
160
177
|
checkBody = [];
|
|
@@ -226,6 +243,7 @@ export function parseProjectMd(text: string): ParsedMd {
|
|
|
226
243
|
} else if (line.trim()) p.warn.push(`${where}: flow-worker lines belong to ## global — ignored under ## ${stage ?? "(no stage)"}`);
|
|
227
244
|
}
|
|
228
245
|
else if (inFence === "flow-guard") guardBody.push({ line, where });
|
|
246
|
+
else if (inFence === "flow-jira") jiraBody.push({ line, where });
|
|
229
247
|
return;
|
|
230
248
|
}
|
|
231
249
|
lastLine = where;
|
|
@@ -238,6 +256,7 @@ export function parseProjectMd(text: string): ParsedMd {
|
|
|
238
256
|
checkName = lang.slice("flow-check".length).trim();
|
|
239
257
|
} else if (lang === "flow-guard") inFence = "flow-guard";
|
|
240
258
|
else if (lang === "flow-worker") inFence = "flow-worker";
|
|
259
|
+
else if (lang === "flow-jira") inFence = "flow-jira";
|
|
241
260
|
else inFence = lang || "code";
|
|
242
261
|
return;
|
|
243
262
|
}
|
|
@@ -312,6 +331,7 @@ export function mdToConfig(p: ParsedMd): Config {
|
|
|
312
331
|
c.checklist = p.checklist;
|
|
313
332
|
c.prose = p.prose;
|
|
314
333
|
if (p.workerPreamble.length) c.workerPreamble = [...p.workerPreamble];
|
|
334
|
+
if (p.jira) c.jira = structuredClone(p.jira);
|
|
315
335
|
return c;
|
|
316
336
|
}
|
|
317
337
|
|
|
@@ -520,7 +540,28 @@ export function ghostFeatureDirs(root: string): string[] {
|
|
|
520
540
|
const df = path.join(root, ".dev-flow");
|
|
521
541
|
if (!existsSync(df)) return [];
|
|
522
542
|
return readdirSync(df, { withFileTypes: true })
|
|
523
|
-
|
|
543
|
+
// a plan/ holding no file has nothing to recover: that dir is an empty one (emptyFeatureDirs), swept without a question
|
|
544
|
+
.filter((d) => d.isDirectory() && existsSync(path.join(df, d.name, "plan")) && !existsSync(path.join(df, d.name, "state.json")) && !holdsNoFile(path.join(df, d.name)))
|
|
545
|
+
.map((d) => `.dev-flow/${d.name}`);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** True when a directory holds no file anywhere beneath it — only (nested) empty directories. */
|
|
549
|
+
function holdsNoFile(dir: string): boolean {
|
|
550
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
551
|
+
if (!e.isDirectory()) return false;
|
|
552
|
+
if (!holdsNoFile(path.join(dir, e.name))) return false;
|
|
553
|
+
}
|
|
554
|
+
return true;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Feature dirs emptied by a hand cleanup that stopped at the directory (gh#282): no file anywhere inside, so
|
|
558
|
+
* neither a feature (no state.json) nor a plan ghost (no plan/*.md). They hold nothing, so removing them loses
|
|
559
|
+
* nothing. `minAgeMs` keeps a dir a `flow start` is creating this very moment out of the sweep. */
|
|
560
|
+
export function emptyFeatureDirs(root: string, minAgeMs = 0, nowMs = Date.now()): string[] {
|
|
561
|
+
const df = path.join(root, ".dev-flow");
|
|
562
|
+
if (!existsSync(df)) return [];
|
|
563
|
+
return readdirSync(df, { withFileTypes: true })
|
|
564
|
+
.filter((d) => d.isDirectory() && holdsNoFile(path.join(df, d.name)) && nowMs - statSync(path.join(df, d.name)).mtimeMs >= minAgeMs)
|
|
524
565
|
.map((d) => `.dev-flow/${d.name}`);
|
|
525
566
|
}
|
|
526
567
|
|
|
@@ -592,6 +633,7 @@ export function doctorFindings(root: string, cfg: Config, md: ParsedMd | null):
|
|
|
592
633
|
if (cfg.commands.run && !cfg.checkList.some((c) => c.name === "health")) f.push('run command configured but no tier-1 health check — add commands.health or a flow-check so "running and healthy" is enforced');
|
|
593
634
|
if (cfg.commands.dev && !healthProbe(cfg)) f.push("dev deploy configured but no health check — flow verify cannot prove the deploy came back serving this build: add commands.health or a flow-check health block");
|
|
594
635
|
if (!cfg.checkList.length) f.push("implement tier-1 gates nothing — no test, no health, no flow-check block: 'flow check' would pass vacuously");
|
|
636
|
+
for (const g of emptyFeatureDirs(root)) f.push(`${g} is an empty feature dir — no state.json, no plan/, no file at all (a hand cleanup that stopped at the directory); flow init removes it`);
|
|
595
637
|
for (const g of ghostFeatureDirs(root)) f.push(`${g} has a plan/ but no state.json — ghost of a closed, aborted or hand-made feature (flow start <slug> --confirmed adopts it as a new feature; flow init offers to remove it)`);
|
|
596
638
|
return f;
|
|
597
639
|
}
|
package/src/runtime/base.ts
CHANGED
|
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
236
236
|
}
|
|
237
237
|
|
|
238
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> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | 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 on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> 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 — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — 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 prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — 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; drop <n> removes an item nobody wants any more (done would record it as shipped); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — 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 — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
239
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | guard <command>|--path <file> | status [slug] [--json] | start <slug> [--jira=<KEY>|--no-jira] [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | jira [status|init [--project=<KEY>] [--types=<A,B>] [--map=<Type>.<stage>=<Status>]… [--mirror=asks|all] [--confirmed]|create [--summary=<text>] [--description=<text>|--description-file=<path>] [--type=<Type>] [--roadmap=<n>[,<n>…]] [--confirmed]|link <KEY>|unlink|check] | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | 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 on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> 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 — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — 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 prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — 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; drop <n> removes an item nobody wants any more (done would record it as shipped); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — 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 — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
240
240
|
export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
241
241
|
export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
242
242
|
export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
package/src/runtime/checks.ts
CHANGED
|
@@ -482,4 +482,6 @@ export interface Session {
|
|
|
482
482
|
/** Operator messages in this session's branch so far, or null/undefined when it cannot be read — a gate
|
|
483
483
|
* compares it with the count it recorded earlier to know whether the operator spoke since (gh#254). */
|
|
484
484
|
operatorMessages?: number | null;
|
|
485
|
+
/** The operator's newest message text, or null/undefined when it cannot be read (gh#299). */
|
|
486
|
+
operatorText?: string | null;
|
|
485
487
|
}
|
package/src/runtime/gates.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/** dev-flow runtime — The gate runner and the gates that do not ship anything. Moved out of extensions/dev-flow.ts as is (exports added). */
|
|
2
2
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { type ReflectFinding, type ReflectOpenCheck, foldCallError, skipsChecks, approveGate, versionArg, playbookVersionChoice, releaseCallQuestion, describeVersionChoice, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState, parseRowIds, DF_GITIGNORE } from "../core.ts";
|
|
5
|
-
import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
|
|
4
|
+
import { type ReflectFinding, type ReflectOpenCheck, ALLOW_REWRITE, forcePushInvocation, guardBash, guardPath, foldCallError, skipsChecks, approveGate, versionArg, playbookVersionChoice, releaseCallQuestion, describeVersionChoice, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState, parseRowIds, DF_GITIGNORE } from "../core.ts";
|
|
5
|
+
import { applyAnswers, buildDraft, doctorFindings, emptyFeatureDirs, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
|
|
6
6
|
import { linkedTag } from "../fold.ts";
|
|
7
|
+
import { namesReleaseCall } from "./grants.ts";
|
|
7
8
|
import { detectProject } from "../detect.ts";
|
|
8
9
|
import { AGENT_MARK } from "../present.ts";
|
|
9
10
|
import { GATE_HELP, SELF_BUILD, refreshDocsCode, type Ui, manifestAt, recordReleaseCall, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
|
|
@@ -11,10 +12,13 @@ import { type RunResult, type Session, ago, behindNote, releaseDevSlot, pendingC
|
|
|
11
12
|
import { GIT_TRACK_NOTE, isSelfRepo, renderQuestions, setupQuestions, tagPatternEvidence } from "./setup.ts";
|
|
12
13
|
import { foldRows, foldView, legacyPluginRows, pluginUpstream, reflectDeferNote, reflectDoneNote, reflectList, reflectMoveNote, reflectNote, reflectPlanNote, reflectReopenNote, reflectSameNote, reflectTidy } from "./reflect.ts";
|
|
13
14
|
import { gateFinish, gateRelease, gateReleaseDone, gateVerify } from "./ship.ts";
|
|
15
|
+
import { type JiraGateHooks, gateJira, linkFlow, linkedStages, slugForIssue, startWithoutKey, syncStageMoves } from "./jira.ts";
|
|
14
16
|
|
|
15
17
|
/** What a gate may need from the extension closure: finish runs the closing reflection worker itself. */
|
|
16
18
|
export interface FlowHooks {
|
|
17
19
|
reflect?: (state: FlowState, note: string) => Promise<{ text: string; recorded: boolean; findings: number; failed: boolean; report?: { findings: ReflectFinding[]; open: ReflectOpenCheck[] } }>;
|
|
20
|
+
/** the Jira sync's delivery of relayed answers and its watch (extensions/dev-flow.ts) */
|
|
21
|
+
jira?: JiraGateHooks;
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
/** Write `.dev-flow/.gitignore` when it is missing; true when it did. Best effort — never fails a gate. */
|
|
@@ -53,10 +57,38 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
|
|
|
53
57
|
state.yolo = true;
|
|
54
58
|
return null;
|
|
55
59
|
};
|
|
56
|
-
|
|
60
|
+
let slugArg = rest.find((a) => !a.startsWith("--"));
|
|
61
|
+
// flow start --jira=KEY: the issue must exist, be in the project and of a synced type — and it names the
|
|
62
|
+
// slug when none was given
|
|
63
|
+
const jiraKey = sub === "start" ? flagValue(rest, "jira")?.toUpperCase() ?? null : null;
|
|
64
|
+
if (jiraKey && !slugArg) {
|
|
65
|
+
const s = await slugForIssue(cfg, jiraKey);
|
|
66
|
+
if ("error" in s) return { text: `start --jira=${jiraKey}: ${s.error}`, isError: true };
|
|
67
|
+
slugArg = s.slug;
|
|
68
|
+
rest.unshift(s.slug);
|
|
69
|
+
} else if (jiraKey && !cfg.jira) return { text: "--jira needs Jira sync configured — run flow jira init first", isError: true };
|
|
57
70
|
const o: GateCtx = { root, ui, sess, cfg, rest, flag, slugArg, takeYoloWord, hooks };
|
|
71
|
+
// the Jira sync follows stage changes: every linked flow's stage before the gate, compared after it
|
|
72
|
+
const before = cfg.jira && sub !== "jira" ? linkedStages(root) : new Map();
|
|
73
|
+
const res = await dispatch(sub, o);
|
|
74
|
+
if (jiraKey && !res.isError && slugArg && readState(root, slugArg)) {
|
|
75
|
+
const r = await linkFlow(root, cfg, slugArg, jiraKey, { seedPlan: true });
|
|
76
|
+
return { ...res, text: `${res.text}\n${"error" in r ? `${AGENT_MARK}jira: the flow started but was not linked to ${jiraKey}: ${r.error} — flow jira link ${jiraKey} retries` : r.lines.join("\n")}` };
|
|
77
|
+
}
|
|
78
|
+
if (sub === "start" && !jiraKey && cfg.jira && !res.isError && slugArg && readState(root, slugArg) && !flag("no-jira")) {
|
|
79
|
+
const lines = await startWithoutKey(root, cfg, slugArg).catch((e) => [`${AGENT_MARK}jira: ${(e as Error).message}`]);
|
|
80
|
+
if (lines.length) return { ...res, text: `${res.text}\n${lines.join("\n")}` };
|
|
81
|
+
}
|
|
82
|
+
const moves = before.size ? await syncStageMoves(root, cfg, before).catch((e) => [`${AGENT_MARK}jira: status sync failed: ${(e as Error).message}`]) : [];
|
|
83
|
+
return moves.length ? { ...res, text: `${res.text}\n${moves.join("\n")}` } : res;
|
|
84
|
+
}
|
|
58
85
|
|
|
86
|
+
async function dispatch(sub: string, o: GateCtx): Promise<RunResult> {
|
|
87
|
+
const { root, cfg, rest, flag, sess, hooks } = o;
|
|
59
88
|
switch (sub) {
|
|
89
|
+
case "jira":
|
|
90
|
+
return gateJira(root, cfg, rest, flag, sess.slug, hooks.jira);
|
|
91
|
+
|
|
60
92
|
case "init":
|
|
61
93
|
return gateInit(o);
|
|
62
94
|
|
|
@@ -75,6 +107,9 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
|
|
|
75
107
|
case "doctor":
|
|
76
108
|
return gateDoctor(o);
|
|
77
109
|
|
|
110
|
+
case "guard":
|
|
111
|
+
return gateGuard(o, rest);
|
|
112
|
+
|
|
78
113
|
case "version":
|
|
79
114
|
return gateVersion(o);
|
|
80
115
|
|
|
@@ -169,6 +204,13 @@ export async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
169
204
|
const draftFresh = buildDraft(det);
|
|
170
205
|
const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
|
|
171
206
|
if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
|
|
207
|
+
// empty feature dirs hold nothing to lose: removed with a note, no question (gh#282). Ten minutes old at
|
|
208
|
+
// least, so a dir a parallel flow start has only just created is not swept before its state.json lands.
|
|
209
|
+
const empties = emptyFeatureDirs(root, 10 * 60_000);
|
|
210
|
+
if (empties.length) {
|
|
211
|
+
for (const g of empties) rmSync(path.join(root, g), { recursive: true, force: true });
|
|
212
|
+
notes.push(`removed ${empties.length} empty feature dir(s) — no state.json, no plan/, no file: ${empties.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
|
|
213
|
+
}
|
|
172
214
|
// ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
|
|
173
215
|
const ghosts = ghostFeatureDirs(root);
|
|
174
216
|
if (ghosts.length) {
|
|
@@ -517,9 +559,14 @@ export async function gateApprove(o: GateCtx): Promise<RunResult> {
|
|
|
517
559
|
state!.stage = "implement";
|
|
518
560
|
state!.approvals.plan = now();
|
|
519
561
|
if (call) recordReleaseCall(root, state!, cfg, call);
|
|
562
|
+
// gh#299: an operator answer that names no kind accepts the plan, not the agent's proposed call — kept, marked
|
|
563
|
+
const proposed = flag("confirmed") && !!relArg.choice && !namesReleaseCall(sess.operatorText ?? null, relArg.choice);
|
|
564
|
+
if (proposed) state!.versionProposed = true;
|
|
565
|
+
else if (relArg.choice) delete state!.versionProposed;
|
|
520
566
|
delete state!.pendingAsk;
|
|
521
567
|
writeState(root, state!);
|
|
522
|
-
|
|
568
|
+
const proposedNote = proposed ? ` — recorded as YOUR PROPOSAL: the operator's answer named no kind, so the call is not theirs yet. Verified? shows it to them; their answer, or flow bump <kind> --confirmed, settles it` : "";
|
|
569
|
+
return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${call ? `\nrelease call: ${describeVersionChoice(call, state!.versionFrom)}${proposedNote} — the number is counted from the newest tag at release; the operator can change the call on any gate call (or flow bump <kind>) until the tag` : ""}${setupNote}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
|
|
523
570
|
}
|
|
524
571
|
|
|
525
572
|
/** `flow bump <patch|minor|major|none> [slug]`: the operator changes the release call at any stage before the tag.
|
|
@@ -540,9 +587,10 @@ export async function gateBump(o: GateCtx): Promise<RunResult> {
|
|
|
540
587
|
if (!cfg.versioning.file && choice !== "unreleased") return { text: "bump FAILED:\n- the playbook sets no version file (versionFile under ## release), so there is nothing to bump — set one first", isError: true };
|
|
541
588
|
if (state!.publish?.tag || state!.approvals.release) return { text: `bump FAILED:\n- ${state!.publish?.tag ?? "the release"} is already ${state!.publish?.tag ? "tagged" : "recorded"} — the call cannot change after the tag`, isError: true };
|
|
542
589
|
const was = state!.versionChoice;
|
|
543
|
-
if (was === choice) return { text: `release call unchanged: ${describeVersionChoice(choice, state!.versionFrom)}` };
|
|
590
|
+
if (was === choice && !(state!.versionProposed && flag("confirmed"))) return { text: `release call unchanged: ${describeVersionChoice(choice, state!.versionFrom)}${state!.versionProposed ? " — still the agent's proposal; flow bump <kind> --confirmed on the operator's word settles it" : ""}` };
|
|
544
591
|
if (!flag("confirmed")) return { text: needsOperator(`change the release call from ${was ? describeVersionChoice(was) : "none"} to ${describeVersionChoice(choice)}`, "Release call?", `this is the operator's word — on it, re-run flow bump ${kind}${slug ? ` ${slug}` : ""} --confirmed`), isError: true };
|
|
545
592
|
recordReleaseCall(root, state!, cfg, choice);
|
|
593
|
+
delete state!.versionProposed; // the operator's own word now (gh#299)
|
|
546
594
|
writeState(root, state!);
|
|
547
595
|
const prep = state!.stage === "pre-release" || state!.stage === "release" ? ` — redo the release prep to match (${choice === "unreleased" ? "revert any bump; the entry goes under Unreleased" : "the version file and its changelog heading"}); flow release names the number` : "";
|
|
548
596
|
return { text: `release call changed (confirmed by operator instruction): ${was ? describeVersionChoice(was) : "none"} → ${describeVersionChoice(choice, state!.versionFrom)}${prep}` };
|
|
@@ -718,6 +766,31 @@ export async function gateRoadmap(o: GateCtx): Promise<RunResult> {
|
|
|
718
766
|
}
|
|
719
767
|
}
|
|
720
768
|
|
|
769
|
+
/** `flow guard "<command>"` / `flow guard --path <file>`: which of the playbook's own flow-guard rules a command
|
|
770
|
+
* or a path trips, through the same matcher the hooks use (gh#287). Reads only; runs nothing. */
|
|
771
|
+
export async function gateGuard(o: GateCtx, rest: string[]): Promise<RunResult> {
|
|
772
|
+
const { root, cfg } = o;
|
|
773
|
+
const g = cfg.guard;
|
|
774
|
+
const nRules = g.deny.length + g.confirm.length + g.protect.length + g.forbid.length;
|
|
775
|
+
const usage = 'usage: flow guard "<command>" (which playbook rule a shell command trips) or flow guard --path <file> (which rule an edit of that path trips)';
|
|
776
|
+
if (rest[0] === "--path") {
|
|
777
|
+
const file = rest.slice(1).join(" ").trim();
|
|
778
|
+
if (!file) return { text: usage, isError: true };
|
|
779
|
+
const v = guardPath(path.resolve(root, file), root, g);
|
|
780
|
+
const verdict = v.block ? `blocked — ${v.block}` : v.confirm ? `asks the operator — ${v.confirm}` : "no playbook rule matches this path";
|
|
781
|
+
return { text: `flow guard --path ${file}: ${verdict}\n(${nRules} playbook rule(s); stage guards — worktree, main-checkout and flow-state rules — are judged separately at the call)` };
|
|
782
|
+
}
|
|
783
|
+
const command = rest.join(" ").trim();
|
|
784
|
+
if (!command) return { text: usage, isError: true };
|
|
785
|
+
const v = guardBash(command, g);
|
|
786
|
+
const lines: string[] = [];
|
|
787
|
+
if (v.block) lines.push(`blocked — ${v.block} (the command never runs)`);
|
|
788
|
+
for (const r of v.confirms) lines.push(`asks the operator — \`${r.pattern}\`${r.why ? ` :: ${r.why}` : ""}`);
|
|
789
|
+
if (forcePushInvocation(command)) lines.push(`asks the operator — dev-flow's own force-push rule (the operator's word is the ${ALLOW_REWRITE} prefix)`);
|
|
790
|
+
if (!lines.length) lines.push("no playbook rule matches — runs as far as the playbook is concerned");
|
|
791
|
+
return { text: `flow guard: \`${command.length > 200 ? `${command.slice(0, 200)}…` : command}\`\n${lines.map((l) => `- ${l}`).join("\n")}\n(${nRules} playbook rule(s); read-only segments such as cat or grep are skipped, as at the call; stage guards are judged separately)` };
|
|
792
|
+
}
|
|
793
|
+
|
|
721
794
|
export async function gateDoctor(o: GateCtx): Promise<RunResult> {
|
|
722
795
|
const { root, rest } = o;
|
|
723
796
|
// read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
|