@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
@@ -0,0 +1,111 @@
1
+ import { GUARDS_STEP } from "./plan.js";
2
+ import { summarize } from "./stats.js";
3
+ const DAY_MS = 24 * 60 * 60 * 1000;
4
+ const BUCKETS = 6;
5
+ export function runsInPeriod(history, days, now) {
6
+ const since = now.getTime() - days * DAY_MS;
7
+ return history.filter((run) => Date.parse(run.at) >= since);
8
+ }
9
+ function stoppersOf(run) {
10
+ if (run.verdict !== "red")
11
+ return [];
12
+ const guards = Object.entries(run.guards)
13
+ .filter(([, findings]) => findings > 0)
14
+ .map(([id]) => ({ kind: "guard", id }));
15
+ const steps = run.steps
16
+ .filter((step) => step.verdict === "fail" && !(step.id === GUARDS_STEP && guards.length > 0))
17
+ .map((step) => ({ kind: "step", id: step.id }));
18
+ return [...guards, ...steps];
19
+ }
20
+ function newestFirst(a, b) {
21
+ return Date.parse(b.at) - Date.parse(a.at);
22
+ }
23
+ export function stoppers(history, days, now) {
24
+ const found = new Map();
25
+ for (const run of runsInPeriod(history, days, now).toSorted(newestFirst)) {
26
+ for (const { kind, id } of stoppersOf(run)) {
27
+ const key = `${kind}:${id}`;
28
+ const own = found.get(key);
29
+ if (own === undefined) {
30
+ found.set(key, { kind, id, runs: 1, ci: run.ci ? 1 : 0, last: run.at, branches: [run.branch] });
31
+ }
32
+ else {
33
+ own.runs += 1;
34
+ if (run.ci)
35
+ own.ci += 1;
36
+ if (!own.branches.includes(run.branch))
37
+ own.branches.push(run.branch);
38
+ }
39
+ }
40
+ }
41
+ return [...found.values()].sort((a, b) => Date.parse(b.last) - Date.parse(a.last) || b.runs - a.runs || a.id.localeCompare(b.id));
42
+ }
43
+ export function causeOf(run) {
44
+ const ids = stoppersOf(run).map((stopper) => stopper.id);
45
+ return ids.length === 0 ? "no cause recorded" : ids.join(", ");
46
+ }
47
+ export function branches(history, days, now) {
48
+ const found = new Map();
49
+ for (const run of runsInPeriod(history, days, now)) {
50
+ const own = found.get(run.branch) ?? { branch: run.branch, runs: 0, ci: 0, red: 0, lastRed: null, lastRedRun: null };
51
+ own.runs += 1;
52
+ if (run.ci)
53
+ own.ci += 1;
54
+ if (run.verdict === "red") {
55
+ own.red += 1;
56
+ if (own.lastRedRun === null || newestFirst(own.lastRedRun, run) > 0)
57
+ own.lastRedRun = run;
58
+ }
59
+ found.set(run.branch, own);
60
+ }
61
+ return [...found.values()]
62
+ .map(({ lastRedRun, ...own }) => ({
63
+ ...own,
64
+ lastRed: lastRedRun === null ? null : { at: lastRedRun.at, cause: causeOf(lastRedRun) },
65
+ }))
66
+ .sort((a, b) => Date.parse(b.lastRed?.at ?? "1970-01-01") - Date.parse(a.lastRed?.at ?? "1970-01-01") ||
67
+ b.runs - a.runs ||
68
+ a.branch.localeCompare(b.branch));
69
+ }
70
+ function between(history, from, to) {
71
+ return history.filter((run) => Date.parse(run.at) >= from && Date.parse(run.at) < to);
72
+ }
73
+ function measures(window, end) {
74
+ const stats = summarize(window.filter((run) => run.mode !== "step"), Number.POSITIVE_INFINITY, new Date(end));
75
+ const red = Object.values(stats.modes).reduce((total, mode) => total + mode.red, 0);
76
+ return {
77
+ redShare: stats.runs === 0 ? null : Math.round((red / stats.runs) * 100),
78
+ quickMedian: stats.quick?.medianSeconds ?? null,
79
+ overBudget: stats.quick?.overBudget ?? 0,
80
+ };
81
+ }
82
+ export function trends(history, days, now) {
83
+ const length = days * DAY_MS;
84
+ const end = now.getTime();
85
+ const start = end - length;
86
+ const current = measures(between(history, start, Number.POSITIVE_INFINITY), end);
87
+ const before = measures(between(history, start - length, start), start);
88
+ const slices = Array.from({ length: BUCKETS }, (_, index) => {
89
+ const from = start + (length / BUCKETS) * index;
90
+ const to = start + (length / BUCKETS) * (index + 1);
91
+ return measures(between(history, from, index === BUCKETS - 1 ? Number.POSITIVE_INFINITY : to), to);
92
+ });
93
+ const point = (key) => ({
94
+ now: current[key],
95
+ before: before[key],
96
+ buckets: slices.map((slice) => slice[key] ?? 0),
97
+ });
98
+ return { redShare: point("redShare"), quickMedian: point("quickMedian"), overBudget: point("overBudget") };
99
+ }
100
+ export function runsPerDay(history, days, now) {
101
+ const found = new Map();
102
+ for (const run of runsInPeriod(history, days, now).toSorted(newestFirst)) {
103
+ const day = new Date(run.at).toISOString().slice(0, 10);
104
+ const own = found.get(day) ?? { day, runs: 0, red: 0 };
105
+ own.runs += 1;
106
+ if (run.verdict === "red")
107
+ own.red += 1;
108
+ found.set(day, own);
109
+ }
110
+ return [...found.values()];
111
+ }
@@ -1,10 +1,13 @@
1
1
  import { type Catalog } from "./config.ts";
