@kirill.konshin/lint 0.8.8 → 0.8.10

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.
@@ -27,6 +27,103 @@ var __exportAll = (all, no_symbols) => {
27
27
  };
28
28
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
29
29
  //#endregion
30
+ //#region spec-tools/src/steward/lib/util.ts
31
+ /** Text helpers shared by every steward command: slugs, tokens, RFC 2119 keywords, absolutes. */
32
+ /**
33
+ * GitHub/Docusaurus heading slug (github-slugger semantics): lowercase, drop punctuation and symbols, every space
34
+ * becomes a hyphen (runs are NOT collapsed, so `a — b` is `a--b`). `seen` makes repeats unique the way a rendered
35
+ * page does (`x`, `x-1`, `x-2`).
36
+ */
37
+ function slugify(heading, seen) {
38
+ const base = heading.toLowerCase().trim().replace(/[^\p{L}\p{N}\p{M}\p{Pc} -]/gu, "").replace(/ /g, "-");
39
+ if (!seen) return base;
40
+ let slug = base;
41
+ while (seen.has(slug)) {
42
+ const next = (seen.get(base) ?? 0) + 1;
43
+ seen.set(base, next);
44
+ slug = `${base}-${next}`;
45
+ }
46
+ seen.set(slug, 0);
47
+ return slug;
48
+ }
49
+ /**
50
+ * Minimal argv parser: `--key value`, `--key=value`, `--flag`, repeated keys collect into arrays. A key listed in
51
+ * `booleans` never takes the next argument as its value.
52
+ */
53
+ function parseArgs(argv, repeatable = [], booleans = []) {
54
+ const opts = { _: [] };
55
+ for (let i = 0; i < argv.length; i++) {
56
+ const arg = argv[i];
57
+ if (!arg.startsWith("--")) {
58
+ opts._.push(arg);
59
+ continue;
60
+ }
61
+ const eq = arg.indexOf("=");
62
+ const key = eq > 0 ? arg.slice(2, eq) : arg.slice(2);
63
+ let value = eq > 0 ? arg.slice(eq + 1) : true;
64
+ if (value === true && !booleans.includes(key) && argv[i + 1] !== void 0 && !argv[i + 1].startsWith("--")) value = argv[++i];
65
+ if (repeatable.includes(key)) (opts[key] ??= []).push(value);
66
+ else opts[key] = value;
67
+ }
68
+ return opts;
69
+ }
70
+ /**
71
+ * A repository-relative glob as a RegExp: `**` spans directories, `*` and `?` stay inside one, `{a,b}` alternates.
72
+ */
73
+ function globToRegExp(glob) {
74
+ let re = "";
75
+ for (let i = 0; i < glob.length; i++) {
76
+ const c = glob[i];
77
+ const end = c === "{" ? glob.indexOf("}", i) : -1;
78
+ if (c === "*" && glob[i + 1] === "*") {
79
+ const slash = glob[i + 2] === "/";
80
+ re += slash ? "(?:.*/)?" : ".*";
81
+ i += slash ? 2 : 1;
82
+ } else if (c === "*") re += "[^/]*";
83
+ else if (c === "?") re += "[^/]";
84
+ else if (end > i) {
85
+ re += `(?:${glob.slice(i + 1, end).split(",").map(escapeRe).join("|")})`;
86
+ i = end;
87
+ } else re += escapeRe(c);
88
+ }
89
+ return new RegExp(`^${re}$`);
90
+ }
91
+ var stripCode, normalize$2, STRONG, WEAK, strongCount, weakCount, ABSOLUTE, EXCEPTION, sentences, absolutesIn, exceptionsIn, STOP, words$1, codeTokens, containment, jaccard, wordCount, escapeRe;
92
+ var init_util = __esmMin((() => {
93
+ stripCode = (text) => text.replace(/`[^`\n]*`/g, " ");
94
+ normalize$2 = (text) => text.replace(/\s+/g, " ").trim();
95
+ STRONG = /\b(MUST NOT|MUST|SHALL NOT|SHALL|REQUIRED)\b/g;
96
+ WEAK = /\b(SHOULD NOT|SHOULD|RECOMMENDED|MAY|OPTIONAL)\b/g;
97
+ strongCount = (text) => (stripCode(text).match(STRONG) ?? []).length;
98
+ weakCount = (text) => (stripCode(text).match(WEAK) ?? []).length;
99
+ ABSOLUTE = /\b(never|always|only|every|all|none|no|any)\b/gi;
100
+ EXCEPTION = /\b(except|unless|where possible|if possible|when feasible|as appropriate|otherwise|instead)\b/gi;
101
+ sentences = (text) => stripCode(text).split(/(?<=[.!?])\s+|\n\s*[-*]\s+|\n{2,}/).map((s) => s.trim()).filter(Boolean);
102
+ absolutesIn = (text) => sentences(text).filter((s) => /\b(MUST|SHALL|REQUIRED)\b/.test(s)).flatMap((s) => (s.match(ABSOLUTE) ?? []).map((w) => w.toLowerCase()));
103
+ exceptionsIn = (text) => (stripCode(text).match(EXCEPTION) ?? []).map((w) => w.toLowerCase());
104
+ STOP = new Set("the a an and or of to in on for with by from at as is are be been was were it its this that these those when then which who what where while if else not no any all each every one two than into onto via per their there them they his her our your can may must shall should will would could does do did has have had only also more most less such same other another so but nor yet very just over under between within without about after before during because both either neither".split(" "));
105
+ words$1 = (text) => (stripCode(text).toLowerCase().match(/[\p{L}][\p{L}\p{N}_-]{3,}/gu) ?? []).filter((w) => !STOP.has(w)).map((w) => w.length > 4 ? w.replace(/(?:ing|ed|es|s)$/, "") : w);
106
+ codeTokens = (text) => [...text.matchAll(/`([^`\n]{2,80})`/g)].map((m) => m[1].trim());
107
+ containment = (a, b) => {
108
+ const sa = new Set(a);
109
+ if (!sa.size) return 0;
110
+ const sb = new Set(b);
111
+ let hit = 0;
112
+ for (const w of sa) if (sb.has(w)) hit++;
113
+ return hit / sa.size;
114
+ };
115
+ jaccard = (a, b) => {
116
+ const sa = new Set(a);
117
+ const sb = new Set(b);
118
+ if (!sa.size && !sb.size) return 1;
119
+ let inter = 0;
120
+ for (const w of sa) if (sb.has(w)) inter++;
121
+ return inter / (sa.size + sb.size - inter);
122
+ };
123
+ wordCount = (text) => (text.match(/\S+/g) ?? []).length;
124
+ escapeRe = (s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&");
125
+ }));
126
+ //#endregion
30
127
  //#region spec-tools/src/files.ts
31
128
  var files_exports = /* @__PURE__ */ __exportAll({
32
129
  AUDIT_DIR: () => AUDIT_DIR,
@@ -88,19 +185,186 @@ var init_files = __esmMin((() => {
88
185
  jobLogFile = (job) => `${AUDIT_DIR}/job-log-${job}.md`;
89
186
  }));
90
187
  //#endregion
91
- //#region spec-tools/src/repo.ts
92
- var repo_exports = /* @__PURE__ */ __exportAll({
93
- git: () => git$1,
94
- root: () => root
188
+ //#region spec-tools/src/steward/lib/git.ts
189
+ /** The few git reads steward needs; every one degrades to "nothing" outside a repository. */
190
+ var git_exports = /* @__PURE__ */ __exportAll({
191
+ changedFiles: () => changedFiles,
192
+ commitOf: () => commitOf,
193
+ filesAt: () => filesAt,
194
+ forget: () => forget,
195
+ git: () => git,
196
+ gitOrThrow: () => gitOrThrow,
197
+ listFiles: () => listFiles,
198
+ mergeBase: () => mergeBase,
199
+ repoRoot: () => repoRoot,
200
+ resolveBase: () => resolveBase,
201
+ show: () => show$1,
202
+ showMany: () => showMany,
203
+ toplevel: () => toplevel
95
204
  });
96
- var top, root, git$1;
97
- var init_repo = __esmMin((() => {
98
- root = () => top ??= execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" }).trim();
99
- git$1 = (args, cwd = root()) => execFileSync("git", args, {
205
+ /** @returns stdout, or null when git fails */
206
+ function git(cwd, args) {
207
+ try {
208
+ return execFileSync("git", args, {
209
+ cwd,
210
+ encoding: "utf8",
211
+ maxBuffer: 268435456,
212
+ stdio: [
213
+ "ignore",
214
+ "pipe",
215
+ "ignore"
216
+ ]
217
+ });
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+ /** Tracked plus untracked-but-not-ignored files, repository-relative; null when git cannot list them. */
223
+ function listFiles(root) {
224
+ return once(`files:${root}`, () => {
225
+ const out = git(root, [
226
+ "ls-files",
227
+ "--cached",
228
+ "--others",
229
+ "--exclude-standard",
230
+ "-z"
231
+ ]);
232
+ return out === null ? null : [...new Set(out.split("\0").filter(Boolean))];
233
+ });
234
+ }
235
+ /** Many files' contents at a ref in one git process; a file absent there maps to null. */
236
+ function showMany(root, ref, files) {
237
+ const out = new Map(files.map((f) => [f, null]));
238
+ if (!files.length) return out;
239
+ let buf;
240
+ try {
241
+ buf = execFileSync("git", ["cat-file", "--batch"], {
242
+ cwd: root,
243
+ input: files.map((f) => `${ref}:${f}\n`).join(""),
244
+ maxBuffer: 268435456,
245
+ stdio: [
246
+ "pipe",
247
+ "pipe",
248
+ "ignore"
249
+ ]
250
+ });
251
+ } catch {
252
+ return out;
253
+ }
254
+ let at = 0;
255
+ for (const file of files) {
256
+ const eol = buf.indexOf(10, at);
257
+ if (eol < 0) break;
258
+ const header = buf.subarray(at, eol).toString("utf8");
259
+ at = eol + 1;
260
+ const size = /^[0-9a-f]+ blob (\d+)$/.exec(header)?.[1];
261
+ if (size === void 0) continue;
262
+ out.set(file, buf.subarray(at, at + Number(size)).toString("utf8"));
263
+ at += Number(size) + 1;
264
+ }
265
+ return out;
266
+ }
267
+ /** Files under `dir` at `ref`. */
268
+ function filesAt(root, ref, dir) {
269
+ const out = git(root, [
270
+ "ls-tree",
271
+ "-r",
272
+ "--name-only",
273
+ "-z",
274
+ ref,
275
+ "--",
276
+ dir
277
+ ]);
278
+ return out ? out.split("\0").filter(Boolean) : [];
279
+ }
280
+ /**
281
+ * Files the working tree changes against `ref`: tracked edits, additions, deletions and renames, plus untracked files.
282
+ */
283
+ function changedFiles(root, ref) {
284
+ const tracked = git(root, [
285
+ "diff",
286
+ "--name-only",
287
+ "-z",
288
+ ref,
289
+ "--"
290
+ ]) ?? "";
291
+ const untracked = git(root, [
292
+ "ls-files",
293
+ "--others",
294
+ "--exclude-standard",
295
+ "-z"
296
+ ]) ?? "";
297
+ return new Set([...tracked.split("\0"), ...untracked.split("\0")].filter(Boolean));
298
+ }
299
+ /**
300
+ * The base `--base` names (R-004): a merge request's diff base in CI, nothing in another CI pipeline, the merge base
301
+ * with `origin/HEAD` (or `origin/main`) locally; an explicit ref is compared through its merge base with HEAD.
302
+ *
303
+ * @param given `auto`, a ref, or true when the flag had no value
304
+ */
305
+ function resolveBase(root, given, env = process.env) {
306
+ if (given !== "auto") {
307
+ if (given === true || !given) return { error: "--base needs a ref, or auto" };
308
+ if (!commitOf(root, given)) return { error: `base ref ${given} not found — git fetch origin` };
309
+ return {
310
+ ref: mergeBase(root, given),
311
+ how: `merge base of ${given}`
312
+ };
313
+ }
314
+ const sha = env.CI_MERGE_REQUEST_DIFF_BASE_SHA;
315
+ if (sha) {
316
+ if (!commitOf(root, sha)) return { error: `CI_MERGE_REQUEST_DIFF_BASE_SHA ${sha} is not in this clone` };
317
+ return {
318
+ ref: sha,
319
+ how: "the merge request diff base"
320
+ };
321
+ }
322
+ if (env.CI) return {
323
+ ref: null,
324
+ how: "none — a CI pipeline outside a merge request"
325
+ };
326
+ for (const upstream of ["origin/HEAD", "origin/main"]) {
327
+ if (!commitOf(root, upstream)) continue;
328
+ const ref = git(root, [
329
+ "merge-base",
330
+ upstream,
331
+ "HEAD"
332
+ ])?.trim();
333
+ if (ref) return {
334
+ ref,
335
+ how: `merge base of ${upstream}`
336
+ };
337
+ }
338
+ return { error: "no origin/HEAD or origin/main to compare against — git fetch origin" };
339
+ }
340
+ var gitOrThrow, top, repoRoot, memo, once, forget, toplevel, show$1, commitOf, mergeBase;
341
+ var init_git = __esmMin((() => {
342
+ gitOrThrow = (cwd, args, input) => execFileSync("git", args, {
100
343
  cwd,
101
344
  encoding: "utf8",
102
- maxBuffer: 67108864
345
+ maxBuffer: 268435456,
346
+ input
103
347
  });
348
+ repoRoot = () => top ??= gitOrThrow(process.cwd(), ["rev-parse", "--show-toplevel"]).trim();
349
+ memo = /* @__PURE__ */ new Map();
350
+ once = (key, read) => {
351
+ if (!memo.has(key)) memo.set(key, read());
352
+ return memo.get(key);
353
+ };
354
+ forget = () => memo.clear();
355
+ toplevel = (dir) => once(`toplevel:${dir}`, () => git(dir, ["rev-parse", "--show-toplevel"])?.trim() || null);
356
+ show$1 = (root, ref, file) => git(root, ["show", `${ref}:${file}`]);
357
+ commitOf = (root, ref) => git(root, [
358
+ "rev-parse",
359
+ "--verify",
360
+ "--quiet",
361
+ `${ref}^{commit}`
362
+ ])?.trim() || null;
363
+ mergeBase = (root, ref) => git(root, [
364
+ "merge-base",
365
+ ref,
366
+ "HEAD"
367
+ ])?.trim() || ref;
104
368
  }));
105
369
  //#endregion
106
370
  //#region ../../node_modules/yaml/dist/nodes/identity.js
@@ -6764,10 +7028,21 @@ var require_dist = /* @__PURE__ */ __commonJSMin(((exports) => {
6764
7028
  */
6765
7029
  /** A value from YAML text; throws with the first parse error and its line. */
6766
7030
  function parseData(text) {
6767
- const doc = (0, import_dist$1.parseDocument)(text, { uniqueKeys: true });
7031
+ const doc = (0, import_dist.parseDocument)(text, { uniqueKeys: true });
6768
7032
  if (doc.errors.length) throw new Error(parseErrors(doc.errors)[0]);
6769
7033
  return doc.toJS({ maxAliasCount: -1 });
6770
7034
  }
7035
+ /**
7036
+ * A value from YAML text that a person edits (the review file): its value, or — duplicate keys included — every parse
7037
+ * error with its line, and no value.
7038
+ */
7039
+ function readEdited(text) {
7040
+ const doc = (0, import_dist.parseDocument)(text, { uniqueKeys: true });
7041
+ return doc.errors.length ? { errors: parseErrors(doc.errors) } : {
7042
+ value: doc.toJS(),
7043
+ errors: []
7044
+ };
7045
+ }
6771
7046
  /** A data file, if it exists and parses; otherwise undefined. */
6772
7047
  function tryReadData(file) {
6773
7048
  try {
@@ -6824,22 +7099,23 @@ function validate(value, schema, at, errors) {
6824
7099
  }
6825
7100
  /** Every problem with a data file's text against its schema: parse errors with their line, then missing or wrong fields. */
6826
7101
  function checkData(text, schema) {
6827
- const doc = (0, import_dist$1.parseDocument)(text, { uniqueKeys: true });
7102
+ const doc = (0, import_dist.parseDocument)(text, { uniqueKeys: true });
6828
7103
  if (doc.errors.length) return parseErrors(doc.errors).slice(0, MAX_ERRORS);
6829
7104
  const errors = [];
6830
7105
  validate(doc.toJS({ maxAliasCount: -1 }), schema, "", errors);
6831
7106
  return errors;
6832
7107
  }
6833
- var import_dist$1, toYaml, readData, parseErrors, MAX_ERRORS, checkFile, str, optStr, strings, optStrings, CONFIDENCE, SEVERITY, READER_FINDINGS, JUDGE_VERDICT, STEWARD_FINDINGS, STEWARD_VERDICT, REVIEW_REPORT;
7108
+ var import_dist, parseErrors, toYaml, readData, readLoose, MAX_ERRORS, checkFile, str, optStr, strings, optStrings, CONFIDENCE, SEVERITY, READER_FINDINGS, JUDGE_VERDICT, STEWARD_FINDINGS, STEWARD_VERDICT, REVIEW_REPORT;
6834
7109
  var init_data = __esmMin((() => {
6835
- import_dist$1 = require_dist();
6836
- toYaml = (data) => (0, import_dist$1.stringify)(data, {
7110
+ import_dist = require_dist();
7111
+ parseErrors = (errors) => errors.map((e) => `line ${e.linePos?.[0]?.line ?? "?"}: not valid YAML: ${e.message.split("\n")[0]}`);
7112
+ toYaml = (data) => (0, import_dist.stringify)(data, {
6837
7113
  lineWidth: 0,
6838
7114
  blockQuote: "literal",
6839
7115
  aliasDuplicateObjects: false
6840
7116
  });
6841
7117
  readData = (file) => parseData(fs$1.readFileSync(file, "utf8"));
6842
- parseErrors = (errors) => errors.map((e) => `line ${e.linePos?.[0]?.line ?? "?"}: not valid YAML: ${e.message.split("\n")[0]}`);
7118
+ readLoose = (file) => (0, import_dist.parseDocument)(fs$1.readFileSync(file, "utf8")).toJS();
6843
7119
  MAX_ERRORS = 20;
6844
7120
  checkFile = (file, schema) => fs$1.existsSync(file) ? checkData(fs$1.readFileSync(file, "utf8"), schema) : [`${file}: the file was not written`];
6845
7121
  str = { type: "string" };
@@ -7013,166 +7289,6 @@ var init_data = __esmMin((() => {
7013
7289
  };
7014
7290
  }));
7015
7291
  //#endregion
7016
- //#region spec-tools/src/steward/lib/git.ts
7017
- /** The few git reads steward needs; every one degrades to "nothing" outside a repository. */
7018
- /** @returns stdout, or null when git fails */
7019
- function git(cwd, args) {
7020
- try {
7021
- return execFileSync("git", args, {
7022
- cwd,
7023
- encoding: "utf8",
7024
- maxBuffer: 268435456,
7025
- stdio: [
7026
- "ignore",
7027
- "pipe",
7028
- "ignore"
7029
- ]
7030
- });
7031
- } catch {
7032
- return null;
7033
- }
7034
- }
7035
- /** Tracked plus untracked-but-not-ignored files, repository-relative; null when git cannot list them. */
7036
- function listFiles(root) {
7037
- return once(`files:${root}`, () => {
7038
- const out = git(root, [
7039
- "ls-files",
7040
- "--cached",
7041
- "--others",
7042
- "--exclude-standard",
7043
- "-z"
7044
- ]);
7045
- return out === null ? null : [...new Set(out.split("\0").filter(Boolean))];
7046
- });
7047
- }
7048
- /** Many files' contents at a ref in one git process; a file absent there maps to null. */
7049
- function showMany(root, ref, files) {
7050
- const out = new Map(files.map((f) => [f, null]));
7051
- if (!files.length) return out;
7052
- let buf;
7053
- try {
7054
- buf = execFileSync("git", ["cat-file", "--batch"], {
7055
- cwd: root,
7056
- input: files.map((f) => `${ref}:${f}\n`).join(""),
7057
- maxBuffer: 268435456,
7058
- stdio: [
7059
- "pipe",
7060
- "pipe",
7061
- "ignore"
7062
- ]
7063
- });
7064
- } catch {
7065
- return out;
7066
- }
7067
- let at = 0;
7068
- for (const file of files) {
7069
- const eol = buf.indexOf(10, at);
7070
- if (eol < 0) break;
7071
- const header = buf.subarray(at, eol).toString("utf8");
7072
- at = eol + 1;
7073
- const size = /^[0-9a-f]+ blob (\d+)$/.exec(header)?.[1];
7074
- if (size === void 0) continue;
7075
- out.set(file, buf.subarray(at, at + Number(size)).toString("utf8"));
7076
- at += Number(size) + 1;
7077
- }
7078
- return out;
7079
- }
7080
- /** Files under `dir` at `ref`. */
7081
- function filesAt(root, ref, dir) {
7082
- const out = git(root, [
7083
- "ls-tree",
7084
- "-r",
7085
- "--name-only",
7086
- "-z",
7087
- ref,
7088
- "--",
7089
- dir
7090
- ]);
7091
- return out ? out.split("\0").filter(Boolean) : [];
7092
- }
7093
- /**
7094
- * Files the working tree changes against `ref`: tracked edits, additions, deletions and renames, plus untracked files.
7095
- */
7096
- function changedFiles(root, ref) {
7097
- const tracked = git(root, [
7098
- "diff",
7099
- "--name-only",
7100
- "-z",
7101
- ref,
7102
- "--"
7103
- ]) ?? "";
7104
- const untracked = git(root, [
7105
- "ls-files",
7106
- "--others",
7107
- "--exclude-standard",
7108
- "-z"
7109
- ]) ?? "";
7110
- return new Set([...tracked.split("\0"), ...untracked.split("\0")].filter(Boolean));
7111
- }
7112
- /**
7113
- * The base `--base` names (R-004): a merge request's diff base in CI, nothing in another CI pipeline, the merge base
7114
- * with `origin/HEAD` (or `origin/main`) locally; an explicit ref is compared through its merge base with HEAD.
7115
- *
7116
- * @param given `auto`, a ref, or true when the flag had no value
7117
- */
7118
- function resolveBase(root, given, env = process.env) {
7119
- if (given !== "auto") {
7120
- if (given === true || !given) return { error: "--base needs a ref, or auto" };
7121
- if (!commitOf(root, given)) return { error: `base ref ${given} not found — git fetch origin` };
7122
- return {
7123
- ref: mergeBase(root, given),
7124
- how: `merge base of ${given}`
7125
- };
7126
- }
7127
- const sha = env.CI_MERGE_REQUEST_DIFF_BASE_SHA;
7128
- if (sha) {
7129
- if (!commitOf(root, sha)) return { error: `CI_MERGE_REQUEST_DIFF_BASE_SHA ${sha} is not in this clone` };
7130
- return {
7131
- ref: sha,
7132
- how: "the merge request diff base"
7133
- };
7134
- }
7135
- if (env.CI) return {
7136
- ref: null,
7137
- how: "none — a CI pipeline outside a merge request"
7138
- };
7139
- for (const upstream of ["origin/HEAD", "origin/main"]) {
7140
- if (!commitOf(root, upstream)) continue;
7141
- const ref = git(root, [
7142
- "merge-base",
7143
- upstream,
7144
- "HEAD"
7145
- ])?.trim();
7146
- if (ref) return {
7147
- ref,
7148
- how: `merge base of ${upstream}`
7149
- };
7150
- }
7151
- return { error: "no origin/HEAD or origin/main to compare against — git fetch origin" };
7152
- }
7153
- var memo, once, forget, toplevel, show$1, commitOf, mergeBase;
7154
- var init_git = __esmMin((() => {
7155
- memo = /* @__PURE__ */ new Map();
7156
- once = (key, read) => {
7157
- if (!memo.has(key)) memo.set(key, read());
7158
- return memo.get(key);
7159
- };
7160
- forget = () => memo.clear();
7161
- toplevel = (dir) => once(`toplevel:${dir}`, () => git(dir, ["rev-parse", "--show-toplevel"])?.trim() || null);
7162
- show$1 = (root, ref, file) => git(root, ["show", `${ref}:${file}`]);
7163
- commitOf = (root, ref) => git(root, [
7164
- "rev-parse",
7165
- "--verify",
7166
- "--quiet",
7167
- `${ref}^{commit}`
7168
- ])?.trim() || null;
7169
- mergeBase = (root, ref) => git(root, [
7170
- "merge-base",
7171
- ref,
7172
- "HEAD"
7173
- ])?.trim() || ref;
7174
- }));
7175
- //#endregion
7176
7292
  //#region spec-tools/src/steward/lib/scan.ts
7177
7293
  /**
7178
7294
  * Classify every character of a C-family source as CODE, COMMENT or STRING. A quoted string never spans a line: an
@@ -7470,122 +7586,25 @@ function stripComments(file, text) {
7470
7586
  const cls = lex(text);
7471
7587
  const chars = text.split("");
7472
7588
  for (let i = 0; i < chars.length; i++) if (cls[i] === 1 && chars[i] !== "\n") chars[i] = " ";
7473
- return chars.join("");
7474
- }
7475
- var isCLike, isDoc, REGEX_AFTER, REGEX_KEYWORD, OPEN, indentOf, TEST_NAME, TEST_MODIFIERS, TYPE_ASSERTION, TYPE_CALL, C_COMMENT_LINE;
7476
- var init_scan = __esmMin((() => {
7477
- isCLike = (file) => /\.(?:[cm]?[jt]sx?|go)$/i.test(file);
7478
- isDoc = (file) => /\.mdx?$/i.test(file);
7479
- REGEX_AFTER = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^".split(""), ""]);
7480
- REGEX_KEYWORD = /^(?:return|typeof|instanceof|in|of|new|delete|void|throw|case|do|else|yield|await)$/;
7481
- OPEN = {
7482
- "(": ")",
7483
- "[": "]",
7484
- "{": "}"
7485
- };
7486
- indentOf = (line) => /^\s*/.exec(line)?.[0].length ?? 0;
7487
- TEST_NAME = /(?<![\w$.])(?:describe|it|test|suite|bench)(?![\w$])/g;
7488
- TEST_MODIFIERS = /* @__PURE__ */ new Set([..."only skip concurrent sequential todo each for runIf skipIf fails".split(" "), ..."describe step serial parallel fixme fail".split(" ")]);
7489
- TYPE_ASSERTION = /^\s*(?:export\s+)?type\s+([\w$]+)\b[^=]*=\s*Expect\s*</;
7490
- TYPE_CALL = /(?<![\w$.])(?:expectTypeOf|assertType)\s*[(<]/;
7491
- C_COMMENT_LINE = /^\s*(?:\/\/|\/\*|\*)/;
7492
- }));
7493
- //#endregion
7494
- //#region spec-tools/src/steward/lib/util.ts
7495
- /** Text helpers shared by every steward command: slugs, tokens, RFC 2119 keywords, absolutes. */
7496
- /**
7497
- * GitHub/Docusaurus heading slug (github-slugger semantics): lowercase, drop punctuation and symbols, every space
7498
- * becomes a hyphen (runs are NOT collapsed, so `a — b` is `a--b`). `seen` makes repeats unique the way a rendered
7499
- * page does (`x`, `x-1`, `x-2`).
7500
- */
7501
- function slugify(heading, seen) {
7502
- const base = heading.toLowerCase().trim().replace(/[^\p{L}\p{N}\p{M}\p{Pc} -]/gu, "").replace(/ /g, "-");
7503
- if (!seen) return base;
7504
- let slug = base;
7505
- while (seen.has(slug)) {
7506
- const next = (seen.get(base) ?? 0) + 1;
7507
- seen.set(base, next);
7508
- slug = `${base}-${next}`;
7509
- }
7510
- seen.set(slug, 0);
7511
- return slug;
7512
- }
7513
- /**
7514
- * Minimal argv parser: `--key value`, `--key=value`, `--flag`, repeated keys collect into arrays. A key listed in
7515
- * `booleans` never takes the next argument as its value.
7516
- */
7517
- function parseArgs(argv, repeatable = [], booleans = []) {
7518
- const opts = { _: [] };
7519
- for (let i = 0; i < argv.length; i++) {
7520
- const arg = argv[i];
7521
- if (!arg.startsWith("--")) {
7522
- opts._.push(arg);
7523
- continue;
7524
- }
7525
- const eq = arg.indexOf("=");
7526
- const key = eq > 0 ? arg.slice(2, eq) : arg.slice(2);
7527
- let value = eq > 0 ? arg.slice(eq + 1) : true;
7528
- if (value === true && !booleans.includes(key) && argv[i + 1] !== void 0 && !argv[i + 1].startsWith("--")) value = argv[++i];
7529
- if (repeatable.includes(key)) (opts[key] ??= []).push(value);
7530
- else opts[key] = value;
7531
- }
7532
- return opts;
7533
- }
7534
- /**
7535
- * A repository-relative glob as a RegExp: `**` spans directories, `*` and `?` stay inside one, `{a,b}` alternates.
7536
- */
7537
- function globToRegExp(glob) {
7538
- let re = "";
7539
- for (let i = 0; i < glob.length; i++) {
7540
- const c = glob[i];
7541
- const end = c === "{" ? glob.indexOf("}", i) : -1;
7542
- if (c === "*" && glob[i + 1] === "*") {
7543
- const slash = glob[i + 2] === "/";
7544
- re += slash ? "(?:.*/)?" : ".*";
7545
- i += slash ? 2 : 1;
7546
- } else if (c === "*") re += "[^/]*";
7547
- else if (c === "?") re += "[^/]";
7548
- else if (end > i) {
7549
- re += `(?:${glob.slice(i + 1, end).split(",").map(escapeRe).join("|")})`;
7550
- i = end;
7551
- } else re += escapeRe(c);
7552
- }
7553
- return new RegExp(`^${re}$`);
7589
+ return chars.join("");
7554
7590
  }
7555
- var stripCode, normalize$2, STRONG, WEAK, strongCount, weakCount, ABSOLUTE, EXCEPTION, sentences, absolutesIn, exceptionsIn, STOP, words$1, codeTokens, containment, jaccard, wordCount, escapeRe;
7556
- var init_util = __esmMin((() => {
7557
- stripCode = (text) => text.replace(/`[^`\n]*`/g, " ");
7558
- normalize$2 = (text) => text.replace(/\s+/g, " ").trim();
7559
- STRONG = /\b(MUST NOT|MUST|SHALL NOT|SHALL|REQUIRED)\b/g;
7560
- WEAK = /\b(SHOULD NOT|SHOULD|RECOMMENDED|MAY|OPTIONAL)\b/g;
7561
- strongCount = (text) => (stripCode(text).match(STRONG) ?? []).length;
7562
- weakCount = (text) => (stripCode(text).match(WEAK) ?? []).length;
7563
- ABSOLUTE = /\b(never|always|only|every|all|none|no|any)\b/gi;
7564
- EXCEPTION = /\b(except|unless|where possible|if possible|when feasible|as appropriate|otherwise|instead)\b/gi;
7565
- sentences = (text) => stripCode(text).split(/(?<=[.!?])\s+|\n\s*[-*]\s+|\n{2,}/).map((s) => s.trim()).filter(Boolean);
7566
- absolutesIn = (text) => sentences(text).filter((s) => /\b(MUST|SHALL|REQUIRED)\b/.test(s)).flatMap((s) => (s.match(ABSOLUTE) ?? []).map((w) => w.toLowerCase()));
7567
- exceptionsIn = (text) => (stripCode(text).match(EXCEPTION) ?? []).map((w) => w.toLowerCase());
7568
- STOP = new Set("the a an and or of to in on for with by from at as is are be been was were it its this that these those when then which who what where while if else not no any all each every one two than into onto via per their there them they his her our your can may must shall should will would could does do did has have had only also more most less such same other another so but nor yet very just over under between within without about after before during because both either neither".split(" "));
7569
- words$1 = (text) => (stripCode(text).toLowerCase().match(/[\p{L}][\p{L}\p{N}_-]{3,}/gu) ?? []).filter((w) => !STOP.has(w)).map((w) => w.length > 4 ? w.replace(/(?:ing|ed|es|s)$/, "") : w);
7570
- codeTokens = (text) => [...text.matchAll(/`([^`\n]{2,80})`/g)].map((m) => m[1].trim());
7571
- containment = (a, b) => {
7572
- const sa = new Set(a);
7573
- if (!sa.size) return 0;
7574
- const sb = new Set(b);
7575
- let hit = 0;
7576
- for (const w of sa) if (sb.has(w)) hit++;
7577
- return hit / sa.size;
7578
- };
7579
- jaccard = (a, b) => {
7580
- const sa = new Set(a);
7581
- const sb = new Set(b);
7582
- if (!sa.size && !sb.size) return 1;
7583
- let inter = 0;
7584
- for (const w of sa) if (sb.has(w)) inter++;
7585
- return inter / (sa.size + sb.size - inter);
7591
+ var isCLike, isDoc, REGEX_AFTER, REGEX_KEYWORD, OPEN, indentOf, TEST_NAME, TEST_MODIFIERS, TYPE_ASSERTION, TYPE_CALL, C_COMMENT_LINE;
7592
+ var init_scan = __esmMin((() => {
7593
+ isCLike = (file) => /\.(?:[cm]?[jt]sx?|go)$/i.test(file);
7594
+ isDoc = (file) => /\.mdx?$/i.test(file);
7595
+ REGEX_AFTER = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^".split(""), ""]);
7596
+ REGEX_KEYWORD = /^(?:return|typeof|instanceof|in|of|new|delete|void|throw|case|do|else|yield|await)$/;
7597
+ OPEN = {
7598
+ "(": ")",
7599
+ "[": "]",
7600
+ "{": "}"
7586
7601
  };
7587
- wordCount = (text) => (text.match(/\S+/g) ?? []).length;
7588
- escapeRe = (s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&");
7602
+ indentOf = (line) => /^\s*/.exec(line)?.[0].length ?? 0;
7603
+ TEST_NAME = /(?<![\w$.])(?:describe|it|test|suite|bench)(?![\w$])/g;
7604
+ TEST_MODIFIERS = /* @__PURE__ */ new Set([..."only skip concurrent sequential todo each for runIf skipIf fails".split(" "), ..."describe step serial parallel fixme fail".split(" ")]);
7605
+ TYPE_ASSERTION = /^\s*(?:export\s+)?type\s+([\w$]+)\b[^=]*=\s*Expect\s*</;
7606
+ TYPE_CALL = /(?<![\w$.])(?:expectTypeOf|assertType)\s*[(<]/;
7607
+ C_COMMENT_LINE = /^\s*(?:\/\/|\/\*|\*)/;
7589
7608
  }));
7590
7609
  //#endregion
7591
7610
  //#region spec-tools/src/steward/lib/citations.ts
@@ -7621,6 +7640,24 @@ function anchorsFor(abs, anchorsOf) {
7621
7640
  return anchorCache.get(abs);
7622
7641
  }
7623
7642
  /**
7643
+ * Reads repository files, keeping the bytes of those `keep` accepts for the next reader of the same file — so the
7644
+ * citation scan and the source index read a source once between them.
7645
+ */
7646
+ function fileReader(root, keep = () => false) {
7647
+ const kept = /* @__PURE__ */ new Map();
7648
+ return (file) => {
7649
+ if (kept.has(file)) return kept.get(file);
7650
+ let buf;
7651
+ try {
7652
+ buf = fs.readFileSync(path.join(root, file));
7653
+ } catch {
7654
+ buf = void 0;
7655
+ }
7656
+ if (keep(file)) kept.set(file, buf);
7657
+ return buf;
7658
+ };
7659
+ }
7660
+ /**
7624
7661
  * Every citation in the repository's text files (a NUL byte marks a binary file).
7625
7662
  *
7626
7663
  * @param anchorsOf renders a spec's anchors
@@ -7628,15 +7665,11 @@ function anchorsFor(abs, anchorsOf) {
7628
7665
  function scanCitations(root, anchorsOf, opts = {}) {
7629
7666
  anchorCache.clear();
7630
7667
  const binds = (opts.binds ?? []).map(globToRegExp);
7668
+ const read = opts.read ?? fileReader(root);
7631
7669
  const out = [];
7632
7670
  for (const file of scanUniverse(root, opts) ?? []) {
7633
- let buf;
7634
- try {
7635
- buf = fs.readFileSync(path.join(root, file));
7636
- } catch {
7637
- continue;
7638
- }
7639
- if (buf.indexOf("openspec/specs/") < 0 || buf.includes(0)) continue;
7671
+ const buf = read(file);
7672
+ if (!buf || buf.indexOf("openspec/specs/") < 0 || buf.includes(0)) continue;
7640
7673
  const text = buf.toString("utf8");
7641
7674
  const lines = text.split("\n");
7642
7675
  const kind = isTestFile(file) ? "test" : isDoc(file) ? "doc" : "code";
@@ -7852,27 +7885,27 @@ function parseSpec(text, file, capability) {
7852
7885
  duplicates
7853
7886
  };
7854
7887
  }
7855
- /** Every spec.md under a directory on disk. */
7856
- function walkSpecs(dir) {
7857
- const out = [];
7858
- if (!fs.existsSync(dir)) return out;
7859
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
7860
- const p = path.join(dir, entry.name);
7861
- if (entry.isDirectory()) out.push(...walkSpecs(p));
7862
- else if (entry.name === "spec.md") out.push(p);
7863
- }
7864
- return out.sort();
7888
+ /**
7889
+ * Every file under a directory on disk whose name `keep` accepts, depth first in the order the directory lists them;
7890
+ * a symbolic link is never followed. Throws when the directory does not exist.
7891
+ */
7892
+ function walkFiles(dir, keep) {
7893
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
7894
+ const full = path.join(dir, entry.name);
7895
+ return entry.isDirectory() ? walkFiles(full, keep) : keep(entry.name) ? [full] : [];
7896
+ });
7865
7897
  }
7866
7898
  /**
7867
7899
  * The corpus as the working tree holds it.
7868
7900
  * @param root absolute repository root
7869
7901
  */
7870
7902
  function loadCorpus(root, { name = path.basename(root), specsDir = DEFAULT_SPECS_DIR } = {}) {
7903
+ const abs = path.join(root, specsDir);
7871
7904
  return {
7872
7905
  name,
7873
7906
  path: root,
7874
7907
  specsDir,
7875
- capabilities: walkSpecs(path.join(root, specsDir)).map((p) => {
7908
+ capabilities: walkSpecs(abs).map((p) => {
7876
7909
  const file = path.relative(root, p).split(path.sep).join("/");
7877
7910
  return parseSpec(fs.readFileSync(p, "utf8"), file, capabilityOf$2(specsDir, file));
7878
7911
  })
@@ -7889,7 +7922,7 @@ function loadCorpusAt(root, ref, { name = path.basename(root), specsDir = DEFAUL
7889
7922
  capabilities: files.map((file) => parseSpec(texts.get(file) ?? "", file, capabilityOf$2(specsDir, file)))
7890
7923
  };
7891
7924
  }
7892
- var DEFAULT_SPECS_DIR, DEFAULT_MARKERS, ADVISORY, KNOWN_GAP, RETIRED, MARKER, INLINE_MARKER, STEP, LABELS, QUOTES, capabilityOf$2, allRequirements, gapExempts;
7925
+ var DEFAULT_SPECS_DIR, DEFAULT_MARKERS, ADVISORY, KNOWN_GAP, RETIRED, MARKER, INLINE_MARKER, STEP, LABELS, QUOTES, walkSpecs, capabilityOf$2, allRequirements, gapExempts;
7893
7926
  var init_corpus = __esmMin((() => {
7894
7927
  init_git();
7895
7928
  init_util();
@@ -7914,6 +7947,7 @@ var init_corpus = __esmMin((() => {
7914
7947
  `_…_`,
7915
7948
  `*…*`
7916
7949
  ];
7950
+ walkSpecs = (dir) => fs.existsSync(dir) ? walkFiles(dir, (name) => name === "spec.md").sort() : [];
7917
7951
  capabilityOf$2 = (specsDir, file) => path.relative(specsDir, path.dirname(file)).split(path.sep).join("/");
7918
7952
  allRequirements = (corpus) => corpus.capabilities.flatMap((c) => c.requirements);
7919
7953
  gapExempts = (r, s) => r.gaps.some((g) => g.exempts.includes(s.slug));
@@ -8506,24 +8540,17 @@ var init_coverage = __esmMin((() => {
8506
8540
  //#endregion
8507
8541
  //#region spec-tools/src/steward/lib/evidence.ts
8508
8542
  /**
8509
- * Evidence for an audit, assembled mechanically so a reader judges instead of searching. For every requirement: the
8510
- * tests bound to it and its scenarios, and where its own terms occur in the sources with comments stripped. Code
8511
- * citations are optional pointers, listed when present and never evidence. Every excerpt keeps its file's own line
8512
- * numbers, as one JSON model (`evidence --json`) — what spec-tools assembles each audit's evidence files from.
8543
+ * The non-test source files of a repository, read once, comments blanked for searching.
8544
+ * @param read shared with the citation scan (`fileReader`), so a source is read once between them
8513
8545
  */
8514
- /** The non-test source files of a repository, read once, comments blanked for searching. */
8515
- function sourceIndex(root) {
8546
+ function sourceIndex(root, read = fileReader(root)) {
8516
8547
  return (listFiles(root) ?? []).filter(isSource).flatMap((file) => {
8517
- try {
8518
- const raw = fs.readFileSync(path.join(root, file), "utf8");
8519
- return raw.length < 4e5 && !raw.includes("\0") ? [{
8520
- file,
8521
- text: stripComments(file, raw),
8522
- lines: raw.split("\n")
8523
- }] : [];
8524
- } catch {
8525
- return [];
8526
- }
8548
+ const raw = read(file)?.toString("utf8");
8549
+ return raw !== void 0 && raw.length < 4e5 && !raw.includes("\0") ? [{
8550
+ file,
8551
+ text: stripComments(file, raw),
8552
+ lines: raw.split("\n")
8553
+ }] : [];
8527
8554
  });
8528
8555
  }
8529
8556
  /** Every line of a source the term occurs on, comments stripped. */
@@ -8531,6 +8558,7 @@ function termHits(term, sources) {
8531
8558
  const re = termPattern(term);
8532
8559
  const hits = [];
8533
8560
  for (const s of sources) {
8561
+ if (!s.text.includes(term)) continue;
8534
8562
  let line = 1;
8535
8563
  let from = 0;
8536
8564
  let last = -1;
@@ -8549,15 +8577,16 @@ function termHits(term, sources) {
8549
8577
  return hits;
8550
8578
  }
8551
8579
  /** Requirements sharing terms or wording with `r`, strongest first. */
8552
- function relatedOf(r, everywhere, corpus) {
8553
- const mine = new Set(searchTerms(r));
8554
- const myWords = words$1(r.statement);
8580
+ function relatedOf(r, everywhere, corpus, vocabulary) {
8581
+ const own = vocabulary(r);
8582
+ const mine = new Set(own.terms);
8555
8583
  return everywhere.filter((x) => x.requirement.id !== r.id || x.corpus.name !== corpus.name).map((x) => {
8556
- const shared = searchTerms(x.requirement).filter((t) => mine.has(t));
8584
+ const other = vocabulary(x.requirement);
8585
+ const shared = other.terms.filter((t) => mine.has(t));
8557
8586
  return {
8558
8587
  x,
8559
8588
  shared,
8560
- score: shared.length + jaccard(myWords, words$1(x.requirement.statement)) * 3
8589
+ score: shared.length + jaccard(own.words, other.words) * 3
8561
8590
  };
8562
8591
  }).filter((y) => y.shared.length || y.score >= 1.2).sort((a, b) => b.score - a.score).slice(0, 5);
8563
8592
  }
@@ -8572,6 +8601,11 @@ function evidenceModel(corpus, citations, sources) {
8572
8601
  corpus,
8573
8602
  requirement
8574
8603
  }));
8604
+ const vocabularies = new Map(everywhere.map(({ requirement: r }) => [r, {
8605
+ terms: searchTerms(r),
8606
+ words: words$1(r.statement)
8607
+ }]));
8608
+ const vocabulary = (r) => vocabularies.get(r);
8575
8609
  const hitsByTerm = /* @__PURE__ */ new Map();
8576
8610
  const hitsOf = (term) => {
8577
8611
  if (!hitsByTerm.has(term)) hitsByTerm.set(term, termHits(term, sources));
@@ -8619,11 +8653,11 @@ function evidenceModel(corpus, citations, sources) {
8619
8653
  kind: c.kind === "doc" ? "doc" : "code",
8620
8654
  window: c.window
8621
8655
  })),
8622
- terms: searchTerms(r).map((term) => ({
8656
+ terms: vocabulary(r).terms.map((term) => ({
8623
8657
  term,
8624
8658
  hits: hitsOf(term)
8625
8659
  })),
8626
- related: relatedOf(r, everywhere, corpus).map(({ x, shared }) => ({
8660
+ related: relatedOf(r, everywhere, corpus, vocabulary).map(({ x, shared }) => ({
8627
8661
  id: x.requirement.id,
8628
8662
  shared
8629
8663
  }))
@@ -8763,14 +8797,13 @@ function stateOf(decision) {
8763
8797
  }
8764
8798
  /** The review file's text as items, or the YAML errors that stop it from being read. */
8765
8799
  function readReview(text) {
8766
- const doc = (0, import_dist.parseDocument)(text, { uniqueKeys: true });
8767
- if (doc.errors.length) return {
8800
+ const { value, errors } = readEdited(text);
8801
+ if (errors.length) return {
8768
8802
  items: [],
8769
- errors: doc.errors.map((e) => `line ${e.linePos?.[0]?.line ?? "?"}: not valid YAML: ${e.message.split("\n")[0]}`)
8803
+ errors
8770
8804
  };
8771
- const data = doc.toJS() ?? {};
8772
8805
  return {
8773
- items: Object.entries(data).map(([id, entry]) => {
8806
+ items: Object.entries(value ?? {}).map(([id, entry]) => {
8774
8807
  const applied = entry?.applied === void 0 ? [] : [entry.applied].flat().map(String);
8775
8808
  return {
8776
8809
  id,
@@ -8867,7 +8900,7 @@ function reviewCli(argv, roots) {
8867
8900
  const [sub, ...rest] = argv;
8868
8901
  const opts = parseArgs(rest, ["root"]);
8869
8902
  const file = opts._[0];
8870
- const load = (f) => (0, import_dist.parseDocument)(fs.readFileSync(f, "utf8")).toJS();
8903
+ const load = (f) => readLoose(f);
8871
8904
  if (sub === "render") {
8872
8905
  const data = load(file);
8873
8906
  const existing = opts.out && opts.append && fs.existsSync(opts.out) ? fs.readFileSync(opts.out, "utf8") : "";
@@ -8912,9 +8945,8 @@ function reviewCli(argv, roots) {
8912
8945
  process.stderr.write("usage: spec-tools steward review render|status|verify|lint <file>\n");
8913
8946
  return 2;
8914
8947
  }
8915
- var import_dist, RESPONSE_STATES, location, confidenceOf, optional, parseLocation, rulesOf;
8948
+ var RESPONSE_STATES, location, confidenceOf, optional, parseLocation, rulesOf;
8916
8949
  var init_review = __esmMin((() => {
8917
- import_dist = require_dist();
8918
8950
  init_data();
8919
8951
  init_util();
8920
8952
  RESPONSE_STATES = [
@@ -9456,7 +9488,11 @@ function oneRoot(roots, cmd) {
9456
9488
  /** The audits' evidence model of one root. */
9457
9489
  function evidenceAt(root, opts = {}) {
9458
9490
  assertScannable(root);
9459
- return evidenceModel(loadCorpus(root.path, root), scanCitations(root.path, anchorsOf, { binds: bindsOf(opts, root.path) }), sourceIndex(root.path));
9491
+ const read = fileReader(root.path, isSource);
9492
+ return evidenceModel(loadCorpus(root.path, root), scanCitations(root.path, anchorsOf, {
9493
+ binds: bindsOf(opts, root.path),
9494
+ read
9495
+ }), sourceIndex(root.path, read));
9460
9496
  }
9461
9497
  async function main$6(argv, cwd) {
9462
9498
  const [cmd, ...rest] = argv;
@@ -9464,7 +9500,7 @@ async function main$6(argv, cwd) {
9464
9500
  "root",
9465
9501
  "lens",
9466
9502
  "binds"
9467
- ], BOOLEANS);
9503
+ ], BOOLEANS$1);
9468
9504
  validateFlags(cmd, opts);
9469
9505
  const roots = rootsOf(opts, cwd);
9470
9506
  if (cmd === "check") {
@@ -9544,7 +9580,7 @@ async function run$1(argv, cwd = process.cwd()) {
9544
9580
  return 2;
9545
9581
  }
9546
9582
  }
9547
- var anchorsOf, FLAGS, COMMON, BOOLEANS, UsageError, bindsOf, ORDER;
9583
+ var anchorsOf, FLAGS, COMMON, BOOLEANS$1, UsageError, bindsOf, ORDER;
9548
9584
  var init_steward = __esmMin((() => {
9549
9585
  init_data();
9550
9586
  init_files();
@@ -9572,7 +9608,7 @@ var init_steward = __esmMin((() => {
9572
9608
  evidence: ["json", "binds"]
9573
9609
  };
9574
9610
  COMMON = ["root", "specs"];
9575
- BOOLEANS = [
9611
+ BOOLEANS$1 = [
9576
9612
  "fix",
9577
9613
  "strict",
9578
9614
  "json",
@@ -9609,7 +9645,7 @@ var ci_exports = /* @__PURE__ */ __exportAll({
9609
9645
  * none in any other pipeline — a default-branch push or the nightly has no branch of its own; locally, the merge base
9610
9646
  * with the default branch.
9611
9647
  */
9612
- function gateBase(env = process.env, rootDir = root()) {
9648
+ function gateBase(env = process.env, rootDir = repoRoot()) {
9613
9649
  const base = resolveBase(rootDir, "auto", env);
9614
9650
  if ("error" in base) throw new Error(base.error);
9615
9651
  return base.ref;
@@ -9621,7 +9657,7 @@ function gateBase(env = process.env, rootDir = root()) {
9621
9657
  */
9622
9658
  function diffBase(env = process.env) {
9623
9659
  if (env.CI_MERGE_REQUEST_DIFF_BASE_SHA) return env.CI_MERGE_REQUEST_DIFF_BASE_SHA;
9624
- if (env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME) return git$1([
9660
+ if (env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME) return gitOrThrow(repoRoot(), [
9625
9661
  "merge-base",
9626
9662
  `origin/${env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,
9627
9663
  "HEAD"
@@ -9656,7 +9692,6 @@ function shard(env = process.env) {
9656
9692
  var isNightly, jobLog;
9657
9693
  var init_ci = __esmMin((() => {
9658
9694
  init_files();
9659
- init_repo();
9660
9695
  init_git();
9661
9696
  isNightly = (env = process.env) => env.SPEC_AUDIT_NIGHTLY === "true";
9662
9697
  jobLog = (env = process.env) => jobLogFile(env.CI_JOB_NAME ?? "local");
@@ -9691,12 +9726,8 @@ var changeGates_exports = /* @__PURE__ */ __exportAll({
9691
9726
  });
9692
9727
  /** Every capability specification in the working tree, with its requirement and scenario headings. */
9693
9728
  function capabilitySpecs() {
9694
- const base = path$1.join(root(), "openspec/specs");
9695
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
9696
- const full = path$1.join(dir, entry.name);
9697
- return entry.isDirectory() ? walk(full) : entry.name === "spec.md" ? [full] : [];
9698
- });
9699
- return walk(base).map((file) => {
9729
+ const base = path$1.join(repoRoot(), "openspec/specs");
9730
+ return walkFiles(base, isSpec).map((file) => {
9700
9731
  const lines = fs$1.readFileSync(file, "utf8").split("\n");
9701
9732
  const headingsAt = (depth, kind) => lines.flatMap((line, i) => {
9702
9733
  const m = new RegExp(`^#{${depth}} (${kind}: .+)$`).exec(line);
@@ -9711,7 +9742,7 @@ function capabilitySpecs() {
9711
9742
  const scenarios = headingsAt(4, "Scenario");
9712
9743
  return {
9713
9744
  capability: path$1.relative(base, path$1.dirname(file)),
9714
- file: path$1.relative(root(), file),
9745
+ file: path$1.relative(repoRoot(), file),
9715
9746
  requirements,
9716
9747
  scenarios
9717
9748
  };
@@ -9743,35 +9774,37 @@ function requirementBlocks(file, text) {
9743
9774
  * The specification files git sees renamed between a ref and the working tree, base path to head path. A capability
9744
9775
  * that moved is the same capability under a new path, so every comparison against a base reads it there.
9745
9776
  */
9746
- function specMovesSince(ref, rootDir = root()) {
9777
+ function specMovesSince(ref, rootDir = repoRoot()) {
9747
9778
  const moves = /* @__PURE__ */ new Map();
9748
- for (const line of git$1([
9779
+ for (const line of gitOrThrow(rootDir, [
9749
9780
  "diff",
9750
9781
  "-M",
9751
9782
  "--name-status",
9752
9783
  ref,
9753
9784
  "--",
9754
9785
  "openspec/specs"
9755
- ], rootDir).split("\n")) {
9786
+ ]).split("\n")) {
9756
9787
  const [kind, from, to] = line.split(" ");
9757
9788
  if (kind?.startsWith("R") && from?.endsWith("/spec.md") && to) moves.set(from, to);
9758
9789
  }
9759
9790
  return moves;
9760
9791
  }
9761
- /** The specification files at a git ref, each with its text there, addressed by its path in the working tree. */
9762
- function specsAt(ref, rootDir = root()) {
9792
+ /**
9793
+ * The specification files at a git ref, each with its text there, addressed by its path in the working tree; read in
9794
+ * one git process.
9795
+ */
9796
+ function specsAt(ref, rootDir = repoRoot()) {
9763
9797
  const moves = specMovesSince(ref, rootDir);
9764
- return git$1([
9765
- "ls-tree",
9766
- "-r",
9767
- "--name-only",
9768
- ref,
9769
- "--",
9770
- "openspec/specs"
9771
- ], rootDir).split("\n").filter((file) => file.endsWith("/spec.md")).map((file) => ({
9772
- file: moves.get(file) ?? file,
9773
- text: git$1(["show", `${ref}:${file}`], rootDir)
9774
- }));
9798
+ const files = filesAt(rootDir, ref, "openspec/specs").filter((file) => file.endsWith("/spec.md"));
9799
+ const texts = showMany(rootDir, ref, files);
9800
+ return files.map((file) => {
9801
+ const text = texts.get(file);
9802
+ if (typeof text !== "string") throw new Error(`${ref}:${file} could not be read`);
9803
+ return {
9804
+ file: moves.get(file) ?? file,
9805
+ text
9806
+ };
9807
+ });
9775
9808
  }
9776
9809
  /** Every requirement in the specifications as they stand at a git ref — the base `spec-diff` renders against. */
9777
9810
  function requirementsAt(ref) {
@@ -9782,7 +9815,7 @@ function requirementsAt(ref) {
9782
9815
  * track an empty directory, so a change folder emptied on disk is invisible to every gate built on `git diff` —
9783
9816
  * which is how two of them survived unnoticed for five days.
9784
9817
  */
9785
- function malformedArchivedChanges(rootDir = root()) {
9818
+ function malformedArchivedChanges(rootDir = repoRoot()) {
9786
9819
  const base = path$1.join(rootDir, "openspec/changes/archive");
9787
9820
  if (!fs$1.existsSync(base)) return [];
9788
9821
  return fs$1.readdirSync(base, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
@@ -9790,13 +9823,7 @@ function malformedArchivedChanges(rootDir = root()) {
9790
9823
  const missing = [".openspec.yaml", "proposal.md"].filter((file) => !fs$1.existsSync(path$1.join(dir, file)));
9791
9824
  if (missing.length) return [`${entry.name} — missing ${missing.join(" and ")}`];
9792
9825
  const specs = path$1.join(dir, "specs");
9793
- if (fs$1.existsSync(specs)) {
9794
- const walk = (current) => fs$1.readdirSync(current, { withFileTypes: true }).flatMap((child) => {
9795
- const full = path$1.join(current, child.name);
9796
- return child.isDirectory() ? walk(full) : child.name.endsWith(".md") ? [full] : [];
9797
- });
9798
- if (walk(specs).length === 0) return [`${entry.name} — carries a specs/ tree with no delta file`];
9799
- }
9826
+ if (fs$1.existsSync(specs) && walkFiles(specs, isMarkdown).length === 0) return [`${entry.name} — carries a specs/ tree with no delta file`];
9800
9827
  return [];
9801
9828
  });
9802
9829
  }
@@ -9807,13 +9834,9 @@ function malformedArchivedChanges(rootDir = root()) {
9807
9834
  * legitimate on a branch (sync, push, watch CI go green) and unfinished on a merge request, which is why
9808
9835
  * `workflowEvidence` — the merge-request gate — reads it and the change gates do not.
9809
9836
  */
9810
- function syncedUnarchivedChanges(rootDir = root()) {
9837
+ function syncedUnarchivedChanges(rootDir = repoRoot()) {
9811
9838
  const changes = path$1.join(rootDir, "openspec/changes");
9812
9839
  if (!fs$1.existsSync(changes)) return [];
9813
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
9814
- const full = path$1.join(dir, entry.name);
9815
- return entry.isDirectory() ? walk(full) : entry.name === "spec.md" ? [full] : [];
9816
- });
9817
9840
  const section = (text, op) => {
9818
9841
  const start = text.indexOf(`## ${op} Requirements`);
9819
9842
  if (start < 0) return "";
@@ -9833,7 +9856,7 @@ function syncedUnarchivedChanges(rootDir = root()) {
9833
9856
  return fs$1.readdirSync(changes, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "archive").flatMap((entry) => {
9834
9857
  const specs = path$1.join(changes, entry.name, "specs");
9835
9858
  if (!fs$1.existsSync(specs)) return [];
9836
- return walk(specs).flatMap((delta) => {
9859
+ return walkFiles(specs, isSpec).flatMap((delta) => {
9837
9860
  const capability = path$1.relative(specs, path$1.dirname(delta));
9838
9861
  const main = path$1.join(rootDir, "openspec/specs", capability, "spec.md");
9839
9862
  if (!fs$1.existsSync(main)) return [];
@@ -9849,7 +9872,7 @@ function syncedUnarchivedChanges(rootDir = root()) {
9849
9872
  });
9850
9873
  }
9851
9874
  /** Every open change — a directory under `openspec/changes/` other than the archive. */
9852
- function openChanges(rootDir = root()) {
9875
+ function openChanges(rootDir = repoRoot()) {
9853
9876
  const changes = path$1.join(rootDir, "openspec/changes");
9854
9877
  if (!fs$1.existsSync(changes)) return [];
9855
9878
  return fs$1.readdirSync(changes, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "archive").map((entry) => entry.name).sort();
@@ -9860,16 +9883,12 @@ function openChanges(rootDir = root()) {
9860
9883
  * the longer they sit. Read from the filesystem so an unstaged delta counts too; a parked proposal is `skip_specs`
9861
9884
  * and carries none.
9862
9885
  */
9863
- function deltaFilesInOpenChanges(rootDir = root()) {
9886
+ function deltaFilesInOpenChanges(rootDir = repoRoot()) {
9864
9887
  const changes = path$1.join(rootDir, "openspec/changes");
9865
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
9866
- const full = path$1.join(dir, entry.name);
9867
- return entry.isDirectory() ? walk(full) : entry.name.endsWith(".md") ? [full] : [];
9868
- });
9869
9888
  return openChanges(rootDir).flatMap((change) => {
9870
9889
  const specs = path$1.join(changes, change, "specs");
9871
9890
  if (!fs$1.existsSync(specs)) return [];
9872
- const deltas = walk(specs).map((f) => path$1.relative(path$1.join(changes, change), f));
9891
+ const deltas = walkFiles(specs, isMarkdown).map((f) => path$1.relative(path$1.join(changes, change), f));
9873
9892
  return deltas.length ? [`${change} — carries ${deltas.length} delta file(s): ${deltas.join(", ")}`] : [];
9874
9893
  });
9875
9894
  }
@@ -9877,20 +9896,20 @@ function deltaFilesInOpenChanges(rootDir = root()) {
9877
9896
  * The open changes this tree touches against a base — files changed or untracked under their directories. On the
9878
9897
  * default branch itself nothing is touched, which keeps a stale change failing its own pipeline and no one else's.
9879
9898
  */
9880
- function touchedOpenChanges(base, rootDir = root()) {
9881
- const files = [...git$1([
9899
+ function touchedOpenChanges(base, rootDir = repoRoot()) {
9900
+ const files = [...gitOrThrow(rootDir, [
9882
9901
  "diff",
9883
9902
  "--name-only",
9884
9903
  base,
9885
9904
  "--",
9886
9905
  "openspec/changes"
9887
- ], rootDir).split("\n"), ...git$1([
9906
+ ]).split("\n"), ...gitOrThrow(rootDir, [
9888
9907
  "ls-files",
9889
9908
  "--others",
9890
9909
  "--exclude-standard",
9891
9910
  "--",
9892
9911
  "openspec/changes"
9893
- ], rootDir).split("\n")];
9912
+ ]).split("\n")];
9894
9913
  const names = /* @__PURE__ */ new Set();
9895
9914
  for (const file of files) {
9896
9915
  const m = /^openspec\/changes\/([^/]+)\//.exec(file);
@@ -9904,16 +9923,12 @@ function touchedOpenChanges(base, rootDir = root()) {
9904
9923
  * renamed or removed, and OpenSpec's own validation lets it through. Judged over the changes named only: a synced
9905
9924
  * change's REMOVED and RENAMED headings are legitimately gone, so callers leave synced changes out.
9906
9925
  */
9907
- function staleDeltaTargets(changes, rootDir = root()) {
9908
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
9909
- const full = path$1.join(dir, entry.name);
9910
- return entry.isDirectory() ? walk(full) : entry.name === "spec.md" ? [full] : [];
9911
- });
9926
+ function staleDeltaTargets(changes, rootDir = repoRoot()) {
9912
9927
  const hits = [];
9913
9928
  for (const change of changes) {
9914
9929
  const specs = path$1.join(rootDir, "openspec/changes", change, "specs");
9915
9930
  if (!fs$1.existsSync(specs)) continue;
9916
- for (const delta of walk(specs)) {
9931
+ for (const delta of walkFiles(specs, isSpec)) {
9917
9932
  const capability = path$1.relative(specs, path$1.dirname(delta));
9918
9933
  const standing = path$1.join(rootDir, "openspec/specs", capability, "spec.md");
9919
9934
  const headings = new Set(fs$1.existsSync(standing) ? [...fs$1.readFileSync(standing, "utf8").matchAll(/^### Requirement: (.+)$/gm)].map((m) => m[1].trim()) : []);
@@ -9940,19 +9955,15 @@ function staleDeltaTargets(changes, rootDir = root()) {
9940
9955
  * delta counts too. It guards after sync as much as at archive: a change that carries deltas never sets `skip_specs`,
9941
9956
  * whatever state its workflow is in.
9942
9957
  */
9943
- function skipSpecsWithDeltas(rootDir = root()) {
9958
+ function skipSpecsWithDeltas(rootDir = repoRoot()) {
9944
9959
  const changes = path$1.join(rootDir, "openspec/changes");
9945
9960
  if (!fs$1.existsSync(changes)) return [];
9946
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
9947
- const full = path$1.join(dir, entry.name);
9948
- return entry.isDirectory() ? walk(full) : entry.name.endsWith(".md") ? [full] : [];
9949
- });
9950
9961
  const dirs = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory());
9951
9962
  return dirs(changes).flatMap((e) => e.name === "archive" ? dirs(path$1.join(changes, "archive")).map((a) => path$1.join(changes, "archive", a.name)) : [path$1.join(changes, e.name)]).flatMap((dir) => {
9952
9963
  const cfg = path$1.join(dir, ".openspec.yaml");
9953
9964
  if (!fs$1.existsSync(cfg) || !/^\s*skip_specs:\s*true/m.test(fs$1.readFileSync(cfg, "utf8"))) return [];
9954
9965
  const specs = path$1.join(dir, "specs");
9955
- if (!fs$1.existsSync(specs) || walk(specs).length === 0) return [];
9966
+ if (!fs$1.existsSync(specs) || walkFiles(specs, isMarkdown).length === 0) return [];
9956
9967
  return [`${path$1.relative(changes, dir)} sets skip_specs: true but carries delta files — archive would discard them`];
9957
9968
  });
9958
9969
  }
@@ -10001,11 +10012,14 @@ function main$5(env = process.env) {
10001
10012
  console.log(`\n${failed === 0 ? "PASS" : "FAIL"} — ${gates.length - failed}/${gates.length} change gates hold`);
10002
10013
  return failed === 0 ? 0 : 1;
10003
10014
  }
10004
- var normalizeBlock;
10015
+ var isSpec, isMarkdown, normalizeBlock;
10005
10016
  var init_changeGates = __esmMin((() => {
10006
10017
  init_ci();
10007
- init_repo();
10018
+ init_corpus();
10019
+ init_git();
10008
10020
  init_util();
10021
+ isSpec = (name) => name === "spec.md";
10022
+ isMarkdown = (name) => name.endsWith(".md");
10009
10023
  normalizeBlock = (text) => text.replace(/\s+/g, " ").trim();
10010
10024
  }));
10011
10025
  //#endregion
@@ -10169,14 +10183,14 @@ function render$1(diff, base, moved = []) {
10169
10183
  }
10170
10184
  /** The working tree's requirement blocks, cut by the same rule as the base's. */
10171
10185
  function requirementsInTree() {
10172
- return capabilitySpecs().flatMap((spec) => requirementBlocks(spec.file, fs$1.readFileSync(path$1.join(root(), spec.file), "utf8")));
10186
+ return capabilitySpecs().flatMap((spec) => requirementBlocks(spec.file, fs$1.readFileSync(path$1.join(repoRoot(), spec.file), "utf8")));
10173
10187
  }
10174
10188
  /** `argv` is what follows the command — `[base]` — never the process's own arguments, which start with it. */
10175
10189
  function main$4(argv = [], env = process.env) {
10176
10190
  const base = argv[0] ?? diffBase(env);
10177
10191
  const text = render$1(classify(requirementsAt(base), requirementsInTree()), base, capabilityMoves(specMovesSince(base)));
10178
- fs$1.mkdirSync(path$1.dirname(path$1.join(root(), DIFF_FILE)), { recursive: true });
10179
- fs$1.writeFileSync(path$1.join(root(), DIFF_FILE), text);
10192
+ fs$1.mkdirSync(path$1.dirname(path$1.join(repoRoot(), DIFF_FILE)), { recursive: true });
10193
+ fs$1.writeFileSync(path$1.join(repoRoot(), DIFF_FILE), text);
10180
10194
  return text;
10181
10195
  }
10182
10196
  var id, body, capabilityOf$1, capabilityMoves, fence, where;
@@ -10184,7 +10198,7 @@ var init_specDiff = __esmMin((() => {
10184
10198
  init_changeGates();
10185
10199
  init_ci();
10186
10200
  init_files();
10187
- init_repo();
10201
+ init_git();
10188
10202
  id = (r) => `${r.file}#${r.slug}`;
10189
10203
  body = (r) => normalizeBlock(r.block.split("\n").slice(1).join("\n"));
10190
10204
  capabilityOf$1 = (file) => path$1.dirname(file).replace(/^openspec\/specs\//, "");
@@ -10225,12 +10239,17 @@ var auditParts_exports = /* @__PURE__ */ __exportAll({
10225
10239
  writeEvidence: () => writeEvidence,
10226
10240
  writeParts: () => writeParts
10227
10241
  });
10228
- /** spec-steward's evidence model of the repository at `cwd`, written for the scope and the focused check. */
10242
+ /**
10243
+ * spec-steward's evidence model of the repository at `cwd`, written for the scope and the focused check; returned, so
10244
+ * the command that wrote it need not read it back.
10245
+ */
10229
10246
  function writeEvidence(cwd) {
10230
- writeData(path$1.join(cwd, EVIDENCE_FILE), evidenceAt(rootsOf({}, cwd)[0]));
10247
+ const model = evidenceAt(rootsOf({}, cwd)[0]);
10248
+ writeData(path$1.join(cwd, EVIDENCE_FILE), model);
10249
+ return model;
10231
10250
  }
10232
10251
  /** The evidence model at a path; a missing file is the operator's to fix — the scope never guesses its evidence. */
10233
- function loadEvidence(file = path$1.join(root(), EVIDENCE_FILE)) {
10252
+ function loadEvidence(file = path$1.join(repoRoot(), EVIDENCE_FILE)) {
10234
10253
  if (!fs$1.existsSync(file)) throw new Error(`${EVIDENCE_FILE} is missing — \`spec-tools scope\` writes it from spec-steward's evidence model`);
10235
10254
  const model = readData(file);
10236
10255
  if (model.version !== 1 || !Array.isArray(model.requirements)) throw new Error(`${EVIDENCE_FILE} is not spec-steward's evidence model, version 1`);
@@ -10280,7 +10299,7 @@ function sourceReader() {
10280
10299
  const cache = /* @__PURE__ */ new Map();
10281
10300
  return (file) => {
10282
10301
  if (!cache.has(file)) try {
10283
- cache.set(file, fs$1.readFileSync(path$1.join(root(), file), "utf8").split("\n"));
10302
+ cache.set(file, fs$1.readFileSync(path$1.join(repoRoot(), file), "utf8").split("\n"));
10284
10303
  } catch {
10285
10304
  cache.set(file, void 0);
10286
10305
  }
@@ -10374,16 +10393,21 @@ function outline(sf, lines, line) {
10374
10393
  cut: true
10375
10394
  };
10376
10395
  }
10377
- /**
10378
- * The code a citation at `line` annotates. In TypeScript a citation in a unit's own doc comment quotes
10379
- * that unit — the function, the class member, the one test — from its comment to its end; a citation
10380
- * inline in a body quotes the outermost enclosing unit that fits the budget. Anything else — a unit
10381
- * past the budget, or a file that is not TypeScript — is a window around the line. Every line carries
10382
- * its number.
10383
- */
10384
- function excerpt(file, code, line) {
10396
+ function parsed(file, code) {
10385
10397
  const lines = code.split("\n");
10386
- if (!/\.(ts|tsx|mts|cts)$/.test(file)) {
10398
+ if (!/\.(ts|tsx|mts|cts)$/.test(file)) return {
10399
+ file,
10400
+ lines
10401
+ };
10402
+ return {
10403
+ file,
10404
+ lines,
10405
+ sf: typescript().createSourceFile(file, code, typescript().ScriptTarget.Latest, true, file.endsWith("x") ? typescript().ScriptKind.TSX : typescript().ScriptKind.TS)
10406
+ };
10407
+ }
10408
+ /** `excerpt` over a file already parsed. */
10409
+ function excerptOf({ file, lines, sf }, line) {
10410
+ if (!sf) {
10387
10411
  if (lines.length <= 150) return {
10388
10412
  startLine: 1,
10389
10413
  text: numbered(lines, 1),
@@ -10391,7 +10415,6 @@ function excerpt(file, code, line) {
10391
10415
  };
10392
10416
  return window(lines, line);
10393
10417
  }
10394
- const sf = typescript().createSourceFile(file, code, typescript().ScriptTarget.Latest, true, file.endsWith("x") ? typescript().ScriptKind.TSX : typescript().ScriptKind.TS);
10395
10418
  const text = lines[line - 1] ?? "";
10396
10419
  const column = Math.max(0, text.indexOf("@link") === -1 ? text.search(/\S/) : text.indexOf("@link"));
10397
10420
  const pos = sf.getPositionOfLineAndCharacter(line - 1, column);
@@ -10426,12 +10449,20 @@ function excerpt(file, code, line) {
10426
10449
  };
10427
10450
  }
10428
10451
  function contextOf(all, read = sourceReader()) {
10452
+ const files = /* @__PURE__ */ new Map();
10453
+ const parsedAt = (file) => {
10454
+ if (!files.has(file)) {
10455
+ const lines = read(file);
10456
+ files.set(file, lines ? parsed(file, lines.join("\n")) : void 0);
10457
+ }
10458
+ return files.get(file);
10459
+ };
10429
10460
  const excerpts = /* @__PURE__ */ new Map();
10430
10461
  const excerptAt = (file, line) => {
10431
10462
  const key = `${file}:${line}`;
10432
10463
  if (!excerpts.has(key)) {
10433
- const lines = read(file);
10434
- excerpts.set(key, lines ? excerpt(file, lines.join("\n"), line) : void 0);
10464
+ const p = parsedAt(file);
10465
+ excerpts.set(key, p ? excerptOf(p, line) : void 0);
10435
10466
  }
10436
10467
  return excerpts.get(key);
10437
10468
  };
@@ -10616,20 +10647,20 @@ function renderChanged(touched, ctx, base = "HEAD", by = "") {
10616
10647
  */
10617
10648
  function writeParts(capabilities, all = requirementsOf(loadEvidence()), only) {
10618
10649
  const ctx = contextOf(all);
10619
- const dir = path$1.join(root(), PARTS_DIR);
10650
+ const dir = path$1.join(repoRoot(), PARTS_DIR);
10620
10651
  if (fs$1.existsSync(dir)) {
10621
10652
  for (const entry of fs$1.readdirSync(dir)) if (entry !== "findings") fs$1.rmSync(path$1.join(dir, entry), { recursive: true });
10622
10653
  }
10623
10654
  fs$1.mkdirSync(path$1.join(dir, "findings"), { recursive: true });
10624
10655
  const units = {};
10625
10656
  for (const r of all) if (capabilities.includes(r.capability) && (!only || only.has(idOf(r)))) units[idOf(r)] = r.advisory ? { advisory: true } : {};
10626
- writeData(path$1.join(root(), UNITS_FILE), units);
10657
+ writeData(path$1.join(repoRoot(), UNITS_FILE), units);
10627
10658
  return capabilities.flatMap((capability) => {
10628
10659
  const slices = renderCapability(capability, ctx, only);
10629
10660
  return slices.map(({ requirements, text }, k) => {
10630
10661
  const file = `${PARTS_DIR}/${capability}${slices.length > 1 ? `.${k + 1}` : ""}.yaml`;
10631
- fs$1.mkdirSync(path$1.dirname(path$1.join(root(), file)), { recursive: true });
10632
- fs$1.writeFileSync(path$1.join(root(), file), text);
10662
+ fs$1.mkdirSync(path$1.dirname(path$1.join(repoRoot(), file)), { recursive: true });
10663
+ fs$1.writeFileSync(path$1.join(repoRoot(), file), text);
10633
10664
  return {
10634
10665
  capability,
10635
10666
  file,
@@ -10640,11 +10671,11 @@ function writeParts(capabilities, all = requirementsOf(loadEvidence()), only) {
10640
10671
  });
10641
10672
  });
10642
10673
  }
10643
- var loaded, typescript, PART_BYTES, isMarker, idOf, isBoundary, isCallbackStatement, isUnit, lineOf, numbered, window, TEST_CALLS;
10674
+ var loaded, typescript, PART_BYTES, isMarker, idOf, isBoundary, isCallbackStatement, isUnit, lineOf, numbered, window, TEST_CALLS, excerpt;
10644
10675
  var init_auditParts = __esmMin((() => {
10645
10676
  init_data();
10646
10677
  init_files();
10647
- init_repo();
10678
+ init_git();
10648
10679
  init_steward();
10649
10680
  typescript = () => loaded ??= createRequire(import.meta.url)("typescript");
10650
10681
  PART_BYTES = 368640;
@@ -10669,6 +10700,7 @@ var init_auditParts = __esmMin((() => {
10669
10700
  "it",
10670
10701
  "test"
10671
10702
  ]);
10703
+ excerpt = (file, code, line) => excerptOf(parsed(file, code), line);
10672
10704
  }));
10673
10705
  //#endregion
10674
10706
  //#region spec-tools/src/auditChanged.ts
@@ -10839,7 +10871,8 @@ function grow(seed, all, edited, options) {
10839
10871
  function affectedScope(base, all = requirementsOf(loadEvidence()), options = affectedOptions()) {
10840
10872
  const set = /* @__PURE__ */ new Map();
10841
10873
  const add = (r) => set.set(idOf(r), r);
10842
- const specHunks = hunksOf(git$1([
10874
+ const root = repoRoot();
10875
+ const specHunks = hunksOf(gitOrThrow(root, [
10843
10876
  "diff",
10844
10877
  "-M",
10845
10878
  "--unified=0",
@@ -10852,18 +10885,14 @@ function affectedScope(base, all = requirementsOf(loadEvidence()), options = aff
10852
10885
  const edited = [...new Set(specHunks.map((h) => capabilityOf(h.file)))].filter((c) => !!c && known.has(c)).sort();
10853
10886
  const synced = new Set(syncedUnarchivedChanges().map((s) => s.split(" — ")[0]));
10854
10887
  for (const change of touchedOpenChanges(base).filter((c) => !synced.has(c))) {
10855
- const specs = path$1.join(root(), "openspec/changes", change, "specs");
10888
+ const specs = path$1.join(root, "openspec/changes", change, "specs");
10856
10889
  if (!fs$1.existsSync(specs)) continue;
10857
- const walk = (dir) => fs$1.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
10858
- const full = path$1.join(dir, entry.name);
10859
- return entry.isDirectory() ? walk(full) : entry.name === "spec.md" ? [full] : [];
10860
- });
10861
- for (const delta of walk(specs)) {
10890
+ for (const delta of walkFiles(specs, (name) => name === "spec.md")) {
10862
10891
  const capability = path$1.relative(specs, path$1.dirname(delta));
10863
10892
  for (const r of deltaRequirements(fs$1.readFileSync(delta, "utf8"), capability, all)) add(r);
10864
10893
  }
10865
10894
  }
10866
- const untracked = git$1([
10895
+ const untracked = gitOrThrow(root, [
10867
10896
  "ls-files",
10868
10897
  "--others",
10869
10898
  "--exclude-standard"
@@ -10873,11 +10902,12 @@ function affectedScope(base, all = requirementsOf(loadEvidence()), options = aff
10873
10902
  count: Number.MAX_SAFE_INTEGER,
10874
10903
  removed: []
10875
10904
  }));
10876
- for (const r of reachedBy([...hunksOf(git$1([
10905
+ const hunks = hunksOf(gitOrThrow(root, [
10877
10906
  "diff",
10878
10907
  "--unified=0",
10879
10908
  base
10880
- ])), ...untracked], all, options.context)) add(r);
10909
+ ]));
10910
+ for (const r of reachedBy([...hunks, ...untracked], all, options.context)) add(r);
10881
10911
  const requirements = grow([...set.values()], all, edited, options);
10882
10912
  return {
10883
10913
  base,
@@ -10887,13 +10917,14 @@ function affectedScope(base, all = requirementsOf(loadEvidence()), options = aff
10887
10917
  options
10888
10918
  };
10889
10919
  }
10890
- function main$3(env = process.env) {
10920
+ /** `spec-tools changed`; `model` is the evidence model the command just wrote, read from its file when not given. */
10921
+ function main$3(env = process.env, model) {
10891
10922
  const base = diffBase(env);
10892
- const all = requirementsOf(loadEvidence());
10923
+ const all = requirementsOf(model ?? loadEvidence());
10893
10924
  const scope = affectedScope(base, all, affectedOptions(env));
10894
10925
  const text = renderChanged(scope.requirements, contextOf(all), base, describeOptions(scope.options));
10895
- fs$1.mkdirSync(path$1.join(root(), PARTS_DIR), { recursive: true });
10896
- fs$1.writeFileSync(path$1.join(root(), CHANGED_FILE), text);
10926
+ fs$1.mkdirSync(path$1.join(repoRoot(), PARTS_DIR), { recursive: true });
10927
+ fs$1.writeFileSync(path$1.join(repoRoot(), CHANGED_FILE), text);
10897
10928
  const by = describeOptions(scope.options);
10898
10929
  return scope.requirements.length ? `${scope.requirements.length} requirement(s) in scope against ${base} (${by}) → ${CHANGED_FILE}:\n${scope.requirements.map((r) => `- ${idOf(r)}`).join("\n")}\n` : `Nothing in scope against ${base} (${by}); ${CHANGED_FILE} says so.\n`;
10899
10930
  }
@@ -10903,8 +10934,9 @@ var init_auditChanged = __esmMin((() => {
10903
10934
  init_changeGates();
10904
10935
  init_ci();
10905
10936
  init_files();
10906
- init_repo();
10937
+ init_corpus();
10907
10938
  init_evidence();
10939
+ init_git();
10908
10940
  init_scan();
10909
10941
  CHANGED_FILE = `${PARTS_DIR}/changed.yaml`;
10910
10942
  AFFECTED_UNITS = [
@@ -11050,16 +11082,13 @@ var stewardAudit_exports = /* @__PURE__ */ __exportAll({
11050
11082
  sweepUnits: () => sweepUnits
11051
11083
  });
11052
11084
  /** The skill's sweeps, each a unit numbered after the last capability part, its files resolved in this repository. */
11053
- function sweepUnits(model, after, cwd = root()) {
11085
+ function sweepUnits(model, after, cwd = repoRoot()) {
11054
11086
  const sweeps = JSON.parse(fs$1.readFileSync(path$1.join(SKILLS_DIR, "spec-steward/sweeps.json"), "utf8"));
11055
- const tracked = git$1([
11056
- "ls-files",
11057
- "-co",
11058
- "--exclude-standard"
11059
- ], cwd).split("\n").filter(Boolean);
11087
+ const tracked = listFiles(cwd);
11088
+ if (!tracked) throw new Error(`git cannot list the files of ${cwd}`);
11060
11089
  const fromEvidence = (kind) => [...new Set(model.requirements.flatMap((r) => r[kind].map((b) => b.file)))];
11061
11090
  return sweeps.map((sweep, i) => {
11062
- const patterns = (sweep.files ?? []).map((glob) => new RegExp(`^${globToRegExp(glob).source.replace(/^\^/, "")}`));
11091
+ const patterns = (sweep.files ?? []).map(globToRegExp);
11063
11092
  const files = sweep.from ? fromEvidence(sweep.from) : tracked.filter((file) => patterns.some((re) => re.test(file)));
11064
11093
  const part = after + i + 1;
11065
11094
  return {
@@ -11095,7 +11124,7 @@ function quoteAt(quote, lines, line) {
11095
11124
  * folded, theme candidates grouped, coverage checked against the judged lists. Writes the data and renders the review
11096
11125
  * file; returns the one-line summary.
11097
11126
  */
11098
- function merge(read, cwd = root()) {
11127
+ function merge(read, cwd = repoRoot()) {
11099
11128
  const scopePath = path$1.join(cwd, FILES.scope);
11100
11129
  const scope = fs$1.existsSync(scopePath) ? readData(scopePath) : void 0;
11101
11130
  if (!scope) throw new Error(`${FILES.scope} is missing — run spec-tools scope --audit spec-steward first`);
@@ -11217,9 +11246,9 @@ var FILES, PLACEMENT, LOAD_SKILL, TOOL_RULE$1, unitLine, brief$1, briefComplete$
11217
11246
  var init_stewardAudit = __esmMin((() => {
11218
11247
  init_data();
11219
11248
  init_files();
11220
- init_repo();
11221
11249
  init_rules();
11222
11250
  init_skillsDir();
11251
+ init_git();
11223
11252
  init_review();
11224
11253
  init_util();
11225
11254
  FILES = AUDIT_FILES["spec-steward"];
@@ -11387,9 +11416,9 @@ function renderScope(parts, kind = "all", detail) {
11387
11416
  * The scope of one audit. spec-verify's parts are capabilities; spec-steward's are the same parts plus its sweeps, each a
11388
11417
  * unit of its own after the last part.
11389
11418
  */
11390
- function main$2(env = process.env, audit = "spec-verify") {
11419
+ function main$2(env = process.env, audit = "spec-verify", evidence) {
11391
11420
  const kind = modeFor(env);
11392
- const model = loadEvidence();
11421
+ const model = evidence ?? loadEvidence();
11393
11422
  const all = requirementsOf(model);
11394
11423
  const affected = kind === "affected" ? affectedScope(diffBase(env), all, affectedOptions(env)) : void 0;
11395
11424
  const corpus = [...new Set(all.map((r) => r.capability))].sort();
@@ -11406,7 +11435,7 @@ function main$2(env = process.env, audit = "spec-verify") {
11406
11435
  readers: 1,
11407
11436
  parts
11408
11437
  };
11409
- writeData(path$1.join(root(), AUDIT_FILES[audit].scope), data);
11438
+ writeData(path$1.join(repoRoot(), AUDIT_FILES[audit].scope), data);
11410
11439
  return report;
11411
11440
  }
11412
11441
  var REQUIREMENT_BYTES, findingsFiles, load, kb;
@@ -11416,7 +11445,7 @@ var init_auditScope = __esmMin((() => {
11416
11445
  init_ci();
11417
11446
  init_data();
11418
11447
  init_files();
11419
- init_repo();
11448
+ init_git();
11420
11449
  init_stewardAudit();
11421
11450
  REQUIREMENT_BYTES = 2048;
11422
11451
  findingsFiles = (part, audit) => Array.from({ length: 1 }, (_, r) => findingsFile(part, r + 1, audit));
@@ -11424,6 +11453,109 @@ var init_auditScope = __esmMin((() => {
11424
11453
  kb = (bytes) => `${Math.max(1, Math.round(bytes / 1024))} KB`;
11425
11454
  }));
11426
11455
  //#endregion
11456
+ //#region spec-tools/src/claude.ts
11457
+ /**
11458
+ * One headless `claude --print` session, the engine under `spec-tools run` and the audit's workers: the command line,
11459
+ * the streamed events kept in a file, the last `result` event, and the exit code — 127 when `claude` cannot start. A
11460
+ * file the session must write is checked as soon as it stops, and its errors go back to the same session
11461
+ * (`correctUntilValid`).
11462
+ */
11463
+ /** One headless session: its exit code, whether its budget killed it, and its last `result` event. */
11464
+ async function claudeSession(o) {
11465
+ fs$1.mkdirSync(path$1.dirname(o.stream), { recursive: true });
11466
+ const stream = fs$1.createWriteStream(o.stream, { flags: o.append ? "a" : "w" });
11467
+ const errFd = o.stderr === void 0 ? void 0 : fs$1.openSync(o.stderr, "w");
11468
+ const child = spawn("claude", claudeArgs(o), {
11469
+ cwd: o.cwd,
11470
+ env: o.env,
11471
+ stdio: [
11472
+ "ignore",
11473
+ "pipe",
11474
+ errFd ?? "inherit"
11475
+ ]
11476
+ });
11477
+ let result;
11478
+ let pending = "";
11479
+ const parse = (line) => {
11480
+ let event;
11481
+ try {
11482
+ event = JSON.parse(line);
11483
+ } catch {
11484
+ return;
11485
+ }
11486
+ if (typeof event !== "object" || event === null) return;
11487
+ if (event.type === "result") result = event;
11488
+ o.onEvent?.(event);
11489
+ };
11490
+ child.stdout?.on("data", (chunk) => {
11491
+ stream.write(chunk);
11492
+ const lines = (pending + chunk.toString("utf8")).split("\n");
11493
+ pending = lines.pop() ?? "";
11494
+ for (const line of lines) parse(line);
11495
+ });
11496
+ let killed = false;
11497
+ const timer = o.budget === void 0 ? void 0 : setTimeout(() => {
11498
+ killed = true;
11499
+ child.kill("SIGTERM");
11500
+ }, o.budget);
11501
+ const code = await new Promise((resolve) => {
11502
+ child.on("error", () => resolve(127));
11503
+ child.on("close", (c) => resolve(c ?? 1));
11504
+ });
11505
+ clearTimeout(timer);
11506
+ if (pending) parse(pending);
11507
+ await new Promise((resolve) => stream.end(resolve));
11508
+ if (errFd !== void 0) fs$1.closeSync(errFd);
11509
+ return {
11510
+ code,
11511
+ killed,
11512
+ result
11513
+ };
11514
+ }
11515
+ /**
11516
+ * The file a session wrote, checked; while it fails and the last session can take a correction, its errors go back to
11517
+ * that session, at most `CORRECTIONS` times. Returns the last session's outcome, the errors that remain and how many
11518
+ * corrections it took.
11519
+ *
11520
+ * @param resumable the session id of a run that finished and can be sent a correction, or undefined
11521
+ * @param correct sends correction `n` to `session`
11522
+ */
11523
+ async function correctUntilValid(first, check, resumable, correct) {
11524
+ let ran = first;
11525
+ let errors = check();
11526
+ let corrections = 0;
11527
+ let session = resumable(ran);
11528
+ while (errors.length && session && corrections < 2) {
11529
+ corrections++;
11530
+ ran = await correct(errors, corrections, session);
11531
+ errors = check();
11532
+ session = resumable(ran);
11533
+ }
11534
+ return {
11535
+ ran,
11536
+ errors,
11537
+ corrections
11538
+ };
11539
+ }
11540
+ var claudeArgs;
11541
+ var init_claude = __esmMin((() => {
11542
+ claudeArgs = ({ prompt, model, effort, tools, resume, flags = [] }) => [
11543
+ ...resume ? ["--resume", resume] : [],
11544
+ "--print",
11545
+ prompt,
11546
+ "--model",
11547
+ model,
11548
+ "--effort",
11549
+ effort,
11550
+ ...flags,
11551
+ "--output-format",
11552
+ "stream-json",
11553
+ "--verbose",
11554
+ "--allowedTools",
11555
+ tools
11556
+ ];
11557
+ }));
11558
+ //#endregion
11427
11559
  //#region spec-tools/src/severity.ts
11428
11560
  /** The thresholds from the variables, validated; an unset or empty one takes its default. */
11429
11561
  function thresholds(env = process.env) {
@@ -11553,22 +11685,27 @@ function cgroupBytes(files) {
11553
11685
  /** The tree as git sees it beyond HEAD: every changed or untracked file with its content's hash. */
11554
11686
  function treeState(cwd) {
11555
11687
  const state = /* @__PURE__ */ new Map();
11556
- for (const file of git$1([
11688
+ const regular = [];
11689
+ const listed = gitOrThrow(cwd, [
11557
11690
  "ls-files",
11558
11691
  "--modified",
11559
11692
  "--others",
11560
11693
  "--exclude-standard",
11561
11694
  "-z"
11562
- ], cwd).split("\0")) {
11695
+ ]).split("\0");
11696
+ for (const file of listed) {
11563
11697
  if (!file) continue;
11564
- const full = path$1.join(cwd, file);
11565
- const stat = fs$1.lstatSync(full, { throwIfNoEntry: false });
11566
- state.set(file, !stat ? "deleted" : stat.isFile() ? git$1([
11698
+ const stat = fs$1.lstatSync(path$1.join(cwd, file), { throwIfNoEntry: false });
11699
+ state.set(file, !stat ? "deleted" : stat.isFile() ? "" : "other");
11700
+ if (stat?.isFile()) regular.push(file);
11701
+ }
11702
+ if (regular.length) {
11703
+ const hashes = gitOrThrow(cwd, [
11567
11704
  "hash-object",
11568
11705
  "--no-filters",
11569
- "--",
11570
- file
11571
- ], cwd).trim() : "other");
11706
+ "--stdin-paths"
11707
+ ], `${regular.join("\n")}\n`).trim().split("\n");
11708
+ regular.forEach((file, i) => state.set(file, hashes[i]));
11572
11709
  }
11573
11710
  return state;
11574
11711
  }
@@ -11587,16 +11724,6 @@ function duration(text) {
11587
11724
  h: 36e5
11588
11725
  }[m[2]];
11589
11726
  }
11590
- /** The last `result` event of a worker's stream, or undefined when it wrote none. */
11591
- function resultOf(jsonl) {
11592
- if (!fs$1.existsSync(jsonl)) return void 0;
11593
- let result;
11594
- for (const line of fs$1.readFileSync(jsonl, "utf8").split("\n")) try {
11595
- const event = JSON.parse(line);
11596
- if (event.type === "result") result = event;
11597
- } catch {}
11598
- return result;
11599
- }
11600
11727
  /**
11601
11728
  * One headless worker under its time budget. A worker that never returns must not hold the whole job to its timeout:
11602
11729
  * past the budget it is killed and writes no findings file; the merge lists its part as short, and the completion pass
@@ -11607,42 +11734,15 @@ function resultOf(jsonl) {
11607
11734
  async function runClaude(run, wrote, budget, env, cwd) {
11608
11735
  const jsonl = path$1.join(cwd, run.dir, `${run.log}.jsonl`);
11609
11736
  const err = path$1.join(cwd, run.dir, `${run.log}.err`);
11610
- const args = [
11611
- ...run.resume ? ["--resume", run.resume] : [],
11612
- "--print",
11613
- run.prompt,
11614
- "--model",
11615
- run.model,
11616
- "--effort",
11617
- run.effort,
11618
- "--permission-mode",
11619
- "default"
11620
- ];
11621
- args.push("--output-format", "stream-json", "--verbose", "--allowedTools", run.tools);
11622
- const out = fs$1.openSync(jsonl, "w");
11623
- const errOut = fs$1.openSync(err, "w");
11624
- const child = spawn("claude", args, {
11625
- cwd,
11737
+ const { code, killed, result: r } = await claudeSession({
11738
+ ...run,
11739
+ flags: ["--permission-mode", "default"],
11626
11740
  env,
11627
- stdio: [
11628
- "ignore",
11629
- out,
11630
- errOut
11631
- ]
11632
- });
11633
- let killed = false;
11634
- const timer = setTimeout(() => {
11635
- killed = true;
11636
- child.kill("SIGTERM");
11637
- }, budget);
11638
- const code = await new Promise((resolve) => {
11639
- child.on("error", () => resolve(127));
11640
- child.on("close", (c) => resolve(c ?? 1));
11741
+ cwd,
11742
+ stream: jsonl,
11743
+ stderr: err,
11744
+ budget
11641
11745
  });
11642
- clearTimeout(timer);
11643
- fs$1.closeSync(out);
11644
- fs$1.closeSync(errOut);
11645
- const r = resultOf(jsonl);
11646
11746
  const session = typeof r?.session_id === "string" ? r.session_id : run.resume;
11647
11747
  if (killed) return {
11648
11748
  status: `killed after ${Math.round(budget / 6e4)}m`,
@@ -11700,19 +11800,12 @@ async function runOnce(run, wrote, budget, env, cwd) {
11700
11800
  */
11701
11801
  async function checked(run, first, file, schema, canEdit, budget, env, cwd) {
11702
11802
  const full = path$1.join(cwd, file);
11703
- let ran = first;
11704
- let errors = checkFile(full, schema);
11705
- let corrections = 0;
11706
- while (errors.length && ran.status === "ok" && ran.session && corrections < 2) {
11707
- corrections++;
11708
- ran = await runClaude({
11709
- ...run,
11710
- prompt: correction(file, errors, canEdit),
11711
- resume: ran.session,
11712
- log: `${run.log}-fix-${corrections}`
11713
- }, () => fs$1.existsSync(full), budget, env, cwd);
11714
- errors = checkFile(full, schema);
11715
- }
11803
+ const { ran, errors, corrections } = await correctUntilValid(first, () => checkFile(full, schema), (r) => r.status === "ok" ? r.session : void 0, (errors, n, session) => runClaude({
11804
+ ...run,
11805
+ prompt: correction(file, errors, canEdit),
11806
+ resume: session,
11807
+ log: `${run.log}-fix-${n}`
11808
+ }, () => fs$1.existsSync(full), budget, env, cwd));
11716
11809
  return {
11717
11810
  status: ran.status,
11718
11811
  errors,
@@ -11728,7 +11821,7 @@ async function pool(tasks, limit) {
11728
11821
  await Promise.all(lanes);
11729
11822
  }
11730
11823
  /** One pass of the audit's workers; the exit code: 0 done, 1 the tree changed, 2 an input is missing. */
11731
- async function workers(pass, { audit = "spec-verify", context, env = process.env, cwd = root(), log = console.log } = {}) {
11824
+ async function workers(pass, { audit = "spec-verify", context, env = process.env, cwd = repoRoot(), log = console.log } = {}) {
11732
11825
  const withContext = (prompt) => context?.trim() ? `${prompt}\nRun context — facts established and decisions the owner has already made. Judge with them. A finding or a verdict that reverses one says so:\n${context.trim()}\n` : prompt;
11733
11826
  const kind = KINDS[audit];
11734
11827
  const { files } = kind;
@@ -11858,12 +11951,13 @@ async function workers(pass, { audit = "spec-verify", context, env = process.env
11858
11951
  var TOOLS, STEWARD_TOOLS, OUTPUTS, EARLY_FAILURE_MS, cgroupLimit, cgroupPeak, gb, memoryLine, shareOf, TOOL_RULE, SKILL, loadSkill, brief, briefComplete, briefVerify, KINDS, clock, checkNote;
11859
11952
  var init_workers = __esmMin((() => {
11860
11953
  init_ci();
11954
+ init_claude();
11861
11955
  init_data();
11862
11956
  init_files();
11863
- init_repo();
11864
11957
  init_rules();
11865
11958
  init_severity();
11866
11959
  init_skillsDir();
11960
+ init_git();
11867
11961
  init_stewardAudit();
11868
11962
  init_tier();
11869
11963
  TOOLS = "Skill,Bash(git:git diff*|git log*|git show*),Read,Glob,Grep,Write,Edit";
@@ -12274,7 +12368,7 @@ function applyVerdicts(findings, verdicts, ran, t = THRESHOLDS) {
12274
12368
  }
12275
12369
  /** Every verdict file the verification pass wrote, by the ERROR's position; one that is not valid is reported and skipped. */
12276
12370
  function readVerdicts(problems) {
12277
- const dir = path$1.join(root(), FINDINGS_DIR);
12371
+ const dir = path$1.join(repoRoot(), FINDINGS_DIR);
12278
12372
  const out = /* @__PURE__ */ new Map();
12279
12373
  if (!fs$1.existsSync(dir)) return out;
12280
12374
  for (const name of fs$1.readdirSync(dir).sort()) {
@@ -12365,9 +12459,9 @@ function scopeHeader(scope) {
12365
12459
  }
12366
12460
  function main$1(read = commitReader, env = process.env) {
12367
12461
  const t = thresholds(env);
12368
- const units = tryReadData(path$1.join(root(), ".spec-audit/parts/units.yaml")) ?? {};
12462
+ const units = tryReadData(path$1.join(repoRoot(), ".spec-audit/parts/units.yaml")) ?? {};
12369
12463
  const advisory = new Set(Object.entries(units).flatMap(([id, u]) => u.advisory ? [id] : []));
12370
- const scopePath = path$1.join(root(), SCOPE_FILE);
12464
+ const scopePath = path$1.join(repoRoot(), SCOPE_FILE);
12371
12465
  const scope = fs$1.existsSync(scopePath) ? readData(scopePath) : void 0;
12372
12466
  const problems = [];
12373
12467
  if (!scope) problems.push(`\`${SCOPE_FILE}\` is missing — run \`spec-tools scope\` first; one part assumed.`);
@@ -12376,7 +12470,7 @@ function main$1(read = commitReader, env = process.env) {
12376
12470
  const parts = /* @__PURE__ */ new Map();
12377
12471
  const readers = scope?.readers ?? 1;
12378
12472
  const readPart = (files, n) => files.map((rel, index) => {
12379
- const file = path$1.join(root(), rel);
12473
+ const file = path$1.join(repoRoot(), rel);
12380
12474
  if (!fs$1.existsSync(file)) {
12381
12475
  problems.push(`\`${rel}\` was not written — reader ${index + 1} of part ${n} counts as not run.`);
12382
12476
  return;
@@ -12395,18 +12489,18 @@ function main$1(read = commitReader, env = process.env) {
12395
12489
  };
12396
12490
  });
12397
12491
  const defaults = (n) => Array.from({ length: readers }, (_, r) => `${FINDINGS_DIR}/part-${n}-${r + 1}.yaml`);
12398
- const dir = path$1.join(root(), FINDINGS_DIR);
12492
+ const dir = path$1.join(repoRoot(), FINDINGS_DIR);
12399
12493
  const present = fs$1.existsSync(dir) ? fs$1.readdirSync(dir).map((f) => `${FINDINGS_DIR}/${f}`) : [];
12400
12494
  for (let n = 1; n <= expected; n++) parts.set(n, readPart(readerFiles(scope?.parts[n - 1]?.findings ?? defaults(n), present, n), n));
12401
12495
  const findings = applyVerdicts(dedupe([...parts.values()].flatMap((readers) => readers.flatMap((p, index) => p ? p.findings.map((f) => ({
12402
12496
  ...grade(f, p.part, read, advisory, t),
12403
12497
  reader: index + 1
12404
- })) : []))), readVerdicts(problems), fs$1.existsSync(path$1.join(root(), VERIFIED_MARKER)), t);
12498
+ })) : []))), readVerdicts(problems), fs$1.existsSync(path$1.join(repoRoot(), VERIFIED_MARKER)), t);
12405
12499
  const expectedIds = new Map((scope?.parts ?? []).map((p) => [p.part, p.requirementIds ?? []]));
12406
12500
  const coverage = mergeCoverage(parts, expectedIds);
12407
12501
  const report = render(header, findings, coverage, problems, t);
12408
- fs$1.mkdirSync(path$1.dirname(path$1.join(root(), REPORT_FILE)), { recursive: true });
12409
- fs$1.writeFileSync(path$1.join(root(), REPORT_FILE), report);
12502
+ fs$1.mkdirSync(path$1.dirname(path$1.join(repoRoot(), REPORT_FILE)), { recursive: true });
12503
+ fs$1.writeFileSync(path$1.join(repoRoot(), REPORT_FILE), report);
12410
12504
  const v = verdict(findings, coverage, t);
12411
12505
  const data = {
12412
12506
  verdict: v.line,
@@ -12417,7 +12511,7 @@ function main$1(read = commitReader, env = process.env) {
12417
12511
  findings,
12418
12512
  short: shortList(parts, expectedIds)
12419
12513
  };
12420
- writeData(path$1.join(root(), REPORT_DATA), data);
12514
+ writeData(path$1.join(repoRoot(), REPORT_DATA), data);
12421
12515
  fs$1.mkdirSync(dir, { recursive: true });
12422
12516
  const merges = fs$1.readdirSync(dir).filter((f) => MERGE_FILE.test(f)).length;
12423
12517
  writeData(path$1.join(dir, `merge-${merges + 1}.yaml`), data);
@@ -12429,12 +12523,12 @@ function cli(argv) {
12429
12523
  process.stdout.write(line + "\n");
12430
12524
  return argv.includes("--gate") ? exitCodeFor(line.split(" ")[0]) : 0;
12431
12525
  }
12432
- var MERGE_FILE, VERDICT_FILE, ERROR_CLASS, WARN_CLASS, INFO_CLASS, CHECKS, normalize, isForeign, gitReader, commitReader, worktreeReader, rank, exitCodeFor, unitOf, firstSentence, readingOf, findingLine;
12526
+ var MERGE_FILE, VERDICT_FILE, ERROR_CLASS, WARN_CLASS, INFO_CLASS, CHECKS, normalize, isForeign, memoized, gitReader, commitReader, worktreeReader, rank, exitCodeFor, unitOf, firstSentence, readingOf, findingLine;
12433
12527
  var init_auditReport = __esmMin((() => {
12434
12528
  init_data();
12435
12529
  init_files();
12436
- init_repo();
12437
12530
  init_severity();
12531
+ init_git();
12438
12532
  MERGE_FILE = /^merge-\d+\.yaml$/;
12439
12533
  VERDICT_FILE = /^verdict-(\d+)\.yaml$/;
12440
12534
  ERROR_CLASS = ["code-mismatch", "undeclared-gap"];
@@ -12449,30 +12543,22 @@ var init_auditReport = __esmMin((() => {
12449
12543
  };
12450
12544
  normalize = (s) => s.replace(/\s+/g, " ").trim();
12451
12545
  isForeign = (file) => file.startsWith(`.spec-audit/`) || /(^|\/)node_modules\//.test(file);
12452
- gitReader = (ref, cwd = root()) => (file) => {
12453
- try {
12454
- return execFileSync("git", ["show", `${ref}:${file}`], {
12455
- cwd,
12456
- encoding: "utf8",
12457
- maxBuffer: 67108864,
12458
- stdio: [
12459
- "ignore",
12460
- "pipe",
12461
- "ignore"
12462
- ]
12463
- }).split("\n");
12464
- } catch {
12465
- return;
12466
- }
12546
+ memoized = (read) => {
12547
+ const cache = /* @__PURE__ */ new Map();
12548
+ return (file) => {
12549
+ if (!cache.has(file)) cache.set(file, read(file));
12550
+ return cache.get(file);
12551
+ };
12467
12552
  };
12553
+ gitReader = (ref, cwd) => memoized((file) => show$1(cwd ?? repoRoot(), ref, file)?.split("\n"));
12468
12554
  commitReader = gitReader("HEAD");
12469
- worktreeReader = (file) => {
12555
+ worktreeReader = memoized((file) => {
12470
12556
  try {
12471
- return fs$1.readFileSync(path$1.join(root(), file), "utf8").split("\n");
12557
+ return fs$1.readFileSync(path$1.join(repoRoot(), file), "utf8").split("\n");
12472
12558
  } catch {
12473
12559
  return;
12474
12560
  }
12475
- };
12561
+ });
12476
12562
  rank = {
12477
12563
  full: 0,
12478
12564
  sampled: 1,
@@ -12564,8 +12650,8 @@ function audit(argv, audit = "spec-verify") {
12564
12650
  const context = given ? path$1.resolve(given) : void 0;
12565
12651
  const here = argv.includes("--here");
12566
12652
  const dry = argv.includes("--dry");
12567
- const top = root();
12568
- const head = git$1([
12653
+ const top = repoRoot();
12654
+ const head = gitOrThrow(top, [
12569
12655
  "rev-parse",
12570
12656
  "--short",
12571
12657
  "HEAD"
@@ -12575,7 +12661,7 @@ function audit(argv, audit = "spec-verify") {
12575
12661
  return sequence(top, true, dry, audit, context);
12576
12662
  }
12577
12663
  const tree = path$1.join(fs$1.mkdtempSync(path$1.join(os.tmpdir(), `${path$1.basename(top)}-audit-`)), "tree");
12578
- git$1([
12664
+ gitOrThrow(top, [
12579
12665
  "worktree",
12580
12666
  "add",
12581
12667
  "--detach",
@@ -12598,7 +12684,7 @@ function audit(argv, audit = "spec-verify") {
12598
12684
  return code;
12599
12685
  } finally {
12600
12686
  try {
12601
- git$1([
12687
+ gitOrThrow(top, [
12602
12688
  "worktree",
12603
12689
  "remove",
12604
12690
  "--force",
@@ -12615,7 +12701,7 @@ function audit(argv, audit = "spec-verify") {
12615
12701
  var outputs, self;
12616
12702
  var init_audit = __esmMin((() => {
12617
12703
  init_files();
12618
- init_repo();
12704
+ init_git();
12619
12705
  outputs = [AUDIT_DIR];
12620
12706
  self = (args, cwd) => spawnSync(process.execPath, [
12621
12707
  ...process.execArgv,
@@ -12662,52 +12748,27 @@ function progress(event, now = /* @__PURE__ */ new Date()) {
12662
12748
  }
12663
12749
  /** One headless session, streamed to the job log; its exit code, its result text and its session id. */
12664
12750
  async function session(prompt, env, resume) {
12665
- const args = [
12666
- ...resume ? ["--resume", resume] : [],
12667
- "--print",
12668
- prompt,
12669
- "--model",
12670
- env.AUDIT_MODEL || "claude-haiku-5-5",
12671
- "--effort",
12672
- env.AUDIT_EFFORT || "high",
12673
- "--output-format",
12674
- "stream-json",
12675
- "--verbose",
12676
- "--include-partial-messages",
12677
- "--allowedTools",
12678
- REVIEW_TOOLS
12679
- ];
12680
- fs$1.mkdirSync(path$1.dirname(STREAM_FILE), { recursive: true });
12681
- const stream = fs$1.createWriteStream(STREAM_FILE, { flags: resume ? "a" : "w" });
12682
- const child = spawn("claude", args, {
12683
- env,
12684
- stdio: [
12685
- "ignore",
12686
- "pipe",
12687
- "inherit"
12688
- ]
12689
- });
12690
12751
  let result = "";
12691
12752
  let id;
12692
- let pending = "";
12693
- child.stdout.on("data", (chunk) => {
12694
- stream.write(chunk);
12695
- const lines = (pending + chunk.toString("utf8")).split("\n");
12696
- pending = lines.pop() ?? "";
12697
- for (const line of lines) try {
12698
- const event = JSON.parse(line);
12753
+ const { code } = await claudeSession({
12754
+ prompt,
12755
+ model: env.AUDIT_MODEL || "claude-haiku-5-5",
12756
+ effort: env.AUDIT_EFFORT || "high",
12757
+ tools: REVIEW_TOOLS,
12758
+ resume,
12759
+ flags: ["--include-partial-messages"],
12760
+ env,
12761
+ stream: STREAM_FILE,
12762
+ append: !!resume,
12763
+ onEvent: (raw) => {
12764
+ const event = raw;
12699
12765
  if (event.type === "result") {
12700
12766
  result = event.result ?? "";
12701
12767
  id = event.session_id ?? id;
12702
12768
  }
12703
12769
  process.stdout.write(progress(event));
12704
- } catch {}
12705
- });
12706
- const code = await new Promise((resolve) => {
12707
- child.on("error", () => resolve(127));
12708
- child.on("close", (c) => resolve(c ?? 1));
12770
+ }
12709
12771
  });
12710
- await new Promise((resolve) => stream.end(resolve));
12711
12772
  return {
12712
12773
  code,
12713
12774
  result,
@@ -12717,13 +12778,12 @@ async function session(prompt, env, resume) {
12717
12778
  async function run(skill, log, report, env = process.env) {
12718
12779
  let ran = await session(`/${skill}`, env);
12719
12780
  if (ran.code === 0 && report) {
12720
- let errors = checkFile(report, REVIEW_REPORT);
12721
- for (let n = 1; errors.length && ran.code === 0 && ran.id && n <= 2; n++) {
12781
+ const checked = await correctUntilValid(ran, () => checkFile(report, REVIEW_REPORT), (r) => r.code === 0 ? r.id : void 0, (errors, n, id) => {
12722
12782
  console.log(`spec-tools run: ${report} has ${errors.length} error(s); correction ${n} of 2`);
12723
- ran = await session(correction(report, errors, false), env, ran.id);
12724
- errors = checkFile(report, REVIEW_REPORT);
12725
- }
12726
- if (errors.length) console.error(`spec-tools run: ${report} is still not valid:\n${errors.join("\n")}`);
12783
+ return session(correction(report, errors, false), env, id);
12784
+ });
12785
+ ran = checked.ran;
12786
+ if (checked.errors.length) console.error(`spec-tools run: ${report} is still not valid:\n${checked.errors.join("\n")}`);
12727
12787
  }
12728
12788
  fs$1.mkdirSync(path$1.dirname(log), { recursive: true });
12729
12789
  fs$1.writeFileSync(log, ran.result ? `${ran.result}\n` : "");
@@ -12732,6 +12792,7 @@ async function run(skill, log, report, env = process.env) {
12732
12792
  }
12733
12793
  var REVIEW_TOOLS;
12734
12794
  var init_run = __esmMin((() => {
12795
+ init_claude();
12735
12796
  init_data();
12736
12797
  init_files();
12737
12798
  init_rules();
@@ -14688,15 +14749,27 @@ ${k.parse(markdown, {
14688
14749
  }));
14689
14750
  //#endregion
14690
14751
  //#region spec-tools/src/cli.ts
14752
+ init_util();
14753
+ /** The flags that never take a value. */
14754
+ const BOOLEANS = [
14755
+ "verify",
14756
+ "complete",
14757
+ "worktree",
14758
+ "gate",
14759
+ "advisory",
14760
+ "here",
14761
+ "dry",
14762
+ "classify"
14763
+ ];
14691
14764
  const [command, ...argv] = process.argv.slice(2);
14692
- /** The value after a flag, or undefined. */
14693
- const flag = (name) => {
14694
- const i = argv.indexOf(name);
14695
- return i >= 0 ? argv[i + 1] : void 0;
14696
- };
14765
+ const opts = parseArgs(argv, [], BOOLEANS);
14766
+ /** The value of a flag (`--name value` or `--name=value`), or undefined. */
14767
+ const flag = (name) => typeof opts[name] === "string" ? opts[name] : void 0;
14768
+ /** Whether a flag that takes no value is given. */
14769
+ const has = (name) => opts[name] === true;
14697
14770
  /** The audit `--audit` names; spec-verify when none is named. */
14698
14771
  async function auditOf() {
14699
- const name = flag("--audit") ?? "spec-verify";
14772
+ const name = flag("audit") ?? "spec-verify";
14700
14773
  const { AUDIT_NAMES } = await Promise.resolve().then(() => (init_files(), files_exports));
14701
14774
  if (!AUDIT_NAMES.includes(name)) throw new Error(`--audit ${name}: expected one of ${AUDIT_NAMES.join(", ")}`);
14702
14775
  return name;
@@ -14704,12 +14777,12 @@ async function auditOf() {
14704
14777
  async function main() {
14705
14778
  switch (command) {
14706
14779
  case "gates": {
14707
- const { root } = await Promise.resolve().then(() => (init_repo(), repo_exports));
14780
+ const { repoRoot } = await Promise.resolve().then(() => (init_git(), git_exports));
14708
14781
  const checked = await (await Promise.resolve().then(() => (init_steward(), steward_exports))).run([
14709
14782
  "check",
14710
14783
  "--base",
14711
14784
  "auto"
14712
- ], root());
14785
+ ], repoRoot());
14713
14786
  const gates = (await Promise.resolve().then(() => (init_changeGates(), changeGates_exports))).main();
14714
14787
  return Math.max(checked, gates);
14715
14788
  }
@@ -14719,9 +14792,9 @@ async function main() {
14719
14792
  console.log((await Promise.resolve().then(() => (init_specDiff(), specDiff_exports))).main(argv));
14720
14793
  return 0;
14721
14794
  case "changed": {
14722
- const { root } = await Promise.resolve().then(() => (init_repo(), repo_exports));
14723
- (await Promise.resolve().then(() => (init_auditParts(), auditParts_exports))).writeEvidence(root());
14724
- process.stdout.write((await Promise.resolve().then(() => (init_auditChanged(), auditChanged_exports))).main());
14795
+ const { repoRoot } = await Promise.resolve().then(() => (init_git(), git_exports));
14796
+ const model = (await Promise.resolve().then(() => (init_auditParts(), auditParts_exports))).writeEvidence(repoRoot());
14797
+ process.stdout.write((await Promise.resolve().then(() => (init_auditChanged(), auditChanged_exports))).main(process.env, model));
14725
14798
  return 0;
14726
14799
  }
14727
14800
  case "tier": {
@@ -14730,14 +14803,14 @@ async function main() {
14730
14803
  return 0;
14731
14804
  }
14732
14805
  case "scope": {
14733
- const { root } = await Promise.resolve().then(() => (init_repo(), repo_exports));
14734
- (await Promise.resolve().then(() => (init_auditParts(), auditParts_exports))).writeEvidence(root());
14735
- process.stdout.write((await Promise.resolve().then(() => (init_auditScope(), auditScope_exports))).main(process.env, await auditOf()));
14806
+ const { repoRoot } = await Promise.resolve().then(() => (init_git(), git_exports));
14807
+ const model = (await Promise.resolve().then(() => (init_auditParts(), auditParts_exports))).writeEvidence(repoRoot());
14808
+ process.stdout.write((await Promise.resolve().then(() => (init_auditScope(), auditScope_exports))).main(process.env, await auditOf(), model));
14736
14809
  return 0;
14737
14810
  }
14738
14811
  case "workers": {
14739
- const pass = argv.includes("--verify") ? "verify" : argv.includes("--complete") ? "complete" : "read";
14740
- const file = flag("--context");
14812
+ const pass = has("verify") ? "verify" : has("complete") ? "complete" : "read";
14813
+ const file = flag("context");
14741
14814
  const context = file ? (await import("node:fs")).readFileSync(file, "utf8") : void 0;
14742
14815
  return (await Promise.resolve().then(() => (init_workers(), workers_exports))).workers(pass, {
14743
14816
  audit: await auditOf(),
@@ -14747,7 +14820,7 @@ async function main() {
14747
14820
  case "report": {
14748
14821
  if (await auditOf() === "spec-verify") return (await Promise.resolve().then(() => (init_auditReport(), auditReport_exports))).cli(argv);
14749
14822
  const { commitReader, worktreeReader } = await Promise.resolve().then(() => (init_auditReport(), auditReport_exports));
14750
- console.log((await Promise.resolve().then(() => (init_stewardAudit(), stewardAudit_exports))).merge(argv.includes("--worktree") ? worktreeReader : commitReader));
14823
+ console.log((await Promise.resolve().then(() => (init_stewardAudit(), stewardAudit_exports))).merge(has("worktree") ? worktreeReader : commitReader));
14751
14824
  return 0;
14752
14825
  }
14753
14826
  case "audit": return (await Promise.resolve().then(() => (init_audit(), audit_exports))).audit(argv, await auditOf());
@@ -14756,16 +14829,16 @@ async function main() {
14756
14829
  if (!skill || skill.startsWith("-")) break;
14757
14830
  const { jobLog } = await Promise.resolve().then(() => (init_ci(), ci_exports));
14758
14831
  const log = jobLog();
14759
- const report = flag("--verdict");
14832
+ const report = flag("verdict");
14760
14833
  const code = await (await Promise.resolve().then(() => (init_run(), run_exports))).run(skill, log, report);
14761
14834
  if (code !== 0 || !report) return code;
14762
- const advisory = argv.includes("--advisory") || process.env.AUDIT_GATING === "advisory";
14835
+ const advisory = has("advisory") || process.env.AUDIT_GATING === "advisory";
14763
14836
  return (await Promise.resolve().then(() => (init_verdict(), verdict_exports))).gate(report, advisory);
14764
14837
  }
14765
14838
  case "verdict": {
14766
14839
  const report = argv[0];
14767
14840
  if (!report || report.startsWith("-")) break;
14768
- const advisory = argv.includes("--advisory") || process.env.AUDIT_GATING === "advisory";
14841
+ const advisory = has("advisory") || process.env.AUDIT_GATING === "advisory";
14769
14842
  return (await Promise.resolve().then(() => (init_verdict(), verdict_exports))).gate(report, advisory);
14770
14843
  }
14771
14844
  case "comment":