@mulmoclaude/core 6.0.1 → 7.0.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 (41) hide show
  1. package/dist/collection/index.cjs +1 -1
  2. package/dist/collection/index.js +1 -1
  3. package/dist/collection/registry/server/index.cjs +6 -6
  4. package/dist/collection/registry/server/index.js +6 -6
  5. package/dist/collection/server/index.cjs +1 -1
  6. package/dist/collection/server/index.js +1 -1
  7. package/dist/collection-watchers/index.cjs +2 -2
  8. package/dist/collection-watchers/index.js +2 -2
  9. package/dist/feeds/server/index.cjs +4 -4
  10. package/dist/feeds/server/index.js +4 -4
  11. package/dist/files/index.cjs +7 -31
  12. package/dist/files/index.cjs.map +1 -1
  13. package/dist/files/index.js +3 -27
  14. package/dist/files/index.js.map +1 -1
  15. package/dist/google/index.cjs +3 -3
  16. package/dist/google/index.js +3 -3
  17. package/dist/plugin-vue/index.cjs +181 -267
  18. package/dist/plugin-vue/index.cjs.map +1 -1
  19. package/dist/plugin-vue/index.js +181 -267
  20. package/dist/plugin-vue/index.js.map +1 -1
  21. package/dist/remote-host/server/index.cjs +1 -1
  22. package/dist/remote-host/server/index.js +1 -1
  23. package/dist/safe-D79sHxq1.cjs +43 -0
  24. package/dist/safe-D79sHxq1.cjs.map +1 -0
  25. package/dist/safe-DRNa8UBp.js +30 -0
  26. package/dist/safe-DRNa8UBp.js.map +1 -0
  27. package/dist/{server-CQ88wv71.cjs → server-CnCUBmSn.cjs} +5 -5
  28. package/dist/{server-CQ88wv71.cjs.map → server-CnCUBmSn.cjs.map} +1 -1
  29. package/dist/{server-Dh7pgRRg.js → server-Dp5KWarO.js} +5 -5
  30. package/dist/{server-Dh7pgRRg.js.map → server-Dp5KWarO.js.map} +1 -1
  31. package/dist/whisper/index.cjs +1 -1
  32. package/dist/whisper/index.js +1 -1
  33. package/dist/wiki/index.cjs +1 -1
  34. package/dist/wiki/index.js +1 -1
  35. package/dist/wiki/server/fs.d.ts +7 -2
  36. package/dist/wiki/server/index.cjs +106 -36
  37. package/dist/wiki/server/index.cjs.map +1 -1
  38. package/dist/wiki/server/index.js +108 -38
  39. package/dist/wiki/server/index.js.map +1 -1
  40. package/dist/wiki/server/locations.d.ts +10 -0
  41. package/package.json +9 -9
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
- const require_dist = require("../dist-734JaRYi.cjs");
4
3
  require("../errors-B9mCEVG9.cjs");
4
+ const require_dist = require("../dist-734JaRYi.cjs");
5
5
  let node_fs = require("node:fs");
6
6
  let node_path = require("node:path");
7
7
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
@@ -1,5 +1,5 @@
1
- import { i as hasStringProp, t as errorMessage } from "../dist-BmO4oSQy.js";
2
1
  import "../errors-0QwjDxsv.js";
