@maniumek/suwgate 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/AGENTS.shared.md +13 -2
  2. package/README.md +95 -9
  3. package/dist/cli.js +208 -12
  4. package/dist/gate/breakdown.d.ts +38 -0
  5. package/dist/gate/breakdown.js +107 -0
  6. package/dist/gate/check.d.ts +3 -0
  7. package/dist/gate/check.js +37 -1
  8. package/dist/gate/config.d.ts +5 -1
  9. package/dist/gate/config.js +56 -2
  10. package/dist/gate/context.d.ts +15 -0
  11. package/dist/gate/context.js +97 -0
  12. package/dist/gate/contract.d.ts +7 -0
  13. package/dist/gate/contract.js +1 -0
  14. package/dist/gate/dashboard.d.ts +107 -0
  15. package/dist/gate/dashboard.js +126 -0
  16. package/dist/gate/dashboardFile.d.ts +31 -0
  17. package/dist/gate/dashboardFile.js +154 -0
  18. package/dist/gate/dashboardJson.d.ts +2 -0
  19. package/dist/gate/dashboardJson.js +25 -0
  20. package/dist/gate/dashboardPage.d.ts +3 -0
  21. package/dist/gate/dashboardPage.js +294 -0
  22. package/dist/gate/dashboardServer.d.ts +11 -0
  23. package/dist/gate/dashboardServer.js +70 -0
  24. package/dist/gate/dashboardTesting.d.ts +12 -0
  25. package/dist/gate/dashboardTesting.js +98 -0
  26. package/dist/gate/guardsStep.d.ts +6 -0
  27. package/dist/gate/guardsStep.js +8 -1
  28. package/dist/gate/history.d.ts +28 -0
  29. package/dist/gate/history.js +72 -0
  30. package/dist/gate/plan.d.ts +3 -1
  31. package/dist/gate/plan.js +6 -3
  32. package/dist/gate/repository.d.ts +1 -0
  33. package/dist/gate/repository.js +1 -1
  34. package/dist/gate/runner.d.ts +3 -0
  35. package/dist/gate/runner.js +4 -1
  36. package/dist/gate/stats.d.ts +27 -0
  37. package/dist/gate/stats.js +84 -0
  38. package/dist/guards/comments/eslint.js +1 -0
  39. package/dist/guards/comments/scan.js +1 -0
  40. package/dist/guards/comments/switches.js +1 -0
  41. package/dist/guards/database/connectionHost.js +1 -0
  42. package/dist/guards/dotnet/appsettingsBound.js +1 -0
  43. package/dist/guards/dotnet/bannedNugetPackages.js +1 -0
  44. package/dist/guards/dotnet/openApiVersions.js +1 -0
  45. package/dist/guards/dotnet/suwbackkitWiring.js +1 -0
  46. package/dist/guards/dotnet/unusedNugetVersions.js +1 -0
  47. package/dist/guards/repository/bannedNpmPackages.js +1 -0
  48. package/dist/guards/repository/composePorts.js +1 -0
  49. package/dist/guards/repository/dependencyDirection.js +1 -0
  50. package/dist/guards/repository/forbiddenNames.js +1 -0
  51. package/dist/guards/repository/humanDocs.js +1 -0
  52. package/dist/guards/repository/imagePins.js +1 -0
  53. package/dist/guards/repository/justModules.js +1 -0
  54. package/dist/guards/repository/noRawColors.js +1 -0
  55. package/dist/guards/repository/repositoryLayout.js +1 -0
  56. package/dist/guards/repository/scriptsCalled.js +1 -0
  57. package/dist/guards/repository/scriptsHelp.js +1 -0
  58. package/dist/guards/repository/suwfrontkitWiring.js +1 -0
  59. package/dist/guards/repository/vsCodeSettings.js +1 -0
  60. package/dist/profiles/holdout.d.ts +2 -0
  61. package/dist/profiles/holdout.js +38 -0
  62. package/dist/profiles/index.d.ts +1 -0
  63. package/dist/profiles/index.js +1 -0
  64. package/dist/profiles/reports.d.ts +6 -0
  65. package/dist/profiles/reports.js +14 -0
  66. package/dist/profiles/verdict.js +41 -2
  67. package/dist/session/doctor.d.ts +26 -0
  68. package/dist/session/doctor.js +265 -0
  69. package/dist/session/gardenRecord.d.ts +12 -0
  70. package/dist/session/gardenRecord.js +58 -0
  71. package/dist/session/guardPr.js +2 -2
  72. package/dist/session/prePush.js +1 -1
  73. package/dist/session/suwagentInfo.d.ts +28 -0
  74. package/dist/session/suwagentInfo.js +103 -0
  75. package/package.json +1 -1
  76. package/schema/suwgate.schema.json +26 -0
