@maniumek/suwgate 0.16.0 → 0.18.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 (78) hide show
  1. package/AGENTS.shared.md +13 -2
  2. package/README.md +98 -9
  3. package/dist/cli.js +217 -13
  4. package/dist/gate/breakdown.d.ts +40 -0
  5. package/dist/gate/breakdown.js +111 -0
  6. package/dist/gate/check.d.ts +4 -0
  7. package/dist/gate/check.js +38 -1
  8. package/dist/gate/ciHistory.d.ts +21 -0
  9. package/dist/gate/ciHistory.js +195 -0
  10. package/dist/gate/config.d.ts +5 -1
  11. package/dist/gate/config.js +56 -2
  12. package/dist/gate/context.d.ts +15 -0
  13. package/dist/gate/context.js +98 -0
  14. package/dist/gate/contract.d.ts +7 -0
  15. package/dist/gate/contract.js +1 -0
  16. package/dist/gate/dashboard.d.ts +112 -0
  17. package/dist/gate/dashboard.js +148 -0
  18. package/dist/gate/dashboardFile.d.ts +33 -0
  19. package/dist/gate/dashboardFile.js +185 -0
  20. package/dist/gate/dashboardJson.d.ts +2 -0
  21. package/dist/gate/dashboardJson.js +26 -0
  22. package/dist/gate/dashboardPage.d.ts +3 -0
  23. package/dist/gate/dashboardPage.js +307 -0
  24. package/dist/gate/dashboardServer.d.ts +11 -0
  25. package/dist/gate/dashboardServer.js +70 -0
  26. package/dist/gate/dashboardTesting.d.ts +12 -0
  27. package/dist/gate/dashboardTesting.js +99 -0
  28. package/dist/gate/guardsStep.d.ts +6 -0
  29. package/dist/gate/guardsStep.js +8 -1
  30. package/dist/gate/history.d.ts +31 -0
  31. package/dist/gate/history.js +105 -0
  32. package/dist/gate/plan.d.ts +3 -1
  33. package/dist/gate/plan.js +6 -3
  34. package/dist/gate/repository.d.ts +1 -0
  35. package/dist/gate/repository.js +1 -1
  36. package/dist/gate/runner.d.ts +3 -0
  37. package/dist/gate/runner.js +4 -1
  38. package/dist/gate/stats.d.ts +27 -0
  39. package/dist/gate/stats.js +84 -0
  40. package/dist/guards/comments/eslint.js +1 -0
  41. package/dist/guards/comments/scan.js +1 -0
  42. package/dist/guards/comments/switches.js +1 -0
  43. package/dist/guards/database/connectionHost.js +1 -0
  44. package/dist/guards/dotnet/appsettingsBound.js +1 -0
  45. package/dist/guards/dotnet/bannedNugetPackages.js +1 -0
  46. package/dist/guards/dotnet/openApiVersions.js +1 -0
  47. package/dist/guards/dotnet/suwbackkitWiring.js +1 -0
  48. package/dist/guards/dotnet/unusedNugetVersions.js +1 -0
  49. package/dist/guards/repository/bannedNpmPackages.js +1 -0
  50. package/dist/guards/repository/composePorts.js +1 -0
  51. package/dist/guards/repository/dependencyDirection.js +1 -0
  52. package/dist/guards/repository/forbiddenNames.js +1 -0
  53. package/dist/guards/repository/humanDocs.js +1 -0
  54. package/dist/guards/repository/imagePins.js +1 -0
  55. package/dist/guards/repository/justModules.js +1 -0
  56. package/dist/guards/repository/noRawColors.js +1 -0
  57. package/dist/guards/repository/repositoryLayout.js +1 -0
  58. package/dist/guards/repository/scriptsCalled.js +1 -0
  59. package/dist/guards/repository/scriptsHelp.js +1 -0
  60. package/dist/guards/repository/suwfrontkitWiring.js +1 -0
  61. package/dist/guards/repository/vsCodeSettings.js +1 -0
  62. package/dist/profiles/holdout.d.ts +2 -0
  63. package/dist/profiles/holdout.js +38 -0
  64. package/dist/profiles/index.d.ts +1 -0
  65. package/dist/profiles/index.js +1 -0
  66. package/dist/profiles/reports.d.ts +6 -0
  67. package/dist/profiles/reports.js +14 -0
  68. package/dist/profiles/verdict.js +41 -2
  69. package/dist/session/doctor.d.ts +26 -0
  70. package/dist/session/doctor.js +265 -0
  71. package/dist/session/gardenRecord.d.ts +12 -0
  72. package/dist/session/gardenRecord.js +58 -0
  73. package/dist/session/guardPr.js +2 -2
  74. package/dist/session/prePush.js +1 -1
  75. package/dist/session/suwagentInfo.d.ts +28 -0
  76. package/dist/session/suwagentInfo.js +103 -0
  77. package/package.json +1 -1
  78. package/schema/suwgate.schema.json +26 -0
