@maniumek/suwgate 0.17.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.
package/README.md CHANGED
@@ -137,7 +137,7 @@ self-hosted runners: [ci/self-hosted](ci/self-hosted/README.md).
137
137
  <summary>suwgate --help</summary>
138
138
 
139
139
  ```text
140
- usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|guard-pr|stop|pre-commit|pre-push> | suwgate ship | suwgate stats [--days <n>] [--json] | suwgate doctor | suwgate context | suwgate dashboard [--days <n>] [--out <path> | --serve [--port <n>] | --json] | suwgate garden-ran <kind>=<count>... | suwgate dev <command> | suwgate agents-shared | suwgate --help | --version
140
+ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|guard-pr|stop|pre-commit|pre-push> | suwgate ship | suwgate stats [--days <n>] [--json] | suwgate doctor | suwgate context | suwgate dashboard [--days <n>] [--no-ci] [--out <path> | --serve [--port <n>] | --json] | suwgate garden-ran <kind>=<count>... | suwgate dev <command> | suwgate agents-shared | suwgate --help | --version
141
141
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
142
142
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
143
143
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
@@ -159,7 +159,7 @@ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verb
159
159
  branch, then records the tree (the pre-push and guard-pr hooks let a push of it through)
160
160
  suwgate stats what the gate caught: runs and red share per mode, quick gate times and budget overruns, the slowest
161
161
  steps, the guards by findings and the guards with none, from suwgate-runs.jsonl in the git common
162
- directory (every run of check, ship, the Stop and pre-commit hooks appends a line there; step does not)
162
+ directory (every run of check, ship, step, the Stop and pre-commit hooks appends a line there)
163
163
  --days <n> the period (30 by default), --json the same numbers as one JSON object
164
164
  suwgate doctor is the wall up: reads the rules and the branch protection of the main branch through gh and fails
165
165
  when it needs no pull request, requires no status check or not the gate's, allows force pushes or
@@ -172,15 +172,18 @@ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verb
172
172
  the wall (as suwgate doctor reads it), runs, what broke and on which branch, what the repository has,
173
173
  which acceptance criteria have a test, the installed suwagent and the last cleaning; written to
174
174
  suwgate-dashboard.html in the git common directory (--out <path> elsewhere), the path is printed;
175
- --days <n> the period (30 by default); never runs the gate and never records a run; exit 2 on a bad suwgate.yml
175
+ --days <n> the period (30 by default, 90 at most); never runs the gate and never records a run; exit 2 on a
176
+ bad suwgate.yml; the runs are this machine's and CI's: each call asks GitHub (gh) only for the gate-history
177
+ artifacts newer than the last one it read, keeps them 90 days in the git common directory and says in the
178
+ page's first line up to when CI was read, or why it was not; --no-ci reads this machine only
176
179
  suwgate dashboard --json
177
- the data of the page as one JSON object on stdout (schemaVersion, attention, wall, runs, stopped,
180
+ the data of the page as one JSON object on stdout (schemaVersion, attention, ci, wall, runs, stopped,
178
181
  branches, steps, guards, exceptions, hooks, quietGuards, criteria, plugin, garden, about), no file
179
182
  suwgate dashboard --serve [--port <n>]
180
183
  the same page live, at http://127.0.0.1:<port>/ (4780, else the next free port), for a browser tab kept
181
184
  open beside the work: it follows new runs, cleaning traces and changes of suwgate.yml within seconds and
182
- keeps the opened parts open; answers only this machine, asks GitHub for the wall at most every 5 minutes,
183
- writes nothing; runs until interrupted, so start it in the background suwgate garden-ran <kind>=<count> ...
185
+ keeps the opened parts open; answers only this machine, asks GitHub for the wall and for new runs of CI at
186
+ most every 5 minutes, writes only the runs of CI it read; runs until interrupted, so start it in the background suwgate garden-ran <kind>=<count> ...
184
187
  records a cleaning run (e.g. suwgate garden-ran docs=3 guards=2) as one line of suwgate-garden.jsonl in the
185
188
  git common directory, which suwgate dashboard shows; a kind is a kebab-case word, a count a whole number
186
189
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
@@ -248,7 +251,7 @@ The plugin has two agents, each with its own clean context. `/suwgate:ship` star
248
251
  | `suwgate:shipper` | shell, files, `Agent`, `Skill` | takes the change to a pull request: `suwgate ship`, push, CI, and starts the simplifier and the suwagent skills |
249
252
  | `suwgate:simplifier` | shell, files | makes the change simpler without changing its behaviour; commits it, never pushes |
250
253
 
251
- The plugin describes suwgate 0.17.0; a repository on an older package lacks `stats`, `doctor`, `dashboard` and `garden-ran`, and the skills say so instead of working around it.
254
+ The plugin describes suwgate 0.18.0; a repository on an older package lacks `stats`, `doctor`, `dashboard` and `garden-ran`, and the skills say so instead of working around it.
252
255
 
253
256
  ## Configuration
254
257
 
package/dist/cli.js CHANGED
@@ -8,7 +8,8 @@ import { dev, realEnvironment } from "./dev/index.js";
8
8
  import { Failure } from "./dev/process.js";
9
9
  import { loadConfig } from "./gate/config.js";
10
10
  import { allSteps } from "./gate/plan.js";
11
- import { branchOf, inCommonDir, readRuns } from "./gate/history.js";
11
+ import { allRuns, RETENTION_DAYS, syncCi } from "./gate/ciHistory.js";
12
+ import { branchOf, inCommonDir } from "./gate/history.js";
12
13
  import { readContext } from "./gate/context.js";
13
14
  import { dashboard, dashboardAsJson, GARDEN_FILE, liveSources } from "./gate/dashboardFile.js";
14
15
  import { startDashboardServer } from "./gate/dashboardServer.js";
@@ -28,7 +29,7 @@ import { preCommit, runTool } from "./session/preCommit.js";
28
29
  import { prePush } from "./session/prePush.js";
29
30
  import { ship } from "./session/ship.js";
30
31
  import { stop } from "./session/stop.js";
31
- const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|guard-pr|stop|pre-commit|pre-push> | suwgate ship | suwgate stats [--days <n>] [--json] | suwgate doctor | suwgate context | suwgate dashboard [--days <n>] [--out <path> | --serve [--port <n>] | --json] | suwgate garden-ran <kind>=<count>... | suwgate dev <command> | suwgate agents-shared | suwgate --help | --version
32
+ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|guard-pr|stop|pre-commit|pre-push> | suwgate ship | suwgate stats [--days <n>] [--json] | suwgate doctor | suwgate context | suwgate dashboard [--days <n>] [--no-ci] [--out <path> | --serve [--port <n>] | --json] | suwgate garden-ran <kind>=<count>... | suwgate dev <command> | suwgate agents-shared | suwgate --help | --version
32
33
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
33
34
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
34
35
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
@@ -50,7 +51,7 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
50
51
  branch, then records the tree (the pre-push and guard-pr hooks let a push of it through)
51
52
  suwgate stats what the gate caught: runs and red share per mode, quick gate times and budget overruns, the slowest
52
53
  steps, the guards by findings and the guards with none, from suwgate-runs.jsonl in the git common
53
- directory (every run of check, ship, the Stop and pre-commit hooks appends a line there; step does not)
54
+ directory (every run of check, ship, step, the Stop and pre-commit hooks appends a line there)
54
55
  --days <n> the period (30 by default), --json the same numbers as one JSON object
55
56
  suwgate doctor is the wall up: reads the rules and the branch protection of the main branch through gh and fails
56
57
  when it needs no pull request, requires no status check or not the gate's, allows force pushes or
@@ -63,15 +64,18 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
63
64
  the wall (as suwgate doctor reads it), runs, what broke and on which branch, what the repository has,
64
65
  which acceptance criteria have a test, the installed suwagent and the last cleaning; written to
65
66
  suwgate-dashboard.html in the git common directory (--out <path> elsewhere), the path is printed;
66
- --days <n> the period (30 by default); never runs the gate and never records a run; exit 2 on a bad suwgate.yml
67
+ --days <n> the period (30 by default, 90 at most); never runs the gate and never records a run; exit 2 on a
68
+ bad suwgate.yml; the runs are this machine's and CI's: each call asks GitHub (gh) only for the gate-history
69
+ artifacts newer than the last one it read, keeps them 90 days in the git common directory and says in the
70
+ page's first line up to when CI was read, or why it was not; --no-ci reads this machine only
67
71
  suwgate dashboard --json
68
- the data of the page as one JSON object on stdout (schemaVersion, attention, wall, runs, stopped,
72
+ the data of the page as one JSON object on stdout (schemaVersion, attention, ci, wall, runs, stopped,
69
73
  branches, steps, guards, exceptions, hooks, quietGuards, criteria, plugin, garden, about), no file
70
74
  suwgate dashboard --serve [--port <n>]
71
75
  the same page live, at http://127.0.0.1:<port>/ (4780, else the next free port), for a browser tab kept
72
76
  open beside the work: it follows new runs, cleaning traces and changes of suwgate.yml within seconds and
73
- keeps the opened parts open; answers only this machine, asks GitHub for the wall at most every 5 minutes,
74
- writes nothing; runs until interrupted, so start it in the background suwgate garden-ran <kind>=<count> ...
77
+ keeps the opened parts open; answers only this machine, asks GitHub for the wall and for new runs of CI at
78
+ most every 5 minutes, writes only the runs of CI it read; runs until interrupted, so start it in the background suwgate garden-ran <kind>=<count> ...
75
79
  records a cleaning run (e.g. suwgate garden-ran docs=3 guards=2) as one line of suwgate-garden.jsonl in the
76
80
  git common directory, which suwgate dashboard shows; a kind is a kebab-case word, a count a whole number
77
81
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
@@ -188,6 +192,7 @@ async function runStep(argv) {
188
192
  cwd: process.cwd(),
189
193
  id: positionals[0],
190
194
  only: values.only === true,
195
+ recordedAs: "step",
191
196
  args,
192
197
  verbose: values.verbose === true,
193
198
  env: process.env,
@@ -218,6 +223,7 @@ async function main(argv) {
218
223
  version: { type: "boolean" },
219
224
  days: { type: "string" },
220
225
  json: { type: "boolean" },
226
+ "no-ci": { type: "boolean" },
221
227
  out: { type: "string" },
222
228
  serve: { type: "boolean" },
223
229
  port: { type: "string" },
@@ -247,6 +253,7 @@ async function main(argv) {
247
253
  catalog,
248
254
  extraFiles: [],
249
255
  wall: () => Promise.resolve([]),
256
+ ci: () => Promise.resolve({ state: "off", syncedTo: null, reason: "" }),
250
257
  criterionIds,
251
258
  plugin: () => null,
252
259
  garden: () => null,
@@ -257,8 +264,8 @@ async function main(argv) {
257
264
  }
258
265
  if (command === "dashboard" && hook === undefined) {
259
266
  const days = values.days === undefined ? 30 : Number(values.days);
260
- if (!Number.isInteger(days) || days < 1) {
261
- console.error(`suwgate dashboard: --days takes a whole number of days, not '${values.days}': pass e.g. --days 30`);
267
+ if (!Number.isInteger(days) || days < 1 || days > RETENTION_DAYS) {
268
+ console.error(`suwgate dashboard: --days takes a whole number of days from 1 to ${RETENTION_DAYS}, not '${values.days}': pass e.g. --days 30`);
262
269
  return 2;
263
270
  }
264
271
  const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
@@ -283,6 +290,7 @@ async function main(argv) {
283
290
  catalog,
284
291
  extraFiles: [path.join(configDir, "plugins", "installed_plugins.json")],
285
292
  wall: async (root) => (await runDoctor(root)).checks,
293
+ ci: (root, now) => values["no-ci"] === true ? Promise.resolve({ state: "off", syncedTo: null, reason: "" }) : syncCi(root, now),
286
294
  criterionIds,
287
295
  plugin: (root) => findSuwagent(configDir, root, pluginFiles),
288
296
  garden: lastGarden,
@@ -340,7 +348,7 @@ async function main(argv) {
340
348
  console.error(`suwgate stats: ${process.cwd()} is not inside a git repository: run it in a checkout`);
341
349
  return 2;
342
350
  }
343
- const stats = summarize(readRuns(root), days, new Date());
351
+ const stats = summarize(allRuns(root), days, new Date());
344
352
  console.log(values.json === true ? JSON.stringify(stats) : formatStats(stats));
345
353
  return 0;
346
354
  }
@@ -367,7 +375,7 @@ async function main(argv) {
367
375
  const verdict = await ship(root, {
368
376
  changedFiles: () => changedFiles(root),
369
377
  quickCheck: () => runCheck(root, true, false, { mode: "ship" }),
370
- e2e: (files) => step({ cwd: root, id: "e2e", only: false, args: files, verbose: false, env: process.env, catalog }),
378
+ e2e: (files) => step({ cwd: root, id: "e2e", only: false, args: files, verbose: false, recordedAs: "ship", env: process.env, catalog }),
371
379
  });
372
380
  (verdict.exitCode === 0 ? console.log : console.error)(verdict.message);
373
381
  return verdict.exitCode;
@@ -3,12 +3,14 @@ export interface Stopper {
3
3
  kind: "guard" | "step";
4
4
  id: string;
5
5
  runs: number;
6
+ ci: number;
6
7
  last: string;
7
8
  branches: string[];
8
9
  }
9
10
  export interface BranchSummary {
10
11
  branch: string;
11
12
  runs: number;
13
+ ci: number;
12
14
  red: number;
13
15
  lastRed: {
14
16
  at: string;
@@ -27,10 +27,12 @@ export function stoppers(history, days, now) {
27
27
  const key = `${kind}:${id}`;
28
28
  const own = found.get(key);
29
29
  if (own === undefined) {
30
- found.set(key, { kind, id, runs: 1, last: run.at, branches: [run.branch] });
30
+ found.set(key, { kind, id, runs: 1, ci: run.ci ? 1 : 0, last: run.at, branches: [run.branch] });
31
31
  }
32
32
  else {
33
33
  own.runs += 1;
34
+ if (run.ci)
35
+ own.ci += 1;
34
36
  if (!own.branches.includes(run.branch))
35
37
  own.branches.push(run.branch);
36
38
  }
@@ -45,8 +47,10 @@ export function causeOf(run) {
45
47
  export function branches(history, days, now) {
46
48
  const found = new Map();
47
49
  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 };
50
+ const own = found.get(run.branch) ?? { branch: run.branch, runs: 0, ci: 0, red: 0, lastRed: null, lastRedRun: null };
49
51
  own.runs += 1;
52
+ if (run.ci)
53
+ own.ci += 1;
50
54
  if (run.verdict === "red") {
51
55
  own.red += 1;
52
56
  if (own.lastRedRun === null || newestFirst(own.lastRedRun, run) > 0)
@@ -67,7 +71,7 @@ function between(history, from, to) {
67
71
  return history.filter((run) => Date.parse(run.at) >= from && Date.parse(run.at) < to);
68
72
  }
69
73
  function measures(window, end) {
70
- const stats = summarize(window, Number.POSITIVE_INFINITY, new Date(end));
74
+ const stats = summarize(window.filter((run) => run.mode !== "step"), Number.POSITIVE_INFINITY, new Date(end));
71
75
  const red = Object.values(stats.modes).reduce((total, mode) => total + mode.red, 0);
72
76
  return {
73
77
  redShare: stats.runs === 0 ? null : Math.round((red / stats.runs) * 100),
@@ -16,6 +16,7 @@ export interface StepOptions {
16
16
  args: readonly string[];
17
17
  verbose: boolean;
18
18
  runFolder?: string;
19
+ recordedAs?: RunMode;
19
20
  env: NodeJS.ProcessEnv;
20
21
  catalog: Catalog;
21
22
  }
@@ -167,5 +167,6 @@ export async function step(options) {
167
167
  catalog: options.catalog,
168
168
  target: { id: options.id, only: options.only, args: options.args },
169
169
  ...(options.runFolder === undefined ? {} : { runFolder: options.runFolder }),
170
+ ...(options.recordedAs === undefined ? {} : { recorded: { mode: options.recordedAs, source: "cli" } }),
170
171
  });
171
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
+ }
@@ -3,7 +3,8 @@ import path from "node:path";
3
3
  import { causeOf, runsInPeriod, stoppers } from "./breakdown.js";
4
4
  import { loadConfig } from "./config.js";
5
5
  import { attentionOf, hookRows } from "./dashboard.js";
6
- import { branchOf, readRuns } from "./history.js";
6
+ import { allRuns } from "./ciHistory.js";
7
+ import { branchOf } from "./history.js";
7
8
  import { git, repositoryRoot } from "./repository.js";
8
9
  const MAX_CHARACTERS = 1800;
9
10
  const PERIOD_DAYS = 30;
@@ -79,7 +80,7 @@ export function readContext(request, version, entry) {
79
80
  }
80
81
  };
81
82
  const now = request.now();
82
- const runs = readRuns(root);
83
+ const runs = allRuns(root);
83
84
  const branch = branchOf(root);
84
85
  const hooks = hookRows(read, git(root, ["config", "--get", "core.hooksPath"])?.trim() ?? "");
85
86
  const stopped = stoppers(runs, PERIOD_DAYS, now);
@@ -1,5 +1,6 @@
1
1
  import { type BranchSummary, type DayCount, type Stopper, type Trends } from "./breakdown.ts";
2
2
  import { type Catalog, type Config } from "./config.ts";
3
+ import type { CiView } from "./ciHistory.ts";
3
4
  import type { RunRecord } from "./history.ts";
4
5
  import { type ListedStep } from "./plan.ts";
5
6
  import { type Stats } from "./stats.ts";
@@ -37,6 +38,7 @@ export interface DashboardInput {
37
38
  days: number;
38
39
  now: Date;
39
40
  runs: readonly RunRecord[];
41
+ ci: CiView;
40
42
  config: Config;
41
43
  catalog: Catalog;
42
44
  wall: readonly WallCheck[];
@@ -88,6 +90,9 @@ export interface DashboardData {
88
90
  wall: readonly WallCheck[];
89
91
  wallCheckedAt: Date;
90
92
  live: boolean;
93
+ ci: CiView & {
94
+ runs: number;
95
+ };
91
96
  stats: Stats;
92
97
  trends: Trends;
93
98
  perDay: DayCount[];
@@ -1,4 +1,5 @@
1
- import { branches, runsPerDay, stoppers, trends } from "./breakdown.js";
1
+ import path from "node:path";
2
+ import { branches, runsInPeriod, runsPerDay, stoppers, trends, } from "./breakdown.js";
2
3
  import { takesGuard } from "./config.js";
3
4
  import { listSteps } from "./plan.js";
4
5
  import { summarize } from "./stats.js";
@@ -27,17 +28,28 @@ function namesCriterion(text, id) {
27
28
  return (['"', "'", "`"].some((quote) => text.includes(`${quote}${id}:`)) ||
