@gobing-ai/knowledge-kit 0.1.15 → 0.1.17

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 (116) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +1765 -40
  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 +17 -9
  43. package/plugins/kk/publish-presets/itc-main.json +42 -0
  44. package/plugins/kk/scripts/cover-compositor.ts +198 -0
  45. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  46. package/plugins/kk/scripts/daily-scheduled-run.ts +188 -3
  47. package/plugins/kk/scripts/daily-stages.ts +134 -26
  48. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  49. package/plugins/kk/scripts/daily-triage.ts +74 -0
  50. package/plugins/kk/scripts/itc-stages.ts +3 -2
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +31 -2
  52. package/plugins/kk/scripts/voice3-publish-window.ts +5 -1
  53. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  54. package/plugins/kk/skills/news-editorial/SKILL.md +3 -3
  55. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +2 -1
  56. package/plugins/kk/skills/publish/SKILL.md +1 -1
  57. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  58. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  59. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +3 -3
  60. package/plugins/kk/workflows/kk-daily-publish3.yaml +10 -3
  61. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  62. package/plugins/publishings/bilibili-pub/dist/index.js +90 -17
  63. package/plugins/publishings/bilibili-pub/dist/profile-check.js +90 -16
  64. package/plugins/publishings/cnblogs-pub/dist/index.js +90 -17
  65. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +90 -16
  66. package/plugins/publishings/csdn-pub/dist/index.js +90 -17
  67. package/plugins/publishings/csdn-pub/dist/profile-check.js +91 -17
  68. package/plugins/publishings/emdash-pub/dist/index.js +1 -1
  69. package/plugins/publishings/infoq-pub/dist/index.js +120 -19
  70. package/plugins/publishings/infoq-pub/dist/profile-check.js +95 -18
  71. package/plugins/publishings/infoq-pub/src/index.ts +40 -1
  72. package/plugins/publishings/jike-pub/dist/index.js +90 -17
  73. package/plugins/publishings/jike-pub/dist/profile-check.js +91 -17
  74. package/plugins/publishings/juejin-pub/dist/index.js +117 -20
  75. package/plugins/publishings/juejin-pub/dist/profile-check.js +94 -18
  76. package/plugins/publishings/juejin-pub/src/index.ts +41 -2
  77. package/plugins/publishings/linkedin-pub/dist/index.js +90 -17
  78. package/plugins/publishings/linkedin-pub/dist/profile-check.js +91 -17
  79. package/plugins/publishings/medium-pub/dist/index.js +1 -1
  80. package/plugins/publishings/podcast-pub/dist/index.js +1 -1
  81. package/plugins/publishings/qiita-pub/dist/index.js +1 -1
  82. package/plugins/publishings/shipinhao-pub/dist/index.js +311 -66
  83. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +138 -17
  84. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  85. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  86. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  87. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  88. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  89. package/plugins/publishings/sspai-pub/dist/index.js +90 -17
  90. package/plugins/publishings/sspai-pub/dist/profile-check.js +90 -16
  91. package/plugins/publishings/substack-pub/dist/index.js +90 -17
  92. package/plugins/publishings/substack-pub/dist/profile-check.js +91 -17
  93. package/plugins/publishings/surfdash-pub/dist/index.js +244 -13
  94. package/plugins/publishings/surfdash-pub/src/index.ts +144 -8
  95. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  96. package/plugins/publishings/threads-pub/dist/index.js +1 -1
  97. package/plugins/publishings/wechatmp-pub/dist/index.js +186 -39
  98. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +96 -19
  99. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +14 -2
  100. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  101. package/plugins/publishings/wechatmp-pub/src/flow.ts +158 -25
  102. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  103. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +8 -1
  104. package/plugins/publishings/weibo-pub/dist/index.js +90 -17
  105. package/plugins/publishings/weibo-pub/dist/profile-check.js +91 -17
  106. package/plugins/publishings/x-pub/dist/index.js +90 -17
  107. package/plugins/publishings/x-pub/dist/profile-check.js +91 -17
  108. package/plugins/publishings/xhs-pub/dist/index.js +646 -47
  109. package/plugins/publishings/xhs-pub/dist/profile-check.js +109 -17
  110. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  111. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  112. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  113. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +90 -17
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +90 -16
  115. package/plugins/publishings/zenn-pub/dist/index.js +94 -2
  116. package/plugins/publishings/zenn-pub/src/index.ts +134 -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();
@@ -37868,8 +37906,11 @@ import {
37868
37906
  mkdirSync as mkdirSync4,
37869
37907
  openSync,
37870
37908
  readdirSync as readdirSync4,
37909
+ readlinkSync,
37871
37910
  realpathSync as realpathSync5,
37872
- rmdirSync
37911
+ renameSync as renameSync3,
37912
+ rmdirSync,
37913
+ unlinkSync as unlinkSync2
37873
37914
  } from "fs";
37874
37915
  import { join as join8 } from "path";
37875
37916
  function lstat(path) {
@@ -37905,6 +37946,33 @@ function rmdir(path) {
37905
37946
  throw error;
37906
37947
  }
37907
37948
  }
37949
+ function readlink(path) {
37950
+ try {
37951
+ return readlinkSync(path);
37952
+ } catch {
37953
+ return null;
37954
+ }
37955
+ }
37956
+ function unlink(path) {
37957
+ try {
37958
+ unlinkSync2(path);
37959
+ return true;
37960
+ } catch (error) {
37961
+ if (error.code === "ENOENT")
37962
+ return false;
37963
+ throw error;
37964
+ }
37965
+ }
37966
+ function rename(from, to) {
37967
+ try {
37968
+ renameSync3(from, to);
37969
+ return true;
37970
+ } catch (error) {
37971
+ if (error.code === "ENOENT")
37972
+ return false;
37973
+ throw error;
37974
+ }
37975
+ }
37908
37976
  function chmod(path, mode) {
37909
37977
  chmodSync(path, mode);
37910
37978
  }