@@ -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") };
@@ -0,0 +1,28 @@
1
+ interface SuwagentSkill {
2
+ name: string;
3
+ summary: string;
4
+ onlyWhenAsked: boolean;
5
+ }
6
+ interface SuwagentHook {
7
+ event: string;
8
+ matcher: string;
9
+ script: string;
10
+ }
11
+ interface SuwagentAgent {
12
+ name: string;
13
+ description: string;
14
+ tools: string;
15
+ }
16
+ export interface SuwagentInfo {
17
+ version: string;
18
+ skills: SuwagentSkill[];
19
+ hookDescription: string;
20
+ hooks: SuwagentHook[];
21
+ agents: SuwagentAgent[];
22
+ }
23
+ export interface PluginFiles {
24
+ read: (file: string) => string | null;
25
+ list: (folder: string) => string[];
26
+ }
27
+ export declare function findSuwagent(configDir: string, root: string, files: PluginFiles): SuwagentInfo | null;
28
+ export {};
@@ -0,0 +1,103 @@
1
+ import path from "node:path";
2
+ const PLUGIN_PREFIX = "suwagent@";
3
+ const ONLY_ON_REQUEST = /only when the user (?:explicitly )?asks|never on your own initiative/i;
4
+ function record(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
6
+ }
7
+ function text(value) {
8
+ return typeof value === "string" ? value : "";
9
+ }
10
+ function parseJson(source) {
11
+ if (source === null)
12
+ return null;
13
+ try {
14
+ return record(JSON.parse(source));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ function frontmatter(source) {
21
+ const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(source ?? "")?.[1];
22
+ if (block === undefined)
23
+ return {};
24
+ const fields = {};
25
+ let key = "";
26
+ for (const line of block.split(/\r?\n/)) {
27
+ const start = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line);
28
+ if (start !== null) {
29
+ key = start[1] ?? "";
30
+ fields[key] = (start[2] ?? "").replace(/^(["'])(.*)\1$/, "$2");
31
+ }
32
+ else if (key !== "" && /^\s+\S/.test(line)) {
33
+ fields[key] = `${fields[key] ?? ""} ${line.trim()}`.trim();
34
+ }
35
+ }
36
+ return fields;
37
+ }
38
+ function firstSentence(description) {
39
+ return /^(.+?[.!?])(?:\s|$)/s.exec(description)?.[1] ?? description;
40
+ }
41
+ function installedEntry(configDir, root, files) {
42
+ const plugins = record(parseJson(files.read(path.join(configDir, "plugins", "installed_plugins.json")))?.["plugins"]);
43
+ if (plugins === null)
44
+ return null;
45
+ const entries = Object.entries(plugins)
46
+ .filter(([key]) => key.startsWith(PLUGIN_PREFIX))
47
+ .flatMap(([, list]) => (Array.isArray(list) ? list : []))
48
+ .flatMap((entry) => {
49
+ const own = record(entry);
50
+ return own === null ? [] : [own];
51
+ });
52
+ const here = entries.find((entry) => text(entry["projectPath"]) !== "" && path.resolve(text(entry["projectPath"])) === path.resolve(root));
53
+ const chosen = here ?? entries.find((entry) => entry["scope"] === "user");
54
+ if (chosen === undefined || text(chosen["installPath"]) === "")
55
+ return null;
56
+ return { installPath: text(chosen["installPath"]), version: text(chosen["version"]) || "unknown" };
57
+ }
58
+ function hooksOf(source) {
59
+ return Object.entries(record(source?.["hooks"]) ?? {}).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : []).flatMap((group) => {
60
+ const own = record(group);
61
+ return (Array.isArray(own?.["hooks"]) ? own["hooks"] : []).flatMap((hook) => {
62
+ const command = record(hook);
63
+ if (command === null)
64
+ return [];
65
+ const args = Array.isArray(command["args"]) ? command["args"].map(text) : [];
66
+ const script = path.basename(args.at(-1) ?? text(command["command"]));
67
+ return [{ event, matcher: text(own?.["matcher"]) || "any", script }];
68
+ });
69
+ }));
70
+ }
71
+ export function findSuwagent(configDir, root, files) {
72
+ const entry = installedEntry(configDir, root, files);
73
+ if (entry === null)
74
+ return null;
75
+ const inside = (...parts) => path.join(entry.installPath, ...parts);
76
+ const skills = files
77
+ .list(inside("skills"))
78
+ .toSorted()
79
+ .flatMap((folder) => {
80
+ const source = files.read(inside("skills", folder, "SKILL.md"));
81
+ if (source === null)
82
+ return [];
83
+ const fields = frontmatter(source);
84
+ const description = fields["description"] ?? "";
85
+ return [
86
+ { name: fields["name"] ?? folder, summary: firstSentence(description), onlyWhenAsked: ONLY_ON_REQUEST.test(description) },
87
+ ];
88
+ });
89
+ const agents = files
90
+ .list(inside("agents"))
91
+ .filter((file) => file.endsWith(".md"))
92
+ .toSorted()
93
+ .map((file) => {
94
+ const fields = frontmatter(files.read(inside("agents", file)));
95
+ return {
96
+ name: fields["name"] ?? file.replace(/\.md$/, ""),
97
+ description: fields["description"] ?? "",
98
+ tools: fields["tools"] ?? "",
99
+ };
100
+ });
101
+ const hookFile = parseJson(files.read(inside("hooks", "hooks.json")));
102
+ return { version: entry.version, skills, hookDescription: text(hookFile?.["description"]), hooks: hooksOf(hookFile), agents };
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "One quality gate for every repository: suwgate check runs the steps of the repository's profiles and its guards, configured in suwgate.yml",
5
5
  "license": "MIT",
6
6
  "author": "Manomenu",
@@ -23,6 +23,32 @@
23
23
  "^": { "$ref": "#/$defs/relativePath" }
24
24
  }
25
25
  },
26
+ "guardSets": {
27
+ "description": "The sets of guards this repository takes; the guards of no set always run. Absent: every set. []: only the guards of no set. Known sets: stack (the owner's stack rules: libraries, naming, layout, style, the kits).",
28
+ "type": "array",
29
+ "uniqueItems": true,
30
+ "items": { "$ref": "#/$defs/id" }
31
+ },
32
+ "holdout": {
33
+ "description": "Holdout scenarios: end-to-end tests kept outside this repository, run only in CI (the step holdout, never in the quick gate or ship). CI checks them out and names the directory in SUWGATE_HOLDOUT; without it the step is skipped, which fails in CI. The command runs there with $SUWGATE_HOLDOUT and must write a JUnit XML report to $SUWGATE_HOLDOUT_REPORT. The gate shows only the names of the failed scenarios, never the command's output.",
34
+ "type": "object",
35
+ "additionalProperties": false,
36
+ "required": ["run"],
37
+ "properties": {
38
+ "run": {
39
+ "type": "string",
40
+ "minLength": 1,
41
+ "description": "A bash command, run in the repository root, that runs the scenarios in $SUWGATE_HOLDOUT and writes a JUnit XML report to $SUWGATE_HOLDOUT_REPORT."
42
+ },
43
+ "after": {
44
+ "type": "array",
45
+ "uniqueItems": true,
46
+ "items": { "$ref": "#/$defs/id" },
47
+ "description": "Steps that must finish first (e.g. the build the scenarios run against)."
48
+ },
49
+ "limitSeconds": { "type": "integer", "minimum": 1, "description": "The step is killed above this (default 600)." }
50
+ }
51
+ },
26
52
  "quick": {
27
53
  "description": "The quick gate (suwgate check --quick).",
28
54
  "type": "object",