@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
@@ -0,0 +1,107 @@
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, last: run.at, branches: [run.branch] });
31
+ }
32
+ else {
33
+ own.runs += 1;
34
+ if (!own.branches.includes(run.branch))
35
+ own.branches.push(run.branch);
36
+ }
37
+ }
38
+ }
39
+ return [...found.values()].sort((a, b) => Date.parse(b.last) - Date.parse(a.last) || b.runs - a.runs || a.id.localeCompare(b.id));
40
+ }
41
+ export function causeOf(run) {
42
+ const ids = stoppersOf(run).map((stopper) => stopper.id);
43
+ return ids.length === 0 ? "no cause recorded" : ids.join(", ");
44
+ }
45
+ export function branches(history, days, now) {
46
+ const found = new Map();
47
+ for (const run of runsInPeriod(history, days, now)) {
48
+ const own = found.get(run.branch) ?? { branch: run.branch, runs: 0, red: 0, lastRed: null, lastRedRun: null };
49
+ own.runs += 1;
50
+ if (run.verdict === "red") {
51
+ own.red += 1;
52
+ if (own.lastRedRun === null || newestFirst(own.lastRedRun, run) > 0)
53
+ own.lastRedRun = run;
54
+ }
55
+ found.set(run.branch, own);
56
+ }
57
+ return [...found.values()]
58
+ .map(({ lastRedRun, ...own }) => ({
59
+ ...own,
60
+ lastRed: lastRedRun === null ? null : { at: lastRedRun.at, cause: causeOf(lastRedRun) },
61
+ }))
62
+ .sort((a, b) => Date.parse(b.lastRed?.at ?? "1970-01-01") - Date.parse(a.lastRed?.at ?? "1970-01-01") ||
63
+ b.runs - a.runs ||
64
+ a.branch.localeCompare(b.branch));
65
+ }
66
+ function between(history, from, to) {
67
+ return history.filter((run) => Date.parse(run.at) >= from && Date.parse(run.at) < to);
68
+ }
69
+ function measures(window, end) {
70
+ const stats = summarize(window, Number.POSITIVE_INFINITY, new Date(end));
71
+ const red = Object.values(stats.modes).reduce((total, mode) => total + mode.red, 0);
72
+ return {
73
+ redShare: stats.runs === 0 ? null : Math.round((red / stats.runs) * 100),
74
+ quickMedian: stats.quick?.medianSeconds ?? null,
75
+ overBudget: stats.quick?.overBudget ?? 0,
76
+ };
77
+ }
78
+ export function trends(history, days, now) {
79
+ const length = days * DAY_MS;
80
+ const end = now.getTime();
81
+ const start = end - length;
82
+ const current = measures(between(history, start, Number.POSITIVE_INFINITY), end);
83
+ const before = measures(between(history, start - length, start), start);
84
+ const slices = Array.from({ length: BUCKETS }, (_, index) => {
85
+ const from = start + (length / BUCKETS) * index;
86
+ const to = start + (length / BUCKETS) * (index + 1);
87
+ return measures(between(history, from, index === BUCKETS - 1 ? Number.POSITIVE_INFINITY : to), to);
88
+ });
89
+ const point = (key) => ({
90
+ now: current[key],
91
+ before: before[key],
92
+ buckets: slices.map((slice) => slice[key] ?? 0),
93
+ });
94
+ return { redShare: point("redShare"), quickMedian: point("quickMedian"), overBudget: point("overBudget") };
95
+ }
96
+ export function runsPerDay(history, days, now) {
97
+ const found = new Map();
98
+ for (const run of runsInPeriod(history, days, now).toSorted(newestFirst)) {
99
+ const day = new Date(run.at).toISOString().slice(0, 10);
100
+ const own = found.get(day) ?? { day, runs: 0, red: 0 };
101
+ own.runs += 1;
102
+ if (run.verdict === "red")
103
+ own.red += 1;
104
+ found.set(day, own);
105
+ }
106
+ return [...found.values()];
107
+ }
@@ -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;
@@ -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: () => [] });
@@ -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;
@@ -0,0 +1,97 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { causeOf, runsInPeriod, stoppers } from "./breakdown.js";
4
+ import { loadConfig } from "./config.js";
5
+ import { attentionOf, hookRows } from "./dashboard.js";
6
+ import { branchOf, readRuns } from "./history.js";
7
+ import { git, repositoryRoot } from "./repository.js";
8
+ const MAX_CHARACTERS = 1800;
9
+ const PERIOD_DAYS = 30;
10
+ const RECENT_RUNS = 10;
11
+ const LISTED = 3;
12
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
13
+ const HOW_WORK_REACHES_A_PULL_REQUEST = [
14
+ "suwgate, how work reaches a pull request here:",
15
+ "- The gate runs quick after every turn and before every commit: fix what it reports.",
16
+ "- Never run the full gate (`suwgate check` without `--quick`): CI does. Never `--no-verify`, never edit the gate.",
17
+ "- A finished change goes to a pull request only through /suwgate:ship: a small change gets the gate only, a normal one also simplify and review, a careful one cannot drop the review.",
18
+ "- The owner reads the PR proof and decides the merge.",
19
+ ];
20
+ const WHERE_TO_LOOK = [
21
+ "Where to look:",
22
+ "- `suwgate dashboard --json` and the insights skill answer questions about the state; /suwgate:dashboard-open shows the owner the page.",
23
+ ];
24
+ function clip(text, length) {
25
+ return text.length <= length ? text : `${text.slice(0, length - 3)}...`;
26
+ }
27
+ function stamp(iso) {
28
+ const date = new Date(iso);
29
+ return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()] ?? ""} ${iso.slice(11, 16)} UTC`;
30
+ }
31
+ function lastRun(data) {
32
+ const recent = data.branchRuns.toSorted((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, RECENT_RUNS);
33
+ const [last] = recent;
34
+ if (last === undefined)
35
+ return `- Branch ${clip(data.branch, 60)}: no run recorded here yet.`;
36
+ const red = recent.filter((run) => run.verdict === "red").length;
37
+ const verdict = last.verdict === "red" ? `red, stopped by ${clip(causeOf(last), 80)}` : "green";
38
+ return `- Branch ${clip(data.branch, 60)}: last run ${stamp(last.at)}, ${verdict}; red runs among the last ${recent.length} here: ${red}.`;
39
+ }
40
+ export function renderContext(data) {
41
+ const sets = data.guardSets === undefined
42
+ ? "all guard sets"
43
+ : data.guardSets.length === 0
44
+ ? "no guard set"
45
+ : `guard sets ${data.guardSets.join(", ")}`;
46
+ const hooks = data.unwiredHooks.length === 0 ? "all five hooks wired" : `hooks not wired here: ${data.unwiredHooks.join(", ")}`;
47
+ const needs = data.attention === 0
48
+ ? "nothing from the runs or the hooks needs the owner"
49
+ : `${data.attention} thing${data.attention === 1 ? "" : "s"} from the runs and the hooks need the owner${data.stoppedIds.length === 0 ? "" : ` (stopped the gate: ${data.stoppedIds.slice(0, LISTED).join(", ")})`}`;
50
+ const text = [
51
+ ...HOW_WORK_REACHES_A_PULL_REQUEST,
52
+ "This repository now:",
53
+ `- suwgate ${data.version}, call it as ${data.binary}; profiles ${data.profiles.join(", ")}; ${sets}; ${hooks}.`,
54
+ lastRun(data),
55
+ `- ${needs}; the wall needs the network: run /suwgate:doctor.`,
56
+ ...WHERE_TO_LOOK,
57
+ ].join("\n");
58
+ return clip(text, MAX_CHARACTERS);
59
+ }
60
+ function binaryOf(root, entry) {
61
+ const relative = path.relative(root, entry);
62
+ return relative.startsWith("..") || relative.includes("node_modules")
63
+ ? "the repository's own `suwgate` (node_modules)"
64
+ : `\`node ${relative}\``;
65
+ }
66
+ export function readContext(request, version, entry) {
67
+ const root = repositoryRoot(request.cwd);
68
+ if (root === null)
69
+ return "";
70
+ const loaded = loadConfig(root, request.catalog);
71
+ if ("problems" in loaded)
72
+ return "";
73
+ const read = (file) => {
74
+ try {
75
+ return readFileSync(path.join(root, file), "utf8");
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ };
81
+ const now = request.now();
82
+ const runs = readRuns(root);
83
+ const branch = branchOf(root);
84
+ const hooks = hookRows(read, git(root, ["config", "--get", "core.hooksPath"])?.trim() ?? "");
85
+ const stopped = stoppers(runs, PERIOD_DAYS, now);
86
+ return `${renderContext({
87
+ version,
88
+ binary: binaryOf(root, entry),
89
+ profiles: loaded.config.profiles,
90
+ guardSets: loaded.config.guardSets,
91
+ unwiredHooks: hooks.filter((hook) => !hook.wired).map((hook) => hook.id),
92
+ branch,
93
+ branchRuns: runsInPeriod(runs, PERIOD_DAYS, now).filter((run) => run.branch === branch),
94
+ stoppedIds: stopped.map((stopper) => stopper.id),
95
+ attention: attentionOf([], stopped, hooks).length,
96
+ })}\n`;
97
+ }
@@ -30,6 +30,7 @@ export interface Guard {
30
30
  id: string;
31
31
  description: string;
32
32
  profiles: readonly Profile[] | "every";
33
+ set?: string;
33
34
  quick?: boolean;
34
35
  settingsSchema?: object;
35
36
  check(context: GuardContext): readonly Finding[] | Promise<readonly Finding[]>;
@@ -45,6 +46,12 @@ export interface StepContext {
45
46
  settings: Readonly<Record<string, unknown>>;
46
47
  changed(): readonly string[];
47
48
  }
49
+ export declare const HOLDOUT_STEP = "holdout";
50
+ export interface Holdout {
51
+ run: string;
52
+ after?: string[];
53
+ limitSeconds?: number;
54
+ }
48
55
  export interface Skip {
49
56
  skip: string;
50
57
  }
@@ -1 +1,2 @@
1
1
  export const PROFILES = ["web", "library", "dotnet", "database"];
2
+ export const HOLDOUT_STEP = "holdout";
@@ -0,0 +1,107 @@
1
+ import { type BranchSummary, type DayCount, type Stopper, type Trends } from "./breakdown.ts";
2
+ import { type Catalog, type Config } from "./config.ts";
3
+ import type { RunRecord } from "./history.ts";
4
+ import { type ListedStep } from "./plan.ts";
5
+ import { type Stats } from "./stats.ts";
6
+ export interface WallCheck {
7
+ name: string;
8
+ state: "holds" | "broken" | "unchecked";
9
+ detail: string;
10
+ }
11
+ export interface PluginView {
12
+ version: string;
13
+ skills: {
14
+ name: string;
15
+ summary: string;
16
+ onlyWhenAsked: boolean;
17
+ }[];
18
+ hookDescription: string;
19
+ hooks: {
20
+ event: string;
21
+ matcher: string;
22
+ script: string;
23
+ }[];
24
+ agents: {
25
+ name: string;
26
+ description: string;
27
+ tools: string;
28
+ }[];
29
+ }
30
+ export interface GardenView {
31
+ at: string;
32
+ branch: string;
33
+ found: Record<string, number>;
34
+ }
35
+ export interface DashboardInput {
36
+ name: string;
37
+ days: number;
38
+ now: Date;
39
+ runs: readonly RunRecord[];
40
+ config: Config;
41
+ catalog: Catalog;
42
+ wall: readonly WallCheck[];
43
+ wallCheckedAt: Date;
44
+ live: boolean;
45
+ files: readonly string[];
46
+ read: (file: string) => string | null;
47
+ hooksPath: string;
48
+ criterionIds: (spec: string) => string[];
49
+ plugin: PluginView | null;
50
+ garden: GardenView | null;
51
+ }
52
+ interface AttentionItem {
53
+ kind: "wall" | "broken" | "have";
54
+ text: string;
55
+ detail: string;
56
+ }
57
+ interface GuardRow {
58
+ id: string;
59
+ set: string;
60
+ state: "active" | "set not taken" | "skipped";
61
+ skipReason: string;
62
+ }
63
+ interface ExceptionRow {
64
+ guard: string;
65
+ target: string;
66
+ reason: string;
67
+ covered: number | null;
68
+ sharedBy: number;
69
+ }
70
+ interface HookRow {
71
+ id: string;
72
+ where: string;
73
+ wired: boolean;
74
+ }
75
+ interface CriterionRow {
76
+ id: string;
77
+ spec: string;
78
+ tests: {
79
+ file: string;
80
+ kind: string;
81
+ }[];
82
+ }
83
+ export interface DashboardData {
84
+ name: string;
85
+ days: number;
86
+ generated: Date;
87
+ attention: AttentionItem[];
88
+ wall: readonly WallCheck[];
89
+ wallCheckedAt: Date;
90
+ live: boolean;
91
+ stats: Stats;
92
+ trends: Trends;
93
+ perDay: DayCount[];
94
+ stopped: Stopper[];
95
+ branches: BranchSummary[];
96
+ steps: ListedStep[];
97
+ guards: GuardRow[];
98
+ exceptions: ExceptionRow[];
99
+ hooks: HookRow[];
100
+ criteria: CriterionRow[] | null;
101
+ plugin: PluginView | null;
102
+ garden: GardenView | null;
103
+ }
104
+ export declare function hookRows(read: (file: string) => string | null, hooksPath: string): HookRow[];
105
+ export declare function attentionOf(wall: readonly WallCheck[], stopped: readonly Stopper[], hooks: readonly HookRow[]): AttentionItem[];
106
+ export declare function collectDashboard(input: DashboardInput): DashboardData;
107
+ export {};