@gobing-ai/knowledge-kit 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +2399 -177
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +60 -54
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +3 -3
  7. package/plugins/generations/daily-article-gen/dist/index.js +3 -3
  8. package/plugins/generations/dailynews-gen/dist/index.js +73 -10
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -1
  10. package/plugins/generations/dailynews-gen/src/script-plan.ts +103 -5
  11. package/plugins/generations/episode-plan-gen/dist/index.js +3 -3
  12. package/plugins/generations/gemini-tts/dist/index.js +3 -3
  13. package/plugins/generations/image-gen/README.md +31 -10
  14. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  31. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  32. package/plugins/generations/image-gen/dist/index.js +3 -3
  33. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  34. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  35. package/plugins/generations/news-report-gen/dist/index.js +3 -3
  36. package/plugins/generations/voice-gen/dist/index.js +3 -3
  37. package/plugins/generations/voxcpm-tts/dist/index.js +3 -3
  38. package/plugins/ingestions/aihot-ingest/dist/index.js +3 -3
  39. package/plugins/ingestions/horizon-ingest/dist/index.js +3 -3
  40. package/plugins/ingestions/last30days-ingest/dist/index.js +3 -3
  41. package/plugins/ingestions/web-search/dist/index.js +3 -3
  42. package/plugins/kk/plugin.json +1 -1
  43. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  44. package/plugins/kk/publish-presets/daily-ai-voice.json +11 -3
  45. package/plugins/kk/scripts/cover-compositor.ts +152 -0
  46. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  47. package/plugins/kk/scripts/daily-scheduled-run.ts +192 -3
  48. package/plugins/kk/scripts/daily-stages.ts +599 -27
  49. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  50. package/plugins/kk/scripts/daily-triage.ts +74 -0
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +51 -6
  52. package/plugins/kk/skills/content-judge/SKILL.md +5 -4
  53. package/plugins/kk/skills/content-judge/references/rubrics.md +14 -0
  54. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  55. package/plugins/kk/skills/news-editorial/SKILL.md +122 -0
  56. package/plugins/kk/skills/news-editorial/references/selection.md +47 -0
  57. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +100 -0
  58. package/plugins/kk/skills/publish/SKILL.md +4 -4
  59. package/plugins/kk/skills/web-automation/SKILL.md +229 -77
  60. package/plugins/kk/skills/web-automation/references/browser-launch.md +127 -36
  61. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  62. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  63. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -6
  64. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +185 -224
  65. package/plugins/kk/workflows/kk-daily-publish3.yaml +16 -8
  66. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  67. package/plugins/publishings/bilibili-pub/dist/index.js +6 -4
  68. package/plugins/publishings/bilibili-pub/dist/profile-check.js +3 -1
  69. package/plugins/publishings/cnblogs-pub/dist/index.js +6 -4
  70. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +3 -1
  71. package/plugins/publishings/csdn-pub/dist/index.js +6 -4
  72. package/plugins/publishings/csdn-pub/dist/profile-check.js +6 -4
  73. package/plugins/publishings/emdash-pub/dist/index.js +3 -3
  74. package/plugins/publishings/infoq-pub/dist/index.js +6 -4
  75. package/plugins/publishings/infoq-pub/dist/profile-check.js +6 -4
  76. package/plugins/publishings/jike-pub/dist/index.js +6 -4
  77. package/plugins/publishings/jike-pub/dist/profile-check.js +6 -4
  78. package/plugins/publishings/juejin-pub/dist/index.js +6 -4
  79. package/plugins/publishings/juejin-pub/dist/profile-check.js +6 -4
  80. package/plugins/publishings/linkedin-pub/dist/index.js +6 -4
  81. package/plugins/publishings/linkedin-pub/dist/profile-check.js +6 -4
  82. package/plugins/publishings/medium-pub/dist/index.js +3 -3
  83. package/plugins/publishings/podcast-pub/dist/index.js +148 -5
  84. package/plugins/publishings/podcast-pub/src/index.ts +71 -2
  85. package/plugins/publishings/podcast-pub/src/map.ts +3 -0
  86. package/plugins/publishings/podcast-pub/src/transcript.ts +195 -0
  87. package/plugins/publishings/qiita-pub/dist/index.js +3 -3
  88. package/plugins/publishings/shipinhao-pub/dist/index.js +227 -53
  89. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +51 -2
  90. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  91. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  92. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  93. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  94. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  95. package/plugins/publishings/sspai-pub/dist/index.js +6 -4
  96. package/plugins/publishings/sspai-pub/dist/profile-check.js +3 -1
  97. package/plugins/publishings/substack-pub/dist/index.js +6 -4
  98. package/plugins/publishings/substack-pub/dist/profile-check.js +6 -4
  99. package/plugins/publishings/surfdash-pub/dist/index.js +237 -14
  100. package/plugins/publishings/surfdash-pub/src/index.ts +127 -6
  101. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  102. package/plugins/publishings/threads-pub/dist/index.js +3 -3
  103. package/plugins/publishings/wechatmp-pub/dist/index.js +62 -40
  104. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +6 -4
  105. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  106. package/plugins/publishings/wechatmp-pub/src/flow.ts +73 -37
  107. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  108. package/plugins/publishings/weibo-pub/dist/index.js +6 -4
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +6 -4
  110. package/plugins/publishings/x-pub/dist/index.js +6 -4
  111. package/plugins/publishings/x-pub/dist/profile-check.js +6 -4
  112. package/plugins/publishings/xhs-pub/dist/index.js +562 -34
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -4
  114. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  115. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  116. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  117. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +6 -4
  118. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +3 -1
  119. package/plugins/publishings/zenn-pub/dist/index.js +3 -3
  120. package/plugins/kk/scripts/daily-voice-style.zh.md +0 -70
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();
@@ -38526,10 +38564,12 @@ var init_bot = __esm(() => {
38526
38564
  CONTROL_CHARACTERS = /\p{Cc}/u;
38527
38565
  BotError = class BotError extends Error {
38528
38566
  code;
38529
- constructor(code, message) {
38567
+ details;
38568
+ constructor(code, message, details = {}) {
38530
38569
  super(message);
38531
38570
  this.name = "BotError";
38532
38571
  this.code = code;
38572
+ this.details = details;
38533
38573
  }
38534
38574
  };
38535
38575
  });
@@ -38796,11 +38836,13 @@ __export(exports_browser, {
38796
38836
  captureSessionFacts: () => captureSessionFacts,
38797
38837
  checkChannelSession: () => checkChannelSession,
38798
38838
  chmod: () => chmod,
38839
+ closeBotContext: () => closeBotContext,
38799
38840
  createExclusiveFile: () => createExclusiveFile,
38800
38841
  createKkBrowserLauncher: () => createKkBrowserLauncher,
38801
38842
  createShadowFinder: () => createShadowFinder,
38802
38843
  enterDelegatedLease: () => enterDelegatedLease,
38803
38844
  execBot: () => execBot,
38845
+ execFailureDetail: () => execFailureDetail,
38804
38846
  expectOutcome: () => expectOutcome,
38805
38847
  fillCodeMirror: () => fillCodeMirror,
38806
38848
  findLeftoverTransaction: () => findLeftoverTransaction,
@@ -38814,11 +38856,13 @@ __export(exports_browser, {
38814
38856
  loginBot: () => loginBot,
38815
38857
  logoutBot: () => logoutBot,
38816
38858
  markdownToHtml: () => markdownToHtml,
38859
+ missingBotProfile: () => missingBotProfile,
38817
38860
  mkdirExclusive: () => mkdirExclusive,
38818
38861
  normalizeBotDefaultUrl: () => normalizeBotDefaultUrl,
38819
38862
  normalizeSessionExpiry: () => normalizeSessionExpiry,
38820
38863
  normalizeSessionIdentity: () => normalizeSessionIdentity,
38821
38864
  openBot: () => openBot,
38865
+ openBotPage: () => openBotPage,
38822
38866
  openChannelSession: () => openChannelSession,
38823
38867
  parseBotMetadata: () => parseBotMetadata,
38824
38868
  pasteHtml: () => pasteHtml,
@@ -38832,6 +38876,7 @@ __export(exports_browser, {
38832
38876
  rmdir: () => rmdir,
38833
38877
  runProfileCli: () => runProfileCli,
38834
38878
  uploadFile: () => uploadFile,
38879
+ validateExecUrl: () => validateExecUrl,
38835
38880
  verifyLeaseHeld: () => verifyLeaseHeld,
38836
38881
  waitUntil: () => waitUntil
38837
38882
  });
@@ -39652,6 +39697,539 @@ var init_browser = __esm(() => {
39652
39697
  ];
39653
39698
  });
39654
39699
 
39700
+ // ../../packages/publish-harness/src/bot-collection.ts
39701
+ var exports_bot_collection = {};
39702
+ __export(exports_bot_collection, {
39703
+ runBotCollection: () => runBotCollection
39704
+ });
39705
+ function isRecord3(value) {
39706
+ return typeof value === "object" && value !== null && !Array.isArray(value);
39707
+ }
39708
+ function usage(path) {
39709
+ return new BotError("usage", `invalid collection plan: ${path}`);
39710
+ }
39711
+ function requireSafeId(value, path, seen) {
39712
+ if (typeof value !== "string" || !SAFE_ID.test(value))
39713
+ throw usage(`${path} must match [A-Za-z0-9][A-Za-z0-9_-]{0,63}`);
39714
+ if (seen.has(value))
39715
+ throw usage(`${path} duplicates an id already declared in this plan`);
39716
+ seen.add(value);
39717
+ return value;
39718
+ }
39719
+ function requireString(value, path) {
39720
+ if (typeof value !== "string" || value.trim() === "")
39721
+ throw usage(`${path} must be a non-empty string`);
39722
+ return value;
39723
+ }
39724
+ function optionalString(value, path) {
39725
+ return value === undefined ? undefined : requireString(value, path);
39726
+ }
39727
+ function optionalTimeout(value, path) {
39728
+ return value === undefined ? undefined : requirePositiveInt(value, path);
39729
+ }
39730
+ function requirePositiveInt(value, path) {
39731
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
39732
+ throw usage(`${path} must be a positive integer`);
39733
+ }
39734
+ return value;
39735
+ }
39736
+ function requireHeaders(value, path) {
39737
+ if (!isRecord3(value))
39738
+ throw usage(`${path} must be an object of string header values`);
39739
+ const headers = {};
39740
+ for (const [name, headerValue] of Object.entries(value)) {
39741
+ headers[name] = requireString(headerValue, `${path}.${name}`);
39742
+ }
39743
+ return headers;
39744
+ }
39745
+ function requireUrl(value, path) {
39746
+ try {
39747
+ return validateExecUrl(requireString(value, path));
39748
+ } catch {
39749
+ throw usage(`${path} must be an absolute http(s) URL without credentials`);
39750
+ }
39751
+ }
39752
+ function normalizeOrigin(value, path) {
39753
+ const raw = requireString(value, path);
39754
+ let parsed;
39755
+ try {
39756
+ parsed = new URL(raw);
39757
+ } catch {
39758
+ throw usage(`${path} must be an absolute http(s) origin`);
39759
+ }
39760
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.origin !== raw) {
39761
+ throw usage(`${path} must be an exact http(s) scheme/host/port origin`);
39762
+ }
39763
+ return parsed.origin;
39764
+ }
39765
+ function normalizePathPrefix(value, path) {
39766
+ const prefix = requireString(value, path);
39767
+ if (!prefix.startsWith("/") || prefix.includes("?") || prefix.includes("#")) {
39768
+ throw usage(`${path} must be an absolute URL path without query or fragment`);
39769
+ }
39770
+ return prefix;
39771
+ }
39772
+ function normalizeStep(raw, path, seen) {
39773
+ if (!isRecord3(raw))
39774
+ throw usage(path);
39775
+ const id = requireSafeId(raw.id, `${path}.id`, seen);
39776
+ switch (raw.type) {
39777
+ case "request": {
39778
+ if (raw.data !== undefined && typeof raw.data !== "string")
39779
+ throw usage(`${path}.data must be a string`);
39780
+ if (raw.followRedirects !== undefined && typeof raw.followRedirects !== "boolean") {
39781
+ throw usage(`${path}.followRedirects must be a boolean`);
39782
+ }
39783
+ return {
39784
+ id,
39785
+ type: "request",
39786
+ url: requireUrl(raw.url, `${path}.url`),
39787
+ ...raw.method === undefined ? {} : { method: requireString(raw.method, `${path}.method`) },
39788
+ ...raw.headers === undefined ? {} : { headers: requireHeaders(raw.headers, `${path}.headers`) },
39789
+ ...raw.data === undefined ? {} : { data: raw.data },
39790
+ ...raw.followRedirects === undefined ? {} : { followRedirects: raw.followRedirects },
39791
+ ...rawTimeout(raw.timeoutMs, path) ?? {}
39792
+ };
39793
+ }
39794
+ case "navigate": {
39795
+ const waitUntil = raw.waitUntil;
39796
+ if (waitUntil !== undefined && !NAVIGATION_WAIT_UNTIL.includes(waitUntil)) {
39797
+ throw usage(`${path}.waitUntil must be one of ${NAVIGATION_WAIT_UNTIL.join(", ")}`);
39798
+ }
39799
+ return {
39800
+ id,
39801
+ type: "navigate",
39802
+ url: requireUrl(raw.url, `${path}.url`),
39803
+ ...waitUntil === undefined ? {} : { waitUntil },
39804
+ ...rawTimeout(raw.timeoutMs, path) ?? {}
39805
+ };
39806
+ }
39807
+ case "wait":
39808
+ case "click":
39809
+ return {
39810
+ id,
39811
+ type: raw.type,
39812
+ selector: requireString(raw.selector, `${path}.selector`),
39813
+ ...rawTimeout(raw.timeoutMs, path) ?? {}
39814
+ };
39815
+ case "scroll": {
39816
+ const deltaY = raw.deltaY;
39817
+ if (typeof deltaY !== "number" || !Number.isFinite(deltaY) || deltaY === 0) {
39818
+ throw usage(`${path}.deltaY must be a finite non-zero number`);
39819
+ }
39820
+ return { id, type: "scroll", deltaY, ...rawTimeout(raw.timeoutMs, path) ?? {} };
39821
+ }
39822
+ case "extract": {
39823
+ if (raw.format !== "html" && raw.format !== "text")
39824
+ throw usage(`${path}.format must be "html" or "text"`);
39825
+ const selector = optionalString(raw.selector, `${path}.selector`);
39826
+ return {
39827
+ id,
39828
+ type: "extract",
39829
+ format: raw.format,
39830
+ ...selector === undefined ? {} : { selector },
39831
+ ...rawTimeout(raw.timeoutMs, path) ?? {}
39832
+ };
39833
+ }
39834
+ default:
39835
+ throw usage(`${path}.type must be request, navigate, wait, click, scroll or extract`);
39836
+ }
39837
+ }
39838
+ function rawTimeout(value, path) {
39839
+ const timeoutMs = optionalTimeout(value, `${path}.timeoutMs`);
39840
+ return timeoutMs === undefined ? undefined : { timeoutMs };
39841
+ }
39842
+ function normalizePlan(plan) {
39843
+ if (!isRecord3(plan))
39844
+ throw usage("plan must be a JSON object");
39845
+ if (!Array.isArray(plan.steps))
39846
+ throw usage("plan.steps must be an array");
39847
+ if (plan.responses !== undefined && !Array.isArray(plan.responses))
39848
+ throw usage("plan.responses must be an array");
39849
+ const seen = new Set;
39850
+ const steps = plan.steps.map((step, index) => normalizeStep(step, `plan.steps[${index}]`, seen));
39851
+ const responses = (plan.responses ?? []).map((raw, index) => {
39852
+ const path = `plan.responses[${index}]`;
39853
+ if (!isRecord3(raw))
39854
+ throw usage(path);
39855
+ return {
39856
+ id: requireSafeId(raw.id, `${path}.id`, seen),
39857
+ ...raw.origin === undefined ? {} : { origin: normalizeOrigin(raw.origin, `${path}.origin`) },
39858
+ pathPrefix: normalizePathPrefix(raw.pathPrefix, `${path}.pathPrefix`)
39859
+ };
39860
+ });
39861
+ const produces = steps.some((step) => step.type === "request" || step.type === "extract");
39862
+ if (!produces && responses.length === 0) {
39863
+ throw usage("plan declares no artifact source: add a request/extract step or a response capture");
39864
+ }
39865
+ let timeoutMs = DEFAULT_RUN_TIMEOUT_MS;
39866
+ if (plan.timeoutMs !== undefined) {
39867
+ timeoutMs = requirePositiveInt(plan.timeoutMs, "plan.timeoutMs");
39868
+ if (timeoutMs > MAX_RUN_TIMEOUT_MS)
39869
+ throw usage(`plan.timeoutMs must not exceed ${MAX_RUN_TIMEOUT_MS}`);
39870
+ }
39871
+ return { steps, responses, timeoutMs };
39872
+ }
39873
+ function safeUrl(input) {
39874
+ try {
39875
+ const parsed = new URL(input);
39876
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
39877
+ return;
39878
+ return `${parsed.origin}${parsed.pathname}`;
39879
+ } catch {
39880
+ return;
39881
+ }
39882
+ }
39883
+ function looksLikeAuthWall(url) {
39884
+ if (url === undefined)
39885
+ return false;
39886
+ try {
39887
+ return AUTH_PATH.test(new URL(url).pathname);
39888
+ } catch {
39889
+ return false;
39890
+ }
39891
+ }
39892
+ function classifyStatus(status, stepIndex, stepId, what = "step") {
39893
+ const details = {
39894
+ ...stepIndex === undefined ? {} : { stepIndex },
39895
+ stepId
39896
+ };
39897
+ if (status === 401 || status === 403) {
39898
+ return new BotError("authentication", `${what} '${stepId}' hit an authentication wall (status ${status}) \u2014 ` + "run `kk bot login <url> --save <profileName>` to renew the session", details);
39899
+ }
39900
+ if (status >= 400) {
39901
+ return new BotError("browser", `${what} '${stepId}' returned status ${status}`, details);
39902
+ }
39903
+ return;
39904
+ }
39905
+ function emptyFailure(id, what, stepIndex) {
39906
+ return new BotError("empty", `${what} '${id}' produced no content`, {
39907
+ ...stepIndex === undefined ? {} : { stepIndex },
39908
+ stepId: id
39909
+ });
39910
+ }
39911
+ async function readBody(response) {
39912
+ return await response.body();
39913
+ }
39914
+ function stepTimeout(step, remaining, stepIndex) {
39915
+ if (remaining <= 0) {
39916
+ throw new BotError("browser", `step '${step.id}' exceeded the collection deadline`, {
39917
+ stepIndex,
39918
+ stepId: step.id
39919
+ });
39920
+ }
39921
+ return Math.min(step.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS2, remaining);
39922
+ }
39923
+ function requestFailureDetail(error, step) {
39924
+ let detail = execFailureDetail(error, step.url);
39925
+ const secrets = [...Object.values(step.headers ?? {}), ...step.data === undefined ? [] : [step.data]];
39926
+ for (const secret of secrets) {
39927
+ if (secret.length > 0)
39928
+ detail = detail.split(secret).join("<redacted>");
39929
+ }
39930
+ return detail.slice(0, 200);
39931
+ }
39932
+ async function runStep(step, index, context, page, timeoutMs) {
39933
+ const details = { stepIndex: index, stepId: step.id };
39934
+ switch (step.type) {
39935
+ case "request": {
39936
+ let response;
39937
+ try {
39938
+ response = await context.request.fetch(step.url, {
39939
+ method: step.method ?? (step.data === undefined ? "GET" : "POST"),
39940
+ ...step.headers === undefined ? {} : { headers: step.headers },
39941
+ ...step.data === undefined ? {} : { data: Buffer.from(step.data, "utf8") },
39942
+ failOnStatusCode: false,
39943
+ ...step.followRedirects === true ? {} : { maxRedirects: 0 },
39944
+ timeout: timeoutMs
39945
+ });
39946
+ } catch (error) {
39947
+ throw new BotError("browser", `step '${step.id}' request failed (${requestFailureDetail(error, step)})`, details);
39948
+ }
39949
+ const status = response.status();
39950
+ const wall = classifyStatus(status, index, step.id);
39951
+ if (wall !== undefined)
39952
+ throw wall;
39953
+ let body;
39954
+ try {
39955
+ body = await readBody(response);
39956
+ } catch {
39957
+ throw new BotError("browser", `step '${step.id}' response body could not be read`, details);
39958
+ }
39959
+ const text = body.toString("utf8");
39960
+ if (text.trim() === "")
39961
+ throw emptyFailure(step.id, "step", index);
39962
+ const requestUrl = safeUrl(step.url);
39963
+ return {
39964
+ result: {
39965
+ index,
39966
+ id: step.id,
39967
+ type: step.type,
39968
+ ...requestUrl === undefined ? {} : { url: requestUrl }
39969
+ },
39970
+ artifact: {
39971
+ id: step.id,
39972
+ kind: "request",
39973
+ body: text,
39974
+ status,
39975
+ ...requestUrl === undefined ? {} : { url: requestUrl },
39976
+ stepIndex: index
39977
+ }
39978
+ };
39979
+ }
39980
+ case "navigate": {
39981
+ let status;
39982
+ try {
39983
+ const response = await page.goto(step.url, {
39984
+ waitUntil: step.waitUntil ?? "load",
39985
+ timeout: timeoutMs
39986
+ });
39987
+ status = response?.status();
39988
+ } catch (error) {
39989
+ throw new BotError("browser", `step '${step.id}' navigation failed (${execFailureDetail(error, step.url)})`, details);
39990
+ }
39991
+ const finalUrl = safeUrl(page.url()) ?? safeUrl(step.url);
39992
+ if (looksLikeAuthWall(page.url())) {
39993
+ throw new BotError("authentication", `step '${step.id}' landed on an authentication page \u2014 ` + "run `kk bot login <url> --save <profileName>` to renew the session", details);
39994
+ }
39995
+ if (status !== undefined) {
39996
+ const wall = classifyStatus(status, index, step.id);
39997
+ if (wall !== undefined)
39998
+ throw wall;
39999
+ }
40000
+ return {
40001
+ result: { index, id: step.id, type: step.type, ...finalUrl === undefined ? {} : { url: finalUrl } }
40002
+ };
40003
+ }
40004
+ case "wait": {
40005
+ try {
40006
+ await page.waitForSelector(step.selector, { timeout: timeoutMs });
40007
+ } catch {
40008
+ throw new BotError("browser", `step '${step.id}' timed out waiting for its selector`, details);
40009
+ }
40010
+ return { result: { index, id: step.id, type: step.type } };
40011
+ }
40012
+ case "click": {
40013
+ try {
40014
+ await page.locator(step.selector).first().click({ timeout: timeoutMs });
40015
+ } catch {
40016
+ throw new BotError("browser", `step '${step.id}' could not click its selector`, details);
40017
+ }
40018
+ return { result: { index, id: step.id, type: step.type } };
40019
+ }
40020
+ case "scroll": {
40021
+ try {
40022
+ await page.evaluate(`window.scrollBy(0, ${JSON.stringify(step.deltaY)})`);
40023
+ } catch {
40024
+ throw new BotError("browser", `step '${step.id}' could not scroll the page`, details);
40025
+ }
40026
+ return { result: { index, id: step.id, type: step.type } };
40027
+ }
40028
+ case "extract": {
40029
+ let text;
40030
+ try {
40031
+ const target = step.selector === undefined ? null : page.locator(step.selector).first();
40032
+ text = await applyTimeout(step.format === "html" ? target === null ? page.content() : target.evaluate("(element) => element.outerHTML").then((value) => String(value)) : target === null ? page.evaluate('document.body ? document.body.innerText : ""').then((value) => String(value)) : target.innerText(), timeoutMs);
40033
+ } catch {
40034
+ throw new BotError("browser", `step '${step.id}' could not extract its content`, details);
40035
+ }
40036
+ if (text.trim() === "")
40037
+ throw emptyFailure(step.id, "step", index);
40038
+ const pageUrl = safeUrl(page.url());
40039
+ return {
40040
+ result: { index, id: step.id, type: step.type, ...pageUrl === undefined ? {} : { url: pageUrl } },
40041
+ artifact: {
40042
+ id: step.id,
40043
+ kind: step.format,
40044
+ body: text,
40045
+ ...pageUrl === undefined ? {} : { url: pageUrl },
40046
+ stepIndex: index
40047
+ }
40048
+ };
40049
+ }
40050
+ }
40051
+ }
40052
+ function enforceCaps(artifact, artifacts, aggregate) {
40053
+ if (artifacts.length >= MAX_ARTIFACTS) {
40054
+ throw new BotError("browser", `collection produced more than ${MAX_ARTIFACTS} artifacts`, {
40055
+ ...artifact.stepIndex === undefined ? {} : { stepIndex: artifact.stepIndex },
40056
+ stepId: artifact.id
40057
+ });
40058
+ }
40059
+ const bytes = Buffer.byteLength(artifact.body, "utf8");
40060
+ if (bytes > MAX_ARTIFACT_BYTES) {
40061
+ throw new BotError("browser", `artifact '${artifact.id}' exceeds the per-artifact body cap`, {
40062
+ ...artifact.stepIndex === undefined ? {} : { stepIndex: artifact.stepIndex },
40063
+ stepId: artifact.id
40064
+ });
40065
+ }
40066
+ const total = aggregate + bytes;
40067
+ if (total > MAX_AGGREGATE_BYTES) {
40068
+ throw new BotError("browser", `collection exceeded the aggregate body cap`, { stepId: artifact.id });
40069
+ }
40070
+ return total;
40071
+ }
40072
+ async function applyTimeout(promise, timeoutMs) {
40073
+ let timer;
40074
+ const expiry = new Promise((_resolve, reject) => {
40075
+ timer = setTimeout(() => reject(new StepTimeoutError), timeoutMs);
40076
+ });
40077
+ try {
40078
+ return await Promise.race([promise, expiry]);
40079
+ } finally {
40080
+ if (timer !== undefined)
40081
+ clearTimeout(timer);
40082
+ }
40083
+ }
40084
+ async function waitWithin(promise, budgetMs) {
40085
+ if (budgetMs <= 0)
40086
+ return false;
40087
+ let timer;
40088
+ const expiry = new Promise((resolve) => {
40089
+ timer = setTimeout(() => resolve(false), budgetMs);
40090
+ });
40091
+ try {
40092
+ return await Promise.race([promise.then(() => true), expiry]);
40093
+ } finally {
40094
+ if (timer !== undefined)
40095
+ clearTimeout(timer);
40096
+ }
40097
+ }
40098
+ async function runBotCollection(profileName, plan, options = {}) {
40099
+ const normalized = normalizePlan(plan);
40100
+ const name = assertSafeBotName(profileName);
40101
+ const fileSystem = options.fileSystem ?? createNodeFileSystem();
40102
+ const now = options.now ?? Date.now;
40103
+ const deadline = now() + normalized.timeoutMs;
40104
+ const profileDir = resolveBotProfileDir(name, { root: options.root });
40105
+ if (lstat(profileDir) === null)
40106
+ throw missingBotProfile(name, false);
40107
+ const acquire = options.acquireLease ?? acquireProfileLease;
40108
+ const lease = await acquire(profileDir, { leaseRoot: options.leaseRoot, fileSystem });
40109
+ const captures = normalized.responses.map((declaration) => ({
40110
+ declaration,
40111
+ matches: [],
40112
+ pending: [],
40113
+ readFailures: 0
40114
+ }));
40115
+ let context;
40116
+ try {
40117
+ const launcher = options.launcher ?? createKkBrowserLauncher(undefined, { lease, physicalProfileDir: profileDir }, { leaseRoot: options.leaseRoot, fileSystem });
40118
+ context = await launcher.launch({ profileDir, headless: true });
40119
+ const activeContext = context;
40120
+ if (captures.length > 0) {
40121
+ activeContext.on("response", (response) => {
40122
+ const raw = response.url();
40123
+ let parsed;
40124
+ try {
40125
+ parsed = new URL(raw);
40126
+ } catch {
40127
+ return;
40128
+ }
40129
+ for (const state of captures) {
40130
+ const { origin, pathPrefix } = state.declaration;
40131
+ if (origin !== undefined && parsed.origin !== origin)
40132
+ continue;
40133
+ if (!parsed.pathname.startsWith(pathPrefix))
40134
+ continue;
40135
+ const status = response.status();
40136
+ const failure = classifyStatus(status, undefined, state.declaration.id, "capture");
40137
+ if (failure !== undefined) {
40138
+ state.failure ??= failure;
40139
+ continue;
40140
+ }
40141
+ state.pending.push(readBody(response).then((body) => {
40142
+ state.matches.push({
40143
+ status,
40144
+ text: body.toString("utf8"),
40145
+ url: `${parsed.origin}${parsed.pathname}`
40146
+ });
40147
+ }, () => {
40148
+ state.readFailures += 1;
40149
+ }));
40150
+ }
40151
+ });
40152
+ }
40153
+ const page = await openBotPage(activeContext);
40154
+ const steps = [];
40155
+ const artifacts = [];
40156
+ let aggregate = 0;
40157
+ for (const [index, step] of normalized.steps.entries()) {
40158
+ const timeoutMs = stepTimeout(step, deadline - now(), index);
40159
+ let outcome;
40160
+ try {
40161
+ outcome = await applyTimeout(runStep(step, index, activeContext, page, timeoutMs), timeoutMs);
40162
+ } catch (error) {
40163
+ if (error instanceof StepTimeoutError) {
40164
+ throw new BotError("browser", `step '${step.id}' exceeded the collection deadline`, {
40165
+ stepIndex: index,
40166
+ stepId: step.id
40167
+ });
40168
+ }
40169
+ throw error;
40170
+ }
40171
+ steps.push(outcome.result);
40172
+ if (outcome.artifact !== undefined) {
40173
+ aggregate = enforceCaps(outcome.artifact, artifacts, aggregate);
40174
+ artifacts.push(outcome.artifact);
40175
+ }
40176
+ }
40177
+ for (const state of captures) {
40178
+ if (state.failure !== undefined)
40179
+ throw state.failure;
40180
+ const settled = await waitWithin(Promise.all(state.pending).then(() => {
40181
+ return;
40182
+ }), deadline - now());
40183
+ if (!settled) {
40184
+ throw new BotError("browser", `response capture '${state.declaration.id}' exceeded the collection deadline`, {
40185
+ stepId: state.declaration.id
40186
+ });
40187
+ }
40188
+ if (state.failure !== undefined)
40189
+ throw state.failure;
40190
+ const found = state.matches.filter((match) => match.text.trim() !== "");
40191
+ if (found.length === 0 && state.readFailures > 0) {
40192
+ throw new BotError("browser", `response capture '${state.declaration.id}' could not be read`, {
40193
+ stepId: state.declaration.id
40194
+ });
40195
+ }
40196
+ if (found.length === 0)
40197
+ throw emptyFailure(state.declaration.id, "capture");
40198
+ for (const match of found) {
40199
+ const artifact = {
40200
+ id: state.declaration.id,
40201
+ kind: "response",
40202
+ body: match.text,
40203
+ status: match.status,
40204
+ url: match.url
40205
+ };
40206
+ aggregate = enforceCaps(artifact, artifacts, aggregate);
40207
+ artifacts.push(artifact);
40208
+ }
40209
+ }
40210
+ return { steps, artifacts };
40211
+ } finally {
40212
+ await closeBotContext(context);
40213
+ await Promise.allSettled(captures.flatMap((state) => state.pending));
40214
+ await lease.release();
40215
+ }
40216
+ }
40217
+ var DEFAULT_STEP_TIMEOUT_MS2 = 30000, DEFAULT_RUN_TIMEOUT_MS = 120000, MAX_RUN_TIMEOUT_MS = 600000, MAX_ARTIFACT_BYTES, MAX_AGGREGATE_BYTES, MAX_ARTIFACTS = 100, SAFE_ID, AUTH_PATH, NAVIGATION_WAIT_UNTIL, StepTimeoutError;
40218
+ var init_bot_collection = __esm(() => {
40219
+ init_dist3();
40220
+ init_bot();
40221
+ init_bot_fs();
40222
+ init_browser();
40223
+ init_profile_lease();
40224
+ MAX_ARTIFACT_BYTES = 5 * 1024 * 1024;
40225
+ MAX_AGGREGATE_BYTES = 20 * 1024 * 1024;
40226
+ SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
40227
+ AUTH_PATH = /(?:^|\/)(?:login|signin|sign-in|auth|sso)(?:\/|$)/i;
40228
+ NAVIGATION_WAIT_UNTIL = ["load", "domcontentloaded", "networkidle"];
40229
+ StepTimeoutError = class StepTimeoutError extends Error {
40230
+ };
40231
+ });
40232
+
39655
40233
  // ../../node_modules/.bun/@logtape+logtape@2.3.1/node_modules/@logtape/logtape/dist/util.node.js
39656
40234
  var exports_util_node = {};
39657
40235
  __export(exports_util_node, {
@@ -41904,7 +42482,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
41904
42482
  shortVideo: Object.freeze({
41905
42483
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
41906
42484
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
41907
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
42485
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
41908
42486
  })
41909
42487
  })
41910
42488
  });