@@ -48,6 +48,7 @@ export const forbiddenNames = {
48
48
  id: "forbidden-names",
49
49
  description: "No folder, project or file is named by a vague word (utils, helpers, common), and no folder or project by the kind of thing it holds (services, components), instead of what it is",
50
50
  profiles: "every",
51
+ set: "stack",
51
52
  settingsSchema: { type: "object", additionalProperties: false, properties: { words: stringList, ignore: stringList } },
52
53
  check(context) {
53
54
  const settings = (context.settings ?? {});
@@ -77,6 +77,7 @@ export const humanDocs = {
77
77
  id: "human-docs",
78
78
  description: "The docs for people (README.md, docs/development.md and the README of a profile's directory) never tell a person to run a script meant for agents (scripts/.internal/, <name>.Gate/scripts/): people run just recipes",
79
79
  profiles: "every",
80
+ set: "stack",
80
81
  check(context) {
81
82
  const agentNames = new Set(context.files.filter((file) => AGENT_SCRIPT.test(file)).map(baseName));
82
83
  return documentsOf(context).flatMap((document) => commandsOf(context.read(document)).flatMap(({ line, text }) => {
@@ -41,6 +41,7 @@ export const imagePins = {
41
41
  id: "image-pins",
42
42
  description: "Every container image (Dockerfile FROM, image: in YAML, IMAGE= in a script) is pinned to a version, never latest, and the Playwright image matches the installed @playwright/test",
43
43
  profiles: "every",
44
+ set: "stack",
44
45
  check(context) {
45
46
  const found = context.files.flatMap((file) => isDockerfile(baseName(file)) || /\.(ya?ml|sh)$/.test(file) ? references(file, context.read(file)) : []);
46
47
  const unpinned = found
@@ -17,6 +17,7 @@ export const justModules = {
17
17
  id: "just-modules",
18
18
  description: "Every just module is <name>.just beside the justfile, <folder>/mod.just, or the file a mod line names by its path (mod <name> '<path>'), and the justfile names each one",
19
19
  profiles: "every",
20
+ set: "stack",
20
21
  check(context) {
21
22
  const modules = context.files.filter((file) => file.endsWith(".just"));
22
23
  const mods = context.files.includes("justfile")
@@ -6,6 +6,7 @@ export const noRawColors = {
6
6
  id: "no-raw-colors",
7
7
  description: "Components use the theme's tokens, never a colour value of their own; it reads the src/ folder of a web app, and the folders settings name, but not the tests",
8
8
  profiles: ["web", "library"],
9
+ set: "stack",
9
10
  settingsSchema: {
10
11
  type: "object",
11
12
  additionalProperties: false,
@@ -83,6 +83,7 @@ export const repositoryLayout = {
83
83
  id: "repository-layout",
84
84
  description: "Every top-level folder has a short line in the map (the section ## The map) of docs/architecture.md, no two files differ only in letter case, and every shell script is executable in git",
85
85
  profiles: "every",
86
+ set: "stack",
86
87
  check(context) {
87
88
  return [
88
89
  ...(context.files.includes(MAP) ? mapFindings(context) : []),
@@ -53,6 +53,7 @@ export const scriptsCalled = {
53
53
  id: "scripts-called",
54
54
  description: "Every script (*.sh, and the files of a scripts/ folder) is called by a recipe, another script, a hook (also a Claude Code plugin's hooks/hooks.json), the workflow or a command of suwgate.yml (steps.add run, steps.configure, env, dev)",
55
55
  profiles: "every",
56
+ set: "stack",
56
57
  check(context) {
57
58
  const callers = callersOf(context);
58
59
  return context.files
@@ -28,6 +28,7 @@ export const scriptsHelp = {
28
28
  id: "scripts-help",
29
29
  description: "Every shell script but the hooks answers --help with a usage text, so an agent asks it instead of reading it",
30
30
  profiles: "every",
31
+ set: "stack",
31
32
  quick: false,
32
33
  check(context) {
33
34
  return context.files
@@ -38,6 +38,7 @@ export const suwfrontkitWiring = {
38
38
  id: "suwfrontkit-wiring",
39
39
  description: `A web app (an index.html with a module script) that depends on ${KIT} loads ${THEME} from its main module or a stylesheet that module imports`,
40
40
  profiles: PROFILES,
41
+ set: "stack",
41
42
  check(context) {
42
43
  const directories = [
43
44
  ...new Set(PROFILES.filter((profile) => context.profiles.includes(profile)).map((profile) => context.directories[profile] ?? "")),
@@ -40,6 +40,7 @@ export const vsCodeSettings = {
40
40
  id: "vscode-settings",
41
41
  description: "The VS Code settings hold glue and no style rules, and every recommended extension id is well formed and listed once",
42
42
  profiles: "every",
43
+ set: "stack",
43
44
  check(context) {
44
45
  return [
45
46
  ...(context.files.includes(SETTINGS) ? settingsFindings(context.read(SETTINGS)) : []),
@@ -0,0 +1,2 @@
1
+ import { type Holdout, type Step } from "../gate/contract.ts";
2
+ export declare function holdoutStep(holdout: Holdout): Step;
@@ -0,0 +1,38 @@
1
+ import { statSync } from "node:fs";
2
+ import { HOLDOUT_STEP } from "../gate/contract.js";
3
+ import { quoted, runDirectory, script, verdictCommand } from "./shell.js";
4
+ const HOLDOUT_LIMIT_SECONDS = 600;
5
+ function holdoutDirectory() {
6
+ const directory = process.env["SUWGATE_HOLDOUT"];
7
+ if (directory === undefined || directory === "")
8
+ return null;
9
+ try {
10
+ return statSync(directory).isDirectory() ? directory : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ function holdoutCommand(holdout) {
17
+ return script([
18
+ runDirectory(HOLDOUT_STEP),
19
+ `trap 'rm -f "$run/output.log"' EXIT`,
20
+ 'rm -f "$run/report.xml"',
21
+ "status=0",
22
+ `SUWGATE_HOLDOUT_REPORT="$run/report.xml" bash -c ${quoted(holdout.run)} >"$run/output.log" 2>&1 || status=$?`,
23
+ verdictCommand('holdout "$run/report.xml" "$status"'),
24
+ ]);
25
+ }
26
+ export function holdoutStep(holdout) {
27
+ return {
28
+ id: HOLDOUT_STEP,
29
+ title: "holdout scenarios, kept outside the repository and run in CI only (a failure shows only the names of the failed scenarios)",
30
+ after: holdout.after ?? [],
31
+ limitSeconds: holdout.limitSeconds ?? HOLDOUT_LIMIT_SECONDS,
32
+ run: () => holdoutDirectory() === null
33
+ ? {
34
+ skip: "SUWGATE_HOLDOUT names no directory: CI provides the holdout scenarios, so pass holdout-repository to the gate workflow (docs/ci.md); to run them here, check them out and set SUWGATE_HOLDOUT to that directory",
35
+ }
36
+ : holdoutCommand(holdout),
37
+ };
38
+ }
@@ -1,5 +1,6 @@
1
1
  import { type Profile, type Step } from "../gate/contract.ts";
2
2
  export { discoverApiIn } from "./contract.ts";
3
3
  export { dotnetGuards } from "./dotnetGuards.ts";
4
+ export { holdoutStep } from "./holdout.ts";
4
5
  export { verdict } from "./verdict.ts";
5
6
  export declare function stepsFor(profiles: readonly Profile[]): Step[];
@@ -8,6 +8,7 @@ import { nodeSteps } from "./node.js";
8
8
  import { webSteps } from "./web.js";
9
9
  export { discoverApiIn } from "./contract.js";
10
10
  export { dotnetGuards } from "./dotnetGuards.js";
11
+ export { holdoutStep } from "./holdout.js";
11
12
  export { verdict } from "./verdict.js";
12
13
  const BY_PROFILE = {
13
14
  web: [...nodeSteps("web"), ...webSteps, ...contractSteps],
@@ -40,6 +40,12 @@ interface PlaywrightReport {
40
40
  export declare function vitestRun(report: VitestReport): TestRun;
41
41
  export declare function playwrightRun(report: PlaywrightReport): TestRun;
42
42
  export declare function xunitRun(xml: string): TestRun;
43
+ export interface JunitCase {
44
+ name: string;
45
+ skipped: boolean;
46
+ failed: boolean;
47
+ }
48
+ export declare function junitCases(xml: string): JunitCase[] | null;
43
49
  export declare function vitestTimes(report: VitestReport): TestTime[];
44
50
  export declare function playwrightTimes(report: PlaywrightReport): TestTime[];
45
51
  export declare function xunitTimes(xml: string): TestTime[];
@@ -48,6 +48,7 @@ export function xunitRun(xml) {
48
48
  };
49
49
  }
50
50
  const MILLISECONDS = 1000;
51
+ const JUNIT_CASE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
51
52
  const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
52
53
  function unescaped(value) {
53
54
  return value.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(\w+));/g, (entity, decimal, hex, named) => {
@@ -58,6 +59,19 @@ function unescaped(value) {
58
59
  return ENTITIES[named ?? ""] ?? entity;
59
60
  });
60
61
  }
62
+ export function junitCases(xml) {
63
+ if (!/<testsuites?\b/.test(xml))
64
+ return null;
65
+ return Array.from(xml.matchAll(JUNIT_CASE), (tag) => {
66
+ const body = tag[2] ?? "";
67
+ const name = /\bname="([^"]*)"/.exec(tag[1] ?? "")?.[1];
68
+ return {
69
+ name: name === undefined ? "(unnamed scenario)" : unescaped(name),
70
+ skipped: /<skipped\b/.test(body),
71
+ failed: /<(failure|error)\b/.test(body),
72
+ };
73
+ });
74
+ }
61
75
  export function vitestTimes(report) {
62
76
  return (report.testResults ?? [])
63
77
  .flatMap((file) => file.assertionResults ?? [])
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { criteriaRan } from "./criteriaRan.js";
3
- import { files, readRun } from "./reports.js";
3
+ import { files, junitCases, readRun } from "./reports.js";
4
4
  const STRICT_FAMILY = [
5
5
  "noImplicitAny",
6
6
  "strictNullChecks",
@@ -24,6 +24,41 @@ export function testsVerdict(format, location, tool) {
24
24
  return null;
25
25
  return `${tool} ran 0 tests (every test skipped or filtered out, or none found), and a gate that ran nothing proves nothing: add a test that runs, or skip the step in suwgate.yml (steps.skip) with a reason`;
26
26
  }
27
+ const FIX_THE_BEHAVIOUR = "fix the behaviour; the scenarios are not in this repository and are never changed to pass";
28
+ const MAX_NAME = 200;
29
+ function scenarioName(name) {
30
+ const line = name.replace(/\s+/g, " ").trim();
31
+ return line.length > MAX_NAME ? `${line.slice(0, MAX_NAME)}...` : line;
32
+ }
33
+ function readHoldout(location) {
34
+ try {
35
+ return junitCases(readFileSync(location, "utf8"));
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function holdoutVerdict(location, exitCode) {
42
+ const cases = readHoldout(location);
43
+ if (cases === null) {
44
+ return "the holdout command wrote no readable JUnit XML report, so suwgate cannot tell that any scenario ran: the command must write a JUnit XML report to the path in $SUWGATE_HOLDOUT_REPORT (its output is hidden, because it could show the scenarios)";
45
+ }
46
+ const executed = cases.filter((scenario) => !scenario.skipped);
47
+ const failed = executed.filter((scenario) => scenario.failed);
48
+ if (failed.length > 0) {
49
+ return [
50
+ `${failed.length} of ${executed.length} holdout scenarios failed:`,
51
+ ...failed.map((scenario) => ` - ${scenarioName(scenario.name)}`),
52
+ FIX_THE_BEHAVIOUR,
53
+ ].join("\n");
54
+ }
55
+ if (executed.length === 0) {
56
+ return "the holdout command ran 0 scenarios (none found, or every one skipped), and a gate that ran nothing proves nothing: tell the owner, who keeps the scenarios, that the holdout repository holds none that run; never add a test here to stand in for one";
57
+ }
58
+ if (exitCode === 0)
59
+ return null;
60
+ return `the holdout command exited with status ${exitCode} although its report names no failed scenario, so the run itself broke (the app did not start, a crash): its output is hidden because it could show the scenarios; ${FIX_THE_BEHAVIOUR}, or tell the owner if the failure is not in the behaviour`;
61
+ }
27
62
  function missingGuards(evidence, required) {
28
63
  const ran = new Set(evidence.split("\n").map((line) => line.split("\t")[0] ?? ""));
29
64
  return required.filter((guard) => !ran.has(guard));
@@ -92,6 +127,10 @@ function judged(argv) {
92
127
  const [location, tool] = rest;
93
128
  return kind === null || location === undefined || tool === undefined ? undefined : testsVerdict(kind, location, tool);
94
129
  }
130
+ case "holdout": {
131
+ const [status] = rest;
132
+ return status === undefined ? undefined : holdoutVerdict(first, Number(status));
133
+ }
95
134
  case "guards":
96
135
  return guardsVerdict(first, rest);
97
136
  case "tsconfig":
@@ -120,7 +159,7 @@ export function verdict(argv) {
120
159
  if (problem === undefined) {
121
160
  return {
122
161
  exitCode: 2,
123
- text: "usage: suwgate verdict tests <vitest|playwright|xunit> <report> <tool> | guards <evidence-dir> <guard>... | tsconfig <file> | eslint <file> <rule>... | criteria <run-dir> <input-json>",
162
+ text: "usage: suwgate verdict tests <vitest|playwright|xunit> <report> <tool> | holdout <report> <exit-status> | guards <evidence-dir> <guard>... | tsconfig <file> | eslint <file> <rule>... | criteria <run-dir> <input-json>",
124
163
  };
125
164
  }
126
165
  return problem === null ? { exitCode: 0, text: "" } : { exitCode: 1, text: problem };
@@ -0,0 +1,26 @@
1
+ import type { RunTool } from "./preCommit.ts";
2
+ interface DoctorFinding {
3
+ target: string;
4
+ message: string;
5
+ }
6
+ interface DoctorCheck {
7
+ name: string;
8
+ state: "holds" | "broken" | "unchecked";
9
+ detail: string;
10
+ }
11
+ export interface DoctorVerdict {
12
+ exitCode: 0 | 1 | 2;
13
+ text: string;
14
+ checks: DoctorCheck[];
15
+ }
16
+ export interface DoctorLocal {
17
+ hookFindings: () => Promise<readonly DoctorFinding[]>;
18
+ }
19
+ type GateCheck = {
20
+ names: readonly string[];
21
+ } | {
22
+ unknown: string;
23
+ };
24
+ export declare function gateCheck(root: string): GateCheck;
25
+ export declare function doctor(root: string, run: RunTool, local: DoctorLocal): Promise<DoctorVerdict>;
26
+ export {};
@@ -0,0 +1,265 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { parse } from "yaml";
5
+ const HOOKS_PATH = ".githooks";
6
+ const GATE_JOB = "gate";
7
+ const WORKFLOWS = ".github/workflows";
8
+ const CHECK_PULL_REQUEST = "pull request required before merging";
9
+ const CHECK_GATE = "the gate's check required";
10
+ const CHECK_FORCE_PUSH = "force pushes blocked";
11
+ const CHECK_DELETION = "deleting the branch blocked";
12
+ const CHECK_HOOKS = "local hooks wired";
13
+ const REMOTE_CHECKS = [CHECK_PULL_REQUEST, CHECK_GATE, CHECK_FORCE_PUSH, CHECK_DELETION];
14
+ function record(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
16
+ }
17
+ function text(value) {
18
+ return typeof value === "string" && value !== "" ? value : null;
19
+ }
20
+ function gitConfig(root, key) {
21
+ try {
22
+ return execFileSync("git", ["config", "--get", key], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
23
+ }
24
+ catch {
25
+ return "";
26
+ }
27
+ }
28
+ function workflowFiles(root) {
29
+ const folder = path.join(root, WORKFLOWS);
30
+ if (!existsSync(folder))
31
+ return [];
32
+ return readdirSync(folder)
33
+ .filter((file) => /\.ya?ml$/.test(file))
34
+ .sort()
35
+ .flatMap((file) => {
36
+ try {
37
+ const document = record(parse(readFileSync(path.join(folder, file), "utf8")));
38
+ return document === null ? [] : [{ file, document }];
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ });
44
+ }
45
+ function innerGateJob(root, uses) {
46
+ const local = /^\.\/\.github\/workflows\/gate\.ya?ml$/.test(uses);
47
+ if (!local)
48
+ return GATE_JOB;
49
+ const file = path.join(root, uses);
50
+ if (!existsSync(file))
51
+ return null;
52
+ const jobs = record(record(parse(readFileSync(file, "utf8")))?.["jobs"]);
53
+ const job = record(jobs?.[GATE_JOB]);
54
+ return job === null ? null : (text(job["name"]) ?? GATE_JOB);
55
+ }
56
+ export function gateCheck(root) {
57
+ const names = [];
58
+ for (const { document } of workflowFiles(root)) {
59
+ const jobs = record(document["jobs"]) ?? {};
60
+ for (const [id, value] of Object.entries(jobs)) {
61
+ const job = record(value);
62
+ const uses = text(job?.["uses"]);
63
+ if (job === null || uses === null || !/\/gate\.ya?ml(@.+)?$/.test(uses))
64
+ continue;
65
+ const inner = innerGateJob(root, uses.replace(/@.+$/, ""));
66
+ if (inner !== null)
67
+ names.push(`${text(job["name"]) ?? id} / ${inner}`);
68
+ }
69
+ }
70
+ return names.length > 0
71
+ ? { names }
72
+ : { unknown: `no job of ${WORKFLOWS} calls the reusable gate.yml, so the name of the gate's check cannot be read from there` };
73
+ }
74
+ function fromRules(rules) {
75
+ const kinds = rules.flatMap((rule) => text(record(rule)?.["type"]) ?? []);
76
+ const checks = rules.flatMap((rule) => {
77
+ const parameters = record(record(rule)?.["parameters"]);
78
+ const required = parameters?.["required_status_checks"];
79
+ return record(rule)?.["type"] === "required_status_checks" && Array.isArray(required)
80
+ ? required.flatMap((check) => text(record(check)?.["context"]) ?? [])
81
+ : [];
82
+ });
83
+ return {
84
+ pullRequest: kinds.includes("pull_request"),
85
+ blocksPushes: kinds.includes("update"),
86
+ checks: kinds.includes("required_status_checks") ? checks : null,
87
+ forcePushBlocked: kinds.includes("non_fast_forward"),
88
+ deletionBlocked: kinds.includes("deletion"),
89
+ };
90
+ }
91
+ function fromProtection(protection) {
92
+ const status = record(protection["required_status_checks"]);
93
+ const contexts = Array.isArray(status?.["contexts"]) ? status["contexts"].flatMap((context) => text(context) ?? []) : [];
94
+ const checks = Array.isArray(status?.["checks"]) ? status["checks"].flatMap((check) => text(record(check)?.["context"]) ?? []) : [];
95
+ return {
96
+ pullRequest: record(protection["required_pull_request_reviews"]) !== null,
97
+ blocksPushes: record(protection["restrictions"]) !== null,
98
+ checks: status === null ? null : [...new Set([...contexts, ...checks])],
99
+ forcePushBlocked: record(protection["allow_force_pushes"])?.["enabled"] === false,
100
+ deletionBlocked: record(protection["allow_deletions"])?.["enabled"] === false,
101
+ };
102
+ }
103
+ function merge(walls) {
104
+ const checkLists = walls.flatMap((wall) => wall.checks ?? []);
105
+ return {
106
+ pullRequest: walls.some((wall) => wall.pullRequest),
107
+ blocksPushes: walls.some((wall) => wall.blocksPushes),
108
+ checks: walls.some((wall) => wall.checks !== null) ? [...new Set(checkLists)] : null,
109
+ forcePushBlocked: walls.some((wall) => wall.forcePushBlocked),
110
+ deletionBlocked: walls.some((wall) => wall.deletionBlocked),
111
+ };
112
+ }
113
+ async function localFindings(root, local) {
114
+ const findings = [];
115
+ if (gitConfig(root, "core.hooksPath") !== HOOKS_PATH) {
116
+ findings.push({
117
+ target: "core.hooksPath",
118
+ message: `it does not point at ${HOOKS_PATH}, so the pre-commit and pre-push hooks do not run in this checkout: run git config core.hooksPath ${HOOKS_PATH}`,
119
+ });
120
+ }
121
+ findings.push(...(await local.hookFindings()));
122
+ return findings;
123
+ }
124
+ function hooksCheck(findings) {
125
+ return {
126
+ name: CHECK_HOOKS,
127
+ state: findings.length === 0 ? "holds" : "broken",
128
+ detail: findings.map((finding) => `${finding.target}: ${finding.message}`).join(" "),
129
+ };
130
+ }
131
+ function cannot(why) {
132
+ return { cannot: why };
133
+ }
134
+ function parseJson(value) {
135
+ try {
136
+ return JSON.parse(value);
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ }
142
+ function failureOf(output, what) {
143
+ if (/auth login|not logged in|GH_TOKEN|authentication/i.test(output)) {
144
+ return cannot("gh is not logged in: run gh auth login, then suwgate doctor again");
145
+ }
146
+ if (/no git remotes|known GitHub host|Could not resolve to a Repository|not a git repository/i.test(output)) {
147
+ return cannot("this repository has no GitHub remote: add one with git remote add origin git@github.com:<owner>/<repo>.git, or run suwgate doctor in a clone of the repository");
148
+ }
149
+ return cannot(`${what} failed (${output.trim().split("\n").at(-1) ?? "no output"}): fix what gh reports, then run suwgate doctor again`);
150
+ }
151
+ async function readWall(root, run, local) {
152
+ const view = await run("gh", ["repo", "view", "--json", "nameWithOwner,defaultBranchRef"], root);
153
+ if (view.missing)
154
+ return cannot("gh is not installed: install the GitHub CLI (https://cli.github.com), run gh auth login, then suwgate doctor again");
155
+ if (view.exitCode !== 0)
156
+ return failureOf(view.text, "gh repo view");
157
+ const repository = record(parseJson(view.text));
158
+ const slug = text(repository?.["nameWithOwner"]);
159
+ const branch = text(record(repository?.["defaultBranchRef"])?.["name"]);
160
+ if (slug === null || branch === null) {
161
+ return cannot("gh repo view named no repository or default branch: push the repository to GitHub first, then run suwgate doctor again");
162
+ }
163
+ const rules = await run("gh", ["api", `repos/${slug}/rules/branches/${branch}`], root);
164
+ if (rules.exitCode !== 0)
165
+ return failureOf(rules.text, `gh api repos/${slug}/rules/branches/${branch}`);
166
+ const ruleList = parseJson(rules.text);
167
+ if (!Array.isArray(ruleList))
168
+ return cannot(`gh api repos/${slug}/rules/branches/${branch} did not return a list of rules`);
169
+ const protection = await run("gh", ["api", `repos/${slug}/branches/${branch}/protection`], root);
170
+ let protectionWall = null;
171
+ if (protection.exitCode === 0) {
172
+ const parsed = record(parseJson(protection.text));
173
+ protectionWall = parsed === null ? null : fromProtection(parsed);
174
+ }
175
+ else if (!/Branch not protected/i.test(protection.text)) {
176
+ if (/HTTP 40[13]/.test(protection.text)) {
177
+ return cannot(`the gh login cannot read the branch protection of ${slug} (the call needs read access to the repository's Administration): log in as an owner of the repository with gh auth login, then run suwgate doctor again`);
178
+ }
179
+ return failureOf(protection.text, `gh api repos/${slug}/branches/${branch}/protection`);
180
+ }
181
+ const wall = merge([fromRules(ruleList), ...(protectionWall === null ? [] : [protectionWall])]);
182
+ const settings = `https://github.com/${slug}/settings/rules`;
183
+ const findings = [];
184
+ const notes = [];
185
+ if (!wall.pullRequest && !wall.blocksPushes) {
186
+ findings.push({
187
+ check: CHECK_PULL_REQUEST,
188
+ target: branch,
189
+ message: `nothing requires a pull request before merging or blocks direct pushes, so anyone can push to ${branch}: open ${settings}, New ruleset, New branch ruleset, target ${branch}, enable "Require a pull request before merging"`,
190
+ });
191
+ }
192
+ if (wall.checks === null || wall.checks.length === 0) {
193
+ findings.push({
194
+ check: CHECK_GATE,
195
+ target: branch,
196
+ message: `no status check is required, so a red gate does not stop a merge: in the ruleset of ${settings} enable "Require status checks to pass" and add the gate's check`,
197
+ });
198
+ }
199
+ else {
200
+ const expected = gateCheck(root);
201
+ if ("names" in expected) {
202
+ const missing = expected.names.filter((name) => !wall.checks?.includes(name));
203
+ if (missing.length > 0) {
204
+ findings.push({
205
+ check: CHECK_GATE,
206
+ target: branch,
207
+ message: `the required checks (${wall.checks.join(", ")}) lack the gate's check ${missing.map((name) => `"${name}"`).join(", ")}: in the ruleset of ${settings}, under "Require status checks to pass", add it (it appears after the gate has run once)`,
208
+ });
209
+ }
210
+ }
211
+ else {
212
+ notes.push(`note: ${expected.unknown}; the required checks are ${wall.checks.join(", ")}: confirm in ${settings} that the gate is among them`);
213
+ }
214
+ }
215
+ if (!wall.forcePushBlocked) {
216
+ findings.push({
217
+ check: CHECK_FORCE_PUSH,
218
+ target: branch,
219
+ message: `force pushes are not blocked: in the ruleset of ${settings} enable "Block force pushes"`,
220
+ });
221
+ }
222
+ if (!wall.deletionBlocked) {
223
+ findings.push({
224
+ check: CHECK_DELETION,
225
+ target: branch,
226
+ message: `deleting the branch is not blocked: in the ruleset of ${settings} enable "Restrict deletions"`,
227
+ });
228
+ }
229
+ const hooks = await localFindings(root, local);
230
+ findings.push(...hooks.map((finding) => ({ ...finding, check: CHECK_HOOKS })));
231
+ const lines = findings.map((finding) => `${finding.target}: ${finding.message}`);
232
+ const checks = [...REMOTE_CHECKS, CHECK_HOOKS].map((name) => {
233
+ const own = findings.filter((finding) => finding.check === name);
234
+ return {
235
+ name,
236
+ state: own.length === 0 ? "holds" : "broken",
237
+ detail: name === CHECK_HOOKS ? hooksCheck(hooks).detail : own.map((finding) => finding.message).join(" "),
238
+ };
239
+ });
240
+ if (findings.length === 0) {
241
+ return { exitCode: 0, text: [`suwgate doctor: the wall is up on ${branch} of ${slug}`, ...notes].join("\n"), checks };
242
+ }
243
+ return {
244
+ exitCode: 1,
245
+ text: [
246
+ ...lines,
247
+ ...notes,
248
+ `suwgate doctor: ${findings.length} finding${findings.length === 1 ? "" : "s"} on ${branch} of ${slug}: fix them above`,
249
+ ].join("\n"),
250
+ checks,
251
+ };
252
+ }
253
+ export async function doctor(root, run, local) {
254
+ const wall = await readWall(root, run, local);
255
+ if (!("cannot" in wall))
256
+ return wall;
257
+ return {
258
+ exitCode: 2,
259
+ text: `suwgate doctor: cannot check the remote wall: ${wall.cannot}`,
260
+ checks: [
261
+ ...REMOTE_CHECKS.map((name) => ({ name, state: "unchecked", detail: wall.cannot })),
262
+ hooksCheck(await localFindings(root, local)),
263
+ ],
264
+ };
265
+ }
@@ -0,0 +1,12 @@
1
+ export interface GardenTrace {
2
+ at: string;
3
+ branch: string;
4
+ found: Record<string, number>;
5
+ }
6
+ export declare function parseFound(args: readonly string[]): {
7
+ found: Record<string, number>;
8
+ } | {
9
+ problem: string;
10
+ };
11
+ export declare function recordGarden(file: string, trace: GardenTrace): void;
12
+ export declare function lastGarden(file: string | null): GardenTrace | null;
@@ -0,0 +1,58 @@
1
+ import { appendFileSync, readFileSync } from "node:fs";
2
+ const KIND = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
3
+ const COUNT = /^\d{1,9}$/;
4
+ export function parseFound(args) {
5
+ if (args.length === 0) {
6
+ return { problem: "suwgate garden-ran takes <kind>=<count> pairs, e.g. suwgate garden-ran docs=3 guards=2" };
7
+ }
8
+ const found = {};
9
+ for (const arg of args) {
10
+ const [kind = "", count = "", ...extra] = arg.split("=");
11
+ if (!KIND.test(kind) || !COUNT.test(count) || extra.length > 0) {
12
+ return {
13
+ problem: `suwgate garden-ran: '${arg}' is not <kind>=<count>: a kind is a kebab-case word (docs, gate-config) and a count a whole number from 0, e.g. docs=3`,
14
+ };
15
+ }
16
+ if (kind in found)
17
+ return { problem: `suwgate garden-ran: the kind '${kind}' is given twice: give each kind once` };
18
+ found[kind] = Number(count);
19
+ }
20
+ return { found };
21
+ }
22
+ export function recordGarden(file, trace) {
23
+ appendFileSync(file, `${JSON.stringify(trace)}\n`);
24
+ }
25
+ function asTrace(value) {
26
+ if (typeof value !== "object" || value === null)
27
+ return null;
28
+ const { at, branch, found } = value;
29
+ if (typeof at !== "string" || Number.isNaN(Date.parse(at)) || typeof branch !== "string")
30
+ return null;
31
+ if (typeof found !== "object" || found === null || Array.isArray(found))
32
+ return null;
33
+ const counts = Object.entries(found);
34
+ if (!counts.every(([kind, count]) => KIND.test(kind) && Number.isInteger(count) && count >= 0))
35
+ return null;
36
+ return { at, branch, found: Object.fromEntries(counts) };
37
+ }
38
+ export function lastGarden(file) {
39
+ if (file === null)
40
+ return null;
41
+ let text;
42
+ try {
43
+ text = readFileSync(file, "utf8");
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ const traces = text.split("\n").flatMap((line) => {
49
+ try {
50
+ const trace = asTrace(JSON.parse(line));
51
+ return trace === null ? [] : [trace];
52
+ }
53
+ catch {
54
+ return [];
55
+ }
56
+ });
57
+ return traces.at(-1) ?? null;
58
+ }
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { hasShipRecord, treeOf } from "./shipRecord.js";
4
4
  const BUILT_IN = ["gh pr create"];
5
5
  const SKIPPED_HOOKS = /(?<![\w-])git\s+(?:\S+\s+)*?(?:push|commit)\b[^;&|]*\s--no-verify(?![\w-])/;
6
- const NO_RECORD = "No ship record for this commit: run /suwagent:ship first; it simplifies, checks the changed tests, then pushes and opens the pull request.";
6
+ const NO_RECORD = "No ship record for this commit: run /suwgate:ship first; it simplifies, checks the changed tests, then pushes and opens the pull request.";
7
7
  function callOf(input, root) {
8
8
  try {
9
9
  const parsed = JSON.parse(input);
@@ -29,7 +29,7 @@ function pattern(words) {
29
29
  .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
30
30
  return new RegExp(`(?<![\\w-])${escaped.join("\\s+")}(?![\\w-])`);
31
31
  }
32
- const SKIPPING = "An agent never skips git hooks: drop --no-verify. A push needs a ship record: run /suwagent:ship, which pushes for you.";
32
+ const SKIPPING = "An agent never skips git hooks: drop --no-verify. A push needs a ship record: run /suwgate:ship, which pushes for you.";
33
33
  export function guardPr(input, root, prCommands) {
34
34
  const call = callOf(input, root);
35
35
  if (SKIPPED_HOOKS.test(call.command))
@@ -7,7 +7,7 @@ export function prePush(input, root) {
7
7
  if (localRef === undefined || localSha === undefined || !localRef.startsWith("refs/heads/") || NO_COMMIT.test(localSha))
8
8
  continue;
9
9
  if (!hasShipRecord(root, treeOf(root, localSha))) {
10
- refused.push(`pre-push: ${localRef} has no ship record for its tree: run /suwagent:ship (an agent) or \`suwgate ship\`, then push again; push refused`);
10
+ refused.push(`pre-push: ${localRef} has no ship record for its tree: run /suwgate:ship (an agent) or \`suwgate ship\`, then push again; push refused`);
11
11
  }
12
12
  }
13
13
  return { exitCode: refused.length === 0 ? 0 : 1, message: refused.join("\n") };