@maniumek/suwgate 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/AGENTS.shared.md +13 -2
  2. package/README.md +98 -9
  3. package/dist/cli.js +217 -13
  4. package/dist/gate/breakdown.d.ts +40 -0
  5. package/dist/gate/breakdown.js +111 -0
  6. package/dist/gate/check.d.ts +4 -0
  7. package/dist/gate/check.js +38 -1
  8. package/dist/gate/ciHistory.d.ts +21 -0
  9. package/dist/gate/ciHistory.js +195 -0
  10. package/dist/gate/config.d.ts +5 -1
  11. package/dist/gate/config.js +56 -2
  12. package/dist/gate/context.d.ts +15 -0
  13. package/dist/gate/context.js +98 -0
  14. package/dist/gate/contract.d.ts +7 -0
  15. package/dist/gate/contract.js +1 -0
  16. package/dist/gate/dashboard.d.ts +112 -0
  17. package/dist/gate/dashboard.js +148 -0
  18. package/dist/gate/dashboardFile.d.ts +33 -0
  19. package/dist/gate/dashboardFile.js +185 -0
  20. package/dist/gate/dashboardJson.d.ts +2 -0
  21. package/dist/gate/dashboardJson.js +26 -0
  22. package/dist/gate/dashboardPage.d.ts +3 -0
  23. package/dist/gate/dashboardPage.js +307 -0
  24. package/dist/gate/dashboardServer.d.ts +11 -0
  25. package/dist/gate/dashboardServer.js +70 -0
  26. package/dist/gate/dashboardTesting.d.ts +12 -0
  27. package/dist/gate/dashboardTesting.js +99 -0
  28. package/dist/gate/guardsStep.d.ts +6 -0
  29. package/dist/gate/guardsStep.js +8 -1
  30. package/dist/gate/history.d.ts +31 -0
  31. package/dist/gate/history.js +105 -0
  32. package/dist/gate/plan.d.ts +3 -1
  33. package/dist/gate/plan.js +6 -3
  34. package/dist/gate/repository.d.ts +1 -0
  35. package/dist/gate/repository.js +1 -1
  36. package/dist/gate/runner.d.ts +3 -0
  37. package/dist/gate/runner.js +4 -1
  38. package/dist/gate/stats.d.ts +27 -0
  39. package/dist/gate/stats.js +84 -0
  40. package/dist/guards/comments/eslint.js +1 -0
  41. package/dist/guards/comments/scan.js +1 -0
  42. package/dist/guards/comments/switches.js +1 -0
  43. package/dist/guards/database/connectionHost.js +1 -0
  44. package/dist/guards/dotnet/appsettingsBound.js +1 -0
  45. package/dist/guards/dotnet/bannedNugetPackages.js +1 -0
  46. package/dist/guards/dotnet/openApiVersions.js +1 -0
  47. package/dist/guards/dotnet/suwbackkitWiring.js +1 -0
  48. package/dist/guards/dotnet/unusedNugetVersions.js +1 -0
  49. package/dist/guards/repository/bannedNpmPackages.js +1 -0
  50. package/dist/guards/repository/composePorts.js +1 -0
  51. package/dist/guards/repository/dependencyDirection.js +1 -0
  52. package/dist/guards/repository/forbiddenNames.js +1 -0
  53. package/dist/guards/repository/humanDocs.js +1 -0
  54. package/dist/guards/repository/imagePins.js +1 -0
  55. package/dist/guards/repository/justModules.js +1 -0
  56. package/dist/guards/repository/noRawColors.js +1 -0
  57. package/dist/guards/repository/repositoryLayout.js +1 -0
  58. package/dist/guards/repository/scriptsCalled.js +1 -0
  59. package/dist/guards/repository/scriptsHelp.js +1 -0
  60. package/dist/guards/repository/suwfrontkitWiring.js +1 -0
  61. package/dist/guards/repository/vsCodeSettings.js +1 -0
  62. package/dist/profiles/holdout.d.ts +2 -0
  63. package/dist/profiles/holdout.js +38 -0
  64. package/dist/profiles/index.d.ts +1 -0
  65. package/dist/profiles/index.js +1 -0
  66. package/dist/profiles/reports.d.ts +6 -0
  67. package/dist/profiles/reports.js +14 -0
  68. package/dist/profiles/verdict.js +41 -2
  69. package/dist/session/doctor.d.ts +26 -0
  70. package/dist/session/doctor.js +265 -0
  71. package/dist/session/gardenRecord.d.ts +12 -0
  72. package/dist/session/gardenRecord.js +58 -0
  73. package/dist/session/guardPr.js +2 -2
  74. package/dist/session/prePush.js +1 -1
  75. package/dist/session/suwagentInfo.d.ts +28 -0
  76. package/dist/session/suwagentInfo.js +103 -0
  77. package/package.json +1 -1
  78. package/schema/suwgate.schema.json +26 -0
