@maniumek/suwgate 0.17.0 → 0.19.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/AGENTS.shared.md CHANGED
@@ -14,7 +14,7 @@ repository's own `AGENTS.md` adds what is only its own, and wins where it says o
14
14
  one step (`suwgate step` lists them). The full gate runs only in CI: an agent never runs `suwgate check` itself. `AGENTS.md` says
15
15
  how this repository runs suwgate.
16
16
  - Done building? `/suwgate:ship`: a small change gets the gate only, a normal one also simplify and review, a careful one cannot drop the review.
17
- It runs `suwgate ship` (the quick gate and the changed e2e tests, which writes the ship record), pushes, opens the pull request,
17
+ It runs `suwgate ship` (every step of the gate except the e2e tests that did not change, which writes the ship record), pushes, opens the pull request,
18
18
  waits for CI, fixes a red run and writes the PR proof. A push or a pull
19
19
  request without a ship record for its commit is refused; a person without the plugin runs `suwgate ship` before pushing.
20
20
  - What the PR proof shows, by the kind of change: a refactor, optimisation, performance or stability change none ("behaviour
package/README.md CHANGED
@@ -49,7 +49,7 @@ Wiring the hooks (`.claude/settings.json`, `.githooks/pre-commit`) and every oth
49
49
 
50
50
  <picture>
51
51
  <source media="(prefers-color-scheme: dark)" srcset="docs/visual/board/img/readme/flow-dark.png">
52
- <img alt="How a change goes through it. On your machine: an agent edits, and guard-edit runs before every edit (gate files refused; lockfiles, API types and migrations refused); the turn ends, and stop runs the quick gate within 20 seconds (guards and changed files, skipped when nothing changed); git commit runs pre-commit (gitleaks, then the quick gate; staged secrets refused); before done, suwgate ship runs the quick gate and the e2e tests of the changed files and records the tree; an agent never runs the full gate, CI does. In CI, gate.yml: proof asks whether the tree already passed, in a few seconds (a green ci/tree stamp of the same tree skips the gate); gate runs suwgate check --verbose, every step in parallel, browser tests and the holdout scenarios included (a SKIP fails in CI); stack runs the smoke test when smoke is true (its own compose project, free ports); stamp writes ci/tree after green (the merge push is proven); release with release-npm or release-nuget (the publish job stays in the caller). Every step has a ceiling; a missing tool is SKIP, and SKIP fails in CI; exit 0 green, 1 red, 2 usage or suwgate.yml problem." src="docs/visual/board/img/readme/flow-light.png" width="100%">
52
+ <img alt="How a change goes through it. On your machine: an agent edits, and guard-edit runs before every edit (gate files refused; lockfiles, API types and migrations refused); the turn ends, and stop runs the quick gate within 20 seconds (guards and changed files, skipped when nothing changed); git commit runs pre-commit (gitleaks, then the quick gate; staged secrets refused); before done, suwgate ship runs every step except the e2e tests that did not change and records the tree; an agent never runs the full gate, CI does. In CI, gate.yml: proof asks whether the tree already passed, in a few seconds (a green ci/tree stamp of the same tree skips the gate); gate runs suwgate check --verbose, every step in parallel, browser tests and the holdout scenarios included (a SKIP fails in CI); stack runs the smoke test when smoke is true (its own compose project, free ports); stamp writes ci/tree after green (the merge push is proven); release with release-npm or release-nuget (the publish job stays in the caller). Every step has a ceiling; a missing tool is SKIP, and SKIP fails in CI; exit 0 green, 1 red, 2 usage or suwgate.yml problem." src="docs/visual/board/img/readme/flow-light.png" width="100%">
53
53
  </picture>
54
54
 
55
55
  The quick gate is what an agent meets after every turn, so it has a time budget; the full gate is what CI runs. A step that cannot
@@ -130,14 +130,14 @@ self-hosted runners: [ci/self-hosted](ci/self-hosted/README.md).
130
130
 
131
131
  <picture>
132
132
  <source media="(prefers-color-scheme: dark)" srcset="docs/visual/board/img/readme/choose-dark.png">
133
- <img alt="Which command, when. While an agent works, after every turn: suwgate check --quick (the Stop hook). Before calling a change done: suwgate ship (the quick gate and the changed e2e tests; the full gate runs in CI). What did the gate catch: suwgate stats. Is the main branch protected: suwgate doctor. Which steps does this repository have: suwgate step (lists them). One step, with what it needs, and its tool's flags: suwgate step e2e -- --headed. Run the whole local stack: suwgate dev tmux start. The server failed, why: suwgate dev logs. A linked worktree needs its own databases and ports: suwgate dev checkout-env, with eval. A sibling repository's images are behind its checkout: suwgate dev sibling name up. suwgate was upgraded and agents-shared is red: suwgate agents-shared (writes the copy)." src="docs/visual/board/img/readme/choose-light.png" width="100%">
133
+ <img alt="Which command, when. While an agent works, after every turn: suwgate check --quick (the Stop hook). Before calling a change done: suwgate ship (every step except the e2e tests that did not change; CI runs them all). What did the gate catch: suwgate stats. Is the main branch protected: suwgate doctor. Which steps does this repository have: suwgate step (lists them). One step, with what it needs, and its tool's flags: suwgate step e2e -- --headed. Run the whole local stack: suwgate dev tmux start. The server failed, why: suwgate dev logs. A linked worktree needs its own databases and ports: suwgate dev checkout-env, with eval. A sibling repository's images are behind its checkout: suwgate dev sibling name up. suwgate was upgraded and agents-shared is red: suwgate agents-shared (writes the copy)." src="docs/visual/board/img/readme/choose-light.png" width="100%">
134
134
  </picture>
135
135
 
136
136
  <details>
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
@@ -155,11 +155,12 @@ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verb
155
155
  suwgate hook stop Claude Code Stop hook: runs the quick gate unless nothing changed since it last passed
156
156
  suwgate hook pre-commit git pre-commit hook: gitleaks on the staged changes, then the quick gate
157
157
  suwgate hook pre-push git pre-push hook: refuses a push of a branch whose tree has no ship record
158
- suwgate ship needs a clean working tree: runs the quick gate and the e2e tests whose files changed on the
159
- branch, then records the tree (the pre-push and guard-pr hooks let a push of it through)
158
+ suwgate ship needs a clean working tree: runs every step of the gate except the e2e tests whose files did
159
+ not change on the branch (CI runs those), then records the tree (the pre-push and guard-pr hooks let a
160
+ push of it through)
160
161
  suwgate stats what the gate caught: runs and red share per mode, quick gate times and budget overruns, the slowest
161
162
  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)
