rungate 0.3.0 → 0.4.1

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.
Files changed (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `contextDocs` — the one binding that decides what a declared doc becomes (#439).
3
+ *
4
+ * Reported from a consumer project's session as "a dead config key". It is
5
+ * not dead: `gates/brief-assembler.ts` consumes it. What was wrong is worse
6
+ * than inert, because the key looked like it worked — three defects stacked in
7
+ * one twenty-line region:
8
+ *
9
+ * 1. Every entry starting with `/` or containing `..` was filtered out with
10
+ * no warning and no difference in the brief. The use case that prompted
11
+ * the report was declaring docs in another project, which is an absolute
12
+ * path. Refusing was indistinguishable from there being nothing to
13
+ * refuse — `.claude/rules/config-access.md`'s *Silent Default
14
+ * Substitution*.
15
+ * 2. The config was read straight from `.claude/rungate.json`, so a project
16
+ * on the directory layout got nothing regardless of the filter.
17
+ * 3. A `catch { return null }` turned a trailing comma into "no docs".
18
+ *
19
+ * This module owns (1) and (3)'s successor; the loader owns (2).
20
+ *
21
+ * ## The decision about paths outside the project root
22
+ *
23
+ * They are ALLOWED, and the brief says so.
24
+ *
25
+ * The filter's instinct was right — an unvalidated path from config into an
26
+ * agent brief is worth thinking about — but the thing being protected is not
27
+ * what it looked like. A brief NAMES files; it does not read them. The config
28
+ * is written by the operator whose session the agent runs in, so a path they
29
+ * declared is not an escalation of anything: they could have put the file in
30
+ * the repo, or pointed the agent at it in a sentence.
31
+ *
32
+ * What is worth protecting is a reader's ability to SEE that a brief reaches
33
+ * outside the repository. So an external doc is included and labelled
34
+ * `(external to this project)`, and a missing one is included and labelled
35
+ * rather than dropped. Nothing declared disappears without a line saying what
36
+ * happened to it — which is the property the old filter did not have and the
37
+ * only one this file is really about.
38
+ */
39
+
40
+ import { existsSync } from "fs";
41
+ import { isAbsolute, relative, resolve } from "path";
42
+
43
+ /**
44
+ * Characters a path must not carry into a brief (BUG-439-A).
45
+ *
46
+ * A brief is an agent instruction and a path is rendered into it inline, so
47
+ * an entry containing a newline writes whatever follows as its own line, in a
48
+ * document whose whole purpose is to be obeyed. The old filter did not stop
49
+ * this: a relative path with no leading `/` and no `..` passed it and could
50
+ * still contain `\n`. This is not a control #439 removed — it is one neither
51
+ * version had, found by security review of the first push.
52
+ *
53
+ * `\u2028` and `\u2029` are in the class because they are line terminators
54
+ * that `\n`-shaped thinking misses.
55
+ */
56
+ const BRIEF_UNSAFE = /[\u0000-\u001f\u007f\u2028\u2029]/;
57
+
58
+ /**
59
+ * One predicate, two callers: `contextDocs` here and the AC `contextFiles`
60
+ * rendered by `gates/brief-assembler.ts`. `contextFiles` had no filtering of
61
+ * any kind, which is also why the old `contextDocs` filter was never a path
62
+ * control — it covered one of two doors.
63
+ */
64
+ export function hasBriefUnsafeChars(value: string): boolean {
65
+ return BRIEF_UNSAFE.test(value);
66
+ }
67
+
68
+ export type ContextDocVerdict =
69
+ | {
70
+ kind: "included";
71
+ /** Exactly as written in the config, for error messages that can be traced back. */
72
+ declared: string;
73
+ /** Absolute, after resolving against the project root. */
74
+ resolved: string;
75
+ /** Outside the project root — reported, not refused. */
76
+ external: boolean;
77
+ /** Declared but not on disk when the brief was assembled. */
78
+ missing: boolean;
79
+ }
80
+ | { kind: "rejected"; declared: string; reason: string };
81
+
82
+ /**
83
+ * Classify ONE declared entry. The single binding, so there is one thing to
84
+ * mutate and each arm is separately observable in the assembled brief.
85
+ */
86
+ export function classifyContextDoc(projectRoot: string, declared: unknown): ContextDocVerdict {
87
+ if (typeof declared !== "string") {
88
+ return { kind: "rejected", declared: JSON.stringify(declared) ?? String(declared), reason: "not a string" };
89
+ }
90
+ const trimmed = declared.trim();
91
+ if (trimmed === "") {
92
+ return { kind: "rejected", declared, reason: "empty" };
93
+ }
94
+ if (hasBriefUnsafeChars(trimmed)) {
95
+ return {
96
+ kind: "rejected",
97
+ declared: JSON.stringify(trimmed),
98
+ reason: "contains a newline or control character, which would write its own lines into the brief",
99
+ };
100
+ }
101
+
102
+ const resolved = isAbsolute(trimmed) ? resolve(trimmed) : resolve(projectRoot, trimmed);
103
+ // `relative` rather than `startsWith`: `/repo-backup` starts with `/repo`
104
+ // and is a different directory. One comparison, computed the way the
105
+ // filesystem means it.
106
+ const rel = relative(resolve(projectRoot), resolved);
107
+ const external = rel === "" || rel.startsWith("..") || isAbsolute(rel);
108
+
109
+ return { kind: "included", declared: trimmed, resolved, external, missing: !existsSync(resolved) };
110
+ }
111
+
112
+ /**
113
+ * Both authored shapes: an array of paths, or an object whose values are paths.
114
+ *
115
+ * A present-but-unusable `contextDocs` — a string, a number, `null` — is ONE
116
+ * rejection rather than silence, because a config that declares the key and
117
+ * gets nothing is exactly the case this issue is about.
118
+ */
119
+ export function classifyContextDocs(projectRoot: string, raw: unknown): ContextDocVerdict[] {
120
+ if (raw === undefined || raw === null) return [];
121
+ const entries: unknown[] = Array.isArray(raw)
122
+ ? raw
123
+ : typeof raw === "object"
124
+ ? Object.values(raw as Record<string, unknown>)
125
+ : [{ __unusable: raw }];
126
+ if (entries.length === 1 && typeof entries[0] === "object" && entries[0] !== null && "__unusable" in (entries[0] as object)) {
127
+ return [{
128
+ kind: "rejected",
129
+ declared: JSON.stringify(raw),
130
+ reason: `contextDocs must be an array or an object, got ${typeof raw}`,
131
+ }];
132
+ }
133
+ return entries.map(e => classifyContextDoc(projectRoot, e));
134
+ }
135
+
136
+ /** The numbered brief lines, one per included doc, labelled where it matters. */
137
+ export function contextDocLines(verdicts: ContextDocVerdict[], startIndex: number): string[] {
138
+ const lines: string[] = [];
139
+ let idx = startIndex;
140
+ for (const v of verdicts) {
141
+ if (v.kind !== "included") continue;
142
+ const notes = [
143
+ v.external ? "external to this project" : null,
144
+ v.missing ? "declared in contextDocs but not present at assembly time" : null,
145
+ ].filter(Boolean);
146
+ lines.push(`${idx}. ${v.resolved}${notes.length ? ` (${notes.join("; ")})` : ""}`);
147
+ idx++;
148
+ }
149
+ return lines;
150
+ }
151
+
152
+ /**
153
+ * The report. Empty when nothing was declared, which is the one case that may
154
+ * be silent — and NOT empty when entries were declared and could not be used,
155
+ * which is the case the old filter made indistinguishable from it.
156
+ */
157
+ export function contextDocNotes(verdicts: ContextDocVerdict[]): string[] {
158
+ // There is no `if (verdicts.length === 0) return []` here, and the absence
159
+ // is deliberate. It was in the first draft, and it was a second decider
160
+ // agreeing with the guard below: an empty list has no rejected, missing or
161
+ // external entries either, so both returned `[]` on exactly the same
162
+ // inputs. Mutating the guard below measured 1 of 54 against a predicted 4
163
+ // because the early return was quietly holding three of the cases up. See
164
+ // `.claude/rules/checks-must-be-able-to-fail.md`, fourth shape.
165
+ const rejected = verdicts.filter(v => v.kind === "rejected");
166
+ const included = verdicts.filter(v => v.kind === "included");
167
+ const missing = included.filter(v => v.kind === "included" && v.missing);
168
+ const external = included.filter(v => v.kind === "included" && v.external);
169
+ if (rejected.length === 0 && missing.length === 0 && external.length === 0) return [];
170
+
171
+ const notes = [`> contextDocs: ${verdicts.length} declared, ${included.length} usable.`];
172
+ for (const v of rejected) {
173
+ if (v.kind === "rejected") notes.push(`> - REJECTED ${v.declared}: ${v.reason}`);
174
+ }
175
+ for (const v of missing) {
176
+ if (v.kind === "included") notes.push(`> - MISSING ${v.declared}: nothing at ${v.resolved}`);
177
+ }
178
+ for (const v of external) {
179
+ if (v.kind === "included") notes.push(`> - EXTERNAL ${v.declared}: resolves to ${v.resolved}, outside this project`);
180
+ }
181
+ return notes;
182
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { readFileSync, writeFileSync, existsSync } from "fs";
8
+ import { writeRoleConfig } from "./config-loader";
8
9
  import type { AgentMeta } from "./generators/types";
9
10
 
10
11
  /**
@@ -83,22 +84,9 @@ export function writeBriefTemplate(templatesDir: string, roleName: string, descr
83
84
  return filePath;
84
85
  }
85
86
 
86
- /**
87
- * Add a new role to the project's rungate.json config.
88
- * Adds brief path, isolation: worktree, and a standardTask.
89
- */
90
- export function addRoleToConfig(configPath: string, roleName: string, description: string): void {
91
- if (!existsSync(configPath)) {
92
- throw new Error(`Config file not found: ${configPath}`);
93
- }
94
- const config = JSON.parse(readFileSync(configPath, "utf-8"));
95
- if (!config.roles) {
96
- config.roles = {};
97
- }
98
- if (config.roles[roleName]) {
99
- throw new Error(`Role '${roleName}' already exists in ${configPath}`);
100
- }
101
- config.roles[roleName] = {
87
+ /** The entry a newly created role gets: brief path, isolation, standardTask. */
88
+ export function buildRoleEntry(roleName: string, description: string) {
89
+ return {
102
90
  brief: `.claude/agents/${roleName}.md`,
103
91
  isolation: "worktree",
104
92
  standardTask: `Perform ${description.toLowerCase()} tasks as assigned`,
@@ -106,7 +94,24 @@ export function addRoleToConfig(configPath: string, roleName: string, descriptio
106
94
  tools: "[Bash, Read]",
107
95
  model: "sonnet",
108
96
  };
109
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
97
+ }
98
+
99
+ /**
100
+ * Register a new role in the project's config, whichever layout it is on.
101
+ *
102
+ * This file decides what a role ENTRY looks like; `writeRoleConfig` decides
103
+ * which file it belongs in. Keeping the second half in the loader is #415:
104
+ * the predecessor took a `configPath` from its caller, and every caller built
105
+ * `.claude/rungate.json` by hand.
106
+ *
107
+ * Returns the file the role was written to.
108
+ */
109
+ export function registerRole(
110
+ projectRoot: string,
111
+ roleName: string,
112
+ description: string,
113
+ ): string {
114
+ return writeRoleConfig(projectRoot, roleName, buildRoleEntry(roleName, description));
110
115
  }
111
116
 
112
117
  export const DEFAULT_AGENT_META: Record<string, AgentMeta> = {
package/lib/create-sc.ts CHANGED
@@ -9,6 +9,8 @@ import { join, dirname } from "path";
9
9
  import { fileURLToPath } from "url";
10
10
 
11
11
  import type { ScRegistry } from "./sc-ids";
12
+ import { isFixtureScId } from "./sc-ids";
13
+ import { tryLoadRungateConfig } from "./config-loader";
12
14
 
13
15
  // ── Types ─────────────────────────────────────────────────────
14
16
 
@@ -41,9 +43,10 @@ function loadBuiltInRegistry(): RegistryEntry[] {
41
43
  /**
42
44
  * Load the matcher registry, optionally merging consumer-defined custom matchers.
43
45
  *
44
- * When projectRoot is provided, looks for .claude/rungate.json in that directory
45
- * and merges any `customMatchers` array entries with the built-in registry.
46
- * Consumer entries with the same `name` as a built-in entry override the built-in.
46
+ * When projectRoot is provided, resolves that project's config through
47
+ * `lib/config-loader.ts` and merges any `customMatchers` array entries with the
48
+ * built-in registry. Consumer entries with the same `name` as a built-in entry
49
+ * override the built-in.
47
50
  */
48
51
  export function loadRegistry(projectRoot?: string): RegistryEntry[] {
49
52
  const cacheKey = projectRoot ?? "__builtin__";
@@ -54,33 +57,26 @@ export function loadRegistry(projectRoot?: string): RegistryEntry[] {
54
57
  return builtIn;
55
58
  }
56
59
 
57
- // Look for consumer custom matchers in .claude/rungate.json
58
- const configPath = join(projectRoot, ".claude", "rungate.json");
59
- if (!existsSync(configPath)) {
60
+ // Through the loader, so a consumer on the directory layout can supply
61
+ // custom matchers at all — this read was monolith-only, which is #212/#90.
62
+ // The parse failure is NOT caught: the old `catch` returned the built-in
63
+ // registry, so a consumer whose config had a trailing comma silently got
64
+ // rungate's matchers and no indication their own had been dropped.
65
+ const config = tryLoadRungateConfig(projectRoot);
66
+ const customMatchers = (config?.customMatchers ?? []) as RegistryEntry[];
67
+ if (customMatchers.length === 0) {
60
68
  _registryCache.set(cacheKey, builtIn);
61
69
  return builtIn;
62
70
  }
63
71
 
64
- try {
65
- const config = JSON.parse(readFileSync(configPath, "utf-8"));
66
- const customMatchers: RegistryEntry[] = config.customMatchers ?? [];
67
- if (customMatchers.length === 0) {
68
- _registryCache.set(cacheKey, builtIn);
69
- return builtIn;
70
- }
72
+ // Merge: consumer entries override built-in entries with same name
73
+ const merged = builtIn.filter(
74
+ (entry) => !customMatchers.some((c) => c.name === entry.name)
75
+ );
76
+ merged.push(...customMatchers);
71
77
 
72
- // Merge: consumer entries override built-in entries with same name
73
- const merged = builtIn.filter(
74
- (entry) => !customMatchers.some((c) => c.name === entry.name)
75
- );
76
- merged.push(...customMatchers);
77
-
78
- _registryCache.set(cacheKey, merged);
79
- return merged;
80
- } catch {
81
- _registryCache.set(cacheKey, builtIn);
82
- return builtIn;
83
- }
78
+ _registryCache.set(cacheKey, merged);
79
+ return merged;
84
80
  }
85
81
 
86
82
  // ── Pattern param definitions ─────────────────────────────────
@@ -248,18 +244,44 @@ export function listPatterns(): string {
248
244
  * that has no registry to hand; silently changing that would be a different
249
245
  * bug. It is the wrong answer in a shared namespace, which is why
250
246
  * `scripts/create-sc.ts` passes one.
247
+ *
248
+ * ## The namespace has a second half, and #392 only fixed the first
249
+ *
250
+ * Consulting the registry stopped two specs minting the same number. It did
251
+ * nothing about test fixtures, which spell SC ids inside the SAME namespace
252
+ * and appear in no registry: `test/sync-sc-status.test.ts:61` is literally
253
+ * `- [ ] SC-9441: AGENTS.md exists`, a checkbox declaration in a string
254
+ * literal. Allocating 900 would mint a criterion out of a scratch number and
255
+ * hand a live claim to a fixture — the shape #392 closed, arriving from the
256
+ * side nothing looks at.
257
+ *
258
+ * So `spelledInSource` is the other half — and only there is the reserved
259
+ * range ignored. The 9000s exist to be safe for fixtures, so counting a
260
+ * FIXTURE at 9450 as taken would push every future criterion past 9000 and
261
+ * destroy the reservation it was built on. That is the one case where a
262
+ * higher number is the wrong answer.
263
+ *
264
+ * A SPEC declaration is authoritative at any number, reserved or not. If a
265
+ * spec has already claimed 9150 then 9150 is claimed, whatever the
266
+ * convention says it should have been, and allocating it again is the
267
+ * collision this function exists to prevent. The reservation is enforced
268
+ * against specs by SC-1524, not by making the allocator pretend.
251
269
  */
252
- export function nextSCNumber(specContent: string, reg?: ScRegistry): number {
270
+ export function nextSCNumber(
271
+ specContent: string,
272
+ reg?: ScRegistry,
273
+ spelledInSource?: Iterable<string>,
274
+ ): number {
253
275
  const ids: number[] = [];
276
+ const take = (raw: string): void => {
277
+ const n = Number(raw.replace(/^SC-[A-Z]?/, ""));
278
+ if (Number.isFinite(n)) ids.push(n);
279
+ };
254
280
  const pattern = /SC-(\d+)/g;
255
281
  let match;
256
- while ((match = pattern.exec(specContent)) !== null) {
257
- ids.push(parseInt(match[1]));
258
- }
259
- for (const id of reg?.declaredById.keys() ?? []) {
260
- const n = Number(id.replace(/^SC-[A-Z]?/, ""));
261
- if (Number.isFinite(n)) ids.push(n);
262
- }
282
+ while ((match = pattern.exec(specContent)) !== null) take(match[0]);
283
+ for (const id of reg?.declaredById.keys() ?? []) take(id);
284
+ for (const id of spelledInSource ?? []) if (!isFixtureScId(id)) take(id);
263
285
  if (ids.length === 0) return 1;
264
286
  return Math.max(...ids) + 1;
265
287
  }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Dependency order for decomposed sub-issues (#189).
3
+ *
4
+ * `workflows/ship.js` asked the decomposer for "sub-issues in dependency order
5
+ * (foundations first)", gave it nowhere in the schema to record the answer,
6
+ * and dispatched every sub-issue at once. The ordering was produced, accepted
7
+ * and discarded — #166's shape exactly: **an instruction the agent can follow
8
+ * perfectly without its output changing anything.**
9
+ *
10
+ * ## The run this comes from
11
+ *
12
+ * `wf_92dbb346-949` (#105) decomposed into four sub-issues with genuinely
13
+ * disjoint file claims, which is all `ship.js` validated. The dependency was
14
+ * not in the files — it was in the API. Sub-issue 1 was building
15
+ * `harnessRootFor()` in `lib/paths.ts`; sub-issue 4 needed to call it and
16
+ * could not see sub-issue 1, so it wrote its own:
17
+ *
18
+ * | worktree | signature | behaviour |
19
+ * |---|---|---|
20
+ * | `-5` | `harnessRootFor(root: string)` | resolves the root the caller names |
21
+ * | `-8` | `harnessRootFor(dir: string)` | walks up looking for `HARNESS.md` |
22
+ *
23
+ * Two functions, one name, one file, opposite contracts. Both defensible,
24
+ * both carefully commented, neither author aware of the other. Eight agents,
25
+ * 77 minutes, four worktrees of good work that cannot be combined.
26
+ *
27
+ * ## Why file-disjointness is the wrong test
28
+ *
29
+ * File overlap detects MERGE conflicts. It does not detect SEMANTIC
30
+ * dependencies, and two sub-issues can hold disjoint files and still be
31
+ * ordered whenever one creates something the other consumes: a function, an
32
+ * exported type, a config key one writes and the other reads, a test helper,
33
+ * a CLI flag. The overlap check stays — it catches a different thing and both
34
+ * are needed (#189 AC-3).
35
+ *
36
+ * ## The direction this is allowed to be wrong in
37
+ *
38
+ * Toward REFUSING, never toward running anyway. A cycle, a reference to a
39
+ * sub-issue that does not exist, and a self-dependency all refuse. Falling
40
+ * back to parallel on a dependency it could not read is the fail-open shape
41
+ * `.claude/rules/checks-must-be-able-to-fail.md` opens with, and it would
42
+ * reproduce `wf_92dbb346-949` exactly while reporting that it had scheduled
43
+ * the work.
44
+ */
45
+
46
+ export interface WaveSubIssue {
47
+ title: string;
48
+ /** Titles of sub-issues that must finish first. Absent means none. */
49
+ dependsOn?: string[] | null;
50
+ }
51
+
52
+ export interface WavePlan {
53
+ /** Indexes into the input array, grouped. Everything in a wave is parallel. */
54
+ waves: number[][];
55
+ /** One line per wave that is not the first, saying what it waited for. */
56
+ reasons: string[];
57
+ /** Non-null when no order exists; `waves` is empty and nothing may run. */
58
+ refusal: string | null;
59
+ }
60
+
61
+ /** Titles are matched after trimming and case-folding; agents are inconsistent. */
62
+ function key(title: unknown): string {
63
+ return String(title ?? "").trim().toLowerCase();
64
+ }
65
+
66
+ /**
67
+ * Group sub-issues into waves. Everything in a wave runs concurrently; wave
68
+ * N+1 does not start until wave N is done.
69
+ *
70
+ * Kahn's algorithm, with every failure mode a refusal rather than a dropped
71
+ * edge:
72
+ *
73
+ * - a `dependsOn` naming a sub-issue that is not in the list — the agent
74
+ * invented a dependency or misspelled one, and ignoring it would schedule
75
+ * the work as if the dependency did not exist
76
+ * - a self-dependency, which can never be satisfied
77
+ * - two sub-issues with the same title, because then an edge has two possible
78
+ * targets and picking one is a guess
79
+ * - a cycle, named by the sub-issues still unscheduled
80
+ *
81
+ * The all-independent case returns ONE wave containing everything, which is
82
+ * the positive control: a scheduler that serialised everything would satisfy
83
+ * every ordering case and throw away the whole benefit of decomposition
84
+ * (#189 AC-1).
85
+ */
86
+ export function dependencyWaves(subIssues: readonly WaveSubIssue[] | null | undefined): WavePlan {
87
+ const list = Array.isArray(subIssues) ? subIssues : [];
88
+ if (list.length === 0) return { waves: [], reasons: [], refusal: null };
89
+
90
+ const byTitle = new Map<string, number>();
91
+ for (let i = 0; i < list.length; i++) {
92
+ const k = key(list[i]?.title);
93
+ if (!k) {
94
+ return {
95
+ waves: [],
96
+ reasons: [],
97
+ refusal: `sub-issue ${i + 1} has no title, so nothing can declare a dependency on it (#189)`,
98
+ };
99
+ }
100
+ if (byTitle.has(k)) {
101
+ return {
102
+ waves: [],
103
+ reasons: [],
104
+ refusal:
105
+ `two sub-issues are both titled ${JSON.stringify(String(list[i]!.title).trim())} — a dependency ` +
106
+ `naming that title has two possible targets and picking one is a guess (#189)`,
107
+ };
108
+ }
109
+ byTitle.set(k, i);
110
+ }
111
+
112
+ const needs: number[][] = list.map(() => []);
113
+ for (let i = 0; i < list.length; i++) {
114
+ for (const raw of list[i]?.dependsOn ?? []) {
115
+ const k = key(raw);
116
+ if (!k) continue;
117
+ const target = byTitle.get(k);
118
+ if (target === undefined) {
119
+ return {
120
+ waves: [],
121
+ reasons: [],
122
+ refusal:
123
+ `sub-issue ${JSON.stringify(String(list[i]!.title).trim())} depends on ` +
124
+ `${JSON.stringify(String(raw).trim())}, which is not one of the sub-issues — ` +
125
+ `scheduling around a dependency this run cannot see is how ${"wf_92dbb346-949"} ` +
126
+ `produced two functions with one name (#189)`,
127
+ };
128
+ }
129
+ if (target === i) {
130
+ return {
131
+ waves: [],
132
+ reasons: [],
133
+ refusal:
134
+ `sub-issue ${JSON.stringify(String(list[i]!.title).trim())} depends on itself (#189)`,
135
+ };
136
+ }
137
+ if (!needs[i]!.includes(target)) needs[i]!.push(target);
138
+ }
139
+ }
140
+
141
+ const waves: number[][] = [];
142
+ const reasons: string[] = [];
143
+ const done = new Set<number>();
144
+
145
+ while (done.size < list.length) {
146
+ const ready = [];
147
+ for (let i = 0; i < list.length; i++) {
148
+ if (done.has(i)) continue;
149
+ if (needs[i]!.every(d => done.has(d))) ready.push(i);
150
+ }
151
+ if (ready.length === 0) {
152
+ const stuck = list
153
+ .map((s, i) => (done.has(i) ? null : String(s.title).trim()))
154
+ .filter(Boolean);
155
+ return {
156
+ waves: [],
157
+ reasons: [],
158
+ refusal:
159
+ `the dependsOn graph has a cycle — ${JSON.stringify(stuck)} can never start, because each ` +
160
+ `waits on another of them. Refusing rather than falling back to parallel: a fallback would ` +
161
+ `run exactly the schedule this field exists to prevent, and report that it had ordered the ` +
162
+ `work (#189)`,
163
+ };
164
+ }
165
+ if (waves.length > 0) {
166
+ const waited = [...new Set(ready.flatMap(i => needs[i]!))]
167
+ .map(d => String(list[d]!.title).trim())
168
+ .sort();
169
+ reasons.push(
170
+ `wave ${waves.length + 1} (${ready.map(i => String(list[i]!.title).trim()).join(", ")}) ` +
171
+ `waited for ${waited.join(", ")} — a declared dependsOn, not a file overlap`,
172
+ );
173
+ }
174
+ waves.push(ready);
175
+ for (const i of ready) done.add(i);
176
+ }
177
+
178
+ return { waves, reasons, refusal: null };
179
+ }
180
+
181
+ /**
182
+ * Was this plan serialised, and how much?
183
+ *
184
+ * A run that quietly takes four times as long is a bug report nobody files
185
+ * (#189 AC-5), so the dispatcher logs this whether or not anything waited.
186
+ */
187
+ export function wavePlanSummary(plan: WavePlan, total: number): string {
188
+ if (plan.refusal) return plan.refusal;
189
+ if (plan.waves.length <= 1) {
190
+ return `${total} sub-issue(s) declared no dependsOn — dispatching all of them concurrently`;
191
+ }
192
+ return (
193
+ `${total} sub-issues in ${plan.waves.length} dependency waves ` +
194
+ `(${plan.waves.map(w => w.length).join(" then ")}) — this run is serialised by ` +
195
+ `${plan.waves.length - 1} barrier(s) and will take correspondingly longer`
196
+ );
197
+ }