@warlock.js/grimoire 5.63.1 → 5.64.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 (194) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/book/build.d.mts.map +1 -1
  3. package/esm/book/build.mjs +24 -2
  4. package/esm/book/build.mjs.map +1 -1
  5. package/esm/check/check-grimoire.d.mts.map +1 -1
  6. package/esm/check/check-grimoire.mjs +11 -1
  7. package/esm/check/check-grimoire.mjs.map +1 -1
  8. package/esm/check/rules/api-snapshot.mjs +39 -0
  9. package/esm/check/rules/api-snapshot.mjs.map +1 -0
  10. package/esm/check/rules/code-rules.mjs +45 -0
  11. package/esm/check/rules/code-rules.mjs.map +1 -0
  12. package/esm/check/rules/drift.mjs +54 -0
  13. package/esm/check/rules/drift.mjs.map +1 -0
  14. package/esm/check/rules/focused-tests.mjs +39 -0
  15. package/esm/check/rules/focused-tests.mjs.map +1 -0
  16. package/esm/check/rules/shows.mjs +52 -0
  17. package/esm/check/rules/shows.mjs.map +1 -0
  18. package/esm/codes/codes.d.mts +48 -0
  19. package/esm/codes/codes.d.mts.map +1 -1
  20. package/esm/codes/codes.mjs +26 -1
  21. package/esm/codes/codes.mjs.map +1 -1
  22. package/esm/contracts/adapter.d.mts +6 -0
  23. package/esm/contracts/adapter.d.mts.map +1 -1
  24. package/esm/contracts/guard.d.mts +104 -0
  25. package/esm/contracts/guard.d.mts.map +1 -0
  26. package/esm/contracts/index.mjs +5 -0
  27. package/esm/contracts/matrix.d.mts +75 -0
  28. package/esm/contracts/matrix.d.mts.map +1 -0
  29. package/esm/contracts/scry.d.mts +21 -0
  30. package/esm/contracts/scry.d.mts.map +1 -1
  31. package/esm/contracts/settings.d.mts +71 -0
  32. package/esm/contracts/settings.d.mts.map +1 -0
  33. package/esm/contracts/settings.mjs +67 -0
  34. package/esm/contracts/settings.mjs.map +1 -0
  35. package/esm/contracts/shots.d.mts +146 -0
  36. package/esm/contracts/shots.d.mts.map +1 -0
  37. package/esm/contracts/snapshot.d.mts +10 -0
  38. package/esm/contracts/snapshot.d.mts.map +1 -1
  39. package/esm/contracts/written.d.mts +13 -0
  40. package/esm/contracts/written.d.mts.map +1 -1
  41. package/esm/contracts/written.mjs +7 -1
  42. package/esm/contracts/written.mjs.map +1 -1
  43. package/esm/devtools/approvals.mjs +59 -0
  44. package/esm/devtools/approvals.mjs.map +1 -0
  45. package/esm/devtools/data.mjs +2 -0
  46. package/esm/devtools/data.mjs.map +1 -1
  47. package/esm/devtools/graphs.mjs +13 -3
  48. package/esm/devtools/graphs.mjs.map +1 -1
  49. package/esm/devtools/index.d.mts.map +1 -1
  50. package/esm/devtools/index.mjs +32 -2
  51. package/esm/devtools/index.mjs.map +1 -1
  52. package/esm/devtools/matrix.mjs +207 -0
  53. package/esm/devtools/matrix.mjs.map +1 -0
  54. package/esm/devtools/product-map.d.mts.map +1 -1
  55. package/esm/devtools/product-map.mjs +87 -1
  56. package/esm/devtools/product-map.mjs.map +1 -1
  57. package/esm/devtools/site.d.mts.map +1 -1
  58. package/esm/devtools/site.mjs +12 -3
  59. package/esm/devtools/site.mjs.map +1 -1
  60. package/esm/devtools/snapshot-source.mjs +5 -1
  61. package/esm/devtools/snapshot-source.mjs.map +1 -1
  62. package/esm/git/index.d.mts +20 -0
  63. package/esm/git/index.d.mts.map +1 -0
  64. package/esm/git/index.mjs +280 -0
  65. package/esm/git/index.mjs.map +1 -0
  66. package/esm/guard/api.mjs +70 -0
  67. package/esm/guard/api.mjs.map +1 -0
  68. package/esm/guard/assertions.mjs +18 -0
  69. package/esm/guard/assertions.mjs.map +1 -0
  70. package/esm/guard/collect.mjs +139 -0
  71. package/esm/guard/collect.mjs.map +1 -0
  72. package/esm/guard/format.mjs +27 -0
  73. package/esm/guard/format.mjs.map +1 -0
  74. package/esm/guard/glob.mjs +79 -0
  75. package/esm/guard/glob.mjs.map +1 -0
  76. package/esm/guard/index.mjs +9 -0
  77. package/esm/guard/rules.mjs +310 -0
  78. package/esm/guard/rules.mjs.map +1 -0
  79. package/esm/guard/scope.mjs +95 -0
  80. package/esm/guard/scope.mjs.map +1 -0
  81. package/esm/index.d.mts +10 -3
  82. package/esm/index.mjs +6 -2
  83. package/esm/paths/index.d.mts +15 -1
  84. package/esm/paths/index.d.mts.map +1 -1
  85. package/esm/paths/index.mjs +27 -3
  86. package/esm/paths/index.mjs.map +1 -1
  87. package/esm/proves/index.mjs +2 -1
  88. package/esm/proves/scan-proofs.mjs +1 -1
  89. package/esm/proves/scan-proofs.mjs.map +1 -1
  90. package/esm/proves/scan-shows.d.mts +21 -0
  91. package/esm/proves/scan-shows.d.mts.map +1 -0
  92. package/esm/proves/scan-shows.mjs +168 -0
  93. package/esm/proves/scan-shows.mjs.map +1 -0
  94. package/esm/releases/index.d.mts.map +1 -1
  95. package/esm/releases/index.mjs +5 -3
  96. package/esm/releases/index.mjs.map +1 -1
  97. package/esm/releases/stamp.mjs +121 -0
  98. package/esm/releases/stamp.mjs.map +1 -0
  99. package/esm/rules/focused.mjs +26 -0
  100. package/esm/rules/focused.mjs.map +1 -0
  101. package/esm/rules/index.mjs +88 -0
  102. package/esm/rules/index.mjs.map +1 -0
  103. package/esm/rules/logical-css.mjs +112 -0
  104. package/esm/rules/logical-css.mjs.map +1 -0
  105. package/esm/rules/no-js-imports.mjs +22 -0
  106. package/esm/rules/no-js-imports.mjs.map +1 -0
  107. package/esm/rules/scan.mjs +196 -0
  108. package/esm/rules/scan.mjs.map +1 -0
  109. package/esm/rules/specific-errors.mjs +51 -0
  110. package/esm/rules/specific-errors.mjs.map +1 -0
  111. package/esm/rules/type-discriminator.mjs +27 -0
  112. package/esm/rules/type-discriminator.mjs.map +1 -0
  113. package/esm/scry/also-changes.mjs +106 -0
  114. package/esm/scry/also-changes.mjs.map +1 -0
  115. package/esm/scry/format.d.mts.map +1 -1
  116. package/esm/scry/format.mjs +22 -0
  117. package/esm/scry/format.mjs.map +1 -1
  118. package/esm/scry/query.d.mts.map +1 -1
  119. package/esm/scry/query.mjs +7 -2
  120. package/esm/scry/query.mjs.map +1 -1
  121. package/esm/scry/search.d.mts.map +1 -1
  122. package/esm/scry/search.mjs +43 -11
  123. package/esm/scry/search.mjs.map +1 -1
  124. package/esm/shots/approve.mjs +195 -0
  125. package/esm/shots/approve.mjs.map +1 -0
  126. package/esm/shots/drift.mjs +174 -0
  127. package/esm/shots/drift.mjs.map +1 -0
  128. package/esm/shots/png.mjs +166 -0
  129. package/esm/shots/png.mjs.map +1 -0
  130. package/esm/shots/state.mjs +43 -0
  131. package/esm/shots/state.mjs.map +1 -0
  132. package/esm/shots/store.mjs +66 -0
  133. package/esm/shots/store.mjs.map +1 -0
  134. package/esm/shots/touched.mjs +38 -0
  135. package/esm/shots/touched.mjs.map +1 -0
  136. package/esm/warlock/adapter.d.mts.map +1 -1
  137. package/esm/warlock/adapter.mjs +15 -2
  138. package/esm/warlock/adapter.mjs.map +1 -1
  139. package/esm/warlock/api-command.mjs +41 -0
  140. package/esm/warlock/api-command.mjs.map +1 -0
  141. package/esm/warlock/approve-command.mjs +80 -0
  142. package/esm/warlock/approve-command.mjs.map +1 -0
  143. package/esm/warlock/commands.d.mts +1 -1
  144. package/esm/warlock/commands.d.mts.map +1 -1
  145. package/esm/warlock/commands.mjs +61 -8
  146. package/esm/warlock/commands.mjs.map +1 -1
  147. package/esm/warlock/guard-command.mjs +116 -0
  148. package/esm/warlock/guard-command.mjs.map +1 -0
  149. package/esm/warlock/index.d.mts +2 -1
  150. package/esm/warlock/index.mjs +2 -1
  151. package/esm/warlock/languages.mjs +75 -0
  152. package/esm/warlock/languages.mjs.map +1 -0
  153. package/esm/warlock/mcp-tools.mjs +2 -2
  154. package/esm/warlock/mcp-tools.mjs.map +1 -1
  155. package/esm/warlock/release-command.mjs +65 -0
  156. package/esm/warlock/release-command.mjs.map +1 -0
  157. package/esm/warlock/shows.d.mts +35 -0
  158. package/esm/warlock/shows.d.mts.map +1 -0
  159. package/esm/warlock/shows.mjs +195 -0
  160. package/esm/warlock/shows.mjs.map +1 -0
  161. package/esm/workspace/cache.mjs +4 -1
  162. package/esm/workspace/cache.mjs.map +1 -1
  163. package/esm/workspace/derived.mjs +11 -6
  164. package/esm/workspace/derived.mjs.map +1 -1
  165. package/esm/workspace/index.d.mts.map +1 -1
  166. package/esm/workspace/index.mjs +8 -1
  167. package/esm/workspace/index.mjs.map +1 -1
  168. package/esm/workspace/stored.mjs +4 -1
  169. package/esm/workspace/stored.mjs.map +1 -1
  170. package/esm/written/features.mjs +21 -5
  171. package/esm/written/features.mjs.map +1 -1
  172. package/esm/written/index.mjs +2 -1
  173. package/esm/written/parse-grimoire.d.mts.map +1 -1
  174. package/esm/written/parse-grimoire.mjs +16 -3
  175. package/esm/written/parse-grimoire.mjs.map +1 -1
  176. package/esm/written/settings.d.mts +11 -0
  177. package/esm/written/settings.d.mts.map +1 -0
  178. package/esm/written/settings.mjs +88 -0
  179. package/esm/written/settings.mjs.map +1 -0
  180. package/llms-full.txt +276 -39
  181. package/llms.txt +2 -0
  182. package/package.json +3 -3
  183. package/skills/backfill-a-grimoire/SKILL.md +4 -0
  184. package/skills/describe-an-app/SKILL.md +4 -1
  185. package/skills/guard-a-change/SKILL.md +85 -0
  186. package/skills/index.md +7 -3
  187. package/skills/record-a-change/SKILL.md +52 -16
  188. package/skills/review-a-change/SKILL.md +53 -0
  189. package/skills/use-the-grimoire/SKILL.md +21 -18
  190. package/skills/write-a-feature/SKILL.md +42 -1
  191. package/ui/grimoire-view.js +756 -40
  192. package/ui/grimoire.css +303 -28
  193. package/ui/product-map.css +43 -7
  194. package/ui/product-map.js +212 -37
