@maniumek/suwgate 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -246,6 +246,26 @@ public sealed class GuardTests
246
246
  the solution, `layers.json`, the sources and the migrations itself, and takes from the test only what it cannot find
247
247
  ([dotnet/Suwgate.Architecture/README.md](dotnet/Suwgate.Architecture/README.md) lists the inputs).
248
248
 
249
+ ### The tests and the docs for people
250
+
251
+ - `test-timing` (`dotnet`, `web`, `library`): no test measures, sleeps on, waits for or limits real time, because a test that
252
+ waits on the clock flakes on a slow machine and a speed promise, in milliseconds or in steps counted instead of them, does not
253
+ belong on the gate. It reads the `.cs` files of the `*.Tests` and `*.Testing` projects (`Stopwatch`, `GetTimestamp`,
254
+ `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute),
255
+ and the `*.test`, `*.spec`, `*.e2e`, `*.visual`
256
+ and `*.stories` files and the helpers of an `e2e/` folder (`performance.now`, `Date.now()` in a subtraction, `setTimeout`,
257
+ `sleep(<n>)`, `waitForTimeout`, `interruptAfterTimeLimit`, and `timeout: <n>` in a Vitest file). It lets through a call that is
258
+ handed a `TimeProvider` (a `FakeTimeProvider` in the tests), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
259
+ or with `Timeout.Infinite`, the timers and the clock of a file that calls `vi.useFakeTimers()`, Playwright's auto-waiting
260
+ `expect` with its own `timeout`, a ceiling against a hang (`CancelAfter`, `new CancellationTokenSource(<delay>)`,
261
+ `WaitAsync(<TimeSpan>)`: the test waits for an event and fails fast, with its name, if it never comes), and the tools' configs
262
+ (`playwright.config.ts`), whose ceilings stop a hang.
263
+ - `human-docs` (every profile): `README.md`, `docs/development.md` and the README of a profile's directory never tell a person to
264
+ run a script meant for agents, one in `scripts/.internal/` or `<name>.Gate/scripts/`; people run `just` recipes. A command is a
265
+ line of a shell code block or an inline code span with a space in it, and a span in parentheses or right after "runs", "calls",
266
+ "starts", "through" or "via" explains what runs the script, so it passes. The message names the recipe that calls the script, or
267
+ asks for one.
268
+
249
269
  ### What the gate proves ran
250
270
 
251
271
  A check counts only when the tool shows it ran, not because a file or a line of text is there:
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const humanDocs: Guard;
@@ -0,0 +1,87 @@
1
+ import { moduleName } from "./justModules.js";
2
+ import { baseName, inProfileDirectory, numberedLines } from "./text.js";
3
+ const AGENT_SCRIPT = /(^|\/)\.internal\/|^[^/]+\.Gate\/scripts\//;
4
+ const AGENT_PATH = /\.internal\/|\.Gate\/scripts\//;
5
+ const FENCE = /^\s*(```|~~~)\s*([\w-]*)/;
6
+ const SHELL_FENCE = new Set(["", "sh", "bash", "zsh", "shell", "console", "shell-session", "powershell", "pwsh", "ps1", "cmd"]);
7
+ const CODE_SPAN = /(`+)(.+?)\1/g;
8
+ const DESCRIBED = /(\(|\b(runs|calls|starts|through|via)\s+)$/;
9
+ const VARIABLE = /^(?:export\s+)?([A-Za-z_][\w-]*)\s*:=/;
10
+ const RECIPE = /^@?([A-Za-z_][\w-]*)(?:\s[^:]*)?:(?!=)/;
11
+ function documentsOf(context) {
12
+ const folders = context.profiles.flatMap((profile) => context.directories[profile] === undefined ? [] : [inProfileDirectory(context.directories, profile, "README.md")]);
13
+ return [...new Set(["README.md", "docs/development.md", ...folders])].filter((file) => context.files.includes(file));
14
+ }
15
+ function commandsOf(text) {
16
+ const commands = [];
17
+ let fence;
18
+ for (const { line, text: content } of numberedLines(text)) {
19
+ const marker = FENCE.exec(content);
20
+ if (marker !== null) {
21
+ fence = fence === undefined ? (marker[2] ?? "") : undefined;
22
+ }
23
+ else if (fence !== undefined) {
24
+ if (SHELL_FENCE.has(fence) && content.trim() !== "")
25
+ commands.push({ line, text: content.trim() });
26
+ }
27
+ else {
28
+ for (const span of content.matchAll(CODE_SPAN)) {
29
+ const code = (span[2] ?? "").trim();
30
+ if (/\s/.test(code) && !DESCRIBED.test(content.slice(0, span.index)))
31
+ commands.push({ line, text: code });
32
+ }
33
+ }
34
+ }
35
+ return commands;
36
+ }
37
+ function scriptIn(command, agentNames) {
38
+ return command
39
+ .split(/\s+/)
40
+ .map((token) => token.replace(/^["'(]+|["'),;]+$/g, "").replace(/^\.\//, ""))
41
+ .find((token) => AGENT_PATH.test(token) || agentNames.has(token));
42
+ }
43
+ function recipesCalling(context, script) {
44
+ const name = baseName(script);
45
+ return context.files
46
+ .filter((file) => file === "justfile" || file.endsWith(".just"))
47
+ .flatMap((file) => {
48
+ const prefix = file === "justfile" ? "" : `${moduleName(file)} `;
49
+ const lines = numberedLines(context.read(file)).map((line) => line.text);
50
+ const variables = lines.flatMap((text) => {
51
+ const variable = VARIABLE.exec(text);
52
+ return variable?.[1] !== undefined && text.includes(name) ? [variable[1]] : [];
53
+ });
54
+ const calls = (text) => text.includes(name) || variables.some((variable) => new RegExp(`\\{\\{\\s*${variable}\\s*\\}\\}`).test(text));
55
+ let recipe;
56
+ const found = [];
57
+ for (const text of lines) {
58
+ const header = /^\s/.test(text) ? null : RECIPE.exec(text);
59
+ if (header !== null)
60
+ recipe = header[1];
61
+ else if (!/^\s/.test(text) && text.trim() !== "")
62
+ recipe = undefined;
63
+ else if (recipe !== undefined && calls(text))
64
+ found.push(`just ${prefix}${recipe}`);
65
+ }
66
+ return found;
67
+ })
68
+ .filter((recipe, index, all) => all.indexOf(recipe) === index);
69
+ }
70
+ function message(context, script) {
71
+ const recipes = recipesCalling(context, script);
72
+ return recipes.length === 0
73
+ ? `a person runs a just recipe, never ${script}, a script for agents: add a recipe that calls it to the justfile and name the recipe here (a doc may still name it to explain what runs it: in parentheses or after runs, calls or starts)`
74
+ : `a person runs a just recipe, never ${script}, a script for agents: name \`${recipes.join("` or `")}\` instead (a doc may still name it to explain what runs it: in parentheses or after runs, calls or starts)`;
75
+ }
76
+ export const humanDocs = {
77
+ id: "human-docs",
78
+ description: "The docs for people (README.md, docs/development.md and the README of a profile's directory) never tell a person to run a script meant for agents (scripts/.internal/, <name>.Gate/scripts/): people run just recipes",
79
+ profiles: "every",
80
+ check(context) {
81
+ const agentNames = new Set(context.files.filter((file) => AGENT_SCRIPT.test(file)).map(baseName));
82
+ return documentsOf(context).flatMap((document) => commandsOf(context.read(document)).flatMap(({ line, text }) => {
83
+ const script = scriptIn(text, agentNames);
84
+ return script === undefined ? [] : [{ target: document, line, message: message(context, script) }];
85
+ }));
86
+ },
87
+ };
@@ -6,6 +6,7 @@ import { dependencyDirection } from "./dependencyDirection.js";
6
6
  import { docsPaths } from "./docsPaths.js";