2
+ import { type RunMode, type RunSource } from "./history.ts";
2
3
  export interface CheckOptions {
3
4
  cwd: string;
4
5
  quick: boolean;
5
6
  verbose: boolean;
6
7
  env: NodeJS.ProcessEnv;
7
8
  catalog: Catalog;
9
+ mode?: RunMode;
10
+ source?: RunSource;
8
11
  }
9
12
  export interface StepOptions {
10
13
  cwd: string;
@@ -13,6 +16,7 @@ export interface StepOptions {
13
16
  args: readonly string[];
14
17
  verbose: boolean;
15
18
  runFolder?: string;
19
+ recordedAs?: RunMode;
16
20
  env: NodeJS.ProcessEnv;
17
21
  catalog: Catalog;
18
22
  }
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import { parse } from "yaml";
5
5
  import { loadConfig, MAX_ALIASES } from "./config.js";
6
6
  import { sameException } from "./guardsStep.js";
7
+ import { branchOf, recordRun } from "./history.js";
7
8
  import { allSteps, GUARDS_STEP, listSteps, plan } from "./plan.js";
8
9
  import { report } from "./report.js";
9
10
  import { changedFiles, fileOnMaster, repositoryFiles, repositoryRoot } from "./repository.js";
@@ -85,14 +86,49 @@ async function run(command, prepared, options) {
85
86
  verbose: options.verbose,
86
87
  ...(options.verbose && options.target !== undefined ? { passedLogOf: options.target.id } : {}),
87
88
  });
89
+ if (options.recorded !== undefined) {
90
+ const quickLimit = options.quick ? (prepared.quickLimit ?? config.quickLimitSeconds ?? DEFAULT_QUICK_LIMIT_SECONDS) : null;
91
+ recordRun(root, runRecord({
92
+ ...options.recorded,
93
+ root,
94
+ results,
95
+ passed,
96
+ elapsed: (performance.now() - began) / 1000,
97
+ overBudget: quickLimit !== null && totalSeconds > quickLimit && results.every((result) => result.status !== "fail"),
98
+ ci: (options.env["CI"] ?? "") !== "",
99
+ }));
100
+ }
88
101
  return { exitCode: passed ? 0 : 1, text };
89
102
  }
