@warlock.js/grimoire 0.0.0-stage → 5.56.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 (211) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/esm/apps/check-apps.mjs +207 -0
  5. package/esm/apps/check-apps.mjs.map +1 -0
  6. package/esm/apps/index.mjs +4 -0
  7. package/esm/apps/match-apps.d.mts +12 -0
  8. package/esm/apps/match-apps.d.mts.map +1 -0
  9. package/esm/apps/match-apps.mjs +30 -0
  10. package/esm/apps/match-apps.mjs.map +1 -0
  11. package/esm/book/build.d.mts +14 -0
  12. package/esm/book/build.d.mts.map +1 -0
  13. package/esm/book/build.mjs +300 -0
  14. package/esm/book/build.mjs.map +1 -0
  15. package/esm/book/index.mjs +5 -0
  16. package/esm/book/io.mjs +162 -0
  17. package/esm/book/io.mjs.map +1 -0
  18. package/esm/book/normalize.mjs +71 -0
  19. package/esm/book/normalize.mjs.map +1 -0
  20. package/esm/book/render.mjs +262 -0
  21. package/esm/book/render.mjs.map +1 -0
  22. package/esm/book/write.d.mts +12 -0
  23. package/esm/book/write.d.mts.map +1 -0
  24. package/esm/book/write.mjs +90 -0
  25. package/esm/book/write.mjs.map +1 -0
  26. package/esm/bookmap/build.d.mts +21 -0
  27. package/esm/bookmap/build.d.mts.map +1 -0
  28. package/esm/bookmap/build.mjs +272 -0
  29. package/esm/bookmap/build.mjs.map +1 -0
  30. package/esm/bookmap/index.mjs +5 -0
  31. package/esm/bookmap/steps.mjs +137 -0
  32. package/esm/bookmap/steps.mjs.map +1 -0
  33. package/esm/bookmap/write.d.mts +19 -0
  34. package/esm/bookmap/write.d.mts.map +1 -0
  35. package/esm/bookmap/write.mjs +118 -0
  36. package/esm/bookmap/write.mjs.map +1 -0
  37. package/esm/check/check-grimoire.d.mts +7 -0
  38. package/esm/check/check-grimoire.d.mts.map +1 -0
  39. package/esm/check/check-grimoire.mjs +98 -0
  40. package/esm/check/check-grimoire.mjs.map +1 -0
  41. package/esm/check/format-check-report.d.mts +20 -0
  42. package/esm/check/format-check-report.d.mts.map +1 -0
  43. package/esm/check/format-check-report.mjs +55 -0
  44. package/esm/check/format-check-report.mjs.map +1 -0
  45. package/esm/check/index.mjs +4 -0
  46. package/esm/check/rules/book-notes.mjs +18 -0
  47. package/esm/check/rules/book-notes.mjs.map +1 -0
  48. package/esm/check/rules/criteria.mjs +48 -0
  49. package/esm/check/rules/criteria.mjs.map +1 -0
  50. package/esm/check/rules/links.mjs +196 -0
  51. package/esm/check/rules/links.mjs.map +1 -0
  52. package/esm/check/rules/lookup.mjs +41 -0
  53. package/esm/check/rules/lookup.mjs.map +1 -0
  54. package/esm/check/rules/source-files.mjs +119 -0
  55. package/esm/check/rules/source-files.mjs.map +1 -0
  56. package/esm/check/rules/versions.mjs +92 -0
  57. package/esm/check/rules/versions.mjs.map +1 -0
  58. package/esm/codes/codes.d.mts +182 -0
  59. package/esm/codes/codes.d.mts.map +1 -0
  60. package/esm/codes/codes.mjs +111 -0
  61. package/esm/codes/codes.mjs.map +1 -0
  62. package/esm/codes/index.d.mts +33 -0
  63. package/esm/codes/index.d.mts.map +1 -0
  64. package/esm/codes/index.mjs +63 -0
  65. package/esm/codes/index.mjs.map +1 -0
  66. package/esm/contracts/adapter.d.mts +209 -0
  67. package/esm/contracts/adapter.d.mts.map +1 -0
  68. package/esm/contracts/book.d.mts +233 -0
  69. package/esm/contracts/book.d.mts.map +1 -0
  70. package/esm/contracts/book.mjs +7 -0
  71. package/esm/contracts/book.mjs.map +1 -0
  72. package/esm/contracts/bookmap.d.mts +175 -0
  73. package/esm/contracts/bookmap.d.mts.map +1 -0
  74. package/esm/contracts/findings.d.mts +79 -0
  75. package/esm/contracts/findings.d.mts.map +1 -0
  76. package/esm/contracts/location.d.mts +22 -0
  77. package/esm/contracts/location.d.mts.map +1 -0
  78. package/esm/contracts/releases.d.mts +53 -0
  79. package/esm/contracts/releases.d.mts.map +1 -0
  80. package/esm/contracts/scry.d.mts +143 -0
  81. package/esm/contracts/scry.d.mts.map +1 -0
  82. package/esm/contracts/snapshot.d.mts +52 -0
  83. package/esm/contracts/snapshot.d.mts.map +1 -0
  84. package/esm/contracts/test-results.d.mts +63 -0
  85. package/esm/contracts/test-results.d.mts.map +1 -0
  86. package/esm/contracts/written.d.mts +363 -0
  87. package/esm/contracts/written.d.mts.map +1 -0
  88. package/esm/contracts/written.mjs +19 -0
  89. package/esm/contracts/written.mjs.map +1 -0
  90. package/esm/devtools/data.mjs +171 -0
  91. package/esm/devtools/data.mjs.map +1 -0
  92. package/esm/devtools/graphs.mjs +142 -0
  93. package/esm/devtools/graphs.mjs.map +1 -0
  94. package/esm/devtools/index.d.mts +42 -0
  95. package/esm/devtools/index.d.mts.map +1 -0
  96. package/esm/devtools/index.mjs +103 -0
  97. package/esm/devtools/index.mjs.map +1 -0
  98. package/esm/devtools/site.d.mts +26 -0
  99. package/esm/devtools/site.d.mts.map +1 -0
  100. package/esm/devtools/site.mjs +190 -0
  101. package/esm/devtools/site.mjs.map +1 -0
  102. package/esm/devtools/snapshot-source.mjs +70 -0
  103. package/esm/devtools/snapshot-source.mjs.map +1 -0
  104. package/esm/front-matter/index.d.mts +33 -0
  105. package/esm/front-matter/index.d.mts.map +1 -0
  106. package/esm/front-matter/index.mjs +130 -0
  107. package/esm/front-matter/index.mjs.map +1 -0
  108. package/esm/graph/index.d.mts +15 -0
  109. package/esm/graph/index.d.mts.map +1 -0
  110. package/esm/graph/index.mjs +42 -0
  111. package/esm/graph/index.mjs.map +1 -0
  112. package/esm/index.d.mts +33 -0
  113. package/esm/index.mjs +33 -0
  114. package/esm/ownership/index.d.mts +8 -0
  115. package/esm/ownership/index.d.mts.map +1 -0
  116. package/esm/ownership/index.mjs +137 -0
  117. package/esm/ownership/index.mjs.map +1 -0
  118. package/esm/paths/index.d.mts +58 -0
  119. package/esm/paths/index.d.mts.map +1 -0
  120. package/esm/paths/index.mjs +137 -0
  121. package/esm/paths/index.mjs.map +1 -0
  122. package/esm/proves/index.mjs +3 -0
  123. package/esm/proves/scan-proofs.d.mts +22 -0
  124. package/esm/proves/scan-proofs.d.mts.map +1 -0
  125. package/esm/proves/scan-proofs.mjs +214 -0
  126. package/esm/proves/scan-proofs.mjs.map +1 -0
  127. package/esm/releases/index.d.mts +29 -0
  128. package/esm/releases/index.d.mts.map +1 -0
  129. package/esm/releases/index.mjs +157 -0
  130. package/esm/releases/index.mjs.map +1 -0
  131. package/esm/scry/format.d.mts +14 -0
  132. package/esm/scry/format.d.mts.map +1 -0
  133. package/esm/scry/format.mjs +193 -0
  134. package/esm/scry/format.mjs.map +1 -0
  135. package/esm/scry/index.mjs +5 -0
  136. package/esm/scry/parse.d.mts +10 -0
  137. package/esm/scry/parse.d.mts.map +1 -0
  138. package/esm/scry/parse.mjs +108 -0
  139. package/esm/scry/parse.mjs.map +1 -0
  140. package/esm/scry/query.d.mts +11 -0
  141. package/esm/scry/query.d.mts.map +1 -0
  142. package/esm/scry/query.mjs +457 -0
  143. package/esm/scry/query.mjs.map +1 -0
  144. package/esm/tasks/index.mjs +116 -0
  145. package/esm/tasks/index.mjs.map +1 -0
  146. package/esm/test-results/criterion-status.d.mts +15 -0
  147. package/esm/test-results/criterion-status.d.mts.map +1 -0
  148. package/esm/test-results/criterion-status.mjs +17 -0
  149. package/esm/test-results/criterion-status.mjs.map +1 -0
  150. package/esm/test-results/index.d.mts +8 -0
  151. package/esm/test-results/index.d.mts.map +1 -0
  152. package/esm/test-results/index.mjs +124 -0
  153. package/esm/test-results/index.mjs.map +1 -0
  154. package/esm/vitest/index.d.mts +15 -0
  155. package/esm/vitest/index.d.mts.map +1 -0
  156. package/esm/vitest/index.mjs +146 -0
  157. package/esm/vitest/index.mjs.map +1 -0
  158. package/esm/warlock/actions.mjs +265 -0
  159. package/esm/warlock/actions.mjs.map +1 -0
  160. package/esm/warlock/adapter.d.mts +28 -0
  161. package/esm/warlock/adapter.d.mts.map +1 -0
  162. package/esm/warlock/adapter.mjs +377 -0
  163. package/esm/warlock/adapter.mjs.map +1 -0
  164. package/esm/warlock/commands.d.mts +15 -0
  165. package/esm/warlock/commands.d.mts.map +1 -0
  166. package/esm/warlock/commands.mjs +199 -0
  167. package/esm/warlock/commands.mjs.map +1 -0
  168. package/esm/warlock/index.d.mts +4 -0
  169. package/esm/warlock/index.mjs +5 -0
  170. package/esm/warlock/mcp-tools.mjs +247 -0
  171. package/esm/warlock/mcp-tools.mjs.map +1 -0
  172. package/esm/warlock/mobile-facts.d.mts +32 -0
  173. package/esm/warlock/mobile-facts.d.mts.map +1 -0
  174. package/esm/warlock/mobile-facts.mjs +185 -0
  175. package/esm/warlock/mobile-facts.mjs.map +1 -0
  176. package/esm/workspace/index.d.mts +11 -0
  177. package/esm/workspace/index.d.mts.map +1 -0
  178. package/esm/workspace/index.mjs +122 -0
  179. package/esm/workspace/index.mjs.map +1 -0
  180. package/esm/written/apps.mjs +227 -0
  181. package/esm/written/apps.mjs.map +1 -0
  182. package/esm/written/features.mjs +400 -0
  183. package/esm/written/features.mjs.map +1 -0
  184. package/esm/written/fields.mjs +173 -0
  185. package/esm/written/fields.mjs.map +1 -0
  186. package/esm/written/index.mjs +3 -0
  187. package/esm/written/lists.mjs +68 -0
  188. package/esm/written/lists.mjs.map +1 -0
  189. package/esm/written/markdown.mjs +173 -0
  190. package/esm/written/markdown.mjs.map +1 -0
  191. package/esm/written/parse-grimoire.d.mts +20 -0
  192. package/esm/written/parse-grimoire.d.mts.map +1 -0
  193. package/esm/written/parse-grimoire.mjs +552 -0
  194. package/esm/written/parse-grimoire.mjs.map +1 -0
  195. package/esm/written/sink.mjs +65 -0
  196. package/esm/written/sink.mjs.map +1 -0
  197. package/esm/written/tasks-releases.mjs +166 -0
  198. package/esm/written/tasks-releases.mjs.map +1 -0
  199. package/llms-full.txt +869 -0
  200. package/llms.txt +15 -0
  201. package/package.json +66 -4
  202. package/skills/backfill-a-grimoire/SKILL.md +128 -0
  203. package/skills/describe-an-app/SKILL.md +162 -0
  204. package/skills/document-a-file/SKILL.md +75 -0
  205. package/skills/index.md +26 -0
  206. package/skills/record-a-change/SKILL.md +139 -0
  207. package/skills/use-the-grimoire/SKILL.md +137 -0
  208. package/skills/write-a-feature/SKILL.md +168 -0
  209. package/ui/grimoire-static.js +136 -0
  210. package/ui/grimoire-view.js +1005 -0
  211. package/ui/grimoire.css +88 -0