163
+ directory (every run of check, ship, step, the Stop and pre-commit hooks appends a line there)
163
164
  --days <n> the period (30 by default), --json the same numbers as one JSON object
164
165
  suwgate doctor is the wall up: reads the rules and the branch protection of the main branch through gh and fails
165
166
  when it needs no pull request, requires no status check or not the gate's, allows force pushes or
@@ -172,15 +173,18 @@ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verb
172
173
  the wall (as suwgate doctor reads it), runs, what broke and on which branch, what the repository has,
173
174
  which acceptance criteria have a test, the installed suwagent and the last cleaning; written to
174
175
  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
176
+ --days <n> the period (30 by default, 90 at most); never runs the gate and never records a run; exit 2 on a
177
+ bad suwgate.yml; the runs are this machine's and CI's: each call asks GitHub (gh) only for the gate-history
178
+ artifacts newer than the last one it read, keeps them 90 days in the git common directory and says in the
179
+ page's first line up to when CI was read, or why it was not; --no-ci reads this machine only
176
180
  suwgate dashboard --json
177
- the data of the page as one JSON object on stdout (schemaVersion, attention, wall, runs, stopped,
181
+ the data of the page as one JSON object on stdout (schemaVersion, attention, ci, wall, runs, stopped,
178
182
  branches, steps, guards, exceptions, hooks, quietGuards, criteria, plugin, garden, about), no file
179
183
  suwgate dashboard --serve [--port <n>]
180
184
  the same page live, at http://127.0.0.1:<port>/ (4780, else the next free port), for a browser tab kept
181
185
  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> ...
186
+ keeps the opened parts open; answers only this machine, asks GitHub for the wall and for new runs of CI at
187
+ 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
188
  records a cleaning run (e.g. suwgate garden-ran docs=3 guards=2) as one line of suwgate-garden.jsonl in the
185
189
  git common directory, which suwgate dashboard shows; a kind is a kebab-case word, a count a whole number
186
190
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
@@ -248,7 +252,7 @@ The plugin has two agents, each with its own clean context. `/suwgate:ship` star
248
252
  | `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
253
  | `suwgate:simplifier` | shell, files | makes the change simpler without changing its behaviour; commits it, never pushes |
250
254
 
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.
255
+ The plugin describes suwgate 0.19.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
256
 
253
257
  ## Configuration
254
258
 
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";
@@ -26,9 +27,9 @@ import { guardPr } from "./session/guardPr.js";
26
27
  import { guardEdit } from "./session/guardEdit.js";
27
28
  import { preCommit, runTool } from "./session/preCommit.js";
28
29
  import { prePush } from "./session/prePush.js";
29
- import { ship } from "./session/ship.js";
30
+ import { LEFT_TO_CI, 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
@@ -46,11 +47,12 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
46
47
  suwgate hook stop Claude Code Stop hook: runs the quick gate unless nothing changed since it last passed
47
48
  suwgate hook pre-commit git pre-commit hook: gitleaks on the staged changes, then the quick gate
48
49
  suwgate hook pre-push git pre-push hook: refuses a push of a branch whose tree has no ship record
49
- suwgate ship needs a clean working tree: runs the quick gate and the e2e tests whose files changed on the
50
- branch, then records the tree (the pre-push and guard-pr hooks let a push of it through)
50
+ suwgate ship needs a clean working tree: runs every step of the gate except the e2e tests whose files did
51
+ not change on the branch (CI runs those), then records the tree (the pre-push and guard-pr hooks let a
52
+ push of it through)
51
53
  suwgate stats what the gate caught: runs and red share per mode, quick gate times and budget overruns, the slowest
52
54
  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)
55
+ directory (every run of check, ship, step, the Stop and pre-commit hooks appends a line there)
54
56
  --days <n> the period (30 by default), --json the same numbers as one JSON object
55
57
  suwgate doctor is the wall up: reads the rules and the branch protection of the main branch through gh and fails
56
58
  when it needs no pull request, requires no status check or not the gate's, allows force pushes or
@@ -63,15 +65,18 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
63
65
  the wall (as suwgate doctor reads it), runs, what broke and on which branch, what the repository has,
64
66
  which acceptance criteria have a test, the installed suwagent and the last cleaning; written to
65
67
  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
68
+ --days <n> the period (30 by default, 90 at most); never runs the gate and never records a run; exit 2 on a
69
+ bad suwgate.yml; the runs are this machine's and CI's: each call asks GitHub (gh) only for the gate-history
70
+ artifacts newer than the last one it read, keeps them 90 days in the git common directory and says in the
71
+ page's first line up to when CI was read, or why it was not; --no-ci reads this machine only
67
72
  suwgate dashboard --json
68
- the data of the page as one JSON object on stdout (schemaVersion, attention, wall, runs, stopped,
73
+ the data of the page as one JSON object on stdout (schemaVersion, attention, ci, wall, runs, stopped,
69
74
  branches, steps, guards, exceptions, hooks, quietGuards, criteria, plugin, garden, about), no file
70
75
  suwgate dashboard --serve [--port <n>]
71
76
  the same page live, at http://127.0.0.1:<port>/ (4780, else the next free port), for a browser tab kept
72
77
  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> ...
78
+ keeps the opened parts open; answers only this machine, asks GitHub for the wall and for new runs of CI at
79
+ 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
80
  records a cleaning run (e.g. suwgate garden-ran docs=3 guards=2) as one line of suwgate-garden.jsonl in the
76
81
  git common directory, which suwgate dashboard shows; a kind is a kebab-case word, a count a whole number
77
82
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
@@ -188,6 +193,7 @@ async function runStep(argv) {
188
193
  cwd: process.cwd(),
189
194
  id: positionals[0],
190
195
  only: values.only === true,
196
+ recordedAs: "step",
191
197
  args,
192
198
  verbose: values.verbose === true,
193
199
  env: process.env,
@@ -218,6 +224,7 @@ async function main(argv) {
218
224
  version: { type: "boolean" },
219
225
  days: { type: "string" },
220
226
  json: { type: "boolean" },
227
+ "no-ci": { type: "boolean" },
221
228
  out: { type: "string" },
222
229
  serve: { type: "boolean" },
223
230
  port: { type: "string" },
@@ -247,6 +254,7 @@ async function main(argv) {
247
254
  catalog,
248
255
  extraFiles: [],
249
256
  wall: () => Promise.resolve([]),
257
+ ci: () => Promise.resolve({ state: "off", syncedTo: null, reason: "" }),
250
258
  criterionIds,
251
259
  plugin: () => null,
252
260
  garden: () => null,
@@ -257,8 +265,8 @@ async function main(argv) {
257
265
  }
258
266
  if (command === "dashboard" && hook === undefined) {
259
267
  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`);