@@ -42103,11 +42681,11 @@ var PluginManifestSchemaBase = looseObject({
42103
42681
  });
42104
42682
  var PluginManifestSchema = PluginManifestSchemaBase.superRefine((manifest, ctx) => {
42105
42683
  if (manifest.browserSession !== undefined) {
42106
- if (manifest.kind !== "publish") {
42684
+ if (manifest.kind !== "publish" && manifest.kind !== "ingestion") {
42107
42685
  ctx.addIssue({
42108
42686
  code: "custom",
42109
42687
  path: ["browserSession"],
42110
- message: `browserSession requires kind "publish", not "${manifest.kind}"`
42688
+ message: `browserSession requires kind "publish" or "ingestion", not "${manifest.kind}"`
42111
42689
  });
42112
42690
  }
42113
42691
  if (manifest.check === undefined) {
@@ -48567,6 +49145,8 @@ function collectSetting2(value, previous) {
48567
49145
  }
48568
49146
 
48569
49147
  // src/commands/bot.ts
49148
+ import { join as join14 } from "path";
49149
+ init_dist3();
48570
49150
  init_commander();
48571
49151
 
48572
49152
  // src/bot-adapter.ts
@@ -48643,6 +49223,20 @@ function bindAdapterSession(candidate) {
48643
49223
  };
48644
49224
  }
48645
49225
 
49226
+ // src/bot-plan.ts
49227
+ function decodeBotPlan(raw) {
49228
+ let parsed;
49229
+ try {
49230
+ parsed = JSON.parse(raw);
49231
+ } catch {
49232
+ return { ok: false, reason: "invalid-json" };
49233
+ }
49234
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
49235
+ return { ok: false, reason: "not-object" };
49236
+ }
49237
+ return { ok: true, plan: parsed };
49238
+ }
49239
+
48646
49240
  // src/byte-output.ts
48647
49241
  import { readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "fs";
48648
49242
  function writeBytes(chunk) {
@@ -48661,7 +49255,10 @@ function writeFileBytes(path, bytes) {
48661
49255
  init_output2();
48662
49256
  var botHarness;
48663
49257
  function loadBotHarness() {
48664
- botHarness ??= Promise.resolve().then(() => (init_browser(), exports_browser));
49258
+ botHarness ??= Promise.all([
49259
+ Promise.resolve().then(() => (init_browser(), exports_browser)),
49260
+ Promise.resolve().then(() => (init_bot_collection(), exports_bot_collection))
49261
+ ]).then(([browser, collection]) => ({ ...browser, ...collection }));
48665
49262
  return botHarness;
48666
49263
  }
48667
49264
  async function runBotAction(load, action) {
@@ -48805,16 +49402,77 @@ function execHeaderBlock(status, statusText, headers) {
48805
49402
 
48806
49403
  `;
48807
49404
  }
49405
+ function parsePlanMaxTime(harness, value) {
49406
+ const seconds = Number(value);
49407
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > 600) {
49408
+ throw new harness.BotError("usage", "--max-time must be a positive number of seconds (up to 600)");
49409
+ }
49410
+ return Math.round(seconds * 1000);
49411
+ }
49412
+ async function readPlanFile(harness, planPath) {
49413
+ let raw;
49414
+ try {
49415
+ raw = await createNodeFileSystem().readFile(planPath);
49416
+ } catch {
49417
+ throw new harness.BotError("usage", `could not read plan file '${planPath}'`);
49418
+ }
49419
+ const decoded = decodeBotPlan(raw);
49420
+ if (!decoded.ok) {
49421
+ throw new harness.BotError("usage", decoded.reason === "not-object" ? "plan must be a JSON object" : "plan file is not valid JSON");
49422
+ }
49423
+ return decoded.plan;
49424
+ }
49425
+ async function botPlanAction(load, name, planPath, options) {
49426
+ await runBotAction(load, async (harness) => {
49427
+ const plan = await readPlanFile(harness, planPath);
49428
+ const timeoutMs = options.maxTime === undefined ? undefined : parsePlanMaxTime(harness, options.maxTime);
49429
+ const result = await harness.runBotCollection(name, plan, {
49430
+ ...timeoutMs === undefined ? {} : { timeoutMs }
49431
+ });
49432
+ if (options.output !== undefined) {
49433
+ const fs = createNodeFileSystem();
49434
+ await fs.ensureDir(options.output);
49435
+ harness.chmod(options.output, 448);
49436
+ const sanitizedArtifacts = [];
49437
+ for (const [index, artifact] of result.artifacts.entries()) {
49438
+ const safeName = `${String(index).padStart(2, "0")}-${artifact.id.replace(/[^A-Za-z0-9_-]/g, "-")}.txt`;
49439
+ const filePath = join14(options.output, safeName);
49440
+ await fs.writeFile(filePath, artifact.body);
49441
+ harness.chmod(filePath, 384);
49442
+ sanitizedArtifacts.push({
49443
+ id: artifact.id,
49444
+ kind: artifact.kind,
49445
+ file: safeName,
49446
+ ...artifact.status !== undefined ? { status: artifact.status } : {},
49447
+ ...artifact.url !== undefined ? { url: artifact.url } : {},
49448
+ ...artifact.stepIndex !== undefined ? { stepIndex: artifact.stepIndex } : {}
49449
+ });
49450
+ }
49451
+ const summary = {
49452
+ ok: true,
49453
+ steps: result.steps,
49454
+ artifacts: sanitizedArtifacts
49455
+ };
49456
+ const resultPath = join14(options.output, "result.json");
49457
+ await fs.writeFile(resultPath, JSON.stringify(summary, null, 2));
49458
+ harness.chmod(resultPath, 384);
49459
+ consoleOutput.write(JSON.stringify(summary, null, 2));
49460
+ } else {
49461
+ consoleOutput.write(JSON.stringify({ ok: true, ...result }, null, 2));
49462
+ }
49463
+ });
49464
+ }
48808
49465
  function registerBotCommand(program, deps = {}) {
48809
49466
  const load = deps.load ?? loadBotHarness;
48810
- const bot = program.command("bot").description("Named local browser sessions (list, login, logout, open, exec)");
49467
+ const bot = program.command("bot").description("Named local browser sessions (list, login, logout, open, exec, plan)");
48811
49468
  bot.command("list").description("List cached local bot profiles: name, cached, default URL, identity, last login, expires").action(() => botListAction(load));
48812
49469
  bot.command("login").description("Open a site headed and save it as a named bot session after terminal confirmation").argument("<url>", "Login URL to open (http/https; its query is never saved)").requiredOption("--save <name>", "Bot name matching [A-Za-z0-9][A-Za-z0-9_-]{0,63}").action((url, options) => botLoginAction(load, url, options));
48813
49470
  bot.command("logout").description("Remove a named bot's local profile and credentials (no server-side revocation)").argument("<name>", "Bot name").action((name) => botLogoutAction(load, name));
48814
49471
  bot.command("open").description("Open a named bot's saved page headed until the browser closes").argument("<name>", "Bot name").option("--login", "Reauthenticate first, then reopen the saved page for interaction").action((name, options) => botOpenAction(load, name, options));
48815
49472
  const exec = bot.command("exec").description("Send one request with a named bot's cached cookie session (curl option subset)").argument("<name>", "Bot name").argument("<url>", "Request URL (http/https, no credentials; sent as given, query kept)").option("-X, --request <method>", "HTTP method (default GET, or POST when -d is given)").option("-H, --header <header>", 'Request header "Name: value" (repeatable)', collectHeader).option("-d, --data <data>", "Request body: a literal, or @file read raw").option("-o, --output <file>", "Write the response body to a file instead of stdout").option("-i, --include", "Include the status line and response headers before the body (stdout or the -o file)").option("-L, --location", "Follow redirects (default: return the 3xx response as-is)").option("-f, --fail", "Exit 1 without the body when the status is 400 or above").option("-m, --max-time <seconds>", "Whole-request timeout in seconds (default: Playwright 30s)").action((name, url, options) => botExecAction(load, name, url, options));
49473
+ const plan = bot.command("plan").description("Execute a declarative collection plan with a named bot session").argument("<name>", "Bot name").argument("<plan>", "Path to plan JSON file").option("-o, --output <dir>", "Directory to write captured artifact bodies (0600 mode)").option("-m, --max-time <seconds>", "Whole-run timeout in seconds (default: 120s, max: 600s)").action((name, planPath, options) => botPlanAction(load, name, planPath, options));
48816
49474
  bot.hook("preSubcommand", (_parent, subcommand) => {
48817
- if (subcommand === exec) {
49475
+ if (subcommand === exec || subcommand === plan) {
48818
49476
  subcommand.exitOverride((error) => {
48819
49477
  throw error.exitCode === 1 ? new CommanderError(2, error.code, error.message) : error;
48820
49478
  });
@@ -48827,7 +49485,7 @@ init_commander();
48827
49485
 
48828
49486
  // src/fanin.ts
48829
49487
  import { tmpdir } from "os";
48830
- import { isAbsolute as isAbsolute6, join as join14, resolve as resolve14 } from "path";
49488
+ import { isAbsolute as isAbsolute6, join as join15, resolve as resolve14 } from "path";
48831
49489
  init_dist3();
48832
49490
  init_dist();
48833
49491
  var DEFAULT_SOURCE_TIMEOUT_MS = 30 * 60 * 1000;
@@ -49023,7 +49681,7 @@ async function collectSourceDocs(discovery, source, timeoutMs) {
49023
49681
  if (!await fs.exists(entryPath)) {
49024
49682
  throw new Error(`Plugin entry script does not exist: ${entryPath}`);
49025
49683
  }
49026
- const outTmp = join14(tmpdir(), `kk-fanin-${source.plugin}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
49684
+ const outTmp = join15(tmpdir(), `kk-fanin-${source.plugin}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
49027
49685
  try {
49028
49686
  const proc = await spawnPluginEntryAsync({
49029
49687
  entryPath,
@@ -49131,7 +49789,7 @@ async function runFanin(argv) {
49131
49789
 
49132
49790
  // src/fanout.ts
49133
49791
  import { tmpdir as tmpdir2 } from "os";
49134
- import { isAbsolute as isAbsolute7, join as join15, resolve as resolve15 } from "path";
49792
+ import { isAbsolute as isAbsolute7, join as join16, resolve as resolve15 } from "path";
49135
49793
  init_dist3();
49136
49794
  init_dist();
49137
49795
  var EXIT_FAILURE = 1;
@@ -49419,7 +50077,7 @@ async function pluginDispatch(target, contentPath, discovery, targetTimeoutMs) {
49419
50077
  if (!await fs.exists(entryPath)) {
49420
50078
  throw new Error(`Plugin entry script does not exist: ${entryPath}`);
49421
50079
  }
49422
- const outTmp = join15(tmpdir2(), `kk-fanout-${target}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
50080
+ const outTmp = join16(tmpdir2(), `kk-fanout-${target}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
49423
50081
  try {
49424
50082
  const proc = await spawnPluginEntryAsync({
49425
50083
  entryPath,
@@ -49632,7 +50290,7 @@ function registerExecutorCommand(program) {
49632
50290
  init_commander();
49633
50291
 
49634
50292
  // src/itc-candidates.ts
49635
- import { join as join18 } from "path";
50293
+ import { join as join19 } from "path";
49636
50294
  init_dist3();
49637
50295
  init_dist();
49638
50296
  init_zod();
@@ -49805,19 +50463,19 @@ async function itcDecision(request, fs = createNodeFileSystem(), executor = new
49805
50463
 
49806
50464
  // src/itc-topic.ts
49807
50465
  import { createHash as createHash3 } from "crypto";
49808
- import { join as join17, resolve as resolve17 } from "path";
50466
+ import { join as join18, resolve as resolve17 } from "path";
49809
50467
  init_dist3();
49810
50468
  init_dist();
49811
50469
  init_zod();
49812
50470
 
49813
50471
  // src/package-root.ts
49814
50472
  init_dist3();
49815
- import { dirname as dirname11, join as join16, resolve as resolve16 } from "path";
50473
+ import { dirname as dirname11, join as join17, resolve as resolve16 } from "path";
49816
50474
  var SHIPPED_DIR = "plugins/kk";
49817
50475
  async function findPackageRoot(fs, start) {
49818
50476
  let dir = resolve16(start);
49819
50477
  for (;; ) {
49820
- if (await fs.exists(join16(dir, SHIPPED_DIR)))
50478
+ if (await fs.exists(join17(dir, SHIPPED_DIR)))
49821
50479
  return dir;
49822
50480
  const parent = resolve16(dir, "..");
49823
50481
  if (parent === dir)
@@ -49873,7 +50531,7 @@ async function resolveTopicProfilePath(fs, topic, customPath) {
49873
50531
  if (customPath !== undefined && await fs.exists(customPath)) {
49874
50532
  return customPath;
49875
50533
  }
49876
- const candidate = join17(await resolvePackageRoot(fs), "plugins/kk/decisions/extract", `${topic}.yaml`);
50534
+ const candidate = join18(await resolvePackageRoot(fs), "plugins/kk/decisions/extract", `${topic}.yaml`);
49877
50535
  if (await fs.exists(candidate))
49878
50536
  return candidate;
49879
50537
  throw new Error(`no profile for topic '${topic}': expected plugins/kk/decisions/extract/${topic}.yaml under the package root (cwd or script tree)`);
@@ -49943,9 +50601,9 @@ async function itcTopicExtract(request, fs = createNodeFileSystem()) {
49943
50601
  poolDigest,
49944
50602
  ...request.refreshRun?.runId ? { collectRunId: request.refreshRun.runId } : {}
49945
50603
  };
49946
- await fs.writeFile(join17(request.intakeDir, "topic-pool.json"), `${JSON.stringify(docs, null, 2)}
50604
+ await fs.writeFile(join18(request.intakeDir, "topic-pool.json"), `${JSON.stringify(docs, null, 2)}
49947
50605
  `);
49948
- await fs.writeFile(join17(request.intakeDir, "topic-pool-manifest.json"), `${JSON.stringify(manifest, null, 2)}
50606
+ await fs.writeFile(join18(request.intakeDir, "topic-pool-manifest.json"), `${JSON.stringify(manifest, null, 2)}
49949
50607
  `);
49950
50608
  return { count: docs.length, poolDigest };
49951
50609
  }
@@ -49968,9 +50626,9 @@ var ItcTopicValidateRequestSchema = object2({
49968
50626
  parentRunId: string2().min(1)
49969
50627
  });
49970
50628
  async function itcTopicValidate(request, fs = createNodeFileSystem()) {
49971
- const manifestPath = join17(request.intakeDir, "topic-pool-manifest.json");
49972
- const poolPath = join17(request.intakeDir, "topic-pool.json");
49973
- const candidatesPath = join17(request.intakeDir, "topic-candidates.json");
50629
+ const manifestPath = join18(request.intakeDir, "topic-pool-manifest.json");
50630
+ const poolPath = join18(request.intakeDir, "topic-pool.json");
50631
+ const candidatesPath = join18(request.intakeDir, "topic-candidates.json");
49974
50632
  if (!await fs.exists(manifestPath) || !await fs.exists(poolPath)) {
49975
50633
  throw new Error(`topic pool artifacts not found in ${request.intakeDir}`);
49976
50634
  }
@@ -50014,7 +50672,7 @@ async function itcTopicValidate(request, fs = createNodeFileSystem()) {
50014
50672
  }
50015
50673
  }
50016
50674
  }
50017
- await fs.writeFile(join17(request.intakeDir, ".topic-candidates-valid"), `${new Date().toISOString()}
50675
+ await fs.writeFile(join18(request.intakeDir, ".topic-candidates-valid"), `${new Date().toISOString()}
50018
50676
  `);
50019
50677
  return { valid: true };
50020
50678
  }
@@ -50027,9 +50685,9 @@ var ItcTopicSelectRequestSchema = object2({
50027
50685
  });
50028
50686
  async function itcTopicSelect(request, fs = createNodeFileSystem()) {
50029
50687
  await itcTopicValidate(request, fs);
50030
- const manifestPath = join17(request.intakeDir, "topic-pool-manifest.json");
50031
- const poolPath = join17(request.intakeDir, "topic-pool.json");
50032
- const candidatesPath = join17(request.intakeDir, "topic-candidates.json");
50688
+ const manifestPath = join18(request.intakeDir, "topic-pool-manifest.json");
50689
+ const poolPath = join18(request.intakeDir, "topic-pool.json");
50690
+ const candidatesPath = join18(request.intakeDir, "topic-candidates.json");
50033
50691
  if (!await fs.exists(manifestPath) || !await fs.exists(poolPath) || !await fs.exists(candidatesPath)) {
50034
50692
  throw new Error(`intake artifacts missing in ${request.intakeDir}`);
50035
50693
  }
@@ -50042,7 +50700,7 @@ async function itcTopicSelect(request, fs = createNodeFileSystem()) {
50042
50700
  }
50043
50701
  const selectedDocSet = new Set(candidate.itemIds);
50044
50702
  const selectedDocs = poolDocs.filter((d) => selectedDocSet.has(d.id));
50045
- const selectedDocsPath = join17(request.intakeDir, "selected-docs.json");
50703
+ const selectedDocsPath = join18(request.intakeDir, "selected-docs.json");
50046
50704
  await fs.writeFile(selectedDocsPath, `${JSON.stringify(selectedDocs, null, 2)}
50047
50705
  `);
50048
50706
  const chosenSource = {
@@ -50056,7 +50714,7 @@ async function itcTopicSelect(request, fs = createNodeFileSystem()) {
50056
50714
  itemIds: candidate.itemIds,
50057
50715
  selectedDocsPath
50058
50716
  };
50059
- await fs.writeFile(join17(request.intakeDir, "chosen-source.json"), `${JSON.stringify(chosenSource, null, 2)}
50717
+ await fs.writeFile(join18(request.intakeDir, "chosen-source.json"), `${JSON.stringify(chosenSource, null, 2)}
50060
50718
  `);
50061
50719
  const storePath = await resolveStorePath(resolveKkConfigPath2(), request.dbPath);
50062
50720
  const store = await openStore({ path: storePath });
@@ -50095,7 +50753,7 @@ async function itcSelectionSettle(request, fs = createNodeFileSystem()) {
50095
50753
  const storePath = await resolveStorePath(resolveKkConfigPath2(), request.dbPath);
50096
50754
  if (request.outcome === "published") {
50097
50755
  let itemIds;
50098
- const chosenSourcePath = join17(request.intakeDir, "chosen-source.json");
50756
+ const chosenSourcePath = join18(request.intakeDir, "chosen-source.json");
50099
50757
  if (await fs.exists(chosenSourcePath)) {
50100
50758
  try {
50101
50759
  const chosen = JSON.parse(await fs.readFile(chosenSourcePath));
@@ -50125,7 +50783,7 @@ async function itcSelectionSettle(request, fs = createNodeFileSystem()) {
50125
50783
  guidance: "reconcile status manually via kk store mark-published or kk store release"
50126
50784
  };
50127
50785
  await fs.ensureDir(request.intakeDir);
50128
- await fs.writeFile(join17(request.intakeDir, ".selection-reconcile.json"), `${JSON.stringify(reconcileInfo, null, 2)}
50786
+ await fs.writeFile(join18(request.intakeDir, ".selection-reconcile.json"), `${JSON.stringify(reconcileInfo, null, 2)}
50129
50787
  `);
50130
50788
  return { settled: "retained", action: "reconcile_retained" };
50131
50789
  }
@@ -50210,7 +50868,7 @@ function buildTopicCandidates(pool) {
50210
50868
  return candidates;
50211
50869
  }
50212
50870
  async function runItcCandidates(options, fs = createNodeFileSystem(), executor) {
50213
- const intakeDir = options.intakeDir ?? join18(process.cwd(), ".itc-intake", options.parentRunId);
50871
+ const intakeDir = options.intakeDir ?? join19(process.cwd(), ".itc-intake", options.parentRunId);
50214
50872
  const { count: poolCount } = await itcTopicExtract({
50215
50873
  schemaVersion: 1,
50216
50874
  parentRunId: options.parentRunId,
@@ -50221,13 +50879,13 @@ async function runItcCandidates(options, fs = createNodeFileSystem(), executor)
50221
50879
  ...options.limit ? { limit: options.limit } : {},
50222
50880
  ...options.dbPath ? { dbPath: options.dbPath } : {}
50223
50881
  }, fs);
50224
- const pool = array(DocSchema).parse(JSON.parse(await fs.readFile(join18(intakeDir, "topic-pool.json"))));
50225
- const manifest = JSON.parse(await fs.readFile(join18(intakeDir, "topic-pool-manifest.json")));
50882
+ const pool = array(DocSchema).parse(JSON.parse(await fs.readFile(join19(intakeDir, "topic-pool.json"))));
50883
+ const manifest = JSON.parse(await fs.readFile(join19(intakeDir, "topic-pool-manifest.json")));
50226
50884
  const candidates = buildTopicCandidates(pool);
50227
50885
  if (candidates.length === 0) {
50228
50886
  throw new Error(`no citable pool item carries a source URI: cannot build topic candidates from ${poolCount} items`);
50229
50887
  }
50230
- await fs.writeFile(join18(intakeDir, "topic-candidates.json"), `${JSON.stringify({
50888
+ await fs.writeFile(join19(intakeDir, "topic-candidates.json"), `${JSON.stringify({
50231
50889
  schemaVersion: 1,
50232
50890
  parentRunId: options.parentRunId,
50233
50891
  poolDigest: manifest.poolDigest,
@@ -50239,8 +50897,8 @@ async function runItcCandidates(options, fs = createNodeFileSystem(), executor)
50239
50897
  parentRunId: options.parentRunId,
50240
50898
  decisionId: "kk-itc-topic-choice",
50241
50899
  candidates: candidates.map((c) => ({ id: c.id, title: c.title, description: c.reason })),
50242
- evidenceFiles: [join18(intakeDir, "topic-candidates.json")],
50243
- outPath: join18(intakeDir, "topic-decision.json")
50900
+ evidenceFiles: [join19(intakeDir, "topic-candidates.json")],
50901
+ outPath: join19(intakeDir, "topic-decision.json")
50244
50902
  }, fs, executor);
50245
50903
  for (const c of candidates) {
50246
50904
  echo(`${c.id} \u2014 ${c.title}`);
@@ -50686,14 +51344,14 @@ init_commander();
50686
51344
 
50687
51345
  // src/itc-stage.ts
50688
51346
  import { createHash as createHash7 } from "crypto";
50689
- import { join as join22 } from "path";
51347
+ import { join as join23 } from "path";
50690
51348
  init_dist3();
50691
51349
  init_dist();
50692
51350
 
50693
51351
  // src/itc-config.ts
50694
51352
  init_dist3();
50695
51353
  import { createHash as createHash4 } from "crypto";
50696
- import { dirname as dirname12, isAbsolute as isAbsolute8, join as join19, resolve as resolve20 } from "path";
51354
+ import { dirname as dirname12, isAbsolute as isAbsolute8, join as join20, resolve as resolve20 } from "path";
50697
51355
 
50698
51356
  class ItcConfigInvalidError extends Error {
50699
51357
  constructor(message) {
@@ -50762,7 +51420,7 @@ function expandHome3(value, homeDir) {
50762
51420
  if (value === "~")
50763
51421
  return homeDir;
50764
51422
  if (value.startsWith("~/"))
50765
- return join19(homeDir, value.slice(2));
51423
+ return join20(homeDir, value.slice(2));
50766
51424
  return value;
50767
51425
  }
50768
51426
  function canonicalJson(value) {
@@ -50780,7 +51438,7 @@ function resolveItcConfigPath(env, homeDir) {
50780
51438
  const explicit = env.KK_CONFIG;
50781
51439
  if (explicit !== undefined && explicit.trim() !== "")
50782
51440
  return expandHome3(explicit.trim(), homeDir);
50783
- return join19(homeDir, ".config", "kk", "config.yaml");
51441
+ return join20(homeDir, ".config", "kk", "config.yaml");
50784
51442
  }
50785
51443
  async function readItcConfigBlock(configPath, fs = createNodeFileSystem()) {
50786
51444
  if (!await fs.exists(configPath))
@@ -51124,18 +51782,18 @@ function resolveItcWorkspace(options, topic, input = {}) {
51124
51782
  dated: input.runDate !== undefined
51125
51783
  };
51126
51784
  }
51127
- const leaf = options.runDate !== null ? join19(slug, options.runDate) : slug;
51128
- return { workDir: join19(options.worksRoot, "kk-itc", leaf), topicName: slug, dated: options.runDate !== null };
51785
+ const leaf = options.runDate !== null ? join20(slug, options.runDate) : slug;
51786
+ return { workDir: join20(options.worksRoot, "kk-itc", leaf), topicName: slug, dated: options.runDate !== null };
51129
51787
  }
51130
51788
  async function writeItcOptionsSnapshot(workDir, options, fs = createNodeFileSystem()) {
51131
- const path = join19(workDir, "itc-options.json");
51789
+ const path = join20(workDir, "itc-options.json");
51132
51790
  await fs.ensureDir(workDir);
51133
51791
  await fs.writeFile(path, `${JSON.stringify(options, null, 2)}
51134
51792
  `);
51135
51793
  return path;
51136
51794
  }
51137
51795
  async function verifyItcOptionsSnapshot(workDir, options, fs = createNodeFileSystem()) {
51138
- const path = join19(workDir, "itc-options.json");
51796
+ const path = join20(workDir, "itc-options.json");
51139
51797
  if (!await fs.exists(path))
51140
51798
  return { ok: true };
51141
51799
  let saved;
@@ -51170,7 +51828,7 @@ async function verifyItcOptionsSnapshot(workDir, options, fs = createNodeFileSys
51170
51828
 
51171
51829
  // src/itc-plan.ts
51172
51830
  import { createHash as createHash5 } from "crypto";
51173
- import { join as join20, resolve as resolve21 } from "path";
51831
+ import { join as join21, resolve as resolve21 } from "path";
51174
51832
  init_dist3();
51175
51833
  init_zod();
51176
51834
  var ItcTargetsOriginSchema = _enum2([
@@ -51218,7 +51876,7 @@ var SLUG_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
51218
51876
  async function resolveDefaultPackageRoot(fs) {
51219
51877
  let dir = resolve21(process.cwd());
51220
51878
  for (;; ) {
51221
- if (await fs.exists(join20(dir, "plugins/kk/publish-presets")))
51879
+ if (await fs.exists(join21(dir, "plugins/kk/publish-presets")))
51222
51880
  return dir;
51223
51881
  const parent = resolve21(dir, "..");
51224
51882
  if (parent === dir)
@@ -51376,7 +52034,7 @@ async function loadPublishPreset(slug, roots = {}, fs = createNodeFileSystem())
51376
52034
  return resolvePresetFromRoots(fs, slug.trim(), projectRoot, packageRoot);
51377
52035
  }
51378
52036
  async function hasCoverImage(fs, workDir) {
51379
- const dir = join20(workDir, "4-illustrations");
52037
+ const dir = join21(workDir, "4-illustrations");
51380
52038
  if (!await fs.exists(dir))
51381
52039
  return false;
51382
52040
  try {
@@ -51387,7 +52045,7 @@ async function hasCoverImage(fs, workDir) {
51387
52045
  }
51388
52046
  }
51389
52047
  async function hasOrderedImages(fs, workDir) {
51390
- const path = join20(workDir, "4-publish", "content.json");
52048
+ const path = join21(workDir, "4-publish", "content.json");
51391
52049
  if (!await fs.exists(path))
51392
52050
  return false;
51393
52051
  try {
@@ -51501,7 +52159,7 @@ async function buildItcPublishPlan(request, plugins, fs = createNodeFileSystem()
51501
52159
 
51502
52160
  // src/itc-publish.ts
51503
52161
  import { createHash as createHash6 } from "crypto";
51504
- import { join as join21 } from "path";
52162
+ import { join as join22 } from "path";
51505
52163
  init_dist3();
51506
52164
  init_dist();
51507
52165
  init_zod();
@@ -51535,11 +52193,11 @@ var ItcReceiptSchema = object2({
51535
52193
  finishedAt: string2().optional()
51536
52194
  }).strict();
51537
52195
  async function findCover(fs, workDir) {
51538
- const dir = join21(workDir, "4-illustrations");
52196
+ const dir = join22(workDir, "4-illustrations");
51539
52197
  if (!await fs.exists(dir))
51540
52198
  return;
51541
52199
  const cover = (await fs.readDir(dir)).find((file) => file.startsWith("cover."));
51542
- return cover ? join21(dir, cover) : undefined;
52200
+ return cover ? join22(dir, cover) : undefined;
51543
52201
  }
51544
52202
  async function readFrontmatter(fs, path) {
51545
52203
  if (!await fs.exists(path))
@@ -51572,7 +52230,7 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51572
52230
  const snapshot = await readOptionsSnapshot(fs, workDir);
51573
52231
  const [targetsArg = "", sourceLocale = "", liveArg = "", presetArg = ""] = snapshot ? [snapshot.publishTargets, snapshot.sourceLocale, String(snapshot.publishLive), ""] : positional;
51574
52232
  const live = liveArg === "true";
51575
- const draftPath = join21(workDir, "3-draft-draft-article.md");
52233
+ const draftPath = join22(workDir, "3-draft-draft-article.md");
51576
52234
  if (!await fs.exists(draftPath)) {
51577
52235
  echoError(`final draft not found: ${draftPath}`);
51578
52236
  return 1;
@@ -51592,10 +52250,10 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51592
52250
  return 1;
51593
52251
  }
51594
52252
  const content = { title, format: "markdown", body };
51595
- const outlinePath = join21(workDir, "2-outline", "outline-approved.md");
52253
+ const outlinePath = join22(workDir, "2-outline", "outline-approved.md");
51596
52254
  if (await fs.exists(outlinePath))
51597
52255
  content.outline = (await fs.readFile(outlinePath)).trim();
51598
- const docsPath = join21(workDir, "docs.json");
52256
+ const docsPath = join22(workDir, "docs.json");
51599
52257
  if (await fs.exists(docsPath)) {
51600
52258
  try {
51601
52259
  const docs = JSON.parse(await fs.readFile(docsPath));
@@ -51612,7 +52270,7 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51612
52270
  const cover = await findCover(fs, workDir);
51613
52271
  if (cover)
51614
52272
  metadata.coverImage = cover;
51615
- const brief = await readFrontmatter(fs, join21(workDir, "brief.md"));
52273
+ const brief = await readFrontmatter(fs, join22(workDir, "brief.md"));
51616
52274
  if (brief.tags)
51617
52275
  metadata.tags = splitList(brief.tags);
51618
52276
  if (brief.keywords)
@@ -51620,9 +52278,9 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51620
52278
  if (brief.description)
51621
52279
  metadata.description = brief.description;
51622
52280
  content.metadata = metadata;
51623
- const publishDir = join21(workDir, "4-publish");
52281
+ const publishDir = join22(workDir, "4-publish");
51624
52282
  await fs.ensureDir(publishDir);
51625
- await fs.writeFile(join21(publishDir, "content.json"), `${JSON.stringify(content, null, 2)}
52283
+ await fs.writeFile(join22(publishDir, "content.json"), `${JSON.stringify(content, null, 2)}
51626
52284
  `);
51627
52285
  const fromLaunch = snapshot?.publishPresetSource === "launch" ? snapshot.publishPreset : null;
51628
52286
  const fromConfig = snapshot?.publishPresetSource === "config" ? snapshot.publishPreset : null;
@@ -51649,7 +52307,7 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51649
52307
  title: `${resolvedTargets.presetName}: ${resolvedTargets.targets.map((t) => t.plugin).join(", ")}`
51650
52308
  }
51651
52309
  ],
51652
- outPath: join21(workDir, "4-publish", "preset-decision.json")
52310
+ outPath: join22(workDir, "4-publish", "preset-decision.json")
51653
52311
  }, fs);
51654
52312
  if (decision.value !== "suggested")
51655
52313
  resolvedTargets = { targets: [], origin: "none" };
@@ -51665,7 +52323,7 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51665
52323
  browser: [],
51666
52324
  targets: []
51667
52325
  };
51668
- await fs.writeFile(join21(publishDir, "publish-plan.json"), `${JSON.stringify(emptyPlan, null, 2)}
52326
+ await fs.writeFile(join22(publishDir, "publish-plan.json"), `${JSON.stringify(emptyPlan, null, 2)}
51669
52327
  `);
51670
52328
  return 0;
51671
52329
  }
@@ -51682,7 +52340,7 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51682
52340
  };
51683
52341
  try {
51684
52342
  const plan = await buildItcPublishPlan(req, plugins, fs);
51685
- const planPath = join21(publishDir, "publish-plan.json");
52343
+ const planPath = join22(publishDir, "publish-plan.json");
51686
52344
  await fs.writeFile(planPath, `${JSON.stringify(plan, null, 2)}
51687
52345
  `);
51688
52346
  await prepareTargetPayloads(fs, workDir, plan, plugins);
@@ -51693,13 +52351,13 @@ async function itcMaterializePlan(args, fs = createNodeFileSystem()) {
51693
52351
  }
51694
52352
  }
51695
52353
  async function readOptionsSnapshot(fs, workDir) {
51696
- const path = join21(workDir, "itc-options.json");
52354
+ const path = join22(workDir, "itc-options.json");
51697
52355
  if (!await fs.exists(path))
51698
52356
  return;
51699
52357
  return JSON.parse(await fs.readFile(path));
51700
52358
  }
51701
52359
  async function prepareTargetPayloads(fs, workDir, plan, plugins) {
51702
- const publishDir = join21(workDir, "4-publish");
52360
+ const publishDir = join22(workDir, "4-publish");
51703
52361
  if (!plan.targets || plan.targets.length === 0)
51704
52362
  return;
51705
52363
  const planned = new Set(plan.targets.map((t) => t.plugin));
@@ -51717,9 +52375,9 @@ async function prepareTargetPayloads(fs, workDir, plan, plugins) {
51717
52375
  for (const target of plan.targets) {
51718
52376
  const variantEntry = plan.variants[target.variant];
51719
52377
  const baseFile = variantEntry?.file ?? "content.json";
51720
- let basePath = join21(publishDir, baseFile);
52378
+ let basePath = join22(publishDir, baseFile);
51721
52379
  if (!await fs.exists(basePath)) {
51722
- basePath = join21(publishDir, "content.json");
52380
+ basePath = join22(publishDir, "content.json");
51723
52381
  }
51724
52382
  if (!await fs.exists(basePath))
51725
52383
  continue;
@@ -51736,7 +52394,7 @@ async function prepareTargetPayloads(fs, workDir, plan, plugins) {
51736
52394
  }
51737
52395
  };
51738
52396
  const targetFileName = `content.${target.plugin}.json`;
51739
- const targetFilePath = join21(publishDir, targetFileName);
52397
+ const targetFilePath = join22(publishDir, targetFileName);
51740
52398
  const contentStr = `${JSON.stringify(isolatedContent, null, 2)}
51741
52399
  `;
51742
52400
  await fs.writeFile(targetFilePath, contentStr);
@@ -51744,7 +52402,7 @@ async function prepareTargetPayloads(fs, workDir, plan, plugins) {
51744
52402
  target.payloadPath = `4-publish/${targetFileName}`;
51745
52403
  target.payloadDigest = payloadDigest;
51746
52404
  }
51747
- await fs.writeFile(join21(publishDir, "publish-plan.json"), `${JSON.stringify(plan, null, 2)}
52405
+ await fs.writeFile(join22(publishDir, "publish-plan.json"), `${JSON.stringify(plan, null, 2)}
51748
52406
  `);
51749
52407
  }
51750
52408
  async function probePlugin(plugin, executor = new NodeProcessExecutor) {
@@ -51779,7 +52437,7 @@ async function itcCheckTargets(args, fs = createNodeFileSystem(), executor = new
51779
52437
  echoError("usage: itc-check-targets <work_dir>");
51780
52438
  return 1;
51781
52439
  }
51782
- const planPath = join21(workDir, "4-publish/publish-plan.json");
52440
+ const planPath = join22(workDir, "4-publish/publish-plan.json");
51783
52441
  if (!await fs.exists(planPath))
51784
52442
  return 0;
51785
52443
  const plan = JSON.parse(await fs.readFile(planPath));
@@ -51808,7 +52466,7 @@ async function sendRows(options) {
51808
52466
  const sameDigest = (priorDigest, digest) => priorDigest !== undefined && digest !== undefined && priorDigest === digest;
51809
52467
  for (const row of rows) {
51810
52468
  const startedAt = new Date().toISOString();
51811
- const targetReceiptPath = join21(receiptsDir, `${row.key}.json`);
52469
+ const targetReceiptPath = join22(receiptsDir, `${row.key}.json`);
51812
52470
  let reattempt = false;
51813
52471
  let payloadPath = row.payloadPath;
51814
52472
  let preparedError;
@@ -51916,7 +52574,7 @@ async function sendRows(options) {
51916
52574
  await options.onReceipt(receipt);
51917
52575
  continue;
51918
52576
  }
51919
- const outPath = join21(publishDir, `fanout-result.${row.key}${retry ? ".retry" : ""}.json`);
52577
+ const outPath = join22(publishDir, `fanout-result.${row.key}${retry ? ".retry" : ""}.json`);
51920
52578
  if (reattempt && await fs.exists(outPath))
51921
52579
  await fs.deleteFile(outPath);
51922
52580
  const fanoutArgs = [
@@ -51995,8 +52653,8 @@ async function itcSendTargets(args, fs = createNodeFileSystem(), dispatch = runF
51995
52653
  echoError("usage: itc-send-targets <work_dir> [--retry]");
51996
52654
  return 1;
51997
52655
  }
51998
- const publishDir = join21(workDir, "4-publish");
51999
- const planPath = join21(publishDir, "publish-plan.json");
52656
+ const publishDir = join22(workDir, "4-publish");
52657
+ const planPath = join22(publishDir, "publish-plan.json");
52000
52658
  if (!await fs.exists(planPath))
52001
52659
  return 0;
52002
52660
  const plan = JSON.parse(await fs.readFile(planPath));
@@ -52004,10 +52662,10 @@ async function itcSendTargets(args, fs = createNodeFileSystem(), dispatch = runF
52004
52662
  return 0;
52005
52663
  const parentRunId = (await readOptionsSnapshot(fs, workDir))?.parentRunId;
52006
52664
  if (!parentRunId) {
52007
- echoError(`itc-send-targets: ${join21(workDir, "itc-options.json")} has no parentRunId`);
52665
+ echoError(`itc-send-targets: ${join22(workDir, "itc-options.json")} has no parentRunId`);
52008
52666
  return 1;
52009
52667
  }
52010
- const receiptsDir = join21(publishDir, "receipts");
52668
+ const receiptsDir = join22(publishDir, "receipts");
52011
52669
  await fs.ensureDir(receiptsDir);
52012
52670
  const planRaw = await fs.readFile(planPath);
52013
52671
  const planDigest = createHash6("sha256").update(planRaw).digest("hex");
@@ -52016,7 +52674,7 @@ async function itcSendTargets(args, fs = createNodeFileSystem(), dispatch = runF
52016
52674
  plugin: target.plugin,
52017
52675
  profile: target.profile,
52018
52676
  mode: target.mode,
52019
- payloadPath: join21(workDir, target.payloadPath ?? `4-publish/content.${target.plugin}.json`),
52677
+ payloadPath: join22(workDir, target.payloadPath ?? `4-publish/content.${target.plugin}.json`),
52020
52678
  transport: target.transport
52021
52679
  }));
52022
52680
  const outcome = await sendRows({
@@ -52040,12 +52698,12 @@ async function itcReconcileReceipts(args, fs = createNodeFileSystem()) {
52040
52698
  echoError("usage: itc-reconcile-receipts <work_dir>");
52041
52699
  return 1;
52042
52700
  }
52043
- const publishDir = join21(workDir, "4-publish");
52044
- const planPath = join21(publishDir, "publish-plan.json");
52701
+ const publishDir = join22(workDir, "4-publish");
52702
+ const planPath = join22(publishDir, "publish-plan.json");
52045
52703
  if (!await fs.exists(planPath))
52046
52704
  return 0;
52047
52705
  const plan = JSON.parse(await fs.readFile(planPath));
52048
- const chosenPath = join21(workDir, "chosen-source.json");
52706
+ const chosenPath = join22(workDir, "chosen-source.json");
52049
52707
  const chosen = await fs.exists(chosenPath) ? JSON.parse(await fs.readFile(chosenPath)) : undefined;
52050
52708
  const settle = async (outcome) => {
52051
52709
  if (chosen === undefined)
@@ -52062,10 +52720,10 @@ async function itcReconcileReceipts(args, fs = createNodeFileSystem()) {
52062
52720
  await settle("author_only");
52063
52721
  return 0;
52064
52722
  }
52065
- const receiptsDir = join21(publishDir, "receipts");
52723
+ const receiptsDir = join22(publishDir, "receipts");
52066
52724
  const receipts = [];
52067
52725
  for (const target of plan.targets) {
52068
- const rPath = join21(receiptsDir, `${target.plugin}.json`);
52726
+ const rPath = join22(receiptsDir, `${target.plugin}.json`);
52069
52727
  if (!await fs.exists(rPath)) {
52070
52728
  echoError(`itc-reconcile-receipts: missing receipt for target '${target.plugin}'`);
52071
52729
  return 1;
@@ -52090,12 +52748,12 @@ async function itcExportSeo(args, fs = createNodeFileSystem()) {
52090
52748
  echoError("usage: itc-export-seo <work_dir> [mode]");
52091
52749
  return 1;
52092
52750
  }
52093
- const seoDir = join21(workDir, "seo");
52751
+ const seoDir = join22(workDir, "seo");
52094
52752
  await fs.ensureDir(seoDir);
52095
52753
  if (mode === "off") {
52096
- await fs.writeFile(join21(seoDir, "prepublish-request.json"), `${JSON.stringify({ schemaVersion: 1, mode: "off", status: "not-assessed" }, null, 2)}
52754
+ await fs.writeFile(join22(seoDir, "prepublish-request.json"), `${JSON.stringify({ schemaVersion: 1, mode: "off", status: "not-assessed" }, null, 2)}
52097
52755
  `);
52098
- await fs.writeFile(join21(seoDir, "published-pages.json"), `${JSON.stringify({ schemaVersion: 1, mode: "off", pages: [], status: "not-assessed" }, null, 2)}
52756
+ await fs.writeFile(join22(seoDir, "published-pages.json"), `${JSON.stringify({ schemaVersion: 1, mode: "off", pages: [], status: "not-assessed" }, null, 2)}
52099
52757
  `);
52100
52758
  return 0;
52101
52759
  }
@@ -52105,14 +52763,14 @@ async function itcExportSeo(args, fs = createNodeFileSystem()) {
52105
52763
  status: "ready",
52106
52764
  draftFile: "3-draft-draft-article.md"
52107
52765
  };
52108
- await fs.writeFile(join21(seoDir, "prepublish-request.json"), `${JSON.stringify(prepublish, null, 2)}
52766
+ await fs.writeFile(join22(seoDir, "prepublish-request.json"), `${JSON.stringify(prepublish, null, 2)}
52109
52767
  `);
52110
- const receiptsDir = join21(workDir, "4-publish/receipts");
52768
+ const receiptsDir = join22(workDir, "4-publish/receipts");
52111
52769
  const verifiedPages = [];
52112
52770
  if (await fs.exists(receiptsDir)) {
52113
52771
  for (const file of (await fs.readDir(receiptsDir)).filter((f) => f.endsWith(".json"))) {
52114
52772
  try {
52115
- const r = JSON.parse(await fs.readFile(join21(receiptsDir, file)));
52773
+ const r = JSON.parse(await fs.readFile(join22(receiptsDir, file)));
52116
52774
  if (r.mode === "live" && r.effect === "confirmed" && r.publicUrlVerified === true && r.url) {
52117
52775
  verifiedPages.push({ plugin: r.plugin, url: r.url });
52118
52776
  }
@@ -52126,7 +52784,7 @@ async function itcExportSeo(args, fs = createNodeFileSystem()) {
52126
52784
  pages: verifiedPages,
52127
52785
  ...verifiedPages.length === 0 ? { reason: "no verified public live URLs available" } : {}
52128
52786
  };
52129
- await fs.writeFile(join21(seoDir, "published-pages.json"), `${JSON.stringify(publishedPages, null, 2)}
52787
+ await fs.writeFile(join22(seoDir, "published-pages.json"), `${JSON.stringify(publishedPages, null, 2)}
52130
52788
  `);
52131
52789
  return 0;
52132
52790
  }
@@ -52136,12 +52794,12 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52136
52794
  echoError("usage: itc-report-summary <work_dir> [max_revisions]");
52137
52795
  return 1;
52138
52796
  }
52139
- const reportDir = join21(workDir, "5-report");
52797
+ const reportDir = join22(workDir, "5-report");
52140
52798
  await fs.ensureDir(reportDir);
52141
52799
  let verdict = "PASS";
52142
52800
  let confidence = null;
52143
52801
  let outcome = "done";
52144
- const verdictPath = join21(workDir, ".itc-verdict.json");
52802
+ const verdictPath = join22(workDir, ".itc-verdict.json");
52145
52803
  const hasVerdict = await fs.exists(verdictPath);
52146
52804
  if (hasVerdict) {
52147
52805
  try {
@@ -52155,7 +52813,7 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52155
52813
  }
52156
52814
  }
52157
52815
  let revisions = 0;
52158
- const revPath = join21(workDir, ".auto-revise-count");
52816
+ const revPath = join22(workDir, ".auto-revise-count");
52159
52817
  if (await fs.exists(revPath)) {
52160
52818
  try {
52161
52819
  revisions = Number((await fs.readFile(revPath)).trim()) || 0;
@@ -52163,12 +52821,12 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52163
52821
  revisions = 0;
52164
52822
  }
52165
52823
  }
52166
- const receiptsDir = join21(workDir, "4-publish/receipts");
52824
+ const receiptsDir = join22(workDir, "4-publish/receipts");
52167
52825
  const receipts = [];
52168
52826
  if (await fs.exists(receiptsDir)) {
52169
52827
  for (const file of (await fs.readDir(receiptsDir)).filter((f) => f.endsWith(".json"))) {
52170
52828
  try {
52171
- const r = JSON.parse(await fs.readFile(join21(receiptsDir, file)));
52829
+ const r = JSON.parse(await fs.readFile(join22(receiptsDir, file)));
52172
52830
  receipts.push(r);
52173
52831
  } catch {}
52174
52832
  }
@@ -52176,7 +52834,7 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52176
52834
  if (receipts.some((r) => r.status !== "succeeded")) {
52177
52835
  outcome = "failed";
52178
52836
  }
52179
- const planPath = join21(workDir, "4-publish/publish-plan.json");
52837
+ const planPath = join22(workDir, "4-publish/publish-plan.json");
52180
52838
  let targetContract;
52181
52839
  if (await fs.exists(planPath)) {
52182
52840
  const planRaw = await fs.readFile(planPath);
@@ -52200,7 +52858,7 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52200
52858
  ...targetContract ? { targetContractFailure: targetContract } : {},
52201
52859
  maxRevisions: Number(maxRevisions) || 2
52202
52860
  };
52203
- await fs.writeFile(join21(reportDir, "report.json"), `${JSON.stringify(reportJson, null, 2)}
52861
+ await fs.writeFile(join22(reportDir, "report.json"), `${JSON.stringify(reportJson, null, 2)}
52204
52862
  `);
52205
52863
  const md = [
52206
52864
  "# ITC Publication Run Report",
@@ -52218,7 +52876,7 @@ async function itcReportSummary(args, fs = createNodeFileSystem()) {
52218
52876
  ...receipts.map((r) => `- ${r.plugin} (${r.profile}): status=${r.status}, effect=${r.effect}`)
52219
52877
  ].join(`
52220
52878
  `);
52221
- await fs.writeFile(join21(reportDir, "report.md"), `${md}
52879
+ await fs.writeFile(join22(reportDir, "report.md"), `${md}
52222
52880
  `);
52223
52881
  return 0;
52224
52882
  }
@@ -52231,13 +52889,13 @@ async function itcAuthorVerdict(args, fs = createNodeFileSystem()) {
52231
52889
  const auto = process.env.KK_ITC_AUTO === "true";
52232
52890
  const maxRevisions = Number(process.env.KK_ITC_MAX_REVISIONS ?? "2") || 2;
52233
52891
  const readCount = async (name) => {
52234
- const p = join21(workDir, name);
52892
+ const p = join22(workDir, name);
52235
52893
  if (!await fs.exists(p))
52236
52894
  return 0;
52237
52895
  const n = Number((await fs.readFile(p)).trim());
52238
52896
  return Number.isFinite(n) ? n : 0;
52239
52897
  };
52240
- const verdictPath = join21(workDir, ".itc-verdict.json");
52898
+ const verdictPath = join22(workDir, ".itc-verdict.json");
52241
52899
  let verdict = "";
52242
52900
  let confidence = "";
52243
52901
  if (await fs.exists(verdictPath)) {
@@ -52263,8 +52921,8 @@ async function itcAuthorVerdict(args, fs = createNodeFileSystem()) {
52263
52921
  } else {
52264
52922
  disposition = "fail";
52265
52923
  }
52266
- await fs.ensureDir(join21(workDir, ".itc"));
52267
- await fs.writeFile(join21(workDir, ".itc/disposition.txt"), `${disposition}
52924
+ await fs.ensureDir(join22(workDir, ".itc"));
52925
+ await fs.writeFile(join22(workDir, ".itc/disposition.txt"), `${disposition}
52268
52926
  `);
52269
52927
  return 0;
52270
52928
  }
@@ -52361,9 +53019,9 @@ async function runItcPublishPlan(args, fs) {
52361
53019
  try {
52362
53020
  const { plugins } = discoverAllPlugins();
52363
53021
  const plan = await buildItcPublishPlan(request, plugins, fs);
52364
- const outDir = join22(request.workDir, "4-publish");
53022
+ const outDir = join23(request.workDir, "4-publish");
52365
53023
  await fs.ensureDir(outDir);
52366
- await fs.writeFile(join22(outDir, "publish-plan.json"), `${JSON.stringify(plan, null, 4)}
53024
+ await fs.writeFile(join23(outDir, "publish-plan.json"), `${JSON.stringify(plan, null, 4)}
52367
53025
  `);
52368
53026
  return 0;
52369
53027
  } catch (err) {
@@ -52403,23 +53061,23 @@ async function runSlotDecision(args, fs) {
52403
53061
  }
52404
53062
  try {
52405
53063
  if (mode === "--topic") {
52406
- const candidatesPath = join22(dir, "topic-candidates.json");
53064
+ const candidatesPath = join23(dir, "topic-candidates.json");
52407
53065
  const artifact = JSON.parse(await fs.readFile(candidatesPath));
52408
53066
  const result = await itcDecision({
52409
53067
  parentRunId,
52410
53068
  decisionId: "kk-itc-topic-choice",
52411
53069
  candidates: artifact.candidates.map((c) => ({ id: c.id, title: c.title, description: c.reason })),
52412
53070
  evidenceFiles: [candidatesPath],
52413
- outPath: join22(dir, "topic-decision.json")
53071
+ outPath: join23(dir, "topic-decision.json")
52414
53072
  }, fs);
52415
53073
  echo(result.value);
52416
53074
  return 0;
52417
53075
  }
52418
- const outlineDir = join22(dir, "2-outline");
53076
+ const outlineDir = join23(dir, "2-outline");
52419
53077
  const candidates = [];
52420
53078
  const evidenceFiles = [];
52421
53079
  for (const id of ["a", "b", "c"]) {
52422
- const file = join22(outlineDir, `outline-option-${id}.md`);
53080
+ const file = join23(outlineDir, `outline-option-${id}.md`);
52423
53081
  if (!await fs.exists(file))
52424
53082
  continue;
52425
53083
  const heading = (await fs.readFile(file)).split(`
@@ -52429,18 +53087,18 @@ async function runSlotDecision(args, fs) {
52429
53087
  }
52430
53088
  if (candidates.length === 0)
52431
53089
  throw new Error(`no outline options in ${outlineDir}`);
52432
- evidenceFiles.push(join22(outlineDir, "outline-recommendation.json"));
53090
+ evidenceFiles.push(join23(outlineDir, "outline-recommendation.json"));
52433
53091
  const result = await itcDecision({
52434
53092
  parentRunId,
52435
53093
  decisionId: "kk-itc-outline-choice",
52436
53094
  candidates,
52437
53095
  evidenceFiles,
52438
- outPath: join22(outlineDir, "outline-decision.json")
53096
+ outPath: join23(outlineDir, "outline-decision.json")
52439
53097
  }, fs);
52440
53098
  const pick = result.value === "defer" ? "" : result.value;
52441
53099
  if (pick === "")
52442
53100
  echoError(`itc-decision: outline choice deferred to the operator: ${result.reason}`);
52443
- await fs.writeFile(join22(outlineDir, ".auto-pick"), pick);
53101
+ await fs.writeFile(join23(outlineDir, ".auto-pick"), pick);
52444
53102
  return 0;
52445
53103
  } catch (err) {
52446
53104
  echoError(`itc-decision: ${err instanceof Error ? err.message : String(err)}`);
@@ -52453,7 +53111,7 @@ async function runItcAuthorComplete(args, fs) {
52453
53111
  echoError("usage: itc-author-complete <work_dir> <parentRunId> [reviewMode]");
52454
53112
  return 1;
52455
53113
  }
52456
- const draftPath = join22(workDir, "3-draft-draft-article.md");
53114
+ const draftPath = join23(workDir, "3-draft-draft-article.md");
52457
53115
  if (!await fs.exists(draftPath)) {
52458
53116
  echoError(`itc-author-complete: draft not found: ${draftPath}`);
52459
53117
  return 1;
@@ -52464,7 +53122,7 @@ async function runItcAuthorComplete(args, fs) {
52464
53122
  return 1;
52465
53123
  }
52466
53124
  const draftDigest = createHash7("sha256").update(draftText).digest("hex");
52467
- const outlinePath = join22(workDir, "2-outline/outline-approved.md");
53125
+ const outlinePath = join23(workDir, "2-outline/outline-approved.md");
52468
53126
  if (!await fs.exists(outlinePath)) {
52469
53127
  echoError(`itc-author-complete: approved outline not found: ${outlinePath}`);
52470
53128
  return 1;
@@ -52475,7 +53133,7 @@ async function runItcAuthorComplete(args, fs) {
52475
53133
  return 1;
52476
53134
  }
52477
53135
  const outlineDigest = createHash7("sha256").update(outlineText).digest("hex");
52478
- const verdictPath = join22(workDir, ".itc-verdict.json");
53136
+ const verdictPath = join23(workDir, ".itc-verdict.json");
52479
53137
  let judgeDigest = null;
52480
53138
  let reviewMode = reviewModeArg === "manual" ? "manual" : "judged";
52481
53139
  if (await fs.exists(verdictPath)) {
@@ -52500,7 +53158,7 @@ async function runItcAuthorComplete(args, fs) {
52500
53158
  } else {
52501
53159
  reviewMode = "manual";
52502
53160
  }
52503
- const runPath = join22(workDir, ".itc/author-run.json");
53161
+ const runPath = join23(workDir, ".itc/author-run.json");
52504
53162
  let childRunId = `${parentRunId}-author`;
52505
53163
  if (await fs.exists(runPath)) {
52506
53164
  try {
@@ -52519,9 +53177,9 @@ async function runItcAuthorComplete(args, fs) {
52519
53177
  reviewMode,
52520
53178
  status: "complete"
52521
53179
  };
52522
- const itcDir = join22(workDir, ".itc");
53180
+ const itcDir = join23(workDir, ".itc");
52523
53181
  await fs.ensureDir(itcDir);
52524
- await fs.writeFile(join22(itcDir, "author-complete.json"), `${JSON.stringify(completeReceipt, null, 2)}
53182
+ await fs.writeFile(join23(itcDir, "author-complete.json"), `${JSON.stringify(completeReceipt, null, 2)}
52525
53183
  `);
52526
53184
  return 0;
52527
53185
  }
@@ -52559,7 +53217,7 @@ async function runItcPrepare(args, fs) {
52559
53217
  echoError("itc-prepare: --chosen applies only to a --from-collect launch");
52560
53218
  return 1;
52561
53219
  }
52562
- const chosenPath = join22(intakeDir, "chosen-source.json");
53220
+ const chosenPath = join23(intakeDir, "chosen-source.json");
52563
53221
  if (!await fs.exists(chosenPath)) {
52564
53222
  echoError(`itc-prepare: chosen source not found: ${chosenPath}`);
52565
53223
  return 1;
@@ -52595,9 +53253,9 @@ async function runItcPrepare(args, fs) {
52595
53253
  ["topic-pool-manifest.json", "topic-pool-manifest.json"]
52596
53254
  ];
52597
53255
  for (const [from, to] of copies) {
52598
- const src = join22(intakeDir, from);
53256
+ const src = join23(intakeDir, from);
52599
53257
  if (await fs.exists(src))
52600
- await fs.writeFile(join22(workDir, to), await fs.readFile(src));
53258
+ await fs.writeFile(join23(workDir, to), await fs.readFile(src));
52601
53259
  }
52602
53260
  }
52603
53261
  } catch (err) {
@@ -52613,7 +53271,7 @@ init_dist3();
52613
53271
 
52614
53272
  // src/publish-matrix.ts
52615
53273
  import { createHash as createHash8 } from "crypto";
52616
- import { dirname as dirname13, join as join23, resolve as resolve22 } from "path";
53274
+ import { dirname as dirname13, join as join24, resolve as resolve22 } from "path";
52617
53275
  init_dist3();
52618
53276
  init_dist();
52619
53277
  init_zod();
@@ -52750,7 +53408,7 @@ function listValue(args, flag) {
52750
53408
  }
52751
53409
  async function appendEvent(fs, publishDir, event) {
52752
53410
  await fs.ensureDir(publishDir);
52753
- const path = join23(publishDir, "publish-events.jsonl");
53411
+ const path = join24(publishDir, "publish-events.jsonl");
52754
53412
  const prior = await fs.exists(path) ? await fs.readFile(path) : "";
52755
53413
  await fs.writeFile(path, `${prior}${JSON.stringify({ at: new Date().toISOString(), ...event })}
52756
53414
  `);
@@ -52778,7 +53436,7 @@ async function runPublishMatrixValidate(args, deps = {}) {
52778
53436
  let candidate = raw === undefined || raw.trim() === "" ? undefined : raw;
52779
53437
  if (candidate === undefined) {
52780
53438
  source = "bundle.json";
52781
- const bundlePath = join23(workDir, "bundle.json");
53439
+ const bundlePath = join24(workDir, "bundle.json");
52782
53440
  if (!await fs.exists(bundlePath)) {
52783
53441
  echoError(`publish-matrix-validate: no --run-date and no bundle at ${bundlePath} to derive one from`);
52784
53442
  return 1;
@@ -52799,8 +53457,8 @@ async function runPublishMatrixValidate(args, deps = {}) {
52799
53457
  echoError(`publish-matrix-validate: run date '${candidate}' (from ${source}) is not a valid calendar day (YYYY-MM-DD or YYYYMMDD)`);
52800
53458
  return 1;
52801
53459
  }
52802
- await fs.ensureDir(join23(workDir, "4-publish"));
52803
- await fs.writeFile(join23(workDir, "4-publish", "run-date.txt"), `${normalized}
53460
+ await fs.ensureDir(join24(workDir, "4-publish"));
53461
+ await fs.writeFile(join24(workDir, "4-publish", "run-date.txt"), `${normalized}
52804
53462
  `);
52805
53463
  echo(`run date ${normalized} (from ${source})`);
52806
53464
  return 0;
@@ -52810,7 +53468,7 @@ var LINK_SOURCES = [
52810
53468
  { placeholder: "{{podcast_url}}", plugin: "podcast-pub", receipt: "podcast" }
52811
53469
  ];
52812
53470
  async function readPlan(fs, workDir, window) {
52813
- const planPath = join23(workDir, "4-publish", `plan.${window}.json`);
53471
+ const planPath = join24(workDir, "4-publish", `plan.${window}.json`);
52814
53472
  if (!await fs.exists(planPath)) {
52815
53473
  throw new Error(`no plan at ${planPath}; run publish-matrix-plan first`);
52816
53474
  }
@@ -52981,8 +53639,8 @@ async function composePlan(fs, input) {
52981
53639
  variantPath: entry.path,
52982
53640
  variantDigest: entry.sha256
52983
53641
  });
52984
- await fs.ensureDir(join23(input.workDir, "4-publish", "payloads"));
52985
- await fs.writeFile(join23(input.workDir, payloadRelative), payloadText);
53642
+ await fs.ensureDir(join24(input.workDir, "4-publish", "payloads"));
53643
+ await fs.writeFile(join24(input.workDir, payloadRelative), payloadText);
52986
53644
  }
52987
53645
  return {
52988
53646
  plan: {
@@ -53033,11 +53691,11 @@ async function planPublishMatrix(args, deps = {}) {
53033
53691
  dummy,
53034
53692
  ...deps.projectRoot ? { projectRoot: deps.projectRoot } : {}
53035
53693
  });
53036
- const publishDir = join23(workDir, "4-publish");
53694
+ const publishDir = join24(workDir, "4-publish");
53037
53695
  await fs.ensureDir(publishDir);
53038
53696
  const planText = `${JSON.stringify(plan, null, 2)}
53039
53697
  `;
53040
- await fs.writeFile(join23(publishDir, `plan.${plan.window}.json`), planText);
53698
+ await fs.writeFile(join24(publishDir, `plan.${plan.window}.json`), planText);
53041
53699
  const planDigest = createHash8("sha256").update(planText).digest("hex");
53042
53700
  for (const target of omitted) {
53043
53701
  const receipt = {
@@ -53055,8 +53713,8 @@ async function planPublishMatrix(args, deps = {}) {
53055
53713
  window: plan.window,
53056
53714
  ...target.mode === "dummy" ? { dummy: true } : {}
53057
53715
  };
53058
- await fs.ensureDir(join23(publishDir, "receipts"));
53059
- await fs.writeFile(join23(publishDir, "receipts", `${target.id}.json`), `${JSON.stringify(receipt, null, 2)}
53716
+ await fs.ensureDir(join24(publishDir, "receipts"));
53717
+ await fs.writeFile(join24(publishDir, "receipts", `${target.id}.json`), `${JSON.stringify(receipt, null, 2)}
53060
53718
  `);
53061
53719
  await appendEvent(fs, publishDir, {
53062
53720
  event: "omitted",
@@ -53138,9 +53796,9 @@ async function checkPublishMatrix(args, deps = {}) {
53138
53796
  echoError(`publish-matrix-check: channel probe for '${name}' refused: ${probe.detail ?? "unknown"}`);
53139
53797
  }
53140
53798
  }
53141
- const publishDir = join23(workDir, "4-publish");
53799
+ const publishDir = join24(workDir, "4-publish");
53142
53800
  await fs.ensureDir(publishDir);
53143
- await fs.writeFile(join23(publishDir, outFile), `${JSON.stringify({ schemaVersion: 1, window: label, plugins: probes }, null, 2)}
53801
+ await fs.writeFile(join24(publishDir, outFile), `${JSON.stringify({ schemaVersion: 1, window: label, plugins: probes }, null, 2)}
53144
53802
  `);
53145
53803
  echo(names.length === 0 ? "no probes" : `${probes.length} probe(s) recorded for ${label}`);
53146
53804
  return 0;
@@ -53168,7 +53826,7 @@ async function runPublishMatrixClassify(args, deps = {}) {
53168
53826
  echoError(`publish-matrix-classify: unknown window '${windowArg}'`);
53169
53827
  return 1;
53170
53828
  }
53171
- const publishDir = join23(workDir, "4-publish");
53829
+ const publishDir = join24(workDir, "4-publish");
53172
53830
  let plan;
53173
53831
  try {
53174
53832
  plan = await readPlan(fs, workDir, parsedWindow.data);
@@ -53183,7 +53841,7 @@ async function runPublishMatrixClassify(args, deps = {}) {
53183
53841
  echoError(`publish-matrix-classify: ${err instanceof Error ? err.message : String(err)}`);
53184
53842
  await fs.ensureDir(publishDir);
53185
53843
  const noneDate = runDate ?? await (async () => {
53186
- const stampPath = join23(publishDir, "run-date.txt");
53844
+ const stampPath = join24(publishDir, "run-date.txt");
53187
53845
  if (!await fs.exists(stampPath))
53188
53846
  return;
53189
53847
  return normalizeRunDate((await fs.readFile(stampPath)).trim());
@@ -53198,16 +53856,16 @@ async function runPublishMatrixClassify(args, deps = {}) {
53198
53856
  excluded: [],
53199
53857
  rows: []
53200
53858
  };
53201
- await fs.writeFile(join23(publishDir, `outcome.${parsedWindow.data}.json`), `${JSON.stringify(none, null, 2)}
53859
+ await fs.writeFile(join24(publishDir, `outcome.${parsedWindow.data}.json`), `${JSON.stringify(none, null, 2)}
53202
53860
  `);
53203
- await fs.writeFile(join23(publishDir, `publish-status.${parsedWindow.data}.txt`), `none
53861
+ await fs.writeFile(join24(publishDir, `publish-status.${parsedWindow.data}.txt`), `none
53204
53862
  `);
53205
- await fs.writeFile(join23(workDir, "publish-classify.summary.txt"), `${JSON.stringify({ status: "none", published: 0, targets: 0 })}
53863
+ await fs.writeFile(join24(workDir, "publish-classify.summary.txt"), `${JSON.stringify({ status: "none", published: 0, targets: 0 })}
53206
53864
  `);
53207
53865
  return 0;
53208
53866
  }
53209
53867
  if (runDate === undefined) {
53210
- const stampPath = join23(publishDir, "run-date.txt");
53868
+ const stampPath = join24(publishDir, "run-date.txt");
53211
53869
  const stamp = await fs.exists(stampPath) ? normalizeRunDate((await fs.readFile(stampPath)).trim()) : undefined;
53212
53870
  if (stamp === undefined) {
53213
53871
  echoError("publish-matrix-classify: plan has no runDate and no usable --run-date/run-date.txt was provided");
@@ -53215,27 +53873,27 @@ async function runPublishMatrixClassify(args, deps = {}) {
53215
53873
  }
53216
53874
  runDate = stamp;
53217
53875
  }
53218
- const receiptsDir = join23(publishDir, "receipts");
53876
+ const receiptsDir = join24(publishDir, "receipts");
53219
53877
  const receipts = [];
53220
53878
  if (await fs.exists(receiptsDir)) {
53221
53879
  for (const name of await fs.readDir(receiptsDir)) {
53222
53880
  if (!name.endsWith(".json"))
53223
53881
  continue;
53224
53882
  try {
53225
- receipts.push(JSON.parse(await fs.readFile(join23(receiptsDir, name))));
53883
+ receipts.push(JSON.parse(await fs.readFile(join24(receiptsDir, name))));
53226
53884
  } catch {}
53227
53885
  }
53228
53886
  }
53229
53887
  const outcome = classifyPublishMatrix(plan, receipts, runDate);
53230
53888
  await fs.ensureDir(publishDir);
53231
- await fs.writeFile(join23(publishDir, `outcome.${outcome.window}.json`), `${JSON.stringify(outcome, null, 2)}
53889
+ await fs.writeFile(join24(publishDir, `outcome.${outcome.window}.json`), `${JSON.stringify(outcome, null, 2)}
53232
53890
  `);
53233
- await fs.writeFile(join23(publishDir, `publish-status.${outcome.window}.txt`), `${outcome.status}
53891
+ await fs.writeFile(join24(publishDir, `publish-status.${outcome.window}.txt`), `${outcome.status}
53234
53892
  `);
53235
- await fs.writeFile(join23(workDir, "publish-classify.summary.txt"), `${JSON.stringify({ status: outcome.status, published: outcome.published, targets: outcome.targets })}
53893
+ await fs.writeFile(join24(workDir, "publish-classify.summary.txt"), `${JSON.stringify({ status: outcome.status, published: outcome.published, targets: outcome.targets })}
53236
53894
  `);
53237
53895
  if (outcome.window === "after-generate") {
53238
- const legacyDir = join23(workDir, "31-publish");
53896
+ const legacyDir = join24(workDir, "31-publish");
53239
53897
  for (const source of LEGACY_RESULT_FILES) {
53240
53898
  const row = plan.rows.find((candidate) => candidate.plugin === source.plugin && candidate.tier === 0);
53241
53899
  if (row === undefined || row.mode === "dummy")
@@ -53247,7 +53905,7 @@ async function runPublishMatrixClassify(args, deps = {}) {
53247
53905
  if (!await fs.exists(aggregate))
53248
53906
  continue;
53249
53907
  await fs.ensureDir(legacyDir);
53250
- await fs.writeFile(join23(legacyDir, `${runDate.replaceAll("-", "")}${source.file}`), await fs.readFile(aggregate));
53908
+ await fs.writeFile(join24(legacyDir, `${runDate.replaceAll("-", "")}${source.file}`), await fs.readFile(aggregate));
53251
53909
  }
53252
53910
  }
53253
53911
  echo(outcome.status);
@@ -53269,7 +53927,7 @@ async function runPublishMatrixSettle(args, deps = {}) {
53269
53927
  echoError(`publish-matrix-settle: unknown window '${windowArg}'`);
53270
53928
  return 1;
53271
53929
  }
53272
- const publishDir = join23(workDir, "4-publish");
53930
+ const publishDir = join24(workDir, "4-publish");
53273
53931
  let plan;
53274
53932
  try {
53275
53933
  plan = await readPlan(fs, workDir, parsedWindow.data);
@@ -53278,9 +53936,9 @@ async function runPublishMatrixSettle(args, deps = {}) {
53278
53936
  return 1;
53279
53937
  }
53280
53938
  const parentRunId = plan.parentRunId;
53281
- const receiptsDir = join23(publishDir, "receipts");
53939
+ const receiptsDir = join24(publishDir, "receipts");
53282
53940
  const receiptFor = async (id) => {
53283
- const path = join23(receiptsDir, `${id}.json`);
53941
+ const path = join24(receiptsDir, `${id}.json`);
53284
53942
  if (!await fs.exists(path))
53285
53943
  return;
53286
53944
  try {
@@ -53332,7 +53990,7 @@ async function runPublishMatrixSettle(args, deps = {}) {
53332
53990
  unresolved
53333
53991
  };
53334
53992
  await fs.ensureDir(publishDir);
53335
- const settlementPath = join23(publishDir, `settlement.${parsedWindow.data}.json`);
53993
+ const settlementPath = join24(publishDir, `settlement.${parsedWindow.data}.json`);
53336
53994
  if (unresolved.length > 0) {
53337
53995
  await fs.writeFile(settlementPath, `${JSON.stringify(settlement, null, 2)}
53338
53996
  `);
@@ -53398,7 +54056,7 @@ async function writeDummyReceipt(fs, row, context) {
53398
54056
  };
53399
54057
  }
53400
54058
  async function readSucceeded(fs, receiptsDir, id) {
53401
- const path = join23(receiptsDir, `${id}.json`);
54059
+ const path = join24(receiptsDir, `${id}.json`);
53402
54060
  if (!await fs.exists(path))
53403
54061
  return false;
53404
54062
  try {
@@ -53415,7 +54073,7 @@ async function readLinkMap(fs, publishDir, plan) {
53415
54073
  const planPaths = (await fs.exists(publishDir) ? await fs.readDir(publishDir) : []).filter((name) => /^plan\..*\.json$/.test(name));
53416
54074
  for (const name of planPaths) {
53417
54075
  try {
53418
- const candidate = JSON.parse(await fs.readFile(join23(publishDir, name)));
54076
+ const candidate = JSON.parse(await fs.readFile(join24(publishDir, name)));
53419
54077
  if (candidate.parentRunId !== plan.parentRunId)
53420
54078
  continue;
53421
54079
  for (const row of candidate.rows) {
@@ -53428,7 +54086,7 @@ async function readLinkMap(fs, publishDir, plan) {
53428
54086
  const entry = tierZero.find((candidate) => candidate.plugin === source.plugin);
53429
54087
  if (entry === undefined)
53430
54088
  continue;
53431
- const path = join23(publishDir, "receipts", `${entry.rowId}.json`);
54089
+ const path = join24(publishDir, "receipts", `${entry.rowId}.json`);
53432
54090
  if (!await fs.exists(path))
53433
54091
  continue;
53434
54092
  try {
@@ -53470,18 +54128,22 @@ async function sendPublishMatrix(args, deps = {}) {
53470
54128
  }
53471
54129
  }
53472
54130
  try {
54131
+ if (retry && !await fs.exists(join24(workDir, "4-publish", `plan.${parsedWindow.data}.json`))) {
54132
+ echo(`publish-matrix-send: no plan for window '${parsedWindow.data}' \u2014 nothing was planned, nothing to resend`);
54133
+ return 0;
54134
+ }
53473
54135
  const plan = await readPlan(fs, workDir, parsedWindow.data);
53474
- const publishDir = join23(workDir, "4-publish");
53475
- const receiptsDir = join23(publishDir, "receipts");
54136
+ const publishDir = join24(workDir, "4-publish");
54137
+ const receiptsDir = join24(publishDir, "receipts");
53476
54138
  await fs.ensureDir(receiptsDir);
53477
- const planDigest = createHash8("sha256").update(await fs.readFile(join23(publishDir, `plan.${plan.window}.json`))).digest("hex");
54139
+ const planDigest = createHash8("sha256").update(await fs.readFile(join24(publishDir, `plan.${plan.window}.json`))).digest("hex");
53478
54140
  const succeededAlready = (id) => readSucceeded(fs, receiptsDir, id);
53479
54141
  const tiers = [...new Set(plan.rows.map((row) => row.tier))].sort((a, b) => a - b);
53480
54142
  const pending = onlyTier === undefined ? plan.rows : plan.rows.filter((row) => row.tier === onlyTier);
53481
54143
  for (const row of pending) {
53482
54144
  if (row.mode === "dummy")
53483
54145
  continue;
53484
- const payloadPath = join23(workDir, row.payloadPath);
54146
+ const payloadPath = join24(workDir, row.payloadPath);
53485
54147
  const payloadRaw = await fs.exists(payloadPath) ? await fs.readFile(payloadPath) : null;
53486
54148
  if (payloadRaw === null) {
53487
54149
  throw new Error(`payload missing for '${row.id}': ${payloadPath}; re-run publish-matrix-plan`);
@@ -53491,7 +54153,7 @@ async function sendPublishMatrix(args, deps = {}) {
53491
54153
  throw new Error(`payload for '${row.id}' changed after the plan was frozen (reviewed ${row.payloadDigest}, on disk ${payloadActual}); re-run publish-matrix-plan`);
53492
54154
  }
53493
54155
  if (row.variantPath !== undefined && row.variantDigest !== undefined) {
53494
- const variantPath = join23(workDir, row.variantPath);
54156
+ const variantPath = join24(workDir, row.variantPath);
53495
54157
  const variantRaw = await fs.exists(variantPath) ? await fs.readFile(variantPath) : null;
53496
54158
  if (variantRaw === null) {
53497
54159
  throw new Error(`variant source missing for '${row.id}': ${variantPath}; re-run publish-matrix-plan`);
@@ -53525,7 +54187,7 @@ async function sendPublishMatrix(args, deps = {}) {
53525
54187
  plugin: row.plugin,
53526
54188
  profile: row.profile ?? "article",
53527
54189
  mode: row.mode,
53528
- payloadPath: join23(workDir, row.payloadPath),
54190
+ payloadPath: join24(workDir, row.payloadPath),
53529
54191
  transport: "fanout",
53530
54192
  receiptExtras: { target: row.id, window: plan.window }
53531
54193
  }));
@@ -53555,7 +54217,7 @@ async function sendPublishMatrix(args, deps = {}) {
53555
54217
  if (LINK_SOURCES.some((source) => resolved.includes(source.placeholder))) {
53556
54218
  return { error: "unresolved-link" };
53557
54219
  }
53558
- const resolvedPath = join23(workDir, "4-publish", "payloads", `content.${row.key}.resolved.json`);
54220
+ const resolvedPath = join24(workDir, "4-publish", "payloads", `content.${row.key}.resolved.json`);
53559
54221
  await fs.writeFile(resolvedPath, resolved);
53560
54222
  return { payloadPath: resolvedPath };
53561
54223
  },
@@ -53627,16 +54289,16 @@ async function runPublishMatrixRssGate(args, deps = {}) {
53627
54289
  echoError("usage: publish-matrix-rss-gate <work_dir> [--date <YYYY-MM-DD|YYYYMMDD>] [--feed <url>]");
53628
54290
  return 1;
53629
54291
  }
53630
- const publishDir = join23(workDir, "4-publish");
54292
+ const publishDir = join24(workDir, "4-publish");
53631
54293
  let date = dateRaw !== undefined && dateRaw.trim() !== "" ? normalizeRunDate(dateRaw) : undefined;
53632
54294
  if (dateRaw !== undefined && dateRaw.trim() !== "" && date === undefined) {
53633
54295
  echoError(`publish-matrix-rss-gate: '${dateRaw}' is not a valid calendar day (YYYY-MM-DD or YYYYMMDD)`);
53634
54296
  return 1;
53635
54297
  }
53636
54298
  let guid = "";
53637
- const receiptsDir = join23(publishDir, "receipts");
54299
+ const receiptsDir = join24(publishDir, "receipts");
53638
54300
  for (const planWindow of ["after-generate", "cn-peak"]) {
53639
- const planPath = join23(publishDir, `plan.${planWindow}.json`);
54301
+ const planPath = join24(publishDir, `plan.${planWindow}.json`);
53640
54302
  if (!await fs.exists(planPath))
53641
54303
  continue;
53642
54304
  const plan = JSON.parse(await fs.readFile(planPath));
@@ -53652,7 +54314,7 @@ async function runPublishMatrixRssGate(args, deps = {}) {
53652
54314
  for (const row of plan.rows) {
53653
54315
  if (row.plugin !== "podcast-pub")
53654
54316
  continue;
53655
- const receiptPath = join23(receiptsDir, `${row.id}.json`);
54317
+ const receiptPath = join24(receiptsDir, `${row.id}.json`);
53656
54318
  if (!await fs.exists(receiptPath))
53657
54319
  continue;
53658
54320
  const receipt = JSON.parse(await fs.readFile(receiptPath));
@@ -53661,7 +54323,7 @@ async function runPublishMatrixRssGate(args, deps = {}) {
53661
54323
  }
53662
54324
  }
53663
54325
  if (date === undefined) {
53664
- const stampPath = join23(publishDir, "run-date.txt");
54326
+ const stampPath = join24(publishDir, "run-date.txt");
53665
54327
  const stamp = await fs.exists(stampPath) ? normalizeRunDate((await fs.readFile(stampPath)).trim()) : undefined;
53666
54328
  if (stamp === undefined) {
53667
54329
  echoError("publish-matrix-rss-gate: no usable --date and no run-date.txt/plan.runDate to derive one from");
@@ -53671,7 +54333,7 @@ async function runPublishMatrixRssGate(args, deps = {}) {
53671
54333
  }
53672
54334
  const write = async (result) => {
53673
54335
  await fs.ensureDir(publishDir);
53674
- await fs.writeFile(join23(publishDir, "rss-gate.json"), `${JSON.stringify(result, null, 2)}
54336
+ await fs.writeFile(join24(publishDir, "rss-gate.json"), `${JSON.stringify(result, null, 2)}
53675
54337
  `);
53676
54338
  await appendEvent(fs, publishDir, {
53677
54339
  event: result.hit ? "gate-hit" : "gate-miss",
@@ -53687,9 +54349,9 @@ async function runPublishMatrixRssGate(args, deps = {}) {
53687
54349
  reason: `feed ${result.feedUrl} has no episode for ${result.date} (${result.reason})`,
53688
54350
  evidence: ["4-publish/rss-gate.json", ...result.detail === undefined ? [] : [result.detail]]
53689
54351
  };
53690
- await fs.writeFile(join23(publishDir, "incident.json"), `${JSON.stringify(incident, null, 2)}
54352
+ await fs.writeFile(join24(publishDir, "incident.json"), `${JSON.stringify(incident, null, 2)}
53691
54353
  `);
53692
- await fs.writeFile(join23(publishDir, "incident.md"), [
54354
+ await fs.writeFile(join24(publishDir, "incident.md"), [
53693
54355
  `# Overseas window missed \u2014 ${result.date}`,
53694
54356
  "",
53695
54357
  `The podcast feed \`${result.feedUrl}\` does not carry the ${result.date} episode (${result.reason}).`,
@@ -53828,7 +54490,7 @@ async function runPublishMatrixBundle(args, deps = {}) {
53828
54490
  echoError("usage: publish-matrix-bundle <work_dir> --run-date <YYYY-MM-DD> --run-id <voice3 run id> [--preset <slug>]");
53829
54491
  return 1;
53830
54492
  }
53831
- const variantsDir = join23(workDir, "30-variants");
54493
+ const variantsDir = join24(workDir, "30-variants");
53832
54494
  if (!await fs.exists(variantsDir)) {
53833
54495
  echoError(`publish-matrix-bundle: no variants at ${variantsDir}; run daily-bundle-variants first`);
53834
54496
  return 1;
@@ -53840,7 +54502,7 @@ async function runPublishMatrixBundle(args, deps = {}) {
53840
54502
  const variants = {};
53841
54503
  for (const file of entries) {
53842
54504
  const key = file.replace(/\.content\.json$/, "").replaceAll("_", ":");
53843
- const raw = await fs.readFile(join23(variantsDir, file));
54505
+ const raw = await fs.readFile(join24(variantsDir, file));
53844
54506
  const parsed = ContentSchema.safeParse(JSON.parse(raw));
53845
54507
  if (!parsed.success) {
53846
54508
  throw new Error(`variant '${key}' is not valid Content: ${parsed.error.message}`);
@@ -53864,7 +54526,7 @@ async function runPublishMatrixBundle(args, deps = {}) {
53864
54526
  }
53865
54527
  }
53866
54528
  const articleTitle = await readVariantTitle(fs, workDir, variants);
53867
- const safetyPath = join23(workDir, "4-safety-variants", "safety.json");
54529
+ const safetyPath = join24(workDir, "4-safety-variants", "safety.json");
53868
54530
  let safety;
53869
54531
  if (await fs.exists(safetyPath)) {
53870
54532
  const safetyParsed = BundleSafetySchema.safeParse(JSON.parse(await fs.readFile(safetyPath)));
@@ -53885,7 +54547,7 @@ async function runPublishMatrixBundle(args, deps = {}) {
53885
54547
  ...safety !== undefined ? { safety } : {}
53886
54548
  };
53887
54549
  const validated = BundleSchema.parse(bundle);
53888
- const bundlePath = join23(workDir, "bundle.json");
54550
+ const bundlePath = join24(workDir, "bundle.json");
53889
54551
  if (await fs.exists(bundlePath)) {
53890
54552
  try {
53891
54553
  const prior = BundleSchema.parse(JSON.parse(await fs.readFile(bundlePath)));
@@ -53912,7 +54574,7 @@ async function readVariantTitle(fs, workDir, variants) {
53912
54574
  if (entry === undefined)
53913
54575
  continue;
53914
54576
  try {
53915
- const parsed = ContentSchema.parse(JSON.parse(await fs.readFile(join23(workDir, entry.path))));
54577
+ const parsed = ContentSchema.parse(JSON.parse(await fs.readFile(join24(workDir, entry.path))));
53916
54578
  if (parsed.title !== undefined && parsed.title.trim() !== "")
53917
54579
  return parsed.title.trim();
53918
54580
  } catch {}
@@ -53982,7 +54644,7 @@ function registerStageCommand(program) {
53982
54644
  }
53983
54645
 
53984
54646
  // src/commands/store.ts
53985
- import { dirname as dirname14, join as join25, resolve as resolve24 } from "path";
54647
+ import { dirname as dirname14, join as join26, resolve as resolve24 } from "path";
53986
54648
  init_dist3();
53987
54649
  init_commander();
53988
54650
 
@@ -53990,7 +54652,7 @@ init_commander();
53990
54652
  init_dist3();
53991
54653
  import { randomUUID as randomUUID2 } from "crypto";
53992
54654
  import { tmpdir as tmpdir3 } from "os";
53993
- import { join as join24, resolve as resolve23 } from "path";
54655
+ import { join as join25, resolve as resolve23 } from "path";
53994
54656
  var STORE_CATALOG_PATH_REL = "plugins/kk/decisions/kk-items.yaml";
53995
54657
  var SPUR_CONFIG_PATH_REL = ".spur/config.yaml";
53996
54658
  var EVIDENCE_MAX_CHARS = 2000;
@@ -54019,7 +54681,7 @@ async function loadInjectedHub() {
54019
54681
  }
54020
54682
  async function readDecisionRouting(projectRoot, fs = createNodeFileSystem()) {
54021
54683
  const catalogPath = await resolveCatalogPath(projectRoot, fs);
54022
- const configPath = join24(projectRoot, SPUR_CONFIG_PATH_REL);
54684
+ const configPath = join25(projectRoot, SPUR_CONFIG_PATH_REL);
54023
54685
  if (!await fs.exists(configPath))
54024
54686
  return { catalogPath, routing: { makers: {} } };
54025
54687
  let parsed;
@@ -54103,8 +54765,8 @@ function createBufferedDecisionFetch(inner = fetch) {
54103
54765
  var bufferedDecisionFetch = createBufferedDecisionFetch();
54104
54766
  function runDecisionSubprocess(decisionId, input, maker, fs = createNodeFileSystem()) {
54105
54767
  const command = process.env.KK_SPUR_BIN ?? "spur";
54106
- const scratch = join24(tmpdir3(), `kk-decision-${randomUUID2()}`);
54107
- const evidencePath = join24(scratch, "evidence.md");
54768
+ const scratch = join25(tmpdir3(), `kk-decision-${randomUUID2()}`);
54769
+ const evidencePath = join25(scratch, "evidence.md");
54108
54770
  try {
54109
54771
  fs.writeFile(evidencePath, input.body);
54110
54772
  const args = [
@@ -54340,8 +55002,8 @@ async function readAnnotations(fs, outputPath) {
54340
55002
  async function heuristicAnnotations(fs, scratch, runId, items) {
54341
55003
  if (items.length === 0)
54342
55004
  return new Map;
54343
- const inputPath = join25(scratch, "label-input.json");
54344
- const outputPath = join25(scratch, "label-out.json");
55005
+ const inputPath = join26(scratch, "label-input.json");
55006
+ const outputPath = join26(scratch, "label-out.json");
54345
55007
  await fs.ensureDir(scratch);
54346
55008
  const docs = items.map((item) => ({
54347
55009
  id: item.id,
@@ -54692,7 +55354,7 @@ async function labelAction(options) {
54692
55354
  const mode = parseLabelMode(options.mode);
54693
55355
  const configPath = resolveKkConfigPath();
54694
55356
  const dbPath = await resolveStorePath(configPath, options.db);
54695
- const scratch = join25(dirname14(plan.kind === "new-ids" ? plan.newIds : dbPath), LABEL_SCRATCH_DIR);
55357
+ const scratch = join26(dirname14(plan.kind === "new-ids" ? plan.newIds : dbPath), LABEL_SCRATCH_DIR);
54696
55358
  const store = await openStore({ path: dbPath });
54697
55359
  const catalogVersion = await readCatalogVersion(fs);
54698
55360
  const labels = (await readStoreConfig(configPath)).labels;
@@ -54994,6 +55656,1565 @@ function registerStoreCommand(program) {
54994
55656
  store.command("release").description("Drop a run\u2019s selected rows so its items re-enter the pool; prints {released}").requiredOption("--run <id>", "Run id whose selected rows are dropped").option("--topic <topic>", "Narrow the release to one topic (default: every topic the run selected for)").option("--db <path>", "Store database path (default: kk config store.db_path, else .works/kk.db)").action(releaseAction);
54995
55657
  }
54996
55658
 
55659
+ // src/commands/wiki.ts
55660
+ init_commander();
55661
+ init_output2();
55662
+
55663
+ // src/wiki/ingest.ts
55664
+ import { extname, isAbsolute as isAbsolute13, join as join33 } from "path";
55665
+
55666
+ // ../../packages/kk-wiki/src/compile.ts
55667
+ function oneLineSummary(body) {
55668
+ for (const line of body.split(`
55669
+ `)) {
55670
+ const text = line.trim();
55671
+ if (text === "" || text.startsWith("#") || text.startsWith("---"))
55672
+ continue;
55673
+ return text.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2").slice(0, 120);
55674
+ }
55675
+ return "No summary yet.";
55676
+ }
55677
+ function groupByType(pages) {
55678
+ const groups = new Map;
55679
+ for (const page of [...pages].sort((a, b) => a.frontmatter.type.localeCompare(b.frontmatter.type) || a.slug.localeCompare(b.slug))) {
55680
+ const list = groups.get(page.frontmatter.type) ?? [];
55681
+ list.push(page);
55682
+ groups.set(page.frontmatter.type, list);
55683
+ }
55684
+ return groups;
55685
+ }
55686
+ function compileIndex(pages, options) {
55687
+ const groups = groupByType(pages);
55688
+ const indexLines = ["# Vault index", "", `Compiled ${options.date}. Do not edit by hand; run \`kk wiki compile\`.`];
55689
+ for (const [type, entries] of groups) {
55690
+ indexLines.push("", `## ${type}`, "");
55691
+ for (const page of entries) {
55692
+ indexLines.push(`- [[${page.slug}|${page.frontmatter.title}]] \u2014 ${oneLineSummary(page.body)}`);
55693
+ }
55694
+ }
55695
+ const mapLines = ["# MAP", "", "Routing table: page type and tags.", ""];
55696
+ for (const [type, entries] of groups) {
55697
+ mapLines.push(`## ${type}`, "");
55698
+ for (const page of entries) {
55699
+ const tags = page.frontmatter.tags.length > 0 ? page.frontmatter.tags.join(", ") : "\u2014";
55700
+ mapLines.push(`- ${page.path} \u2192 ${page.slug} (tags: ${tags})`);
55701
+ }
55702
+ }
55703
+ return { index: `${indexLines.join(`
55704
+ `)}
55705
+ `, map: `${mapLines.join(`
55706
+ `)}
55707
+ ` };
55708
+ }
55709
+ function needsWrite(current, rendered) {
55710
+ return current !== rendered;
55711
+ }
55712
+ // ../../packages/kk-wiki/src/page.ts
55713
+ init_zod();
55714
+ var PageTypeSchema = _enum2(["concept", "entity", "source", "index"]);
55715
+ var PageFrontmatterSchema = object2({
55716
+ title: string2().min(1),
55717
+ type: PageTypeSchema,
55718
+ tags: array(string2()).default([]),
55719
+ sources: array(string2()).default([]),
55720
+ updated_at: string2().min(1),
55721
+ user_edited: boolean2().optional(),
55722
+ redirect_to: string2().min(1).optional()
55723
+ });
55724
+
55725
+ class FrontmatterError extends Error {
55726
+ path;
55727
+ issues;
55728
+ constructor(path, issues) {
55729
+ super(`invalid frontmatter in ${path}: ${issues.join("; ")}`);
55730
+ this.path = path;
55731
+ this.issues = issues;
55732
+ this.name = "FrontmatterError";
55733
+ }
55734
+ }
55735
+ var FENCE = "---";
55736
+ function parseScalar(raw) {
55737
+ const trimmed = raw.trim();
55738
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
55739
+ return trimmed.slice(1, -1);
55740
+ }
55741
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) {
55742
+ return trimmed.slice(1, -1);
55743
+ }
55744
+ if (trimmed === "true")
55745
+ return true;
55746
+ if (trimmed === "false")
55747
+ return false;
55748
+ return trimmed;
55749
+ }
55750
+ function parseFrontmatter(raw) {
55751
+ const errors = [];
55752
+ const text = raw.replace(/^\uFEFF/, "");
55753
+ const lines = text.split(`
55754
+ `);
55755
+ if (lines[0]?.trim() !== FENCE) {
55756
+ return { data: {}, body: text, errors: ["missing-frontmatter"], bodyStartLine: 1 };
55757
+ }
55758
+ const close = lines.findIndex((line, index) => index > 0 && line.trim() === FENCE);
55759
+ if (close < 0) {
55760
+ return { data: {}, body: text, errors: ["unterminated-frontmatter"], bodyStartLine: 1 };
55761
+ }
55762
+ const data = {};
55763
+ let openArrayKey = null;
55764
+ for (const line of lines.slice(1, close)) {
55765
+ if (line.trim() === "")
55766
+ continue;
55767
+ const item = /^\s+-\s+(.*)$/.exec(line);
55768
+ if (item !== null) {
55769
+ if (openArrayKey === null) {
55770
+ errors.push(`array item without a key: ${line.trim()}`);
55771
+ continue;
55772
+ }
55773
+ const list = data[openArrayKey];
55774
+ if (Array.isArray(list))
55775
+ list.push(String(parseScalar(item[1] ?? "")));
55776
+ continue;
55777
+ }
55778
+ const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line);
55779
+ if (pair === null) {
55780
+ errors.push(`unsupported frontmatter line (nested or malformed): ${line.trim()}`);
55781
+ continue;
55782
+ }
55783
+ const key = pair[1] ?? "";
55784
+ const value = (pair[2] ?? "").trim();
55785
+ openArrayKey = value === "" ? key : null;
55786
+ if (value === "" || value === "[]") {
55787
+ data[key] = [];
55788
+ continue;
55789
+ }
55790
+ data[key] = parseScalar(value);
55791
+ }
55792
+ const rest = lines.slice(close + 1);
55793
+ const leadingBlank = rest[0] === "" ? 1 : 0;
55794
+ return {
55795
+ data,
55796
+ body: rest.join(`
55797
+ `).replace(/^\n/, ""),
55798
+ errors,
55799
+ bodyStartLine: close + 2 + leadingBlank
55800
+ };
55801
+ }
55802
+ function parsePage(text, path) {
55803
+ const parsed = parseFrontmatter(text);
55804
+ const result = PageFrontmatterSchema.safeParse(parsed.data);
55805
+ if (!result.success) {
55806
+ const issues = parsed.errors.concat(result.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`));
55807
+ throw new FrontmatterError(path, issues);
55808
+ }
55809
+ return { path, frontmatter: result.data, body: parsed.body };
55810
+ }
55811
+ function renderValue(value) {
55812
+ if (typeof value === "boolean")
55813
+ return value ? "true" : "false";
55814
+ if (value === "" || /[:#\n]/.test(value) || value.trim() !== value)
55815
+ return `"${value.replace(/"/g, "\\\"")}"`;
55816
+ return value;
55817
+ }
55818
+ function renderPage(page) {
55819
+ const fm = page.frontmatter;
55820
+ const lines = [FENCE, `title: ${renderValue(fm.title)}`, `type: ${fm.type}`];
55821
+ if (fm.tags.length === 0) {
55822
+ lines.push("tags: []");
55823
+ } else {
55824
+ lines.push("tags:", ...fm.tags.map((tag) => ` - ${renderValue(tag)}`));
55825
+ }
55826
+ if (fm.sources.length === 0) {
55827
+ lines.push("sources: []");
55828
+ } else {
55829
+ lines.push("sources:", ...fm.sources.map((source) => ` - ${renderValue(source)}`));
55830
+ }
55831
+ lines.push(`updated_at: ${renderValue(fm.updated_at)}`);
55832
+ if (fm.user_edited === true)
55833
+ lines.push("user_edited: true");
55834
+ if (fm.redirect_to !== undefined)
55835
+ lines.push(`redirect_to: ${renderValue(fm.redirect_to)}`);
55836
+ lines.push(FENCE, "");
55837
+ return `${lines.join(`
55838
+ `)}
55839
+ ${page.body.replace(/\s+$/, "")}
55840
+ `;
55841
+ }
55842
+ function resolveSlug(title) {
55843
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
55844
+ }
55845
+
55846
+ // ../../packages/kk-wiki/src/context.ts
55847
+ function packContext(index, topic, options = {}) {
55848
+ const slug = resolveSlug(topic);
55849
+ const topicPage = index.bySlug.get(slug) ?? index.pages.find((page) => page.path === topic);
55850
+ if (topicPage === undefined)
55851
+ return { markdown: "", pages: [] };
55852
+ const included = [topicPage];
55853
+ const neighbours = index.pages.filter((page) => page !== topicPage && (page.links.some((link) => resolveSlug(link.target) === topicPage.slug) || topicPage.links.some((link) => resolveSlug(link.target) === page.slug)));
55854
+ for (const page of neighbours.slice(0, Math.max(0, options.depth ?? 1) === 0 ? 0 : neighbours.length)) {
55855
+ included.push(page);
55856
+ }
55857
+ const markdown = included.map((page) => `## ${page.path}
55858
+
55859
+ ${page.body.trim()}
55860
+ `).join(`
55861
+ `).trimEnd();
55862
+ return { markdown: `${markdown}
55863
+ `, pages: included.map((page) => page.path) };
55864
+ }
55865
+ // ../../packages/kk-wiki/src/gc.ts
55866
+ import { dirname as dirname15, isAbsolute as isAbsolute9, join as join27 } from "path";
55867
+ async function planGc(index, options) {
55868
+ const fs = options.fileSystem;
55869
+ const root = dirname15(options.rawDir);
55870
+ const mirrorPaths = (options.mirrors ?? []).map((mirror) => isAbsolute9(mirror) ? mirror : join27(root, mirror));
55871
+ const referenced = new Set;
55872
+ for (const page of index.pages) {
55873
+ for (const source of page.frontmatter.sources)
55874
+ referenced.add(source.trim());
55875
+ }
55876
+ const candidates = [];
55877
+ for (const type of ["url", "pdf", "html", "rss"]) {
55878
+ const dir = join27(options.rawDir, type);
55879
+ if (!await fs.exists(dir))
55880
+ continue;
55881
+ for (const name of await fs.readDir(dir))
55882
+ candidates.push(join27(dir, name));
55883
+ }
55884
+ const tmpDir = join27(options.rawDir, "tmp");
55885
+ if (await fs.exists(tmpDir)) {
55886
+ for (const name of await fs.readDir(tmpDir))
55887
+ candidates.push(join27(tmpDir, name));
55888
+ }
55889
+ const skippedMirrors = (options.mirrors ?? []).filter((_, index) => {
55890
+ const path = mirrorPaths[index];
55891
+ return path !== undefined && fs.exists(path);
55892
+ });
55893
+ const plan = { delete: [], keep: [], skippedMirrors };
55894
+ for (const path of candidates) {
55895
+ if (mirrorPaths.some((mirror) => path.startsWith(mirror)))
55896
+ continue;
55897
+ const snapshotId = path.split("/").pop()?.replace(/\.md$/, "") ?? path;
55898
+ if (referenced.has(snapshotId) || referenced.has(path))
55899
+ plan.keep.push(path);
55900
+ else
55901
+ plan.delete.push(path);
55902
+ }
55903
+ plan.delete.sort();
55904
+ plan.keep.sort();
55905
+ return plan;
55906
+ }
55907
+ async function applyGc(plan, fileSystem) {
55908
+ for (const path of plan.delete)
55909
+ await fileSystem.deleteFile(path);
55910
+ return { deleted: [...plan.delete] };
55911
+ }
55912
+ // ../../packages/kk-wiki/src/graph.ts
55913
+ init_dist3();
55914
+ import { relative as relative3 } from "path";
55915
+ function scanLines(body) {
55916
+ const result = [];
55917
+ let inFence = false;
55918
+ body.split(`
55919
+ `).forEach((raw, index) => {
55920
+ const isFence = /^\s*(```|~~~)/.test(raw);
55921
+ if (isFence)
55922
+ inFence = !inFence;
55923
+ const masked = raw.replace(/`[^`]*`/g, (span) => " ".repeat(span.length));
55924
+ result.push({ line: index + 1, text: masked, inFence: isFence ? true : inFence });
55925
+ });
55926
+ return result;
55927
+ }
55928
+ function extractLinks(body) {
55929
+ const links = [];
55930
+ for (const scanned of scanLines(body)) {
55931
+ if (scanned.inFence)
55932
+ continue;
55933
+ const pattern = /\[\[([^\]|]+?)(?:\|([^\]]+))?\]\]/g;
55934
+ for (const match of scanned.text.matchAll(pattern)) {
55935
+ links.push({
55936
+ target: (match[1] ?? "").trim(),
55937
+ surface: match[2] === undefined ? null : match[2].trim(),
55938
+ line: scanned.line
55939
+ });
55940
+ }
55941
+ }
55942
+ return links;
55943
+ }
55944
+ function pageSlug(title) {
55945
+ return resolveSlug(title);
55946
+ }
55947
+ async function listMarkdown(dir, fs) {
55948
+ const files = await walkDir(dir, fs);
55949
+ return files.filter((file) => file.endsWith(".md")).sort();
55950
+ }
55951
+ function duplicateSlugFindings(pages) {
55952
+ const seen = new Map;
55953
+ for (const page of pages) {
55954
+ const paths = seen.get(page.slug) ?? [];
55955
+ paths.push(page.path);
55956
+ seen.set(page.slug, paths);
55957
+ }
55958
+ const findings = [];
55959
+ for (const [slug, paths] of seen) {
55960
+ if (paths.length < 2)
55961
+ continue;
55962
+ for (const path of paths) {
55963
+ findings.push({
55964
+ code: "duplicate-slug",
55965
+ path,
55966
+ line: 1,
55967
+ message: `slug '${slug}' is shared by ${paths.length} pages`
55968
+ });
55969
+ }
55970
+ }
55971
+ return findings;
55972
+ }
55973
+ async function buildVaultIndex(contentDir, fileSystem = createNodeFileSystem()) {
55974
+ const pages = [];
55975
+ const findings = [];
55976
+ for (const file of await listMarkdown(contentDir, fileSystem)) {
55977
+ const path = relative3(contentDir, file);
55978
+ const text = await fileSystem.readFile(file);
55979
+ const parsed = parseFrontmatter(text);
55980
+ const validated = PageFrontmatterSchema.safeParse(parsed.data);
55981
+ if (!validated.success) {
55982
+ const code = parsed.errors.includes("missing-frontmatter") ? "missing-frontmatter" : "invalid-frontmatter";
55983
+ findings.push({
55984
+ code,
55985
+ path,
55986
+ line: 1,
55987
+ message: parsed.errors[0] ?? validated.error.issues.map((issue) => `${issue.path.join(".") || "frontmatter"}: ${issue.message}`).join("; ")
55988
+ });
55989
+ continue;
55990
+ }
55991
+ const page = {
55992
+ path,
55993
+ slug: pageSlug(validated.data.title),
55994
+ frontmatter: validated.data,
55995
+ body: parsed.body,
55996
+ bodyStartLine: parsed.bodyStartLine,
55997
+ links: extractLinks(parsed.body).map((link) => ({
55998
+ ...link,
55999
+ line: link.line + parsed.bodyStartLine - 1
56000
+ })),
56001
+ inbound: 0
56002
+ };
56003
+ pages.push(page);
56004
+ }
56005
+ const bySlug = new Map;
56006
+ for (const page of pages)
56007
+ bySlug.set(page.slug, page);
56008
+ for (const page of pages) {
56009
+ for (const link of page.links) {
56010
+ const target = bySlug.get(resolveSlug(link.target));
56011
+ if (target !== undefined && target !== page)
56012
+ target.inbound += 1;
56013
+ }
56014
+ }
56015
+ findings.push(...duplicateSlugFindings(pages));
56016
+ return { contentDir, pages, bySlug, findings };
56017
+ }
56018
+ function resolveLink(index, link) {
56019
+ return index.bySlug.get(resolveSlug(link.target));
56020
+ }
56021
+ // ../../packages/kk-wiki/src/link.ts
56022
+ init_dist3();
56023
+ import { join as join28 } from "path";
56024
+
56025
+ // ../../packages/kk-wiki/src/write.ts
56026
+ function guardHeading(date) {
56027
+ return `## AI Updates (${date})`;
56028
+ }
56029
+ function appendGuarded(body, material, date) {
56030
+ const heading = guardHeading(date);
56031
+ const trimmed = material.replace(/\s+$/, "");
56032
+ const lines = body.replace(/\s+$/, "").split(`
56033
+ `);
56034
+ const headingIndex = lines.findIndex((line) => line.trim() === heading);
56035
+ if (headingIndex === -1)
56036
+ return `${lines.join(`
56037
+ `)}
56038
+
56039
+ ${heading}
56040
+
56041
+ ${trimmed}
56042
+ `;
56043
+ const nextHeading = lines.findIndex((line, index) => index > headingIndex && /^##\s+/.test(line));
56044
+ const insertAt = nextHeading === -1 ? lines.length : nextHeading;
56045
+ const head = lines.slice(0, insertAt);
56046
+ while (head.length > 0 && (head[head.length - 1] ?? "").trim() === "")
56047
+ head.pop();
56048
+ return `${[...head, "", trimmed].join(`
56049
+ `)}
56050
+ ${lines.slice(insertAt).join(`
56051
+ `)}`.replace(/\n{3,}/g, `
56052
+
56053
+ `);
56054
+ }
56055
+ function applyWrite(page, material, options) {
56056
+ const guarded = page.frontmatter.user_edited === true;
56057
+ if (guarded)
56058
+ return { body: appendGuarded(page.body, material, options.date), guard: "appended" };
56059
+ if (options.mode === "append")
56060
+ return { body: appendGuarded(page.body, material, options.date), guard: "clean" };
56061
+ return { body: `${material.replace(/\s+$/, "")}
56062
+ `, guard: "clean" };
56063
+ }
56064
+ function applyWriteToPage(page, material, options) {
56065
+ const result = applyWrite(page, material, options);
56066
+ const text = renderPage({
56067
+ ...page,
56068
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56069
+ body: result.body
56070
+ });
56071
+ return { text, guard: result.guard };
56072
+ }
56073
+
56074
+ // ../../packages/kk-wiki/src/link.ts
56075
+ function escapeRegExp(value) {
56076
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
56077
+ }
56078
+ function findMentions(index) {
56079
+ const mentions = [];
56080
+ const titles = index.pages.map((page) => ({ page, title: page.frontmatter.title.trim() })).filter((entry) => entry.title.length >= 3);
56081
+ for (const page of index.pages) {
56082
+ const linked = new Set(page.links.map((link) => link.target.toLowerCase()));
56083
+ for (const scanned of scanLines(page.body)) {
56084
+ if (scanned.inFence)
56085
+ continue;
56086
+ const masked = scanned.text.replace(/\[\[[^\]]*\]\]/g, (span) => " ".repeat(span.length));
56087
+ for (const { page: target, title } of titles) {
56088
+ if (target.slug === page.slug || linked.has(target.slug) || linked.has(title.toLowerCase()))
56089
+ continue;
56090
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56091
+ const hit = pattern.exec(masked);
56092
+ if (hit === null)
56093
+ continue;
56094
+ mentions.push({
56095
+ path: page.path,
56096
+ line: scanned.line + page.bodyStartLine - 1,
56097
+ slug: target.slug,
56098
+ surface: title,
56099
+ text: title
56100
+ });
56101
+ break;
56102
+ }
56103
+ }
56104
+ }
56105
+ return mentions;
56106
+ }
56107
+ function rewriteBody(body, pageMentions, lineOffset) {
56108
+ const lines = body.split(`
56109
+ `);
56110
+ for (const mention of pageMentions) {
56111
+ const index = mention.line - lineOffset;
56112
+ const line = lines[index];
56113
+ if (line === undefined)
56114
+ continue;
56115
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(mention.text)}(?![\\w\\]])`, "i");
56116
+ lines[index] = line.replace(pattern, `[[${mention.slug}|${mention.surface}]]`);
56117
+ }
56118
+ return lines.join(`
56119
+ `);
56120
+ }
56121
+ async function fixLinks(index, options = { date: "" }) {
56122
+ const fs = options.fileSystem ?? createNodeFileSystem();
56123
+ const contentDir = options.contentDir ?? index.contentDir;
56124
+ const mentions = findMentions(index);
56125
+ const grouped = new Map;
56126
+ for (const mention of mentions) {
56127
+ const list = grouped.get(mention.path) ?? [];
56128
+ list.push(mention);
56129
+ grouped.set(mention.path, list);
56130
+ }
56131
+ const changed = [];
56132
+ const refused = [];
56133
+ for (const [path, pageMentions] of grouped) {
56134
+ const raw = await fs.readFile(join28(contentDir, path));
56135
+ const page = parsePage(raw, path);
56136
+ const rewritten = rewriteBody(page.body, pageMentions, parseFrontmatter(raw).bodyStartLine);
56137
+ const { text, guard } = applyWriteToPage(page, rewritten, {
56138
+ mode: "full",
56139
+ date: options.date
56140
+ });
56141
+ if (options.dryRun === true) {
56142
+ changed.push(path);
56143
+ continue;
56144
+ }
56145
+ await fs.writeFile(join28(contentDir, path), text);
56146
+ if (guard === "appended")
56147
+ refused.push(path);
56148
+ else
56149
+ changed.push(path);
56150
+ }
56151
+ return { changed, refused, mentions };
56152
+ }
56153
+ function linkTitlesInText(index, text) {
56154
+ let linked = text;
56155
+ const titles = index.pages.map((page) => ({ slug: page.slug, title: page.frontmatter.title.trim() })).filter((entry) => entry.title.length >= 3).sort((a, b) => b.title.length - a.title.length);
56156
+ for (const { slug, title } of titles) {
56157
+ const pattern = new RegExp(`(?<![\\w\\[|])${escapeRegExp(title)}(?![\\w\\]])`, "i");
56158
+ linked = linked.replace(pattern, `[[${slug}|${title}]]`);
56159
+ }
56160
+ return linked;
56161
+ }
56162
+ // ../../packages/kk-wiki/src/lint.ts
56163
+ var ORPHAN_EXEMPT_FILES = new Set(["index.md", "MAP.md"]);
56164
+ function lintPages(index) {
56165
+ const findings = [...index.findings];
56166
+ for (const page of index.pages) {
56167
+ for (const link of page.links) {
56168
+ if (resolveLink(index, link) !== undefined)
56169
+ continue;
56170
+ findings.push({
56171
+ code: "broken-link",
56172
+ path: page.path,
56173
+ line: link.line,
56174
+ message: `[[${link.target}]] resolves to no page`
56175
+ });
56176
+ }
56177
+ const basename = page.path.split("/").pop() ?? page.path;
56178
+ if (page.inbound === 0 && !ORPHAN_EXEMPT_FILES.has(basename)) {
56179
+ findings.push({
56180
+ code: "orphan",
56181
+ path: page.path,
56182
+ line: 1,
56183
+ message: "no page links here"
56184
+ });
56185
+ }
56186
+ }
56187
+ return findings.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.code.localeCompare(b.code));
56188
+ }
56189
+ function lintExitCode(findings) {
56190
+ return findings.length === 0 ? 0 : 1;
56191
+ }
56192
+ // ../../packages/kk-wiki/src/markitdown.ts
56193
+ init_dist3();
56194
+ import { createHash as createHash9 } from "crypto";
56195
+ import { tmpdir as tmpdir4 } from "os";
56196
+ import { isAbsolute as isAbsolute10, join as join29 } from "path";
56197
+
56198
+ class MissingNormalizerError extends Error {
56199
+ binary;
56200
+ constructor(binary) {
56201
+ super(`missing normaliser '${binary}': install it (\`uv tool install markitdown\`) or pass markdown on stdin`);
56202
+ this.binary = binary;
56203
+ this.name = "MissingNormalizerError";
56204
+ }
56205
+ }
56206
+ function resolveBinary(binary) {
56207
+ if (isAbsolute10(binary) || binary.includes("/"))
56208
+ return binary;
56209
+ const found = Bun.which(binary, { PATH: process.env.PATH });
56210
+ if (found === null)
56211
+ throw new MissingNormalizerError(binary);
56212
+ return found;
56213
+ }
56214
+ function createMarkitdownRunner(options = {}) {
56215
+ const binary = options.binary ?? "markitdown";
56216
+ const executor = options.executor ?? new NodeProcessExecutor;
56217
+ const fs = options.fileSystem ?? createNodeFileSystem();
56218
+ const timeoutMs = options.timeoutMs ?? 120000;
56219
+ return async (input) => {
56220
+ const executable = resolveBinary(binary);
56221
+ let tempPath;
56222
+ let target = input.target;
56223
+ if (input.kind === "html") {
56224
+ const id = createHash9("sha256").update(input.body ?? "").digest("hex").slice(0, 12);
56225
+ tempPath = join29(tmpdir4(), `kk-wiki-${id}.html`);
56226
+ await fs.writeFile(tempPath, input.body ?? "");
56227
+ target = tempPath;
56228
+ }
56229
+ try {
56230
+ const result = await executor.run({ command: executable, args: [target], timeout: timeoutMs });
56231
+ if (result.exitCode !== 0) {
56232
+ const last = result.stderr.trim().split(`
56233
+ `).slice(-1)[0] ?? "unknown error";
56234
+ throw new Error(`${binary} exited ${result.exitCode}: ${last}`);
56235
+ }
56236
+ if (result.stdout.trim() === "") {
56237
+ throw new Error(`${binary} produced an empty body for ${input.target}`);
56238
+ }
56239
+ return result.stdout;
56240
+ } finally {
56241
+ if (tempPath !== undefined && await fs.exists(tempPath))
56242
+ await fs.deleteFile(tempPath);
56243
+ }
56244
+ };
56245
+ }
56246
+ // ../../packages/kk-wiki/src/merge.ts
56247
+ function mergePages(index, from, to, options) {
56248
+ const source = index.pages.find((page) => page.path === from || page.slug === from);
56249
+ const target = index.pages.find((page) => page.path === to || page.slug === to);
56250
+ if (source === undefined)
56251
+ throw new Error(`merge: no source page '${from}'`);
56252
+ if (target === undefined)
56253
+ throw new Error(`merge: no target page '${to}'`);
56254
+ if (source.frontmatter.user_edited === true) {
56255
+ return {
56256
+ written: target.path,
56257
+ sourceSlug: source.slug,
56258
+ redirects: 0,
56259
+ guard: "refused",
56260
+ targetText: renderPage(target),
56261
+ sourceText: renderPage(source),
56262
+ rewritten: [],
56263
+ rewrittenPages: []
56264
+ };
56265
+ }
56266
+ const mergedSources = [...new Set([...target.frontmatter.sources, ...source.frontmatter.sources, source.slug])];
56267
+ const unitedBody = `${target.body.replace(/\s+$/, "")}
56268
+
56269
+ ${source.body.replace(/^\s+/, "")}`;
56270
+ const written = applyWriteToPage({ ...target, frontmatter: { ...target.frontmatter, sources: mergedSources } }, unitedBody, { mode: "full", date: options.date });
56271
+ let redirects = 0;
56272
+ const rewritten = [];
56273
+ const rewrittenPages = [];
56274
+ for (const page of index.pages) {
56275
+ if (page.slug === source.slug || page.slug === target.slug)
56276
+ continue;
56277
+ const linked = page.body.replace(/\[\[([^\]|]+)(\|[^\]]+)?\]\]/g, (whole, rawTarget, surface) => {
56278
+ const slug = rawTarget.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
56279
+ if (slug !== source.slug)
56280
+ return whole;
56281
+ redirects += 1;
56282
+ return surface === undefined ? `[[${target.slug}]]` : `[[${target.slug}${surface}]]`;
56283
+ });
56284
+ if (linked !== page.body) {
56285
+ page.body = linked;
56286
+ rewritten.push(page.path);
56287
+ rewrittenPages.push({
56288
+ path: page.path,
56289
+ text: renderPage({
56290
+ ...page,
56291
+ frontmatter: { ...page.frontmatter, updated_at: options.date },
56292
+ body: linked
56293
+ })
56294
+ });
56295
+ }
56296
+ }
56297
+ const sourceText = renderPage({
56298
+ ...source,
56299
+ frontmatter: {
56300
+ ...source.frontmatter,
56301
+ updated_at: options.date,
56302
+ redirect_to: target.slug
56303
+ },
56304
+ body: `Merged into [[${target.slug}|${target.frontmatter.title}]].
56305
+ `
56306
+ });
56307
+ return {
56308
+ written: target.path,
56309
+ sourceSlug: source.slug,
56310
+ redirects,
56311
+ guard: written.guard,
56312
+ targetText: written.text,
56313
+ sourceText,
56314
+ rewritten,
56315
+ rewrittenPages
56316
+ };
56317
+ }
56318
+ // ../../packages/kk-wiki/src/publish.ts
56319
+ import { dirname as dirname16, isAbsolute as isAbsolute11, join as join30, relative as relative4, resolve as resolve25 } from "path";
56320
+ function isInside(parent, child) {
56321
+ const rel = relative4(parent, child);
56322
+ return rel === "" || !rel.startsWith("..") && !isAbsolute11(rel);
56323
+ }
56324
+ async function publishVault(index, options) {
56325
+ const targetRoot = resolve25(options.target);
56326
+ if (isInside(resolve25(index.contentDir), targetRoot))
56327
+ return { files: [], refused: "target-inside-vault" };
56328
+ const fs = options.fileSystem;
56329
+ const files = [];
56330
+ for (const page of index.pages) {
56331
+ const source = join30(index.contentDir, page.path);
56332
+ const destination = join30(targetRoot, "content", page.path);
56333
+ await fs.ensureDir(dirname16(destination));
56334
+ await fs.writeFile(destination, await fs.readFile(source));
56335
+ files.push(join30("content", page.path));
56336
+ }
56337
+ return { files: files.sort() };
56338
+ }
56339
+ // ../../packages/kk-wiki/src/query.ts
56340
+ function terms(prompt) {
56341
+ return [
56342
+ ...new Set(prompt.toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2))
56343
+ ].sort();
56344
+ }
56345
+ function scoreOf2(page, terms_) {
56346
+ const title = page.frontmatter.title.toLowerCase();
56347
+ const tags = page.frontmatter.tags.join(" ").toLowerCase();
56348
+ const body = page.body.toLowerCase();
56349
+ let score = 0;
56350
+ for (const term of terms_) {
56351
+ if (title.includes(term))
56352
+ score += 3;
56353
+ if (tags.includes(term))
56354
+ score += 2;
56355
+ if (body.includes(term))
56356
+ score += 1;
56357
+ }
56358
+ return score;
56359
+ }
56360
+ function excerptOf(page, terms_) {
56361
+ for (const line of page.body.split(`
56362
+ `)) {
56363
+ const text = line.trim();
56364
+ if (text === "" || text.startsWith("#"))
56365
+ continue;
56366
+ const lower = text.toLowerCase();
56367
+ if (terms_.some((term) => lower.includes(term)))
56368
+ return text.slice(0, 200);
56369
+ }
56370
+ return page.body.trim().split(`
56371
+ `)[0]?.slice(0, 200) ?? "";
56372
+ }
56373
+ function rankPages(index, prompt, options = {}) {
56374
+ const terms_ = terms(prompt);
56375
+ const hits = [];
56376
+ for (const page of index.pages) {
56377
+ const score = scoreOf2(page, terms_);
56378
+ if (score === 0)
56379
+ continue;
56380
+ hits.push({ path: page.path, title: page.frontmatter.title, excerpt: excerptOf(page, terms_), score });
56381
+ }
56382
+ return hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, options.limit ?? 10);
56383
+ }
56384
+ // ../../packages/kk-wiki/src/raw.ts
56385
+ init_dist3();
56386
+ import { createHash as createHash10 } from "crypto";
56387
+ import { dirname as dirname17, join as join31 } from "path";
56388
+ var RAW_SOURCE_TYPES = ["url", "pdf", "html", "rss"];
56389
+ function rawSnapshotId(sourceUri, body) {
56390
+ return createHash10("sha256").update(`${sourceUri}
56391
+ ${body}`).digest("hex").slice(0, 16);
56392
+ }
56393
+ function escapeValue(value) {
56394
+ return /[:#\n]/.test(value) || value.trim() !== value ? `"${value.replace(/"/g, "\\\"")}"` : value;
56395
+ }
56396
+ function renderRawSnapshot(snapshot, body) {
56397
+ const lines = [
56398
+ "---",
56399
+ `title: ${escapeValue(snapshot.title)}`,
56400
+ `source_type: ${snapshot.type}`,
56401
+ `source_uri: ${escapeValue(snapshot.sourceUri)}`,
56402
+ `ingested_at: ${snapshot.ingestedAt}`,
56403
+ "---",
56404
+ ""
56405
+ ];
56406
+ return `${lines.join(`
56407
+ `)}
56408
+ ${body.replace(/\s+$/, "")}
56409
+ `;
56410
+ }
56411
+ async function writeRawSnapshot(input, fileSystem = createNodeFileSystem()) {
56412
+ const ingestedAt = input.ingestedAt ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
56413
+ const id = rawSnapshotId(input.sourceUri, input.body);
56414
+ const snapshot = {
56415
+ id,
56416
+ path: join31(input.dir, input.type, `${id}.md`),
56417
+ type: input.type,
56418
+ title: input.title,
56419
+ sourceUri: input.sourceUri,
56420
+ ingestedAt
56421
+ };
56422
+ await fileSystem.ensureDir(dirname17(snapshot.path));
56423
+ await fileSystem.writeFile(snapshot.path, renderRawSnapshot(snapshot, input.body));
56424
+ return snapshot;
56425
+ }
56426
+ function deriveTitle(body, sourceUri) {
56427
+ for (const line of body.split(`
56428
+ `)) {
56429
+ const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(line);
56430
+ if (heading !== null)
56431
+ return heading[1] ?? sourceUri;
56432
+ }
56433
+ const tail = sourceUri === "stdin" ? "stdin" : sourceUri.split("/").pop() ?? sourceUri;
56434
+ return tail.replace(/\.[a-z0-9]+$/i, "") || "untitled";
56435
+ }
56436
+ // ../../packages/kk-wiki/src/summarize.ts
56437
+ var SUMMARY_HEADING = "## Summary";
56438
+ function summarizePage(index, target, material, options) {
56439
+ const linkedText = linkTitlesInText(index, material).trim();
56440
+ const lines = target.body.split(`
56441
+ `);
56442
+ const headingIndex = lines.findIndex((line) => line.trim() === SUMMARY_HEADING);
56443
+ let body;
56444
+ if (headingIndex === -1) {
56445
+ body = `${target.body.replace(/\s+$/, "")}
56446
+
56447
+ ${SUMMARY_HEADING}
56448
+
56449
+ ${linkedText}
56450
+ `;
56451
+ } else {
56452
+ const nextHeading = lines.findIndex((line, position) => position > headingIndex && /^##\s+/.test(line));
56453
+ const head = lines.slice(0, headingIndex + 1);
56454
+ const tail = nextHeading === -1 ? [] : lines.slice(nextHeading);
56455
+ body = `${[...head, "", linkedText, "", ...tail].join(`
56456
+ `).replace(/\n{3,}/g, `
56457
+
56458
+ `).trimEnd()}
56459
+ `;
56460
+ }
56461
+ const written = target.frontmatter.user_edited === true ? applyWrite({ ...target, body }, `${SUMMARY_HEADING}
56462
+
56463
+ ${linkedText}`, {
56464
+ mode: "full",
56465
+ date: options.date
56466
+ }) : { body: `${body.replace(/\s+$/, "")}
56467
+ `, guard: "clean" };
56468
+ return {
56469
+ path: target.path,
56470
+ guard: written.guard,
56471
+ text: renderPage({
56472
+ ...target,
56473
+ frontmatter: { ...target.frontmatter, updated_at: options.date },
56474
+ body: written.body
56475
+ }),
56476
+ links: (linkedText.match(/\[\[/g) ?? []).length
56477
+ };
56478
+ }
56479
+ // ../../packages/kk-wiki/src/sync.ts
56480
+ class UnknownRemoteError extends Error {
56481
+ name;
56482
+ declared;
56483
+ constructor(name, declared) {
56484
+ super(`unknown remote '${name}' (declared: ${declared.length === 0 ? "none" : declared.join(", ")})`);
56485
+ this.name = name;
56486
+ this.declared = declared;
56487
+ this.name = "UnknownRemoteError";
56488
+ }
56489
+ }
56490
+ function resolveRemote(remotes, name, substitutions) {
56491
+ const declared = Object.keys(remotes).sort();
56492
+ const entry = remotes[name];
56493
+ if (entry === undefined)
56494
+ throw new UnknownRemoteError(name, declared);
56495
+ const command = entry.command.replaceAll("{content}", substitutions.content).replaceAll("{remote}", entry.remote);
56496
+ return { argv: command.split(/\s+/).filter((part) => part !== ""), remote: entry.remote, command };
56497
+ }
56498
+ // ../../packages/kk-wiki/src/synthesize.ts
56499
+ function folderFor(type) {
56500
+ if (type === "entity")
56501
+ return "entities";
56502
+ if (type === "source")
56503
+ return "sources";
56504
+ return "concepts";
56505
+ }
56506
+ function synthesizePage(index, input) {
56507
+ const existing = index.bySlug.get(resolveSlug(input.target)) ?? index.pages.find((page) => page.path === input.target);
56508
+ const linkedText = linkTitlesInText(index, input.material).trim();
56509
+ if (existing === undefined) {
56510
+ const type = input.type ?? "concept";
56511
+ const slug = resolveSlug(input.target);
56512
+ const path = `${folderFor(type)}/${slug}.md`;
56513
+ const text = renderPage({
56514
+ path,
56515
+ frontmatter: {
56516
+ title: input.target,
56517
+ type,
56518
+ tags: [],
56519
+ sources: [],
56520
+ updated_at: input.date
56521
+ },
56522
+ body: `${linkedText}
56523
+ `
56524
+ });
56525
+ return { path, slug, guard: "clean", created: true, text };
56526
+ }
56527
+ const written = applyWrite(existing, linkedText, { mode: "append", date: input.date });
56528
+ return {
56529
+ path: existing.path,
56530
+ slug: existing.slug,
56531
+ guard: written.guard,
56532
+ created: false,
56533
+ text: renderPage({
56534
+ ...existing,
56535
+ frontmatter: { ...existing.frontmatter, updated_at: input.date },
56536
+ body: written.body
56537
+ })
56538
+ };
56539
+ }
56540
+ // src/wiki/ingest.ts
56541
+ init_dist3();
56542
+
56543
+ // src/wiki/config.ts
56544
+ import { isAbsolute as isAbsolute12, join as join32, resolve as resolve26 } from "path";
56545
+ init_dist3();
56546
+ var WIKI_CONFIG_FILE = "kk.config.json";
56547
+
56548
+ class WikiConfigError extends Error {
56549
+ constructor(message) {
56550
+ super(message);
56551
+ this.name = "WikiConfigError";
56552
+ }
56553
+ }
56554
+ var KEYS = ["root", "raw", "content", "defaultType", "mirrors", "remotes"];
56555
+ var DEFAULTS = {
56556
+ root: ".",
56557
+ raw: "raw",
56558
+ content: "content",
56559
+ defaultType: "html",
56560
+ mirrors: [],
56561
+ remotes: {}
56562
+ };
56563
+ var ENV_MAP = {
56564
+ KK_WIKI_ROOT: "root",
56565
+ KK_WIKI_RAW: "raw",
56566
+ KK_WIKI_CONTENT: "content",
56567
+ KK_WIKI_DEFAULT_TYPE: "defaultType"
56568
+ };
56569
+ function isRecord4(value) {
56570
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56571
+ }
56572
+ function stringField3(block, key, source) {
56573
+ const value = block[key];
56574
+ if (value === undefined)
56575
+ return;
56576
+ if (typeof value !== "string" || value.trim() === "") {
56577
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.${key} must be a non-empty string (${source})`);
56578
+ }
56579
+ return value;
56580
+ }
56581
+ function parseBlock(raw) {
56582
+ if (raw === undefined)
56583
+ return {};
56584
+ if (!isRecord4(raw))
56585
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: "wiki" must be an object`);
56586
+ for (const key of Object.keys(raw)) {
56587
+ if (!KEYS.includes(key)) {
56588
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: unsupported key wiki.${key} (allowed: ${KEYS.join(", ")})`);
56589
+ }
56590
+ }
56591
+ const block = {};
56592
+ const root = stringField3(raw, "root", "wiki.root");
56593
+ const rawDir = stringField3(raw, "raw", "wiki.raw");
56594
+ const content = stringField3(raw, "content", "wiki.content");
56595
+ if (root !== undefined)
56596
+ block.root = root;
56597
+ if (rawDir !== undefined)
56598
+ block.raw = rawDir;
56599
+ if (content !== undefined)
56600
+ block.content = content;
56601
+ const defaultType = stringField3(raw, "defaultType", "wiki.defaultType");
56602
+ if (defaultType !== undefined) {
56603
+ if (!RAW_SOURCE_TYPES.includes(defaultType)) {
56604
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.defaultType '${defaultType}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56605
+ }
56606
+ block.defaultType = defaultType;
56607
+ }
56608
+ const mirrors = raw.mirrors;
56609
+ if (mirrors !== undefined) {
56610
+ if (!Array.isArray(mirrors) || mirrors.some((entry) => typeof entry !== "string")) {
56611
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.mirrors must be an array of strings`);
56612
+ }
56613
+ block.mirrors = mirrors;
56614
+ }
56615
+ const remotes = raw.remotes;
56616
+ if (remotes !== undefined) {
56617
+ if (!isRecord4(remotes))
56618
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes must be an object`);
56619
+ const parsed = {};
56620
+ for (const [name, value] of Object.entries(remotes)) {
56621
+ if (!isRecord4(value) || typeof value.command !== "string" || typeof value.remote !== "string") {
56622
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: wiki.remotes.${name} must be { command: string, remote: string }`);
56623
+ }
56624
+ parsed[name] = { command: value.command, remote: value.remote };
56625
+ }
56626
+ block.remotes = parsed;
56627
+ }
56628
+ return block;
56629
+ }
56630
+ async function readConfigFile(cwd, fileSystem) {
56631
+ const path = join32(cwd, WIKI_CONFIG_FILE);
56632
+ if (!await fileSystem.exists(path))
56633
+ return {};
56634
+ let text;
56635
+ try {
56636
+ text = await fileSystem.readFile(path);
56637
+ } catch (error) {
56638
+ const code = error.code;
56639
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: cannot read (${String(code ?? error)})`);
56640
+ }
56641
+ let parsed;
56642
+ try {
56643
+ parsed = JSON.parse(text);
56644
+ } catch (error) {
56645
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: invalid JSON (${error.message})`);
56646
+ }
56647
+ if (!isRecord4(parsed))
56648
+ throw new WikiConfigError(`${WIKI_CONFIG_FILE}: top level must be an object`);
56649
+ return parseBlock(parsed.wiki);
56650
+ }
56651
+ async function resolveWikiConfig(options = {}) {
56652
+ const cwd = options.cwd ?? process.cwd();
56653
+ const env = options.env ?? process.env;
56654
+ const fileConfig = await readConfigFile(cwd, options.fileSystem ?? createNodeFileSystem());
56655
+ const merged = { ...DEFAULTS, ...fileConfig };
56656
+ for (const [name, key] of Object.entries(ENV_MAP)) {
56657
+ const value = env[name];
56658
+ if (value === undefined || value.trim() === "")
56659
+ continue;
56660
+ if (key === "defaultType") {
56661
+ if (!RAW_SOURCE_TYPES.includes(value)) {
56662
+ throw new WikiConfigError(`${name} '${value}' is not one of ${RAW_SOURCE_TYPES.join("|")}`);
56663
+ }
56664
+ merged.defaultType = value;
56665
+ continue;
56666
+ }
56667
+ merged[key] = value;
56668
+ }
56669
+ Object.assign(merged, Object.fromEntries(Object.entries(options.overrides ?? {}).filter(([, v]) => v !== undefined)));
56670
+ merged.root = resolve26(cwd, merged.root);
56671
+ for (const key of ["raw", "content"]) {
56672
+ if (!isAbsolute12(merged[key]))
56673
+ merged[key] = join32(merged.root, merged[key]);
56674
+ }
56675
+ return merged;
56676
+ }
56677
+
56678
+ // src/wiki/ingest.ts
56679
+ var EXTENSION_TYPES = {
56680
+ ".html": "html",
56681
+ ".htm": "html",
56682
+ ".pdf": "pdf"
56683
+ };
56684
+ function detectSourceType(source) {
56685
+ if (/^https?:\/\//i.test(source))
56686
+ return "url";
56687
+ return EXTENSION_TYPES[extname(source).toLowerCase()];
56688
+ }
56689
+ function asSourceType(raw) {
56690
+ return RAW_SOURCE_TYPES.includes(raw) ? raw : undefined;
56691
+ }
56692
+ async function readStdin(stream = Bun.stdin.stream()) {
56693
+ const chunks = [];
56694
+ for await (const chunk of stream)
56695
+ chunks.push(chunk);
56696
+ return Buffer.concat(chunks).toString("utf8");
56697
+ }
56698
+ async function runIngest(args, deps = {}) {
56699
+ const explicit = args.type === undefined ? undefined : asSourceType(args.type);
56700
+ if (args.type !== undefined && explicit === undefined) {
56701
+ return {
56702
+ ok: false,
56703
+ code: 2,
56704
+ payload: { error: `unsupported --type '${args.type}' (want ${RAW_SOURCE_TYPES.join("|")})` }
56705
+ };
56706
+ }
56707
+ const fromStdin = args.source === "-";
56708
+ const detected = explicit ?? (fromStdin ? undefined : detectSourceType(args.source));
56709
+ if (detected === undefined) {
56710
+ const what = fromStdin ? "stdin requires --type" : `unsupported source type for '${args.source}'`;
56711
+ return { ok: false, code: 2, payload: { error: `${what} (want ${RAW_SOURCE_TYPES.join("|")})` } };
56712
+ }
56713
+ let config;
56714
+ try {
56715
+ config = await resolveWikiConfig({ cwd: deps.cwd, env: deps.env, overrides: { raw: args.out } });
56716
+ } catch (error) {
56717
+ if (error instanceof WikiConfigError)
56718
+ return { ok: false, code: 1, payload: { error: error.message } };
56719
+ throw error;
56720
+ }
56721
+ const fs = deps.fileSystem ?? createNodeFileSystem();
56722
+ const readStdinFn = deps.readStdin ?? readStdin;
56723
+ const normalise = deps.markitdown ?? createMarkitdownRunner();
56724
+ const sourcePath = isAbsolute13(args.source) ? args.source : join33(deps.cwd ?? process.cwd(), args.source);
56725
+ let sourceText;
56726
+ try {
56727
+ if (fromStdin) {
56728
+ sourceText = await readStdinFn();
56729
+ } else if (detected === "rss") {
56730
+ sourceText = await fs.readFile(sourcePath);
56731
+ } else {
56732
+ sourceText = await normalise({
56733
+ kind: detected,
56734
+ target: sourcePath,
56735
+ body: detected === "html" ? await fs.readFile(sourcePath) : undefined
56736
+ });
56737
+ }
56738
+ } catch (error) {
56739
+ if (error instanceof MissingNormalizerError)
56740
+ return { ok: false, code: 1, payload: { error: error.message } };
56741
+ const detail = error instanceof Error ? error.message : String(error);
56742
+ return { ok: false, code: 1, payload: { error: `ingest failed for '${args.source}': ${detail}` } };
56743
+ }
56744
+ const sourceUri = fromStdin ? "stdin" : args.source;
56745
+ const snapshot = await writeRawSnapshot({
56746
+ type: detected,
56747
+ sourceUri,
56748
+ title: deriveTitle(sourceText, sourceUri),
56749
+ body: sourceText,
56750
+ dir: config.raw
56751
+ }, fs);
56752
+ return {
56753
+ ok: true,
56754
+ code: 0,
56755
+ payload: { path: snapshot.path, id: snapshot.id, type: snapshot.type, title: snapshot.title }
56756
+ };
56757
+ }
56758
+
56759
+ // src/wiki/link.ts
56760
+ init_output2();
56761
+ async function runLink(options = {}) {
56762
+ let contentDir;
56763
+ try {
56764
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56765
+ } catch (error) {
56766
+ if (error instanceof WikiConfigError)
56767
+ return { ok: false, code: 1, payload: { error: error.message } };
56768
+ throw error;
56769
+ }
56770
+ const index = await buildVaultIndex(contentDir);
56771
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
56772
+ if (options.fix !== true) {
56773
+ const mentions = findMentions(index);
56774
+ return { ok: true, code: 0, payload: { ok: true, fix: false, mentions } };
56775
+ }
56776
+ const result = await fixLinks(index, { date, contentDir });
56777
+ return { ok: true, code: 0, payload: { ok: true, fix: true, ...result } };
56778
+ }
56779
+ function printLinkOutcome(outcome, json) {
56780
+ if (json) {
56781
+ consoleOutput.write(toJson(outcome.payload));
56782
+ return;
56783
+ }
56784
+ const payload = outcome.payload;
56785
+ if (payload.error !== undefined) {
56786
+ consoleOutput.error(`kk.wiki.link: ${payload.error}`);
56787
+ return;
56788
+ }
56789
+ if (payload.fix === true) {
56790
+ for (const path of payload.changed ?? [])
56791
+ consoleOutput.write(`linked: ${path}`);
56792
+ for (const path of payload.refused ?? [])
56793
+ consoleOutput.write(`guard: ${path} (appended under AI Updates)`);
56794
+ if ((payload.changed ?? []).length === 0 && (payload.refused ?? []).length === 0) {
56795
+ consoleOutput.write("no unlinked mentions");
56796
+ }
56797
+ return;
56798
+ }
56799
+ for (const mention of payload.mentions ?? []) {
56800
+ consoleOutput.write(`${mention.path}:${mention.line} ${mention.surface} -> [[${mention.slug}]]`);
56801
+ }
56802
+ if ((payload.mentions ?? []).length === 0)
56803
+ consoleOutput.write("no unlinked mentions");
56804
+ }
56805
+
56806
+ // src/wiki/lint.ts
56807
+ init_dist3();
56808
+ init_output2();
56809
+ async function runLint(options = {}) {
56810
+ let contentDir;
56811
+ try {
56812
+ contentDir = (await resolveWikiConfig({ cwd: options.cwd, env: options.env })).content;
56813
+ } catch (error) {
56814
+ if (error instanceof WikiConfigError)
56815
+ return { ok: false, code: 1, payload: { error: error.message } };
56816
+ throw error;
56817
+ }
56818
+ const index = await buildVaultIndex(contentDir, createNodeFileSystem());
56819
+ const findings = lintPages(index);
56820
+ return {
56821
+ ok: findings.length === 0,
56822
+ code: lintExitCode(findings),
56823
+ payload: { ok: findings.length === 0, findings, pages: index.pages.length }
56824
+ };
56825
+ }
56826
+ function printLintOutcome(outcome, json) {
56827
+ if (json) {
56828
+ consoleOutput.write(toJson(outcome.payload));
56829
+ return;
56830
+ }
56831
+ const payload = outcome.payload;
56832
+ if (payload.error !== undefined) {
56833
+ consoleOutput.error(`kk.wiki.lint: ${payload.error}`);
56834
+ return;
56835
+ }
56836
+ for (const finding of payload.findings ?? []) {
56837
+ consoleOutput.write(`${finding.path}:${finding.line} ${finding.code}: ${finding.message}`);
56838
+ }
56839
+ if ((payload.findings ?? []).length === 0)
56840
+ consoleOutput.write("vault is clean");
56841
+ }
56842
+
56843
+ // src/wiki/maintenance.ts
56844
+ import { join as join34 } from "path";
56845
+ init_dist3();
56846
+ init_output2();
56847
+ async function withConfig2(options, run) {
56848
+ try {
56849
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
56850
+ return await run({ contentDir: config.content, rawDir: config.raw, mirrors: config.mirrors });
56851
+ } catch (error) {
56852
+ if (error instanceof WikiConfigError)
56853
+ return { error: error.message };
56854
+ throw error;
56855
+ }
56856
+ }
56857
+ async function runMerge(options) {
56858
+ const result = await withConfig2(options, async ({ contentDir }) => {
56859
+ const index = await buildVaultIndex(contentDir);
56860
+ const merge = mergePages(index, options.from ?? "", options.to ?? "", {
56861
+ date: options.date ?? new Date().toISOString().slice(0, 10)
56862
+ });
56863
+ if (merge.guard === "refused")
56864
+ return { refused: true, path: merge.written };
56865
+ const fs = createNodeFileSystem();
56866
+ await fs.writeFile(join34(contentDir, merge.written), merge.targetText);
56867
+ const sourcePage = index.pages.find((page) => page.slug === merge.sourceSlug);
56868
+ if (sourcePage !== undefined)
56869
+ await fs.writeFile(join34(contentDir, sourcePage.path), merge.sourceText);
56870
+ for (const page of merge.rewrittenPages)
56871
+ await fs.writeFile(join34(contentDir, page.path), page.text);
56872
+ return {
56873
+ refused: false,
56874
+ path: merge.written,
56875
+ redirects: merge.redirects,
56876
+ rewritten: merge.rewritten,
56877
+ rewrittenPages: merge.rewrittenPages,
56878
+ sourceText: merge.sourceText,
56879
+ sourceSlug: merge.sourceSlug
56880
+ };
56881
+ });
56882
+ if ("error" in result)
56883
+ return { ok: false, code: 1, payload: result };
56884
+ if (result.refused === true) {
56885
+ return { ok: false, code: 1, payload: { ok: false, error: "source page is user_edited; merge refused" } };
56886
+ }
56887
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56888
+ }
56889
+ async function runCompile(options) {
56890
+ const result = await withConfig2(options, async ({ contentDir }) => {
56891
+ const index = await buildVaultIndex(contentDir);
56892
+ const compiled = compileIndex(index.pages, { date: options.date ?? new Date().toISOString().slice(0, 10) });
56893
+ const fs = createNodeFileSystem();
56894
+ const written = [];
56895
+ for (const [name, rendered] of [
56896
+ ["index.md", compiled.index],
56897
+ ["MAP.md", compiled.map]
56898
+ ]) {
56899
+ const path = join34(contentDir, name);
56900
+ const current = await fs.exists(path) ? await fs.readFile(path) : null;
56901
+ if (!needsWrite(current, rendered))
56902
+ continue;
56903
+ await fs.writeFile(path, rendered);
56904
+ written.push(name);
56905
+ }
56906
+ return { written };
56907
+ });
56908
+ if ("error" in result)
56909
+ return { ok: false, code: 1, payload: result };
56910
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56911
+ }
56912
+ async function runGc(options) {
56913
+ const result = await withConfig2(options, async ({ contentDir, rawDir, mirrors }) => {
56914
+ const fs = createNodeFileSystem();
56915
+ const index = await buildVaultIndex(contentDir);
56916
+ const plan = await planGc(index, { rawDir, mirrors, fileSystem: fs });
56917
+ if (options.yes !== true)
56918
+ return { plan, deleted: [] };
56919
+ const { deleted } = await applyGc(plan, fs);
56920
+ return { plan, deleted };
56921
+ });
56922
+ if ("error" in result)
56923
+ return { ok: false, code: 1, payload: result };
56924
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56925
+ }
56926
+ function printMaintenanceOutcome(outcome, json) {
56927
+ if (json) {
56928
+ consoleOutput.write(toJson(outcome.payload));
56929
+ return;
56930
+ }
56931
+ const payload = outcome.payload;
56932
+ if (payload.error !== undefined) {
56933
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
56934
+ return;
56935
+ }
56936
+ if (payload.plan !== undefined) {
56937
+ for (const path of payload.plan.delete)
56938
+ consoleOutput.write(`delete: ${path}`);
56939
+ for (const path of payload.plan.skippedMirrors)
56940
+ consoleOutput.write(`skip (mirror): ${path}`);
56941
+ if ((payload.deleted ?? []).length === 0)
56942
+ consoleOutput.write("dry run \u2014 pass --yes to delete");
56943
+ return;
56944
+ }
56945
+ if (payload.rewritten !== undefined) {
56946
+ consoleOutput.write(`merged into ${payload.path} (${payload.redirects} links rewritten)`);
56947
+ return;
56948
+ }
56949
+ for (const name of payload.written ?? [])
56950
+ consoleOutput.write(`compiled: ${name}`);
56951
+ if ((payload.written ?? []).length === 0)
56952
+ consoleOutput.write("already up to date");
56953
+ }
56954
+
56955
+ // src/wiki/retrieval.ts
56956
+ init_dist3();
56957
+ init_output2();
56958
+ async function configOrError(options) {
56959
+ try {
56960
+ return await resolveWikiConfig({ cwd: options.cwd, env: options.env });
56961
+ } catch (error) {
56962
+ if (error instanceof WikiConfigError)
56963
+ return { error: error.message };
56964
+ throw error;
56965
+ }
56966
+ }
56967
+ async function runPublish(options) {
56968
+ const config = await configOrError(options);
56969
+ if ("error" in config)
56970
+ return { ok: false, code: 1, payload: config };
56971
+ try {
56972
+ const index = await buildVaultIndex(config.content);
56973
+ const result = await publishVault(index, {
56974
+ target: options.value ?? "",
56975
+ fileSystem: createNodeFileSystem()
56976
+ });
56977
+ if (result.refused !== undefined) {
56978
+ return { ok: false, code: 2, payload: { ok: false, error: "target is inside the vault" } };
56979
+ }
56980
+ return { ok: true, code: 0, payload: { ok: true, ...result } };
56981
+ } catch (error) {
56982
+ return { ok: false, code: 1, payload: { ok: false, error: error.message } };
56983
+ }
56984
+ }
56985
+ async function runSync(options) {
56986
+ const config = await configOrError(options);
56987
+ if ("error" in config)
56988
+ return { ok: false, code: 1, payload: config };
56989
+ try {
56990
+ const resolved = resolveRemote(config.remotes, options.value ?? "", { content: config.content });
56991
+ return { ok: true, code: 0, payload: { ok: true, dryRun: options.dryRun !== false, ...resolved } };
56992
+ } catch (error) {
56993
+ return { ok: false, code: 2, payload: { ok: false, error: error.message } };
56994
+ }
56995
+ }
56996
+ async function runQuery(options) {
56997
+ const config = await configOrError(options);
56998
+ if ("error" in config)
56999
+ return { ok: false, code: 1, payload: config };
57000
+ const index = await buildVaultIndex(config.content);
57001
+ const hits = rankPages(index, options.value ?? "", { limit: options.limit });
57002
+ return { ok: true, code: 0, payload: { ok: true, hits } };
57003
+ }
57004
+ async function runContext(options) {
57005
+ const config = await configOrError(options);
57006
+ if ("error" in config)
57007
+ return { ok: false, code: 1, payload: config };
57008
+ const index = await buildVaultIndex(config.content);
57009
+ const packed = packContext(index, options.value ?? "", { depth: options.depth });
57010
+ return { ok: true, code: 0, payload: { ok: true, ...packed } };
57011
+ }
57012
+ function printRetrievalOutcome(outcome, json) {
57013
+ if (json) {
57014
+ consoleOutput.write(toJson(outcome.payload));
57015
+ return;
57016
+ }
57017
+ const payload = outcome.payload;
57018
+ if (payload.error !== undefined) {
57019
+ consoleOutput.error(`kk.wiki: ${payload.error}`);
57020
+ return;
57021
+ }
57022
+ if (payload.files !== undefined) {
57023
+ consoleOutput.write(`published ${payload.files.length} file(s)`);
57024
+ return;
57025
+ }
57026
+ if (payload.command !== undefined) {
57027
+ consoleOutput.write(`remote: ${payload.command}`);
57028
+ return;
57029
+ }
57030
+ if (payload.hits !== undefined) {
57031
+ for (const hit of payload.hits)
57032
+ consoleOutput.write(`${hit.path} (${hit.score})`);
57033
+ return;
57034
+ }
57035
+ consoleOutput.write(payload.markdown ?? "");
57036
+ }
57037
+
57038
+ // src/wiki/write-verbs.ts
57039
+ import { isAbsolute as isAbsolute14, join as join35 } from "path";
57040
+ init_dist3();
57041
+ init_output2();
57042
+ async function readMaterial(options) {
57043
+ if (options.from === "-") {
57044
+ if (options.readStdin !== undefined)
57045
+ return options.readStdin();
57046
+ const chunks = [];
57047
+ for await (const chunk of Bun.stdin.stream())
57048
+ chunks.push(chunk);
57049
+ return Buffer.concat(chunks).toString("utf8");
57050
+ }
57051
+ const path = isAbsolute14(options.from) ? options.from : join35(options.cwd ?? process.cwd(), options.from);
57052
+ return createNodeFileSystem().readFile(path);
57053
+ }
57054
+ async function resolveContext(options) {
57055
+ try {
57056
+ const config = await resolveWikiConfig({ cwd: options.cwd, env: options.env });
57057
+ const index = await buildVaultIndex(config.content);
57058
+ return { index, contentDir: config.content };
57059
+ } catch (error) {
57060
+ if (error instanceof WikiConfigError)
57061
+ return { error: error.message };
57062
+ throw error;
57063
+ }
57064
+ }
57065
+ async function runSummarize(options) {
57066
+ const context = await resolveContext(options);
57067
+ if ("error" in context)
57068
+ return { ok: false, code: 1, payload: { error: context.error } };
57069
+ const target = context.index.pages.find((page) => page.path === options.target);
57070
+ if (target === undefined) {
57071
+ return { ok: false, code: 1, payload: { error: `no page at '${options.target}'` } };
57072
+ }
57073
+ const material = await readMaterial(options);
57074
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57075
+ const result = summarizePage(context.index, target, material, { date });
57076
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57077
+ return { ok: true, code: 0, payload: { ok: true, path: result.path, guard: result.guard, links: result.links } };
57078
+ }
57079
+ async function runSynthesize(options) {
57080
+ const context = await resolveContext(options);
57081
+ if ("error" in context)
57082
+ return { ok: false, code: 1, payload: { error: context.error } };
57083
+ const material = await readMaterial(options);
57084
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
57085
+ const type = options.type;
57086
+ const result = synthesizePage(context.index, { target: options.target, material, type, date });
57087
+ await createNodeFileSystem().writeFile(join35(context.contentDir, result.path), result.text);
57088
+ return {
57089
+ ok: true,
57090
+ code: 0,
57091
+ payload: { ok: true, path: result.path, slug: result.slug, guard: result.guard, created: result.created }
57092
+ };
57093
+ }
57094
+ function printWriteOutcome(outcome, json) {
57095
+ if (json) {
57096
+ consoleOutput.write(toJson(outcome.payload));
57097
+ return;
57098
+ }
57099
+ const payload = outcome.payload;
57100
+ if (payload.error !== undefined) {
57101
+ consoleOutput.error(`kk.wiki.write: ${payload.error}`);
57102
+ return;
57103
+ }
57104
+ consoleOutput.write(`${payload.created === true ? "created" : "updated"} ${payload.path} (guard: ${payload.guard})`);
57105
+ }
57106
+
57107
+ // src/commands/wiki.ts
57108
+ async function ingestAction2(source, options) {
57109
+ const outcome = await runIngest({ source, type: options.type, out: options.out, json: options.json });
57110
+ if (outcome.ok) {
57111
+ if (options.json === true)
57112
+ consoleOutput.write(toJson(outcome.payload));
57113
+ else
57114
+ consoleOutput.write(`raw snapshot: ${outcome.payload.path}`);
57115
+ return;
57116
+ }
57117
+ const message = `kk.wiki.ingest: ${outcome.payload.error}`;
57118
+ if (options.json === true)
57119
+ consoleOutput.write(toJson({ ok: false, error: outcome.payload.error }));
57120
+ consoleOutput.error(message);
57121
+ throw new CommanderError(outcome.code, "kk.wiki.ingest", message);
57122
+ }
57123
+ async function linkAction(options) {
57124
+ const outcome = await runLink({ fix: options.fix === true, json: options.json === true });
57125
+ printLinkOutcome(outcome, options.json === true);
57126
+ if (!outcome.ok)
57127
+ throw new CommanderError(outcome.code, "kk.wiki.link", "kk.wiki.link failed");
57128
+ }
57129
+ async function lintAction(options) {
57130
+ const outcome = await runLint({ json: options.json === true });
57131
+ printLintOutcome(outcome, options.json === true);
57132
+ if (outcome.code !== 0)
57133
+ throw new CommanderError(outcome.code, "kk.wiki.lint", "kk.wiki.lint findings");
57134
+ }
57135
+ async function summarizeAction(target, options) {
57136
+ const outcome = await runSummarize({ target, from: options.from, json: options.json === true });
57137
+ printWriteOutcome(outcome, options.json === true);
57138
+ if (!outcome.ok)
57139
+ throw new CommanderError(outcome.code, "kk.wiki.summarize", "kk.wiki.summarize failed");
57140
+ }
57141
+ async function synthesizeAction(target, options) {
57142
+ const outcome = await runSynthesize({
57143
+ target,
57144
+ from: options.from,
57145
+ type: options.type,
57146
+ json: options.json === true
57147
+ });
57148
+ printWriteOutcome(outcome, options.json === true);
57149
+ if (!outcome.ok)
57150
+ throw new CommanderError(outcome.code, "kk.wiki.synthesize", "kk.wiki.synthesize failed");
57151
+ }
57152
+ async function mergeAction(source, target, options) {
57153
+ const outcome = await runMerge({ from: source, to: target, json: options.json === true });
57154
+ printMaintenanceOutcome(outcome, options.json === true);
57155
+ if (!outcome.ok)
57156
+ throw new CommanderError(outcome.code, "kk.wiki.merge", "kk.wiki.merge failed");
57157
+ }
57158
+ async function compileAction(options) {
57159
+ const outcome = await runCompile({ json: options.json === true });
57160
+ printMaintenanceOutcome(outcome, options.json === true);
57161
+ if (!outcome.ok)
57162
+ throw new CommanderError(outcome.code, "kk.wiki.compile", "kk.wiki.compile failed");
57163
+ }
57164
+ async function gcAction(options) {
57165
+ const outcome = await runGc({ yes: options.yes === true, json: options.json === true });
57166
+ printMaintenanceOutcome(outcome, options.json === true);
57167
+ if (!outcome.ok)
57168
+ throw new CommanderError(outcome.code, "kk.wiki.gc", "kk.wiki.gc failed");
57169
+ }
57170
+ async function publishAction(options) {
57171
+ const outcome = await runPublish({ value: options.target, json: options.json === true });
57172
+ printRetrievalOutcome(outcome, options.json === true);
57173
+ if (!outcome.ok)
57174
+ throw new CommanderError(outcome.code, "kk.wiki.publish", "kk.wiki.publish failed");
57175
+ }
57176
+ async function syncAction(remote, options) {
57177
+ const outcome = await runSync({ value: remote, dryRun: options.dryRun === true, json: options.json === true });
57178
+ printRetrievalOutcome(outcome, options.json === true);
57179
+ if (!outcome.ok)
57180
+ throw new CommanderError(outcome.code, "kk.wiki.sync", "kk.wiki.sync failed");
57181
+ }
57182
+ async function queryAction(prompt, options) {
57183
+ const outcome = await runQuery({
57184
+ value: prompt,
57185
+ limit: options.limit === undefined ? undefined : Number(options.limit),
57186
+ json: options.json === true
57187
+ });
57188
+ printRetrievalOutcome(outcome, options.json === true);
57189
+ if (!outcome.ok)
57190
+ throw new CommanderError(outcome.code, "kk.wiki.query", "kk.wiki.query failed");
57191
+ }
57192
+ async function contextAction(topic, options) {
57193
+ const outcome = await runContext({
57194
+ value: topic,
57195
+ depth: options.depth === undefined ? undefined : Number(options.depth),
57196
+ json: options.json === true
57197
+ });
57198
+ printRetrievalOutcome(outcome, options.json === true);
57199
+ if (!outcome.ok)
57200
+ throw new CommanderError(outcome.code, "kk.wiki.context", "kk.wiki.context failed");
57201
+ }
57202
+ function registerWikiCommand(parent) {
57203
+ const wiki = parent.command("wiki").description("Deterministic Markdown vault mechanics (ADR-048)");
57204
+ wiki.command("ingest").description("Normalise a file, URL or stdin body into a layer-1 raw snapshot").argument("<source>", "File path, http(s) URL, or - for stdin").option("--type <type>", "Source type: url | pdf | html | rss (default: from the extension)").option("--out <dir>", "Raw directory override (default: wiki.raw from kk.config.json)").option("--json", "Print one JSON document instead of a one-line summary").action(ingestAction2);
57205
+ wiki.command("link").description("Report unlinked mentions of existing page titles; --fix injects them").option("--fix", "Rewrite the reported mentions to [[slug|Surface]]").option("--json", "Print one JSON document").action(linkAction);
57206
+ wiki.command("summarize").description("Place authored summary text into a page and link the references it mentions").argument("<target>", "Vault-relative page path, e.g. concepts/vector-index.md").requiredOption("--from <source>", "Text source: - for stdin, or a file path").option("--json", "Print one JSON document").action(summarizeAction);
57207
+ wiki.command("synthesize").description("Create a page for a new topic, or extend an existing page, from authored text").argument("<target>", "Topic title or vault-relative page path").requiredOption("--from <source>", "Text source: - for stdin, or a file path").option("--type <pageType>", "Page class for a created page: concept | entity | source | index").option("--json", "Print one JSON document").action(synthesizeAction);
57208
+ wiki.command("merge").description("Merge a source page into a target page, leaving a redirect and rewriting inbound links").argument("<source>", "Page path or slug to absorb").argument("<target>", "Page path or slug to survive").option("--json", "Print one JSON document").action(mergeAction);
57209
+ wiki.command("compile").description("Regenerate content/index.md and content/MAP.md from the vault structure").option("--json", "Print one JSON document").action(compileAction);
57210
+ wiki.command("gc").description("Reclaim unreferenced raw snapshots; prints the plan unless --yes is passed").option("--yes", "Delete the planned files").option("--json", "Print one JSON document").action(gcAction);
57211
+ wiki.command("publish").description("Project content/ into a Quartz-compatible tree at --target").requiredOption("--target <dir>", "Destination directory (the published tree lands under <dir>/content)").option("--json", "Print one JSON document").action(publishAction);
57212
+ wiki.command("sync").description("Resolve a configured remote into its command; --dry-run transfers nothing").argument("<remote>", "Remote name declared in kk.config.json wiki.remotes").option("--dry-run", "Print the resolved command without transferring").option("--json", "Print one JSON document").action(syncAction);
57213
+ wiki.command("query").description("Rank vault pages against a prompt and print their paths").argument("<prompt>", "Search prompt").option("--limit <n>", "Maximum hits (default 10)").option("--json", "Print one JSON document").action(queryAction);
57214
+ wiki.command("context").description("Pack the topic page and its graph neighbours into one Markdown block").argument("<topic>", "Topic title or slug").option("--depth <n>", "Neighbour depth (default 1)").option("--json", "Print one JSON document").action(contextAction);
57215
+ wiki.command("lint").description("Audit the vault for broken links, orphan pages and frontmatter defects").option("--json", "Print one JSON document").action(lintAction);
57216
+ }
57217
+
54997
57218
  // src/config.ts
54998
57219
  import { readFileSync as readFileSync9 } from "fs";
54999
57220
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -55018,6 +57239,7 @@ function createProgram() {
55018
57239
  registerScheduleCommand(program);
55019
57240
  registerStageCommand(program);
55020
57241
  registerStoreCommand(program);
57242
+ registerWikiCommand(program);
55021
57243
  return program;
55022
57244
  }
55023
57245