@@ -0,0 +1,272 @@
1
+ import { BOOK_SCHEMA_VERSION } from "../contracts/book.mjs";
2
+ import { toPosixPath } from "../paths/index.mjs";
3
+ import { fileGraph } from "../graph/index.mjs";
4
+ import { criterionStatus } from "../test-results/criterion-status.mjs";
5
+ import "../test-results/index.mjs";
6
+ import { resolveStep } from "./steps.mjs";
7
+
8
+ //#region ../../packages/grimoire/src/bookmap/build.ts
9
+ /** The file name of a flow without `.md`: the name of its book map. */
10
+ function flowFileId(flow) {
11
+ const name = toPosixPath(flow.file).split("/").pop() ?? flow.id.value;
12
+ return name.endsWith(".md") ? name.slice(0, -3) : name;
13
+ }
14
+ /**
15
+ * The result recorded for the test a proof line points at: same file and
16
+ * line, else (the test moved) same name among the results whose line no
17
+ * proof of that file claims.
18
+ */
19
+ function resultFor(proof, line, results, claimedLines) {
20
+ const file = toPosixPath(proof.at.file);
21
+ const sameProof = (result) => result.feature === proof.feature && result.flow === proof.flow && result.criterion === proof.criterion;
22
+ const inFile = results.filter((result) => toPosixPath(result.testFile) === file);
23
+ const atLine = inFile.filter((result) => result.line === line);
24
+ const byLine = atLine.find(sameProof) ?? atLine[0];
25
+ if (byLine) return byLine;
26
+ const name = proof.test?.name ?? null;
27
+ if (name === null) return null;
28
+ const named = inFile.filter((result) => !claimedLines.has(`${file}:${result.line}`) && (result.testName === name || result.testName.endsWith(` > ${name}`)));
29
+ return named.find(sameProof) ?? named[0] ?? null;
30
+ }
31
+ function flowCriteria(flow, input) {
32
+ const results = input.results?.results ?? [];
33
+ const claimedLines = new Set(input.proofs.flatMap((proof) => proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`]));
34
+ return flow.criteria.map((criterion) => {
35
+ const tests = input.proofs.filter((proof) => proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null).map((proof) => {
36
+ const line = proof.test?.line ?? proof.at.line;
37
+ const file = toPosixPath(proof.at.file);
38
+ const result = resultFor(proof, line, results, claimedLines);
39
+ const currentHash = input.testHashes[file];
40
+ const stale = result !== null && currentHash !== void 0 && result.testFileHash !== currentHash;
41
+ return {
42
+ file,
43
+ line,
44
+ name: proof.test?.name ?? null,
45
+ result: result?.outcome ?? "not-run",
46
+ stale
47
+ };
48
+ }).sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
49
+ return {
50
+ id: criterion.id,
51
+ app: criterion.app,
52
+ text: criterion.text,
53
+ tests,
54
+ status: criterionStatus(tests)
55
+ };
56
+ });
57
+ }
58
+ function shownBy(flow, written) {
59
+ const shown = [];
60
+ for (const app of written.apps) {
61
+ const appId = app.id.value;
62
+ for (const layout of app.layouts) for (const row of layout.blocks) if (row.flow === flow.ref) shown.push({
63
+ app: appId,
64
+ type: "layout",
65
+ id: layout.id,
66
+ block: row.block,
67
+ file: layout.file
68
+ });
69
+ for (const page of [...app.pages, ...app.screens]) for (const row of page.blocks) if (row.flow === flow.ref) shown.push({
70
+ app: appId,
71
+ type: page.type,
72
+ id: page.id,
73
+ block: row.block,
74
+ file: page.file
75
+ });
76
+ }
77
+ return shown;
78
+ }
79
+ function flowBookmap(feature, flow, input, context) {
80
+ return {
81
+ schemaVersion: 1,
82
+ feature: feature.id,
83
+ flow: flowFileId(flow),
84
+ ref: flow.ref,
85
+ steps: flow.steps.map((step) => resolveStep(step, feature, context)),
86
+ criteria: flowCriteria(flow, input),
87
+ shownBy: shownBy(flow, input.written)
88
+ };
89
+ }
90
+ function featureBookmap(feature, flows, input, byPath) {
91
+ const { ownership, facts } = input;
92
+ const own = ownership.features[feature.id]?.own ?? [];
93
+ const ownSet = new Set(own);
94
+ const importersOf = /* @__PURE__ */ new Map();
95
+ for (const ownFile of own) for (const entry of byPath.get(ownFile)?.imports ?? []) {
96
+ if (entry.file === null) continue;
97
+ const list = importersOf.get(entry.file) ?? [];
98
+ if (list.at(-1) !== ownFile) list.push(ownFile);
99
+ importersOf.set(entry.file, list);
100
+ }
101
+ const borrowed = (ownership.features[feature.id]?.borrowed ?? []).map((file) => ({
102
+ file,
103
+ owner: ownership.files[file]?.owner ?? null,
104
+ by: importersOf.get(file) ?? []
105
+ }));
106
+ const routes = [];
107
+ for (const route of facts.routes ?? []) {
108
+ if (route.isPage) continue;
109
+ const file = route.handlerFile !== null && ownSet.has(route.handlerFile) ? route.handlerFile : route.sourceFile !== null && ownSet.has(route.sourceFile) ? route.sourceFile : null;
110
+ if (file !== null) routes.push({
111
+ method: route.method,
112
+ path: route.path,
113
+ name: route.name,
114
+ file
115
+ });
116
+ }
117
+ const pages = {};
118
+ const add = (app, item) => {
119
+ (pages[app] ??= []).push(item);
120
+ };
121
+ const appOfSite = /* @__PURE__ */ new Map();
122
+ const appOfMobile = /* @__PURE__ */ new Map();
123
+ for (const match of Object.values(input.apps)) {
124
+ if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);
125
+ if (match.mobile && !appOfMobile.has(match.mobile.id)) appOfMobile.set(match.mobile.id, match.app);
126
+ }
127
+ for (const page of facts.pages) if (ownSet.has(page.file) || page.setupFile !== null && ownSet.has(page.setupFile)) add(appOfSite.get(page.site) ?? page.site, {
128
+ route: page.route,
129
+ file: page.file,
130
+ type: "page"
131
+ });
132
+ for (const mobile of facts.mobile) for (const screen of mobile.screens) if (ownSet.has(screen.file)) add(appOfMobile.get(mobile.id) ?? mobile.id, {
133
+ route: screen.route,
134
+ file: screen.file,
135
+ type: "screen"
136
+ });
137
+ const sortedPages = {};
138
+ for (const app of Object.keys(pages).sort()) sortedPages[app] = (pages[app] ?? []).sort((left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file));
139
+ const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => step.files)));
140
+ return {
141
+ schemaVersion: 1,
142
+ feature: feature.id,
143
+ own,
144
+ borrowed,
145
+ routes,
146
+ pages: sortedPages,
147
+ unreached: own.filter((file) => !reached.has(file))
148
+ };
149
+ }
150
+ function compareVersions(left, right) {
151
+ const [leftWhole = 0, leftDecimal = 0] = left.split(".").map(Number);
152
+ const [rightWhole = 0, rightDecimal = 0] = right.split(".").map(Number);
153
+ return leftWhole - rightWhole || leftDecimal - rightDecimal;
154
+ }
155
+ function featuresIndex(written) {
156
+ const features = [];
157
+ for (const feature of [...written.features].sort((left, right) => left.id.localeCompare(right.id))) {
158
+ const readme = feature.readme;
159
+ if (readme === null) continue;
160
+ const releases = /* @__PURE__ */ new Map();
161
+ for (const entry of feature.changelog?.entries ?? []) {
162
+ if (entry.release === null || entry.date === null) continue;
163
+ const version = entry.version.value;
164
+ const known = releases.get(version);
165
+ if (!known || entry.date > known.date) releases.set(version, {
166
+ version,
167
+ release: entry.release,
168
+ date: entry.date
169
+ });
170
+ }
171
+ features.push({
172
+ id: feature.id,
173
+ title: readme.title.value,
174
+ status: readme.status.value,
175
+ version: readme.version.value,
176
+ updated: readme.updated.value,
177
+ apps: readme.apps.map((app) => app.value),
178
+ origin: readme.origin?.value ?? null,
179
+ flows: feature.flows.map((flow) => ({
180
+ id: flow.id.value,
181
+ status: flow.status.value,
182
+ since: flow.since.value
183
+ })),
184
+ releases: [...releases.values()].sort((left, right) => right.date.localeCompare(left.date) || compareVersions(right.version, left.version))
185
+ });
186
+ }
187
+ return {
188
+ schemaVersion: 1,
189
+ features
190
+ };
191
+ }
192
+ function taskNumber(id) {
193
+ const match = /^T-(\d+)$/.exec(id);
194
+ return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;
195
+ }
196
+ function taskSummary(task) {
197
+ return {
198
+ id: task.id.value,
199
+ title: task.heading?.value ?? task.id.value,
200
+ type: task.type.value,
201
+ status: task.status.value,
202
+ feature: task.feature?.value ?? null,
203
+ flow: task.flow?.value ?? null,
204
+ apps: task.apps.map((app) => app.value),
205
+ file: task.file,
206
+ shipped: task.shipped ? {
207
+ feature: task.shipped.value.feature,
208
+ version: task.shipped.value.version
209
+ } : null,
210
+ decisionNeeded: task.decisionNeeded
211
+ };
212
+ }
213
+ function tasksIndex(written) {
214
+ const sorted = [...written.tasks].sort((left, right) => taskNumber(left.id.value) - taskNumber(right.id.value) || left.id.value.localeCompare(right.id.value));
215
+ const open = sorted.filter((task) => task.folder === "open").map(taskSummary);
216
+ return {
217
+ schemaVersion: 1,
218
+ open,
219
+ waiting: open.filter((task) => task.status === "waiting for approval" || task.decisionNeeded !== null),
220
+ done: sorted.filter((task) => task.folder === "done").map(taskSummary)
221
+ };
222
+ }
223
+ /** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */
224
+ function buildCollectedFiles(input) {
225
+ const context = {
226
+ written: input.written,
227
+ facts: input.facts,
228
+ apps: input.apps,
229
+ graph: fileGraph(input.facts.files)
230
+ };
231
+ const byPath = new Map(input.facts.files.map((file) => [file.file, file]));
232
+ const features = {};
233
+ const flows = {};
234
+ for (const feature of [...input.written.features].sort((left, right) => left.id.localeCompare(right.id))) {
235
+ const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));
236
+ for (const map of maps) flows[map.ref] = map;
237
+ features[feature.id] = featureBookmap(feature, maps, input, byPath);
238
+ }
239
+ return {
240
+ features,
241
+ flows,
242
+ featuresIndex: featuresIndex(input.written),
243
+ tasksIndex: tasksIndex(input.written)
244
+ };
245
+ }
246
+ /** The per-file owner, borrowers and flows the book entries show. Pure. */
247
+ function annotationsFrom(input, collected, manifest) {
248
+ const flowsOf = /* @__PURE__ */ new Map();
249
+ for (const map of Object.values(collected.flows)) for (const step of map.steps) for (const file of step.files) {
250
+ const set = flowsOf.get(file) ?? /* @__PURE__ */ new Set();
251
+ set.add(map.ref);
252
+ flowsOf.set(file, set);
253
+ }
254
+ const files = {};
255
+ for (const file of input.facts.files) {
256
+ const ownership = input.ownership.files[file.file];
257
+ files[file.file] = {
258
+ feature: ownership?.owner ?? null,
259
+ borrowedBy: [...ownership?.borrowedBy ?? []],
260
+ flows: [...flowsOf.get(file.file) ?? []].sort()
261
+ };
262
+ }
263
+ return {
264
+ writtenHash: input.written.hash,
265
+ tests: { ...manifest.tests },
266
+ files
267
+ };
268
+ }
269
+
270
+ //#endregion
271
+ export { annotationsFrom, buildCollectedFiles, flowFileId };
272
+ //# sourceMappingURL=build.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"sourcesContent":["/**\n * Builds the book maps and the collected indexes in memory. Pure: reads only\n * its input.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookAnnotations, type BookManifest } from \"../contracts/book\";\nimport type {\n CollectedFiles,\n FeatureBookmap,\n FeaturesIndex,\n FlowBookmap,\n FlowBookmapCriterion,\n Ownership,\n TaskSummary,\n TasksIndex,\n} from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { ProofLine, ProofResult, TestResultsStore } from \"../contracts/test-results\";\nimport type {\n WrittenFeature,\n WrittenFlow,\n WrittenGrimoire,\n WrittenTask,\n} from \"../contracts/written\";\nimport { fileGraph } from \"../graph\";\nimport { toPosixPath } from \"../paths\";\nimport { criterionStatus } from \"../test-results\";\nimport { resolveStep, type StepContext } from \"./steps\";\n\n/** Everything the book maps are computed from. */\nexport type CollectedInput = {\n written: WrittenGrimoire;\n facts: BookFacts;\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n results: TestResultsStore | null;\n /** Test file → current sha256 (a result with another hash is stale). */\n testHashes: Record<string, string>;\n};\n\n/** The file name of a flow without `.md`: the name of its book map. */\nexport function flowFileId(flow: WrittenFlow): string {\n const name = toPosixPath(flow.file).split(\"/\").pop() ?? flow.id.value;\n\n return name.endsWith(\".md\") ? name.slice(0, -3) : name;\n}\n\n// ── Flow book maps ─────────────────────────────────────────────────────────\n\n/**\n * The result recorded for the test a proof line points at: same file and\n * line, else (the test moved) same name among the results whose line no\n * proof of that file claims.\n */\nfunction resultFor(\n proof: ProofLine,\n line: number,\n results: readonly ProofResult[],\n claimedLines: ReadonlySet<string>,\n): ProofResult | null {\n const file = toPosixPath(proof.at.file);\n const sameProof = (result: ProofResult): boolean =>\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion;\n const inFile = results.filter((result) => toPosixPath(result.testFile) === file);\n const atLine = inFile.filter((result) => result.line === line);\n const byLine = atLine.find(sameProof) ?? atLine[0];\n\n if (byLine) return byLine;\n\n const name = proof.test?.name ?? null;\n\n if (name === null) return null;\n\n const named = inFile.filter(\n (result) =>\n !claimedLines.has(`${file}:${result.line}`) &&\n (result.testName === name || result.testName.endsWith(` > ${name}`)),\n );\n\n return named.find(sameProof) ?? named[0] ?? null;\n}\n\nfunction flowCriteria(flow: WrittenFlow, input: CollectedInput): FlowBookmapCriterion[] {\n const results = input.results?.results ?? [];\n const claimedLines = new Set(\n input.proofs.flatMap((proof) =>\n proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`],\n ),\n );\n\n return flow.criteria.map((criterion) => {\n const tests = input.proofs\n .filter(\n (proof) =>\n proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null,\n )\n .map((proof) => {\n const line = proof.test?.line ?? proof.at.line;\n const file = toPosixPath(proof.at.file);\n const result = resultFor(proof, line, results, claimedLines);\n const currentHash = input.testHashes[file];\n const stale =\n result !== null && currentHash !== undefined && result.testFileHash !== currentHash;\n\n return {\n file,\n line,\n name: proof.test?.name ?? null,\n result: result?.outcome ?? (\"not-run\" as const),\n stale,\n };\n })\n .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);\n\n return {\n id: criterion.id,\n app: criterion.app,\n text: criterion.text,\n tests,\n status: criterionStatus(tests),\n };\n });\n}\n\nfunction shownBy(flow: WrittenFlow, written: WrittenGrimoire): FlowBookmap[\"shownBy\"] {\n const shown: FlowBookmap[\"shownBy\"] = [];\n\n for (const app of written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: \"layout\",\n id: layout.id,\n block: row.block,\n file: layout.file,\n });\n }\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: page.type,\n id: page.id,\n block: row.block,\n file: page.file,\n });\n }\n }\n }\n }\n\n return shown;\n}\n\nfunction flowBookmap(\n feature: WrittenFeature,\n flow: WrittenFlow,\n input: CollectedInput,\n context: StepContext,\n): FlowBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n flow: flowFileId(flow),\n ref: flow.ref,\n steps: flow.steps.map((step) => resolveStep(step, feature, context)),\n criteria: flowCriteria(flow, input),\n shownBy: shownBy(flow, input.written),\n };\n}\n\n// ── Feature book maps ──────────────────────────────────────────────────────\n\nfunction featureBookmap(\n feature: WrittenFeature,\n flows: readonly FlowBookmap[],\n input: CollectedInput,\n byPath: ReadonlyMap<string, BookFile>,\n): FeatureBookmap {\n const { ownership, facts } = input;\n const own = ownership.features[feature.id]?.own ?? [];\n const ownSet = new Set(own);\n\n // Own files importing each file, from one pass over the own files' imports (`own` is sorted, so each list is too).\n const importersOf = new Map<string, string[]>();\n\n for (const ownFile of own) {\n for (const entry of byPath.get(ownFile)?.imports ?? []) {\n if (entry.file === null) continue;\n\n const list = importersOf.get(entry.file) ?? [];\n\n if (list.at(-1) !== ownFile) list.push(ownFile);\n importersOf.set(entry.file, list);\n }\n }\n\n const borrowed: FeatureBookmap[\"borrowed\"] = (ownership.features[feature.id]?.borrowed ?? []).map(\n (file) => ({\n file,\n owner: ownership.files[file]?.owner ?? null,\n by: importersOf.get(file) ?? [],\n }),\n );\n\n const routes: FeatureBookmap[\"routes\"] = [];\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n const file =\n route.handlerFile !== null && ownSet.has(route.handlerFile)\n ? route.handlerFile\n : route.sourceFile !== null && ownSet.has(route.sourceFile)\n ? route.sourceFile\n : null;\n\n if (file !== null)\n routes.push({ method: route.method, path: route.path, name: route.name, file });\n }\n\n const pages: FeatureBookmap[\"pages\"] = {};\n const add = (app: string, item: FeatureBookmap[\"pages\"][string][number]): void => {\n (pages[app] ??= []).push(item);\n };\n const appOfSite = new Map<string, string>();\n const appOfMobile = new Map<string, string>();\n\n for (const match of Object.values(input.apps)) {\n if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);\n if (match.mobile && !appOfMobile.has(match.mobile.id))\n appOfMobile.set(match.mobile.id, match.app);\n }\n\n for (const page of facts.pages) {\n const owned = ownSet.has(page.file) || (page.setupFile !== null && ownSet.has(page.setupFile));\n\n if (owned)\n add(appOfSite.get(page.site) ?? page.site, {\n route: page.route,\n file: page.file,\n type: \"page\",\n });\n }\n\n for (const mobile of facts.mobile) {\n for (const screen of mobile.screens) {\n if (ownSet.has(screen.file)) {\n add(appOfMobile.get(mobile.id) ?? mobile.id, {\n route: screen.route,\n file: screen.file,\n type: \"screen\",\n });\n }\n }\n }\n\n const sortedPages: FeatureBookmap[\"pages\"] = {};\n\n for (const app of Object.keys(pages).sort()) {\n sortedPages[app] = (pages[app] ?? []).sort(\n (left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file),\n );\n }\n\n const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => step.files)));\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n own,\n borrowed,\n routes,\n pages: sortedPages,\n unreached: own.filter((file) => !reached.has(file)),\n };\n}\n\n// ── Indexes ────────────────────────────────────────────────────────────────\n\nfunction compareVersions(left: string, right: string): number {\n const [leftWhole = 0, leftDecimal = 0] = left.split(\".\").map(Number);\n const [rightWhole = 0, rightDecimal = 0] = right.split(\".\").map(Number);\n\n return leftWhole - rightWhole || leftDecimal - rightDecimal;\n}\n\nfunction featuresIndex(written: WrittenGrimoire): FeaturesIndex {\n const features: FeaturesIndex[\"features\"] = [];\n\n for (const feature of [...written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const readme = feature.readme;\n\n if (readme === null) continue;\n\n const releases = new Map<string, { version: string; release: string; date: string }>();\n\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null || entry.date === null) continue;\n\n const version = entry.version.value;\n const known = releases.get(version);\n\n if (!known || entry.date > known.date) {\n releases.set(version, { version, release: entry.release, date: entry.date });\n }\n }\n\n features.push({\n id: feature.id,\n title: readme.title.value,\n status: readme.status.value,\n version: readme.version.value,\n updated: readme.updated.value,\n apps: readme.apps.map((app) => app.value),\n origin: readme.origin?.value ?? null,\n flows: feature.flows.map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n })),\n releases: [...releases.values()].sort(\n (left, right) =>\n right.date.localeCompare(left.date) || compareVersions(right.version, left.version),\n ),\n });\n }\n\n return { schemaVersion: BOOK_SCHEMA_VERSION, features };\n}\n\nfunction taskNumber(id: string): number {\n const match = /^T-(\\d+)$/.exec(id);\n\n return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;\n}\n\nfunction taskSummary(task: WrittenTask): TaskSummary {\n return {\n id: task.id.value,\n title: task.heading?.value ?? task.id.value,\n type: task.type.value,\n status: task.status.value,\n feature: task.feature?.value ?? null,\n flow: task.flow?.value ?? null,\n apps: task.apps.map((app) => app.value),\n file: task.file,\n shipped: task.shipped\n ? { feature: task.shipped.value.feature, version: task.shipped.value.version }\n : null,\n decisionNeeded: task.decisionNeeded,\n };\n}\n\nfunction tasksIndex(written: WrittenGrimoire): TasksIndex {\n const sorted = [...written.tasks].sort(\n (left, right) =>\n taskNumber(left.id.value) - taskNumber(right.id.value) ||\n left.id.value.localeCompare(right.id.value),\n );\n const open = sorted.filter((task) => task.folder === \"open\").map(taskSummary);\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n open,\n waiting: open.filter(\n (task) => task.status === \"waiting for approval\" || task.decisionNeeded !== null,\n ),\n done: sorted.filter((task) => task.folder === \"done\").map(taskSummary),\n };\n}\n\n// ── Public ─────────────────────────────────────────────────────────────────\n\n/** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */\nexport function buildCollectedFiles(input: CollectedInput): CollectedFiles {\n const context: StepContext = {\n written: input.written,\n facts: input.facts,\n apps: input.apps,\n graph: fileGraph(input.facts.files),\n };\n const byPath = new Map(input.facts.files.map((file) => [file.file, file]));\n const features: CollectedFiles[\"features\"] = {};\n const flows: CollectedFiles[\"flows\"] = {};\n\n for (const feature of [...input.written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));\n\n for (const map of maps) flows[map.ref] = map;\n\n features[feature.id] = featureBookmap(feature, maps, input, byPath);\n }\n\n return {\n features,\n flows,\n featuresIndex: featuresIndex(input.written),\n tasksIndex: tasksIndex(input.written),\n };\n}\n\n/** The per-file owner, borrowers and flows the book entries show. Pure. */\nexport function annotationsFrom(\n input: CollectedInput,\n collected: CollectedFiles,\n manifest: Pick<BookManifest, \"tests\">,\n): BookAnnotations {\n const flowsOf = new Map<string, Set<string>>();\n\n for (const map of Object.values(collected.flows)) {\n for (const step of map.steps) {\n for (const file of step.files) {\n const set = flowsOf.get(file) ?? new Set<string>();\n set.add(map.ref);\n flowsOf.set(file, set);\n }\n }\n }\n\n const files: BookAnnotations[\"files\"] = {};\n\n for (const file of input.facts.files) {\n const ownership = input.ownership.files[file.file];\n\n files[file.file] = {\n feature: ownership?.owner ?? null,\n borrowedBy: [...(ownership?.borrowedBy ?? [])],\n flows: [...(flowsOf.get(file.file) ?? [])].sort(),\n };\n }\n\n return { writtenHash: input.written.hash, tests: { ...manifest.tests }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AO,CAAC,GAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,CAAE,CAAC,CAAC,KAAK;EAClD;CACF;CAEA,OAAO;EAAE,aAAa,MAAM,QAAQ;EAAM,OAAO,EAAE,GAAG,SAAS,MAAM;EAAG;CAAM;AAChF"}
@@ -0,0 +1,5 @@
1
+ import { normalizeRoutePath, routeMatches } from "./steps.mjs";
2
+ import { annotationsFrom, buildCollectedFiles, flowFileId } from "./build.mjs";
3
+ import { writeCollectedFiles } from "./write.mjs";
4
+
5
+ export { annotationsFrom, buildCollectedFiles, normalizeRoutePath, routeMatches, writeCollectedFiles };
@@ -0,0 +1,137 @@
1
+ import { importClosure } from "../graph/index.mjs";
2
+
3
+ //#region ../../packages/grimoire/src/bookmap/steps.ts
4
+ const NAMED_TYPES = /* @__PURE__ */ new Set([
5
+ "mail",
6
+ "job",
7
+ "event",
8
+ "notification"
9
+ ]);
10
+ /** A route path with params written one way (`:id` and `[id]` → `:id`) and no trailing `/`. */
11
+ function normalizeRoutePath(route) {
12
+ const trimmed = route.trim().replace(/\[\.\.\.([^\]]+)\]/g, ":$1").replace(/\[([^\]]+)\]/g, ":$1").replace(/\/+$/, "");
13
+ return trimmed === "" ? "/" : trimmed;
14
+ }
15
+ /**
16
+ * Whether a route answers `METHOD path`: paths compared after
17
+ * `normalizeRoutePath` (`:id` ≡ `[id]`, trailing `/` ignored), methods
18
+ * without regard to case, `ALL` on either side matching any method. The
19
+ * check, the book maps and `scry --route` all match this way.
20
+ */
21
+ function routeMatches(route, method, path) {
22
+ const routeMethod = route.method.toUpperCase();
23
+ const asked = method.toUpperCase();
24
+ return (routeMethod === asked || routeMethod === "ALL" || asked === "ALL") && normalizeRoutePath(route.path) === normalizeRoutePath(path);
25
+ }
26
+ function sortedUnique(files) {
27
+ return [...new Set(files)].sort();
28
+ }
29
+ const NOTHING = {
30
+ found: false,
31
+ entry: null,
32
+ files: []
33
+ };
34
+ function routeStep(step, facts, graph) {
35
+ if (facts.routes === null || step.route === null) return {
36
+ found: null,
37
+ entry: null,
38
+ files: []
39
+ };
40
+ const target = step.route;
41
+ const routes = facts.routes.filter((route) => routeMatches(route, target.method, target.path));
42
+ const first = routes[0];
43
+ if (!first) return NOTHING;
44
+ const files = /* @__PURE__ */ new Set();
45
+ for (const route of routes) {
46
+ if (route.handlerFile !== null) importClosure(graph, [route.handlerFile]).forEach((file) => files.add(file));
47
+ if (route.sourceFile !== null) files.add(route.sourceFile);
48
+ }
49
+ return {
50
+ found: true,
51
+ entry: first.handlerFile ?? first.sourceFile,
52
+ files: sortedUnique(files)
53
+ };
54
+ }
55
+ function pageStep(step, feature, facts, apps, graph) {
56
+ const wanted = normalizeRoutePath(step.target);
57
+ const entries = [];
58
+ const files = /* @__PURE__ */ new Set();
59
+ const appIds = step.app === null ? feature.readme?.apps.map((app) => app.value) ?? [] : [step.app];
60
+ for (const appId of appIds) {
61
+ const match = apps[appId];
62
+ if (!match) continue;
63
+ if (match.site) {
64
+ const siteId = match.site.id;
65
+ for (const page of facts.pages) {
66
+ if (page.site !== siteId || normalizeRoutePath(page.route) !== wanted) continue;
67
+ entries.push(page.file);
68
+ const start = page.setupFile === null ? [page.file] : [page.file, page.setupFile];
69
+ importClosure(graph, start).forEach((file) => files.add(file));
70
+ start.forEach((file) => files.add(file));
71
+ }
72
+ }
73
+ if (match.mobile) for (const screen of match.mobile.screens) {
74
+ if (normalizeRoutePath(screen.route) !== wanted) continue;
75
+ entries.push(screen.file);
76
+ importClosure(graph, [screen.file]).forEach((file) => files.add(file));
77
+ files.add(screen.file);
78
+ }
79
+ }
80
+ const entry = entries[0];
81
+ if (entry === void 0) return NOTHING;
82
+ return {
83
+ found: true,
84
+ entry,
85
+ files: sortedUnique(files)
86
+ };
87
+ }
88
+ function namedStep(step, facts, graph) {
89
+ const named = facts.named.filter((thing) => thing.type === step.type && thing.name === step.target);
90
+ const first = named[0];
91
+ if (!first) return NOTHING;
92
+ const files = /* @__PURE__ */ new Set();
93
+ for (const thing of named) {
94
+ if (thing.file === null) continue;
95
+ importClosure(graph, [thing.file]).forEach((file) => files.add(file));
96
+ files.add(thing.file);
97
+ }
98
+ return {
99
+ found: true,
100
+ entry: first.file,
101
+ files: sortedUnique(files)
102
+ };
103
+ }
104
+ function affectsStep(step, written) {
105
+ const target = step.affects;
106
+ if (target === null) return NOTHING;
107
+ const feature = written.features.find((candidate) => candidate.id === target.feature);
108
+ return {
109
+ found: feature !== void 0 && (target.flow === null || feature.flows.some((flow) => flow.id.value === target.flow)),
110
+ entry: null,
111
+ files: []
112
+ };
113
+ }
114
+ /** One step of a flow of `feature`, with what it matched in the book. */
115
+ function resolveStep(step, feature, context) {
116
+ let match;
117
+ if (step.type === "route") match = routeStep(step, context.facts, context.graph);
118
+ else if (step.type === "page") match = pageStep(step, feature, context.facts, context.apps, context.graph);
119
+ else if (NAMED_TYPES.has(step.type)) match = namedStep(step, context.facts, context.graph);
120
+ else if (step.type === "affects") match = affectsStep(step, context.written);
121
+ else match = {
122
+ found: null,
123
+ entry: null,
124
+ files: []
125
+ };
126
+ const target = step.app === null ? step.target : `${step.target} [${step.app}]`;
127
+ return {
128
+ index: step.index,
129
+ type: step.type,
130
+ target,
131
+ ...match
132
+ };
133
+ }
134
+
135
+ //#endregion
136
+ export { normalizeRoutePath, resolveStep, routeMatches };
137
+ //# sourceMappingURL=steps.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"steps.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/steps.ts"],"sourcesContent":["/**\n * The files behind each step of a flow: what a route, page, mail, job, event\n * or notification step reaches in the book.\n */\nimport type { BookFacts, BookNamedType } from \"../contracts/adapter\";\nimport type { FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenGrimoire, WrittenStep } from \"../contracts/written\";\nimport { importClosure, type FileGraph } from \"../graph\";\n\nconst NAMED_TYPES: ReadonlySet<string> = new Set<BookNamedType>([\n \"mail\",\n \"job\",\n \"event\",\n \"notification\",\n]);\n\n/** A route path with params written one way (`:id` and `[id]` → `:id`) and no trailing `/`. */\nexport function normalizeRoutePath(route: string): string {\n const withParams = route\n .trim()\n .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \":$1\")\n .replace(/\\[([^\\]]+)\\]/g, \":$1\");\n const trimmed = withParams.replace(/\\/+$/, \"\");\n\n return trimmed === \"\" ? \"/\" : trimmed;\n}\n\n/**\n * Whether a route answers `METHOD path`: paths compared after\n * `normalizeRoutePath` (`:id` ≡ `[id]`, trailing `/` ignored), methods\n * without regard to case, `ALL` on either side matching any method. The\n * check, the book maps and `scry --route` all match this way.\n */\nexport function routeMatches(\n route: { readonly method: string; readonly path: string },\n method: string,\n path: string,\n): boolean {\n const routeMethod = route.method.toUpperCase();\n const asked = method.toUpperCase();\n const methodMatches = routeMethod === asked || routeMethod === \"ALL\" || asked === \"ALL\";\n\n return methodMatches && normalizeRoutePath(route.path) === normalizeRoutePath(path);\n}\n\nfunction sortedUnique(files: Iterable<string>): string[] {\n return [...new Set(files)].sort();\n}\n\n/** What the step matched: its entry file and the files behind it. */\ntype StepMatch = Pick<FlowBookmapStep, \"found\" | \"entry\" | \"files\">;\n\nconst NOTHING: StepMatch = { found: false, entry: null, files: [] };\n\nfunction routeStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n if (facts.routes === null || step.route === null) return { found: null, entry: null, files: [] };\n\n const target = step.route;\n const routes = facts.routes.filter((route) => routeMatches(route, target.method, target.path));\n const first = routes[0];\n\n if (!first) return NOTHING;\n\n const files = new Set<string>();\n\n for (const route of routes) {\n if (route.handlerFile !== null)\n importClosure(graph, [route.handlerFile]).forEach((file) => files.add(file));\n if (route.sourceFile !== null) files.add(route.sourceFile);\n }\n\n return { found: true, entry: first.handlerFile ?? first.sourceFile, files: sortedUnique(files) };\n}\n\nfunction pageStep(\n step: WrittenStep,\n feature: WrittenFeature,\n facts: BookFacts,\n apps: Record<string, AppMatch>,\n graph: FileGraph,\n): StepMatch {\n const wanted = normalizeRoutePath(step.target);\n const entries: string[] = [];\n const files = new Set<string>();\n\n // `page /support [web-admin]` looks in that app only; without a scope, in the feature's apps.\n const appIds =\n step.app === null ? (feature.readme?.apps.map((app) => app.value) ?? []) : [step.app];\n\n for (const appId of appIds) {\n const match = apps[appId];\n\n if (!match) continue;\n\n if (match.site) {\n const siteId = match.site.id;\n\n for (const page of facts.pages) {\n if (page.site !== siteId || normalizeRoutePath(page.route) !== wanted) continue;\n\n entries.push(page.file);\n const start = page.setupFile === null ? [page.file] : [page.file, page.setupFile];\n importClosure(graph, start).forEach((file) => files.add(file));\n start.forEach((file) => files.add(file));\n }\n }\n\n if (match.mobile) {\n for (const screen of match.mobile.screens) {\n if (normalizeRoutePath(screen.route) !== wanted) continue;\n\n entries.push(screen.file);\n importClosure(graph, [screen.file]).forEach((file) => files.add(file));\n files.add(screen.file);\n }\n }\n }\n\n const entry = entries[0];\n\n if (entry === undefined) return NOTHING;\n\n return { found: true, entry, files: sortedUnique(files) };\n}\n\nfunction namedStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n const named = facts.named.filter(\n (thing) => thing.type === step.type && thing.name === step.target,\n );\n const first = named[0];\n\n if (!first) return NOTHING;\n\n const files = new Set<string>();\n\n for (const thing of named) {\n if (thing.file === null) continue;\n\n importClosure(graph, [thing.file]).forEach((file) => files.add(file));\n files.add(thing.file);\n }\n\n return { found: true, entry: first.file, files: sortedUnique(files) };\n}\n\nfunction affectsStep(step: WrittenStep, written: WrittenGrimoire): StepMatch {\n const target = step.affects;\n\n if (target === null) return NOTHING;\n\n const feature = written.features.find((candidate) => candidate.id === target.feature);\n const found =\n feature !== undefined &&\n (target.flow === null || feature.flows.some((flow) => flow.id.value === target.flow));\n\n return { found, entry: null, files: [] };\n}\n\n/** Everything the step resolver reads. */\nexport type StepContext = {\n written: WrittenGrimoire;\n facts: BookFacts;\n apps: Record<string, AppMatch>;\n graph: FileGraph;\n};\n\n/** One step of a flow of `feature`, with what it matched in the book. */\nexport function resolveStep(\n step: WrittenStep,\n feature: WrittenFeature,\n context: StepContext,\n): FlowBookmapStep {\n let match: StepMatch;\n\n if (step.type === \"route\") match = routeStep(step, context.facts, context.graph);\n else if (step.type === \"page\")\n match = pageStep(step, feature, context.facts, context.apps, context.graph);\n else if (NAMED_TYPES.has(step.type)) match = namedStep(step, context.facts, context.graph);\n else if (step.type === \"affects\") match = affectsStep(step, context.written);\n else match = { found: null, entry: null, files: [] };\n\n const target = step.app === null ? step.target : `${step.target} [${step.app}]`;\n\n return { index: step.index, type: step.type, target, ...match };\n}\n"],"mappings":";;;AAUA,MAAM,8BAAmC,IAAI,IAAmB;CAC9D;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,mBAAmB,OAAuB;CAKxD,MAAM,UAJa,MAChB,KAAK,CAAC,CACN,QAAQ,uBAAuB,KAAK,CAAC,CACrC,QAAQ,iBAAiB,KACH,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE7C,OAAO,YAAY,KAAK,MAAM;AAChC;;;;;;;AAQA,SAAgB,aACd,OACA,QACA,MACS;CACT,MAAM,cAAc,MAAM,OAAO,YAAY;CAC7C,MAAM,QAAQ,OAAO,YAAY;CAGjC,QAFsB,gBAAgB,SAAS,gBAAgB,SAAS,UAAU,UAE1D,mBAAmB,MAAM,IAAI,MAAM,mBAAmB,IAAI;AACpF;AAEA,SAAS,aAAa,OAAmC;CACvD,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK;AAClC;AAKA,MAAM,UAAqB;CAAE,OAAO;CAAO,OAAO;CAAM,OAAO,CAAC;AAAE;AAElE,SAAS,UAAU,MAAmB,OAAkB,OAA6B;CACnF,IAAI,MAAM,WAAW,QAAQ,KAAK,UAAU,MAAM,OAAO;EAAE,OAAO;EAAM,OAAO;EAAM,OAAO,CAAC;CAAE;CAE/F,MAAM,SAAS,KAAK;CACpB,MAAM,SAAS,MAA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J,IAAI,KAAK,SAAS,SAAS,QAAQ,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK;MAC1E,IAAI,KAAK,SAAS,QACrB,QAAQ,SAAS,MAAM,SAAS,QAAQ,OAAO,QAAQ,MAAM,QAAQ,KAAK;MACvE,IAAI,YAAY,IAAI,KAAK,IAAI,GAAG,QAAQ,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK;MACpF,IAAI,KAAK,SAAS,WAAW,QAAQ,YAAY,MAAM,QAAQ,OAAO;MACtE,QAAQ;EAAE,OAAO;EAAM,OAAO;EAAM,OAAO,CAAC;CAAE;CAEnD,MAAM,SAAS,KAAK,QAAQ,OAAO,KAAK,SAAS,GAAG,KAAK,OAAO,IAAI,KAAK,IAAI;CAE7E,OAAO;EAAE,OAAO,KAAK;EAAO,MAAM,KAAK;EAAM;EAAQ,GAAG;CAAM;AAChE"}
@@ -0,0 +1,19 @@
1
+ import { CollectedFiles } from "../contracts/bookmap.mjs";
2
+ //#region ../../packages/grimoire/src/bookmap/write.d.ts
3
+ /**
4
+ * Write the collected files under `grimoire/features` and `grimoire/tasks`,
5
+ * only those whose content changed, and remove book maps of features and flows
6
+ * that no longer exist.
7
+ *
8
+ * An index with no entries is written only when its folder exists, so a
9
+ * project without written files gets no `grimoire/features` or
10
+ * `grimoire/tasks` folder.
11
+ *
12
+ * @returns Project-relative files written and removed, sorted.
13
+ */
14
+ export declare function writeCollectedFiles(root: string, collected: CollectedFiles): Promise<{
15
+ written: string[];
16
+ removed: string[];
17
+ }>;
18
+ //#endregion
19
+ //# sourceMappingURL=write.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/write.ts"],"mappings":";;;;;;;;;;;;;wBAiGsB,oBACpB,cACA,WAAW,iBACV;EAAU;EAAmB"}
@@ -0,0 +1,118 @@
1
+ import { GRIMOIRE_PATHS, featureBookmapPath, flowBookmapPath } from "../paths/index.mjs";
2
+ import path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ import { mkdir, readFile, readdir, rename, rm, rmdir, writeFile } from "node:fs/promises";
5
+ import { existsSync } from "node:fs";
6
+
7
+ //#region ../../packages/grimoire/src/bookmap/write.ts
8
+ /**
9
+ * Writes the collected files. Warlock writes only `index.json` and
10
+ * `*.bookmap.json` files here, never a file an agent wrote.
11
+ */
12
+ function absolute(root, file) {
13
+ return path.join(root, ...file.split("/"));
14
+ }
15
+ function json(value) {
16
+ return `${JSON.stringify(value, null, 2)}\n`;
17
+ }
18
+ async function readText(file) {
19
+ try {
20
+ return await readFile(file, "utf8");
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ /** Write through a temporary file and a rename, so a reader (the devtools tab) never sees half a file. */
26
+ async function writeAtomic(target, content) {
27
+ const temporary = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
28
+ try {
29
+ await writeFile(temporary, content);
30
+ await rename(temporary, target);
31
+ } catch (error) {
32
+ await rm(temporary, { force: true });
33
+ throw error;
34
+ }
35
+ }
36
+ async function listDir(directory) {
37
+ try {
38
+ return (await readdir(directory, { withFileTypes: true })).map((entry) => ({
39
+ name: entry.name,
40
+ directory: entry.isDirectory()
41
+ }));
42
+ } catch {
43
+ return [];
44
+ }
45
+ }
46
+ /** Book map files on disk: `features/<f>/bookmap.json` and `features/<f>/flows/<flow>.bookmap.json`. */
47
+ async function existingBookmaps(root) {
48
+ const found = [];
49
+ const featuresDir = absolute(root, GRIMOIRE_PATHS.features);
50
+ for (const feature of await listDir(featuresDir)) {
51
+ if (!feature.directory) continue;
52
+ const featureDir = path.join(featuresDir, feature.name);
53
+ for (const entry of await listDir(featureDir)) if (!entry.directory && entry.name === "bookmap.json") found.push(featureBookmapPath(feature.name));
54
+ for (const entry of await listDir(path.join(featureDir, "flows"))) if (!entry.directory && entry.name.endsWith(".bookmap.json")) found.push(flowBookmapPath(feature.name, entry.name.slice(0, -13)));
55
+ }
56
+ return found;
57
+ }
58
+ /** Remove a folder when it is empty (a deleted feature leaves only Warlock's files). */
59
+ async function removeIfEmpty(directory) {
60
+ if ((await listDir(directory)).length > 0) return;
61
+ try {
62
+ await rmdir(directory);
63
+ } catch {}
64
+ }
65
+ /**
66
+ * Write the collected files under `grimoire/features` and `grimoire/tasks`,
67
+ * only those whose content changed, and remove book maps of features and flows
68
+ * that no longer exist.
69
+ *
70
+ * An index with no entries is written only when its folder exists, so a
71
+ * project without written files gets no `grimoire/features` or
72
+ * `grimoire/tasks` folder.
73
+ *
74
+ * @returns Project-relative files written and removed, sorted.
75
+ */
76
+ async function writeCollectedFiles(root, collected) {
77
+ const wanted = /* @__PURE__ */ new Map();
78
+ for (const map of Object.values(collected.features)) wanted.set(featureBookmapPath(map.feature), json(map));
79
+ for (const map of Object.values(collected.flows)) wanted.set(flowBookmapPath(map.feature, map.flow), json(map));
80
+ const indexes = [[
81
+ GRIMOIRE_PATHS.featuresIndex,
82
+ collected.featuresIndex,
83
+ collected.featuresIndex.features.length + Object.keys(collected.features).length > 0
84
+ ], [
85
+ GRIMOIRE_PATHS.tasksIndex,
86
+ collected.tasksIndex,
87
+ collected.tasksIndex.open.length + collected.tasksIndex.done.length > 0
88
+ ]];
89
+ for (const [file, value, hasEntries] of indexes) if (hasEntries || existsSync(path.dirname(absolute(root, file)))) wanted.set(file, json(value));
90
+ const written = [];
91
+ const removed = [];
92
+ for (const [file, content] of wanted) {
93
+ const target = absolute(root, file);
94
+ if (await readText(target) === content) continue;
95
+ await mkdir(path.dirname(target), { recursive: true });
96
+ await writeAtomic(target, content);
97
+ written.push(file);
98
+ }
99
+ for (const file of await existingBookmaps(root)) {
100
+ if (wanted.has(file)) continue;
101
+ const target = absolute(root, file);
102
+ await rm(target, { force: true });
103
+ removed.push(file);
104
+ if (file.endsWith(".bookmap.json")) {
105
+ const flowsDir = path.dirname(target);
106
+ await removeIfEmpty(flowsDir);
107
+ await removeIfEmpty(path.dirname(flowsDir));
108
+ } else await removeIfEmpty(path.dirname(target));
109
+ }
110
+ return {
111
+ written: written.sort(),
112
+ removed: removed.sort()
113
+ };
114
+ }
115
+
116
+ //#endregion
117
+ export { writeCollectedFiles };
118
+ //# sourceMappingURL=write.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/write.ts"],"sourcesContent":["/**\n * Writes the collected files. Warlock writes only `index.json` and\n * `*.bookmap.json` files here, never a file an agent wrote.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readdir, readFile, rename, rm, rmdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { CollectedFiles } from \"../contracts/bookmap\";\nimport { featureBookmapPath, flowBookmapPath, GRIMOIRE_PATHS } from \"../paths\";\n\nfunction absolute(root: string, file: string): string {\n return path.join(root, ...file.split(\"/\"));\n}\n\nfunction json(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nasync function readText(file: string): Promise<string | null> {\n try {\n return await readFile(file, \"utf8\");\n } catch {\n return null;\n }\n}\n\n/** Write through a temporary file and a rename, so a reader (the devtools tab) never sees half a file. */\nasync function writeAtomic(target: string, content: string): Promise<void> {\n const temporary = `${target}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`;\n\n try {\n await writeFile(temporary, content);\n await rename(temporary, target);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nasync function listDir(directory: string): Promise<{ name: string; directory: boolean }[]> {\n try {\n const entries = await readdir(directory, { withFileTypes: true });\n\n return entries.map((entry) => ({ name: entry.name, directory: entry.isDirectory() }));\n } catch {\n return [];\n }\n}\n\n/** Book map files on disk: `features/<f>/bookmap.json` and `features/<f>/flows/<flow>.bookmap.json`. */\nasync function existingBookmaps(root: string): Promise<string[]> {\n const found: string[] = [];\n const featuresDir = absolute(root, GRIMOIRE_PATHS.features);\n\n for (const feature of await listDir(featuresDir)) {\n if (!feature.directory) continue;\n\n const featureDir = path.join(featuresDir, feature.name);\n\n for (const entry of await listDir(featureDir)) {\n if (!entry.directory && entry.name === \"bookmap.json\")\n found.push(featureBookmapPath(feature.name));\n }\n\n for (const entry of await listDir(path.join(featureDir, \"flows\"))) {\n if (!entry.directory && entry.name.endsWith(\".bookmap.json\")) {\n found.push(flowBookmapPath(feature.name, entry.name.slice(0, -\".bookmap.json\".length)));\n }\n }\n }\n\n return found;\n}\n\n/** Remove a folder when it is empty (a deleted feature leaves only Warlock's files). */\nasync function removeIfEmpty(directory: string): Promise<void> {\n if ((await listDir(directory)).length > 0) return;\n\n try {\n await rmdir(directory);\n } catch {\n // Another process wrote into it, or it is gone already.\n }\n}\n\n/**\n * Write the collected files under `grimoire/features` and `grimoire/tasks`,\n * only those whose content changed, and remove book maps of features and flows\n * that no longer exist.\n *\n * An index with no entries is written only when its folder exists, so a\n * project without written files gets no `grimoire/features` or\n * `grimoire/tasks` folder.\n *\n * @returns Project-relative files written and removed, sorted.\n */\nexport async function writeCollectedFiles(\n root: string,\n collected: CollectedFiles,\n): Promise<{ written: string[]; removed: string[] }> {\n const wanted = new Map<string, string>();\n\n for (const map of Object.values(collected.features)) {\n wanted.set(featureBookmapPath(map.feature), json(map));\n }\n\n for (const map of Object.values(collected.flows)) {\n wanted.set(flowBookmapPath(map.feature, map.flow), json(map));\n }\n\n const indexes: [string, unknown, boolean][] = [\n [\n GRIMOIRE_PATHS.featuresIndex,\n collected.featuresIndex,\n collected.featuresIndex.features.length + Object.keys(collected.features).length > 0,\n ],\n [\n GRIMOIRE_PATHS.tasksIndex,\n collected.tasksIndex,\n collected.tasksIndex.open.length + collected.tasksIndex.done.length > 0,\n ],\n ];\n\n for (const [file, value, hasEntries] of indexes) {\n if (hasEntries || existsSync(path.dirname(absolute(root, file)))) wanted.set(file, json(value));\n }\n\n const written: string[] = [];\n const removed: string[] = [];\n\n for (const [file, content] of wanted) {\n const target = absolute(root, file);\n\n if ((await readText(target)) === content) continue;\n\n await mkdir(path.dirname(target), { recursive: true });\n await writeAtomic(target, content);\n written.push(file);\n }\n\n for (const file of await existingBookmaps(root)) {\n if (wanted.has(file)) continue;\n\n const target = absolute(root, file);\n\n await rm(target, { force: true });\n removed.push(file);\n\n if (file.endsWith(\".bookmap.json\")) {\n const flowsDir = path.dirname(target);\n await removeIfEmpty(flowsDir);\n await removeIfEmpty(path.dirname(flowsDir));\n } else {\n await removeIfEmpty(path.dirname(target));\n }\n }\n\n return { written: written.sort(), removed: removed.sort() };\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAS,SAAS,MAAc,MAAsB;CACpD,OAAO,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC;AAC3C;AAEA,SAAS,KAAK,OAAwB;CACpC,OAAO,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE;AAC3C;AAEA,eAAe,SAAS,MAAsC;CAC5D,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAe,YAAY,QAAgB,SAAgC;CACzE,MAAM,YAAY,GAAG,OAAO,GAAG,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CAE7E,IAAI;EACF,MAAM,UAAU,WAAW,OAAO;EAClC,MAAM,OAAO,WAAW,MAAM;CAChC,SAAS,OAAO;EACd,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;EACnC,MAAM;CACR;AACF;AAEA,eAAe,QAAQ,WAAoE;CACzF,IAAI;EAGF,QAAO,MAFe,QAAQ,WAAW,EAAE,eAAe,KAAK,CAAC,EAElD,CAAC,KAAK,WAAW;GAAE,MAAM,MAAM;GAAM,WAAW,MAAM,YAAY;EAAE,EAAE;CACtF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,eAAe,iBAAiB,MAAiC;CAC/D,MAAM,QAAkB,CAAC;CACzB,MAAM,cAAc,SAAS,MAAM,eAAe,QAAQ;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WAAW,KAAK,QAAQ,SAAS,MAAM,IAAI,CAAC,CAAC,GAAG,OAAO,IAAI,MAAM,KAAK,KAAK,CAAC;CAGhG,MAAM,UAAoB,CAAC;CAC3B,MAAM,UAAoB,CAAC;CAE3B,KAAK,MAAM,CAAC,MAAM,YAAY,QAAQ;EACpC,MAAM,SAAS,SAAS,MAAM,IAAI;EAElC,IAAK,MAAM,SAAS,MAAM,MAAO,SAAS;EAE1C,MAAM,MAAM,KAAK,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EACrD,MAAM,YAAY,QAAQ,OAAO;EACjC,QAAQ,KAAK,IAAI;CACnB;CAEA,KAAK,MAAM,QAAQ,MAAM,iBAAiB,IAAI,GAAG;EAC/C,IAAI,OAAO,IAAI,IAAI,GAAG;EAEtB,MAAM,SAAS,SAAS,MAAM,IAAI;EAElC,MAAM,GAAG,QAAQ,EAAE,OAAO,KAAK,CAAC;EAChC,QAAQ,KAAK,IAAI;EAEjB,IAAI,KAAK,SAAS,eAAe,GAAG;GAClC,MAAM,WAAW,KAAK,QAAQ,MAAM;GACpC,MAAM,cAAc,QAAQ;GAC5B,MAAM,cAAc,KAAK,QAAQ,QAAQ,CAAC;EAC5C,OACE,MAAM,cAAc,KAAK,QAAQ,MAAM,CAAC;CAE5C;CAEA,OAAO;EAAE,SAAS,QAAQ,KAAK;EAAG,SAAS,QAAQ,KAAK;CAAE;AAC5D"}
@@ -0,0 +1,7 @@
1
+ import { GrimoireCheckReport } from "../contracts/findings.mjs";
2
+ import { GrimoireSnapshot } from "../contracts/snapshot.mjs";
3
+ //#region ../../packages/grimoire/src/check/check-grimoire.d.ts
4
+ /** Run every rule over a snapshot. Pure; never writes. */
5
+ export declare function checkGrimoire(snapshot: GrimoireSnapshot): GrimoireCheckReport;
6
+ //#endregion
7
+ //# sourceMappingURL=check-grimoire.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check-grimoire.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/check/check-grimoire.ts"],"mappings":";;;;wBA8BgB,cAAc,UAAU,mBAAmB"}