@maniumek/suwgate 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/AGENTS.shared.md +13 -2
  2. package/README.md +95 -9
  3. package/dist/cli.js +208 -12
  4. package/dist/eslint/index.d.ts +1 -0
  5. package/dist/eslint/index.js +20 -1
  6. package/dist/gate/breakdown.d.ts +38 -0
  7. package/dist/gate/breakdown.js +107 -0
  8. package/dist/gate/check.d.ts +3 -0
  9. package/dist/gate/check.js +37 -1
  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 +97 -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 +107 -0
  17. package/dist/gate/dashboard.js +126 -0
  18. package/dist/gate/dashboardFile.d.ts +31 -0
  19. package/dist/gate/dashboardFile.js +154 -0
  20. package/dist/gate/dashboardJson.d.ts +2 -0
  21. package/dist/gate/dashboardJson.js +25 -0
  22. package/dist/gate/dashboardPage.d.ts +3 -0
  23. package/dist/gate/dashboardPage.js +294 -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 +98 -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 +28 -0
  31. package/dist/gate/history.js +72 -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/node.d.ts +1 -0
  67. package/dist/profiles/node.js +12 -4
  68. package/dist/profiles/reports.d.ts +6 -0
  69. package/dist/profiles/reports.js +14 -0
  70. package/dist/profiles/verdict.js +45 -3
  71. package/dist/session/doctor.d.ts +26 -0
  72. package/dist/session/doctor.js +265 -0
  73. package/dist/session/gardenRecord.d.ts +12 -0
  74. package/dist/session/gardenRecord.js +58 -0
  75. package/dist/session/guardPr.js +2 -2
  76. package/dist/session/prePush.js +1 -1
  77. package/dist/session/suwagentInfo.d.ts +28 -0
  78. package/dist/session/suwagentInfo.js +103 -0
  79. package/package.json +3 -1
  80. package/schema/suwgate.schema.json +26 -0