28
29
  new RegExp(`Trait\\(\\s*"criterion"\\s*,\\s*"${escaped}"\\s*\\)`).test(text));
29
30
  }
30
- function specsFolder(read) {
31
+ function criteriaSettings(read) {
31
32
  try {
32
33
  const parsed = JSON.parse(read("criteria.json") ?? "{}");
33
- return typeof parsed.specs === "string" ? parsed.specs : DEFAULT_SPECS_FOLDER;
34
+ const kinds = Array.isArray(parsed.kinds) ? parsed.kinds : [];
35
+ return {
36
+ specs: typeof parsed.specs === "string" ? parsed.specs : DEFAULT_SPECS_FOLDER,
37
+ kinds: kinds.flatMap((kind) => typeof kind.kind === "string" && Array.isArray(kind.paths)
38
+ ? [{ kind: kind.kind, paths: kind.paths.filter((entry) => typeof entry === "string") }]
39
+ : []),
40
+ };
34
41
  }
35
42
  catch {
36
- return DEFAULT_SPECS_FOLDER;
43
+ return { specs: DEFAULT_SPECS_FOLDER, kinds: [] };
37
44
  }
38
45
  }
46
+ function namesAsWord(text, id) {
47
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
+ return new RegExp(`(?<![A-Za-z0-9-])${escaped}(?![A-Za-z0-9-])`).test(text);
49
+ }
39
50
  function criteriaOf(input) {
40
- const folder = specsFolder(input.read);
51
+ const settings = criteriaSettings(input.read);
52
+ const folder = settings.specs;
41
53
  const specs = input.files.filter((file) => file.startsWith(`${folder}/`) && file.endsWith(".html") && !file.slice(folder.length + 1).includes("/"));
42
54
  if (specs.length === 0)
43
55
  return null;
@@ -47,10 +59,19 @@ function criteriaOf(input) {
47
59
  const text = input.read(file);
48
60
  return text === null ? [] : [{ file, text }];
49
61
  });
62
+ const own = settings.kinds.flatMap((kind) => input.files
63
+ .filter((file) => !TEST_FILE.test(file) && kind.paths.some((pattern) => path.matchesGlob(file, pattern)))
64
+ .flatMap((file) => {
65
+ const text = input.read(file);
66
+ return text === null ? [] : [{ file, text, kind: kind.kind }];
67
+ }));
50
68
  return specs.flatMap((spec) => input.criterionIds(input.read(spec) ?? "").map((id) => ({
51
69
  id,
52
70
  spec,
53
- tests: tests.filter((test) => namesCriterion(test.text, id)).map((test) => ({ file: test.file, kind: testKind(test.file) })),
71
+ tests: [
72
+ ...tests.filter((test) => namesCriterion(test.text, id)).map((test) => ({ file: test.file, kind: testKind(test.file) })),
73
+ ...own.filter((test) => namesAsWord(test.text, id)).map((test) => ({ file: test.file, kind: test.kind })),
74
+ ],
54
75
  })));
55
76
  }