@@ -0,0 +1,307 @@
1
+ const LIST_LIMIT = 5;
2
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3
+ const RECORDING_COMMANDS = "suwgate check, suwgate ship, suwgate step, the Stop hook and the pre-commit hook";
4
+ const STYLE = `
5
+ :root{--bg:#fafafa;--surface:#fff;--text:#1d1d1f;--muted:#6b6b70;--line:#e2e2e6;--spark:#8a8a90;--holds:#1a7f37;--broken:#cf222e;--unchecked:#9a6700}
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}}
7
+ *{box-sizing:border-box}
8
+ body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
9
+ main{max-width:880px;margin:0 auto;padding:24px 16px 64px}
10
+ h1{font-size:20px;margin:0}
11
+ .sub{color:var(--muted);margin:2px 0 20px}
12
+ .panel{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 16px;margin-bottom:16px}
13
+ .panel .headline{font-weight:600;margin:0 0 4px}
14
+ details.part{background:var(--surface);border:1px solid var(--line);border-radius:8px;margin-bottom:8px;position:relative}
15
+ .tip{display:none;position:absolute;left:12px;top:calc(100% - 4px);z-index:3;max-width:520px;padding:8px 12px;background:var(--text);color:var(--bg);border-radius:6px;font-size:13px;line-height:1.4;font-weight:400;white-space:normal}
16
+ details.part:not([open])>summary:hover .tip,details.part:not([open])>summary:focus-visible .tip{display:block}
17
+ .about{color:var(--muted);font-size:13px;margin:0 0 8px}
18
+ details.part>summary{display:flex;gap:12px;align-items:baseline;padding:10px 16px;cursor:pointer;list-style:none}
19
+ details.part>summary::-webkit-details-marker{display:none}
20
+ details.part>summary::after{content:"+";margin-left:auto;color:var(--muted);padding-left:12px}
21
+ details.part[open]>summary::after{content:"-"}
22
+ .part-title{font-weight:600;white-space:nowrap}
23
+ .conclusion{color:var(--muted);text-align:right;margin-left:auto;min-width:0}
24
+ .body{padding:4px 16px 14px;border-top:1px solid var(--line)}
25
+ .body h3{font-size:13px;color:var(--muted);font-weight:600;margin:14px 0 4px;text-transform:uppercase;letter-spacing:.04em}
26
+ ul.rows{list-style:none;margin:0;padding:0}
27
+ .row{display:flex;gap:16px;justify-content:space-between;align-items:baseline;padding:5px 0;border-bottom:1px solid var(--line)}
28
+ .row:last-child{border-bottom:0}
29
+ .row .name{min-width:0;overflow-wrap:anywhere}
30
+ .row .nums{display:flex;gap:14px;align-items:center;justify-content:flex-end;text-align:right;color:var(--muted);font-variant-numeric:tabular-nums;white-space:nowrap}
31
+ .row .note{display:block;color:var(--muted);font-size:13px}
32
+ .mark{font-size:12px;font-weight:600;white-space:nowrap}
33
+ .mark.holds{color:var(--holds)}
34
+ .mark.broken{color:var(--broken)}
35
+ .mark.unchecked{color:var(--unchecked)}
36
+ .spark{width:64px;height:18px;vertical-align:middle}
37
+ .spark polyline{fill:none;stroke:var(--spark);stroke-width:1.5}
38
+ details.more>summary{cursor:pointer;color:var(--muted);padding:5px 0;font-size:13px}
39
+ a{color:inherit}
40
+ .live{color:var(--muted);border:1px solid var(--line);border-radius:4px;padding:0 5px;font-size:12px}
41
+ #live-note{color:var(--muted)}
42
+ .empty{color:var(--muted);margin:8px 0}
43
+ code{font:13px ui-monospace,Menlo,Consolas,monospace}
44
+ `;
45
+ function escapeHtml(value) {
46
+ return String(value).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
47
+ }
48
+ function day(iso) {
49
+ const date = new Date(iso);
50
+ return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()] ?? ""}`;
51
+ }
52
+ function stamp(date) {
53
+ const time = date.toISOString();
54
+ return `${day(time)} ${date.getUTCFullYear()} ${time.slice(11, 16)} UTC`;
55
+ }
56
+ function seconds(value) {
57
+ return value === null ? "-" : `${value} s`;
58
+ }
59
+ function percent(value) {
60
+ return value === null ? "-" : `${value}%`;
61
+ }
62
+ function plural(count, one, many = `${one}s`) {
63
+ return `${count} ${count === 1 ? one : many}`;
64
+ }
65
+ function mark(state, label) {
66
+ return `<span class="mark ${state}">${escapeHtml(label)}</span>`;
67
+ }
68
+ function row(name, numbers = [], note = "") {
69
+ const noteHtml = note === "" ? "" : `<span class="note">${note}</span>`;
70
+ return `<li class="row"><span class="name">${name}${noteHtml}</span><span class="nums">${numbers.map((value) => `<span>${value}</span>`).join("")}</span></li>`;
71
+ }
72
+ function list(rows, noun) {
73
+ if (rows.length === 0)
74
+ return "";
75
+ const shown = rows.slice(0, LIST_LIMIT);
76
+ const rest = rows.slice(LIST_LIMIT);
77
+ const more = rest.length === 0
78
+ ? ""
79
+ : `<details class="more"><summary>show ${rest.length} more ${escapeHtml(noun)}</summary><ul class="rows">${rest.join("")}</ul></details>`;
80
+ return `<ul class="rows">${shown.join("")}</ul>${more}`;
81
+ }
82
+ function sparkline(values) {
83
+ const low = Math.min(...values);
84
+ const high = Math.max(...values);
85
+ const points = values
86
+ .map((value, index) => {
87
+ const x = values.length === 1 ? 32 : (index / (values.length - 1)) * 64;
88
+ const y = high === low ? 9 : 16 - ((value - low) / (high - low)) * 14;
89
+ return `${x.toFixed(1)},${y.toFixed(1)}`;
90
+ })
91
+ .join(" ");
92
+ return `<svg class="spark" viewBox="0 0 64 18" role="img" aria-label="trend over the period"><polyline points="${points}"/></svg>`;
93
+ }
94
+ function metric(name, point, show) {
95
+ return row(escapeHtml(name), [
96
+ sparkline(point.buckets),
97
+ `<strong>${escapeHtml(show(point.now))}</strong>`,
98
+ `was ${escapeHtml(show(point.before))}`,
99
+ ]);
100
+ }
101
+ function keyed(prefix, html) {
102
+ let index = 0;
103
+ return html.replace(/<details class="more">/g, () => `<details class="more" data-key="${prefix}-${index++}">`);
104
+ }
105
+ export const ABOUT = {
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 and read from CI, where alone the full gate runs, beside the previous period.",
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
+ branches: "Where does it break? Each branch with its runs, its red runs and the cause of the last red one.",
110
+ have: "What guards this repository? The steps of the gate, the guards with their sets, the exceptions with their reasons, and the hooks.",
111
+ criteria: "Does every promise of a spec have a test? Each acceptance criterion with the test files that name it.",
112
+ suwagent: "How is the agent set up? The installed suwagent plugin: its skills, its hooks and its agents.",
113
+ cleaning: "When did the cleaning last run, and what did it find? The trace /suwgate:garden leaves. Information only.",
114
+ };
115
+ function part(slug, number, title, conclusion, body) {
116
+ const about = escapeHtml(ABOUT[slug] ?? "");
117
+ return `<details class="part" id="part-${slug}"><summary><span class="part-title">${number}. ${escapeHtml(title)}</span><span class="tip" role="tooltip">${about}</span><span class="conclusion">${escapeHtml(conclusion)}</span></summary><div class="body"><p class="about">${about}</p>${keyed(slug, body)}</div></details>`;
118
+ }
119
+ function sentence(text) {
120
+ return `<p class="empty">${escapeHtml(text)}</p>`;
121
+ }
122
+ function noRuns(days) {
123
+ return sentence(`No runs recorded in the last ${days} days. Commands that record a run: ${RECORDING_COMMANDS}.`);
124
+ }
125
+ const PARTS = { wall: 1, broken: 3, have: 5 };
126
+ function attention(data) {
127
+ const count = data.attention.length;
128
+ const headline = count === 0 ? "Nothing needs you" : `${plural(count, "thing")} ${count === 1 ? "needs" : "need"} you`;
129
+ const rows = data.attention.map((item) => {
130
+ const target = PARTS[item.kind];
131
+ 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>`]);
133
+ });
134
+ return `<section class="panel"><p class="headline">${escapeHtml(headline)}</p>${keyed("attention", list(rows, "items"))}</section>`;
135
+ }
136
+ function wallPart(data) {
137
+ const broken = data.wall.filter((check) => check.state === "broken").length;
138
+ const unchecked = data.wall.filter((check) => check.state === "unchecked").length;
139
+ const conclusion = broken > 0
140
+ ? `${broken} of ${data.wall.length} checks broken`
141
+ : unchecked > 0
142
+ ? `${unchecked} of ${data.wall.length} checks not checked`
143
+ : `all ${data.wall.length} checks hold`;
144
+ const labels = { holds: "holds", broken: "broken", unchecked: "not checked" };
145
+ const rows = data.wall.map((check) => row(escapeHtml(check.name), [mark(check.state, labels[check.state])], escapeHtml(check.detail)));
146
+ return part("wall", 1, "The wall", conclusion, `${sentence(`Checked ${stamp(data.wallCheckedAt)}`)}${list(rows, "checks")}`);
147
+ }
148
+ function runsPart(data) {
149
+ const { stats, trends } = data;
150
+ if (stats.runs === 0)
151
+ return part("runs", 2, "Runs", "no runs recorded", noRuns(data.days));
152
+ const conclusion = `${plural(stats.runs, "run")} · ${percent(trends.redShare.now)} red (was ${percent(trends.redShare.before)}) · median ${seconds(trends.quickMedian.now)} (was ${seconds(trends.quickMedian.before)})`;
153
+ const modes = Object.entries(stats.modes).map(([mode, own]) => row(escapeHtml(mode), [plural(own.runs, "run"), `${own.red} red (${Math.round((own.red / own.runs) * 100)}%)`]));
154
+ const metrics = [
155
+ metric("Red share", trends.redShare, percent),
156
+ metric("Quick gate, median", trends.quickMedian, seconds),
157
+ metric("Over the budget", trends.overBudget, (value) => String(value ?? 0)),
158
+ ...(stats.quick === null ? [] : [row("Slowest quick run", [seconds(stats.quick.slowestSeconds)])]),
159
+ ];
160
+ const steps = stats.slowestSteps.map((step) => row(escapeHtml(step.id), [seconds(step.medianSeconds)]));
161
+ const perDay = data.perDay.map((own) => row(escapeHtml(day(`${own.day}T00:00:00Z`)), [plural(own.runs, "run"), `${own.red} red`]));
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
+ }
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
+ }
177
+ function brokenPart(data) {
178
+ if (data.stats.runs === 0)
179
+ return part("broken", 3, "Broken", "no runs recorded", noRuns(data.days));
180
+ if (data.stopped.length === 0)
181
+ return part("broken", 3, "Broken", "nothing stopped the gate", sentence("No guard or step stopped the gate in this period."));
182
+ const guards = data.stopped.filter((stopper) => stopper.kind === "guard").length;
183
+ const steps = data.stopped.length - guards;
184
+ const conclusion = [guards > 0 ? plural(guards, "guard") : "", steps > 0 ? plural(steps, "step") : ""]
185
+ .filter((text) => text !== "")
186
+ .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(", ")}`));
188
+ return part("broken", 3, "Broken", `${conclusion}, last ${day(data.stopped[0]?.last ?? "")}`, list(rows, "items"));
189
+ }
190
+ function branchesPart(data) {
191
+ if (data.stats.runs === 0)
192
+ return part("branches", 4, "Branches", "no runs recorded", noRuns(data.days));
193
+ const red = data.branches.filter((branch) => branch.red > 0).length;
194
+ const conclusion = `${plural(data.branches.length, "branch", "branches")}, ${red} with red runs`;
195
+ const rows = data.branches.map((branch) => row(escapeHtml(branch.branch), [
196
+ `${plural(branch.runs, "run")}${inCi(branch.ci)}`,
197
+ `${branch.red} red`,
198
+ branch.lastRed === null ? "-" : `last red ${escapeHtml(day(branch.lastRed.at))}`,
199
+ ], branch.lastRed === null ? "" : `last red: ${escapeHtml(branch.lastRed.cause)}`));
200
+ return part("branches", 4, "Branches", conclusion, list(rows, "branches"));
201
+ }
202
+ function havePart(data) {
203
+ const active = data.guards.filter((guard) => guard.state === "active").length;
204
+ const wired = data.hooks.filter((hook) => hook.wired).length;
205
+ const guardCount = active === data.guards.length ? plural(active, "guard") : `${active} of ${plural(data.guards.length, "guard")} active`;
206
+ const hookCount = wired === data.hooks.length ? plural(wired, "hook") : `${wired} of ${plural(data.hooks.length, "hook")} wired`;
207
+ const conclusion = `${guardCount} · ${plural(data.exceptions.length, "exception")} · ${hookCount}`;
208
+ const steps = data.steps.map((step) => row(escapeHtml(step.id), [step.skipped === undefined ? "" : "skipped"], escapeHtml(step.skipped === undefined ? step.title : `${step.title}: ${step.skipped}`)));
209
+ const guards = data.guards.map((guard) => row(escapeHtml(guard.id), [escapeHtml(guard.set), escapeHtml(guard.state)], guard.skipReason === "" ? "" : escapeHtml(guard.skipReason)));
210
+ const exceptions = data.exceptions.map((exception) => row(`${escapeHtml(exception.guard)} <span class="note">${escapeHtml(exception.target)}</span>`, [
211
+ exception.covered === null
212
+ ? "no run yet"
213
+ : `${plural(exception.covered, "finding")} in the latest run${exception.sharedBy > 1 ? " of the guard" : ""}`,
214
+ ], escapeHtml(exception.reason)));
215
+ const hooks = data.hooks.map((hook) => row(escapeHtml(hook.id), [escapeHtml(hook.where), hook.wired ? mark("holds", "wired") : mark("broken", "not wired")]));
216
+ const quiet = data.stats.runs === 0
217
+ ? ""
218
+ : `<h3>Guards with no finding in ${data.days} days</h3>${data.stats.quiet.length === 0
219
+ ? sentence("None.")
220
+ : list(data.stats.quiet.map((id) => row(escapeHtml(id))), "guards")}`;
221
+ return part("have", 5, "What we have", conclusion, `<h3>Steps</h3>${list(steps, "steps")}<h3>Guards</h3>${list(guards, "guards")}<h3>Exceptions</h3>${exceptions.length === 0 ? sentence("None.") : list(exceptions, "exceptions")}<h3>Hooks</h3>${list(hooks, "hooks")}${quiet}`);
222
+ }
223
+ function criteriaPart(data) {
224
+ if (data.criteria === null)
225
+ return part("criteria", 6, "Criteria", "no specs", sentence("No specification in the specs folder."));
226
+ const unnamed = data.criteria.filter((criterion) => criterion.tests.length === 0).length;
227
+ const conclusion = `${plural(data.criteria.length, "criterion", "criteria")} · ${unnamed === 0 ? "all with a test" : `${unnamed} without a test`}`;
228
+ const rows = data.criteria.map((criterion) => row(escapeHtml(criterion.id), [criterion.tests.length === 0 ? mark("broken", "no test") : mark("holds", plural(criterion.tests.length, "test"))], criterion.tests.map((test) => `${escapeHtml(test.file)} (${escapeHtml(test.kind)})`).join("<br>")));
229
+ return part("criteria", 6, "Criteria", conclusion, list(rows, "criteria"));
230
+ }
231
+ function suwagentPart(data) {
232
+ const { plugin } = data;
233
+ if (plugin === null)
234
+ return part("suwagent", 7, "Suwagent", "not installed here", sentence("The suwagent plugin is not installed here."));
235
+ const conclusion = `version ${plugin.version} · ${plural(plugin.skills.length, "skill")} · ${plural(plugin.hooks.length, "hook")} · ${plural(plugin.agents.length, "agent")}`;
236
+ const skills = plugin.skills.map((skill) => row(escapeHtml(skill.name), [skill.onlyWhenAsked ? "only when you ask" : "the agent may start it"], escapeHtml(skill.summary)));
237
+ const hooks = plugin.hooks.map((hook) => row(escapeHtml(hook.script), [escapeHtml(hook.event), escapeHtml(hook.matcher)]));
238
+ const agents = plugin.agents.map((agent) => row(escapeHtml(agent.name), [escapeHtml(agent.tools)], escapeHtml(agent.description)));
239
+ const hookNote = plugin.hookDescription === "" ? "" : sentence(plugin.hookDescription);
240
+ return part("suwagent", 7, "Suwagent", conclusion, `<h3>Skills</h3>${list(skills, "skills")}<h3>Hooks</h3>${hookNote}${list(hooks, "hooks")}<h3>Agents</h3>${list(agents, "agents")}`);
241
+ }
242
+ function cleaningPart(data) {
243
+ if (data.garden === null)
244
+ return part("cleaning", 8, "Cleaning", "has not run here yet", sentence("The cleaning has not run here yet."));
245
+ const kinds = Object.entries(data.garden.found);
246
+ const total = kinds.reduce((sum, [, count]) => sum + count, 0);
247
+ const rows = kinds.map(([kind, count]) => row(escapeHtml(kind), [String(count)]));
248
+ return part("cleaning", 8, "Cleaning", `last run ${day(data.garden.at)} · ${plural(total, "item")} found`, `${sentence(`Last run ${day(data.garden.at)} on ${data.garden.branch}.`)}${list(rows, "kinds")}`);
249
+ }
250
+ const LIVE_SCRIPT = `
251
+ (function () {
252
+ var last = document.body.dataset.version;
253
+ function openKeys(root) {
254
+ return Array.prototype.filter.call(root.querySelectorAll("details"), function (d) { return d.open; }).map(function (d) {
255
+ return d.id ? "#" + d.id : "[data-key='" + d.dataset.key + "']";
256
+ });
257
+ }
258
+ function refresh(text) {
259
+ var root = document.getElementById("live-root");
260
+ var fresh = new DOMParser().parseFromString(text, "text/html").getElementById("live-root");
261
+ if (!root || !fresh) { return; }
262
+ var keys = openKeys(root);
263
+ var y = window.scrollY;
264
+ root.innerHTML = fresh.innerHTML;
265
+ keys.forEach(function (key) { var d = root.querySelector(key); if (d) { d.open = true; } });
266
+ window.scrollTo(0, y);
267
+ }
268
+ function say(text) { var note = document.getElementById("live-note"); if (note) { note.textContent = text; } }
269
+ function ok(response) { if (!response.ok) { throw new Error("status"); } return response.text(); }
270
+ function tick() {
271
+ fetch("/version", { cache: "no-store" }).then(ok).then(function (version) {
272
+ if (version === last) { say(""); return; }
273
+ return fetch("/", { cache: "no-store" }).then(ok).then(function (text) { refresh(text); last = version; say(""); });
274
+ }).catch(function () { say("not live: the server stopped"); });
275
+ }
276
+ setInterval(tick, 3000);
277
+ })();
278
+ `;
279
+ export function renderDashboard(data) {
280
+ const title = `suwgate · ${data.name}`;
281
+ return `<!doctype html>
282
+ <html lang="en">
283
+ <head>
284
+ <meta charset="utf-8">
285
+ <meta name="viewport" content="width=device-width, initial-scale=1">
286
+ <meta name="color-scheme" content="light dark">
287
+ <title>${escapeHtml(title)}</title>
288
+ <style>${STYLE}</style>
289
+ </head>
290
+ <body data-version="">
291
+ <main id="live-root">
292
+ <h1>${escapeHtml(title)}</h1>
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>
294
+ ${attention(data)}
295
+ ${wallPart(data)}
296
+ ${runsPart(data)}
297
+ ${brokenPart(data)}
298
+ ${branchesPart(data)}
299
+ ${havePart(data)}
300
+ ${criteriaPart(data)}
301
+ ${suwagentPart(data)}
302
+ ${cleaningPart(data)}
303
+ </main>
304
+ ${data.live ? `<script>${LIVE_SCRIPT}</script>\n` : ""}</body>
305
+ </html>
306
+ `;
307
+ }
@@ -0,0 +1,11 @@
1
+ export interface DashboardServerOptions {
2
+ port: number;
3
+ fallbacks: number;
4
+ page: () => Promise<string>;
5
+ fingerprint: () => string;
6
+ }
7
+ export interface DashboardServer {
8
+ port: number;
9
+ close: () => Promise<void>;
10
+ }
11
+ export declare function startDashboardServer(options: DashboardServerOptions): Promise<DashboardServer>;
@@ -0,0 +1,70 @@
1
+ import { createServer } from "node:http";
2
+ const HOST = "127.0.0.1";
3
+ const LOCAL_NAMES = ["127.0.0.1", "localhost"];
4
+ function reply(response, status, type, body) {
5
+ response.writeHead(status, {
6
+ "content-type": `${type}; charset=utf-8`,
7
+ "cache-control": "no-store",
8
+ ...(status === 405 ? { allow: "GET" } : {}),
9
+ });
10
+ response.end(body);
11
+ }
12
+ function fromThisMachine(request) {
13
+ const address = request.socket.remoteAddress ?? "";
14
+ const host = (request.headers.host ?? "").replace(/:\d+$/, "");
15
+ return (address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1") && LOCAL_NAMES.includes(host);
16
+ }
17
+ function handler(options) {
18
+ return (request, response) => {
19
+ const pathname = new URL(request.url ?? "/", `http://${HOST}`).pathname;
20
+ if (!fromThisMachine(request)) {
21
+ reply(response, 403, "text/plain", "this page answers only requests from this machine");
22
+ }
23
+ else if (request.method !== "GET") {
24
+ reply(response, 405, "text/plain", "only GET");
25
+ }
26
+ else if (pathname === "/version") {
27
+ reply(response, 200, "text/plain", options.fingerprint());
28
+ }
29
+ else if (pathname !== "/") {
30
+ reply(response, 404, "text/plain", "not found");
31
+ }
32
+ else {
33
+ serveRoot(options, response);
34
+ }
35
+ };
36
+ }
37
+ function serveRoot(options, response) {
38
+ const version = options.fingerprint();
39
+ options
40
+ .page()
41
+ .then((html) => reply(response, 200, "text/html", html.replace('data-version=""', `data-version="${version}"`)))
42
+ .catch((error) => reply(response, 500, "text/plain", error instanceof Error ? error.message : String(error)));
43
+ }
44
+ function listen(server, port) {
45
+ return new Promise((resolve, reject) => {
46
+ const failed = (error) => (error.code === "EADDRINUSE" ? resolve("in use") : reject(error));
47
+ server.once("error", failed);
48
+ server.listen(port, HOST, () => {
49
+ server.off("error", failed);
50
+ resolve("listening");
51
+ });
52
+ });
53
+ }
54
+ export async function startDashboardServer(options) {
55
+ const server = createServer(handler(options));
56
+ const attempts = options.port === 0 ? 1 : options.fallbacks + 1;
57
+ for (let offset = 0; offset < attempts; offset += 1) {
58
+ if ((await listen(server, options.port + offset)) === "listening") {
59
+ const address = server.address();
60
+ return {
61
+ port: typeof address === "object" && address !== null ? address.port : options.port + offset,
62
+ close: () => new Promise((resolve) => {
63
+ server.close(() => resolve());
64
+ server.closeAllConnections();
65
+ }),
66
+ };
67
+ }
68
+ }
69
+ throw new Error(`suwgate dashboard: the ports ${options.port} to ${options.port + options.fallbacks} are all in use: stop what holds them or pass --port <n>`);
70
+ }
@@ -0,0 +1,12 @@
1
+ import type { Catalog } from "./config.ts";
2
+ import type { DashboardInput } from "./dashboard.ts";
3
+ import type { RunRecord } from "./history.ts";
4
+ export declare const NOW: Date;
5
+ export declare function run(overrides: Partial<RunRecord>): RunRecord;
6
+ export declare const history: RunRecord[];
7
+ export declare const fakeCatalog: Catalog;
8
+ export declare function collected(overrides?: Partial<DashboardInput>): import("./dashboard.ts").DashboardData;
9
+ export declare const wiredHooks: {
10
+ read: (file: string) => string | null;
11
+ hooksPath: string;
12
+ };
@@ -0,0 +1,99 @@
1
+ import { collectDashboard } from "./dashboard.js";
2
+ export const NOW = new Date("2026-12-02T10:40:00.000Z");
3
+ export function run(overrides) {
4
+ return {
5
+ at: "2026-12-01T10:00:00.000Z",
6
+ mode: "quick",
7
+ source: "cli",
8
+ branch: "feature/x",
9
+ verdict: "green",
10
+ seconds: 5,
11
+ overBudget: false,
12
+ steps: [],
13
+ ran: ["core-guard", "quiet-guard"],
14
+ guards: {},
15
+ excepted: {},
16
+ ci: false,
17
+ ...overrides,
18
+ };
19
+ }
20
+ export const history = [
21
+ run({ at: "2026-10-20T10:00:00.000Z", seconds: 4, branch: "master" }),
22
+ run({ at: "2026-11-30T10:00:00.000Z", seconds: 6, branch: "master" }),
23
+ run({
24
+ at: "2026-12-01T10:00:00.000Z",
25
+ verdict: "red",
26
+ seconds: 7,
27
+ guards: { "repository-layout": 2 },
28
+ excepted: { "core-guard": 3 },
29
+ ran: ["core-guard", "repository-layout", "quiet-guard"],
30
+ }),
31
+ run({
32
+ at: "2026-12-02T09:00:00.000Z",
33
+ verdict: "red",
34
+ seconds: 25,
35
+ overBudget: true,
36
+ branch: "feature/y",
37
+ steps: [
38
+ { id: "lint", verdict: "pass", seconds: 3 },
39
+ { id: "unit-tests", verdict: "fail", seconds: 12 },
40
+ ],
41
+ }),
42
+ ];
43
+ const config = {
44
+ profiles: ["library"],
45
+ directories: {},
46
+ guardSets: [],
47
+ add: [],
48
+ skip: [],
49
+ configure: {},
50
+ environment: {},
51
+ skippedGuards: [{ guard: "skipped-guard", reason: "not needed here" }],
52
+ exceptions: [{ guard: "core-guard", target: "docs/a.md", reason: "the doc names files of another repository" }],
53
+ settings: {},
54
+ };
55
+ const check = () => [];
56
+ export const fakeCatalog = {
57
+ guards: [
58
+ { id: "core-guard", description: "d", profiles: "every", check },
59
+ { id: "quiet-guard", description: "d", profiles: "every", check },
60
+ { id: "repository-layout", description: "d", profiles: "every", set: "stack", check },
61
+ { id: "skipped-guard", description: "d", profiles: "every", check },
62
+ { id: "dotnet-only", description: "d", profiles: ["dotnet"], check },
63
+ ],
64
+ dotnetGuards: [],
65
+ stepsFor: () => [{ id: "lint", title: "lint (eslint)", run: "true" }],
66
+ };
67
+ function dashboardInput(overrides = {}) {
68
+ return {
69
+ name: "owner/repo",
70
+ days: 30,
71
+ now: NOW,
72
+ runs: history,
73
+ ci: { state: "off", syncedTo: null, reason: "" },
74
+ config,
75
+ catalog: fakeCatalog,
76
+ wall: [
77
+ { name: "pull request required before merging", state: "holds", detail: "" },
78
+ { name: "force pushes blocked", state: "broken", detail: 'force pushes are not blocked: enable "Block force pushes"' },
79
+ ],
80
+ wallCheckedAt: NOW,
81
+ live: false,
82
+ files: [],
83
+ read: () => null,
84
+ hooksPath: "",
85
+ criterionIds: () => [],
86
+ plugin: null,
87
+ garden: null,
88
+ ...overrides,
89
+ };
90
+ }
91
+ export function collected(overrides = {}) {
92
+ return collectDashboard(dashboardInput(overrides));
93
+ }
94
+ const WIRED = {
95
+ ".claude/settings.json": "suwgate hook guard-edit, suwgate hook guard-pr, suwgate hook stop",
96
+ ".githooks/pre-commit": "suwgate hook pre-commit",
97
+ ".githooks/pre-push": "suwgate hook pre-push",
98
+ };
99
+ export const wiredHooks = { read: (file) => WIRED[file] ?? null, hooksPath: ".githooks" };
@@ -1,8 +1,14 @@
1
1
  import { type Config } from "./config.ts";
