@warlock.js/grimoire 5.62.0 → 5.63.1
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 +28 -0
- package/esm/book/build.d.mts +17 -0
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs +78 -16
- package/esm/book/build.mjs.map +1 -1
- package/esm/book/index.mjs +2 -2
- package/esm/codes/codes.d.mts +2 -0
- package/esm/codes/codes.d.mts.map +1 -1
- package/esm/codes/codes.mjs +2 -1
- package/esm/codes/codes.mjs.map +1 -1
- package/esm/contracts/book.d.mts +7 -0
- package/esm/contracts/book.d.mts.map +1 -1
- package/esm/contracts/book.mjs.map +1 -1
- package/esm/contracts/scry.d.mts +29 -5
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/contracts/snapshot.d.mts +8 -0
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/devtools/snapshot-source.mjs +27 -7
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/index.d.mts +5 -3
- package/esm/index.mjs +4 -2
- package/esm/scry/error.mjs +20 -0
- package/esm/scry/error.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +22 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/index.mjs +3 -2
- package/esm/scry/parse.d.mts +1 -1
- package/esm/scry/parse.d.mts.map +1 -1
- package/esm/scry/parse.mjs +12 -9
- package/esm/scry/parse.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +77 -268
- package/esm/scry/query.mjs.map +1 -1
- package/esm/scry/search.d.mts +8 -0
- package/esm/scry/search.d.mts.map +1 -0
- package/esm/scry/search.mjs +401 -0
- package/esm/scry/search.mjs.map +1 -0
- package/esm/warlock/actions.mjs +15 -12
- package/esm/warlock/actions.mjs.map +1 -1
- package/esm/warlock/commands.mjs +14 -4
- package/esm/warlock/commands.mjs.map +1 -1
- package/esm/warlock/mcp-tools.mjs +46 -21
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/workspace/cache.mjs +13 -1
- package/esm/workspace/cache.mjs.map +1 -1
- package/esm/workspace/derived.mjs +107 -0
- package/esm/workspace/derived.mjs.map +1 -0
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +22 -18
- package/esm/workspace/index.mjs.map +1 -1
- package/esm/workspace/stored.d.mts +12 -0
- package/esm/workspace/stored.d.mts.map +1 -0
- package/esm/workspace/stored.mjs +46 -0
- package/esm/workspace/stored.mjs.map +1 -0
- package/llms-full.txt +28 -12
- package/package.json +3 -3
- package/skills/use-the-grimoire/SKILL.md +28 -12
- package/ui/grimoire-view.js +16 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/search.ts"],"sourcesContent":["/**\n * `scry --search`: ranks the book's features, flows, blocks, pages, screens,\n * routes, mails, jobs, files, exports and tasks for a text, which may be a whole\n * sentence (a commit title, a bug report).\n *\n * Two tiers. Names come first: a candidate whose id or title is the whole query,\n * starts with it, or holds every query word as a whole word ranks above everything\n * else. Below them, a BM25F score ranks every candidate that shares words with the\n * query: whole words only, light stemming, no stop words, over four fields (id and\n * path words 3, export names 2, header sentence 1, written text 1).\n *\n * The index is built once per snapshot and kept in a `WeakMap`, so the MCP server\n * and the dev tab do not rebuild it for each query.\n */\nimport type { ScryHit, ScryHitType, ScryQuery } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\n\n/**\n * Words that carry no meaning in a sentence and are left out of the query and the\n * index. The set is extendable: add words before the first search of a process.\n */\nexport const SCRY_STOP_WORDS: Set<string> = new Set(\n \"the a an and or of to in on for with at by from is are was be been not no only its it their this that these those into through after before when then than so as has have had do does did can will should would via per if but also each any\".split(\n \" \",\n ),\n);\n\n/** BM25 term saturation. */\nconst K1 = 1.2;\n\n/** BM25 length normalisation. */\nconst B = 0.75;\n\n/** Field weights of the BM25F score. */\nconst WEIGHT = { id: 3, exports: 2, about: 1, body: 1 } as const;\n\n/** Added to the name level of features and flows, so written content ranks above files of the same match. */\nconst WRITTEN_BOOST = 2;\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\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\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\n/** What a candidate is before it is ranked: the hit without its score. */\ntype Candidate = {\n hit: Omit<ScryHit, \"score\" | \"matched\">;\n /** Name shown to the name tier (an export's own name, a block's `<app>/<page>`). */\n name: string;\n /** Text of the id field of the BM25F score. */\n idText: string;\n exportNames: string[];\n about: string;\n body: BodyPart[];\n /** Whether the BM25F score counts it (exports are found by name and through their file). */\n scored: boolean;\n /** A page or screen file: it outranks helper files on an equal score. */\n pageFile: boolean;\n};\n\ntype Doc = {\n candidate: Candidate;\n /** The name of the candidate as lower-case words, and its last segment, and its title. */\n nameText: string;\n lastText: string;\n nameWords: string[];\n titleText: string;\n titleWords: string[];\n boost: number;\n /** Length of the weighted token list (0 when the document is not scored). */\n length: number;\n /** Tokens of the written parts, per part, for the `matched` text. */\n bodyTokens: string[][];\n};\n\ntype SearchIndex = {\n docs: Doc[];\n postings: Map<string, [number, number][]>;\n idf: Map<string, number>;\n average: number;\n};\n\n/** An id such as `AC-5` is one word (`ac5`), so it never matches `ac` alone. */\nconst ID_PATTERN = /\\b([a-z]{1,5})-(\\d+)\\b/gi;\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`; `AC-5` → `ac5`. */\nexport function wordsOf(text: string): string[] {\n return text\n .replace(ID_PATTERN, \"$1$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .split(\" \")\n .filter((word) => word !== \"\");\n}\n\n/** Light stemming: `ies`, `ing`, `ed`, `es` and a plural `s` come off a longer word. */\nfunction stem(word: string): string {\n if (word.length > 4 && word.endsWith(\"ies\")) return `${word.slice(0, -3)}y`;\n if (word.length > 5 && word.endsWith(\"ing\")) return word.slice(0, -3);\n if (word.length > 4 && word.endsWith(\"ed\")) return word.slice(0, -2);\n if (word.length > 4 && word.endsWith(\"es\")) return word.slice(0, -2);\n if (word.length > 3 && word.endsWith(\"s\") && !word.endsWith(\"ss\")) return word.slice(0, -1);\n\n return word;\n}\n\n/** The searchable tokens of a text: whole words without stop words, stemmed. */\nfunction tokensOf(text: string): string[] {\n return wordsOf(text)\n .filter((word) => !SCRY_STOP_WORDS.has(word))\n .map(stem);\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 wordsOf(text).join(\"-\");\n}\n\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\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\n/** The written app id of a site, or its own id. */\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 app a file belongs to: the mobile app that owns it, else the site or mobile root that holds it. */\nfunction appOfFile(\n snapshot: GrimoireSnapshot,\n file: { file: string; mobileApp: string | null },\n): string | undefined {\n if (file.mobileApp !== null) return mobileApp(snapshot, file.mobileApp);\n\n let best: { app: string; length: number } | undefined;\n\n for (const match of Object.values(snapshot.apps)) {\n const root = match.site?.root ?? match.mobile?.root;\n\n if (root === undefined || root === \"\" || root === \".\") continue;\n if (file.file !== root && !file.file.startsWith(`${root}/`)) continue;\n if (best === undefined || root.length > best.length) {\n best = { app: match.app, length: root.length };\n }\n }\n\n return best?.app;\n}\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n const pageFiles = new Set<string>([\n ...facts.pages.map((page) => page.file),\n ...facts.mobile.flatMap((app) => app.screens.map((screen) => screen.file)),\n ]);\n\n const add = (hit: Candidate[\"hit\"], extra: Partial<Omit<Candidate, \"hit\">> = {}): void => {\n list.push({\n hit,\n name: extra.name ?? hit.id,\n idText: extra.idText ?? hit.id,\n exportNames: extra.exportNames ?? [],\n about: extra.about ?? hit.detail ?? \"\",\n body: extra.body ?? [],\n scored: extra.scored ?? true,\n pageFile: extra.pageFile ?? false,\n });\n };\n\n for (const feature of snapshot.written.features) {\n add(\n { type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null },\n { body: featureBody(feature) },\n );\n\n for (const flow of feature.flows) {\n add(\n { type: \"flow\", id: flow.ref, 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 const rows = [\n ...app.layouts.flatMap((layout) => layout.blocks.map((row) => ({ page: layout.id, row }))),\n ...[...app.pages, ...app.screens].flatMap((page) =>\n page.blocks.map((row) => ({ page: page.id, row })),\n ),\n ];\n\n for (const { page, row } of rows) {\n // A block is found through its page and its text, never through the slug of its whole text.\n add(\n {\n type: \"block\",\n id: `${appId}/${page}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n app: appId,\n },\n { name: `${appId}/${page}`, idText: `${appId}/${page}`, about: row.block },\n );\n }\n }\n\n for (const page of facts.pages) {\n const app = siteApp(snapshot, page.site);\n\n add({ type: \"page\", id: `${app} ${page.route}`, detail: page.file, app });\n }\n\n for (const mobile of facts.mobile) {\n const app = mobileApp(snapshot, mobile.id);\n\n for (const screen of mobile.screens) {\n add({ type: \"screen\", id: `${app} ${screen.route}`, detail: screen.file, app });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n add({ 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 add({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n const app = appOfFile(snapshot, file);\n\n add(\n {\n type: \"file\",\n id: file.file,\n detail: file.about,\n ...(app === undefined ? {} : { app }),\n },\n {\n exportNames: file.exports\n .filter((entry) => entry.name !== \"default\" && entry.name !== \"*\")\n .map((entry) => entry.name),\n pageFile: pageFiles.has(file.file),\n },\n );\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n add(\n { type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about },\n { name: entry.name, scored: false },\n );\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n add({ type: \"task\", id: task.id, detail: task.title });\n }\n\n // The first candidate of a type and id wins.\n const seen = new Set<string>();\n\n return list.filter((item) => {\n const key = `${item.hit.type} ${item.hit.id}`;\n\n if (seen.has(key)) return false;\n\n seen.add(key);\n\n return true;\n });\n}\n\nfunction buildIndex(snapshot: GrimoireSnapshot): SearchIndex {\n const docs: Doc[] = [];\n const postings = new Map<string, [number, number][]>();\n let scoredCount = 0;\n let totalLength = 0;\n\n for (const candidate of candidates(snapshot)) {\n const nameWords = wordsOf(candidate.name);\n const titleWords = wordsOf(candidate.hit.detail ?? \"\");\n const bodyTokens = candidate.body.map((part) => tokensOf(part.text));\n const doc: Doc = {\n candidate,\n nameText: nameWords.join(\" \"),\n lastText: wordsOf(lastSegment(candidate.name)).join(\" \"),\n nameWords,\n titleText: titleWords.join(\" \"),\n titleWords,\n boost: candidate.hit.type === \"feature\" || candidate.hit.type === \"flow\" ? WRITTEN_BOOST : 0,\n length: 0,\n bodyTokens,\n };\n\n if (candidate.scored) {\n const frequency = new Map<string, number>();\n const count = (tokens: string[], weight: number): void => {\n for (const token of tokens) {\n frequency.set(token, (frequency.get(token) ?? 0) + weight);\n doc.length += weight;\n }\n };\n\n count(tokensOf(candidate.idText), WEIGHT.id);\n count(tokensOf(candidate.exportNames.join(\" \")), WEIGHT.exports);\n count(tokensOf(candidate.about), WEIGHT.about);\n\n for (const tokens of bodyTokens) count(tokens, WEIGHT.body);\n\n for (const [token, weighted] of frequency) {\n const list = postings.get(token) ?? [];\n\n list.push([docs.length, weighted]);\n postings.set(token, list);\n }\n\n scoredCount++;\n totalLength += doc.length;\n }\n\n docs.push(doc);\n }\n\n const idf = new Map<string, number>();\n\n for (const [token, list] of postings) {\n idf.set(token, Math.log(1 + (scoredCount - list.length + 0.5) / (list.length + 0.5)));\n }\n\n return { docs, postings, idf, average: scoredCount === 0 ? 1 : totalLength / scoredCount };\n}\n\nconst indexes = new WeakMap<GrimoireSnapshot, SearchIndex>();\n\nfunction indexOf(snapshot: GrimoireSnapshot): SearchIndex {\n let index = indexes.get(snapshot);\n\n if (index === undefined) {\n index = buildIndex(snapshot);\n indexes.set(snapshot, index);\n }\n\n return index;\n}\n\n/**\n * The name level of a candidate for the query, or 0: the whole query is the name\n * or the title (7), starts it (6), every word is a whole word of the name or of the\n * title (5), or the words are spread over both (4).\n */\nfunction nameLevel(doc: Doc, query: string, words: readonly string[]): number {\n if (doc.nameText === query || doc.lastText === query || doc.titleText === query) return 7;\n if (\n doc.nameText.startsWith(query) ||\n doc.lastText.startsWith(query) ||\n doc.titleText.startsWith(query)\n ) {\n return 6;\n }\n\n if (\n words.every((word) => doc.nameWords.includes(word)) ||\n words.every((word) => doc.titleWords.includes(word))\n ) {\n return 5;\n }\n\n return words.every((word) => doc.nameWords.includes(word) || doc.titleWords.includes(word))\n ? 4\n : 0;\n}\n\n/** The written part that holds most of the query tokens, as `label: text`, or `undefined`. */\nfunction matchedPart(doc: Doc, tokens: readonly string[]): string | undefined {\n let best = 0;\n let found: BodyPart | undefined;\n\n doc.bodyTokens.forEach((partTokens, position) => {\n const count = tokens.filter((token) => partTokens.includes(token)).length;\n\n if (count > best) {\n best = count;\n found = doc.candidate.body[position];\n }\n });\n\n if (found === undefined) return undefined;\n\n const text = found.text.replace(/\\s+/g, \" \").trim();\n\n return `${found.label}: ${text.length > 90 ? `${text.slice(0, 89)}…` : text}`;\n}\n\nexport type SearchOutcome = {\n /** How many candidates matched, per type, before the limit cut the list. */\n counts: Partial<Record<ScryHitType, number>>;\n /** Best first. */\n hits: ScryHit[];\n};\n\n/**\n * Rank the book for a search query. A query of stop words only matches nothing.\n * Hits are in score order; on an equal score written content comes first, then a\n * page or screen file before helper files, then the type, then the id.\n */\nexport function searchSnapshot(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): SearchOutcome {\n const index = indexOf(snapshot);\n const words = wordsOf(query.text);\n const queryText = words.join(\" \");\n const tokens = [...new Set(tokensOf(query.text))];\n const outcome: SearchOutcome = { counts: {}, hits: [] };\n\n if (tokens.length === 0) return outcome;\n\n // BM25F over the terms of the query.\n const bm25 = new Map<number, number>();\n\n for (const token of tokens) {\n const list = index.postings.get(token);\n const idf = index.idf.get(token);\n\n if (list === undefined || idf === undefined) continue;\n\n for (const [position, weighted] of list) {\n const length = index.docs[position]?.length ?? 0;\n const part =\n (idf * weighted * (K1 + 1)) / (weighted + K1 * (1 - B + (B * length) / index.average));\n\n bm25.set(position, (bm25.get(position) ?? 0) + part);\n }\n }\n\n const levels = new Map<number, number>();\n\n index.docs.forEach((doc, position) => {\n const level = nameLevel(doc, queryText, words);\n\n if (level > 0) levels.set(position, level);\n });\n\n // Name matches score above every BM25F score; the BM25F score orders them inside a level.\n let highest = 0;\n\n for (const value of bm25.values()) highest = Math.max(highest, value);\n\n const offset = highest + 1;\n const matched = new Set([...bm25.keys(), ...levels.keys()]);\n const ranked: { doc: Doc; score: number; named: boolean }[] = [];\n\n for (const position of matched) {\n const doc = index.docs[position];\n\n if (doc === undefined) continue;\n if (query.app !== undefined && doc.candidate.hit.app !== query.app) continue;\n\n const level = levels.get(position);\n const score = bm25.get(position) ?? 0;\n\n ranked.push(\n level === undefined\n ? { doc, score, named: false }\n : { doc, score: offset + level + doc.boost + score / offset, named: true },\n );\n }\n\n ranked.sort(\n (left, right) =>\n right.score - left.score ||\n Number(right.doc.boost > 0) - Number(left.doc.boost > 0) ||\n Number(right.doc.candidate.pageFile) - Number(left.doc.candidate.pageFile) ||\n TYPE_ORDER.indexOf(left.doc.candidate.hit.type) -\n TYPE_ORDER.indexOf(right.doc.candidate.hit.type) ||\n byText(left.doc.candidate.hit.id, right.doc.candidate.hit.id),\n );\n\n for (const { doc } of ranked) {\n const type = doc.candidate.hit.type;\n\n outcome.counts[type] = (outcome.counts[type] ?? 0) + 1;\n }\n\n for (const { doc, score, named } of ranked.slice(0, query.limit ?? 20)) {\n // A feature or flow found by its written text shows the part that matched.\n const part = named || doc.boost === 0 ? undefined : matchedPart(doc, tokens);\n\n outcome.hits.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,SAAS,QAAQ,OAAO,SAAS,KAAK;CACvD;CAEA,KAAK,MAAM,EAAE,KAAK,OAAO,WAAW,OAAO,MAAM,GAAG,MAAM,SAAS,EAAE,GAAG;EAEtE,MAAM,OAAO,SAAS,IAAI,UAAU,IAAI,SAAY,YAAY,KAAK,MAAM;EAE3E,QAAQ,KAAK,KAAK;GAChB,GAAG,IAAI,UAAU;GACjB;GACA,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,SAAS,KAAK;EAChD,CAAC;CACH;CAEA,OAAO;AACT"}
|
package/esm/warlock/actions.mjs
CHANGED
|
@@ -13,7 +13,8 @@ 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 {
|
|
16
|
+
import { scryErrorOf } from "../scry/error.mjs";
|
|
17
|
+
import { openStoredGrimoireCached } from "../workspace/cache.mjs";
|
|
17
18
|
import path from "node:path";
|
|
18
19
|
import { createHash } from "node:crypto";
|
|
19
20
|
import { readFile, readdir } from "node:fs/promises";
|
|
@@ -59,10 +60,6 @@ async function withFreshRoutes(open) {
|
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
|
-
/** Whether the book holds route facts already (a `--route` question with none boots once). */
|
|
63
|
-
async function hasRouteFacts(root) {
|
|
64
|
-
return (await loadBook(root))?.facts.routes != null;
|
|
65
|
-
}
|
|
66
63
|
/** sha256 of a project file, `""` when it is missing (the book's boot-cache rule). */
|
|
67
64
|
async function inputHash(root, file) {
|
|
68
65
|
try {
|
|
@@ -159,6 +156,7 @@ async function runBuild(context, options = {}) {
|
|
|
159
156
|
site = exported.outDir;
|
|
160
157
|
siteUpToDate = exported.upToDate;
|
|
161
158
|
}
|
|
159
|
+
const routeNote = run.snapshot.book.routeNote;
|
|
162
160
|
if (options.json === true) {
|
|
163
161
|
printJson(io, {
|
|
164
162
|
rebuilt: run.rebuilt,
|
|
@@ -169,7 +167,8 @@ async function runBuild(context, options = {}) {
|
|
|
169
167
|
site,
|
|
170
168
|
siteUpToDate,
|
|
171
169
|
siteMode: site === null ? null : options.product === true ? "product" : "full",
|
|
172
|
-
problems: bootProblem === null ? [] : [bootProblem]
|
|
170
|
+
problems: bootProblem === null ? [] : [bootProblem],
|
|
171
|
+
...routeNote === void 0 ? {} : { note: routeNote }
|
|
173
172
|
});
|
|
174
173
|
return 0;
|
|
175
174
|
}
|
|
@@ -180,6 +179,7 @@ async function runBuild(context, options = {}) {
|
|
|
180
179
|
}
|
|
181
180
|
io.out(summary.book);
|
|
182
181
|
io.out(summary.collected);
|
|
182
|
+
if (routeNote !== void 0) io.out(`note ${routeNote}`);
|
|
183
183
|
if (site !== null) io.out(`site ${site}/index.html${options.product === true ? " (product map only)" : ""}${siteUpToDate ? " (up to date, not rebuilt)" : ""}`);
|
|
184
184
|
io.out(elapsedLine(started));
|
|
185
185
|
return 0;
|
|
@@ -246,14 +246,13 @@ async function runRelease(context, release, options = {}) {
|
|
|
246
246
|
return reportError(io, error);
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
|
-
/** Open the snapshot for a scry question:
|
|
250
|
-
async function openForScry(root, adapter
|
|
251
|
-
|
|
252
|
-
return openGrimoireCached(root, adapter, { routes });
|
|
249
|
+
/** Open the snapshot for a scry question: the stored book, read only (`GR9007` when it was never built). */
|
|
250
|
+
async function openForScry(root, adapter) {
|
|
251
|
+
return openStoredGrimoireCached(root, adapter);
|
|
253
252
|
}
|
|
254
253
|
/** Answer a parsed query (shared by the CLI and the MCP tools). */
|
|
255
254
|
async function answer(root, adapter, query) {
|
|
256
|
-
return scry(await openForScry(root, adapter
|
|
255
|
+
return scry(await openForScry(root, adapter), query);
|
|
257
256
|
}
|
|
258
257
|
/** `warlock scry <file> | --impact … | --route … | --feature … | --flow … | --search … [--limit n] [--all] [--json]`. */
|
|
259
258
|
async function runScry(context, args, options = {}) {
|
|
@@ -264,10 +263,14 @@ async function runScry(context, args, options = {}) {
|
|
|
264
263
|
else for (const line of formatScryResult(result, { all: options.all === true })) io.out(line);
|
|
265
264
|
return 0;
|
|
266
265
|
} catch (error) {
|
|
266
|
+
if (options.json === true && error instanceof GrimoireError) {
|
|
267
|
+
printJson(io, scryErrorOf(error));
|
|
268
|
+
return 1;
|
|
269
|
+
}
|
|
267
270
|
return reportError(io, error);
|
|
268
271
|
}
|
|
269
272
|
}
|
|
270
273
|
|
|
271
274
|
//#endregion
|
|
272
|
-
export { answer,
|
|
275
|
+
export { answer, isMultiSite, needsBoot, reportError, runBuild, runCheck, runRelease, runScry };
|
|
273
276
|
//# sourceMappingURL=actions.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/actions.ts"],"sourcesContent":["/**\n * What `warlock grimoire …` and `warlock scry …` do, as functions that write\n * to an `io` and return the exit code, so specs run them without a process.\n * Loaded lazily by the commands: it pulls in every Grimoire module.\n */\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkGrimoire, formatCheckReport } from \"../check\";\nimport { createFinding, explainGrimoireCode, GrimoireError } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireCheckReport, GrimoireFinding } from \"../contracts/findings\";\nimport type { ScryQuery, ScryResult } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { loadBook } from \"../book\";\nimport { projectPath } from \"../paths\";\nimport { writeRelease } from \"../releases\";\nimport { formatScryResult, parseScryQuery, scry } from \"../scry\";\nimport { runGrimoire, type GrimoireRun } from \"../workspace\";\nimport { openGrimoireCached } from \"../workspace/cache\";\nimport { parseGrimoire } from \"../written\";\n\n/** Where a command writes: `out` for its answer, `err` for problems. */\nexport type CommandIO = {\n out(line: string): void;\n err(line: string): void;\n};\n\n/** The project and adapter a command runs against. */\nexport type CommandContext = {\n /** Absolute project root. */\n root: string;\n adapter: BookAdapter;\n io: CommandIO;\n};\n\ntype Options = Readonly<Record<string, string | boolean | number>>;\n\nconst plural = (count: number, word: string, many = `${word}s`): string =>\n `${count} ${count === 1 ? word : many}`;\n\n/** Print a Grimoire error the way every command does, and return exit code 1. */\nexport function reportError(io: CommandIO, error: unknown): number {\n if (error instanceof GrimoireError) {\n io.err(`${error.code} ${error.message}`);\n\n const fix = explainGrimoireCode(error.code)?.fix;\n\n if (fix) io.err(` fix: ${fix}`);\n\n return 1;\n }\n\n throw error;\n}\n\nfunction printJson(io: CommandIO, value: unknown): void {\n io.out(JSON.stringify(value, null, 2));\n}\n\n/**\n * Open with fresh routes; when the app does not boot (`GR8002`), open again\n * with the cached ones and return the boot problem as a warning finding.\n */\nasync function withFreshRoutes<T>(\n open: (routes: \"fresh\" | \"cached\") => Promise<T>,\n): Promise<{ value: T; bootProblem: GrimoireFinding | null }> {\n try {\n return { value: await open(\"fresh\"), bootProblem: null };\n } catch (error) {\n if (!(error instanceof GrimoireError) || error.code !== \"GR8002\") throw error;\n\n return {\n value: await open(\"cached\"),\n // Finding messages start lower-case, like every other line of the check report.\n bootProblem: createFinding({\n code: \"GR8002\",\n message: `${error.message.charAt(0).toLowerCase()}${error.message.slice(1)}`,\n }),\n };\n }\n}\n\n/** Whether the book holds route facts already (a `--route` question with none boots once). */\nexport async function hasRouteFacts(root: string): Promise<boolean> {\n return (await loadBook(root))?.facts.routes != null;\n}\n\n/** sha256 of a project file, `\"\"` when it is missing (the book's boot-cache rule). */\nasync function inputHash(root: string, file: string): Promise<string> {\n try {\n return createHash(\"sha256\")\n .update(await readFile(path.join(root, ...file.split(\"/\"))))\n .digest(\"hex\");\n } catch {\n return \"\";\n }\n}\n\n/** File names whose appearance makes the route facts stale: routes files and named mails, jobs, events, notifications. */\nconst BOOT_INPUT = /^(?:routes|.+\\.(?:mail|job|event|notification))\\.[cm]?[jt]sx?$/;\n\n/** Every boot-cache candidate under `src/`: a new one makes the route facts stale. */\nasync function routesFiles(root: string, dir = \"src\"): Promise<string[]> {\n let entries;\n\n try {\n entries = await readdir(path.join(root, ...dir.split(\"/\")), { withFileTypes: true });\n } catch {\n return [];\n }\n\n const found: string[] = [];\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const file = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) found.push(...(await routesFiles(root, file)));\n else if (\n BOOT_INPUT.test(entry.name) ||\n (file.startsWith(\"src/config/\") && /\\.[cm]?[jt]sx?$/.test(entry.name))\n )\n found.push(file);\n }\n\n return found;\n}\n\n/**\n * Whether `build` or `check` will have to boot the app: `force`, no book, no\n * route facts yet, or a route-cache input changed, appeared or went away.\n * Reads files only and never calls the adapter, so it runs before anything\n * is loaded.\n */\nexport async function needsBoot(root: string, force: boolean): Promise<boolean> {\n if (force) return true;\n\n const book = await loadBook(root);\n\n if (!book || book.facts.routes === null || book.manifest.boot.collectedAt === null) return true;\n\n const inputs = book.manifest.boot.inputs;\n\n for (const [file, hash] of Object.entries(inputs)) {\n if ((await inputHash(root, file)) !== hash) return true;\n }\n\n return (await routesFiles(root)).some((file) => inputs[file] === undefined);\n}\n\n/** Whether the app has several sites, whose page routes need `src/config/web.ts` loaded. */\nexport async function isMultiSite(root: string): Promise<boolean> {\n try {\n return (await readdir(path.join(root, \"src\", \"web\", \"$sites\"), { withFileTypes: true })).some(\n (entry) => entry.isDirectory(),\n );\n } catch {\n return false;\n }\n}\n\nfunction buildSummary(run: GrimoireRun): { book: string; collected: string } {\n const snapshot = run.snapshot;\n const tasks = snapshot.collected.tasksIndex;\n const bookmaps = run.collected.written.filter((file) => file.endsWith(\"bookmap.json\")).length;\n const nothing =\n !run.rebuilt &&\n run.book.written.length +\n run.book.removed.length +\n run.collected.written.length +\n run.collected.removed.length ===\n 0;\n const book = nothing\n ? \"book up to date\"\n : `book ${plural(snapshot.book.facts.files.length, \"file\")} (${run.book.written.length} written, ${run.book.removed.length} removed), routes ${snapshot.routes}`;\n\n return {\n book,\n // `waiting` is a part of `open`: count each task once, as the devtools tab does.\n collected: `features ${snapshot.collected.featuresIndex.features.length} (bookmaps written: ${bookmaps}) tasks ${tasks.open.length - tasks.waiting.length} open, ${tasks.waiting.length} waiting, ${tasks.done.length} done`,\n };\n}\n\n/**\n * The `--out` folder of the static site, project-relative. A folder outside\n * the project, or the project itself (its own `index.html`), is refused.\n */\nfunction siteFolder(root: string, out: string): string {\n const folder = projectPath(root, out.trim());\n\n if (\n out.trim() === \"\" ||\n folder === \"\" ||\n folder === \"..\" ||\n folder.startsWith(\"../\") ||\n path.isAbsolute(folder)\n ) {\n throw new GrimoireError(\n \"GR9006\",\n `--out ${JSON.stringify(out)} is not a folder inside the project. Pass a project-relative folder, like --out public/grimoire.`,\n );\n }\n\n return folder;\n}\n\n/** `time 4.2s`, the last line of `build` and `check`. */\nfunction elapsedLine(started: number): string {\n return `time ${((Date.now() - started) / 1000).toFixed(1)}s`;\n}\n\n/** `warlock grimoire build [--force] [--site [--product] [--out <dir>]] [--json]`. */\nexport async function runBuild(context: CommandContext, options: Options = {}): Promise<number> {\n const { root, adapter, io } = context;\n const started = Date.now();\n\n try {\n const force = options.force === true;\n const outDir = typeof options.out === \"string\" ? siteFolder(root, options.out) : undefined;\n const { value: run, bootProblem } = await withFreshRoutes((routes) =>\n runGrimoire(root, adapter, { routes, force }),\n );\n let site: string | null = null;\n let siteUpToDate = false;\n\n if (options.site === true || options.product === true || typeof options.out === \"string\") {\n const { exportGrimoireSiteDetailed } = await import(\"../devtools\");\n // A page built from the same book is kept; --force writes it again.\n const exported = await exportGrimoireSiteDetailed(root, {\n adapter,\n snapshot: run.snapshot,\n force,\n ...(options.product === true ? { product: true } : {}),\n ...(outDir === undefined ? {} : { outDir }),\n });\n\n site = exported.outDir;\n siteUpToDate = exported.upToDate;\n }\n\n if (options.json === true) {\n printJson(io, {\n rebuilt: run.rebuilt,\n changed: run.changed,\n written: [...run.book.written, ...run.collected.written],\n removed: [...run.book.removed, ...run.collected.removed],\n routes: run.snapshot.routes,\n site,\n siteUpToDate,\n siteMode: site === null ? null : options.product === true ? \"product\" : \"full\",\n problems: bootProblem === null ? [] : [bootProblem],\n });\n\n return 0;\n }\n\n const summary = buildSummary(run);\n\n // The app's own boot output comes before this point; the summary is always the last lines.\n if (bootProblem !== null) {\n io.err(`${bootProblem.code} ${bootProblem.message}`);\n io.err(` fix: ${bootProblem.hint}`);\n }\n\n io.out(summary.book);\n io.out(summary.collected);\n\n if (site !== null) {\n io.out(\n `site ${site}/index.html${options.product === true ? \" (product map only)\" : \"\"}${siteUpToDate ? \" (up to date, not rebuilt)\" : \"\"}`,\n );\n }\n\n io.out(elapsedLine(started));\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** Add a boot problem to a check report as an unexpected warning. */\nfunction withProblem(\n report: GrimoireCheckReport,\n problem: GrimoireFinding | null,\n): GrimoireCheckReport {\n if (problem === null) return report;\n\n const firstExpected = report.findings.findIndex((finding) => finding.expected);\n const findings = [...report.findings];\n\n findings.splice(firstExpected === -1 ? findings.length : firstExpected, 0, problem);\n\n return {\n ...report,\n findings,\n counts: { ...report.counts, warnings: report.counts.warnings + 1 },\n };\n}\n\n/** `warlock grimoire check [--all] [--json]`: exit 1 only when the report is not ok. */\nexport async function runCheck(context: CommandContext, options: Options = {}): Promise<number> {\n const { root, adapter, io } = context;\n const started = Date.now();\n\n try {\n const { value: run, bootProblem } = await withFreshRoutes((routes) =>\n runGrimoire(root, adapter, { routes }),\n );\n const report = withProblem(checkGrimoire(run.snapshot), bootProblem);\n\n if (options.json === true) printJson(io, report);\n else {\n for (const line of formatCheckReport(report, { all: options.all === true })) io.out(line);\n\n // The app's own boot output comes before the report; the summary is always the last lines.\n io.out(buildSummary(run).book);\n io.out(elapsedLine(started));\n }\n\n return report.ok ? 0 : 1;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** `warlock grimoire release <release> [--json]`. */\nexport async function runRelease(\n context: CommandContext,\n release: string | undefined,\n options: Options = {},\n): Promise<number> {\n const { root, io } = context;\n\n try {\n const name = release?.trim() ?? \"\";\n\n if (name === \"\" || /[\\\\/]/.test(name) || name.startsWith(\".\")) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass the release name, like warlock grimoire release 1.1.0 (got ${JSON.stringify(release ?? \"\")}). It must match a file in grimoire/releases/.`,\n );\n }\n\n const { written } = await parseGrimoire(root);\n const outcome = await writeRelease(root, written, name);\n\n if (options.json === true) {\n printJson(io, outcome);\n return 0;\n }\n\n const entries = outcome.collection.entries;\n const listed = entries\n .map((entry) => `${entry.feature} ${entry.version} ${entry.word}`)\n .join(\", \");\n\n io.out(\n `${outcome.file}: ${plural(entries.length, \"entry\", \"entries\")} collected${\n entries.length > 0 ? ` (${listed})` : \"\"\n }${outcome.changed ? \"\" : \", file unchanged\"}`,\n );\n\n const unreleased = outcome.unreleased;\n\n if (unreleased.length > 0) {\n const names = unreleased.map((entry) => `${entry.feature} ${entry.version}`).join(\", \");\n const verb = unreleased.length === 1 ? \"entry is\" : \"entries are\";\n\n io.out(\n `note: ${unreleased.length} ${verb} still unreleased: ${names}. To ship them in ${name}, move them under \"## ${name} (${outcome.collection.date})\" in each feature's CHANGELOG.md and run this command again.`,\n );\n }\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** Open the snapshot for a scry question: cached routes, fresh once when a route question finds none. */\nasync function openForScry(\n root: string,\n adapter: BookAdapter,\n query: ScryQuery,\n): Promise<GrimoireSnapshot> {\n const routes: \"fresh\" | \"cached\" =\n query.type === \"route\" && !(await hasRouteFacts(root)) ? \"fresh\" : \"cached\";\n\n return openGrimoireCached(root, adapter, { routes });\n}\n\n/** Answer a parsed query (shared by the CLI and the MCP tools). */\nexport async function answer(\n root: string,\n adapter: BookAdapter,\n query: ScryQuery,\n): Promise<ScryResult> {\n return scry(await openForScry(root, adapter, query), query);\n}\n\n/** `warlock scry <file> | --impact … | --route … | --feature … | --flow … | --search … [--limit n] [--all] [--json]`. */\nexport async function runScry(\n context: CommandContext,\n args: readonly string[],\n options: Options = {},\n): Promise<number> {\n const { root, adapter, io } = context;\n\n try {\n const query = parseScryQuery(args, options);\n const result = await answer(root, adapter, query);\n\n if (options.json === true) printJson(io, result);\n else for (const line of formatScryResult(result, { all: options.all === true })) io.out(line);\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,UAAU,OAAe,MAAc,OAAO,GAAG,KAAK,OAC1D,GAAG,MAAM,GAAG,UAAU,IAAI,OAAO;;AAGnC,SAAgB,YAAY,IAAe,OAAwB;CACjE,IAAI,iBAAiB,eAAe;EAClC,GAAG,IAAI,GAAG,MAAM,KAAK,IAAI,MAAM,SAAS;EAExC,MAAM,MAAM,oBAAoB,MAAM,IAAI,CAAC,EAAE;EAE7C,IAAI,KAAK,GAAG,IAAI,UAAU,KAAK;EAE/B,OAAO;CACT;CAEA,MAAM;AACR;AAEA,SAAS,UAAU,IAAe,OAAsB;CACtD,GAAG,IAAI,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AACvC;;;;;AAMA,eAAe,gBACb,MAC4D;CAC5D,IAAI;EACF,OAAO;GAAE,OAAO,MAAM,KAAK,OAAO;GAAG,aAAa;EAAK;CACzD,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,kBAAkB,MAAM,SAAS,UAAU,MAAM;EAExE,OAAO;GACL,OAAO,MAAM,KAAK,QAAQ;GAE1B,aAAa,cAAc;IACzB,MAAM;IACN,SAAS,GAAG,MAAM,QAAQ,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,QAAQ,MAAM,CAAC;GAC3E,CAAC;EACH;CACF;AACF;;AAGA,eAAsB,cAAc,MAAgC;CAClE,QAAQ,MAAM,SAAS,IAAI,EAAC,EAAG,MAAM,UAAU;AACjD;;AAGA,eAAe,UAAU,MAAc,MA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,IAAK,UAAU;CAErE,OAAO,mBAAmB,MAAM,SAAS,EAAE,OAAO,CAAC;AACrD;;AAGA,eAAsB,OACpB,MACA,SACA,OACqB;CACrB,OAAO,KAAK,MAAM,YAAY,MAAM,SAAS,KAAK,GAAG,KAAK;AAC5D;;AAGA,eAAsB,QACpB,SACA,MACA,UAAmB,CAAC,GACH;CACjB,MAAM,EAAE,MAAM,SAAS,OAAO;CAE9B,IAAI;EAEF,MAAM,SAAS,MAAM,OAAO,MAAM,SADpB,eAAe,MAAM,OACY,CAAC;EAEhD,IAAI,QAAQ,SAAS,MAAM,UAAU,IAAI,MAAM;OAC1C,KAAK,MAAM,QAAQ,iBAAiB,QAAQ,EAAE,KAAK,QAAQ,QAAQ,KAAK,CAAC,GAAG,GAAG,IAAI,IAAI;EAE5F,OAAO;CACT,SAAS,OAAO;EACd,OAAO,YAAY,IAAI,KAAK;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"actions.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/actions.ts"],"sourcesContent":["/**\n * What `warlock grimoire …` and `warlock scry …` do, as functions that write\n * to an `io` and return the exit code, so specs run them without a process.\n * Loaded lazily by the commands: it pulls in every Grimoire module.\n */\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkGrimoire, formatCheckReport } from \"../check\";\nimport { createFinding, explainGrimoireCode, GrimoireError } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireCheckReport, GrimoireFinding } from \"../contracts/findings\";\nimport type { ScryQuery, ScryResult } from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { loadBook } from \"../book\";\nimport { projectPath } from \"../paths\";\nimport { writeRelease } from \"../releases\";\nimport { formatScryResult, parseScryQuery, scry } from \"../scry\";\nimport { scryErrorOf } from \"../scry/error\";\nimport { runGrimoire, type GrimoireRun } from \"../workspace\";\nimport { openStoredGrimoireCached } from \"../workspace/cache\";\nimport { parseGrimoire } from \"../written\";\n\n/** Where a command writes: `out` for its answer, `err` for problems. */\nexport type CommandIO = {\n out(line: string): void;\n err(line: string): void;\n};\n\n/** The project and adapter a command runs against. */\nexport type CommandContext = {\n /** Absolute project root. */\n root: string;\n adapter: BookAdapter;\n io: CommandIO;\n};\n\ntype Options = Readonly<Record<string, string | boolean | number>>;\n\nconst plural = (count: number, word: string, many = `${word}s`): string =>\n `${count} ${count === 1 ? word : many}`;\n\n/** Print a Grimoire error the way every command does, and return exit code 1. */\nexport function reportError(io: CommandIO, error: unknown): number {\n if (error instanceof GrimoireError) {\n io.err(`${error.code} ${error.message}`);\n\n const fix = explainGrimoireCode(error.code)?.fix;\n\n if (fix) io.err(` fix: ${fix}`);\n\n return 1;\n }\n\n throw error;\n}\n\nfunction printJson(io: CommandIO, value: unknown): void {\n io.out(JSON.stringify(value, null, 2));\n}\n\n/**\n * Open with fresh routes; when the app does not boot (`GR8002`), open again\n * with the cached ones and return the boot problem as a warning finding.\n */\nasync function withFreshRoutes<T>(\n open: (routes: \"fresh\" | \"cached\") => Promise<T>,\n): Promise<{ value: T; bootProblem: GrimoireFinding | null }> {\n try {\n return { value: await open(\"fresh\"), bootProblem: null };\n } catch (error) {\n if (!(error instanceof GrimoireError) || error.code !== \"GR8002\") throw error;\n\n return {\n value: await open(\"cached\"),\n // Finding messages start lower-case, like every other line of the check report.\n bootProblem: createFinding({\n code: \"GR8002\",\n message: `${error.message.charAt(0).toLowerCase()}${error.message.slice(1)}`,\n }),\n };\n }\n}\n\n/** sha256 of a project file, `\"\"` when it is missing (the book's boot-cache rule). */\nasync function inputHash(root: string, file: string): Promise<string> {\n try {\n return createHash(\"sha256\")\n .update(await readFile(path.join(root, ...file.split(\"/\"))))\n .digest(\"hex\");\n } catch {\n return \"\";\n }\n}\n\n/** File names whose appearance makes the route facts stale: routes files and named mails, jobs, events, notifications. */\nconst BOOT_INPUT = /^(?:routes|.+\\.(?:mail|job|event|notification))\\.[cm]?[jt]sx?$/;\n\n/** Every boot-cache candidate under `src/`: a new one makes the route facts stale. */\nasync function routesFiles(root: string, dir = \"src\"): Promise<string[]> {\n let entries;\n\n try {\n entries = await readdir(path.join(root, ...dir.split(\"/\")), { withFileTypes: true });\n } catch {\n return [];\n }\n\n const found: string[] = [];\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const file = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) found.push(...(await routesFiles(root, file)));\n else if (\n BOOT_INPUT.test(entry.name) ||\n (file.startsWith(\"src/config/\") && /\\.[cm]?[jt]sx?$/.test(entry.name))\n )\n found.push(file);\n }\n\n return found;\n}\n\n/**\n * Whether `build` or `check` will have to boot the app: `force`, no book, no\n * route facts yet, or a route-cache input changed, appeared or went away.\n * Reads files only and never calls the adapter, so it runs before anything\n * is loaded.\n */\nexport async function needsBoot(root: string, force: boolean): Promise<boolean> {\n if (force) return true;\n\n const book = await loadBook(root);\n\n if (!book || book.facts.routes === null || book.manifest.boot.collectedAt === null) return true;\n\n const inputs = book.manifest.boot.inputs;\n\n for (const [file, hash] of Object.entries(inputs)) {\n if ((await inputHash(root, file)) !== hash) return true;\n }\n\n return (await routesFiles(root)).some((file) => inputs[file] === undefined);\n}\n\n/** Whether the app has several sites, whose page routes need `src/config/web.ts` loaded. */\nexport async function isMultiSite(root: string): Promise<boolean> {\n try {\n return (await readdir(path.join(root, \"src\", \"web\", \"$sites\"), { withFileTypes: true })).some(\n (entry) => entry.isDirectory(),\n );\n } catch {\n return false;\n }\n}\n\nfunction buildSummary(run: GrimoireRun): { book: string; collected: string } {\n const snapshot = run.snapshot;\n const tasks = snapshot.collected.tasksIndex;\n const bookmaps = run.collected.written.filter((file) => file.endsWith(\"bookmap.json\")).length;\n const nothing =\n !run.rebuilt &&\n run.book.written.length +\n run.book.removed.length +\n run.collected.written.length +\n run.collected.removed.length ===\n 0;\n const book = nothing\n ? \"book up to date\"\n : `book ${plural(snapshot.book.facts.files.length, \"file\")} (${run.book.written.length} written, ${run.book.removed.length} removed), routes ${snapshot.routes}`;\n\n return {\n book,\n // `waiting` is a part of `open`: count each task once, as the devtools tab does.\n collected: `features ${snapshot.collected.featuresIndex.features.length} (bookmaps written: ${bookmaps}) tasks ${tasks.open.length - tasks.waiting.length} open, ${tasks.waiting.length} waiting, ${tasks.done.length} done`,\n };\n}\n\n/**\n * The `--out` folder of the static site, project-relative. A folder outside\n * the project, or the project itself (its own `index.html`), is refused.\n */\nfunction siteFolder(root: string, out: string): string {\n const folder = projectPath(root, out.trim());\n\n if (\n out.trim() === \"\" ||\n folder === \"\" ||\n folder === \"..\" ||\n folder.startsWith(\"../\") ||\n path.isAbsolute(folder)\n ) {\n throw new GrimoireError(\n \"GR9006\",\n `--out ${JSON.stringify(out)} is not a folder inside the project. Pass a project-relative folder, like --out public/grimoire.`,\n );\n }\n\n return folder;\n}\n\n/** `time 4.2s`, the last line of `build` and `check`. */\nfunction elapsedLine(started: number): string {\n return `time ${((Date.now() - started) / 1000).toFixed(1)}s`;\n}\n\n/** `warlock grimoire build [--force] [--site [--product] [--out <dir>]] [--json]`. */\nexport async function runBuild(context: CommandContext, options: Options = {}): Promise<number> {\n const { root, adapter, io } = context;\n const started = Date.now();\n\n try {\n const force = options.force === true;\n const outDir = typeof options.out === \"string\" ? siteFolder(root, options.out) : undefined;\n const { value: run, bootProblem } = await withFreshRoutes((routes) =>\n runGrimoire(root, adapter, { routes, force }),\n );\n let site: string | null = null;\n let siteUpToDate = false;\n\n if (options.site === true || options.product === true || typeof options.out === \"string\") {\n const { exportGrimoireSiteDetailed } = await import(\"../devtools\");\n // A page built from the same book is kept; --force writes it again.\n const exported = await exportGrimoireSiteDetailed(root, {\n adapter,\n snapshot: run.snapshot,\n force,\n ...(options.product === true ? { product: true } : {}),\n ...(outDir === undefined ? {} : { outDir }),\n });\n\n site = exported.outDir;\n siteUpToDate = exported.upToDate;\n }\n\n // A live read refused for finding far fewer routes than the book holds.\n const routeNote = run.snapshot.book.routeNote;\n\n if (options.json === true) {\n printJson(io, {\n rebuilt: run.rebuilt,\n changed: run.changed,\n written: [...run.book.written, ...run.collected.written],\n removed: [...run.book.removed, ...run.collected.removed],\n routes: run.snapshot.routes,\n site,\n siteUpToDate,\n siteMode: site === null ? null : options.product === true ? \"product\" : \"full\",\n problems: bootProblem === null ? [] : [bootProblem],\n ...(routeNote === undefined ? {} : { note: routeNote }),\n });\n\n return 0;\n }\n\n const summary = buildSummary(run);\n\n // The app's own boot output comes before this point; the summary is always the last lines.\n if (bootProblem !== null) {\n io.err(`${bootProblem.code} ${bootProblem.message}`);\n io.err(` fix: ${bootProblem.hint}`);\n }\n\n io.out(summary.book);\n io.out(summary.collected);\n\n if (routeNote !== undefined) io.out(`note ${routeNote}`);\n\n if (site !== null) {\n io.out(\n `site ${site}/index.html${options.product === true ? \" (product map only)\" : \"\"}${siteUpToDate ? \" (up to date, not rebuilt)\" : \"\"}`,\n );\n }\n\n io.out(elapsedLine(started));\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** Add a boot problem to a check report as an unexpected warning. */\nfunction withProblem(\n report: GrimoireCheckReport,\n problem: GrimoireFinding | null,\n): GrimoireCheckReport {\n if (problem === null) return report;\n\n const firstExpected = report.findings.findIndex((finding) => finding.expected);\n const findings = [...report.findings];\n\n findings.splice(firstExpected === -1 ? findings.length : firstExpected, 0, problem);\n\n return {\n ...report,\n findings,\n counts: { ...report.counts, warnings: report.counts.warnings + 1 },\n };\n}\n\n/** `warlock grimoire check [--all] [--json]`: exit 1 only when the report is not ok. */\nexport async function runCheck(context: CommandContext, options: Options = {}): Promise<number> {\n const { root, adapter, io } = context;\n const started = Date.now();\n\n try {\n const { value: run, bootProblem } = await withFreshRoutes((routes) =>\n runGrimoire(root, adapter, { routes }),\n );\n const report = withProblem(checkGrimoire(run.snapshot), bootProblem);\n\n if (options.json === true) printJson(io, report);\n else {\n for (const line of formatCheckReport(report, { all: options.all === true })) io.out(line);\n\n // The app's own boot output comes before the report; the summary is always the last lines.\n io.out(buildSummary(run).book);\n io.out(elapsedLine(started));\n }\n\n return report.ok ? 0 : 1;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** `warlock grimoire release <release> [--json]`. */\nexport async function runRelease(\n context: CommandContext,\n release: string | undefined,\n options: Options = {},\n): Promise<number> {\n const { root, io } = context;\n\n try {\n const name = release?.trim() ?? \"\";\n\n if (name === \"\" || /[\\\\/]/.test(name) || name.startsWith(\".\")) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass the release name, like warlock grimoire release 1.1.0 (got ${JSON.stringify(release ?? \"\")}). It must match a file in grimoire/releases/.`,\n );\n }\n\n const { written } = await parseGrimoire(root);\n const outcome = await writeRelease(root, written, name);\n\n if (options.json === true) {\n printJson(io, outcome);\n return 0;\n }\n\n const entries = outcome.collection.entries;\n const listed = entries\n .map((entry) => `${entry.feature} ${entry.version} ${entry.word}`)\n .join(\", \");\n\n io.out(\n `${outcome.file}: ${plural(entries.length, \"entry\", \"entries\")} collected${\n entries.length > 0 ? ` (${listed})` : \"\"\n }${outcome.changed ? \"\" : \", file unchanged\"}`,\n );\n\n const unreleased = outcome.unreleased;\n\n if (unreleased.length > 0) {\n const names = unreleased.map((entry) => `${entry.feature} ${entry.version}`).join(\", \");\n const verb = unreleased.length === 1 ? \"entry is\" : \"entries are\";\n\n io.out(\n `note: ${unreleased.length} ${verb} still unreleased: ${names}. To ship them in ${name}, move them under \"## ${name} (${outcome.collection.date})\" in each feature's CHANGELOG.md and run this command again.`,\n );\n }\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n\n/** Open the snapshot for a scry question: the stored book, read only (`GR9007` when it was never built). */\nasync function openForScry(root: string, adapter: BookAdapter): Promise<GrimoireSnapshot> {\n return openStoredGrimoireCached(root, adapter);\n}\n\n/** Answer a parsed query (shared by the CLI and the MCP tools). */\nexport async function answer(\n root: string,\n adapter: BookAdapter,\n query: ScryQuery,\n): Promise<ScryResult> {\n return scry(await openForScry(root, adapter), query);\n}\n\n/** `warlock scry <file> | --impact … | --route … | --feature … | --flow … | --search … [--limit n] [--all] [--json]`. */\nexport async function runScry(\n context: CommandContext,\n args: readonly string[],\n options: Options = {},\n): Promise<number> {\n const { root, adapter, io } = context;\n\n try {\n const query = parseScryQuery(args, options);\n const result = await answer(root, adapter, query);\n\n if (options.json === true) printJson(io, result);\n else for (const line of formatScryResult(result, { all: options.all === true })) io.out(line);\n\n return 0;\n } catch (error) {\n if (options.json === true && error instanceof GrimoireError) {\n printJson(io, scryErrorOf(error));\n\n return 1;\n }\n\n return reportError(io, error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,UAAU,OAAe,MAAc,OAAO,GAAG,KAAK,OAC1D,GAAG,MAAM,GAAG,UAAU,IAAI,OAAO;;AAGnC,SAAgB,YAAY,IAAe,OAAwB;CACjE,IAAI,iBAAiB,eAAe;EAClC,GAAG,IAAI,GAAG,MAAM,KAAK,IAAI,MAAM,SAAS;EAExC,MAAM,MAAM,oBAAoB,MAAM,IAAI,CAAC,EAAE;EAE7C,IAAI,KAAK,GAAG,IAAI,UAAU,KAAK;EAE/B,OAAO;CACT;CAEA,MAAM;AACR;AAEA,SAAS,UAAU,IAAe,OAAsB;CACtD,GAAG,IAAI,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AACvC;;;;;AAMA,eAAe,gBACb,MAC4D;CAC5D,IAAI;EACF,OAAO;GAAE,OAAO,MAAM,KAAK,OAAO;GAAG,aAAa;EAAK;CACzD,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,kBAAkB,MAAM,SAAS,UAAU,MAAM;EAExE,OAAO;GACL,OAAO,MAAM,KAAK,QAAQ;GAE1B,aAAa,cAAc;IACzB,MAAM;IACN,SAAS,GAAG,MAAM,QAAQ,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,QAAQ,MAAM,CAAC;GAC3E,CAAC;E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AK,8DAClJ;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,OAAO,YAAY,IAAI,KAAK;CAC9B;AACF;;AAGA,eAAe,YAAY,MAAc,SAAiD;CACxF,OAAO,yBAAyB,MAAM,OAAO;AAC/C;;AAGA,eAAsB,OACpB,MACA,SACA,OACqB;CACrB,OAAO,KAAK,MAAM,YAAY,MAAM,OAAO,GAAG,KAAK;AACrD;;AAGA,eAAsB,QACpB,SACA,MACA,UAAmB,CAAC,GACH;CACjB,MAAM,EAAE,MAAM,SAAS,OAAO;CAE9B,IAAI;EAEF,MAAM,SAAS,MAAM,OAAO,MAAM,SADpB,eAAe,MAAM,OACY,CAAC;EAEhD,IAAI,QAAQ,SAAS,MAAM,UAAU,IAAI,MAAM;OAC1C,KAAK,MAAM,QAAQ,iBAAiB,QAAQ,EAAE,KAAK,QAAQ,QAAQ,KAAK,CAAC,GAAG,GAAG,IAAI,IAAI;EAE5F,OAAO;CACT,SAAS,OAAO;EACd,IAAI,QAAQ,SAAS,QAAQ,iBAAiB,eAAe;GAC3D,UAAU,IAAI,YAAY,KAAK,CAAC;GAEhC,OAAO;EACT;EAEA,OAAO,YAAY,IAAI,KAAK;CAC9B;AACF"}
|
package/esm/warlock/commands.mjs
CHANGED
|
@@ -141,10 +141,10 @@ function registerGrimoireCommands(options = {}) {
|
|
|
141
141
|
});
|
|
142
142
|
const scry = command({
|
|
143
143
|
name: "scry [file]",
|
|
144
|
-
description: "Grimoire (experimental): ask about a file, --impact <file>, --route \"<METHOD path>\", --feature <id>, --flow <feature>/<flow> or --search \"<text>\"; --json for JSON",
|
|
144
|
+
description: "Grimoire (experimental): ask the stored book about a file, --impact <file>, --route \"<METHOD path>\" (an API route or a page URL), --feature <id>, --flow <feature>/<flow> or --search \"<text>\" (pass the whole sentence; hits come in score order, --app limits to one app); --json for JSON. Reads only; run warlock grimoire build after editing",
|
|
145
145
|
preAction: async ({ options: flags }) => {
|
|
146
146
|
scry.commandPreload = void 0;
|
|
147
|
-
const preload = await preloadFor(async () =>
|
|
147
|
+
const preload = await preloadFor(async () => false);
|
|
148
148
|
if (preload) scry.commandPreload = preload;
|
|
149
149
|
},
|
|
150
150
|
action: async ({ args, options: flags }) => {
|
|
@@ -159,7 +159,12 @@ function registerGrimoireCommands(options = {}) {
|
|
|
159
159
|
},
|
|
160
160
|
{
|
|
161
161
|
text: "--route",
|
|
162
|
-
description: "One route: \"<METHOD> <path>\"",
|
|
162
|
+
description: "One route or page URL: \"<METHOD> <path>\" (GET and HEAD also find pages and screens)",
|
|
163
|
+
type: "string"
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
text: "--site",
|
|
167
|
+
description: "--route: only the page of this site or app",
|
|
163
168
|
type: "string"
|
|
164
169
|
},
|
|
165
170
|
{
|
|
@@ -174,7 +179,12 @@ function registerGrimoireCommands(options = {}) {
|
|
|
174
179
|
},
|
|
175
180
|
{
|
|
176
181
|
text: "--search",
|
|
177
|
-
description: "Search by words",
|
|
182
|
+
description: "Search by a sentence (a commit title, a bug report) or words; names first, then best match",
|
|
183
|
+
type: "string"
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
text: "--app",
|
|
187
|
+
description: "--search: only hits of this app",
|
|
178
188
|
type: "string"
|
|
179
189
|
},
|
|
180
190
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/commands.ts"],"sourcesContent":["/**\n * The `warlock grimoire` and `warlock scry` commands. Light on purpose: the\n * work lives in `./actions`, imported when a command runs.\n */\nimport {\n command,\n withExplainCodes,\n withMcpTools,\n type CLICommand,\n type CLICommandPreload,\n} from \"@warlock.js/core\";\nimport { explainGrimoireCode, grimoireCodeDocsUrl } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { WarlockAdapterOptions } from \"./adapter\";\nimport { createGrimoireMcpTools } from \"./mcp-tools\";\n\n/** The preload of a command that reads routes: the `warlock inspect` boot. */\nconst BOOT: CLICommandPreload = {\n runtimeStrategy: \"development\",\n config: true,\n env: true,\n bootstrap: true,\n};\n\n/** No boot, but a multi-site app's `src/config/web.ts` (its sites' base paths shape the page routes). */\nconst WEB_CONFIG: CLICommandPreload = { config: [\"web\"] };\n\n/** The preload of a question that boots only when `boot` says so. */\nasync function preloadFor(boot: () => Promise<boolean>): Promise<CLICommandPreload | undefined> {\n try {\n const actions = await import(\"./actions\");\n\n if (await boot()) return BOOT;\n\n return (await actions.isMultiSite(process.cwd())) ? WEB_CONFIG : undefined;\n } catch {\n // The action runs the same steps and reports the problem with its code.\n return undefined;\n }\n}\n\nconst GRIMOIRE_ACTIONS = [\"build\", \"check\", \"release\"] as const;\n\n/** Print with the stream's own write, so a boot that moves `console.log` never mixes into the answer. */\nconst io = {\n out: (line: string) => void process.stdout.write(`${line}\\n`),\n err: (line: string) => void process.stderr.write(`${line}\\n`),\n};\n\n/** Exit with `code` once stdout and stderr are flushed (a non-zero code only; 0 lets the CLI finish). */\nasync function exitWith(code: number): Promise<void> {\n if (code === 0) return;\n\n process.exitCode = code;\n\n await Promise.race([\n Promise.all(\n [process.stdout, process.stderr].map(\n (stream) => new Promise<void>((resolve) => stream.write(\"\", () => resolve())),\n ),\n ),\n new Promise<void>((resolve) => setTimeout(resolve, 500).unref()),\n ]);\n\n process.exit(code);\n}\n\n/** Explain a Grimoire code for `warlock explain GR2001`. */\nfunction explainCode(code: string) {\n const definition = explainGrimoireCode(code);\n\n return definition\n ? {\n code: definition.code,\n title: definition.title,\n area: definition.area,\n fix: definition.fix,\n skill: definition.skill,\n docs: grimoireCodeDocsUrl(definition.code),\n }\n : undefined;\n}\n\n/**\n * The `grimoire <action> [release]` and `scry [file]` commands, with the\n * Grimoire MCP tools and the `GRnnnn` explainer attached. `cli.commands`\n * accepts this array as one entry.\n *\n * @example\n * // warlock.config.ts\n * export default defineConfig({ cli: { commands: [registerGrimoireCommands()] } });\n */\nexport function registerGrimoireCommands(options: WarlockAdapterOptions = {}): CLICommand[] {\n let adapter: Promise<BookAdapter> | undefined;\n const loadAdapter = (): Promise<BookAdapter> => {\n adapter ??= import(\"./adapter\").then(({ createWarlockAdapter }) =>\n createWarlockAdapter(options),\n );\n\n return adapter;\n };\n const context = async () => ({ root: process.cwd(), adapter: await loadAdapter(), io });\n\n const grimoire: CLICommand = command({\n name: \"grimoire <action> [release]\",\n description:\n \"Grimoire (experimental): build the book (build [--force] [--site [--product] [--out <dir>]]), check the written files (check [--all]), collect a release (release <version>); --json for JSON\",\n preAction: async ({ args, options: flags }) => {\n grimoire.commandPreload = undefined;\n\n if (args[0] !== \"build\" && args[0] !== \"check\") return;\n\n const preload = await preloadFor(async () =>\n (await import(\"./actions\")).needsBoot(process.cwd(), flags.force === true),\n );\n\n if (preload) grimoire.commandPreload = preload;\n },\n action: async ({ args, options: flags }) => {\n const actions = await import(\"./actions\");\n const ctx = await context();\n const [name, release] = args;\n let code: number;\n\n switch (name) {\n case \"build\":\n code = await actions.runBuild(ctx, flags);\n break;\n case \"check\":\n code = await actions.runCheck(ctx, flags);\n break;\n case \"release\":\n code = await actions.runRelease(ctx, release, flags);\n break;\n default: {\n const { GrimoireError } = await import(\"../codes\");\n\n code = actions.reportError(\n io,\n new GrimoireError(\n \"GR9006\",\n `Unknown action ${JSON.stringify(name ?? \"\")}. Use one of: ${GRIMOIRE_ACTIONS.join(\", \")} (warlock grimoire build).`,\n ),\n );\n }\n }\n\n await exitWith(code);\n },\n options: [\n { text: \"--json, -j\", description: \"Print the result as JSON\", type: \"boolean\" },\n {\n text: \"--all\",\n description: \"check: list every finding (text output groups warnings by code)\",\n type: \"boolean\",\n },\n {\n text: \"--force, -f\",\n description:\n \"build: rebuild every book entry and read the routes again, and write the site even when it is up to date\",\n type: \"boolean\",\n },\n {\n text: \"--site\",\n description: \"build: also write the static Grimoire site (default grimoire/book/site)\",\n type: \"boolean\",\n },\n {\n text: \"--product\",\n description:\n \"build --site: export the share-safe Product map only (no file paths, test names or per-file answers; opens on the map)\",\n type: \"boolean\",\n },\n {\n text: \"--out\",\n description: \"build --site: the folder to write the site to (project-relative)\",\n type: \"string\",\n },\n ],\n });\n\n const scry: CLICommand = command({\n name: \"scry [file]\",\n description:\n 'Grimoire (experimental): ask about a file, --impact <file>, --route \"<METHOD path>\", --feature <id>, --flow <feature>/<flow> or --search \"<text>\"; --json for JSON',\n preAction: async ({ options: flags }) => {\n scry.commandPreload = undefined;\n\n // The first route question of a project with no route facts reads them once.\n const preload = await preloadFor(\n async () =>\n flags.route !== undefined &&\n !(await (await import(\"./actions\")).hasRouteFacts(process.cwd())),\n );\n\n if (preload) scry.commandPreload = preload;\n },\n action: async ({ args, options: flags }) => {\n const { runScry } = await import(\"./actions\");\n\n await exitWith(await runScry(await context(), args, flags));\n },\n options: [\n { text: \"--impact\", description: \"What a change to this file reaches\", type: \"string\" },\n { text: \"--route\", description: 'One route: \"<METHOD> <path>\"', type: \"string\" },\n { text: \"--feature\", description: \"One feature by id\", type: \"string\" },\n { text: \"--flow\", description: \"One flow: <feature>/<flow>\", type: \"string\" },\n { text: \"--search\", description: \"Search by words\", type: \"string\" },\n { text: \"--limit\", description: \"--search: most hits (default 20)\", type: \"number\" },\n {\n text: \"--all\",\n description: \"--impact: print every line of every list (text output stops at 20)\",\n type: \"boolean\",\n },\n { text: \"--json, -j\", description: \"Print the answer as JSON\", type: \"boolean\" },\n ],\n });\n\n withMcpTools(grimoire, [(mcp) => createGrimoireMcpTools(mcp, options)]);\n withExplainCodes(grimoire, explainCode);\n\n return [grimoire, scry];\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,OAA0B;CAC9B,iBAAiB;CACjB,QAAQ;CACR,KAAK;CACL,WAAW;AACb;;AAGA,MAAM,aAAgC,EAAE,QAAQ,CAAC,KAAK,EAAE;;AAGxD,eAAe,WAAW,MAAsE;CAC9F,IAAI;EACF,MAAM,UAAU,MAAM,OAAO;EAE7B,IAAI,MAAM,KAAK,GAAG,OAAO;EAEzB,OAAQ,MA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,cAAc,QAAQ,IAAI,CAAC,CACnE;GAEA,IAAI,SAAS,KAAK,iBAAiB;EACrC;EACA,QAAQ,OAAO,EAAE,MAAM,SAAS,YAAY;GAC1C,MAAM,EAAE,YAAY,MAAM,OAAO;GAEjC,MAAM,SAAS,MAAM,QAAQ,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC;EAC5D;EACA,SAAS;GACP;IAAE,MAAM;IAAY,aAAa;IAAsC,MAAM;GAAS;GACtF;IAAE,MAAM;IAAW,aAAa;IAAgC,MAAM;GAAS;GAC/E;IAAE,MAAM;IAAa,aAAa;IAAqB,MAAM;GAAS;GACtE;IAAE,MAAM;IAAU,aAAa;IAA8B,MAAM;GAAS;GAC5E;IAAE,MAAM;IAAY,aAAa;IAAmB,MAAM;GAAS;GACnE;IAAE,MAAM;IAAW,aAAa;IAAoC,MAAM;GAAS;GACnF;IACE,MAAM;IACN,aAAa;IACb,MAAM;GACR;GACA;IAAE,MAAM;IAAc,aAAa;IAA4B,MAAM;GAAU;EACjF;CACF,CAAC;CAED,aAAa,UAAU,EAAE,QAAQ,uBAAuB,KAAK,OAAO,CAAC,CAAC;CACtE,iBAAiB,UAAU,WAAW;CAEtC,OAAO,CAAC,UAAU,IAAI;AACxB"}
|
|
1
|
+
{"version":3,"file":"commands.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/commands.ts"],"sourcesContent":["/**\n * The `warlock grimoire` and `warlock scry` commands. Light on purpose: the\n * work lives in `./actions`, imported when a command runs.\n */\nimport {\n command,\n withExplainCodes,\n withMcpTools,\n type CLICommand,\n type CLICommandPreload,\n} from \"@warlock.js/core\";\nimport { explainGrimoireCode, grimoireCodeDocsUrl } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { WarlockAdapterOptions } from \"./adapter\";\nimport { createGrimoireMcpTools } from \"./mcp-tools\";\n\n/** The preload of a command that reads routes: the `warlock inspect` boot. */\nconst BOOT: CLICommandPreload = {\n runtimeStrategy: \"development\",\n config: true,\n env: true,\n bootstrap: true,\n};\n\n/** No boot, but a multi-site app's `src/config/web.ts` (its sites' base paths shape the page routes). */\nconst WEB_CONFIG: CLICommandPreload = { config: [\"web\"] };\n\n/** The preload of a question that boots only when `boot` says so. */\nasync function preloadFor(boot: () => Promise<boolean>): Promise<CLICommandPreload | undefined> {\n try {\n const actions = await import(\"./actions\");\n\n if (await boot()) return BOOT;\n\n return (await actions.isMultiSite(process.cwd())) ? WEB_CONFIG : undefined;\n } catch {\n // The action runs the same steps and reports the problem with its code.\n return undefined;\n }\n}\n\nconst GRIMOIRE_ACTIONS = [\"build\", \"check\", \"release\"] as const;\n\n/** Print with the stream's own write, so a boot that moves `console.log` never mixes into the answer. */\nconst io = {\n out: (line: string) => void process.stdout.write(`${line}\\n`),\n err: (line: string) => void process.stderr.write(`${line}\\n`),\n};\n\n/** Exit with `code` once stdout and stderr are flushed (a non-zero code only; 0 lets the CLI finish). */\nasync function exitWith(code: number): Promise<void> {\n if (code === 0) return;\n\n process.exitCode = code;\n\n await Promise.race([\n Promise.all(\n [process.stdout, process.stderr].map(\n (stream) => new Promise<void>((resolve) => stream.write(\"\", () => resolve())),\n ),\n ),\n new Promise<void>((resolve) => setTimeout(resolve, 500).unref()),\n ]);\n\n process.exit(code);\n}\n\n/** Explain a Grimoire code for `warlock explain GR2001`. */\nfunction explainCode(code: string) {\n const definition = explainGrimoireCode(code);\n\n return definition\n ? {\n code: definition.code,\n title: definition.title,\n area: definition.area,\n fix: definition.fix,\n skill: definition.skill,\n docs: grimoireCodeDocsUrl(definition.code),\n }\n : undefined;\n}\n\n/**\n * The `grimoire <action> [release]` and `scry [file]` commands, with the\n * Grimoire MCP tools and the `GRnnnn` explainer attached. `cli.commands`\n * accepts this array as one entry.\n *\n * @example\n * // warlock.config.ts\n * export default defineConfig({ cli: { commands: [registerGrimoireCommands()] } });\n */\nexport function registerGrimoireCommands(options: WarlockAdapterOptions = {}): CLICommand[] {\n let adapter: Promise<BookAdapter> | undefined;\n const loadAdapter = (): Promise<BookAdapter> => {\n adapter ??= import(\"./adapter\").then(({ createWarlockAdapter }) =>\n createWarlockAdapter(options),\n );\n\n return adapter;\n };\n const context = async () => ({ root: process.cwd(), adapter: await loadAdapter(), io });\n\n const grimoire: CLICommand = command({\n name: \"grimoire <action> [release]\",\n description:\n \"Grimoire (experimental): build the book (build [--force] [--site [--product] [--out <dir>]]), check the written files (check [--all]), collect a release (release <version>); --json for JSON\",\n preAction: async ({ args, options: flags }) => {\n grimoire.commandPreload = undefined;\n\n if (args[0] !== \"build\" && args[0] !== \"check\") return;\n\n const preload = await preloadFor(async () =>\n (await import(\"./actions\")).needsBoot(process.cwd(), flags.force === true),\n );\n\n if (preload) grimoire.commandPreload = preload;\n },\n action: async ({ args, options: flags }) => {\n const actions = await import(\"./actions\");\n const ctx = await context();\n const [name, release] = args;\n let code: number;\n\n switch (name) {\n case \"build\":\n code = await actions.runBuild(ctx, flags);\n break;\n case \"check\":\n code = await actions.runCheck(ctx, flags);\n break;\n case \"release\":\n code = await actions.runRelease(ctx, release, flags);\n break;\n default: {\n const { GrimoireError } = await import(\"../codes\");\n\n code = actions.reportError(\n io,\n new GrimoireError(\n \"GR9006\",\n `Unknown action ${JSON.stringify(name ?? \"\")}. Use one of: ${GRIMOIRE_ACTIONS.join(\", \")} (warlock grimoire build).`,\n ),\n );\n }\n }\n\n await exitWith(code);\n },\n options: [\n { text: \"--json, -j\", description: \"Print the result as JSON\", type: \"boolean\" },\n {\n text: \"--all\",\n description: \"check: list every finding (text output groups warnings by code)\",\n type: \"boolean\",\n },\n {\n text: \"--force, -f\",\n description:\n \"build: rebuild every book entry and read the routes again, and write the site even when it is up to date\",\n type: \"boolean\",\n },\n {\n text: \"--site\",\n description: \"build: also write the static Grimoire site (default grimoire/book/site)\",\n type: \"boolean\",\n },\n {\n text: \"--product\",\n description:\n \"build --site: export the share-safe Product map only (no file paths, test names or per-file answers; opens on the map)\",\n type: \"boolean\",\n },\n {\n text: \"--out\",\n description: \"build --site: the folder to write the site to (project-relative)\",\n type: \"string\",\n },\n ],\n });\n\n const scry: CLICommand = command({\n name: \"scry [file]\",\n description:\n 'Grimoire (experimental): ask the stored book about a file, --impact <file>, --route \"<METHOD path>\" (an API route or a page URL), --feature <id>, --flow <feature>/<flow> or --search \"<text>\" (pass the whole sentence; hits come in score order, --app limits to one app); --json for JSON. Reads only; run warlock grimoire build after editing',\n preAction: async ({ options: flags }) => {\n scry.commandPreload = undefined;\n\n // scry only reads the stored book: it never boots the app (a multi-site app still loads its web config).\n const preload = await preloadFor(async () => false);\n\n if (preload) scry.commandPreload = preload;\n },\n action: async ({ args, options: flags }) => {\n const { runScry } = await import(\"./actions\");\n\n await exitWith(await runScry(await context(), args, flags));\n },\n options: [\n { text: \"--impact\", description: \"What a change to this file reaches\", type: \"string\" },\n {\n text: \"--route\",\n description:\n 'One route or page URL: \"<METHOD> <path>\" (GET and HEAD also find pages and screens)',\n type: \"string\",\n },\n { text: \"--site\", description: \"--route: only the page of this site or app\", type: \"string\" },\n { text: \"--feature\", description: \"One feature by id\", type: \"string\" },\n { text: \"--flow\", description: \"One flow: <feature>/<flow>\", type: \"string\" },\n {\n text: \"--search\",\n description:\n \"Search by a sentence (a commit title, a bug report) or words; names first, then best match\",\n type: \"string\",\n },\n { text: \"--app\", description: \"--search: only hits of this app\", type: \"string\" },\n { text: \"--limit\", description: \"--search: most hits (default 20)\", type: \"number\" },\n {\n text: \"--all\",\n description: \"--impact: print every line of every list (text output stops at 20)\",\n type: \"boolean\",\n },\n { text: \"--json, -j\", description: \"Print the answer as JSON\", type: \"boolean\" },\n ],\n });\n\n withMcpTools(grimoire, [(mcp) => createGrimoireMcpTools(mcp, options)]);\n withExplainCodes(grimoire, explainCode);\n\n return [grimoire, scry];\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,OAA0B;CAC9B,iBAAiB;CACjB,QAAQ;CACR,KAAK;CACL,WAAW;AACb;;AAGA,MAAM,aAAgC,EAAE,QAAQ,CAAC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W,OAAO,EAAE,SAAS,YAAY;GACvC,KAAK,iBAAiB;GAGtB,MAAM,UAAU,MAAM,WAAW,YAAY,KAAK;GAElD,IAAI,SAAS,KAAK,iBAAiB;EACrC;EACA,QAAQ,OAAO,EAAE,MAAM,SAAS,YAAY;GAC1C,MAAM,EAAE,YAAY,MAAM,OAAO;GAEjC,MAAM,SAAS,MAAM,QAAQ,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC;EAC5D;EACA,SAAS;GACP;IAAE,MAAM;IAAY,aAAa;IAAsC,MAAM;GAAS;GACtF;IACE,MAAM;IACN,aACE;IACF,MAAM;GACR;GACA;IAAE,MAAM;IAAU,aAAa;IAA8C,MAAM;GAAS;GAC5F;IAAE,MAAM;IAAa,aAAa;IAAqB,MAAM;GAAS;GACtE;IAAE,MAAM;IAAU,aAAa;IAA8B,MAAM;GAAS;GAC5E;IACE,MAAM;IACN,aACE;IACF,MAAM;GACR;GACA;IAAE,MAAM;IAAS,aAAa;IAAmC,MAAM;GAAS;GAChF;IAAE,MAAM;IAAW,aAAa;IAAoC,MAAM;GAAS;GACnF;IACE,MAAM;IACN,aAAa;IACb,MAAM;GACR;GACA;IAAE,MAAM;IAAc,aAAa;IAA4B,MAAM;GAAU;EACjF;CACF,CAAC;CAED,aAAa,UAAU,EAAE,QAAQ,uBAAuB,KAAK,OAAO,CAAC,CAAC;CACtE,iBAAiB,UAAU,WAAW;CAEtC,OAAO,CAAC,UAAU,IAAI;AACxB"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GrimoireError, explainGrimoireCode, grimoireCodeDocsUrl } from "../codes/index.mjs";
|
|
2
|
+
import { scryErrorOf } from "../scry/error.mjs";
|
|
2
3
|
import { inputSchema } from "@warlock.js/core";
|
|
3
4
|
|
|
4
5
|
//#region ../../packages/grimoire/src/warlock/mcp-tools.ts
|
|
@@ -7,7 +8,7 @@ import { inputSchema } from "@warlock.js/core";
|
|
|
7
8
|
* loads its code inside `run`, so registering them costs nothing at start.
|
|
8
9
|
* Answers are the same JSON objects `--json` prints.
|
|
9
10
|
*/
|
|
10
|
-
/** A Grimoire error as a tool error: the code, what failed, and what to do. */
|
|
11
|
+
/** A Grimoire error of a non-scry tool (check, build, release) as a tool error: the code, what failed, and what to do. */
|
|
11
12
|
function toolError(error) {
|
|
12
13
|
if (error instanceof GrimoireError) {
|
|
13
14
|
const fix = explainGrimoireCode(error.code)?.fix;
|
|
@@ -15,6 +16,15 @@ function toolError(error) {
|
|
|
15
16
|
}
|
|
16
17
|
throw error;
|
|
17
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* A scry error as a tool error whose text is the `ScryError` JSON that
|
|
21
|
+
* `warlock scry --json` prints (`{ "type": "error", "code", "message", "fix" }`).
|
|
22
|
+
* It stays a thrown error so the MCP result is still marked `isError`.
|
|
23
|
+
*/
|
|
24
|
+
function scryToolError(error) {
|
|
25
|
+
if (error instanceof GrimoireError) throw new Error(JSON.stringify(scryErrorOf(error)));
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
18
28
|
function text(input, name) {
|
|
19
29
|
const value = input[name];
|
|
20
30
|
return typeof value === "string" ? value : "";
|
|
@@ -35,7 +45,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
35
45
|
const { answer } = await import("./actions.mjs");
|
|
36
46
|
return await answer(root, await loadAdapter(), await query(input));
|
|
37
47
|
} catch (error) {
|
|
38
|
-
return
|
|
48
|
+
return scryToolError(error);
|
|
39
49
|
}
|
|
40
50
|
};
|
|
41
51
|
const scryParts = () => import("../scry/index.mjs");
|
|
@@ -68,7 +78,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
68
78
|
},
|
|
69
79
|
{
|
|
70
80
|
name: "grimoire_route",
|
|
71
|
-
description: "One HTTP route: handler and its file, routes file, middleware, guard, the files behind it and the flow steps that name it. Read-only.",
|
|
81
|
+
description: "One HTTP route: handler and its file, routes file, middleware, guard, the files behind it and the flow steps that name it. For GET and HEAD a page or screen URL also works: it returns every site serving the page with its file, setup file, layouts and their imports. Read-only.",
|
|
72
82
|
input: inputSchema({
|
|
73
83
|
method: {
|
|
74
84
|
type: "string",
|
|
@@ -76,15 +86,21 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
76
86
|
},
|
|
77
87
|
path: {
|
|
78
88
|
type: "string",
|
|
79
|
-
description: "Path as registered (/api/products/:id)."
|
|
89
|
+
description: "Path as registered (/api/products/:id), or a page URL for GET and HEAD."
|
|
90
|
+
},
|
|
91
|
+
site: {
|
|
92
|
+
type: "string",
|
|
93
|
+
description: "Only the page of this site or mobile app, when several serve the path."
|
|
80
94
|
}
|
|
81
95
|
}, ["method", "path"]),
|
|
82
96
|
writes: false,
|
|
83
97
|
run: ask(async (input) => {
|
|
84
98
|
const { parseRouteText } = await scryParts();
|
|
99
|
+
const site = text(input, "site").trim();
|
|
85
100
|
return {
|
|
86
101
|
type: "route",
|
|
87
|
-
...parseRouteText(`${text(input, "method")} ${text(input, "path")}`)
|
|
102
|
+
...parseRouteText(`${text(input, "method")} ${text(input, "path")}`),
|
|
103
|
+
...site === "" ? {} : { site }
|
|
88
104
|
};
|
|
89
105
|
})
|
|
90
106
|
},
|
|
@@ -131,7 +147,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
131
147
|
writes: false,
|
|
132
148
|
run: async (input) => {
|
|
133
149
|
try {
|
|
134
|
-
const [{ parseFlowText, scry }, {
|
|
150
|
+
const [{ parseFlowText, scry }, { openStoredGrimoireCached }, compact] = await Promise.all([
|
|
135
151
|
scryParts(),
|
|
136
152
|
import("../workspace/cache.mjs"),
|
|
137
153
|
import("../scry/compact.mjs")
|
|
@@ -140,7 +156,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
140
156
|
type: "flow",
|
|
141
157
|
...parseFlowText(text(input, "flow"))
|
|
142
158
|
};
|
|
143
|
-
const snapshot = await
|
|
159
|
+
const snapshot = await openStoredGrimoireCached(root, await loadAdapter());
|
|
144
160
|
const result = scry(snapshot, query);
|
|
145
161
|
if (result.type !== "flow") return result;
|
|
146
162
|
const set = input.files;
|
|
@@ -152,48 +168,55 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
152
168
|
const offset = typeof input.offset === "number" && input.offset > 0 ? input.offset : 0;
|
|
153
169
|
return compact.stepFilePage(snapshot, result.bookmap, step, set, offset, 200);
|
|
154
170
|
} catch (error) {
|
|
155
|
-
return
|
|
171
|
+
return scryToolError(error);
|
|
156
172
|
}
|
|
157
173
|
}
|
|
158
174
|
},
|
|
159
175
|
{
|
|
160
176
|
name: "grimoire_search",
|
|
161
|
-
description: "Search the Grimoire
|
|
177
|
+
description: "Search the Grimoire with a sentence or words (pass the whole commit title or bug report, not two keywords): features, flows, blocks, pages, screens, routes, file paths, export names, header sentences, written text (summary, story, cases, criteria such as AC-5) and tasks. Hits whose name or title holds the words come first; every other hit follows by BM25F score. Hits are in score order and carry their score and app. Read-only.",
|
|
162
178
|
input: inputSchema({
|
|
163
179
|
text: {
|
|
164
180
|
type: "string",
|
|
165
|
-
description: "
|
|
181
|
+
description: "A sentence or words to look for; whole words, in any order."
|
|
166
182
|
},
|
|
167
183
|
limit: {
|
|
168
184
|
type: "integer",
|
|
169
185
|
description: "Most hits to return (default 20).",
|
|
170
186
|
minimum: 1
|
|
187
|
+
},
|
|
188
|
+
app: {
|
|
189
|
+
type: "string",
|
|
190
|
+
description: "Keep only the hits of this app (a page, screen, block or file of it)."
|
|
171
191
|
}
|
|
172
192
|
}, ["text"]),
|
|
173
193
|
writes: false,
|
|
174
194
|
run: ask(async (input) => {
|
|
175
|
-
const limit = input
|
|
176
|
-
|
|
177
|
-
type: "search",
|
|
178
|
-
text: text(input, "text")
|
|
179
|
-
};
|
|
180
|
-
const { parseLimit } = await scryParts();
|
|
195
|
+
const { limit, app } = input;
|
|
196
|
+
const { parseLimit, parseApp } = await scryParts();
|
|
181
197
|
return {
|
|
182
198
|
type: "search",
|
|
183
199
|
text: text(input, "text"),
|
|
184
|
-
limit: parseLimit(typeof limit === "number" || typeof limit === "string" ? limit : true)
|
|
200
|
+
...limit === void 0 || limit === null ? {} : { limit: parseLimit(typeof limit === "number" || typeof limit === "string" ? limit : true) },
|
|
201
|
+
...app === void 0 || app === null ? {} : { app: parseApp(typeof app === "string" ? app : true) }
|
|
185
202
|
};
|
|
186
203
|
})
|
|
187
204
|
},
|
|
188
205
|
{
|
|
189
206
|
name: "grimoire_check",
|
|
190
|
-
description: "Run the Grimoire check: written names that point at nothing, files without a header or feature, criteria without tests, version and changelog problems. Findings on proposed work are marked expected. Read-only;
|
|
207
|
+
description: "Run the Grimoire check: written names that point at nothing, files without a header or feature, criteria without tests, version and changelog problems. Findings on proposed work are marked expected. Read-only; checks the stored book (run warlock grimoire build after editing); `note` says when the book is behind the files.",
|
|
191
208
|
input: inputSchema({}),
|
|
192
209
|
writes: false,
|
|
193
210
|
run: async () => {
|
|
194
211
|
try {
|
|
195
|
-
const [{
|
|
196
|
-
|
|
212
|
+
const [{ openStoredGrimoireCached }, { checkGrimoire }] = await Promise.all([import("../workspace/cache.mjs"), import("../check/index.mjs")]);
|
|
213
|
+
const snapshot = await openStoredGrimoireCached(root, await loadAdapter());
|
|
214
|
+
const report = checkGrimoire(snapshot);
|
|
215
|
+
const changed = snapshot.behind?.changed;
|
|
216
|
+
return changed === void 0 ? report : {
|
|
217
|
+
...report,
|
|
218
|
+
note: `book is stale (${changed} ${changed === 1 ? "file" : "files"} changed); run warlock grimoire build`
|
|
219
|
+
};
|
|
197
220
|
} catch (error) {
|
|
198
221
|
return toolError(error);
|
|
199
222
|
}
|
|
@@ -227,12 +250,14 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
227
250
|
force
|
|
228
251
|
});
|
|
229
252
|
}
|
|
253
|
+
const routeNote = run.snapshot.book.routeNote;
|
|
254
|
+
const notes = [note, routeNote ?? null].filter((item) => item !== null);
|
|
230
255
|
return {
|
|
231
256
|
rebuilt: run.rebuilt,
|
|
232
257
|
written: [...run.book.written, ...run.collected.written],
|
|
233
258
|
removed: [...run.book.removed, ...run.collected.removed],
|
|
234
259
|
routes: run.snapshot.routes,
|
|
235
|
-
...
|
|
260
|
+
...notes.length === 0 ? {} : { note: notes.join("; ") }
|
|
236
261
|
};
|
|
237
262
|
} catch (error) {
|
|
238
263
|
return toolError(error);
|