268
+ if (!Number.isInteger(days) || days < 1 || days > RETENTION_DAYS) {
269
+ 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
270
  return 2;
263
271
  }
264
272
  const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
@@ -283,6 +291,7 @@ async function main(argv) {
283
291
  catalog,
284
292
  extraFiles: [path.join(configDir, "plugins", "installed_plugins.json")],
285
293
  wall: async (root) => (await runDoctor(root)).checks,
294
+ ci: (root, now) => values["no-ci"] === true ? Promise.resolve({ state: "off", syncedTo: null, reason: "" }) : syncCi(root, now),
286
295
  criterionIds,
287
296
  plugin: (root) => findSuwagent(configDir, root, pluginFiles),
288
297
  garden: lastGarden,
@@ -340,7 +349,7 @@ async function main(argv) {
340
349
  console.error(`suwgate stats: ${process.cwd()} is not inside a git repository: run it in a checkout`);
341
350
  return 2;
342
351
  }
343
- const stats = summarize(readRuns(root), days, new Date());
352
+ const stats = summarize(allRuns(root), days, new Date());
344
353
  console.log(values.json === true ? JSON.stringify(stats) : formatStats(stats));
345
354
  return 0;
346
355
  }
@@ -366,8 +375,8 @@ async function main(argv) {
366
375
  const root = repositoryRoot(process.cwd()) ?? process.cwd();
367
376
  const verdict = await ship(root, {
368
377
  changedFiles: () => changedFiles(root),
369
- 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
+ gate: () => runCheck(root, false, false, { mode: "ship", without: LEFT_TO_CI }),
379
+ e2e: (files) => step({ cwd: root, id: "e2e", only: false, args: files, verbose: false, recordedAs: "ship", env: process.env, catalog }),
371
380
  });
372
381
  (verdict.exitCode === 0 ? console.log : console.error)(verdict.message);
373
382
  return verdict.exitCode;
@@ -3,12 +3,15 @@ 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[];
9
+ open: string[];
8
10
  }