2
2
  import type { Guard, GuardException } from "./contract.ts";
3
+ export interface GuardTally {
4
+ ran: string[];
5
+ failed: Record<string, number>;
6
+ excepted: Record<string, number>;
7
+ }
3
8
  interface GuardsSummary {
4
9
  passed: boolean;
5
10
  log: string;
11
+ tally: GuardTally;
6
12
  }
7
13
  interface GuardsInput {
8
14
  root: string;
@@ -35,6 +35,10 @@ export async function runGuards(input) {
35
35
  const lines = [];
36
36
  let excepted = 0;
37
37
  let failed = false;
38
+ const tally = { ran: input.guards.map((guard) => guard.id), failed: {}, excepted: {} };
39
+ const count = (counts, id) => {
40
+ counts[id] = (counts[id] ?? 0) + 1;
41
+ };
38
42
  for (const guard of input.guards) {
39
43
  const own = input.config.exceptions.filter((exception) => exception.guard === guard.id);
40
44
  const merged = own.filter((exception) => (input.merged ?? []).some((done) => sameException(done, exception)));
@@ -45,15 +49,18 @@ export async function runGuards(input) {
45
49
  if (exception === undefined) {
46
50
  lines.push(shown(guard, finding));
47
51
  failed = true;
52
+ count(tally.failed, guard.id);
48
53
  }
49
54
  else {
50
55
  used.add(exception);
56
+ count(tally.excepted, guard.id);
51
57
  }
52
58
  }
53
59
  excepted += used.size;
54
60
  for (const stale of exceptions.filter((exception) => !used.has(exception))) {
55
61
  lines.push(`${guard.id}: ${stale.target}: the exception in ${CONFIG_FILE}${stale.message === undefined ? "" : ` (message: ${stale.message})`} matches nothing any more: delete it`);
56
62
  failed = true;
63
+ count(tally.failed, guard.id);
57
64
  }
58
65
  for (const done of merged) {
59
66
  lines.push(`${guard.id}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
@@ -63,5 +70,5 @@ export async function runGuards(input) {
63
70
  lines.push(`${done.guard}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
64
71
  }
65
72
  const header = `${input.guards.length} guard${input.guards.length === 1 ? "" : "s"}, ${excepted} findings excepted in ${CONFIG_FILE}`;
66
- return { passed: !failed, log: [header, ...lines].join("\n") };
73
+ return { passed: !failed, log: [header, ...lines].join("\n"), tally };
67
74
  }
@@ -0,0 +1,31 @@
1
+ export declare const HISTORY_FILE = "suwgate-runs.jsonl";
2
+ export type RunMode = "quick" | "full" | "ship" | "step";
3
+ export type RunSource = "cli" | "stop" | "pre-commit";
4
+ interface StepRecord {
5
+ id: string;
6
+ verdict: "pass" | "fail" | "skip";
7
+ seconds: number;
8
+ }
9
+ export interface RunRecord {
10
+ at: string;
11
+ mode: RunMode;
12
+ source: RunSource;
13
+ branch: string;
14
+ verdict: "green" | "red";
15
+ seconds: number;
16
+ overBudget: boolean;
17
+ steps: StepRecord[];
18
+ ran: string[];
19
+ guards: Record<string, number>;
20
+ excepted: Record<string, number>;
21
+ ci: boolean;
22
+ commit?: string;
23
+ run?: string;
24
+ }
25
+ export declare function inCommonDir(root: string, file: string): string | null;
26
+ export declare function historyFile(root: string): string | null;
27
+ export declare function branchOf(root: string): string;
28
+ export declare function recordRun(root: string, record: RunRecord, maxBytes?: number): void;
29
+ export declare function readRuns(root: string): RunRecord[];
30
+ export declare function parseRuns(text: string): RunRecord[];
31
+ export {};