@warlock.js/grimoire 5.58.0 → 5.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/esm/apps/check-apps.mjs +11 -5
- package/esm/apps/check-apps.mjs.map +1 -1
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs.map +1 -1
- package/esm/bookmap/build.d.mts.map +1 -1
- package/esm/bookmap/build.mjs +5 -3
- package/esm/bookmap/build.mjs.map +1 -1
- package/esm/bookmap/steps.mjs +34 -3
- package/esm/bookmap/steps.mjs.map +1 -1
- package/esm/contracts/adapter.d.mts +22 -1
- package/esm/contracts/adapter.d.mts.map +1 -1
- package/esm/contracts/scry.d.mts +26 -6
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/contracts/snapshot.d.mts +3 -1
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/devtools/data.mjs +23 -3
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/feature-map.mjs +149 -0
- package/esm/devtools/feature-map.mjs.map +1 -0
- package/esm/devtools/index.d.mts +2 -2
- package/esm/devtools/index.mjs +30 -9
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/product-map.d.mts.map +1 -1
- package/esm/devtools/product-map.mjs +82 -7
- package/esm/devtools/product-map.mjs.map +1 -1
- package/esm/devtools/site.d.mts +43 -1
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +111 -15
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +15 -2
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/index.d.mts +3 -3
- package/esm/ownership/index.d.mts.map +1 -1
- package/esm/ownership/index.mjs +60 -1
- package/esm/ownership/index.mjs.map +1 -1
- package/esm/scry/compact.mjs +2 -1
- package/esm/scry/compact.mjs.map +1 -1
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +12 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +147 -23
- package/esm/scry/query.mjs.map +1 -1
- package/esm/test-results/index.d.mts.map +1 -1
- package/esm/test-results/index.mjs.map +1 -1
- package/esm/warlock/actions.mjs +15 -7
- package/esm/warlock/actions.mjs.map +1 -1
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +36 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/commands.mjs +7 -2
- package/esm/warlock/commands.mjs.map +1 -1
- package/esm/warlock/logo.mjs +12 -0
- package/esm/warlock/logo.mjs.map +1 -0
- package/esm/warlock/mcp-tools.mjs +6 -6
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/workspace/cache.mjs +194 -0
- package/esm/workspace/cache.mjs.map +1 -0
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +3 -1
- package/esm/workspace/index.mjs.map +1 -1
- package/llms-full.txt +32 -9
- package/package.json +3 -3
- package/skills/record-a-change/SKILL.md +2 -0
- package/skills/use-the-grimoire/SKILL.md +30 -9
- package/ui/grimoire-static.js +57 -6
- package/ui/grimoire-view.js +1289 -310
- package/ui/grimoire.css +583 -2
- package/ui/product-map.css +157 -8
- package/ui/product-map.js +507 -59
package/esm/scry/query.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"query.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"mappings":";;;;;;;;wBA6zBgB,KAAK,UAAU,kBAAkB,OAAO,YAAY"}
|
package/esm/scry/query.mjs
CHANGED
|
@@ -255,20 +255,29 @@ function emptyFeatureBookmap(feature) {
|
|
|
255
255
|
function scryFeature(snapshot, query) {
|
|
256
256
|
const feature = writtenFeature(snapshot, query.feature);
|
|
257
257
|
if (feature.readme === null) throw new GrimoireError("GR9003", `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`);
|
|
258
|
+
const findings = findingsFor(snapshot, (finding) => finding.subject.feature === feature.id || (finding.subject.flow ?? "").startsWith(`${feature.id}/`));
|
|
258
259
|
return {
|
|
259
260
|
type: "feature",
|
|
260
261
|
...notesOf(snapshot, false),
|
|
261
262
|
readme: feature.readme,
|
|
262
|
-
flows: [...feature.flows].sort((left, right) => byText(left.id.value, right.id.value)).map((flow) =>
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
263
|
+
flows: [...feature.flows].sort((left, right) => byText(left.id.value, right.id.value)).map((flow) => {
|
|
264
|
+
const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];
|
|
265
|
+
return {
|
|
266
|
+
id: flow.id.value,
|
|
267
|
+
status: flow.status.value,
|
|
268
|
+
since: flow.since.value,
|
|
269
|
+
heading: flow.heading?.value ?? null,
|
|
270
|
+
steps: flow.steps.length,
|
|
271
|
+
cases: flow.cases.length,
|
|
272
|
+
criteria: flow.criteria.length,
|
|
273
|
+
tested: criteria.filter((criterion) => criterion.tests.length > 0).length,
|
|
274
|
+
findings: findings.filter((finding) => !finding.expected && finding.subject.flow === flow.ref).length
|
|
275
|
+
};
|
|
276
|
+
}),
|
|
268
277
|
bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),
|
|
269
278
|
changes: (feature.changelog?.entries ?? []).slice(0, 10),
|
|
270
279
|
tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),
|
|
271
|
-
findings
|
|
280
|
+
findings
|
|
272
281
|
};
|
|
273
282
|
}
|
|
274
283
|
function scryFlow(snapshot, query) {
|
|
@@ -316,6 +325,50 @@ function lastSegment(id) {
|
|
|
316
325
|
function slug(text) {
|
|
317
326
|
return words(text).split(" ").join("-");
|
|
318
327
|
}
|
|
328
|
+
/** The searchable written text of a flow: summary, who, story, cases, criteria. */
|
|
329
|
+
function flowBody(flow) {
|
|
330
|
+
return [
|
|
331
|
+
...flow.summary === null ? [] : [{
|
|
332
|
+
label: "summary",
|
|
333
|
+
text: flow.summary
|
|
334
|
+
}],
|
|
335
|
+
{
|
|
336
|
+
label: "who",
|
|
337
|
+
text: flow.who.value
|
|
338
|
+
},
|
|
339
|
+
...flow.story.map((step) => ({
|
|
340
|
+
label: `story ${step.index}`,
|
|
341
|
+
text: step.text
|
|
342
|
+
})),
|
|
343
|
+
...flow.cases.map((item) => ({
|
|
344
|
+
label: `case ${item.question}`,
|
|
345
|
+
text: `${item.question} ${item.answer} ${item.criteria.join(" ")}`
|
|
346
|
+
})),
|
|
347
|
+
...flow.criteria.map((item) => ({
|
|
348
|
+
label: item.id,
|
|
349
|
+
text: `${item.id} ${item.text}`
|
|
350
|
+
}))
|
|
351
|
+
];
|
|
352
|
+
}
|
|
353
|
+
/** The searchable written text of a feature: summary, why, audience. */
|
|
354
|
+
function featureBody(feature) {
|
|
355
|
+
const readme = feature.readme;
|
|
356
|
+
if (readme === null) return [];
|
|
357
|
+
return [
|
|
358
|
+
...readme.summary === null ? [] : [{
|
|
359
|
+
label: "summary",
|
|
360
|
+
text: readme.summary
|
|
361
|
+
}],
|
|
362
|
+
...readme.why === null ? [] : [{
|
|
363
|
+
label: "why",
|
|
364
|
+
text: readme.why
|
|
365
|
+
}],
|
|
366
|
+
...readme.audience.map((item) => ({
|
|
367
|
+
label: "audience",
|
|
368
|
+
text: item.value
|
|
369
|
+
}))
|
|
370
|
+
];
|
|
371
|
+
}
|
|
319
372
|
function candidates(snapshot) {
|
|
320
373
|
const facts = snapshot.book.facts;
|
|
321
374
|
const list = [];
|
|
@@ -323,12 +376,14 @@ function candidates(snapshot) {
|
|
|
323
376
|
list.push({
|
|
324
377
|
type: "feature",
|
|
325
378
|
id: feature.id,
|
|
326
|
-
detail: feature.readme?.title.value ?? null
|
|
379
|
+
detail: feature.readme?.title.value ?? null,
|
|
380
|
+
body: featureBody(feature)
|
|
327
381
|
});
|
|
328
382
|
for (const flow of feature.flows) list.push({
|
|
329
383
|
type: "flow",
|
|
330
384
|
id: flow.ref,
|
|
331
|
-
detail: flow.heading?.value ?? null
|
|
385
|
+
detail: flow.heading?.value ?? null,
|
|
386
|
+
body: flowBody(flow)
|
|
332
387
|
});
|
|
333
388
|
}
|
|
334
389
|
for (const app of snapshot.written.apps) {
|
|
@@ -403,25 +458,89 @@ function isSubsequence(needle, text) {
|
|
|
403
458
|
}
|
|
404
459
|
/** Shortest query that may match by fuzzy (in-order letters), so short queries stay precise. */
|
|
405
460
|
const FUZZY_MIN = 4;
|
|
461
|
+
/** Added to the score of written content (features, flows) so it ranks above files and exports of the same match. */
|
|
462
|
+
const WRITTEN_BOOST = 2;
|
|
463
|
+
/** Whether a word list holds a word that is, or starts with, every token (a short token must equal a word). */
|
|
464
|
+
function partMatches(partWords, tokens) {
|
|
465
|
+
return tokens.every((token) => partWords.some((word) => token.length >= 3 ? word.startsWith(token) : word === token));
|
|
466
|
+
}
|
|
467
|
+
/** The first body part holding every token, as `label: text`, or `null`. */
|
|
468
|
+
function bodyMatch(candidate, tokens, base) {
|
|
469
|
+
for (const part of candidate.body ?? []) {
|
|
470
|
+
const partWords = words(part.text).split(" ");
|
|
471
|
+
const rest = tokens.filter((token) => !base.includes(token));
|
|
472
|
+
if (rest.length > 0 && partMatches(partWords, rest)) {
|
|
473
|
+
const text = part.text.replace(/\s+/g, " ").trim();
|
|
474
|
+
return `${part.label}: ${text.length > 90 ? `${text.slice(0, 89)}…` : text}`;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
406
479
|
/**
|
|
407
480
|
* Score of a candidate for the query words, or 0 when it does not match. From best
|
|
408
481
|
* to worst: exact name or path (7), prefix (6), whole-word match (5), substring of
|
|
409
|
-
* the name or path (4), the words found only in the detail (3),
|
|
482
|
+
* the name or path (4), the words found only in the detail or in written text (3),
|
|
483
|
+
* fuzzy (2). Features and flows add {@link WRITTEN_BOOST} to a match.
|
|
410
484
|
*/
|
|
411
485
|
function scoreOf(candidate, query, tokens) {
|
|
412
486
|
const id = words(candidate.type === "export" ? candidate.id.split("#")[1] ?? candidate.id : candidate.id);
|
|
413
487
|
const last = words(lastSegment(candidate.id));
|
|
414
|
-
const
|
|
415
|
-
|
|
488
|
+
const base = `${id} ${words(candidate.detail ?? "")}`;
|
|
489
|
+
const boost = candidate.type === "feature" || candidate.type === "flow" ? WRITTEN_BOOST : 0;
|
|
490
|
+
if (!tokens.every((token) => base.includes(token))) {
|
|
491
|
+
const matched = bodyMatch(candidate, tokens, base);
|
|
492
|
+
if (matched !== null) return {
|
|
493
|
+
score: 3 + boost,
|
|
494
|
+
matched
|
|
495
|
+
};
|
|
416
496
|
const squeezed = id.replace(/ /g, "");
|
|
417
|
-
return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed)) ?
|
|
497
|
+
return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed)) ? {
|
|
498
|
+
score: 2,
|
|
499
|
+
matched: null
|
|
500
|
+
} : {
|
|
501
|
+
score: 0,
|
|
502
|
+
matched: null
|
|
503
|
+
};
|
|
418
504
|
}
|
|
419
|
-
if (id === query || last === query) return
|
|
420
|
-
|
|
505
|
+
if (id === query || last === query) return {
|
|
506
|
+
score: 7 + boost,
|
|
507
|
+
matched: null
|
|
508
|
+
};
|
|
509
|
+
if (id.startsWith(query) || last.startsWith(query)) return {
|
|
510
|
+
score: 6 + boost,
|
|
511
|
+
matched: null
|
|
512
|
+
};
|
|
421
513
|
const idWords = id.split(" ");
|
|
422
|
-
if (tokens.every((token) => idWords.includes(token))) return
|
|
423
|
-
|
|
424
|
-
|
|
514
|
+
if (tokens.every((token) => idWords.includes(token))) return {
|
|
515
|
+
score: 5 + boost,
|
|
516
|
+
matched: null
|
|
517
|
+
};
|
|
518
|
+
if (tokens.every((token) => id.includes(token))) return {
|
|
519
|
+
score: 4 + boost,
|
|
520
|
+
matched: null
|
|
521
|
+
};
|
|
522
|
+
return {
|
|
523
|
+
score: 3 + boost,
|
|
524
|
+
matched: null
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** The most hits of features and flows set aside before files and exports fill the list (a share of the limit). */
|
|
528
|
+
const WRITTEN_SHARE = .75;
|
|
529
|
+
const byRank = (left, right) => right.score - left.score || TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) || byText(left.id, right.id);
|
|
530
|
+
/**
|
|
531
|
+
* The hits to return: the best features and flows first (up to a share of the
|
|
532
|
+
* limit, so files and exports never push matching written content out), then
|
|
533
|
+
* the best of the rest. Grouped by type in {@link TYPE_ORDER}, best first.
|
|
534
|
+
*/
|
|
535
|
+
function pickHits(hits, limit) {
|
|
536
|
+
const ranked = [...hits].sort(byRank);
|
|
537
|
+
const written = ranked.filter((hit) => hit.type === "feature" || hit.type === "flow").slice(0, Math.max(1, Math.ceil(limit * WRITTEN_SHARE)));
|
|
538
|
+
const chosen = new Set(written);
|
|
539
|
+
for (const hit of ranked) {
|
|
540
|
+
if (chosen.size >= limit) break;
|
|
541
|
+
chosen.add(hit);
|
|
542
|
+
}
|
|
543
|
+
return [...chosen].slice(0, limit).sort((left, right) => TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) || right.score - left.score || byText(left.id, right.id));
|
|
425
544
|
}
|
|
426
545
|
function scrySearch(snapshot, query) {
|
|
427
546
|
const text = words(query.text);
|
|
@@ -433,18 +552,23 @@ function scrySearch(snapshot, query) {
|
|
|
433
552
|
const key = `${candidate.type} ${candidate.id}`;
|
|
434
553
|
if (seen.has(key)) continue;
|
|
435
554
|
seen.add(key);
|
|
436
|
-
const score = scoreOf(candidate, text, tokens);
|
|
555
|
+
const { score, matched } = scoreOf(candidate, text, tokens);
|
|
437
556
|
if (score > 0) hits.push({
|
|
438
|
-
|
|
439
|
-
|
|
557
|
+
type: candidate.type,
|
|
558
|
+
id: candidate.id,
|
|
559
|
+
detail: candidate.detail,
|
|
560
|
+
score,
|
|
561
|
+
...matched === null ? {} : { matched }
|
|
440
562
|
});
|
|
441
563
|
}
|
|
442
|
-
|
|
564
|
+
const counts = {};
|
|
565
|
+
for (const hit of hits) counts[hit.type] = (counts[hit.type] ?? 0) + 1;
|
|
443
566
|
return {
|
|
444
567
|
type: "search",
|
|
445
568
|
...notesOf(snapshot, false),
|
|
446
569
|
text: query.text,
|
|
447
|
-
|
|
570
|
+
counts,
|
|
571
|
+
hits: pickHits(hits, query.limit ?? 20)
|
|
448
572
|
};
|
|
449
573
|
}
|
|
450
574
|
/**
|
package/esm/scry/query.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryHit,\n ScryHitType,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Notes every answer carries: how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n\n if (facts.routes === null) {\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n const hint =\n samePath.length > 0\n ? ` Routes on that path: ${samePath.join(\", \")}.`\n : \" Run warlock routes to list them, or warlock grimoire build when the route is new.\";\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n })),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings: findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n ),\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`. */\nfunction words(text: string): string {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .trim();\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return words(text).split(\" \").join(\"-\");\n}\n\ntype Candidate = Omit<ScryHit, \"score\">;\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n\n for (const feature of snapshot.written.features) {\n list.push({ type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null });\n\n for (const flow of feature.flows) {\n list.push({ type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null });\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${layout.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${page.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n }\n\n for (const page of facts.pages) {\n list.push({\n type: \"page\",\n id: `${siteApp(snapshot, page.site)} ${page.route}`,\n detail: page.file,\n });\n }\n\n for (const app of facts.mobile) {\n for (const screen of app.screens) {\n list.push({\n type: \"screen\",\n id: `${mobileApp(snapshot, app.id)} ${screen.route}`,\n detail: screen.file,\n });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n list.push({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n list.push({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n list.push({ type: \"file\", id: file.file, detail: file.about });\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n list.push({ type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about });\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n list.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n return list;\n}\n\n/** Whether every character of `needle` appears in `text` in order. */\nfunction isSubsequence(needle: string, text: string): boolean {\n let position = 0;\n\n for (const char of text) {\n if (char === needle[position]) position++;\n\n if (position === needle.length) return true;\n }\n\n return needle.length === 0;\n}\n\n/** Shortest query that may match by fuzzy (in-order letters), so short queries stay precise. */\nconst FUZZY_MIN = 4;\n\n/**\n * Score of a candidate for the query words, or 0 when it does not match. From best\n * to worst: exact name or path (7), prefix (6), whole-word match (5), substring of\n * the name or path (4), the words found only in the detail (3), fuzzy (2).\n */\nfunction scoreOf(candidate: Candidate, query: string, tokens: readonly string[]): number {\n const id = words(\n candidate.type === \"export\" ? (candidate.id.split(\"#\")[1] ?? candidate.id) : candidate.id,\n );\n const last = words(lastSegment(candidate.id));\n const all = `${id} ${words(candidate.detail ?? \"\")}`;\n\n if (!tokens.every((token) => all.includes(token))) {\n const squeezed = id.replace(/ /g, \"\");\n\n return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed))\n ? 2\n : 0;\n }\n\n if (id === query || last === query) return 7;\n if (id.startsWith(query) || last.startsWith(query)) return 6;\n\n const idWords = id.split(\" \");\n\n if (tokens.every((token) => idWords.includes(token))) return 5;\n if (tokens.every((token) => id.includes(token))) return 4;\n\n return 3;\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n const text = words(query.text);\n const tokens = text.split(\" \").filter((token) => token !== \"\");\n\n if (tokens.length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const seen = new Set<string>();\n const hits: ScryHit[] = [];\n\n for (const candidate of candidates(snapshot)) {\n const key = `${candidate.type} ${candidate.id}`;\n\n if (seen.has(key)) continue;\n\n seen.add(key);\n\n const score = scoreOf(candidate, text, tokens);\n\n if (score > 0) hits.push({ ...candidate, score });\n }\n\n hits.sort(\n (left, right) =>\n right.score - left.score ||\n TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) ||\n byText(left.id, right.id),\n );\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n hits: hits.slice(0, query.limit ?? 20),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,SAAS,QAAQ,UAA4B,aAAiC;CAC5E,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS,WAAW,SAAS,MAAM,KAAK,mDAAmD;CAC/F,IAAI,SAAS,WAAW,aAAa,aACnC,MAAM,KAAK,yDAAyD;CAGtE,OAAO;EAAE,QAAQ,SAAS;EAAQ;CAAM;AAC1C;;AAGA,SAAS,OAAO,UAA4B,MAAsB;CAChE,OAAO,YAAY,SAAS,MAAM,YAAY,KAAK,KAAK,CAAC,CAAC;AAC5D;AAEA,SAAS,SAAS,UAA4B,MAAwB;CACpE,MAAM,QAAQ,SAAS,KAAK,MAAM,MAAM,MAAM,SAAS,KAAK,SAAS,IAAI;CAEzE,IAAI,CAAC,OAAO;EACV,MAAM,QAAQ,CACZ,GAAG,IAAI,IAAI,SAAS,KAAK,MAAM,MAAM,KAAK,SAAS,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,CACnF,CAAC,CACE,QAAQ,SAAS,SAAS,EAAE,CAAC,CAC7B,KAAK,MAAM;EAEd,MAAM,IAAI,cACR,UACA,GAAG,KAAK,8CAA8C,MAAM,KAAK,IAAI,KAAK,mBAAmB,6EAC/F;CACF;CAEA,OAAO;AACT;;AAGA,SAAS,QAAQ,UAA4B,MAAsB;CAGjE,OAFc,OAAO,OAAO,SAAS,IAAI,CAAC,CAAC,MAAM,QAAQ,IAAI,MAAM,OAAO,IAE/D,CAAC,EAAE,OAAO;AACvB;;AAGA,SAAS,UAAU,UA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AAG;EAEnB,KAAK,IAAI,GAAG;EAEZ,MAAM,QAAQ,QAAQ,WAAW,MAAM,MAAM;EAE7C,IAAI,QAAQ,GAAG,KAAK,KAAK;GAAE,GAAG;GAAW;EAAM,CAAC;CAClD;CAEA,KAAK,MACF,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,WAAW,QAAQ,KAAK,IAAI,IAAI,WAAW,QAAQ,MAAM,IAAI,KAC7D,OAAO,KAAK,IAAI,MAAM,EAAE,CAC5B;CAEA,OAAO;EACL,MAAM;EACN,GAAG,QAAQ,UAAU,KAAK;EAC1B,MAAM,MAAM;EACZ,MAAM,KAAK,MAAM,GAAG,MAAM,SAAS,EAAE;CACvC;AACF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryHit,\n ScryHitType,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Notes every answer carries: how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n\n if (facts.routes === null) {\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n const hint =\n samePath.length > 0\n ? ` Routes on that path: ${samePath.join(\", \")}.`\n : \" Run warlock routes to list them, or warlock grimoire build when the route is new.\";\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n const findings = findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n );\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => {\n const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];\n\n return {\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n steps: flow.steps.length,\n cases: flow.cases.length,\n criteria: flow.criteria.length,\n tested: criteria.filter((criterion) => criterion.tests.length > 0).length,\n findings: findings.filter(\n (finding) => !finding.expected && finding.subject.flow === flow.ref,\n ).length,\n };\n }),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings,\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`. */\nfunction words(text: string): string {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .trim();\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return words(text).split(\" \").join(\"-\");\n}\n\n/** One searchable piece of written text of a feature or flow (a summary, a story, a case, a criterion). */\ntype BodyPart = { label: string; text: string };\n\ntype Candidate = Omit<ScryHit, \"score\" | \"matched\"> & { body?: BodyPart[] };\n\n/** The searchable written text of a flow: summary, who, story, cases, criteria. */\nfunction flowBody(flow: WrittenFlow): BodyPart[] {\n return [\n ...(flow.summary === null ? [] : [{ label: \"summary\", text: flow.summary }]),\n { label: \"who\", text: flow.who.value },\n ...flow.story.map((step) => ({ label: `story ${step.index}`, text: step.text })),\n ...flow.cases.map((item) => ({\n label: `case ${item.question}`,\n text: `${item.question} ${item.answer} ${item.criteria.join(\" \")}`,\n })),\n ...flow.criteria.map((item) => ({ label: item.id, text: `${item.id} ${item.text}` })),\n ];\n}\n\n/** The searchable written text of a feature: summary, why, audience. */\nfunction featureBody(feature: WrittenFeature): BodyPart[] {\n const readme = feature.readme;\n\n if (readme === null) return [];\n\n return [\n ...(readme.summary === null ? [] : [{ label: \"summary\", text: readme.summary }]),\n ...(readme.why === null ? [] : [{ label: \"why\", text: readme.why }]),\n ...readme.audience.map((item) => ({ label: \"audience\", text: item.value })),\n ];\n}\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n\n for (const feature of snapshot.written.features) {\n list.push({\n type: \"feature\",\n id: feature.id,\n detail: feature.readme?.title.value ?? null,\n body: featureBody(feature),\n });\n\n for (const flow of feature.flows) {\n list.push({\n type: \"flow\",\n id: flow.ref,\n detail: flow.heading?.value ?? null,\n body: flowBody(flow),\n });\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${layout.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${page.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n }\n\n for (const page of facts.pages) {\n list.push({\n type: \"page\",\n id: `${siteApp(snapshot, page.site)} ${page.route}`,\n detail: page.file,\n });\n }\n\n for (const app of facts.mobile) {\n for (const screen of app.screens) {\n list.push({\n type: \"screen\",\n id: `${mobileApp(snapshot, app.id)} ${screen.route}`,\n detail: screen.file,\n });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n list.push({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n list.push({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n list.push({ type: \"file\", id: file.file, detail: file.about });\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n list.push({ type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about });\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n list.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n return list;\n}\n\n/** Whether every character of `needle` appears in `text` in order. */\nfunction isSubsequence(needle: string, text: string): boolean {\n let position = 0;\n\n for (const char of text) {\n if (char === needle[position]) position++;\n\n if (position === needle.length) return true;\n }\n\n return needle.length === 0;\n}\n\n/** Shortest query that may match by fuzzy (in-order letters), so short queries stay precise. */\nconst FUZZY_MIN = 4;\n\n/** Added to the score of written content (features, flows) so it ranks above files and exports of the same match. */\nconst WRITTEN_BOOST = 2;\n\n/** Whether a word list holds a word that is, or starts with, every token (a short token must equal a word). */\nfunction partMatches(partWords: readonly string[], tokens: readonly string[]): boolean {\n return tokens.every((token) =>\n partWords.some((word) => (token.length >= 3 ? word.startsWith(token) : word === token)),\n );\n}\n\n/** The first body part holding every token, as `label: text`, or `null`. */\nfunction bodyMatch(candidate: Candidate, tokens: readonly string[], base: string): string | null {\n for (const part of candidate.body ?? []) {\n const partWords = words(part.text).split(\" \");\n // Tokens may be split between the name and one written part.\n const rest = tokens.filter((token) => !base.includes(token));\n\n if (rest.length > 0 && partMatches(partWords, rest)) {\n const text = part.text.replace(/\\s+/g, \" \").trim();\n\n return `${part.label}: ${text.length > 90 ? `${text.slice(0, 89)}…` : text}`;\n }\n }\n\n return null;\n}\n\n/**\n * Score of a candidate for the query words, or 0 when it does not match. From best\n * to worst: exact name or path (7), prefix (6), whole-word match (5), substring of\n * the name or path (4), the words found only in the detail or in written text (3),\n * fuzzy (2). Features and flows add {@link WRITTEN_BOOST} to a match.\n */\nfunction scoreOf(\n candidate: Candidate,\n query: string,\n tokens: readonly string[],\n): { score: number; matched: string | null } {\n const id = words(\n candidate.type === \"export\" ? (candidate.id.split(\"#\")[1] ?? candidate.id) : candidate.id,\n );\n const last = words(lastSegment(candidate.id));\n const base = `${id} ${words(candidate.detail ?? \"\")}`;\n const boost = candidate.type === \"feature\" || candidate.type === \"flow\" ? WRITTEN_BOOST : 0;\n\n if (!tokens.every((token) => base.includes(token))) {\n const matched = bodyMatch(candidate, tokens, base);\n\n if (matched !== null) return { score: 3 + boost, matched };\n\n const squeezed = id.replace(/ /g, \"\");\n\n return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed))\n ? { score: 2, matched: null }\n : { score: 0, matched: null };\n }\n\n if (id === query || last === query) return { score: 7 + boost, matched: null };\n if (id.startsWith(query) || last.startsWith(query)) return { score: 6 + boost, matched: null };\n\n const idWords = id.split(\" \");\n\n if (tokens.every((token) => idWords.includes(token))) return { score: 5 + boost, matched: null };\n if (tokens.every((token) => id.includes(token))) return { score: 4 + boost, matched: null };\n\n return { score: 3 + boost, matched: null };\n}\n\n/** The most hits of features and flows set aside before files and exports fill the list (a share of the limit). */\nconst WRITTEN_SHARE = 0.75;\n\nconst byRank = (left: ScryHit, right: ScryHit): number =>\n right.score - left.score ||\n TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) ||\n byText(left.id, right.id);\n\n/**\n * The hits to return: the best features and flows first (up to a share of the\n * limit, so files and exports never push matching written content out), then\n * the best of the rest. Grouped by type in {@link TYPE_ORDER}, best first.\n */\nfunction pickHits(hits: ScryHit[], limit: number): ScryHit[] {\n const ranked = [...hits].sort(byRank);\n const written = ranked\n .filter((hit) => hit.type === \"feature\" || hit.type === \"flow\")\n .slice(0, Math.max(1, Math.ceil(limit * WRITTEN_SHARE)));\n const chosen = new Set(written);\n\n for (const hit of ranked) {\n if (chosen.size >= limit) break;\n\n chosen.add(hit);\n }\n\n return [...chosen]\n .slice(0, limit)\n .sort(\n (left, right) =>\n TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) ||\n right.score - left.score ||\n byText(left.id, right.id),\n );\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n const text = words(query.text);\n const tokens = text.split(\" \").filter((token) => token !== \"\");\n\n if (tokens.length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const seen = new Set<string>();\n const hits: ScryHit[] = [];\n\n for (const candidate of candidates(snapshot)) {\n const key = `${candidate.type} ${candidate.id}`;\n\n if (seen.has(key)) continue;\n\n seen.add(key);\n\n const { score, matched } = scoreOf(candidate, text, tokens);\n\n if (score > 0) {\n hits.push({\n type: candidate.type,\n id: candidate.id,\n detail: candidate.detail,\n score,\n ...(matched === null ? {} : { matched }),\n });\n }\n }\n\n const counts: Partial<Record<ScryHitType, number>> = {};\n\n for (const hit of hits) counts[hit.type] = (counts[hit.type] ?? 0) + 1;\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n counts,\n hits: pickHits(hits, query.limit ?? 20),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,SAAS,QAAQ,UAA4B,aAAiC;CAC5E,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS,WAAW,SAAS,MAAM,KAAK,mDAAmD;CAC/F,IAAI,SAAS,WAAW,aAAa,aACnC,MAAM,KAAK,yDAAyD;CAGtE,OAAO;EAAE,QAAQ,SAAS;EAAQ;CAAM;AAC1C;;AAGA,SAAS,OAAO,UAA4B,MAAsB;CAChE,OAAO,YAAY,SAAS,MAAM,YAAY,KAAK,KAAK,CAAC,CAAC;AAC5D;AAEA,SAAS,SAAS,UAA4B,MAAwB;CACpE,MAAM,QAAQ,SAAS,KAAK,MAAM,MAAM,MAAM,SAAS,KAAK,SAAS,IAAI;CAEzE,IAAI,CAAC,OAAO;EACV,MAAM,QAAQ,CACZ,GAAG,IAAI,IAAI,SAAS,KAAK,MAAM,MAAM,KAAK,SAAS,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,CACnF,CAAC,CACE,QAAQ,SAAS,SAAS,EAAE,CAAC,CAC7B,KAAK,MAAM;EAEd,MAAM,IAAI,cACR,UACA,G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IAAI,SAAS,KAAK;CAErE,OAAO;EACL,MAAM;EACN,GAAG,QAAQ,UAAU,KAAK;EAC1B,MAAM,MAAM;EACZ;EACA,MAAM,SAAS,MAAM,MAAM,SAAS,EAAE;CACxC;AACF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"mappings":";;;;;;;;;wBAwDsB,gBACpB,cACA,gBACC,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"sourcesContent":["/**\n * Test results per criterion: reading, merging, writing the store the Vitest\n * reporter fills, and the check rules over it (`GR4006`–`GR4010`).\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../codes\";\nimport { GRIMOIRE_PATHS, toPosixPath } from \"../paths\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type {\n ProofResult,\n TestResultsInfo,\n TestResultsStore,\n UnmatchedProof,\n} from \"../contracts/test-results\";\n\nexport { criterionStatus, type CriterionTestResult } from \"./criterion-status\";\n\n/** sha256 (hex) of a test file's bytes: the value stored as `testFileHash`. */\nexport function hashTestFile(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * The absolute path of the results file: `file` (project-relative or\n * absolute) when given, else `grimoire/book/test-results.json`.\n */\nexport function resolveResultsFile(root: string, file?: string): string {\n return file === undefined || file === \"\"\n ? path.join(root, ...GRIMOIRE_PATHS.testResults.split(\"/\"))\n : path.resolve(root, file);\n}\n\n/**\n * The results file as the snapshot reports it: project-relative POSIX when it\n * lies inside the project, else the absolute path.\n */\nexport function resultsFileLabel(root: string, file?: string): string {\n const absolute = resolveResultsFile(root, file);\n const relative = path.relative(root, absolute);\n\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) return toPosixPath(absolute);\n\n return toPosixPath(relative);\n}\n\n/**\n * Read the results store (`grimoire/book/test-results.json`, or `file`);\n * `null` when absent or unreadable.\n *\n * @param file Project-relative or absolute path of another results file.\n */\nexport async function readTestResults(root: string, file?: string): Promise<TestResultsStore | null> {\n try {\n const parsed: unknown = JSON.parse(await readFile(resolveResultsFile(root, file), \"utf8\"));\n\n if (!isStore(parsed)) return null;\n\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction isStore(value: unknown): value is TestResultsStore {\n if (typeof value !== \"object\" || value === null) return false;\n\n const store = value as Partial<TestResultsStore>;\n\n return store.schemaVersion === 1 && Array.isArray(store.results);\n}\n\n/**\n * What the readers know about the results store: whether one was read, where\n * from, and how many `@proves` lines have a result. Lets a view tell \"never\n * recorded\" from \"did not run\".\n */\nexport function testResultsInfo(snapshot: GrimoireSnapshot): TestResultsInfo {\n const store = snapshot.results;\n const results = store?.results ?? [];\n const withResult = snapshot.proofs.filter((proof) =>\n results.some(\n (result) =>\n toPosixPath(result.testFile) === toPosixPath(proof.at.file) &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n ),\n ).length;\n\n return {\n recorded: store !== null,\n file: snapshot.resultsFile,\n updatedAt: store?.updatedAt ?? null,\n proofs: snapshot.proofs.length,\n withResult,\n unmatched: store?.unmatched?.length ?? 0,\n };\n}\n\nfunction compareResults(a: ProofResult, b: ProofResult): number {\n if (a.testFile !== b.testFile) return a.testFile < b.testFile ? -1 : 1;\n if (a.line !== b.line) return a.line - b.line;\n if (a.feature !== b.feature) return a.feature < b.feature ? -1 : 1;\n if (a.flow !== b.flow) return a.flow < b.flow ? -1 : 1;\n\n return a.criterion < b.criterion ? -1 : a.criterion > b.criterion ? 1 : 0;\n}\n\n/**\n * Merge one run into the store: results of the test files the run covered\n * replace the old ones; results of other files stay. Pure.\n *\n * @param ranFiles Test files the run executed (even those with no proving test).\n */\nexport function mergeTestResults(\n store: TestResultsStore | null,\n run: readonly ProofResult[],\n ranFiles: readonly string[],\n now: Date,\n unmatched: readonly UnmatchedProof[] = [],\n): TestResultsStore {\n const ran = new Set([...ranFiles, ...run.map((result) => result.testFile)].map(toPosixPath));\n const kept = (store?.results ?? []).filter((result) => !ran.has(toPosixPath(result.testFile)));\n const keptUnmatched = (store?.unmatched ?? []).filter(\n (entry) => !ran.has(toPosixPath(entry.testFile)),\n );\n const allUnmatched = [...keptUnmatched, ...unmatched].sort(\n (a, b) => (a.testFile < b.testFile ? -1 : a.testFile > b.testFile ? 1 : 0) || a.line - b.line,\n );\n\n return {\n schemaVersion: 1,\n updatedAt: now.toISOString(),\n runner: \"vitest\",\n results: [...kept, ...run].sort(compareResults),\n ...(allUnmatched.length > 0 ? { unmatched: allUnmatched } : {}),\n };\n}\n\n/** Write the store (atomically: temp file, then rename), to `file` when given. */\nexport async function writeTestResults(\n root: string,\n store: TestResultsStore,\n file?: string,\n): Promise<void> {\n const target = resolveResultsFile(root, file);\n const temp = `${target}.${process.pid}.${Date.now()}.tmp`;\n\n await mkdir(path.dirname(target), { recursive: true });\n\n try {\n await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n await rename(temp, target);\n } catch (error) {\n await rm(temp, { force: true });\n\n throw error;\n }\n}\n\n/** The GR4006–GR4010 rules. Read-only. */\nexport function checkTestResults(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const store = snapshot.results;\n\n if (!store) {\n const first = snapshot.proofs[0];\n\n // Proofs exist and no run ever wrote results: one finding for the project, at the first proof.\n return first === undefined\n ? []\n : [\n createFinding({\n code: \"GR4009\",\n message: `${snapshot.proofs.length} proving ${snapshot.proofs.length === 1 ? \"test is\" : \"tests are\"} written but no test results were found at ${snapshot.resultsFile}`,\n at: first.at,\n feature: first.feature,\n flow: first.ref,\n file: toPosixPath(first.at.file),\n }),\n ];\n }\n\n const proposed = new Set(\n snapshot.written.features.flatMap((feature) =>\n feature.flows.filter((flow) => flow.status.value === \"proposed\").map((flow) => flow.ref),\n ),\n );\n const hashes = new Map<string, string | null>();\n const currentHash = (file: string): string | null => {\n if (!hashes.has(file)) {\n try {\n hashes.set(file, hashTestFile(readFileSync(path.join(snapshot.root, file))));\n } catch {\n hashes.set(file, null);\n }\n }\n\n return hashes.get(file) ?? null;\n };\n const findings: GrimoireFinding[] = [];\n\n for (const proof of snapshot.proofs) {\n const file = toPosixPath(proof.at.file);\n const candidates = store.results.filter(\n (result) =>\n toPosixPath(result.testFile) === file &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n );\n const result = candidates.find((item) => item.outcome === \"fail\") ?? candidates[0];\n const label = `${proof.ref} ${proof.criterion}`;\n const base = { at: proof.at, feature: proof.feature, flow: proof.ref, file };\n let finding: GrimoireFinding | null = null;\n\n if (!result || result.outcome === \"skip\") {\n finding = createFinding({\n ...base,\n code: \"GR4008\",\n message: `${label}: its test did not run in the last run${proof.test?.name ? ` (\"${proof.test.name}\")` : \"\"}`,\n });\n } else if (result.outcome === \"fail\") {\n finding = createFinding({\n ...base,\n code: \"GR4006\",\n message: `${label}: its test failed in the last run (\"${result.testName}\")`,\n });\n } else {\n const hash = currentHash(file);\n\n if (hash !== null && hash !== result.testFileHash) {\n finding = createFinding({\n ...base,\n code: \"GR4007\",\n message: `${label}: its result is older than ${file} (ran ${result.ranAt})`,\n });\n }\n }\n\n if (finding) {\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n }\n\n for (const entry of store.unmatched ?? []) {\n const file = toPosixPath(entry.testFile);\n const proof = snapshot.proofs.find(\n (item) =>\n toPosixPath(item.at.file) === file &&\n item.at.line === entry.line &&\n item.feature === entry.feature &&\n item.flow === entry.flow &&\n item.criterion === entry.criterion,\n );\n\n // The `@proves` line is gone or moved since the run: the next run replaces the entry.\n if (!proof) continue;\n\n const finding = createFinding({\n code: \"GR4010\",\n message: `${proof.ref} ${proof.criterion}: the reporter could not match the test under this @proves line to a result`,\n at: proof.at,\n feature: proof.feature,\n flow: proof.ref,\n file,\n });\n\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,SAAgB,aAAa,SAAsC;CACjE,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;AAC1D;;;;;AAMA,SAAgB,mBAAmB,MAAc,MAAuB;CACtE,OAAO,SAAS,UAAa,SAAS,KAClC,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,MAAM,GAAG,CAAC,IACxD,KAAK,QAAQ,MAAM,IAAI;AAC7B;;;;;AAMA,SAAgB,iBAAiB,MAAc,MAAuB;CACpE,MAAM,WAAW,mBAAmB,MAAM,IAAI;CAC9C,MAAM,WAAW,KAAK,SAAS,MAAM,QAAQ;CAE7C,IAAI,aAAa,MAAM,SAAS,WAAW,IAAI,KAAK,KAAK,WAAW,QAAQ,GAAG,OAAO,YAAY,QAAQ;CAE1G,OAAO,YAAY,QAAQ;AAC7B;;;;;;;AAQA,eAAsB,gBAAgB,MAAc,MAAiD;CACnG,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,M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AG,MAAM,wCAAwC,MAAM,MAAM,OAAO,MAAM,MAAM,KAAK,KAAK,MAAM;EAC3G,CAAC;OACI,IAAI,OAAO,YAAY,QAC5B,UAAU,cAAc;GACtB,GAAG;GACH,MAAM;GACN,SAAS,GAAG,MAAM,sCAAsC,OAAO,SAAS;EAC1E,CAAC;OACI;GACL,MAAM,OAAO,YAAY,IAAI;GAE7B,IAAI,SAAS,QAAQ,SAAS,OAAO,cACnC,UAAU,cAAc;IACtB,GAAG;IACH,MAAM;IACN,SAAS,GAAG,MAAM,6BAA6B,KAAK,QAAQ,OAAO,MAAM;GAC3E,CAAC;EAEL;EAEA,IAAI,SAAS;GACX,IAAI,SAAS,IAAI,MAAM,GAAG,GAAG,QAAQ,WAAW;GAEhD,SAAS,KAAK,OAAO;EACvB;CACF;CAEA,KAAK,MAAM,SAAS,MAAM,aAAa,CAAC,GAAG;EACzC,MAAM,OAAO,YAAY,MAAM,QAAQ;EACvC,MAAM,QAAQ,SAAS,OAAO,MAC3B,SACC,YAAY,KAAK,GAAG,IAAI,MAAM,QAC9B,KAAK,GAAG,SAAS,MAAM,QACvB,KAAK,YAAY,MAAM,WACvB,KAAK,SAAS,MAAM,QACpB,KAAK,cAAc,MAAM,SAC7B;EAGA,IAAI,CAAC,OAAO;EAEZ,MAAM,UAAU,cAAc;GAC5B,MAAM;GACN,SAAS,GAAG,MAAM,IAAI,GAAG,MAAM,UAAU;GACzC,IAAI,MAAM;GACV,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;EAED,IAAI,SAAS,IAAI,MAAM,GAAG,GAAG,QAAQ,WAAW;EAEhD,SAAS,KAAK,OAAO;CACvB;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"sourcesContent":["/**\n * Test results per criterion: reading, merging, writing the store the Vitest\n * reporter fills, and the check rules over it (`GR4006`–`GR4010`).\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../codes\";\nimport { GRIMOIRE_PATHS, toPosixPath } from \"../paths\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type {\n ProofResult,\n TestResultsInfo,\n TestResultsStore,\n UnmatchedProof,\n} from \"../contracts/test-results\";\n\nexport { criterionStatus, type CriterionTestResult } from \"./criterion-status\";\n\n/** sha256 (hex) of a test file's bytes: the value stored as `testFileHash`. */\nexport function hashTestFile(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * The absolute path of the results file: `file` (project-relative or\n * absolute) when given, else `grimoire/book/test-results.json`.\n */\nexport function resolveResultsFile(root: string, file?: string): string {\n return file === undefined || file === \"\"\n ? path.join(root, ...GRIMOIRE_PATHS.testResults.split(\"/\"))\n : path.resolve(root, file);\n}\n\n/**\n * The results file as the snapshot reports it: project-relative POSIX when it\n * lies inside the project, else the absolute path.\n */\nexport function resultsFileLabel(root: string, file?: string): string {\n const absolute = resolveResultsFile(root, file);\n const relative = path.relative(root, absolute);\n\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative))\n return toPosixPath(absolute);\n\n return toPosixPath(relative);\n}\n\n/**\n * Read the results store (`grimoire/book/test-results.json`, or `file`);\n * `null` when absent or unreadable.\n *\n * @param file Project-relative or absolute path of another results file.\n */\nexport async function readTestResults(\n root: string,\n file?: string,\n): Promise<TestResultsStore | null> {\n try {\n const parsed: unknown = JSON.parse(await readFile(resolveResultsFile(root, file), \"utf8\"));\n\n if (!isStore(parsed)) return null;\n\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction isStore(value: unknown): value is TestResultsStore {\n if (typeof value !== \"object\" || value === null) return false;\n\n const store = value as Partial<TestResultsStore>;\n\n return store.schemaVersion === 1 && Array.isArray(store.results);\n}\n\n/**\n * What the readers know about the results store: whether one was read, where\n * from, and how many `@proves` lines have a result. Lets a view tell \"never\n * recorded\" from \"did not run\".\n */\nexport function testResultsInfo(snapshot: GrimoireSnapshot): TestResultsInfo {\n const store = snapshot.results;\n const results = store?.results ?? [];\n const withResult = snapshot.proofs.filter((proof) =>\n results.some(\n (result) =>\n toPosixPath(result.testFile) === toPosixPath(proof.at.file) &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n ),\n ).length;\n\n return {\n recorded: store !== null,\n file: snapshot.resultsFile,\n updatedAt: store?.updatedAt ?? null,\n proofs: snapshot.proofs.length,\n withResult,\n unmatched: store?.unmatched?.length ?? 0,\n };\n}\n\nfunction compareResults(a: ProofResult, b: ProofResult): number {\n if (a.testFile !== b.testFile) return a.testFile < b.testFile ? -1 : 1;\n if (a.line !== b.line) return a.line - b.line;\n if (a.feature !== b.feature) return a.feature < b.feature ? -1 : 1;\n if (a.flow !== b.flow) return a.flow < b.flow ? -1 : 1;\n\n return a.criterion < b.criterion ? -1 : a.criterion > b.criterion ? 1 : 0;\n}\n\n/**\n * Merge one run into the store: results of the test files the run covered\n * replace the old ones; results of other files stay. Pure.\n *\n * @param ranFiles Test files the run executed (even those with no proving test).\n */\nexport function mergeTestResults(\n store: TestResultsStore | null,\n run: readonly ProofResult[],\n ranFiles: readonly string[],\n now: Date,\n unmatched: readonly UnmatchedProof[] = [],\n): TestResultsStore {\n const ran = new Set([...ranFiles, ...run.map((result) => result.testFile)].map(toPosixPath));\n const kept = (store?.results ?? []).filter((result) => !ran.has(toPosixPath(result.testFile)));\n const keptUnmatched = (store?.unmatched ?? []).filter(\n (entry) => !ran.has(toPosixPath(entry.testFile)),\n );\n const allUnmatched = [...keptUnmatched, ...unmatched].sort(\n (a, b) => (a.testFile < b.testFile ? -1 : a.testFile > b.testFile ? 1 : 0) || a.line - b.line,\n );\n\n return {\n schemaVersion: 1,\n updatedAt: now.toISOString(),\n runner: \"vitest\",\n results: [...kept, ...run].sort(compareResults),\n ...(allUnmatched.length > 0 ? { unmatched: allUnmatched } : {}),\n };\n}\n\n/** Write the store (atomically: temp file, then rename), to `file` when given. */\nexport async function writeTestResults(\n root: string,\n store: TestResultsStore,\n file?: string,\n): Promise<void> {\n const target = resolveResultsFile(root, file);\n const temp = `${target}.${process.pid}.${Date.now()}.tmp`;\n\n await mkdir(path.dirname(target), { recursive: true });\n\n try {\n await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n await rename(temp, target);\n } catch (error) {\n await rm(temp, { force: true });\n\n throw error;\n }\n}\n\n/** The GR4006–GR4010 rules. Read-only. */\nexport function checkTestResults(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const store = snapshot.results;\n\n if (!store) {\n const first = snapshot.proofs[0];\n\n // Proofs exist and no run ever wrote results: one finding for the project, at the first proof.\n return first === undefined\n ? []\n : [\n createFinding({\n code: \"GR4009\",\n message: `${snapshot.proofs.length} proving ${snapshot.proofs.length === 1 ? \"test is\" : \"tests are\"} written but no test results were found at ${snapshot.resultsFile}`,\n at: first.at,\n feature: first.feature,\n flow: first.ref,\n file: toPosixPath(first.at.file),\n }),\n ];\n }\n\n const proposed = new Set(\n snapshot.written.features.flatMap((feature) =>\n feature.flows.filter((flow) => flow.status.value === \"proposed\").map((flow) => flow.ref),\n ),\n );\n const hashes = new Map<string, string | null>();\n const currentHash = (file: string): string | null => {\n if (!hashes.has(file)) {\n try {\n hashes.set(file, hashTestFile(readFileSync(path.join(snapshot.root, file))));\n } catch {\n hashes.set(file, null);\n }\n }\n\n return hashes.get(file) ?? null;\n };\n const findings: GrimoireFinding[] = [];\n\n for (const proof of snapshot.proofs) {\n const file = toPosixPath(proof.at.file);\n const candidates = store.results.filter(\n (result) =>\n toPosixPath(result.testFile) === file &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n );\n const result = candidates.find((item) => item.outcome === \"fail\") ?? candidates[0];\n const label = `${proof.ref} ${proof.criterion}`;\n const base = { at: proof.at, feature: proof.feature, flow: proof.ref, file };\n let finding: GrimoireFinding | null = null;\n\n if (!result || result.outcome === \"skip\") {\n finding = createFinding({\n ...base,\n code: \"GR4008\",\n message: `${label}: its test did not run in the last run${proof.test?.name ? ` (\"${proof.test.name}\")` : \"\"}`,\n });\n } else if (result.outcome === \"fail\") {\n finding = createFinding({\n ...base,\n code: \"GR4006\",\n message: `${label}: its test failed in the last run (\"${result.testName}\")`,\n });\n } else {\n const hash = currentHash(file);\n\n if (hash !== null && hash !== result.testFileHash) {\n finding = createFinding({\n ...base,\n code: \"GR4007\",\n message: `${label}: its result is older than ${file} (ran ${result.ranAt})`,\n });\n }\n }\n\n if (finding) {\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n }\n\n for (const entry of store.unmatched ?? []) {\n const file = toPosixPath(entry.testFile);\n const proof = snapshot.proofs.find(\n (item) =>\n toPosixPath(item.at.file) === file &&\n item.at.line === entry.line &&\n item.feature === entry.feature &&\n item.flow === entry.flow &&\n item.criterion === entry.criterion,\n );\n\n // The `@proves` line is gone or moved since the run: the next run replaces the entry.\n if (!proof) continue;\n\n const finding = createFinding({\n code: \"GR4010\",\n message: `${proof.ref} ${proof.criterion}: the reporter could not match the test under this @proves line to a result`,\n at: proof.at,\n feature: proof.feature,\n flow: proof.ref,\n file,\n });\n\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,SAAgB,aAAa,SAAsC;CACjE,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;AAC1D;;;;;AAMA,SAAgB,mBAAmB,MAAc,MAAuB;CACtE,OAAO,SAAS,UAAa,SAAS,KAClC,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,MAAM,GAAG,CAAC,IACxD,KAAK,QAAQ,MAAM,IAAI;AAC7B;;;;;AAMA,SAAgB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,MAAM,MAAM;GACZ;EACF,CAAC;EAED,IAAI,SAAS,IAAI,MAAM,GAAG,GAAG,QAAQ,WAAW;EAEhD,SAAS,KAAK,OAAO;CACvB;CAEA,OAAO;AACT"}
|
package/esm/warlock/actions.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { parseGrimoire } from "../written/parse-grimoire.mjs";
|
|
|
4
4
|
import "../written/index.mjs";
|
|
5
5
|
import { loadBook } from "../book/build.mjs";
|
|
6
6
|
import "../book/index.mjs";
|
|
7
|
-
import {
|
|
7
|
+
import { runGrimoire } from "../workspace/index.mjs";
|
|
8
8
|
import { writeRelease } from "../releases/index.mjs";
|
|
9
9
|
import { checkGrimoire } from "../check/check-grimoire.mjs";
|
|
10
10
|
import { formatCheckReport } from "../check/format-check-report.mjs";
|
|
@@ -13,6 +13,7 @@ import { formatScryResult } from "../scry/format.mjs";
|
|
|
13
13
|
import { parseScryQuery } from "../scry/parse.mjs";
|
|
14
14
|
import { scry } from "../scry/query.mjs";
|
|
15
15
|
import "../scry/index.mjs";
|
|
16
|
+
import { openGrimoireCached } from "../workspace/cache.mjs";
|
|
16
17
|
import path from "node:path";
|
|
17
18
|
import { createHash } from "node:crypto";
|
|
18
19
|
import { readFile, readdir } from "node:fs/promises";
|
|
@@ -133,7 +134,7 @@ function siteFolder(root, out) {
|
|
|
133
134
|
function elapsedLine(started) {
|
|
134
135
|
return `time ${((Date.now() - started) / 1e3).toFixed(1)}s`;
|
|
135
136
|
}
|
|
136
|
-
/** `warlock grimoire build [--force] [--site [--out <dir>]] [--json]`. */
|
|
137
|
+
/** `warlock grimoire build [--force] [--site [--product] [--out <dir>]] [--json]`. */
|
|
137
138
|
async function runBuild(context, options = {}) {
|
|
138
139
|
const { root, adapter, io } = context;
|
|
139
140
|
const started = Date.now();
|
|
@@ -145,13 +146,18 @@ async function runBuild(context, options = {}) {
|
|
|
145
146
|
force
|
|
146
147
|
}));
|
|
147
148
|
let site = null;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
let siteUpToDate = false;
|
|
150
|
+
if (options.site === true || options.product === true || typeof options.out === "string") {
|
|
151
|
+
const { exportGrimoireSiteDetailed } = await import("../devtools/index.mjs");
|
|
152
|
+
const exported = await exportGrimoireSiteDetailed(root, {
|
|
151
153
|
adapter,
|
|
152
154
|
snapshot: run.snapshot,
|
|
155
|
+
force,
|
|
156
|
+
...options.product === true ? { product: true } : {},
|
|
153
157
|
...outDir === void 0 ? {} : { outDir }
|
|
154
158
|
});
|
|
159
|
+
site = exported.outDir;
|
|
160
|
+
siteUpToDate = exported.upToDate;
|
|
155
161
|
}
|
|
156
162
|
if (options.json === true) {
|
|
157
163
|
printJson(io, {
|
|
@@ -161,6 +167,8 @@ async function runBuild(context, options = {}) {
|
|
|
161
167
|
removed: [...run.book.removed, ...run.collected.removed],
|
|
162
168
|
routes: run.snapshot.routes,
|
|
163
169
|
site,
|
|
170
|
+
siteUpToDate,
|
|
171
|
+
siteMode: site === null ? null : options.product === true ? "product" : "full",
|
|
164
172
|
problems: bootProblem === null ? [] : [bootProblem]
|
|
165
173
|
});
|
|
166
174
|
return 0;
|
|
@@ -172,7 +180,7 @@ async function runBuild(context, options = {}) {
|
|
|
172
180
|
}
|
|
173
181
|
io.out(summary.book);
|
|
174
182
|
io.out(summary.collected);
|
|
175
|
-
if (site !== null) io.out(`site ${site}/index.html`);
|
|
183
|
+
if (site !== null) io.out(`site ${site}/index.html${options.product === true ? " (product map only)" : ""}${siteUpToDate ? " (up to date, not rebuilt)" : ""}`);
|
|
176
184
|
io.out(elapsedLine(started));
|
|
177
185
|
return 0;
|
|
178
186
|
} catch (error) {
|
|
@@ -241,7 +249,7 @@ async function runRelease(context, release, options = {}) {
|
|
|
241
249
|
/** Open the snapshot for a scry question: cached routes, fresh once when a route question finds none. */
|
|
242
250
|
async function openForScry(root, adapter, query) {
|
|
243
251
|
const routes = query.type === "route" && !await hasRouteFacts(root) ? "fresh" : "cached";
|
|
244
|
-
return
|
|
252
|
+
return openGrimoireCached(root, adapter, { routes });
|
|
245
253
|
}
|
|
246
254
|
/** Answer a parsed query (shared by the CLI and the MCP tools). */
|
|
247
255
|
async function answer(root, adapter, query) {
|