cyber-sdd 0.4.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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/cyberuni/cyber-sdd",
9
9
  "repository": "https://github.com/cyberuni/cyber-sdd",
10
- "version": "0.4.0",
10
+ "version": "0.4.1",
11
11
  "skills": "./skills",
12
12
  "agents": [
13
13
  "./agents/sdd-automaton.md",
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/cyberuni/cyber-sdd",
9
9
  "repository": "https://github.com/cyberuni/cyber-sdd",
10
- "version": "0.4.0",
10
+ "version": "0.4.1",
11
11
  "skills": "./skills",
12
12
  "agents": [
13
13
  "./agents/sdd-automaton.md",
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/cyberuni/cyber-sdd",
9
9
  "repository": "https://github.com/cyberuni/cyber-sdd",
10
- "version": "0.4.0",
10
+ "version": "0.4.1",
11
11
  "skills": "./skills",
12
12
  "agents": [
13
13
  "./agents/sdd-automaton.md",
@@ -104,5 +104,9 @@ depth-2 behavior described here.
104
104
  when a capability is available, prefer its **warm** unit over a cold one-shot, else fall back to a
105
105
  portable cold subagent. context-clear a warm judge (`npx cyberlegion@<version> unit clear <ref>`) to a fresh context before **each** judgment; a warm
106
106
  impl-producer builder **keeps** its context across the mission. Reset or tear down every warm unit at
107
- handoff. Full model: `start-mission`'s "Dispatch transport" note and the `design/harness-spawning`
107
+ handoff. Hand SDD's own judges (`sdd-spec-judge`, `sdd-impl-judge`) to the
108
+ capability **by file path, never by name** — `agents/<name>.md` under the SDD plugin root, the folder
109
+ your own definition ships in. Locate that root from the SDD skill that spawned you (two levels above
110
+ its base directory) or the plugin root your brief names; if no file is there, send the capability no
111
+ request for that judge and spawn it as a portable cold subagent (`sdd:<name>`) instead. Full model: `start-mission`'s "Dispatch transport" note and the `design/harness-spawning`
108
112
  node of the SDD project spec (repo-only).
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ import { scanProjectSpec } from "../../check-spec-structure/scripts/check-spec-structure.js";
3
+ import { classifyFile } from "../../spec-gate/scripts/classify-edit-class.js";
4
+ import { existsSync, readdirSync, realpathSync } from "node:fs";
5
+ import { isAbsolute, join, relative } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ //#region skills/align-spec/scripts/align-spec.mts
8
+ const DEFAULT_BASE = "HEAD";
9
+ function selectNodes(records, only) {
10
+ if (!only || only.length === 0) return records;
11
+ const wanted = new Set(only.map(normalizeNodeRef));
12
+ return records.filter((r) => wanted.has(normalizeNodeRef(r.display)) || wanted.has(normalizeNodeRef(r.relPath)));
13
+ }
14
+ function normalizeNodeRef(ref) {
15
+ return ref.replace(/\\/g, "/").replace(/\/README\.md$/, "").replace(/\/+$/, "");
16
+ }
17
+ function findFeaturePath(specDir, node) {
18
+ const nodeDir = join(specDir, node.relPath.replace(/README\.md$/, ""));
19
+ if (!existsSync(nodeDir)) return null;
20
+ const feature = readdirSync(nodeDir, { withFileTypes: true }).find((e) => e.isFile() && e.name.endsWith(".feature"));
21
+ return feature ? join(nodeDir, feature.name) : null;
22
+ }
23
+ function detectNarrowing(node, specDir, base, cwd = ".") {
24
+ const featurePath = findFeaturePath(specDir, node);
25
+ if (!featurePath) return [];
26
+ const relFeaturePath = isAbsolute(featurePath) ? relative(cwd, featurePath) : featurePath;
27
+ const result = classifyFile(relFeaturePath, base, cwd);
28
+ if (result.classification !== "narrowing" && result.classification !== "mixed") return [];
29
+ const narrowed = result.scenarios.filter((s) => s.change === "modified" || s.change === "removed");
30
+ return [{
31
+ kind: "narrowing",
32
+ severity: "clearance",
33
+ node: node.display,
34
+ detail: `scenario-diff vs ${base} narrows: ${narrowed.map((s) => s.name).join(", ")} — escalate a Clearance CR, do not silently rewrite`
35
+ }];
36
+ }
37
+ function detect(records, specDir, base, cwd = ".") {
38
+ return records.flatMap((node) => detectNarrowing(node, specDir, base, cwd));
39
+ }
40
+ function hasDrift(findings) {
41
+ return findings.length > 0;
42
+ }
43
+ function splitFrontmatter(text) {
44
+ const m = /^(---\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$))([\s\S]*)$/.exec(text);
45
+ if (!m) return {
46
+ frontmatter: "",
47
+ body: text
48
+ };
49
+ return {
50
+ frontmatter: m[1],
51
+ body: m[2]
52
+ };
53
+ }
54
+ function trimProse(readmeText, proseToRemove) {
55
+ const { frontmatter, body } = splitFrontmatter(readmeText);
56
+ return frontmatter + body.split(proseToRemove).join("");
57
+ }
58
+ function appendScenario(featureText, scenarioBlock) {
59
+ return `${featureText.replace(/\s+$/, "")}\n\n${scenarioBlock.trim()}\n`;
60
+ }
61
+ function renderFindings(findings, specDir) {
62
+ const lines = [`align-spec: spec-dir=${specDir}`, `drift[${findings.length}]:`];
63
+ for (const f of findings) lines.push(` ${f.node} — ${f.kind} (${f.severity}): ${f.detail}`);
64
+ if (findings.length === 0) lines.push(" (none — mechanical scenario-diff found no narrowing)");
65
+ lines.push("note: coverage gaps and prose/scenario contradictions are judge-only (no scenario IDs in prose) — this engine reports only the mechanical scenario-diff");
66
+ return lines.join("\n");
67
+ }
68
+ function parseNodesArg(value) {
69
+ if (!value) return void 0;
70
+ const parts = value.split(",").map((s) => s.trim()).filter(Boolean);
71
+ return parts.length > 0 ? parts : void 0;
72
+ }
73
+ function main(argv) {
74
+ let specDir = ".";
75
+ let base = DEFAULT_BASE;
76
+ let mode = "detect";
77
+ let format = "toon";
78
+ let only;
79
+ for (let i = 0; i < argv.length; i++) {
80
+ const a = argv[i];
81
+ if (a === "--spec-dir") specDir = argv[++i] ?? ".";
82
+ else if (a === "--check") mode = "check";
83
+ else if (a === "--base") base = argv[++i] ?? "HEAD";
84
+ else if (a === "--format") format = argv[++i] ?? "toon";
85
+ else if (a === "--nodes") only = parseNodesArg(argv[++i]);
86
+ }
87
+ const findings = detect(selectNodes(scanProjectSpec(specDir), only), specDir, base);
88
+ if (mode === "check") {
89
+ if (hasDrift(findings)) {
90
+ process.stderr.write(`align-spec: ${findings.length} drift finding(s) (mechanical scenario-diff)\n`);
91
+ return 1;
92
+ }
93
+ process.stdout.write("align-spec: no mechanical drift\n");
94
+ return 0;
95
+ }
96
+ if (format === "json") process.stdout.write(`${JSON.stringify(findings)}\n`);
97
+ else process.stdout.write(`${renderFindings(findings, specDir)}\n`);
98
+ return 0;
99
+ }
100
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exit(main(process.argv.slice(2)));
101
+ //#endregion
102
+ export { DEFAULT_BASE, appendScenario, detect, detectNarrowing, findFeaturePath, hasDrift, main, renderFindings, selectNodes, splitFrontmatter, trimProse };
@@ -0,0 +1,311 @@
1
+ #!/usr/bin/env node
2
+ import { collectSpecs, discoverSpecFiles, parseFrontmatter } from "../../discover-specs/scripts/discover-specs.js";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import { dirname, join, relative, resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ //#region skills/check-project-specs/scripts/check-project-specs.mts
8
+ const HERE = fileURLToPath(import.meta.url);
9
+ const ENGINES = [
10
+ {
11
+ name: "check-spec-state",
12
+ script: "spec-gate/scripts/check-spec-state.mts",
13
+ args: (d) => ["--root", d]
14
+ },
15
+ {
16
+ name: "check-suite",
17
+ script: "spec-gate/scripts/check-suite.mts",
18
+ args: (d) => ["--root", d]
19
+ },
20
+ {
21
+ name: "concept-index",
22
+ script: "concept-index/scripts/concept-index.mts",
23
+ args: (d) => [
24
+ "--spec-dir",
25
+ d,
26
+ "--check"
27
+ ]
28
+ },
29
+ {
30
+ name: "check-spec-structure",
31
+ script: "check-spec-structure/scripts/check-spec-structure.mts",
32
+ args: (d) => [
33
+ "--spec-dir",
34
+ d,
35
+ "--check"
36
+ ]
37
+ },
38
+ {
39
+ name: "align-spec",
40
+ script: "align-spec/scripts/align-spec.mts",
41
+ args: (d) => [
42
+ "--spec-dir",
43
+ d,
44
+ "--check"
45
+ ]
46
+ },
47
+ {
48
+ name: "check-spec-references",
49
+ script: "check-spec-references/scripts/check-spec-references.mts",
50
+ args: (d) => ["--spec-dir", d]
51
+ },
52
+ {
53
+ name: "check-scenario-overlap",
54
+ script: "check-scenario-overlap/scripts/check-scenario-overlap.mts",
55
+ args: (d) => [
56
+ "--spec-dir",
57
+ d,
58
+ "--check"
59
+ ]
60
+ }
61
+ ];
62
+ /**
63
+ * Where an engine runs from. The .mts source runs its siblings in the skills tree; the
64
+ * published bin runs from dist/, which mirrors that tree compiled to .js (tsdown.config.ts)
65
+ * — Node will not strip types under node_modules, so the bin must never reach back into
66
+ * the .mts tree.
67
+ */
68
+ function enginePath(e, here = HERE) {
69
+ const skillsDir = resolve(dirname(here), "../..");
70
+ return join(skillsDir, here.endsWith(".mts") ? e.script : e.script.replace(/\.mts$/, ".js"));
71
+ }
72
+ /** Walk up from `start` for the workspace marker. Returns '' when not found. */
73
+ function findRepoRoot(start) {
74
+ let dir = resolve(start);
75
+ for (;;) {
76
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
77
+ const up = dirname(dir);
78
+ if (up === dir) return "";
79
+ dir = up;
80
+ }
81
+ }
82
+ /**
83
+ * Find the spec whose `project-path` names `projectRel` (a repo-relative dir).
84
+ * A project with no spec is `none` — not an error: the script is uniform across
85
+ * every workspace member, and some members are governed by no spec.
86
+ */
87
+ function resolveSpecFor(specs, projectRel) {
88
+ const hits = specs.filter((s) => s.projectPath !== "" && s.projectPath === projectRel);
89
+ if (hits.length === 0) return { kind: "none" };
90
+ if (hits.length > 1) return {
91
+ kind: "ambiguous",
92
+ specs: hits
93
+ };
94
+ return {
95
+ kind: "resolved",
96
+ spec: hits[0]
97
+ };
98
+ }
99
+ /**
100
+ * Every spec must be reachable from a project that actually checks it. Without
101
+ * this, a spec silently goes unchecked the moment its project drops the script —
102
+ * which is exactly how the corpus ended up with one audited project out of ten.
103
+ *
104
+ * `specFiles` are the spec.md paths found at the recognized locations *before*
105
+ * the lifecycle-status filter; `specs` are the ones that survived it. A file in
106
+ * the first set and not the second is a spec whose status is not in the enum:
107
+ * discovery drops it, so every engine silently skips it and it is checked by
108
+ * nothing. That is a gap to escalate, not to exempt.
109
+ */
110
+ function findCoverageGaps(root, specFiles, specs, readPkg) {
111
+ const gaps = [];
112
+ const recognized = new Set(specs.map((s) => s.path === "" ? "spec.md" : `${s.path}/spec.md`));
113
+ for (const f of specFiles) if (!recognized.has(f)) gaps.push({
114
+ spec: f,
115
+ projectPath: "",
116
+ reason: "unrecognized"
117
+ });
118
+ for (const s of specs) {
119
+ if (s.projectPath === "") {
120
+ gaps.push({
121
+ spec: s.path,
122
+ projectPath: "",
123
+ reason: "no-project-path"
124
+ });
125
+ continue;
126
+ }
127
+ const pkg = readPkg(join(root, s.projectPath, "package.json"));
128
+ if (!pkg) {
129
+ gaps.push({
130
+ spec: s.path,
131
+ projectPath: s.projectPath,
132
+ reason: "no-manifest"
133
+ });
134
+ continue;
135
+ }
136
+ if (!pkg.scripts?.["check:spec"]) gaps.push({
137
+ spec: s.path,
138
+ projectPath: s.projectPath,
139
+ reason: "no-check-script"
140
+ });
141
+ }
142
+ return gaps;
143
+ }
144
+ /**
145
+ * A spec.md sitting at a recognized location that discovery DROPPED (its status is not
146
+ * in the lifecycle enum) and that belongs to `projectRel` — by the `project-path` it
147
+ * declares, or by sitting inside the project (`<project>/.agents/spec/spec.md`, which
148
+ * survives frontmatter corruption because it is location-derived).
149
+ *
150
+ * Without this, a per-project run resolves such a spec to `none` and prints "no spec
151
+ * governs <project> — skipped" with exit 0: a status typo silently exempts the whole
152
+ * project from every engine. A spec that exists but cannot be classified is escalated,
153
+ * not exempted — the same call the corpus scope’s coverage guard makes.
154
+ */
155
+ function findDroppedSpecFor(specFiles, specs, projectRel, readText) {
156
+ const recognized = new Set(specs.map((s) => s.path === "" ? "spec.md" : `${s.path}/spec.md`));
157
+ const out = [];
158
+ for (const f of specFiles) {
159
+ if (recognized.has(f)) continue;
160
+ const text = readText(f);
161
+ const fm = text === null ? null : parseFrontmatter(text);
162
+ const dir = f.replace(/(^|\/)spec\.md$/, "");
163
+ const nested = /^(.+)\/\.agents\/spec$/.exec(dir)?.[1] ?? "";
164
+ if (fm?.projectPath === projectRel || nested === projectRel) out.push({
165
+ file: f,
166
+ status: fm?.status ?? ""
167
+ });
168
+ }
169
+ return out;
170
+ }
171
+ const REASON_TEXT = {
172
+ unrecognized: "sits at a spec location but its status is not in the lifecycle enum, so discovery drops it and nothing checks it",
173
+ "no-project-path": "declares no project-path, so no project can be resolved to check it",
174
+ "no-manifest": "names a project with no package.json, so it is not a workspace member",
175
+ "no-check-script": "names a project that defines no `check:spec` script"
176
+ };
177
+ /** Read a file, or null when it cannot be read. */
178
+ function readTextOrNull(path) {
179
+ try {
180
+ return readFileSync(path, "utf8");
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+ /**
186
+ * Run the whole engine set against one project-spec dir. Every engine runs even
187
+ * after one fails: a run that stops at the first failure reports one defect per
188
+ * invocation, and the corpus scope exists to report the tree's defects in one go.
189
+ */
190
+ function runEngines(repoRoot, specDir) {
191
+ let failed = 0;
192
+ for (const e of ENGINES) try {
193
+ execFileSync("node", [enginePath(e), ...e.args(specDir)], {
194
+ cwd: repoRoot,
195
+ stdio: "inherit"
196
+ });
197
+ process.stdout.write(` ok ${e.name}\n`);
198
+ } catch {
199
+ process.stderr.write(` FAIL ${e.name}\n`);
200
+ failed++;
201
+ }
202
+ return failed;
203
+ }
204
+ function checkCoverage(root) {
205
+ const gaps = findCoverageGaps(root, discoverSpecFiles(root), collectSpecs(root), (p) => {
206
+ try {
207
+ return JSON.parse(readFileSync(p, "utf8"));
208
+ } catch {
209
+ return null;
210
+ }
211
+ });
212
+ if (gaps.length === 0) {
213
+ process.stdout.write("check-project-specs: every spec is checked by its project\n");
214
+ return 0;
215
+ }
216
+ for (const g of gaps) process.stderr.write(` ${g.spec} — ${REASON_TEXT[g.reason]}\n`);
217
+ process.stderr.write(`check-project-specs: ${gaps.length} spec(s) no project checks\n`);
218
+ return 1;
219
+ }
220
+ /** The flags the harness defines. Anything else is an error, never a default. */
221
+ const KNOWN_FLAGS = ["--corpus", "--project"];
222
+ /**
223
+ * The scope is chosen by a flag, so an unrecognized one must not fall through to a
224
+ * default. It used to: project scope at a repo root resolves no governing spec and
225
+ * exits 0, so a misspelled or retired flag reported success having checked nothing.
226
+ * That is how `--check-coverage` guarded commits and CI while running no engine.
227
+ */
228
+ function unknownFlags(argv) {
229
+ const out = [];
230
+ for (let i = 0; i < argv.length; i++) {
231
+ const a = argv[i];
232
+ if (!a.startsWith("-")) continue;
233
+ if (a === "--project") {
234
+ i++;
235
+ continue;
236
+ }
237
+ if (!KNOWN_FLAGS.includes(a)) out.push(a);
238
+ }
239
+ return out;
240
+ }
241
+ function main(argv) {
242
+ const unknown = unknownFlags(argv);
243
+ if (unknown.length) {
244
+ process.stderr.write(`check-project-specs: unrecognized flag(s) ${unknown.join(", ")} — the scope is ${KNOWN_FLAGS.join(" | ")} (or none, meaning the cwd's project)\n`);
245
+ return 1;
246
+ }
247
+ if (argv.includes("--corpus") && argv.includes("--project")) {
248
+ process.stderr.write("check-project-specs: --corpus and --project name contradictory scopes — pass one\n");
249
+ return 1;
250
+ }
251
+ if (argv.includes("--corpus")) return checkCorpus();
252
+ return checkProject(argv);
253
+ }
254
+ /**
255
+ * Corpus scope — the commit floor. Total by definition: every project-spec the
256
+ * corpus holds is checked, and a spec that cannot be classified fails rather than
257
+ * being skipped.
258
+ *
259
+ * It runs BOTH sub-checks because neither subsumes the other. The sweep iterates
260
+ * the specs discovery *recognizes*, so a spec whose lifecycle `status` is a typo is
261
+ * invisible to it — and would report clean. The coverage guard sees that file on
262
+ * disk and escalates it, but says nothing about whether the engines pass. Run either
263
+ * alone and a whole project-spec leaves the floor silently.
264
+ */
265
+ function checkCorpus() {
266
+ const root = findRepoRoot(process.cwd());
267
+ if (!root) {
268
+ process.stderr.write("check-project-specs: no pnpm-workspace.yaml found above the cwd\n");
269
+ return 1;
270
+ }
271
+ let failed = checkCoverage(root) === 0 ? 0 : 1;
272
+ const specs = collectSpecs(root);
273
+ if (specs.length === 0) {
274
+ process.stdout.write("check-project-specs: the corpus holds no project-spec\n");
275
+ return failed;
276
+ }
277
+ for (const s of specs) {
278
+ process.stdout.write(`check-project-specs: ${s.path}\n`);
279
+ if (runEngines(root, join(root, s.path)) > 0) failed = 1;
280
+ }
281
+ return failed;
282
+ }
283
+ function checkProject(argv) {
284
+ const projectArg = argv.includes("--project") ? argv[argv.indexOf("--project") + 1] : void 0;
285
+ const projectDir = resolve(projectArg ?? process.cwd());
286
+ const repoRoot = findRepoRoot(projectDir);
287
+ if (!repoRoot) {
288
+ process.stderr.write(`check-project-specs: no pnpm-workspace.yaml found above ${projectDir}\n`);
289
+ return 1;
290
+ }
291
+ const projectRel = relative(repoRoot, projectDir) || ".";
292
+ const specs = collectSpecs(repoRoot);
293
+ const res = resolveSpecFor(specs, projectRel);
294
+ if (res.kind === "none") {
295
+ const dropped = findDroppedSpecFor(discoverSpecFiles(repoRoot), specs, projectRel, (rel) => readTextOrNull(join(repoRoot, rel)));
296
+ for (const d of dropped) process.stderr.write(`check-project-specs: \`${d.file}\` sits at a spec location and governs \`${projectRel}\` but ` + (d.status === "" ? "declares no lifecycle status" : `its status \`${d.status}\` is not in the lifecycle enum`) + " (draft | approved | implemented | deprecated) — discovery drops it, so it is checked by nothing\n");
297
+ if (dropped.length) return 1;
298
+ process.stdout.write(`check-project-specs: no spec governs \`${projectRel}\` — skipped\n`);
299
+ return 0;
300
+ }
301
+ if (res.kind === "ambiguous") {
302
+ process.stderr.write(`check-project-specs: \`${projectRel}\` is claimed by ${res.specs.length} specs (${res.specs.map((s) => s.path).join(", ")}) — a project has exactly one spec\n`);
303
+ return 1;
304
+ }
305
+ const specDir = join(repoRoot, res.spec.path);
306
+ process.stdout.write(`check-project-specs: ${projectRel} -> ${res.spec.path}\n`);
307
+ return runEngines(repoRoot, specDir) === 0 ? 0 : 1;
308
+ }
309
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exit(main(process.argv.slice(2)));
310
+ //#endregion
311
+ export { ENGINES, KNOWN_FLAGS, enginePath, findCoverageGaps, findDroppedSpecFor, findRepoRoot, main, resolveSpecFor, unknownFlags };
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, readdirSync, realpathSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region skills/check-scenario-overlap/scripts/check-scenario-overlap.mts
6
+ const SKIP_DIRS = /* @__PURE__ */ new Set([
7
+ "node_modules",
8
+ ".git",
9
+ "dist",
10
+ ".turbo",
11
+ ".next",
12
+ "coverage"
13
+ ]);
14
+ function normalize(s) {
15
+ return s.trim().replace(/\s+/g, " ").toLowerCase();
16
+ }
17
+ const STEP = /^\s*(Given|When|Then|And|But)\s+(.*\S)\s*$/;
18
+ const SCENARIO = /^\s*Scenario(?: Outline)?:\s*(.*\S)\s*$/;
19
+ const TABLE_ROW = /^\s*\|(.*)\|\s*$/;
20
+ function normalizeRow(line) {
21
+ return (TABLE_ROW.exec(line)?.[1] ?? line).split("|").map((cell) => normalize(cell)).join("|");
22
+ }
23
+ function parseFeature(featureText) {
24
+ const scenarios = [];
25
+ let title = null;
26
+ let steps = [];
27
+ let exampleRows = [];
28
+ const flush = () => {
29
+ if (title !== null) {
30
+ const fingerprint = exampleRows.length === 0 ? steps.map(normalize).join("\n") : `${steps.map(normalize).join("\n")}\n EXAMPLES \n${exampleRows.join("\n")}`;
31
+ scenarios.push({
32
+ title,
33
+ titleKey: normalize(title),
34
+ fingerprint
35
+ });
36
+ }
37
+ title = null;
38
+ steps = [];
39
+ exampleRows = [];
40
+ };
41
+ for (const line of featureText.split("\n")) {
42
+ const sc = SCENARIO.exec(line);
43
+ if (sc) {
44
+ flush();
45
+ title = sc[1];
46
+ continue;
47
+ }
48
+ if (title === null) continue;
49
+ const st = STEP.exec(line);
50
+ if (st) {
51
+ steps.push(st[2]);
52
+ continue;
53
+ }
54
+ if (TABLE_ROW.test(line)) exampleRows.push(normalizeRow(line));
55
+ }
56
+ flush();
57
+ return scenarios;
58
+ }
59
+ function displayPath(relPath) {
60
+ const p = relPath.replace(/\\/g, "/");
61
+ return p.endsWith("/README.md") ? p.slice(0, -9) : p;
62
+ }
63
+ function scanSuites(specDir) {
64
+ const suites = [];
65
+ walk(specDir, specDir, suites);
66
+ return suites.sort((a, b) => a.node.localeCompare(b.node));
67
+ }
68
+ function walk(dir, specDir, out) {
69
+ const entries = readdirSync(dir, { withFileTypes: true });
70
+ for (const entry of entries) {
71
+ if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
72
+ const full = join(dir, entry.name);
73
+ if (entry.isDirectory()) {
74
+ walk(full, specDir, out);
75
+ continue;
76
+ }
77
+ if (!entry.name.endsWith(".feature")) continue;
78
+ const scenarios = parseFeature(readFileSync(full, "utf8"));
79
+ if (scenarios.length === 0) continue;
80
+ const relDir = dir.slice(specDir.length + 1).replace(/\\/g, "/");
81
+ out.push({
82
+ node: displayPath(`${relDir}/`),
83
+ scenarios
84
+ });
85
+ }
86
+ }
87
+ function detect(suites) {
88
+ const byFingerprint = /* @__PURE__ */ new Map();
89
+ const byTitle = /* @__PURE__ */ new Map();
90
+ for (const suite of suites) for (const sc of suite.scenarios) {
91
+ if (sc.fingerprint !== "") {
92
+ let m = byFingerprint.get(sc.fingerprint);
93
+ if (!m) byFingerprint.set(sc.fingerprint, m = /* @__PURE__ */ new Map());
94
+ if (!m.has(suite.node)) m.set(suite.node, sc.title);
95
+ }
96
+ let t = byTitle.get(sc.titleKey);
97
+ if (!t) byTitle.set(sc.titleKey, t = /* @__PURE__ */ new Map());
98
+ let e = t.get(suite.node);
99
+ if (!e) t.set(suite.node, e = {
100
+ fps: /* @__PURE__ */ new Set(),
101
+ title: sc.title
102
+ });
103
+ e.fps.add(sc.fingerprint);
104
+ }
105
+ const candidates = [];
106
+ for (const [, nodeMap] of byFingerprint) {
107
+ if (nodeMap.size < 2) continue;
108
+ const nodes = [...nodeMap.keys()].sort();
109
+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) candidates.push({
110
+ kind: "exact-duplicate",
111
+ severity: "blocking",
112
+ nodes: [nodes[i], nodes[j]],
113
+ scenario: nodeMap.get(nodes[i]) ?? "",
114
+ detail: "identical step fingerprint — the same behavior is specified in both nodes; one behavior = one owning node"
115
+ });
116
+ }
117
+ for (const [, nodeMap] of byTitle) {
118
+ if (nodeMap.size < 2) continue;
119
+ const nodes = [...nodeMap.keys()].sort();
120
+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
121
+ const a = nodeMap.get(nodes[i]);
122
+ const b = nodeMap.get(nodes[j]);
123
+ if (!a || !b) continue;
124
+ if ([...a.fps].some((fp) => b.fps.has(fp))) continue;
125
+ candidates.push({
126
+ kind: "title-overlap",
127
+ severity: "advisory",
128
+ nodes: [nodes[i], nodes[j]],
129
+ scenario: a.title,
130
+ detail: "same scenario title, differing steps — a weaker overlap hint the Warden judges"
131
+ });
132
+ }
133
+ }
134
+ return candidates;
135
+ }
136
+ function hasBlocking(candidates) {
137
+ return candidates.some((c) => c.severity === "blocking");
138
+ }
139
+ function renderCandidates(candidates, specDir) {
140
+ const blocking = candidates.filter((c) => c.severity === "blocking");
141
+ const advisory = candidates.filter((c) => c.severity === "advisory");
142
+ const lines = [`check-scenario-overlap: spec-dir=${specDir}`];
143
+ lines.push(`blocking[${blocking.length}]:`);
144
+ for (const c of blocking) lines.push(` ${c.nodes[0]} <-> ${c.nodes[1]} — ${c.kind}: "${c.scenario}" — ${c.detail}`);
145
+ lines.push(`advisory[${advisory.length}]:`);
146
+ for (const c of advisory) lines.push(` ${c.nodes[0]} <-> ${c.nodes[1]} — ${c.kind}: "${c.scenario}" — ${c.detail}`);
147
+ lines.push("note: advisory — candidates feed the Warden formation pass; the engine writes nothing");
148
+ return lines.join("\n");
149
+ }
150
+ function main(argv) {
151
+ let specDir = ".";
152
+ let mode = "audit";
153
+ let format = "toon";
154
+ for (let i = 0; i < argv.length; i++) {
155
+ const a = argv[i];
156
+ if (a === "--spec-dir") specDir = argv[++i] ?? ".";
157
+ else if (a === "--check") mode = "check";
158
+ else if (a === "--format") format = argv[++i] ?? "toon";
159
+ }
160
+ const candidates = detect(scanSuites(specDir));
161
+ if (mode === "check") {
162
+ if (hasBlocking(candidates)) {
163
+ process.stderr.write(`check-scenario-overlap: ${candidates.filter((c) => c.severity === "blocking").length} exact-duplicate candidate(s)\n`);
164
+ return 1;
165
+ }
166
+ process.stdout.write("check-scenario-overlap: no exact-duplicate candidates\n");
167
+ return 0;
168
+ }
169
+ if (format === "json") process.stdout.write(`${JSON.stringify(candidates)}\n`);
170
+ else process.stdout.write(`${renderCandidates(candidates, specDir)}\n`);
171
+ return 0;
172
+ }
173
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exit(main(process.argv.slice(2)));
174
+ //#endregion
175
+ export { detect, hasBlocking, main, normalize, parseFeature, renderCandidates, scanSuites };