103
+ function runRecord(input) {
104
+ const tally = input.results.find((result) => result.guards !== undefined)?.guards;
105
+ return {
106
+ at: new Date().toISOString(),
107
+ mode: input.mode,
108
+ source: input.source,
109
+ branch: branchOf(input.root),
110
+ verdict: input.passed ? "green" : "red",
111
+ seconds: tenths(input.elapsed),
112
+ overBudget: input.overBudget,
113
+ steps: input.results.map((result) => ({ id: result.step.id, verdict: result.status, seconds: tenths(result.elapsed ?? 0) })),
114
+ ran: tally?.ran ?? [],
115
+ guards: tally?.failed ?? {},
116
+ excepted: tally?.excepted ?? {},
117
+ ci: input.ci,
118
+ };
119
+ }
120
+ function tenths(seconds) {
121
+ return Math.round(seconds * 10) / 10;
122
+ }
90
123
  export async function check(options) {
91
124
  const command = `suwgate check${options.quick ? " --quick" : ""}`;
92
125
  const prepared = prepare(command, options.cwd, options.env, options.catalog);
93
126
  if ("exitCode" in prepared)
94
127
  return prepared;
95
- return run(command, prepared, options);
128
+ return run(command, prepared, {
129
+ ...options,
130
+ recorded: { mode: options.mode ?? (options.quick ? "quick" : "full"), source: options.source ?? "cli" },
131
+ });
96
132
  }
97
133
  function listing(config, root, catalog) {
98
134
  const listed = listSteps({ root, quick: false, config, catalog, files: [], changed: () => [] });
@@ -131,5 +167,6 @@ export async function step(options) {
131
167
  catalog: options.catalog,
132
168
  target: { id: options.id, only: options.only, args: options.args },
133
169
  ...(options.runFolder === undefined ? {} : { runFolder: options.runFolder }),
170
+ ...(options.recordedAs === undefined ? {} : { recorded: { mode: options.recordedAs, source: "cli" } }),
134
171
  });
135
172
  }