@@ -0,0 +1,126 @@
1
+ import { branches, runsPerDay, stoppers, trends } from "./breakdown.js";
2
+ import { takesGuard } from "./config.js";
3
+ import { listSteps } from "./plan.js";
4
+ import { summarize } from "./stats.js";
5
+ const DEFAULT_SPECS_FOLDER = "docs/visual/spec";
6
+ const HOOKS = [
7
+ { id: "guard-edit", where: ".claude/settings.json" },
8
+ { id: "guard-pr", where: ".claude/settings.json" },
9
+ { id: "stop", where: ".claude/settings.json" },
10
+ { id: "pre-commit", where: "core.hooksPath" },
11
+ { id: "pre-push", where: "core.hooksPath" },
12
+ ];
13
+ const TEST_FILE = /\.(?:test|spec|e2e)\.[cm]?[jt]sx?$|Tests?\.cs$|(?:^|\/)test_[^/]*\.py$|_test\.py$/;
14
+ function testKind(file) {
15
+ if (file.includes(".e2e."))
16
+ return "e2e";
17
+ if (/\.(?:test|spec)\.[cm]?tsx?$/.test(file))
18
+ return "unit";
19
+ if (file.endsWith(".cs"))
20
+ return ".NET";
21
+ if (file.endsWith(".py"))
22
+ return "Python";
23
+ return "other";
24
+ }
25
+ function namesCriterion(text, id) {
26
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27
+ return (['"', "'", "`"].some((quote) => text.includes(`${quote}${id}:`)) ||
28
+ new RegExp(`Trait\\(\\s*"criterion"\\s*,\\s*"${escaped}"\\s*\\)`).test(text));
29
+ }
30
+ function specsFolder(read) {
31
+ try {
32
+ const parsed = JSON.parse(read("criteria.json") ?? "{}");
33
+ return typeof parsed.specs === "string" ? parsed.specs : DEFAULT_SPECS_FOLDER;
34
+ }
35
+ catch {
36
+ return DEFAULT_SPECS_FOLDER;
37
+ }
38
+ }
39
+ function criteriaOf(input) {
40
+ const folder = specsFolder(input.read);
41
+ const specs = input.files.filter((file) => file.startsWith(`${folder}/`) && file.endsWith(".html") && !file.slice(folder.length + 1).includes("/"));
42
+ if (specs.length === 0)
43
+ return null;
44
+ const tests = input.files
45
+ .filter((file) => TEST_FILE.test(file))
46
+ .flatMap((file) => {
47
+ const text = input.read(file);
48
+ return text === null ? [] : [{ file, text }];
49
+ });
50
+ return specs.flatMap((spec) => input.criterionIds(input.read(spec) ?? "").map((id) => ({
51
+ id,
52
+ spec,
53
+ tests: tests.filter((test) => namesCriterion(test.text, id)).map((test) => ({ file: test.file, kind: testKind(test.file) })),
54
+ })));
55
+ }
56
+ function guardRows(input) {
57
+ return input.catalog.guards
58
+ .filter((guard) => guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile)))
59
+ .map((guard) => {
60
+ const skipped = input.config.skippedGuards.find((entry) => entry.guard === guard.id);
61
+ const state = skipped !== undefined ? "skipped" : takesGuard(input.config, guard) ? "active" : "set not taken";
62
+ return { id: guard.id, set: guard.set ?? "core", state, skipReason: skipped?.reason ?? "" };
63
+ });
64
+ }
65
+ function latestRunOf(guard, runs) {
66
+ return runs.filter((run) => run.ran.includes(guard)).toSorted((a, b) => Date.parse(b.at) - Date.parse(a.at))[0];
67
+ }
68
+ function exceptionRows(input) {
69
+ return input.config.exceptions.map((exception) => {
70
+ const latest = latestRunOf(exception.guard, input.runs);
71
+ return {
72
+ guard: exception.guard,
73
+ target: exception.target,
74
+ reason: exception.reason,
75
+ covered: latest === undefined ? null : (latest.excepted[exception.guard] ?? 0),
76
+ sharedBy: input.config.exceptions.filter((other) => other.guard === exception.guard).length,
77
+ };
78
+ });
79
+ }
80
+ export function hookRows(read, hooksPath) {
81
+ const settings = read(".claude/settings.json") ?? "";
82
+ return HOOKS.map(({ id, where }) => {
83
+ const file = hooksPath === "" ? null : read(`${hooksPath}/${id}`);
84
+ const wired = where === "core.hooksPath" ? file?.includes(`hook ${id}`) === true : settings.includes(`hook ${id}`);
85
+ return { id, where, wired };
86
+ });
87
+ }
88
+ export function attentionOf(wall, stopped, hooks) {
89
+ return [
90
+ ...wall
91
+ .filter((check) => check.state === "broken")
92
+ .map((check) => ({ kind: "wall", text: check.name, detail: "is not in place" })),
93
+ ...stopped.map((stopper) => ({
94
+ kind: "broken",
95
+ text: `${stopper.id} stopped the gate ${stopper.runs} time${stopper.runs === 1 ? "" : "s"}`,
96
+ detail: `on ${stopper.branches.join(", ")}`,
97
+ })),
98
+ ...hooks
99
+ .filter((hook) => !hook.wired)
100
+ .map((hook) => ({ kind: "have", text: `the ${hook.id} hook is not wired`, detail: `in ${hook.where}` })),
101
+ ];
102
+ }
103
+ export function collectDashboard(input) {
104
+ const stopped = stoppers(input.runs, input.days, input.now);
105
+ return {
106
+ name: input.name,
107
+ days: input.days,
108
+ generated: input.now,
109
+ attention: attentionOf(input.wall, stopped, hookRows(input.read, input.hooksPath)),
110
+ wall: input.wall,
111
+ wallCheckedAt: input.wallCheckedAt,
112
+ live: input.live,
113
+ stats: summarize(input.runs, input.days, input.now),
114
+ trends: trends(input.runs, input.days, input.now),
115
+ perDay: runsPerDay(input.runs, input.days, input.now),
116
+ stopped,
117
+ branches: branches(input.runs, input.days, input.now),
118
+ steps: listSteps({ root: "", quick: false, config: input.config, catalog: input.catalog, files: [], changed: () => [] }),
119
+ guards: guardRows(input),
120
+ exceptions: exceptionRows(input),
121
+ hooks: hookRows(input.read, input.hooksPath),
122
+ criteria: criteriaOf(input),
123
+ plugin: input.plugin,
124
+ garden: input.garden,
125
+ };
126
+ }
@@ -0,0 +1,31 @@
1
+ import { type Catalog } from "./config.ts";
2
+ import { type GardenView, type PluginView, type WallCheck } from "./dashboard.ts";
3
+ export declare const GARDEN_FILE = "suwgate-garden.jsonl";
4
+ export interface DashboardRequest {
5
+ cwd: string;
6
+ days: number;
7
+ out: string | undefined;
8
+ now: () => Date;
9
+ catalog: Catalog;
10
+ extraFiles: readonly string[];
11
+ wall: (root: string) => Promise<readonly WallCheck[]>;
12
+ criterionIds: (spec: string) => string[];
13
+ plugin: (root: string) => PluginView | null;
14
+ garden: (file: string | null) => GardenView | null;
15
+ }
16
+ export interface LiveSources {
17
+ page: () => Promise<string>;
18
+ fingerprint: () => string;
19
+ }
20
+ export declare function dashboardAsJson(request: DashboardRequest): Promise<{
21
+ exitCode: 0 | 2;
22
+ text: string;
23
+ }>;
24
+ export declare function dashboard(request: DashboardRequest): Promise<{
25
+ exitCode: 0 | 2;
26
+ text: string;
27
+ }>;
28
+ export declare function liveSources(request: DashboardRequest): LiveSources | {
29
+ exitCode: 2;
30
+ text: string;
31
+ };
@@ -0,0 +1,154 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { CONFIG_FILE, loadConfig } from "./config.js";
5
+ import { collectDashboard } from "./dashboard.js";
6
+ import { dashboardJson } from "./dashboardJson.js";
7
+ import { renderDashboard } from "./dashboardPage.js";
8
+ import { HISTORY_FILE, inCommonDir, readRuns } from "./history.js";
9
+ import { git, repositoryFiles, repositoryRoot } from "./repository.js";
10
+ const DASHBOARD_FILE = "suwgate-dashboard.html";
11
+ const SPECS_FOLDER = "docs/visual/spec";
12
+ const WALL_TTL_MS = 5 * 60 * 1000;
13
+ export const GARDEN_FILE = "suwgate-garden.jsonl";
14
+ function repositoryName(root) {
15
+ const remote = git(root, ["remote", "get-url", "origin"])?.trim() ?? "";
16
+ const slug = /[:/]([^/:]+\/[^/:]+?)(?:\.git)?$/.exec(remote)?.[1];
17
+ return slug ?? path.basename(root);
18
+ }
19
+ function readOptional(root, file) {
20
+ try {
21
+ return readFileSync(path.join(root, file), "utf8");
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ function prepare(request) {
28
+ const root = repositoryRoot(request.cwd);
29
+ if (root === null) {
30
+ return { exitCode: 2, text: `suwgate dashboard: ${request.cwd} is not inside a git repository: run it in a checkout` };
31
+ }
32
+ const loaded = loadConfig(root, request.catalog);
33
+ if ("problems" in loaded) {
34
+ return {
35
+ exitCode: 2,
36
+ text: ["suwgate dashboard: suwgate.yml is not valid:", ...loaded.problems.map((line) => ` ${line}`)].join("\n"),
37
+ };
38
+ }
39
+ return { root, config: loaded.config };
40
+ }
41
+ function collect(request, root, config, wall, live) {
42
+ return collectDashboard({
43
+ name: repositoryName(root),
44
+ days: request.days,
45
+ now: request.now(),
46
+ runs: readRuns(root),
47
+ config,
48
+ catalog: request.catalog,
49
+ wall: wall.checks,
50
+ wallCheckedAt: wall.checkedAt,
51
+ live,
52
+ files: repositoryFiles(root),
53
+ read: (file) => readOptional(root, file),
54
+ hooksPath: git(root, ["config", "--get", "core.hooksPath"])?.trim() ?? "",
55
+ criterionIds: request.criterionIds,
56
+ plugin: request.plugin(root),
57
+ garden: request.garden(inCommonDir(root, GARDEN_FILE)),
58
+ });
59
+ }
60
+ function build(request, root, config, wall, live) {
61
+ return renderDashboard(collect(request, root, config, wall, live));
62
+ }
63
+ export async function dashboardAsJson(request) {
64
+ const prepared = prepare(request);
65
+ if ("exitCode" in prepared)
66
+ return prepared;
67
+ 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))) };
69
+ }
70
+ export async function dashboard(request) {
71
+ const prepared = prepare(request);
72
+ if ("exitCode" in prepared)
73
+ return prepared;
74
+ const { root, config } = prepared;
75
+ const wall = { checks: await request.wall(root), checkedAt: request.now() };
76
+ const html = build(request, root, config, wall, false);
77
+ const target = request.out === undefined ? inCommonDir(root, DASHBOARD_FILE) : path.resolve(request.cwd, request.out);
78
+ if (target === null)
79
+ return { exitCode: 2, text: "suwgate dashboard: no place to write the page: pass --out <path>" };
80
+ writeFileSync(target, html);
81
+ return { exitCode: 0, text: target };
82
+ }
83
+ function cachedWall(read, now) {
84
+ let current = null;
85
+ let pending = null;
86
+ const expired = () => current === null || now().getTime() - current.checkedAt.getTime() >= WALL_TTL_MS;
87
+ return {
88
+ stamp: () => (expired() ? "due" : String(current?.checkedAt.getTime())),
89
+ get: async () => {
90
+ if (current !== null && !expired())
91
+ return current;
92
+ pending ??= read()
93
+ .then((checks) => {
94
+ current = { checks, checkedAt: now() };
95
+ return current;
96
+ })
97
+ .finally(() => {
98
+ pending = null;
99
+ });
100
+ return await pending;
101
+ },
102
+ };
103
+ }
104
+ function fileStamp(file) {
105
+ try {
106
+ const found = statSync(file);
107
+ return `${file}:${found.size}:${found.mtimeMs}`;
108
+ }
109
+ catch {
110
+ return `${file}:-`;
111
+ }
112
+ }
113
+ function folderStamps(folder) {
114
+ try {
115
+ return readdirSync(folder)
116
+ .toSorted()
117
+ .map((name) => fileStamp(path.join(folder, name)));
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ }
123
+ export function liveSources(request) {
124
+ const prepared = prepare(request);
125
+ if ("exitCode" in prepared)
126
+ return prepared;
127
+ const { root } = prepared;
128
+ const wall = cachedWall(() => request.wall(root), request.now);
129
+ const watched = [
130
+ inCommonDir(root, HISTORY_FILE),
131
+ inCommonDir(root, GARDEN_FILE),
132
+ path.join(root, CONFIG_FILE),
133
+ path.join(root, ".claude", "settings.json"),
134
+ path.join(root, "criteria.json"),
135
+ ...request.extraFiles,
136
+ ];
137
+ return {
138
+ page: async () => {
139
+ const current = prepare(request);
140
+ if ("exitCode" in current)
141
+ throw new Error(current.text);
142
+ return build(request, root, current.config, await wall.get(), true);
143
+ },
144
+ fingerprint: () => createHash("sha1")
145
+ .update([
146
+ ...watched.map((file) => (file === null ? "-" : fileStamp(file))),
147
+ ...folderStamps(path.join(root, SPECS_FOLDER)),
148
+ wall.stamp(),
149
+ request.now().toISOString().slice(0, 10),
150
+ ].join("\n"))
151
+ .digest("hex")
152
+ .slice(0, 16),
153
+ };
154
+ }
@@ -0,0 +1,2 @@
1
+ import type { DashboardData } from "./dashboard.ts";
2
+ export declare function dashboardJson(data: DashboardData): Record<string, unknown>;
@@ -0,0 +1,25 @@
1
+ import { ABOUT } from "./dashboardPage.js";
2
+ const SCHEMA_VERSION = 1;
3
+ export function dashboardJson(data) {
4
+ const { quiet, ...stats } = data.stats;
5
+ return {
6
+ schemaVersion: SCHEMA_VERSION,
7
+ repository: data.name,
8
+ days: data.days,
9
+ generated: data.generated.toISOString(),
10
+ attention: data.attention.map((item) => ({ kind: item.kind, text: item.text, detail: item.detail, part: item.kind })),
11
+ wall: { checkedAt: data.wallCheckedAt.toISOString(), checks: data.wall },
12
+ runs: { ...stats, trends: data.trends, perDay: data.perDay },
13
+ stopped: data.stopped,
14
+ branches: data.branches,
15
+ steps: data.steps,
16
+ guards: data.guards,
17
+ exceptions: data.exceptions,
18
+ hooks: data.hooks,
19
+ quietGuards: quiet,
20
+ criteria: data.criteria,
21
+ plugin: data.plugin,
22
+ garden: data.garden,
23
+ about: ABOUT,
24
+ };
25
+ }
@@ -0,0 +1,3 @@
1
+ import type { DashboardData } from "./dashboard.ts";
2
+ export declare const ABOUT: Record<string, string>;
3
+ export declare function renderDashboard(data: DashboardData): string;
@@ -0,0 +1,294 @@
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, 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, 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 brokenPart(data) {
165
+ if (data.stats.runs === 0)
166
+ return part("broken", 3, "Broken", "no runs recorded", noRuns(data.days));
167
+ if (data.stopped.length === 0)
168
+ return part("broken", 3, "Broken", "nothing stopped the gate", sentence("No guard or step stopped the gate in this period."));
169
+ const guards = data.stopped.filter((stopper) => stopper.kind === "guard").length;
170
+ const steps = data.stopped.length - guards;
171
+ const conclusion = [guards > 0 ? plural(guards, "guard") : "", steps > 0 ? plural(steps, "step") : ""]
172
+ .filter((text) => text !== "")
173
+ .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(", ")}`));
175
+ return part("broken", 3, "Broken", `${conclusion}, last ${day(data.stopped[0]?.last ?? "")}`, list(rows, "items"));
176
+ }
177
+ function branchesPart(data) {
178
+ if (data.stats.runs === 0)
179
+ return part("branches", 4, "Branches", "no runs recorded", noRuns(data.days));
180
+ const red = data.branches.filter((branch) => branch.red > 0).length;
181
+ const conclusion = `${plural(data.branches.length, "branch", "branches")}, ${red} with red runs`;
182
+ const rows = data.branches.map((branch) => row(escapeHtml(branch.branch), [
183
+ plural(branch.runs, "run"),
184
+ `${branch.red} red`,
185
+ branch.lastRed === null ? "-" : `last red ${escapeHtml(day(branch.lastRed.at))}`,
186
+ ], branch.lastRed === null ? "" : `last red: ${escapeHtml(branch.lastRed.cause)}`));
187
+ return part("branches", 4, "Branches", conclusion, list(rows, "branches"));
188
+ }
189
+ function havePart(data) {
190
+ const active = data.guards.filter((guard) => guard.state === "active").length;
191
+ const wired = data.hooks.filter((hook) => hook.wired).length;
192
+ const guardCount = active === data.guards.length ? plural(active, "guard") : `${active} of ${plural(data.guards.length, "guard")} active`;
193
+ const hookCount = wired === data.hooks.length ? plural(wired, "hook") : `${wired} of ${plural(data.hooks.length, "hook")} wired`;
194
+ const conclusion = `${guardCount} · ${plural(data.exceptions.length, "exception")} · ${hookCount}`;
195
+ const steps = data.steps.map((step) => row(escapeHtml(step.id), [step.skipped === undefined ? "" : "skipped"], escapeHtml(step.skipped === undefined ? step.title : `${step.title}: ${step.skipped}`)));
196
+ const guards = data.guards.map((guard) => row(escapeHtml(guard.id), [escapeHtml(guard.set), escapeHtml(guard.state)], guard.skipReason === "" ? "" : escapeHtml(guard.skipReason)));
197
+ const exceptions = data.exceptions.map((exception) => row(`${escapeHtml(exception.guard)} <span class="note">${escapeHtml(exception.target)}</span>`, [
198
+ exception.covered === null
199
+ ? "no run yet"
200
+ : `${plural(exception.covered, "finding")} in the latest run${exception.sharedBy > 1 ? " of the guard" : ""}`,
201
+ ], escapeHtml(exception.reason)));
202
+ const hooks = data.hooks.map((hook) => row(escapeHtml(hook.id), [escapeHtml(hook.where), hook.wired ? mark("holds", "wired") : mark("broken", "not wired")]));
203
+ const quiet = data.stats.runs === 0
204
+ ? ""
205
+ : `<h3>Guards with no finding in ${data.days} days</h3>${data.stats.quiet.length === 0
206
+ ? sentence("None.")
207
+ : list(data.stats.quiet.map((id) => row(escapeHtml(id))), "guards")}`;
208
+ 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}`);
209
+ }
210
+ function criteriaPart(data) {
211
+ if (data.criteria === null)
212
+ return part("criteria", 6, "Criteria", "no specs", sentence("No specification in the specs folder."));
213
+ const unnamed = data.criteria.filter((criterion) => criterion.tests.length === 0).length;
214
+ const conclusion = `${plural(data.criteria.length, "criterion", "criteria")} · ${unnamed === 0 ? "all with a test" : `${unnamed} without a test`}`;
215
+ 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>")));
216
+ return part("criteria", 6, "Criteria", conclusion, list(rows, "criteria"));
217
+ }
218
+ function suwagentPart(data) {
219
+ const { plugin } = data;
220
+ if (plugin === null)
221
+ return part("suwagent", 7, "Suwagent", "not installed here", sentence("The suwagent plugin is not installed here."));
222
+ const conclusion = `version ${plugin.version} · ${plural(plugin.skills.length, "skill")} · ${plural(plugin.hooks.length, "hook")} · ${plural(plugin.agents.length, "agent")}`;
223
+ const skills = plugin.skills.map((skill) => row(escapeHtml(skill.name), [skill.onlyWhenAsked ? "only when you ask" : "the agent may start it"], escapeHtml(skill.summary)));
224
+ const hooks = plugin.hooks.map((hook) => row(escapeHtml(hook.script), [escapeHtml(hook.event), escapeHtml(hook.matcher)]));
225
+ const agents = plugin.agents.map((agent) => row(escapeHtml(agent.name), [escapeHtml(agent.tools)], escapeHtml(agent.description)));
226
+ const hookNote = plugin.hookDescription === "" ? "" : sentence(plugin.hookDescription);
227
+ 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")}`);
228
+ }
229
+ function cleaningPart(data) {
230
+ if (data.garden === null)
231
+ return part("cleaning", 8, "Cleaning", "has not run here yet", sentence("The cleaning has not run here yet."));
232
+ const kinds = Object.entries(data.garden.found);
233
+ const total = kinds.reduce((sum, [, count]) => sum + count, 0);
234
+ const rows = kinds.map(([kind, count]) => row(escapeHtml(kind), [String(count)]));
235
+ 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")}`);
236
+ }
237
+ const LIVE_SCRIPT = `
238
+ (function () {
239
+ var last = document.body.dataset.version;
240
+ function openKeys(root) {
241
+ return Array.prototype.filter.call(root.querySelectorAll("details"), function (d) { return d.open; }).map(function (d) {
242
+ return d.id ? "#" + d.id : "[data-key='" + d.dataset.key + "']";
243
+ });
244
+ }
245
+ function refresh(text) {
246
+ var root = document.getElementById("live-root");
247
+ var fresh = new DOMParser().parseFromString(text, "text/html").getElementById("live-root");
248
+ if (!root || !fresh) { return; }
249
+ var keys = openKeys(root);
250
+ var y = window.scrollY;
251
+ root.innerHTML = fresh.innerHTML;
252
+ keys.forEach(function (key) { var d = root.querySelector(key); if (d) { d.open = true; } });
253
+ window.scrollTo(0, y);
254
+ }
255
+ function say(text) { var note = document.getElementById("live-note"); if (note) { note.textContent = text; } }
256
+ function ok(response) { if (!response.ok) { throw new Error("status"); } return response.text(); }
257
+ function tick() {
258
+ fetch("/version", { cache: "no-store" }).then(ok).then(function (version) {
259
+ if (version === last) { say(""); return; }
260
+ return fetch("/", { cache: "no-store" }).then(ok).then(function (text) { refresh(text); last = version; say(""); });
261
+ }).catch(function () { say("not live: the server stopped"); });
262
+ }
263
+ setInterval(tick, 3000);
264
+ })();
265
+ `;
266
+ export function renderDashboard(data) {
267
+ const title = `suwgate · ${data.name}`;
268
+ return `<!doctype html>
269
+ <html lang="en">
270
+ <head>
271
+ <meta charset="utf-8">
272
+ <meta name="viewport" content="width=device-width, initial-scale=1">
273
+ <meta name="color-scheme" content="light dark">
274
+ <title>${escapeHtml(title)}</title>
275
+ <style>${STYLE}</style>
276
+ </head>
277
+ <body data-version="">
278
+ <main id="live-root">
279
+ <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>
281
+ ${attention(data)}
282
+ ${wallPart(data)}
283
+ ${runsPart(data)}
284
+ ${brokenPart(data)}
285
+ ${branchesPart(data)}
286
+ ${havePart(data)}
287
+ ${criteriaPart(data)}
288
+ ${suwagentPart(data)}
289
+ ${cleaningPart(data)}
290
+ </main>
291
+ ${data.live ? `<script>${LIVE_SCRIPT}</script>\n` : ""}</body>
292
+ </html>
293
+ `;
294
+ }
@@ -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>;