9
11
  export interface BranchSummary {
10
12
  branch: string;
11
13
  runs: number;
14
+ ci: number;
12
15
  red: number;
13
16
  lastRed: {
14
17
  at: string;
@@ -20,22 +20,43 @@ function stoppersOf(run) {
20
20
  function newestFirst(a, b) {
21
21
  return Date.parse(b.at) - Date.parse(a.at);
22
22
  }
23
+ function ran(run, stopper) {
24
+ if (isRedIn(run, stopper))
25
+ return true;
26
+ if (stopper.kind === "guard")
27
+ return run.ran.includes(stopper.id);
28
+ return run.steps.some((record) => record.id === stopper.id && record.verdict !== "skip");
29
+ }
30
+ function isRedIn(run, stopper) {
31
+ return stoppersOf(run).some((other) => other.kind === stopper.kind && other.id === stopper.id);
32
+ }
33
+ function stillRedOn(runs, stopper) {
34
+ return stopper.branches.filter((branch) => {
35
+ const newest = runs.find((run) => run.branch === branch && ran(run, stopper));
36
+ return newest !== undefined && isRedIn(newest, stopper);
37
+ });
38
+ }
23
39
  export function stoppers(history, days, now) {
24
40
  const found = new Map();
25
- for (const run of runsInPeriod(history, days, now).toSorted(newestFirst)) {
41
+ const runs = runsInPeriod(history, days, now).toSorted(newestFirst);
42
+ for (const run of runs) {
26
43
  for (const { kind, id } of stoppersOf(run)) {
27
44
  const key = `${kind}:${id}`;
28
45
  const own = found.get(key);
29
46
  if (own === undefined) {
30
- found.set(key, { kind, id, runs: 1, last: run.at, branches: [run.branch] });
47
+ found.set(key, { kind, id, runs: 1, ci: run.ci ? 1 : 0, last: run.at, branches: [run.branch], open: [] });
31
48
  }
32
49
  else {
33
50
  own.runs += 1;
51
+ if (run.ci)
52
+ own.ci += 1;
34
53
  if (!own.branches.includes(run.branch))
35
54
  own.branches.push(run.branch);
36
55
  }
37
56
  }
38
57
  }
58
+ for (const stopper of found.values())
59
+ stopper.open = stillRedOn(runs, stopper);
39
60
  return [...found.values()].sort((a, b) => Date.parse(b.last) - Date.parse(a.last) || b.runs - a.runs || a.id.localeCompare(b.id));
40
61
  }
41
62
  export function causeOf(run) {
@@ -45,8 +66,10 @@ export function causeOf(run) {
45
66
  export function branches(history, days, now) {
46
67
  const found = new Map();
47
68
  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 };
69
+ const own = found.get(run.branch) ?? { branch: run.branch, runs: 0, ci: 0, red: 0, lastRed: null, lastRedRun: null };
49
70
  own.runs += 1;
71
+ if (run.ci)
72
+ own.ci += 1;
50
73
  if (run.verdict === "red") {
51
74
  own.red += 1;
52
75
  if (own.lastRedRun === null || newestFirst(own.lastRedRun, run) > 0)
@@ -67,7 +90,7 @@ function between(history, from, to) {
67
90
  return history.filter((run) => Date.parse(run.at) >= from && Date.parse(run.at) < to);
68
91
  }
69
92
  function measures(window, end) {
70
- const stats = summarize(window, Number.POSITIVE_INFINITY, new Date(end));
93
+ const stats = summarize(window.filter((run) => run.mode !== "step"), Number.POSITIVE_INFINITY, new Date(end));
71
94
  const red = Object.values(stats.modes).reduce((total, mode) => total + mode.red, 0);
72
95
  return {
73
96
  redShare: stats.runs === 0 ? null : Math.round((red / stats.runs) * 100),
@@ -8,6 +8,7 @@ export interface CheckOptions {
8
8
  catalog: Catalog;
9
9
  mode?: RunMode;
10
10
  source?: RunSource;
11
+ without?: readonly string[];
11
12
  }
12
13
  export interface StepOptions {
13
14
  cwd: string;
@@ -16,6 +17,7 @@ export interface StepOptions {
16
17
  args: readonly string[];
17
18
  verbose: boolean;
18
19
  runFolder?: string;
20
+ recordedAs?: RunMode;
19
21
  env: NodeJS.ProcessEnv;
20
22
  catalog: Catalog;
21
23
  }
@@ -66,6 +66,7 @@ async function run(command, prepared, options) {
66
66
  changed: () => (changed ??= changedFiles(root)),
67
67
  merged,
68
68
  ...(options.target === undefined ? {} : { target: options.target }),
69
+ ...(options.without === undefined ? {} : { without: options.without }),
69
70
  });
70
71
  const began = performance.now();
71
72
  const keep = options.runFolder !== undefined;
@@ -167,5 +168,6 @@ export async function step(options) {
167
168
  catalog: options.catalog,
168
169
  target: { id: options.id, only: options.only, args: options.args },
169
170
  ...(options.runFolder === undefined ? {} : { runFolder: options.runFolder }),
171
+ ...(options.recordedAs === undefined ? {} : { recorded: { mode: options.recordedAs, source: "cli" } }),
170
172
  });
171
173
  }
@@ -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) {
@@ -90,10 +111,12 @@ export function attentionOf(wall, stopped, hooks) {
90
111
  ...wall
91
112
  .filter((check) => check.state === "broken")
92
113
  .map((check) => ({ kind: "wall", text: check.name, detail: "is not in place" })),
93
- ...stopped.map((stopper) => ({
114
+ ...stopped
115
+ .filter((stopper) => stopper.open.length > 0)
116
+ .map((stopper) => ({
94
117
  kind: "broken",
95
118
  text: `${stopper.id} stopped the gate ${stopper.runs} time${stopper.runs === 1 ? "" : "s"}`,
96
- detail: `on ${stopper.branches.join(", ")}`,
119
+ detail: `still red on ${stopper.open.join(", ")}`,
97
120
  })),
98
121
  ...hooks
99
122
  .filter((hook) => !hook.wired)
@@ -110,6 +133,7 @@ export function collectDashboard(input) {
110
133
  wall: input.wall,
111
134
  wallCheckedAt: input.wallCheckedAt,
112
135
  live: input.live,
136
+ ci: { ...input.ci, runs: runsInPeriod(input.runs, input.days, input.now).filter((run) => run.ci).length },
113
137
  stats: summarize(input.runs, input.days, input.now),
114
138
  trends: trends(input.runs, input.days, input.now),
115
139
  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.",
@@ -122,14 +122,12 @@ function sentence(text) {
122
122
  function noRuns(days) {
123
123
  return sentence(`No runs recorded in the last ${days} days. Commands that record a run: ${RECORDING_COMMANDS}.`);
124
124
  }
125
- const PARTS = { wall: 1, broken: 3, have: 5 };
126
125
  function attention(data) {
127
126
  const count = data.attention.length;
128
127
  const headline = count === 0 ? "Nothing needs you" : `${plural(count, "thing")} ${count === 1 ? "needs" : "need"} you`;
129
128
  const rows = data.attention.map((item) => {
130
- const target = PARTS[item.kind];
131
129
  const label = mark("broken", item.kind === "have" ? "hook" : item.kind);
132
- return row(`${label} ${escapeHtml(item.text)}`, [escapeHtml(item.detail), `<a href="#part-${item.kind}">&rarr; ${target}</a>`]);
130
+ return row(`${label} ${escapeHtml(item.text)}`, [escapeHtml(item.detail), `<a href="#part-${item.kind}">details</a>`]);
133
131
  });
134
132
  return `<section class="panel"><p class="headline">${escapeHtml(headline)}</p>${keyed("attention", list(rows, "items"))}</section>`;
135
133
  }
@@ -161,6 +159,19 @@ function runsPart(data) {
161
159
  const perDay = data.perDay.map((own) => row(escapeHtml(day(`${own.day}T00:00:00Z`)), [plural(own.runs, "run"), `${own.red} red`]));
162
160
  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
161
  }
162
+ function inCi(count) {
163
+ return count === 0 ? "" : ` (${count} in CI)`;
164
+ }
165
+ function sourcesOf(ci) {
166
+ const upTo = ci.syncedTo === null ? "" : ` up to ${escapeHtml(stamp(new Date(ci.syncedTo)))}`;
167
+ if (ci.state === "off")
168
+ return "this machine";
169
+ if (ci.state === "syncing")
170
+ return `this machine and CI${upTo} · reading CI now`;
171
+ if (ci.state === "unavailable")
172
+ return `this machine${upTo === "" ? "" : ` and CI${upTo}`} · CI not read: ${escapeHtml(ci.reason)}`;
173
+ return ci.syncedTo === null ? "this machine and CI · no run of CI recorded yet" : `this machine and CI${upTo}`;
174
+ }
164
175
  function brokenPart(data) {
165
176
  if (data.stats.runs === 0)
166
177
  return part("broken", 3, "Broken", "no runs recorded", noRuns(data.days));
@@ -171,7 +182,7 @@ function brokenPart(data) {
171
182
  const conclusion = [guards > 0 ? plural(guards, "guard") : "", steps > 0 ? plural(steps, "step") : ""]
172
183
  .filter((text) => text !== "")
173
184
  .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(", ")}`));
185
+ 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
186
  return part("broken", 3, "Broken", `${conclusion}, last ${day(data.stopped[0]?.last ?? "")}`, list(rows, "items"));
176
187
  }
177
188
  function branchesPart(data) {
@@ -180,7 +191,7 @@ function branchesPart(data) {
180
191
  const red = data.branches.filter((branch) => branch.red > 0).length;
181
192
  const conclusion = `${plural(data.branches.length, "branch", "branches")}, ${red} with red runs`;
182
193
  const rows = data.branches.map((branch) => row(escapeHtml(branch.branch), [
183
- plural(branch.runs, "run"),
194
+ `${plural(branch.runs, "run")}${inCi(branch.ci)}`,
184
195
  `${branch.red} red`,
185
196
  branch.lastRed === null ? "-" : `last red ${escapeHtml(day(branch.lastRed.at))}`,
186
197
  ], branch.lastRed === null ? "" : `last red: ${escapeHtml(branch.lastRed.cause)}`));
@@ -277,7 +288,7 @@ export function renderDashboard(data) {
277
288
  <body data-version="">
278
289
  <main id="live-root">
279
290
  <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>
291
+ <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
292
  ${attention(data)}
282
293
  ${wallPart(data)}
283
294
  ${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 [];
@@ -11,6 +11,7 @@ export interface PlannedStep {
11
11
  id: string;
12
12
  title: string;
13
13
  after: readonly string[];
14
+ orderOnly?: readonly string[];
14
15
  limitSeconds: number;
15
16
  environment: readonly Environment[];
16
17
  skipped?: {
@@ -38,6 +39,7 @@ export interface PlanInput {
38
39
  changed: () => readonly string[];
39
40
  merged?: readonly GuardException[];
40
41
  target?: Target;
42
+ without?: readonly string[];
41
43
  }
42
44
  export interface ListedStep {
43
45
  id: string;
package/dist/gate/plan.js CHANGED
@@ -108,17 +108,21 @@ export function plan(input) {
108
108
  const steps = allSteps(input.config, input.catalog);
109
109
  const chosen = selected(steps, input);
110
110
  const planned = chosen.has(GUARDS_STEP) ? [guardsStep(input)] : [];
111
- for (const step of steps.filter((candidate) => chosen.has(candidate.id))) {
111
+ const left = new Set(input.without ?? []);
112
+ for (const step of steps.filter((candidate) => chosen.has(candidate.id) && !left.has(candidate.id))) {
112
113
  const asked = input.target?.id === step.id;
113
114
  const run = chosenRun(step, input.quick);
114
115
  if (run === undefined)
115
116
  continue;
116
117
  const cwd = path.join(input.root, (step.profile === undefined ? undefined : input.config.directories[step.profile]) ?? "");
117
118
  const configured = input.config.configure[step.id];
119
+ const required = needed(step, input.config);
120
+ const orderOnly = (step.orderAfter ?? []).filter((id) => !required.includes(id));
118
121
  const base = {
119
122
  id: step.id,
120
123
  title: step.title,
121
- after: [...needed(step, input.config), ...(step.orderAfter ?? [])],
124
+ after: [...required, ...orderOnly],
125
+ ...(orderOnly.length === 0 ? {} : { orderOnly }),
122
126
  limitSeconds: configured?.limitSeconds ?? step.limitSeconds ?? DEFAULT_LIMIT_SECONDS,
123
127
  environment: environmentOf(step, input.config),
124
128
  };
@@ -68,7 +68,9 @@ export async function runSteps(steps, env, stepLimit) {
68
68
  const finished = await Promise.all(dependencies);
69
69
  if (step.skipped !== undefined)
70
70
  return { step, status: "skip", seconds: 0, log: step.skipped.reason };
71
- const failed = finished.filter((dependency) => dependency.status === "fail").map((dependency) => dependency.step.id);
71
+ const failed = finished
72
+ .filter((dependency) => dependency.status === "fail" && !(step.orderOnly ?? []).includes(dependency.step.id))
73
+ .map((dependency) => dependency.step.id);
72
74
  if (failed.length > 0)
73
75
  return { step, status: "fail", seconds: 0, log: `not run: ${failed.join(", ")} failed first` };
74
76
  const began = performance.now();
@@ -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);
@@ -1,10 +1,11 @@
1
+ export declare const LEFT_TO_CI: string[];
1
2
  export interface ShipVerdict {
2
3
  exitCode: 0 | 1;
3
4
  message: string;
4
5
  }
5
6
  export interface ShipSteps {
6
7
  changedFiles: () => readonly string[];
7
- quickCheck: () => Promise<{
8
+ gate: () => Promise<{
8
9
  exitCode: number;
9
10
  text: string;
10
11
  }>;
@@ -1,5 +1,6 @@
1
1
  import { isClean, treeOf, writeShipRecord } from "./shipRecord.js";
2
2
  const SHOWN_LINES = 80;
3
+ export const LEFT_TO_CI = ["e2e", "criteria-ran"];
3
4
  function tail(text) {
4
5
  return text.trimEnd().split("\n").slice(-SHOWN_LINES).join("\n");
5
6
  }
@@ -10,9 +11,9 @@ export async function ship(root, steps) {
10
11
  message: "ship: the working tree has uncommitted or untracked changes: commit your work first, ship records the committed tree",
11
12
  };
12
13
  }
13
- const quick = await steps.quickCheck();
14
- if (quick.exitCode !== 0) {
15
- return { exitCode: 1, message: `${tail(quick.text)}\nship: the quick gate is red (above): fix it, commit, and run ship again` };
14
+ const gate = await steps.gate();
15
+ if (gate.exitCode !== 0) {
16
+ return { exitCode: 1, message: `${tail(gate.text)}\nship: the gate is red (above): fix it, commit, and run ship again` };
16
17
  }
17
18
  const tests = steps.changedFiles().filter((file) => file.endsWith(".e2e.ts"));
18
19
  if (tests.length > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.17.0",
3
+ "version": "0.19.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",