@gobing-ai/knowledge-kit 0.1.15 → 0.1.16

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 (103) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +1603 -1
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +58 -52
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +1 -1
  7. package/plugins/generations/daily-article-gen/dist/index.js +1 -1
  8. package/plugins/generations/dailynews-gen/dist/index.js +1 -1
  9. package/plugins/generations/episode-plan-gen/dist/index.js +1 -1
  10. package/plugins/generations/gemini-tts/dist/index.js +1 -1
  11. package/plugins/generations/image-gen/README.md +31 -10
  12. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  13. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  14. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/dist/index.js +1 -1
  31. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  32. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  33. package/plugins/generations/news-report-gen/dist/index.js +1 -1
  34. package/plugins/generations/voice-gen/dist/index.js +1 -1
  35. package/plugins/generations/voxcpm-tts/dist/index.js +1 -1
  36. package/plugins/ingestions/aihot-ingest/dist/index.js +1 -1
  37. package/plugins/ingestions/horizon-ingest/dist/index.js +1 -1
  38. package/plugins/ingestions/last30days-ingest/dist/index.js +1 -1
  39. package/plugins/ingestions/web-search/dist/index.js +1 -1
  40. package/plugins/kk/plugin.json +1 -1
  41. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  42. package/plugins/kk/publish-presets/daily-ai-voice.json +11 -3
  43. package/plugins/kk/scripts/cover-compositor.ts +152 -0
  44. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  45. package/plugins/kk/scripts/daily-scheduled-run.ts +188 -3
  46. package/plugins/kk/scripts/daily-stages.ts +134 -26
  47. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  48. package/plugins/kk/scripts/daily-triage.ts +74 -0
  49. package/plugins/kk/scripts/kk-workflow-stages.ts +31 -2
  50. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  51. package/plugins/kk/skills/news-editorial/SKILL.md +3 -3
  52. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +2 -1
  53. package/plugins/kk/skills/publish/SKILL.md +1 -1
  54. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  55. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  56. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +3 -3
  57. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  58. package/plugins/publishings/bilibili-pub/dist/index.js +1 -1
  59. package/plugins/publishings/cnblogs-pub/dist/index.js +1 -1
  60. package/plugins/publishings/csdn-pub/dist/index.js +1 -1
  61. package/plugins/publishings/csdn-pub/dist/profile-check.js +1 -1
  62. package/plugins/publishings/emdash-pub/dist/index.js +1 -1
  63. package/plugins/publishings/infoq-pub/dist/index.js +1 -1
  64. package/plugins/publishings/infoq-pub/dist/profile-check.js +1 -1
  65. package/plugins/publishings/jike-pub/dist/index.js +1 -1
  66. package/plugins/publishings/jike-pub/dist/profile-check.js +1 -1
  67. package/plugins/publishings/juejin-pub/dist/index.js +1 -1
  68. package/plugins/publishings/juejin-pub/dist/profile-check.js +1 -1
  69. package/plugins/publishings/linkedin-pub/dist/index.js +1 -1
  70. package/plugins/publishings/linkedin-pub/dist/profile-check.js +1 -1
  71. package/plugins/publishings/medium-pub/dist/index.js +1 -1
  72. package/plugins/publishings/podcast-pub/dist/index.js +1 -1
  73. package/plugins/publishings/qiita-pub/dist/index.js +1 -1
  74. package/plugins/publishings/shipinhao-pub/dist/index.js +222 -50
  75. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +48 -1
  76. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  77. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  78. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  79. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  80. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  81. package/plugins/publishings/sspai-pub/dist/index.js +1 -1
  82. package/plugins/publishings/substack-pub/dist/index.js +1 -1
  83. package/plugins/publishings/substack-pub/dist/profile-check.js +1 -1
  84. package/plugins/publishings/surfdash-pub/dist/index.js +235 -12
  85. package/plugins/publishings/surfdash-pub/src/index.ts +127 -6
  86. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  87. package/plugins/publishings/threads-pub/dist/index.js +1 -1
  88. package/plugins/publishings/wechatmp-pub/dist/index.js +10 -7
  89. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +1 -1
  90. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  91. package/plugins/publishings/wechatmp-pub/src/flow.ts +3 -4
  92. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  93. package/plugins/publishings/weibo-pub/dist/index.js +1 -1
  94. package/plugins/publishings/weibo-pub/dist/profile-check.js +1 -1
  95. package/plugins/publishings/x-pub/dist/index.js +1 -1
  96. package/plugins/publishings/x-pub/dist/profile-check.js +1 -1
  97. package/plugins/publishings/xhs-pub/dist/index.js +557 -31
  98. package/plugins/publishings/xhs-pub/dist/profile-check.js +20 -1
  99. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  100. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  101. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  102. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +1 -1
  103. package/plugins/publishings/zenn-pub/dist/index.js +1 -1
package/dist/index.js CHANGED
@@ -31832,6 +31832,40 @@ var init_path = __esm(() => {
31832
31832
  SEP = globalThis.process?.platform === "win32" ? "\\" : "/";
31833
31833
  });
31834
31834
 
31835
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/fs.js
31836
+ async function walkDir(path, fs = createNodeFileSystem(), exclude) {
31837
+ const startReal = fs.realPath?.(path) ?? path;
31838
+ const visited = new Set([startReal]);
31839
+ const result = [];
31840
+ await walkDirInto(path, fs, exclude, startReal, visited, result);
31841
+ return result;
31842
+ }
31843
+ async function walkDirInto(path, fs, exclude, startReal, visited, result) {
31844
+ const entries = (await fs.readDir(path)).sort();
31845
+ for (const entry of entries) {
31846
+ if (exclude?.has(entry))
31847
+ continue;
31848
+ const fullPath = joinPath(path, entry);
31849
+ const entryStat = await fs.stat(fullPath);
31850
+ if (entryStat?.isDirectory()) {
31851
+ const entryReal = fs.realPath?.(fullPath) ?? fullPath;
31852
+ if (visited.has(entryReal))
31853
+ continue;
31854
+ if (fs.realPath !== undefined && entryReal !== startReal && !entryReal.startsWith(`${startReal}/`) && !entryReal.startsWith(`${startReal}\\`)) {
31855
+ continue;
31856
+ }
31857
+ visited.add(entryReal);
31858
+ await walkDirInto(fullPath, fs, exclude, startReal, visited, result);
31859
+ } else if (entryStat?.isFile()) {
31860
+ result.push(fullPath);
31861
+ }
31862
+ }
31863
+ }
31864
+ var init_fs = __esm(() => {
31865
+ init_file_system_node();
31866
+ init_path();
31867
+ });
31868
+
31835
31869
  // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/schema-validation.js
31836
31870
  var REMOTE_SCHEMA_MAX_BYTES;