@@ -0,0 +1,139 @@
1
+ import { DEFAULT_GRIMOIRE_SETTINGS } from "../contracts/settings.mjs";
2
+ import { GrimoireError } from "../codes/index.mjs";
3
+ import { parseGrimoire } from "../written/parse-grimoire.mjs";
4
+ import "../written/index.mjs";
5
+ import { readApiSnapshot, routeLines } from "./api.mjs";
6
+ import { matchesAny } from "./glob.mjs";
7
+ import { findTask, mergeScopes, readTaskScope } from "./scope.mjs";
8
+ import { commitsIn, filesAt, showFile } from "../git/index.mjs";
9
+ import path from "node:path";
10
+ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+
13
+ //#region ../../packages/grimoire/src/guard/collect.ts
14
+ /**
15
+ * Gathering a {@link GuardInput}: the part of the guard that talks to git
16
+ * and the file system. The rules themselves are in `rules.ts`.
17
+ */
18
+ /** Files Warlock writes and git ignores; they never count as changes (the snapshot is opened after `git` lists the change, but a project may lack the ignore lines). */
19
+ const GENERATED = [
20
+ "grimoire/book/**",
21
+ "grimoire/screenshots/captured/**",
22
+ "grimoire/features/index.json",
23
+ "grimoire/features/**/bookmap.json",
24
+ "grimoire/features/**/*.bookmap.json",
25
+ "grimoire/tasks/index.json"
26
+ ];
27
+ const TEXT_FILE = /\.(?:[cm]?[jt]sx?|css|scss|less|json)$/;
28
+ const MAX_TEXT = 1048576;
29
+ /** The changes the guard looks at: git's list without the files Warlock generates. */
30
+ function guardedChanges(changed) {
31
+ return changed.filter((change) => !matchesAny(change.file, GENERATED));
32
+ }
33
+ async function readCurrent(root, file) {
34
+ const absolute = path.join(root, ...file.split("/"));
35
+ try {
36
+ if ((await stat(absolute)).size > MAX_TEXT) return null;
37
+ return await readFile(absolute, "utf8");
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+ /** The text of every changed code, style and JSON file, now and at the base. */
43
+ async function readTexts(root, base, changed) {
44
+ const texts = {};
45
+ for (const change of changed) {
46
+ if (!TEXT_FILE.test(change.file) && !(change.from !== null && TEXT_FILE.test(change.from))) continue;
47
+ const before = change.status === "added" ? null : await showFile(root, base, change.from ?? change.file);
48
+ texts[change.file] = {
49
+ base: before !== null && before.length > MAX_TEXT ? null : before,
50
+ current: change.status === "deleted" ? null : await readCurrent(root, change.file)
51
+ };
52
+ }
53
+ return texts;
54
+ }
55
+ /** The written features at the base, parsed from a temporary copy; `null` when the change touches none. */
56
+ async function readBaseWritten(root, base, changed) {
57
+ if (!changed.some((change) => [change.file, change.from ?? ""].some((file) => file.startsWith("grimoire/features/")))) return null;
58
+ const folder = await mkdtemp(path.join(tmpdir(), "grimoire-guard-"));
59
+ try {
60
+ for (const file of await filesAt(root, base, "grimoire/features")) {
61
+ if (!file.endsWith(".md")) continue;
62
+ const text = await showFile(root, base, file);
63
+ if (text === null) continue;
64
+ const target = path.join(folder, ...file.split("/"));
65
+ await mkdir(path.dirname(target), { recursive: true });
66
+ await writeFile(target, text);
67
+ }
68
+ return (await parseGrimoire(folder)).written;
69
+ } finally {
70
+ await rm(folder, {
71
+ recursive: true,
72
+ force: true
73
+ });
74
+ }
75
+ }
76
+ /** The task ids the commit messages name (`T-12`), in the order they appear. */
77
+ function taskIdsIn(commits) {
78
+ const ids = [];
79
+ for (const commit of commits) for (const match of `${commit.subject}\n${commit.body}`.matchAll(/\bT-(\d+)\b/g)) {
80
+ const id = `T-${Number(match[1])}`;
81
+ if (!ids.includes(id)) ids.push(id);
82
+ }
83
+ return ids;
84
+ }
85
+ /**
86
+ * The task(s) the change is checked against: the argument, else the tasks
87
+ * the commits name, else the one task `in progress`. `null` when none.
88
+ * Throws `GR9008` when the argument names no task file.
89
+ */
90
+ function resolveScope(snapshot, argument, commits) {
91
+ const { written } = snapshot;
92
+ if (argument !== void 0 && argument.trim() !== "") {
93
+ const task = findTask(written, argument);
94
+ if (task === null) throw new GrimoireError("GR9008", `${JSON.stringify(argument)} matches no task file under grimoire/tasks. Pass an id like T-12.`);
95
+ return readTaskScope(task);
96
+ }
97
+ if (commits !== null) {
98
+ const named = taskIdsIn(commits).flatMap((id) => {
99
+ const task = findTask(written, id);
100
+ return task === null ? [] : [task];
101
+ });
102
+ if (named.length > 0) return mergeScopes(named.map(readTaskScope));
103
+ }
104
+ const active = written.tasks.filter((task) => task.status.value === "in progress");
105
+ return active.length === 1 && active[0] ? readTaskScope(active[0]) : null;
106
+ }
107
+ /** Gather everything the rules read. `snapshot` is opened by the caller. */
108
+ async function collectGuardInput(root, snapshot, changed, options) {
109
+ const commits = options.commits === void 0 ? null : await commitsIn(root, options.commits);
110
+ const flowFiles = {};
111
+ for (const [ref, flow] of Object.entries(snapshot.collected.flows)) flowFiles[ref] = [...new Set(flow.steps.flatMap((step) => [
112
+ ...step.files,
113
+ ...step.typeOnlyFiles,
114
+ ...step.entries
115
+ ]))];
116
+ const routes = snapshot.book.facts.routes;
117
+ return {
118
+ scope: resolveScope(snapshot, options.task, commits),
119
+ changed: [...changed],
120
+ texts: await readTexts(root, options.base, changed),
121
+ ownership: snapshot.ownership,
122
+ flowFiles,
123
+ proofs: snapshot.proofs,
124
+ baseWritten: await readBaseWritten(root, options.base, changed),
125
+ written: snapshot.written,
126
+ settings: snapshot.settings ?? DEFAULT_GRIMOIRE_SETTINGS,
127
+ testFiles: snapshot.book.facts.tests,
128
+ api: {
129
+ approved: await readApiSnapshot(root),
130
+ routes: routes === null ? null : routeLines(routes)
131
+ },
132
+ commits,
133
+ taskIds: snapshot.written.tasks.map((task) => task.id.value)
134
+ };
135
+ }
136
+
137
+ //#endregion
138
+ export { collectGuardInput, guardedChanges, readBaseWritten, readTexts, resolveScope, taskIdsIn };
139
+ //# sourceMappingURL=collect.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collect.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/guard/collect.ts"],"sourcesContent":["/**\n * Gathering a {@link GuardInput}: the part of the guard that talks to git\n * and the file system. The rules themselves are in `rules.ts`.\n */\nimport { mkdtemp, mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport { GrimoireError } from \"../codes\";\nimport type { GuardFileText, GuardInput, TaskScope } from \"../contracts/guard\";\nimport { DEFAULT_GRIMOIRE_SETTINGS } from \"../contracts/settings\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { commitsIn, filesAt, showFile, type ChangedFile, type CommitInfo } from \"../git\";\nimport { parseGrimoire } from \"../written\";\nimport { readApiSnapshot, routeLines } from \"./api\";\nimport { matchesAny } from \"./glob\";\nimport { findTask, mergeScopes, readTaskScope } from \"./scope\";\n\n/** Files Warlock writes and git ignores; they never count as changes (the snapshot is opened after `git` lists the change, but a project may lack the ignore lines). */\nconst GENERATED = [\n \"grimoire/book/**\",\n \"grimoire/screenshots/captured/**\",\n \"grimoire/features/index.json\",\n \"grimoire/features/**/bookmap.json\",\n \"grimoire/features/**/*.bookmap.json\",\n \"grimoire/tasks/index.json\",\n];\n\nconst TEXT_FILE = /\\.(?:[cm]?[jt]sx?|css|scss|less|json)$/;\nconst MAX_TEXT = 1024 * 1024;\n\n/** The changes the guard looks at: git's list without the files Warlock generates. */\nexport function guardedChanges(changed: readonly ChangedFile[]): ChangedFile[] {\n return changed.filter((change) => !matchesAny(change.file, GENERATED));\n}\n\nasync function readCurrent(root: string, file: string): Promise<string | null> {\n const absolute = path.join(root, ...file.split(\"/\"));\n\n try {\n if ((await stat(absolute)).size > MAX_TEXT) return null;\n\n return await readFile(absolute, \"utf8\");\n } catch {\n return null;\n }\n}\n\n/** The text of every changed code, style and JSON file, now and at the base. */\nexport async function readTexts(\n root: string,\n base: string,\n changed: readonly ChangedFile[],\n): Promise<Record<string, GuardFileText>> {\n const texts: Record<string, GuardFileText> = {};\n\n for (const change of changed) {\n if (!TEXT_FILE.test(change.file) && !(change.from !== null && TEXT_FILE.test(change.from)))\n continue;\n\n const before =\n change.status === \"added\" ? null : await showFile(root, base, change.from ?? change.file);\n\n texts[change.file] = {\n base: before !== null && before.length > MAX_TEXT ? null : before,\n current: change.status === \"deleted\" ? null : await readCurrent(root, change.file),\n };\n }\n\n return texts;\n}\n\n/** The written features at the base, parsed from a temporary copy; `null` when the change touches none. */\nexport async function readBaseWritten(\n root: string,\n base: string,\n changed: readonly ChangedFile[],\n): Promise<WrittenGrimoire | null> {\n const touchesFeatures = changed.some((change) =>\n [change.file, change.from ?? \"\"].some((file) => file.startsWith(\"grimoire/features/\")),\n );\n\n if (!touchesFeatures) return null;\n\n const folder = await mkdtemp(path.join(tmpdir(), \"grimoire-guard-\"));\n\n try {\n for (const file of await filesAt(root, base, \"grimoire/features\")) {\n if (!file.endsWith(\".md\")) continue;\n\n const text = await showFile(root, base, file);\n\n if (text === null) continue;\n\n const target = path.join(folder, ...file.split(\"/\"));\n\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, text);\n }\n\n return (await parseGrimoire(folder)).written;\n } finally {\n await rm(folder, { recursive: true, force: true });\n }\n}\n\n/** The task ids the commit messages name (`T-12`), in the order they appear. */\nexport function taskIdsIn(commits: readonly CommitInfo[]): string[] {\n const ids: string[] = [];\n\n for (const commit of commits) {\n for (const match of `${commit.subject}\\n${commit.body}`.matchAll(/\\bT-(\\d+)\\b/g)) {\n const id = `T-${Number(match[1])}`;\n\n if (!ids.includes(id)) ids.push(id);\n }\n }\n\n return ids;\n}\n\n/**\n * The task(s) the change is checked against: the argument, else the tasks\n * the commits name, else the one task `in progress`. `null` when none.\n * Throws `GR9008` when the argument names no task file.\n */\nexport function resolveScope(\n snapshot: GrimoireSnapshot,\n argument: string | undefined,\n commits: readonly CommitInfo[] | null,\n): TaskScope | null {\n const { written } = snapshot;\n\n if (argument !== undefined && argument.trim() !== \"\") {\n const task = findTask(written, argument);\n\n if (task === null) {\n throw new GrimoireError(\n \"GR9008\",\n `${JSON.stringify(argument)} matches no task file under grimoire/tasks. Pass an id like T-12.`,\n );\n }\n\n return readTaskScope(task);\n }\n\n if (commits !== null) {\n const named = taskIdsIn(commits).flatMap((id) => {\n const task = findTask(written, id);\n\n return task === null ? [] : [task];\n });\n\n if (named.length > 0) return mergeScopes(named.map(readTaskScope));\n }\n\n const active = written.tasks.filter((task) => task.status.value === \"in progress\");\n\n return active.length === 1 && active[0] ? readTaskScope(active[0]) : null;\n}\n\n/** What the command was asked. */\nexport type GuardOptions = { task?: string; base: string; commits?: string };\n\n/** Gather everything the rules read. `snapshot` is opened by the caller. */\nexport async function collectGuardInput(\n root: string,\n snapshot: GrimoireSnapshot,\n changed: readonly ChangedFile[],\n options: GuardOptions,\n): Promise<GuardInput> {\n const commits = options.commits === undefined ? null : await commitsIn(root, options.commits);\n const flowFiles: Record<string, string[]> = {};\n\n for (const [ref, flow] of Object.entries(snapshot.collected.flows)) {\n flowFiles[ref] = [\n ...new Set(\n flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles, ...step.entries]),\n ),\n ];\n }\n\n const routes = snapshot.book.facts.routes;\n\n return {\n scope: resolveScope(snapshot, options.task, commits),\n changed: [...changed],\n texts: await readTexts(root, options.base, changed),\n ownership: snapshot.ownership,\n flowFiles,\n proofs: snapshot.proofs,\n baseWritten: await readBaseWritten(root, options.base, changed),\n written: snapshot.written,\n settings: snapshot.settings ?? DEFAULT_GRIMOIRE_SETTINGS,\n testFiles: snapshot.book.facts.tests,\n api: {\n approved: await readApiSnapshot(root),\n routes: routes === null ? null : routeLines(routes),\n },\n commits,\n taskIds: snapshot.written.tasks.map((task) => task.id.value),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,YAAY;AAClB,MAAM,WAAW;;AAGjB,SAAgB,eAAe,SAAgD;CAC7E,OAAO,QAAQ,QAAQ,WAAW,CAAC,WAAW,OAAO,MAAM,SAAS,CAAC;AACvE;AAEA,eAAe,YAAY,MAAc,MAAsC;CAC7E,MAAM,WAAW,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC;CAEnD,IAAI;EACF,KAAK,MAAM,KAAK,QAAQ,EAAC,CAAE,OAAO,UAAU,OAAO;EAEnD,OAAO,MAAM,SAAS,UAAU,MAAM;CACxC,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,UACpB,MACA,MACA,SACwC;CACxC,MAAM,QAA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M,SAAS,SAAS,KAAK,MAAM;CAEnC,OAAO;EACL,OAAO,aAAa,UAAU,QAAQ,MAAM,OAAO;EACnD,SAAS,CAAC,GAAG,OAAO;EACpB,OAAO,MAAM,UAAU,MAAM,QAAQ,MAAM,OAAO;EAClD,WAAW,SAAS;EACpB;EACA,QAAQ,SAAS;EACjB,aAAa,MAAM,gBAAgB,MAAM,QAAQ,MAAM,OAAO;EAC9D,SAAS,SAAS;EAClB,UAAU,SAAS,YAAY;EAC/B,WAAW,SAAS,KAAK,MAAM;EAC/B,KAAK;GACH,UAAU,MAAM,gBAAgB,IAAI;GACpC,QAAQ,WAAW,OAAO,OAAO,WAAW,MAAM;EACpD;EACA;EACA,SAAS,SAAS,QAAQ,MAAM,KAAK,SAAS,KAAK,GAAG,KAAK;CAC7D;AACF"}
@@ -0,0 +1,27 @@
1
+ import { formatCheckReport } from "../check/format-check-report.mjs";
2
+
3
+ //#region ../../packages/grimoire/src/guard/format.ts
4
+ /** The text of a guard report: the check's finding lines, the changes not approved, and the verdict. */
5
+ /** Lines for `warlock grimoire guard` (no `--json`). */
6
+ function formatGuardReport(report, root) {
7
+ const check = {
8
+ schemaVersion: 1,
9
+ root,
10
+ findings: report.findings,
11
+ counts: report.counts,
12
+ ok: report.ok,
13
+ routes: "cached"
14
+ };
15
+ const lines = formatCheckReport(check, { all: true }).slice(0, -1);
16
+ if (report.notApproved.length > 0) {
17
+ lines.push(`not approved: ${report.notApproved.length} change${report.notApproved.length === 1 ? "" : "s"}`);
18
+ for (const item of report.notApproved) lines.push(` ${item.id}`);
19
+ }
20
+ const { errors, warnings } = report.counts;
21
+ lines.push(report.ok ? `guard: ok${warnings > 0 ? ` (${warnings} warning${warnings === 1 ? "" : "s"})` : ""}` : `guard: ${errors} error${errors === 1 ? "" : "s"}`);
22
+ return lines;
23
+ }
24
+
25
+ //#endregion
26
+ export { formatGuardReport };
27
+ //# sourceMappingURL=format.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/guard/format.ts"],"sourcesContent":["/** The text of a guard report: the check's finding lines, the changes not approved, and the verdict. */\nimport { formatCheckReport } from \"../check/format-check-report\";\nimport type { GrimoireCheckReport } from \"../contracts/findings\";\nimport type { GuardReport } from \"../contracts/guard\";\n\n/** Lines for `warlock grimoire guard` (no `--json`). */\nexport function formatGuardReport(report: GuardReport, root: string): string[] {\n const check: GrimoireCheckReport = {\n schemaVersion: 1,\n root,\n findings: report.findings,\n counts: report.counts,\n ok: report.ok,\n routes: \"cached\",\n };\n const lines = formatCheckReport(check, { all: true }).slice(0, -1);\n\n if (report.notApproved.length > 0) {\n lines.push(\n `not approved: ${report.notApproved.length} change${report.notApproved.length === 1 ? \"\" : \"s\"}`,\n );\n\n for (const item of report.notApproved) lines.push(` ${item.id}`);\n }\n\n const { errors, warnings } = report.counts;\n\n lines.push(\n report.ok\n ? `guard: ok${warnings > 0 ? ` (${warnings} warning${warnings === 1 ? \"\" : \"s\"})` : \"\"}`\n : `guard: ${errors} error${errors === 1 ? \"\" : \"s\"}`,\n );\n\n return lines;\n}\n"],"mappings":";;;;;AAMA,SAAgB,kBAAkB,QAAqB,MAAwB;CAC7E,MAAM,QAA6B;EACjC,eAAe;EACf;EACA,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,IAAI,OAAO;EACX,QAAQ;CACV;CACA,MAAM,QAAQ,kBAAkB,OAAO,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,EAAE;CAEjE,IAAI,OAAO,YAAY,SAAS,GAAG;EACjC,MAAM,KACJ,iBAAiB,OAAO,YAAY,OAAO,SAAS,OAAO,YAAY,WAAW,IAAI,KAAK,KAC7F;EAEA,KAAK,MAAM,QAAQ,OAAO,aAAa,MAAM,KAAK,KAAK,KAAK,IAAI;CAClE;CAEA,MAAM,EAAE,QAAQ,aAAa,OAAO;CAEpC,MAAM,KACJ,OAAO,KACH,YAAY,WAAW,IAAI,KAAK,SAAS,UAAU,aAAa,IAAI,KAAK,IAAI,KAAK,OAClF,UAAU,OAAO,QAAQ,WAAW,IAAI,KAAK,KACnD;CAEA,OAAO;AACT"}
@@ -0,0 +1,79 @@
1
+ //#region ../../packages/grimoire/src/guard/glob.ts
2
+ /**
3
+ * The small glob language of `Files:`, `Locked:` and the protected areas:
4
+ * `**` crosses folders, `*` and `?` stay inside one, `{a,b}` picks one.
5
+ * A plain path (no wildcard) matches itself and everything under it.
6
+ */
7
+ const cache = /* @__PURE__ */ new Map();
8
+ /** Split a comma list, leaving commas inside `{…}` alone. Entries are trimmed; empty ones dropped. */
9
+ function splitList(value) {
10
+ const parts = [];
11
+ let depth = 0;
12
+ let current = "";
13
+ for (const char of value) {
14
+ if (char === "{") depth++;
15
+ if (char === "}") depth = Math.max(0, depth - 1);
16
+ if (char === "," && depth === 0) {
17
+ parts.push(current);
18
+ current = "";
19
+ continue;
20
+ }
21
+ current += char;
22
+ }
23
+ parts.push(current);
24
+ return parts.map((part) => part.trim().replace(/^`+|`+$/g, "").trim()).filter((part) => part !== "");
25
+ }
26
+ function escapeRegExp(char) {
27
+ return /[\\^$.*+?()[\]{}|/-]/.test(char) ? `\\${char}` : char;
28
+ }
29
+ function toSource(glob) {
30
+ let source = "";
31
+ let braces = 0;
32
+ for (let index = 0; index < glob.length; index++) {
33
+ const char = glob[index] ?? "";
34
+ if (char === "*") {
35
+ if (glob[index + 1] === "*") {
36
+ if (glob[index + 2] === "/") {
37
+ source += "(?:.*/)?";
38
+ index += 2;
39
+ } else {
40
+ source += ".*";
41
+ index += 1;
42
+ }
43
+ } else source += "[^/]*";
44
+ } else if (char === "?") source += "[^/]";
45
+ else if (char === "{") {
46
+ braces++;
47
+ source += "(?:";
48
+ } else if (char === "}" && braces > 0) {
49
+ braces--;
50
+ source += ")";
51
+ } else if (char === "," && braces > 0) source += "|";
52
+ else source += escapeRegExp(char);
53
+ }
54
+ return source + ")".repeat(braces);
55
+ }
56
+ /** The pattern of a glob. */
57
+ function globToRegExp(glob) {
58
+ const key = glob;
59
+ const known = cache.get(key);
60
+ if (known) return known;
61
+ const normalized = glob.replace(/\\/g, "/").replace(/^\.\//, "");
62
+ const plain = !/[*?{]/.test(normalized);
63
+ const folder = normalized.replace(/\/+$/, "");
64
+ const regex = plain ? new RegExp(`^${toSource(folder)}(?:/.*)?$`) : new RegExp(`^${toSource(normalized.endsWith("/") ? `${folder}/**` : normalized)}$`);
65
+ cache.set(key, regex);
66
+ return regex;
67
+ }
68
+ /** Whether a project-relative path matches the glob. */
69
+ function matchesGlob(file, glob) {
70
+ return globToRegExp(glob).test(file.replace(/\\/g, "/"));
71
+ }
72
+ /** Whether a path matches any of the globs. */
73
+ function matchesAny(file, globs) {
74
+ return globs.some((glob) => matchesGlob(file, glob));
75
+ }
76
+
77
+ //#endregion
78
+ export { globToRegExp, matchesAny, matchesGlob, splitList };
79
+ //# sourceMappingURL=glob.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"glob.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/guard/glob.ts"],"sourcesContent":["/**\n * The small glob language of `Files:`, `Locked:` and the protected areas:\n * `**` crosses folders, `*` and `?` stay inside one, `{a,b}` picks one.\n * A plain path (no wildcard) matches itself and everything under it.\n */\n\nconst cache = new Map<string, RegExp>();\n\n/** Split a comma list, leaving commas inside `{…}` alone. Entries are trimmed; empty ones dropped. */\nexport function splitList(value: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n\n for (const char of value) {\n if (char === \"{\") depth++;\n if (char === \"}\") depth = Math.max(0, depth - 1);\n\n if (char === \",\" && depth === 0) {\n parts.push(current);\n current = \"\";\n continue;\n }\n\n current += char;\n }\n\n parts.push(current);\n\n return parts\n .map((part) =>\n part\n .trim()\n .replace(/^`+|`+$/g, \"\")\n .trim(),\n )\n .filter((part) => part !== \"\");\n}\n\nfunction escapeRegExp(char: string): string {\n return /[\\\\^$.*+?()[\\]{}|/-]/.test(char) ? `\\\\${char}` : char;\n}\n\nfunction toSource(glob: string): string {\n let source = \"\";\n let braces = 0;\n\n for (let index = 0; index < glob.length; index++) {\n const char = glob[index] ?? \"\";\n\n if (char === \"*\") {\n if (glob[index + 1] === \"*\") {\n const after = glob[index + 2];\n\n if (after === \"/\") {\n source += \"(?:.*/)?\";\n index += 2;\n } else {\n source += \".*\";\n index += 1;\n }\n } else {\n source += \"[^/]*\";\n }\n } else if (char === \"?\") source += \"[^/]\";\n else if (char === \"{\") {\n braces++;\n source += \"(?:\";\n } else if (char === \"}\" && braces > 0) {\n braces--;\n source += \")\";\n } else if (char === \",\" && braces > 0) source += \"|\";\n else source += escapeRegExp(char);\n }\n\n return source + \")\".repeat(braces);\n}\n\n/** The pattern of a glob. */\nexport function globToRegExp(glob: string): RegExp {\n const key = glob;\n const known = cache.get(key);\n\n if (known) return known;\n\n const normalized = glob.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n const plain = !/[*?{]/.test(normalized);\n const folder = normalized.replace(/\\/+$/, \"\");\n const regex = plain\n ? new RegExp(`^${toSource(folder)}(?:/.*)?$`)\n : new RegExp(`^${toSource(normalized.endsWith(\"/\") ? `${folder}/**` : normalized)}$`);\n\n cache.set(key, regex);\n\n return regex;\n}\n\n/** Whether a project-relative path matches the glob. */\nexport function matchesGlob(file: string, glob: string): boolean {\n return globToRegExp(glob).test(file.replace(/\\\\/g, \"/\"));\n}\n\n/** Whether a path matches any of the globs. */\nexport function matchesAny(file: string, globs: readonly string[]): boolean {\n return globs.some((glob) => matchesGlob(file, glob));\n}\n"],"mappings":";;;;;;AAMA,MAAM,wBAAQ,IAAI,IAAoB;;AAGtC,SAAgB,UAAU,OAAyB;CACjD,MAAM,QAAkB,CAAC;CACzB,IAAI,QAAQ;CACZ,IAAI,UAAU;CAEd,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,SAAS,KAAK;EAClB,IAAI,SAAS,KAAK,QAAQ,KAAK,IAAI,GAAG,QAAQ,CAAC;EAE/C,IAAI,SAAS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,MAAM,EAAE,UAAU,IAC1C,IAAI,OAAO,IAAI,SAAS,WAAW,SAAS,GAAG,IAAI,GAAG,OAAO,OAAO,UAAU,EAAE,EAAE;CAEtF,MAAM,IAAI,KAAK,KAAK;CAEpB,OAAO;AACT;;AAGA,SAAgB,YAAY,MAAc,MAAuB;CAC/D,OAAO,aAAa,IAAI,CAAC,CAAC,KAAK,KAAK,QAAQ,OAAO,GAAG,CAAC;AACzD;;AAGA,SAAgB,WAAW,MAAc,OAAmC;CAC1E,OAAO,MAAM,MAAM,SAAS,YAAY,MAAM,IAAI,CAAC;AACrD"}
@@ -0,0 +1,9 @@
1
+ import { describeRouteDiff, diffRoutes, parseApiSnapshot, readApiSnapshot, routeLines, writeApiSnapshot } from "./api.mjs";
2
+ import { countAssertions } from "./assertions.mjs";
3
+ import { globToRegExp, matchesAny, matchesGlob, splitList } from "./glob.mjs";
4
+ import { findTask, mergeScopes, parseRemoveEntry, readTaskScope, scopeFeatures, scopeFlows, taskNumber } from "./scope.mjs";
5
+ import { isTestPath, runGuardChecks } from "./rules.mjs";
6
+ import { collectGuardInput, guardedChanges, readBaseWritten, readTexts, resolveScope, taskIdsIn } from "./collect.mjs";
7
+ import { formatGuardReport } from "./format.mjs";
8
+
9
+ export { collectGuardInput, describeRouteDiff, diffRoutes, formatGuardReport, guardedChanges, readApiSnapshot, routeLines, runGuardChecks, writeApiSnapshot };
@@ -0,0 +1,310 @@
1
+ import { CODE_RULES } from "../contracts/settings.mjs";
2
+ import { createFinding } from "../codes/index.mjs";
3
+ import { scanProofsInText } from "../proves/scan-proofs.mjs";
4
+ import "../proves/index.mjs";
5
+ import { describeRouteDiff, diffRoutes } from "./api.mjs";
6
+ import { runCodeRules } from "../rules/index.mjs";
7
+ import { findFocusedTests } from "../rules/focused.mjs";
8
+ import { countAssertions } from "./assertions.mjs";
9
+ import { matchesAny } from "./glob.mjs";
10
+ import { scopeFeatures, scopeFlows } from "./scope.mjs";
11
+
12
+ //#region ../../packages/grimoire/src/guard/rules.ts
13
+ /**
14
+ * The guard's rules: a pure function over a {@link GuardInput}. No git and
15
+ * no file is read here, so every rule is tested with plain data.
16
+ */
17
+ const TEST_FILE = /(?:\.(?:test|spec|e2e)\.[cm]?[jt]sx?$|(?:^|\/)(?:tests?|e2e|__tests__)\/)/;
18
+ const DEPENDENCY_SECTIONS = [
19
+ "dependencies",
20
+ "devDependencies",
21
+ "peerDependencies",
22
+ "optionalDependencies"
23
+ ];
24
+ /** Whether a path is a test file by name or folder. */
25
+ function isTestPath(file) {
26
+ return TEST_FILE.test(file);
27
+ }
28
+ function at(file, line) {
29
+ return {
30
+ file,
31
+ line: line ?? 1,
32
+ column: null
33
+ };
34
+ }
35
+ /** The paths of a change: each file, and the old path of a rename. */
36
+ function pathsOf(input) {
37
+ return input.changed.flatMap((change) => change.from === null ? [change.file] : [change.file, change.from]);
38
+ }
39
+ /** Whether `removes` names this feature, flow, criterion or case (a wider entry covers what is inside it). */
40
+ function isRemoved(scope, feature, flow, criterion, caseQuestion) {
41
+ return scope.removes.some((entry) => {
42
+ if (entry.feature !== feature) return false;
43
+ if (entry.flow === null) return true;
44
+ if (flow === void 0 || entry.flow !== flow) return false;
45
+ if (entry.criterion === null && entry.case === null) return true;
46
+ return criterion !== void 0 && entry.criterion === criterion.toUpperCase() || caseQuestion !== void 0 && entry.case === caseQuestion.toLowerCase();
47
+ });
48
+ }
49
+ /** The files a task allows (everything else that changes is GR7006). */
50
+ function allowedFiles(input, scope) {
51
+ const allowed = /* @__PURE__ */ new Set([scope.file]);
52
+ const features = scopeFeatures(scope);
53
+ const flows = scopeFlows(scope);
54
+ for (const feature of features) for (const file of input.ownership.features[feature]?.own ?? []) allowed.add(file);
55
+ for (const [file, owner] of Object.entries(input.ownership.files)) if (owner.owner !== null && features.includes(owner.owner)) allowed.add(file);
56
+ for (const ref of flows) for (const file of input.flowFiles[ref] ?? []) allowed.add(file);
57
+ for (const proof of input.proofs) if (flows.length > 0 ? flows.includes(proof.ref) : features.includes(proof.feature)) allowed.add(proof.at.file);
58
+ for (const [file, text] of Object.entries(input.texts)) {
59
+ if (text.base === null || !text.base.includes("@proves")) continue;
60
+ for (const proof of scanProofsInText(text.base, file).proofs) if (flows.length > 0 ? flows.includes(proof.ref) : features.includes(proof.feature)) allowed.add(file);
61
+ }
62
+ return allowed;
63
+ }
64
+ function inScope(file, scope, allowed) {
65
+ return allowed.has(file) || file.startsWith("grimoire/tasks/") || file.startsWith("grimoire/releases/") || file.startsWith("grimoire/approved/") || file.startsWith("grimoire/screenshots/approved/") || scopeFeatures(scope).some((feature) => file.startsWith(`grimoire/features/${feature}/`)) || matchesAny(file, scope.files);
66
+ }
67
+ function scopeFindings(input, scope) {
68
+ const allowed = allowedFiles(input, scope);
69
+ const findings = [];
70
+ for (const change of input.changed) {
71
+ const outside = [change.file, ...change.from === null ? [] : [change.from]].filter((file) => !inScope(file, scope, allowed));
72
+ if (outside.length === 0) continue;
73
+ findings.push(createFinding({
74
+ code: "GR7006",
75
+ message: `${change.status} ${JSON.stringify(outside[0])} is outside ${scope.id}${scope.feature === null ? "" : ` (${scope.flow ?? scope.feature})`}`,
76
+ at: at(change.file, null),
77
+ task: scope.id
78
+ }));
79
+ }
80
+ return findings;
81
+ }
82
+ function removalFindings(input, scope) {
83
+ const base = input.baseWritten;
84
+ const findings = [];
85
+ if (base === null) return findings;
86
+ const report = (message, file, line, feature, flow) => {
87
+ findings.push(createFinding({
88
+ code: "GR7007",
89
+ message,
90
+ at: at(file, line),
91
+ task: scope.id,
92
+ feature,
93
+ flow
94
+ }));
95
+ };
96
+ for (const feature of base.features) {
97
+ const current = input.written.features.find((item) => item.id === feature.id);
98
+ if (current === void 0) {
99
+ if (!isRemoved(scope, feature.id)) report(`the change removes the feature ${JSON.stringify(feature.id)} (${feature.flows.length} flows)`, feature.readme?.file ?? `grimoire/features/${feature.id}/README.md`, 1, feature.id, null);
100
+ continue;
101
+ }
102
+ for (const flow of feature.flows) {
103
+ const next = current.flows.find((item) => item.id.value === flow.id.value);
104
+ if (next === void 0) {
105
+ if (!isRemoved(scope, feature.id, flow.id.value)) report(`the change removes the flow ${JSON.stringify(flow.ref)}`, flow.file, 1, feature.id, flow.ref);
106
+ continue;
107
+ }
108
+ for (const criterion of flow.criteria) {
109
+ if (next.criteria.some((item) => item.id === criterion.id)) continue;
110
+ if (!isRemoved(scope, feature.id, flow.id.value, criterion.id)) report(`the change removes ${criterion.id} of ${flow.ref}: ${JSON.stringify(criterion.text)}`, next.file, 1, feature.id, flow.ref);
111
+ }
112
+ for (const item of flow.cases) {
113
+ if (next.cases.some((other) => other.question === item.question)) continue;
114
+ if (!isRemoved(scope, feature.id, flow.id.value, void 0, item.question)) report(`the change removes the case ${JSON.stringify(item.question)} of ${flow.ref}`, next.file, 1, feature.id, flow.ref);
115
+ }
116
+ }
117
+ }
118
+ return findings;
119
+ }
120
+ function proofFindings(input, scope) {
121
+ const touched = new Set(pathsOf(input));
122
+ const current = /* @__PURE__ */ new Set();
123
+ const findings = [];
124
+ for (const proof of input.proofs) if (!touched.has(proof.at.file)) current.add(`${proof.ref} ${proof.criterion}`);
125
+ for (const [file, text] of Object.entries(input.texts)) {
126
+ if (text.current === null) continue;
127
+ for (const proof of scanProofsInText(text.current, file).proofs) current.add(`${proof.ref} ${proof.criterion}`);
128
+ }
129
+ const reported = /* @__PURE__ */ new Set();
130
+ for (const [file, text] of Object.entries(input.texts)) {
131
+ if (text.base === null || !text.base.includes("@proves")) continue;
132
+ for (const proof of scanProofsInText(text.base, file).proofs) {
133
+ const key = `${proof.ref} ${proof.criterion}`;
134
+ if (current.has(key) || reported.has(key)) continue;
135
+ if (isRemoved(scope, proof.feature, proof.flow, proof.criterion)) continue;
136
+ reported.add(key);
137
+ findings.push(createFinding({
138
+ code: "GR7008",
139
+ message: `no test proves ${proof.criterion} of ${proof.ref} any more${proof.test?.name ? ` (was ${JSON.stringify(proof.test.name)})` : ""}`,
140
+ at: at(file, proof.at.line),
141
+ task: scope.id,
142
+ feature: proof.feature,
143
+ flow: proof.ref
144
+ }));
145
+ }
146
+ }
147
+ return findings;
148
+ }
149
+ function lockedFindings(input, scope) {
150
+ if (scope.locked.length === 0) return [];
151
+ return input.changed.flatMap((change) => {
152
+ const locked = [change.file, ...change.from === null ? [] : [change.from]].find((file) => matchesAny(file, scope.locked));
153
+ return locked === void 0 ? [] : [createFinding({
154
+ code: "GR7009",
155
+ message: `${JSON.stringify(locked)} is a locked test of ${scope.id} and was ${change.status}`,
156
+ at: at(change.file, null),
157
+ task: scope.id
158
+ })];
159
+ });
160
+ }
161
+ function assertionFindings(input, scope) {
162
+ const tests = new Set(input.testFiles);
163
+ const findings = [];
164
+ for (const [file, text] of Object.entries(input.texts)) {
165
+ if (text.base === null || text.current === null || !(tests.has(file) || isTestPath(file))) continue;
166
+ const before = countAssertions(text.base);
167
+ const after = countAssertions(text.current);
168
+ if (after < before) findings.push(createFinding({
169
+ code: "GR7010",
170
+ message: `the test file has ${after} assertions, it had ${before}`,
171
+ at: at(file, null),
172
+ task: scope?.id ?? null
173
+ }));
174
+ }
175
+ return findings;
176
+ }
177
+ function dependencyChanges(before, after) {
178
+ if (after === null) return [];
179
+ let next;
180
+ let previous = {};
181
+ try {
182
+ next = JSON.parse(after);
183
+ if (before !== null) previous = JSON.parse(before);
184
+ } catch {
185
+ return [];
186
+ }
187
+ const changes = [];
188
+ for (const section of DEPENDENCY_SECTIONS) {
189
+ const now = next[section];
190
+ const was = previous[section];
191
+ if (typeof now !== "object" || now === null) continue;
192
+ for (const [name, version] of Object.entries(now)) if ((typeof was === "object" && was !== null ? was[name] : void 0) !== version) changes.push(`${name}@${String(version)}`);
193
+ }
194
+ return changes;
195
+ }
196
+ function protectedFindings(input, scope) {
197
+ const findings = [];
198
+ for (const area of input.settings.protected) {
199
+ const name = area.name.toLowerCase();
200
+ if (scope.touches.includes(name)) continue;
201
+ if (name === "public-api") {
202
+ const { approved, routes } = input.api;
203
+ if (approved === null || routes === null) continue;
204
+ const diff = diffRoutes(approved.routes, routes);
205
+ if (diff.added.length + diff.removed.length > 0) findings.push(createFinding({
206
+ code: "GR7011",
207
+ message: `the public API changed (${describeRouteDiff(diff)}) and ${scope.id} does not name public-api in Touches`,
208
+ at: at("grimoire/approved/api.json", null),
209
+ task: scope.id
210
+ }));
211
+ continue;
212
+ }
213
+ for (const change of input.changed) {
214
+ const file = [change.file, change.from ?? ""].find((candidate) => candidate !== "" && matchesAny(candidate, area.globs));
215
+ if (file === void 0) continue;
216
+ if (name === "dependencies") {
217
+ const text = input.texts[change.file];
218
+ const added = dependencyChanges(text?.base ?? null, text?.current ?? null);
219
+ if (added.length === 0) continue;
220
+ findings.push(createFinding({
221
+ code: "GR7011",
222
+ message: `${JSON.stringify(file)} adds or changes ${added.slice(0, 5).join(", ")}${added.length > 5 ? ` and ${added.length - 5} more` : ""}, and ${scope.id} does not name dependencies in Touches`,
223
+ at: at(change.file, null),
224
+ task: scope.id
225
+ }));
226
+ continue;
227
+ }
228
+ findings.push(createFinding({
229
+ code: "GR7011",
230
+ message: `${JSON.stringify(file)} is in the protected area ${JSON.stringify(area.name)} and ${scope.id} does not name it in Touches`,
231
+ at: at(change.file, null),
232
+ task: scope.id
233
+ }));
234
+ }
235
+ }
236
+ return findings;
237
+ }
238
+ function addedLineFindings(input, scope) {
239
+ const findings = [];
240
+ const rules = input.settings.rules ?? CODE_RULES;
241
+ const tests = new Set(input.testFiles);
242
+ for (const change of input.changed) {
243
+ const text = input.texts[change.file]?.current;
244
+ if (change.status === "deleted" || text === void 0 || text === null) continue;
245
+ const added = new Set(change.addedLines);
246
+ if (rules.length > 0) for (const hit of runCodeRules(change.file, text, rules)) {
247
+ if (!added.has(hit.line)) continue;
248
+ findings.push(createFinding({
249
+ code: hit.code,
250
+ message: hit.message,
251
+ at: {
252
+ file: change.file,
253
+ line: hit.line,
254
+ column: hit.column
255
+ },
256
+ task: scope?.id ?? null
257
+ }));
258
+ }
259
+ if (tests.has(change.file) || isTestPath(change.file)) for (const hit of findFocusedTests(text)) {
260
+ if (!added.has(hit.line)) continue;
261
+ findings.push(createFinding({
262
+ code: hit.type === "only" ? "GR4011" : "GR4012",
263
+ severity: "error",
264
+ message: `${hit.call} was added`,
265
+ at: {
266
+ file: change.file,
267
+ line: hit.line,
268
+ column: null
269
+ },
270
+ task: scope?.id ?? null
271
+ }));
272
+ }
273
+ }
274
+ return findings;
275
+ }
276
+ function commitFindings(input) {
277
+ if (input.commits === null) return [];
278
+ const known = new Set(input.taskIds.map((id) => Number(id.replace(/\D/g, ""))));
279
+ const findings = [];
280
+ for (const commit of input.commits) {
281
+ if (/^Merge (?:pull request|branch|remote-tracking branch)\b/.test(commit.subject)) continue;
282
+ const ids = [...new Set([...`${commit.subject}\n${commit.body}`.matchAll(/\bT-(\d+)\b/g)].map((match) => Number(match[1])))];
283
+ const label = `commit ${commit.sha.slice(0, 7)} ${JSON.stringify(commit.subject)}`;
284
+ if (ids.length === 0) findings.push(createFinding({
285
+ code: "GR7012",
286
+ message: `${label} names no task`
287
+ }));
288
+ else if (!ids.some((id) => known.has(id))) findings.push(createFinding({
289
+ code: "GR7012",
290
+ message: `${label} names ${ids.map((id) => `T-${id}`).join(", ")}, which has no task file`
291
+ }));
292
+ }
293
+ return findings;
294
+ }
295
+ /** Every finding of the guard for a change. Pure. */
296
+ function runGuardChecks(input) {
297
+ const { scope } = input;
298
+ const findings = [];
299
+ if (scope === null) findings.push(createFinding({
300
+ code: "GR9008",
301
+ message: "no task was found: none was passed, the commits name none, and not exactly one task is in progress"
302
+ }));
303
+ else findings.push(...scopeFindings(input, scope), ...removalFindings(input, scope), ...proofFindings(input, scope), ...lockedFindings(input, scope), ...protectedFindings(input, scope));
304
+ findings.push(...assertionFindings(input, scope), ...addedLineFindings(input, scope), ...commitFindings(input));
305
+ return findings;
306
+ }
307
+
308
+ //#endregion
309
+ export { isTestPath, runGuardChecks };
310
+ //# sourceMappingURL=rules.mjs.map