56
77
  function guardRows(input) {
@@ -110,6 +131,7 @@ export function collectDashboard(input) {
110
131
  wall: input.wall,
111
132
  wallCheckedAt: input.wallCheckedAt,
112
133
  live: input.live,
134
+ ci: { ...input.ci, runs: runsInPeriod(input.runs, input.days, input.now).filter((run) => run.ci).length },
113
135
  stats: summarize(input.runs, input.days, input.now),
114
136
  trends: trends(input.runs, input.days, input.now),
115
137
  perDay: runsPerDay(input.runs, input.days, input.now),
@@ -1,3 +1,4 @@
1
+ import { type CiView } from "./ciHistory.ts";
1
2
  import { type Catalog } from "./config.ts";
2
3
  import { type GardenView, type PluginView, type WallCheck } from "./dashboard.ts";
3
4
  export declare const GARDEN_FILE = "suwgate-garden.jsonl";
@@ -9,6 +10,7 @@ export interface DashboardRequest {
9
10
  catalog: Catalog;
10
11
  extraFiles: readonly string[];
11
12
  wall: (root: string) => Promise<readonly WallCheck[]>;
13
+ ci: (root: string, now: Date) => Promise<CiView>;
12
14
  criterionIds: (spec: string) => string[];
13
15
  plugin: (root: string) => PluginView | null;
14
16
  garden: (file: string | null) => GardenView | null;
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import { allRuns, CI_HISTORY_FILE, syncedTo } from "./ciHistory.js";
4
5
  import { CONFIG_FILE, loadConfig } from "./config.js";
5
6
  import { collectDashboard } from "./dashboard.js";
6
7
  import { dashboardJson } from "./dashboardJson.js";
@@ -38,12 +39,13 @@ function prepare(request) {
38
39
  }
39
40
  return { root, config: loaded.config };
40
41
  }
41
- function collect(request, root, config, wall, live) {
42
+ function collect(request, root, config, wall, ci, live) {
42
43
  return collectDashboard({
43
44
  name: repositoryName(root),
44
45
  days: request.days,
45
46
  now: request.now(),
46
- runs: readRuns(root),
47
+ runs: ci.state === "off" ? readRuns(root) : allRuns(root),
48
+ ci,
47
49
  config,
48
50
  catalog: request.catalog,
49
51
  wall: wall.checks,
@@ -57,15 +59,13 @@ function collect(request, root, config, wall, live) {
57
59
  garden: request.garden(inCommonDir(root, GARDEN_FILE)),
58
60
  });
59
61
  }
60
- function build(request, root, config, wall, live) {
61
- return renderDashboard(collect(request, root, config, wall, live));
62
- }
63
62
  export async function dashboardAsJson(request) {
64
63
  const prepared = prepare(request);
65
64
  if ("exitCode" in prepared)
66
65
  return prepared;
67
66
  const wall = { checks: await request.wall(prepared.root), checkedAt: request.now() };
68
- return { exitCode: 0, text: JSON.stringify(dashboardJson(collect(request, prepared.root, prepared.config, wall, false))) };
67
+ const ci = await request.ci(prepared.root, request.now());
68
+ return { exitCode: 0, text: JSON.stringify(dashboardJson(collect(request, prepared.root, prepared.config, wall, ci, false))) };
69
69
  }
70
70
  export async function dashboard(request) {
71
71
  const prepared = prepare(request);
@@ -73,7 +73,7 @@ export async function dashboard(request) {
73
73
  return prepared;
74
74
  const { root, config } = prepared;
75
75
  const wall = { checks: await request.wall(root), checkedAt: request.now() };
76
- const html = build(request, root, config, wall, false);
76
+ const html = renderDashboard(collect(request, root, config, wall, await request.ci(root, request.now()), false));
77
77
  const target = request.out === undefined ? inCommonDir(root, DASHBOARD_FILE) : path.resolve(request.cwd, request.out);
78
78
  if (target === null)
79
79
  return { exitCode: 2, text: "suwgate dashboard: no place to write the page: pass --out <path>" };
@@ -101,6 +101,34 @@ function cachedWall(read, now) {
101
101
  },
102
102
  };
103
103
  }
104
+ function backgroundCi(read, before, now) {
105
+ let current = { state: "syncing", syncedTo: before, reason: "" };
106
+ let finishedAt = 0;
107
+ let pending = false;
108
+ return {
109
+ get: () => {
110
+ if (!pending && now().getTime() - finishedAt >= WALL_TTL_MS) {
111
+ pending = true;
112
+ read()
113
+ .then((view) => {
114
+ current = view;
115
+ })
116
+ .catch((error) => {
117
+ current = {
118
+ state: "unavailable",
119
+ syncedTo: current.syncedTo,
120
+ reason: error instanceof Error ? error.message : String(error),
121
+ };
122
+ })
123
+ .finally(() => {
124
+ finishedAt = now().getTime();
125
+ pending = false;
126
+ });
127
+ }
128
+ return current;
129
+ },
130
+ };
131
+ }
104
132
  function fileStamp(file) {
105
133
  try {
106
134
  const found = statSync(file);
@@ -126,8 +154,10 @@ export function liveSources(request) {
126
154
  return prepared;
127
155
  const { root } = prepared;
128
156
  const wall = cachedWall(() => request.wall(root), request.now);
157
+ const ci = backgroundCi(() => request.ci(root, request.now()), syncedTo(root), request.now);
129
158
  const watched = [
130
159
  inCommonDir(root, HISTORY_FILE),
160
+ inCommonDir(root, CI_HISTORY_FILE),
131
161
  inCommonDir(root, GARDEN_FILE),
132
162
  path.join(root, CONFIG_FILE),
133
163
  path.join(root, ".claude", "settings.json"),
@@ -139,13 +169,14 @@ export function liveSources(request) {
139
169
  const current = prepare(request);
140
170
  if ("exitCode" in current)
141
171
  throw new Error(current.text);
142
- return build(request, root, current.config, await wall.get(), true);
172
+ return renderDashboard(collect(request, root, current.config, await wall.get(), ci.get(), true));
143
173
  },
144
174
  fingerprint: () => createHash("sha1")
145
175
  .update([
146
176
  ...watched.map((file) => (file === null ? "-" : fileStamp(file))),
147
177
  ...folderStamps(path.join(root, SPECS_FOLDER)),
148
178
  wall.stamp(),
179
+ JSON.stringify(ci.get()),
149
180
  request.now().toISOString().slice(0, 10),
150
181
  ].join("\n"))
151
182
  .digest("hex")
@@ -8,6 +8,7 @@ export function dashboardJson(data) {
8
8
  days: data.days,
9
9
  generated: data.generated.toISOString(),
10
10
  attention: data.attention.map((item) => ({ kind: item.kind, text: item.text, detail: item.detail, part: item.kind })),
11
+ ci: data.ci,
11
12
  wall: { checkedAt: data.wallCheckedAt.toISOString(), checks: data.wall },
12
13
  runs: { ...stats, trends: data.trends, perDay: data.perDay },
13
14
  stopped: data.stopped,
@@ -1,6 +1,6 @@
1
1
  const LIST_LIMIT = 5;
2
2
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3
- const RECORDING_COMMANDS = "suwgate check, suwgate ship, the Stop hook and the pre-commit hook";
3
+ const RECORDING_COMMANDS = "suwgate check, suwgate ship, suwgate step, the Stop hook and the pre-commit hook";
4
4
  const STYLE = `
5
5
  :root{--bg:#fafafa;--surface:#fff;--text:#1d1d1f;--muted:#6b6b70;--line:#e2e2e6;--spark:#8a8a90;--holds:#1a7f37;--broken:#cf222e;--unchecked:#9a6700}
6
6
  @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121214;--surface:#1a1a1d;--text:#e8e8ea;--muted:#9a9aa0;--line:#2c2c31;--spark:#7a7a82;--holds:#3fb950;--broken:#ff7b72;--unchecked:#d29922}}
@@ -104,7 +104,7 @@ function keyed(prefix, html) {
104
104
  }
105
105
  export const ABOUT = {
106
106
  wall: "Can the gate be bypassed? The protection of the main branch on GitHub and the hooks of this checkout. When every check holds, nothing reaches the main branch without a pull request whose gate passed.",
107
- runs: "How often is the gate red, and how long does it take? Every run of the gate recorded on this machine, beside the previous period.",
107
+ runs: "How often is the gate red, and how long does it take? Every run of the gate recorded on this machine and read from CI, where alone the full gate runs, beside the previous period.",
108
108
  broken: "What stopped the gate, when and how often? Each guard and step that turned a run red, the newest first, with its branches.",
109
109
  branches: "Where does it break? Each branch with its runs, its red runs and the cause of the last red one.",
110
110
  have: "What guards this repository? The steps of the gate, the guards with their sets, the exceptions with their reasons, and the hooks.",
@@ -161,6 +161,19 @@ function runsPart(data) {
161
161
  const perDay = data.perDay.map((own) => row(escapeHtml(day(`${own.day}T00:00:00Z`)), [plural(own.runs, "run"), `${own.red} red`]));
162
162
  return part("runs", 2, "Runs", conclusion, `<h3>Per mode</h3>${list(modes, "modes")}<h3>Against the previous period</h3>${list(metrics, "metrics")}<h3>Slowest steps (median)</h3>${list(steps, "steps")}<h3>Runs per day</h3>${list(perDay, "days")}`);
163
163
  }
164
+ function inCi(count) {
165
+ return count === 0 ? "" : ` (${count} in CI)`;
166
+ }
167
+ function sourcesOf(ci) {
168
+ const upTo = ci.syncedTo === null ? "" : ` up to ${escapeHtml(stamp(new Date(ci.syncedTo)))}`;
169
+ if (ci.state === "off")
170
+ return "this machine";
171
+ if (ci.state === "syncing")
172
+ return `this machine and CI${upTo} · reading CI now`;
173
+ if (ci.state === "unavailable")
174
+ return `this machine${upTo === "" ? "" : ` and CI${upTo}`} · CI not read: ${escapeHtml(ci.reason)}`;
175
+ return ci.syncedTo === null ? "this machine and CI · no run of CI recorded yet" : `this machine and CI${upTo}`;
176
+ }
164
177
  function brokenPart(data) {
165
178
  if (data.stats.runs === 0)
166
179
  return part("broken", 3, "Broken", "no runs recorded", noRuns(data.days));
@@ -171,7 +184,7 @@ function brokenPart(data) {
171
184
  const conclusion = [guards > 0 ? plural(guards, "guard") : "", steps > 0 ? plural(steps, "step") : ""]
172
185
  .filter((text) => text !== "")
173
186
  .join(", ");
174
- const rows = data.stopped.map((stopper) => row(`${escapeHtml(stopper.id)} <span class="note">${stopper.kind}</span>`, [plural(stopper.runs, "run"), `last ${escapeHtml(day(stopper.last))}`], `on ${stopper.branches.map(escapeHtml).join(", ")}`));
187
+ const rows = data.stopped.map((stopper) => row(`${escapeHtml(stopper.id)} <span class="note">${stopper.kind}</span>`, [`${plural(stopper.runs, "run")}${inCi(stopper.ci)}`, `last ${escapeHtml(day(stopper.last))}`], `on ${stopper.branches.map(escapeHtml).join(", ")}`));
175
188
  return part("broken", 3, "Broken", `${conclusion}, last ${day(data.stopped[0]?.last ?? "")}`, list(rows, "items"));
176
189
  }
177
190
  function branchesPart(data) {
@@ -180,7 +193,7 @@ function branchesPart(data) {
180
193
  const red = data.branches.filter((branch) => branch.red > 0).length;
181
194
  const conclusion = `${plural(data.branches.length, "branch", "branches")}, ${red} with red runs`;
182
195
  const rows = data.branches.map((branch) => row(escapeHtml(branch.branch), [
183
- plural(branch.runs, "run"),
196
+ `${plural(branch.runs, "run")}${inCi(branch.ci)}`,
184
197
  `${branch.red} red`,
185
198
  branch.lastRed === null ? "-" : `last red ${escapeHtml(day(branch.lastRed.at))}`,
186
199
  ], branch.lastRed === null ? "" : `last red: ${escapeHtml(branch.lastRed.cause)}`));
@@ -277,7 +290,7 @@ export function renderDashboard(data) {
277
290
  <body data-version="">
278
291
  <main id="live-root">
279
292
  <h1>${escapeHtml(title)}</h1>
280
- <p class="sub">last ${data.days} days · this machine · ${escapeHtml(stamp(data.generated))}${data.live ? ' · <span class="live">live</span> <span id="live-note"></span>' : ""}</p>
293
+ <p class="sub">last ${data.days} days · ${sourcesOf(data.ci)} · ${escapeHtml(stamp(data.generated))}${data.live ? ' · <span class="live">live</span> <span id="live-note"></span>' : ""}</p>
281
294
  ${attention(data)}
282
295
  ${wallPart(data)}
283
296
  ${runsPart(data)}
@@ -70,6 +70,7 @@ function dashboardInput(overrides = {}) {
70
70
  days: 30,
71
71
  now: NOW,
72
72
  runs: history,
73
+ ci: { state: "off", syncedTo: null, reason: "" },
73
74
  config,
74
75
  catalog: fakeCatalog,
75
76
  wall: [
@@ -1,5 +1,5 @@
1
1
  export declare const HISTORY_FILE = "suwgate-runs.jsonl";
2
- export type RunMode = "quick" | "full" | "ship";
2
+ export type RunMode = "quick" | "full" | "ship" | "step";
3
3
  export type RunSource = "cli" | "stop" | "pre-commit";
4
4
  interface StepRecord {
5
5
  id: string;
@@ -19,10 +19,13 @@ export interface RunRecord {
19
19
  guards: Record<string, number>;
20
20
  excepted: Record<string, number>;
21
21
  ci: boolean;
22
+ commit?: string;
23
+ run?: string;
22
24
  }
23
25
  export declare function inCommonDir(root: string, file: string): string | null;
24
26
  export declare function historyFile(root: string): string | null;
25
27
  export declare function branchOf(root: string): string;
26
28
  export declare function recordRun(root: string, record: RunRecord, maxBytes?: number): void;
27
29
  export declare function readRuns(root: string): RunRecord[];
30
+ export declare function parseRuns(text: string): RunRecord[];
28
31
  export {};
@@ -60,10 +60,43 @@ export function readRuns(root) {
60
60
  catch {
61
61
  return [];
62
62
  }
63
+ return parseRuns(text);
64
+ }
65
+ const MODES = ["quick", "full", "ship", "step"];
66
+ const STEP_VERDICTS = ["pass", "fail", "skip"];
67
+ function counts(value) {
68
+ return typeof value === "object" && value !== null && Object.values(value).every((count) => typeof count === "number");
69
+ }
70
+ function isStep(value) {
71
+ const step = value;
72
+ return (typeof step?.id === "string" &&
73
+ typeof step.verdict === "string" &&
74
+ STEP_VERDICTS.includes(step.verdict) &&
75
+ typeof step.seconds === "number");
76
+ }
77
+ function isRun(value) {
78
+ if (typeof value !== "object" || value === null)
79
+ return false;
80
+ const run = value;
81
+ return (typeof run.at === "string" &&
82
+ !Number.isNaN(Date.parse(run.at)) &&
83
+ typeof run.mode === "string" &&
84
+ MODES.includes(run.mode) &&
85
+ typeof run.branch === "string" &&
86
+ (run.verdict === "green" || run.verdict === "red") &&
87
+ typeof run.seconds === "number" &&
88
+ Array.isArray(run.steps) &&
89
+ run.steps.every(isStep) &&
90
+ Array.isArray(run.ran) &&
91
+ run.ran.every((id) => typeof id === "string") &&
92
+ counts(run.guards) &&
93
+ counts(run.excepted));
94
+ }
95
+ export function parseRuns(text) {
63
96
  return text.split("\n").flatMap((line) => {
64
97
  try {
65
98
  const parsed = JSON.parse(line);
66
- return typeof parsed === "object" && parsed !== null && "at" in parsed ? [parsed] : [];
99
+ return isRun(parsed) ? [parsed] : [];
67
100
  }
68
101
  catch {
69
102
  return [];
@@ -1,5 +1,5 @@
1
1
  const SLOWEST_STEPS = 5;
2
- const MODES = ["quick", "full", "ship"];
2
+ const MODES = ["quick", "full", "ship", "step"];
3
3
  const DAY_MS = 24 * 60 * 60 * 1000;
4
4
  function median(values) {
5
5
  const sorted = [...values].sort((a, b) => a - b);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.17.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",