31837
31871
  var init_schema_validation = __esm(() => {
@@ -31845,6 +31879,7 @@ var init_types = () => {};
31845
31879
  // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/index.js
31846
31880
  var init_dist3 = __esm(() => {
31847
31881
  init_file_system_node();
31882
+ init_fs();
31848
31883
  init_process_executor();
31849
31884
  init_runtime_node_bun();
31850
31885
  init_process_executor();
@@ -37172,6 +37207,9 @@ var init_dist5 = __esm(() => {
37172
37207
  function withoutFinalLineEnding(message) {
37173
37208
  return message.replace(/\r?\n$/, "");
37174
37209
  }
37210
+ function toJson(value) {
37211
+ return JSON.stringify(value, null, 2);
37212
+ }
37175
37213
  var consoleOutput;
37176
37214
  var init_output2 = __esm(() => {
37177
37215
  init_dist();
@@ -42444,7 +42482,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
42444
42482
  shortVideo: Object.freeze({
42445
42483
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
42446
42484
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
42447
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
42485
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
42448
42486
  })
42449
42487
  })
42450
42488
  });
@@ -54090,6 +54128,10 @@ async function sendPublishMatrix(args, deps = {}) {
54090
54128
  }
54091
54129
  }
54092
54130
  try {
54131
+ if (retry && !await fs.exists(join24(workDir, "4-publish", `plan.${parsedWindow.data}.json`))) {
54132
+ echo(`publish-matrix-send: no plan for window '${parsedWindow.data}' \u2014 nothing was planned, nothing to resend`);
54133
+ return 0;
54134
+ }
54093
54135
  const plan = await readPlan(fs, workDir, parsedWindow.data);
54094
54136
  const publishDir = join24(workDir, "4-publish");
54095
54137
  const receiptsDir = join24(publishDir, "receipts");
@@ -55614,6 +55656,1565 @@ function registerStoreCommand(program) {
55614
55656
  store.command("release").description("Drop a run\u2019s selected rows so its items re-enter the pool; prints {released}").requiredOption("--run <id>", "Run id whose selected rows are dropped").option("--topic <topic>", "Narrow the release to one topic (default: every topic the run selected for)").option("--db <path>", "Store database path (default: kk config store.db_path, else .works/kk.db)").action(releaseAction);
55615
55657
  }
55616
55658
 
55659
+ // src/commands/wiki.ts
55660
+ init_commander();
55661
+ init_output2();
55662
+
55663
+ // src/wiki/ingest.ts
55664
+ import { extname, isAbsolute as isAbsolute13, join as join33 } from "path";
55665
+
55666
+ // ../../packages/kk-wiki/src/compile.ts
55667
+ function oneLineSummary(body) {
55668
+ for (const line of body.split(`
55669
+ `)) {
55670
+ const text = line.trim();
55671
+ if (text === "" || text.startsWith("#") || text.startsWith("---"))
55672
+ continue;
55673
+ return text.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2").slice(0, 120);
55674
+ }
55675
+ return "No summary yet.";
55676
+ }
55677
+ function groupByType(pages) {
55678
+ const groups = new Map;
55679
+ for (const page of [...pages].sort((a, b) => a.frontmatter.type.localeCompare(b.frontmatter.type) || a.slug.localeCompare(b.slug))) {
55680
+ const list = groups.get(page.frontmatter.type) ?? [];
55681
+ list.push(page);
55682
+ groups.set(page.frontmatter.type, list);
55683
+ }
55684
+ return groups;
55685
+ }
55686
+ function compileIndex(pages, options) {
55687
+ const groups = groupByType(pages);
55688
+ const indexLines = ["# Vault index", "", `Compiled ${options.date}. Do not edit by hand; run \`kk wiki compile\`.`];
55689
+ for (const [type, entries] of groups) {
55690
+ indexLines.push("", `## ${type}`, "");
55691
+ for (const page of entries) {
55692
+ indexLines.push(`- [[${page.slug}|${page.frontmatter.title}]] \u2014 ${oneLineSummary(page.body)}`);
55693
+ }
55694
+ }
55695
+ const mapLines = ["# MAP", "", "Routing table: page type and tags.", ""];
55696
+ for (const [type, entries] of groups) {
55697
+ mapLines.push(`## ${type}`, "");
55698
+ for (const page of entries) {
55699
+ const tags = page.frontmatter.tags.length > 0 ? page.frontmatter.tags.join(", ") : "\u2014";
55700
+ mapLines.push(`- ${page.path} \u2192 ${page.slug} (tags: ${tags})`);
55701
+ }
55702
+ }
55703
+ return { index: `${indexLines.join(`
55704
+ `)}
55705
+ `, map: `${mapLines.join(`
55706
+ `)}
55707
+ ` };
55708
+ }
55709
+ function needsWrite(current, rendered) {
55710
+ return current !== rendered;
55711
+ }
55712
+ // ../../packages/kk-wiki/src/page.ts
55713
+ init_zod();
55714
+ var PageTypeSchema = _enum2(["concept", "entity", "source", "index"]);
55715
+ var PageFrontmatterSchema = object2({
55716
+ title: string2().min(1),
55717
+ type: PageTypeSchema,
55718
+ tags: array(string2()).default([]),
55719
+ sources: array(string2()).default([]),
55720
+ updated_at: string2().min(1),
55721
+ user_edited: boolean2().optional(),
55722
+ redirect_to: string2().min(1).optional()
55723
+ });
55724
+
55725
+ class FrontmatterError extends Error {
55726
+ path;
55727
+ issues;
55728
+ constructor(path, issues) {
55729
+ super(`invalid frontmatter in ${path}: ${issues.join("; ")}`);
55730
+ this.path = path;
55731
+ this.issues = issues;
55732
+ this.name = "FrontmatterError";
55733
+ }
55734
+ }
55735
+ var FENCE = "---";
55736
+ function parseScalar(raw) {
55737
+ const trimmed = raw.trim();
55738
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
55739
+ return trimmed.slice(1, -1);
55740
+ }
55741
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) {
55742
+ return trimmed.slice(1, -1);
55743
+ }
55744
+ if (trimmed === "true")
55745
+ return true;
55746
+ if (trimmed === "false")
55747
+ return false;
55748
+ return trimmed;
55749
+ }
55750
+ function parseFrontmatter(raw) {
55751
+ const errors = [];
55752
+ const text = raw.replace(/^\uFEFF/, "");
55753
+ const lines = text.split(`
55754
+ `);
55755
+ if (lines[0]?.trim() !== FENCE) {
55756
+ return { data: {}, body: text, errors: ["missing-frontmatter"], bodyStartLine: 1 };
55757
+ }
55758
+ const close = lines.findIndex((line, index) => index > 0 && line.trim() === FENCE);
55759
+ if (close < 0) {
55760
+ return { data: {}, body: text, errors: ["unterminated-frontmatter"], bodyStartLine: 1 };
55761
+ }
55762
+ const data = {};
55763
+ let openArrayKey = null;
55764
+ for (const line of lines.slice(1, close)) {
55765
+ if (line.trim() === "")
55766
+ continue;
55767
+ const item = /^\s+-\s+(.*)$/.exec(line);
55768
+ if (item !== null) {
55769
+ if (openArrayKey === null) {
55770
+ errors.push(`array item without a key: ${line.trim()}`);
55771
+ continue;
55772
+ }
55773
+ const list = data[openArrayKey];
55774
+ if (Array.isArray(list))
55775
+ list.push(String(parseScalar(item[1] ?? "")));
55776
+ continue;
55777
+ }
55778
+ const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line);
55779
+ if (pair === null) {
55780
+ errors.push(`unsupported frontmatter line (nested or malformed): ${line.trim()}`);
55781
+ continue;
55782
+ }
55783
+ const key = pair[1] ?? "";
55784
+ const value = (pair[2] ?? "").trim();
55785
+ openArrayKey = value === "" ? key : null;
55786
+ if (value === "" || value === "[]") {
55787
+ data[key] = [];
55788
+ continue;
55789
+ }
55790
+ data[key] = parseScalar(value);
55791
+ }
55792
+ const rest = lines.slice(close + 1);
55793
+ const leadingBlank = rest[0] === "" ? 1 : 0;
55794
+ return {
55795
+ data,
55796
+ body: rest.join(`
55797
+ `).replace(/^\n/, ""),
55798
+ errors,
55799
+ bodyStartLine: close + 2 + leadingBlank
55800
+ };
55801
+ }
55802
+ function parsePage(text, path) {
55803
+ const parsed = parseFrontmatter(text);
55804
+ const result = PageFrontmatterSchema.safeParse(parsed.data);
55805
+ if (!result.success) {
55806
+ const issues = parsed.errors.concat(result.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`));
55807
+ throw new FrontmatterError(path, issues);
55808
+ }
55809
+ return { path, frontmatter: result.data, body: parsed.body };
55810
+ }
55811
+ function renderValue(value) {
55812
+ if (typeof value === "boolean")
55813
+ return value ? "true" : "false";
55814
+ if (value === "" || /[:#\n]/.test(value) || value.trim() !== value)
55815
+ return `"${value.replace(/"/g, "\\\"")}"`;
55816
+ return value;
55817
+ }
55818
+ function renderPage(page) {
55819
+ const fm = page.frontmatter;
55820
+ const lines = [FENCE, `title: ${renderValue(fm.title)}`, `type: ${fm.type}`];
55821
+ if (fm.tags.length === 0) {
55822
+ lines.push("tags: []");
55823
+ } else {
55824
+ lines.push("tags:", ...fm.tags.map((tag) => ` - ${renderValue(tag)}`));
55825
+ }
55826
+ if (fm.sources.length === 0) {
55827
+ lines.push("sources: []");
55828
+ } else {
55829
+ lines.push("sources:", ...fm.sources.map((source) => ` - ${renderValue(source)}`));
55830
+ }
55831
+ lines.push(`updated_at: ${renderValue(fm.updated_at)}`);
55832
+ if (fm.user_edited === true)
55833
+ lines.push("user_edited: true");
55834
+ if (fm.redirect_to !== undefined)
55835
+ lines.push(`redirect_to: ${renderValue(fm.redirect_to)}`);
55836
+ lines.push(FENCE, "");
55837
+ return `${lines.join(`
55838
+ `)}
55839
+ ${page.body.replace(/\s+$/, "")}
55840
+ `;
55841
+ }
55842
+ function resolveSlug(title) {
55843
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
55844
+ }
55845
+
55846
+ // ../../packages/kk-wiki/src/context.ts
55847
+ function packContext(index, topic, options = {}) {
55848
+ const slug = resolveSlug(topic);
55849
+ const topicPage = index.bySlug.get(slug) ?? index.pages.find((page) => page.path === topic);
55850
+ if (topicPage === undefined)
55851
+ return { markdown: "", pages: [] };
55852
+ const included = [topicPage];
55853
+ const neighbours = index.pages.filter((page) => page !== topicPage && (page.links.some((link) => resolveSlug(link.target) === topicPage.slug) || topicPage.links.some((link) => resolveSlug(link.target) === page.slug)));
55854
+ for (const page of neighbours.slice(0, Math.max(0, options.depth ?? 1) === 0 ? 0 : neighbours.length)) {
55855
+ included.push(page);
55856
+ }
55857
+ const markdown = included.map((page) => `## ${page.path}
55858
+
55859
+ ${page.body.trim()}
55860
+ `).join(`
55861
+ `).trimEnd();
55862
+ return { markdown: `${markdown}
55863
+ `, pages: included.map((page) => page.path) };
55864
+ }
55865
+ // ../../packages/kk-wiki/src/gc.ts
55866
+ import { dirname as dirname15, isAbsolute as isAbsolute9, join as join27 } from "path";
55867
+ async function planGc(index, options) {
55868
+ const fs = options.fileSystem;
55869
+ const root = dirname15(options.rawDir);
55870
+ const mirrorPaths = (options.mirrors ?? []).map((mirror) => isAbsolute9(mirror) ? mirror : join27(root, mirror));
55871
+ const referenced = new Set;
55872
+ for (const page of index.pages) {
55873
+ for (const source of page.frontmatter.sources)
55874
+ referenced.add(source.trim());
55875
+ }
55876
+ const candidates = [];
55877
+ for (const type of ["url", "pdf", "html", "rss"]) {
55878
+ const dir = join27(options.rawDir, type);
55879
+ if (!await fs.exists(dir))
55880
+ continue;
55881
+ for (const name of await fs.readDir(dir))
55882
+ candidates.push(join27(dir, name));
55883
+ }
55884
+ const tmpDir = join27(options.rawDir, "tmp");
55885
+ if (await fs.exists(tmpDir)) {
55886
+ for (const name of await fs.readDir(tmpDir))
55887
+ candidates.push(join27(tmpDir, name));
55888
+ }
55889
+ const skippedMirrors = (options.mirrors ?? []).filter((_, index) => {
55890
+ const path = mirrorPaths[index];
55891
+ return path !== undefined && fs.exists(path);
55892
+ });
55893
+ const plan = { delete: [], keep: [], skippedMirrors };
55894
+ for (const path of candidates) {
55895
+ if (mirrorPaths.some((mirror) => path.startsWith(mirror)))
55896
+ continue;
55897
+ const snapshotId = path.split("/").pop()?.replace(/\.md$/, "") ?? path;
55898
+ if (referenced.has(snapshotId) || referenced.has(path))
55899
+ plan.keep.push(path);
55900
+ else
55901
+ plan.delete.push(path);
55902
+ }
55903
+ plan.delete.sort();
55904
+ plan.keep.sort();
55905
+ return plan;
55906
+ }
55907
+ async function applyGc(plan, fileSystem) {
55908
+ for (const path of plan.delete)
55909
+ await fileSystem.deleteFile(path);
55910
+ return { deleted: [...plan.delete] };
55911
+ }
55912
+ // ../../packages/kk-wiki/src/graph.ts
55913
+ init_dist3();
55914
+ import { relative as relative3 } from "path";
55915
+ function scanLines(body) {
55916
+ const result = [];
55917
+ let inFence = false;
55918
+ body.split(`
55919
+ `).forEach((raw, index) => {
55920
+ const isFence = /^\s*(```|~~~)/.test(raw);
55921
+ if (isFence)
55922
+ inFence = !inFence;
55923
+ const masked = raw.replace(/`[^`]*`/g, (span) => " ".repeat(span.length));
55924
+ result.push({ line: index + 1, text: masked, inFence: isFence ? true : inFence });
55925
+ });
55926
+ return result;
55927
+ }
55928
+ function extractLinks(body) {
55929
+ const links = [];
55930
+ for (const scanned of scanLines(body)) {
55931
+ if (scanned.inFence)
55932
+ continue;
55933
+ const pattern = /\[\[([^\]|]+?)(?:\|([^\]]+))?\]\]/g;
55934
+ for (const match of scanned.text.matchAll(pattern)) {
55935
+ links.push({
55936
+ target: (match[1] ?? "").trim(),
55937
+ surface: match[2] === undefined ? null : match[2].trim(),
55938
+ line: scanned.line
55939
+ });
55940
+ }
55941
+ }
55942
+ return links;
55943
+ }
55944
+ function pageSlug(title) {
55945
+ return resolveSlug(title);
55946
+ }
55947
+ async function listMarkdown(dir, fs) {
55948
+ const files = await walkDir(dir, fs);
55949
+ return files.filter((file) => file.endsWith(".md")).sort();
55950
+ }
55951
+ function duplicateSlugFindings(pages) {
55952
+ const seen = new Map;
55953
+ for (const page of pages) {
55954
+ const paths = seen.get(page.slug) ?? [];
55955
+ paths.push(page.path);
55956
+ seen.set(page.slug, paths);
55957
+ }
55958
+ const findings = [];
55959
+ for (const [slug, paths] of seen) {
55960
+ if (paths.length < 2)
55961
+ continue;
55962
+ for (const path of paths) {
55963
+ findings.push({
55964
+ code: "duplicate-slug",
55965
+ path,
55966
+ line: 1,
55967
+ message: `slug '${slug}' is shared by ${paths.length} pages`
55968
+ });
55969
+ }
55970
+ }
55971
+ return findings;
55972
+ }
55973
+ async function buildVaultIndex(contentDir, fileSystem = createNodeFileSystem()) {
55974
+ const pages = [];
55975
+ const findings = [];
55976
+ for (const file of await listMarkdown(contentDir, fileSystem)) {
55977
+ const path = relative3(contentDir, file);
55978
+ const text = await fileSystem.readFile(file);
55979
+ const parsed = parseFrontmatter(text);
55980
+ const validated = PageFrontmatterSchema.safeParse(parsed.data);
55981
+ if (!validated.success) {
55982
+ const code = parsed.errors.includes("missing-frontmatter") ? "missing-frontmatter" : "invalid-frontmatter";
55983
+ findings.push({
55984
+ code,
55985
+ path,
55986
+ line: 1,
55987
+ message: parsed.errors[0] ?? validated.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`).join("; ")
55988
+ });
55989
+ continue;
55990
+ }
55991
+ const page = {
55992
+ path,
55993
+ slug: pageSlug(validated.data.title),
55994
+ frontmatter: validated.data,
55995
+ body: parsed.body,
55996
+ bodyStartLine: parsed.bodyStartLine,
55997
+ links: extractLinks(parsed.body).map((link) => ({
55998
+ ...link,
55999
+ line: link.line + parsed.bodyStartLine - 1
56000
+ })),
56001
+ inbound: 0
56002
+ };
56003
+ pages.push(page);
56004
+ }
56005
+ const bySlug = new Map;
56006
+ for (const page of pages)
56007
+ bySlug.set(page.slug, page);
56008
+ for (const page of pages) {
56009
+ for (const link of page.links) {
56010
+ const target = bySlug.get(resolveSlug(link.target));
56011
+ if (target !== undefined && target !== page)
56012
+ target.inbound += 1;
56013
+ }
56014
+ }
56015
+ findings.push(...duplicateSlugFindings(pages));
56016
+ return { contentDir, pages, bySlug, findings };
56017
+ }
56018
+ function resolveLink(index, link) {
56019
+ return index.bySlug.get(resolveSlug(link.target));
56020
+ }
56021
+ // ../../packages/kk-wiki/src/link.ts
56022
+ init_dist3();
56023
+ import { join as join28 } from "path";
56024
+
56025
+ // ../../packages/kk-wiki/src/write.ts
56026
+ function guardHeading(date) {
56027
+ return `## AI Updates (${date})`;
56028
+ }
56029
+ function appendGuarded(body, material, date) {
56030
+ const heading = guardHeading(date);
56031
+ const trimmed = material.replace(/\s+$/, "");
56032
+ const lines = body.replace(/\s+$/, "").split(`
56033
+ `);
56034
+ const headingIndex = lines.findIndex((line) => line.trim() === heading);
56035
+ if (headingIndex === -1)
56036
+ return `${lines.join(`
56037
+ `)}
56038
+
56039
+ ${heading}
56040
+
56041
+ ${trimmed}
56042
+ `;
56043
+ const nextHeading = lines.findIndex((line, index) => index > headingIndex && /^##\s+/.test(line));
56044
+ const insertAt = nextHeading === -1 ? lines.length : nextHeading;
56045
+ const head = lines.slice(0, insertAt);
56046
+ while (head.length > 0 && (head[head.length - 1] ?? "").trim() === "")
56047
+ head.pop();
56048
+ return `${[...head, "", trimmed].join(`
56049
+ `)}
56050
+ ${lines.slice(insertAt).join(`
56051
+ `)}`.replace(/\n{3,}/g, `
56052
+
56053
+ `);
56054
+ }
56055
+ function applyWrite(page, material, options) {
56056
+ const guarded = page.frontmatter.user_edited === true;
56057
+ if (guarded)
56058
+ return { body: appendGuarded(page.body, material, options.date), guard: "appended" };
56059
+ if (options.mode === "append")
56060
+ return { body: appendGuarded(page.body, material, options.date), guard: "clean" };
56061
+ return { body: `${material.replace(/\s+$/, "")}
56062
+ `, guard: "clean" };
56063
+ }
56064
+ function applyWriteToPage(page, material, options) {
56065
+ const result = applyWrite(page, material, options);
56066
+ const text = renderPage({
56067
+ ...page,
56068
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56069
+ body: result.body
56070
+ });
56071
+ return { text, guard: result.guard };
56072
+ }
56073
+
56074
+ // ../../packages/kk-wiki/src/link.ts
56075
+ function escapeRegExp(value) {
56076
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
56077
+ }
56078
+ function findMentions(index) {
56079
+ const mentions = [];
56080
+ const titles = index.pages.map((page) => ({ page, title: page.frontmatter.title.trim() })).filter((entry) => entry.title.length >= 3);
56081
+ for (const page of index.pages) {
56082
+ const linked = new Set(page.links.map((link) => link.target.toLowerCase()));
56083
+ for (const scanned of scanLines(page.body)) {
56084
+ if (scanned.inFence)
56085
+ continue;
56086
+ const masked = scanned.text.replace(/\[\[[^\]]*\]\]/g, (span) => " ".repeat(span.length));
56087
+ for (const { page: target, title } of titles) {
56088
+ if (target.slug === page.slug || linked.has(target.slug) || linked.has(title.toLowerCase()))
56089
+ continue;
56090
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56091
+ const hit = pattern.exec(masked);
56092
+ if (hit === null)
56093
+ continue;
56094
+ mentions.push({
56095
+ path: page.path,
56096
+ line: scanned.line + page.bodyStartLine - 1,
56097
+ slug: target.slug,
56098
+ surface: title,
56099
+ text: title
56100
+ });
56101
+ break;
56102
+ }
56103
+ }
56104
+ }
56105
+ return mentions;
56106
+ }
56107
+ function rewriteBody(body, pageMentions, lineOffset) {
56108
+ const lines = body.split(`
56109
+ `);
56110
+ for (const mention of pageMentions) {
56111
+ const index = mention.line - lineOffset;
56112
+ const line = lines[index];
56113
+ if (line === undefined)
56114
+ continue;
56115
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(mention.text)}(?![\\w\\]])`, "i");
56116
+ lines[index] = line.replace(pattern, `[[${mention.slug}|${mention.surface}]]`);
56117
+ }
56118
+ return lines.join(`
56119
+ `);
56120
+ }
56121
+ async function fixLinks(index, options = { date: "" }) {
56122
+ const fs = options.fileSystem ?? createNodeFileSystem();
56123
+ const contentDir = options.contentDir ?? index.contentDir;
56124
+ const mentions = findMentions(index);
56125
+ const grouped = new Map;
56126
+ for (const mention of mentions) {
56127
+ const list = grouped.get(mention.path) ?? [];
56128
+ list.push(mention);
56129
+ grouped.set(mention.path, list);
56130
+ }
56131
+ const changed = [];
56132
+ const refused = [];
56133
+ for (const [path, pageMentions] of grouped) {
56134
+ const raw = await fs.readFile(join28(contentDir, path));
56135
+ const page = parsePage(raw, path);
56136
+ const rewritten = rewriteBody(page.body, pageMentions, parseFrontmatter(raw).bodyStartLine);
56137
+ const { text, guard } = applyWriteToPage(page, rewritten, {
56138
+ mode: "full",
56139
+ date: options.date
56140
+ });
56141
+ if (options.dryRun === true) {
56142
+ changed.push(path);
56143
+ continue;
56144
+ }
56145
+ await fs.writeFile(join28(contentDir, path), text);
56146
+ if (guard === "appended")
56147
+ refused.push(path);
56148
+ else
56149
+ changed.push(path);
56150
+ }
56151
+ return { changed, refused, mentions };
56152
+ }
56153
+ function linkTitlesInText(index, text) {
56154
+ let linked = text;
56155
+ const titles = index.pages.map((page) => ({ slug: page.slug, title: page.frontmatter.title.trim() })).filter((entry) => entry.title.length >= 3).sort((a, b) => b.title.length - a.title.length);
56156
+ for (const { slug, title } of titles) {
56157
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56158
+ linked = linked.replace(pattern, `[[${slug}|${title}]]`);
56159
+ }
56160
+ return linked;
56161
+ }
56162
+ // ../../packages/kk-wiki/src/lint.ts
56163
+ var ORPHAN_EXEMPT_FILES = new Set(["index.md", "MAP.md"]);
56164
+ function lintPages(index) {
56165
+ const findings = [...index.findings];
56166
+ for (const page of index.pages) {
56167
+ for (const link of page.links) {
56168
+ if (resolveLink(index, link) !== undefined)
56169
+ continue;
56170
+ findings.push({
56171
+ code: "broken-link",
56172
+ path: page.path,
56173
+ line: link.line,
56174
+ message: `[[${link.target}]] resolves to no page`
56175
+ });
56176
+ }
56177
+ const basename = page.path.split("/").pop() ?? page.path;
56178
+ if (page.inbound === 0 && !ORPHAN_EXEMPT_FILES.has(basename)) {
56179
+ findings.push({
56180
+ code: "orphan",
56181
+ path: page.path,
56182
+ line: 1,
56183
+ message: "no page links here"
56184
+ });
56185
+ }
56186
+ }
56187
+ return findings.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.code.localeCompare(b.code));
56188
+ }
56189
+ function lintExitCode(findings) {
56190
+ return findings.length === 0 ? 0 : 1;
56191
+ }
56192
+ // ../../packages/kk-wiki/src/markitdown.ts
56193
+ init_dist3();
56194
+ import { createHash as createHash9 } from "crypto";
56195
+ import { tmpdir as tmpdir4 } from "os";
56196
+ import { isAbsolute as isAbsolute10, join as join29 } from "path";
56197
+
56198
+ class MissingNormalizerError extends Error {
56199
+ binary;
56200
+ constructor(binary) {
56201
+ super(`missing normaliser '${binary}': install it (\`uv tool install markitdown\`) or pass markdown on stdin`);
56202
+ this.binary = binary;
56203
+ this.name = "MissingNormalizerError";
56204
+ }
56205
+ }
56206
+ function resolveBinary(binary) {
56207
+ if (isAbsolute10(binary) || binary.includes("/"))
56208
+ return binary;
56209
+ const found = Bun.which(binary, { PATH: process.env.PATH });
56210
+ if (found === null)
56211
+ throw new MissingNormalizerError(binary);
56212
+ return found;
56213
+ }
56214
+ function createMarkitdownRunner(options = {}) {
56215
+ const binary = options.binary ?? "markitdown";
56216
+ const executor = options.executor ?? new NodeProcessExecutor;
56217
+ const fs = options.fileSystem ?? createNodeFileSystem();
56218
+ const timeoutMs = options.timeoutMs ?? 120000;
56219
+ return async (input) => {
56220
+ const executable = resolveBinary(binary);
56221
+ let tempPath;
56222
+ let target = input.target;
56223
+ if (input.kind === "html") {
56224
+ const id = createHash9("sha256").update(input.body ?? "").digest("hex").slice(0, 12);
56225
+ tempPath = join29(tmpdir4(), `kk-wiki-${id}.html`);
56226
+ await fs.writeFile(tempPath, input.body ?? "");
56227
+ target = tempPath;
56228
+ }
56229
+ try {
56230
+ const result = await executor.run({ command: executable, args: [target], timeout: timeoutMs });
56231
+ if (result.exitCode !== 0) {
56232
+ const last = result.stderr.trim().split(`
56233
+ `).slice(-1)[0] ?? "unknown error";
56234
+ throw new Error(`${binary} exited ${result.exitCode}: ${last}`);
56235
+ }
56236
+ if (result.stdout.trim() === "") {
56237
+ throw new Error(`${binary} produced an empty body for ${input.target}`);
56238
+ }
56239
+ return result.stdout;
56240
+ } finally {
56241
+ if (tempPath !== undefined && await fs.exists(tempPath))
56242
+ await fs.deleteFile(tempPath);
56243
+ }
56244
+ };
56245
+ }
56246
+ // ../../packages/kk-wiki/src/merge.ts
56247
+ function mergePages(index, from, to, options) {
56248
+ const source = index.pages.find((page) => page.path === from || page.slug === from);
56249
+ const target = index.pages.find((page) => page.path === to || page.slug === to);
56250
+ if (source === undefined)
56251
+ throw new Error(`merge: no source page '${from}'`);
56252
+ if (target === undefined)
56253
+ throw new Error(`merge: no target page '${to}'`);
56254
+ if (source.frontmatter.user_edited === true) {
56255
+ return {
56256
+ written: target.path,
56257
+ sourceSlug: source.slug,
56258
+ redirects: 0,
56259
+ guard: "refused",
56260
+ targetText: renderPage(target),
56261
+ sourceText: renderPage(source),
56262
+ rewritten: [],
56263
+ rewrittenPages: []
56264
+ };
56265
+ }
56266
+ const mergedSources = [...new Set([...target.frontmatter.sources, ...source.frontmatter.sources, source.slug])];
56267
+ const unitedBody = `${target.body.replace(/\s+$/, "")}
56268
+
56269
+ ${source.body.replace(/^\s+/, "")}`;
56270
+ const written = applyWriteToPage({ ...target, frontmatter: { ...target.frontmatter, sources: mergedSources } }, unitedBody, { mode: "full", date: options.date });
56271
+ let redirects = 0;
56272
+ const rewritten = [];
56273
+ const rewrittenPages = [];
56274
+ for (const page of index.pages) {
56275
+ if (page.slug === source.slug || page.slug === target.slug)
56276
+ continue;
56277
+ const linked = page.body.replace(/\[\[([^\]|]+)(\|[^\]]+)?\]\]/g, (whole, rawTarget, surface) => {
56278
+ const slug = rawTarget.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
56279
+ if (slug !== source.slug)
56280
+ return whole;
56281
+ redirects += 1;
56282
+ return surface === undefined ? `[[${target.slug}]]` : `[[${target.slug}${surface}]]`;
56283
+ });
56284
+ if (linked !== page.body) {
56285
+ page.body = linked;
56286
+ rewritten.push(page.path);
56287
+ rewrittenPages.push({
56288
+ path: page.path,
56289
+ text: renderPage({
56290
+ ...page,
56291
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56292
+ body: linked
56293
+ })
56294
+ });
56295
+ }
56296
+ }
56297
+ const sourceText = renderPage({
56298
+ ...source,
56299
+ frontmatter: {
56300
+ ...source.frontmatter,
56301
+ updated_at: options.date,
56302
+ redirect_to: target.slug
56303
+ },
56304
+ body: `Merged into [[${target.slug}|${target.frontmatter.title}]].
56305
+ `
56306
+ });
56307
+ return {
56308
+ written: target.path,
56309
+ sourceSlug: source.slug,
56310
+ redirects,
56311
+ guard: written.guard,
56312
+ targetText: written.text,
56313
+ sourceText,
56314
+ rewritten,
56315
+ rewrittenPages
56316
+ };
56317
+ }
56318
+ // ../../packages/kk-wiki/src/publish.ts
56319
+ import { dirname as dirname16, isAbsolute as isAbsolute11, join as join30, relative as relative4, resolve as resolve25 } from "path";
56320
+ function isInside(parent, child) {
56321
+ const rel = relative4(parent, child);
56322
+ return rel === "" || !rel.startsWith("..") && !isAbsolute11(rel);
56323
+ }
56324
+ async function publishVault(index, options) {
56325
+ const targetRoot = resolve25(options.target);
56326
+ if (isInside(resolve25(index.contentDir), targetRoot))
56327
+ return { files: [], refused: "target-inside-vault" };
56328
+ const fs = options.fileSystem;
56329
+ const files = [];
56330
+ for (const page of index.pages) {
56331
+ const source = join30(index.contentDir, page.path);
56332
+ const destination = join30(targetRoot, "content", page.path);
56333
+ await fs.ensureDir(dirname16(destination));
56334
+ await fs.writeFile(destination, await fs.readFile(source));
56335
+ files.push(join30("content", page.path));
56336
+ }
56337
+ return { files: files.sort() };
56338
+ }
56339
+ // ../../packages/kk-wiki/src/query.ts
56340
+ function terms(prompt) {
56341
+ return [
56342
+ ...new Set(prompt.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2))
56343
+ ].sort();
56344
+ }
56345
+ function scoreOf2(page, terms_) {
56346
+ const title = page.frontmatter.title.toLowerCase();
56347
+ const tags = page.frontmatter.tags.join(" ").toLowerCase();
56348
+ const body = page.body.toLowerCase();
56349
+ let score = 0;
56350
+ for (const term of terms_) {
56351
+ if (title.includes(term))
56352
+ score += 3;
56353
+ if (tags.includes(term))
56354
+ score += 2;
56355
+ if (body.includes(term))
56356
+ score += 1;
56357
+ }
56358
+ return score;
56359
+ }
56360
+ function excerptOf(page, terms_) {
56361
+ for (const line of page.body.split(`
56362
+ `)) {
56363
+ const text = line.trim();
56364
+ if (text === "" || text.startsWith("#"))
56365
+ continue;
56366
+ const lower = text.toLowerCase();
56367
+ if (terms_.some((term) => lower.includes(term)))
56368
+ return text.slice(0, 200);
56369
+ }
56370
+ return page.body.trim().split(`
56371
+ `)[0]?.slice(0, 200) ?? "";
56372
+ }
56373
+ function rankPages(index, prompt, options = {}) {
56374
+ const terms_ = terms(prompt);
56375
+ const hits = [];
56376
+ for (const page of index.pages) {
56377
+ const score = scoreOf2(page, terms_);
56378
+ if (score === 0)
56379
+ continue;
56380
+ hits.push({ path: page.path, title: page.frontmatter.title, excerpt: excerptOf(page, terms_), score });
56381
+ }
56382
+ return hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, options.limit ?? 10);
56383
+ }
56384
+ // ../../packages/kk-wiki/src/raw.ts
56385
+ init_dist3();
56386
+ import { createHash as createHash10 } from "crypto";
56387
+ import { dirname as dirname17, join as join31 } from "path";
56388
+ var RAW_SOURCE_TYPES = ["url", "pdf", "html", "rss"];
56389
+ function rawSnapshotId(sourceUri, body) {
56390
+ return createHash10("sha256").update(`${sourceUri}
56391
+ ${body}`).digest("hex").slice(0, 16);
56392
+ }
56393
+ function escapeValue(value) {
56394
+ return /[:#\n]/.test(value) || value.trim() !== value ? `"${value.replace(/"/g, "\\\"")}"` : value;
56395
+ }
56396
+ function renderRawSnapshot(snapshot, body) {
56397
+ const lines = [
56398
+ "---",
56399
+ `title: ${escapeValue(snapshot.title)}`,
56400
+ `source_type: ${snapshot.type}`,
56401
+ `source_uri: ${escapeValue(snapshot.sourceUri)}`,
56402
+ `ingested_at: ${snapshot.ingestedAt}`,
56403
+ "---",
56404
+ ""
56405
+ ];
56406
+ return `${lines.join(`
56407
+ `)}
56408
+ ${body.replace(/\s+$/, "")}
56409
+ `;
56410
+ }
56411
+ async function writeRawSnapshot(input, fileSystem = createNodeFileSystem()) {
56412
+ const ingestedAt = input.ingestedAt ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
56413
+ const id = rawSnapshotId(input.sourceUri, input.body);
56414
+ const snapshot = {
56415
+ id,
56416
+ path: join31(input.dir, input.type, `${id}.md`),
56417
+ type: input.type,
56418
+ title: input.title,
56419
+ sourceUri: input.sourceUri,
56420
+ ingestedAt
56421
+ };
56422
+ await fileSystem.ensureDir(dirname17(snapshot.path));
56423
+ await fileSystem.writeFile(snapshot.path, renderRawSnapshot(snapshot, input.body));
56424
+ return snapshot;
56425
+ }
56426
+ function deriveTitle(body, sourceUri) {
56427
+ for (const line of body.split(`
56428
+ `)) {
56429
+ const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(line);
56430
+ if (heading !== null)
56431
+ return heading[1] ?? sourceUri;
56432
+ }
56433
+ const tail = sourceUri === "stdin" ? "stdin" : sourceUri.split("/").pop() ?? sourceUri;
56434
+ return tail.replace(/\.[a-z0-9]+$/i, "") || "untitled";
56435
+ }
56436
+ // ../../packages/kk-wiki/src/summarize.ts
56437
+ var SUMMARY_HEADING = "## Summary";
56438
+ function summarizePage(index, target, material, options) {
56439
+ const linkedText = linkTitlesInText(index, material).trim();
56440
+ const lines = target.body.split(`
56441
+ `);
56442
+ const headingIndex = lines.findIndex((line) => line.trim() === SUMMARY_HEADING);
56443
+ let body;
56444
+ if (headingIndex === -1) {
56445
+ body = `${target.body.replace(/\s+$/, "")}
56446
+
56447
+ ${SUMMARY_HEADING}
56448
+
56449
+ ${linkedText}
56450
+ `;
56451
+ } else {
56452
+ const nextHeading = lines.findIndex((line, position) => position > headingIndex && /^##\s+/.test(line));
56453
+ const head = lines.slice(0, headingIndex + 1);
56454
+ const tail = nextHeading === -1 ? [] : lines.slice(nextHeading);
56455
+ body = `${[...head, "", linkedText, "", ...tail].join(`
56456
+ `).replace(/\n{3,}/g, `
56457
+
56458
+ `).trimEnd()}
56459
+ `;
56460
+ }
56461
+ const written = target.frontmatter.user_edited === true ? applyWrite({ ...target, body }, `${SUMMARY_HEADING}
56462
+
56463
+ ${linkedText}`, {
56464
+ mode: "full",
56465
+ date: options.date
56466
+ }) : { body: `${body.replace(/\s+$/, "")}
56467
+ `, guard: "clean" };
56468
+ return {
56469
+ path: target.path,
56470
+ guard: written.guard,
56471
+ text: renderPage({
56472
+ ...target,
56473
+ frontmatter: { ...target.frontmatter, updated_at: options.date },
56474
+ body: written.body
56475
+ }),
56476
+ links: (linkedText.match(/\[\[/g) ?? []).length
56477
+ };
56478
+ }
56479
+ // ../../packages/kk-wiki/src/sync.ts
56480
+ class UnknownRemoteError extends Error {
56481
+ name;
56482
+ declared;
56483
+ constructor(name, declared) {
56484
+ super(`unknown remote '${name}' (declared: ${declared.length === 0 ? "none" : declared.join(", ")})`);
56485
+ this.name = name;
56486
+ this.declared = declared;
56487
+ this.name = "UnknownRemoteError";
56488
+ }
56489
+ }
56490
+ function resolveRemote(remotes, name, substitutions) {
56491
+ const declared = Object.keys(remotes).sort();
56492
+ const entry = remotes[name];
56493
+ if (entry === undefined)
56494
+ throw new UnknownRemoteError(name, declared);
56495
+ const command = entry.command.replaceAll("{content}", substitutions.content).replaceAll("{remote}", entry.remote);
56496
+ return { argv: command.split(/\s+/).filter((part) => part !== ""), remote: entry.remote, command };
56497
+ }
56498
+ // ../../packages/kk-wiki/src/synthesize.ts
56499
+ function folderFor(type) {
56500
+ if (type === "entity")
56501
+ return "entities";
56502
+ if (type === "source")
56503
+ return "sources";
56504
+ return "concepts";
56505
+ }
56506
+ function synthesizePage(index, input) {
56507
+ const existing = index.bySlug.get(resolveSlug(input.target)) ?? index.pages.find((page) => page.path === input.target);
56508
+ const linkedText = linkTitlesInText(index, input.material).trim();
56509
+ if (existing === undefined) {
56510
+ const type = input.type ?? "concept";
56511
+ const slug = resolveSlug(input.target);
56512
+ const path = `${folderFor(type)}/${slug}.md`;
56513
+ const text = renderPage({
56514
+ path,
56515
+ frontmatter: {
56516
+ title: input.target,
56517
+ type,
56518
+ tags: [],
56519
+ sources: [],
56520
+ updated_at: input.date
56521
+ },
56522
+ body: `${linkedText}
56523
+ `
56524
+ });
56525
+ return { path, slug, guard: "clean", created: true, text };
56526
+ }
56527
+ const written = applyWrite(existing, linkedText, { mode: "append", date: input.date });
56528
+ return {
56529
+ path: existing.path,
56530
+ slug: existing.slug,
56531
+ guard: written.guard,
56532
+ created: false,
56533
+ text: renderPage({
56534
+ ...existing,
56535
+ frontmatter: { ...existing.frontmatter, updated_at: input.date },
56536
+ body: written.body
56537
+ })
56538
+ };
56539
+ }
56540
+ // src/wiki/ingest.ts
56541
+ init_dist3();
56542
+
56543
+ // src/wiki/config.ts
56544
+ import { isAbsolute as isAbsolute12, join as join32, resolve as resolve26 } from "path";
56545
+ init_dist3();
56546
+ var WIKI_CONFIG_FILE = "kk.config.json";
56547
+
56548
+ class WikiConfigError extends Error {
56549
+ constructor(message) {
56550
+ super(message);
56551
+ this.name = "WikiConfigError";
56552
+ }
56553
+ }
56554
+ var KEYS = ["root", "raw", "content", "defaultType", "mirrors", "remotes"];
56555
+ var DEFAULTS = {
56556
+ root: ".",
56557
+ raw: "raw",
56558
+ content: "content",
56559
+ defaultType: "html",
56560
+ mirrors: [],
56561
+ remotes: {}
56562
+ };
56563
+ var ENV_MAP = {
56564
+ KK_WIKI_ROOT: "root",
56565
+ KK_WIKI_RAW: "raw",
56566
+ KK_WIKI_CONTENT: "content",
56567
+ KK_WIKI_DEFAULT_TYPE: "defaultType"
56568
+ };
56569
+ function isRecord4(value) {
56570
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56571
+ }
56572
+ function stringField3(block, key, source) {
56573
+ const value = block[key];
56574
+ if (value === undefined)
56575
+ return;
56576
+ if (typeof value !== "string" || value.trim() === "") {
56577
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.${key} must be a non-empty string (${source})`);
56578
+ }
56579
+ return value;
56580
+ }
56581
+ function parseBlock(raw) {
56582
+ if (raw === undefined)
56583
+ return {};
56584
+ if (!isRecord4(raw))
56585
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: "wiki" must be an object`);
56586
+ for (const key of Object.keys(raw)) {
56587
+ if (!KEYS.includes(key)) {
56588
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: unsupported key wiki.${key} (allowed: ${KEYS.join(", ")})`);
56589
+ }
56590
+ }
56591
+ const block = {};
56592
+ const root = stringField3(raw, "root", "wiki.root");
56593
+ const rawDir = stringField3(raw, "raw", "wiki.raw");
56594
+ const content = stringField3(raw, "content", "wiki.content");
56595
+ if (root !== undefined)
56596
+ block.root = root;
56597
+ if (rawDir !== undefined)
56598
+ block.raw = rawDir;
56599
+ if (content !== undefined)
56600
+ block.content = content;
56601
+ const defaultType = stringField3(raw, "defaultType", "wiki.defaultType");
56602
+ if (defaultType !== undefined) {
56603
+ if (!RAW_SOURCE_TYPES.includes(defaultType)) {
56604
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.defaultType '${defaultType}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56605
+ }
56606
+ block.defaultType = defaultType;
56607
+ }
56608
+ const mirrors = raw.mirrors;
56609
+ if (mirrors !== undefined) {
56610
+ if (!Array.isArray(mirrors) || mirrors.some((entry) => typeof entry !== "string")) {
56611
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.mirrors must be an array of strings`);
56612
+ }
56613
+ block.mirrors = mirrors;
56614
+ }
56615
+ const remotes = raw.remotes;
56616
+ if (remotes !== undefined) {
56617
+ if (!isRecord4(remotes))
56618
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes must be an object`);
56619
+ const parsed = {};
56620
+ for (const [name, value] of Object.entries(remotes)) {
56621
+ if (!isRecord4(value) || typeof value.command !== "string" || typeof value.remote !== "string") {
56622
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes.${name} must be { command: string, remote: string }`);
56623
+ }
56624
+ parsed[name] = { command: value.command, remote: value.remote };
56625
+ }
56626
+ block.remotes = parsed;
56627
+ }
56628
+ return block;
56629
+ }
56630
+ async function readConfigFile(cwd, fileSystem) {
56631
+ const path = join32(cwd, WIKI_CONFIG_FILE);
56632
+ if (!await fileSystem.exists(path))
56633
+ return {};
56634
+ let text;
56635
+ try {
56636
+ text = await fileSystem.readFile(path);
56637
+ } catch (error) {
56638
+ const code = error.code;
56639
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: cannot read (${String(code ?? error)})`);
56640
+ }
56641
+ let parsed;
56642
+ try {
56643
+ parsed = JSON.parse(text);
56644
+ } catch (error) {
56645
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: invalid JSON (${error.message})`);
56646
+ }
56647
+ if (!isRecord4(parsed))
56648
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: top level must be an object`);
56649
+ return parseBlock(parsed.wiki);
56650
+ }
56651
+ async function resolveWikiConfig(options = {}) {
56652
+ const cwd = options.cwd ?? process.cwd();
56653
+ const env = options.env ?? process.env;
56654
+ const fileConfig = await readConfigFile(cwd, options.fileSystem ?? createNodeFileSystem());
56655
+ const merged = { ...DEFAULTS, ...fileConfig };
56656
+ for (const [name, key] of Object.entries(ENV_MAP)) {
56657
+ const value = env[name];
56658
+ if (value === undefined || value.trim() === "")
56659
+ continue;
56660
+ if (key === "defaultType") {
56661
+ if (!RAW_SOURCE_TYPES.includes(value)) {
56662
+ throw new WikiConfigError(`${name} '${value}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56663
+ }
56664
+ merged.defaultType = value;
56665
+ continue;
56666
+ }
56667
+ merged[key] = value;
56668
+ }
56669
+ Object.assign(merged, Object.fromEntries(Object.entries(options.overrides ?? {}).filter(([, v]) => v !== undefined)));
56670
+ merged.root = resolve26(cwd, merged.root);
56671
+ for (const key of ["raw", "content"]) {
56672
+ if (!isAbsolute12(merged[key]))
56673
+ merged[key] = join32(merged.root, merged[key]);
56674
+ }
56675
+ return merged;
56676
+ }
56677
+
56678
+ // src/wiki/ingest.ts
56679
+ var EXTENSION_TYPES = {
56680
+ ".html": "html",
56681
+ ".htm": "html",
56682
+ ".pdf": "pdf"
56683
+ };
56684
+ function detectSourceType(source) {
56685
+ if (/^https?:\/\//i.test(source))
56686
+ return "url";
56687
+ return EXTENSION_TYPES[extname(source).toLowerCase()];
56688
+ }
56689
+ function asSourceType(raw) {
56690
+ return RAW_SOURCE_TYPES.includes(raw) ? raw : undefined;
56691
+ }
56692
+ async function readStdin(stream = Bun.stdin.stream()) {
56693
+ const chunks = [];
56694
+ for await (const chunk of stream)
56695
+ chunks.push(chunk);
56696
+ return Buffer.concat(chunks).toString("utf8");
56697
+ }
56698
+ async function runIngest(args, deps = {}) {
56699
+ const explicit = args.type === undefined ? undefined : asSourceType(args.type);
56700
+ if (args.type !== undefined && explicit === undefined) {
56701
+ return {
56702
+ ok: false,
56703
+ code: 2,
56704
+ payload: { error: `unsupported --type '${args.type}' (want ${RAW_SOURCE_TYPES.join("|")})` }
56705
+ };
56706
+ }
56707
+ const fromStdin = args.source === "-";
56708
+ const detected = explicit ?? (fromStdin ? undefined : detectSourceType(args.source));
56709
+ if (detected === undefined) {
56710
+ const what = fromStdin ? "stdin requires --type" : `unsupported source type for '${args.source}'`;
56711
+ return { ok: false, code: 2, payload: { error: `${what} (want ${RAW_SOURCE_TYPES.join("|")})` } };
56712
+ }
56713
+ let config;
56714
+ try {
56715
+ config = await resolveWikiConfig({ cwd: deps.cwd, env: deps.env, overrides: { raw: args.out } });
56716
+ } catch (error) {
56717
+ if (error instanceof WikiConfigError)
56718
+ return { ok: false, code: 1, payload: { error: error.message } };
56719
+ throw error;
56720
+ }
56721
+ const fs = deps.fileSystem ?? createNodeFileSystem();
56722
+ const readStdinFn = deps.readStdin ?? readStdin;
56723
+ const normalise = deps.markitdown ?? createMarkitdownRunner();
56724
+ const sourcePath = isAbsolute13(args.source) ? args.source : join33(deps.cwd ?? process.cwd(), args.source);
56725
+ let sourceText;
56726
+ try {
56727
+ if (fromStdin) {
56728
+ sourceText = await readStdinFn();
56729
+ } else if (detected === "rss") {
56730
+ sourceText = await fs.readFile(sourcePath);
56731
+ } else {
56732
+ sourceText = await normalise({
56733
+ kind: detected,
56734
+ target: sourcePath,
56735
+ body: detected === "html" ? await fs.readFile(sourcePath) : undefined
56736
+ });
56737
+ }
56738
+ } catch (error) {
56739
+ if (error instanceof MissingNormalizerError)
56740
+ return { ok: false, code: 1, payload: { error: error.message } };
56741
+ const detail = error instanceof Error ? error.message : String(error);
56742
+ return { ok: false, code: 1, payload: { error: `ingest failed for '${args.source}': ${detail}` } };
56743
+ }
56744
+ const sourceUri = fromStdin ? "stdin" : args.source;
56745
+ const snapshot = await writeRawSnapshot({
56746
+ type: detected,
56747
+ sourceUri,
56748
+ title: deriveTitle(sourceText, sourceUri),
56749
+ body: sourceText,
56750
+ dir: config.raw
56751
+ }, fs);
56752
+ return {
56753
+ ok: true,
56754
+ code: 0,
56755
+ payload: { path: snapshot.path, id: snapshot.id, type: snapshot.type, title: snapshot.title }
56756
+ };
56757
+ }
56758
+
56759
+ // src/wiki/link.ts
56760
+ init_output2();
56761
+ async function runLink(options = {}) {
56762
+ let contentDir;
56763
+ try {
56764
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56765
+ } catch (error) {
56766
+ if (error instanceof WikiConfigError)
56767
+ return { ok: false, code: 1, payload: { error: error.message } };
56768
+ throw error;
56769
+ }
56770
+ const index = await buildVaultIndex(contentDir);
56771
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
56772
+ if (options.fix !== true) {
56773
+ const mentions = findMentions(index);
56774
+ return { ok: true, code: 0, payload: { ok: true, fix: false, mentions } };
56775
+ }
56776
+ const result = await fixLinks(index, { date, contentDir });
56777
+ return { ok: true, code: 0, payload: { ok: true, fix: true, ...result } };
56778
+ }
56779
+ function printLinkOutcome(outcome, json) {
56780
+ if (json) {
56781
+ consoleOutput.write(toJson(outcome.payload));
56782
+ return;
56783
+ }
56784
+ const payload = outcome.payload;
56785
+ if (payload.error !== undefined) {
56786
+ consoleOutput.error(`kk.wiki.link: ${payload.error}`);
56787
+ return;
56788
+ }
56789
+ if (payload.fix === true) {
56790
+ for (const path of payload.changed ?? [])
56791
+ consoleOutput.write(`linked: ${path}`);
56792
+ for (const path of payload.refused ?? [])
56793
+ consoleOutput.write(`guard: ${path} (appended under AI Updates)`);
56794
+ if ((payload.changed ?? []).length === 0 && (payload.refused ?? []).length === 0) {
56795
+ consoleOutput.write("no unlinked mentions");
56796
+ }
56797
+ return;
56798
+ }
56799
+ for (const mention of payload.mentions ?? []) {
56800
+ consoleOutput.write(`${mention.path}:${mention.line} ${mention.surface} -> [[${mention.slug}]]`);
56801
+ }
56802
+ if ((payload.mentions ?? []).length === 0)
56803
+ consoleOutput.write("no unlinked mentions");
56804
+ }
56805
+
56806
+ // src/wiki/lint.ts
56807
+ init_dist3();
56808
+ init_output2();
56809
+ async function runLint(options = {}) {
56810
+ let contentDir;
56811
+ try {
56812
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56813
+ } catch (error) {
56814
+ if (error instanceof WikiConfigError)
56815
+ return { ok: false, code: 1, payload: { error: error.message } };
56816
+ throw error;
56817
+ }
56818
+ const index = await buildVaultIndex(contentDir, createNodeFileSystem());
56819
+ const findings = lintPages(index);
56820
+ return {
56821
+ ok: findings.length === 0,
56822
+ code: lintExitCode(findings),
56823
+ payload: { ok: findings.length === 0, findings, pages: index.pages.length }
56824
+ };
56825
+ }
56826
+ function printLintOutcome(outcome, json) {
56827
+ if (json) {
56828
+ consoleOutput.write(toJson(outcome.payload));
56829
+ return;
56830
+ }
56831
+ const payload = outcome.payload;
56832
+ if (payload.error !== undefined) {
56833
+ consoleOutput.error(`kk.wiki.lint: ${payload.error}`);
56834
+ return;
56835
+ }
56836
+ for (const finding of payload.findings ?? []) {
56837
+ consoleOutput.write(`${finding.path}:${finding.line} ${finding.code}: ${finding.message}`);
56838
+ }
56839
+ if ((payload.findings ?? []).length === 0)
56840
+ consoleOutput.write("vault is clean");
56841
+ }
56842
+
56843
+ // src/wiki/maintenance.ts
56844
+ import { join as join34 } from "path";
56845
+ init_dist3();
56846
+ init_output2();
56847
+ async function withConfig2(options, run) {
56848
+ try {
56849
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
56850
+ return await run({ contentDir: config.content, rawDir: config.raw, mirrors: config.mirrors });
56851
+ } catch (error) {
56852
+ if (error instanceof WikiConfigError)
56853
+ return { error: error.message };
56854
+ throw error;
56855
+ }
56856
+ }
56857
+ async function runMerge(options) {
56858
+ const result = await withConfig2(options, async ({ contentDir }) => {
56859
+ const index = await buildVaultIndex(contentDir);
56860
+ const merge = mergePages(index, options.from ?? "", options.to ?? "", {
56861
+ date: options.date ?? new Date().toISOString().slice(0, 10)
56862
+ });
56863
+ if (merge.guard === "refused")
56864
+ return { refused: true, path: merge.written };
56865
+ const fs = createNodeFileSystem();
56866
+ await fs.writeFile(join34(contentDir, merge.written), merge.targetText);
56867
+ const sourcePage = index.pages.find((page) => page.slug === merge.sourceSlug);
56868
+ if (sourcePage !== undefined)
56869
+ await fs.writeFile(join34(contentDir, sourcePage.path), merge.sourceText);
56870
+ for (const page of merge.rewrittenPages)
56871
+ await fs.writeFile(join34(contentDir, page.path), page.text);
56872
+ return {
56873
+ refused: false,
56874
+ path: merge.written,
56875
+ redirects: merge.redirects,
56876
+ rewritten: merge.rewritten,
56877
+ rewrittenPages: merge.rewrittenPages,
56878
+ sourceText: merge.sourceText,
56879
+ sourceSlug: merge.sourceSlug
56880
+ };
56881
+ });
56882
+ if ("error" in result)
56883
+ return { ok: false, code: 1, payload: result };
56884
+ if (result.refused === true) {
56885
+ return { ok: false, code: 1, payload: { ok: false, error: "source page is user_edited; merge refused" } };
56886
+ }
56887
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56888
+ }
56889
+ async function runCompile(options) {
56890
+ const result = await withConfig2(options, async ({ contentDir }) => {
56891
+ const index = await buildVaultIndex(contentDir);
56892
+ const compiled = compileIndex(index.pages, { date: options.date ?? new Date().toISOString().slice(0, 10) });
56893
+ const fs = createNodeFileSystem();
56894
+ const written = [];
56895
+ for (const [name, rendered] of [
56896
+ ["index.md", compiled.index],
56897
+ ["MAP.md", compiled.map]
56898
+ ]) {
56899
+ const path = join34(contentDir, name);
56900
+ const current = await fs.exists(path) ? await fs.readFile(path) : null;
56901
+ if (!needsWrite(current, rendered))
56902
+ continue;
56903
+ await fs.writeFile(path, rendered);
56904
+ written.push(name);
56905
+ }
56906
+ return { written };
56907
+ });
56908
+ if ("error" in result)
56909
+ return { ok: false, code: 1, payload: result };
56910
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56911
+ }
56912
+ async function runGc(options) {
56913
+ const result = await withConfig2(options, async ({ contentDir, rawDir, mirrors }) => {
56914
+ const fs = createNodeFileSystem();
56915
+ const index = await buildVaultIndex(contentDir);
56916
+ const plan = await planGc(index, { rawDir, mirrors, fileSystem: fs });
56917
+ if (options.yes !== true)
56918
+ return { plan, deleted: [] };
56919
+ const { deleted } = await applyGc(plan, fs);
56920
+ return { plan, deleted };
56921
+ });
56922
+ if ("error" in result)
56923
+ return { ok: false, code: 1, payload: result };
56924
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56925
+ }
56926
+ function printMaintenanceOutcome(outcome, json) {
56927
+ if (json) {
56928
+ consoleOutput.write(toJson(outcome.payload));
56929
+ return;
56930
+ }
56931
+ const payload = outcome.payload;
56932
+ if (payload.error !== undefined) {
56933
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
56934
+ return;
56935
+ }
56936
+ if (payload.plan !== undefined) {
56937
+ for (const path of payload.plan.delete)
56938
+ consoleOutput.write(`delete: ${path}`);
56939
+ for (const path of payload.plan.skippedMirrors)
56940
+ consoleOutput.write(`skip (mirror): ${path}`);
56941
+ if ((payload.deleted ?? []).length === 0)
56942
+ consoleOutput.write("dry run \u2014 pass --yes to delete");
56943
+ return;
56944
+ }
56945
+ if (payload.rewritten !== undefined) {
56946
+ consoleOutput.write(`merged into ${payload.path} (${payload.redirects} links rewritten)`);
56947
+ return;
56948
+ }
56949
+ for (const name of payload.written ?? [])
56950
+ consoleOutput.write(`compiled: ${name}`);
56951
+ if ((payload.written ?? []).length === 0)
56952
+ consoleOutput.write("already up to date");
56953
+ }
56954
+
56955
+ // src/wiki/retrieval.ts
56956
+ init_dist3();
56957
+ init_output2();
56958
+ async function configOrError(options) {
56959
+ try {
56960
+ return await resolveWikiConfig({ cwd: options.cwd, env: options.env });
56961
+ } catch (error) {
56962
+ if (error instanceof WikiConfigError)
56963
+ return { error: error.message };
56964
+ throw error;
56965
+ }
56966
+ }
56967
+ async function runPublish(options) {
56968
+ const config = await configOrError(options);
56969
+ if ("error" in config)
56970
+ return { ok: false, code: 1, payload: config };
56971
+ try {
56972
+ const index = await buildVaultIndex(config.content);
56973
+ const result = await publishVault(index, {
56974
+ target: options.value ?? "",
56975
+ fileSystem: createNodeFileSystem()
56976
+ });
56977
+ if (result.refused !== undefined) {
56978
+ return { ok: false, code: 2, payload: { ok: false, error: "target is inside the vault" } };
56979
+ }
56980
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56981
+ } catch (error) {
56982
+ return { ok: false, code: 1, payload: { ok: false, error: error.message } };
56983
+ }
56984
+ }
56985
+ async function runSync(options) {
56986
+ const config = await configOrError(options);
56987
+ if ("error" in config)
56988
+ return { ok: false, code: 1, payload: config };
56989
+ try {
56990
+ const resolved = resolveRemote(config.remotes, options.value ?? "", { content: config.content });
56991
+ return { ok: true, code: 0, payload: { ok: true, dryRun: options.dryRun !== false, ...resolved } };
56992
+ } catch (error) {
56993
+ return { ok: false, code: 2, payload: { ok: false, error: error.message } };
56994
+ }
56995
+ }
56996
+ async function runQuery(options) {
56997
+ const config = await configOrError(options);
56998
+ if ("error" in config)
56999
+ return { ok: false, code: 1, payload: config };
57000
+ const index = await buildVaultIndex(config.content);
57001
+ const hits = rankPages(index, options.value ?? "", { limit: options.limit });
57002
+ return { ok: true, code: 0, payload: { ok: true, hits } };
57003
+ }
57004
+ async function runContext(options) {
57005
+ const config = await configOrError(options);
57006
+ if ("error" in config)
57007
+ return { ok: false, code: 1, payload: config };
57008
+ const index = await buildVaultIndex(config.content);
57009
+ const packed = packContext(index, options.value ?? "", { depth: options.depth });
57010
+ return { ok: true, code: 0, payload: { ok: true, ...packed } };
57011
+ }
57012
+ function printRetrievalOutcome(outcome, json) {
57013
+ if (json) {
57014
+ consoleOutput.write(toJson(outcome.payload));
57015
+ return;
57016
+ }
57017
+ const payload = outcome.payload;
57018
+ if (payload.error !== undefined) {
57019
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
57020
+ return;
57021
+ }
57022
+ if (payload.files !== undefined) {
57023
+ consoleOutput.write(`published ${payload.files.length} file(s)`);
57024
+ return;
57025
+ }
57026
+ if (payload.command !== undefined) {
57027
+ consoleOutput.write(`remote: ${payload.command}`);
57028
+ return;
57029
+ }
57030
+ if (payload.hits !== undefined) {
57031
+ for (const hit of payload.hits)
57032
+ consoleOutput.write(`${hit.path} (${hit.score})`);
57033
+ return;
57034
+ }
57035
+ consoleOutput.write(payload.markdown ?? "");
57036
+ }
57037
+
57038
+ // src/wiki/write-verbs.ts
57039
+ import { isAbsolute as isAbsolute14, join as join35 } from "path";
57040
+ init_dist3();
57041
+ init_output2();
57042
+ async function readMaterial(options) {
57043
+ if (options.from === "-") {
57044
+ if (options.readStdin !== undefined)
57045
+ return options.readStdin();
57046
+ const chunks = [];
57047
+ for await (const chunk of Bun.stdin.stream())
57048
+ chunks.push(chunk);
57049
+ return Buffer.concat(chunks).toString("utf8");
57050
+ }
57051
+ const path = isAbsolute14(options.from) ? options.from : join35(options.cwd ?? process.cwd(), options.from);
57052
+ return createNodeFileSystem().readFile(path);
57053
+ }
57054
+ async function resolveContext(options) {
57055
+ try {
57056
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
57057
+ const index = await buildVaultIndex(config.content);
57058
+ return { index, contentDir: config.content };
57059
+ } catch (error) {
57060
+ if (error instanceof WikiConfigError)
57061
+ return { error: error.message };
57062
+ throw error;
57063
+ }
57064
+ }
57065
+ async function runSummarize(options) {
57066
+ const context = await resolveContext(options);
57067
+ if ("error" in context)
57068
+ return { ok: false, code: 1, payload: { error: context.error } };
57069
+ const target = context.index.pages.find((page) => page.path === options.target);
57070
+ if (target === undefined) {
57071
+ return { ok: false, code: 1, payload: { error: `no page at '${options.target}'` } };
57072
+ }
57073
+ const material = await readMaterial(options);
57074
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57075
+ const result = summarizePage(context.index, target, material, { date });
57076
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57077
+ return { ok: true, code: 0, payload: { ok: true, path: result.path, guard: result.guard, links: result.links } };
57078
+ }
57079
+ async function runSynthesize(options) {
57080
+ const context = await resolveContext(options);
57081
+ if ("error" in context)
57082
+ return { ok: false, code: 1, payload: { error: context.error } };
57083
+ const material = await readMaterial(options);
57084
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57085
+ const type = options.type;
57086
+ const result = synthesizePage(context.index, { target: options.target, material, type, date });
57087
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57088
+ return {
57089
+ ok: true,
57090
+ code: 0,
57091
+ payload: { ok: true, path: result.path, slug: result.slug, guard: result.guard, created: result.created }
57092
+ };
57093
+ }
57094
+ function printWriteOutcome(outcome, json) {
57095
+ if (json) {
57096
+ consoleOutput.write(toJson(outcome.payload));
57097
+ return;
57098
+ }
57099
+ const payload = outcome.payload;
57100
+ if (payload.error !== undefined) {
57101
+ consoleOutput.error(`kk.wiki.write: ${payload.error}`);
57102
+ return;
57103
+ }
57104
+ consoleOutput.write(`${payload.created === true ? "created" : "updated"} ${payload.path} (guard: ${payload.guard})`);
57105
+ }
57106
+
57107
+ // src/commands/wiki.ts
57108
+ async function ingestAction2(source, options) {
57109
+ const outcome = await runIngest({ source, type: options.type, out: options.out, json: options.json });
57110
+ if (outcome.ok) {
57111
+ if (options.json === true)
57112
+ consoleOutput.write(toJson(outcome.payload));
57113
+ else
57114
+ consoleOutput.write(`raw snapshot: ${outcome.payload.path}`);
57115
+ return;
57116
+ }
57117
+ const message = `kk.wiki.ingest: ${outcome.payload.error}`;
57118
+ if (options.json === true)
57119
+ consoleOutput.write(toJson({ ok: false, error: outcome.payload.error }));
57120
+ consoleOutput.error(message);
57121
+ throw new CommanderError(outcome.code, "kk.wiki.ingest", message);
57122
+ }
57123
+ async function linkAction(options) {
57124
+ const outcome = await runLink({ fix: options.fix === true, json: options.json === true });
57125
+ printLinkOutcome(outcome, options.json === true);
57126
+ if (!outcome.ok)
57127
+ throw new CommanderError(outcome.code, "kk.wiki.link", "kk.wiki.link failed");
57128
+ }
57129
+ async function lintAction(options) {
57130
+ const outcome = await runLint({ json: options.json === true });
57131
+ printLintOutcome(outcome, options.json === true);
57132
+ if (outcome.code !== 0)
57133
+ throw new CommanderError(outcome.code, "kk.wiki.lint", "kk.wiki.lint findings");
57134
+ }
57135
+ async function summarizeAction(target, options) {
57136
+ const outcome = await runSummarize({ target, from: options.from, json: options.json === true });
57137
+ printWriteOutcome(outcome, options.json === true);
57138
+ if (!outcome.ok)
57139
+ throw new CommanderError(outcome.code, "kk.wiki.summarize", "kk.wiki.summarize failed");
57140
+ }
57141
+ async function synthesizeAction(target, options) {
57142
+ const outcome = await runSynthesize({
57143
+ target,
57144
+ from: options.from,
57145
+ type: options.type,
57146
+ json: options.json === true
57147
+ });
57148
+ printWriteOutcome(outcome, options.json === true);
57149
+ if (!outcome.ok)
57150
+ throw new CommanderError(outcome.code, "kk.wiki.synthesize", "kk.wiki.synthesize failed");
57151
+ }
57152
+ async function mergeAction(source, target, options) {
57153
+ const outcome = await runMerge({ from: source, to: target, json: options.json === true });
57154
+ printMaintenanceOutcome(outcome, options.json === true);
57155
+ if (!outcome.ok)
57156
+ throw new CommanderError(outcome.code, "kk.wiki.merge", "kk.wiki.merge failed");
57157
+ }
57158
+ async function compileAction(options) {
57159
+ const outcome = await runCompile({ json: options.json === true });
57160
+ printMaintenanceOutcome(outcome, options.json === true);
57161
+ if (!outcome.ok)
57162
+ throw new CommanderError(outcome.code, "kk.wiki.compile", "kk.wiki.compile failed");
57163
+ }
57164
+ async function gcAction(options) {
57165
+ const outcome = await runGc({ yes: options.yes === true, json: options.json === true });
57166
+ printMaintenanceOutcome(outcome, options.json === true);
57167
+ if (!outcome.ok)
57168
+ throw new CommanderError(outcome.code, "kk.wiki.gc", "kk.wiki.gc failed");
57169
+ }
57170
+ async function publishAction(options) {
57171
+ const outcome = await runPublish({ value: options.target, json: options.json === true });
57172
+ printRetrievalOutcome(outcome, options.json === true);
57173
+ if (!outcome.ok)
57174
+ throw new CommanderError(outcome.code, "kk.wiki.publish", "kk.wiki.publish failed");
57175
+ }
57176
+ async function syncAction(remote, options) {
57177
+ const outcome = await runSync({ value: remote, dryRun: options.dryRun === true, json: options.json === true });
57178
+ printRetrievalOutcome(outcome, options.json === true);
57179
+ if (!outcome.ok)
57180
+ throw new CommanderError(outcome.code, "kk.wiki.sync", "kk.wiki.sync failed");
57181
+ }
57182
+ async function queryAction(prompt, options) {
57183
+ const outcome = await runQuery({
57184
+ value: prompt,
57185
+ limit: options.limit === undefined ? undefined : Number(options.limit),
57186
+ json: options.json === true
57187
+ });
57188
+ printRetrievalOutcome(outcome, options.json === true);
57189
+ if (!outcome.ok)
57190
+ throw new CommanderError(outcome.code, "kk.wiki.query", "kk.wiki.query failed");
57191
+ }
57192
+ async function contextAction(topic, options) {
57193
+ const outcome = await runContext({
57194
+ value: topic,
57195
+ depth: options.depth === undefined ? undefined : Number(options.depth),
57196
+ json: options.json === true
57197
+ });
57198
+ printRetrievalOutcome(outcome, options.json === true);
57199
+ if (!outcome.ok)
57200
+ throw new CommanderError(outcome.code, "kk.wiki.context", "kk.wiki.context failed");
57201
+ }
57202
+ function registerWikiCommand(parent) {
57203
+ const wiki = parent.command("wiki").description("Deterministic Markdown vault mechanics (ADR-048)");
57204
+ wiki.command("ingest").description("Normalise a file, URL or stdin body into a layer-1 raw snapshot").argument("<source>", "File path, http(s) URL, or - for stdin").option("--type <type>", "Source type: url | pdf | html | rss (default: from the extension)").option("--out <dir>", "Raw directory override (default: wiki.raw from kk.config.json)").option("--json", "Print one JSON document instead of a one-line summary").action(ingestAction2);
57205
+ wiki.command("link").description("Report unlinked mentions of existing page titles; --fix injects them").option("--fix", "Rewrite the reported mentions to [[slug|Surface]]").option("--json", "Print one JSON document").action(linkAction);
57206
+ wiki.command("summarize").description("Place authored summary text into a page and link the references it mentions").argument("<target>", "Vault-relative page path, e.g. concepts/vector-index.md").requiredOption("--from <source>", "Text source: - for stdin, or a file path").option("--json", "Print one JSON document").action(summarizeAction);
57207
+ wiki.command("synthesize").description("Create a page for a new topic, or extend an existing page, from authored text").argument("<target>", "Topic title or vault-relative page path").requiredOption("--from <source>", "Text source: - for stdin, or a file path").option("--type <pageType>", "Page class for a created page: concept | entity | source | index").option("--json", "Print one JSON document").action(synthesizeAction);
57208
+ wiki.command("merge").description("Merge a source page into a target page, leaving a redirect and rewriting inbound links").argument("<source>", "Page path or slug to absorb").argument("<target>", "Page path or slug to survive").option("--json", "Print one JSON document").action(mergeAction);
57209
+ wiki.command("compile").description("Regenerate content/index.md and content/MAP.md from the vault structure").option("--json", "Print one JSON document").action(compileAction);
57210
+ wiki.command("gc").description("Reclaim unreferenced raw snapshots; prints the plan unless --yes is passed").option("--yes", "Delete the planned files").option("--json", "Print one JSON document").action(gcAction);
57211
+ wiki.command("publish").description("Project content/ into a Quartz-compatible tree at --target").requiredOption("--target <dir>", "Destination directory (the published tree lands under <dir>/content)").option("--json", "Print one JSON document").action(publishAction);
57212
+ wiki.command("sync").description("Resolve a configured remote into its command; --dry-run transfers nothing").argument("<remote>", "Remote name declared in kk.config.json wiki.remotes").option("--dry-run", "Print the resolved command without transferring").option("--json", "Print one JSON document").action(syncAction);
57213
+ wiki.command("query").description("Rank vault pages against a prompt and print their paths").argument("<prompt>", "Search prompt").option("--limit <n>", "Maximum hits (default 10)").option("--json", "Print one JSON document").action(queryAction);
57214
+ wiki.command("context").description("Pack the topic page and its graph neighbours into one Markdown block").argument("<topic>", "Topic title or slug").option("--depth <n>", "Neighbour depth (default 1)").option("--json", "Print one JSON document").action(contextAction);
57215
+ wiki.command("lint").description("Audit the vault for broken links, orphan pages and frontmatter defects").option("--json", "Print one JSON document").action(lintAction);
57216
+ }
57217
+
55617
57218
  // src/config.ts
55618
57219
  import { readFileSync as readFileSync9 } from "fs";
55619
57220
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -55638,6 +57239,7 @@ function createProgram() {
55638
57239
  registerScheduleCommand(program);
55639
57240
  registerStageCommand(program);
55640
57241
  registerStoreCommand(program);
57242
+ registerWikiCommand(program);
55641
57243
  return program;
55642
57244
  }
55643
57245