7
7
  import { forbiddenNames } from "./forbiddenNames.js";
8
8
  import { hooks } from "./hooks.js";
9
+ import { humanDocs } from "./humanDocs.js";
9
10
  import { imagePins } from "./imagePins.js";
10
11
  import { justModules } from "./justModules.js";
11
12
  import { noRawColors } from "./noRawColors.js";
@@ -14,6 +15,7 @@ import { requiredFiles } from "./requiredFiles.js";
14
15
  import { scriptsCalled } from "./scriptsCalled.js";
15
16
  import { scriptsHelp } from "./scriptsHelp.js";
16
17
  import { suwfrontkitWiring } from "./suwfrontkitWiring.js";
18
+ import { testTiming } from "./testTiming.js";
17
19
  import { vsCodeSettings } from "./vsCodeSettings.js";
18
20
  export const repositoryGuards = [
19
21
  requiredFiles,
@@ -33,4 +35,6 @@ export const repositoryGuards = [
33
35
  dependencyDirection,
34
36
  hooks,
35
37
  suwfrontkitWiring,
38
+ testTiming,
39
+ humanDocs,
36
40
  ];
@@ -1,2 +1,3 @@
1
1
  import type { Guard } from "../../gate/contract.ts";
2
+ export declare function moduleName(file: string): string;
2
3
  export declare const justModules: Guard;
@@ -1,7 +1,7 @@
1
1
  import { baseName } from "./text.js";
2
2
  const MOD_LINE = /^mod\??\s+([\w-]+)(?:\s+(['"])([^'"]+)\2)?\s*$/gm;
3
3
  const SOURCES_IN_A_FOLDER = ["mod.just", "justfile", ".justfile"];
4
- function moduleName(file) {
4
+ export function moduleName(file) {
5
5
  return file.endsWith("/mod.just") ? (file.split("/")[0] ?? "") : baseName(file).replace(/\.just$/, "");
6
6
  }
7
7
  function normalized(file) {
@@ -0,0 +1,2 @@
1
+ import type { Guard } from "../../gate/contract.ts";
2
+ export declare const testTiming: Guard;
@@ -0,0 +1,198 @@
1
+ import { lineAt, numberedLines } from "./text.js";
2
+ const FIX = "a test never measures, waits on or limits real time, so it neither flakes on a slow machine nor promises speed: to prove a retry or a timeout, give the code a TimeProvider and advance a FakeTimeProvider (in Vitest, vi.useFakeTimers() and vi.advanceTimersByTime()); to see that something happened, await the event (a task, a signal, Playwright's auto-waiting expect, a later event that must come after it); a speed promise, in milliseconds or in steps counted instead of them, does not belong on the gate, so drop it and its criterion";
3
+ const CSHARP_TEST = /(^|\/)[^/]+\.Test(s|ing)\/.+\.cs$/;
4
+ const WEB_TEST = /\.(test|spec|e2e|visual|stories)\.[cm]?[jt]sx?$/;
5
+ const E2E_HELPER = /(^|\/)e2e\/.+\.[cm]?[jt]sx?$/;
6
+ const TOOL_CONFIG = /\.config\.[cm]?[jt]s$/;
7
+ const VITEST_TEST = /\.test\.[cm]?[jt]sx?$/;
8
+ const FAKE_TIMERS = /\buseFakeTimers\s*\(/;
9
+ const MEASURES = "measures real time";
10
+ const READS_CLOCK = "reads the real clock";
11
+ const WAITS = "waits on real time";
12
+ const LIMITS = "limits the test in real time";
13
+ const CSHARP_RULES = [
14
+ { pattern: /\b(?<found>Stopwatch|GetElapsedTime|GetTimestamp|TickCount64|TickCount)\b/dg, verb: MEASURES },
15
+ { pattern: /\b(?<found>(DateTime|DateTimeOffset)\.(Now|UtcNow|Today))\b/dg, verb: READS_CLOCK },
16
+ { pattern: /\b(?<found>Thread\.Sleep)\b/dg, verb: "sleeps on real time" },
17
+ { pattern: /\[[^[\]]*?\b(?<found>Timeout\s*=)(?!=)/dg, verb: LIMITS },
18
+ ];
19
+ const onFakeClock = (call) => call.args.slice(1).some((arg) => /provider|clock/i.test(arg));
20
+ const CSHARP_CALLS = [
21
+ {
22
+ pattern: /\bTask\.Delay\s*\(/g,
23
+ verb: `${WAITS} outside a polling loop`,
24
+ allowed: (call) => onFakeClock(call) || /^Timeout\.Infinite(TimeSpan)?$/.test(call.args[0] ?? "") || insideLoop(call.text, call.at),
25
+ },
26
+ ];
27
+ const WEB_RULES = [
28
+ { name: "performance.now", pattern: /\bperformance\.now\b/, verb: MEASURES, faked: true },
29
+ { name: "Date.now()", pattern: /\bDate\.now\(\)\s*-|-\s*Date\.now\(\)/, verb: MEASURES, faked: true },
30
+ { name: "setTimeout", pattern: /\bsetTimeout\s*\(/, verb: "waits on or limits real time", faked: true },
31
+ { name: "sleep or delay", pattern: /\b(sleep|delay)\(\s*\d/, verb: WAITS, faked: true },
32
+ { name: "waitForTimeout", pattern: /\bwaitForTimeout\b/, verb: WAITS },
33
+ { name: "interruptAfterTimeLimit", pattern: /\binterruptAfterTimeLimit\b/, verb: LIMITS },
34
+ { name: "timeout:", pattern: /\btimeout\s*:\s*[1-9]/, verb: LIMITS, vitestOnly: true },
35
+ ];
36
+ function blank(text) {
37
+ return text.replace(/[^\n]/g, " ");
38
+ }
39
+ function quoteRun(text, at) {
40
+ let end = at;
41
+ while (text[end] === '"')
42
+ end++;
43
+ return end - at;
44
+ }
45
+ function literalEnd(text, at) {
46
+ const quotes = quoteRun(text, at);
47
+ if (quotes >= 3) {
48
+ let end = at + quotes;
49
+ while (end < text.length && !(text[end] === '"' && quoteRun(text, end) >= quotes))
50
+ end++;
51
+ return Math.min(text.length, end + quotes);
52
+ }
53
+ if (quotes === 2)
54
+ return at + 2;
55
+ const verbatim = /@\$?$|\$@$/.test(text.slice(Math.max(0, at - 2), at));
56
+ let end = at + 1;
57
+ while (end < text.length) {
58
+ const sign = text[end];
59
+ if (sign === "\\" && !verbatim)
60
+ end += 2;
61
+ else if (sign === '"' && verbatim && text[end + 1] === '"')
62
+ end += 2;
63
+ else if (sign === '"' || (sign === "\n" && !verbatim))
64
+ return end + 1;
65
+ else
66
+ end++;
67
+ }
68
+ return text.length;
69
+ }
70
+ function charEnd(text, at) {
71
+ const close = text.indexOf("'", text[at + 1] === "\\" ? at + 3 : at + 2);
72
+ return close === -1 || close - at > 10 ? at + 1 : close + 1;
73
+ }
74
+ function endOfSkipped(text, at) {
75
+ const sign = text.charAt(at);
76
+ const next = text.charAt(at + 1);
77
+ if (sign === "/" && next === "/")
78
+ return text.includes("\n", at) ? text.indexOf("\n", at) : text.length;
79
+ if (sign === "/" && next === "*")
80
+ return text.includes("*/", at + 2) ? text.indexOf("*/", at + 2) + 2 : text.length;
81
+ if (sign === '"')
82
+ return literalEnd(text, at);
83
+ return sign === "'" ? charEnd(text, at) : undefined;
84
+ }
85
+ function codeOnly(text) {
86
+ let kept = "";
87
+ let at = 0;
88
+ while (at < text.length) {
89
+ const end = endOfSkipped(text, at);
90
+ kept += end === undefined ? text.charAt(at) : blank(text.slice(at, end));
91
+ at = end ?? at + 1;
92
+ }
93
+ return kept;
94
+ }
95
+ function matchingBackwards(text, close, open, closing) {
96
+ let depth = 0;
97
+ for (let at = close; at >= 0; at--) {
98
+ if (text[at] === closing)
99
+ depth++;
100
+ else if (text[at] === open && --depth === 0)
101
+ return at;
102
+ }
103
+ return -1;
104
+ }
105
+ function isLoopHeader(header, text, end) {
106
+ if (/\bdo$/.test(header))
107
+ return true;
108
+ if (!header.endsWith(")"))
109
+ return false;
110
+ const open = matchingBackwards(text, end, "(", ")");
111
+ return open > 0 && /\b(while|for|foreach)\s*$/.test(text.slice(0, open));
112
+ }
113
+ function statementStart(text, at) {
114
+ let depth = 0;
115
+ for (let position = at - 1; position >= 0; position--) {
116
+ const sign = text.charAt(position);
117
+ if (sign === ")")
118
+ depth++;
119
+ else if (sign === "(")
120
+ depth--;
121
+ else if (depth === 0 && (sign === ";" || sign === "{" || sign === "}"))
122
+ return position + 1;
123
+ }
124
+ return 0;
125
+ }
126
+ function insideLoop(text, at) {
127
+ if (/^\s*(while|for|foreach)\s*\(/.test(text.slice(statementStart(text, at), at)))
128
+ return true;
129
+ let depth = 0;
130
+ for (let position = at - 1; position >= 0; position--) {
131
+ if (text[position] === "}")
132
+ depth++;
133
+ else if (text[position] === "{" && depth > 0)
134
+ depth--;
135
+ else if (text[position] === "{") {
136
+ const header = text.slice(0, position).trimEnd();
137
+ if (isLoopHeader(header, text, header.length - 1))
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ function argumentsOf(text, open) {
144
+ const args = [];
145
+ let depth = 0;
146
+ let start = open + 1;
147
+ for (let at = open; at < text.length; at++) {
148
+ const sign = text[at];
149
+ if (sign === "(" || sign === "[" || sign === "{")
150
+ depth++;
151
+ else if (sign === ")" || sign === "]" || sign === "}")
152
+ depth--;
153
+ if ((depth === 1 && sign === ",") || depth === 0) {
154
+ args.push(text.slice(start, at).trim());
155
+ start = at + 1;
156
+ }
157
+ if (depth === 0)
158
+ break;
159
+ }
160
+ return args.filter((arg) => arg !== "");
161
+ }
162
+ function finding(file, line, found, verb) {
163
+ return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${FIX}` };
164
+ }
165
+ function csharpFindings(file, source) {
166
+ const text = codeOnly(source);
167
+ const plain = CSHARP_RULES.flatMap((rule) => [...text.matchAll(rule.pattern)].flatMap((match) => {
168
+ const found = match.indices?.groups?.["found"];
169
+ return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb)];
170
+ }));
171
+ const calls = CSHARP_CALLS.flatMap((rule) => [...text.matchAll(rule.pattern)]
172
+ .filter((match) => !rule.allowed({ text, at: match.index, args: argumentsOf(text, match.index + match[0].length - 1) }))
173
+ .map((match) => finding(file, lineAt(text, match.index), match[0].replace(/^\.|\s*\($/g, ""), rule.verb)));
174
+ return [...plain, ...calls].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
175
+ }
176
+ function webFindings(file, source) {
177
+ const faked = FAKE_TIMERS.test(source);
178
+ const rules = WEB_RULES.filter((rule) => !(faked && rule.faked) && (VITEST_TEST.test(file) || rule.vitestOnly !== true));
179
+ return numberedLines(source).flatMap(({ line, text }) => rules.flatMap((rule) => {
180
+ const match = rule.pattern.exec(text);
181
+ return match === null ? [] : [finding(file, line, rule.name, rule.verb)];
182
+ }));
183
+ }
184
+ function isWebTest(file) {
185
+ return !file.includes("node_modules/") && !TOOL_CONFIG.test(file) && (WEB_TEST.test(file) || E2E_HELPER.test(file));
186
+ }
187
+ export const testTiming = {
188
+ id: "test-timing",
189
+ description: "No test measures, sleeps on, waits for or limits real time (the .cs files of *.Tests and *.Testing projects; *.test, *.spec, *.e2e, *.visual and *.stories files and e2e/ helpers): tests drive a fake clock",
190
+ profiles: ["dotnet", "web", "library"],
191
+ check(context) {
192
+ return context.files.flatMap((file) => {
193
+ if (CSHARP_TEST.test(file))
194
+ return csharpFindings(file, context.read(file));
195
+ return isWebTest(file) ? webFindings(file, context.read(file)) : [];
196
+ });
197
+ },
198
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",