2
+ import { i as hasStringProp, t as errorMessage } from "../dist-BmO4oSQy.js";
3
3
  import { createWriteStream, mkdirSync, renameSync, statSync, unlinkSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { randomUUID } from "node:crypto";
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dist = require("../dist-734JaRYi.cjs");
3
2
  const require_graph = require("../graph-BvVMZfDV.cjs");
4
3
  const require_slug = require("../slug-DVkuPjIv.cjs");
4
+ const require_dist = require("../dist-734JaRYi.cjs");
5
5
  // src/wiki/route.ts
6
6
  var WIKI_ROUTE_SECTION = {
7
7
  pages: "pages",
@@ -1,6 +1,6 @@
1
- import { c as isRecord, n as escapeHtml } from "../dist-BmO4oSQy.js";
2
1
  import { _ as resolveLinkTarget, a as findMissingFiles, b as parseWikiLink, c as formatLintReport, d as buildTableColumnMap, f as extractHashTags, g as matchWikiSlug, h as parseTagsCell, i as findBrokenLinksInPage, l as BULLET_LINK_PATTERN, m as parseIndexEntries, n as incomingLinks, o as findOrphanPages, p as extractSlugFromBulletHref, r as pageOutgoingSlugs, s as findTagDrift, t as buildWikiGraph, u as BULLET_WIKI_LINK_PATTERN, v as slugByIndexTitle, y as WIKI_LINK_PATTERN } from "../graph-DBbzemby.js";
3
2
  import { n as wikiPageStem, r as wikiSlugify, t as isSafeSlug } from "../slug-D24AYqCZ.js";
3
+ import { c as isRecord, n as escapeHtml } from "../dist-BmO4oSQy.js";
4
4
  // src/wiki/route.ts
5
5
  var WIKI_ROUTE_SECTION = {
6
6
  pages: "pages",
@@ -1,5 +1,10 @@
1
1
  import { Dirent, Stats } from 'node:fs';
2
- export declare function readTextSafe(absPath: string): Promise<string | null>;
3
- export declare function readTextSafeSync(absPath: string): string | null;
2
+ export declare function isWithin(rootReal: string, candidateReal: string): boolean;
3
+ export declare function realpathOrNull(absPath: string): string | null;
4
+ /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
5
+ * or is unreadable. */
6
+ export declare function readTextSafe(absPath: string, rootReal: string): Promise<string | null>;
7
+ /** Sync twin of `readTextSafe`. */
8
+ export declare function readTextSafeSync(absPath: string, rootReal: string): string | null;
4
9
  export declare function statSafeAsync(absPath: string): Promise<Stats | null>;
5
10
  export declare function readDirSafeAsync(absPath: string): Promise<Dirent[]>;
@@ -1,24 +1,63 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../../rolldown-runtime-CmQyd0Gu.cjs");
3
+ const require_wiki_paths = require("../paths.cjs");
4
+ const require_safe = require("../../safe-D79sHxq1.cjs");
3
5
  const require_graph = require("../../graph-BvVMZfDV.cjs");
4
6
  const require_slug = require("../../slug-DVkuPjIv.cjs");
5
- const require_wiki_paths = require("../paths.cjs");
6
7
  let node_fs = require("node:fs");
7
8
  let node_path = require("node:path");
8
9
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
9
10
  let node_fs_promises = require("node:fs/promises");
10
11
  let _mulmoclaude_markdown_utils_markdown_frontmatter = require("@mulmoclaude/markdown-utils/markdown/frontmatter");
11
12
  // src/wiki/server/fs.ts
12
- async function readTextSafe(absPath) {
13
+ var READ_FLAGS = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0) | (node_fs.constants.O_NONBLOCK ?? 0);
14
+ function isWithin(rootReal, candidateReal) {
15
+ const rel = node_path.default.relative(rootReal, candidateReal);
16
+ return rel !== ".." && !rel.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(rel);
17
+ }
18
+ function realpathOrNull(absPath) {
19
+ try {
20
+ return node_fs.realpathSync.native(absPath);
21
+ } catch (err) {
22
+ return require_safe.isEnoent(err) ? null : jsRealpathOrNull(absPath);
23
+ }
24
+ }
25
+ function jsRealpathOrNull(absPath) {
13
26
  try {
14
- return await (0, node_fs_promises.readFile)(absPath, "utf-8");
27
+ return (0, node_fs.realpathSync)(absPath);
15
28
  } catch {
16
29
  return null;
17
30
  }
18
31
  }
19
- function readTextSafeSync(absPath) {
32
+ function isOpenedFileInside(absPath, rootReal, opened) {
33
+ const real = realpathOrNull(absPath);
34
+ if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
35
+ const onDisk = (0, node_fs.lstatSync)(real, { bigint: true });
36
+ return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
37
+ }
38
+ /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
39
+ * or is unreadable. */
40
+ async function readTextSafe(absPath, rootReal) {
20
41
  try {
21
- return (0, node_fs.readFileSync)(absPath, "utf-8");
42
+ const handle = await (0, node_fs_promises.open)(absPath, READ_FLAGS);
43
+ try {
44
+ return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
45
+ } finally {
46
+ await handle.close();
47
+ }
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+ /** Sync twin of `readTextSafe`. */
53
+ function readTextSafeSync(absPath, rootReal) {
54
+ try {
55
+ const descriptor = (0, node_fs.openSync)(absPath, READ_FLAGS);
56
+ try {
57
+ return isOpenedFileInside(absPath, rootReal, (0, node_fs.fstatSync)(descriptor, { bigint: true })) ? (0, node_fs.readFileSync)(descriptor, "utf-8") : null;
58
+ } finally {
59
+ (0, node_fs.closeSync)(descriptor);
60
+ }
22
61
  } catch {
23
62
  return null;
24
63
  }
@@ -84,10 +123,29 @@ function parseFrontmatterTags(content) {
84
123
  if (!Array.isArray(tagsValue)) return [];
85
124
  return tagsValue.filter((item) => typeof item === "string").map(cleanTagToken).filter((token) => token.length > 0);
86
125
  }
126
+ // src/wiki/server/locations.ts
127
+ function wikiReadLocations(workspace) {
128
+ const dirs = require_wiki_paths.wikiDirs(workspace);
129
+ const workspaceReal = realpathOrNull(workspace);
130
+ const insideWorkspace = (absPath) => {
131
+ const candidateReal = workspaceReal === null ? null : realpathOrNull(node_path.default.resolve(workspaceReal, node_path.default.relative(workspace, absPath)));
132
+ return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
133
+ };
134
+ return {
135
+ pagesDir: dirs.pagesDir,
136
+ workspaceReal,
137
+ pagesReal: insideWorkspace(dirs.pagesDir),
138
+ indexReal: insideWorkspace(dirs.indexFile),
139
+ logReal: insideWorkspace(dirs.logFile)
140
+ };
141
+ }
87
142
  // src/wiki/server/engine.ts
88
143
  var MIN_FUZZY_SLUG_LEN = 6;
89
- function readFileOrEmpty(absPath) {
90
- return readTextSafeSync(absPath) ?? "";
144
+ function readFileOrEmpty(absPath, workspaceReal) {
145
+ return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
146
+ }
147
+ async function pageSlugs(locations) {
148
+ return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
91
149
  }
92
150
  /** Walk every indexed slug for an `includes`-style match. Returns the
93
151
  * single best candidate, or null when the slug is too short OR several
@@ -113,8 +171,8 @@ function pickFuzzyMatch(slug, slugs) {
113
171
  /** File matching an index.md entry whose title equals `target` — the
114
172
  * last resort for a link written as the display title rather than
115
173
  * the page's own name. */
116
- function fileByIndexTitle(indexFile, target, slugs) {
117
- const entries = require_graph.parseIndexEntries(readFileOrEmpty(indexFile));
174
+ function fileByIndexTitle(locations, target, slugs) {
175
+ const entries = require_graph.parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
118
176
  const trimmed = target.trim();
119
177
  const titleMatch = entries.find((entry) => entry.title === trimmed);
120
178
  return titleMatch ? slugs.get(titleMatch.slug) : void 0;
@@ -124,21 +182,25 @@ function fileByIndexTitle(indexFile, target, slugs) {
124
182
  * the `[[target|display]]` form; `parseWikiLink` strips the display
125
183
  * half so the lookup uses just the target. */
126
184
  async function resolvePagePath(workspace, pageName) {
127
- const { pagesDir, indexFile } = require_wiki_paths.wikiDirs(workspace);
128
- const { slugs } = await getPageIndex(pagesDir);
185
+ const locations = wikiReadLocations(workspace);
186
+ const fileName = await resolvePageFile(locations, pageName);
187
+ return fileName === null ? null : node_path.default.join(locations.pagesDir, fileName);
188
+ }
189
+ async function resolvePageFile(locations, pageName) {
190
+ const slugs = await pageSlugs(locations);
129
191
  if (slugs.size === 0) return null;
130
192
  const { target } = require_graph.parseWikiLink(pageName);
131
193
  const matched = require_graph.matchWikiSlug(target, slugs);
132
194
  const matchedFile = matched === null ? void 0 : slugs.get(matched);
133
- if (matchedFile) return node_path.default.join(pagesDir, matchedFile);
195
+ if (matchedFile) return matchedFile;
134
196
  const fuzzy = pickFuzzyMatch(require_slug.wikiSlugify(target), slugs);
135
- if (fuzzy) return node_path.default.join(pagesDir, fuzzy);
136
- const titleFile = fileByIndexTitle(indexFile, target, slugs);
137
- return titleFile ? node_path.default.join(pagesDir, titleFile) : null;
197
+ if (fuzzy) return fuzzy;
198
+ return fileByIndexTitle(locations, target, slugs) ?? null;
138
199
  }
139
200
  /** Raw `index.md` content + its parsed entries. */
140
201
  function readWikiIndex(workspace) {
141
- const content = readFileOrEmpty(require_wiki_paths.wikiDirs(workspace).indexFile);
202
+ const locations = wikiReadLocations(workspace);
203
+ const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);
142
204
  return {
143
205
  content,
144
206
  entries: require_graph.parseIndexEntries(content)
@@ -146,42 +208,50 @@ function readWikiIndex(workspace) {
146
208
  }
147
209
  /** Raw `log.md` content (empty string if absent). */
148
210
  function readWikiLog(workspace) {
149
- return readFileOrEmpty(require_wiki_paths.wikiDirs(workspace).logFile);
211
+ const locations = wikiReadLocations(workspace);
212
+ return readFileOrEmpty(locations.logReal, locations.workspaceReal);
150
213
  }
151
214
  /** Resolve + read a page. Distinguishes missing (`exists: false`) from
152
215
  * empty-but-present (`exists: true`, `content: ""`). */
153
216
  async function readWikiPage(workspace, pageName) {
154
- const filePath = await resolvePagePath(workspace, pageName);
155
- const content = filePath ? readFileOrEmpty(filePath) : "";
156
- const resolvedTitle = filePath ? node_path.default.basename(filePath, ".md") : pageName;
217
+ const locations = wikiReadLocations(workspace);
218
+ const fileName = await resolvePageFile(locations, pageName);
219
+ if (fileName === null || locations.pagesReal === null) return {
220
+ filePath: null,
221
+ content: "",
222
+ exists: false,
223
+ resolvedTitle: pageName
224
+ };
225
+ const content = readFileOrEmpty(node_path.default.join(locations.pagesReal, fileName), locations.workspaceReal);
157
226
  return {
158
- filePath,
227
+ filePath: node_path.default.join(locations.pagesDir, fileName),
159
228
  content,
160
- exists: Boolean(filePath),
161
- resolvedTitle
229
+ exists: true,
230
+ resolvedTitle: node_path.default.basename(fileName, ".md")
162
231
  };
163
232
  }
164
233
  /** Page body, or "" when the file vanished between indexing and reading. */
165
- async function readPageBody(pagesDir, fileName) {
166
- return await readTextSafe(node_path.default.join(pagesDir, fileName)) ?? "";
234
+ async function readPageBody(locations, fileName) {
235
+ const { pagesReal, workspaceReal } = locations;
236
+ return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(node_path.default.join(pagesReal, fileName), workspaceReal) ?? "";
167
237
  }
168
238
  /** Read every page + the index and build the page→page link graph.
169
239
  * No cache: the graph is requested explicitly and a content edit does
170
240
  * not advance the pagesDir mtime the page index caches on. */
171
241
  async function loadWikiGraph(workspace) {
172
- const { pagesDir, indexFile } = require_wiki_paths.wikiDirs(workspace);
173
- const { slugs } = await getPageIndex(pagesDir);
242
+ const locations = wikiReadLocations(workspace);
243
+ const slugs = await pageSlugs(locations);
174
244
  const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({
175
245
  slug,
176
- content: await readPageBody(pagesDir, fileName)
246
+ content: await readPageBody(locations, fileName)
177
247
  })));
178
- const indexEntries = require_graph.parseIndexEntries(readFileOrEmpty(indexFile));
248
+ const indexEntries = require_graph.parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
179
249
  return require_graph.buildWikiGraph(pages, indexEntries);
180
250
  }
181
- async function readPageBodies(pagesDir, fileNames) {
251
+ async function readPageBodies(locations, fileNames) {
182
252
  return Promise.all(fileNames.map(async (fileName) => ({
183
253
  fileName,
184
- content: await readPageBody(pagesDir, fileName)
254
+ content: await readPageBody(locations, fileName)
185
255
  })));
186
256
  }
187
257
  /** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so
@@ -196,13 +266,13 @@ function frontmatterTagIndex(bodies) {
196
266
  }
197
267
  /** Run every lint rule over the on-disk wiki, returning issue strings. */
198
268
  async function collectLintIssues(workspace) {
199
- const { pagesDir, indexFile } = require_wiki_paths.wikiDirs(workspace);
200
- const { slugs } = await getPageIndex(pagesDir);
201
- if (slugs.size === 0) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
202
- const pageEntries = require_graph.parseIndexEntries(readFileOrEmpty(indexFile));
269
+ const locations = wikiReadLocations(workspace);
270
+ const slugs = await pageSlugs(locations);
271
+ if (slugs.size === 0 || locations.pagesReal === null) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
272
+ const pageEntries = require_graph.parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
203
273
  const fileSlugs = new Set(slugs.keys());
204
274
  const slugByTitle = require_graph.slugByIndexTitle(pageEntries);
205
- const bodies = await readPageBodies(pagesDir, [...slugs.values()]);
275
+ const bodies = await readPageBodies(locations, [...slugs.values()]);
206
276
  return [
207
277
  ...require_graph.findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),
208
278
  ...require_graph.findMissingFiles(pageEntries, fileSlugs),
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readFile","readFileSync","stat","readdir","parseFrontmatter","parseIndexEntries","wikiDirs","parseWikiLink","matchWikiSlug","path","wikiSlugify","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n\nexport async function readTextSafe(absPath: string): Promise<string | null> {\n try {\n return await readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function readTextSafeSync(absPath: string): string | null {\n try {\n return readFileSync(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { wikiDirs } from \"./paths.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string): string {\n return readTextSafeSync(absPath) ?? \"\";\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(indexFile: string, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(indexFile));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return path.join(pagesDir, matchedFile);\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return path.join(pagesDir, fuzzy);\n\n const titleFile = fileByIndexTitle(indexFile, target, slugs);\n return titleFile ? path.join(pagesDir, titleFile) : null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const content = readFileOrEmpty(wikiDirs(workspace).indexFile);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n return readFileOrEmpty(wikiDirs(workspace).logFile);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const filePath = await resolvePagePath(workspace, pageName);\n const content = filePath ? readFileOrEmpty(filePath) : \"\";\n const resolvedTitle = filePath ? path.basename(filePath, \".md\") : pageName;\n return { filePath, content, exists: Boolean(filePath), resolvedTitle };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(pagesDir: string, fileName: string): Promise<string> {\n return (await readTextSafe(path.join(pagesDir, fileName))) ?? \"\";\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(pagesDir, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(pagesDir: string, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(pagesDir, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const { pagesDir, indexFile } = wikiDirs(workspace);\n const { slugs } = await getPageIndex(pagesDir);\n if (slugs.size === 0) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(pagesDir, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;;;AAUA,eAAsB,aAAa,SAAyC;CAC1E,IAAI;EACF,OAAO,OAAA,GAAMA,iBAAAA,SAAAA,CAAS,SAAS,OAAO;CACxC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,iBAAiB,SAAgC;CAC/D,IAAI;EACF,QAAA,GAAOC,QAAAA,aAAAA,CAAa,SAAS,OAAO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,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["constants","path","realpathSync","isEnoent","lstatSync","open","openSync","fstatSync","readFileSync","stat","readdir","parseFrontmatter","wikiDirs","path","parseIndexEntries","path","parseWikiLink","matchWikiSlug","wikiSlugify","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { BigIntStats, Dirent, Stats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../../files/safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a workspace at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithin(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(absPath: string, rootReal: string, opened: BigIntStats): boolean {\n const real = realpathOrNull(absPath);\n if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,\n * or is unreadable. */\nexport async function readTextSafe(absPath: string, rootReal: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextSafe`. */\nexport function readTextSafeSync(absPath: string, rootReal: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithin, realpathOrNull } from \"./fs.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextSafeSync(absPath, workspaceReal) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextSafe(path.join(pagesReal, fileName), workspaceReal)) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;;;;AAcA,IAAM,aAAaA,QAAAA,UAAU,YAAYA,QAAAA,UAAU,cAAc,MAAMA,QAAAA,UAAU,cAAc;AAG/F,SAAgB,SAAS,UAAkB,eAAgC;CACzE,MAAM,MAAMC,UAAAA,QAAK,SAAS,UAAU,aAAa;CACjD,OAAO,QAAQ,QAAQ,CAAC,IAAI,WAAW,KAAKA,UAAAA,QAAK,KAAK,KAAK,CAACA,UAAAA,QAAK,WAAW,GAAG;AACjF;AAIA,SAAgB,eAAe,SAAgC;CAC7D,IAAI;EACF,OAAOC,QAAAA,aAAa,OAAO,OAAO;CACpC,SAAS,KAAK;EACZ,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AAQ;CAAE,EAAE,CAAC;AACxH;;;;AAKA,SAAgB,oBAAoB,QAAoD;CACtF,MAAM,6BAAa,IAAI,IAAsB;CAC7C,OAAO,SAAS,EAAE,UAAU,cAAc;EACxC,WAAW,IAAI,SAAS,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY,GAAG,qBAAqB,OAAO,CAAC;CAC5F,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,YAAY,kBAAkB,SAAS;CAC7C,MAAM,QAAQ,MAAM,UAAU,SAAS;CACvC,IAAI,MAAM,SAAS,KAAK,UAAU,cAAc,MAC9C,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAcL,cAAAA,kBAAkB,gBAAgB,UAAU,WAAW,UAAU,aAAa,CAAC;CACnG,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,cAAcM,cAAAA,iBAAiB,WAAW;CAChD,MAAM,SAAS,MAAM,eAAe,WAAW,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;CAClE,OAAO;EACL,GAAGC,cAAAA,gBAAgB,WAAW,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC;EAC7E,GAAGC,cAAAA,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAcC,cAAAA,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
@@ -1,21 +1,60 @@
1
+ import { wikiDirs, wikiSlugFromAbsPath } from "../paths.js";
2
+ import { t as isEnoent } from "../../safe-DRNa8UBp.js";
1
3
  import { a as findMissingFiles, b as parseWikiLink, g as matchWikiSlug, i as findBrokenLinksInPage, m as parseIndexEntries, o as findOrphanPages, s as findTagDrift, t as buildWikiGraph, v as slugByIndexTitle } from "../../graph-DBbzemby.js";
2
4
  import { r as wikiSlugify } from "../../slug-D24AYqCZ.js";
3
- import { wikiDirs, wikiSlugFromAbsPath } from "../paths.js";
4
- import { readFileSync } from "node:fs";
5
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
5
6
  import path from "node:path";
6
- import { readFile, readdir, stat } from "node:fs/promises";
7
+ import { open, readdir, stat } from "node:fs/promises";
7
8
  import { parseFrontmatter } from "@mulmoclaude/markdown-utils/markdown/frontmatter";
8
9
  // src/wiki/server/fs.ts
9
- async function readTextSafe(absPath) {
10
+ var READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
11
+ function isWithin(rootReal, candidateReal) {
12
+ const rel = path.relative(rootReal, candidateReal);
13
+ return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
14
+ }
15
+ function realpathOrNull(absPath) {
16
+ try {
17
+ return realpathSync.native(absPath);
18
+ } catch (err) {
19
+ return isEnoent(err) ? null : jsRealpathOrNull(absPath);
20
+ }
21
+ }
22
+ function jsRealpathOrNull(absPath) {
10
23
  try {
11
- return await readFile(absPath, "utf-8");
24
+ return realpathSync(absPath);
12
25
  } catch {
13
26
  return null;
14
27
  }
15
28
  }
16
- function readTextSafeSync(absPath) {
29
+ function isOpenedFileInside(absPath, rootReal, opened) {
30
+ const real = realpathOrNull(absPath);
31
+ if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
32
+ const onDisk = lstatSync(real, { bigint: true });
33
+ return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
34
+ }
35
+ /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
36
+ * or is unreadable. */
37
+ async function readTextSafe(absPath, rootReal) {
17
38
  try {
18
- return readFileSync(absPath, "utf-8");
39
+ const handle = await open(absPath, READ_FLAGS);
40
+ try {
41
+ return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
42
+ } finally {
43
+ await handle.close();
44
+ }
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ /** Sync twin of `readTextSafe`. */
50
+ function readTextSafeSync(absPath, rootReal) {
51
+ try {
52
+ const descriptor = openSync(absPath, READ_FLAGS);
53
+ try {
54
+ return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, "utf-8") : null;
55
+ } finally {
56
+ closeSync(descriptor);
57
+ }
19
58
  } catch {
20
59
  return null;
21
60
  }
@@ -81,10 +120,29 @@ function parseFrontmatterTags(content) {
81
120
  if (!Array.isArray(tagsValue)) return [];
82
121
  return tagsValue.filter((item) => typeof item === "string").map(cleanTagToken).filter((token) => token.length > 0);
83
122
  }
123
+ // src/wiki/server/locations.ts
124
+ function wikiReadLocations(workspace) {
125
+ const dirs = wikiDirs(workspace);
126
+ const workspaceReal = realpathOrNull(workspace);
127
+ const insideWorkspace = (absPath) => {
128
+ const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));
129
+ return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
130
+ };
131
+ return {
132
+ pagesDir: dirs.pagesDir,
133
+ workspaceReal,
134
+ pagesReal: insideWorkspace(dirs.pagesDir),
135
+ indexReal: insideWorkspace(dirs.indexFile),
136
+ logReal: insideWorkspace(dirs.logFile)
137
+ };
138
+ }
84
139
  // src/wiki/server/engine.ts
85
140
  var MIN_FUZZY_SLUG_LEN = 6;
86
- function readFileOrEmpty(absPath) {
87
- return readTextSafeSync(absPath) ?? "";
141
+ function readFileOrEmpty(absPath, workspaceReal) {
142
+ return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
143
+ }
144
+ async function pageSlugs(locations) {
145
+ return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
88
146
  }
89
147
  /** Walk every indexed slug for an `includes`-style match. Returns the
90
148
  * single best candidate, or null when the slug is too short OR several
@@ -110,8 +168,8 @@ function pickFuzzyMatch(slug, slugs) {
110
168
  /** File matching an index.md entry whose title equals `target` — the
111
169
  * last resort for a link written as the display title rather than
112
170
  * the page's own name. */
113
- function fileByIndexTitle(indexFile, target, slugs) {
114
- const entries = parseIndexEntries(readFileOrEmpty(indexFile));
171
+ function fileByIndexTitle(locations, target, slugs) {
172
+ const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
115
173
  const trimmed = target.trim();
116
174
  const titleMatch = entries.find((entry) => entry.title === trimmed);
117
175
  return titleMatch ? slugs.get(titleMatch.slug) : void 0;
@@ -121,21 +179,25 @@ function fileByIndexTitle(indexFile, target, slugs) {
121
179
  * the `[[target|display]]` form; `parseWikiLink` strips the display
122
180
  * half so the lookup uses just the target. */
123
181
  async function resolvePagePath(workspace, pageName) {
124
- const { pagesDir, indexFile } = wikiDirs(workspace);
125
- const { slugs } = await getPageIndex(pagesDir);
182
+ const locations = wikiReadLocations(workspace);
183
+ const fileName = await resolvePageFile(locations, pageName);
184
+ return fileName === null ? null : path.join(locations.pagesDir, fileName);
185
+ }
186
+ async function resolvePageFile(locations, pageName) {
187
+ const slugs = await pageSlugs(locations);
126
188
  if (slugs.size === 0) return null;
127
189
  const { target } = parseWikiLink(pageName);
128
190
  const matched = matchWikiSlug(target, slugs);
129
191
  const matchedFile = matched === null ? void 0 : slugs.get(matched);
130
- if (matchedFile) return path.join(pagesDir, matchedFile);
192
+ if (matchedFile) return matchedFile;
131
193
  const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);
132
- if (fuzzy) return path.join(pagesDir, fuzzy);
133
- const titleFile = fileByIndexTitle(indexFile, target, slugs);
134
- return titleFile ? path.join(pagesDir, titleFile) : null;
194
+ if (fuzzy) return fuzzy;
195
+ return fileByIndexTitle(locations, target, slugs) ?? null;
135
196
  }
136
197
  /** Raw `index.md` content + its parsed entries. */
137
198
  function readWikiIndex(workspace) {
138
- const content = readFileOrEmpty(wikiDirs(workspace).indexFile);
199
+ const locations = wikiReadLocations(workspace);
200
+ const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);
139
201
  return {
140
202
  content,
141
203
  entries: parseIndexEntries(content)
@@ -143,42 +205,50 @@ function readWikiIndex(workspace) {
143
205
  }
144
206
  /** Raw `log.md` content (empty string if absent). */
145
207
  function readWikiLog(workspace) {
146
- return readFileOrEmpty(wikiDirs(workspace).logFile);
208
+ const locations = wikiReadLocations(workspace);
209
+ return readFileOrEmpty(locations.logReal, locations.workspaceReal);
147
210
  }
148
211
  /** Resolve + read a page. Distinguishes missing (`exists: false`) from
149
212
  * empty-but-present (`exists: true`, `content: ""`). */
150
213
  async function readWikiPage(workspace, pageName) {
151
- const filePath = await resolvePagePath(workspace, pageName);
152
- const content = filePath ? readFileOrEmpty(filePath) : "";
153
- const resolvedTitle = filePath ? path.basename(filePath, ".md") : pageName;
214
+ const locations = wikiReadLocations(workspace);
215
+ const fileName = await resolvePageFile(locations, pageName);
216
+ if (fileName === null || locations.pagesReal === null) return {
217
+ filePath: null,
218
+ content: "",
219
+ exists: false,
220
+ resolvedTitle: pageName
221
+ };
222
+ const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);
154
223
  return {
155
- filePath,
224
+ filePath: path.join(locations.pagesDir, fileName),
156
225
  content,
157
- exists: Boolean(filePath),
158
- resolvedTitle
226
+ exists: true,
227
+ resolvedTitle: path.basename(fileName, ".md")
159
228
  };
160
229
  }
161
230
  /** Page body, or "" when the file vanished between indexing and reading. */
162
- async function readPageBody(pagesDir, fileName) {
163
- return await readTextSafe(path.join(pagesDir, fileName)) ?? "";
231
+ async function readPageBody(locations, fileName) {
232
+ const { pagesReal, workspaceReal } = locations;
233
+ return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(path.join(pagesReal, fileName), workspaceReal) ?? "";
164
234
  }
165
235
  /** Read every page + the index and build the page→page link graph.
166
236
  * No cache: the graph is requested explicitly and a content edit does
167
237
  * not advance the pagesDir mtime the page index caches on. */
168
238
  async function loadWikiGraph(workspace) {
169
- const { pagesDir, indexFile } = wikiDirs(workspace);
170
- const { slugs } = await getPageIndex(pagesDir);
239
+ const locations = wikiReadLocations(workspace);
240
+ const slugs = await pageSlugs(locations);
171
241
  const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({
172
242
  slug,
173
- content: await readPageBody(pagesDir, fileName)
243
+ content: await readPageBody(locations, fileName)
174
244
  })));
175
- const indexEntries = parseIndexEntries(readFileOrEmpty(indexFile));
245
+ const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
176
246
  return buildWikiGraph(pages, indexEntries);
177
247
  }
178
- async function readPageBodies(pagesDir, fileNames) {
248
+ async function readPageBodies(locations, fileNames) {
179
249
  return Promise.all(fileNames.map(async (fileName) => ({
180
250
  fileName,
181
- content: await readPageBody(pagesDir, fileName)
251
+ content: await readPageBody(locations, fileName)
182
252
  })));
183
253
  }
184
254
  /** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so
@@ -193,13 +263,13 @@ function frontmatterTagIndex(bodies) {
193
263
  }
194
264
  /** Run every lint rule over the on-disk wiki, returning issue strings. */
195
265
  async function collectLintIssues(workspace) {
196
- const { pagesDir, indexFile } = wikiDirs(workspace);
197
- const { slugs } = await getPageIndex(pagesDir);
198
- if (slugs.size === 0) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
199
- const pageEntries = parseIndexEntries(readFileOrEmpty(indexFile));
266
+ const locations = wikiReadLocations(workspace);
267
+ const slugs = await pageSlugs(locations);
268
+ if (slugs.size === 0 || locations.pagesReal === null) return ["- Wiki `pages/` directory does not exist yet. Start ingesting sources."];
269
+ const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));
200
270
  const fileSlugs = new Set(slugs.keys());
201
271
  const slugByTitle = slugByIndexTitle(pageEntries);
202
- const bodies = await readPageBodies(pagesDir, [...slugs.values()]);
272
+ const bodies = await readPageBodies(locations, [...slugs.values()]);
203
273
  return [
204
274
  ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),
205
275
  ...findMissingFiles(pageEntries, fileSlugs),