@@ -0,0 +1,21 @@
1
+ import { type RunRecord } from "./history.ts";
2
+ export declare const CI_HISTORY_FILE = "suwgate-ci-runs.jsonl";
3
+ export declare const CI_ARTIFACT = "gate-history";
4
+ export declare const CI_ARTIFACT_FILE = "runs.jsonl";
5
+ export declare const RETENTION_DAYS = 90;
6
+ interface GhResult {
7
+ ok: boolean;
8
+ stdout: string;
9
+ stderr: string;
10
+ }
11
+ export type Gh = (root: string, args: readonly string[]) => Promise<GhResult>;
12
+ export interface CiView {
13
+ state: "synced" | "syncing" | "unavailable" | "off";
14
+ syncedTo: string | null;
15
+ reason: string;
16
+ }
17
+ export declare function readCiRuns(root: string): RunRecord[];
18
+ export declare function allRuns(root: string): RunRecord[];
19
+ export declare function syncedTo(root: string): string | null;
20
+ export declare function syncCi(root: string, now: Date, run?: Gh): Promise<CiView>;
21
+ export {};
@@ -0,0 +1,195 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { inCommonDir, parseRuns, readRuns } from "./history.js";
6
+ export const CI_HISTORY_FILE = "suwgate-ci-runs.jsonl";
7
+ const CI_SYNC_FILE = "suwgate-ci-sync.json";
8
+ export const CI_ARTIFACT = "gate-history";
9
+ export const CI_ARTIFACT_FILE = "runs.jsonl";
10
+ export const RETENTION_DAYS = 90;
11
+ const DAY_MS = 24 * 60 * 60 * 1000;
12
+ const PAGE_SIZE = 100;
13
+ const MAX_PAGES = 100;
14
+ const OVERLAP_MS = 60 * 60 * 1000;
15
+ const PARALLEL = 6;
16
+ const GH_TIMEOUT_MS = 60_000;
17
+ const GH_BUFFER_BYTES = 32 * 1024 * 1024;
18
+ const gh = (root, args) => new Promise((resolve) => {
19
+ execFile("gh", [...args], { cwd: root, timeout: GH_TIMEOUT_MS, maxBuffer: GH_BUFFER_BYTES }, (error, stdout, stderr) => {
20
+ const missing = error !== null && error.code === "ENOENT";
21
+ resolve({ ok: error === null, stdout, stderr: missing ? "the gh command is not installed" : stderr });
22
+ });
23
+ });
24
+ export function readCiRuns(root) {
25
+ const file = inCommonDir(root, CI_HISTORY_FILE);
26
+ if (file === null)
27
+ return [];
28
+ try {
29
+ return parseRuns(readFileSync(file, "utf8"));
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ }
35
+ export function allRuns(root) {
36
+ return [...readRuns(root), ...readCiRuns(root)];
37
+ }
38
+ function syncState(root) {
39
+ const file = inCommonDir(root, CI_SYNC_FILE);
40
+ if (file === null)
41
+ return { syncedTo: null, seen: {} };
42
+ try {
43
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
44
+ const to = typeof parsed.syncedTo === "string" && !Number.isNaN(Date.parse(parsed.syncedTo)) ? parsed.syncedTo : null;
45
+ const seen = typeof parsed.seen === "object" && parsed.seen !== null ? parsed.seen : {};
46
+ return {
47
+ syncedTo: to,
48
+ seen: Object.fromEntries(Object.entries(seen).filter((entry) => typeof entry[1] === "string")),
49
+ };
50
+ }
51
+ catch {
52
+ return { syncedTo: null, seen: {} };
53
+ }
54
+ }
55
+ export function syncedTo(root) {
56
+ return syncState(root).syncedTo;
57
+ }
58
+ function artifactOf(value) {
59
+ const item = value;
60
+ const runId = item.workflow_run?.id;
61
+ if (typeof item.id !== "number" || typeof item.name !== "string" || !item.name.startsWith(CI_ARTIFACT))
62
+ return null;
63
+ if (typeof item.created_at !== "string" || typeof runId !== "number" || item.expired === true)
64
+ return null;
65
+ const repository = typeof item.url === "string" ? (/\/repos\/([^/]+\/[^/]+)\//.exec(item.url)?.[1] ?? "") : "";
66
+ return {
67
+ id: item.id,
68
+ name: item.name,
69
+ createdAt: item.created_at,
70
+ runId,
71
+ branch: typeof item.workflow_run?.head_branch === "string" ? item.workflow_run.head_branch : null,
72
+ commit: typeof item.workflow_run?.head_sha === "string" ? item.workflow_run.head_sha : null,
73
+ runUrl: repository === "" ? String(runId) : `https://github.com/${repository}/actions/runs/${runId}`,
74
+ };
75
+ }
76
+ function createdAt(item) {
77
+ const value = item.created_at;
78
+ return typeof value === "string" ? Date.parse(value) : Number.NaN;
79
+ }
80
+ async function listUnread(root, since, seen, run) {
81
+ const found = [];
82
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
83
+ const listed = await run(root, ["api", `repos/{owner}/{repo}/actions/artifacts?per_page=${PAGE_SIZE}&page=${page}`]);
84
+ if (!listed.ok)
85
+ return firstLine(listed.stderr);
86
+ let items;
87
+ try {
88
+ const parsed = JSON.parse(listed.stdout);
89
+ items = Array.isArray(parsed.artifacts) ? parsed.artifacts : [];
90
+ }
91
+ catch {
92
+ return "GitHub's answer about the artifacts is not JSON";
93
+ }
94
+ const recent = items.filter((item) => createdAt(item) >= since);
95
+ found.push(...recent.flatMap((item) => artifactOf(item) ?? []).filter((artifact) => seen[String(artifact.id)] === undefined));
96
+ if (items.length < PAGE_SIZE || recent.length === 0)
97
+ break;
98
+ }
99
+ return found.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id - b.id);
100
+ }
101
+ function firstLine(text) {
102
+ return (text
103
+ .split("\n")
104
+ .map((line) => line.trim())
105
+ .find((line) => line !== "") ?? "gh failed without a message");
106
+ }
107
+ async function recordsOf(root, artifact, run) {
108
+ const folder = mkdtempSync(path.join(tmpdir(), "suwgate-ci-"));
109
+ try {
110
+ const downloaded = await run(root, ["run", "download", String(artifact.runId), "--name", artifact.name, "--dir", folder]);
111
+ if (!downloaded.ok)
112
+ return firstLine(downloaded.stderr);
113
+ let text;
114
+ try {
115
+ text = readFileSync(path.join(folder, CI_ARTIFACT_FILE), "utf8");
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ return parseRuns(text).map((record) => ({
121
+ ...record,
122
+ branch: artifact.branch ?? record.branch,
123
+ ci: true,
124
+ run: artifact.runUrl,
125
+ ...(artifact.commit === null ? {} : { commit: artifact.commit }),
126
+ }));
127
+ }
128
+ finally {
129
+ rmSync(folder, { recursive: true, force: true });
130
+ }
131
+ }
132
+ function keyOf(record) {
133
+ return `${record.run ?? ""}|${record.at}`;
134
+ }
135
+ function replace(file, text) {
136
+ const draft = `${file}.${process.pid}.tmp`;
137
+ writeFileSync(draft, text);
138
+ renameSync(draft, file);
139
+ }
140
+ function later(a, b) {
141
+ if (a === null || b === null)
142
+ return a ?? b;
143
+ return Date.parse(a) >= Date.parse(b) ? a : b;
144
+ }
145
+ function save(root, read, state, floor) {
146
+ const history = inCommonDir(root, CI_HISTORY_FILE);
147
+ const sync = inCommonDir(root, CI_SYNC_FILE);
148
+ if (history === null || sync === null)
149
+ return state.syncedTo;
150
+ const onDisk = syncState(root);
151
+ const records = new Map([...readCiRuns(root), ...read].map((record) => [keyOf(record), record]));
152
+ const to = later(onDisk.syncedTo, state.syncedTo);
153
+ const overlap = to === null ? 0 : Date.parse(to) - OVERLAP_MS;
154
+ const seen = Object.fromEntries(Object.entries({ ...onDisk.seen, ...state.seen }).filter(([, at]) => Date.parse(at) >= overlap));
155
+ replace(history, [...records.values()]
156
+ .filter((record) => Date.parse(record.at) >= floor)
157
+ .map((record) => `${JSON.stringify(record)}\n`)
158
+ .join(""));
159
+ if (to !== null)
160
+ replace(sync, `${JSON.stringify({ syncedTo: to, seen })}\n`);
161
+ return to;
162
+ }
163
+ export async function syncCi(root, now, run = gh) {
164
+ const floor = now.getTime() - RETENTION_DAYS * DAY_MS;
165
+ const before = syncState(root);
166
+ const since = before.syncedTo === null ? floor : Math.max(floor, Date.parse(before.syncedTo) - OVERLAP_MS);
167
+ const listed = await listUnread(root, since, before.seen, run);
168
+ if (typeof listed === "string")
169
+ return { state: "unavailable", syncedTo: before.syncedTo, reason: listed };
170
+ const read = [];
171
+ const state = { syncedTo: before.syncedTo, seen: {} };
172
+ let failure = "";
173
+ for (let start = 0; start < listed.length && failure === ""; start += PARALLEL) {
174
+ const batch = listed.slice(start, start + PARALLEL);
175
+ const results = await Promise.all(batch.map((artifact) => recordsOf(root, artifact, run)));
176
+ for (const [index, result] of results.entries()) {
177
+ const artifact = batch[index];
178
+ if (typeof result === "string" || artifact === undefined) {
179
+ failure = typeof result === "string" ? result : failure;
180
+ break;
181
+ }
182
+ read.push(...result);
183
+ state.seen[String(artifact.id)] = artifact.createdAt;
184
+ state.syncedTo = later(state.syncedTo, artifact.createdAt);
185
+ }
186
+ }
187
+ let to;
188
+ try {
189
+ to = save(root, read, state, floor);
190
+ }
191
+ catch {
192
+ return { state: "unavailable", syncedTo: before.syncedTo, reason: "the runs of CI could not be written to the git directory" };
193
+ }
194
+ return failure === "" ? { state: "synced", syncedTo: to, reason: "" } : { state: "unavailable", syncedTo: to, reason: failure };
195
+ }
@@ -1,4 +1,4 @@
1
- import { type DotnetGuard, type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
1
+ import { type DotnetGuard, type Guard, type GuardException, type Holdout, type Profile, type Step } from "./contract.ts";
2
2
  export declare const CONFIG_FILE = "suwgate.yml";
3
3
  export declare const MAX_ALIASES = 10000;
4
4
  interface AddedStep {
@@ -29,6 +29,8 @@ interface ConfiguredStep extends Environment {
29
29
  export interface Config {
30
30
  profiles: Profile[];
31
31
  directories: Partial<Record<Profile, string>>;
32
+ guardSets?: string[];
33
+ holdout?: Holdout;
32
34
  add: AddedStep[];
33
35
  skip: SkippedStep[];
34
36
  configure: Record<string, ConfiguredStep>;
@@ -42,12 +44,14 @@ export interface Catalog {
42
44
  guards: readonly Guard[];
43
45
  dotnetGuards: readonly DotnetGuard[];
44
46
  stepsFor(profiles: readonly Profile[]): readonly Step[];
47
+ holdoutStep?(holdout: Holdout): Step;
45
48
  }
46
49
  export type Loaded = {
47
50
  config: Config;
48
51
  } | {
49
52
  problems: string[];
50
53
  };
54
+ export declare function takesGuard(config: Pick<Config, "guardSets">, guard: Pick<Guard, "set">): boolean;
51
55
  export declare function parseConfig(text: string, catalog: Catalog): Loaded;
52
56
  export declare function loadConfig(root: string, catalog: Catalog): Loaded;
53
57
  export {};
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Ajv2020 } from "ajv/dist/2020.js";
4
4
  import { isNode, LineCounter, parseDocument } from "yaml";
5
- import { PROFILES } from "./contract.js";
5
+ import { HOLDOUT_STEP, PROFILES, } from "./contract.js";
6
6
  export const CONFIG_FILE = "suwgate.yml";
7
7
  const SCHEMA_FILE = new URL("../../schema/suwgate.schema.json", import.meta.url);
8
8
  export const MAX_ALIASES = 10_000;
@@ -37,7 +37,11 @@ function describe(error) {
37
37
  case "required": {
38
38
  const missing = String(params["missingProperty"]);
39
39
  const what = parts[0] === "exceptions" ? "exception" : parts[0] === "guards" ? "skipped guard" : "skipped step";
40
- const fix = missing === "reason" ? `: every ${what} says why (reason: <why>)` : "";
40
+ const fix = missing === "reason"
41
+ ? `: every ${what} says why (reason: <why>)`
42
+ : parts[0] === "holdout" && missing === "run"
43
+ ? ": give the bash command that runs the scenarios and writes a JUnit XML report to $SUWGATE_HOLDOUT_REPORT (run: <command>)"
44
+ : "";
41
45
  return `${where} has no "${missing}"${fix}`;
42
46
  }
43
47
  case "additionalProperties":
@@ -57,6 +61,25 @@ function describe(error) {
57
61
  function relevant(errors) {
58
62
  return errors.filter((error) => error.keyword !== "if" && !(error.keyword === "enum" && errors.some((other) => other.keyword === "propertyNames")));
59
63
  }
64
+ export function takesGuard(config, guard) {
65
+ return guard.set === undefined || config.guardSets === undefined || config.guardSets.includes(guard.set);
66
+ }
67
+ function knownSets(catalog) {
68
+ return [...new Set(catalog.guards.flatMap((guard) => (guard.set === undefined ? [] : [guard.set])))];
69
+ }
70
+ function untakenSet(raw, catalog, id, what) {
71
+ const set = catalog.guards.find((guard) => guard.id === id)?.set;
72
+ if (set === undefined || raw.guardSets === undefined || raw.guardSets.includes(set))
73
+ return null;
74
+ return `"${id}" is a guard of the set "${set}", which this repository does not take: delete the ${what}, or add "${set}" to guardSets`;
75
+ }
76
+ function checkGuardSets(raw, catalog, problem) {
77
+ const known = knownSets(catalog);
78
+ (raw.guardSets ?? []).forEach((set, index) => {
79
+ if (!known.includes(set))
80
+ problem(["guardSets", index], `no guard set "${set}": the sets are ${known.join(", ")}`);
81
+ });
82
+ }
60
83
  function guardProfile(id, guards) {
61
84
  if (Object.keys(DOTNET_GUARD_PREFIXES).some((prefix) => id.startsWith(prefix)))
62
85
  return "dotnet-guard";
@@ -80,12 +103,34 @@ function checkExceptions(raw, catalog, problem) {
80
103
  else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
81
104
  problem(where, `"${exception.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the exception`);
82
105
  }
106
+ const untaken = untakenSet(raw, catalog, exception.guard, "exception");
107
+ if (untaken !== null)
108
+ problem(where, untaken);
83
109
  const key = `${exception.guard}\u0000${exception.target}\u0000${exception.message ?? ""}`;
84
110
  if (seen.has(key))
85
111
  problem(where, `the same exception (${exception.guard}, ${exception.target}) is listed twice: keep one`);
86
112
  seen.add(key);
87
113
  });
88
114
  }
115
+ function checkHoldout(raw, catalog, problem) {
116
+ if (raw.holdout === undefined)
117
+ return;
118
+ const known = catalog.stepsFor(raw.profiles).map((step) => step.id);
119
+ const added = (raw.steps?.add ?? []).map((step) => step.name);
120
+ (raw.holdout.after ?? []).forEach((after, at) => {
121
+ if (!known.includes(after) && !added.includes(after)) {
122
+ problem(["holdout", "after", at], `no step "${after}": the steps are ${[...known, ...added].join(", ")}`);
123
+ }
124
+ });
125
+ added.forEach((name, index) => {
126
+ if (name === HOLDOUT_STEP)
127
+ problem(["steps", "add", index, "name"], `"${HOLDOUT_STEP}" is the step of the holdout key: pick another name, or delete the holdout key`);
128
+ });
129
+ (raw.steps?.skip ?? []).forEach((skipped, index) => {
130
+ if (skipped.step === HOLDOUT_STEP)
131
+ problem(["steps", "skip", index, "step"], `"${HOLDOUT_STEP}" is the step of the holdout key, not of a profile: delete the holdout key to run no holdout scenarios`);
132
+ });
133
+ }
89
134
  function checkSteps(raw, catalog, problem) {
90
135
  const known = catalog.stepsFor(raw.profiles).map((step) => step.id);
91
136
  const added = (raw.steps?.add ?? []).map((step) => step.name);
@@ -149,6 +194,8 @@ function circle(raw, catalog) {
149
194
  }
150
195
  for (const step of raw.steps?.add ?? [])
151
196
  waits.set(step.name, step.after ?? []);
197
+ if (raw.holdout !== undefined)
198
+ waits.set(HOLDOUT_STEP, raw.holdout.after ?? []);
152
199
  const done = new Set();
153
200
  const visit = (id, path) => {
154
201
  if (path.includes(id))
@@ -188,6 +235,9 @@ function checkSkippedGuards(raw, catalog, problem) {
188
235
  else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
189
236
  problem(where, `"${entry.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the entry`);
190
237
  }
238
+ const untaken = untakenSet(raw, catalog, entry.guard, "entry");
239
+ if (untaken !== null)
240
+ problem(where, untaken);
191
241
  if (skipped.indexOf(entry.guard) !== index)
192
242
  problem(where, `"${entry.guard}" is skipped twice: keep one entry`);
193
243
  });
@@ -244,8 +294,10 @@ export function parseConfig(text, catalog) {
244
294
  problems.push(`${locate(document, lineCounter, parts)}: ${shownPath(parts)}: ${text}`);
245
295
  };
246
296
  checkDirectories(data, problem);
297
+ checkGuardSets(data, catalog, problem);
247
298
  checkExceptions(data, catalog, problem);
248
299
  checkSteps(data, catalog, problem);
300
+ checkHoldout(data, catalog, problem);
249
301
  checkSkippedGuards(data, catalog, problem);
250
302
  checkSettings(data, catalog, problem);
251
303
  checkConfigure(data, catalog, problem);
@@ -260,6 +312,8 @@ export function parseConfig(text, catalog) {
260
312
  config: {
261
313
  profiles: PROFILES.filter((profile) => data.profiles.includes(profile)),
262
314
  directories: data.directories ?? {},
315
+ ...(data.guardSets === undefined ? {} : { guardSets: data.guardSets }),
316
+ ...(data.holdout === undefined ? {} : { holdout: data.holdout }),
263
317
  add: data.steps?.add ?? [],
264
318
  skip: data.steps?.skip ?? [],
265
319
  configure: data.steps?.configure ?? {},
@@ -0,0 +1,15 @@
1
+ import type { DashboardRequest } from "./dashboardFile.ts";
2
+ import { type RunRecord } from "./history.ts";
3
+ export interface ContextData {
4
+ version: string;
5
+ binary: string;
6
+ profiles: readonly string[];
7
+ guardSets: readonly string[] | undefined;
8
+ unwiredHooks: readonly string[];
9
+ branch: string;
10
+ branchRuns: readonly RunRecord[];
11
+ stoppedIds: readonly string[];
12
+ attention: number;
13
+ }
14
+ export declare function renderContext(data: ContextData): string;
15
+ export declare function readContext(request: DashboardRequest, version: string, entry: string): string;