opencode-model-router 2.8.0 → 2.9.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 +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
|
@@ -0,0 +1,1492 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { splitPlan, structureMask, type PlacedStep } from "../../routing/commands/annotate-plan";
|
|
3
|
+
import { fenceMask } from "../../routing/classify/fences";
|
|
4
|
+
import { parseRouteLine } from "../../routing/classify/route-line";
|
|
5
|
+
import type { RouteLine } from "../../routing/classify/types";
|
|
6
|
+
import type { AnnotatedPlan, PlanStep } from "../../routing/engine";
|
|
7
|
+
import { parseAcceptanceBlock } from "../../verify/dod";
|
|
8
|
+
import { ExecutorError, PHASE_ID_PATTERN, isTaskId, type TaskKind, type Tier } from "../types";
|
|
9
|
+
// @@IMPORTS-CHECK
|
|
10
|
+
|
|
11
|
+
export interface Span { line: number; endLine: number }
|
|
12
|
+
export interface CompileIssue { code: string; line: number; message: string }
|
|
13
|
+
export interface LabeledList { line: number; text: string; none: boolean }
|
|
14
|
+
export type IdSource = "explicit" | "dogfood" | "preflight" | "block" | "hash";
|
|
15
|
+
|
|
16
|
+
export interface ParsedTask {
|
|
17
|
+
id: string;
|
|
18
|
+
idSource: IdSource;
|
|
19
|
+
phase: string | null;
|
|
20
|
+
kind: TaskKind;
|
|
21
|
+
title: string;
|
|
22
|
+
text: string;
|
|
23
|
+
body: string;
|
|
24
|
+
span: Span;
|
|
25
|
+
subtasks: string[];
|
|
26
|
+
tierTag: Tier | null;
|
|
27
|
+
route: { line: string; fields: RouteLine | null; conflict: boolean; inferred?: boolean } | null;
|
|
28
|
+
verify: "required" | "deferred" | "none" | null;
|
|
29
|
+
cap: number | "none" | null;
|
|
30
|
+
acceptance: string | null;
|
|
31
|
+
writesLine: LabeledList | null;
|
|
32
|
+
readsLine: LabeledList | null;
|
|
33
|
+
manual: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface OrderChain { groups: string[][]; line: number; raw: string }
|
|
37
|
+
|
|
38
|
+
export interface ParsedPhase {
|
|
39
|
+
id: string;
|
|
40
|
+
title: string;
|
|
41
|
+
wave: string;
|
|
42
|
+
span: Span;
|
|
43
|
+
dogfood: boolean;
|
|
44
|
+
synthetic: boolean;
|
|
45
|
+
dependsOn: Array<{ id: string; external: boolean; line: number }>;
|
|
46
|
+
order: OrderChain | null;
|
|
47
|
+
fixTemplate: ParsedTask | null;
|
|
48
|
+
intro: string;
|
|
49
|
+
newTests: string | null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ParsedWave { id: string; title: string; line: number; phases: string[] }
|
|
53
|
+
export interface GraphBlock {
|
|
54
|
+
line: number;
|
|
55
|
+
edges: Array<{ from: string; to: string; line: number; raw: string }>;
|
|
56
|
+
}
|
|
57
|
+
export interface OwnershipRow { path: string; owners: string[]; format: "file-major" | "phase-major"; line: number }
|
|
58
|
+
export interface ExplicitPhrase {
|
|
59
|
+
subject: { kind: "task" | "phase" | "wave"; id: string };
|
|
60
|
+
verb: string;
|
|
61
|
+
refs: string[];
|
|
62
|
+
line: number;
|
|
63
|
+
excerpt: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ParsedPlan {
|
|
67
|
+
waves: ParsedWave[];
|
|
68
|
+
phases: ParsedPhase[];
|
|
69
|
+
tasks: ParsedTask[];
|
|
70
|
+
graphs: GraphBlock[];
|
|
71
|
+
ownership: OwnershipRow[];
|
|
72
|
+
phrases: ExplicitPhrase[];
|
|
73
|
+
sharedContextRaw: string;
|
|
74
|
+
sharedContextSource: "block" | "preamble";
|
|
75
|
+
warnings: CompileIssue[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
79
|
+
// Id grammar (memo §3)
|
|
80
|
+
|
|
81
|
+
/** Explicit task id: the leading token of a top-level item, after the marker and optional checkbox. */
|
|
82
|
+
const EXPLICIT_ID_RE = /^(?:\*\*)?((?:T|P)?\d+(?:\.(?:\d+|[A-Z]{1,4}))+[a-z]?)(?:\*\*)?(?=\s|:|$)/;
|
|
83
|
+
|
|
84
|
+
/** Pure-tag code spans: a code span whose whole content is `[tier:X]` or `[route …]`. */
|
|
85
|
+
const PURE_TAG_SPAN_RE = /(`+)[ \t]*(\[(?:tier:[A-Za-z]+|route(?:[ \t][^\]`]*)?)\])[ \t]*\1/g;
|
|
86
|
+
|
|
87
|
+
/** Replaces pure-tag code spans (`` `[tier:medium]` ``, `` `[route …]` ``) by their plain text. */
|
|
88
|
+
export function unwrapPureTagSpans(line: string): string {
|
|
89
|
+
return line.replace(PURE_TAG_SPAN_RE, "$2");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const LIST_MARKER_RE = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+/;
|
|
93
|
+
const HEADING_HASH_RE = /^[ \t]*#{1,6}[ \t]+/;
|
|
94
|
+
const CHECKBOX_RE = /^\[[ xX]\][ \t]*/;
|
|
95
|
+
const TIER_TAG_RE = /\[tier:[A-Za-z]+\]/g;
|
|
96
|
+
const ROUTE_TAG_RE = /\[route(?:[ \t][^\]]*)?\]/g;
|
|
97
|
+
const VERIFY_TOKEN_RE = /\bVERIFY:[A-Za-z]+\b/g;
|
|
98
|
+
const CAP_TOKEN_RE = /\bCAP:(?:\d+|none)\b/g;
|
|
99
|
+
|
|
100
|
+
/** The stable text an id hash is computed from; annotation tags and markup never change it. */
|
|
101
|
+
export function normalizeFirstLine(line: string): string {
|
|
102
|
+
let s = line.replace(/\r?\n[\s\S]*$/, "");
|
|
103
|
+
s = s.replace(HEADING_HASH_RE, "").replace(LIST_MARKER_RE, "").replace(CHECKBOX_RE, "");
|
|
104
|
+
s = unwrapPureTagSpans(s);
|
|
105
|
+
s = s.replace(TIER_TAG_RE, " ").replace(ROUTE_TAG_RE, " ").replace(VERIFY_TOKEN_RE, " ").replace(CAP_TOKEN_RE, " ");
|
|
106
|
+
s = s.replace(/\*\*|__/g, "");
|
|
107
|
+
return s.normalize("NFC").replace(/\s+/g, " ").trim().toLowerCase();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `S<8 hex of sha1(normalized first line)>-<ordinal among equal hashes>`; `seen` counts per hash, in plan order. */
|
|
111
|
+
export function fallbackTaskId(firstLine: string, seen: Map<string, number>): string {
|
|
112
|
+
const hash = createHash("sha1").update(normalizeFirstLine(firstLine), "utf8").digest("hex").slice(0, 8);
|
|
113
|
+
const n = (seen.get(hash) ?? 0) + 1;
|
|
114
|
+
seen.set(hash, n);
|
|
115
|
+
return `S${hash}-${n}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
119
|
+
// Errors and small helpers
|
|
120
|
+
|
|
121
|
+
function compileError(code: string, line: number, message: string): ExecutorError {
|
|
122
|
+
return new ExecutorError("E_COMPILE", `${code} (line ${line}): ${message}`, { code, line });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function warn(out: CompileIssue[], code: string, line: number, message: string): void {
|
|
126
|
+
out.push({ code, line, message });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
130
|
+
// Headings and block labels (memo §2 steps 2-3)
|
|
131
|
+
|
|
132
|
+
const LINE_SPLIT_RE = /\r\n|\n|\r/;
|
|
133
|
+
const PID = "[A-Za-z0-9]+(?:\\.[A-Za-z0-9]+)*";
|
|
134
|
+
const WAVE_HEADING_RE = /^ {0,3}#{2,3}[ \t]+Wave[ \t]+(\d+[A-Za-z]?)\b(.*)$/;
|
|
135
|
+
const PHASE_WORD_HEADING_RE = new RegExp(`^ {0,3}#{2,4}[ \\t]+Phase[ \\t]+(${PID})(.*)$`);
|
|
136
|
+
const PHASE_P_HEADING_RE = /^ {0,3}#{2,4}[ \t]+(P\d+(?:\.\d+)+)\b(.*)$/;
|
|
137
|
+
const DOGFOOD_HEADING_RE = /^ {0,3}#{2,4}[ \t]+Dogfood switch DF-(\d+)\b(.*)$/;
|
|
138
|
+
const GENERIC_HEADING_RE = new RegExp(`^ {0,3}#{2,4}[ \\t]+(?:\\*\\*)?(${PID})(?:\\*\\*)?(?=[\\s:.)]|$)(.*)$`);
|
|
139
|
+
const ANY_HEADING_RE = /^ {0,3}#{1,6}[ \t]+(.*)$/;
|
|
140
|
+
/** `Task`/`Steps` (singular or looser wording) label a task list only when marked (heading or bold), never as plain prose. */
|
|
141
|
+
const BLOCK_LABEL_RE =
|
|
142
|
+
/^ {0,3}(?:(?:#{1,6}[ \t]+|\*\*|__)(Task|Steps)(?=(?:\*\*|__)?[ \t]*:?(?:\*\*|__)?[ \t]*$)|(?:#{1,6}[ \t]+|\*\*|__)(Pre-flight|Tasks|New tests|Acceptance criteria|Definition of Done|QA review|Order)\b|(Pre-flight|Tasks|New tests|Acceptance criteria|Definition of Done|QA review|Order)(?=[ \t]*(?:\([^)\n]*\))?[ \t]*(?::|$)))/;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Any other bold label at the start of a line (`**Fallback:** …`, `**Goal:** …`) ends a Tasks block: the list under it is
|
|
146
|
+
* not a task list (cpx:3904, the DF-2 fallback steps). `Writes:`/`Reads:` belong to the task above and do not end it.
|
|
147
|
+
*/
|
|
148
|
+
const OTHER_LABEL_RE = /^ {0,3}(?:\*\*|__)(?!Writes\b|Reads\b)[A-Z][^*_\n]{0,60}?(?::(?:\*\*|__)|(?:\*\*|__):)/;
|
|
149
|
+
|
|
150
|
+
type BlockName = "pre-flight" | "tasks" | "new-tests" | "acceptance" | "dod" | "qa-review" | "order";
|
|
151
|
+
|
|
152
|
+
function blockNameOf(label: string): BlockName {
|
|
153
|
+
switch (label) {
|
|
154
|
+
case "Pre-flight": return "pre-flight";
|
|
155
|
+
case "Tasks":
|
|
156
|
+
case "Task":
|
|
157
|
+
case "Steps": return "tasks";
|
|
158
|
+
case "New tests": return "new-tests";
|
|
159
|
+
case "Acceptance criteria": return "acceptance";
|
|
160
|
+
case "Definition of Done": return "dod";
|
|
161
|
+
case "QA review": return "qa-review";
|
|
162
|
+
default: return "order";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
interface HeadingInfo {
|
|
167
|
+
/** 0-based line index. */
|
|
168
|
+
idx: number;
|
|
169
|
+
/** Markdown heading level (number of `#`). */
|
|
170
|
+
level: number;
|
|
171
|
+
/** Heading text without the hashes. */
|
|
172
|
+
text: string;
|
|
173
|
+
kind: "wave" | "phase" | "dogfood" | "generic" | "other";
|
|
174
|
+
/** Wave id, phase id, `DF<n>` or the id-shaped first token of a generic heading. */
|
|
175
|
+
id: string;
|
|
176
|
+
/** What follows the id on the heading line. */
|
|
177
|
+
rest: string;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function headingLevelOf(line: string): number {
|
|
181
|
+
let n = 0;
|
|
182
|
+
let i = 0;
|
|
183
|
+
while (i < line.length && line[i] === " ") i += 1;
|
|
184
|
+
while (line[i] === "#") {
|
|
185
|
+
n += 1;
|
|
186
|
+
i += 1;
|
|
187
|
+
}
|
|
188
|
+
return n;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* `## 3. Waves, phases, tasks`: a bare number with a trailing period labels a document section, not a phase, unless the section holds
|
|
193
|
+
* list items with a task id of its own (`<n>.…`) before the next heading of any level.
|
|
194
|
+
*/
|
|
195
|
+
function isNumberedSectionHeading(lines: readonly string[], mask: readonly boolean[], idx: number, id: string, rest: string): boolean {
|
|
196
|
+
if (!/^\d+$/.test(id) || !rest.startsWith(".")) return false;
|
|
197
|
+
const own = new RegExp(`^ {0,3}(?:[-*+]|\\d{1,9}[.)])[ \\t]+(?:\\[[ xX]\\][ \\t]+)?(?:\\*\\*|__)?T?${id}\\.`);
|
|
198
|
+
for (let j = idx + 1; j < lines.length; j += 1) {
|
|
199
|
+
if (mask[j] === true) continue;
|
|
200
|
+
const l = lines[j] as string;
|
|
201
|
+
if (ANY_HEADING_RE.test(l)) break;
|
|
202
|
+
if (own.test(l)) return false;
|
|
203
|
+
}
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Headings on unmasked lines, classified (memo §2 step 2). */
|
|
208
|
+
function scanHeadings(lines: readonly string[], mask: readonly boolean[]): HeadingInfo[] {
|
|
209
|
+
const out: HeadingInfo[] = [];
|
|
210
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
211
|
+
if (mask[i] === true) continue;
|
|
212
|
+
const line = lines[i] as string;
|
|
213
|
+
const any = ANY_HEADING_RE.exec(line);
|
|
214
|
+
if (any === null) continue;
|
|
215
|
+
const level = headingLevelOf(line);
|
|
216
|
+
const text = (any[1] as string).replace(/[ \t]+#+[ \t]*$/, "").trim();
|
|
217
|
+
const base = { idx: i, level, text };
|
|
218
|
+
const wave = WAVE_HEADING_RE.exec(line);
|
|
219
|
+
if (wave !== null) {
|
|
220
|
+
out.push({ ...base, kind: "wave", id: wave[1] as string, rest: wave[2] ?? "" });
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const df = DOGFOOD_HEADING_RE.exec(line);
|
|
224
|
+
if (df !== null) {
|
|
225
|
+
out.push({ ...base, kind: "dogfood", id: `DF${df[1] as string}`, rest: df[2] ?? "" });
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const pw = PHASE_WORD_HEADING_RE.exec(line) ?? PHASE_P_HEADING_RE.exec(line);
|
|
229
|
+
if (pw !== null && level >= 2 && level <= 4) {
|
|
230
|
+
out.push({ ...base, kind: "phase", id: pw[1] as string, rest: pw[2] ?? "" });
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const gen = level >= 2 && level <= 4 ? GENERIC_HEADING_RE.exec(line) : null;
|
|
234
|
+
if (gen !== null && !isNumberedSectionHeading(lines, mask, i, gen[1] as string, gen[2] ?? "")) {
|
|
235
|
+
out.push({ ...base, kind: "generic", id: gen[1] as string, rest: gen[2] ?? "" });
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
out.push({ ...base, kind: "other", id: "", rest: "" });
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 1-based line of a top-level fence that is still open at the end of the text and swallows everything after it (the structure mask runs
|
|
245
|
+
* to EOF), else 0. The probe lines let the shared `fenceMask` tell "open at EOF" from "closed": a long closer ends an open fence of its
|
|
246
|
+
* character, so the probe's `x` stays unmasked only when a fence was open.
|
|
247
|
+
*/
|
|
248
|
+
function unclosedFenceLine(lines: readonly string[], fm: readonly boolean[], mask: readonly boolean[]): number {
|
|
249
|
+
let start = -1;
|
|
250
|
+
for (let i = lines.length - 1; i >= 0 && fm[i] === true; i -= 1) start = i;
|
|
251
|
+
if (start < 0) return 0;
|
|
252
|
+
for (const probe of ["`".repeat(200), "~".repeat(200)]) {
|
|
253
|
+
const m = fenceMask([...lines, probe, "x"]);
|
|
254
|
+
if (m[lines.length + 1] !== true) {
|
|
255
|
+
for (let i = start; i < lines.length; i += 1) if (mask[i] !== true) return 0;
|
|
256
|
+
return start + 1;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return 0;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const ACCEPT_OPEN_RE = /^\s*\[(?:acceptance|dod)\]\s*$/i;
|
|
263
|
+
const ACCEPT_CLOSE_RE = /^\s*\[\/(?:acceptance|dod)\]\s*$/i;
|
|
264
|
+
|
|
265
|
+
/** 1-based line of an `[acceptance]` opener that never closes, else 0. */
|
|
266
|
+
function unclosedAcceptanceLine(lines: readonly string[], mask: readonly boolean[]): number {
|
|
267
|
+
let open = 0;
|
|
268
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
269
|
+
if (mask[i] === true) continue;
|
|
270
|
+
const line = lines[i] as string;
|
|
271
|
+
if (open === 0) {
|
|
272
|
+
if (ACCEPT_OPEN_RE.test(line)) open = i + 1;
|
|
273
|
+
} else if (ACCEPT_CLOSE_RE.test(line)) {
|
|
274
|
+
open = 0;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return open;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
281
|
+
// Per-step text (memo §2 step 7)
|
|
282
|
+
|
|
283
|
+
const ITEM_RE = /^( {0,3})([-*+]|\d{1,9}[.)])([ \t]+)\S/;
|
|
284
|
+
const ITEM_LEAD_RE = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+/;
|
|
285
|
+
const DOGFOOD_ID_RE = /^(?:\*\*)?DF-?(\d+)\.(\d+|QA|FIX)(?:\*\*)?(?=\s|:|$)/i;
|
|
286
|
+
const TIER_RE = /\[tier:(fast|medium|heavy)\]/i;
|
|
287
|
+
const VERIFY_RE = /\bVERIFY:([A-Za-z]+)\b/;
|
|
288
|
+
const CAP_RE = /\bCAP:(\d+|none)\b/;
|
|
289
|
+
const INLINE_CODE_RE = /`[^`\n]*`/g;
|
|
290
|
+
const WRITES_READS_LABEL_RE = /\b(Writes|Reads)(?:[ \t]*\([^)\n]*\))?(?:\*\*|__)?:(?:\*\*|__)?/g;
|
|
291
|
+
const ROUTE_START_LINE_RE = /^\s*\[route\b/;
|
|
292
|
+
const NESTED_ITEM_RE = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+/;
|
|
293
|
+
|
|
294
|
+
/** `Writes:`/`Reads:` labels of a line, outside inline code (offsets stay those of the original line). */
|
|
295
|
+
function labelsOf(line: string): RegExpMatchArray[] {
|
|
296
|
+
return [...line.replace(INLINE_CODE_RE, (m) => " ".repeat(m.length)).matchAll(WRITES_READS_LABEL_RE)];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function escapeRe(s: string): string {
|
|
300
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function columnsOf(ws: string): number {
|
|
304
|
+
let n = 0;
|
|
305
|
+
for (const ch of ws) n += ch === "\t" ? 4 : 1;
|
|
306
|
+
return n;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Content column of a list item (0 for a heading-run step or an indented line). */
|
|
310
|
+
function contentColumn(firstLine: string): number {
|
|
311
|
+
const m = ITEM_RE.exec(firstLine);
|
|
312
|
+
if (m === null) return 0;
|
|
313
|
+
return (m[1] as string).length + (m[2] as string).length + columnsOf(m[3] as string);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Removes up to `cols` columns of leading whitespace. */
|
|
317
|
+
function dedentLine(line: string, cols: number): string {
|
|
318
|
+
let n = 0;
|
|
319
|
+
let i = 0;
|
|
320
|
+
while (i < line.length && n < cols) {
|
|
321
|
+
const ch = line[i];
|
|
322
|
+
if (ch === " ") n += 1;
|
|
323
|
+
else if (ch === "\t") n += 4;
|
|
324
|
+
else break;
|
|
325
|
+
i += 1;
|
|
326
|
+
}
|
|
327
|
+
return line.slice(i);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function splitStepLines(text: string): string[] {
|
|
331
|
+
const lines = text.split(LINE_SPLIT_RE);
|
|
332
|
+
if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
|
|
333
|
+
return lines;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The item's lead (what follows the marker/heading hashes and the checkbox) of a step's first line. */
|
|
337
|
+
function leadOf(firstLine: string): string {
|
|
338
|
+
return firstLine.replace(HEADING_HASH_RE, "").replace(ITEM_LEAD_RE, "").replace(CHECKBOX_RE, "");
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function withoutInlineCode(line: string): string {
|
|
342
|
+
return line.replace(INLINE_CODE_RE, " ");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function titleOf(firstLine: string, idToken: string | null): string {
|
|
346
|
+
let s = unwrapPureTagSpans(leadOf(firstLine));
|
|
347
|
+
s = s.replace(TIER_TAG_RE, " ").replace(ROUTE_TAG_RE, " ").replace(VERIFY_TOKEN_RE, " ").replace(CAP_TOKEN_RE, " ");
|
|
348
|
+
s = s.replace(/\*\*|__/g, "").replace(/\s+/g, " ").trim();
|
|
349
|
+
if (idToken !== null && s.startsWith(idToken)) s = s.slice(idToken.length).replace(/^[\s:.\-–—]+/, "");
|
|
350
|
+
return s.slice(0, 120).trim();
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Dedented body: fenced lines blanked, pure-tag code spans unwrapped. */
|
|
354
|
+
function bodyLinesOf(stepLines: readonly string[]): { body: string[]; fenced: boolean[] } {
|
|
355
|
+
const first = stepLines[0] ?? "";
|
|
356
|
+
const col = contentColumn(first);
|
|
357
|
+
const dedented = stepLines.map((l, i) => (i === 0 ? l : dedentLine(l, col)));
|
|
358
|
+
const fenced = fenceMask(dedented);
|
|
359
|
+
const body = dedented.map((l, i) => (fenced[i] === true ? "" : unwrapPureTagSpans(l)));
|
|
360
|
+
return { body, fenced };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Raw text of the first `[acceptance]`…`[/acceptance]` pair of non-fenced lines, validated by `parseAcceptanceBlock`. */
|
|
364
|
+
function firstAcceptance(body: readonly string[], line: number, out: CompileIssue[]): string | null {
|
|
365
|
+
let open = -1;
|
|
366
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
367
|
+
const l = body[i] as string;
|
|
368
|
+
if (open < 0) {
|
|
369
|
+
if (ACCEPT_OPEN_RE.test(l)) open = i;
|
|
370
|
+
} else if (ACCEPT_CLOSE_RE.test(l)) {
|
|
371
|
+
const raw = body.slice(open, i + 1).join("\n");
|
|
372
|
+
if (parseAcceptanceBlock(raw) === null) warn(out, "acceptance-malformed", line + open, "acceptance block did not parse");
|
|
373
|
+
return raw;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The raw route line parseRouteLine removed from `body` (first line that differs from the stripped text). */
|
|
380
|
+
function removedRouteLine(body: string, stripped: string): string | null {
|
|
381
|
+
const a = body.split(LINE_SPLIT_RE);
|
|
382
|
+
const b = stripped.split(LINE_SPLIT_RE);
|
|
383
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
384
|
+
if (a[i] !== b[i]) return (a[i] as string).trim();
|
|
385
|
+
}
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Matcher for the item line of a subtask of `parentId` (`2.3.2.a`), else null. */
|
|
390
|
+
function subtaskItemRe(parentId: string | null): RegExp | null {
|
|
391
|
+
if (parentId === null) return null;
|
|
392
|
+
const bare = parentId.replace(/^(?:T|P)(?=\d)/, "");
|
|
393
|
+
return new RegExp(`^[ \\t]*(?:[-*+]|\\d{1,9}[.)])[ \\t]+(?:\\*\\*)?(?:T|P)?${escapeRe(bare)}\\.([a-z])\\b`);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
interface LabelParse {
|
|
397
|
+
writes: LabeledList | null;
|
|
398
|
+
reads: LabeledList | null;
|
|
399
|
+
subtasks: string[];
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function mergeLabeled(prev: LabeledList | null, line: number, text: string): LabeledList {
|
|
403
|
+
const trimmed = text.replace(/^(?:\*\*|__)/, "").replace(/\s+/g, " ").trim();
|
|
404
|
+
const none = /^(?:`?none`?|\*\*none\*\*)[.;]?$/i.test(trimmed);
|
|
405
|
+
if (prev === null) return { line, text: trimmed, none };
|
|
406
|
+
return { line: prev.line, text: `${prev.text} ${trimmed}`.trim(), none: prev.none && none };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* `Writes:` / `Reads:` segments and subtask ids of a task body (memo §2 step 7). A segment runs to the other label, a blank line, the next
|
|
411
|
+
* item at the task's indent, an acceptance block, a route line or a subtask item; a label with nothing after it takes the nested items that
|
|
412
|
+
* follow. Several labels of one kind are merged (never dropped). Linear: every line is visited once per segment it belongs to, and a
|
|
413
|
+
* segment never extends over a line another segment started on.
|
|
414
|
+
*/
|
|
415
|
+
function parseLabels(body: readonly string[], firstLine: number, parentId: string | null, hashItems: boolean): LabelParse {
|
|
416
|
+
const sub = subtaskItemRe(parentId);
|
|
417
|
+
let writes: LabeledList | null = null;
|
|
418
|
+
let reads: LabeledList | null = null;
|
|
419
|
+
const subtasks: string[] = [];
|
|
420
|
+
const inAcceptance: boolean[] = new Array<boolean>(body.length).fill(false);
|
|
421
|
+
let acc = false;
|
|
422
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
423
|
+
const l = body[i] as string;
|
|
424
|
+
if (!acc && ACCEPT_OPEN_RE.test(l)) acc = true;
|
|
425
|
+
inAcceptance[i] = acc;
|
|
426
|
+
if (acc && ACCEPT_CLOSE_RE.test(l)) acc = false;
|
|
427
|
+
}
|
|
428
|
+
const stops = (l: string): boolean =>
|
|
429
|
+
// The body is dedented to the item's content column, so a nested item sits at column 0 here; a sibling item cannot be in a step.
|
|
430
|
+
l.trim() === "" || ACCEPT_OPEN_RE.test(l) || ROUTE_START_LINE_RE.test(l) || (sub !== null && sub.test(l));
|
|
431
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
432
|
+
const l = body[i] as string;
|
|
433
|
+
if (inAcceptance[i] === true) continue;
|
|
434
|
+
if (i > 0) {
|
|
435
|
+
const m = sub?.exec(l) ?? null;
|
|
436
|
+
if (m !== null) subtasks.push(`${parentId ?? ""}.${m[1] as string}`);
|
|
437
|
+
else if (hashItems && NESTED_ITEM_RE.test(l)) {
|
|
438
|
+
const n = normalizeFirstLine(l);
|
|
439
|
+
if (n !== "") subtasks.push(n);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const labels = labelsOf(l);
|
|
443
|
+
for (let k = 0; k < labels.length; k += 1) {
|
|
444
|
+
const lab = labels[k] as RegExpMatchArray;
|
|
445
|
+
const start = (lab.index ?? 0) + lab[0].length;
|
|
446
|
+
const end = k + 1 < labels.length ? (labels[k + 1]?.index ?? l.length) : l.length;
|
|
447
|
+
let text = l.slice(start, end);
|
|
448
|
+
if (k + 1 === labels.length) {
|
|
449
|
+
for (let j = i + 1; j < body.length; j += 1) {
|
|
450
|
+
const next = body[j] as string;
|
|
451
|
+
if (inAcceptance[j] === true || stops(next) || labelsOf(next).length > 0) break;
|
|
452
|
+
text += ` ${next.trim()}`;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (lab[1] === "Writes") writes = mergeLabeled(writes, firstLine + i, text);
|
|
456
|
+
else reads = mergeLabeled(reads, firstLine + i, text);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return { writes, reads, subtasks };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
463
|
+
// `Order:` chains and `Depends on:` lines (memo §2 step 4)
|
|
464
|
+
|
|
465
|
+
const ORDER_LABEL_RE = /Order(?:\*\*|__)?:(?:\*\*|__)?/;
|
|
466
|
+
const ORDER_ID_Y = /(?:\*\*)?((?:T|P)?\d+(?:\.(?:\d+|[A-Z]{1,4}))+[a-z]?)(?:\*\*)?(?=[\s,;:.)∥|→-]|$)/y;
|
|
467
|
+
const ORDER_QA_Y = /QA(?![A-Za-z0-9_-])/y;
|
|
468
|
+
const ORDER_FIX_Y = /FIX(?:[ \t]*\([ \t]*[A-Za-z-]+[ \t]*\))?(?![A-Za-z0-9_])/y;
|
|
469
|
+
const ORDER_WORD_PAREN_Y = /[ \t]*\([ \t]*[A-Za-z-]+[ \t]*\)/y;
|
|
470
|
+
const ORDER_ARROW_Y = /[ \t]*(?:→|-->|->)[ \t]*/y;
|
|
471
|
+
const ORDER_SEP_Y = /[ \t]*(?:∥|\|\||,)[ \t]*/y;
|
|
472
|
+
const ORDER_OPEN_Y = /[ \t]*\([ \t]*/y;
|
|
473
|
+
const ORDER_CLOSE_Y = /[ \t]*\)/y;
|
|
474
|
+
|
|
475
|
+
function stickyAt(re: RegExp, s: string, at: number): RegExpExecArray | null {
|
|
476
|
+
re.lastIndex = at;
|
|
477
|
+
return re.exec(s);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** `chain := group (ARROW group)*`; stops at the first token outside the grammar. QA → `<P>.QA`, FIX → `<P>.FIX`. */
|
|
481
|
+
function parseOrderChain(s: string, phaseId: string): string[][] {
|
|
482
|
+
const groups: string[][] = [];
|
|
483
|
+
let i = 0;
|
|
484
|
+
const item = (at: number): { id: string; end: number } | null => {
|
|
485
|
+
const id = stickyAt(ORDER_ID_Y, s, at);
|
|
486
|
+
if (id !== null) {
|
|
487
|
+
const end = at + id[0].length;
|
|
488
|
+
// `6.2.FIX (loop)`: the FIX template spelled as an id keeps its optional parenthetical word.
|
|
489
|
+
const tail = (id[1] as string).endsWith(".FIX") ? stickyAt(ORDER_WORD_PAREN_Y, s, end) : null;
|
|
490
|
+
return { id: id[1] as string, end: tail === null ? end : end + tail[0].length };
|
|
491
|
+
}
|
|
492
|
+
const qa = stickyAt(ORDER_QA_Y, s, at);
|
|
493
|
+
if (qa !== null) return { id: `${phaseId}.QA`, end: at + qa[0].length };
|
|
494
|
+
const fix = stickyAt(ORDER_FIX_Y, s, at);
|
|
495
|
+
if (fix !== null) return { id: `${phaseId}.FIX`, end: at + fix[0].length };
|
|
496
|
+
return null;
|
|
497
|
+
};
|
|
498
|
+
const group = (at: number): { ids: string[]; end: number } | null => {
|
|
499
|
+
const open = stickyAt(ORDER_OPEN_Y, s, at);
|
|
500
|
+
if (open === null) {
|
|
501
|
+
let p = at;
|
|
502
|
+
while (s[p] === " " || s[p] === "\t") p += 1;
|
|
503
|
+
const first = item(p);
|
|
504
|
+
return first === null ? null : { ids: [first.id], end: first.end };
|
|
505
|
+
}
|
|
506
|
+
const ids: string[] = [];
|
|
507
|
+
let pos = at + open[0].length;
|
|
508
|
+
for (;;) {
|
|
509
|
+
while (s[pos] === " " || s[pos] === "\t") pos += 1;
|
|
510
|
+
const it = item(pos);
|
|
511
|
+
if (it === null) return null;
|
|
512
|
+
ids.push(it.id);
|
|
513
|
+
pos = it.end;
|
|
514
|
+
const sep = stickyAt(ORDER_SEP_Y, s, pos);
|
|
515
|
+
if (sep === null) break;
|
|
516
|
+
pos += sep[0].length;
|
|
517
|
+
}
|
|
518
|
+
const close = stickyAt(ORDER_CLOSE_Y, s, pos);
|
|
519
|
+
return close === null ? null : { ids, end: pos + close[0].length };
|
|
520
|
+
};
|
|
521
|
+
for (;;) {
|
|
522
|
+
const g = group(i);
|
|
523
|
+
if (g === null) break;
|
|
524
|
+
groups.push(g.ids);
|
|
525
|
+
i = g.end;
|
|
526
|
+
const arrow = stickyAt(ORDER_ARROW_Y, s, i);
|
|
527
|
+
if (arrow === null) break;
|
|
528
|
+
i += arrow[0].length;
|
|
529
|
+
}
|
|
530
|
+
return groups;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* The `Depends on:` label: at the start of a line (after an optional list marker and bold), or bold anywhere
|
|
535
|
+
* (`**Worktree:** … · **Depends on:** 0.P`). The colon is required, so prose "depends on X" is not a label (D8).
|
|
536
|
+
*/
|
|
537
|
+
const DEPENDS_LABEL_RE =
|
|
538
|
+
/(?:^[ \t>]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)?(?:\*\*|__)?|\*\*|__)Depends on(?:\*\*|__)?:(?:\*\*|__)?/i;
|
|
539
|
+
const DF_TOKEN_RE = /\bDF-(\d+)\b/g;
|
|
540
|
+
const PID_TOKEN_RE = /(?<![A-Za-z0-9.])[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)*(?![A-Za-z0-9])/g;
|
|
541
|
+
const DOTTED_ID_RE = /^[A-Za-z]?\d+(?:\.[A-Za-z0-9]+)+$/;
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* End of the dependency clause: the next bold label, a middle dot or a "parallel with"-style phrase (the ids such a
|
|
545
|
+
* phrase governs are dropped with the rest), or a sentence boundary `. ` unless an id follows (QA-2.3-27). Not `;`:
|
|
546
|
+
* `1.1 (config); 1.3` keeps both ids, and so does a clause wrapped as `1.1.` + newline + `1.3`.
|
|
547
|
+
*/
|
|
548
|
+
const DEPENDS_CLAUSE_END_RE =
|
|
549
|
+
/\*\*[A-Za-z][^*\n]*:\*\*|·|\.[ \t]+(?![ \t]*`?(?:DF-?\d|[A-Za-z]?\d+\.[A-Za-z0-9]))|\b(?:in parallel|parallel with|parallel to|alongside|independent of)\b/i;
|
|
550
|
+
|
|
551
|
+
/** The part of a `Depends on:` line that names dependencies (cut at the clause end, see DEPENDS_CLAUSE_END_RE). */
|
|
552
|
+
function dependsText(line: string): string | null {
|
|
553
|
+
const m = DEPENDS_LABEL_RE.exec(line);
|
|
554
|
+
if (m === null) return null;
|
|
555
|
+
const rest = line.slice(m.index + m[0].length);
|
|
556
|
+
const cut = rest.search(DEPENDS_CLAUSE_END_RE);
|
|
557
|
+
return cut >= 0 ? rest.slice(0, cut) : rest;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function resolveDepends(
|
|
561
|
+
text: string,
|
|
562
|
+
line: number,
|
|
563
|
+
selfId: string,
|
|
564
|
+
known: ReadonlySet<string>,
|
|
565
|
+
warnings: CompileIssue[],
|
|
566
|
+
): Array<{ id: string; external: boolean; line: number }> {
|
|
567
|
+
const out: Array<{ id: string; external: boolean; line: number }> = [];
|
|
568
|
+
const seen = new Set<string>();
|
|
569
|
+
const add = (id: string, external: boolean): void => {
|
|
570
|
+
if (id === selfId || seen.has(id)) return;
|
|
571
|
+
seen.add(id);
|
|
572
|
+
out.push({ id, external, line });
|
|
573
|
+
};
|
|
574
|
+
const cleaned = text.replace(/§\S+/g, " ").replace(/`/g, " ");
|
|
575
|
+
const dfRemoved = cleaned.replace(DF_TOKEN_RE, (_all, n: string) => {
|
|
576
|
+
// `DF-<n>` is external unless the plan has the `Dogfood switch DF-<n>` section; then it is a phase gate like any other.
|
|
577
|
+
add(`DF${n}`, !known.has(`DF${n}`));
|
|
578
|
+
return " ";
|
|
579
|
+
});
|
|
580
|
+
for (const m of dfRemoved.matchAll(PID_TOKEN_RE)) {
|
|
581
|
+
const tok = m[0];
|
|
582
|
+
if (known.has(tok)) add(tok, false);
|
|
583
|
+
else if (DOTTED_ID_RE.test(tok)) warn(warnings, "depends-unknown", line, `Depends on: unknown id ${tok}`);
|
|
584
|
+
}
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
589
|
+
// Graph blocks, ownership tables and explicit phrases (memo §2 step 4)
|
|
590
|
+
|
|
591
|
+
const ARROW_LINE_RE = /\S\s*(?:->|→|-->)\s*\S/;
|
|
592
|
+
const ARROW_SPLIT_RE = /-->|->|→/;
|
|
593
|
+
const NODE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
594
|
+
const GRAPH_KEYWORDS: ReadonlySet<string> = new Set(["graph", "flowchart", "subgraph", "end", "TD", "TB", "BT", "LR", "RL"]);
|
|
595
|
+
const FENCE_CLOSER_RE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*$/;
|
|
596
|
+
|
|
597
|
+
/** Node tokens of one side of an arrow: mermaid labels removed, `A, B` lists supported. */
|
|
598
|
+
function nodesOf(part: string): string[] {
|
|
599
|
+
const cleaned = part.replace(/\|[^|\n]*\|/g, " ").replace(/\[[^\]\n]*\]/g, " ").replace(/\([^)\n]*\)/g, " ").replace(/\{[^}\n]*\}/g, " ");
|
|
600
|
+
const out: string[] = [];
|
|
601
|
+
for (const raw of cleaned.split(/[\s,&;]+/)) {
|
|
602
|
+
const tok = raw.replace(/[.-]+$/, "");
|
|
603
|
+
if (tok !== "" && NODE_RE.test(tok) && !GRAPH_KEYWORDS.has(tok)) out.push(tok);
|
|
604
|
+
}
|
|
605
|
+
return out;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function graphEdgesOfLine(line: string, lineNo: number): GraphBlock["edges"] {
|
|
609
|
+
const parts = line.split(ARROW_SPLIT_RE).map(nodesOf).filter((p) => p.length > 0);
|
|
610
|
+
const edges: GraphBlock["edges"] = [];
|
|
611
|
+
for (let i = 0; i + 1 < parts.length; i += 1) {
|
|
612
|
+
for (const from of parts[i] as string[]) {
|
|
613
|
+
for (const to of parts[i + 1] as string[]) edges.push({ from, to, line: lineNo, raw: line.trim() });
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return edges;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Is the fence at line `i` inside an HTML comment? The structure mask also covers comments, the fence-only mask does not: the
|
|
621
|
+
* nearest masked line before the fence that is not a fence line is a comment line, still open unless it holds the `-->`.
|
|
622
|
+
*/
|
|
623
|
+
function insideComment(lines: readonly string[], fm: readonly boolean[], mask: readonly boolean[], i: number): boolean {
|
|
624
|
+
for (let k = i - 1; k >= 0 && mask[k] === true; k -= 1) {
|
|
625
|
+
if (fm[k] === true) continue;
|
|
626
|
+
return !(lines[k] as string).includes("-->");
|
|
627
|
+
}
|
|
628
|
+
return false;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Fenced blocks (any info string) with at least one arrow line, except those inside HTML comments. */
|
|
632
|
+
function scanGraphs(lines: readonly string[], fm: readonly boolean[], mask: readonly boolean[]): GraphBlock[] {
|
|
633
|
+
const out: GraphBlock[] = [];
|
|
634
|
+
let i = 0;
|
|
635
|
+
while (i < lines.length) {
|
|
636
|
+
if (fm[i] !== true) {
|
|
637
|
+
i += 1;
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
let end = i;
|
|
641
|
+
while (end + 1 < lines.length && fm[end + 1] === true) end += 1;
|
|
642
|
+
if (insideComment(lines, fm, mask, i)) {
|
|
643
|
+
i = end + 1;
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
const last = end > i && FENCE_CLOSER_RE.test(lines[end] as string) ? end : end + 1;
|
|
647
|
+
const edges: GraphBlock["edges"] = [];
|
|
648
|
+
let hasArrow = false;
|
|
649
|
+
for (let k = i + 1; k < last; k += 1) {
|
|
650
|
+
const l = lines[k] as string;
|
|
651
|
+
if (!ARROW_LINE_RE.test(l)) continue;
|
|
652
|
+
hasArrow = true;
|
|
653
|
+
edges.push(...graphEdgesOfLine(l, k + 1));
|
|
654
|
+
}
|
|
655
|
+
if (hasArrow) out.push({ line: i + 1, edges });
|
|
656
|
+
i = end + 1;
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const PHRASE_RES: ReadonlyArray<{ verb: string; re: RegExp }> = [
|
|
662
|
+
{ verb: "after", re: new RegExp(`\\bafter\\s+(?:Phase\\s+)?(${PID})\\b(?:\\s+(?:is\\s+|are\\s+)?(?:merged|merges|passed|done|lands))?`, "gi") },
|
|
663
|
+
{ verb: "before", re: new RegExp(`\\bbefore\\s+(?:Phase\\s+)?(${PID})\\b`, "gi") },
|
|
664
|
+
{ verb: "merged-first", re: new RegExp(`\\b(?:Phase\\s+)?(${PID})\\s+(?:(?:is|are|must|be)\\s+)*merged\\s+first\\b`, "gi") },
|
|
665
|
+
];
|
|
666
|
+
/** Further explicit-dependency phrases (memo §5 pass 3); all carry the `after` semantics (the reference precedes the subject). */
|
|
667
|
+
/** Id-shaped token: a dotted id (`2.3.4`, `P2.1`) or a `T`/`P`/`W` letter plus number; bare words and `QA`/`FIX` never match. */
|
|
668
|
+
const FULL_ID = "(?:[A-Za-z]{0,2}\\d+(?:\\.[A-Za-z0-9]+)+|[TPWtpw]\\d+)";
|
|
669
|
+
const ID_SHAPED_RE = new RegExp(`^${FULL_ID}$`);
|
|
670
|
+
const AFTER_LIKE_RES: readonly RegExp[] = [
|
|
671
|
+
new RegExp(`\\bstarts?\\s+after\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
672
|
+
new RegExp(`\\bdepend(?:s|ing)?\\s+on\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
673
|
+
new RegExp(`\\brequires?\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
674
|
+
new RegExp(`\\bblocked\\s+by\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
675
|
+
new RegExp(`\\bonce\\s+(?:Phase\\s+)?(${FULL_ID})\\s+(?:is\\s+|are\\s+|has\\s+been\\s+)?(?:merged|merges|lands|done|passed)\\b`, "gi"),
|
|
676
|
+
new RegExp(`(?<![A-Za-z0-9.])(?:Phase\\s+)?(${FULL_ID})\\s+merges\\b`, "gi"),
|
|
677
|
+
new RegExp(`\\bbuilds?\\s+on\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
678
|
+
new RegExp(`\\bcodes?\\s+against\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
679
|
+
new RegExp(`\\buses?\\s+the\\s+API\\s+from\\s+(?:Phase\\s+)?(${FULL_ID})(?![A-Za-z0-9.]*[A-Za-z0-9])`, "gi"),
|
|
680
|
+
];
|
|
681
|
+
const MERGED_FIRST_BARE_RE = /\bmerged\s+first\b/i;
|
|
682
|
+
|
|
683
|
+
const QUOTED_RE = /"[^"\n]*"|“[^”\n]*”/g;
|
|
684
|
+
const CLAUSE_SPLIT_RE = /;|\.(?=\s|$)/;
|
|
685
|
+
const CLAUSE_MAX = 160;
|
|
686
|
+
|
|
687
|
+
/** Clauses of one line, bounded by `;`, `. ` and 160 characters; quoted spans are blanked first. */
|
|
688
|
+
function clausesOf(text: string): string[] {
|
|
689
|
+
const out: string[] = [];
|
|
690
|
+
for (const part of text.replace(QUOTED_RE, (q) => " ".repeat(q.length)).split(CLAUSE_SPLIT_RE)) {
|
|
691
|
+
for (let i = 0; i < part.length; i += CLAUSE_MAX) out.push(part.slice(i, i + CLAUSE_MAX));
|
|
692
|
+
}
|
|
693
|
+
return out;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function scanAfterLike(text: string, line: number, subject: ExplicitPhrase["subject"], out: ExplicitPhrase[]): boolean {
|
|
697
|
+
let any = false;
|
|
698
|
+
const seen = new Set<string>();
|
|
699
|
+
// Phrases are collected in line order: only the tail written for this very line can duplicate.
|
|
700
|
+
for (let k = out.length - 1; k >= 0; k -= 1) {
|
|
701
|
+
const p = out[k] as ExplicitPhrase;
|
|
702
|
+
if (p.line < line) break;
|
|
703
|
+
if (p.line === line && p.subject.id === subject.id && p.verb === "after" && p.refs[0] !== undefined) seen.add(p.refs[0]);
|
|
704
|
+
}
|
|
705
|
+
for (const clause of clausesOf(text)) {
|
|
706
|
+
for (const re of AFTER_LIKE_RES) {
|
|
707
|
+
for (const m of clause.matchAll(re)) {
|
|
708
|
+
any = true;
|
|
709
|
+
const ref = m[1] as string;
|
|
710
|
+
if (seen.has(ref)) continue;
|
|
711
|
+
seen.add(ref);
|
|
712
|
+
out.push({ subject, verb: "after", refs: [m[1] as string], line, excerpt: m[0].slice(0, 160) });
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return any;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function scanPhrases(raw: string, line: number, subject: ExplicitPhrase["subject"], out: ExplicitPhrase[]): void {
|
|
720
|
+
const text = withoutInlineCode(raw);
|
|
721
|
+
let any = scanAfterLike(text, line, subject, out);
|
|
722
|
+
for (const { verb, re } of PHRASE_RES) {
|
|
723
|
+
for (const m of text.matchAll(re)) {
|
|
724
|
+
any = true;
|
|
725
|
+
out.push({ subject, verb, refs: [m[1] as string], line, excerpt: m[0].slice(0, 160) });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (!any && MERGED_FIRST_BARE_RE.test(text)) {
|
|
729
|
+
out.push({ subject, verb: "merged-first", refs: [], line, excerpt: text.trim().slice(0, 160) });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function splitCells(row: string): string[] {
|
|
734
|
+
let s = row.trim();
|
|
735
|
+
if (s.startsWith("|")) s = s.slice(1);
|
|
736
|
+
if (s.endsWith("|")) s = s.slice(0, -1);
|
|
737
|
+
return s.split("|").map((c) => c.trim());
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
const TABLE_ROW_RE = /^ {0,3}\|/;
|
|
741
|
+
const TABLE_SEP_RE = /^[\s|:-]*-[\s|:-]*$/;
|
|
742
|
+
const BACKTICK_SPAN_RE = /`([^`\n]+)`/g;
|
|
743
|
+
|
|
744
|
+
function pathLike(s: string): boolean {
|
|
745
|
+
return /[\\/]/.test(s) || /\.[A-Za-z0-9]{1,8}$/.test(s);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function phaseTokens(cell: string, known: ReadonlySet<string>): string[] {
|
|
749
|
+
const out: string[] = [];
|
|
750
|
+
for (const m of cell.replace(/`/g, " ").matchAll(PID_TOKEN_RE)) if (known.has(m[0]) && !out.includes(m[0])) out.push(m[0]);
|
|
751
|
+
return out;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/** Ownership tables, file-major and phase-major; phrases inside phase-major cells become phrases about that phase. */
|
|
755
|
+
function scanTables(
|
|
756
|
+
lines: readonly string[],
|
|
757
|
+
mask: readonly boolean[],
|
|
758
|
+
known: ReadonlySet<string>,
|
|
759
|
+
rows: OwnershipRow[],
|
|
760
|
+
phrases: ExplicitPhrase[],
|
|
761
|
+
): void {
|
|
762
|
+
let i = 0;
|
|
763
|
+
while (i < lines.length) {
|
|
764
|
+
if (mask[i] === true || !TABLE_ROW_RE.test(lines[i] as string)) {
|
|
765
|
+
i += 1;
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
let end = i;
|
|
769
|
+
while (end + 1 < lines.length && mask[end + 1] !== true && TABLE_ROW_RE.test(lines[end + 1] as string)) end += 1;
|
|
770
|
+
const header = splitCells(lines[i] as string);
|
|
771
|
+
const hasSep = end > i && TABLE_SEP_RE.test(lines[i + 1] as string);
|
|
772
|
+
const first = (header[0] ?? "").replace(/[`*_]/g, "").trim();
|
|
773
|
+
const fileMajor = /^(?:File|Path)s?$/i.test(first);
|
|
774
|
+
// An ownership table with named columns (`| Wave | Phase | Owns (writes) |`): the phase and the owned-paths column by header.
|
|
775
|
+
const names = header.map((h) => h.replace(/[`*_]/g, "").trim());
|
|
776
|
+
const namedPhase = names.findIndex((h) => /^Phases?$/i.test(h));
|
|
777
|
+
const namedOwns = names.findIndex((h, c) => c !== namedPhase && /^(?:Owns|Writes)\b/i.test(h));
|
|
778
|
+
const named = !fileMajor && namedPhase >= 0 && namedOwns >= 0;
|
|
779
|
+
const phaseCol = named ? namedPhase : 0;
|
|
780
|
+
const ownsCol = named ? namedOwns : -1;
|
|
781
|
+
for (let r = hasSep ? i + 2 : i + 1; r <= end; r += 1) {
|
|
782
|
+
const cells = splitCells(lines[r] as string);
|
|
783
|
+
const c1 = cells[0] ?? "";
|
|
784
|
+
if (fileMajor) {
|
|
785
|
+
const span = /`([^`\n]+)`/.exec(c1);
|
|
786
|
+
const path = (span?.[1] ?? c1.replace(/[*_]/g, "")).trim();
|
|
787
|
+
if (path === "") continue;
|
|
788
|
+
const owners: string[] = [];
|
|
789
|
+
for (let c = 1; c < cells.length; c += 1) {
|
|
790
|
+
const cell = cells[c] as string;
|
|
791
|
+
const ids = phaseTokens(cell, known);
|
|
792
|
+
const fromHeader = ids.length === 0 && /[^\s\-—–]/.test(cell.replace(/[`*_]/g, "")) && !/^(?:no|none|n\/a)$/i.test(cell.trim());
|
|
793
|
+
for (const id of fromHeader ? phaseTokens(header[c] ?? "", known) : ids) if (!owners.includes(id)) owners.push(id);
|
|
794
|
+
}
|
|
795
|
+
rows.push({ path, owners, format: "file-major", line: r + 1 });
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
const owner = phaseTokens(cells[phaseCol] ?? "", known)[0];
|
|
799
|
+
if (owner === undefined || cells.length < 2) continue;
|
|
800
|
+
const own = cells.slice(phaseCol + 1);
|
|
801
|
+
const c2 = (ownsCol >= 0 ? cells[ownsCol] : own[0]) ?? "";
|
|
802
|
+
for (const m of c2.matchAll(BACKTICK_SPAN_RE)) {
|
|
803
|
+
const p = (m[1] as string).trim();
|
|
804
|
+
if (pathLike(p)) rows.push({ path: p, owners: [owner], format: "phase-major", line: r + 1 });
|
|
805
|
+
}
|
|
806
|
+
scanPhrases(own.join(" | "), r + 1, { kind: "phase", id: owner }, phrases);
|
|
807
|
+
}
|
|
808
|
+
i = end + 1;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
813
|
+
// One task's annotations (memo §2 step 7)
|
|
814
|
+
|
|
815
|
+
interface StepAnno {
|
|
816
|
+
body: string;
|
|
817
|
+
bodyLines: string[];
|
|
818
|
+
tierTag: Tier | null;
|
|
819
|
+
route: ParsedTask["route"];
|
|
820
|
+
verify: ParsedTask["verify"];
|
|
821
|
+
cap: ParsedTask["cap"];
|
|
822
|
+
acceptance: string | null;
|
|
823
|
+
writesLine: LabeledList | null;
|
|
824
|
+
readsLine: LabeledList | null;
|
|
825
|
+
subtasks: string[];
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function isTier(v: unknown): v is Tier {
|
|
829
|
+
return v === "fast" || v === "medium" || v === "heavy";
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function annotateText(text: string, line: number, parentId: string | null, hashItems: boolean, warnings: CompileIssue[]): StepAnno {
|
|
833
|
+
const { body: bodyLines } = bodyLinesOf(splitStepLines(text));
|
|
834
|
+
const body = bodyLines.join("\n");
|
|
835
|
+
const firstClean = withoutInlineCode(bodyLines[0] ?? "");
|
|
836
|
+
|
|
837
|
+
let tierTag: Tier | null = null;
|
|
838
|
+
for (let i = 0; i < bodyLines.length && tierTag === null; i += 1) {
|
|
839
|
+
const l = bodyLines[i] as string;
|
|
840
|
+
if (i > 0 && NESTED_ITEM_RE.test(l)) continue;
|
|
841
|
+
const m = TIER_RE.exec(withoutInlineCode(l));
|
|
842
|
+
if (m !== null) tierTag = (m[1] as string).toLowerCase() as Tier;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
let route: ParsedTask["route"] = null;
|
|
846
|
+
const parsed = parseRouteLine(body, { positions: "any" });
|
|
847
|
+
if (parsed.line !== null) {
|
|
848
|
+
route = { line: removedRouteLine(body, parsed.stripped) ?? "", fields: parsed.line, conflict: parsed.conflict };
|
|
849
|
+
if (parsed.conflict) warn(warnings, "route-conflict", line, "step has conflicting route lines");
|
|
850
|
+
} else if (parsed.malformed === true) {
|
|
851
|
+
warn(warnings, "route-malformed", line, "first route line is malformed");
|
|
852
|
+
}
|
|
853
|
+
if (tierTag === null && route !== null && route.fields !== null && isTier(route.fields.tier)) tierTag = route.fields.tier;
|
|
854
|
+
|
|
855
|
+
let verify: ParsedTask["verify"] = null;
|
|
856
|
+
const vm = VERIFY_RE.exec(firstClean);
|
|
857
|
+
if (vm !== null) {
|
|
858
|
+
const w = vm[1] as string;
|
|
859
|
+
if (w === "required" || w === "deferred" || w === "none") verify = w;
|
|
860
|
+
else warn(warnings, "verify-unknown", line, `unknown VERIFY value ${w}`);
|
|
861
|
+
}
|
|
862
|
+
let cap: ParsedTask["cap"] = null;
|
|
863
|
+
const cm = CAP_RE.exec(firstClean);
|
|
864
|
+
if (cm !== null) cap = cm[1] === "none" ? "none" : Number(cm[1]);
|
|
865
|
+
|
|
866
|
+
const acceptance = firstAcceptance(bodyLines, line, warnings);
|
|
867
|
+
const labels = parseLabels(bodyLines, line, parentId, hashItems);
|
|
868
|
+
return {
|
|
869
|
+
body,
|
|
870
|
+
bodyLines,
|
|
871
|
+
tierTag,
|
|
872
|
+
route,
|
|
873
|
+
verify,
|
|
874
|
+
cap,
|
|
875
|
+
acceptance,
|
|
876
|
+
writesLine: labels.writes,
|
|
877
|
+
readsLine: labels.reads,
|
|
878
|
+
subtasks: labels.subtasks,
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function onlyTestWrites(w: LabeledList | null): boolean {
|
|
883
|
+
if (w === null || w.none) return false;
|
|
884
|
+
const paths: string[] = [];
|
|
885
|
+
for (const m of w.text.matchAll(BACKTICK_SPAN_RE)) if (pathLike((m[1] as string).trim())) paths.push((m[1] as string).trim());
|
|
886
|
+
return paths.length > 0 && paths.every((p) => /^(?:\.\/)?test\//i.test(p.replace(/\\/g, "/")) || /\.(?:test|spec)\./i.test(p));
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
const MANUAL_TITLE_RE = /^(?:Orchestrator|Planned human action)/i;
|
|
890
|
+
const TESTS_TITLE_RE = /^(?:New tests|Tests)\b/i;
|
|
891
|
+
const META_LEAD_RE = /^(?:\*\*|__)?(Depends on|Worktree|Goal)\b/i;
|
|
892
|
+
const QA_LEAD_RE = /^(?:\*\*|__)?QA\b(?![-\w])/;
|
|
893
|
+
|
|
894
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
895
|
+
// parsePlan (memo §2)
|
|
896
|
+
|
|
897
|
+
interface PhaseDraft {
|
|
898
|
+
phase: ParsedPhase;
|
|
899
|
+
level: number;
|
|
900
|
+
/** 0-based heading line, and the exclusive 0-based end of the section. */
|
|
901
|
+
head: number;
|
|
902
|
+
end: number;
|
|
903
|
+
hasIds: boolean;
|
|
904
|
+
hasLabels: boolean;
|
|
905
|
+
hasTasksBlock: boolean;
|
|
906
|
+
dependsTexts: Array<{ text: string; line: number }>;
|
|
907
|
+
pfCount: number;
|
|
908
|
+
dfOrdinal: number;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
interface BlockSpan { draft: PhaseDraft; name: BlockName; start: number; end: number }
|
|
912
|
+
|
|
913
|
+
interface StepInfo {
|
|
914
|
+
step: PlacedStep;
|
|
915
|
+
/** Exclusive 0-based end line of the step. */
|
|
916
|
+
endIdx: number;
|
|
917
|
+
lead: string;
|
|
918
|
+
ex: RegExpExecArray | null;
|
|
919
|
+
df: RegExpExecArray | null;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const HEADING_START_RE = /^ {0,3}#{1,6}[ \t]/;
|
|
923
|
+
const RESERVED_AUTHORED_RE = /^(.+)\.(?:QA\d+|FIX\d+-\d+)$/;
|
|
924
|
+
const PLAN_CONTEXT_OPEN_RE = /^\s*<!--\s*plan-context\s*-->\s*$/;
|
|
925
|
+
const PLAN_CONTEXT_CLOSE_RE = /^\s*<!--\s*\/plan-context\s*-->\s*$/;
|
|
926
|
+
|
|
927
|
+
/** `T`/`P` prefixes are not part of the identity of a phase or task id prefix. */
|
|
928
|
+
function bareId(id: string): string {
|
|
929
|
+
return id.replace(/^(?:T|P)(?=\d)/, "");
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function trimmedEnd(lines: readonly string[], start: number, end: number): number {
|
|
933
|
+
let e = end;
|
|
934
|
+
while (e > start + 1 && (lines[e - 1] as string).trim() === "") e -= 1;
|
|
935
|
+
return e;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
function dedentJoin(lines: readonly string[], start: number, end: number): string {
|
|
939
|
+
return lines.slice(start, end).join("\n");
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
export function parsePlan(text: string): ParsedPlan {
|
|
943
|
+
const warnings: CompileIssue[] = [];
|
|
944
|
+
const lines = text.split(LINE_SPLIT_RE);
|
|
945
|
+
const mask = structureMask(lines);
|
|
946
|
+
const fm = fenceMask(lines);
|
|
947
|
+
|
|
948
|
+
const openFence = unclosedFenceLine(lines, fm, mask);
|
|
949
|
+
if (openFence > 0) throw compileError("fence-unclosed", openFence, "a fenced block is never closed and would hide the rest of the plan");
|
|
950
|
+
const openAcceptance = unclosedAcceptanceLine(lines, mask);
|
|
951
|
+
if (openAcceptance > 0) throw compileError("acceptance-unclosed", openAcceptance, "[acceptance] has no matching [/acceptance]");
|
|
952
|
+
|
|
953
|
+
// --- steps (step 5) ------------------------------------------------------------------------------------------
|
|
954
|
+
const steps = splitPlan(text);
|
|
955
|
+
const headingRun = steps.length > 0 && steps.every((s) => HEADING_START_RE.test(lines[s.line - 1] ?? ""));
|
|
956
|
+
const inStep: boolean[] = new Array<boolean>(lines.length).fill(false);
|
|
957
|
+
const infos: StepInfo[] = steps.map((step) => {
|
|
958
|
+
const endIdx = Math.min(lines.length, step.line - 1 + splitStepLines(step.text).length);
|
|
959
|
+
for (let i = step.line - 1; i < endIdx; i += 1) inStep[i] = true;
|
|
960
|
+
const lead = leadOf(lines[step.line - 1] ?? "");
|
|
961
|
+
return { step, endIdx, lead, ex: EXPLICIT_ID_RE.exec(lead), df: DOGFOOD_ID_RE.exec(lead) };
|
|
962
|
+
});
|
|
963
|
+
const explicitTasks: Array<{ idx: number; id: string }> = [];
|
|
964
|
+
for (const info of infos) {
|
|
965
|
+
if (info.ex !== null) explicitTasks.push({ idx: info.step.line - 1, id: bareId(info.ex[1] as string) });
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// --- headings, waves, phases (step 2) ----------------------------------------------------------------------
|
|
969
|
+
const scanned = scanHeadings(lines, mask);
|
|
970
|
+
/** An id-shaped heading is confirmed only by explicit task ids inside its own section. */
|
|
971
|
+
const confirmedByChildren = (hi: number): boolean => {
|
|
972
|
+
const h = scanned[hi] as HeadingInfo;
|
|
973
|
+
let end = lines.length;
|
|
974
|
+
for (let j = hi + 1; j < scanned.length; j += 1) {
|
|
975
|
+
if ((scanned[j] as HeadingInfo).level <= h.level) {
|
|
976
|
+
end = (scanned[j] as HeadingInfo).idx;
|
|
977
|
+
break;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
const prefix = `${bareId(h.id)}.`;
|
|
981
|
+
return explicitTasks.some((t) => t.idx > h.idx && t.idx < end && t.id.startsWith(prefix));
|
|
982
|
+
};
|
|
983
|
+
const headings = scanned.map((h, hi): HeadingInfo => {
|
|
984
|
+
if (headingRun) return { ...h, kind: "other" };
|
|
985
|
+
if (h.kind === "generic" && !confirmedByChildren(hi)) return { ...h, kind: "other" };
|
|
986
|
+
return h;
|
|
987
|
+
});
|
|
988
|
+
|
|
989
|
+
const waves: ParsedWave[] = [];
|
|
990
|
+
const waveById = new Map<string, ParsedWave>();
|
|
991
|
+
const drafts: PhaseDraft[] = [];
|
|
992
|
+
const draftById = new Map<string, PhaseDraft>();
|
|
993
|
+
const graphs: GraphBlock[] = [];
|
|
994
|
+
const phrases: ExplicitPhrase[] = [];
|
|
995
|
+
const allPhases: ParsedPhase[] = [];
|
|
996
|
+
const phaseById = new Map<string, ParsedPhase>();
|
|
997
|
+
|
|
998
|
+
const addWave = (id: string, title: string, line: number): ParsedWave => {
|
|
999
|
+
const w: ParsedWave = { id, title, line, phases: [] };
|
|
1000
|
+
waves.push(w);
|
|
1001
|
+
waveById.set(id, w);
|
|
1002
|
+
return w;
|
|
1003
|
+
};
|
|
1004
|
+
const addPhase = (p: ParsedPhase): void => {
|
|
1005
|
+
if (!PHASE_ID_PATTERN.test(p.id)) throw compileError("phase-id-invalid", p.span.line, `invalid phase id ${p.id}`);
|
|
1006
|
+
if (phaseById.has(p.id)) throw compileError("phase-duplicate", p.span.line, `duplicate phase ${p.id}`);
|
|
1007
|
+
phaseById.set(p.id, p);
|
|
1008
|
+
allPhases.push(p);
|
|
1009
|
+
};
|
|
1010
|
+
const newPhase = (id: string, title: string, wave: string, line: number, endLine: number, dogfood: boolean, synthetic: boolean): ParsedPhase => ({
|
|
1011
|
+
id, title, wave, span: { line, endLine }, dogfood, synthetic, dependsOn: [], order: null, fixTemplate: null, intro: "", newTests: null,
|
|
1012
|
+
});
|
|
1013
|
+
|
|
1014
|
+
let curWave: { w: ParsedWave; level: number } | null = null;
|
|
1015
|
+
const syntheticWaves = new Set<ParsedWave>();
|
|
1016
|
+
let curDraft: PhaseDraft | null = null;
|
|
1017
|
+
const closePhase = (idx: number): void => {
|
|
1018
|
+
if (curDraft !== null) curDraft.end = idx;
|
|
1019
|
+
curDraft = null;
|
|
1020
|
+
};
|
|
1021
|
+
for (const h of headings) {
|
|
1022
|
+
if (h.kind === "wave") {
|
|
1023
|
+
closePhase(h.idx);
|
|
1024
|
+
const clash = waveById.get(h.id);
|
|
1025
|
+
if (clash !== undefined && syntheticWaves.has(clash)) {
|
|
1026
|
+
// A synthetic wave never stands for a real `Wave N` heading: move it aside (it keeps its place in plan order).
|
|
1027
|
+
let moved = `${h.id}.w`;
|
|
1028
|
+
while (waveById.has(moved)) moved += "w";
|
|
1029
|
+
waveById.delete(h.id);
|
|
1030
|
+
for (const p of allPhases) if (p.wave === clash.id) p.wave = moved;
|
|
1031
|
+
clash.id = moved;
|
|
1032
|
+
waveById.set(moved, clash);
|
|
1033
|
+
}
|
|
1034
|
+
const existing = waveById.get(h.id);
|
|
1035
|
+
if (existing !== undefined) warn(warnings, "wave-duplicate", h.idx + 1, `duplicate wave ${h.id}`);
|
|
1036
|
+
const w = existing ?? addWave(h.id, h.text, h.idx + 1);
|
|
1037
|
+
curWave = { w, level: h.level };
|
|
1038
|
+
const paren = /\(([^)\n]*(?:→|->|-->)[^)\n]*)\)/.exec(h.rest);
|
|
1039
|
+
if (paren !== null) {
|
|
1040
|
+
const parts = (paren[1] as string).split(ARROW_SPLIT_RE).map((part) => [...part.matchAll(PID_TOKEN_RE)].map((m) => m[0]).filter((t) => /\d/.test(t)));
|
|
1041
|
+
const edges: GraphBlock["edges"] = [];
|
|
1042
|
+
for (let i = 0; i + 1 < parts.length; i += 1) {
|
|
1043
|
+
for (const from of parts[i] as string[]) for (const to of parts[i + 1] as string[]) edges.push({ from, to, line: h.idx + 1, raw: h.text });
|
|
1044
|
+
}
|
|
1045
|
+
if (edges.length > 0) graphs.push({ line: h.idx + 1, edges });
|
|
1046
|
+
}
|
|
1047
|
+
scanPhrases(h.rest, h.idx + 1, { kind: "wave", id: h.id }, phrases);
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
if (h.kind === "phase" || h.kind === "dogfood" || h.kind === "generic") {
|
|
1051
|
+
closePhase(h.idx);
|
|
1052
|
+
let waveId: string;
|
|
1053
|
+
if (curWave !== null && h.level > curWave.level) {
|
|
1054
|
+
waveId = curWave.w.id;
|
|
1055
|
+
} else {
|
|
1056
|
+
curWave = null;
|
|
1057
|
+
waveId = h.id;
|
|
1058
|
+
while (waveById.has(waveId)) waveId = `${waveId}.w`;
|
|
1059
|
+
syntheticWaves.add(addWave(waveId, h.text, h.idx + 1));
|
|
1060
|
+
}
|
|
1061
|
+
const phase = newPhase(h.id, h.text, waveId, h.idx + 1, h.idx + 1, h.kind === "dogfood", false);
|
|
1062
|
+
addPhase(phase);
|
|
1063
|
+
const draft: PhaseDraft = {
|
|
1064
|
+
phase, level: h.level, head: h.idx, end: lines.length, hasIds: false, hasLabels: false, hasTasksBlock: false,
|
|
1065
|
+
dependsTexts: [], pfCount: 0, dfOrdinal: 0,
|
|
1066
|
+
};
|
|
1067
|
+
drafts.push(draft);
|
|
1068
|
+
draftById.set(h.id, draft);
|
|
1069
|
+
curDraft = draft;
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
if (curDraft !== null && h.level <= (curDraft as PhaseDraft).level) closePhase(h.idx);
|
|
1073
|
+
if (curWave !== null && h.level <= curWave.level) curWave = null;
|
|
1074
|
+
}
|
|
1075
|
+
closePhase(lines.length);
|
|
1076
|
+
for (const d of drafts) d.phase.span = { line: d.head + 1, endLine: d.end };
|
|
1077
|
+
|
|
1078
|
+
const phaseAt: number[] = new Array<number>(lines.length).fill(-1);
|
|
1079
|
+
drafts.forEach((d, di) => {
|
|
1080
|
+
for (let i = d.head; i < d.end; i += 1) phaseAt[i] = di;
|
|
1081
|
+
});
|
|
1082
|
+
for (const info of infos) {
|
|
1083
|
+
const di = phaseAt[info.step.line - 1] as number;
|
|
1084
|
+
if (di >= 0 && (info.ex !== null || info.df !== null)) (drafts[di] as PhaseDraft).hasIds = true;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// --- block labels (step 3) ---------------------------------------------------------------------------------
|
|
1088
|
+
const blockAt: Array<BlockName | null> = new Array<BlockName | null>(lines.length).fill(null);
|
|
1089
|
+
const blocks: BlockSpan[] = [];
|
|
1090
|
+
/** Lines (0-based) of explicit-id items, by the draft's own id prefix. */
|
|
1091
|
+
const ownIdLines = (d: PhaseDraft): Set<number> => {
|
|
1092
|
+
const own = new Set<number>();
|
|
1093
|
+
if (d.phase.dogfood) return own;
|
|
1094
|
+
for (const info of infos) {
|
|
1095
|
+
if (info.ex === null || RESERVED_AUTHORED_RE.test(info.ex[1] as string)) continue;
|
|
1096
|
+
const idx = info.step.line - 1;
|
|
1097
|
+
if (idx <= d.head || idx >= d.end) continue;
|
|
1098
|
+
if (bareId(info.ex[1] as string).split(".").slice(0, -1).join(".") === bareId(d.phase.id)) own.add(idx);
|
|
1099
|
+
}
|
|
1100
|
+
return own;
|
|
1101
|
+
};
|
|
1102
|
+
for (const d of drafts) {
|
|
1103
|
+
const ownIdAt = ownIdLines(d);
|
|
1104
|
+
let cur: BlockSpan | null = null;
|
|
1105
|
+
const close = (end: number): void => {
|
|
1106
|
+
if (cur !== null) {
|
|
1107
|
+
cur.end = trimmedEnd(lines, cur.start, end);
|
|
1108
|
+
blocks.push(cur);
|
|
1109
|
+
}
|
|
1110
|
+
cur = null;
|
|
1111
|
+
};
|
|
1112
|
+
for (let i = d.head + 1; i < d.end; i += 1) {
|
|
1113
|
+
const l = lines[i] as string;
|
|
1114
|
+
if (mask[i] !== true && !(inStep[i] === true && columnsOf(/^[ \t]*/.exec(l)?.[0] ?? "") > 0)) {
|
|
1115
|
+
const m = BLOCK_LABEL_RE.exec(l);
|
|
1116
|
+
if (m !== null) {
|
|
1117
|
+
close(i);
|
|
1118
|
+
const name = blockNameOf((m[1] ?? m[2] ?? m[3]) as string);
|
|
1119
|
+
cur = { draft: d, name, start: i, end: i + 1 };
|
|
1120
|
+
d.hasLabels = true;
|
|
1121
|
+
if (name === "tasks") d.hasTasksBlock = true;
|
|
1122
|
+
} else if (cur !== null && ((cur as BlockSpan).name === "tasks" || (cur as BlockSpan).name === "pre-flight") && OTHER_LABEL_RE.test(l)) {
|
|
1123
|
+
close(i);
|
|
1124
|
+
} else if (cur !== null && (cur as BlockSpan).name !== "tasks" && ownIdAt.has(i)) {
|
|
1125
|
+
// An item carrying the phase's own id prefix is a task of the phase: it closes any metadata block.
|
|
1126
|
+
close(i);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
blockAt[i] = cur === null ? null : (cur as BlockSpan).name;
|
|
1130
|
+
}
|
|
1131
|
+
close(d.end);
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// --- phase prose: Depends on, intro, phrases (step 4) --------------------------------------------------------
|
|
1135
|
+
for (const d of drafts) {
|
|
1136
|
+
let firstContent = d.end;
|
|
1137
|
+
for (const info of infos) {
|
|
1138
|
+
const idx = info.step.line - 1;
|
|
1139
|
+
if (idx > d.head && idx < d.end && idx < firstContent) firstContent = idx;
|
|
1140
|
+
}
|
|
1141
|
+
for (const b of blocks) if (b.draft === d && b.start < firstContent) firstContent = b.start;
|
|
1142
|
+
d.phase.intro = lines.slice(d.head + 1, firstContent).join("\n").trim();
|
|
1143
|
+
for (let i = d.head + 1; i < d.end; i += 1) {
|
|
1144
|
+
if (mask[i] === true || inStep[i] === true || ANY_HEADING_RE.test(lines[i] as string)) continue;
|
|
1145
|
+
const l = lines[i] as string;
|
|
1146
|
+
if (DEPENDS_LABEL_RE.test(l)) {
|
|
1147
|
+
// Join the continuation lines first, then cut: the clause may run over several lines.
|
|
1148
|
+
let joined = l;
|
|
1149
|
+
for (let j = i + 1; j < d.end && (lines[j] as string).trim() !== "" && mask[j] !== true && !ITEM_RE.test(lines[j] as string) &&
|
|
1150
|
+
!ANY_HEADING_RE.test(lines[j] as string) && !BLOCK_LABEL_RE.test(lines[j] as string); j += 1) {
|
|
1151
|
+
joined += ` ${lines[j] as string}`;
|
|
1152
|
+
}
|
|
1153
|
+
const t = dependsText(joined);
|
|
1154
|
+
if (t !== null) d.dependsTexts.push({ text: t, line: i + 1 });
|
|
1155
|
+
continue;
|
|
1156
|
+
}
|
|
1157
|
+
if (blockAt[i] === "order") continue;
|
|
1158
|
+
scanPhrases(l, i + 1, { kind: "phase", id: d.phase.id }, phrases);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// --- tasks (steps 5-7) ---------------------------------------------------------------------------------------
|
|
1163
|
+
const tasks: ParsedTask[] = [];
|
|
1164
|
+
const taskById = new Map<string, ParsedTask>();
|
|
1165
|
+
/** Id index while tasks are still being collected (duplicates are reported later, from the full list). */
|
|
1166
|
+
const early = new Map<string, ParsedTask>();
|
|
1167
|
+
const implicit = new Map<string, ParsedPhase>();
|
|
1168
|
+
const seenHash = new Map<string, number>();
|
|
1169
|
+
const hasHeadingPhases = drafts.length > 0;
|
|
1170
|
+
|
|
1171
|
+
const ensureImplicit = (id: string, line: number): ParsedPhase => {
|
|
1172
|
+
const known = phaseById.get(id);
|
|
1173
|
+
if (known !== undefined) {
|
|
1174
|
+
known.span = { line: Math.min(known.span.line, line), endLine: Math.max(known.span.endLine, line) };
|
|
1175
|
+
return known;
|
|
1176
|
+
}
|
|
1177
|
+
let waveId = id;
|
|
1178
|
+
if (waveById.has(waveId)) waveId = `${id}.w`;
|
|
1179
|
+
addWave(waveId, id, line);
|
|
1180
|
+
const p = newPhase(id, id, waveId, line, line, false, true);
|
|
1181
|
+
addPhase(p);
|
|
1182
|
+
implicit.set(id, p);
|
|
1183
|
+
return p;
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1186
|
+
const build = (a: {
|
|
1187
|
+
id: string; idSource: IdSource; phase: string; text: string; line: number; endLine: number; idToken: string | null;
|
|
1188
|
+
title?: string; hashItems: boolean; dogfood: boolean; forceKind?: TaskKind;
|
|
1189
|
+
}): ParsedTask => {
|
|
1190
|
+
const anno = annotateText(a.text, a.line, a.hashItems ? null : a.id, a.hashItems, warnings);
|
|
1191
|
+
const first = splitStepLines(a.text)[0] ?? "";
|
|
1192
|
+
const title = a.title ?? titleOf(first, a.idToken === null ? null : a.idToken.replace(/\*\*|__/g, ""));
|
|
1193
|
+
let kind: TaskKind;
|
|
1194
|
+
if (a.forceKind !== undefined) kind = a.forceKind;
|
|
1195
|
+
else if (a.id.endsWith(".FIX")) kind = "fix";
|
|
1196
|
+
else if (a.id.endsWith(".QA")) kind = "qa";
|
|
1197
|
+
else if (a.dogfood || (anno.route === null && MANUAL_TITLE_RE.test(title))) kind = "manual";
|
|
1198
|
+
else if (TESTS_TITLE_RE.test(title) || onlyTestWrites(anno.writesLine)) kind = "tests";
|
|
1199
|
+
else kind = "task";
|
|
1200
|
+
return {
|
|
1201
|
+
id: a.id, idSource: a.idSource, phase: a.phase, kind, title, text: a.text, body: anno.body,
|
|
1202
|
+
span: { line: a.line, endLine: a.endLine }, subtasks: anno.subtasks, tierTag: anno.tierTag, route: anno.route,
|
|
1203
|
+
verify: anno.verify, cap: anno.cap, acceptance: anno.acceptance, writesLine: anno.writesLine, readsLine: anno.readsLine,
|
|
1204
|
+
manual: kind === "manual" || kind === "preflight" || a.dogfood,
|
|
1205
|
+
};
|
|
1206
|
+
};
|
|
1207
|
+
const addTask = (t: ParsedTask, owner: ParsedPhase): void => {
|
|
1208
|
+
if (t.kind === "fix") {
|
|
1209
|
+
if (owner.fixTemplate === null) owner.fixTemplate = t;
|
|
1210
|
+
else warn(warnings, "fix-template-duplicate", t.span.line, `second FIX template for phase ${owner.id}`);
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
tasks.push(t);
|
|
1214
|
+
early.set(t.id, t);
|
|
1215
|
+
};
|
|
1216
|
+
|
|
1217
|
+
for (const info of infos) {
|
|
1218
|
+
const { step } = info;
|
|
1219
|
+
const idx = step.line - 1;
|
|
1220
|
+
const di = phaseAt[idx] as number;
|
|
1221
|
+
const d = di >= 0 ? (drafts[di] as PhaseDraft) : undefined;
|
|
1222
|
+
const block = d === undefined ? null : blockAt[idx] ?? null;
|
|
1223
|
+
const base = { text: step.text, line: step.line, endLine: info.endIdx };
|
|
1224
|
+
|
|
1225
|
+
if (info.ex === null && info.df === null && META_LEAD_RE.test(info.lead)) {
|
|
1226
|
+
const dep = d !== undefined && /^(?:\*\*|__)?Depends on/i.test(info.lead) ? dependsText(lines.slice(idx, info.endIdx).join(" ")) : null;
|
|
1227
|
+
if (d !== undefined && dep !== null) d.dependsTexts.push({ text: dep, line: step.line });
|
|
1228
|
+
continue;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// A DF section's items outside the Tasks block (Worktrees, Acceptance, DoD lists) are not tasks unless they carry a DF id.
|
|
1232
|
+
if (d !== undefined && d.phase.dogfood && (block === "acceptance" || block === "dod" || (block === null && d.hasLabels && info.df === null))) continue;
|
|
1233
|
+
|
|
1234
|
+
if (d !== undefined && d.phase.dogfood && block !== "pre-flight") {
|
|
1235
|
+
d.dfOrdinal += 1;
|
|
1236
|
+
const n = d.phase.id.slice(2);
|
|
1237
|
+
let id: string;
|
|
1238
|
+
if (info.df !== null) id = `DF${info.df[1] as string}.${(info.df[2] as string).toUpperCase()}`;
|
|
1239
|
+
else if (QA_LEAD_RE.test(info.lead)) id = `DF${n}.QA`;
|
|
1240
|
+
else id = `DF${n}.${d.dfOrdinal}`;
|
|
1241
|
+
addTask(build({ ...base, id, idSource: "dogfood", phase: d.phase.id, idToken: info.df === null ? null : info.df[0], hashItems: info.df === null, dogfood: true }), d.phase);
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
if (d !== undefined && block === "pre-flight") {
|
|
1246
|
+
d.pfCount += 1;
|
|
1247
|
+
addTask(build({ ...base, id: `${d.phase.id}.PF${d.pfCount}`, idSource: "preflight", phase: d.phase.id, idToken: info.ex === null ? null : info.ex[0], hashItems: true, dogfood: false, forceKind: "preflight" }), d.phase);
|
|
1248
|
+
continue;
|
|
1249
|
+
}
|
|
1250
|
+
if (d !== undefined && (block === "new-tests" || block === "acceptance" || block === "dod" || block === "order" || block === "qa-review")) {
|
|
1251
|
+
if (info.ex !== null) warn(warnings, "item-in-metadata-block", step.line, `item ${info.ex[1] as string} sits in the ${block} block of ${d.phase.id}; not a task`);
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
const first = lines[idx] as string;
|
|
1256
|
+
const token = /^(?:\*\*|__)?([A-Za-z0-9][A-Za-z0-9.-]*)/.exec(info.lead)?.[1] ?? "";
|
|
1257
|
+
const reserved = RESERVED_AUTHORED_RE.exec(token);
|
|
1258
|
+
if (reserved !== null && (d === undefined || bareId(reserved[1] as string) === bareId(d.phase.id))) {
|
|
1259
|
+
throw compileError("id-reserved", step.line, `id ${token} is reserved for the QA loop`);
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
if (info.ex !== null) {
|
|
1263
|
+
const id = info.ex[1] as string;
|
|
1264
|
+
const prefix = bareId(id).split(".").slice(0, -1).join(".");
|
|
1265
|
+
let owner: ParsedPhase;
|
|
1266
|
+
if (d !== undefined) {
|
|
1267
|
+
owner = d.phase;
|
|
1268
|
+
if (bareId(d.phase.id) !== prefix) warn(warnings, "id-phase-mismatch", step.line, `id ${id} sits in phase ${d.phase.id}`);
|
|
1269
|
+
} else if (phaseById.has(id)) {
|
|
1270
|
+
// `- **0.P** …` outside every phase names a phase (a summary list), not a task of an implicit phase `0`.
|
|
1271
|
+
warn(warnings, "item-outside-phase", step.line, `list item ${id} outside any phase names a phase; not a task`);
|
|
1272
|
+
continue;
|
|
1273
|
+
} else {
|
|
1274
|
+
owner = ensureImplicit(prefix, step.line);
|
|
1275
|
+
}
|
|
1276
|
+
addTask(build({ ...base, id, idSource: "explicit", phase: owner.id, idToken: info.ex[0], hashItems: false, dogfood: false }), owner);
|
|
1277
|
+
continue;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// An item without an id.
|
|
1281
|
+
let owner: ParsedPhase | null = null;
|
|
1282
|
+
if (d !== undefined) {
|
|
1283
|
+
if (block === "tasks" || (block === null && !d.hasLabels)) {
|
|
1284
|
+
owner = d.phase;
|
|
1285
|
+
if (d.hasIds) warn(warnings, "id-less-item", step.line, "item without a task id in a phase that has ids");
|
|
1286
|
+
} else {
|
|
1287
|
+
warn(warnings, "intro-item-ignored", step.line, "list item outside the Tasks block is not a task");
|
|
1288
|
+
}
|
|
1289
|
+
} else if (!hasHeadingPhases) {
|
|
1290
|
+
owner = ensureImplicit("main", step.line);
|
|
1291
|
+
} else {
|
|
1292
|
+
warn(warnings, "item-outside-phase", step.line, "list item outside any phase is not a task");
|
|
1293
|
+
}
|
|
1294
|
+
if (owner === null) continue;
|
|
1295
|
+
addTask(build({ ...base, id: fallbackTaskId(first, seenHash), idSource: "hash", phase: owner.id, idToken: null, hashItems: true, dogfood: false }), owner);
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// --- QA review and New tests blocks (step 6) -----------------------------------------------------------------
|
|
1299
|
+
for (const b of blocks) {
|
|
1300
|
+
const p = b.draft.phase;
|
|
1301
|
+
if (b.name === "new-tests") {
|
|
1302
|
+
const t = dedentJoin(lines, b.start, b.end);
|
|
1303
|
+
p.newTests = p.newTests === null ? t : `${p.newTests}\n${t}`;
|
|
1304
|
+
if (!b.draft.hasIds && !early.has(`${p.id}.TESTS`)) {
|
|
1305
|
+
addTask(build({ text: t, line: b.start + 1, endLine: b.end, id: `${p.id}.TESTS`, idSource: "block", phase: p.id, idToken: null, title: "New tests", hashItems: true, dogfood: false, forceKind: "tests" }), p);
|
|
1306
|
+
}
|
|
1307
|
+
} else if (b.name === "qa-review" && !p.dogfood) {
|
|
1308
|
+
const t = dedentJoin(lines, b.start, b.end);
|
|
1309
|
+
const qaId = `${p.id}.QA`;
|
|
1310
|
+
const existing = early.get(qaId);
|
|
1311
|
+
const made = build({ text: t, line: b.start + 1, endLine: b.end, id: qaId, idSource: "block", phase: p.id, idToken: null, title: "QA review", hashItems: true, dogfood: false, forceKind: "qa" });
|
|
1312
|
+
if (existing === undefined) {
|
|
1313
|
+
addTask(made, p);
|
|
1314
|
+
} else {
|
|
1315
|
+
existing.text = `${existing.text}\n${t}`;
|
|
1316
|
+
existing.body = `${existing.body}\n${made.body}`;
|
|
1317
|
+
existing.span = { line: existing.span.line, endLine: Math.max(existing.span.endLine, b.end) };
|
|
1318
|
+
existing.acceptance = existing.acceptance ?? made.acceptance;
|
|
1319
|
+
existing.writesLine = existing.writesLine ?? made.writesLine;
|
|
1320
|
+
existing.readsLine = existing.readsLine ?? made.readsLine;
|
|
1321
|
+
existing.tierTag = existing.tierTag ?? made.tierTag;
|
|
1322
|
+
existing.route = existing.route ?? made.route;
|
|
1323
|
+
existing.verify = existing.verify ?? made.verify;
|
|
1324
|
+
existing.cap = existing.cap ?? made.cap;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
tasks.sort((a, b) => a.span.line - b.span.line);
|
|
1329
|
+
|
|
1330
|
+
// --- ids: validity, reservation, uniqueness (§3) -------------------------------------------------------------
|
|
1331
|
+
const folded = new Map<string, string>();
|
|
1332
|
+
const templates = allPhases.flatMap((p) => (p.fixTemplate === null ? [] : [p.fixTemplate]));
|
|
1333
|
+
for (const t of [...tasks, ...templates]) {
|
|
1334
|
+
if (!isTaskId(t.id)) throw compileError("id-invalid", t.span.line, `invalid task id ${t.id}`);
|
|
1335
|
+
const key = t.id.toLowerCase();
|
|
1336
|
+
const prior = folded.get(key);
|
|
1337
|
+
if (prior !== undefined) throw compileError("id-duplicate", t.span.line, `duplicate task id ${t.id}${prior === t.id ? "" : ` (also ${prior})`}`);
|
|
1338
|
+
folded.set(key, t.id);
|
|
1339
|
+
taskById.set(t.id, t);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// --- Order chains, D3 post-QA phases ---------------------------------------------------------------------
|
|
1343
|
+
for (const b of blocks) {
|
|
1344
|
+
if (b.name !== "order" || b.draft.phase.order !== null) continue;
|
|
1345
|
+
const p = b.draft.phase;
|
|
1346
|
+
const joined = lines.slice(b.start, b.end).join(" ");
|
|
1347
|
+
const lab = ORDER_LABEL_RE.exec(joined);
|
|
1348
|
+
if (lab === null) continue;
|
|
1349
|
+
const groups = parseOrderChain(joined.slice(lab.index + lab[0].length), p.id);
|
|
1350
|
+
if (groups.length === 0) continue;
|
|
1351
|
+
for (const g of groups) {
|
|
1352
|
+
for (const id of g) {
|
|
1353
|
+
if (id === `${p.id}.QA` || id === `${p.id}.FIX`) continue;
|
|
1354
|
+
if (!taskById.has(id)) throw compileError("order-unknown-id", b.start + 1, `Order: names unknown task ${id}`);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
p.order = { groups, line: b.start + 1, raw: (lines[b.start] as string).trim() };
|
|
1358
|
+
const qaAt = groups.findIndex((g) => g.includes(`${p.id}.QA`));
|
|
1359
|
+
if (qaAt < 0) continue;
|
|
1360
|
+
const later = new Set(groups.slice(qaAt + 1).flat());
|
|
1361
|
+
const moved = tasks.filter((t) => t.phase === p.id && later.has(t.id));
|
|
1362
|
+
if (moved.length === 0) continue;
|
|
1363
|
+
const post = newPhase(`${p.id}.post`, `${p.title} (after QA)`, p.wave, p.span.line, p.span.endLine, false, true);
|
|
1364
|
+
post.dependsOn = [{ id: p.id, external: false, line: b.start + 1 }];
|
|
1365
|
+
addPhase(post);
|
|
1366
|
+
for (const t of moved) t.phase = post.id;
|
|
1367
|
+
warn(warnings, "post-qa-phase", b.start + 1, `${moved.length} task(s) after QA in ${p.id} moved to phase ${post.id}`);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// --- finish phases, waves, dependencies ----------------------------------------------------------------------
|
|
1371
|
+
const sortedPhases = [...allPhases].sort((a, b) => a.span.line - b.span.line || Number(a.id.endsWith(".post")) - Number(b.id.endsWith(".post")));
|
|
1372
|
+
const knownPhaseIds: ReadonlySet<string> = new Set(sortedPhases.map((p) => p.id));
|
|
1373
|
+
for (const d of drafts) {
|
|
1374
|
+
for (const dep of d.dependsTexts) {
|
|
1375
|
+
for (const r of resolveDepends(dep.text, dep.line, d.phase.id, knownPhaseIds, warnings)) {
|
|
1376
|
+
if (!d.phase.dependsOn.some((x) => x.id === r.id)) d.phase.dependsOn.push(r);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
const sortedWaves = [...waves].sort((a, b) => a.line - b.line);
|
|
1381
|
+
for (const w of sortedWaves) w.phases = sortedPhases.filter((p) => p.wave === w.id).map((p) => p.id);
|
|
1382
|
+
|
|
1383
|
+
// --- ownership, graphs, phrases ----------------------------------------------------------------------------------
|
|
1384
|
+
const ownership: OwnershipRow[] = [];
|
|
1385
|
+
scanTables(lines, mask, knownPhaseIds, ownership, phrases);
|
|
1386
|
+
graphs.push(...scanGraphs(lines, fm, mask));
|
|
1387
|
+
graphs.sort((a, b) => a.line - b.line);
|
|
1388
|
+
const knownNodes = new Set<string>([...knownPhaseIds, ...taskById.keys(), ...waveById.keys()]);
|
|
1389
|
+
for (const g of graphs) {
|
|
1390
|
+
const unknown = new Set<string>();
|
|
1391
|
+
for (const e of g.edges) for (const n of [e.from, e.to]) if (!knownNodes.has(n)) unknown.add(n);
|
|
1392
|
+
for (const n of unknown) warn(warnings, "graph-node-unknown", g.line, `graph node ${n} is not a known phase, task or wave`);
|
|
1393
|
+
}
|
|
1394
|
+
for (const t of tasks) {
|
|
1395
|
+
const bodyLines = t.body.split(LINE_SPLIT_RE);
|
|
1396
|
+
for (let k = 0; k < bodyLines.length; k += 1) {
|
|
1397
|
+
const l = bodyLines[k] as string;
|
|
1398
|
+
if (DEPENDS_LABEL_RE.test(l)) {
|
|
1399
|
+
// A task-level `Depends on:` line is an explicit `after` phrase on the task (continuation lines joined before the cut).
|
|
1400
|
+
let joined = l;
|
|
1401
|
+
// QA-2.3-27: the join ends at a `Writes:`/`Reads:` line or a `[route …]` line, which never continue the clause.
|
|
1402
|
+
for (let j = k + 1; j < bodyLines.length && (bodyLines[j] as string).trim() !== "" && !NESTED_ITEM_RE.test(bodyLines[j] as string) &&
|
|
1403
|
+
!/^\s*(?:[-*]\s+)?(?:\*\*|__)?(?:Writes|Reads)\b|^\s*(?:[-*]\s+)?`?\[route\b/i.test(bodyLines[j] as string); j += 1) {
|
|
1404
|
+
joined += ` ${bodyLines[j] as string}`;
|
|
1405
|
+
}
|
|
1406
|
+
const clause = (dependsText(joined) ?? "").replace(/§\S+/g, " ").replace(/`/g, " ");
|
|
1407
|
+
const refs: string[] = [];
|
|
1408
|
+
for (const m of clause.matchAll(PID_TOKEN_RE)) {
|
|
1409
|
+
if (ID_SHAPED_RE.test(m[0]) && !refs.includes(m[0])) refs.push(m[0]);
|
|
1410
|
+
}
|
|
1411
|
+
if (refs.length > 0) {
|
|
1412
|
+
phrases.push({ subject: { kind: "task", id: t.id }, verb: "after", refs, line: t.span.line + k, excerpt: l.trim().slice(0, 160) });
|
|
1413
|
+
}
|
|
1414
|
+
continue;
|
|
1415
|
+
}
|
|
1416
|
+
scanPhrases(l, t.span.line + k, { kind: "task", id: t.id }, phrases);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
const knownRefs = new Set<string>([...knownNodes]);
|
|
1420
|
+
const warnedRefs = new Set<string>();
|
|
1421
|
+
for (const p of phrases) {
|
|
1422
|
+
for (const r of p.refs) {
|
|
1423
|
+
if (knownRefs.has(r) || !ID_SHAPED_RE.test(r) || warnedRefs.has(`${p.line}:${r}`)) continue;
|
|
1424
|
+
warnedRefs.add(`${p.line}:${r}`);
|
|
1425
|
+
warn(warnings, "explicit-ref-unknown", p.line, `unknown reference ${r}: ${p.excerpt.slice(0, 80)}`);
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
const keptPhrases = phrases
|
|
1429
|
+
.map((p) => ({ ...p, refs: p.refs.filter((r) => knownRefs.has(r) && r !== p.subject.id) }))
|
|
1430
|
+
.filter((p) => p.refs.length > 0 || (p.verb === "merged-first" && p.subject.kind === "wave"))
|
|
1431
|
+
.sort((a, b) => a.line - b.line);
|
|
1432
|
+
|
|
1433
|
+
// --- shared context (step 9) -----------------------------------------------------------------------------
|
|
1434
|
+
let sharedContextRaw: string;
|
|
1435
|
+
let sharedContextSource: "block" | "preamble" = "preamble";
|
|
1436
|
+
let ctxOpen = -1;
|
|
1437
|
+
let ctxClose = -1;
|
|
1438
|
+
for (let i = 0; i < lines.length && ctxClose < 0; i += 1) {
|
|
1439
|
+
if (fm[i] === true) continue;
|
|
1440
|
+
if (ctxOpen < 0) {
|
|
1441
|
+
if (PLAN_CONTEXT_OPEN_RE.test(lines[i] as string)) ctxOpen = i;
|
|
1442
|
+
} else if (PLAN_CONTEXT_CLOSE_RE.test(lines[i] as string)) {
|
|
1443
|
+
ctxClose = i;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
if (ctxOpen >= 0 && ctxClose < 0) throw compileError("plan-context-unclosed", ctxOpen + 1, "<!-- plan-context --> has no closing marker");
|
|
1447
|
+
if (ctxOpen >= 0) {
|
|
1448
|
+
sharedContextRaw = lines.slice(ctxOpen + 1, ctxClose).join("\n").trim();
|
|
1449
|
+
sharedContextSource = "block";
|
|
1450
|
+
} else {
|
|
1451
|
+
const firstStructural = headings.find((h) => h.kind === "wave" || h.kind === "phase" || h.kind === "dogfood" || h.kind === "generic");
|
|
1452
|
+
sharedContextRaw = lines.slice(0, firstStructural === undefined ? lines.length : firstStructural.idx).join("\n").trim();
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
return {
|
|
1456
|
+
waves: sortedWaves,
|
|
1457
|
+
phases: sortedPhases,
|
|
1458
|
+
tasks,
|
|
1459
|
+
graphs,
|
|
1460
|
+
ownership,
|
|
1461
|
+
phrases: keptPhrases,
|
|
1462
|
+
sharedContextRaw,
|
|
1463
|
+
sharedContextSource,
|
|
1464
|
+
warnings,
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
1469
|
+
// annotateUnrouted (step 8)
|
|
1470
|
+
|
|
1471
|
+
/** One `annotate` call over unrouted tasks; mark inferred routes so write footprints can reconcile them before role selection. */
|
|
1472
|
+
export async function annotateUnrouted(
|
|
1473
|
+
p: ParsedPlan,
|
|
1474
|
+
annotate: (s: readonly PlanStep[]) => Promise<AnnotatedPlan>,
|
|
1475
|
+
): Promise<ParsedPlan> {
|
|
1476
|
+
const pending = p.tasks.filter((t) => t.route === null && t.kind !== "manual" && t.kind !== "preflight");
|
|
1477
|
+
if (pending.length === 0) return p;
|
|
1478
|
+
const annotated = await annotate(pending.map((t): PlanStep => ({ id: t.id, text: t.body })));
|
|
1479
|
+
const byId = new Map<string, (typeof annotated)[number]>();
|
|
1480
|
+
for (const a of annotated) byId.set(a.id, a);
|
|
1481
|
+
const tasks = p.tasks.map((t): ParsedTask => {
|
|
1482
|
+
const a = t.route === null ? byId.get(t.id) : undefined;
|
|
1483
|
+
if (a === undefined) return t;
|
|
1484
|
+
const fields = parseRouteLine(a.routeLine, { positions: "any" }).line;
|
|
1485
|
+
return {
|
|
1486
|
+
...t,
|
|
1487
|
+
tierTag: t.tierTag ?? (isTier(a.tier) ? a.tier : null),
|
|
1488
|
+
route: { line: a.routeLine, fields, conflict: false, inferred: true },
|
|
1489
|
+
};
|
|
1490
|
+
});
|
|
1491
|
+
return { ...p, tasks };
|
|
1492
|
+
}
|