@warlock.js/grimoire 5.61.0 → 5.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/esm/book/build.d.mts +17 -0
  3. package/esm/book/build.d.mts.map +1 -1
  4. package/esm/book/build.mjs +78 -16
  5. package/esm/book/build.mjs.map +1 -1
  6. package/esm/book/index.mjs +2 -2
  7. package/esm/codes/codes.d.mts +2 -0
  8. package/esm/codes/codes.d.mts.map +1 -1
  9. package/esm/codes/codes.mjs +2 -1
  10. package/esm/codes/codes.mjs.map +1 -1
  11. package/esm/contracts/book.d.mts +7 -0
  12. package/esm/contracts/book.d.mts.map +1 -1
  13. package/esm/contracts/book.mjs.map +1 -1
  14. package/esm/contracts/scry.d.mts +29 -5
  15. package/esm/contracts/scry.d.mts.map +1 -1
  16. package/esm/contracts/snapshot.d.mts +8 -0
  17. package/esm/contracts/snapshot.d.mts.map +1 -1
  18. package/esm/devtools/snapshot-source.mjs +27 -7
  19. package/esm/devtools/snapshot-source.mjs.map +1 -1
  20. package/esm/index.d.mts +5 -3
  21. package/esm/index.mjs +4 -2
  22. package/esm/scry/error.mjs +20 -0
  23. package/esm/scry/error.mjs.map +1 -0
  24. package/esm/scry/format.d.mts.map +1 -1
  25. package/esm/scry/format.mjs +22 -1
  26. package/esm/scry/format.mjs.map +1 -1
  27. package/esm/scry/index.mjs +3 -2
  28. package/esm/scry/parse.d.mts +1 -1
  29. package/esm/scry/parse.d.mts.map +1 -1
  30. package/esm/scry/parse.mjs +12 -9
  31. package/esm/scry/parse.mjs.map +1 -1
  32. package/esm/scry/query.d.mts.map +1 -1
  33. package/esm/scry/query.mjs +77 -268
  34. package/esm/scry/query.mjs.map +1 -1
  35. package/esm/scry/search.d.mts +8 -0
  36. package/esm/scry/search.d.mts.map +1 -0
  37. package/esm/scry/search.mjs +401 -0
  38. package/esm/scry/search.mjs.map +1 -0
  39. package/esm/warlock/actions.mjs +15 -12
  40. package/esm/warlock/actions.mjs.map +1 -1
  41. package/esm/warlock/commands.mjs +14 -4
  42. package/esm/warlock/commands.mjs.map +1 -1
  43. package/esm/warlock/mcp-tools.mjs +46 -21
  44. package/esm/warlock/mcp-tools.mjs.map +1 -1
  45. package/esm/workspace/cache.mjs +13 -1
  46. package/esm/workspace/cache.mjs.map +1 -1
  47. package/esm/workspace/derived.mjs +107 -0
  48. package/esm/workspace/derived.mjs.map +1 -0
  49. package/esm/workspace/index.d.mts.map +1 -1
  50. package/esm/workspace/index.mjs +22 -18
  51. package/esm/workspace/index.mjs.map +1 -1
  52. package/esm/workspace/stored.d.mts +12 -0
  53. package/esm/workspace/stored.d.mts.map +1 -0
  54. package/esm/workspace/stored.mjs +46 -0
  55. package/esm/workspace/stored.mjs.map +1 -0
  56. package/llms-full.txt +28 -12
  57. package/package.json +3 -3
  58. package/skills/use-the-grimoire/SKILL.md +28 -12
  59. package/ui/grimoire-view.js +16 -0
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-tools.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/mcp-tools.ts"],"sourcesContent":["/**\n * The Grimoire tools `warlock mcp` and `warlock dev --mcp` serve. Each tool\n * loads its code inside `run`, so registering them costs nothing at start.\n * Answers are the same JSON objects `--json` prints.\n */\nimport { inputSchema, type WarlockMcpContext, type WarlockMcpTool } from \"@warlock.js/core\";\nimport { explainGrimoireCode, GrimoireError, grimoireCodeDocsUrl } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { ScryQuery } from \"../contracts/scry\";\nimport type { WarlockAdapterOptions } from \"./adapter\";\n\n/** The names of the tools, in the order they are listed. */\nexport const GRIMOIRE_MCP_TOOL_NAMES = [\n \"grimoire_file\",\n \"grimoire_impact\",\n \"grimoire_route\",\n \"grimoire_feature\",\n \"grimoire_flow\",\n \"grimoire_search\",\n \"grimoire_check\",\n \"grimoire_build\",\n \"grimoire_release\",\n \"grimoire_explain\",\n] as const;\n\n/** A Grimoire error as a tool error: the code, what failed, and what to do. */\nfunction toolError(error: unknown): never {\n if (error instanceof GrimoireError) {\n const fix = explainGrimoireCode(error.code)?.fix;\n\n throw new Error(`${error.code}: ${error.message}${fix ? ` Fix: ${fix}` : \"\"}`);\n }\n\n throw error;\n}\n\nfunction text(input: Record<string, unknown>, name: string): string {\n const value = input[name];\n\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** The tools for one MCP server. `adapterFor` is replaced in specs. */\nexport function createGrimoireMcpTools(\n context: Pick<WarlockMcpContext, \"cwd\" | \"inspect\">,\n options: WarlockAdapterOptions = {},\n adapterFor?: () => Promise<BookAdapter>,\n): WarlockMcpTool[] {\n const root = context.cwd;\n let adapter: Promise<BookAdapter> | undefined;\n\n // The server's own inspect: `warlock mcp` boots once for every tool, `warlock dev --mcp` reads the live app.\n const loadAdapter = (): Promise<BookAdapter> => {\n adapter ??=\n adapterFor?.() ??\n import(\"./adapter\").then(({ createWarlockAdapter }) =>\n createWarlockAdapter({\n ...options,\n inspect: (_root, sections) => context.inspect(sections),\n }),\n );\n\n return adapter;\n };\n\n const ask =\n (query: (input: Record<string, unknown>) => Promise<ScryQuery> | ScryQuery) =>\n async (input: Record<string, unknown>): Promise<unknown> => {\n try {\n const { answer } = await import(\"./actions\");\n\n return await answer(root, await loadAdapter(), await query(input));\n } catch (error) {\n return toolError(error);\n }\n };\n\n const scryParts = () => import(\"../scry\");\n\n return [\n {\n name: \"grimoire_file\",\n description:\n \"One source file from the Grimoire book: header sentence, owning feature and borrowers, flows that reach it, exports, imports, importers, routes, pages. Read-only; reads cached route facts and never boots the app.\",\n input: inputSchema(\n { file: { type: \"string\", description: \"Project-relative path (either separator).\" } },\n [\"file\"],\n ),\n writes: false,\n run: ask((input) => ({ type: \"file\", file: text(input, \"file\") })),\n },\n {\n name: \"grimoire_impact\",\n description:\n \"What a change to a file reaches: importers (direct and all), API routes, pages and screens, flows, features (owner and borrowers) and tests. Read-only.\",\n input: inputSchema(\n { file: { type: \"string\", description: \"Project-relative path of the file to change.\" } },\n [\"file\"],\n ),\n writes: false,\n run: ask((input) => ({ type: \"impact\", file: text(input, \"file\") })),\n },\n {\n name: \"grimoire_route\",\n description:\n \"One HTTP route: handler and its file, routes file, middleware, guard, the files behind it and the flow steps that name it. Read-only.\",\n input: inputSchema(\n {\n method: { type: \"string\", description: \"HTTP method (GET, POST…).\" },\n path: { type: \"string\", description: \"Path as registered (/api/products/:id).\" },\n },\n [\"method\", \"path\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const { parseRouteText } = await scryParts();\n\n return {\n type: \"route\",\n ...parseRouteText(`${text(input, \"method\")} ${text(input, \"path\")}`),\n };\n }),\n },\n {\n name: \"grimoire_feature\",\n description:\n \"One feature: README, flows with status, its book map (own, borrowed and unreached files, routes, pages), recent changes, open tasks and its check findings. Read-only.\",\n input: inputSchema(\n {\n feature: { type: \"string\", description: \"Feature id (folder under grimoire/features/).\" },\n },\n [\"feature\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const { parseFeatureText } = await scryParts();\n\n return { type: \"feature\", feature: parseFeatureText(text(input, \"feature\")) };\n }),\n },\n {\n name: \"grimoire_flow\",\n description:\n \"One flow: its summary, steps with file counts (direct, in the feature, reachable, type-only) and the first direct imports of each, cases, criteria with their tests and last results (pass, fail, stale, not run, no test), where it is shown, history and findings. Pass files with step to list one step's reachable or type-only files, a page at a time. Read-only.\",\n input: inputSchema(\n {\n flow: { type: \"string\", description: \"<feature>/<flow>, like catalog/new-arrivals.\" },\n files: {\n type: \"string\",\n enum: [\"reachable\", \"type-only\"],\n description:\n \"With step: list the step's files that run (reachable) or only type imports reach (type-only).\",\n },\n step: { type: \"integer\", description: \"Step number, for files.\", minimum: 0 },\n offset: {\n type: \"integer\",\n description: \"First file to list (default 0); a page holds 200.\",\n minimum: 0,\n },\n },\n [\"flow\"],\n ),\n writes: false,\n run: async (input) => {\n try {\n const [{ parseFlowText, scry }, { openGrimoireCached }, compact] = await Promise.all([\n scryParts(),\n import(\"../workspace/cache\"),\n import(\"../scry/compact\"),\n ]);\n const query = { type: \"flow\" as const, ...parseFlowText(text(input, \"flow\")) };\n const snapshot = await openGrimoireCached(root, await loadAdapter(), {\n routes: \"cached\",\n });\n const result = scry(snapshot, query);\n\n if (result.type !== \"flow\") return result;\n\n const set = input.files;\n\n if (set === undefined || set === null) return compact.compactFlow(snapshot, result);\n\n if (set !== \"reachable\" && set !== \"type-only\") {\n throw new GrimoireError(\"GR9006\", 'Pass files as \"reachable\" or \"type-only\".');\n }\n\n const stepNumber = input.step;\n const step = result.bookmap.steps.find((item) => item.index === stepNumber);\n\n if (typeof stepNumber !== \"number\" || step === undefined) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass step as one of the step numbers of ${result.bookmap.ref} (${result.bookmap.steps.map((item) => item.index).join(\", \")}).`,\n );\n }\n\n const offset = typeof input.offset === \"number\" && input.offset > 0 ? input.offset : 0;\n\n return compact.stepFilePage(snapshot, result.bookmap, step, set, offset, 200);\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_search\",\n description:\n \"Search the Grimoire by words (the written text of flows too: summary, story, cases, criteria such as AC-5; written content ranks first and hits are grouped by type): features, flows, blocks, pages, screens, routes, file paths, export names, header sentences and tasks, best match first. Read-only.\",\n input: inputSchema(\n {\n text: { type: \"string\", description: \"Words to look for, in any order.\" },\n limit: { type: \"integer\", description: \"Most hits to return (default 20).\", minimum: 1 },\n },\n [\"text\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const limit = input.limit;\n\n if (limit === undefined || limit === null)\n return { type: \"search\", text: text(input, \"text\") };\n\n const { parseLimit } = await scryParts();\n\n // A limit of 0, a negative or a fraction is refused with GR9006, as `--limit` is.\n return {\n type: \"search\",\n text: text(input, \"text\"),\n limit: parseLimit(typeof limit === \"number\" || typeof limit === \"string\" ? limit : true),\n };\n }),\n },\n {\n name: \"grimoire_check\",\n description:\n \"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; uses cached route facts.\",\n input: inputSchema({}),\n writes: false,\n run: async () => {\n try {\n const [{ openGrimoireCached }, { checkGrimoire }] = await Promise.all([\n import(\"../workspace/cache\"),\n import(\"../check\"),\n ]);\n\n return checkGrimoire(\n await openGrimoireCached(root, await loadAdapter(), { routes: \"cached\" }),\n );\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_build\",\n description:\n \"Bring the generated book (grimoire/book, a git-ignored cache) up to date, reading the routes again when they changed. Writes no project file.\",\n input: inputSchema({ force: { type: \"boolean\", description: \"Rebuild every entry.\" } }),\n writes: false,\n run: async (input) => {\n try {\n const { runGrimoire } = await import(\"../workspace\");\n const loaded = await loadAdapter();\n const force = input.force === true;\n let run;\n let note: string | null = null;\n\n try {\n run = await runGrimoire(root, loaded, { routes: \"fresh\", force });\n } catch (error) {\n if (!(error instanceof GrimoireError) || error.code !== \"GR8002\") throw error;\n\n note = `${error.code}: ${error.message}`;\n run = await runGrimoire(root, loaded, { routes: \"cached\", force });\n }\n\n return {\n rebuilt: run.rebuilt,\n written: [...run.book.written, ...run.collected.written],\n removed: [...run.book.removed, ...run.collected.removed],\n routes: run.snapshot.routes,\n ...(note === null ? {} : { note }),\n };\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_release\",\n description:\n \"Write the collected list of a release into grimoire/releases/<release>.md (between its markers; the agent writes the brief and stamps the changelog entries first). Writes a project file.\",\n input: inputSchema(\n { release: { type: \"string\", description: \"Release name, like 1.1.0.\" } },\n [\"release\"],\n ),\n writes: true,\n run: async (input) => {\n try {\n const [{ parseGrimoire }, { writeRelease }] = await Promise.all([\n import(\"../written\"),\n import(\"../releases\"),\n ]);\n const release = text(input, \"release\").trim();\n\n if (release === \"\" || /[\\\\/]/.test(release)) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass a release name like 1.1.0 (got ${JSON.stringify(release)}).`,\n );\n }\n\n return await writeRelease(root, (await parseGrimoire(root)).written, release);\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_explain\",\n description:\n \"What a Grimoire code (GR1001…GR9006) means, what to do, the skill that explains it and its docs link. Read-only.\",\n input: inputSchema({ code: { type: \"string\", description: \"The code, like GR2001.\" } }, [\n \"code\",\n ]),\n writes: false,\n run: async (input) => {\n const definition = explainGrimoireCode(text(input, \"code\"));\n\n if (!definition) {\n throw new Error(\n `Unknown Grimoire code ${JSON.stringify(text(input, \"code\"))}. Codes look like GR2001; the full list is at the check guide.`,\n );\n }\n\n return { ...definition, docs: grimoireCodeDocsUrl(definition.code) };\n },\n },\n ];\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAS,UAAU,OAAuB;CACxC,IAAI,iBAAiB,eAAe;EAClC,MAAM,MAAM,oBAAoB,MAAM,IAAI,CAAC,EAAE;EAE7C,MAAM,IAAI,MAAM,GAAG,MAAM,KAAK,IAAI,MAAM,UAAU,MAAM,SAAS,QAAQ,IAAI;CAC/E;CAEA,MAAM;AACR;AAEA,SAAS,KAAK,OAAgC,MAAsB;CAClE,MAAM,QAAQ,MAAM;CAEpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;;AAGA,SAAgB,uBACd,SACA,UAAiC,CAAC,GAClC,YACkB;CAClB,MAAM,OAAO,QAAQ;CACrB,IAAI;CAGJ,MAAM,oBAA0C;EAC9C,YACE,aAAa,KACb,OAAO,gBAAY,CAAC,MAAM,EAAE,2BAC1B,qBAAqB;GACnB,GAAG;GACH,UAAU,OAAO,aAAa,QAAQ,QAAQ,QAAQ;EACxD,CAAC,CACH;EAEF,OAAO;CACT;CAEA,MAAM,OACH,UACD,OAAO,UAAqD;EAC1D,IAAI;GACF,MAAM,EAAE,WAAW,MAAM,OAAO;GAEhC,OAAO,MAAM,OAAO,MAAM,MAAM,YAAY,GAAG,MAAM,MAAM,KAAK,CAAC;EACnE,SAAS,OAAO;GACd,OAAO,UAAU,KAAK;EACxB;C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,KAAK,UAAU,KAAK,OAAO,MAAM,CAAC,EAAE,+DAC/D;IAGF,OAAO;KAAE,GAAG;KAAY,MAAM,oBAAoB,WAAW,IAAI;IAAE;GACrE;EACF;CACF;AACF"}
1
+ {"version":3,"file":"mcp-tools.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/mcp-tools.ts"],"sourcesContent":["/**\n * The Grimoire tools `warlock mcp` and `warlock dev --mcp` serve. Each tool\n * loads its code inside `run`, so registering them costs nothing at start.\n * Answers are the same JSON objects `--json` prints.\n */\nimport { inputSchema, type WarlockMcpContext, type WarlockMcpTool } from \"@warlock.js/core\";\nimport { explainGrimoireCode, GrimoireError, grimoireCodeDocsUrl } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { ScryQuery } from \"../contracts/scry\";\nimport { scryErrorOf } from \"../scry/error\";\nimport type { WarlockAdapterOptions } from \"./adapter\";\n\n/** The names of the tools, in the order they are listed. */\nexport const GRIMOIRE_MCP_TOOL_NAMES = [\n \"grimoire_file\",\n \"grimoire_impact\",\n \"grimoire_route\",\n \"grimoire_feature\",\n \"grimoire_flow\",\n \"grimoire_search\",\n \"grimoire_check\",\n \"grimoire_build\",\n \"grimoire_release\",\n \"grimoire_explain\",\n] as const;\n\n/** A Grimoire error of a non-scry tool (check, build, release) as a tool error: the code, what failed, and what to do. */\nfunction toolError(error: unknown): never {\n if (error instanceof GrimoireError) {\n const fix = explainGrimoireCode(error.code)?.fix;\n\n throw new Error(`${error.code}: ${error.message}${fix ? ` Fix: ${fix}` : \"\"}`);\n }\n\n throw error;\n}\n\n/**\n * A scry error as a tool error whose text is the `ScryError` JSON that\n * `warlock scry --json` prints (`{ \"type\": \"error\", \"code\", \"message\", \"fix\" }`).\n * It stays a thrown error so the MCP result is still marked `isError`.\n */\nfunction scryToolError(error: unknown): never {\n if (error instanceof GrimoireError) throw new Error(JSON.stringify(scryErrorOf(error)));\n\n throw error;\n}\n\nfunction text(input: Record<string, unknown>, name: string): string {\n const value = input[name];\n\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** The tools for one MCP server. `adapterFor` is replaced in specs. */\nexport function createGrimoireMcpTools(\n context: Pick<WarlockMcpContext, \"cwd\" | \"inspect\">,\n options: WarlockAdapterOptions = {},\n adapterFor?: () => Promise<BookAdapter>,\n): WarlockMcpTool[] {\n const root = context.cwd;\n let adapter: Promise<BookAdapter> | undefined;\n\n // The server's own inspect: `warlock mcp` boots once for every tool, `warlock dev --mcp` reads the live app.\n const loadAdapter = (): Promise<BookAdapter> => {\n adapter ??=\n adapterFor?.() ??\n import(\"./adapter\").then(({ createWarlockAdapter }) =>\n createWarlockAdapter({\n ...options,\n inspect: (_root, sections) => context.inspect(sections),\n }),\n );\n\n return adapter;\n };\n\n const ask =\n (query: (input: Record<string, unknown>) => Promise<ScryQuery> | ScryQuery) =>\n async (input: Record<string, unknown>): Promise<unknown> => {\n try {\n const { answer } = await import(\"./actions\");\n\n return await answer(root, await loadAdapter(), await query(input));\n } catch (error) {\n return scryToolError(error);\n }\n };\n\n const scryParts = () => import(\"../scry\");\n\n return [\n {\n name: \"grimoire_file\",\n description:\n \"One source file from the Grimoire book: header sentence, owning feature and borrowers, flows that reach it, exports, imports, importers, routes, pages. Read-only; reads cached route facts and never boots the app.\",\n input: inputSchema(\n { file: { type: \"string\", description: \"Project-relative path (either separator).\" } },\n [\"file\"],\n ),\n writes: false,\n run: ask((input) => ({ type: \"file\", file: text(input, \"file\") })),\n },\n {\n name: \"grimoire_impact\",\n description:\n \"What a change to a file reaches: importers (direct and all), API routes, pages and screens, flows, features (owner and borrowers) and tests. Read-only.\",\n input: inputSchema(\n { file: { type: \"string\", description: \"Project-relative path of the file to change.\" } },\n [\"file\"],\n ),\n writes: false,\n run: ask((input) => ({ type: \"impact\", file: text(input, \"file\") })),\n },\n {\n name: \"grimoire_route\",\n description:\n \"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.\",\n input: inputSchema(\n {\n method: { type: \"string\", description: \"HTTP method (GET, POST…).\" },\n path: {\n type: \"string\",\n description: \"Path as registered (/api/products/:id), or a page URL for GET and HEAD.\",\n },\n site: {\n type: \"string\",\n description: \"Only the page of this site or mobile app, when several serve the path.\",\n },\n },\n [\"method\", \"path\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const { parseRouteText } = await scryParts();\n\n const site = text(input, \"site\").trim();\n\n return {\n type: \"route\",\n ...parseRouteText(`${text(input, \"method\")} ${text(input, \"path\")}`),\n ...(site === \"\" ? {} : { site }),\n };\n }),\n },\n {\n name: \"grimoire_feature\",\n description:\n \"One feature: README, flows with status, its book map (own, borrowed and unreached files, routes, pages), recent changes, open tasks and its check findings. Read-only.\",\n input: inputSchema(\n {\n feature: { type: \"string\", description: \"Feature id (folder under grimoire/features/).\" },\n },\n [\"feature\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const { parseFeatureText } = await scryParts();\n\n return { type: \"feature\", feature: parseFeatureText(text(input, \"feature\")) };\n }),\n },\n {\n name: \"grimoire_flow\",\n description:\n \"One flow: its summary, steps with file counts (direct, in the feature, reachable, type-only) and the first direct imports of each, cases, criteria with their tests and last results (pass, fail, stale, not run, no test), where it is shown, history and findings. Pass files with step to list one step's reachable or type-only files, a page at a time. Read-only.\",\n input: inputSchema(\n {\n flow: { type: \"string\", description: \"<feature>/<flow>, like catalog/new-arrivals.\" },\n files: {\n type: \"string\",\n enum: [\"reachable\", \"type-only\"],\n description:\n \"With step: list the step's files that run (reachable) or only type imports reach (type-only).\",\n },\n step: { type: \"integer\", description: \"Step number, for files.\", minimum: 0 },\n offset: {\n type: \"integer\",\n description: \"First file to list (default 0); a page holds 200.\",\n minimum: 0,\n },\n },\n [\"flow\"],\n ),\n writes: false,\n run: async (input) => {\n try {\n const [{ parseFlowText, scry }, { openStoredGrimoireCached }, compact] =\n await Promise.all([\n scryParts(),\n import(\"../workspace/cache\"),\n import(\"../scry/compact\"),\n ]);\n const query = { type: \"flow\" as const, ...parseFlowText(text(input, \"flow\")) };\n const snapshot = await openStoredGrimoireCached(root, await loadAdapter());\n const result = scry(snapshot, query);\n\n if (result.type !== \"flow\") return result;\n\n const set = input.files;\n\n if (set === undefined || set === null) return compact.compactFlow(snapshot, result);\n\n if (set !== \"reachable\" && set !== \"type-only\") {\n throw new GrimoireError(\"GR9006\", 'Pass files as \"reachable\" or \"type-only\".');\n }\n\n const stepNumber = input.step;\n const step = result.bookmap.steps.find((item) => item.index === stepNumber);\n\n if (typeof stepNumber !== \"number\" || step === undefined) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass step as one of the step numbers of ${result.bookmap.ref} (${result.bookmap.steps.map((item) => item.index).join(\", \")}).`,\n );\n }\n\n const offset = typeof input.offset === \"number\" && input.offset > 0 ? input.offset : 0;\n\n return compact.stepFilePage(snapshot, result.bookmap, step, set, offset, 200);\n } catch (error) {\n return scryToolError(error);\n }\n },\n },\n {\n name: \"grimoire_search\",\n description:\n \"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.\",\n input: inputSchema(\n {\n text: {\n type: \"string\",\n description: \"A sentence or words to look for; whole words, in any order.\",\n },\n limit: { type: \"integer\", description: \"Most hits to return (default 20).\", minimum: 1 },\n app: {\n type: \"string\",\n description: \"Keep only the hits of this app (a page, screen, block or file of it).\",\n },\n },\n [\"text\"],\n ),\n writes: false,\n run: ask(async (input) => {\n const { limit, app } = input;\n const { parseLimit, parseApp } = await scryParts();\n\n // A limit of 0, a negative or a fraction is refused with GR9006, as `--limit` is.\n return {\n type: \"search\",\n text: text(input, \"text\"),\n ...(limit === undefined || limit === null\n ? {}\n : {\n limit: parseLimit(\n typeof limit === \"number\" || typeof limit === \"string\" ? limit : true,\n ),\n }),\n ...(app === undefined || app === null\n ? {}\n : { app: parseApp(typeof app === \"string\" ? app : true) }),\n };\n }),\n },\n {\n name: \"grimoire_check\",\n description:\n \"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.\",\n input: inputSchema({}),\n writes: false,\n run: async () => {\n try {\n const [{ openStoredGrimoireCached }, { checkGrimoire }] = await Promise.all([\n import(\"../workspace/cache\"),\n import(\"../check\"),\n ]);\n\n const snapshot = await openStoredGrimoireCached(root, await loadAdapter());\n const report = checkGrimoire(snapshot);\n const changed = snapshot.behind?.changed;\n\n // The stored book may be behind the files: say so, as scry answers do.\n return changed === undefined\n ? report\n : {\n ...report,\n note: `book is stale (${changed} ${changed === 1 ? \"file\" : \"files\"} changed); run warlock grimoire build`,\n };\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_build\",\n description:\n \"Bring the generated book (grimoire/book, a git-ignored cache) up to date, reading the routes again when they changed. Writes no project file.\",\n input: inputSchema({ force: { type: \"boolean\", description: \"Rebuild every entry.\" } }),\n writes: false,\n run: async (input) => {\n try {\n const { runGrimoire } = await import(\"../workspace\");\n const loaded = await loadAdapter();\n const force = input.force === true;\n let run;\n let note: string | null = null;\n\n try {\n run = await runGrimoire(root, loaded, { routes: \"fresh\", force });\n } catch (error) {\n if (!(error instanceof GrimoireError) || error.code !== \"GR8002\") throw error;\n\n note = `${error.code}: ${error.message}`;\n run = await runGrimoire(root, loaded, { routes: \"cached\", force });\n }\n\n const routeNote = run.snapshot.book.routeNote;\n const notes = [note, routeNote ?? null].filter((item): item is string => item !== null);\n\n return {\n rebuilt: run.rebuilt,\n written: [...run.book.written, ...run.collected.written],\n removed: [...run.book.removed, ...run.collected.removed],\n routes: run.snapshot.routes,\n ...(notes.length === 0 ? {} : { note: notes.join(\"; \") }),\n };\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_release\",\n description:\n \"Write the collected list of a release into grimoire/releases/<release>.md (between its markers; the agent writes the brief and stamps the changelog entries first). Writes a project file.\",\n input: inputSchema(\n { release: { type: \"string\", description: \"Release name, like 1.1.0.\" } },\n [\"release\"],\n ),\n writes: true,\n run: async (input) => {\n try {\n const [{ parseGrimoire }, { writeRelease }] = await Promise.all([\n import(\"../written\"),\n import(\"../releases\"),\n ]);\n const release = text(input, \"release\").trim();\n\n if (release === \"\" || /[\\\\/]/.test(release)) {\n throw new GrimoireError(\n \"GR9006\",\n `Pass a release name like 1.1.0 (got ${JSON.stringify(release)}).`,\n );\n }\n\n return await writeRelease(root, (await parseGrimoire(root)).written, release);\n } catch (error) {\n return toolError(error);\n }\n },\n },\n {\n name: \"grimoire_explain\",\n description:\n \"What a Grimoire code (GR1001…GR9006) means, what to do, the skill that explains it and its docs link. Read-only.\",\n input: inputSchema({ code: { type: \"string\", description: \"The code, like GR2001.\" } }, [\n \"code\",\n ]),\n writes: false,\n run: async (input) => {\n const definition = explainGrimoireCode(text(input, \"code\"));\n\n if (!definition) {\n throw new Error(\n `Unknown Grimoire code ${JSON.stringify(text(input, \"code\"))}. Codes look like GR2001; the full list is at the check guide.`,\n );\n }\n\n return { ...definition, docs: grimoireCodeDocsUrl(definition.code) };\n },\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAS,UAAU,OAAuB;CACxC,IAAI,iBAAiB,eAAe;EAClC,MAAM,MAAM,oBAAoB,MAAM,IAAI,CAAC,EAAE;EAE7C,MAAM,IAAI,MAAM,GAAG,MAAM,KAAK,IAAI,MAAM,UAAU,MAAM,SAAS,QAAQ,IAAI;CAC/E;CAEA,MAAM;AACR;;;;;;AAOA,SAAS,cAAc,OAAuB;CAC5C,IAAI,iBAAiB,eAAe,MAAM,IAAI,MAAM,KAAK,UAAU,YAAY,KAAK,CAAC,CAAC;CAEtF,MAAM;AACR;AAEA,SAAS,KAAK,OAAgC,MAAsB;CAClE,MAAM,QAAQ,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js";
2
2
  import { resolveResultsFile } from "../test-results/index.mjs";
3
+ import { DERIVED_PATH } from "./derived.mjs";
3
4
  import { openGrimoire } from "./index.mjs";
5
+ import { openStoredGrimoire } from "./stored.mjs";
4
6
  import path from "node:path";
5
7
  import { createHash } from "node:crypto";
6
8
  import { readdir, stat } from "node:fs/promises";
@@ -100,6 +102,7 @@ async function takeStamp(root, snapshot, testResultsFile) {
100
102
  const singles = [
101
103
  path.join(root, ...GRIMOIRE_PATHS.bookManifest.split("/")),
102
104
  path.join(root, ...GRIMOIRE_PATHS.bookRoutes.split("/")),
105
+ path.join(root, ...DERIVED_PATH.split("/")),
103
106
  resolveResultsFile(root, testResultsFile),
104
107
  path.join(root, "package.json")
105
108
  ];
@@ -188,7 +191,16 @@ const openedBooks = createBookCache();
188
191
  function openGrimoireCached(root, adapter, options = {}) {
189
192
  return openedBooks.open(root, adapter, options);
190
193
  }
194
+ /** The same cache over the read-only open (`openStoredGrimoire`): never builds, never writes. */
195
+ const storedBooks = createBookCache(openStoredGrimoire);
196
+ /** `openStoredGrimoire` that keeps the book in memory while nothing changed. */
197
+ function openStoredGrimoireCached(root, adapter, options = {}) {
198
+ return storedBooks.open(root, adapter, {
199
+ ...options,
200
+ write: false
201
+ });
202
+ }
191
203
 
192
204
  //#endregion
193
- export { createBookCache, openGrimoireCached, openedBooks, stampOf };
205
+ export { createBookCache, openGrimoireCached, openStoredGrimoireCached, openedBooks, stampOf, storedBooks };
194
206
  //# sourceMappingURL=cache.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/cache.ts"],"sourcesContent":["/**\n * Keeps the opened book in memory between calls of one process (the MCP\n * server answers many questions per process) and says cheaply whether it is\n * still current.\n *\n * Freshness is a stamp of `stat` results, no file is read: the size and\n * modified time of every code and test file the book lists, the modified time\n * of each folder that holds one and of every folder above it up to the project root (a new or removed file moves its\n * folder; a new module folder moves its parent), every\n * file under the written folders (`grimoire/features`, `apps`, `releases`,\n * `tasks`, `screenshots`), the book manifest, the test results file and\n * `package.json`. A stamp that equals the one taken after the last open\n * returns the same snapshot; any difference opens the book again.\n */\nimport { createHash } from \"node:crypto\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot, OpenGrimoireOptions } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"./index\";\n\n/** The written folders whose every file is part of the stamp. */\nconst WRITTEN_TREES = [\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.releases,\n GRIMOIRE_PATHS.tasks,\n GRIMOIRE_PATHS.screenshots,\n];\n\nconst STAT_BATCH = 256;\n\nasync function statLine(absolute: string, withSize: boolean): Promise<string> {\n try {\n const info = await stat(absolute);\n\n return withSize ? `${info.size}:${info.mtimeMs}` : String(info.mtimeMs);\n } catch {\n return \"-\";\n }\n}\n\nasync function statAll(files: readonly string[], withSize: boolean): Promise<string[]> {\n const lines: string[] = [];\n\n for (let start = 0; start < files.length; start += STAT_BATCH) {\n lines.push(\n ...(await Promise.all(\n files.slice(start, start + STAT_BATCH).map((file) => statLine(file, withSize)),\n )),\n );\n }\n\n return lines;\n}\n\n/** Every file below `folder` (absolute paths, sorted); a missing folder gives none. */\nasync function filesUnder(folder: string): Promise<string[]> {\n const found: string[] = [];\n const walk = async (current: string): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const next = path.join(current, entry.name);\n\n if (entry.isDirectory()) await walk(next);\n else found.push(next);\n }\n };\n\n await walk(folder);\n\n return found.sort();\n}\n\n/**\n * The freshness stamp of a project, from the files of `snapshot` (its code and\n * test files) and the written folders as they are now. Reads no file content.\n */\nexport async function stampOf(\n root: string,\n snapshot: GrimoireSnapshot,\n testResultsFile?: string,\n): Promise<string> {\n return (await takeStamp(root, snapshot, testResultsFile)).stamp;\n}\n\n/**\n * The stat lines of a stamp hold `size:mtime` or `mtime`; the newest mtime of them that is not after `until`\n * (a time in the future is clock skew, not an edit), 0 when none.\n */\nfunction newestOf(lines: readonly string[], until: number): number {\n let newest = 0;\n\n for (const line of lines) {\n const value = Number(line.split(\":\").pop());\n\n if (Number.isFinite(value) && value <= until && value > newest) newest = value;\n }\n\n return newest;\n}\n\n/** Every folder above `folder` up to (not including) the project root. */\nfunction withAncestors(folders: readonly string[]): string[] {\n const all = new Set<string>();\n\n for (const folder of folders) {\n let current = folder;\n\n while (current !== \".\" && current !== \"\" && current !== \"/\") {\n all.add(current);\n current = path.posix.dirname(current.split(path.sep).join(\"/\"));\n }\n }\n\n return [...all].sort();\n}\n\n/** The stamp, and the newest modified time among the code, test and written files and their folders. */\nasync function takeStamp(\n root: string,\n snapshot: GrimoireSnapshot,\n testResultsFile?: string,\n): Promise<{ stamp: string; newest: number }> {\n const listed = [\n ...snapshot.book.facts.files.map((file) => file.file),\n ...snapshot.book.facts.tests,\n ];\n const folders = withAncestors([...new Set(listed.map((file) => path.dirname(file)))]);\n const written = (\n await Promise.all(WRITTEN_TREES.map((tree) => filesUnder(path.join(root, ...tree.split(\"/\")))))\n ).flat();\n const singles = [\n path.join(root, ...GRIMOIRE_PATHS.bookManifest.split(\"/\")),\n path.join(root, ...GRIMOIRE_PATHS.bookRoutes.split(\"/\")),\n resolveResultsFile(root, testResultsFile),\n path.join(root, \"package.json\"),\n ];\n const [fileLines, folderLines, writtenLines, singleLines] = await Promise.all([\n statAll(\n listed.map((file) => path.join(root, ...file.split(\"/\"))),\n true,\n ),\n statAll(\n folders.map((folder) => path.join(root, ...folder.split(path.sep))),\n false,\n ),\n statAll(written, true),\n statAll(singles, true),\n ]);\n\n const stamp = createHash(\"sha1\")\n .update(\n JSON.stringify([listed, fileLines, folders, folderLines, written, writtenLines, singleLines]),\n )\n .digest(\"hex\");\n\n return { stamp, newest: newestOf([...fileLines, ...folderLines, ...writtenLines], Date.now()) };\n}\n\ntype Entry = { snapshot: GrimoireSnapshot; stamp: string };\n\n/** What a cached open is asked with; two different asks never share an entry. */\nfunction keyOf(root: string, options: OpenGrimoireOptions): string {\n return JSON.stringify([root, options.write !== false, options.testResultsFile ?? null]);\n}\n\n/** A book cache: `open()` returns the kept snapshot while the stamp holds. */\nexport type BookCache = {\n /** The snapshot for `root`: kept when nothing changed, else opened again. `force`, or `routes: \"fresh\"`, always opens. */\n open(\n root: string,\n adapter: BookAdapter,\n options?: OpenGrimoireOptions,\n ): Promise<GrimoireSnapshot>;\n /** Forget everything kept. */\n clear(): void;\n};\n\n/**\n * Create a cache. `reopen` is how the book is opened (default `openGrimoire`);\n * specs pass a counter to see how many times the book was really opened.\n */\nexport function createBookCache(reopen: typeof openGrimoire = openGrimoire): BookCache {\n const kept = new Map<string, Entry>();\n const opening = new Map<string, Promise<GrimoireSnapshot>>();\n // Opens that write the book's files wait for each other, per project.\n const writing = new Map<string, Promise<unknown>>();\n\n const openOnce = async (\n key: string,\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions,\n ): Promise<GrimoireSnapshot> => {\n // The clock is read before the open, so a file edited while it ran is seen as newer than the stamp.\n const startedAt = Date.now();\n const snapshot = await reopen(root, adapter, options);\n const { stamp, newest } = await takeStamp(root, snapshot, options.testResultsFile);\n\n // A change after the start may not be in the snapshot: keep it unstamped so the next call opens again.\n kept.set(key, {\n snapshot,\n stamp: newest > startedAt ? `unsettled:${stamp}` : stamp,\n });\n\n return snapshot;\n };\n\n return {\n async open(root, adapter, options = {}) {\n const key = keyOf(root, options);\n const known = kept.get(key);\n const mustOpen = options.force === true || options.routes === \"fresh\";\n\n if (known !== undefined && !mustOpen) {\n const stamp = await stampOf(root, known.snapshot, options.testResultsFile);\n\n if (stamp === known.stamp) return known.snapshot;\n }\n\n // Concurrent callers wait for the same open.\n const running = opening.get(key);\n\n if (running !== undefined && !mustOpen) return running;\n\n let started: Promise<GrimoireSnapshot>;\n\n if (options.write === false) {\n started = openOnce(key, root, adapter, options);\n } else {\n const before = writing.get(root) ?? Promise.resolve();\n\n started = before.catch(() => undefined).then(() => openOnce(key, root, adapter, options));\n writing.set(root, started);\n started\n .catch(() => undefined)\n .finally(() => {\n if (writing.get(root) === started) writing.delete(root);\n });\n }\n\n const tracked = started.finally(() => {\n if (opening.get(key) === tracked) opening.delete(key);\n });\n\n opening.set(key, tracked);\n\n return tracked;\n },\n clear() {\n kept.clear();\n },\n };\n}\n\n/** The process-wide cache the MCP tools and `warlock scry` use. */\nexport const openedBooks: BookCache = createBookCache();\n\n/** `openGrimoire` that keeps the book in memory while nothing changed. */\nexport function openGrimoireCached(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireSnapshot> {\n return openedBooks.open(root, adapter, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB;CACpB,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;AAEA,MAAM,aAAa;AAEnB,eAAe,SAAS,UAAkB,UAAoC;CAC5E,IAAI;EACF,MAAM,OAAO,MAAM,KAAK,QAAQ;EAEhC,OAAO,WAAW,GAAG,KAAK,KAAK,GAAG,KAAK,YAAY,OAAO,KAAK,OAAO;CACxE,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,QAAQ,OAA0B,UAAsC;CACrF,MAAM,QAAkB,CAAC;CAEzB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,YACjD,MAAM,KACJ,GAAI,MAAM,QAAQ,IAChB,MAAM,MAAM,OAAO,QAAQ,UAAU,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAC/E,CACF;CAGF,OAAO;AACT;;AAGA,eAAe,WAAW,QAAmC;CAC3D,MAAM,QAAkB,CAAC;CACzB,MAAM,OAAO,OAAO,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AGA,MAAa,cAAyB,gBAAgB;;AAGtD,SAAgB,mBACd,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,OAAO,YAAY,KAAK,MAAM,SAAS,OAAO;AAChD"}
1
+ {"version":3,"file":"cache.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/cache.ts"],"sourcesContent":["/**\n * Keeps the opened book in memory between calls of one process (the MCP\n * server answers many questions per process) and says cheaply whether it is\n * still current.\n *\n * Freshness is a stamp of `stat` results, no file is read: the size and\n * modified time of every code and test file the book lists, the modified time\n * of each folder that holds one and of every folder above it up to the project root (a new or removed file moves its\n * folder; a new module folder moves its parent), every\n * file under the written folders (`grimoire/features`, `apps`, `releases`,\n * `tasks`, `screenshots`), the book manifest, the test results file and\n * `package.json`. A stamp that equals the one taken after the last open\n * returns the same snapshot; any difference opens the book again.\n */\nimport { createHash } from \"node:crypto\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot, OpenGrimoireOptions } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { DERIVED_PATH } from \"./derived\";\nimport { openGrimoire } from \"./index\";\nimport { openStoredGrimoire } from \"./stored\";\n\n/** The written folders whose every file is part of the stamp. */\nconst WRITTEN_TREES = [\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.releases,\n GRIMOIRE_PATHS.tasks,\n GRIMOIRE_PATHS.screenshots,\n];\n\nconst STAT_BATCH = 256;\n\nasync function statLine(absolute: string, withSize: boolean): Promise<string> {\n try {\n const info = await stat(absolute);\n\n return withSize ? `${info.size}:${info.mtimeMs}` : String(info.mtimeMs);\n } catch {\n return \"-\";\n }\n}\n\nasync function statAll(files: readonly string[], withSize: boolean): Promise<string[]> {\n const lines: string[] = [];\n\n for (let start = 0; start < files.length; start += STAT_BATCH) {\n lines.push(\n ...(await Promise.all(\n files.slice(start, start + STAT_BATCH).map((file) => statLine(file, withSize)),\n )),\n );\n }\n\n return lines;\n}\n\n/** Every file below `folder` (absolute paths, sorted); a missing folder gives none. */\nasync function filesUnder(folder: string): Promise<string[]> {\n const found: string[] = [];\n const walk = async (current: string): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const next = path.join(current, entry.name);\n\n if (entry.isDirectory()) await walk(next);\n else found.push(next);\n }\n };\n\n await walk(folder);\n\n return found.sort();\n}\n\n/**\n * The freshness stamp of a project, from the files of `snapshot` (its code and\n * test files) and the written folders as they are now. Reads no file content.\n */\nexport async function stampOf(\n root: string,\n snapshot: GrimoireSnapshot,\n testResultsFile?: string,\n): Promise<string> {\n return (await takeStamp(root, snapshot, testResultsFile)).stamp;\n}\n\n/**\n * The stat lines of a stamp hold `size:mtime` or `mtime`; the newest mtime of them that is not after `until`\n * (a time in the future is clock skew, not an edit), 0 when none.\n */\nfunction newestOf(lines: readonly string[], until: number): number {\n let newest = 0;\n\n for (const line of lines) {\n const value = Number(line.split(\":\").pop());\n\n if (Number.isFinite(value) && value <= until && value > newest) newest = value;\n }\n\n return newest;\n}\n\n/** Every folder above `folder` up to (not including) the project root. */\nfunction withAncestors(folders: readonly string[]): string[] {\n const all = new Set<string>();\n\n for (const folder of folders) {\n let current = folder;\n\n while (current !== \".\" && current !== \"\" && current !== \"/\") {\n all.add(current);\n current = path.posix.dirname(current.split(path.sep).join(\"/\"));\n }\n }\n\n return [...all].sort();\n}\n\n/** The stamp, and the newest modified time among the code, test and written files and their folders. */\nasync function takeStamp(\n root: string,\n snapshot: GrimoireSnapshot,\n testResultsFile?: string,\n): Promise<{ stamp: string; newest: number }> {\n const listed = [\n ...snapshot.book.facts.files.map((file) => file.file),\n ...snapshot.book.facts.tests,\n ];\n const folders = withAncestors([...new Set(listed.map((file) => path.dirname(file)))]);\n const written = (\n await Promise.all(WRITTEN_TREES.map((tree) => filesUnder(path.join(root, ...tree.split(\"/\")))))\n ).flat();\n const singles = [\n path.join(root, ...GRIMOIRE_PATHS.bookManifest.split(\"/\")),\n path.join(root, ...GRIMOIRE_PATHS.bookRoutes.split(\"/\")),\n path.join(root, ...DERIVED_PATH.split(\"/\")),\n resolveResultsFile(root, testResultsFile),\n path.join(root, \"package.json\"),\n ];\n const [fileLines, folderLines, writtenLines, singleLines] = await Promise.all([\n statAll(\n listed.map((file) => path.join(root, ...file.split(\"/\"))),\n true,\n ),\n statAll(\n folders.map((folder) => path.join(root, ...folder.split(path.sep))),\n false,\n ),\n statAll(written, true),\n statAll(singles, true),\n ]);\n\n const stamp = createHash(\"sha1\")\n .update(\n JSON.stringify([listed, fileLines, folders, folderLines, written, writtenLines, singleLines]),\n )\n .digest(\"hex\");\n\n return { stamp, newest: newestOf([...fileLines, ...folderLines, ...writtenLines], Date.now()) };\n}\n\ntype Entry = { snapshot: GrimoireSnapshot; stamp: string };\n\n/** What a cached open is asked with; two different asks never share an entry. */\nfunction keyOf(root: string, options: OpenGrimoireOptions): string {\n return JSON.stringify([root, options.write !== false, options.testResultsFile ?? null]);\n}\n\n/** A book cache: `open()` returns the kept snapshot while the stamp holds. */\nexport type BookCache = {\n /** The snapshot for `root`: kept when nothing changed, else opened again. `force`, or `routes: \"fresh\"`, always opens. */\n open(\n root: string,\n adapter: BookAdapter,\n options?: OpenGrimoireOptions,\n ): Promise<GrimoireSnapshot>;\n /** Forget everything kept. */\n clear(): void;\n};\n\n/**\n * Create a cache. `reopen` is how the book is opened (default `openGrimoire`);\n * specs pass a counter to see how many times the book was really opened.\n */\nexport function createBookCache(reopen: typeof openGrimoire = openGrimoire): BookCache {\n const kept = new Map<string, Entry>();\n const opening = new Map<string, Promise<GrimoireSnapshot>>();\n // Opens that write the book's files wait for each other, per project.\n const writing = new Map<string, Promise<unknown>>();\n\n const openOnce = async (\n key: string,\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions,\n ): Promise<GrimoireSnapshot> => {\n // The clock is read before the open, so a file edited while it ran is seen as newer than the stamp.\n const startedAt = Date.now();\n const snapshot = await reopen(root, adapter, options);\n const { stamp, newest } = await takeStamp(root, snapshot, options.testResultsFile);\n\n // A change after the start may not be in the snapshot: keep it unstamped so the next call opens again.\n kept.set(key, {\n snapshot,\n stamp: newest > startedAt ? `unsettled:${stamp}` : stamp,\n });\n\n return snapshot;\n };\n\n return {\n async open(root, adapter, options = {}) {\n const key = keyOf(root, options);\n const known = kept.get(key);\n const mustOpen = options.force === true || options.routes === \"fresh\";\n\n if (known !== undefined && !mustOpen) {\n const stamp = await stampOf(root, known.snapshot, options.testResultsFile);\n\n if (stamp === known.stamp) return known.snapshot;\n }\n\n // Concurrent callers wait for the same open.\n const running = opening.get(key);\n\n if (running !== undefined && !mustOpen) return running;\n\n let started: Promise<GrimoireSnapshot>;\n\n if (options.write === false) {\n started = openOnce(key, root, adapter, options);\n } else {\n const before = writing.get(root) ?? Promise.resolve();\n\n started = before.catch(() => undefined).then(() => openOnce(key, root, adapter, options));\n writing.set(root, started);\n started\n .catch(() => undefined)\n .finally(() => {\n if (writing.get(root) === started) writing.delete(root);\n });\n }\n\n const tracked = started.finally(() => {\n if (opening.get(key) === tracked) opening.delete(key);\n });\n\n opening.set(key, tracked);\n\n return tracked;\n },\n clear() {\n kept.clear();\n },\n };\n}\n\n/** The process-wide cache the MCP tools and `warlock scry` use. */\nexport const openedBooks: BookCache = createBookCache();\n\n/** `openGrimoire` that keeps the book in memory while nothing changed. */\nexport function openGrimoireCached(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireSnapshot> {\n return openedBooks.open(root, adapter, options);\n}\n\n/** The same cache over the read-only open (`openStoredGrimoire`): never builds, never writes. */\nexport const storedBooks: BookCache = createBookCache(openStoredGrimoire);\n\n/** `openStoredGrimoire` that keeps the book in memory while nothing changed. */\nexport function openStoredGrimoireCached(\n root: string,\n adapter: BookAdapter,\n options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AAQ,UAAU,QAAQ,QAAQ,WAAW;GAE9D,IAAI,UAAU,UAAa,CAAC,UAG1B;QAAI,MAFgB,QAAQ,MAAM,MAAM,UAAU,QAAQ,eAAe,MAE3D,MAAM,OAAO,OAAO,MAAM;GAAQ;GAIlD,MAAM,UAAU,QAAQ,IAAI,GAAG;GAE/B,IAAI,YAAY,UAAa,CAAC,UAAU,OAAO;GAE/C,IAAI;GAEJ,IAAI,QAAQ,UAAU,OACpB,UAAU,SAAS,KAAK,MAAM,SAAS,OAAO;QACzC;IAGL,WAFe,QAAQ,IAAI,IAAI,KAAK,QAAQ,QAAQ,EAEpC,CAAC,YAAY,MAAS,CAAC,CAAC,WAAW,SAAS,KAAK,MAAM,SAAS,OAAO,CAAC;IACxF,QAAQ,IAAI,MAAM,OAAO;IACzB,QACG,YAAY,MAAS,CAAC,CACtB,cAAc;KACb,IAAI,QAAQ,IAAI,IAAI,MAAM,SAAS,QAAQ,OAAO,IAAI;IACxD,CAAC;GACL;GAEA,MAAM,UAAU,QAAQ,cAAc;IACpC,IAAI,QAAQ,IAAI,GAAG,MAAM,SAAS,QAAQ,OAAO,GAAG;GACtD,CAAC;GAED,QAAQ,IAAI,KAAK,OAAO;GAExB,OAAO;EACT;EACA,QAAQ;GACN,KAAK,MAAM;EACb;CACF;AACF;;AAGA,MAAa,cAAyB,gBAAgB;;AAGtD,SAAgB,mBACd,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,OAAO,YAAY,KAAK,MAAM,SAAS,OAAO;AAChD;;AAGA,MAAa,cAAyB,gBAAgB,kBAAkB;;AAGxE,SAAgB,yBACd,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,OAAO,YAAY,KAAK,MAAM,SAAS;EAAE,GAAG;EAAS,OAAO;CAAM,CAAC;AACrE"}
@@ -0,0 +1,107 @@
1
+ import { GRIMOIRE_PATHS } from "../paths/index.mjs";
2
+ import { readJson, writeBookFile } from "../book/io.mjs";
3
+ import { resolveResultsFile } from "../test-results/index.mjs";
4
+ import path from "node:path";
5
+ import { readdir, stat } from "node:fs/promises";
6
+
7
+ //#region ../../packages/grimoire/src/workspace/derived.ts
8
+ /**
9
+ * The derived half of a snapshot, kept on disk so that a read-only command
10
+ * (`warlock scry`, the MCP tools) never computes it again.
11
+ *
12
+ * `runGrimoire` writes `grimoire/book/.cache/derived.json` after the book and
13
+ * the collected files: the parsed written files, the owners, the matched apps,
14
+ * the proofs, the test results, the book maps and the annotations. Together
15
+ * with `manifest.json` and `.cache/facts.json` it is the whole snapshot.
16
+ * `openStoredGrimoire` loads it and compares the files with the fingerprint it
17
+ * was written with, so it can say that the book is behind without rebuilding.
18
+ */
19
+ /** Where `runGrimoire` keeps the derived data. */
20
+ const DERIVED_PATH = `${GRIMOIRE_PATHS.book}/.cache/derived.json`;
21
+ /** Bump when the shape below changes: an older file is treated as missing. */
22
+ const DERIVED_SCHEMA_VERSION = 2;
23
+ /** The written folders whose every file is part of the fingerprint. */
24
+ const WRITTEN_TREES = [
25
+ GRIMOIRE_PATHS.features,
26
+ GRIMOIRE_PATHS.apps,
27
+ GRIMOIRE_PATHS.releases,
28
+ GRIMOIRE_PATHS.tasks,
29
+ GRIMOIRE_PATHS.screenshots
30
+ ];
31
+ /** Every file below `folder`, absolute and sorted; a missing folder gives none. */
32
+ async function filesUnder(folder) {
33
+ const found = [];
34
+ const walk = async (current) => {
35
+ let entries;
36
+ try {
37
+ entries = await readdir(current, { withFileTypes: true });
38
+ } catch {
39
+ return;
40
+ }
41
+ for (const entry of entries) {
42
+ const next = path.join(current, entry.name);
43
+ if (entry.isDirectory()) await walk(next);
44
+ else found.push(next);
45
+ }
46
+ };
47
+ await walk(folder);
48
+ return found.sort();
49
+ }
50
+ /** `size:mtimeMs` of every written file and of the test results file (`-` when it is missing). */
51
+ async function derivedInputs(root, testResultsFile) {
52
+ const files = (await Promise.all(WRITTEN_TREES.map((tree) => filesUnder(path.join(root, ...tree.split("/")))))).flat();
53
+ const results = resolveResultsFile(root, testResultsFile);
54
+ const inputs = {};
55
+ for (const file of [...files, results]) {
56
+ const key = path.relative(root, file).split(path.sep).join("/");
57
+ try {
58
+ const info = await stat(file);
59
+ inputs[key] = `${info.size}:${info.mtimeMs}`;
60
+ } catch {
61
+ inputs[key] = "-";
62
+ }
63
+ }
64
+ return inputs;
65
+ }
66
+ /** How many of the stored inputs differ from the files now (changed, added or removed). */
67
+ function movedInputs(stored, current) {
68
+ let moved = 0;
69
+ for (const [file, stamp] of Object.entries(current)) if (stored[file] !== stamp && !(stored[file] === void 0 && stamp === "-")) moved++;
70
+ for (const [file, stamp] of Object.entries(stored)) if (current[file] === void 0 && stamp !== "-") moved++;
71
+ return moved;
72
+ }
73
+ /** Keep the derived half of `snapshot` (the file is rewritten only when its content changed). */
74
+ async function writeDerived(root, snapshot, version, testResultsFile) {
75
+ const stored = {
76
+ schemaVersion: 2,
77
+ grimoireVersion: version,
78
+ builtAt: snapshot.book.manifest.builtAt,
79
+ inputs: await derivedInputs(root, testResultsFile),
80
+ snapshot: {
81
+ written: snapshot.written,
82
+ structure: snapshot.structure,
83
+ ownership: snapshot.ownership,
84
+ apps: snapshot.apps,
85
+ proofs: snapshot.proofs,
86
+ proofFindings: snapshot.proofFindings,
87
+ results: snapshot.results,
88
+ resultsFile: snapshot.resultsFile,
89
+ collected: snapshot.collected,
90
+ annotations: snapshot.annotations,
91
+ host: snapshot.host ?? null
92
+ }
93
+ };
94
+ const previous = await readJson(path.join(root, ...DERIVED_PATH.split("/")));
95
+ if (previous !== null && JSON.stringify(previous) === JSON.stringify(stored)) return;
96
+ await writeBookFile(root, DERIVED_PATH, `${JSON.stringify(stored)}\n`);
97
+ }
98
+ /** The stored derived data; `null` when missing, unreadable, or written by another schema or version. */
99
+ async function readDerived(root, version) {
100
+ const stored = await readJson(path.join(root, ...DERIVED_PATH.split("/")));
101
+ if (stored === null || stored.schemaVersion !== 2 || stored.grimoireVersion !== version || typeof stored.builtAt !== "string" || typeof stored.inputs !== "object" || stored.inputs === null || typeof stored.snapshot !== "object" || stored.snapshot === null) return null;
102
+ return stored;
103
+ }
104
+
105
+ //#endregion
106
+ export { DERIVED_PATH, derivedInputs, movedInputs, readDerived, writeDerived };
107
+ //# sourceMappingURL=derived.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derived.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/derived.ts"],"sourcesContent":["/**\n * The derived half of a snapshot, kept on disk so that a read-only command\n * (`warlock scry`, the MCP tools) never computes it again.\n *\n * `runGrimoire` writes `grimoire/book/.cache/derived.json` after the book and\n * the collected files: the parsed written files, the owners, the matched apps,\n * the proofs, the test results, the book maps and the annotations. Together\n * with `manifest.json` and `.cache/facts.json` it is the whole snapshot.\n * `openStoredGrimoire` loads it and compares the files with the fingerprint it\n * was written with, so it can say that the book is behind without rebuilding.\n */\nimport { readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { readJson, writeBookFile } from \"../book/io\";\nimport type { BookAnnotations } from \"../contracts/book\";\nimport type { CollectedFiles, Ownership } from \"../contracts/bookmap\";\nimport type { BookHost } from \"../contracts/adapter\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { AppMatch, GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { ProofLine, TestResultsStore } from \"../contracts/test-results\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\n\n/** Where `runGrimoire` keeps the derived data. */\nexport const DERIVED_PATH = `${GRIMOIRE_PATHS.book}/.cache/derived.json`;\n\n/** Bump when the shape below changes: an older file is treated as missing. */\nexport const DERIVED_SCHEMA_VERSION = 2;\n\n/** The written folders whose every file is part of the fingerprint. */\nconst WRITTEN_TREES = [\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.releases,\n GRIMOIRE_PATHS.tasks,\n GRIMOIRE_PATHS.screenshots,\n];\n\n/** What a snapshot holds besides the book. */\nexport type DerivedSnapshot = {\n written: WrittenGrimoire;\n structure: GrimoireFinding[];\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n proofFindings: GrimoireFinding[];\n results: TestResultsStore | null;\n resultsFile: string;\n collected: CollectedFiles;\n annotations: BookAnnotations;\n host: BookHost | null;\n};\n\n/** The file as stored. */\nexport type StoredDerived = {\n schemaVersion: number;\n grimoireVersion: string;\n /** `manifest.builtAt` of the book this was derived from: a build that stopped between the two writes leaves a mismatch. */\n builtAt: string;\n /** Project-relative POSIX path → `size:mtimeMs`, of every written file and the test results file. */\n inputs: Record<string, string>;\n snapshot: DerivedSnapshot;\n};\n\n/** Every file below `folder`, absolute and sorted; a missing folder gives none. */\nasync function filesUnder(folder: string): Promise<string[]> {\n const found: string[] = [];\n const walk = async (current: string): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const next = path.join(current, entry.name);\n\n if (entry.isDirectory()) await walk(next);\n else found.push(next);\n }\n };\n\n await walk(folder);\n\n return found.sort();\n}\n\n/** `size:mtimeMs` of every written file and of the test results file (`-` when it is missing). */\nexport async function derivedInputs(\n root: string,\n testResultsFile?: string,\n): Promise<Record<string, string>> {\n const files = (\n await Promise.all(WRITTEN_TREES.map((tree) => filesUnder(path.join(root, ...tree.split(\"/\")))))\n ).flat();\n const results = resolveResultsFile(root, testResultsFile);\n const inputs: Record<string, string> = {};\n\n for (const file of [...files, results]) {\n const key = path.relative(root, file).split(path.sep).join(\"/\");\n\n try {\n const info = await stat(file);\n\n inputs[key] = `${info.size}:${info.mtimeMs}`;\n } catch {\n inputs[key] = \"-\";\n }\n }\n\n return inputs;\n}\n\n/** How many of the stored inputs differ from the files now (changed, added or removed). */\nexport function movedInputs(\n stored: Record<string, string>,\n current: Record<string, string>,\n): number {\n let moved = 0;\n\n for (const [file, stamp] of Object.entries(current)) {\n if (stored[file] !== stamp && !(stored[file] === undefined && stamp === \"-\")) moved++;\n }\n\n for (const [file, stamp] of Object.entries(stored)) {\n if (current[file] === undefined && stamp !== \"-\") moved++;\n }\n\n return moved;\n}\n\n/** Keep the derived half of `snapshot` (the file is rewritten only when its content changed). */\nexport async function writeDerived(\n root: string,\n snapshot: GrimoireSnapshot,\n version: string,\n testResultsFile?: string,\n): Promise<void> {\n const stored: StoredDerived = {\n schemaVersion: DERIVED_SCHEMA_VERSION,\n grimoireVersion: version,\n builtAt: snapshot.book.manifest.builtAt,\n inputs: await derivedInputs(root, testResultsFile),\n snapshot: {\n written: snapshot.written,\n structure: snapshot.structure,\n ownership: snapshot.ownership,\n apps: snapshot.apps,\n proofs: snapshot.proofs,\n proofFindings: snapshot.proofFindings,\n results: snapshot.results,\n resultsFile: snapshot.resultsFile,\n collected: snapshot.collected,\n annotations: snapshot.annotations,\n host: snapshot.host ?? null,\n },\n };\n const previous = await readJson<StoredDerived>(path.join(root, ...DERIVED_PATH.split(\"/\")));\n\n // A rerun with nothing changed writes nothing.\n if (previous !== null && JSON.stringify(previous) === JSON.stringify(stored)) return;\n\n await writeBookFile(root, DERIVED_PATH, `${JSON.stringify(stored)}\\n`);\n}\n\n/** The stored derived data; `null` when missing, unreadable, or written by another schema or version. */\nexport async function readDerived(root: string, version: string): Promise<StoredDerived | null> {\n const stored = await readJson<StoredDerived>(path.join(root, ...DERIVED_PATH.split(\"/\")));\n\n if (\n stored === null ||\n stored.schemaVersion !== DERIVED_SCHEMA_VERSION ||\n stored.grimoireVersion !== version ||\n typeof stored.builtAt !== \"string\" ||\n typeof stored.inputs !== \"object\" ||\n stored.inputs === null ||\n typeof stored.snapshot !== \"object\" ||\n stored.snapshot === null\n ) {\n return null;\n }\n\n return stored;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAAa,eAAe,GAAG,eAAe,KAAK;;AAGnD,MAAa,yBAAyB;;AAGtC,MAAM,gBAAgB;CACpB,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe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a,UAAU,KAAK;CAGpD,OAAO;AACT;;AAGA,eAAsB,aACpB,MACA,UACA,SACA,iBACe;CACf,MAAM,SAAwB;EAC5B;EACA,iBAAiB;EACjB,SAAS,SAAS,KAAK,SAAS;EAChC,QAAQ,MAAM,cAAc,MAAM,eAAe;EACjD,UAAU;GACR,SAAS,SAAS;GAClB,WAAW,SAAS;GACpB,WAAW,SAAS;GACpB,MAAM,SAAS;GACf,QAAQ,SAAS;GACjB,eAAe,SAAS;GACxB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,WAAW,SAAS;GACpB,aAAa,SAAS;GACtB,MAAM,SAAS,QAAQ;EACzB;CACF;CACA,MAAM,WAAW,MAAM,SAAwB,KAAK,KAAK,MAAM,GAAG,aAAa,MAAM,GAAG,CAAC,CAAC;CAG1F,IAAI,aAAa,QAAQ,KAAK,UAAU,QAAQ,MAAM,KAAK,UAAU,MAAM,GAAG;CAE9E,MAAM,cAAc,MAAM,cAAc,GAAG,KAAK,UAAU,MAAM,EAAE,GAAG;AACvE;;AAGA,eAAsB,YAAY,MAAc,SAAgD;CAC9F,MAAM,SAAS,MAAM,SAAwB,KAAK,KAAK,MAAM,GAAG,aAAa,MAAM,GAAG,CAAC,CAAC;CAExF,IACE,WAAW,QACX,OAAO,uBACP,OAAO,oBAAoB,WAC3B,OAAO,OAAO,YAAY,YAC1B,OAAO,OAAO,WAAW,YACzB,OAAO,WAAW,QAClB,OAAO,OAAO,aAAa,YAC3B,OAAO,aAAa,MAEpB,OAAO;CAGT,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/index.ts"],"mappings":";;;;;;;;wBAuJsB,aACpB,cACA,SAAS,aACT,UAAS,sBACR,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/index.ts"],"mappings":";;;;;;;;wBA8JsB,aACpB,cACA,SAAS,aACT,UAAS,sBACR,QAAQ"}
@@ -1,7 +1,7 @@
1
1
  import { toPosixPath } from "../paths/index.mjs";
2
2
  import { parseGrimoire } from "../written/parse-grimoire.mjs";
3
3
  import "../written/index.mjs";
4
- import { buildBook } from "../book/build.mjs";
4
+ import { buildBook, grimoireVersion } from "../book/build.mjs";
5
5
  import { writeBook } from "../book/write.mjs";
6
6
  import "../book/index.mjs";
7
7
  import { resolveOwnership } from "../ownership/index.mjs";
@@ -13,6 +13,7 @@ import { writeCollectedFiles } from "../bookmap/write.mjs";
13
13
  import "../bookmap/index.mjs";
14
14
  import { scanProofs } from "../proves/scan-proofs.mjs";
15
15
  import "../proves/index.mjs";
16
+ import { writeDerived } from "./derived.mjs";
16
17
  import path from "node:path";
17
18
  import { createHash } from "node:crypto";
18
19
  import { readFile } from "node:fs/promises";
@@ -25,7 +26,8 @@ import { readFile } from "node:fs/promises";
25
26
  * 2. `buildBook(root, adapter, { routes })`;
26
27
  * 3. `matchApps`, `resolveOwnership`, `scanProofs`, `readTestResults`;
27
28
  * 4. `buildCollectedFiles`, `annotationsFrom`;
28
- * 5. when `write` is not `false`: `writeBook` and `writeCollectedFiles`.
29
+ * 5. when `write` is not `false`: `writeBook`, `writeCollectedFiles` and the derived file
30
+ * (`derived.ts`) that `openStoredGrimoire` reads instead of computing 1–4.
29
31
  *
30
32
  * A second run with nothing changed calls no adapter method and writes no file.
31
33
  */
@@ -89,23 +91,25 @@ async function runGrimoire(root, adapter, options = {}) {
89
91
  collectedWrite = await writeCollectedFiles(root, collected);
90
92
  }
91
93
  const host = await adapter.host?.(root) ?? null;
94
+ const snapshot = {
95
+ root,
96
+ written,
97
+ structure,
98
+ book,
99
+ ownership,
100
+ apps,
101
+ proofs,
102
+ proofFindings,
103
+ results,
104
+ resultsFile,
105
+ collected,
106
+ annotations,
107
+ routes: book.routes,
108
+ host
109
+ };
110
+ if (write) await writeDerived(root, snapshot, grimoireVersion(), options.testResultsFile);
92
111
  return {
93
- snapshot: {
94
- root,
95
- written,
96
- structure,
97
- book,
98
- ownership,
99
- apps,
100
- proofs,
101
- proofFindings,
102
- results,
103
- resultsFile,
104
- collected,
105
- annotations,
106
- routes: book.routes,
107
- host
108
- },
112
+ snapshot,
109
113
  rebuilt,
110
114
  changed,
111
115
  book: bookWrite,
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/index.ts"],"sourcesContent":["/**\n * The pipeline every command runs first (owned by T-128):\n *\n * 1. `parseGrimoire(root)`;\n * 2. `buildBook(root, adapter, { routes })`;\n * 3. `matchApps`, `resolveOwnership`, `scanProofs`, `readTestResults`;\n * 4. `buildCollectedFiles`, `annotationsFrom`;\n * 5. when `write` is not `false`: `writeBook` and `writeCollectedFiles`.\n *\n * A second run with nothing changed calls no adapter method and writes no file.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { matchApps } from \"../apps\";\nimport { buildBook, writeBook } from \"../book\";\nimport {\n annotationsFrom,\n buildCollectedFiles,\n writeCollectedFiles,\n type CollectedInput,\n} from \"../bookmap\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { BuildBookOptions, WriteBookResult } from \"../contracts/book\";\nimport type { GrimoireSnapshot, OpenGrimoireOptions } from \"../contracts/snapshot\";\nimport { resolveOwnership } from \"../ownership\";\nimport { toPosixPath } from \"../paths\";\nimport { scanProofs } from \"../proves\";\nimport { readTestResults, resultsFileLabel } from \"../test-results\";\nimport { parseGrimoire } from \"../written\";\n\n/** The current sha256 of each test file: the manifest's, else read now (missing files are left out). */\nasync function testFileHashes(\n root: string,\n tests: readonly string[],\n known: Readonly<Record<string, string>>,\n): Promise<Record<string, string>> {\n const hashes: Record<string, string> = {};\n\n for (const test of [...new Set(tests.map(toPosixPath))].sort()) {\n const hash = known[test];\n\n if (hash !== undefined) {\n hashes[test] = hash;\n continue;\n }\n\n try {\n const content = await readFile(path.join(root, ...test.split(\"/\")));\n hashes[test] = createHash(\"sha256\").update(content).digest(\"hex\");\n } catch {\n // A listed test file that is gone has no hash; its results are not marked stale.\n }\n }\n\n return hashes;\n}\n\n/** What one pass of the pipeline did, with the snapshot it produced (`warlock grimoire build` prints it). */\nexport type GrimoireRun = {\n snapshot: GrimoireSnapshot;\n /** `false` when the book's fingerprint matched and the adapter was not asked for files. */\n rebuilt: boolean;\n /** Source files added, changed or removed since the last build. */\n changed: string[];\n /** Book files written and removed (both empty with `write: false`). */\n book: WriteBookResult;\n /** Collected files (book maps, indexes) written and removed (both empty with `write: false`). */\n collected: { written: string[]; removed: string[] };\n};\n\n/**\n * Run the pipeline and say what it wrote. `openGrimoire` is this without the\n * counts.\n *\n * @param root Absolute project root.\n */\nexport async function runGrimoire(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireRun> {\n const write = options.write !== false;\n const { written, findings: structure } = await parseGrimoire(root);\n\n const bookOptions: BuildBookOptions & { write?: boolean } = {\n routes: options.routes ?? \"cached\",\n };\n\n if (options.force !== undefined) bookOptions.force = options.force;\n if (options.now !== undefined) bookOptions.now = options.now;\n if (!write) bookOptions.write = false;\n\n const { book, rebuilt, changed } = await buildBook(root, adapter, bookOptions);\n const apps = matchApps(written.apps, book.facts);\n const ownership = resolveOwnership(written, book.facts);\n const { proofs, findings: proofFindings } = await scanProofs(root, book.facts.tests);\n const resultsFile = resultsFileLabel(root, options.testResultsFile);\n const results = await readTestResults(root, options.testResultsFile);\n const testHashes = await testFileHashes(root, book.facts.tests, book.manifest.tests);\n\n const input: CollectedInput = {\n written,\n facts: book.facts,\n ownership,\n apps,\n proofs,\n results,\n testHashes,\n };\n const collected = buildCollectedFiles(input);\n const annotations = annotationsFrom(input, collected, { tests: testHashes });\n let bookWrite: WriteBookResult = { written: [], removed: [] };\n let collectedWrite: { written: string[]; removed: string[] } = { written: [], removed: [] };\n\n if (write) {\n bookWrite = await writeBook(book, annotations);\n collectedWrite = await writeCollectedFiles(root, collected);\n }\n\n const host = (await adapter.host?.(root)) ?? null;\n\n return {\n snapshot: {\n root,\n written,\n structure,\n book,\n ownership,\n apps,\n proofs,\n proofFindings,\n results,\n resultsFile,\n collected,\n annotations,\n routes: book.routes,\n host,\n },\n rebuilt,\n changed,\n book: bookWrite,\n collected: collectedWrite,\n };\n}\n\n/**\n * Load, refresh and return everything about the project's grimoire.\n *\n * @param root Absolute project root.\n */\nexport async function openGrimoire(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireSnapshot> {\n return (await runGrimoire(root, adapter, options)).snapshot;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAe,eACb,MACA,OACA,OACiC;CACjC,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;EAC9D,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS,QAAW;GACtB,OAAO,QAAQ;GACf;EACF;EAEA,IAAI;GACF,MAAM,UAAU,MAAM,SAAS,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC;GAClE,OAAO,QAAQ,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;EAClE,QAAQ,CAER;CACF;CAEA,OAAO;AACT;;;;;;;AAqBA,eAAsB,YACpB,MACA,SACA,UAA+B,CAAC,GACV;CACtB,MAAM,QAAQ,QAAQ,UAAU;CAChC,MAAM,EAAE,SAAS,UAAU,cAAc,MAAM,cAAc,IAAI;CAEjE,MAAM,cAAsD,EAC1D,QAAQ,QAAQ,UAAU,SAC5B;CAEA,IAAI,QAAQ,UAAU,QAAW,YAAY,QAAQ,QAAQ;CAC7D,IAAI,QAAQ,QAAQ,QAAW,YAAY,MAAM,QAAQ;CACzD,IAAI,CAAC,OAAO,YAAY,QAAQ;CAEhC,MAAM,EAAE,MAAM,SAAS,YAAY,MAAM,UAAU,MAAM,SAAS,WAAW;CAC7E,MAAM,OAAO,UAAU,QAAQ,MAAM,KAAK,KAAK;CAC/C,MAAM,YAAY,iBAAiB,SAAS,KAAK,KAAK;CACtD,MAAM,EAAE,QAAQ,UAAU,kBAAkB,MAAM,WAAW,MAAM,KAAK,MAAM,KAAK;CACnF,MAAM,cAAc,iBAAiB,MAAM,QAAQ,eAAe;CAClE,MAAM,UAAU,MAAM,gBAAgB,MAAM,QAAQ,eAAe;CACnE,MAAM,aAAa,MAAM,eAAe,MAAM,KAAK,MAAM,OAAO,KAAK,SAAS,KAAK;CAEnF,MAAM,QAAwB;EAC5B;EACA,OAAO,KAAK;EACZ;EACA;EACA;EACA;EACA;CACF;CACA,MAAM,YAAY,oBAAoB,KAAK;CAC3C,MAAM,cAAc,gBAAgB,OAAO,WAAW,EAAE,OAAO,WAAW,CAAC;CAC3E,IAAI,YAA6B;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAC5D,IAAI,iBAA2D;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAE1F,IAAI,OAAO;EACT,YAAY,MAAM,UAAU,MAAM,WAAW;EAC7C,iBAAiB,MAAM,oBAAoB,MAAM,SAAS;CAC5D;CAEA,MAAM,OAAQ,MAAM,QAAQ,OAAO,IAAI,KAAM;CAE7C,OAAO;EACL,UAAU;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ,KAAK;GACb;EACF;EACA;EACA;EACA,MAAM;EACN,WAAW;CACb;AACF;;;;;;AAOA,eAAsB,aACpB,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,QAAQ,MAAM,YAAY,MAAM,SAAS,OAAO,EAAC,CAAE;AACrD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/index.ts"],"sourcesContent":["/**\n * The pipeline every command runs first (owned by T-128):\n *\n * 1. `parseGrimoire(root)`;\n * 2. `buildBook(root, adapter, { routes })`;\n * 3. `matchApps`, `resolveOwnership`, `scanProofs`, `readTestResults`;\n * 4. `buildCollectedFiles`, `annotationsFrom`;\n * 5. when `write` is not `false`: `writeBook`, `writeCollectedFiles` and the derived file\n * (`derived.ts`) that `openStoredGrimoire` reads instead of computing 1–4.\n *\n * A second run with nothing changed calls no adapter method and writes no file.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { matchApps } from \"../apps\";\nimport { buildBook, writeBook } from \"../book\";\nimport { grimoireVersion } from \"../book/build\";\nimport {\n annotationsFrom,\n buildCollectedFiles,\n writeCollectedFiles,\n type CollectedInput,\n} from \"../bookmap\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { BuildBookOptions, WriteBookResult } from \"../contracts/book\";\nimport type { GrimoireSnapshot, OpenGrimoireOptions } from \"../contracts/snapshot\";\nimport { resolveOwnership } from \"../ownership\";\nimport { toPosixPath } from \"../paths\";\nimport { scanProofs } from \"../proves\";\nimport { readTestResults, resultsFileLabel } from \"../test-results\";\nimport { parseGrimoire } from \"../written\";\nimport { writeDerived } from \"./derived\";\n\n/** The current sha256 of each test file: the manifest's, else read now (missing files are left out). */\nasync function testFileHashes(\n root: string,\n tests: readonly string[],\n known: Readonly<Record<string, string>>,\n): Promise<Record<string, string>> {\n const hashes: Record<string, string> = {};\n\n for (const test of [...new Set(tests.map(toPosixPath))].sort()) {\n const hash = known[test];\n\n if (hash !== undefined) {\n hashes[test] = hash;\n continue;\n }\n\n try {\n const content = await readFile(path.join(root, ...test.split(\"/\")));\n hashes[test] = createHash(\"sha256\").update(content).digest(\"hex\");\n } catch {\n // A listed test file that is gone has no hash; its results are not marked stale.\n }\n }\n\n return hashes;\n}\n\n/** What one pass of the pipeline did, with the snapshot it produced (`warlock grimoire build` prints it). */\nexport type GrimoireRun = {\n snapshot: GrimoireSnapshot;\n /** `false` when the book's fingerprint matched and the adapter was not asked for files. */\n rebuilt: boolean;\n /** Source files added, changed or removed since the last build. */\n changed: string[];\n /** Book files written and removed (both empty with `write: false`). */\n book: WriteBookResult;\n /** Collected files (book maps, indexes) written and removed (both empty with `write: false`). */\n collected: { written: string[]; removed: string[] };\n};\n\n/**\n * Run the pipeline and say what it wrote. `openGrimoire` is this without the\n * counts.\n *\n * @param root Absolute project root.\n */\nexport async function runGrimoire(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireRun> {\n const write = options.write !== false;\n const { written, findings: structure } = await parseGrimoire(root);\n\n const bookOptions: BuildBookOptions & { write?: boolean } = {\n routes: options.routes ?? \"cached\",\n };\n\n if (options.force !== undefined) bookOptions.force = options.force;\n if (options.now !== undefined) bookOptions.now = options.now;\n if (!write) bookOptions.write = false;\n\n const { book, rebuilt, changed } = await buildBook(root, adapter, bookOptions);\n const apps = matchApps(written.apps, book.facts);\n const ownership = resolveOwnership(written, book.facts);\n const { proofs, findings: proofFindings } = await scanProofs(root, book.facts.tests);\n const resultsFile = resultsFileLabel(root, options.testResultsFile);\n const results = await readTestResults(root, options.testResultsFile);\n const testHashes = await testFileHashes(root, book.facts.tests, book.manifest.tests);\n\n const input: CollectedInput = {\n written,\n facts: book.facts,\n ownership,\n apps,\n proofs,\n results,\n testHashes,\n };\n const collected = buildCollectedFiles(input);\n const annotations = annotationsFrom(input, collected, { tests: testHashes });\n let bookWrite: WriteBookResult = { written: [], removed: [] };\n let collectedWrite: { written: string[]; removed: string[] } = { written: [], removed: [] };\n\n if (write) {\n bookWrite = await writeBook(book, annotations);\n collectedWrite = await writeCollectedFiles(root, collected);\n }\n\n const host = (await adapter.host?.(root)) ?? null;\n const snapshot: GrimoireSnapshot = {\n root,\n written,\n structure,\n book,\n ownership,\n apps,\n proofs,\n proofFindings,\n results,\n resultsFile,\n collected,\n annotations,\n routes: book.routes,\n host,\n };\n\n // The derived half is kept for the read-only commands (`warlock scry`).\n if (write) await writeDerived(root, snapshot, grimoireVersion(), options.testResultsFile);\n\n return {\n snapshot,\n rebuilt,\n changed,\n book: bookWrite,\n collected: collectedWrite,\n };\n}\n\n/**\n * Load, refresh and return everything about the project's grimoire.\n *\n * @param root Absolute project root.\n */\nexport async function openGrimoire(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireSnapshot> {\n return (await runGrimoire(root, adapter, options)).snapshot;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAe,eACb,MACA,OACA,OACiC;CACjC,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;EAC9D,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS,QAAW;GACtB,OAAO,QAAQ;GACf;EACF;EAEA,IAAI;GACF,MAAM,UAAU,MAAM,SAAS,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC;GAClE,OAAO,QAAQ,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;EAClE,QAAQ,CAER;CACF;CAEA,OAAO;AACT;;;;;;;AAqBA,eAAsB,YACpB,MACA,SACA,UAA+B,CAAC,GACV;CACtB,MAAM,QAAQ,QAAQ,UAAU;CAChC,MAAM,EAAE,SAAS,UAAU,cAAc,MAAM,cAAc,IAAI;CAEjE,MAAM,cAAsD,EAC1D,QAAQ,QAAQ,UAAU,SAC5B;CAEA,IAAI,QAAQ,UAAU,QAAW,YAAY,QAAQ,QAAQ;CAC7D,IAAI,QAAQ,QAAQ,QAAW,YAAY,MAAM,QAAQ;CACzD,IAAI,CAAC,OAAO,YAAY,QAAQ;CAEhC,MAAM,EAAE,MAAM,SAAS,YAAY,MAAM,UAAU,MAAM,SAAS,WAAW;CAC7E,MAAM,OAAO,UAAU,QAAQ,MAAM,KAAK,KAAK;CAC/C,MAAM,YAAY,iBAAiB,SAAS,KAAK,KAAK;CACtD,MAAM,EAAE,QAAQ,UAAU,kBAAkB,MAAM,WAAW,MAAM,KAAK,MAAM,KAAK;CACnF,MAAM,cAAc,iBAAiB,MAAM,QAAQ,eAAe;CAClE,MAAM,UAAU,MAAM,gBAAgB,MAAM,QAAQ,eAAe;CACnE,MAAM,aAAa,MAAM,eAAe,MAAM,KAAK,MAAM,OAAO,KAAK,SAAS,KAAK;CAEnF,MAAM,QAAwB;EAC5B;EACA,OAAO,KAAK;EACZ;EACA;EACA;EACA;EACA;CACF;CACA,MAAM,YAAY,oBAAoB,KAAK;CAC3C,MAAM,cAAc,gBAAgB,OAAO,WAAW,EAAE,OAAO,WAAW,CAAC;CAC3E,IAAI,YAA6B;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAC5D,IAAI,iBAA2D;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CAE1F,IAAI,OAAO;EACT,YAAY,MAAM,UAAU,MAAM,WAAW;EAC7C,iBAAiB,MAAM,oBAAoB,MAAM,SAAS;CAC5D;CAEA,MAAM,OAAQ,MAAM,QAAQ,OAAO,IAAI,KAAM;CAC7C,MAAM,WAA6B;EACjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ,KAAK;EACb;CACF;CAGA,IAAI,OAAO,MAAM,aAAa,MAAM,UAAU,gBAAgB,GAAG,QAAQ,eAAe;CAExF,OAAO;EACL;EACA;EACA;EACA,MAAM;EACN,WAAW;CACb;AACF;;;;;;AAOA,eAAsB,aACpB,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,QAAQ,MAAM,YAAY,MAAM,SAAS,OAAO,EAAC,CAAE;AACrD"}
@@ -0,0 +1,12 @@
1
+ import { BookAdapter } from "../contracts/adapter.mjs";
2
+ import { GrimoireSnapshot, OpenGrimoireOptions } from "../contracts/snapshot.mjs";
3
+ //#region ../../packages/grimoire/src/workspace/stored.d.ts
4
+ /**
5
+ * Open the stored book without building it. Throws `GR9007` when there is no
6
+ * book, or its derived data is missing or from another version.
7
+ *
8
+ * @param root Absolute project root.
9
+ */
10
+ export declare function openStoredGrimoire(root: string, adapter: BookAdapter, options?: OpenGrimoireOptions): Promise<GrimoireSnapshot>;
11
+ //#endregion
12
+ //# sourceMappingURL=stored.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stored.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/stored.ts"],"mappings":";;;;;;;;;wBA+BsB,mBACpB,cACA,SAAS,aACT,UAAS,sBACR,QAAQ"}
@@ -0,0 +1,46 @@
1
+ import { GrimoireError } from "../codes/index.mjs";
2
+ import { checkBook, grimoireVersion } from "../book/build.mjs";
3
+ import { derivedInputs, movedInputs, readDerived } from "./derived.mjs";
4
+
5
+ //#region ../../packages/grimoire/src/workspace/stored.ts
6
+ /**
7
+ * The read-only open: `warlock scry` and the MCP tools. It loads the book the
8
+ * last `warlock grimoire build` left on disk and never rebuilds or writes it.
9
+ *
10
+ * What it reads: `manifest.json` and `.cache/facts.json` (the book) and
11
+ * `.cache/derived.json` (owners, apps, proofs, results, book maps,
12
+ * annotations, the parsed written files). What it computes: one change check,
13
+ * the `buildBook` scan of the source roots and tests (no adapter `files()`
14
+ * call) and a `stat` of the written files. Anything that moved is reported in
15
+ * `snapshot.behind`; the answer is still the stored one.
16
+ */
17
+ /** The error of a project whose book was never built, or was built by another version. */
18
+ function notBuilt(reason) {
19
+ return new GrimoireError("GR9007", `${reason} Run warlock grimoire build, then ask again (warlock scry only reads the book).`);
20
+ }
21
+ /**
22
+ * Open the stored book without building it. Throws `GR9007` when there is no
23
+ * book, or its derived data is missing or from another version.
24
+ *
25
+ * @param root Absolute project root.
26
+ */
27
+ async function openStoredGrimoire(root, adapter, options = {}) {
28
+ const checked = await checkBook(root, adapter);
29
+ if (checked === null) throw notBuilt("The book has not been built yet.");
30
+ const derived = await readDerived(root, grimoireVersion());
31
+ if (derived === null) throw notBuilt("The book's derived data is missing or was written by another version.");
32
+ if (derived.builtAt !== checked.book.manifest.builtAt) throw notBuilt("The book's derived data does not match its manifest (a build did not finish).");
33
+ const moved = movedInputs(derived.inputs, await derivedInputs(root, options.testResultsFile));
34
+ const changed = checked.changed.length + moved;
35
+ return {
36
+ root: checked.book.root,
37
+ book: checked.book,
38
+ routes: checked.book.routes,
39
+ ...derived.snapshot,
40
+ ...changed > 0 ? { behind: { changed } } : {}
41
+ };
42
+ }
43
+
44
+ //#endregion
45
+ export { openStoredGrimoire };
46
+ //# sourceMappingURL=stored.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stored.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/workspace/stored.ts"],"sourcesContent":["/**\n * The read-only open: `warlock scry` and the MCP tools. It loads the book the\n * last `warlock grimoire build` left on disk and never rebuilds or writes it.\n *\n * What it reads: `manifest.json` and `.cache/facts.json` (the book) and\n * `.cache/derived.json` (owners, apps, proofs, results, book maps,\n * annotations, the parsed written files). What it computes: one change check,\n * the `buildBook` scan of the source roots and tests (no adapter `files()`\n * call) and a `stat` of the written files. Anything that moved is reported in\n * `snapshot.behind`; the answer is still the stored one.\n */\nimport { checkBook, grimoireVersion } from \"../book/build\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot, OpenGrimoireOptions } from \"../contracts/snapshot\";\nimport { derivedInputs, movedInputs, readDerived } from \"./derived\";\n\n/** The error of a project whose book was never built, or was built by another version. */\nfunction notBuilt(reason: string): GrimoireError {\n return new GrimoireError(\n \"GR9007\",\n `${reason} Run warlock grimoire build, then ask again (warlock scry only reads the book).`,\n );\n}\n\n/**\n * Open the stored book without building it. Throws `GR9007` when there is no\n * book, or its derived data is missing or from another version.\n *\n * @param root Absolute project root.\n */\nexport async function openStoredGrimoire(\n root: string,\n adapter: BookAdapter,\n options: OpenGrimoireOptions = {},\n): Promise<GrimoireSnapshot> {\n const checked = await checkBook(root, adapter);\n\n if (checked === null) throw notBuilt(\"The book has not been built yet.\");\n\n const derived = await readDerived(root, grimoireVersion());\n\n if (derived === null) {\n throw notBuilt(\"The book's derived data is missing or was written by another version.\");\n }\n\n if (derived.builtAt !== checked.book.manifest.builtAt) {\n throw notBuilt(\"The book's derived data does not match its manifest (a build did not finish).\");\n }\n\n const moved = movedInputs(derived.inputs, await derivedInputs(root, options.testResultsFile));\n const changed = checked.changed.length + moved;\n\n return {\n root: checked.book.root,\n book: checked.book,\n routes: checked.book.routes,\n ...derived.snapshot,\n ...(changed > 0 ? { behind: { changed } } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,SAAS,SAAS,QAA+B;CAC/C,OAAO,IAAI,cACT,UACA,GAAG,OAAO,gFACZ;AACF;;;;;;;AAQA,eAAsB,mBACpB,MACA,SACA,UAA+B,CAAC,GACL;CAC3B,MAAM,UAAU,MAAM,UAAU,MAAM,OAAO;CAE7C,IAAI,YAAY,MAAM,MAAM,SAAS,kCAAkC;CAEvE,MAAM,UAAU,MAAM,YAAY,MAAM,gBAAgB,CAAC;CAEzD,IAAI,YAAY,MACd,MAAM,SAAS,uEAAuE;CAGxF,IAAI,QAAQ,YAAY,QAAQ,KAAK,SAAS,SAC5C,MAAM,SAAS,+EAA+E;CAGhG,MAAM,QAAQ,YAAY,QAAQ,QAAQ,MAAM,cAAc,MAAM,QAAQ,eAAe,CAAC;CAC5F,MAAM,UAAU,QAAQ,QAAQ,SAAS;CAEzC,OAAO;EACL,MAAM,QAAQ,KAAK;EACnB,MAAM,QAAQ;EACd,QAAQ,QAAQ,KAAK;EACrB,GAAG,QAAQ;EACX,GAAI,UAAU,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,CAAC;CAC/C;AACF"}
package/llms-full.txt CHANGED
@@ -615,17 +615,21 @@ edits a file you wrote either.
615
615
 
616
616
  1. Find the feature and flow the task is about.
617
617
 
618
+ Pass the whole task sentence (the commit title or the bug report), not two keywords:
619
+
618
620
  ```bash
619
- npx warlock scry --search "new arrivals"
621
+ npx warlock scry --search "new arrivals are empty for customers with no country"
620
622
  ```
621
623
 
622
624
  ```text
623
- flow catalog/new-arrivals New arrivals
624
- block web-client/home/new-arrivals catalog/new-arrivals
625
- route GET /api/products/new-arrivals
626
- file src/app/catalog/services/new-arrivals.service.ts Lists the newest products sold in the customer's country.
625
+ 21.4 flow catalog/new-arrivals New arrivals
626
+ 12.9 block web-client/home/new-arrivals catalog/new-arrivals
627
+ 11.3 route GET /api/products/new-arrivals catalog.new-arrivals
628
+ 9.8 file src/app/catalog/services/new-arrivals.service.ts Lists the newest products sold in the customer's country.
627
629
  ```
628
630
 
631
+ The number in front is the score: hits are in score order, best first, whatever their type.
632
+
629
633
  2. Read the feature's `README.md`, then the flow file. They say what the behaviour should be.
630
634
  3. Ask for the flow's book map. It lists the files behind each step, the tests that prove each
631
635
  criterion and the pages that show the flow.
@@ -642,13 +646,22 @@ edits a file you wrote either.
642
646
  npx warlock scry src/app/catalog/services/new-arrivals.service.ts # what is this file?
643
647
  npx warlock scry --impact src/app/catalog/models/product.model.ts # what breaks if I change it?
644
648
  npx warlock scry --route "POST /api/orders" # what is behind this URL?
649
+ npx warlock scry --route "GET /chat" # a page URL works too (--site <id> picks one site)
645
650
  npx warlock scry --feature catalog # the whole feature
646
651
  npx warlock scry --flow catalog/new-arrivals # one flow, step by step
647
652
  ```
648
653
 
649
- Add `--json` for machine-readable output. `--impact` lists API routes, pages, flows and features,
654
+ `scry` only reads the book the last `warlock grimoire build` left; it never rebuilds it. After you
655
+ finish editing files, run `npx warlock grimoire build`. When code, test or written files differ from
656
+ the book, the answer is the stored one and ends with
657
+ `note book is stale (12 files changed); run warlock grimoire build` (in `--json`, the `notes` list):
658
+ build, then ask again. A project with no book stops with `GR9007`. A note
659
+ `route facts look incomplete; run warlock grimoire build` means the stored routes are missing their source files
660
+ (an empty or partial route list): `--route` and `--impact` routes cannot be trusted until you build.
661
+
662
+ Add `--json` for machine-readable output; a failed call then prints `{ "type": "error", "code", "message", "fix" }` on stdout and exits 1 (the scry MCP tools return the same JSON as their error text). `--impact` lists API routes, pages, flows and features,
650
663
  including features that only borrow the file; each list has a count and stops at 20 lines, and `--all`
651
- prints every line. `--search` also reads a flow's summary, story, cases and criteria (`AC-5` works), ranks features and flows above files, and groups hits by type; a hit found by written text shows the part that matched in brackets. Read the flows it names and run their tests after
664
+ prints every line. `--search` takes the whole sentence (the commit title or the bug report, not two keywords): hits whose name or title holds the words come first, every other hit follows by score, and the list is printed in score order with the score in front. It also reads a flow's summary, story, cases and criteria (`AC-5` works); a hit found by written text shows the part that matched in brackets. Page, screen, block and file hits carry their app, and `--app <id>` keeps one app's hits. Read the flows it names and run their tests after
652
665
  your change.
653
666
 
654
667
  A file's entry is also at a fixed path: `src/app/auth/controllers/login.controller.ts` is described
@@ -658,7 +671,7 @@ in `grimoire/book/app/auth/controllers/login.controller.json`.
658
671
 
659
672
  | Command | Does |
660
673
  | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
661
- | `warlock grimoire build` | Builds or refreshes the book. `scry` and `check` do it when it is stale |
674
+ | `warlock grimoire build` | Builds or refreshes the book (and its derived data). Run it after you finish editing; `scry` only reads and never builds |
662
675
  | `warlock grimoire build --site [--out dir]` | Also writes the book as a static site (default `grimoire/book/site`); skipped when the folder is already current (`--force` writes it) |
663
676
  | `warlock grimoire build --site --product` | Writes the business export: the Product map only, no file paths, test names or per-file answers |
664
677
  | `warlock grimoire check` | Reports broken names, untested criteria, files with no owner. Exit 1 on an error; `--all` lists every warning |
@@ -672,7 +685,7 @@ that is still `proposed`; it does not fail the check.
672
685
 
673
686
  - **Exports, imports, importers, routes, middleware, pages:** read from the code. Trust them.
674
687
  - **Route middleware:** a route step also reaches the middleware files the matched route names (not the routes file's other imports). Roles that run by being present (migration, seed, command, main, layout, root) and spec-only helpers are not listed as unreached.
675
- - **Dev tab route facts:** the dev tab reads routes, events and jobs from the running dev server (nothing is booted twice), so it shows `routes: fresh` on the first open; they are read once, so rebuild with `warlock grimoire build` after changing routes.
688
+ - **Dev tab route facts:** the dev tab reads routes, events and jobs from the running dev server (nothing is booted twice), so it shows `routes: fresh` on the first open, and reads them again after a routes file changes. `scry` and the MCP tools use the routes of the last `warlock grimoire build`.
676
689
  - **Without route facts** (`routes: missing`): route, mail, notification, job and event steps are `found: null` (not checked), not resolved and not failed; `GR5008` skips mail and notification entries.
677
690
  - **Files behind a route:** every file the handler can reach through imports. It is not the exact
678
691
  call path; open the handler to see which ones it really uses.
@@ -684,8 +697,9 @@ that is still `proposed`; it does not fail the check.
684
697
 
685
698
  - No flow matches the task: the behaviour is undescribed. Describe it first with
686
699
  `write-a-feature`, then change the code.
687
- - The command says the book is missing or stale: it rebuilds on its own. If it reports problems,
688
- read them; `npx warlock grimoire check` prints the same list.
700
+ - The command says the book is missing (`GR9007`) or stale (`note book is stale …`): run
701
+ `npx warlock grimoire build`, then ask again. If the build reports problems, read them;
702
+ `npx warlock grimoire check` prints the same list.
689
703
  - The project has code but no `grimoire/` folder: use `backfill-a-grimoire`.
690
704
 
691
705
  ## See also
@@ -701,8 +715,10 @@ From `@warlock.js/grimoire` (no dependency on core or web):
701
715
  - `openGrimoire` loads everything once (it runs `parseGrimoire`, `buildBook`, `matchApps`,
702
716
  `resolveOwnership`, `scanProofs`, `readTestResults`, `buildCollectedFiles`, then `writeBook`
703
717
  and `writeCollectedFiles`), and returns a snapshot.
718
+ - `openStoredGrimoire(root, adapter)` is the read-only open behind `scry` (the stored snapshot, `behind` set when files moved; `GR9007` when never built) and `checkBook()` is `buildBook`'s change check with nothing rebuilt or written.
704
719
  - `scry` answers a query from the snapshot; `formatScryResult` prints it; `parseScryQuery` reads
705
- CLI arguments into a query.
720
+ CLI arguments into a query. `SCRY_STOP_WORDS` is the set of small words search leaves out (add to it
721
+ before the first search of a process).
706
722
  - `checkGrimoire` runs every rule; `formatCheckReport` prints the report. Each finding has a code
707
723
  from `GRIMOIRE_CODES` (also `GRIMOIRE_CODE_LIST`); `explainGrimoireCode`, `isGrimoireCode` and
708
724
  `grimoireCodeDocsUrl` (based on `GRIMOIRE_CODES_DOCS_URL`) describe it, and rules build