@shaulavo/standards 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +928 -165
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -11530,6 +11530,340 @@ var require_lib = __commonJS(function(exports, module) {
11530
11530
  module.exports = validate;
11531
11531
  });
11532
11532
 
11533
+ // src/report.ts
11534
+ import { randomBytes } from "node:crypto";
11535
+ import {
11536
+ existsSync,
11537
+ mkdirSync,
11538
+ readdirSync,
11539
+ readFileSync,
11540
+ renameSync,
11541
+ writeFileSync
11542
+ } from "node:fs";
11543
+ import { join } from "node:path";
11544
+ var MAX_EXCERPT_LINES = 30;
11545
+ var MAX_EXCERPT_CHARS = 2000;
11546
+ var TRUNCATION_SUFFIX = `
11547
+ ... (truncated)`;
11548
+ var GATE_STATUSES = new Set(["pass", "findings", "failed"]);
11549
+ function isGateStatus(value) {
11550
+ return typeof value === "string" && GATE_STATUSES.has(value);
11551
+ }
11552
+ var REPORT_HEADING = {
11553
+ success: "✅ CI Passed",
11554
+ failure: "❌ CI Failed",
11555
+ cancelled: "⚪ CI Cancelled"
11556
+ };
11557
+ var GATE_STATUS_ICON = {
11558
+ pass: "✅",
11559
+ findings: "❌",
11560
+ failed: "⚠️"
11561
+ };
11562
+ var GATE_STATUS_LABEL = {
11563
+ pass: "Pass",
11564
+ findings: "Findings",
11565
+ failed: "Failed"
11566
+ };
11567
+ var activeNote;
11568
+ function resetGateNote() {
11569
+ activeNote = undefined;
11570
+ }
11571
+ function recordGateNote(note) {
11572
+ activeNote = note;
11573
+ }
11574
+ function consumeGateNote() {
11575
+ const note = activeNote;
11576
+ activeNote = undefined;
11577
+ return note;
11578
+ }
11579
+ function gateStatusFromExit(exitCode) {
11580
+ if (exitCode === 0)
11581
+ return "pass";
11582
+ if (exitCode === 1)
11583
+ return "findings";
11584
+ return "failed";
11585
+ }
11586
+ function capExcerpt(raw) {
11587
+ if (raw === undefined)
11588
+ return;
11589
+ const trimmed = raw.trim();
11590
+ if (trimmed === "")
11591
+ return;
11592
+ const lines = trimmed.split(/\r?\n/);
11593
+ const clippedLines = lines.length > MAX_EXCERPT_LINES ? `${lines.slice(0, MAX_EXCERPT_LINES).join(`
11594
+ `)}${TRUNCATION_SUFFIX}` : lines.join(`
11595
+ `);
11596
+ if (clippedLines.length <= MAX_EXCERPT_CHARS)
11597
+ return clippedLines;
11598
+ const head = clippedLines.slice(0, MAX_EXCERPT_CHARS - TRUNCATION_SUFFIX.length).trimEnd();
11599
+ return `${head}${TRUNCATION_SUFFIX}`;
11600
+ }
11601
+ function writeGateRecord(dir, input) {
11602
+ const targetDir = dir?.trim();
11603
+ if (!targetDir)
11604
+ return;
11605
+ mkdirSync(targetDir, { recursive: true });
11606
+ const excerpt = capExcerpt(input.excerpt);
11607
+ const record = {
11608
+ kind: "gate",
11609
+ gate: input.gate,
11610
+ status: input.status,
11611
+ exitCode: input.exitCode,
11612
+ durationMs: Math.max(0, Math.round(input.durationMs)),
11613
+ timestamp: input.timestamp,
11614
+ ...input.summary !== undefined ? { summary: input.summary } : {},
11615
+ ...excerpt !== undefined ? { excerpt } : {}
11616
+ };
11617
+ const safeGate = input.gate.replace(/[^a-z0-9._-]/gi, "_");
11618
+ const id = randomBytes(4).toString("hex");
11619
+ const baseName = `${record.timestamp}-${process.pid}-${id}-${safeGate}`;
11620
+ const finalPath = join(targetDir, `${baseName}.json`);
11621
+ const partialPath = join(targetDir, `${baseName}.partial`);
11622
+ writeFileSync(partialPath, `${JSON.stringify(record)}
11623
+ `);
11624
+ renameSync(partialPath, finalPath);
11625
+ return finalPath;
11626
+ }
11627
+ function readReportDir(dir) {
11628
+ if (!dir || !existsSync(dir))
11629
+ return { gates: [], invalid: [] };
11630
+ const files = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).toSorted();
11631
+ const gates = [];
11632
+ const invalid = [];
11633
+ for (const file of files) {
11634
+ loadRecordFile(join(dir, file), file, gates, invalid);
11635
+ }
11636
+ gates.sort((left, right) => {
11637
+ if (left.record.timestamp !== right.record.timestamp) {
11638
+ return left.record.timestamp - right.record.timestamp;
11639
+ }
11640
+ return left.file.localeCompare(right.file);
11641
+ });
11642
+ return {
11643
+ gates: gates.map((entry) => entry.record),
11644
+ invalid
11645
+ };
11646
+ }
11647
+ function markerComment(marker) {
11648
+ return `<!-- standards:ci-report:${marker} -->`;
11649
+ }
11650
+ function renderReport(input) {
11651
+ const blocks = [markerComment(input.marker), renderHeading(input.status, input.gates)];
11652
+ const meta = renderMetadata(input);
11653
+ if (meta !== undefined)
11654
+ blocks.push(meta);
11655
+ if (input.gates.length > 0)
11656
+ blocks.push(renderGateTable(input.gates));
11657
+ const statusNote = renderStatusNote(input.status, input.gates, input.runUrl);
11658
+ if (statusNote !== undefined)
11659
+ blocks.push(statusNote);
11660
+ const excerpts = renderFailureExcerpts(input.gates);
11661
+ if (excerpts.length > 0)
11662
+ blocks.push(excerpts.join(`
11663
+
11664
+ `));
11665
+ if (input.invalid.length > 0)
11666
+ blocks.push(renderInvalidRecords(input.invalid));
11667
+ return `${blocks.join(`
11668
+
11669
+ `)}
11670
+ `;
11671
+ }
11672
+ function renderHeading(status, gates) {
11673
+ const base = `### ${REPORT_HEADING[status]}`;
11674
+ if (gates.length === 0)
11675
+ return base;
11676
+ const passed = gates.filter((gate) => gate.status === "pass").length;
11677
+ const failed = gates.length - passed;
11678
+ if (failed === 0) {
11679
+ return `${base} · ${passed}/${gates.length} ${gates.length === 1 ? "gate" : "gates"}`;
11680
+ }
11681
+ const parts = [`${failed} failed`].concat(passed > 0 ? [`${passed} passed`] : []);
11682
+ return `${base} · ${parts.join(", ")}`;
11683
+ }
11684
+ function loadRecordFile(fullPath, file, gates, invalid) {
11685
+ const parsed = parseJsonFile(fullPath);
11686
+ if (!parsed.ok) {
11687
+ invalid.push({ file, reason: parsed.reason });
11688
+ return;
11689
+ }
11690
+ const value = parsed.value;
11691
+ if (!isPlainObject(value)) {
11692
+ invalid.push({ file, reason: "record must be a JSON object" });
11693
+ return;
11694
+ }
11695
+ if (value.kind !== "gate") {
11696
+ invalid.push({ file, reason: `unknown record kind ${JSON.stringify(value.kind)}` });
11697
+ return;
11698
+ }
11699
+ const validated = validateGateRecord(value);
11700
+ if (!validated.ok) {
11701
+ invalid.push({ file, reason: validated.reason });
11702
+ return;
11703
+ }
11704
+ gates.push({ record: validated.record, file });
11705
+ }
11706
+ function parseJsonFile(path) {
11707
+ try {
11708
+ return { ok: true, value: JSON.parse(readFileSync(path, "utf8")) };
11709
+ } catch (error) {
11710
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
11711
+ }
11712
+ }
11713
+ function validateGateRecord(raw) {
11714
+ if (typeof raw.gate !== "string" || raw.gate.trim() === "") {
11715
+ return { ok: false, reason: "gate must be a non-empty string" };
11716
+ }
11717
+ if (!isGateStatus(raw.status)) {
11718
+ return { ok: false, reason: "status must be pass, findings, or failed" };
11719
+ }
11720
+ if (typeof raw.exitCode !== "number" || !Number.isSafeInteger(raw.exitCode) || raw.exitCode < 0) {
11721
+ return { ok: false, reason: "exitCode must be a non-negative integer" };
11722
+ }
11723
+ if (typeof raw.durationMs !== "number" || !Number.isFinite(raw.durationMs) || raw.durationMs < 0) {
11724
+ return { ok: false, reason: "durationMs must be a non-negative finite number" };
11725
+ }
11726
+ if (typeof raw.timestamp !== "number" || !Number.isFinite(raw.timestamp) || raw.timestamp < 0) {
11727
+ return { ok: false, reason: "timestamp must be a non-negative finite number" };
11728
+ }
11729
+ if (raw.summary !== undefined && typeof raw.summary !== "string") {
11730
+ return { ok: false, reason: "summary must be a string when present" };
11731
+ }
11732
+ if (raw.excerpt !== undefined && typeof raw.excerpt !== "string") {
11733
+ return { ok: false, reason: "excerpt must be a string when present" };
11734
+ }
11735
+ const excerpt = capExcerpt(raw.excerpt);
11736
+ return {
11737
+ ok: true,
11738
+ record: {
11739
+ kind: "gate",
11740
+ gate: raw.gate,
11741
+ status: raw.status,
11742
+ exitCode: raw.exitCode,
11743
+ durationMs: raw.durationMs,
11744
+ timestamp: raw.timestamp,
11745
+ ...raw.summary !== undefined ? { summary: raw.summary } : {},
11746
+ ...excerpt !== undefined ? { excerpt } : {}
11747
+ }
11748
+ };
11749
+ }
11750
+ function renderMetadata(input) {
11751
+ const parts = [];
11752
+ if (input.sha !== undefined && input.sha !== "") {
11753
+ const shortSha = input.sha.slice(0, 7);
11754
+ const commitUrl = input.repo !== undefined && input.serverUrl !== undefined ? `${input.serverUrl.replace(/\/+$/, "")}/${input.repo}/commit/${encodeURIComponent(input.sha)}` : undefined;
11755
+ parts.push(commitUrl !== undefined ? `[\`${escapeInlineCode(shortSha)}\`](${commitUrl})` : `\`${escapeInlineCode(shortSha)}\``);
11756
+ }
11757
+ if (input.gates.length > 0) {
11758
+ const totalMs = input.gates.reduce((sum, gate) => sum + gate.durationMs, 0);
11759
+ parts.push(formatDuration(totalMs));
11760
+ }
11761
+ if (input.runUrl !== undefined && input.runUrl !== "") {
11762
+ parts.push(`[Workflow run](${input.runUrl})`);
11763
+ }
11764
+ return parts.length > 0 ? parts.join(" · ") : undefined;
11765
+ }
11766
+ function renderGateTable(gates) {
11767
+ const header = ["| | Gate | Result | Time |", "| :-: | :--- | :--- | ---: |"];
11768
+ const rows = gates.map((gate) => {
11769
+ const icon = GATE_STATUS_ICON[gate.status];
11770
+ const name = `**${escapeTableCell(gate.gate)}**`;
11771
+ const details = gate.summary !== undefined && gate.summary.trim() !== "" ? escapeTableCell(gate.summary) : "—";
11772
+ const duration = formatDuration(gate.durationMs);
11773
+ return `| ${icon} | ${name} | ${details} | ${duration} |`;
11774
+ });
11775
+ return header.concat(rows).join(`
11776
+ `);
11777
+ }
11778
+ function renderStatusNote(status, gates, runUrl) {
11779
+ const runSuffix = runUrl !== undefined && runUrl !== "" ? ` See the [workflow run](${runUrl}) for details.` : "";
11780
+ if (status === "failure") {
11781
+ if (gates.length === 0) {
11782
+ return `> **Note:** No standards gates were recorded before CI failed. A non-standards step (such as install, build, or tests) failed.${runSuffix}`;
11783
+ }
11784
+ if (gates.every((gate) => gate.status === "pass")) {
11785
+ return `> **Note:** Every recorded standards gate passed, but a non-standards step (such as build or tests) failed.${runSuffix}`;
11786
+ }
11787
+ return;
11788
+ }
11789
+ if (gates.length > 0)
11790
+ return;
11791
+ if (status === "cancelled") {
11792
+ return `> **Note:** CI was cancelled before any standards gates were recorded.${runSuffix}`;
11793
+ }
11794
+ return "> **Note:** No standards gates were recorded for this run.";
11795
+ }
11796
+ function renderFailureExcerpts(gates) {
11797
+ const blocks = [];
11798
+ for (const gate of gates) {
11799
+ if (gate.status === "pass")
11800
+ continue;
11801
+ const excerpt = capExcerpt(gate.excerpt);
11802
+ if (excerpt === undefined)
11803
+ continue;
11804
+ const summaryText = escapeHtml(`Failure output: ${gate.gate} (${GATE_STATUS_LABEL[gate.status]})`);
11805
+ blocks.push([
11806
+ "<details>",
11807
+ `<summary>${summaryText}</summary>`,
11808
+ "",
11809
+ fencedCodeBlock(excerpt),
11810
+ "",
11811
+ "</details>"
11812
+ ].join(`
11813
+ `));
11814
+ }
11815
+ return blocks;
11816
+ }
11817
+ function renderInvalidRecords(invalid) {
11818
+ const items = invalid.map((entry) => `- ${inlineCode(entry.file)}: ${escapeTableCell(entry.reason)}`);
11819
+ return ["### Invalid report records", ""].concat(items).join(`
11820
+ `);
11821
+ }
11822
+ function fencedCodeBlock(text) {
11823
+ const fence = "`".repeat(Math.max(3, longestBacktickRun(text) + 1));
11824
+ return `${fence}text
11825
+ ${text}
11826
+ ${fence}`;
11827
+ }
11828
+ function formatDuration(ms) {
11829
+ if (ms < 1000)
11830
+ return `${Math.round(ms)}ms`;
11831
+ if (ms < 60000)
11832
+ return `${(ms / 1000).toFixed(1)}s`;
11833
+ const minutes = Math.floor(ms / 60000);
11834
+ const seconds = (ms % 60000 / 1000).toFixed(1);
11835
+ return `${minutes}m ${seconds}s`;
11836
+ }
11837
+ function escapeTableCell(text) {
11838
+ return escapeHtml(flattenLine(text)).replace(/[\\|`*_[\]~]/g, (char) => `\\${char}`).replaceAll("://", "&#58;//").replace(/\bwww\./gi, (match) => `${match.slice(0, 3)}&#46;`).replaceAll("@", "&#64;");
11839
+ }
11840
+ function inlineCode(text) {
11841
+ const ticks = "`".repeat(longestBacktickRun(text) + 1);
11842
+ const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";
11843
+ return `${ticks}${pad}${text}${pad}${ticks}`;
11844
+ }
11845
+ function longestBacktickRun(text) {
11846
+ let longest = 0;
11847
+ for (const match of text.matchAll(/`+/g)) {
11848
+ const length = match[0].length;
11849
+ if (length > longest)
11850
+ longest = length;
11851
+ }
11852
+ return longest;
11853
+ }
11854
+ function escapeInlineCode(text) {
11855
+ return text.replace(/[`\r\n]/g, "");
11856
+ }
11857
+ function flattenLine(text) {
11858
+ return text.replace(/(?:\r\n|\r|\n)+/g, " ").trim();
11859
+ }
11860
+ function escapeHtml(text) {
11861
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
11862
+ }
11863
+ function isPlainObject(value) {
11864
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11865
+ }
11866
+
11533
11867
  // src/gate.ts
11534
11868
  var EXIT = {
11535
11869
  pass: 0,
@@ -11558,6 +11892,10 @@ function verdict(command, scan) {
11558
11892
  `) ? scan.report : `${scan.report}
11559
11893
  `);
11560
11894
  if (scan.inputs === 0) {
11895
+ recordGateNote({
11896
+ summary: `0 ${scan.unit} scanned`,
11897
+ excerpt: scan.report
11898
+ });
11561
11899
  process.stderr.write(`standards ${command}: scanned zero ${scan.unit} (${scan.tool}). Check the paths, scope and ignore patterns.
11562
11900
  `);
11563
11901
  return EXIT.failed;
@@ -11565,10 +11903,15 @@ function verdict(command, scan) {
11565
11903
  const checked = `checked ${count(scan.inputs, scan.unit)}`;
11566
11904
  const scanned = scan.tool === command ? checked : `${scan.tool} ${checked}`;
11567
11905
  if (scan.findings > 0) {
11906
+ recordGateNote({
11907
+ summary: `${count(scan.findings, "problems")} (${count(scan.inputs, scan.unit)})`,
11908
+ excerpt: scan.report
11909
+ });
11568
11910
  process.stderr.write(`standards ${command}: ${scanned} and found ${count(scan.findings, "problems")}.
11569
11911
  `);
11570
11912
  return EXIT.findings;
11571
11913
  }
11914
+ recordGateNote({ summary: count(scan.inputs, scan.unit) });
11572
11915
  process.stdout.write(`standards ${command}: ${scanned}, no findings.
11573
11916
  `);
11574
11917
  return EXIT.pass;
@@ -11611,12 +11954,12 @@ async function runAdapter(adapter, cwd, args) {
11611
11954
  }
11612
11955
 
11613
11956
  // src/adapters/knip.ts
11614
- import { existsSync as existsSync3 } from "node:fs";
11615
- import { join as join3 } from "node:path";
11957
+ import { existsSync as existsSync4 } from "node:fs";
11958
+ import { join as join4 } from "node:path";
11616
11959
 
11617
11960
  // src/files.ts
11618
- import { existsSync, readFileSync } from "node:fs";
11619
- import { join } from "node:path";
11961
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
11962
+ import { join as join2 } from "node:path";
11620
11963
  import { spawnSync } from "node:child_process";
11621
11964
 
11622
11965
  // node_modules/jsonc-parser/lib/esm/impl/scanner.js
@@ -12462,10 +12805,10 @@ function printParseErrorCode(code) {
12462
12805
 
12463
12806
  // src/files.ts
12464
12807
  function readJsonc(path) {
12465
- if (!existsSync(path))
12808
+ if (!existsSync2(path))
12466
12809
  throw new GateError(`${path} does not exist.`);
12467
12810
  const errors = [];
12468
- const value = parse2(readFileSync(path, "utf8"), errors, { allowTrailingComma: true });
12811
+ const value = parse2(readFileSync2(path, "utf8"), errors, { allowTrailingComma: true });
12469
12812
  const first = errors[0];
12470
12813
  if (first)
12471
12814
  throw new GateError(`cannot parse ${path}: ${printParseErrorCode(first.error)} at offset ${first.offset}.`);
@@ -12490,7 +12833,7 @@ function listFiles(cwd) {
12490
12833
  if (result.status !== 0) {
12491
12834
  throw new GateError(`cannot list files with git in ${cwd}: ${result.stderr.trim()}. Run the gate inside a Git work tree.`);
12492
12835
  }
12493
- return result.stdout.split("\x00").filter((file) => file !== "" && existsSync(join(cwd, file)));
12836
+ return result.stdout.split("\x00").filter((file) => file !== "" && existsSync2(join2(cwd, file)));
12494
12837
  }
12495
12838
 
12496
12839
  // src/knip-reporter.ts
@@ -12512,22 +12855,22 @@ function size(hints) {
12512
12855
  }
12513
12856
 
12514
12857
  // src/package.ts
12515
- import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync } from "node:fs";
12858
+ import { existsSync as existsSync3, readFileSync as readFileSync3, realpathSync } from "node:fs";
12516
12859
  import { spawn } from "node:child_process";
12517
12860
  import { once } from "node:events";
12518
- import { basename, dirname, extname, join as join2 } from "node:path";
12861
+ import { basename, dirname, extname, join as join3 } from "node:path";
12519
12862
  import { text } from "node:stream/consumers";
12520
12863
  import { fileURLToPath } from "node:url";
12521
12864
  var PACKAGE_NAME = "@shaulavo/standards";
12522
12865
  var MODULE_FILE = realpathSync(fileURLToPath(import.meta.url));
12523
12866
  var PACKAGE_ROOT = findPackageRoot(dirname(MODULE_FILE));
12524
- var manifest = readRecord(join2(PACKAGE_ROOT, "package.json"));
12867
+ var manifest = readRecord(join3(PACKAGE_ROOT, "package.json"));
12525
12868
  var PACKAGE_VERSION = stringField(manifest, "version");
12526
12869
  function presetPath(...parts) {
12527
- return join2(PACKAGE_ROOT, "config", ...parts);
12870
+ return join3(PACKAGE_ROOT, "config", ...parts);
12528
12871
  }
12529
12872
  function siblingModule(name) {
12530
- return join2(dirname(MODULE_FILE), `${name}${extname(MODULE_FILE)}`);
12873
+ return join3(dirname(MODULE_FILE), `${name}${extname(MODULE_FILE)}`);
12531
12874
  }
12532
12875
  function ownDependency(name) {
12533
12876
  const pin = pinnedVersion(name);
@@ -12555,10 +12898,10 @@ function findInstalled(name, from) {
12555
12898
  for (const dir of ancestors(from)) {
12556
12899
  if (basename(dir) === "node_modules")
12557
12900
  continue;
12558
- const candidate = join2(dir, "node_modules", name);
12559
- if (!existsSync2(join2(candidate, "package.json")))
12901
+ const candidate = join3(dir, "node_modules", name);
12902
+ if (!existsSync3(join3(candidate, "package.json")))
12560
12903
  continue;
12561
- const pkg = readRecord(join2(candidate, "package.json"));
12904
+ const pkg = readRecord(join3(candidate, "package.json"));
12562
12905
  return {
12563
12906
  name,
12564
12907
  version: stringField(pkg, "version"),
@@ -12572,8 +12915,8 @@ function binPath(pkg, command) {
12572
12915
  const relative = binEntry(pkg.manifest.bin, command);
12573
12916
  if (typeof relative !== "string")
12574
12917
  throw new GateError(`${pkg.name} ${pkg.version} has no "${command}" executable.`);
12575
- const path = join2(pkg.dir, relative);
12576
- if (!existsSync2(path))
12918
+ const path = join3(pkg.dir, relative);
12919
+ if (!existsSync3(path))
12577
12920
  throw new GateError(`${pkg.name} ${pkg.version} is missing its executable ${path}.`);
12578
12921
  return path;
12579
12922
  }
@@ -12610,8 +12953,8 @@ function ancestors(from) {
12610
12953
  }
12611
12954
  function findPackageRoot(from) {
12612
12955
  const root = ancestors(from).find((dir) => {
12613
- const path = join2(dir, "package.json");
12614
- return existsSync2(path) && JSON.parse(readFileSync2(path, "utf8")).name === PACKAGE_NAME;
12956
+ const path = join3(dir, "package.json");
12957
+ return existsSync3(path) && JSON.parse(readFileSync3(path, "utf8")).name === PACKAGE_NAME;
12615
12958
  });
12616
12959
  if (!root)
12617
12960
  throw new GateError(`cannot find the ${PACKAGE_NAME} package.json above ${from}.`);
@@ -12674,7 +13017,7 @@ var knip = {
12674
13017
  const tool = ownDependency("knip");
12675
13018
  const enforced = [
12676
13019
  "-c",
12677
- join3(cwd, relativeConfig(cwd)),
13020
+ join4(cwd, relativeConfig(cwd)),
12678
13021
  "--no-progress",
12679
13022
  "--treat-config-hints-as-errors",
12680
13023
  "--treat-tag-hints-as-errors",
@@ -12688,7 +13031,7 @@ var knip = {
12688
13031
  }
12689
13032
  };
12690
13033
  function relativeConfig(cwd) {
12691
- const found = CONFIG_FILES.find((file) => existsSync3(join3(cwd, file)));
13034
+ const found = CONFIG_FILES.find((file) => existsSync4(join4(cwd, file)));
12692
13035
  if (!found)
12693
13036
  throw new GateError(`missing knip.json in ${cwd}. Knip has no shared config; the project lists its entries there.`);
12694
13037
  return found;
@@ -12739,15 +13082,15 @@ function parseEvidence(text) {
12739
13082
 
12740
13083
  // src/adapters/oxfmt.ts
12741
13084
  var import_ignore = __toESM(require_ignore(), 1);
12742
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
12743
- import { basename as basename3, join as join5 } from "node:path";
13085
+ import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
13086
+ import { basename as basename3, join as join6 } from "node:path";
12744
13087
 
12745
13088
  // src/workspace.ts
12746
- import { existsSync as existsSync4 } from "node:fs";
12747
- import { join as join4 } from "node:path";
13089
+ import { existsSync as existsSync5 } from "node:fs";
13090
+ import { join as join5 } from "node:path";
12748
13091
 
12749
13092
  // node_modules/tinyglobby/dist/index.mjs
12750
- import { readdir, readdirSync, realpath, realpathSync as realpathSync2, stat, statSync } from "fs";
13093
+ import { readdir, readdirSync as readdirSync2, realpath, realpathSync as realpathSync2, stat, statSync } from "fs";
12751
13094
  import { isAbsolute, posix, resolve as resolve2 } from "path";
12752
13095
  import { fileURLToPath as fileURLToPath2 } from "url";
12753
13096
 
@@ -13548,7 +13891,7 @@ function getOptions(options) {
13548
13891
  opts.ignore = ensureStringArray(opts.ignore);
13549
13892
  opts.fs && (opts.fs = {
13550
13893
  readdir: opts.fs.readdir || readdir,
13551
- readdirSync: opts.fs.readdirSync || readdirSync,
13894
+ readdirSync: opts.fs.readdirSync || readdirSync2,
13552
13895
  realpath: opts.fs.realpath || realpath,
13553
13896
  realpathSync: opts.fs.realpathSync || realpathSync2,
13554
13897
  stat: opts.fs.stat || stat,
@@ -13580,12 +13923,12 @@ var DEPENDENCY_FIELDS = [
13580
13923
  "optionalDependencies"
13581
13924
  ];
13582
13925
  function workspacePackages(cwd) {
13583
- const rootPath = join4(cwd, "package.json");
13584
- if (!existsSync4(rootPath))
13926
+ const rootPath = join5(cwd, "package.json");
13927
+ if (!existsSync5(rootPath))
13585
13928
  return [];
13586
13929
  const root = readRecord(rootPath);
13587
13930
  const members = memberDirs(cwd, workspacePatterns(root, rootPath)).map((dir) => {
13588
- const manifest = readRecord(join4(cwd, dir, "package.json"));
13931
+ const manifest = readRecord(join5(cwd, dir, "package.json"));
13589
13932
  return { dir, name: packageName(manifest, dir), manifest };
13590
13933
  });
13591
13934
  return [{ dir: ".", name: packageName(root, "."), manifest: root }].concat(members);
@@ -13620,7 +13963,7 @@ function memberDirs(cwd, patterns) {
13620
13963
  cwd,
13621
13964
  onlyDirectories: true,
13622
13965
  ignore: exclude.concat("**/node_modules/**")
13623
- }).map((dir) => dir.replace(/\/$/, "")).filter((dir) => dir !== "" && dir !== "." && existsSync4(join4(cwd, dir, "package.json"))).toSorted();
13966
+ }).map((dir) => dir.replace(/\/$/, "")).filter((dir) => dir !== "" && dir !== "." && existsSync5(join5(cwd, dir, "package.json"))).toSorted();
13624
13967
  }
13625
13968
  function packageName(manifest, dir) {
13626
13969
  return typeof manifest.name === "string" ? manifest.name : dir;
@@ -13659,19 +14002,19 @@ var oxfmt = {
13659
14002
  const files = ownedFiles(cwd);
13660
14003
  rejectPrettier(cwd, files);
13661
14004
  rejectLocalConfig(files);
13662
- return `no Prettier; formatting uses the shared config${existsSync5(join5(cwd, OXFMT_IGNORE)) ? ` and ${OXFMT_IGNORE}` : ""}`;
14005
+ return `no Prettier; formatting uses the shared config${existsSync6(join6(cwd, OXFMT_IGNORE)) ? ` and ${OXFMT_IGNORE}` : ""}`;
13663
14006
  },
13664
14007
  async scan(cwd, args) {
13665
14008
  const tool = ownDependency("oxfmt");
13666
- const ignores = [".gitignore", OXFMT_IGNORE].filter((file) => existsSync5(join5(cwd, file))).flatMap((file) => ["--ignore-path", file]);
14009
+ const ignores = [".gitignore", OXFMT_IGNORE].filter((file) => existsSync6(join6(cwd, file))).flatMap((file) => ["--ignore-path", file]);
13667
14010
  const enforced = ["-c", presetPath("oxfmt", "base.json"), "--disable-nested-config"].concat(ignores);
13668
14011
  const run = await runTool("oxfmt", binPath(tool, "oxfmt"), enforced.concat(args), cwd);
13669
14012
  return parseReport2(run, `oxfmt ${tool.version}`);
13670
14013
  }
13671
14014
  };
13672
14015
  function ownedFiles(cwd) {
13673
- const path = join5(cwd, OXFMT_IGNORE);
13674
- const listed = existsSync5(path) ? import_ignore.default().add(readFileSync3(path, "utf8")) : import_ignore.default();
14016
+ const path = join6(cwd, OXFMT_IGNORE);
14017
+ const listed = existsSync6(path) ? import_ignore.default().add(readFileSync4(path, "utf8")) : import_ignore.default();
13675
14018
  return listFiles(cwd).filter((file) => !listed.ignores(file));
13676
14019
  }
13677
14020
  function rejectPrettier(cwd, files) {
@@ -13679,7 +14022,7 @@ function rejectPrettier(cwd, files) {
13679
14022
  if (config)
13680
14023
  throw new GateError(`${config} is a Prettier file. Oxfmt is the only formatter; delete it.`);
13681
14024
  for (const file of files.filter((entry) => basename3(entry) === "package.json")) {
13682
- const manifest = readRecord(join5(cwd, file));
14025
+ const manifest = readRecord(join6(cwd, file));
13683
14026
  if ("prettier" in manifest)
13684
14027
  throw new GateError(`${file} has a "prettier" key. Oxfmt is the only formatter; remove it.`);
13685
14028
  const dependency = dependencyNames(manifest).find((name) => PRETTIER_PACKAGE.test(name));
@@ -13718,17 +14061,17 @@ ${output}`);
13718
14061
  }
13719
14062
 
13720
14063
  // src/adapters/oxlint.ts
13721
- import { existsSync as existsSync7 } from "node:fs";
13722
- import { join as join7 } from "node:path";
14064
+ import { existsSync as existsSync8 } from "node:fs";
14065
+ import { join as join8 } from "node:path";
13723
14066
 
13724
14067
  // src/oxlint-config.ts
13725
- import { existsSync as existsSync6, realpathSync as realpathSync3 } from "node:fs";
13726
- import { dirname as dirname3, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
14068
+ import { existsSync as existsSync7, realpathSync as realpathSync3 } from "node:fs";
14069
+ import { dirname as dirname3, join as join7, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
13727
14070
  var OXLINT_CONFIG = ".oxlintrc.json";
13728
14071
  var EXTENDS_HINT = "./node_modules/@shaulavo/standards/config/oxlint/base.json";
13729
14072
  function oxlintChain(dir) {
13730
- const path = join6(dir, OXLINT_CONFIG);
13731
- if (!existsSync6(path)) {
14073
+ const path = join7(dir, OXLINT_CONFIG);
14074
+ if (!existsSync7(path)) {
13732
14075
  throw new GateError(`missing ${OXLINT_CONFIG} in ${dir}. Create it with "extends": ["${EXTENDS_HINT}"].`);
13733
14076
  }
13734
14077
  return load(realpathSync3(path), new Set);
@@ -13759,13 +14102,13 @@ function extendsOf(data, path) {
13759
14102
  }
13760
14103
  return entries.map((entry) => {
13761
14104
  const target = resolve3(dirname3(path), entry);
13762
- if (!existsSync6(target))
14105
+ if (!existsSync7(target))
13763
14106
  throw new GateError(`${path} extends ${entry}, which does not exist (${target}).`);
13764
14107
  return realpathSync3(target);
13765
14108
  });
13766
14109
  }
13767
14110
  function isShipped(path) {
13768
- return path.startsWith(realpathSync3(join6(PACKAGE_ROOT, "config")) + sep2);
14111
+ return path.startsWith(realpathSync3(join7(PACKAGE_ROOT, "config")) + sep2);
13769
14112
  }
13770
14113
 
13771
14114
  // src/adapters/oxlint.ts
@@ -13822,7 +14165,7 @@ var oxlint = {
13822
14165
  },
13823
14166
  async scan(cwd, args) {
13824
14167
  const tool = ownDependency("oxlint");
13825
- const config = join7(cwd, OXLINT_CONFIG);
14168
+ const config = join8(cwd, OXLINT_CONFIG);
13826
14169
  const enforced = [
13827
14170
  "-c",
13828
14171
  config,
@@ -13848,8 +14191,8 @@ function requireReactPreset(cwd, chain) {
13848
14191
  if (first && !reaches(chain, "react")) {
13849
14192
  throw new GateError(`${describe(first.dir, first.name)} depends on react, but ${OXLINT_CONFIG} does not extend ./node_modules/@shaulavo/standards/config/oxlint/react.json.`);
13850
14193
  }
13851
- for (const pkg of reactPackages.filter((entry) => entry.dir !== "." && existsSync7(join7(cwd, entry.dir, OXLINT_CONFIG)))) {
13852
- if (!reaches(oxlintChain(join7(cwd, pkg.dir)), "react")) {
14194
+ for (const pkg of reactPackages.filter((entry) => entry.dir !== "." && existsSync8(join8(cwd, entry.dir, OXLINT_CONFIG)))) {
14195
+ if (!reaches(oxlintChain(join8(cwd, pkg.dir)), "react")) {
13853
14196
  throw new GateError(`${describe(pkg.dir, pkg.name)} depends on react, but ${pkg.dir}/${OXLINT_CONFIG} does not reach the shared react.json.`);
13854
14197
  }
13855
14198
  }
@@ -13914,8 +14257,8 @@ function render(diagnostic) {
13914
14257
  }
13915
14258
 
13916
14259
  // src/adapters/tsc.ts
13917
- import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
13918
- import { isAbsolute as isAbsolute2, join as join8, sep as sep3 } from "node:path";
14260
+ import { existsSync as existsSync9, statSync as statSync2 } from "node:fs";
14261
+ import { isAbsolute as isAbsolute2, join as join9, sep as sep3 } from "node:path";
13919
14262
  var NATIVE_PREVIEW = "@typescript/native-preview";
13920
14263
  var PROJECT_FLAGS = ["p", "project"];
13921
14264
  var tsc = {
@@ -14029,9 +14372,9 @@ function rejectLooseArgs(args) {
14029
14372
  });
14030
14373
  }
14031
14374
  function projectConfig(cwd, project) {
14032
- const path = isAbsolute2(project) ? project : join8(cwd, project);
14033
- const config = existsSync8(path) && statSync2(path).isDirectory() ? join8(path, "tsconfig.json") : path;
14034
- if (!existsSync8(config))
14375
+ const path = isAbsolute2(project) ? project : join9(cwd, project);
14376
+ const config = existsSync9(path) && statSync2(path).isDirectory() ? join9(path, "tsconfig.json") : path;
14377
+ if (!existsSync9(config))
14035
14378
  throw new GateError(`missing ${project}. standards tsc always type-checks an explicit tsconfig.`);
14036
14379
  return config;
14037
14380
  }
@@ -14061,7 +14404,7 @@ function parseReport4(run, tool) {
14061
14404
  `);
14062
14405
  const summaryStart = lines.findLastIndex((line) => line.startsWith("Files:"));
14063
14406
  const body = summaryStart === -1 ? lines : lines.slice(0, summaryStart);
14064
- const listed = body.filter((line) => isAbsolute2(line) && existsSync8(line));
14407
+ const listed = body.filter((line) => isAbsolute2(line) && existsSync9(line));
14065
14408
  const inputs = listed.filter((line) => !line.split(sep3).includes("node_modules")).length;
14066
14409
  const report = body.filter((line) => !listed.includes(line)).join(`
14067
14410
  `).trim();
@@ -14096,13 +14439,13 @@ function parseSummary(lines) {
14096
14439
 
14097
14440
  // src/compatibility.ts
14098
14441
  var import_semver = __toESM(require_semver2(), 1);
14099
- import { existsSync as existsSync9 } from "node:fs";
14100
- import { join as join9 } from "node:path";
14442
+ import { existsSync as existsSync10 } from "node:fs";
14443
+ import { join as join10 } from "node:path";
14101
14444
  var STANDARDS_CONFIG = ".standards.json";
14102
14445
  var ALLOWED_KEYS = new Set(["$schema", "minVersion"]);
14103
14446
  function checkMinVersion(cwd, installedVersion = PACKAGE_VERSION) {
14104
- const path = join9(cwd, STANDARDS_CONFIG);
14105
- if (!existsSync9(path))
14447
+ const path = join10(cwd, STANDARDS_CONFIG);
14448
+ if (!existsSync10(path))
14106
14449
  return;
14107
14450
  const config = readRecord(path);
14108
14451
  validateMinVersionConfig(config, path, installedVersion);
@@ -14143,17 +14486,17 @@ function parseSemver(value) {
14143
14486
  // src/gates/actionlint.ts
14144
14487
  import { createHash } from "node:crypto";
14145
14488
  import {
14146
- existsSync as existsSync10,
14147
- mkdirSync,
14489
+ existsSync as existsSync11,
14490
+ mkdirSync as mkdirSync2,
14148
14491
  mkdtempSync,
14149
- readFileSync as readFileSync4,
14150
- renameSync,
14492
+ readFileSync as readFileSync5,
14493
+ renameSync as renameSync2,
14151
14494
  rmSync,
14152
- writeFileSync
14495
+ writeFileSync as writeFileSync2
14153
14496
  } from "node:fs";
14154
14497
  import { spawnSync as spawnSync2 } from "node:child_process";
14155
14498
  import { homedir, tmpdir } from "node:os";
14156
- import { basename as basename4, join as join10 } from "node:path";
14499
+ import { basename as basename4, join as join11 } from "node:path";
14157
14500
 
14158
14501
  // src/gates/tools.ts
14159
14502
  var ACTIONLINT_VERSION = "1.7.12";
@@ -14206,7 +14549,7 @@ async function actionlint(cwd, args) {
14206
14549
  }
14207
14550
  const tool = platformTool();
14208
14551
  const archive = await verifiedArchive(tool);
14209
- const dir = mkdtempSync(join10(tmpdir(), "standards-actionlint-"));
14552
+ const dir = mkdtempSync(join11(tmpdir(), "standards-actionlint-"));
14210
14553
  try {
14211
14554
  const bin = extract(archive, tool, dir);
14212
14555
  const flags = ["-format", "{{json .}}", "-verbose", "-no-color", "-shellcheck=", "-pyflakes="];
@@ -14224,10 +14567,10 @@ function platformTool() {
14224
14567
  throw new GateError(`no pinned actionlint archive for ${platform}.`);
14225
14568
  }
14226
14569
  async function verifiedArchive(tool) {
14227
- const cache = join10(process.env.XDG_CACHE_HOME || join10(homedir(), ".cache"), "standards");
14228
- const path = join10(cache, basename4(tool.url));
14229
- if (existsSync10(path)) {
14230
- if (sha256(readFileSync4(path)) === tool.sha256)
14570
+ const cache = join11(process.env.XDG_CACHE_HOME || join11(homedir(), ".cache"), "standards");
14571
+ const path = join11(cache, basename4(tool.url));
14572
+ if (existsSync11(path)) {
14573
+ if (sha256(readFileSync5(path)) === tool.sha256)
14231
14574
  return path;
14232
14575
  throw new GateError(`the cached archive ${path} does not match the pinned sha256 ${tool.sha256}. Delete it and run again.`);
14233
14576
  }
@@ -14236,10 +14579,10 @@ async function verifiedArchive(tool) {
14236
14579
  if (digest !== tool.sha256) {
14237
14580
  throw new GateError(`${tool.url} has sha256 ${digest}, but ${tool.name} ${tool.version} is pinned to ${tool.sha256}.`);
14238
14581
  }
14239
- mkdirSync(cache, { recursive: true });
14582
+ mkdirSync2(cache, { recursive: true });
14240
14583
  const partial = `${path}.${process.pid}.partial`;
14241
- writeFileSync(partial, bytes);
14242
- renameSync(partial, path);
14584
+ writeFileSync2(partial, bytes);
14585
+ renameSync2(partial, path);
14243
14586
  return path;
14244
14587
  }
14245
14588
  async function download(url) {
@@ -14252,8 +14595,8 @@ async function download(url) {
14252
14595
  }
14253
14596
  function extract(archive, tool, dir) {
14254
14597
  const result = spawnSync2("tar", ["-xzf", archive, "-C", dir, tool.bin], { encoding: "utf8" });
14255
- const bin = join10(dir, tool.bin);
14256
- if (result.status === 0 && existsSync10(bin))
14598
+ const bin = join11(dir, tool.bin);
14599
+ if (result.status === 0 && existsSync11(bin))
14257
14600
  return bin;
14258
14601
  throw new GateError(`cannot extract ${tool.bin} from ${archive}: ${result.stderr || result.error?.message}`);
14259
14602
  }
@@ -14311,19 +14654,19 @@ function isProblem(value) {
14311
14654
  }
14312
14655
 
14313
14656
  // src/gates/doctor.ts
14314
- import { existsSync as existsSync15 } from "node:fs";
14315
- import { join as join14 } from "node:path";
14657
+ import { existsSync as existsSync16 } from "node:fs";
14658
+ import { join as join15 } from "node:path";
14316
14659
 
14317
14660
  // src/gates/contract.ts
14318
14661
  import {
14319
- existsSync as existsSync11,
14662
+ existsSync as existsSync12,
14320
14663
  lstatSync,
14321
- readdirSync as readdirSync2,
14322
- readFileSync as readFileSync5,
14664
+ readdirSync as readdirSync3,
14665
+ readFileSync as readFileSync6,
14323
14666
  readlinkSync,
14324
14667
  realpathSync as realpathSync4
14325
14668
  } from "node:fs";
14326
- import { join as join11, resolve as resolve4, sep as sep4 } from "node:path";
14669
+ import { join as join12, resolve as resolve4, sep as sep4 } from "node:path";
14327
14670
 
14328
14671
  // node_modules/yaml/dist/index.js
14329
14672
  var composer = require_composer();
@@ -14398,15 +14741,15 @@ var CONTRACT_CHECKS = [
14398
14741
  { label: "renovate", run: renovateConfig }
14399
14742
  ];
14400
14743
  function isSelfCheckout(cwd) {
14401
- const path = join11(cwd, "package.json");
14402
- if (!existsSync11(path))
14744
+ const path = join12(cwd, "package.json");
14745
+ if (!existsSync12(path))
14403
14746
  return false;
14404
14747
  const manifest = readRecord(path);
14405
14748
  return manifest.name === PACKAGE_NAME2;
14406
14749
  }
14407
14750
  function checkScript(cwd) {
14408
- const path = join11(cwd, "package.json");
14409
- if (!existsSync11(path)) {
14751
+ const path = join12(cwd, "package.json");
14752
+ if (!existsSync12(path)) {
14410
14753
  throw new GateError("missing package.json (docs/repo-contract.md#entry-points).");
14411
14754
  }
14412
14755
  const manifest = readRecord(path);
@@ -14418,15 +14761,15 @@ function checkScript(cwd) {
14418
14761
  return 'package.json defines a "check" script';
14419
14762
  }
14420
14763
  function agentsDoc(cwd) {
14421
- const agentsPath = join11(cwd, "AGENTS.md");
14422
- if (!existsSync11(agentsPath)) {
14764
+ const agentsPath = join12(cwd, "AGENTS.md");
14765
+ if (!existsSync12(agentsPath)) {
14423
14766
  throw new GateError("missing AGENTS.md (docs/repo-contract.md#entry-points).");
14424
14767
  }
14425
- const content = readFileSync5(agentsPath, "utf8");
14768
+ const content = readFileSync6(agentsPath, "utf8");
14426
14769
  if (!/^## Verification map\s*$/m.test(content)) {
14427
14770
  throw new GateError('AGENTS.md has no "## Verification map" section (docs/repo-contract.md#entry-points).');
14428
14771
  }
14429
- const claudePath = join11(cwd, "CLAUDE.md");
14772
+ const claudePath = join12(cwd, "CLAUDE.md");
14430
14773
  const stat = lstatSync(claudePath, { throwIfNoEntry: false });
14431
14774
  if (!stat?.isSymbolicLink()) {
14432
14775
  throw new GateError("CLAUDE.md must be a symlink pointing to AGENTS.md (docs/repo-contract.md#entry-points).");
@@ -14458,8 +14801,8 @@ function duplicatedTools(manifest) {
14458
14801
  return OWNED_TOOLS.filter((tool) => names.has(tool));
14459
14802
  }
14460
14803
  function tsconfigPreset(cwd) {
14461
- const path = join11(cwd, "tsconfig.json");
14462
- if (!existsSync11(path)) {
14804
+ const path = join12(cwd, "tsconfig.json");
14805
+ if (!existsSync12(path)) {
14463
14806
  throw new GateError("missing tsconfig.json (docs/repo-contract.md#shared-config).");
14464
14807
  }
14465
14808
  const self = isSelfCheckout(cwd);
@@ -14493,10 +14836,10 @@ function localTsconfigTarget(dir, entry) {
14493
14836
  if (!entry.startsWith("."))
14494
14837
  return;
14495
14838
  const direct = resolve4(dir, entry);
14496
- if (existsSync11(direct))
14839
+ if (existsSync12(direct))
14497
14840
  return direct;
14498
14841
  const withJson = `${direct}.json`;
14499
- return existsSync11(withJson) ? withJson : undefined;
14842
+ return existsSync12(withJson) ? withJson : undefined;
14500
14843
  }
14501
14844
  function extendsList(value, path) {
14502
14845
  if (value === undefined)
@@ -14513,23 +14856,23 @@ function matchesSharedTsconfig(cwd, entry, self) {
14513
14856
  if (!entry.startsWith("."))
14514
14857
  return false;
14515
14858
  const candidate = resolve4(cwd, entry);
14516
- if (!existsSync11(candidate))
14859
+ if (!existsSync12(candidate))
14517
14860
  return false;
14518
- const shippedDir = realpathSync4(join11(PACKAGE_ROOT, "config", "tsconfig")) + sep4;
14861
+ const shippedDir = realpathSync4(join12(PACKAGE_ROOT, "config", "tsconfig")) + sep4;
14519
14862
  return realpathSync4(candidate).startsWith(shippedDir);
14520
14863
  }
14521
14864
  function workflowPins(cwd) {
14522
- const workflowsDir = join11(cwd, ".github", "workflows");
14523
- if (!existsSync11(workflowsDir)) {
14865
+ const workflowsDir = join12(cwd, ".github", "workflows");
14866
+ if (!existsSync12(workflowsDir)) {
14524
14867
  return "no workflow files (private repo or local-only checks)";
14525
14868
  }
14526
- const files = readdirSync2(workflowsDir).filter((file) => file.endsWith(".yml") || file.endsWith(".yaml")).toSorted();
14869
+ const files = readdirSync3(workflowsDir).filter((file) => file.endsWith(".yml") || file.endsWith(".yaml")).toSorted();
14527
14870
  if (files.length === 0) {
14528
14871
  return "no workflow files (private repo or local-only checks)";
14529
14872
  }
14530
14873
  const refs = files.flatMap((file) => {
14531
14874
  const relPath = `.github/workflows/${file}`;
14532
- return extractWorkflowUses(readFileSync5(join11(workflowsDir, file), "utf8"), relPath).map((entry) => ({ file: relPath, entry }));
14875
+ return extractWorkflowUses(readFileSync6(join12(workflowsDir, file), "utf8"), relPath).map((entry) => ({ file: relPath, entry }));
14533
14876
  });
14534
14877
  const violations = refs.flatMap(({ file, entry }) => {
14535
14878
  const reason = workflowPinProblem(entry);
@@ -14603,8 +14946,8 @@ function workflowPinProblem(entry) {
14603
14946
  return;
14604
14947
  }
14605
14948
  function renovateConfig(cwd) {
14606
- const path = join11(cwd, "renovate.json");
14607
- if (!existsSync11(path)) {
14949
+ const path = join12(cwd, "renovate.json");
14950
+ if (!existsSync12(path)) {
14608
14951
  throw new GateError('missing renovate.json extending "github>ShaulLavo/standards//renovate/default" (docs/repo-contract.md#staying-current).');
14609
14952
  }
14610
14953
  const config = readRecord(path);
@@ -14617,16 +14960,16 @@ function renovateConfig(cwd) {
14617
14960
  }
14618
14961
 
14619
14962
  // src/gates/dupes.ts
14620
- import { existsSync as existsSync13, mkdtempSync as mkdtempSync2, readFileSync as readFileSync7, rmSync as rmSync3 } from "node:fs";
14963
+ import { existsSync as existsSync14, mkdtempSync as mkdtempSync2, readFileSync as readFileSync8, rmSync as rmSync3 } from "node:fs";
14621
14964
  import { tmpdir as tmpdir2 } from "node:os";
14622
- import { isAbsolute as isAbsolute3, join as join12, relative as relative5 } from "node:path";
14965
+ import { isAbsolute as isAbsolute3, join as join13, relative as relative5 } from "node:path";
14623
14966
 
14624
14967
  // src/baseline/gate.ts
14625
- import { readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
14968
+ import { readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
14626
14969
  import { relative as relative4 } from "node:path";
14627
14970
 
14628
14971
  // src/baseline/base.ts
14629
- import { existsSync as existsSync12, realpathSync as realpathSync5 } from "node:fs";
14972
+ import { existsSync as existsSync13, realpathSync as realpathSync5 } from "node:fs";
14630
14973
  import { spawnSync as spawnSync3 } from "node:child_process";
14631
14974
  import { relative as relative3 } from "node:path";
14632
14975
  function readAtBase(cwd, file, env = process.env) {
@@ -14700,7 +15043,7 @@ function eventCommit(value, name) {
14700
15043
  }
14701
15044
  function eventPayload(env) {
14702
15045
  const path = env.GITHUB_EVENT_PATH;
14703
- if (path === undefined || !existsSync12(path)) {
15046
+ if (path === undefined || !existsSync13(path)) {
14704
15047
  throw new GateError("GITHUB_EVENT_PATH does not name the event payload, so the comparison base is unknown.");
14705
15048
  }
14706
15049
  return readRecord(path);
@@ -14961,7 +15304,7 @@ function judgeBaseline(produced, cwd, baselinePath, shrinking) {
14961
15304
  }
14962
15305
  function readBaseline(path, display) {
14963
15306
  try {
14964
- return readFileSync6(path, "utf8");
15307
+ return readFileSync7(path, "utf8");
14965
15308
  } catch (error) {
14966
15309
  if (isRecord(error) && error.code === "ENOENT")
14967
15310
  return null;
@@ -14982,8 +15325,8 @@ function shrunk(scan, text, display) {
14982
15325
  function replaceFile(path, text, display) {
14983
15326
  const partial = `${path}.${process.pid}.partial`;
14984
15327
  try {
14985
- writeFileSync2(partial, text);
14986
- renameSync2(partial, path);
15328
+ writeFileSync3(partial, text);
15329
+ renameSync3(partial, path);
14987
15330
  } catch (error) {
14988
15331
  rmSync2(partial, { force: true });
14989
15332
  throw new GateError(`cannot write ${display}: ${errorMessage(error)}.`);
@@ -15019,7 +15362,7 @@ function invalidMessage(subject, diagnostics) {
15019
15362
 
15020
15363
  // src/gates/dupes.ts
15021
15364
  var CONFIG = ".jscpd.json";
15022
- var DUPES_BASELINE = join12(".baselines", "dupes.json");
15365
+ var DUPES_BASELINE = join13(".baselines", "dupes.json");
15023
15366
  var FINGERPRINT = "jscpdCloneHash/v1";
15024
15367
  var REPORT = "jscpd-report";
15025
15368
  var ALLOWED_SETTINGS = new Set([
@@ -15075,25 +15418,25 @@ async function dupes(cwd, args) {
15075
15418
  }
15076
15419
  dupesPreflight(cwd);
15077
15420
  const produced = await scanDupes(cwd);
15078
- return judgeBaseline(produced, cwd, join12(cwd, DUPES_BASELINE), args.includes("--shrink"));
15421
+ return judgeBaseline(produced, cwd, join13(cwd, DUPES_BASELINE), args.includes("--shrink"));
15079
15422
  }
15080
15423
  function dupesPreflight(cwd) {
15081
- const path = join12(cwd, CONFIG);
15082
- if (!existsSync13(path))
15424
+ const path = join13(cwd, CONFIG);
15425
+ if (!existsSync14(path))
15083
15426
  throw new GateError(`missing ${CONFIG} in ${cwd}. It sets the scope and thresholds.`);
15084
15427
  const setting = Object.keys(readRecord(path)).find((key) => !ALLOWED_SETTINGS.has(key));
15085
15428
  if (setting !== undefined) {
15086
15429
  const reason = SETTING_REASONS[setting] ?? "standards dupes does not accept this setting";
15087
15430
  throw new GateError(`${CONFIG} sets "${setting}": ${reason}.`);
15088
15431
  }
15089
- const mode = existsSync13(join12(cwd, DUPES_BASELINE)) ? `baseline ${DUPES_BASELINE}` : "zero mode";
15432
+ const mode = existsSync14(join13(cwd, DUPES_BASELINE)) ? `baseline ${DUPES_BASELINE}` : "zero mode";
15090
15433
  return `${CONFIG} sets scope and thresholds only; ${mode}`;
15091
15434
  }
15092
15435
  async function scanDupes(cwd) {
15093
15436
  const tool = ownDependency("jscpd");
15094
- const output = mkdtempSync2(join12(tmpdir2(), "standards-jscpd-"));
15437
+ const output = mkdtempSync2(join13(tmpdir2(), "standards-jscpd-"));
15095
15438
  try {
15096
- const enforced = ["-c", join12(cwd, CONFIG), "-r", "sarif,json", "-o", output];
15439
+ const enforced = ["-c", join13(cwd, CONFIG), "-r", "sarif,json", "-o", output];
15097
15440
  const flags = [
15098
15441
  "--report-name",
15099
15442
  REPORT,
@@ -15110,9 +15453,9 @@ async function scanDupes(cwd) {
15110
15453
  }
15111
15454
  }
15112
15455
  function parseReports(run, output, cwd, version) {
15113
- const sarifPath = join12(output, `${REPORT}.sarif`);
15114
- const jsonPath = join12(output, `${REPORT}.json`);
15115
- if (!existsSync13(sarifPath) || !existsSync13(jsonPath)) {
15456
+ const sarifPath = join13(output, `${REPORT}.sarif`);
15457
+ const jsonPath = join13(output, `${REPORT}.json`);
15458
+ if (!existsSync14(sarifPath) || !existsSync14(jsonPath)) {
15116
15459
  const printed = (run.stdout + run.stderr).trim();
15117
15460
  throw new GateError(`jscpd failed with exit code ${run.exitCode} and wrote no report:
15118
15461
  ${printed}`);
@@ -15163,7 +15506,7 @@ ${unexpected.join(`
15163
15506
  }
15164
15507
  function readReport(path) {
15165
15508
  try {
15166
- const value = JSON.parse(readFileSync7(path, "utf8"));
15509
+ const value = JSON.parse(readFileSync8(path, "utf8"));
15167
15510
  if (isRecord(value))
15168
15511
  return value;
15169
15512
  } catch {}
@@ -15229,12 +15572,12 @@ function groupClones(clones) {
15229
15572
  }
15230
15573
 
15231
15574
  // src/gates/structure.ts
15232
- import { existsSync as existsSync14 } from "node:fs";
15233
- import { join as join13, resolve as resolve5 } from "node:path";
15575
+ import { existsSync as existsSync15 } from "node:fs";
15576
+ import { join as join14, resolve as resolve5 } from "node:path";
15234
15577
  var SCOPE_KEYS = new Set(["projects", "ignore"]);
15235
15578
  var EXEMPTION_FILE = ".unknot.allow";
15236
15579
  var NO_SOURCES = "no TypeScript or JavaScript sources";
15237
- var STRUCTURE_BASELINE = join13(".baselines", "structure.json");
15580
+ var STRUCTURE_BASELINE = join14(".baselines", "structure.json");
15238
15581
  var MEASURES = {
15239
15582
  "module-cycle": /^(\d+) modules? import each other/,
15240
15583
  "import-cycle": /^(\d+) files? import each other/,
@@ -15252,14 +15595,14 @@ async function structure(cwd, args) {
15252
15595
  const dir = scanDir(cwd, args.filter((arg) => arg !== "--shrink"));
15253
15596
  structurePreflight(dir);
15254
15597
  const produced = await scanStructure(dir);
15255
- return judgeBaseline(produced, dir, join13(dir, STRUCTURE_BASELINE), shrinking);
15598
+ return judgeBaseline(produced, dir, join14(dir, STRUCTURE_BASELINE), shrinking);
15256
15599
  }
15257
15600
  function structurePreflight(dir) {
15258
- if (existsSync14(join13(dir, EXEMPTION_FILE))) {
15601
+ if (existsSync15(join14(dir, EXEMPTION_FILE))) {
15259
15602
  throw new GateError(`${EXEMPTION_FILE} is an exemption file. standards structure requires zero findings; fix them instead.`);
15260
15603
  }
15261
- const config = join13(dir, ".unknot.json");
15262
- if (!existsSync14(config))
15604
+ const config = join14(dir, ".unknot.json");
15605
+ if (!existsSync15(config))
15263
15606
  return "Unknot default rules, no exemption files";
15264
15607
  const key = Object.keys(readRecord(config)).find((name) => !SCOPE_KEYS.has(name));
15265
15608
  if (key)
@@ -15273,7 +15616,7 @@ function scanDir(cwd, args) {
15273
15616
  if (args.length > 1)
15274
15617
  throw new GateError(`rejected arguments ${args.join(" ")}: standards structure accepts one directory.`);
15275
15618
  const dir = resolve5(cwd, args[0] ?? ".");
15276
- if (!existsSync14(dir))
15619
+ if (!existsSync15(dir))
15277
15620
  throw new GateError(`${dir} does not exist.`);
15278
15621
  return dir;
15279
15622
  }
@@ -15364,13 +15707,19 @@ function doctor(cwd, args) {
15364
15707
  process.stdout.write(`${results.map((result) => result.line).join(`
15365
15708
  `)}
15366
15709
  `);
15367
- const failed = results.filter((result) => !result.ok).length;
15368
- if (failed === 0) {
15710
+ const failed = results.filter((result) => !result.ok);
15711
+ if (failed.length === 0) {
15712
+ recordGateNote({ summary: `${results.length} checks` });
15369
15713
  process.stdout.write(`standards doctor: ${results.length} checks passed.
15370
15714
  `);
15371
15715
  return EXIT.pass;
15372
15716
  }
15373
- process.stderr.write(`standards doctor: ${failed} of ${results.length} checks failed.
15717
+ recordGateNote({
15718
+ summary: `${failed.length} of ${results.length} checks failed`,
15719
+ excerpt: failed.map((result) => result.line).join(`
15720
+ `)
15721
+ });
15722
+ process.stderr.write(`standards doctor: ${failed.length} of ${results.length} checks failed.
15374
15723
  `);
15375
15724
  return EXIT.findings;
15376
15725
  }
@@ -15384,8 +15733,8 @@ function outcome(check, cwd) {
15384
15733
  }
15385
15734
  }
15386
15735
  function lockfileCheck(cwd) {
15387
- const path = join14(cwd, "package.json");
15388
- const manifest = existsSync15(path) ? readRecord(path) : {};
15736
+ const path = join15(cwd, "package.json");
15737
+ const manifest = existsSync16(path) ? readRecord(path) : {};
15389
15738
  if (manifest.name === PACKAGE_NAME3)
15390
15739
  return `this is the ${PACKAGE_NAME3} checkout at ${PACKAGE_ROOT}`;
15391
15740
  const locked = lockedPackage(cwd);
@@ -15407,10 +15756,10 @@ function pinDrift(recorded) {
15407
15756
  return `${name} ${String(lockedDeps[name] ?? "missing")} for ${PACKAGE_NAME3}, but it pins ${String(pinnedDependencies()[name])}`;
15408
15757
  }
15409
15758
  function lockedPackage(cwd) {
15410
- if (existsSync15(join14(cwd, "bun.lock")))
15411
- return bunLocked(readJsonc(join14(cwd, "bun.lock")));
15412
- if (existsSync15(join14(cwd, "package-lock.json"))) {
15413
- return npmLocked(readRecord(join14(cwd, "package-lock.json")));
15759
+ if (existsSync16(join15(cwd, "bun.lock")))
15760
+ return bunLocked(readJsonc(join15(cwd, "bun.lock")));
15761
+ if (existsSync16(join15(cwd, "package-lock.json"))) {
15762
+ return npmLocked(readRecord(join15(cwd, "package-lock.json")));
15414
15763
  }
15415
15764
  throw new GateError(`no bun.lock or package-lock.json in ${cwd}. Commit a lockfile so the standards version is pinned.`);
15416
15765
  }
@@ -20937,16 +21286,16 @@ var import_validate_npm_package_name = __toESM(require_lib(), 1);
20937
21286
  import { spawn as spawn2, spawnSync as spawnSync4 } from "node:child_process";
20938
21287
  import { once as once2 } from "node:events";
20939
21288
  import {
20940
- existsSync as existsSync16,
20941
- mkdirSync as mkdirSync2,
21289
+ existsSync as existsSync17,
21290
+ mkdirSync as mkdirSync3,
20942
21291
  mkdtempSync as mkdtempSync3,
20943
- readdirSync as readdirSync3,
20944
- renameSync as renameSync3,
21292
+ readdirSync as readdirSync4,
21293
+ renameSync as renameSync4,
20945
21294
  rmdirSync,
20946
21295
  rmSync as rmSync4,
20947
21296
  statSync as statSync3
20948
21297
  } from "node:fs";
20949
- import { basename as basename5, dirname as dirname4, join as join15, resolve as resolve6 } from "node:path";
21298
+ import { basename as basename5, dirname as dirname4, join as join16, resolve as resolve6 } from "node:path";
20950
21299
  var DEFAULT_TEMPLATE = "https://github.com/ShaulLavo/standards.git";
20951
21300
  var PINNED_COPIER = "9.19.1";
20952
21301
  var MIN_COPIER = "9.6.0";
@@ -20973,7 +21322,7 @@ async function newProject(cwd, args) {
20973
21322
  await renderIntoTarget({ cwd, options, templateSource, vcsRef, projectName, targetDir });
20974
21323
  const displayArgs = buildCopierArgs({ options, templateSource, vcsRef, projectName, targetDir });
20975
21324
  ran.push({ command: formatCommand("copier", displayArgs), result: "rendered template" });
20976
- if (!existsSync16(join15(targetDir, ".git"))) {
21325
+ if (!existsSync17(join16(targetDir, ".git"))) {
20977
21326
  const gitInit = await runProcess("git", "git", ["init", "-q"], targetDir);
20978
21327
  if (gitInit.exitCode !== 0) {
20979
21328
  throw new GateError(`git init failed: ${(gitInit.stderr + gitInit.stdout).trim()}`);
@@ -20999,8 +21348,8 @@ function validatePackageName(name) {
20999
21348
  throw new GateError(`invalid package name "${name}": ${reasons.join("; ")}.`);
21000
21349
  }
21001
21350
  async function renderIntoTarget(input) {
21002
- mkdirSync2(dirname4(input.targetDir), { recursive: true });
21003
- const stagingDir = mkdtempSync3(join15(dirname4(input.targetDir), ".standards-new-"));
21351
+ mkdirSync3(dirname4(input.targetDir), { recursive: true });
21352
+ const stagingDir = mkdtempSync3(join16(dirname4(input.targetDir), ".standards-new-"));
21004
21353
  try {
21005
21354
  const copierArgs = buildCopierArgs({
21006
21355
  options: input.options,
@@ -21017,16 +21366,16 @@ async function renderIntoTarget(input) {
21017
21366
  }
21018
21367
  }
21019
21368
  function requireRenderedMinVersion(dir) {
21020
- const manifestPath = join15(dir, STANDARDS_CONFIG);
21021
- if (!existsSync16(manifestPath)) {
21369
+ const manifestPath = join16(dir, STANDARDS_CONFIG);
21370
+ if (!existsSync17(manifestPath)) {
21022
21371
  throw new GateError(`rendered template is missing ${STANDARDS_CONFIG}.`);
21023
21372
  }
21024
21373
  checkMinVersion(dir);
21025
21374
  }
21026
21375
  function moveStagingToTarget(stagingDir, targetDir) {
21027
- if (existsSync16(targetDir))
21376
+ if (existsSync17(targetDir))
21028
21377
  rmdirSync(targetDir);
21029
- renameSync3(stagingDir, targetDir);
21378
+ renameSync4(stagingDir, targetDir);
21030
21379
  }
21031
21380
  function parseArgs2(args) {
21032
21381
  let dir;
@@ -21175,12 +21524,12 @@ function checkCopierVersion(output) {
21175
21524
  }
21176
21525
  function validateTargetDir(cwd, dir) {
21177
21526
  const target = resolve6(cwd, dir);
21178
- if (!existsSync16(target))
21527
+ if (!existsSync17(target))
21179
21528
  return target;
21180
21529
  if (!statSync3(target).isDirectory()) {
21181
21530
  throw new GateError(`${target} exists and is not a directory.`);
21182
21531
  }
21183
- if (readdirSync3(target).length > 0) {
21532
+ if (readdirSync4(target).length > 0) {
21184
21533
  throw new GateError(`${target} is not empty. standards new is for new projects only; adopt an existing repository by hand (docs/repo-contract.md#adoption).`);
21185
21534
  }
21186
21535
  return target;
@@ -21233,23 +21582,23 @@ function formatCommand(command, args) {
21233
21582
  return [command].concat(args).join(" ");
21234
21583
  }
21235
21584
  function printSummary(targetDir, ran, noInstall) {
21236
- const lines = [`Created project in ${targetDir}`, "", "Commands run:"].concat(ran.map((entry) => ` - ${entry.command} (${entry.result})`)).concat(["", "Next steps:", ` cd ${targetDir}`]).concat(noInstall ? [" bun install"] : []).concat([" bun run check", ' git add . && git commit -m "Initial commit"']).concat(existsSync16(join15(targetDir, "lefthook.yml")) ? [" lefthook install # optional: enable local pre-commit and pre-push hooks"] : []);
21585
+ const lines = [`Created project in ${targetDir}`, "", "Commands run:"].concat(ran.map((entry) => ` - ${entry.command} (${entry.result})`)).concat(["", "Next steps:", ` cd ${targetDir}`]).concat(noInstall ? [" bun install"] : []).concat([" bun run check", ' git add . && git commit -m "Initial commit"']).concat(existsSync17(join16(targetDir, "lefthook.yml")) ? [" lefthook install # optional: enable local pre-commit and pre-push hooks"] : []);
21237
21586
  process.stdout.write(`${lines.join(`
21238
21587
  `)}
21239
21588
  `);
21240
21589
  }
21241
21590
 
21242
21591
  // src/gates/publint.ts
21243
- import { existsSync as existsSync17, readFileSync as readFileSync8 } from "node:fs";
21592
+ import { existsSync as existsSync18, readFileSync as readFileSync9 } from "node:fs";
21244
21593
  import { createRequire as createRequire3 } from "node:module";
21245
- import { join as join16, resolve as resolve7 } from "node:path";
21594
+ import { join as join17, resolve as resolve7 } from "node:path";
21246
21595
  import { pathToFileURL } from "node:url";
21247
21596
  var FAILING = new Set(["error", "warning"]);
21248
21597
  async function publint(cwd, args) {
21249
21598
  const tarball = tarballArg(cwd, args);
21250
21599
  const tool = ownDependency("publint");
21251
21600
  const api = await load2(tool.dir);
21252
- const unpacked = await run("unpack the tarball", () => api.unpack(new Uint8Array(readFileSync8(tarball)).buffer));
21601
+ const unpacked = await run("unpack the tarball", () => api.unpack(new Uint8Array(readFileSync9(tarball)).buffer));
21253
21602
  const result = await run("lint the tarball", () => api.publint({ pack: { files: unpacked.files }, pkgDir: unpacked.rootDir, level: "suggestion" }));
21254
21603
  if (!Array.isArray(result.messages) || !result.messages.every(isMessage)) {
21255
21604
  throw new GateError("publint returned messages without a code and type.");
@@ -21270,12 +21619,12 @@ function tarballArg(cwd, args) {
21270
21619
  throw new GateError("standards publint takes one argument: the .tgz the build packed. It never packs one itself.");
21271
21620
  }
21272
21621
  const tarball = resolve7(cwd, path);
21273
- if (!existsSync17(tarball))
21622
+ if (!existsSync18(tarball))
21274
21623
  throw new GateError(`${tarball} does not exist.`);
21275
21624
  return tarball;
21276
21625
  }
21277
21626
  async function load2(dir) {
21278
- const require2 = createRequire3(join16(dir, "package.json"));
21627
+ const require2 = createRequire3(join17(dir, "package.json"));
21279
21628
  const imported = await Promise.all(["publint", "publint/utils", "@publint/pack"].map((name) => import(pathToFileURL(require2.resolve(name)).href)));
21280
21629
  const [main, utils, pack] = imported.map((module) => isRecord(module) ? module : {});
21281
21630
  const api = { publint: main?.publint, formatMessage: utils?.formatMessage, unpack: pack?.unpack };
@@ -21294,6 +21643,374 @@ function isMessage(value) {
21294
21643
  return isRecord(value) && typeof value.code === "string" && typeof value.type === "string";
21295
21644
  }
21296
21645
 
21646
+ // src/gates/report.ts
21647
+ import { appendFileSync, existsSync as existsSync19, mkdirSync as mkdirSync4, readFileSync as readFileSync10 } from "node:fs";
21648
+ import { dirname as dirname5 } from "node:path";
21649
+ var VALID_STATUSES = new Set(["success", "failure", "cancelled"]);
21650
+ var MARKER_PATTERN = /^[a-z0-9._-]+$/;
21651
+ var PR_NUMBER2 = /^[1-9]\d*$/;
21652
+ var PR_EVENTS = new Set(["pull_request", "pull_request_target"]);
21653
+ var NEXT_LINK_PATTERN = /<([^>]+)>;\s*rel="next"/;
21654
+ var MAX_COMMENT_PAGES = 50;
21655
+ var DEFAULT_API_URL = "https://api.github.com";
21656
+ var DEFAULT_SERVER_URL = "https://github.com";
21657
+ var USAGE = "usage: standards report --status <success|failure|cancelled> [--dir <path>] [--summary-file <path>] [--comment] [--repo <owner/repo>] [--pr <number>] [--sha <sha>] [--run-url <url>] [--marker <id>]";
21658
+ async function report3(_cwd, args) {
21659
+ const options = parseArgs3(args);
21660
+ const env = process.env;
21661
+ const event = readPullRequestEvent(env);
21662
+ const dir = options.dir ?? nonEmpty(env.STANDARDS_REPORT_DIR);
21663
+ const summaryFile = options.summaryFile ?? nonEmpty(env.GITHUB_STEP_SUMMARY);
21664
+ const repo = options.repo ?? envRepo(env);
21665
+ const serverUrl = trimTrailingSlashes(nonEmpty(env.GITHUB_SERVER_URL) ?? DEFAULT_SERVER_URL);
21666
+ const runUrl = options.runUrl ?? defaultRunUrl(env);
21667
+ const pr = options.pr ?? event.pr;
21668
+ const sha = options.sha ?? event.sha ?? nonEmpty(env.GITHUB_SHA);
21669
+ const loaded = readReportDir(dir);
21670
+ for (const problem of loaded.invalid) {
21671
+ process.stderr.write(`standards report: invalid record ${problem.file}: ${problem.reason}.
21672
+ `);
21673
+ }
21674
+ const markdown = renderReport({
21675
+ status: options.status,
21676
+ marker: options.marker,
21677
+ gates: loaded.gates,
21678
+ invalid: loaded.invalid,
21679
+ sha,
21680
+ repo,
21681
+ serverUrl,
21682
+ runUrl
21683
+ });
21684
+ if (summaryFile !== undefined) {
21685
+ mkdirSync4(dirname5(summaryFile), { recursive: true });
21686
+ appendFileSync(summaryFile, markdown);
21687
+ }
21688
+ if (!options.comment)
21689
+ return EXIT.pass;
21690
+ if (pr === undefined) {
21691
+ process.stdout.write(`standards report: skipping PR comment (not a pull request).
21692
+ `);
21693
+ return EXIT.pass;
21694
+ }
21695
+ if (repo === undefined) {
21696
+ process.stdout.write(`standards report: skipping PR comment (missing repository).
21697
+ `);
21698
+ return EXIT.pass;
21699
+ }
21700
+ const token = nonEmpty(env.GITHUB_TOKEN);
21701
+ if (event.isFork || token === undefined) {
21702
+ process.stdout.write(`standards report: skipping PR comment: fork PR or missing GITHUB_TOKEN.
21703
+ `);
21704
+ return EXIT.pass;
21705
+ }
21706
+ const apiUrl = trimTrailingSlashes(nonEmpty(env.GITHUB_API_URL) ?? DEFAULT_API_URL);
21707
+ await upsertStickyComment({ apiUrl, repo, pr, marker: options.marker, body: markdown, token });
21708
+ return EXIT.pass;
21709
+ }
21710
+ var VALUE_FLAGS2 = new Set([
21711
+ "--status",
21712
+ "--dir",
21713
+ "--summary-file",
21714
+ "--repo",
21715
+ "--pr",
21716
+ "--sha",
21717
+ "--run-url",
21718
+ "--marker"
21719
+ ]);
21720
+ function parseArgs3(args) {
21721
+ const parsed = { comment: false };
21722
+ const seen = new Set;
21723
+ for (let index = 0;index < args.length; index += 1) {
21724
+ const arg = args[index] ?? "";
21725
+ if (arg === "--comment") {
21726
+ markFlagSeen(seen, "--comment");
21727
+ parsed.comment = true;
21728
+ continue;
21729
+ }
21730
+ index += parseValueFlag(arg, args[index + 1], seen, parsed);
21731
+ }
21732
+ if (parsed.status === undefined) {
21733
+ throw new GateError(`missing --status: ${USAGE}.`);
21734
+ }
21735
+ return {
21736
+ status: parsed.status,
21737
+ dir: parsed.dir,
21738
+ summaryFile: parsed.summaryFile,
21739
+ comment: parsed.comment,
21740
+ repo: parsed.repo,
21741
+ pr: parsed.pr,
21742
+ sha: parsed.sha,
21743
+ runUrl: parsed.runUrl,
21744
+ marker: parsed.marker ?? "check"
21745
+ };
21746
+ }
21747
+ function markFlagSeen(seen, flag) {
21748
+ if (seen.has(flag))
21749
+ throw new GateError(`duplicate ${flag} flag.`);
21750
+ seen.add(flag);
21751
+ }
21752
+ function parseValueFlag(arg, next, seen, target) {
21753
+ const eqIndex = arg.indexOf("=");
21754
+ const flag = eqIndex === -1 ? arg : arg.slice(0, eqIndex);
21755
+ if (!VALUE_FLAGS2.has(flag)) {
21756
+ throw new GateError(`rejected argument ${arg}: ${USAGE}.`);
21757
+ }
21758
+ markFlagSeen(seen, flag);
21759
+ const value = eqIndex === -1 ? next : arg.slice(eqIndex + 1);
21760
+ if (value === undefined || value === "") {
21761
+ throw new GateError(`${flag} needs a value.`);
21762
+ }
21763
+ assignFlag(flag, value, target);
21764
+ return eqIndex === -1 ? 1 : 0;
21765
+ }
21766
+ function assignFlag(flag, value, target) {
21767
+ if (flag === "--status") {
21768
+ target.status = parseStatus(value);
21769
+ return;
21770
+ }
21771
+ if (flag === "--marker") {
21772
+ target.marker = parseMarker(value);
21773
+ return;
21774
+ }
21775
+ if (flag === "--pr") {
21776
+ target.pr = parsePrNumber2(value);
21777
+ return;
21778
+ }
21779
+ if (flag === "--repo") {
21780
+ target.repo = validateRepo(value);
21781
+ return;
21782
+ }
21783
+ if (flag === "--dir") {
21784
+ target.dir = value;
21785
+ return;
21786
+ }
21787
+ if (flag === "--summary-file") {
21788
+ target.summaryFile = value;
21789
+ return;
21790
+ }
21791
+ if (flag === "--sha") {
21792
+ target.sha = value;
21793
+ return;
21794
+ }
21795
+ if (flag === "--run-url") {
21796
+ target.runUrl = value;
21797
+ }
21798
+ }
21799
+ function parseStatus(raw) {
21800
+ if (raw === "success" || raw === "failure" || raw === "cancelled")
21801
+ return raw;
21802
+ throw new GateError(`invalid --status "${raw}": expected ${Array.from(VALID_STATUSES).join(", ")}.`);
21803
+ }
21804
+ function parseMarker(raw) {
21805
+ if (!MARKER_PATTERN.test(raw)) {
21806
+ throw new GateError(`invalid --marker "${raw}": must match /^[a-z0-9._-]+$/.`);
21807
+ }
21808
+ return raw;
21809
+ }
21810
+ function parsePrNumber2(raw) {
21811
+ const parsed = PR_NUMBER2.test(raw) ? Number(raw) : Number.NaN;
21812
+ if (Number.isSafeInteger(parsed))
21813
+ return parsed;
21814
+ throw new GateError(`invalid --pr "${raw}": expected a positive integer.`);
21815
+ }
21816
+ function envRepo(env) {
21817
+ const raw = nonEmpty(env.GITHUB_REPOSITORY);
21818
+ return raw === undefined ? undefined : validateRepo(raw);
21819
+ }
21820
+ function defaultRunUrl(env) {
21821
+ const server = nonEmpty(env.GITHUB_SERVER_URL);
21822
+ const repo = nonEmpty(env.GITHUB_REPOSITORY);
21823
+ const runId = nonEmpty(env.GITHUB_RUN_ID);
21824
+ if (server === undefined || repo === undefined || runId === undefined)
21825
+ return;
21826
+ return `${trimTrailingSlashes(server)}/${repo}/actions/runs/${encodeURIComponent(runId)}`;
21827
+ }
21828
+ function readPullRequestEvent(env) {
21829
+ const eventName = nonEmpty(env.GITHUB_EVENT_NAME);
21830
+ const eventPath = nonEmpty(env.GITHUB_EVENT_PATH);
21831
+ if (eventName === undefined || !PR_EVENTS.has(eventName) || eventPath === undefined) {
21832
+ return { isFork: false };
21833
+ }
21834
+ const payload = readJsonObjectQuietly(eventPath);
21835
+ if (payload === undefined)
21836
+ return { isFork: false };
21837
+ const pullRequest = isRecord(payload.pull_request) ? payload.pull_request : undefined;
21838
+ if (pullRequest === undefined)
21839
+ return { isFork: false };
21840
+ const pr = typeof pullRequest.number === "number" && Number.isSafeInteger(pullRequest.number) && pullRequest.number > 0 ? pullRequest.number : undefined;
21841
+ const head = isRecord(pullRequest.head) ? pullRequest.head : undefined;
21842
+ const base = isRecord(pullRequest.base) ? pullRequest.base : undefined;
21843
+ const sha = head !== undefined && typeof head.sha === "string" && head.sha !== "" ? head.sha : undefined;
21844
+ return { pr, sha, isFork: isForkPullRequest(head, base) };
21845
+ }
21846
+ function isForkPullRequest(head, base) {
21847
+ if (head === undefined)
21848
+ return false;
21849
+ if (head.repo === null)
21850
+ return true;
21851
+ const headFull = repoFullName(head.repo);
21852
+ const baseFull = repoFullName(base?.repo);
21853
+ if (baseFull === undefined)
21854
+ return false;
21855
+ return headFull !== baseFull;
21856
+ }
21857
+ function repoFullName(value) {
21858
+ if (!isRecord(value))
21859
+ return;
21860
+ return typeof value.full_name === "string" && value.full_name !== "" ? value.full_name : undefined;
21861
+ }
21862
+ function readJsonObjectQuietly(path) {
21863
+ if (!existsSync19(path))
21864
+ return;
21865
+ try {
21866
+ const parsed = JSON.parse(readFileSync10(path, "utf8"));
21867
+ return isRecord(parsed) ? parsed : undefined;
21868
+ } catch {
21869
+ return;
21870
+ }
21871
+ }
21872
+ async function upsertStickyComment(input) {
21873
+ const headers = githubHeaders(input.token);
21874
+ try {
21875
+ const existing = await findStickyCommentId(input, headers);
21876
+ if (!existing.ok) {
21877
+ warnCommentApi(`failed to list comments on PR #${input.pr}`, existing.detail, input.token);
21878
+ return;
21879
+ }
21880
+ await writeStickyComment(input, headers, existing.id);
21881
+ } catch (error) {
21882
+ const detail = error instanceof Error ? error.message : String(error);
21883
+ warnCommentApi(`failed to update comment on PR #${input.pr}`, detail, input.token);
21884
+ }
21885
+ }
21886
+ async function findStickyCommentId(input, headers) {
21887
+ const needle = markerComment(input.marker);
21888
+ const expectedOrigin = new URL(input.apiUrl).origin;
21889
+ const visited = new Set;
21890
+ let nextUrl = `${input.apiUrl}/repos/${input.repo}/issues/${input.pr}/comments?per_page=100`;
21891
+ let latestId;
21892
+ for (let page = 0;page < MAX_COMMENT_PAGES && nextUrl !== undefined; page += 1) {
21893
+ if (visited.has(nextUrl))
21894
+ break;
21895
+ visited.add(nextUrl);
21896
+ const response = await fetch(nextUrl, { method: "GET", headers });
21897
+ if (!response.ok) {
21898
+ return { ok: false, detail: await describeHttpError(response) };
21899
+ }
21900
+ const items = await response.json();
21901
+ if (!Array.isArray(items)) {
21902
+ return { ok: false, detail: "unexpected non-array response from comments endpoint" };
21903
+ }
21904
+ latestId = matchCommentId(items, needle, latestId);
21905
+ nextUrl = nextPageUrl(response.headers.get("link"), expectedOrigin);
21906
+ }
21907
+ return { ok: true, id: latestId };
21908
+ }
21909
+ var REPORT_BOT_LOGIN = "github-actions[bot]";
21910
+ var REPORT_APP_SLUG = "github-actions";
21911
+ function matchCommentId(items, needle, current) {
21912
+ let matched = current;
21913
+ for (const item of items) {
21914
+ if (!isRecord(item))
21915
+ continue;
21916
+ if (typeof item.id !== "number" || !Number.isSafeInteger(item.id))
21917
+ continue;
21918
+ if (!isReportOwnedComment(item))
21919
+ continue;
21920
+ if (typeof item.body === "string" && hasFirstLineMarker(item.body, needle))
21921
+ matched = item.id;
21922
+ }
21923
+ return matched;
21924
+ }
21925
+ function isReportOwnedComment(item) {
21926
+ if (!isRecord(item.user))
21927
+ return false;
21928
+ if (item.user.login !== REPORT_BOT_LOGIN || item.user.type !== "Bot")
21929
+ return false;
21930
+ if (item.performed_via_github_app === undefined || item.performed_via_github_app === null) {
21931
+ return true;
21932
+ }
21933
+ return isRecord(item.performed_via_github_app) && item.performed_via_github_app.slug === REPORT_APP_SLUG;
21934
+ }
21935
+ function hasFirstLineMarker(body, needle) {
21936
+ return body.split(/\r\n|\n|\r/, 1)[0] === needle;
21937
+ }
21938
+ function nextPageUrl(linkHeader, expectedOrigin) {
21939
+ if (!linkHeader)
21940
+ return;
21941
+ const match = NEXT_LINK_PATTERN.exec(linkHeader);
21942
+ const candidate = match?.[1];
21943
+ if (candidate === undefined)
21944
+ return;
21945
+ try {
21946
+ const parsed = new URL(candidate);
21947
+ return parsed.origin === expectedOrigin ? parsed.href : undefined;
21948
+ } catch {
21949
+ return;
21950
+ }
21951
+ }
21952
+ async function writeStickyComment(input, headers, commentId) {
21953
+ const isUpdate = commentId !== undefined;
21954
+ const url = isUpdate ? `${input.apiUrl}/repos/${input.repo}/issues/comments/${commentId}` : `${input.apiUrl}/repos/${input.repo}/issues/${input.pr}/comments`;
21955
+ const response = await fetch(url, {
21956
+ method: isUpdate ? "PATCH" : "POST",
21957
+ headers: { ...headers, "content-type": "application/json" },
21958
+ body: JSON.stringify({ body: input.body })
21959
+ });
21960
+ if (!response.ok) {
21961
+ const action = isUpdate ? `update comment ${commentId}` : "create comment";
21962
+ warnCommentApi(`failed to ${action} on PR #${input.pr}`, await describeHttpError(response), input.token);
21963
+ return;
21964
+ }
21965
+ const commentUrl = await readCommentUrl(response);
21966
+ const verb = isUpdate ? "updated" : "created";
21967
+ const fallback = isUpdate ? ` #${commentId}` : "";
21968
+ const suffix = commentUrl === undefined ? fallback : ` (${commentUrl})`;
21969
+ process.stdout.write(`standards report: ${verb} PR #${input.pr} comment${suffix}.
21970
+ `);
21971
+ }
21972
+ function githubHeaders(token) {
21973
+ return {
21974
+ accept: "application/vnd.github+json",
21975
+ authorization: `Bearer ${token}`,
21976
+ "user-agent": "@shaulavo/standards",
21977
+ "x-github-api-version": "2022-11-28"
21978
+ };
21979
+ }
21980
+ async function describeHttpError(response) {
21981
+ const status = `HTTP ${response.status}`;
21982
+ try {
21983
+ const payload = await response.json();
21984
+ if (isRecord(payload) && typeof payload.message === "string" && payload.message.trim() !== "") {
21985
+ return `${status}: ${payload.message.trim()}`;
21986
+ }
21987
+ } catch {}
21988
+ return status;
21989
+ }
21990
+ async function readCommentUrl(response) {
21991
+ try {
21992
+ const payload = await response.json();
21993
+ if (isRecord(payload) && typeof payload.html_url === "string" && payload.html_url !== "") {
21994
+ return payload.html_url;
21995
+ }
21996
+ } catch {}
21997
+ return;
21998
+ }
21999
+ function warnCommentApi(context, detail, token) {
22000
+ const safeDetail = detail.replaceAll(token, "[REDACTED]");
22001
+ process.stderr.write(`standards report: warning: ${context} (${safeDetail}); continuing.
22002
+ `);
22003
+ }
22004
+ function nonEmpty(value) {
22005
+ if (value === undefined)
22006
+ return;
22007
+ const trimmed = value.trim();
22008
+ return trimmed === "" ? undefined : trimmed;
22009
+ }
22010
+ function trimTrailingSlashes(value) {
22011
+ return value.replace(/\/+$/, "");
22012
+ }
22013
+
21297
22014
  // src/gates/source.ts
21298
22015
  var import_ignore2 = __toESM(require_ignore(), 1);
21299
22016
 
@@ -21336,8 +22053,8 @@ function source(cwd, args) {
21336
22053
 
21337
22054
  // src/gates/suppressions.ts
21338
22055
  var import_ignore3 = __toESM(require_ignore(), 1);
21339
- import { existsSync as existsSync18, readFileSync as readFileSync9 } from "node:fs";
21340
- import { join as join17 } from "node:path";
22056
+ import { existsSync as existsSync20, readFileSync as readFileSync11 } from "node:fs";
22057
+ import { join as join18 } from "node:path";
21341
22058
  var SCANNED = /\.(?:[cm]?[jt]s|[jt]sx)$/;
21342
22059
  var DIRECTIVE = /^(oxlint|eslint)-disable(?:-next-line|-line)?(?=\s|$)/;
21343
22060
  async function suppressions(cwd, args) {
@@ -21346,7 +22063,7 @@ async function suppressions(cwd, args) {
21346
22063
  const files = listFiles(cwd).filter((file) => SCANNED.test(file) && !linted.ignores(file));
21347
22064
  const { parseSync } = await import("oxc-parser");
21348
22065
  const directives = files.flatMap((file) => {
21349
- const text = readFileSync9(join17(cwd, file), "utf8");
22066
+ const text = readFileSync11(join18(cwd, file), "utf8");
21350
22067
  if (!text.includes("-disable"))
21351
22068
  return [];
21352
22069
  return parseSync(file, text).comments.flatMap((comment) => directive(file, text, comment.value, comment.start));
@@ -21362,7 +22079,7 @@ async function suppressions(cwd, args) {
21362
22079
  });
21363
22080
  }
21364
22081
  function lintScope(cwd) {
21365
- if (!existsSync18(join17(cwd, OXLINT_CONFIG)))
22082
+ if (!existsSync20(join18(cwd, OXLINT_CONFIG)))
21366
22083
  return import_ignore3.default();
21367
22084
  const patterns = oxlintChain(cwd)[0]?.data.ignorePatterns;
21368
22085
  const list = Array.isArray(patterns) ? patterns.filter((entry) => typeof entry === "string") : [];
@@ -21392,7 +22109,7 @@ function directiveProblems(entry, forbidden) {
21392
22109
  return missingReason.concat(forbiddenHits);
21393
22110
  }
21394
22111
  function configProblems(cwd, forbidden) {
21395
- if (forbidden.size === 0 || !existsSync18(join17(cwd, OXLINT_CONFIG)))
22112
+ if (forbidden.size === 0 || !existsSync20(join18(cwd, OXLINT_CONFIG)))
21396
22113
  return [];
21397
22114
  return oxlintChain(cwd).filter((config) => config.local).flatMap((config) => ruleBlocks(config.data).flatMap((rules) => Object.keys(rules)).filter((rule) => forbidden.has(bareName(rule))).map((rule) => `${config.path}: configures ${rule}, which this project forbids suppressing.`));
21398
22115
  }
@@ -21422,10 +22139,12 @@ var COMMANDS = {
21422
22139
  doctor,
21423
22140
  merge,
21424
22141
  new: newProject,
22142
+ report: report3,
21425
22143
  tools
21426
22144
  };
21427
- var SKIP_MIN_VERSION = new Set(["tools", "new"]);
21428
- var USAGE = `Usage: standards <command> [arguments]
22145
+ var SKIP_MIN_VERSION = new Set(["tools", "new", "report"]);
22146
+ var SKIP_REPORT_RECORD = new Set(["tools", "merge", "new", "report"]);
22147
+ var USAGE2 = `Usage: standards <command> [arguments]
21429
22148
 
21430
22149
  Tool adapters (native arguments pass through, except ones that weaken enforcement):
21431
22150
  oxlint lint with ./.oxlintrc.json, which extends the shared preset
@@ -21443,28 +22162,72 @@ Gates:
21443
22162
  doctor run every preflight and repo-contract check together
21444
22163
  merge verify approval and checks, then squash-merge <pr> [--repo <owner/repo>] [--dry-run]
21445
22164
  new create a new project from the template <dir> [--preset ts-library]
22165
+ report summarize recorded gates to step summary or PR comment --status <success|failure|cancelled> [--comment]
21446
22166
  tools native tools this package owns [--json]
21447
22167
  `;
21448
22168
  async function main(argv) {
21449
22169
  const [name, ...args] = argv;
21450
22170
  const command = name === undefined ? undefined : COMMANDS[name];
21451
22171
  if (name === undefined || !command) {
21452
- process.stderr.write(name === undefined ? USAGE : `standards: unknown command "${name}".
22172
+ process.stderr.write(name === undefined ? USAGE2 : `standards: unknown command "${name}".
21453
22173
 
21454
- ${USAGE}`);
22174
+ ${USAGE2}`);
21455
22175
  return EXIT.failed;
21456
22176
  }
22177
+ const startedAt = Date.now();
22178
+ resetGateNote();
21457
22179
  try {
21458
22180
  const cwd = process.cwd();
21459
22181
  if (!SKIP_MIN_VERSION.has(name))
21460
22182
  checkMinVersion(cwd);
21461
- return await command(cwd, args);
22183
+ const exitCode = await command(cwd, args);
22184
+ recordCompletion(name, exitCode, startedAt);
22185
+ return exitCode;
21462
22186
  } catch (error) {
21463
22187
  if (!(error instanceof GateError))
21464
22188
  throw error;
21465
22189
  process.stderr.write(`standards ${name}: ${error.message}
21466
22190
  `);
22191
+ recordGateError(name, error.message, startedAt);
21467
22192
  return EXIT.failed;
21468
22193
  }
21469
22194
  }
22195
+ function recordCompletion(name, exitCode, startedAt) {
22196
+ const note = consumeGateNote();
22197
+ if (SKIP_REPORT_RECORD.has(name))
22198
+ return;
22199
+ tryWriteGateRecord(name, {
22200
+ gate: name,
22201
+ status: gateStatusFromExit(exitCode),
22202
+ exitCode,
22203
+ durationMs: Date.now() - startedAt,
22204
+ timestamp: Date.now(),
22205
+ summary: note?.summary,
22206
+ excerpt: note?.excerpt
22207
+ });
22208
+ }
22209
+ function recordGateError(name, message, startedAt) {
22210
+ resetGateNote();
22211
+ if (SKIP_REPORT_RECORD.has(name))
22212
+ return;
22213
+ const firstLine = message.split(/\r?\n/)[0]?.trim() ?? message.trim();
22214
+ tryWriteGateRecord(name, {
22215
+ gate: name,
22216
+ status: "failed",
22217
+ exitCode: EXIT.failed,
22218
+ durationMs: Date.now() - startedAt,
22219
+ timestamp: Date.now(),
22220
+ summary: firstLine,
22221
+ excerpt: message
22222
+ });
22223
+ }
22224
+ function tryWriteGateRecord(name, record) {
22225
+ try {
22226
+ writeGateRecord(process.env.STANDARDS_REPORT_DIR, record);
22227
+ } catch (error) {
22228
+ const detail = error instanceof Error ? error.message : String(error);
22229
+ process.stderr.write(`standards ${name}: warning: could not write report record (${detail}).
22230
+ `);
22231
+ }
22232
+ }
21470
22233
  process.exitCode = await main(process.argv.slice(2));