@@ -38083,7 +38151,7 @@ var init_bot_transaction = __esm(() => {
38083
38151
 
38084
38152
  // ../../packages/publish-harness/src/profile-lease.ts
38085
38153
  import { createHash, randomBytes } from "crypto";
38086
- import { homedir as homedir7 } from "os";
38154
+ import { homedir as homedir7, hostname as hostname3 } from "os";
38087
38155
  import { basename as basename2, dirname as dirname9, join as join10, resolve as resolve10 } from "path";
38088
38156
  async function acquireProfileLease(profileDir, options = {}) {
38089
38157
  const fileSystem = options.fileSystem ?? createNodeFileSystem();
@@ -38252,6 +38320,8 @@ function isProcessAlive(pid) {
38252
38320
  }
38253
38321
  }
38254
38322
  function refuseNativeLock(profileDir) {
38323
+ if (reclaimStaleNativeLock(profileDir))
38324
+ return;
38255
38325
  for (const name of NATIVE_LOCK_FILES) {
38256
38326
  const path = join10(profileDir, name);
38257
38327
  if (lstat(path) !== null) {
@@ -38259,6 +38329,24 @@ function refuseNativeLock(profileDir) {
38259
38329
  }
38260
38330
  }
38261
38331
  }
38332
+ function reclaimStaleNativeLock(profileDir) {
38333
+ const lockPath = join10(profileDir, "SingletonLock");
38334
+ const target = readlink(lockPath);
38335
+ if (target === null)
38336
+ return false;
38337
+ const match = /^(.*)-(\d+)$/.exec(target);
38338
+ if (match === null)
38339
+ return false;
38340
+ const [, host, pidText] = match;
38341
+ if (host !== hostname3())
38342
+ return false;
38343
+ const pid = Number(pidText);
38344
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
38345
+ return false;
38346
+ for (const name of NATIVE_LOCK_FILES)
38347
+ unlink(join10(profileDir, name));
38348
+ return true;
38349
+ }
38262
38350
  function sha256Hex2(value) {
38263
38351
  return createHash("sha256").update(value).digest("hex");
38264
38352
  }
@@ -38268,7 +38356,7 @@ var init_profile_lease = __esm(() => {
38268
38356
  init_bot();
38269
38357
  init_bot_fs();
38270
38358
  DEFAULT_BOT_LEASE_ROOT = join10(homedir7(), ".config", "kk", "browser-leases");
38271
- NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket"];
38359
+ NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
38272
38360
  });
38273
38361
 
38274
38362
  // ../../packages/publish-harness/src/bot.ts
@@ -38845,6 +38933,27 @@ __export(exports_browser, {
38845
38933
  import { join as join13, resolve as resolve13 } from "path";
38846
38934
  import { createInterface } from "readline";
38847
38935
  import { parseArgs } from "util";
38936
+ function isInstantBrowserDeath(message) {
38937
+ return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
38938
+ }
38939
+ function classifyLaunchError(error, profileDir, channel) {
38940
+ const message = errorMessage2(error);
38941
+ if (/singleton|already in use|in use by another/i.test(message))
38942
+ return new BrowserProfileBusyError(profileDir, error);
38943
+ if (/playwright install|executable doesn't exist/i.test(message)) {
38944
+ return new PlaywrightUnavailableError(`Browser channel '${channel}' is not installed. Run \`bunx playwright install chromium\` (or install Google Chrome for KK_BROWSER_CHANNEL=chrome).`, { cause: error });
38945
+ }
38946
+ if (isInstantBrowserDeath(message)) {
38947
+ return new PlaywrightUnavailableError(`browser profile ${profileDir} makes Chromium exit during startup (no diagnostic reported). Move it aside (\`mv ${profileDir} ${profileDir}.broken-<date>\`) and log in again; \`storage-state.json\` is the only state worth keeping.`, { cause: error });
38948
+ }
38949
+ return error instanceof Error ? error : new Error(message);
38950
+ }
38951
+ function quarantineProfileSyncData(profileDir) {
38952
+ const syncData = join13(profileDir, "Default", "Sync Data");
38953
+ if (lstat(syncData) === null)
38954
+ return false;
38955
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
38956
+ }
38848
38957
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
38849
38958
  return {
38850
38959
  async launch(request) {
@@ -38873,23 +38982,25 @@ async function launchKkContext(loadPlaywright, profileDir, headless) {
38873
38982
  throw new PlaywrightUnavailableError('The "playwright" dependency is not installed. Run `bunx playwright install chromium`.', { cause: error });
38874
38983
  }
38875
38984
  const channel = process.env.KK_BROWSER_CHANNEL?.trim() || "chromium";
38985
+ const launch = () => playwright.chromium.launchPersistentContext(profileDir, {
38986
+ headless,
38987
+ channel,
38988
+ args: ["--disable-blink-features=AutomationControlled"],
38989
+ ignoreDefaultArgs: ["--enable-automation"]
38990
+ });
38876
38991
  let context;
38877
38992
  try {
38878
- context = await playwright.chromium.launchPersistentContext(profileDir, {
38879
- headless,
38880
- channel,
38881
- args: ["--disable-blink-features=AutomationControlled"],
38882
- ignoreDefaultArgs: ["--enable-automation"]
38883
- });
38993
+ context = await launch();
38884
38994
  } catch (error) {
38885
- const message = errorMessage2(error);
38886
- if (/singleton|already in use|in use by another/i.test(message)) {
38887
- throw new BrowserProfileBusyError(profileDir, error);
38888
- }
38889
- if (/playwright install|executable doesn't exist/i.test(message)) {
38890
- throw new PlaywrightUnavailableError(`Browser channel '${channel}' is not installed. Run \`bunx playwright install chromium\` (or install Google Chrome for KK_BROWSER_CHANNEL=chrome).`, { cause: error });
38995
+ if (!isInstantBrowserDeath(errorMessage2(error)))
38996
+ throw classifyLaunchError(error, profileDir, channel);
38997
+ if (!quarantineProfileSyncData(profileDir))
38998
+ throw classifyLaunchError(error, profileDir, channel);
38999
+ try {
39000
+ context = await launch();
39001
+ } catch (retryError) {
39002
+ throw classifyLaunchError(retryError, profileDir, channel);
38891
39003
  }
38892
- throw error;
38893
39004
  }
38894
39005
  try {
38895
39006
  await context.addInitScript(() => {
@@ -39045,6 +39156,7 @@ async function runProfileCli(config, argv = process.argv.slice(2), deps = {}) {
39045
39156
  if (command === "login") {
39046
39157
  const loginTimeoutMs = timeoutMs ?? config.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS;
39047
39158
  const launcher = deps.launcher ?? kkBrowserLauncher;
39159
+ stdout(`${config.channel} profile login: a browser window is opening \u2014 sign in there; waiting up to ${Math.round(loginTimeoutMs / 1000)}s for the signed-in state`);
39048
39160
  try {
39049
39161
  if (url === undefined) {
39050
39162
  await loginWithProfile({
@@ -39281,6 +39393,7 @@ async function loginBot(name, url, options = {}) {
39281
39393
  context = await launcher.launch({ profileDir: transaction.stageDir, headless: false });
39282
39394
  const page = await openBotPage(context);
39283
39395
  await navigateBot(page, navigationUrl);
39396
+ await focusBotPage(page);
39284
39397
  const confirm = options.confirm ?? confirmBotLogin;
39285
39398
  if (!await confirm(options.timeoutMs ?? DEFAULT_BOT_LOGIN_TIMEOUT_MS)) {
39286
39399
  throw new BotError("unconfirmed", `login for bot '${name}' was not confirmed \u2014 nothing was saved and the previous profile is unchanged`);
@@ -39433,6 +39546,7 @@ async function openBot(name, options = {}) {
39433
39546
  });
39434
39547
  const page = await openBotPage(context);
39435
39548
  await navigateBot(page, openUrl);
39549
+ await focusBotPage(page);
39436
39550
  await closed;
39437
39551
  return {
39438
39552
  name,
@@ -39539,6 +39653,14 @@ async function navigateBot(page, url) {
39539
39653
  throw new BotError("browser", `could not open the supplied login URL (${redactNavigationError(error, url)})`);
39540
39654
  }
39541
39655
  }
39656
+ async function focusBotPage(page) {
39657
+ const target = page;
39658
+ if (typeof target.bringToFront !== "function")
39659
+ return;
39660
+ await target.bringToFront().catch(() => {
39661
+ return;
39662
+ });
39663
+ }
39542
39664
  function redactNavigationError(error, url) {
39543
39665
  let detail = error instanceof Error ? error.message : String(error);
39544
39666
  detail = detail.split(url).join("<login-url>");
@@ -39565,7 +39687,7 @@ async function confirmBotLogin(timeoutMs) {
39565
39687
  if (process.stdin.isTTY !== true) {
39566
39688
  throw new BotError("unconfirmed", "no interactive terminal is available \u2014 a generic login needs an affirmative confirmation (site adapters are the non-interactive route)");
39567
39689
  }
39568
- echo(`Sign in to the opened browser window, then type y + Enter within ${Math.round(timeoutMs / 1000)}s to save this bot session (anything else cancels).`);
39690
+ echo(`Sign in to the browser window that just came to the front (click into its email field first if the window lost focus), then type y + Enter within ${Math.round(timeoutMs / 1000)}s to save this bot session (anything else cancels).`);
39569
39691
  return await new Promise((resolve, reject) => {
39570
39692
  const reader = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
39571
39693
  let settled = false;
@@ -42444,7 +42566,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
42444
42566
  shortVideo: Object.freeze({
42445
42567
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
42446
42568
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
42447
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
42569
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
42448
42570
  })
42449
42571
  })
42450
42572
  });
@@ -51379,10 +51501,12 @@ function slugifyTopicName(name) {
51379
51501
  return slug;
51380
51502
  }
51381
51503
  function expandHome3(value, homeDir) {
51382
- if (value === "~")
51504
+ if (value === "~" || value === "$HOME")
51383
51505
  return homeDir;
51384
51506
  if (value.startsWith("~/"))
51385
51507
  return join20(homeDir, value.slice(2));
51508
+ if (value.startsWith("$HOME/"))
51509
+ return join20(homeDir, value.slice("$HOME/".length));
51386
51510
  return value;
51387
51511
  }
51388
51512
  function canonicalJson(value) {
@@ -51813,7 +51937,7 @@ var PublishPresetTargetSchema = object2({
51813
51937
  variant: string2().min(1).optional(),
51814
51938
  tier: number2().int().min(0).max(3).optional(),
51815
51939
  window: PublishWindowSchema.optional(),
51816
- mode: _enum2(["off", "dummy", "draft"]).optional(),
51940
+ mode: _enum2(["off", "dummy", "draft", "live"]).optional(),
51817
51941
  required: boolean2().optional(),
51818
51942
  options: record(string2(), unknown()).optional()
51819
51943
  }).strict();
@@ -51836,15 +51960,7 @@ var ItcPlanRequestSchema = object2({
51836
51960
  });
51837
51961
  var SLUG_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
51838
51962
  async function resolveDefaultPackageRoot(fs) {
51839
- let dir = resolve21(process.cwd());
51840
- for (;; ) {
51841
- if (await fs.exists(join21(dir, "plugins/kk/publish-presets")))
51842
- return dir;
51843
- const parent = resolve21(dir, "..");
51844
- if (parent === dir)
51845
- return process.cwd();
51846
- dir = parent;
51847
- }
51963
+ return resolvePackageRoot(fs);
51848
51964
  }
51849
51965
  function parseTargetTokens(raw) {
51850
51966
  const tokens = raw.split(",").map((t) => t.trim()).filter(Boolean);
@@ -52043,6 +52159,7 @@ async function buildItcPublishPlan(request, plugins, fs = createNodeFileSystem()
52043
52159
  const fanoutMap = new Map;
52044
52160
  const browser = [];
52045
52161
  const targetDetails = [];
52162
+ const warnings = [];
52046
52163
  for (const targetReq of uniqueTargets) {
52047
52164
  const plugin = pluginsByName.get(targetReq.plugin);
52048
52165
  if (!plugin?.publishing) {
@@ -52062,7 +52179,8 @@ async function buildItcPublishPlan(request, plugins, fs = createNodeFileSystem()
52062
52179
  throw new Error(`target ${targetReq.plugin} has no draft mode; it needs publish_live=true`);
52063
52180
  }
52064
52181
  if (profile.requires?.cover && !hasCover) {
52065
- throw new Error(`target ${targetReq.plugin} needs a cover image at 4-illustrations/cover.* in ${request.workDir}`);
52182
+ warnings.push(`skipped ${targetReq.plugin}: needs a cover image at 4-illustrations/cover.* in ${request.workDir}`);
52183
+ continue;
52066
52184
  }
52067
52185
  if (profile.requires?.orderedImages && !await hasOrderedImages(fs, request.workDir)) {
52068
52186
  throw new Error(`target ${targetReq.plugin} requires ordered metadata.images with real paths; a hero cover alone does not satisfy that requirement`);
@@ -52111,6 +52229,7 @@ async function buildItcPublishPlan(request, plugins, fs = createNodeFileSystem()
52111
52229
  ...request.origin !== undefined ? { origin: request.origin } : {},
52112
52230
  ...request.presetName !== undefined ? { presetName: request.presetName } : {},
52113
52231
  ...request.presetDigest !== undefined ? { presetDigest: request.presetDigest } : {},
52232
+ ...warnings.length > 0 ? { warnings } : {},
52114
52233
  live: request.live,
52115
52234
  sourceLocale: request.sourceLocale,
52116
52235
  variants,
@@ -52305,6 +52424,8 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
52305
52424
  const planPath = join22(publishDir, "publish-plan.json");
52306
52425
  await fs.writeFile(planPath, `${JSON.stringify(plan, null, 2)}
52307
52426
  `);
52427
+ for (const warning of plan.warnings ?? [])
52428
+ echoError(`itc-materialize-plan: ${warning}`);
52308
52429
  await prepareTargetPayloads(fs, workDir, plan, plugins);
52309
52430
  return 0;
52310
52431
  } catch (err) {
@@ -52321,7 +52442,7 @@ async function readOptionsSnapshot(fs, workDir) {
52321
52442
  async function prepareTargetPayloads(fs, workDir, plan, plugins) {
52322
52443
  const publishDir = join22(workDir, "4-publish");
52323
52444
  if (!plan.targets || plan.targets.length === 0)
52324
- return;
52445
+ return plan;
52325
52446
  const planned = new Set(plan.targets.map((t) => t.plugin));
52326
52447
  const modeKeys = new Set(["operation", "published", "publishStatus", "private", "mode"]);
52327
52448
  for (const plugin of plugins) {
@@ -52334,8 +52455,10 @@ async function prepareTargetPayloads(fs, workDir, plan, plugins) {
52334
52455
  }
52335
52456
  }
52336
52457
  }
52458
+ const variants = plan.variants ?? {};
52459
+ let written = false;
52337
52460
  for (const target of plan.targets) {
52338
- const variantEntry = plan.variants[target.variant];
52461
+ const variantEntry = variants[target.variant];
52339
52462
  const baseFile = variantEntry?.file ?? "content.json";
52340
52463
  let basePath = join22(publishDir, baseFile);
52341
52464
  if (!await fs.exists(basePath)) {
@@ -52363,9 +52486,13 @@ async function prepareTargetPayloads(fs, workDir, plan, plugins) {
52363
52486
  const payloadDigest = createHash6("sha256").update(contentStr).digest("hex");
52364
52487
  target.payloadPath = `4-publish/${targetFileName}`;
52365
52488
  target.payloadDigest = payloadDigest;
52489
+ written = true;
52366
52490
  }
52367
- await fs.writeFile(join22(publishDir, "publish-plan.json"), `${JSON.stringify(plan, null, 2)}
52491
+ if (written) {
52492
+ await fs.writeFile(join22(publishDir, "publish-plan.json"), `${JSON.stringify(plan, null, 2)}
52368
52493
  `);
52494
+ }
52495
+ return plan;
52369
52496
  }
52370
52497
  async function probePlugin(plugin, executor = new NodeProcessExecutor) {
52371
52498
  if (!plugin.check)
@@ -52402,22 +52529,43 @@ async function itcCheckTargets(args, fs = createNodeFileSystem(), executor = new
52402
52529
  const planPath = join22(workDir, "4-publish/publish-plan.json");
52403
52530
  if (!await fs.exists(planPath))
52404
52531
  return 0;
52405
- const plan = JSON.parse(await fs.readFile(planPath));
52532
+ let plan;
52533
+ try {
52534
+ plan = JSON.parse(await fs.readFile(planPath));
52535
+ } catch (error) {
52536
+ echoError(`itc-check-targets: unreadable plan at ${planPath}: ${error instanceof Error ? error.message : String(error)}`);
52537
+ return 1;
52538
+ }
52406
52539
  if (!plan.targets || plan.targets.length === 0)
52407
52540
  return 0;
52408
52541
  const { plugins } = discoverAllPlugins();
52409
52542
  const byName = new Map(plugins.map((p) => [p.name, p]));
52543
+ const probes = [];
52410
52544
  for (const target of plan.targets) {
52545
+ if (probes.some((row) => row.plugin === target.plugin))
52546
+ continue;
52411
52547
  const plugin = byName.get(target.plugin);
52412
- if (!plugin?.check)
52548
+ if (plugin === undefined) {
52549
+ probes.push({ plugin: target.plugin, ok: false, detail: "plugin not installed" });
52550
+ continue;
52551
+ }
52552
+ if (!plugin.check)
52413
52553
  continue;
52414
52554
  const probe = await probePlugin(plugin, executor);
52555
+ probes.push({ plugin: target.plugin, ok: probe.ok, ...probe.detail ? { detail: probe.detail } : {} });
52415
52556
  if (!probe.ok) {
52416
52557
  const botName = plugin.browserSession?.profileName ?? plugin.name;
52417
- echoError(probe.detail ? `channel probe for '${target.plugin}' refused: ${probe.detail}` : `channel probe for '${target.plugin}' refused: run \`kk bot open/login ${botName}\` to authenticate`);
52418
- return 1;
52558
+ echoError(`channel probe for '${target.plugin}': ${probe.detail ?? `run \`kk bot open/login ${botName}\` to authenticate`}`);
52419
52559
  }
52420
52560
  }
52561
+ try {
52562
+ await fs.ensureDir(join22(workDir, "4-publish"));
52563
+ await fs.writeFile(join22(workDir, "4-publish/check-targets.json"), `${JSON.stringify({ schemaVersion: 1, plugins: probes }, null, 2)}
52564
+ `);
52565
+ } catch (error) {
52566
+ echoError(`itc-check-targets: cannot write probes: ${error instanceof Error ? error.message : String(error)}`);
52567
+ return 1;
52568
+ }
52421
52569
  return 0;
52422
52570
  }
52423
52571
  async function sendRows(options) {
@@ -52619,7 +52767,7 @@ async function itcSendTargets(args, fs = createNodeFileSystem(), dispatch = runF
52619
52767
  const planPath = join22(publishDir, "publish-plan.json");
52620
52768
  if (!await fs.exists(planPath))
52621
52769
  return 0;
52622
- const plan = JSON.parse(await fs.readFile(planPath));
52770
+ let plan = JSON.parse(await fs.readFile(planPath));
52623
52771
  if (!plan.targets || plan.targets.length === 0)
52624
52772
  return 0;
52625
52773
  const parentRunId = (await readOptionsSnapshot(fs, workDir))?.parentRunId;
@@ -52627,11 +52775,22 @@ async function itcSendTargets(args, fs = createNodeFileSystem(), dispatch = runF
52627
52775
  echoError(`itc-send-targets: ${join22(workDir, "itc-options.json")} has no parentRunId`);
52628
52776
  return 1;
52629
52777
  }
52778
+ const { plugins } = discoverAllPlugins();
52779
+ plan = await prepareTargetPayloads(fs, workDir, plan, plugins);
52780
+ const targets = plan.targets ?? [];
52781
+ for (const target of targets) {
52782
+ const entry = plan.variants?.[target.variant];
52783
+ if (entry?.adapt !== true)
52784
+ continue;
52785
+ if (await fs.exists(join22(publishDir, entry.file)))
52786
+ continue;
52787
+ echoError(`itc-send-targets: variant ${target.variant} has no ${entry.file}; '${target.plugin}' receives the ${plan.sourceLocale} source article`);
52788
+ }
52630
52789
  const receiptsDir = join22(publishDir, "receipts");
52631
52790
  await fs.ensureDir(receiptsDir);
52632
52791
  const planRaw = await fs.readFile(planPath);
52633
52792
  const planDigest = createHash6("sha256").update(planRaw).digest("hex");
52634
- const rows = plan.targets.map((target) => ({
52793
+ const rows = targets.map((target) => ({
52635
52794
  key: target.plugin,
52636
52795
  plugin: target.plugin,
52637
52796
  profile: target.profile,
@@ -52985,6 +53144,8 @@ async function runItcPublishPlan(args, fs) {
52985
53144
  await fs.ensureDir(outDir);
52986
53145
  await fs.writeFile(join23(outDir, "publish-plan.json"), `${JSON.stringify(plan, null, 4)}
52987
53146
  `);
53147
+ for (const warning of plan.warnings ?? [])
53148
+ echoError(`itc-publish-plan: ${warning}`);
52988
53149
  return 0;
52989
53150
  } catch (err) {
52990
53151
  const msg = err instanceof Error ? err.message : String(err);
@@ -53519,7 +53680,7 @@ async function composePlan(fs, input) {
53519
53680
  if (liveToken !== undefined && target.mode === "dummy") {
53520
53681
  throw new Error(`channel '${liveToken}' is dummy-only and cannot be promoted to live`);
53521
53682
  }
53522
- const mode = input.dummy ? "dummy" : liveToken !== undefined ? "live" : target.mode === "dummy" ? "dummy" : "draft";
53683
+ const mode = input.dummy ? "dummy" : liveToken !== undefined || target.mode === "live" ? "live" : target.mode === "dummy" ? "dummy" : "draft";
53523
53684
  if (mode === "live" && safety === undefined) {
53524
53685
  throw new Error(`bundle has no final-variant safety evidence; run the variants safety gate (kk-daily-safety scope=variants) before a live launch`);
53525
53686
  }
@@ -54090,6 +54251,10 @@ async function sendPublishMatrix(args, deps = {}) {
54090
54251
  }
54091
54252
  }
54092
54253
  try {
54254
+ if (retry && !await fs.exists(join24(workDir, "4-publish", `plan.${parsedWindow.data}.json`))) {
54255
+ echo(`publish-matrix-send: no plan for window '${parsedWindow.data}' \u2014 nothing was planned, nothing to resend`);
54256
+ return 0;
54257
+ }
54093
54258
  const plan = await readPlan(fs, workDir, parsedWindow.data);
54094
54259
  const publishDir = join24(workDir, "4-publish");
54095
54260
  const receiptsDir = join24(publishDir, "receipts");
@@ -55614,6 +55779,1565 @@ function registerStoreCommand(program) {
55614
55779
  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
55780
  }
55616
55781
 
55782
+ // src/commands/wiki.ts
55783
+ init_commander();
55784
+ init_output2();
55785
+
55786
+ // src/wiki/ingest.ts
55787
+ import { extname, isAbsolute as isAbsolute13, join as join33 } from "path";
55788
+
55789
+ // ../../packages/kk-wiki/src/compile.ts
55790
+ function oneLineSummary(body) {
55791
+ for (const line of body.split(`
55792
+ `)) {
55793
+ const text = line.trim();
55794
+ if (text === "" || text.startsWith("#") || text.startsWith("---"))
55795
+ continue;
55796
+ return text.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2").slice(0, 120);
55797
+ }
55798
+ return "No summary yet.";
55799
+ }
55800
+ function groupByType(pages) {
55801
+ const groups = new Map;
55802
+ for (const page of [...pages].sort((a, b) => a.frontmatter.type.localeCompare(b.frontmatter.type) || a.slug.localeCompare(b.slug))) {
55803
+ const list = groups.get(page.frontmatter.type) ?? [];
55804
+ list.push(page);
55805
+ groups.set(page.frontmatter.type, list);
55806
+ }
55807
+ return groups;
55808
+ }
55809
+ function compileIndex(pages, options) {
55810
+ const groups = groupByType(pages);
55811
+ const indexLines = ["# Vault index", "", `Compiled ${options.date}. Do not edit by hand; run \`kk wiki compile\`.`];
55812
+ for (const [type, entries] of groups) {
55813
+ indexLines.push("", `## ${type}`, "");
55814
+ for (const page of entries) {
55815
+ indexLines.push(`- [[${page.slug}|${page.frontmatter.title}]] \u2014 ${oneLineSummary(page.body)}`);
55816
+ }
55817
+ }
55818
+ const mapLines = ["# MAP", "", "Routing table: page type and tags.", ""];
55819
+ for (const [type, entries] of groups) {
55820
+ mapLines.push(`## ${type}`, "");
55821
+ for (const page of entries) {
55822
+ const tags = page.frontmatter.tags.length > 0 ? page.frontmatter.tags.join(", ") : "\u2014";
55823
+ mapLines.push(`- ${page.path} \u2192 ${page.slug} (tags: ${tags})`);
55824
+ }
55825
+ }
55826
+ return { index: `${indexLines.join(`
55827
+ `)}
55828
+ `, map: `${mapLines.join(`
55829
+ `)}
55830
+ ` };
55831
+ }
55832
+ function needsWrite(current, rendered) {
55833
+ return current !== rendered;
55834
+ }
55835
+ // ../../packages/kk-wiki/src/page.ts
55836
+ init_zod();
55837
+ var PageTypeSchema = _enum2(["concept", "entity", "source", "index"]);
55838
+ var PageFrontmatterSchema = object2({
55839
+ title: string2().min(1),
55840
+ type: PageTypeSchema,
55841
+ tags: array(string2()).default([]),
55842
+ sources: array(string2()).default([]),
55843
+ updated_at: string2().min(1),
55844
+ user_edited: boolean2().optional(),
55845
+ redirect_to: string2().min(1).optional()
55846
+ });
55847
+
55848
+ class FrontmatterError extends Error {
55849
+ path;
55850
+ issues;
55851
+ constructor(path, issues) {
55852
+ super(`invalid frontmatter in ${path}: ${issues.join("; ")}`);
55853
+ this.path = path;
55854
+ this.issues = issues;
55855
+ this.name = "FrontmatterError";
55856
+ }
55857
+ }
55858
+ var FENCE = "---";
55859
+ function parseScalar(raw) {
55860
+ const trimmed = raw.trim();
55861
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
55862
+ return trimmed.slice(1, -1);
55863
+ }
55864
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) {
55865
+ return trimmed.slice(1, -1);
55866
+ }
55867
+ if (trimmed === "true")
55868
+ return true;
55869
+ if (trimmed === "false")
55870
+ return false;
55871
+ return trimmed;
55872
+ }
55873
+ function parseFrontmatter(raw) {
55874
+ const errors = [];
55875
+ const text = raw.replace(/^\uFEFF/, "");
55876
+ const lines = text.split(`
55877
+ `);
55878
+ if (lines[0]?.trim() !== FENCE) {
55879
+ return { data: {}, body: text, errors: ["missing-frontmatter"], bodyStartLine: 1 };
55880
+ }
55881
+ const close = lines.findIndex((line, index) => index > 0 && line.trim() === FENCE);
55882
+ if (close < 0) {
55883
+ return { data: {}, body: text, errors: ["unterminated-frontmatter"], bodyStartLine: 1 };
55884
+ }
55885
+ const data = {};
55886
+ let openArrayKey = null;
55887
+ for (const line of lines.slice(1, close)) {
55888
+ if (line.trim() === "")
55889
+ continue;
55890
+ const item = /^\s+-\s+(.*)$/.exec(line);
55891
+ if (item !== null) {
55892
+ if (openArrayKey === null) {
55893
+ errors.push(`array item without a key: ${line.trim()}`);
55894
+ continue;
55895
+ }
55896
+ const list = data[openArrayKey];
55897
+ if (Array.isArray(list))
55898
+ list.push(String(parseScalar(item[1] ?? "")));
55899
+ continue;
55900
+ }
55901
+ const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line);
55902
+ if (pair === null) {
55903
+ errors.push(`unsupported frontmatter line (nested or malformed): ${line.trim()}`);
55904
+ continue;
55905
+ }
55906
+ const key = pair[1] ?? "";
55907
+ const value = (pair[2] ?? "").trim();
55908
+ openArrayKey = value === "" ? key : null;
55909
+ if (value === "" || value === "[]") {
55910
+ data[key] = [];
55911
+ continue;
55912
+ }
55913
+ data[key] = parseScalar(value);
55914
+ }
55915
+ const rest = lines.slice(close + 1);
55916
+ const leadingBlank = rest[0] === "" ? 1 : 0;
55917
+ return {
55918
+ data,
55919
+ body: rest.join(`
55920
+ `).replace(/^\n/, ""),
55921
+ errors,
55922
+ bodyStartLine: close + 2 + leadingBlank
55923
+ };
55924
+ }
55925
+ function parsePage(text, path) {
55926
+ const parsed = parseFrontmatter(text);
55927
+ const result = PageFrontmatterSchema.safeParse(parsed.data);
55928
+ if (!result.success) {
55929
+ const issues = parsed.errors.concat(result.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`));
55930
+ throw new FrontmatterError(path, issues);
55931
+ }
55932
+ return { path, frontmatter: result.data, body: parsed.body };
55933
+ }
55934
+ function renderValue(value) {
55935
+ if (typeof value === "boolean")
55936
+ return value ? "true" : "false";
55937
+ if (value === "" || /[:#\n]/.test(value) || value.trim() !== value)
55938
+ return `"${value.replace(/"/g, "\\\"")}"`;
55939
+ return value;
55940
+ }
55941
+ function renderPage(page) {
55942
+ const fm = page.frontmatter;
55943
+ const lines = [FENCE, `title: ${renderValue(fm.title)}`, `type: ${fm.type}`];
55944
+ if (fm.tags.length === 0) {
55945
+ lines.push("tags: []");
55946
+ } else {
55947
+ lines.push("tags:", ...fm.tags.map((tag) => ` - ${renderValue(tag)}`));
55948
+ }
55949
+ if (fm.sources.length === 0) {
55950
+ lines.push("sources: []");
55951
+ } else {
55952
+ lines.push("sources:", ...fm.sources.map((source) => ` - ${renderValue(source)}`));
55953
+ }
55954
+ lines.push(`updated_at: ${renderValue(fm.updated_at)}`);
55955
+ if (fm.user_edited === true)
55956
+ lines.push("user_edited: true");
55957
+ if (fm.redirect_to !== undefined)
55958
+ lines.push(`redirect_to: ${renderValue(fm.redirect_to)}`);
55959
+ lines.push(FENCE, "");
55960
+ return `${lines.join(`
55961
+ `)}
55962
+ ${page.body.replace(/\s+$/, "")}
55963
+ `;
55964
+ }
55965
+ function resolveSlug(title) {
55966
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
55967
+ }
55968
+
55969
+ // ../../packages/kk-wiki/src/context.ts
55970
+ function packContext(index, topic, options = {}) {
55971
+ const slug = resolveSlug(topic);
55972
+ const topicPage = index.bySlug.get(slug) ?? index.pages.find((page) => page.path === topic);
55973
+ if (topicPage === undefined)
55974
+ return { markdown: "", pages: [] };
55975
+ const included = [topicPage];
55976
+ 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)));
55977
+ for (const page of neighbours.slice(0, Math.max(0, options.depth ?? 1) === 0 ? 0 : neighbours.length)) {
55978
+ included.push(page);
55979
+ }
55980
+ const markdown = included.map((page) => `## ${page.path}
55981
+
55982
+ ${page.body.trim()}
55983
+ `).join(`
55984
+ `).trimEnd();
55985
+ return { markdown: `${markdown}
55986
+ `, pages: included.map((page) => page.path) };
55987
+ }
55988
+ // ../../packages/kk-wiki/src/gc.ts
55989
+ import { dirname as dirname15, isAbsolute as isAbsolute9, join as join27 } from "path";
55990
+ async function planGc(index, options) {
55991
+ const fs = options.fileSystem;
55992
+ const root = dirname15(options.rawDir);
55993
+ const mirrorPaths = (options.mirrors ?? []).map((mirror) => isAbsolute9(mirror) ? mirror : join27(root, mirror));
55994
+ const referenced = new Set;
55995
+ for (const page of index.pages) {
55996
+ for (const source of page.frontmatter.sources)
55997
+ referenced.add(source.trim());
55998
+ }
55999
+ const candidates = [];
56000
+ for (const type of ["url", "pdf", "html", "rss"]) {
56001
+ const dir = join27(options.rawDir, type);
56002
+ if (!await fs.exists(dir))
56003
+ continue;
56004
+ for (const name of await fs.readDir(dir))
56005
+ candidates.push(join27(dir, name));
56006
+ }
56007
+ const tmpDir = join27(options.rawDir, "tmp");
56008
+ if (await fs.exists(tmpDir)) {
56009
+ for (const name of await fs.readDir(tmpDir))
56010
+ candidates.push(join27(tmpDir, name));
56011
+ }
56012
+ const skippedMirrors = (options.mirrors ?? []).filter((_, index) => {
56013
+ const path = mirrorPaths[index];
56014
+ return path !== undefined && fs.exists(path);
56015
+ });
56016
+ const plan = { delete: [], keep: [], skippedMirrors };
56017
+ for (const path of candidates) {
56018
+ if (mirrorPaths.some((mirror) => path.startsWith(mirror)))
56019
+ continue;
56020
+ const snapshotId = path.split("/").pop()?.replace(/\.md$/, "") ?? path;
56021
+ if (referenced.has(snapshotId) || referenced.has(path))
56022
+ plan.keep.push(path);
56023
+ else
56024
+ plan.delete.push(path);
56025
+ }
56026
+ plan.delete.sort();
56027
+ plan.keep.sort();
56028
+ return plan;
56029
+ }
56030
+ async function applyGc(plan, fileSystem) {
56031
+ for (const path of plan.delete)
56032
+ await fileSystem.deleteFile(path);
56033
+ return { deleted: [...plan.delete] };
56034
+ }
56035
+ // ../../packages/kk-wiki/src/graph.ts
56036
+ init_dist3();
56037
+ import { relative as relative3 } from "path";
56038
+ function scanLines(body) {
56039
+ const result = [];
56040
+ let inFence = false;
56041
+ body.split(`
56042
+ `).forEach((raw, index) => {
56043
+ const isFence = /^\s*(```|~~~)/.test(raw);
56044
+ if (isFence)
56045
+ inFence = !inFence;
56046
+ const masked = raw.replace(/`[^`]*`/g, (span) => " ".repeat(span.length));
56047
+ result.push({ line: index + 1, text: masked, inFence: isFence ? true : inFence });
56048
+ });
56049
+ return result;
56050
+ }
56051
+ function extractLinks(body) {
56052
+ const links = [];
56053
+ for (const scanned of scanLines(body)) {
56054
+ if (scanned.inFence)
56055
+ continue;
56056
+ const pattern = /\[\[([^\]|]+?)(?:\|([^\]]+))?\]\]/g;
56057
+ for (const match of scanned.text.matchAll(pattern)) {
56058
+ links.push({
56059
+ target: (match[1] ?? "").trim(),
56060
+ surface: match[2] === undefined ? null : match[2].trim(),
56061
+ line: scanned.line
56062
+ });
56063
+ }
56064
+ }
56065
+ return links;
56066
+ }
56067
+ function pageSlug(title) {
56068
+ return resolveSlug(title);
56069
+ }
56070
+ async function listMarkdown(dir, fs) {
56071
+ const files = await walkDir(dir, fs);
56072
+ return files.filter((file) => file.endsWith(".md")).sort();
56073
+ }
56074
+ function duplicateSlugFindings(pages) {
56075
+ const seen = new Map;
56076
+ for (const page of pages) {
56077
+ const paths = seen.get(page.slug) ?? [];
56078
+ paths.push(page.path);
56079
+ seen.set(page.slug, paths);
56080
+ }
56081
+ const findings = [];
56082
+ for (const [slug, paths] of seen) {
56083
+ if (paths.length < 2)
56084
+ continue;
56085
+ for (const path of paths) {
56086
+ findings.push({
56087
+ code: "duplicate-slug",
56088
+ path,
56089
+ line: 1,
56090
+ message: `slug '${slug}' is shared by ${paths.length} pages`
56091
+ });
56092
+ }
56093
+ }
56094
+ return findings;
56095
+ }
56096
+ async function buildVaultIndex(contentDir, fileSystem = createNodeFileSystem()) {
56097
+ const pages = [];
56098
+ const findings = [];
56099
+ for (const file of await listMarkdown(contentDir, fileSystem)) {
56100
+ const path = relative3(contentDir, file);
56101
+ const text = await fileSystem.readFile(file);
56102
+ const parsed = parseFrontmatter(text);
56103
+ const validated = PageFrontmatterSchema.safeParse(parsed.data);
56104
+ if (!validated.success) {
56105
+ const code = parsed.errors.includes("missing-frontmatter") ? "missing-frontmatter" : "invalid-frontmatter";
56106
+ findings.push({
56107
+ code,
56108
+ path,
56109
+ line: 1,
56110
+ message: parsed.errors[0] ?? validated.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`).join("; ")
56111
+ });
56112
+ continue;
56113
+ }
56114
+ const page = {
56115
+ path,
56116
+ slug: pageSlug(validated.data.title),
56117
+ frontmatter: validated.data,
56118
+ body: parsed.body,
56119
+ bodyStartLine: parsed.bodyStartLine,
56120
+ links: extractLinks(parsed.body).map((link) => ({
56121
+ ...link,
56122
+ line: link.line + parsed.bodyStartLine - 1
56123
+ })),
56124
+ inbound: 0
56125
+ };
56126
+ pages.push(page);
56127
+ }
56128
+ const bySlug = new Map;
56129
+ for (const page of pages)
56130
+ bySlug.set(page.slug, page);
56131
+ for (const page of pages) {
56132
+ for (const link of page.links) {
56133
+ const target = bySlug.get(resolveSlug(link.target));
56134
+ if (target !== undefined && target !== page)
56135
+ target.inbound += 1;
56136
+ }
56137
+ }
56138
+ findings.push(...duplicateSlugFindings(pages));
56139
+ return { contentDir, pages, bySlug, findings };
56140
+ }
56141
+ function resolveLink(index, link) {
56142
+ return index.bySlug.get(resolveSlug(link.target));
56143
+ }
56144
+ // ../../packages/kk-wiki/src/link.ts
56145
+ init_dist3();
56146
+ import { join as join28 } from "path";
56147
+
56148
+ // ../../packages/kk-wiki/src/write.ts
56149
+ function guardHeading(date) {
56150
+ return `## AI Updates (${date})`;
56151
+ }
56152
+ function appendGuarded(body, material, date) {
56153
+ const heading = guardHeading(date);
56154
+ const trimmed = material.replace(/\s+$/, "");
56155
+ const lines = body.replace(/\s+$/, "").split(`
56156
+ `);
56157
+ const headingIndex = lines.findIndex((line) => line.trim() === heading);
56158
+ if (headingIndex === -1)
56159
+ return `${lines.join(`
56160
+ `)}
56161
+
56162
+ ${heading}
56163
+
56164
+ ${trimmed}
56165
+ `;
56166
+ const nextHeading = lines.findIndex((line, index) => index > headingIndex && /^##\s+/.test(line));
56167
+ const insertAt = nextHeading === -1 ? lines.length : nextHeading;
56168
+ const head = lines.slice(0, insertAt);
56169
+ while (head.length > 0 && (head[head.length - 1] ?? "").trim() === "")
56170
+ head.pop();
56171
+ return `${[...head, "", trimmed].join(`
56172
+ `)}
56173
+ ${lines.slice(insertAt).join(`
56174
+ `)}`.replace(/\n{3,}/g, `
56175
+
56176
+ `);
56177
+ }
56178
+ function applyWrite(page, material, options) {
56179
+ const guarded = page.frontmatter.user_edited === true;
56180
+ if (guarded)
56181
+ return { body: appendGuarded(page.body, material, options.date), guard: "appended" };
56182
+ if (options.mode === "append")
56183
+ return { body: appendGuarded(page.body, material, options.date), guard: "clean" };
56184
+ return { body: `${material.replace(/\s+$/, "")}
56185
+ `, guard: "clean" };
56186
+ }
56187
+ function applyWriteToPage(page, material, options) {
56188
+ const result = applyWrite(page, material, options);
56189
+ const text = renderPage({
56190
+ ...page,
56191
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56192
+ body: result.body
56193
+ });
56194
+ return { text, guard: result.guard };
56195
+ }
56196
+
56197
+ // ../../packages/kk-wiki/src/link.ts
56198
+ function escapeRegExp(value) {
56199
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
56200
+ }
56201
+ function findMentions(index) {
56202
+ const mentions = [];
56203
+ const titles = index.pages.map((page) => ({ page, title: page.frontmatter.title.trim() })).filter((entry) => entry.title.length >= 3);
56204
+ for (const page of index.pages) {
56205
+ const linked = new Set(page.links.map((link) => link.target.toLowerCase()));
56206
+ for (const scanned of scanLines(page.body)) {
56207
+ if (scanned.inFence)
56208
+ continue;
56209
+ const masked = scanned.text.replace(/\[\[[^\]]*\]\]/g, (span) => " ".repeat(span.length));
56210
+ for (const { page: target, title } of titles) {
56211
+ if (target.slug === page.slug || linked.has(target.slug) || linked.has(title.toLowerCase()))
56212
+ continue;
56213
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56214
+ const hit = pattern.exec(masked);
56215
+ if (hit === null)
56216
+ continue;
56217
+ mentions.push({
56218
+ path: page.path,
56219
+ line: scanned.line + page.bodyStartLine - 1,
56220
+ slug: target.slug,
56221
+ surface: title,
56222
+ text: title
56223
+ });
56224
+ break;
56225
+ }
56226
+ }
56227
+ }
56228
+ return mentions;
56229
+ }
56230
+ function rewriteBody(body, pageMentions, lineOffset) {
56231
+ const lines = body.split(`
56232
+ `);
56233
+ for (const mention of pageMentions) {
56234
+ const index = mention.line - lineOffset;
56235
+ const line = lines[index];
56236
+ if (line === undefined)
56237
+ continue;
56238
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(mention.text)}(?![\\w\\]])`, "i");
56239
+ lines[index] = line.replace(pattern, `[[${mention.slug}|${mention.surface}]]`);
56240
+ }
56241
+ return lines.join(`
56242
+ `);
56243
+ }
56244
+ async function fixLinks(index, options = { date: "" }) {
56245
+ const fs = options.fileSystem ?? createNodeFileSystem();
56246
+ const contentDir = options.contentDir ?? index.contentDir;
56247
+ const mentions = findMentions(index);
56248
+ const grouped = new Map;
56249
+ for (const mention of mentions) {
56250
+ const list = grouped.get(mention.path) ?? [];
56251
+ list.push(mention);
56252
+ grouped.set(mention.path, list);
56253
+ }
56254
+ const changed = [];
56255
+ const refused = [];
56256
+ for (const [path, pageMentions] of grouped) {
56257
+ const raw = await fs.readFile(join28(contentDir, path));
56258
+ const page = parsePage(raw, path);
56259
+ const rewritten = rewriteBody(page.body, pageMentions, parseFrontmatter(raw).bodyStartLine);
56260
+ const { text, guard } = applyWriteToPage(page, rewritten, {
56261
+ mode: "full",
56262
+ date: options.date
56263
+ });
56264
+ if (options.dryRun === true) {
56265
+ changed.push(path);
56266
+ continue;
56267
+ }
56268
+ await fs.writeFile(join28(contentDir, path), text);
56269
+ if (guard === "appended")
56270
+ refused.push(path);
56271
+ else
56272
+ changed.push(path);
56273
+ }
56274
+ return { changed, refused, mentions };
56275
+ }
56276
+ function linkTitlesInText(index, text) {
56277
+ let linked = text;
56278
+ 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);
56279
+ for (const { slug, title } of titles) {
56280
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56281
+ linked = linked.replace(pattern, `[[${slug}|${title}]]`);
56282
+ }
56283
+ return linked;
56284
+ }
56285
+ // ../../packages/kk-wiki/src/lint.ts
56286
+ var ORPHAN_EXEMPT_FILES = new Set(["index.md", "MAP.md"]);
56287
+ function lintPages(index) {
56288
+ const findings = [...index.findings];
56289
+ for (const page of index.pages) {
56290
+ for (const link of page.links) {
56291
+ if (resolveLink(index, link) !== undefined)
56292
+ continue;
56293
+ findings.push({
56294
+ code: "broken-link",
56295
+ path: page.path,
56296
+ line: link.line,
56297
+ message: `[[${link.target}]] resolves to no page`
56298
+ });
56299
+ }
56300
+ const basename = page.path.split("/").pop() ?? page.path;
56301
+ if (page.inbound === 0 && !ORPHAN_EXEMPT_FILES.has(basename)) {
56302
+ findings.push({
56303
+ code: "orphan",
56304
+ path: page.path,
56305
+ line: 1,
56306
+ message: "no page links here"
56307
+ });
56308
+ }
56309
+ }
56310
+ return findings.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.code.localeCompare(b.code));
56311
+ }
56312
+ function lintExitCode(findings) {
56313
+ return findings.length === 0 ? 0 : 1;
56314
+ }
56315
+ // ../../packages/kk-wiki/src/markitdown.ts
56316
+ init_dist3();
56317
+ import { createHash as createHash9 } from "crypto";
56318
+ import { tmpdir as tmpdir4 } from "os";
56319
+ import { isAbsolute as isAbsolute10, join as join29 } from "path";
56320
+
56321
+ class MissingNormalizerError extends Error {
56322
+ binary;
56323
+ constructor(binary) {
56324
+ super(`missing normaliser '${binary}': install it (\`uv tool install markitdown\`) or pass markdown on stdin`);
56325
+ this.binary = binary;
56326
+ this.name = "MissingNormalizerError";
56327
+ }
56328
+ }
56329
+ function resolveBinary(binary) {
56330
+ if (isAbsolute10(binary) || binary.includes("/"))
56331
+ return binary;
56332
+ const found = Bun.which(binary, { PATH: process.env.PATH });
56333
+ if (found === null)
56334
+ throw new MissingNormalizerError(binary);
56335
+ return found;
56336
+ }
56337
+ function createMarkitdownRunner(options = {}) {
56338
+ const binary = options.binary ?? "markitdown";
56339
+ const executor = options.executor ?? new NodeProcessExecutor;
56340
+ const fs = options.fileSystem ?? createNodeFileSystem();
56341
+ const timeoutMs = options.timeoutMs ?? 120000;
56342
+ return async (input) => {
56343
+ const executable = resolveBinary(binary);
56344
+ let tempPath;
56345
+ let target = input.target;
56346
+ if (input.kind === "html") {
56347
+ const id = createHash9("sha256").update(input.body ?? "").digest("hex").slice(0, 12);
56348
+ tempPath = join29(tmpdir4(), `kk-wiki-${id}.html`);
56349
+ await fs.writeFile(tempPath, input.body ?? "");
56350
+ target = tempPath;
56351
+ }
56352
+ try {
56353
+ const result = await executor.run({ command: executable, args: [target], timeout: timeoutMs });
56354
+ if (result.exitCode !== 0) {
56355
+ const last = result.stderr.trim().split(`
56356
+ `).slice(-1)[0] ?? "unknown error";
56357
+ throw new Error(`${binary} exited ${result.exitCode}: ${last}`);
56358
+ }
56359
+ if (result.stdout.trim() === "") {
56360
+ throw new Error(`${binary} produced an empty body for ${input.target}`);
56361
+ }
56362
+ return result.stdout;
56363
+ } finally {
56364
+ if (tempPath !== undefined && await fs.exists(tempPath))
56365
+ await fs.deleteFile(tempPath);
56366
+ }
56367
+ };
56368
+ }
56369
+ // ../../packages/kk-wiki/src/merge.ts
56370
+ function mergePages(index, from, to, options) {
56371
+ const source = index.pages.find((page) => page.path === from || page.slug === from);
56372
+ const target = index.pages.find((page) => page.path === to || page.slug === to);
56373
+ if (source === undefined)
56374
+ throw new Error(`merge: no source page '${from}'`);
56375
+ if (target === undefined)
56376
+ throw new Error(`merge: no target page '${to}'`);
56377
+ if (source.frontmatter.user_edited === true) {
56378
+ return {
56379
+ written: target.path,
56380
+ sourceSlug: source.slug,
56381
+ redirects: 0,
56382
+ guard: "refused",
56383
+ targetText: renderPage(target),
56384
+ sourceText: renderPage(source),
56385
+ rewritten: [],
56386
+ rewrittenPages: []
56387
+ };
56388
+ }
56389
+ const mergedSources = [...new Set([...target.frontmatter.sources, ...source.frontmatter.sources, source.slug])];
56390
+ const unitedBody = `${target.body.replace(/\s+$/, "")}
56391
+
56392
+ ${source.body.replace(/^\s+/, "")}`;
56393
+ const written = applyWriteToPage({ ...target, frontmatter: { ...target.frontmatter, sources: mergedSources } }, unitedBody, { mode: "full", date: options.date });
56394
+ let redirects = 0;
56395
+ const rewritten = [];
56396
+ const rewrittenPages = [];
56397
+ for (const page of index.pages) {
56398
+ if (page.slug === source.slug || page.slug === target.slug)
56399
+ continue;
56400
+ const linked = page.body.replace(/\[\[([^\]|]+)(\|[^\]]+)?\]\]/g, (whole, rawTarget, surface) => {
56401
+ const slug = rawTarget.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
56402
+ if (slug !== source.slug)
56403
+ return whole;
56404
+ redirects += 1;
56405
+ return surface === undefined ? `[[${target.slug}]]` : `[[${target.slug}${surface}]]`;
56406
+ });
56407
+ if (linked !== page.body) {
56408
+ page.body = linked;
56409
+ rewritten.push(page.path);
56410
+ rewrittenPages.push({
56411
+ path: page.path,
56412
+ text: renderPage({
56413
+ ...page,
56414
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56415
+ body: linked
56416
+ })
56417
+ });
56418
+ }
56419
+ }
56420
+ const sourceText = renderPage({
56421
+ ...source,
56422
+ frontmatter: {
56423
+ ...source.frontmatter,
56424
+ updated_at: options.date,
56425
+ redirect_to: target.slug
56426
+ },
56427
+ body: `Merged into [[${target.slug}|${target.frontmatter.title}]].
56428
+ `
56429
+ });
56430
+ return {
56431
+ written: target.path,
56432
+ sourceSlug: source.slug,
56433
+ redirects,
56434
+ guard: written.guard,
56435
+ targetText: written.text,
56436
+ sourceText,
56437
+ rewritten,
56438
+ rewrittenPages
56439
+ };
56440
+ }
56441
+ // ../../packages/kk-wiki/src/publish.ts
56442
+ import { dirname as dirname16, isAbsolute as isAbsolute11, join as join30, relative as relative4, resolve as resolve25 } from "path";
56443
+ function isInside(parent, child) {
56444
+ const rel = relative4(parent, child);
56445
+ return rel === "" || !rel.startsWith("..") && !isAbsolute11(rel);
56446
+ }
56447
+ async function publishVault(index, options) {
56448
+ const targetRoot = resolve25(options.target);
56449
+ if (isInside(resolve25(index.contentDir), targetRoot))
56450
+ return { files: [], refused: "target-inside-vault" };
56451
+ const fs = options.fileSystem;
56452
+ const files = [];
56453
+ for (const page of index.pages) {
56454
+ const source = join30(index.contentDir, page.path);
56455
+ const destination = join30(targetRoot, "content", page.path);
56456
+ await fs.ensureDir(dirname16(destination));
56457
+ await fs.writeFile(destination, await fs.readFile(source));
56458
+ files.push(join30("content", page.path));
56459
+ }
56460
+ return { files: files.sort() };
56461
+ }
56462
+ // ../../packages/kk-wiki/src/query.ts
56463
+ function terms(prompt) {
56464
+ return [
56465
+ ...new Set(prompt.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2))
56466
+ ].sort();
56467
+ }
56468
+ function scoreOf2(page, terms_) {
56469
+ const title = page.frontmatter.title.toLowerCase();
56470
+ const tags = page.frontmatter.tags.join(" ").toLowerCase();
56471
+ const body = page.body.toLowerCase();
56472
+ let score = 0;
56473
+ for (const term of terms_) {
56474
+ if (title.includes(term))
56475
+ score += 3;
56476
+ if (tags.includes(term))
56477
+ score += 2;
56478
+ if (body.includes(term))
56479
+ score += 1;
56480
+ }
56481
+ return score;
56482
+ }
56483
+ function excerptOf(page, terms_) {
56484
+ for (const line of page.body.split(`
56485
+ `)) {
56486
+ const text = line.trim();
56487
+ if (text === "" || text.startsWith("#"))
56488
+ continue;
56489
+ const lower = text.toLowerCase();
56490
+ if (terms_.some((term) => lower.includes(term)))
56491
+ return text.slice(0, 200);
56492
+ }
56493
+ return page.body.trim().split(`
56494
+ `)[0]?.slice(0, 200) ?? "";
56495
+ }
56496
+ function rankPages(index, prompt, options = {}) {
56497
+ const terms_ = terms(prompt);
56498
+ const hits = [];
56499
+ for (const page of index.pages) {
56500
+ const score = scoreOf2(page, terms_);
56501
+ if (score === 0)
56502
+ continue;
56503
+ hits.push({ path: page.path, title: page.frontmatter.title, excerpt: excerptOf(page, terms_), score });
56504
+ }
56505
+ return hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, options.limit ?? 10);
56506
+ }
56507
+ // ../../packages/kk-wiki/src/raw.ts
56508
+ init_dist3();
56509
+ import { createHash as createHash10 } from "crypto";
56510
+ import { dirname as dirname17, join as join31 } from "path";
56511
+ var RAW_SOURCE_TYPES = ["url", "pdf", "html", "rss"];
56512
+ function rawSnapshotId(sourceUri, body) {
56513
+ return createHash10("sha256").update(`${sourceUri}
56514
+ ${body}`).digest("hex").slice(0, 16);
56515
+ }
56516
+ function escapeValue(value) {
56517
+ return /[:#\n]/.test(value) || value.trim() !== value ? `"${value.replace(/"/g, "\\\"")}"` : value;
56518
+ }
56519
+ function renderRawSnapshot(snapshot, body) {
56520
+ const lines = [
56521
+ "---",
56522
+ `title: ${escapeValue(snapshot.title)}`,
56523
+ `source_type: ${snapshot.type}`,
56524
+ `source_uri: ${escapeValue(snapshot.sourceUri)}`,
56525
+ `ingested_at: ${snapshot.ingestedAt}`,
56526
+ "---",
56527
+ ""
56528
+ ];
56529
+ return `${lines.join(`
56530
+ `)}
56531
+ ${body.replace(/\s+$/, "")}
56532
+ `;
56533
+ }
56534
+ async function writeRawSnapshot(input, fileSystem = createNodeFileSystem()) {
56535
+ const ingestedAt = input.ingestedAt ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
56536
+ const id = rawSnapshotId(input.sourceUri, input.body);
56537
+ const snapshot = {
56538
+ id,
56539
+ path: join31(input.dir, input.type, `${id}.md`),
56540
+ type: input.type,
56541
+ title: input.title,
56542
+ sourceUri: input.sourceUri,
56543
+ ingestedAt
56544
+ };
56545
+ await fileSystem.ensureDir(dirname17(snapshot.path));
56546
+ await fileSystem.writeFile(snapshot.path, renderRawSnapshot(snapshot, input.body));
56547
+ return snapshot;
56548
+ }
56549
+ function deriveTitle(body, sourceUri) {
56550
+ for (const line of body.split(`
56551
+ `)) {
56552
+ const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(line);
56553
+ if (heading !== null)
56554
+ return heading[1] ?? sourceUri;
56555
+ }
56556
+ const tail = sourceUri === "stdin" ? "stdin" : sourceUri.split("/").pop() ?? sourceUri;
56557
+ return tail.replace(/\.[a-z0-9]+$/i, "") || "untitled";
56558
+ }
56559
+ // ../../packages/kk-wiki/src/summarize.ts
56560
+ var SUMMARY_HEADING = "## Summary";
56561
+ function summarizePage(index, target, material, options) {
56562
+ const linkedText = linkTitlesInText(index, material).trim();
56563
+ const lines = target.body.split(`
56564
+ `);
56565
+ const headingIndex = lines.findIndex((line) => line.trim() === SUMMARY_HEADING);
56566
+ let body;
56567
+ if (headingIndex === -1) {
56568
+ body = `${target.body.replace(/\s+$/, "")}
56569
+
56570
+ ${SUMMARY_HEADING}
56571
+
56572
+ ${linkedText}
56573
+ `;
56574
+ } else {
56575
+ const nextHeading = lines.findIndex((line, position) => position > headingIndex && /^##\s+/.test(line));
56576
+ const head = lines.slice(0, headingIndex + 1);
56577
+ const tail = nextHeading === -1 ? [] : lines.slice(nextHeading);
56578
+ body = `${[...head, "", linkedText, "", ...tail].join(`
56579
+ `).replace(/\n{3,}/g, `
56580
+
56581
+ `).trimEnd()}
56582
+ `;
56583
+ }
56584
+ const written = target.frontmatter.user_edited === true ? applyWrite({ ...target, body }, `${SUMMARY_HEADING}
56585
+
56586
+ ${linkedText}`, {
56587
+ mode: "full",
56588
+ date: options.date
56589
+ }) : { body: `${body.replace(/\s+$/, "")}
56590
+ `, guard: "clean" };
56591
+ return {
56592
+ path: target.path,
56593
+ guard: written.guard,
56594
+ text: renderPage({
56595
+ ...target,
56596
+ frontmatter: { ...target.frontmatter, updated_at: options.date },
56597
+ body: written.body
56598
+ }),
56599
+ links: (linkedText.match(/\[\[/g) ?? []).length
56600
+ };
56601
+ }
56602
+ // ../../packages/kk-wiki/src/sync.ts
56603
+ class UnknownRemoteError extends Error {
56604
+ name;
56605
+ declared;
56606
+ constructor(name, declared) {
56607
+ super(`unknown remote '${name}' (declared: ${declared.length === 0 ? "none" : declared.join(", ")})`);
56608
+ this.name = name;
56609
+ this.declared = declared;
56610
+ this.name = "UnknownRemoteError";
56611
+ }
56612
+ }
56613
+ function resolveRemote(remotes, name, substitutions) {
56614
+ const declared = Object.keys(remotes).sort();
56615
+ const entry = remotes[name];
56616
+ if (entry === undefined)
56617
+ throw new UnknownRemoteError(name, declared);
56618
+ const command = entry.command.replaceAll("{content}", substitutions.content).replaceAll("{remote}", entry.remote);
56619
+ return { argv: command.split(/\s+/).filter((part) => part !== ""), remote: entry.remote, command };
56620
+ }
56621
+ // ../../packages/kk-wiki/src/synthesize.ts
56622
+ function folderFor(type) {
56623
+ if (type === "entity")
56624
+ return "entities";
56625
+ if (type === "source")
56626
+ return "sources";
56627
+ return "concepts";
56628
+ }
56629
+ function synthesizePage(index, input) {
56630
+ const existing = index.bySlug.get(resolveSlug(input.target)) ?? index.pages.find((page) => page.path === input.target);
56631
+ const linkedText = linkTitlesInText(index, input.material).trim();
56632
+ if (existing === undefined) {
56633
+ const type = input.type ?? "concept";
56634
+ const slug = resolveSlug(input.target);
56635
+ const path = `${folderFor(type)}/${slug}.md`;
56636
+ const text = renderPage({
56637
+ path,
56638
+ frontmatter: {
56639
+ title: input.target,
56640
+ type,
56641
+ tags: [],
56642
+ sources: [],
56643
+ updated_at: input.date
56644
+ },
56645
+ body: `${linkedText}
56646
+ `
56647
+ });
56648
+ return { path, slug, guard: "clean", created: true, text };
56649
+ }
56650
+ const written = applyWrite(existing, linkedText, { mode: "append", date: input.date });
56651
+ return {
56652
+ path: existing.path,
56653
+ slug: existing.slug,
56654
+ guard: written.guard,
56655
+ created: false,
56656
+ text: renderPage({
56657
+ ...existing,
56658
+ frontmatter: { ...existing.frontmatter, updated_at: input.date },
56659
+ body: written.body
56660
+ })
56661
+ };
56662
+ }
56663
+ // src/wiki/ingest.ts
56664
+ init_dist3();
56665
+
56666
+ // src/wiki/config.ts
56667
+ import { isAbsolute as isAbsolute12, join as join32, resolve as resolve26 } from "path";
56668
+ init_dist3();
56669
+ var WIKI_CONFIG_FILE = "kk.config.json";
56670
+
56671
+ class WikiConfigError extends Error {
56672
+ constructor(message) {
56673
+ super(message);
56674
+ this.name = "WikiConfigError";
56675
+ }
56676
+ }
56677
+ var KEYS = ["root", "raw", "content", "defaultType", "mirrors", "remotes"];
56678
+ var DEFAULTS = {
56679
+ root: ".",
56680
+ raw: "raw",
56681
+ content: "content",
56682
+ defaultType: "html",
56683
+ mirrors: [],
56684
+ remotes: {}
56685
+ };
56686
+ var ENV_MAP = {
56687
+ KK_WIKI_ROOT: "root",
56688
+ KK_WIKI_RAW: "raw",
56689
+ KK_WIKI_CONTENT: "content",
56690
+ KK_WIKI_DEFAULT_TYPE: "defaultType"
56691
+ };
56692
+ function isRecord4(value) {
56693
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56694
+ }
56695
+ function stringField3(block, key, source) {
56696
+ const value = block[key];
56697
+ if (value === undefined)
56698
+ return;
56699
+ if (typeof value !== "string" || value.trim() === "") {
56700
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.${key} must be a non-empty string (${source})`);
56701
+ }
56702
+ return value;
56703
+ }
56704
+ function parseBlock(raw) {
56705
+ if (raw === undefined)
56706
+ return {};
56707
+ if (!isRecord4(raw))
56708
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: "wiki" must be an object`);
56709
+ for (const key of Object.keys(raw)) {
56710
+ if (!KEYS.includes(key)) {
56711
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: unsupported key wiki.${key} (allowed: ${KEYS.join(", ")})`);
56712
+ }
56713
+ }
56714
+ const block = {};
56715
+ const root = stringField3(raw, "root", "wiki.root");
56716
+ const rawDir = stringField3(raw, "raw", "wiki.raw");
56717
+ const content = stringField3(raw, "content", "wiki.content");
56718
+ if (root !== undefined)
56719
+ block.root = root;
56720
+ if (rawDir !== undefined)
56721
+ block.raw = rawDir;
56722
+ if (content !== undefined)
56723
+ block.content = content;
56724
+ const defaultType = stringField3(raw, "defaultType", "wiki.defaultType");
56725
+ if (defaultType !== undefined) {
56726
+ if (!RAW_SOURCE_TYPES.includes(defaultType)) {
56727
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.defaultType '${defaultType}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56728
+ }
56729
+ block.defaultType = defaultType;
56730
+ }
56731
+ const mirrors = raw.mirrors;
56732
+ if (mirrors !== undefined) {
56733
+ if (!Array.isArray(mirrors) || mirrors.some((entry) => typeof entry !== "string")) {
56734
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.mirrors must be an array of strings`);
56735
+ }
56736
+ block.mirrors = mirrors;
56737
+ }
56738
+ const remotes = raw.remotes;
56739
+ if (remotes !== undefined) {
56740
+ if (!isRecord4(remotes))
56741
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes must be an object`);
56742
+ const parsed = {};
56743
+ for (const [name, value] of Object.entries(remotes)) {
56744
+ if (!isRecord4(value) || typeof value.command !== "string" || typeof value.remote !== "string") {
56745
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes.${name} must be { command: string, remote: string }`);
56746
+ }
56747
+ parsed[name] = { command: value.command, remote: value.remote };
56748
+ }
56749
+ block.remotes = parsed;
56750
+ }
56751
+ return block;
56752
+ }
56753
+ async function readConfigFile(cwd, fileSystem) {
56754
+ const path = join32(cwd, WIKI_CONFIG_FILE);
56755
+ if (!await fileSystem.exists(path))
56756
+ return {};
56757
+ let text;
56758
+ try {
56759
+ text = await fileSystem.readFile(path);
56760
+ } catch (error) {
56761
+ const code = error.code;
56762
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: cannot read (${String(code ?? error)})`);
56763
+ }
56764
+ let parsed;
56765
+ try {
56766
+ parsed = JSON.parse(text);
56767
+ } catch (error) {
56768
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: invalid JSON (${error.message})`);
56769
+ }
56770
+ if (!isRecord4(parsed))
56771
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: top level must be an object`);
56772
+ return parseBlock(parsed.wiki);
56773
+ }
56774
+ async function resolveWikiConfig(options = {}) {
56775
+ const cwd = options.cwd ?? process.cwd();
56776
+ const env = options.env ?? process.env;
56777
+ const fileConfig = await readConfigFile(cwd, options.fileSystem ?? createNodeFileSystem());
56778
+ const merged = { ...DEFAULTS, ...fileConfig };
56779
+ for (const [name, key] of Object.entries(ENV_MAP)) {
56780
+ const value = env[name];
56781
+ if (value === undefined || value.trim() === "")
56782
+ continue;
56783
+ if (key === "defaultType") {
56784
+ if (!RAW_SOURCE_TYPES.includes(value)) {
56785
+ throw new WikiConfigError(`${name} '${value}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56786
+ }
56787
+ merged.defaultType = value;
56788
+ continue;
56789
+ }
56790
+ merged[key] = value;
56791
+ }
56792
+ Object.assign(merged, Object.fromEntries(Object.entries(options.overrides ?? {}).filter(([, v]) => v !== undefined)));
56793
+ merged.root = resolve26(cwd, merged.root);
56794
+ for (const key of ["raw", "content"]) {
56795
+ if (!isAbsolute12(merged[key]))
56796
+ merged[key] = join32(merged.root, merged[key]);
56797
+ }
56798
+ return merged;
56799
+ }
56800
+
56801
+ // src/wiki/ingest.ts
56802
+ var EXTENSION_TYPES = {
56803
+ ".html": "html",
56804
+ ".htm": "html",
56805
+ ".pdf": "pdf"
56806
+ };
56807
+ function detectSourceType(source) {
56808
+ if (/^https?:\/\//i.test(source))
56809
+ return "url";
56810
+ return EXTENSION_TYPES[extname(source).toLowerCase()];
56811
+ }
56812
+ function asSourceType(raw) {
56813
+ return RAW_SOURCE_TYPES.includes(raw) ? raw : undefined;
56814
+ }
56815
+ async function readStdin(stream = Bun.stdin.stream()) {
56816
+ const chunks = [];
56817
+ for await (const chunk of stream)
56818
+ chunks.push(chunk);
56819
+ return Buffer.concat(chunks).toString("utf8");
56820
+ }
56821
+ async function runIngest(args, deps = {}) {
56822
+ const explicit = args.type === undefined ? undefined : asSourceType(args.type);
56823
+ if (args.type !== undefined && explicit === undefined) {
56824
+ return {
56825
+ ok: false,
56826
+ code: 2,
56827
+ payload: { error: `unsupported --type '${args.type}' (want ${RAW_SOURCE_TYPES.join("|")})` }
56828
+ };
56829
+ }
56830
+ const fromStdin = args.source === "-";
56831
+ const detected = explicit ?? (fromStdin ? undefined : detectSourceType(args.source));
56832
+ if (detected === undefined) {
56833
+ const what = fromStdin ? "stdin requires --type" : `unsupported source type for '${args.source}'`;
56834
+ return { ok: false, code: 2, payload: { error: `${what} (want ${RAW_SOURCE_TYPES.join("|")})` } };
56835
+ }
56836
+ let config;
56837
+ try {
56838
+ config = await resolveWikiConfig({ cwd: deps.cwd, env: deps.env, overrides: { raw: args.out } });
56839
+ } catch (error) {
56840
+ if (error instanceof WikiConfigError)
56841
+ return { ok: false, code: 1, payload: { error: error.message } };
56842
+ throw error;
56843
+ }
56844
+ const fs = deps.fileSystem ?? createNodeFileSystem();
56845
+ const readStdinFn = deps.readStdin ?? readStdin;
56846
+ const normalise = deps.markitdown ?? createMarkitdownRunner();
56847
+ const sourcePath = isAbsolute13(args.source) ? args.source : join33(deps.cwd ?? process.cwd(), args.source);
56848
+ let sourceText;
56849
+ try {
56850
+ if (fromStdin) {
56851
+ sourceText = await readStdinFn();
56852
+ } else if (detected === "rss") {
56853
+ sourceText = await fs.readFile(sourcePath);
56854
+ } else {
56855
+ sourceText = await normalise({
56856
+ kind: detected,
56857
+ target: sourcePath,
56858
+ body: detected === "html" ? await fs.readFile(sourcePath) : undefined
56859
+ });
56860
+ }
56861
+ } catch (error) {
56862
+ if (error instanceof MissingNormalizerError)
56863
+ return { ok: false, code: 1, payload: { error: error.message } };
56864
+ const detail = error instanceof Error ? error.message : String(error);
56865
+ return { ok: false, code: 1, payload: { error: `ingest failed for '${args.source}': ${detail}` } };
56866
+ }
56867
+ const sourceUri = fromStdin ? "stdin" : args.source;
56868
+ const snapshot = await writeRawSnapshot({
56869
+ type: detected,
56870
+ sourceUri,
56871
+ title: deriveTitle(sourceText, sourceUri),
56872
+ body: sourceText,
56873
+ dir: config.raw
56874
+ }, fs);
56875
+ return {
56876
+ ok: true,
56877
+ code: 0,
56878
+ payload: { path: snapshot.path, id: snapshot.id, type: snapshot.type, title: snapshot.title }
56879
+ };
56880
+ }
56881
+
56882
+ // src/wiki/link.ts
56883
+ init_output2();
56884
+ async function runLink(options = {}) {
56885
+ let contentDir;
56886
+ try {
56887
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56888
+ } catch (error) {
56889
+ if (error instanceof WikiConfigError)
56890
+ return { ok: false, code: 1, payload: { error: error.message } };
56891
+ throw error;
56892
+ }
56893
+ const index = await buildVaultIndex(contentDir);
56894
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
56895
+ if (options.fix !== true) {
56896
+ const mentions = findMentions(index);
56897
+ return { ok: true, code: 0, payload: { ok: true, fix: false, mentions } };
56898
+ }
56899
+ const result = await fixLinks(index, { date, contentDir });
56900
+ return { ok: true, code: 0, payload: { ok: true, fix: true, ...result } };
56901
+ }
56902
+ function printLinkOutcome(outcome, json) {
56903
+ if (json) {
56904
+ consoleOutput.write(toJson(outcome.payload));
56905
+ return;
56906
+ }
56907
+ const payload = outcome.payload;
56908
+ if (payload.error !== undefined) {
56909
+ consoleOutput.error(`kk.wiki.link: ${payload.error}`);
56910
+ return;
56911
+ }
56912
+ if (payload.fix === true) {
56913
+ for (const path of payload.changed ?? [])
56914
+ consoleOutput.write(`linked: ${path}`);
56915
+ for (const path of payload.refused ?? [])
56916
+ consoleOutput.write(`guard: ${path} (appended under AI Updates)`);
56917
+ if ((payload.changed ?? []).length === 0 && (payload.refused ?? []).length === 0) {
56918
+ consoleOutput.write("no unlinked mentions");
56919
+ }
56920
+ return;
56921
+ }
56922
+ for (const mention of payload.mentions ?? []) {
56923
+ consoleOutput.write(`${mention.path}:${mention.line} ${mention.surface} -> [[${mention.slug}]]`);
56924
+ }
56925
+ if ((payload.mentions ?? []).length === 0)
56926
+ consoleOutput.write("no unlinked mentions");
56927
+ }
56928
+
56929
+ // src/wiki/lint.ts
56930
+ init_dist3();
56931
+ init_output2();
56932
+ async function runLint(options = {}) {
56933
+ let contentDir;
56934
+ try {
56935
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56936
+ } catch (error) {
56937
+ if (error instanceof WikiConfigError)
56938
+ return { ok: false, code: 1, payload: { error: error.message } };
56939
+ throw error;
56940
+ }
56941
+ const index = await buildVaultIndex(contentDir, createNodeFileSystem());
56942
+ const findings = lintPages(index);
56943
+ return {
56944
+ ok: findings.length === 0,
56945
+ code: lintExitCode(findings),
56946
+ payload: { ok: findings.length === 0, findings, pages: index.pages.length }
56947
+ };
56948
+ }
56949
+ function printLintOutcome(outcome, json) {
56950
+ if (json) {
56951
+ consoleOutput.write(toJson(outcome.payload));
56952
+ return;
56953
+ }
56954
+ const payload = outcome.payload;
56955
+ if (payload.error !== undefined) {
56956
+ consoleOutput.error(`kk.wiki.lint: ${payload.error}`);
56957
+ return;
56958
+ }
56959
+ for (const finding of payload.findings ?? []) {
56960
+ consoleOutput.write(`${finding.path}:${finding.line} ${finding.code}: ${finding.message}`);
56961
+ }
56962
+ if ((payload.findings ?? []).length === 0)
56963
+ consoleOutput.write("vault is clean");
56964
+ }
56965
+
56966
+ // src/wiki/maintenance.ts
56967
+ import { join as join34 } from "path";
56968
+ init_dist3();
56969
+ init_output2();
56970
+ async function withConfig2(options, run) {
56971
+ try {
56972
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
56973
+ return await run({ contentDir: config.content, rawDir: config.raw, mirrors: config.mirrors });
56974
+ } catch (error) {
56975
+ if (error instanceof WikiConfigError)
56976
+ return { error: error.message };
56977
+ throw error;
56978
+ }
56979
+ }
56980
+ async function runMerge(options) {
56981
+ const result = await withConfig2(options, async ({ contentDir }) => {
56982
+ const index = await buildVaultIndex(contentDir);
56983
+ const merge = mergePages(index, options.from ?? "", options.to ?? "", {
56984
+ date: options.date ?? new Date().toISOString().slice(0, 10)
56985
+ });
56986
+ if (merge.guard === "refused")
56987
+ return { refused: true, path: merge.written };
56988
+ const fs = createNodeFileSystem();
56989
+ await fs.writeFile(join34(contentDir, merge.written), merge.targetText);
56990
+ const sourcePage = index.pages.find((page) => page.slug === merge.sourceSlug);
56991
+ if (sourcePage !== undefined)
56992
+ await fs.writeFile(join34(contentDir, sourcePage.path), merge.sourceText);
56993
+ for (const page of merge.rewrittenPages)
56994
+ await fs.writeFile(join34(contentDir, page.path), page.text);
56995
+ return {
56996
+ refused: false,
56997
+ path: merge.written,
56998
+ redirects: merge.redirects,
56999
+ rewritten: merge.rewritten,
57000
+ rewrittenPages: merge.rewrittenPages,
57001
+ sourceText: merge.sourceText,
57002
+ sourceSlug: merge.sourceSlug
57003
+ };
57004
+ });
57005
+ if ("error" in result)
57006
+ return { ok: false, code: 1, payload: result };
57007
+ if (result.refused === true) {
57008
+ return { ok: false, code: 1, payload: { ok: false, error: "source page is user_edited; merge refused" } };
57009
+ }
57010
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
57011
+ }
57012
+ async function runCompile(options) {
57013
+ const result = await withConfig2(options, async ({ contentDir }) => {
57014
+ const index = await buildVaultIndex(contentDir);
57015
+ const compiled = compileIndex(index.pages, { date: options.date ?? new Date().toISOString().slice(0, 10) });
57016
+ const fs = createNodeFileSystem();
57017
+ const written = [];
57018
+ for (const [name, rendered] of [
57019
+ ["index.md", compiled.index],
57020
+ ["MAP.md", compiled.map]
57021
+ ]) {
57022
+ const path = join34(contentDir, name);
57023
+ const current = await fs.exists(path) ? await fs.readFile(path) : null;
57024
+ if (!needsWrite(current, rendered))
57025
+ continue;
57026
+ await fs.writeFile(path, rendered);
57027
+ written.push(name);
57028
+ }
57029
+ return { written };
57030
+ });
57031
+ if ("error" in result)
57032
+ return { ok: false, code: 1, payload: result };
57033
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
57034
+ }
57035
+ async function runGc(options) {
57036
+ const result = await withConfig2(options, async ({ contentDir, rawDir, mirrors }) => {
57037
+ const fs = createNodeFileSystem();
57038
+ const index = await buildVaultIndex(contentDir);
57039
+ const plan = await planGc(index, { rawDir, mirrors, fileSystem: fs });
57040
+ if (options.yes !== true)
57041
+ return { plan, deleted: [] };
57042
+ const { deleted } = await applyGc(plan, fs);
57043
+ return { plan, deleted };
57044
+ });
57045
+ if ("error" in result)
57046
+ return { ok: false, code: 1, payload: result };
57047
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
57048
+ }
57049
+ function printMaintenanceOutcome(outcome, json) {
57050
+ if (json) {
57051
+ consoleOutput.write(toJson(outcome.payload));
57052
+ return;
57053
+ }
57054
+ const payload = outcome.payload;
57055
+ if (payload.error !== undefined) {
57056
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
57057
+ return;
57058
+ }
57059
+ if (payload.plan !== undefined) {
57060
+ for (const path of payload.plan.delete)
57061
+ consoleOutput.write(`delete: ${path}`);
57062
+ for (const path of payload.plan.skippedMirrors)
57063
+ consoleOutput.write(`skip (mirror): ${path}`);
57064
+ if ((payload.deleted ?? []).length === 0)
57065
+ consoleOutput.write("dry run \u2014 pass --yes to delete");
57066
+ return;
57067
+ }
57068
+ if (payload.rewritten !== undefined) {
57069
+ consoleOutput.write(`merged into ${payload.path} (${payload.redirects} links rewritten)`);
57070
+ return;
57071
+ }
57072
+ for (const name of payload.written ?? [])
57073
+ consoleOutput.write(`compiled: ${name}`);
57074
+ if ((payload.written ?? []).length === 0)
57075
+ consoleOutput.write("already up to date");
57076
+ }
57077
+
57078
+ // src/wiki/retrieval.ts
57079
+ init_dist3();
57080
+ init_output2();
57081
+ async function configOrError(options) {
57082
+ try {
57083
+ return await resolveWikiConfig({ cwd: options.cwd, env: options.env });
57084
+ } catch (error) {
57085
+ if (error instanceof WikiConfigError)
57086
+ return { error: error.message };
57087
+ throw error;
57088
+ }
57089
+ }
57090
+ async function runPublish(options) {
57091
+ const config = await configOrError(options);
57092
+ if ("error" in config)
57093
+ return { ok: false, code: 1, payload: config };
57094
+ try {
57095
+ const index = await buildVaultIndex(config.content);
57096
+ const result = await publishVault(index, {
57097
+ target: options.value ?? "",
57098
+ fileSystem: createNodeFileSystem()
57099
+ });
57100
+ if (result.refused !== undefined) {
57101
+ return { ok: false, code: 2, payload: { ok: false, error: "target is inside the vault" } };
57102
+ }
57103
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
57104
+ } catch (error) {
57105
+ return { ok: false, code: 1, payload: { ok: false, error: error.message } };
57106
+ }
57107
+ }
57108
+ async function runSync(options) {
57109
+ const config = await configOrError(options);
57110
+ if ("error" in config)
57111
+ return { ok: false, code: 1, payload: config };
57112
+ try {
57113
+ const resolved = resolveRemote(config.remotes, options.value ?? "", { content: config.content });
57114
+ return { ok: true, code: 0, payload: { ok: true, dryRun: options.dryRun !== false, ...resolved } };
57115
+ } catch (error) {
57116
+ return { ok: false, code: 2, payload: { ok: false, error: error.message } };
57117
+ }
57118
+ }
57119
+ async function runQuery(options) {
57120
+ const config = await configOrError(options);
57121
+ if ("error" in config)
57122
+ return { ok: false, code: 1, payload: config };
57123
+ const index = await buildVaultIndex(config.content);
57124
+ const hits = rankPages(index, options.value ?? "", { limit: options.limit });
57125
+ return { ok: true, code: 0, payload: { ok: true, hits } };
57126
+ }
57127
+ async function runContext(options) {
57128
+ const config = await configOrError(options);
57129
+ if ("error" in config)
57130
+ return { ok: false, code: 1, payload: config };
57131
+ const index = await buildVaultIndex(config.content);
57132
+ const packed = packContext(index, options.value ?? "", { depth: options.depth });
57133
+ return { ok: true, code: 0, payload: { ok: true, ...packed } };
57134
+ }
57135
+ function printRetrievalOutcome(outcome, json) {
57136
+ if (json) {
57137
+ consoleOutput.write(toJson(outcome.payload));
57138
+ return;
57139
+ }
57140
+ const payload = outcome.payload;
57141
+ if (payload.error !== undefined) {
57142
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
57143
+ return;
57144
+ }
57145
+ if (payload.files !== undefined) {
57146
+ consoleOutput.write(`published ${payload.files.length} file(s)`);
57147
+ return;
57148
+ }
57149
+ if (payload.command !== undefined) {
57150
+ consoleOutput.write(`remote: ${payload.command}`);
57151
+ return;
57152
+ }
57153
+ if (payload.hits !== undefined) {
57154
+ for (const hit of payload.hits)
57155
+ consoleOutput.write(`${hit.path} (${hit.score})`);
57156
+ return;
57157
+ }
57158
+ consoleOutput.write(payload.markdown ?? "");
57159
+ }
57160
+
57161
+ // src/wiki/write-verbs.ts
57162
+ import { isAbsolute as isAbsolute14, join as join35 } from "path";
57163
+ init_dist3();
57164
+ init_output2();
57165
+ async function readMaterial(options) {
57166
+ if (options.from === "-") {
57167
+ if (options.readStdin !== undefined)
57168
+ return options.readStdin();
57169
+ const chunks = [];
57170
+ for await (const chunk of Bun.stdin.stream())
57171
+ chunks.push(chunk);
57172
+ return Buffer.concat(chunks).toString("utf8");
57173
+ }
57174
+ const path = isAbsolute14(options.from) ? options.from : join35(options.cwd ?? process.cwd(), options.from);
57175
+ return createNodeFileSystem().readFile(path);
57176
+ }
57177
+ async function resolveContext(options) {
57178
+ try {
57179
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
57180
+ const index = await buildVaultIndex(config.content);
57181
+ return { index, contentDir: config.content };
57182
+ } catch (error) {
57183
+ if (error instanceof WikiConfigError)
57184
+ return { error: error.message };
57185
+ throw error;
57186
+ }
57187
+ }
57188
+ async function runSummarize(options) {
57189
+ const context = await resolveContext(options);
57190
+ if ("error" in context)
57191
+ return { ok: false, code: 1, payload: { error: context.error } };
57192
+ const target = context.index.pages.find((page) => page.path === options.target);
57193
+ if (target === undefined) {
57194
+ return { ok: false, code: 1, payload: { error: `no page at '${options.target}'` } };
57195
+ }
57196
+ const material = await readMaterial(options);
57197
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57198
+ const result = summarizePage(context.index, target, material, { date });
57199
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57200
+ return { ok: true, code: 0, payload: { ok: true, path: result.path, guard: result.guard, links: result.links } };
57201
+ }
57202
+ async function runSynthesize(options) {
57203
+ const context = await resolveContext(options);
57204
+ if ("error" in context)
57205
+ return { ok: false, code: 1, payload: { error: context.error } };
57206
+ const material = await readMaterial(options);
57207
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57208
+ const type = options.type;
57209
+ const result = synthesizePage(context.index, { target: options.target, material, type, date });
57210
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57211
+ return {
57212
+ ok: true,
57213
+ code: 0,
57214
+ payload: { ok: true, path: result.path, slug: result.slug, guard: result.guard, created: result.created }
57215
+ };
57216
+ }
57217
+ function printWriteOutcome(outcome, json) {
57218
+ if (json) {
57219
+ consoleOutput.write(toJson(outcome.payload));
57220
+ return;
57221
+ }
57222
+ const payload = outcome.payload;
57223
+ if (payload.error !== undefined) {
57224
+ consoleOutput.error(`kk.wiki.write: ${payload.error}`);
57225
+ return;
57226
+ }
57227
+ consoleOutput.write(`${payload.created === true ? "created" : "updated"} ${payload.path} (guard: ${payload.guard})`);
57228
+ }
57229
+
57230
+ // src/commands/wiki.ts
57231
+ async function ingestAction2(source, options) {
57232
+ const outcome = await runIngest({ source, type: options.type, out: options.out, json: options.json });
57233
+ if (outcome.ok) {
57234
+ if (options.json === true)
57235
+ consoleOutput.write(toJson(outcome.payload));
57236
+ else
57237
+ consoleOutput.write(`raw snapshot: ${outcome.payload.path}`);
57238
+ return;
57239
+ }
57240
+ const message = `kk.wiki.ingest: ${outcome.payload.error}`;
57241
+ if (options.json === true)
57242
+ consoleOutput.write(toJson({ ok: false, error: outcome.payload.error }));
57243
+ consoleOutput.error(message);
57244
+ throw new CommanderError(outcome.code, "kk.wiki.ingest", message);
57245
+ }
57246
+ async function linkAction(options) {
57247
+ const outcome = await runLink({ fix: options.fix === true, json: options.json === true });
57248
+ printLinkOutcome(outcome, options.json === true);
57249
+ if (!outcome.ok)
57250
+ throw new CommanderError(outcome.code, "kk.wiki.link", "kk.wiki.link failed");
57251
+ }
57252
+ async function lintAction(options) {
57253
+ const outcome = await runLint({ json: options.json === true });
57254
+ printLintOutcome(outcome, options.json === true);
57255
+ if (outcome.code !== 0)
57256
+ throw new CommanderError(outcome.code, "kk.wiki.lint", "kk.wiki.lint findings");
57257
+ }
57258
+ async function summarizeAction(target, options) {
57259
+ const outcome = await runSummarize({ target, from: options.from, json: options.json === true });
57260
+ printWriteOutcome(outcome, options.json === true);
57261
+ if (!outcome.ok)
57262
+ throw new CommanderError(outcome.code, "kk.wiki.summarize", "kk.wiki.summarize failed");
57263
+ }
57264
+ async function synthesizeAction(target, options) {
57265
+ const outcome = await runSynthesize({
57266
+ target,
57267
+ from: options.from,
57268
+ type: options.type,
57269
+ json: options.json === true
57270
+ });
57271
+ printWriteOutcome(outcome, options.json === true);
57272
+ if (!outcome.ok)
57273
+ throw new CommanderError(outcome.code, "kk.wiki.synthesize", "kk.wiki.synthesize failed");
57274
+ }
57275
+ async function mergeAction(source, target, options) {
57276
+ const outcome = await runMerge({ from: source, to: target, json: options.json === true });
57277
+ printMaintenanceOutcome(outcome, options.json === true);
57278
+ if (!outcome.ok)
57279
+ throw new CommanderError(outcome.code, "kk.wiki.merge", "kk.wiki.merge failed");
57280
+ }
57281
+ async function compileAction(options) {
57282
+ const outcome = await runCompile({ json: options.json === true });
57283
+ printMaintenanceOutcome(outcome, options.json === true);
57284
+ if (!outcome.ok)
57285
+ throw new CommanderError(outcome.code, "kk.wiki.compile", "kk.wiki.compile failed");
57286
+ }
57287
+ async function gcAction(options) {
57288
+ const outcome = await runGc({ yes: options.yes === true, json: options.json === true });
57289
+ printMaintenanceOutcome(outcome, options.json === true);
57290
+ if (!outcome.ok)
57291
+ throw new CommanderError(outcome.code, "kk.wiki.gc", "kk.wiki.gc failed");
57292
+ }
57293
+ async function publishAction(options) {
57294
+ const outcome = await runPublish({ value: options.target, json: options.json === true });
57295
+ printRetrievalOutcome(outcome, options.json === true);
57296
+ if (!outcome.ok)
57297
+ throw new CommanderError(outcome.code, "kk.wiki.publish", "kk.wiki.publish failed");
57298
+ }
57299
+ async function syncAction(remote, options) {
57300
+ const outcome = await runSync({ value: remote, dryRun: options.dryRun === true, json: options.json === true });
57301
+ printRetrievalOutcome(outcome, options.json === true);
57302
+ if (!outcome.ok)
57303
+ throw new CommanderError(outcome.code, "kk.wiki.sync", "kk.wiki.sync failed");
57304
+ }
57305
+ async function queryAction(prompt, options) {
57306
+ const outcome = await runQuery({
57307
+ value: prompt,
57308
+ limit: options.limit === undefined ? undefined : Number(options.limit),
57309
+ json: options.json === true
57310
+ });
57311
+ printRetrievalOutcome(outcome, options.json === true);
57312
+ if (!outcome.ok)
57313
+ throw new CommanderError(outcome.code, "kk.wiki.query", "kk.wiki.query failed");
57314
+ }
57315
+ async function contextAction(topic, options) {
57316
+ const outcome = await runContext({
57317
+ value: topic,
57318
+ depth: options.depth === undefined ? undefined : Number(options.depth),
57319
+ json: options.json === true
57320
+ });
57321
+ printRetrievalOutcome(outcome, options.json === true);
57322
+ if (!outcome.ok)
57323
+ throw new CommanderError(outcome.code, "kk.wiki.context", "kk.wiki.context failed");
57324
+ }
57325
+ function registerWikiCommand(parent) {
57326
+ const wiki = parent.command("wiki").description("Deterministic Markdown vault mechanics (ADR-048)");
57327
+ 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);
57328
+ 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);
57329
+ 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);
57330
+ 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);
57331
+ 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);
57332
+ wiki.command("compile").description("Regenerate content/index.md and content/MAP.md from the vault structure").option("--json", "Print one JSON document").action(compileAction);
57333
+ 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);
57334
+ 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);
57335
+ 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);
57336
+ 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);
57337
+ 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);
57338
+ wiki.command("lint").description("Audit the vault for broken links, orphan pages and frontmatter defects").option("--json", "Print one JSON document").action(lintAction);
57339
+ }
57340
+
55617
57341
  // src/config.ts
55618
57342
  import { readFileSync as readFileSync9 } from "fs";
55619
57343
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -55638,6 +57362,7 @@ function createProgram() {
55638
57362
  registerScheduleCommand(program);
55639
57363
  registerStageCommand(program);
55640
57364
  registerStoreCommand(program);
57365
+ registerWikiCommand(program);
55641
57366
  return program;
55642
57367
  }
55643
57368