@kingsleyasher/dsh-knowledge-base 0.0.0-stage → 3.1.5

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 (516) hide show
  1. package/ARCHITECTURE.en.md +35 -0
  2. package/ARCHITECTURE.md +40 -0
  3. package/BETA4.md +31 -0
  4. package/BETA7.md +35 -0
  5. package/BETA8.md +39 -0
  6. package/BETA9.md +38 -0
  7. package/CONTRIBUTING.md +5 -0
  8. package/DEVELOPMENT.en.md +26 -0
  9. package/DEVELOPMENT.md +27 -0
  10. package/EXISTING-FRAMEWORK-OPTIMIZATION.md +101 -0
  11. package/LICENSE +21 -0
  12. package/MONOREPO.md +34 -0
  13. package/NPM-EDITION.md +12 -0
  14. package/PARSING-PREVIEW.md +84 -0
  15. package/PERFORMANCE.md +43 -0
  16. package/PRIVACY.md +7 -0
  17. package/PROJECT-RECORD.en.md +782 -0
  18. package/PROJECT-RECORD.md +793 -0
  19. package/README.md +109 -3
  20. package/README.zh-CN.md +117 -0
  21. package/RELEASE.en.md +559 -0
  22. package/RELEASE.md +570 -0
  23. package/RETRIEVAL.md +93 -0
  24. package/SECURITY.md +7 -0
  25. package/THIRD-PARTY-NOTICES.md +5 -0
  26. package/VERSIONING.en.md +51 -0
  27. package/VERSIONING.md +50 -0
  28. package/WORKBENCH.en.md +201 -0
  29. package/WORKBENCH.md +195 -0
  30. package/browser-extension/background.js +146 -0
  31. package/browser-extension/icons/knowledge-base-128.png +0 -0
  32. package/browser-extension/icons/knowledge-base-16.png +0 -0
  33. package/browser-extension/icons/knowledge-base-32.png +0 -0
  34. package/browser-extension/icons/knowledge-base-48.png +0 -0
  35. package/browser-extension/manifest.json +25 -0
  36. package/browser-extension/options.html +22 -0
  37. package/browser-extension/options.js +41 -0
  38. package/browser-extension/popup.html +17 -0
  39. package/browser-extension/popup.js +58 -0
  40. package/browser-extension/style.css +11 -0
  41. package/cordis.patch.yml +88 -0
  42. package/docs/LEGACY-246-BOOTSTRAP.md +21 -0
  43. package/docs/LIBRARY-FRAMEWORK-MIGRATION.md +45 -0
  44. package/docs/ORIGINAL-FILE-INDEX-ARCHITECTURE.md +43 -0
  45. package/docs/TODO-LIFECYCLE-VALIDATION.md +42 -0
  46. package/docs/UPDATE-RECOVERY.en.md +18 -0
  47. package/docs/UPDATE-RECOVERY.md +70 -0
  48. package/docs/WINDOWS-SIGNING.md +30 -0
  49. package/docs/client/ARCHITECTURE.en.md +17 -0
  50. package/docs/client/ARCHITECTURE.md +17 -0
  51. package/docs/client/CONTRIBUTING.md +5 -0
  52. package/docs/client/CROSS-VOLUME-TRASH.md +13 -0
  53. package/docs/client/DEVELOPMENT.en.md +33 -0
  54. package/docs/client/DEVELOPMENT.md +33 -0
  55. package/docs/client/EXISTING-FRAMEWORK-OPTIMIZATION.md +3 -0
  56. package/docs/client/PERFORMANCE.md +3 -0
  57. package/docs/client/PRIVACY.md +7 -0
  58. package/docs/client/PROJECT-RECORD.en.md +199 -0
  59. package/docs/client/PROJECT-RECORD.md +219 -0
  60. package/docs/client/README.md +55 -0
  61. package/docs/client/README.zh-CN.md +45 -0
  62. package/docs/client/RELEASE.en.md +148 -0
  63. package/docs/client/RELEASE.md +149 -0
  64. package/docs/client/RETRIEVAL.md +3 -0
  65. package/docs/client/SECURITY.md +7 -0
  66. package/docs/client/THIRD-PARTY-NOTICES.md +5 -0
  67. package/docs/client/VERSIONING.en.md +9 -0
  68. package/docs/client/VERSIONING.md +9 -0
  69. package/docs/client/WORKBENCH.en.md +24 -0
  70. package/docs/client/WORKBENCH.md +24 -0
  71. package/docs/client/skills/personal-knowledge-base/SKILL.md +38 -0
  72. package/docs/releases/client-1.0.1.md +32 -0
  73. package/docs/releases/client-1.0.2.md +32 -0
  74. package/docs/releases/client-1.0.3.md +31 -0
  75. package/docs/releases/client-1.1.1.md +28 -0
  76. package/docs/releases/client-1.1.2.md +16 -0
  77. package/docs/releases/client-1.1.4.md +7 -0
  78. package/docs/releases/client-2.0.0.en.md +13 -0
  79. package/docs/releases/client-2.0.0.md +13 -0
  80. package/docs/releases/client-2.0.1.en.md +10 -0
  81. package/docs/releases/client-2.0.1.md +10 -0
  82. package/docs/releases/client-2.0.3.en.md +8 -0
  83. package/docs/releases/client-2.0.3.md +8 -0
  84. package/docs/releases/plugin-2.4.1.md +24 -0
  85. package/docs/releases/plugin-2.4.10.md +22 -0
  86. package/docs/releases/plugin-2.4.11.md +14 -0
  87. package/docs/releases/plugin-2.4.12.md +14 -0
  88. package/docs/releases/plugin-2.4.13.md +27 -0
  89. package/docs/releases/plugin-2.4.14.md +18 -0
  90. package/docs/releases/plugin-2.4.2.md +31 -0
  91. package/docs/releases/plugin-2.4.3.md +25 -0
  92. package/docs/releases/plugin-2.4.4.md +31 -0
  93. package/docs/releases/plugin-2.4.5.md +23 -0
  94. package/docs/releases/plugin-2.4.6.md +23 -0
  95. package/docs/releases/plugin-2.4.7.md +14 -0
  96. package/docs/releases/plugin-2.4.8.md +14 -0
  97. package/docs/releases/plugin-2.4.9.md +18 -0
  98. package/docs/releases/plugin-2.5.10.md +11 -0
  99. package/docs/releases/plugin-2.5.13.en.md +11 -0
  100. package/docs/releases/plugin-2.5.13.md +11 -0
  101. package/docs/releases/plugin-2.5.3.md +28 -0
  102. package/docs/releases/plugin-2.5.4.md +14 -0
  103. package/docs/releases/plugin-2.5.5.md +16 -0
  104. package/docs/releases/plugin-2.5.6.md +3 -0
  105. package/docs/releases/plugin-2.5.7.md +7 -0
  106. package/docs/releases/plugin-2.5.8.md +7 -0
  107. package/docs/releases/plugin-2.5.9.md +7 -0
  108. package/docs/releases/plugin-3.0.0.en.md +13 -0
  109. package/docs/releases/plugin-3.0.0.md +13 -0
  110. package/docs/releases/plugin-3.0.1.en.md +10 -0
  111. package/docs/releases/plugin-3.0.1.md +10 -0
  112. package/docs/releases/plugin-3.1.3.en.md +11 -0
  113. package/docs/releases/plugin-3.1.3.md +11 -0
  114. package/docs/validation/windows-auto-update-2.4.13.md +31 -0
  115. package/docs/validation/windows-direct-246-to-2413.md +32 -0
  116. package/package.json +78 -6
  117. package/packages/kb-contracts/desktop.js +29 -0
  118. package/packages/kb-contracts/index.js +132 -0
  119. package/packages/kb-contracts/node.js +3 -0
  120. package/packages/kb-contracts/package.json +17 -0
  121. package/packages/kb-contracts/schema.js +42 -0
  122. package/packages/kb-contracts/tools.js +1 -0
  123. package/packages/kb-contracts/version-policy.js +45 -0
  124. package/packages/kb-core/index.js +9 -0
  125. package/packages/kb-core/package.json +15 -0
  126. package/packages/kb-core/src/capture-surface.js +22 -0
  127. package/packages/kb-core/src/documents.js +105 -0
  128. package/packages/kb-core/src/embedded.js +29 -0
  129. package/packages/kb-core/src/file-catalog.js +151 -0
  130. package/packages/kb-core/src/file-classification.js +60 -0
  131. package/packages/kb-core/src/flow-workspace.js +66 -0
  132. package/packages/kb-core/src/flows.js +1136 -0
  133. package/packages/kb-core/src/fsindex.js +293 -0
  134. package/packages/kb-core/src/import-service.js +486 -0
  135. package/packages/kb-core/src/importer.js +909 -0
  136. package/packages/kb-core/src/inbox-flow.js +2 -0
  137. package/packages/kb-core/src/index-architecture.js +48 -0
  138. package/packages/kb-core/src/index-maintenance.js +81 -0
  139. package/packages/kb-core/src/index-policy-service.js +191 -0
  140. package/packages/kb-core/src/index-policy.js +121 -0
  141. package/packages/kb-core/src/kbcore.js +2519 -0
  142. package/packages/kb-core/src/library-framework.js +186 -0
  143. package/packages/kb-core/src/library-state.js +68 -0
  144. package/packages/kb-core/src/managed-files.js +69 -0
  145. package/packages/kb-core/src/map.js +171 -0
  146. package/packages/kb-core/src/parse-credentials.js +49 -0
  147. package/packages/kb-core/src/parse-discovery.js +119 -0
  148. package/packages/kb-core/src/parse-job-storage.js +40 -0
  149. package/packages/kb-core/src/parse-native.js +87 -0
  150. package/packages/kb-core/src/parse-presets.js +46 -0
  151. package/packages/kb-core/src/parse-source-authority.js +72 -0
  152. package/packages/kb-core/src/parsing.js +2307 -0
  153. package/packages/kb-core/src/relation-name-lookup.js +43 -0
  154. package/packages/kb-core/src/retrieval-api.js +79 -0
  155. package/packages/kb-core/src/retrieval-cache.js +22 -0
  156. package/packages/kb-core/src/retrieval-chunks.js +128 -0
  157. package/packages/kb-core/src/retrieval-pool.js +102 -0
  158. package/packages/kb-core/src/retrieval-worker.js +190 -0
  159. package/packages/kb-core/src/retrieval.js +618 -0
  160. package/packages/kb-core/src/runtime-resources.js +73 -0
  161. package/packages/kb-core/src/service-ownership.js +18 -0
  162. package/packages/kb-core/src/source-references.js +61 -0
  163. package/packages/kb-core/src/storage-io.js +121 -0
  164. package/packages/kb-core/src/system-upgrades.js +104 -0
  165. package/packages/kb-core/src/workbench-backup.js +219 -0
  166. package/packages/kb-core/src/workbench-deliverables.js +73 -0
  167. package/packages/kb-core/src/workbench-files.js +25 -0
  168. package/packages/kb-core/src/workbench-inbox.js +57 -0
  169. package/packages/kb-core/src/workbench-links.js +236 -0
  170. package/packages/kb-core/src/workbench-question.js +131 -0
  171. package/packages/kb-core/src/workbench-relation-index.js +110 -0
  172. package/packages/kb-core/src/workbench-state.js +102 -0
  173. package/packages/kb-core/src/workbench-trash.js +213 -0
  174. package/packages/kb-core/src/workbench.js +936 -0
  175. package/packages/kb-service/auth.js +39 -0
  176. package/packages/kb-service/build.js +18 -0
  177. package/packages/kb-service/cli.js +26 -0
  178. package/packages/kb-service/client.js +64 -0
  179. package/packages/kb-service/clipper.js +15 -0
  180. package/packages/kb-service/compatibility.js +34 -0
  181. package/packages/kb-service/desktop-files.js +514 -0
  182. package/packages/kb-service/desktop-host-links.js +39 -0
  183. package/packages/kb-service/dsh-broker.js +64 -0
  184. package/packages/kb-service/dsh-host.js +168 -0
  185. package/packages/kb-service/dsh-stream-relay.js +32 -0
  186. package/packages/kb-service/engines.js +32 -0
  187. package/packages/kb-service/extension.js +8 -0
  188. package/packages/kb-service/first-library-handoff.js +28 -0
  189. package/packages/kb-service/handoff-api.js +22 -0
  190. package/packages/kb-service/host-adapter.js +151 -0
  191. package/packages/kb-service/host-assets.js +9 -0
  192. package/packages/kb-service/host-python.js +30 -0
  193. package/packages/kb-service/host-updates.js +97 -0
  194. package/packages/kb-service/inbox-host.js +47 -0
  195. package/packages/kb-service/inbox-jobs.js +54 -0
  196. package/packages/kb-service/index.js +3 -0
  197. package/packages/kb-service/io.js +24 -0
  198. package/packages/kb-service/launch-lock.js +27 -0
  199. package/packages/kb-service/launcher.js +18 -0
  200. package/packages/kb-service/legacy-handoff.js +27 -0
  201. package/packages/kb-service/legacy-ports.js +18 -0
  202. package/packages/kb-service/main.js +13 -0
  203. package/packages/kb-service/memory-channel.js +57 -0
  204. package/packages/kb-service/memory-sync.js +42 -0
  205. package/packages/kb-service/migration.js +131 -0
  206. package/packages/kb-service/native.py +216 -0
  207. package/packages/kb-service/operations.js +19 -0
  208. package/packages/kb-service/package.json +1 -0
  209. package/packages/kb-service/runtime.js +185 -0
  210. package/packages/kb-service/safe-update.js +104 -0
  211. package/packages/kb-service/service.js +494 -0
  212. package/packages/kb-service/tool-definitions.json +934 -0
  213. package/packages/kb-service/tool-router.js +45 -0
  214. package/packages/kb-service/vector-profiles.js +41 -0
  215. package/presets/01-knowledge-agent.patch.yml +347 -0
  216. package/runtime/python/LICENSE.txt +676 -0
  217. package/runtime/python/_asyncio.pyd +0 -0
  218. package/runtime/python/_bz2.pyd +0 -0
  219. package/runtime/python/_ctypes.pyd +0 -0
  220. package/runtime/python/_decimal.pyd +0 -0
  221. package/runtime/python/_elementtree.pyd +0 -0
  222. package/runtime/python/_hashlib.pyd +0 -0
  223. package/runtime/python/_lzma.pyd +0 -0
  224. package/runtime/python/_multiprocessing.pyd +0 -0
  225. package/runtime/python/_overlapped.pyd +0 -0
  226. package/runtime/python/_queue.pyd +0 -0
  227. package/runtime/python/_remote_debugging.pyd +0 -0
  228. package/runtime/python/_socket.pyd +0 -0
  229. package/runtime/python/_sqlite3.pyd +0 -0
  230. package/runtime/python/_ssl.pyd +0 -0
  231. package/runtime/python/_uuid.pyd +0 -0
  232. package/runtime/python/_wmi.pyd +0 -0
  233. package/runtime/python/_zoneinfo.pyd +0 -0
  234. package/runtime/python/_zstd.pyd +0 -0
  235. package/runtime/python/libcrypto-3.dll +0 -0
  236. package/runtime/python/libffi-8.dll +0 -0
  237. package/runtime/python/libssl-3.dll +0 -0
  238. package/runtime/python/libtommath.dll +0 -0
  239. package/runtime/python/pyexpat.pyd +0 -0
  240. package/runtime/python/python.cat +0 -0
  241. package/runtime/python/python.exe +0 -0
  242. package/runtime/python/python3.dll +0 -0
  243. package/runtime/python/python314._pth +5 -0
  244. package/runtime/python/python314.dll +0 -0
  245. package/runtime/python/python314.zip +0 -0
  246. package/runtime/python/pythonw.exe +0 -0
  247. package/runtime/python/select.pyd +0 -0
  248. package/runtime/python/sqlite3.dll +0 -0
  249. package/runtime/python/unicodedata.pyd +0 -0
  250. package/runtime/python/vcruntime140.dll +0 -0
  251. package/runtime/python/vcruntime140_1.dll +0 -0
  252. package/runtime/python/winsound.pyd +0 -0
  253. package/skills/personal-knowledge-base/SKILL.md +38 -0
  254. package/src/client/capture-icon-192.png +0 -0
  255. package/src/client/capture-icon-512.png +0 -0
  256. package/src/client/capture-icon.svg +12 -0
  257. package/src/client/capture-sw.js +10 -0
  258. package/src/client/capture.css +1 -0
  259. package/src/client/capture.html +1 -0
  260. package/src/client/capture.js +37 -0
  261. package/src/client/capture.webmanifest +1 -0
  262. package/src/client/inbox-organize-bridge.js +22 -0
  263. package/src/client/index.js +4975 -0
  264. package/src/client/knowledge-ui.css +255 -0
  265. package/src/client/pdfjs/LICENSE +177 -0
  266. package/src/client/pdfjs/cmaps/78-EUC-H.bcmap +0 -0
  267. package/src/client/pdfjs/cmaps/78-EUC-V.bcmap +0 -0
  268. package/src/client/pdfjs/cmaps/78-H.bcmap +0 -0
  269. package/src/client/pdfjs/cmaps/78-RKSJ-H.bcmap +0 -0
  270. package/src/client/pdfjs/cmaps/78-RKSJ-V.bcmap +0 -0
  271. package/src/client/pdfjs/cmaps/78-V.bcmap +0 -0
  272. package/src/client/pdfjs/cmaps/78ms-RKSJ-H.bcmap +0 -0
  273. package/src/client/pdfjs/cmaps/78ms-RKSJ-V.bcmap +0 -0
  274. package/src/client/pdfjs/cmaps/83pv-RKSJ-H.bcmap +0 -0
  275. package/src/client/pdfjs/cmaps/90ms-RKSJ-H.bcmap +0 -0
  276. package/src/client/pdfjs/cmaps/90ms-RKSJ-V.bcmap +0 -0
  277. package/src/client/pdfjs/cmaps/90msp-RKSJ-H.bcmap +0 -0
  278. package/src/client/pdfjs/cmaps/90msp-RKSJ-V.bcmap +0 -0
  279. package/src/client/pdfjs/cmaps/90pv-RKSJ-H.bcmap +0 -0
  280. package/src/client/pdfjs/cmaps/90pv-RKSJ-V.bcmap +0 -0
  281. package/src/client/pdfjs/cmaps/Add-H.bcmap +0 -0
  282. package/src/client/pdfjs/cmaps/Add-RKSJ-H.bcmap +0 -0
  283. package/src/client/pdfjs/cmaps/Add-RKSJ-V.bcmap +0 -0
  284. package/src/client/pdfjs/cmaps/Add-V.bcmap +0 -0
  285. package/src/client/pdfjs/cmaps/Adobe-CNS1-0.bcmap +0 -0
  286. package/src/client/pdfjs/cmaps/Adobe-CNS1-1.bcmap +0 -0
  287. package/src/client/pdfjs/cmaps/Adobe-CNS1-2.bcmap +0 -0
  288. package/src/client/pdfjs/cmaps/Adobe-CNS1-3.bcmap +0 -0
  289. package/src/client/pdfjs/cmaps/Adobe-CNS1-4.bcmap +0 -0
  290. package/src/client/pdfjs/cmaps/Adobe-CNS1-5.bcmap +0 -0
  291. package/src/client/pdfjs/cmaps/Adobe-CNS1-6.bcmap +0 -0
  292. package/src/client/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
  293. package/src/client/pdfjs/cmaps/Adobe-GB1-0.bcmap +0 -0
  294. package/src/client/pdfjs/cmaps/Adobe-GB1-1.bcmap +0 -0
  295. package/src/client/pdfjs/cmaps/Adobe-GB1-2.bcmap +0 -0
  296. package/src/client/pdfjs/cmaps/Adobe-GB1-3.bcmap +0 -0
  297. package/src/client/pdfjs/cmaps/Adobe-GB1-4.bcmap +0 -0
  298. package/src/client/pdfjs/cmaps/Adobe-GB1-5.bcmap +0 -0
  299. package/src/client/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
  300. package/src/client/pdfjs/cmaps/Adobe-Japan1-0.bcmap +0 -0
  301. package/src/client/pdfjs/cmaps/Adobe-Japan1-1.bcmap +0 -0
  302. package/src/client/pdfjs/cmaps/Adobe-Japan1-2.bcmap +0 -0
  303. package/src/client/pdfjs/cmaps/Adobe-Japan1-3.bcmap +0 -0
  304. package/src/client/pdfjs/cmaps/Adobe-Japan1-4.bcmap +0 -0
  305. package/src/client/pdfjs/cmaps/Adobe-Japan1-5.bcmap +0 -0
  306. package/src/client/pdfjs/cmaps/Adobe-Japan1-6.bcmap +0 -0
  307. package/src/client/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
  308. package/src/client/pdfjs/cmaps/Adobe-Korea1-0.bcmap +0 -0
  309. package/src/client/pdfjs/cmaps/Adobe-Korea1-1.bcmap +0 -0
  310. package/src/client/pdfjs/cmaps/Adobe-Korea1-2.bcmap +0 -0
  311. package/src/client/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
  312. package/src/client/pdfjs/cmaps/B5-H.bcmap +0 -0
  313. package/src/client/pdfjs/cmaps/B5-V.bcmap +0 -0
  314. package/src/client/pdfjs/cmaps/B5pc-H.bcmap +0 -0
  315. package/src/client/pdfjs/cmaps/B5pc-V.bcmap +0 -0
  316. package/src/client/pdfjs/cmaps/CNS-EUC-H.bcmap +0 -0
  317. package/src/client/pdfjs/cmaps/CNS-EUC-V.bcmap +0 -0
  318. package/src/client/pdfjs/cmaps/CNS1-H.bcmap +0 -0
  319. package/src/client/pdfjs/cmaps/CNS1-V.bcmap +0 -0
  320. package/src/client/pdfjs/cmaps/CNS2-H.bcmap +0 -0
  321. package/src/client/pdfjs/cmaps/CNS2-V.bcmap +3 -0
  322. package/src/client/pdfjs/cmaps/ETHK-B5-H.bcmap +0 -0
  323. package/src/client/pdfjs/cmaps/ETHK-B5-V.bcmap +0 -0
  324. package/src/client/pdfjs/cmaps/ETen-B5-H.bcmap +0 -0
  325. package/src/client/pdfjs/cmaps/ETen-B5-V.bcmap +0 -0
  326. package/src/client/pdfjs/cmaps/ETenms-B5-H.bcmap +3 -0
  327. package/src/client/pdfjs/cmaps/ETenms-B5-V.bcmap +0 -0
  328. package/src/client/pdfjs/cmaps/EUC-H.bcmap +0 -0
  329. package/src/client/pdfjs/cmaps/EUC-V.bcmap +0 -0
  330. package/src/client/pdfjs/cmaps/Ext-H.bcmap +0 -0
  331. package/src/client/pdfjs/cmaps/Ext-RKSJ-H.bcmap +0 -0
  332. package/src/client/pdfjs/cmaps/Ext-RKSJ-V.bcmap +0 -0
  333. package/src/client/pdfjs/cmaps/Ext-V.bcmap +0 -0
  334. package/src/client/pdfjs/cmaps/GB-EUC-H.bcmap +0 -0
  335. package/src/client/pdfjs/cmaps/GB-EUC-V.bcmap +0 -0
  336. package/src/client/pdfjs/cmaps/GB-H.bcmap +4 -0
  337. package/src/client/pdfjs/cmaps/GB-V.bcmap +0 -0
  338. package/src/client/pdfjs/cmaps/GBK-EUC-H.bcmap +0 -0
  339. package/src/client/pdfjs/cmaps/GBK-EUC-V.bcmap +0 -0
  340. package/src/client/pdfjs/cmaps/GBK2K-H.bcmap +0 -0
  341. package/src/client/pdfjs/cmaps/GBK2K-V.bcmap +0 -0
  342. package/src/client/pdfjs/cmaps/GBKp-EUC-H.bcmap +0 -0
  343. package/src/client/pdfjs/cmaps/GBKp-EUC-V.bcmap +0 -0
  344. package/src/client/pdfjs/cmaps/GBT-EUC-H.bcmap +0 -0
  345. package/src/client/pdfjs/cmaps/GBT-EUC-V.bcmap +0 -0
  346. package/src/client/pdfjs/cmaps/GBT-H.bcmap +0 -0
  347. package/src/client/pdfjs/cmaps/GBT-V.bcmap +0 -0
  348. package/src/client/pdfjs/cmaps/GBTpc-EUC-H.bcmap +0 -0
  349. package/src/client/pdfjs/cmaps/GBTpc-EUC-V.bcmap +0 -0
  350. package/src/client/pdfjs/cmaps/GBpc-EUC-H.bcmap +0 -0
  351. package/src/client/pdfjs/cmaps/GBpc-EUC-V.bcmap +0 -0
  352. package/src/client/pdfjs/cmaps/H.bcmap +0 -0
  353. package/src/client/pdfjs/cmaps/HKdla-B5-H.bcmap +0 -0
  354. package/src/client/pdfjs/cmaps/HKdla-B5-V.bcmap +0 -0
  355. package/src/client/pdfjs/cmaps/HKdlb-B5-H.bcmap +0 -0
  356. package/src/client/pdfjs/cmaps/HKdlb-B5-V.bcmap +0 -0
  357. package/src/client/pdfjs/cmaps/HKgccs-B5-H.bcmap +0 -0
  358. package/src/client/pdfjs/cmaps/HKgccs-B5-V.bcmap +0 -0
  359. package/src/client/pdfjs/cmaps/HKm314-B5-H.bcmap +0 -0
  360. package/src/client/pdfjs/cmaps/HKm314-B5-V.bcmap +0 -0
  361. package/src/client/pdfjs/cmaps/HKm471-B5-H.bcmap +0 -0
  362. package/src/client/pdfjs/cmaps/HKm471-B5-V.bcmap +0 -0
  363. package/src/client/pdfjs/cmaps/HKscs-B5-H.bcmap +0 -0
  364. package/src/client/pdfjs/cmaps/HKscs-B5-V.bcmap +0 -0
  365. package/src/client/pdfjs/cmaps/Hankaku.bcmap +0 -0
  366. package/src/client/pdfjs/cmaps/Hiragana.bcmap +0 -0
  367. package/src/client/pdfjs/cmaps/KSC-EUC-H.bcmap +0 -0
  368. package/src/client/pdfjs/cmaps/KSC-EUC-V.bcmap +0 -0
  369. package/src/client/pdfjs/cmaps/KSC-H.bcmap +0 -0
  370. package/src/client/pdfjs/cmaps/KSC-Johab-H.bcmap +0 -0
  371. package/src/client/pdfjs/cmaps/KSC-Johab-V.bcmap +0 -0
  372. package/src/client/pdfjs/cmaps/KSC-V.bcmap +0 -0
  373. package/src/client/pdfjs/cmaps/KSCms-UHC-H.bcmap +0 -0
  374. package/src/client/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
  375. package/src/client/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
  376. package/src/client/pdfjs/cmaps/KSCms-UHC-V.bcmap +0 -0
  377. package/src/client/pdfjs/cmaps/KSCpc-EUC-H.bcmap +0 -0
  378. package/src/client/pdfjs/cmaps/KSCpc-EUC-V.bcmap +0 -0
  379. package/src/client/pdfjs/cmaps/Katakana.bcmap +0 -0
  380. package/src/client/pdfjs/cmaps/LICENSE +36 -0
  381. package/src/client/pdfjs/cmaps/NWP-H.bcmap +0 -0
  382. package/src/client/pdfjs/cmaps/NWP-V.bcmap +0 -0
  383. package/src/client/pdfjs/cmaps/RKSJ-H.bcmap +0 -0
  384. package/src/client/pdfjs/cmaps/RKSJ-V.bcmap +0 -0
  385. package/src/client/pdfjs/cmaps/Roman.bcmap +0 -0
  386. package/src/client/pdfjs/cmaps/UniCNS-UCS2-H.bcmap +0 -0
  387. package/src/client/pdfjs/cmaps/UniCNS-UCS2-V.bcmap +0 -0
  388. package/src/client/pdfjs/cmaps/UniCNS-UTF16-H.bcmap +0 -0
  389. package/src/client/pdfjs/cmaps/UniCNS-UTF16-V.bcmap +0 -0
  390. package/src/client/pdfjs/cmaps/UniCNS-UTF32-H.bcmap +0 -0
  391. package/src/client/pdfjs/cmaps/UniCNS-UTF32-V.bcmap +0 -0
  392. package/src/client/pdfjs/cmaps/UniCNS-UTF8-H.bcmap +0 -0
  393. package/src/client/pdfjs/cmaps/UniCNS-UTF8-V.bcmap +0 -0
  394. package/src/client/pdfjs/cmaps/UniGB-UCS2-H.bcmap +0 -0
  395. package/src/client/pdfjs/cmaps/UniGB-UCS2-V.bcmap +0 -0
  396. package/src/client/pdfjs/cmaps/UniGB-UTF16-H.bcmap +0 -0
  397. package/src/client/pdfjs/cmaps/UniGB-UTF16-V.bcmap +0 -0
  398. package/src/client/pdfjs/cmaps/UniGB-UTF32-H.bcmap +0 -0
  399. package/src/client/pdfjs/cmaps/UniGB-UTF32-V.bcmap +0 -0
  400. package/src/client/pdfjs/cmaps/UniGB-UTF8-H.bcmap +0 -0
  401. package/src/client/pdfjs/cmaps/UniGB-UTF8-V.bcmap +0 -0
  402. package/src/client/pdfjs/cmaps/UniJIS-UCS2-H.bcmap +0 -0
  403. package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
  404. package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
  405. package/src/client/pdfjs/cmaps/UniJIS-UCS2-V.bcmap +0 -0
  406. package/src/client/pdfjs/cmaps/UniJIS-UTF16-H.bcmap +0 -0
  407. package/src/client/pdfjs/cmaps/UniJIS-UTF16-V.bcmap +0 -0
  408. package/src/client/pdfjs/cmaps/UniJIS-UTF32-H.bcmap +0 -0
  409. package/src/client/pdfjs/cmaps/UniJIS-UTF32-V.bcmap +0 -0
  410. package/src/client/pdfjs/cmaps/UniJIS-UTF8-H.bcmap +0 -0
  411. package/src/client/pdfjs/cmaps/UniJIS-UTF8-V.bcmap +0 -0
  412. package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
  413. package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
  414. package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
  415. package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
  416. package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
  417. package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
  418. package/src/client/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
  419. package/src/client/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
  420. package/src/client/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
  421. package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
  422. package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
  423. package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
  424. package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
  425. package/src/client/pdfjs/cmaps/UniKS-UCS2-H.bcmap +0 -0
  426. package/src/client/pdfjs/cmaps/UniKS-UCS2-V.bcmap +0 -0
  427. package/src/client/pdfjs/cmaps/UniKS-UTF16-H.bcmap +0 -0
  428. package/src/client/pdfjs/cmaps/UniKS-UTF16-V.bcmap +0 -0
  429. package/src/client/pdfjs/cmaps/UniKS-UTF32-H.bcmap +0 -0
  430. package/src/client/pdfjs/cmaps/UniKS-UTF32-V.bcmap +0 -0
  431. package/src/client/pdfjs/cmaps/UniKS-UTF8-H.bcmap +0 -0
  432. package/src/client/pdfjs/cmaps/UniKS-UTF8-V.bcmap +0 -0
  433. package/src/client/pdfjs/cmaps/V.bcmap +0 -0
  434. package/src/client/pdfjs/cmaps/WP-Symbol.bcmap +0 -0
  435. package/src/client/pdfjs/pdf.mjs +26779 -0
  436. package/src/client/pdfjs/pdf.worker.mjs +63420 -0
  437. package/src/client/pdfjs/standard_fonts/FoxitDingbats.pfb +0 -0
  438. package/src/client/pdfjs/standard_fonts/FoxitFixed.pfb +0 -0
  439. package/src/client/pdfjs/standard_fonts/FoxitFixedBold.pfb +0 -0
  440. package/src/client/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
  441. package/src/client/pdfjs/standard_fonts/FoxitFixedItalic.pfb +0 -0
  442. package/src/client/pdfjs/standard_fonts/FoxitSerif.pfb +0 -0
  443. package/src/client/pdfjs/standard_fonts/FoxitSerifBold.pfb +0 -0
  444. package/src/client/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
  445. package/src/client/pdfjs/standard_fonts/FoxitSerifItalic.pfb +0 -0
  446. package/src/client/pdfjs/standard_fonts/FoxitSymbol.pfb +0 -0
  447. package/src/client/pdfjs/standard_fonts/LICENSE_FOXIT +27 -0
  448. package/src/client/pdfjs/standard_fonts/LICENSE_LIBERATION +102 -0
  449. package/src/client/pdfjs/standard_fonts/LiberationSans-Bold.ttf +0 -0
  450. package/src/client/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
  451. package/src/client/pdfjs/standard_fonts/LiberationSans-Italic.ttf +0 -0
  452. package/src/client/pdfjs/standard_fonts/LiberationSans-Regular.ttf +0 -0
  453. package/src/client/pdfjs/wasm/LICENSE_JBIG2 +196 -0
  454. package/src/client/pdfjs/wasm/LICENSE_OPENJPEG +39 -0
  455. package/src/client/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  456. package/src/client/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  457. package/src/client/pdfjs/wasm/LICENSE_PDFJS_QCMS +22 -0
  458. package/src/client/pdfjs/wasm/LICENSE_QCMS +21 -0
  459. package/src/client/pdfjs/wasm/jbig2.wasm +0 -0
  460. package/src/client/pdfjs/wasm/openjpeg.wasm +0 -0
  461. package/src/client/pdfjs/wasm/openjpeg_nowasm_fallback.js +17 -0
  462. package/src/client/pdfjs/wasm/qcms_bg.wasm +0 -0
  463. package/src/client/todo-lifecycle-ui.js +58 -0
  464. package/src/client/workbench-features.js +148 -0
  465. package/src/client/workbench-relations.js +86 -0
  466. package/src/client/workbench-theme.css +81 -0
  467. package/src/client/workbench-ui.js +1761 -0
  468. package/src/host/capture-surface.js +2 -0
  469. package/src/host/citation-guard.js +40 -0
  470. package/src/host/command-description.js +43 -0
  471. package/src/host/flow-workspace.js +62 -0
  472. package/src/host/flows.js +2 -0
  473. package/src/host/fsindex.js +2 -0
  474. package/src/host/gateway.js +916 -0
  475. package/src/host/import-service.js +2 -0
  476. package/src/host/importer.js +2 -0
  477. package/src/host/index-maintenance.js +2 -0
  478. package/src/host/index-policy-service.js +2 -0
  479. package/src/host/index-policy.js +2 -0
  480. package/src/host/index.js +2220 -0
  481. package/src/host/kbcore.js +2 -0
  482. package/src/host/managed-files.js +2 -0
  483. package/src/host/map.js +2 -0
  484. package/src/host/parse-credentials.js +2 -0
  485. package/src/host/parse-discovery.js +2 -0
  486. package/src/host/parse-native.js +2 -0
  487. package/src/host/parse-presets.js +2 -0
  488. package/src/host/parse-source-authority.js +2 -0
  489. package/src/host/parsing.js +7 -0
  490. package/src/host/relation-name-lookup.js +2 -0
  491. package/src/host/retrieval-api.js +2 -0
  492. package/src/host/retrieval-cache.js +2 -0
  493. package/src/host/retrieval-chunks.js +2 -0
  494. package/src/host/retrieval-pool.js +2 -0
  495. package/src/host/retrieval-worker.js +2 -0
  496. package/src/host/retrieval.js +2 -0
  497. package/src/host/runtime-resources.js +2 -0
  498. package/src/host/selftest.js +747 -0
  499. package/src/host/storage-io.js +2 -0
  500. package/src/host/system-upgrades.js +2 -0
  501. package/src/host/todo-lifecycle.js +66 -0
  502. package/src/host/updates.js +281 -0
  503. package/src/host/versioning.js +2 -0
  504. package/src/host/workbench-backup.js +2 -0
  505. package/src/host/workbench-deliverables.js +2 -0
  506. package/src/host/workbench-files.js +2 -0
  507. package/src/host/workbench-inbox.js +2 -0
  508. package/src/host/workbench-links.js +2 -0
  509. package/src/host/workbench-question.js +2 -0
  510. package/src/host/workbench-relation-index.js +2 -0
  511. package/src/host/workbench-state.js +2 -0
  512. package/src/host/workbench-trash.js +2 -0
  513. package/src/host/workbench.js +5 -0
  514. package/tools/kb-local-model.py +141 -0
  515. package/tools/kb-pdf-pages.py +78 -0
  516. package/tools/kb-transactional-update.py +292 -0
@@ -0,0 +1,2519 @@
1
+ import { isDeepStrictEqual } from 'node:util'
2
+ import { assertServiceOwner } from './service-ownership.js'
3
+ // 知识库核心逻辑(P0.1:按验收意见 A–D 修复,E/F/G 中可顺手处理的一并修)
4
+ // 只依赖 node 内置模块,不 import @deepseek-ai/*。
5
+ //
6
+ // 相对 0.1.0-p0 的关键变化:
7
+ // A. init 成为公开可调用动作(bind 预览 + 确认初始化),不再只能靠自检钩子
8
+ // B. 每个返回值都带"业务结论",供自检断言;不再有"没抛异常就算通过"的空间
9
+ // C. 配置损坏 ≠ 文件不存在:损坏时**不播种、不换库**,明确报 degraded 并给恢复入口;
10
+ // 初始化有完成状态,半成品重试补齐,半成品不得报 healthy
11
+ // D. update 强制 expectedRevision(两层都校验);索引路径进文件操作前做边界校验
12
+ // E. 同库写入走进程内互斥;临时文件名带随机;索引失败返回部分完成而不是普通成功
13
+ // F. 索引缺失/损坏时检索走**磁盘发现兜底**,并明确说"是兜底";check 先取旧快照再比差异
14
+ // G. frontmatter 的 tags 用带引号的 flow 序列,含逗号的标签不被拆开;未知字段保留
15
+ import crypto from 'node:crypto'
16
+ import os from 'node:os'
17
+ import { constants, existsSync } from 'node:fs'
18
+ import { access, appendFile, lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
19
+ import path from 'node:path'
20
+ import { atomicJsonStream, fileFingerprint } from './storage-io.js'
21
+ import { createByteCache } from './retrieval-cache.js'
22
+ import { policyExcludes, readIndexPolicy, policyExcluded, excludedSource, EXCLUDED_PARTITION, registerDerived, resolveAssetPath } from './index-policy.js'
23
+ import { readImportSources, derivedPrivatePartitions, effectivePrivateDirs, foldGeneratedPairs } from './fsindex.js'
24
+ import { sourceReferences, reconcileImportedSources, SOURCE_TEXT } from './source-references.js'
25
+ import {catalogActive,readCatalog,refreshCatalog,classifyOriginal} from './file-catalog.js'
26
+ import { CLASSIFICATION_VERSION } from './file-classification.js'
27
+
28
+ // 版本单一来源:package.json 的 version 必须与此一致(详见 INSTALL 说明)
29
+ export const VERSION = '3.1.5'
30
+
31
+ export const REQUIRED_FIELDS = ['title', 'type', 'tags', 'status', 'updated']
32
+ export const SCHEMA_VERSION = 1
33
+
34
+ const KIND_TO_CATEGORY = {
35
+ 知识: '20-知识笔记',
36
+ 项目: '10-项目',
37
+ 人物: '30-人物关系',
38
+ 素材: '40-素材资源',
39
+ 画像: '00-画像',
40
+ }
41
+
42
+ export const TEMPLATES = {
43
+ '知识条目.md': '# 标题\n\n> 一句话结论。\n\n## 正文\n\n',
44
+ '项目条目.md': '# 项目名\n\n> 目标与当前状态。\n\n## 进展\n\n',
45
+ '素材条目.md': '# 素材名\n\n> 是什么、能干什么。\n\n## 用法\n\n',
46
+ }
47
+
48
+ // 这些目录**不是知识条目**,任何情况下都不进索引(配置只能加、不能去掉)。
49
+ const DEFAULT_EXCLUDES = ['_模板', '_手册', '.kbmeta', '.kb-state', '50-底稿']
50
+
51
+ const nowIso = () => new Date().toISOString()
52
+ const today = () => nowIso().slice(0, 10)
53
+ /**
54
+ * 按指定时区取「日期」(YYYY-MM-DD)。时区非法时退回 UTC 日期并在日志里留一句,
55
+ * 绝不因为一个时区串写错就拒绝写入。
56
+ */
57
+ function dateInTz(iso, tz) {
58
+ try {
59
+ return new Intl.DateTimeFormat('sv-SE', { timeZone: tz, dateStyle: 'short' }).format(new Date(iso))
60
+ } catch {
61
+ return String(iso).slice(0, 10)
62
+ }
63
+ }
64
+
65
+ function sha12(buf) {
66
+ return crypto.createHash('sha256').update(buf).digest('hex').slice(0, 12)
67
+ }
68
+ function sha256(buf) {
69
+ return crypto.createHash('sha256').update(buf).digest('hex')
70
+ }
71
+ function toPosix(p) {
72
+ return String(p).replace(/\\/g, '/')
73
+ }
74
+ const normAbs = (p) => toPosix(path.resolve(String(p ?? ''))).toLowerCase()
75
+ function slugOf(title) {
76
+ const s = String(title)
77
+ .replace(/[\\/:*?"<>|\r\n\t]/g, '')
78
+ .replace(/\s+/g, '-')
79
+ .trim()
80
+ return s.slice(0, 40) || 'untitled'
81
+ }
82
+
83
+ // ── R3:frontmatter 采用「受限 YAML 子集 + 写前拒绝」───────────────
84
+ // 原则:**能无损识别的才允许写回**。缩进/嵌套映射、嵌套列表、块标量(| >)、
85
+ // 流式映射({...})、注释行、重复键、未闭合的 [...] 一律标 unsupported ——
86
+ // updateEntry 见到它直接拒绝写盘(unsupported-frontmatter),绝不静默改坏数据。
87
+ // 能无损处理的:顶层 `key: 标量`(引号原样解析)、`key: [a, b]`(含转义与引号)。
88
+
89
+ const UNSUPPORTED = {
90
+ indent: 'frontmatter 含缩进/嵌套结构(本版不支持写回)',
91
+ comment: 'frontmatter 含注释行(本版不支持写回)',
92
+ sequence: 'frontmatter 含列表项(本版不支持写回)',
93
+ block: 'frontmatter 含块标量(本版不支持写回)',
94
+ flowMap: 'frontmatter 含流式映射(本版不支持写回)',
95
+ duplicate: 'frontmatter 含重复键(本版不支持写回)',
96
+ unclosed: 'frontmatter 的 [...] 未闭合(本版不支持写回)',
97
+ multiline: 'frontmatter 含多行或嵌套结构(本版不支持写回)',
98
+ }
99
+
100
+ /** 双引号内转义:只认 \n \r \t \" \\;其它未知转义**保留反斜杠**(宁可保守,不吞字符) */
101
+ function unescapeDouble(s) {
102
+ let out = ''
103
+ for (let i = 0; i < s.length; i += 1) {
104
+ const ch = s[i]
105
+ if (ch !== '\\' || i + 1 >= s.length) {
106
+ out += ch
107
+ continue
108
+ }
109
+ const n = s[i + 1]
110
+ if (n === 'n') { out += '\n'; i += 1 }
111
+ else if (n === 'r') { out += '\r'; i += 1 }
112
+ else if (n === 't') { out += '\t'; i += 1 }
113
+ else if (n === '"') { out += '"'; i += 1 }
114
+ else if (n === '\\') { out += '\\'; i += 1 }
115
+ else out += ch
116
+ }
117
+ return out
118
+ }
119
+
120
+ function unquoteScalar(rawIn) {
121
+ const s = String(rawIn ?? '').trim()
122
+ if (s === '' || s === '~' || s === 'null') return ''
123
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) return unescapeDouble(s.slice(1, -1))
124
+ if (s.length >= 2 && s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1).replace(/''/g, "'")
125
+ return s
126
+ }
127
+
128
+ /** 行内 flow 序列:引号内的逗号不拆;返回 closed=false 表示引号未闭合 */
129
+ function parseFlowSeq(inner) {
130
+ const parts = []
131
+ let buf = ''
132
+ let quote = null
133
+ for (let i = 0; i < inner.length; i += 1) {
134
+ const ch = inner[i]
135
+ if (quote !== null) {
136
+ if (quote === '"' && ch === '\\' && i + 1 < inner.length) { buf += ch + inner[i + 1]; i += 1; continue }
137
+ if (quote === "'" && ch === "'" && inner[i + 1] === "'") { buf += "''"; i += 1; continue }
138
+ if (ch === quote) { quote = null; buf += ch; continue }
139
+ buf += ch
140
+ continue
141
+ }
142
+ if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue }
143
+ if (ch === ',') { parts.push(buf.trim()); buf = ''; continue }
144
+ buf += ch
145
+ }
146
+ parts.push(buf.trim())
147
+ return { values: parts.filter((x) => x !== '').map(unquoteScalar), closed: quote === null }
148
+ }
149
+
150
+ /** 解析 frontmatter 区块(不含 --- 定界行);不支持的语法只打标,不抛异常 */
151
+ function parseHeaderBlock(headerRaw) {
152
+ const data = {}
153
+ const lines = []
154
+ const seen = new Set()
155
+ let unsupported = null
156
+ const mark = (why) => { if (unsupported === null) unsupported = why }
157
+ for (const rawLine of String(headerRaw ?? '').split('\n')) {
158
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
159
+ if (line.trim() === '') continue
160
+ if (/^[ \t]/.test(line)) { mark(UNSUPPORTED.indent); continue }
161
+ const trimmed = line.trim()
162
+ if (trimmed.startsWith('#')) { mark(UNSUPPORTED.comment); continue }
163
+ if (/^-(\s|$)/.test(trimmed)) { mark(UNSUPPORTED.sequence); continue }
164
+ const m = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(trimmed)
165
+ if (!m) { mark(UNSUPPORTED.multiline); continue }
166
+ const key = m[1]
167
+ const rest = m[2].trim()
168
+ if (seen.has(key)) { mark(UNSUPPORTED.duplicate); continue }
169
+ seen.add(key)
170
+ lines.push({ key, raw: line })
171
+ if (/^[|>]/.test(rest)) { mark(UNSUPPORTED.block); data[key] = rest; continue }
172
+ if (/^\{/.test(rest)) { mark(UNSUPPORTED.flowMap); data[key] = rest; continue }
173
+ if (rest.startsWith('[')) {
174
+ if (!rest.endsWith(']')) { mark(UNSUPPORTED.unclosed); data[key] = rest; continue }
175
+ const seq = parseFlowSeq(rest.slice(1, -1))
176
+ if (!seq.closed) mark(UNSUPPORTED.unclosed)
177
+ data[key] = seq.values
178
+ continue
179
+ }
180
+ data[key] = unquoteScalar(rest)
181
+ }
182
+ return { data, lines, unsupported }
183
+ }
184
+
185
+ /**
186
+ * 切出 frontmatter 的三个区间。bodyRaw **保留原文**(含分隔空行与行尾),
187
+ * 供 rewriteFrontmatter 做字节级拼回 —— 这是「只改元数据时正文逐字不变」的基础。
188
+ */
189
+ function splitFrontmatter(text) {
190
+ if (typeof text !== 'string' || !text.startsWith('---')) return { ok: false, reason: 'no-frontmatter' }
191
+ const firstNl = text.indexOf('\n')
192
+ if (firstNl < 0) return { ok: false, reason: 'frontmatter 未闭合' }
193
+ let cursor = firstNl + 1
194
+ let closeStart = -1
195
+ let closeEnd = -1
196
+ while (cursor <= text.length) {
197
+ const nl = text.indexOf('\n', cursor)
198
+ const lineEnd = nl < 0 ? text.length : nl
199
+ let line = text.slice(cursor, lineEnd)
200
+ if (line.endsWith('\r')) line = line.slice(0, -1)
201
+ if (line === '---' || line === '...') {
202
+ closeStart = cursor
203
+ closeEnd = nl < 0 ? text.length : nl + 1
204
+ break
205
+ }
206
+ if (nl < 0) break
207
+ cursor = nl + 1
208
+ }
209
+ if (closeStart < 0) return { ok: false, reason: 'frontmatter 未闭合' }
210
+ return {
211
+ ok: true,
212
+ openLine: text.slice(0, firstNl + 1),
213
+ headerRaw: text.slice(firstNl + 1, closeStart),
214
+ closeLine: text.slice(closeStart, closeEnd),
215
+ bodyRaw: text.slice(closeEnd),
216
+ }
217
+ }
218
+
219
+ /** 解析 frontmatter:返回 data / body / raw / valid / unsupported */
220
+ export function parseFrontmatter(text) {
221
+ const parts = splitFrontmatter(text)
222
+ if (!parts.ok) {
223
+ if (parts.reason === 'no-frontmatter') return { data: {}, body: text, raw: '', valid: true, unsupported: null }
224
+ return { data: {}, body: text, raw: '', valid: false, reason: parts.reason, unsupported: null }
225
+ }
226
+ const parsed = parseHeaderBlock(parts.headerRaw)
227
+ const sep = /^\r?\n/.exec(parts.bodyRaw)
228
+ return {
229
+ data: parsed.data,
230
+ body: sep ? parts.bodyRaw.slice(sep[0].length) : parts.bodyRaw,
231
+ raw: parts.headerRaw,
232
+ valid: true,
233
+ unsupported: parsed.unsupported,
234
+ parts,
235
+ }
236
+ }
237
+
238
+ /** 序列化:含逗号/引号/换行的标签加引号,避免被拆开(G);未知字段保留 */
239
+ /** 探测文本主导换行符,写回时保留(P1-E:不能静默把 CRLF 改成 LF) */
240
+ export function detectEol(text) {
241
+ if (typeof text !== 'string' || text === '') return '\n'
242
+ const crlf = (text.match(/\r\n/g) || []).length
243
+ const lf = (text.match(/\n/g) || []).length
244
+ return crlf > 0 && crlf * 2 >= lf ? '\r\n' : '\n'
245
+ }
246
+
247
+ export const ALLOWED_TYPES = ['知识', '项目', '人物', '素材', '画像', '索引', '会议', '复盘']
248
+
249
+ /**
250
+ * 库**根目录**的导航/说明文件:不是条目,不参与索引与缺陷检查。
251
+ * 与库自己的 `.kb/kb-check.ps1` 的 `$NavFiles` 对齐(2026-10-17)。
252
+ * 只对根目录生效 —— 子目录里的同名文件(如 10-项目/每日信息/README.md)仍是条目。
253
+ */
254
+ export const ROOT_NAV_FILES = new Set(['AGENTS.md', 'README.md', 'INDEX.md', '知识库清单.md'])
255
+
256
+ /**
257
+ * 派生稳定 id(2026-10-17)——frontmatter 没写 `id` 时,用**库内相对路径**派生身份。
258
+ *
259
+ * 动机:本库的写入者不止本产品一个(人工编辑、其他 Agent 都按 AGENTS.md 只写
260
+ * title/type/tags/status/updated,从不写 id)。若把 `id` 定为必填,任何一次非产品写入
261
+ * 都会变成永久的 noId 缺陷;而 path 本来就是本产品全链路的主键(索引按 path、diff 按 path)。
262
+ *
263
+ * 取舍:**改名会换身份**。本库条目名是 `YYYY-MM-DD-*`,改名极少(改名需先问主人)。
264
+ * 显式写了 `id` 的条目仍以显式 id 为准(create 生成的 `kb-xxxxxxxx`)。
265
+ */
266
+ export function derivedEntryId(relPath) {
267
+ return 'p-' + crypto.createHash('sha1').update(String(relPath).replace(/\\/g, '/'), 'utf8').digest('hex').slice(0, 12)
268
+ }
269
+
270
+ /**
271
+ * ⚠️ R1 起**不再用于检索预筛**(旧实现用它做"排除",会漏掉 `implement`/`pha`/单字「库」这类查询)。
272
+ * 现在检索直接在索引条目的 `text` 上做 includes;本函数仅为兼容旧调用方保留导出,
273
+ * 新代码请不要用它过滤结果集。
274
+ */
275
+ export function tokenizeForIndex(text) {
276
+ const out = new Set()
277
+ const lower = String(text ?? '').toLowerCase()
278
+ for (const m of lower.matchAll(/[a-z0-9_]{2,}/g)) out.add(m[0])
279
+ for (const m of lower.matchAll(/[\u4e00-\u9fff]+/g)) {
280
+ const s = m[0]
281
+ if (s.length === 1) out.add(s)
282
+ for (let i = 0; i + 1 < s.length; i += 1) out.add(s.slice(i, i + 2))
283
+ }
284
+ return [...out]
285
+ }
286
+
287
+ // 需要引号的字符:YAML 里会改变含义的那些(逗号/冒号/井号/括号/引号/反斜杠/换行…)
288
+ const QUOTE_TRIGGER = /[,:#\[\]{}&*!|>'"%@`\r\n\t\\]/
289
+ const FIELD_ORDER = ['id', 'title', 'type', 'tags', 'status', 'created', 'updated', 'source', 'see_also']
290
+
291
+ function needsQuote(s) {
292
+ if (s === '') return true
293
+ if (/^\s|\s$/.test(s)) return true
294
+ if (QUOTE_TRIGGER.test(s)) return true
295
+ if (/^[-?]/.test(s)) return true
296
+ if (/^(true|false|null|yes|no|on|off|~)$/i.test(s)) return true
297
+ if (/^-?\d+(\.\d+)?$/.test(s)) return true
298
+ return false
299
+ }
300
+
301
+ /** 标量序列化:必要时按 YAML 双引号规则转义(`\` → `\\`、`"` → `\"`、换行 → `\n`) */
302
+ function quoteScalar(v) {
303
+ const s = String(v)
304
+ if (!needsQuote(s)) return s
305
+ return '"' + s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"'
306
+ }
307
+
308
+ function formatValue(v) {
309
+ if (Array.isArray(v)) return `[${v.map((x) => quoteScalar(x)).join(', ')}]`
310
+ return quoteScalar(v)
311
+ }
312
+
313
+ function presentKeys(data) {
314
+ const has = (k) => data[k] !== undefined && data[k] !== ''
315
+ return [...FIELD_ORDER.filter(has), ...Object.keys(data).filter((k) => !FIELD_ORDER.includes(k) && has(k))]
316
+ }
317
+
318
+ /** 按原始行尾切开(保留每行自己的 \r\n / \n),供「未改动的行按原字节保留」 */
319
+ function splitLinesKeepEol(text) {
320
+ const out = []
321
+ let i = 0
322
+ while (i < text.length) {
323
+ const nl = text.indexOf('\n', i)
324
+ if (nl < 0) {
325
+ out.push({ text: text.slice(i), eol: '' })
326
+ break
327
+ }
328
+ const raw = text.slice(i, nl)
329
+ if (raw.endsWith('\r')) out.push({ text: raw.slice(0, -1), eol: '\r\n' })
330
+ else out.push({ text: raw, eol: '\n' })
331
+ i = nl + 1
332
+ }
333
+ return out
334
+ }
335
+
336
+ /**
337
+ * 只重建 frontmatter 区块:**未改动的行按原字节(含各自行尾)保留**,
338
+ * 数据里已不存在的键删除,新键追加在末尾。正文由调用方原样拼回。
339
+ */
340
+ function rewriteHeader(parts, data) {
341
+ const keys = presentKeys(data)
342
+ const keySet = new Set(keys)
343
+ const lines = splitLinesKeepEol(parts.headerRaw)
344
+ const originalKeys = new Set()
345
+ const out = []
346
+ for (const { text, eol } of lines) {
347
+ const m = /^([A-Za-z_][\w-]*)\s*:/.exec(text)
348
+ if (!m) {
349
+ out.push(text + eol) // 空行等原样保留
350
+ continue
351
+ }
352
+ const key = m[1]
353
+ originalKeys.add(key)
354
+ if (!keySet.has(key)) continue
355
+ out.push(`${key}: ${formatValue(data[key])}${eol}`)
356
+ }
357
+ const appended = keys.filter((k) => !originalKeys.has(k))
358
+ if (appended.length > 0) {
359
+ const nl = parts.closeLine.endsWith('\r\n') ? '\r\n' : '\n'
360
+ if (out.length > 0 && !out[out.length - 1].endsWith('\n')) out[out.length - 1] += nl
361
+ for (const key of appended) out.push(`${key}: ${formatValue(data[key])}${nl}`)
362
+ }
363
+ return out.join('')
364
+ }
365
+
366
+ export function buildFile(data, body, eol = '\n') {
367
+ const keys = presentKeys(data)
368
+ const lines = keys.map((k) => `${k}: ${formatValue(data[k])}`)
369
+ // 正文也按目标 EOL 归一:CRLF 文件里正文若仍是 LF,就不是"无损"
370
+ const normalizedBody = String(body ?? '').split('\r\n').join('\n').split('\n').join(eol)
371
+ return `---${eol}${lines.join(eol)}${eol}---${eol}${eol}${normalizedBody}`
372
+ }
373
+
374
+ /**
375
+ * 字节级拼回:只替换 frontmatter 区块,正文按原始字节(parts.bodyRaw)保留。
376
+ * content 有变时正文按文件主导 EOL 归一后替换。
377
+ */
378
+ function composeWithHeader(parts, data, contentText) {
379
+ const header = rewriteHeader(parts, data)
380
+ let bodyRaw = parts.bodyRaw
381
+ if (typeof contentText === 'string') {
382
+ const eol = parts.closeLine.endsWith('\r\n') ? '\r\n' : '\n'
383
+ bodyRaw = eol + String(contentText).trimEnd().split('\r\n').join('\n').split('\n').join(eol) + eol
384
+ }
385
+ return parts.openLine + header + parts.closeLine + bodyRaw
386
+ }
387
+
388
+ function isInside(root, candidate) {
389
+ const rel = path.relative(path.resolve(root), path.resolve(candidate))
390
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
391
+ }
392
+
393
+ /** 真实路径:解析失败返回 null(不存在/无权限) */
394
+ export async function realOf(p) {
395
+ try {
396
+ return await realpath(p)
397
+ } catch {
398
+ return null
399
+ }
400
+ }
401
+
402
+ /** 两个真实路径的包含判断(大小写不敏感,Windows) */
403
+ export function insideReal(realRoot, candidate) {
404
+ if (!realRoot || !candidate) return false
405
+ const norm = (s) => s.replace(/\\/g, '/').toLowerCase()
406
+ const r = norm(realRoot)
407
+ const c = norm(candidate)
408
+ return c === r || c.startsWith(r.endsWith('/') ? r : r + '/')
409
+ }
410
+
411
+ /**
412
+ * P1-A 真实路径边界校验。
413
+ * 返回值:{ ok:true, realRoot } 或 { ok:false, reason, detail }
414
+ * reason: path-escape(字符串层面越界)/ path-reparse(库内链接,默认拒绝)
415
+ * / path-reparse-escape(链接指向库外)/ root-missing
416
+ */
417
+ export async function checkRealPath(root, candidate, opts = {}) {
418
+ const followLinks = opts.followLinks === true
419
+ const realRoot = await realOf(root)
420
+ if (realRoot === null) return { ok: false, reason: 'root-missing', detail: String(root) }
421
+ const absRoot = path.resolve(root)
422
+ const absCandidate = path.resolve(candidate)
423
+ if (!isInside(absRoot, absCandidate)) {
424
+ return { ok: false, reason: 'path-escape', detail: String(candidate) }
425
+ }
426
+ const rel = path.relative(absRoot, absCandidate)
427
+ const parts = rel.split(path.sep).filter(Boolean)
428
+ let cur = absRoot
429
+ for (const part of parts) {
430
+ cur = path.join(cur, part)
431
+ const st = await lstat(cur).catch(() => null)
432
+ if (st === null) break // 之后都不存在,由调用方按“新建”处理
433
+ if (st.isSymbolicLink()) {
434
+ const real = await realOf(cur)
435
+ if (!real || !insideReal(realRoot, real)) {
436
+ return { ok: false, reason: 'path-reparse-escape', detail: `${toPosix(path.relative(absRoot, cur))} → ${toPosix(real ?? '(无法解析)')}` }
437
+ }
438
+ if (!followLinks) {
439
+ return { ok: false, reason: 'path-reparse', detail: `${toPosix(path.relative(absRoot, cur))} 是链接/重解析点(默认拒绝;followLinks=true 可允许指向库内)` }
440
+ }
441
+ }
442
+ }
443
+ // 目标若已存在,再用真实路径核一次(防"中间没问题、末段是链接")
444
+ const realTarget = await realOf(absCandidate)
445
+ if (realTarget !== null && !insideReal(realRoot, realTarget)) {
446
+ return { ok: false, reason: 'path-reparse-escape', detail: `${toPosix(path.relative(absRoot, absCandidate))} → ${toPosix(realTarget)}` }
447
+ }
448
+ return { ok: true, realRoot, detail: '' }
449
+ }
450
+
451
+ export function createCore(cfg, logger) {
452
+ const log = logger ?? (() => {})
453
+ const stateDir = path.resolve(cfg.stateDir)
454
+ const configFile = path.join(stateDir, 'config.json')
455
+ const bindingFile = path.join(stateDir, 'binding.json')
456
+ const logFile = path.join(stateDir, 'kb.log')
457
+
458
+ let config = null
459
+ let configHealth = { ok: true, state: 'unloaded', detail: '' }
460
+ const locks = new Map()
461
+ const indexCache = createByteCache({ maxBytes: 64 * 1024 * 1024, maxEntries: 4, sizeOf: v => v.bytes * 4 + 512 })
462
+ const indexPending = new Map(), diskPending = new Map(), validPayloads = new WeakSet()
463
+ const ioMetrics = { indexReads: 0, indexCacheHits: 0, indexValidations: 0, indexCommits: 0, diskScans: 0, diskMerged: 0 }
464
+ async function readIndexState(file) {
465
+ try {
466
+ const before = await stat(file, { bigint: true }), fingerprint = fileFingerprint(before)
467
+ const old = indexCache.get(file)
468
+ if (old?.fingerprint === fingerprint) { ioMetrics.indexCacheHits++; return old.result }
469
+ const key = file + '\0' + fingerprint
470
+ if (indexPending.has(key)) return indexPending.get(key)
471
+ const pending = (async () => {
472
+ ioMetrics.indexReads++
473
+ const result = await readJsonState(file), after = await stat(file, { bigint: true })
474
+ if (fingerprint !== fileFingerprint(after)) return { state: 'unreadable', error: '索引在读取期间改变,请重试' }
475
+ if (result.state === 'ok') {
476
+ const compact = { state: result.state, value: result.value }
477
+ indexCache.set(file, { fingerprint, result: compact, bytes: Number(after.size) })
478
+ return compact
479
+ }
480
+ indexCache.delete(file); return result
481
+ })().finally(() => indexPending.delete(key))
482
+ indexPending.set(key, pending); return pending
483
+ } catch (error) {
484
+ indexCache.delete(file)
485
+ return { state: error.code === 'ENOENT' ? 'missing' : 'unreadable', error: String(error.code || error.message) }
486
+ }
487
+ }
488
+ async function commitIndex(file, payload) {
489
+ await atomicJsonStream(file, payload)
490
+ indexCache.delete(file); ioMetrics.indexCommits++
491
+ }
492
+
493
+ async function writeLog(level, message) {
494
+ try {
495
+ await appendFile(logFile, `${nowIso()}\t${level}\t${message}\n`, 'utf8')
496
+ } catch {
497
+ /* 日志失败不影响主流程 */
498
+ }
499
+ log(level, message)
500
+ }
501
+
502
+ function withLock(key, fn) {
503
+ const prev = locks.get(key) ?? Promise.resolve()
504
+ const next = prev.then(fn, fn)
505
+ locks.set(
506
+ key,
507
+ next.then(
508
+ () => undefined,
509
+ () => undefined,
510
+ ),
511
+ )
512
+ return next
513
+ }
514
+
515
+ async function atomicWrite(file, text) {
516
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`
517
+ await writeFile(tmp, text, 'utf8')
518
+ // Windows 上 rename 偶发 EPERM/EBUSY(杀软/索引服务持句柄):短退避重试,别让一次抖动毁掉一次写入
519
+ let lastError = null
520
+ for (let i = 0; i < 6; i += 1) {
521
+ try {
522
+ await rename(tmp, file)
523
+ return
524
+ } catch (error) {
525
+ lastError = error
526
+ const code = String((error && error.code) ?? '')
527
+ if (!['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(code)) throw error
528
+ await new Promise((r) => setTimeout(r, 20 * 2 ** i))
529
+ }
530
+ }
531
+ throw lastError
532
+ }
533
+
534
+ async function readJsonState(file) {
535
+ try {
536
+ const raw = await readFile(file, 'utf8')
537
+ try {
538
+ return { state: 'ok', value: JSON.parse(raw), raw }
539
+ } catch (error) {
540
+ return { state: 'corrupt', error: String(error.message ?? error), raw }
541
+ }
542
+ } catch (error) {
543
+ if (error && error.code === 'ENOENT') return { state: 'missing' }
544
+ return { state: 'unreadable', error: String((error && (error.code || error.message)) ?? error) }
545
+ }
546
+ }
547
+
548
+ // ── 配置(C:损坏不覆盖、不换库)──────────────────────────────────
549
+ /** R3:私密目录白名单校验(只接受库内相对路径;绝对路径/.. 一律拒绝) */
550
+ function sanitizePrivateDirs(list) {
551
+ if (!Array.isArray(list)) return { ok: false, reason: 'privateDirs 必须是数组' }
552
+ const out = []
553
+ for (const raw of list) {
554
+ if (typeof raw !== 'string') return { ok: false, reason: 'privateDirs 里必须都是字符串' }
555
+ const posix = toPosix(raw.trim())
556
+ if (posix === '' || posix.startsWith('/') || /^[a-zA-Z]:/.test(posix)) return { ok: false, reason: `私密目录必须是库内相对路径:${raw}` }
557
+ const segs = posix.split('/').filter((s) => s !== '' && s !== '.')
558
+ if (segs.length === 0 || segs.some((s) => s === '..')) return { ok: false, reason: `私密目录不得越界:${raw}` }
559
+ out.push(segs.join('/'))
560
+ }
561
+ return { ok: true, value: [...new Set(out)] }
562
+ }
563
+
564
+ /** 只接受库内相对路径或空串;空串保持空串(R6:不能再被 path.resolve 变成 cwd) */
565
+ function normKbPath(raw) {
566
+ const s = typeof raw === 'string' ? raw.trim() : ''
567
+ return s === '' ? '' : toPosix(path.resolve(s))
568
+ }
569
+
570
+ function seededPrivateDirs(raw) {
571
+ const s = sanitizePrivateDirs(raw)
572
+ return s.ok ? s.value : null
573
+ }
574
+
575
+ async function loadConfig() {
576
+ await mkdir(stateDir, { recursive: true })
577
+ const disk = await readJsonState(configFile)
578
+ if (disk.state === 'ok') {
579
+ if (disk.value.schemaVersion !== SCHEMA_VERSION) {
580
+ // C2:以前这里只设 configHealth.ok=false,返回对象没有 degraded,
581
+ // 而 bind/init 只看 conf.degraded → 于是"先建库、后报错"。统一带上 degraded。
582
+ config = { ...disk.value, degraded: true }
583
+ // R3:旧配置(p3 及更早)没有 privateDirs 字段 → 用插件配置兜底(内存态,不回写)
584
+ if (!Array.isArray(config.privateDirs)) {
585
+ const seeded = seededPrivateDirs(cfg.privateDirs)
586
+ if (seeded !== null) config.privateDirs = seeded
587
+ }
588
+ configHealth = {
589
+ ok: false,
590
+ state: 'unsupported-schema',
591
+ detail: `config.json 的 schemaVersion=${disk.value.schemaVersion},本版支持 ${SCHEMA_VERSION};未改动原文件`,
592
+ recovery: '备份后可删除 config.json 让程序重新播种,或等产品提供迁移工具',
593
+ }
594
+ await writeLog('warn', `配置 schema 不支持:${configHealth.detail}`)
595
+ return config
596
+ }
597
+ config = disk.value
598
+ // R3:旧配置没有 privateDirs → 用插件配置兜底(内存态;下次 setConfig 才落盘)
599
+ if (!Array.isArray(config.privateDirs)) {
600
+ const seeded = seededPrivateDirs(cfg.privateDirs)
601
+ if (seeded !== null) config.privateDirs = seeded
602
+ }
603
+ configHealth = { ok: true, state: 'loaded', detail: '' }
604
+ await writeLog('info', `配置从磁盘载入 revision=${config.revision ?? '-'} kbPath=${config.kbPath}`)
605
+ return config
606
+ }
607
+ if (disk.state === 'corrupt' || disk.state === 'unreadable') {
608
+ configHealth = {
609
+ ok: false,
610
+ state: disk.state === 'corrupt' ? 'corrupt' : 'unreadable',
611
+ detail:
612
+ disk.state === 'corrupt'
613
+ ? `config.json 不是合法 JSON(${disk.error});文件已保留、未覆盖`
614
+ : `config.json 读失败(${disk.error});文件已保留`,
615
+ recovery: `检查 ${toPosix(configFile)};修好或改名备份后重启,程序才会重新播种。原文件未动。`,
616
+ }
617
+ config = {
618
+ schemaVersion: SCHEMA_VERSION,
619
+ revision: null,
620
+ kbPath: normKbPath(cfg.kbPath),
621
+ categories: cfg.categories ?? Object.values(KIND_TO_CATEGORY),
622
+ excludeFromSearch: cfg.excludeFromSearch ?? [],
623
+ followLinks: cfg.followLinks === true,
624
+ privateDirs: seededPrivateDirs(cfg.privateDirs),
625
+ seededFrom: 'cordis.config(只读占位,未落盘)',
626
+ degraded: true,
627
+ }
628
+ await writeLog('warn', `配置降级:${configHealth.detail}`)
629
+ return config
630
+ }
631
+ config = {
632
+ schemaVersion: SCHEMA_VERSION,
633
+ revision: 1,
634
+ kbPath: normKbPath(cfg.kbPath),
635
+ categories: cfg.categories ?? Object.values(KIND_TO_CATEGORY),
636
+ excludeFromSearch: cfg.excludeFromSearch ?? [],
637
+ followLinks: cfg.followLinks === true,
638
+ // R3:privateDirs 必须进配置 schema 并落盘(以前只从插件配置读、没播种 → API 回退默认两分区)
639
+ privateDirs: seededPrivateDirs(cfg.privateDirs),
640
+ seededFrom: 'cordis.config',
641
+ updatedAt: nowIso(),
642
+ }
643
+ await atomicWrite(configFile, JSON.stringify(config, null, 2))
644
+ configHealth = { ok: true, state: 'seeded', detail: '首次播种(原文件不存在)' }
645
+ await writeLog('info', `配置播种完成 → ${toPosix(configFile)}`)
646
+ return config
647
+ }
648
+
649
+ async function setConfig(patch) {
650
+ // F4:配置写入走 stateDir 级跨实例锁(与 atomic commit 共用同一临界区)
651
+ const lock = await acquireConfigLock('set-config')
652
+ if (!lock.ok) return { ok: false, reason: 'config-lock-timeout', detail: lock.detail ?? '' }
653
+ try {
654
+ await loadConfig()
655
+ if (configHealth.ok === false) {
656
+ return { ok: false, reason: 'config-degraded', detail: configHealth.detail, recovery: configHealth.recovery }
657
+ }
658
+ const built = buildConfigPatch(config, patch)
659
+ if (!built.ok) return built
660
+ // Validate under the lock, but do not invalidate watchers for an unchanged policy.
661
+ if (isDeepStrictEqual(built.value, config)) return { ok: true, revision: config.revision, unchanged: true }
662
+ const next = { ...built.value, revision: (config.revision ?? 1) + 1, updatedAt: nowIso() }
663
+ await atomicWrite(configFile, JSON.stringify(next, null, 2))
664
+ config = next
665
+ configHealth = { ok: true, state: 'loaded', detail: '' }
666
+ await writeLog('info', `配置写入成功 revision=${next.revision}`)
667
+ return { ok: true, revision: next.revision }
668
+ } finally {
669
+ await releaseConfigLock(lock.token)
670
+ }
671
+ }
672
+
673
+ /** 配置字段白名单/校验(setConfig 与原子 commit 共用,避免两套口径) */
674
+ function buildConfigPatch(current, patch) {
675
+ // R3:白名单 + 校验。以前是 {...config, ...patch} 全量合并,未知/非法字段会原样落盘。
676
+ const next = { ...current }
677
+ const allowed = new Set(['kbPath', 'categories', 'excludeFromSearch', 'followLinks', 'privateDirs', 'parsing', 'autoIndex'])
678
+ for (const key of Object.keys(patch ?? {})) {
679
+ if (!allowed.has(key)) return { ok: false, reason: 'unknown-config-field', detail: `不接受的配置字段:${key}` }
680
+ }
681
+ if (patch?.autoIndex !== undefined) {
682
+ if (typeof patch.autoIndex !== 'boolean') return { ok: false, reason: 'bad-auto-index' }
683
+ next.autoIndex = patch.autoIndex
684
+ }
685
+ // 第二轮:解析服务提供方(OCR/ASR)。深校验在 parsing.js 里做;这里只挡住形状错误。
686
+ // 注意:这里存的是**非敏感配置 + 凭据引用名**,任何密钥值都不允许落盘(由 parsing.js 拒绝)。
687
+ if (patch && patch.parsing !== undefined) {
688
+ const p = patch.parsing
689
+ if (p === null || typeof p !== 'object' || Array.isArray(p)) return { ok: false, reason: 'bad-parsing', detail: 'parsing 必须是对象' }
690
+ if (!Array.isArray(p.providers)) return { ok: false, reason: 'bad-parsing', detail: 'parsing.providers 必须是数组' }
691
+ next.parsing = p
692
+ }
693
+ if (patch && patch.kbPath !== undefined) next.kbPath = normKbPath(patch.kbPath)
694
+ if (patch && patch.categories !== undefined) {
695
+ if (!Array.isArray(patch.categories) || patch.categories.length === 0) return { ok: false, reason: 'bad-categories', detail: 'categories 必须是非空数组' }
696
+ next.categories = patch.categories.map((s) => toPosix(String(s).trim())).filter(Boolean)
697
+ }
698
+ if (patch && patch.excludeFromSearch !== undefined) {
699
+ if (!Array.isArray(patch.excludeFromSearch)) return { ok: false, reason: 'bad-excludes', detail: 'excludeFromSearch 必须是数组' }
700
+ next.excludeFromSearch = patch.excludeFromSearch.map((s) => toPosix(String(s).trim())).filter(Boolean)
701
+ }
702
+ if (patch && patch.followLinks !== undefined) next.followLinks = patch.followLinks === true
703
+ if (patch && patch.privateDirs !== undefined) {
704
+ const checked = sanitizePrivateDirs(patch.privateDirs)
705
+ if (!checked.ok) return { ok: false, reason: 'bad-private-dirs', detail: checked.reason }
706
+ next.privateDirs = checked.value
707
+ }
708
+ return { ok: true, value: next }
709
+ }
710
+
711
+ async function getConfig() {
712
+ if (config === null) await loadConfig()
713
+ return { ...config }
714
+ }
715
+ /** 强制重读磁盘(防止"内存里还是好配置、磁盘已坏"导致先动手再报错) */
716
+ async function getConfigFresh() {
717
+ await loadConfig()
718
+ return { ...config }
719
+ }
720
+ async function getConfigHealth() {
721
+ if (config === null) await loadConfig()
722
+ return { ...configHealth }
723
+ }
724
+
725
+ /**
726
+ * R6:空 kbPath **不是** cwd。
727
+ * 以前 `path.resolve('')` = 进程工作目录,于是"未绑定"被当成"绑定在一个真实目录"。
728
+ * 现在:空/空白 → null(上层必须按 unbound 处理,不得扫描、不得写入)。
729
+ */
730
+ function kbRootOf(conf) {
731
+ const raw = typeof conf?.kbPath === 'string' ? conf.kbPath.trim() : ''
732
+ return raw === '' ? null : path.resolve(raw)
733
+ }
734
+ function excludesOf(conf) {
735
+ const fromConf = Array.isArray(conf.excludeFromSearch) ? conf.excludeFromSearch : []
736
+ return [...new Set([...DEFAULT_EXCLUDES, '索引层', ...policyExcludes(kbRootOf(conf)), ...fromConf])]
737
+ }
738
+
739
+ async function readMeta(root) {
740
+ return readJsonState(path.join(root, '.kbmeta', 'kb.json'))
741
+ }
742
+
743
+ // ── F4:stateDir 级配置锁(跨实例)────────────────────────────────
744
+ // 作用:让「核对预期 + 写 config/binding」落在同一个临界区;不同进程/不同 core 实例都必须排队。
745
+ // 与库级锁(root/.kbmeta/lock.json)不是一把锁:那把保护"某个库",这把保护"这个 profile 的绑定"。
746
+ const configLockFile = path.join(stateDir, 'config.lock')
747
+ async function acquireConfigLock(label) {
748
+ const deadline = Date.now() + 4000
749
+ const token = crypto.randomUUID()
750
+ for (;;) {
751
+ try {
752
+ const handle = await open(configLockFile, 'wx')
753
+ await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname(), at: nowIso(), token, label }), 'utf8')
754
+ await handle.close()
755
+ return { ok: true, token }
756
+ } catch (error) {
757
+ if (!error || error.code !== 'EEXIST') return { ok: false, reason: 'config-lock-error', detail: String((error && (error.code || error.message)) ?? error) }
758
+ let cur = null
759
+ try { cur = JSON.parse(await readFile(configLockFile, 'utf8')) } catch { cur = null }
760
+ let stale = false
761
+ if (cur === null) {
762
+ const st = await stat(configLockFile).catch(() => null)
763
+ stale = st !== null && Date.now() - st.mtimeMs > 5000
764
+ } else {
765
+ stale = cur.host === os.hostname() && !pidAlive(cur.pid)
766
+ }
767
+ if (stale) {
768
+ await rm(configLockFile, { force: true }).catch(() => {})
769
+ continue
770
+ }
771
+ if (Date.now() >= deadline) return { ok: false, reason: 'config-lock-timeout', detail: `config.lock 被持有:${cur ? `${cur.pid}@${cur.host}` : '未知'}(${label})` }
772
+ await new Promise((r) => setTimeout(r, 25))
773
+ }
774
+ }
775
+ }
776
+ async function releaseConfigLock(token) {
777
+ let cur = null
778
+ try { cur = JSON.parse(await readFile(configLockFile, 'utf8')) } catch { cur = null }
779
+ if (cur && cur.token && cur.token !== token) return { ok: false, reason: 'lock-owner-changed' }
780
+ await rm(configLockFile, { force: true }).catch(() => {})
781
+ return { ok: true }
782
+ }
783
+
784
+ // ── R2:跨实例锁(库级)────────────────────────────────────────────
785
+ // 修三条危险边界:
786
+ // ① 活着的持有者**不凭时间强抢**(时间过期 ≠ 临界区已停;没有续约/fencing 就不能抢)
787
+ // ② 半写/空锁不给"立即判 stale"——按文件 mtime 给宽限期,过了才回收
788
+ // ③ 释放要核 ownerToken;旧持有者删不掉继任者的锁
789
+ // 另:锁内容用「临时文件 + rename」写入,保证读者看到的永远是一份完整 JSON。
790
+ const LOCK_LEASE_MS = 30_000
791
+ const LOCK_WAIT_MS = 4_000
792
+ const LOCK_PARTIAL_GRACE_MS = 5_000
793
+ const lockFileOf = (root) => path.join(root, '.kbmeta', 'lock.json')
794
+ // 进程内已持有的锁(root → info):同一进程内的嵌套调用直接复用,避免自锁死
795
+ const heldLocks = new Map()
796
+
797
+ function pidAlive(pid) {
798
+ if (!Number.isInteger(pid) || pid <= 0) return false
799
+ if (pid === process.pid) return true
800
+ try {
801
+ process.kill(pid, 0)
802
+ return true
803
+ } catch (error) {
804
+ return Boolean(error && error.code === 'EPERM') // 存在但无权限
805
+ }
806
+ }
807
+
808
+ async function releaseKbLock(root, token) {
809
+ const file = lockFileOf(root)
810
+ let cur = null
811
+ try {
812
+ cur = JSON.parse(await readFile(file, 'utf8'))
813
+ } catch {
814
+ cur = null
815
+ }
816
+ // 只有仍是自己那一把才删;否则宁可留着让后来者判活
817
+ if (cur && cur.token && cur.token !== token) return { ok: false, reason: 'lock-owner-changed' }
818
+ await rm(file, { force: true }).catch(() => {})
819
+ return { ok: true }
820
+ }
821
+
822
+ async function acquireKbLock(root, label) {
823
+ const existing = heldLocks.get(root)
824
+ if (existing) return { ok: true, file: lockFileOf(root), info: existing, reentrant: true }
825
+ const file = lockFileOf(root)
826
+ await mkdir(path.dirname(file), { recursive: true })
827
+ const deadline = Date.now() + LOCK_WAIT_MS
828
+ for (let attempt = 0; ; attempt += 1) {
829
+ const info = { pid: process.pid, host: os.hostname(), at: nowIso(), leaseMs: LOCK_LEASE_MS, label, token: crypto.randomUUID() }
830
+ try {
831
+ // 先把内容写进临时文件,再以 wx 的方式"占位"——若占位成功,内容早已完整
832
+ const tmp = path.join(path.dirname(file), `lock.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`)
833
+ await writeFile(tmp, JSON.stringify(info), 'utf8')
834
+ let handle = null
835
+ try {
836
+ handle = await open(file, 'wx')
837
+ } catch (error) {
838
+ await rm(tmp, { force: true }).catch(() => {})
839
+ throw error
840
+ }
841
+ await handle.close()
842
+ await rename(tmp, file)
843
+ heldLocks.set(root, info)
844
+ return { ok: true, file, info }
845
+ } catch (error) {
846
+ if (!error || error.code !== 'EEXIST') {
847
+ return { ok: false, reason: 'lock-error', detail: String((error && (error.code || error.message)) ?? error) }
848
+ }
849
+ let cur = null
850
+ try { cur = JSON.parse(await readFile(file, 'utf8')) } catch { cur = null }
851
+ const sameHost = cur !== null && cur.host === os.hostname()
852
+ let stale = false
853
+ if (cur === null) {
854
+ // 半写/空锁:给宽限期,过了才当残留回收
855
+ const st = await stat(file).catch(() => null)
856
+ const age = st === null ? Number.POSITIVE_INFINITY : Date.now() - st.mtimeMs
857
+ stale = age > LOCK_PARTIAL_GRACE_MS
858
+ } else if (sameHost && Number.isInteger(cur.pid) && !pidAlive(cur.pid)) {
859
+ stale = true // 本机确认持有者已死
860
+ } else if (!sameHost && cur.leaseMs > 0 && Date.parse(cur.at) && Date.now() - Date.parse(cur.at) > cur.leaseMs) {
861
+ stale = true // 跨主机无法查 pid,只能按租约
862
+ }
863
+ // 本机确认仍活着 → **永不凭时间抢占**(超租期也等/返 busy)
864
+ if (stale) {
865
+ await writeLog('warn', `回收残留锁(${label}):${JSON.stringify(cur)}`)
866
+ await rm(file, { force: true }).catch(() => {})
867
+ continue
868
+ }
869
+ if (Date.now() > deadline) {
870
+ return { ok: false, reason: 'lock-busy', detail: `持有者 pid=${cur && cur.pid} host=${cur && cur.host} at=${cur && cur.at} label=${cur && cur.label}` }
871
+ }
872
+ await new Promise((r) => setTimeout(r, 40 + attempt * 25))
873
+ }
874
+ }
875
+ }
876
+
877
+ /** 在库级锁内执行;拿不到锁返回 lock-* 结构(不抛异常,调用方按 schema 处理) */
878
+ async function withKbLock(root, label, fn, { freshSetup = false } = {}) {
879
+ await assertServiceOwner(root, cfg.serviceOwnerToken, { freshSetup })
880
+ const lock = await acquireKbLock(root, label)
881
+ if (!lock.ok) {
882
+ await writeLog('warn', `取锁失败(${label}):${lock.reason} ${lock.detail}`)
883
+ return { ok: false, reason: lock.reason, detail: lock.detail, lock: { held: false } }
884
+ }
885
+ try {
886
+ await assertServiceOwner(root, cfg.serviceOwnerToken, { freshSetup })
887
+ return await fn()
888
+ } finally {
889
+ if (lock.reentrant !== true) {
890
+ heldLocks.delete(root)
891
+ await releaseKbLock(root, lock.info.token)
892
+ }
893
+ }
894
+ }
895
+
896
+ // ── P1-D / R1:索引 meta、全文条目与新鲜度 ─────────────────────────
897
+ // R1 的核心决定:**不再用 token 做「排除」**。索引条目直接带可检索全文(text),
898
+ // 搜索在 text 上做 includes —— 与"读盘扫描"是同一份拼接口径,因此同一快照下
899
+ // 两路结果集合必然相同(旧实现的 ASCII 全词键 + 中文二元组无法表达任意子串)。
900
+ // 外部改动靠 contentFingerprint(path|size|mtimeMs 汇总)失效 → 回退扫描磁盘。
901
+ const INDEX_FORMAT = 2
902
+ const INDEX_TOKENIZER = 'fulltext-v1'
903
+
904
+ function excludesFingerprint(conf) {
905
+ return sha12(Buffer.from(excludesOf(conf).join('|'), 'utf8'))
906
+ }
907
+
908
+ /** 由「路径 + 字节数 + mtime」拼内容指纹:外部改正文/加删文件都会变 */
909
+ function fingerprintOf(rows) {
910
+ const lines = rows.map((r) => `${r.path}|${r.size}|${r.mtimeMs}`).sort()
911
+ return sha12(Buffer.from(lines.join('\n'), 'utf8'))
912
+ }
913
+
914
+ function validIndexPayload(payload) {
915
+ if (payload && validPayloads.has(payload)) return true
916
+ ioMetrics.indexValidations++
917
+ const valid = payload?.meta?.format === INDEX_FORMAT && payload.meta.tokenizer === INDEX_TOKENIZER
918
+ && Array.isArray(payload.entries) && payload.meta.entries === payload.entries.length
919
+ && payload.entries.every(r => r && typeof r.path === 'string' && typeof r.text === 'string'
920
+ && Number.isFinite(r.mtimeMs) && r.size === Buffer.byteLength(r.text)
921
+ && r.revision === sha12(Buffer.from(r.text)))
922
+ && payload.meta.fingerprint === fingerprintOf(payload.entries)
923
+ if (valid) validPayloads.add(payload)
924
+ return valid
925
+ }
926
+
927
+ function entryFromBuffer(relPath, abs, buf, mtimeMs, ctimeMs) {
928
+ const text = buf.toString('utf8')
929
+ const parsed = parseFrontmatter(text)
930
+ return {
931
+ // 2026-10-17:无 frontmatter id 时按路径派生(见 derivedEntryId)
932
+ entryId: parsed.data.id ?? derivedEntryId(relPath),
933
+ path: relPath,
934
+ title: parsed.data.title ?? path.basename(abs, '.md'),
935
+ kind: parsed.data.type ?? null,
936
+ tags: Array.isArray(parsed.data.tags) ? parsed.data.tags : [],
937
+ status: parsed.data.status ?? null,
938
+ updated: parsed.data.updated ?? null,
939
+ revision: sha12(buf),
940
+ size: buf.length,
941
+ mtimeMs: Number.isFinite(mtimeMs) ? mtimeMs : 0,
942
+ ctimeMs: Number.isFinite(ctimeMs) ? ctimeMs : null,
943
+ frontmatterValid: parsed.valid !== false,
944
+ // 全文(含 frontmatter):与旧口径「整份文件读出来做 includes」逐字一致
945
+ text,
946
+ }
947
+ }
948
+
949
+ async function indexMetaOf(conf, entries, rootIn = kbRootOf(conf)) {
950
+ const meta = rootIn === null ? { state: 'missing' } : await readMeta(rootIn)
951
+ return {
952
+ kbId: meta.state === 'ok' ? (meta.value.kbId ?? null) : null,
953
+ excludes: excludesFingerprint(conf),
954
+ entries: entries.length,
955
+ format: INDEX_FORMAT,
956
+ tokenizer: INDEX_TOKENIZER,
957
+ fingerprint: fingerprintOf(entries),
958
+ writtenAt: nowIso(),
959
+ }
960
+ }
961
+
962
+ /** 索引是否可用于检索:身份/排除规则/格式版本/内容指纹全部对上才算 fresh */
963
+ async function freshnessOf(conf, payload) {
964
+ const root = kbRootOf(conf)
965
+ if (!payload || typeof payload !== 'object' || !Array.isArray(payload.entries)) {
966
+ return { fresh: false, reason: 'index-corrupt', detail: '索引结构不是 { entries: [...] }' }
967
+ }
968
+ const meta = payload.meta ?? null
969
+ if (meta === null) return { fresh: false, reason: 'index-legacy', detail: '索引缺 meta(旧格式),需重建' }
970
+ if (typeof meta.kbId !== 'string' || !meta.kbId.trim()) return { fresh: false, reason: 'index-legacy', detail: '索引缺少有效的知识库身份摘要,需完整重建' }
971
+ const kb = await readMeta(root)
972
+ const kbId = kb.state === 'ok' ? (kb.value.kbId ?? null) : null
973
+ if (meta.kbId !== kbId) return { fresh: false, reason: 'index-kbid-mismatch', detail: `索引 kbId=${meta.kbId} 当前=${kbId}` }
974
+ const excludes = excludesFingerprint(conf)
975
+ if (meta.excludes !== excludes) return { fresh: false, reason: 'index-excludes-changed', detail: '排除规则与索引不一致(需重建)' }
976
+ if (meta.format !== INDEX_FORMAT) return { fresh: false, reason: 'index-format-old', detail: `索引格式 ${meta.format ?? '(缺)'},本版需要 ${INDEX_FORMAT}` }
977
+ if (meta.tokenizer !== INDEX_TOKENIZER) return { fresh: false, reason: 'index-tokenizer-old', detail: `索引分词版本 ${meta.tokenizer ?? '(缺)'},本版需要 ${INDEX_TOKENIZER}` }
978
+ if (!validIndexPayload(payload)) return { fresh: false, reason: 'index-corrupt', detail: '索引条目或摘要校验失败,需安全重建' }
979
+ // 内容指纹:需要 walk+stat(不读文件),用来抓"用户在文件系统里直接改了正文"
980
+ const current = await diskFingerprint(conf)
981
+ if (current.error) return { fresh: false, reason: 'index-fingerprint-unknown', detail: current.error }
982
+ if (meta.fingerprint !== current.fingerprint) {
983
+ return { fresh: false, reason: 'index-stale-content', detail: `文件清单或属性有变化(${current.files} 个 .md;索引写入于 ${meta.writtenAt ?? '-'}),等待核对内容并增量同步` }
984
+ }
985
+ return { fresh: true, reason: 'ok', detail: '', meta }
986
+ }
987
+
988
+ /** 读索引并判新鲜度:一次读取、一个快照(避免 search 里重复 readIndex) */
989
+ async function indexSnapshot(conf) {
990
+ const root = kbRootOf(conf)
991
+ const res = await readIndexState(indexPath(root))
992
+ if (res.state !== 'ok') {
993
+ return { state: res.state, entries: [], freshness: { fresh: false, reason: res.state === 'missing' ? 'index-missing' : 'index-corrupt', detail: res.error ?? '' } }
994
+ }
995
+ const payload = res.value ?? {}
996
+ const freshness = await freshnessOf(conf, payload)
997
+ const entries = freshness.reason === 'index-corrupt' ? [] : Array.isArray(payload.entries) ? payload.entries : []
998
+ return { state: 'ok', entries, payload, generatedAt: payload.generatedAt ?? null, freshness }
999
+ }
1000
+
1001
+ async function indexFreshness(confIn) {
1002
+ const conf = confIn ?? (await getConfig())
1003
+ if (!conf || !conf.kbPath) return { fresh: false, reason: 'unbound', detail: '未绑定知识库' }
1004
+ const snap = await indexSnapshot(conf)
1005
+ return snap.state === 'ok' ? snap.freshness : { fresh: false, reason: snap.freshness.reason, detail: snap.freshness.detail ?? '' }
1006
+ }
1007
+
1008
+ /** 只更新索引里的某一条(增量);索引不可用时退回整库重建(重建失败则如实报 failed) */
1009
+ async function updateIndexFor(conf, relPath, action = 'upsert') {
1010
+ const root = kbRootOf(conf)
1011
+ if (policyExcluded(readIndexPolicy(root), relPath)) action = 'remove'
1012
+ const idx = await readIndex(conf)
1013
+ if (idx.state !== 'ok') {
1014
+ const rebuilt = await reindexLocked(conf)
1015
+ if (rebuilt.ok === false) return { mode: 'failed', reason: rebuilt.reason, scanErrors: rebuilt.scanErrors ?? [] }
1016
+ return { mode: 'full', reason: idx.state, count: rebuilt.entries.length }
1017
+ }
1018
+ const policy = readIndexPolicy(root)
1019
+ const entries = Array.isArray(idx.entries) ? idx.entries.filter(e => !policyExcluded(policy, e.path)) : []
1020
+ const at = entries.findIndex((e) => e.path === relPath)
1021
+ if (action === 'remove') {
1022
+ if (at >= 0) entries.splice(at, 1)
1023
+ } else {
1024
+ const abs = path.join(root, relPath)
1025
+ const buf = await readFile(abs)
1026
+ const st = await stat(abs).catch(() => null)
1027
+ const entry = entryFromBuffer(relPath, abs, buf, st ? st.mtimeMs : 0, st?.ctimeMs)
1028
+ if (at >= 0) entries[at] = entry
1029
+ else entries.push(entry)
1030
+ }
1031
+ const payload = { generatedAt: nowIso(), meta: await indexMetaOf(conf, entries), entries }
1032
+ await commitIndex(indexPath(root), payload)
1033
+ return { mode: 'incremental', count: entries.length }
1034
+ }
1035
+
1036
+ /**
1037
+ * C1/C2:统一配置闸门。所有"可能写盘"的公开入口都必须先过这里:
1038
+ * - 强制重读磁盘(不依赖调用过 status 刷新缓存)
1039
+ * - 判据统一用 configHealth.ok,不再用有时有、有时没有的 conf.degraded
1040
+ * - 返回可直接透传给工具的结构(含工具 output schema 要求的字段)
1041
+ */
1042
+ async function configGate() {
1043
+ await assertServiceOwner(kbRootOf(await getConfigFresh()), cfg.serviceOwnerToken)
1044
+ const conf = await getConfigFresh()
1045
+ const health = await getConfigHealth()
1046
+ if (health.ok === false) {
1047
+ return {
1048
+ ok: false,
1049
+ conf,
1050
+ health,
1051
+ refusal: {
1052
+ ok: false,
1053
+ reason: 'config-degraded',
1054
+ state: health.state,
1055
+ detail: health.detail,
1056
+ recovery: health.recovery ?? null,
1057
+ },
1058
+ }
1059
+ }
1060
+ // R6:未绑定就是未绑定 —— 不扫描 cwd、不写入、不假装有一个库
1061
+ if (kbRootOf(conf) === null) {
1062
+ return {
1063
+ ok: false,
1064
+ conf,
1065
+ health,
1066
+ refusal: {
1067
+ ok: false,
1068
+ reason: 'unbound',
1069
+ state: 'unbound',
1070
+ detail: '未绑定知识库(kbPath 为空)。本版不会把空路径当成当前工作目录;请先选择并绑定一个目录(kb_bind / 设置页「自动建库 / 识别」)。',
1071
+ recovery: '绑定一个目录后重试;老用户的既有绑定不受影响',
1072
+ },
1073
+ }
1074
+ }
1075
+ return { ok: true, conf, health }
1076
+ }
1077
+
1078
+ /** C3:健康检查要校验身份与结构,缺身份不能算健康,也不能自动换身份 */
1079
+ async function healthOf(conf, rootIn = kbRootOf(conf)) {
1080
+ const root = rootIn
1081
+ if (root === null) return { healthy: false, reason: 'unbound', detail: '未绑定知识库(kbPath 为空)' }
1082
+ const metaDir = path.join(root, '.kbmeta')
1083
+ const metaFile = path.join(metaDir, 'kb.json')
1084
+ const indexDir = path.join(metaDir, 'index')
1085
+ for (const dir of [metaDir, indexDir]) {
1086
+ const st = await stat(dir).catch(() => null)
1087
+ if (st === null) {
1088
+ return { healthy: false, reason: 'not-initialized', detail: `缺 ${toPosix(path.relative(root, dir)) || dir}` }
1089
+ }
1090
+ if (!st.isDirectory()) {
1091
+ return { healthy: false, reason: 'meta-invalid', detail: `${toPosix(path.relative(root, dir))} 不是目录` }
1092
+ }
1093
+ }
1094
+ const meta = await readMeta(root)
1095
+ if (meta.state !== 'ok') {
1096
+ return { healthy: false, reason: meta.state === 'missing' ? 'not-initialized' : `meta-${meta.state}`, detail: meta.error ?? '' }
1097
+ }
1098
+ const m = meta.value
1099
+ if (m.installState !== 'complete') {
1100
+ return { healthy: false, reason: 'half-initialized', detail: `installState=${m.installState ?? '(缺)'}` }
1101
+ }
1102
+ if (typeof m.kbId !== 'string' || m.kbId.trim() === '') {
1103
+ return { healthy: false, reason: 'invalid-kb-id', detail: 'kb.json 缺 kbId:库身份无效。请恢复元数据,本程序不会自动换身份' }
1104
+ }
1105
+ if (m.schemaVersion !== SCHEMA_VERSION) {
1106
+ return { healthy: false, reason: 'unsupported-meta-schema', detail: `kb.json schemaVersion=${m.schemaVersion},本版支持 ${SCHEMA_VERSION}` }
1107
+ }
1108
+ if (m.freshOriginalIndex === true && !catalogActive(root)) {
1109
+ return { healthy: false, reason: 'catalog-missing', detail: '原件目录缺失,请恢复索引后重试;不会自动切换旧模式' }
1110
+ }
1111
+ const bad = []
1112
+ if (!catalogActive(root)) {
1113
+ for (const category of conf.categories ?? []) {
1114
+ const st = await stat(path.join(root, category)).catch(() => null)
1115
+ if (st === null) bad.push(`${category}(缺)`)
1116
+ else if (!st.isDirectory()) bad.push(`${category}(不是目录)`)
1117
+ }
1118
+ }
1119
+ if (bad.length > 0) {
1120
+ return { healthy: false, reason: 'invalid-categories', detail: bad.join('、') }
1121
+ }
1122
+ return { healthy: true, reason: 'ok', detail: '' }
1123
+ }
1124
+
1125
+ // ── A:绑定(含初始化预览与确认)──────────────────────────────────
1126
+ async function bind(kbPathIn, options = {}) {
1127
+ // R6:空路径不是 cwd;相对路径也不猜(一律要求绝对路径)
1128
+ const raw = String(kbPathIn ?? '').trim()
1129
+ if (raw === '') {
1130
+ return { ok: false, kbPath: null, needsConfirm: false, initialized: false, alreadyInitialized: false, kbId: null, willCreate: [], willModify: [], reason: 'empty-path', note: '路径为空:本版不会把空路径当成当前工作目录,请选择一个具体文件夹' }
1131
+ }
1132
+ if (!path.isAbsolute(raw)) {
1133
+ return { ok: false, kbPath: raw, needsConfirm: false, initialized: false, alreadyInitialized: false, kbId: null, willCreate: [], willModify: [], reason: 'relative-path', note: '请传文件夹的绝对路径(相对路径不按进程工作目录解释)' }
1134
+ }
1135
+ const target = path.resolve(raw)
1136
+ await assertServiceOwner(target, cfg.serviceOwnerToken)
1137
+ // F4:原子提交入口。预期当前绑定 / 配置 revision / 目标身份 + 写入,必须在同一临界区内完成;
1138
+ // 任何前置条件不符 → 零改动拒绝(不 bind、不写 config、不写 binding)。
1139
+ if (options && options.commit === true) {
1140
+ return await commitBind(target, options)
1141
+ }
1142
+ // 注意:bind 的**正常场景**就是从"未绑定"开始,所以不能走 configGate(它会把 unbound 当拒绝)。
1143
+ // 这里只拒绝「配置损坏/降级」。
1144
+ const gate = await configGate()
1145
+ if (!gate.ok && gate.refusal.reason === 'config-degraded') {
1146
+ // 失败返回也要满足 kb_bind 的 output schema(要求 ok + kbPath)
1147
+ return {
1148
+ ok: false,
1149
+ kbPath: toPosix(target),
1150
+ needsConfirm: false,
1151
+ initialized: false,
1152
+ alreadyInitialized: false,
1153
+ kbId: null,
1154
+ willCreate: [],
1155
+ willModify: [],
1156
+ ...gate.refusal,
1157
+ }
1158
+ }
1159
+ const conf = gate.conf
1160
+ const result = {
1161
+ ok: false,
1162
+ kbPath: toPosix(target),
1163
+ existed: existsSync(target),
1164
+ writable: false,
1165
+ alreadyInitialized: false,
1166
+ kbId: null,
1167
+ willCreate: [],
1168
+ willModify: [],
1169
+ initialized: false,
1170
+ needsConfirm: false,
1171
+ note: '',
1172
+ }
1173
+
1174
+ // 预览阶段**不创建任何东西**(复核意见 §6-3):只做只读探测
1175
+ if (result.existed) {
1176
+ const st = await stat(target).catch(() => null)
1177
+ if (st === null || !st.isDirectory()) {
1178
+ result.note = '目标路径已存在但不是目录'
1179
+ await writeLog('warn', `bind 失败:${result.note} ${result.kbPath}`)
1180
+ return result
1181
+ }
1182
+ try {
1183
+ await access(target, constants.W_OK)
1184
+ result.writable = true
1185
+ } catch (error) {
1186
+ result.note = `目录不可写:${String((error && (error.code || error.message)) ?? error)}`
1187
+ await writeLog('warn', `bind 失败:${result.note}`)
1188
+ return result
1189
+ }
1190
+ } else {
1191
+ // 目标不存在:查最近的已存在祖先是否可写(只读判断,不 mkdir)
1192
+ let anc = path.dirname(target)
1193
+ while (!existsSync(anc) && path.dirname(anc) !== anc) anc = path.dirname(anc)
1194
+ try {
1195
+ await access(anc, constants.W_OK)
1196
+ result.writable = true
1197
+ result.note = `目标不存在;确认后会创建(父级 ${toPosix(anc)} 可写)`
1198
+ } catch (error) {
1199
+ result.note = `目标不存在且父级不可写:${String((error && (error.code || error.message)) ?? error)}(${toPosix(anc)})`
1200
+ await writeLog('warn', `bind 失败:${result.note}`)
1201
+ return result
1202
+ }
1203
+ }
1204
+
1205
+ const meta = await readMeta(target)
1206
+ if (meta.state === 'ok') {
1207
+ result.alreadyInitialized = true
1208
+ result.initialized = meta.value.installState === 'complete'
1209
+ result.kbId = meta.value.kbId ?? null
1210
+ result.note = '已初始化,接入时不覆盖任何既有文件'
1211
+ const restoreReport = await readJsonState(path.join(target, '.kbmeta/restore-report.json'))
1212
+ const restorePolicy = await readJsonState(path.join(target, '.kbmeta/restore-policy.json'))
1213
+ const recovered = restoreReport.state === 'ok' && restoreReport.value.verified === true && restoreReport.value.kbId === result.kbId && restorePolicy.state === 'ok'
1214
+ ? Object.fromEntries(['categories','privateDirs','excludeFromSearch','autoIndex'].filter(k => restorePolicy.value[k] !== undefined).map(k => [k,restorePolicy.value[k]])) : {}
1215
+ const written = await setConfig({ ...recovered, kbPath: toPosix(target) })
1216
+ if (!written.ok) return { ...result, ...written, ok: false, kbPath: toPosix(target) }
1217
+ await writeBinding(result.kbId, target)
1218
+ result.ok = true
1219
+ await writeLog('info', `bind 接入既有库 kbPath=${result.kbPath} kbId=${result.kbId}`)
1220
+ return result
1221
+ }
1222
+ if (meta.state === 'corrupt') {
1223
+ result.note = '目标目录的 .kbmeta/kb.json 已损坏:未做任何改动,请人工检查'
1224
+ return result
1225
+ }
1226
+
1227
+ result.willCreate = ['.kbmeta/kb.json', '.kbmeta/index/', '.kbmeta/backups/', ...(conf.categories ?? []), 'INDEX.md(仅当缺失)', '_模板/(仅当缺失)']
1228
+ if (options.confirmInit !== true) {
1229
+ result.needsConfirm = true
1230
+ result.note = result.note || '这是全新目录。确认后才会创建上述内容(不会覆盖任何既有文件)。'
1231
+ return result
1232
+ }
1233
+ // 确认后才创建目录并写探针
1234
+ try {
1235
+ await mkdir(target, { recursive: true })
1236
+ const probe = path.join(target, `.kb-write-probe-${process.pid}-${crypto.randomBytes(3).toString('hex')}`)
1237
+ await writeFile(probe, 'ok', 'utf8')
1238
+ await rm(probe, { force: true })
1239
+ } catch (error) {
1240
+ result.note = `创建目录失败:${String((error && (error.code || error.message)) ?? error)}`
1241
+ await writeLog('warn', `bind 失败:${result.note}`)
1242
+ return result
1243
+ }
1244
+ // R2:初始化也会写 .kbmeta(索引/备份目录/恢复记录),走同一把库级锁
1245
+ const initResult = await withKbLock(target, 'bind-init', async () => initTo(target, conf, { originalIndex: options.originalIndex === true }))
1246
+ result.initialized = initResult.installState === 'complete'
1247
+ result.kbId = initResult.kbId ?? null
1248
+ const written = await setConfig({ kbPath: toPosix(target) })
1249
+ if (!written.ok) return { ...result, ...written, ok: false, kbPath: toPosix(target) }
1250
+ await writeBinding(result.kbId, target)
1251
+ result.ok = result.initialized
1252
+ result.note = result.initialized ? '新库已初始化并绑定' : '初始化未完成,见 init 步骤'
1253
+ result.init = initResult
1254
+ await writeLog(result.ok ? 'info' : 'warn', `bind+init kbPath=${result.kbPath} 完成=${result.initialized}`)
1255
+ return result
1256
+ }
1257
+
1258
+ /**
1259
+ * F4:原子提交切库。
1260
+ * 在 stateDir 配置锁(跨实例)内:重读磁盘配置 → 核对预期当前绑定 / 配置 revision →
1261
+ * 核对目标库身份 → 写 config + binding。任一步不符 → commit-conflict,且**零写入**。
1262
+ * 注意:不在 bind 之后再检查目标身份(那会让"先切库、再报失败"仍然发生)。
1263
+ */
1264
+ async function commitBind(target, options = {}) {
1265
+ const lock = await acquireConfigLock('commit-bind')
1266
+ if (!lock.ok) return { ok: false, kbPath: toPosix(target), reason: 'config-lock-timeout', detail: lock.detail ?? '', needsConfirm: false }
1267
+ try {
1268
+ const confNow = await loadConfig()
1269
+ const cfgHealth = await getConfigHealth()
1270
+ if (cfgHealth.ok === false) return { ok: false, kbPath: toPosix(target), reason: 'config-degraded', detail: cfgHealth.detail, needsConfirm: false }
1271
+ const expectedRev = options.expectedConfigRevision
1272
+ const expectedPath = typeof options.expectedCurrentKbPath === 'string' ? options.expectedCurrentKbPath : null
1273
+ const expectedCurrentKbId = options.expectedCurrentKbId ?? null
1274
+ const expectedTargetKbId = options.expectedTargetKbId ?? null
1275
+ const nowPath = confNow.kbPath ?? ''
1276
+ const conflict = (kind, extra) => ({
1277
+ ok: false,
1278
+ kbPath: toPosix(target),
1279
+ needsConfirm: false,
1280
+ reason: 'commit-conflict',
1281
+ conflict: kind,
1282
+ expected: { revision: expectedRev ?? null, kbPath: expectedPath, kbId: expectedCurrentKbId, targetKbId: expectedTargetKbId },
1283
+ actual: { revision: confNow.revision ?? null, kbPath: nowPath, kbId: null, targetKbId: null },
1284
+ note: '提交前置条件不符:未绑定、config.json 与 binding 文件均未改动',
1285
+ ...extra,
1286
+ })
1287
+ if (expectedRev !== undefined && expectedRev !== null && String(confNow.revision ?? '') !== String(expectedRev)) {
1288
+ return conflict('config-revision')
1289
+ }
1290
+ if (expectedPath !== null && normAbs(nowPath) !== normAbs(expectedPath)) {
1291
+ return conflict('current-binding')
1292
+ }
1293
+ let currentKbId = null
1294
+ try {
1295
+ const b = JSON.parse(await readFile(bindingFile, 'utf8'))
1296
+ currentKbId = b.kbId ?? null
1297
+ } catch {
1298
+ currentKbId = null
1299
+ }
1300
+ if (expectedCurrentKbId !== null && String(currentKbId ?? '') !== String(expectedCurrentKbId)) {
1301
+ return conflict('current-kbId', { actual: { revision: confNow.revision ?? null, kbPath: nowPath, kbId: currentKbId, targetKbId: null } })
1302
+ }
1303
+ // 目标身份必须在**写入之前**核对
1304
+ const meta = await readMeta(target)
1305
+ if (meta.state !== 'ok') {
1306
+ return { ...conflict('target-meta'), detail: `目标库元数据不可用(${meta.state}):${meta.error ?? ''}` }
1307
+ }
1308
+ if (meta.value.installState !== 'complete') {
1309
+ return { ...conflict('target-meta'), detail: `目标库初始化未完成(installState=${meta.value.installState ?? '(缺)'})` }
1310
+ }
1311
+ const targetKbId = meta.value.kbId ?? null
1312
+ if (expectedTargetKbId !== null && String(targetKbId ?? '') !== String(expectedTargetKbId)) {
1313
+ return { ...conflict('target-kbId', { actual: { revision: confNow.revision ?? null, kbPath: nowPath, kbId: currentKbId, targetKbId } }) }
1314
+ }
1315
+ if (options.sharedInstanceId) {
1316
+ const marker = await readJsonState(path.join(target, '.kbmeta/service-mode.json'))
1317
+ if (marker.state !== 'ok' || marker.value.state !== 'active' || marker.value.kbId !== targetKbId || marker.value.instanceId !== options.sharedInstanceId) return conflict('target-service')
1318
+ }
1319
+ const built = buildConfigPatch(confNow, { kbPath: toPosix(target) })
1320
+ if (!built.ok) return { ok: false, kbPath: toPosix(target), needsConfirm: false, ...built }
1321
+ const next = { ...built.value, revision: (confNow.revision ?? 1) + 1, updatedAt: nowIso() }
1322
+ await atomicWrite(configFile, JSON.stringify(next, null, 2))
1323
+ config = next
1324
+ configHealth = { ok: true, state: 'loaded', detail: '' }
1325
+ await writeBinding(targetKbId, target)
1326
+ await writeLog('info', `原子提交切库 kbPath=${toPosix(target)} kbId=${targetKbId} revision=${next.revision}`)
1327
+ return {
1328
+ ok: true,
1329
+ kbPath: toPosix(target),
1330
+ existed: true,
1331
+ writable: true,
1332
+ alreadyInitialized: true,
1333
+ initialized: true,
1334
+ kbId: targetKbId,
1335
+ revision: next.revision,
1336
+ willCreate: [],
1337
+ willModify: [],
1338
+ needsConfirm: false,
1339
+ note: '已原子提交(前置条件与写入在同一临界区)',
1340
+ }
1341
+ } finally {
1342
+ await releaseConfigLock(lock.token)
1343
+ }
1344
+ }
1345
+
1346
+ async function writeBinding(kbId, target) {
1347
+ await atomicWrite(bindingFile, JSON.stringify({ kbId, kbPath: toPosix(target), boundAt: nowIso(), stateDir: toPosix(stateDir) }, null, 2))
1348
+ }
1349
+
1350
+ // ── C:初始化有完成标记;半成品重试补齐 ─────────────────────────────
1351
+ async function initTo(root, conf, { freshSetup = false, originalIndex = freshSetup } = {}) {
1352
+ const created = []
1353
+ const repaired = []
1354
+ const skipped = []
1355
+ await mkdir(root, { recursive: true })
1356
+ // Only a genuinely empty directory receives the new default. Existing
1357
+ // directories still go through the explicit original-file migration.
1358
+ const entriesAtStart = await readdir(root)
1359
+ const metaEntries = entriesAtStart.length === 1 && entriesAtStart[0] === '.kbmeta'
1360
+ ? await readdir(path.join(root, '.kbmeta')) : []
1361
+ const emptyAtStart = entriesAtStart.length === 0 || (entriesAtStart.length === 1 && entriesAtStart[0] === '.kbmeta' && metaEntries.length === 1 && metaEntries[0] === 'lock.json')
1362
+ const metaDir = path.join(root, '.kbmeta')
1363
+ const metaFile = path.join(metaDir, 'kb.json')
1364
+ const meta = await readMeta(root)
1365
+ let state = meta.state === 'ok' ? meta.value : null
1366
+ if (meta.state === 'corrupt') {
1367
+ return { installState: 'blocked', reason: 'meta-corrupt', detail: 'kb.json 损坏,未改动', kbId: null, created, repaired, skipped }
1368
+ }
1369
+ if (freshSetup && !(state ? state.freshSharedSetup === true : emptyAtStart)) {
1370
+ return { installState: 'blocked', reason: 'not-fresh', detail: '仅空目录可新建共享库', kbId: null, created, repaired, skipped }
1371
+ }
1372
+ await mkdir(path.join(metaDir, 'index'), { recursive: true })
1373
+ await mkdir(path.join(metaDir, 'backups'), { recursive: true })
1374
+ if (state === null) {
1375
+ state = {
1376
+ schemaVersion: SCHEMA_VERSION,
1377
+ kbId: crypto.randomUUID(),
1378
+ name: path.basename(root),
1379
+ createdAt: nowIso(),
1380
+ createdBy: `dsh-knowledge-base@${VERSION}`,
1381
+ stateDir: toPosix(stateDir),
1382
+ installState: 'partial',
1383
+ freshOriginalIndex: originalIndex && emptyAtStart,
1384
+ ...(freshSetup ? { freshSharedSetup: true } : {}),
1385
+ }
1386
+ await atomicWrite(metaFile, JSON.stringify(state, null, 2))
1387
+ created.push('.kbmeta/kb.json')
1388
+ } else if (state.installState !== 'complete') {
1389
+ repaired.push(`继续未完成的初始化(原 installState=${state.installState ?? '(缺)'})`)
1390
+ } else {
1391
+ skipped.push('.kbmeta/kb.json')
1392
+ }
1393
+ if (state.freshOriginalIndex === true && state.installState === 'complete' && !catalogActive(root)) {
1394
+ return { installState: 'blocked', reason: 'catalog-missing', detail: '原件目录缺失,请恢复索引后重试;不会重建空目录或切换旧模式', kbId: state.kbId, created, repaired, skipped }
1395
+ }
1396
+ if (state.freshOriginalIndex === true && state.installState !== 'complete' && !catalogActive(root)) {
1397
+ const canonical = await realpath(root)
1398
+ const key = crypto.createHash('sha256').update(state.kbId + '\0' + canonical.toLowerCase()).digest('hex').slice(0, 24)
1399
+ const folder = path.join(root, '索引层')
1400
+ await mkdir(folder, { recursive: true })
1401
+ const at = Date.now()
1402
+ await atomicWrite(path.join(folder, '文件目录.json'), JSON.stringify({format:'original-files-v1',kbId:state.kbId,key,revision:1,policyRevision:1,createdAt:at,updatedAt:at,classificationVersion:CLASSIFICATION_VERSION,files:[],references:[],coverage:{files:0,originals:0,references:0,errors:0}}, null, 2))
1403
+ created.push('索引层/文件目录.json')
1404
+ }
1405
+ if (!catalogActive(root)) {
1406
+ for (const category of conf.categories ?? []) {
1407
+ const dir = path.join(root, category)
1408
+ if (existsSync(dir)) skipped.push(category)
1409
+ else {
1410
+ try {
1411
+ await mkdir(dir, { recursive: true })
1412
+ created.push(category + '/')
1413
+ } catch (error) {
1414
+ const detail = `${category}: ${(error && (error.code || error.message)) ?? error}`
1415
+ await writeLog('warn', `建分类目录失败 ${detail}`)
1416
+ return { installState: 'partial', reason: 'mkdir-failed', detail, kbId: state.kbId, created, repaired, skipped }
1417
+ }
1418
+ }
1419
+ }
1420
+ const indexFile = path.join(root, 'INDEX.md')
1421
+ if (existsSync(indexFile)) skipped.push('INDEX.md')
1422
+ else {
1423
+ await atomicWrite(
1424
+ indexFile,
1425
+ buildFile(
1426
+ { title: '索引', type: '索引', tags: ['索引'], status: '进行中', created: today(), updated: today() },
1427
+ '# 索引\n\n> 人工维护的导航页。插件不会覆盖本文件。\n\n## 板块\n\n' + (conf.categories ?? []).map((c) => `- [${c}/](${c}/)`).join('\n') + '\n',
1428
+ ),
1429
+ )
1430
+ created.push('INDEX.md')
1431
+ }
1432
+ const tplDir = path.join(root, '_模板')
1433
+ if (existsSync(tplDir)) skipped.push('_模板/')
1434
+ else {
1435
+ await mkdir(tplDir, { recursive: true })
1436
+ for (const [name, text] of Object.entries(TEMPLATES)) await atomicWrite(path.join(tplDir, name), text)
1437
+ created.push('_模板/(3 个模板)')
1438
+ }
1439
+ }
1440
+ state.installState = 'complete'
1441
+ state.completedAt = nowIso()
1442
+ await atomicWrite(metaFile, JSON.stringify(state, null, 2))
1443
+ await writeLog('info', `init 完成 kbId=${state.kbId} 新建=${created.length} 补齐=${repaired.length}`)
1444
+ return { installState: 'complete', kbId: state.kbId, created, repaired, skipped }
1445
+ }
1446
+
1447
+ async function init() {
1448
+ const gate = await configGate()
1449
+ if (!gate.ok) {
1450
+ // kb_init 的 output schema 要求 installState,失败返回也必须带上
1451
+ return { ok: false, installState: 'blocked', reason: gate.refusal.reason, detail: gate.refusal.detail, recovery: gate.refusal.recovery }
1452
+ }
1453
+ const conf = gate.conf
1454
+ const root = kbRootOf(conf)
1455
+ // R2:init 也会写 .kbmeta(含 index 目录),必须与 create/update/check 共用同一把锁
1456
+ return withLock(root, () => withKbLock(root, 'init', async () => {
1457
+ const result = await initTo(root, conf)
1458
+ const health = await healthOf(conf)
1459
+ if (result.installState === 'complete') await writeBinding(result.kbId, root)
1460
+ return { ok: result.installState === 'complete', ...result, health }
1461
+ }))
1462
+ }
1463
+
1464
+ // ── 索引 ────────────────────────────────────────────────────────────
1465
+ const indexPath = (root) => catalogActive(root) ? path.join(root,'索引层','全文','entries.json') : path.join(root, '.kbmeta', 'index', 'entries.json')
1466
+ async function indexStorageGuard(root) {
1467
+ for (const file of [indexPath(root), path.join(path.dirname(indexPath(root)), 'snapshots')]) {
1468
+ const guard = await checkRealPath(root, file)
1469
+ if (!guard.ok) return guard
1470
+ }
1471
+ return { ok: true }
1472
+ }
1473
+
1474
+ async function readIndex(conf) {
1475
+ const res = await readIndexState(indexPath(kbRootOf(conf)))
1476
+ if (res.state === 'ok') {
1477
+ if (!res.value || !Array.isArray(res.value.entries)) return { state: 'corrupt', entries: [] }
1478
+ return { state: 'ok', ...res.value, entries: res.value.entries.filter(e => e && typeof e.path === 'string') }
1479
+ }
1480
+ return { state: res.state, entries: [] }
1481
+ }
1482
+
1483
+ async function writeIndex(conf, entries, options = {}) {
1484
+ const payload = { generatedAt: nowIso(), meta: await indexMetaOf(conf, entries), entries }
1485
+ const root = kbRootOf(conf)
1486
+ if (root === null) return { ok: false, reason: 'unbound' }
1487
+ const guard = await indexStorageGuard(root)
1488
+ if (!guard.ok) throw Object.assign(new Error(guard.detail), { code: guard.reason })
1489
+ const currentConf = await getConfigFresh()
1490
+ if (kbRootOf(currentConf) !== root || currentConf.revision !== conf.revision) throw Object.assign(new Error('绑定或配置已改变,索引未替换'), { code: 'binding-changed' })
1491
+ const disk = await diskFingerprint(conf)
1492
+ if (disk.error || disk.fingerprint !== fingerprintOf(entries)) throw Object.assign(new Error('扫描期间文件发生变化或不可读,旧索引已保留'), { code: 'source-unstable' })
1493
+ const old = await readIndexState(indexPath(root))
1494
+ if (old.state === 'ok' && Array.isArray(old.value?.entries) && typeof old.value.meta?.kbId === 'string' && old.value.meta.kbId.trim() && old.value.meta.kbId !== payload.meta.kbId) throw Object.assign(new Error('索引知识库身份不匹配'), { code: 'index-kbid-mismatch' })
1495
+ const oldCount = Array.isArray(old.value?.entries) ? old.value.entries.filter(e => e && typeof e.path === 'string').length : 0
1496
+ const drop = oldCount - entries.length
1497
+ const token = sha12(Buffer.from(JSON.stringify([old.value?.meta?.fingerprint, payload.meta.fingerprint, oldCount, entries.length])))
1498
+ const nextPaths = new Set(entries.map(e => e.path)), known = new Set(options.knownRemovedPaths || [])
1499
+ const onlyKnownRemovals = known.size > 0 && (old.value?.entries || []).filter(e => e && typeof e.path === 'string' && !nextPaths.has(e.path)).every(e => known.has(e.path))
1500
+ if ((oldCount > 0 && !entries.length || oldCount >= 20 && drop / oldCount >= .2) && options.confirmDrop !== token && !onlyKnownRemovals) {
1501
+ throw Object.assign(new Error('条目数量明显下降,已保留旧索引;请核对差异后确认'), { code: 'index-drop-confirmation', confirmationToken: token, oldCount, newCount: entries.length })
1502
+ }
1503
+ if (options.snapshot !== false && old.state === 'ok' && validIndexPayload(old.value) && old.value.meta?.kbId === payload.meta.kbId) {
1504
+ const directory = path.join(path.dirname(indexPath(root)), 'snapshots')
1505
+ await mkdir(directory, { recursive: true })
1506
+ const name = `${Date.now()}-${crypto.randomBytes(4).toString('hex')}.json`
1507
+ await atomicJsonStream(path.join(directory, name), old.value)
1508
+ const snapshots = (await readdir(directory)).filter(n => /^\d+-[a-f0-9]+\.json$/.test(n)).sort().reverse()
1509
+ for (const file of snapshots.slice(3)) await rm(path.join(directory, file), { force: true }).catch(() => {})
1510
+ }
1511
+ await mkdir(path.dirname(indexPath(root)),{recursive:true})
1512
+ await atomicJsonStream(indexPath(root), payload, { beforePublish: async () => {
1513
+ const current = await getConfigFresh(), live = await diskFingerprint(conf, true)
1514
+ if (kbRootOf(current) !== root || current.revision !== conf.revision || live.error || live.fingerprint !== payload.meta.fingerprint) throw Object.assign(new Error('提交前资料或配置已改变,旧索引已保留'), { code: 'source-unstable' })
1515
+ } })
1516
+ indexCache.delete(indexPath(root)); ioMetrics.indexCommits++
1517
+ return payload
1518
+ }
1519
+
1520
+ async function purgePolicyIndex({ expectedRoot, expectedKbId } = {}) {
1521
+ const conf = await getConfigFresh(), root = kbRootOf(conf)
1522
+ if (expectedRoot && await realpath(root) !== await realpath(expectedRoot) || expectedKbId && (await readMeta(root)).value?.kbId !== expectedKbId) throw Object.assign(new Error('知识库绑定已变化,未清理索引'), { code: 'BINDING_CHANGED' })
1523
+ return withLock(root, () => withKbLock(root, 'index-policy-purge', async () => {
1524
+ const current = await getConfigFresh()
1525
+ if (kbRootOf(current) !== root || current.revision !== conf.revision) throw Object.assign(new Error('知识库绑定已变化,未清理索引'), { code: 'BINDING_CHANGED' })
1526
+ const guard = await indexStorageGuard(root)
1527
+ if (!guard.ok) throw Object.assign(new Error(guard.detail), { code: guard.reason })
1528
+ const old = await readIndexState(indexPath(root)), policy = readIndexPolicy(root)
1529
+ if (old.value?.meta?.kbId && old.value.meta.kbId !== (await readMeta(root)).value?.kbId) throw Object.assign(new Error('索引知识库身份不一致,未修改'), { code: 'index-kbid-mismatch' })
1530
+ if (old.state === 'ok' && Array.isArray(old.value?.entries)) {
1531
+ const entries = old.value.entries.filter(e => !policyExcluded(policy, e.path))
1532
+ await commitIndex(indexPath(root), { generatedAt: nowIso(), entries, meta: await indexMetaOf(conf, entries) })
1533
+ }
1534
+ // Disposable index history must not retain excluded text or restore it later.
1535
+ const directory = path.join(path.dirname(indexPath(root)), 'snapshots')
1536
+ for (const name of await readdir(directory).catch(e => { if (e.code === 'ENOENT') return []; throw e })) {
1537
+ if (!/^\d+-[a-f0-9]+\.json$/.test(name)) continue
1538
+ const checked = await checkRealPath(root, path.join(directory, name))
1539
+ if (!checked.ok) throw new Error(checked.detail)
1540
+ await rm(path.join(directory, name))
1541
+ }
1542
+ indexCache.clear()
1543
+ return { ok: true }
1544
+ }))
1545
+ }
1546
+
1547
+ let maintenanceState = { state: 'idle', reason: null, lastCompletedAt: null, diff: null }
1548
+ const maintenanceStatus = () => ({ ...maintenanceState })
1549
+ async function maintainIndex({ expectedKbId, expectedRevision, paths = [], full = false, confirmDrop, knownRemovedPaths = [], automatic = false, signal } = {}) {
1550
+ const gate = await configGate()
1551
+ if (!gate.ok) return { ok: false, reason: gate.refusal.reason }
1552
+ const conf = gate.conf, root = kbRootOf(conf)
1553
+ if (!root) return { ok: false, reason: 'unbound' }
1554
+ const storage = await indexStorageGuard(root)
1555
+ if (!storage.ok) return { ...storage, indexPreserved: true }
1556
+ const configLock = await acquireConfigLock('index-maintenance')
1557
+ if (!configLock.ok) return { ok: false, reason: 'config-lock-timeout' }
1558
+ try { return await withLock(root, () => withKbLock(root, 'index-maintenance', async () => {
1559
+ try {
1560
+ const current = await getConfigFresh(), health = await healthOf(current)
1561
+ const meta = await readMeta(root)
1562
+ if (kbRootOf(current) !== root || current.revision !== conf.revision || expectedRevision != null && expectedRevision !== current.revision || expectedKbId && meta.value?.kbId !== expectedKbId) return { ok: false, reason: 'binding-changed' }
1563
+ if (!health.healthy || current.degraded || automatic && current.autoIndex === false) return { ok: false, reason: 'maintenance-disabled-or-unhealthy' }
1564
+ await reconcileImportedSources(root, meta.value?.kbId)
1565
+ if(catalogActive(root))await refreshCatalog({root,st:{kbId:meta.value.kbId},privateDirs:effectivePrivateDirs(conf.privateDirs,derivedPrivatePartitions(await readImportSources(root))),core:{_internal:{parseFrontmatter}}},{paths})
1566
+ maintenanceState = { ...maintenanceState, state: 'running', reason: null }
1567
+ const snap = await indexSnapshot(conf)
1568
+ if (snap.freshness.reason === 'index-kbid-mismatch') throw Object.assign(new Error('索引身份不一致,未自动替换'), { code: 'index-kbid-mismatch' })
1569
+ const incremental = !full && snap.state === 'ok' && validIndexPayload(snap.payload) && ['ok', 'index-stale-content', 'index-excludes-changed'].includes(snap.freshness.reason)
1570
+ let entries = [], errors = [], metadataChanged = false
1571
+ // Damaged/legacy cache rows must never prevent a full source scan.
1572
+ const comparable = snap.entries.filter(e => e && typeof e.path === 'string' && typeof e.revision === 'string')
1573
+ const previous = new Map(comparable.map(e => [e.path, e]))
1574
+ if (incremental) {
1575
+ const files = await walkMd(root, excludesOf(conf), root, [], errors, [])
1576
+ const dirty = new Set(paths.map(p => toPosix(p)))
1577
+ let processed = 0
1578
+ for (const file of files) {
1579
+ if (++processed % 50 === 0) await cfg.resources?.checkpoint(signal)
1580
+ if (signal?.aborted) throw Object.assign(new Error('维护已取消'), { code: 'canceled' })
1581
+ const rel = toPosix(path.relative(root, file)), before = await stat(file), old = previous.get(rel)
1582
+ if (old && old.size === before.size && old.mtimeMs === before.mtimeMs && old.ctimeMs === before.ctimeMs && ![...dirty].some(p=>rel===p||rel.startsWith(p+'/'))) entries.push(old)
1583
+ else {
1584
+ const buf = await readFile(file), after = await stat(file)
1585
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || buf.length !== after.size) throw Object.assign(new Error('文件仍在写入'), { code: 'source-unstable' })
1586
+ entries.push(entryFromBuffer(rel, file, buf, after.mtimeMs, after.ctimeMs)); metadataChanged = true
1587
+ }
1588
+ }
1589
+ } else {
1590
+ const scanned = await scanDisk(conf, root)
1591
+ entries = scanned.entries; errors = scanned.scanErrors
1592
+ }
1593
+ if (errors.length) throw Object.assign(new Error('扫描不完整,保留旧索引'), { code: 'scan-incomplete' })
1594
+ const next = new Map(entries.map(e => [e.path, e]))
1595
+ const diff = { added: entries.filter(e => !previous.has(e.path)).map(e => e.path), removed: comparable.filter(e => !next.has(e.path)).map(e => e.path), changed: entries.filter(e => previous.has(e.path) && previous.get(e.path).revision !== e.revision).map(e => e.path) }
1596
+ const changed = diff.added.length + diff.removed.length + diff.changed.length
1597
+ maintenanceState = { ...maintenanceState, diff, indexedAtBefore: snap.generatedAt || null }
1598
+ if (signal?.aborted) throw Object.assign(new Error('维护已取消'), { code: 'canceled' })
1599
+ let mode = 'unchanged'
1600
+ if (!incremental || changed || metadataChanged || snap.freshness.reason === 'index-excludes-changed') {
1601
+ await writeIndex(conf, entries, { confirmDrop, knownRemovedPaths, snapshot: !incremental || Boolean(changed) })
1602
+ mode = !incremental ? 'full' : changed ? 'incremental' : 'metadata'
1603
+ }
1604
+ maintenanceState = { state: 'synced', reason: null, mode, lastCompletedAt: nowIso(), diff, entries: entries.length }
1605
+ if (mode !== 'unchanged') await writeLog('info', `索引维护 ${mode} entries=${entries.length} added=${diff.added.length} removed=${diff.removed.length} changed=${diff.changed.length}`)
1606
+ return { ok: true, execution: 'ok', indexWritten: mode !== 'unchanged', mode, entries: entries.length, diff, ...maintenanceState }
1607
+ } catch (e) {
1608
+ maintenanceState = { ...maintenanceState, state: 'failed', reason: e.code || 'maintenance-failed', detail: e.message, confirmationToken: e.confirmationToken, oldCount: e.oldCount, newCount: e.newCount }
1609
+ await writeLog('warn', `索引维护未替换旧索引 reason=${maintenanceState.reason}`)
1610
+ return { ok: false, ...maintenanceState, indexPreserved: true }
1611
+ }
1612
+ })) } finally { await releaseConfigLock(configLock.token) }
1613
+ }
1614
+
1615
+ async function indexSnapshots({ restore, expectedKbId } = {}) {
1616
+ const gate = await configGate()
1617
+ if (!gate.ok) return { ok: false, reason: gate.refusal.reason }
1618
+ const conf = gate.conf, root = kbRootOf(conf)
1619
+ if (!root) return { ok: false, reason: 'unbound' }
1620
+ const storage = await indexStorageGuard(root)
1621
+ if (!storage.ok) return storage
1622
+ const configLock = await acquireConfigLock('index-snapshot')
1623
+ if (!configLock.ok) return { ok: false, reason: 'config-lock-timeout' }
1624
+ try { return await withLock(root, () => withKbLock(root, 'index-snapshot', async () => {
1625
+ const meta = await readMeta(root)
1626
+ if (expectedKbId && expectedKbId !== meta.value?.kbId) return { ok: false, reason: 'binding-changed' }
1627
+ const directory = path.join(path.dirname(indexPath(root)), 'snapshots')
1628
+ const names = await readdir(directory).catch(e => { if (e.code === 'ENOENT') return []; throw e })
1629
+ const files = names.filter(n => /^\d+-[a-f0-9]+\.json$/.test(n)).sort().reverse()
1630
+ for (const file of files) { const guard = await checkRealPath(root, path.join(directory, file)); if (!guard.ok) return guard }
1631
+ if (!restore) return { ok: true, snapshots: await Promise.all(files.map(async name => { const r = await readJsonState(path.join(directory, name)); return { name, generatedAt: r.value?.generatedAt, entries: r.value?.entries?.length } })) }
1632
+ if (!files.includes(restore)) return { ok: false, reason: 'snapshot-not-found' }
1633
+ const r = await readJsonState(path.join(directory, restore)), current = await getConfigFresh()
1634
+ if (r.state !== 'ok' || !validIndexPayload(r.value) || r.value.meta?.kbId !== meta.value?.kbId || current.revision !== conf.revision || kbRootOf(current) !== root) return { ok: false, reason: 'snapshot-invalid-or-binding-changed' }
1635
+ const disabled = { ...current, autoIndex: false, revision: (current.revision ?? 1) + 1, updatedAt: nowIso() }
1636
+ await atomicWrite(configFile, JSON.stringify(disabled, null, 2))
1637
+ config = disabled
1638
+ const entries = r.value.entries.filter(e => !policyExcluded(readIndexPolicy(root), e.path))
1639
+ await commitIndex(indexPath(root), { ...r.value, entries, meta: await indexMetaOf(disabled, entries) })
1640
+ maintenanceState = { state: 'restored', reason: 'snapshot-restored', lastCompletedAt: nowIso() }
1641
+ return { ok: true, note: '仅恢复索引缓存,未恢复或修改原文;自动维护已关闭' }
1642
+ })) } finally { await releaseConfigLock(configLock.token) }
1643
+ }
1644
+
1645
+ /** 对**指定根目录**写索引(R6:初始化新库时当前绑定还没切,不能用 kbRootOf(conf)) */
1646
+ async function writeIndexAtRoot(root, conf, entries) {
1647
+ await mkdir(path.dirname(indexPath(root)), { recursive: true })
1648
+ const payload = { generatedAt: nowIso(), meta: await indexMetaOf(conf, entries, root), entries }
1649
+ await commitIndex(indexPath(root), payload)
1650
+ return payload
1651
+ }
1652
+
1653
+ /**
1654
+ * R6 / R1:在**指定目录**建库或补齐(不切换当前绑定、不写 binding.json)。
1655
+ * 用于:
1656
+ * · setup 新建空库(先建好、验证健康,再 bind 切库);
1657
+ * · 导入任务的目标库(任务有自己的 core,不应借道当前绑定)。
1658
+ * rebuildIndex=true 时若索引不存在则写一份**有效空索引**(避免"刚建好就提示要重建")。
1659
+ */
1660
+ async function initializeLibrary(kbPathIn, options = {}) {
1661
+ const raw = String(kbPathIn ?? '').trim()
1662
+ if (raw === '') return { ok: false, reason: 'empty-path', error: '路径为空' }
1663
+ if (!path.isAbsolute(raw)) return { ok: false, reason: 'relative-path', error: '请传绝对路径' }
1664
+ const target = path.resolve(raw)
1665
+ const gate = await configGate()
1666
+ if (!gate.ok && gate.refusal.reason === 'config-degraded') return { ok: false, ...gate.refusal }
1667
+ const conf = gate.conf
1668
+ const st = await stat(target).catch(() => null)
1669
+ if (st !== null && !st.isDirectory()) return { ok: false, reason: 'not-a-directory', error: '目标不是文件夹' }
1670
+ if (st === null) {
1671
+ try {
1672
+ await mkdir(target, { recursive: true })
1673
+ } catch (error) {
1674
+ return { ok: false, reason: 'mkdir-failed', error: String((error && (error.code || error.message)) ?? error) }
1675
+ }
1676
+ }
1677
+ const freshSetup = options.freshSetup === true
1678
+ const initResult = await withLock(target, () => withKbLock(target, 'bind-init', async () => initTo(target, conf, { freshSetup }), { freshSetup }))
1679
+ if (initResult.installState !== 'complete') {
1680
+ return { ok: false, reason: 'init-incomplete', error: '初始化未完成:' + (initResult.reason ?? initResult.detail ?? initResult.installState), init: initResult }
1681
+ }
1682
+ let indexWritten = false
1683
+ if (options.rebuildIndex === true && !existsSync(indexPath(target))) {
1684
+ await writeIndexAtRoot(target, conf, [])
1685
+ indexWritten = true
1686
+ }
1687
+ const health = await healthOf(conf, target)
1688
+ return {
1689
+ ok: true,
1690
+ kbPath: toPosix(target),
1691
+ kbId: initResult.kbId ?? null,
1692
+ initialized: true,
1693
+ indexWritten,
1694
+ health,
1695
+ created: initResult.created,
1696
+ repaired: initResult.repaired,
1697
+ }
1698
+ }
1699
+
1700
+ async function walkMd(root, exclude, dir = root, acc = [], errors = [], links = [], policy = readIndexPolicy(root)) {
1701
+ const originalMode=catalogActive(root)
1702
+ if(dir===root&&originalMode)exclude=[...exclude,...(await readCatalog(root)).references.map(r=>r.path)]
1703
+ let items = []
1704
+ try {
1705
+ items = await readdir(dir, { withFileTypes: true })
1706
+ } catch (error) {
1707
+ // R4:目录枚举错误必须回传(以前这个 errors 数组被调用方丢掉,扫描不完整也当成功)
1708
+ errors.push(`${toPosix(path.relative(root, dir)) || '.'}: ${(error && (error.code || error.message)) ?? error}`)
1709
+ return acc
1710
+ }
1711
+ for (const item of items) {
1712
+ const full = path.join(dir, item.name)
1713
+ const rel = toPosix(path.relative(root, full))
1714
+ if (exclude.some((e) => rel === e || rel.startsWith(e + '/') || item.name === e)) continue
1715
+ // 2026-10-17:导航文件不算条目(与库自己的 kb-check.ps1 的 $NavFiles 对齐)。
1716
+ // · INDEX.md 在任何层级都是导航(根索引 + 各板块索引),一律跳过;
1717
+ // · AGENTS.md / README.md / 知识库清单.md **只在根目录**跳过 ——
1718
+ // 子目录里的 README.md(如 10-项目/每日信息/README.md 交付台账)仍是条目。
1719
+ if (item.name === 'INDEX.md' || (dir === root && ROOT_NAV_FILES.has(item.name))) continue
1720
+ // P1-A:链接/重解析点一律跳过,并登记(以前是静默忽略,无法说明覆盖范围)
1721
+ if (item.isSymbolicLink()) {
1722
+ links.push(rel)
1723
+ continue
1724
+ }
1725
+ if (item.isDirectory()) await walkMd(root, exclude, full, acc, errors, links, policy)
1726
+ else if ((item.name.endsWith('.md') || (originalMode || rel.startsWith('90-收件箱/')) && SOURCE_TEXT.test(rel)) && !item.name.includes('.tmp-') && !policyExcluded(policy, rel)) acc.push(full)
1727
+ }
1728
+ return acc
1729
+ }
1730
+
1731
+ /** 只 stat 不读内容的指纹(用于"外部是否改过"的廉价检测) */
1732
+ function diskFingerprint(conf, fresh = false) {
1733
+ const key = JSON.stringify([kbRootOf(conf), excludesOf(conf)])
1734
+ if (!fresh && diskPending.has(key)) { ioMetrics.diskMerged++; return diskPending.get(key) }
1735
+ ioMetrics.diskScans++
1736
+ const pending = scanDiskFingerprint(conf).finally(() => { if (diskPending.get(key) === pending) diskPending.delete(key) })
1737
+ if (!fresh) diskPending.set(key, pending)
1738
+ return pending
1739
+ }
1740
+ async function scanDiskFingerprint(conf) {
1741
+ const root = kbRootOf(conf)
1742
+ const dirErrors = []
1743
+ const links = []
1744
+ let files = []
1745
+ try {
1746
+ files = await walkMd(root, excludesOf(conf), root, [], dirErrors, links)
1747
+ } catch (error) {
1748
+ return { error: String((error && error.message) ?? error), files: 0 }
1749
+ }
1750
+ if (dirErrors.length > 0) return { error: `目录枚举失败:${dirErrors[0]}`, files: files.length }
1751
+ const rows = []
1752
+ for (const file of files) {
1753
+ const rel = toPosix(path.relative(root, file))
1754
+ if (rel === 'INDEX.md') continue
1755
+ const st = await stat(file).catch(() => null)
1756
+ if (st === null) return { error: `无法读取文件属性:${rel}`, files: files.length }
1757
+ rows.push({ path: rel, size: st.size, mtimeMs: st.mtimeMs })
1758
+ }
1759
+ return { fingerprint: fingerprintOf(rows), files: rows.length }
1760
+ }
1761
+
1762
+ async function scanDisk(conf, root) {
1763
+ const links = []
1764
+ const dirErrors = []
1765
+ const files = await walkMd(root, excludesOf(conf), root, [], dirErrors, links)
1766
+ const entries = []
1767
+ const scanErrors = [...dirErrors]
1768
+ for (const file of files) {
1769
+ const rel = toPosix(path.relative(root, file))
1770
+ if (rel === 'INDEX.md') continue
1771
+ try {
1772
+ const before = await stat(file)
1773
+ const buf = await readFile(file)
1774
+ const st = await stat(file)
1775
+ if (before.size !== st.size || before.mtimeMs !== st.mtimeMs || buf.length !== st.size) throw new Error('文件扫描期间发生变化')
1776
+ entries.push(entryFromBuffer(rel, file, buf, st ? st.mtimeMs : 0, st?.ctimeMs))
1777
+ } catch (error) {
1778
+ scanErrors.push(`${rel}: ${(error && (error.code || error.message)) ?? error}`)
1779
+ }
1780
+ }
1781
+ return { entries, scanErrors, scannedFiles: files.length, skippedLinks: links }
1782
+ }
1783
+
1784
+ /**
1785
+ * 重建索引(调用方必须已持库级锁)。
1786
+ * R4:扫描不完整时**不得**用不完整结果覆盖完整索引 —— 保留旧索引并如实报 partial。
1787
+ */
1788
+ async function reindexLocked(conf) {
1789
+ const root = kbRootOf(conf)
1790
+ const { entries, scanErrors, scannedFiles, skippedLinks } = await scanDisk(conf, root)
1791
+ if (scanErrors.length > 0) {
1792
+ await writeLog('warn', `索引未重建:扫描不完整(${scanErrors.length} 处错误,已扫描 ${scannedFiles} 个 .md),保留旧索引`)
1793
+ return { ok: false, partial: true, indexPreserved: true, reason: 'scan-incomplete', entries: [], scanErrors, scannedFiles, skippedLinks }
1794
+ }
1795
+ const payload = await writeIndex(conf, entries)
1796
+ await writeLog('info', `索引重建:${entries.length} 条(扫描 ${scannedFiles} 个 .md)`)
1797
+ return { ok: true, ...payload, scanErrors, scannedFiles, skippedLinks }
1798
+ }
1799
+
1800
+ /** 公开重建入口:自己上锁(在锁内调用请用 reindexLocked) */
1801
+ async function reindex() {
1802
+ const conf = await getConfig()
1803
+ const root = kbRootOf(conf)
1804
+ return withLock(root, () => withKbLock(root, 'reindex', () => reindexLocked(conf)))
1805
+ }
1806
+
1807
+ // ── R4:幂等请求标识(重试不重复建条目)────────────────────────────
1808
+ // 落盘 .kbmeta/requests.json。只对自己「上次没写完」的同一个请求做续做;
1809
+ // **不按标题合并已完成条目**(用户主动再建 = 新请求)。
1810
+ const requestsFileOf = (root) => path.join(root, '.kbmeta', 'requests.json')
1811
+ const REQUESTS_KEEP = 200
1812
+ const REQUESTS_TTL_MS = 7 * 24 * 3600 * 1000
1813
+
1814
+ async function readRequests(root) {
1815
+ const res = await readJsonState(requestsFileOf(root))
1816
+ if (res.state === 'ok' && res.value && typeof res.value.items === 'object' && res.value.items !== null) {
1817
+ return { items: res.value.items }
1818
+ }
1819
+ return { items: {} }
1820
+ }
1821
+
1822
+ async function saveRequests(root, store) {
1823
+ const now = Date.now()
1824
+ const keys = Object.keys(store.items)
1825
+ // 先丢"已完成且过期"的,再按时间保留最近 N 条;partial 的一律留着(它是恢复证据)
1826
+ for (const key of keys) {
1827
+ const it = store.items[key]
1828
+ const at = Date.parse(it && it.at)
1829
+ if (it && it.partial !== true && Number.isFinite(at) && now - at > REQUESTS_TTL_MS) delete store.items[key]
1830
+ }
1831
+ const rest = Object.keys(store.items)
1832
+ if (rest.length > REQUESTS_KEEP) {
1833
+ rest
1834
+ .filter((k) => store.items[k].partial !== true)
1835
+ .sort((a, b) => String(store.items[a].at).localeCompare(String(store.items[b].at)))
1836
+ .slice(0, rest.length - REQUESTS_KEEP)
1837
+ .forEach((k) => delete store.items[k])
1838
+ }
1839
+ await atomicWrite(requestsFileOf(root), JSON.stringify({ schemaVersion: 1, items: store.items }))
1840
+ }
1841
+
1842
+ function contentHashOf(text) {
1843
+ return sha12(Buffer.from(String(text ?? ''), 'utf8'))
1844
+ }
1845
+
1846
+ // ── 写入(D:路径边界 + 强制版本;E:互斥 + 部分完成)───────────────
1847
+ async function createEntry(args) {
1848
+ return args.expectedBinding ? withExpectedBinding(args, 'flow-create', () => createEntryUnchecked(args)) : createEntryUnchecked(args)
1849
+ }
1850
+
1851
+ async function withExpectedBinding(args, label, write) {
1852
+ // Flows snapshot their destination. Validate and hold the same config lock
1853
+ // used by commitBind, so a switch cannot redirect a running report.
1854
+ if (args.expectedBinding) {
1855
+ const lock = await acquireConfigLock(label)
1856
+ if (!lock.ok) return { ok: false, reason: lock.reason ?? 'config-lock-timeout' }
1857
+ try {
1858
+ const gate = await configGate()
1859
+ if (!gate.ok) return { ok: false, reason: gate.refusal.reason }
1860
+ const expected = args.expectedBinding
1861
+ const root = kbRootOf(gate.conf)
1862
+ const meta = await readMeta(root)
1863
+ if (normAbs(root) !== normAbs(expected.kbPath) || meta.state !== 'ok' || meta.value.kbId !== expected.kbId
1864
+ || (expected.revision != null && gate.conf.revision !== expected.revision)) {
1865
+ return { ok: false, reason: 'flow-binding-changed', detail: '流程目标库或配置版本已改变,未写入报告' }
1866
+ }
1867
+ args.signal?.throwIfAborted()
1868
+ return await write()
1869
+ } finally {
1870
+ await releaseConfigLock(lock.token)
1871
+ }
1872
+ }
1873
+ return write()
1874
+ }
1875
+
1876
+ async function createEntryUnchecked(args) {
1877
+ // C1:写入口必须强制重读并校验配置,不能吃 status 留下的缓存
1878
+ const gate = await configGate()
1879
+ if (!gate.ok) return { ok: false, entryId: null, reason: gate.refusal.reason, detail: gate.refusal.detail }
1880
+ const conf = gate.conf
1881
+ const root = kbRootOf(conf)
1882
+ const health = await healthOf(conf)
1883
+ if (!health.healthy) {
1884
+ return {
1885
+ ok: false,
1886
+ reason: 'not-initialized',
1887
+ detail: `知识库不可用(${health.reason}${health.detail ? ': ' + health.detail : ''})。请先 kb_bind(新目录需 confirmInit=true)或 kb_init 补齐。`,
1888
+ }
1889
+ }
1890
+ const kind = args.kind ?? '知识'
1891
+ const category = KIND_TO_CATEGORY[kind]
1892
+ if (!category) return { ok: false, reason: 'bad-kind', detail: `可用:${Object.keys(KIND_TO_CATEGORY).join(' / ')}` }
1893
+ const requestIdIn = typeof args.requestId === 'string' && args.requestId.trim() !== '' ? args.requestId.trim() : null
1894
+ const titleIn = String(args.title ?? '')
1895
+ const contentHash = contentHashOf(args.content)
1896
+ return withLock(root, () => withKbLock(root, 'create', async () => {
1897
+ const store = await readRequests(root)
1898
+ // R4:重试同一个请求 → 返回原结果并继续未完成步骤(绝不新建第二个条目)
1899
+ let reqId = requestIdIn
1900
+ let resume = reqId !== null && store.items[reqId] ? store.items[reqId] : null
1901
+ if (resume === null) {
1902
+ // 没带 requestId 时,只认「上一次 partial 且文件仍在」的同一请求;
1903
+ // 不按标题合并已完成条目(用户主动再建 = 新请求)。
1904
+ const cand = Object.values(store.items).find(
1905
+ (it) => it && it.op === 'create' && it.partial === true && it.title === titleIn && it.contentHash === contentHash && typeof it.path === 'string' && existsSync(path.join(root, it.path)),
1906
+ )
1907
+ if (cand) { resume = cand; reqId = cand.requestId }
1908
+ }
1909
+ if (resume !== null) {
1910
+ resume = { ...resume, path: resolveAssetPath(root, resume.path) }
1911
+ // F1:同一 requestId 的**不同 payload** 必须拒绝,而不是返回旧结果
1912
+ if (requestIdIn !== null && (resume.title !== titleIn || (typeof resume.contentHash === 'string' && resume.contentHash !== contentHash))) {
1913
+ await writeLog('warn', `create 拒绝:requestId=${reqId} 的 payload 与上次不同`)
1914
+ return { ok: false, reason: 'request-payload-mismatch', requestId: reqId, detail: '同一 requestId 的标题/正文与上次不同:请为新内容使用新的 requestId(旧结果不能代表新内容)' }
1915
+ }
1916
+ const abs = path.join(root, resume.path)
1917
+ const buf = await readFile(abs)
1918
+ let indexSynced = true
1919
+ let indexMode = 'incremental'
1920
+ try {
1921
+ const synced = await updateIndexFor(conf, resume.path, 'upsert')
1922
+ indexMode = synced.mode
1923
+ if (synced.mode === 'failed') indexSynced = false
1924
+ } catch (error) {
1925
+ indexSynced = false
1926
+ indexMode = 'failed'
1927
+ await appendFile(path.join(root, '.kbmeta', 'recover-todo.log'), `${nowIso()}\t${resume.entryId}\t${resume.path}\treindex-failed\n`, 'utf8')
1928
+ await writeLog('warn', `create 重试后索引仍失败(条目已在):${String(error)}`)
1929
+ }
1930
+ store.items[resume.requestId] = { ...resume, op: 'create', title: titleIn, contentHash, partial: !indexSynced, indexSynced, at: nowIso() }
1931
+ await saveRequests(root, store)
1932
+ await writeLog('info', `create 同一请求重试 → 复用 entryId=${resume.entryId}(${indexSynced ? '已补索引' : '索引仍失败'})`)
1933
+ return {
1934
+ ok: true, resumed: true, deduplicated: true, partial: !indexSynced,
1935
+ indexSynced, indexMode, recoveryPending: !indexSynced,
1936
+ entryId: resume.entryId, revision: sha12(buf), path: resume.path,
1937
+ }
1938
+ }
1939
+ const entryId = 'kb-' + crypto.randomBytes(4).toString('hex')
1940
+ const sources = (Array.isArray(args.source) ? args.source : args.source ? [args.source] : []).map(p => resolveAssetPath(root, p))
1941
+ const source = sources.find(p => excludedSource(root, p)) || sources[0] || null
1942
+ const excludeIndex = source && excludedSource(root, source)
1943
+ const archiveCategory = excludeIndex ? EXCLUDED_PARTITION + '/' + category : category
1944
+ const dir = path.join(root, archiveCategory)
1945
+ if (!isInside(root, dir)) return { ok: false, reason: 'path-escape', detail: category }
1946
+ // P1-A:分类目录若是链接/重解析点(或指到库外),拒绝写入
1947
+ const dirCheck = await checkRealPath(root, dir, { followLinks: conf.followLinks })
1948
+ if (!dirCheck.ok) {
1949
+ await writeLog('warn', `拒绝写入(分类目录真实路径异常):${category} ${dirCheck.reason} ${dirCheck.detail}`)
1950
+ return { ok: false, reason: dirCheck.reason, detail: `分类目录 ${category}:${dirCheck.detail}` }
1951
+ }
1952
+ await mkdir(dir, { recursive: true })
1953
+ // 2026-10-18(flows 落库用):可选 tz / status。
1954
+ // 缺省行为**逐字不变**(tz 为空 → 仍用 today()=UTC 日期;status 为空 → 仍写"进行中"),
1955
+ // 因此既有调用方零影响;流程执行器传入 outputRules.tz 后,
1956
+ // 文件名前缀与 frontmatter 的 created/updated 会**用同一个时区**取日期(不再一处 UTC 一处本地)。
1957
+ const tzIn = typeof args.tz === 'string' && args.tz.trim() !== '' ? args.tz.trim() : ''
1958
+ const statusIn = typeof args.status === 'string' && args.status.trim() !== '' ? args.status.trim() : '进行中'
1959
+ const dayStamp = tzIn === '' ? today() : dateInTz(nowIso(), tzIn)
1960
+ let file = path.join(dir, `${dayStamp}-${slugOf(args.title)}.md`)
1961
+ if (existsSync(file)) file = path.join(dir, `${dayStamp}-${slugOf(args.title)}-${entryId.slice(3)}.md`)
1962
+ if (!isInside(root, file)) return { ok: false, reason: 'path-escape', detail: toPosix(file) }
1963
+ const fileCheck = await checkRealPath(root, file, { followLinks: conf.followLinks })
1964
+ if (!fileCheck.ok) {
1965
+ await writeLog('warn', `拒绝写入(目标文件真实路径异常):${fileCheck.reason} ${fileCheck.detail}`)
1966
+ return { ok: false, reason: fileCheck.reason, detail: fileCheck.detail }
1967
+ }
1968
+ const data = {
1969
+ id: entryId,
1970
+ title: args.title,
1971
+ type: kind,
1972
+ tags: args.tags ?? [],
1973
+ status: statusIn,
1974
+ created: dayStamp,
1975
+ updated: dayStamp,
1976
+ }
1977
+ if (source) data.source = sources.length > 1 ? sources : source
1978
+ await atomicWrite(file, buildFile(data, String(args.content ?? '').trimEnd() + '\n'))
1979
+ const buf = await readFile(file)
1980
+ const relPath = toPosix(path.relative(root, file))
1981
+ for (const source of sources) await registerDerived(root, source, relPath, excludeIndex ? relPath.slice(EXCLUDED_PARTITION.length + 1) : relPath)
1982
+ const recId = reqId ?? entryId
1983
+ // P1-D/F:只更新自己那一条,不再整库重建;索引不可用才退回全量
1984
+ let indexMode = 'incremental'
1985
+ let partial = false
1986
+ try {
1987
+ const synced = await updateIndexFor(conf, relPath, 'upsert')
1988
+ indexMode = synced.mode
1989
+ if (synced.mode === 'failed') partial = true
1990
+ } catch (error) {
1991
+ partial = true
1992
+ indexMode = 'failed'
1993
+ await appendFile(path.join(root, '.kbmeta', 'recover-todo.log'), `${nowIso()}\t${entryId}\t${relPath}\treindex-failed\n`, 'utf8')
1994
+ await writeLog('warn', `create 后索引失败(条目已写入):${String(error)}`)
1995
+ }
1996
+ store.items[recId] = {
1997
+ requestId: recId, op: 'create', entryId, path: relPath, title: titleIn, contentHash,
1998
+ revision: sha12(buf), partial, indexSynced: !partial, at: nowIso(),
1999
+ }
2000
+ await saveRequests(root, store)
2001
+ if (partial) return { ok: true, partial: true, indexSynced: false, indexMode: 'failed', recoveryPending: true, entryId, revision: sha12(buf), path: relPath, requestId: recId }
2002
+ await writeLog('info', `create ${entryId} → ${relPath}`)
2003
+ return { ok: true, indexSynced: true, indexMode, entryId, revision: sha12(buf), path: relPath, requestId: recId }
2004
+ }))
2005
+ }
2006
+
2007
+ async function updateEntry(args) {
2008
+ return args.expectedBinding ? withExpectedBinding(args, 'parse-update', () => updateEntryUnchecked(args)) : updateEntryUnchecked(args)
2009
+ }
2010
+
2011
+ async function updateEntryUnchecked(args) {
2012
+ // C1:同上——配置损坏时 update 曾经仍按旧缓存写入
2013
+ const gate = await configGate()
2014
+ if (!gate.ok) return { ok: false, entryId: args?.entryId ?? null, reason: gate.refusal.reason, detail: gate.refusal.detail }
2015
+ const conf = gate.conf
2016
+ if (typeof args.expectedRevision !== 'string' || args.expectedRevision.trim() === '') {
2017
+ return { ok: false, reason: 'revision-required', detail: 'update 必须带非空 expectedRevision;先用 kb_search/kb_status 取当前 revision' }
2018
+ }
2019
+ if (typeof args.entryId !== 'string' || args.entryId.trim() === '') {
2020
+ return { ok: false, reason: 'entry-required', detail: 'update 必须带 entryId' }
2021
+ }
2022
+ const root = kbRootOf(conf)
2023
+ return withLock(root, () => withKbLock(root, 'update', async () => {
2024
+ const index = await readIndex(conf)
2025
+ if (index.state !== 'ok') {
2026
+ return { ok: false, reason: 'index-unavailable', detail: `索引状态=${index.state};先跑 kb_check(rebuild)再更新` }
2027
+ }
2028
+ let hit = index.entries.find((e) => e.entryId === args.entryId)
2029
+ if (!hit) {
2030
+ for (const f of Object.values(readIndexPolicy(root).groups).flatMap(g => g.files)) {
2031
+ if (!f.current.endsWith('.md')) continue
2032
+ const checked = await checkRealPath(root, path.join(root, f.current))
2033
+ if (!checked.ok) continue
2034
+ const bytes = await readFile(path.join(root, f.current)).catch(e => { if (e.code === 'ENOENT') return null; throw e })
2035
+ if (bytes && parseFrontmatter(bytes.toString('utf8')).data.id === args.entryId) { hit = { path: f.current }; break }
2036
+ }
2037
+ }
2038
+ if (!hit) return { ok: false, notFound: true, entryId: args.entryId, detail: '索引中没有这个 entryId' }
2039
+ if (path.isAbsolute(hit.path) || hit.path.includes('..') || !isInside(root, path.join(root, hit.path))) {
2040
+ await writeLog('warn', `拒绝越界路径 entryId=${args.entryId} path=${hit.path}`)
2041
+ return { ok: false, reason: 'path-escape', detail: `索引路径越出知识库:${hit.path}` }
2042
+ }
2043
+ const file = path.join(root, hit.path)
2044
+ if (!existsSync(file)) return { ok: false, notFound: true, entryId: args.entryId, detail: '索引有、文件已不在' }
2045
+ // P1-A:索引里的路径也必须通过真实路径校验(防索引被改成指向库外的 junction)
2046
+ const fileCheck = await checkRealPath(root, file, { followLinks: conf.followLinks })
2047
+ if (!fileCheck.ok) {
2048
+ await writeLog('warn', `拒绝更新(真实路径异常):${args.entryId} ${fileCheck.reason} ${fileCheck.detail}`)
2049
+ return { ok: false, reason: fileCheck.reason, detail: fileCheck.detail }
2050
+ }
2051
+ const buf = await readFile(file)
2052
+ const currentRevision = sha12(buf)
2053
+ const reqIdIn = typeof args.requestId === 'string' && args.requestId.trim() !== '' ? args.requestId.trim() : null
2054
+ // F1:把"这次要写的内容"也算进请求身份,避免同一 requestId 的不同 payload 被当成重试
2055
+ const payloadHash = sha256(Buffer.from(JSON.stringify({ content: typeof args.content === 'string' ? args.content : null, patch: args.patch ?? null }), 'utf8'))
2056
+ // R4:同一 requestId 重试 —— 若上次已经写成功(当前 revision 就是那次的结果),直接返回原结果
2057
+ if (reqIdIn !== null) {
2058
+ const store = await readRequests(root)
2059
+ const prev = store.items[reqIdIn]
2060
+ if (prev && prev.op === 'update' && prev.entryId === args.entryId) {
2061
+ if (typeof prev.payloadHash === 'string' && prev.payloadHash !== payloadHash) {
2062
+ await writeLog('warn', `update 拒绝:requestId=${reqIdIn} 的 payload 与上次不同`)
2063
+ return { ok: false, reason: 'request-payload-mismatch', requestId: reqIdIn, detail: '同一 requestId 的内容/patch 与上次不同:请为新内容使用新的 requestId' }
2064
+ }
2065
+ if (prev.revision === currentRevision) {
2066
+ await writeLog('info', `update 同一请求重试 → 返回原结果 entryId=${args.entryId}`)
2067
+ return {
2068
+ ok: true, deduplicated: true, resumed: true, entryId: prev.entryId, revision: prev.revision,
2069
+ path: hit.path, indexSynced: prev.indexSynced !== false, indexMode: prev.indexMode ?? 'incremental',
2070
+ partial: prev.indexSynced === false, recoveryPending: prev.indexSynced === false,
2071
+ }
2072
+ }
2073
+ }
2074
+ }
2075
+ if (args.expectedRevision !== currentRevision) {
2076
+ await writeLog('warn', `update 冲突 ${args.entryId}: 期望 ${args.expectedRevision} 实际 ${currentRevision}`)
2077
+ return { ok: false, conflict: true, entryId: args.entryId, currentRevision, currentPath: hit.path, diffSummary: `期望 revision ${args.expectedRevision},当前 ${currentRevision}(未写入任何内容)` }
2078
+ }
2079
+ const text0 = buf.toString('utf8')
2080
+ const parsed = parseFrontmatter(text0)
2081
+ if (!parsed.parts) {
2082
+ return { ok: false, reason: 'frontmatter-invalid', detail: `frontmatter 无法安全解析(${parsed.reason ?? '无 frontmatter'});为免毁坏数据,本次拒绝写回` }
2083
+ }
2084
+ // 2026-10-17:无 frontmatter id 的条目走派生 id(path → id),此处按**有效 id** 比对
2085
+ const effectiveId = parsed.data.id ?? derivedEntryId(hit.path)
2086
+ if (effectiveId !== args.entryId) {
2087
+ return { ok: false, reason: 'id-mismatch', detail: `索引 entryId=${args.entryId} 与文件有效 id=${effectiveId}(frontmatter id=${parsed.data.id ?? '(缺,按路径派生)'})不一致` }
2088
+ }
2089
+ // R3:认不出的结构(嵌套/缩进/块标量/注释/重复键…)一律在写盘前拒绝
2090
+ if (parsed.unsupported) return { ok: false, reason: 'unsupported-frontmatter', detail: parsed.unsupported + ';为避免毁坏数据,本次拒绝写回' }
2091
+ const data = { ...parsed.data }
2092
+ const changed = []
2093
+ if (typeof args.content === 'string') changed.push('content')
2094
+ if (args.patch && typeof args.patch === 'object') {
2095
+ for (const key of ['title', 'type', 'tags', 'status', 'source']) {
2096
+ if (args.patch[key] !== undefined) {
2097
+ if (key === 'type' && !ALLOWED_TYPES.includes(args.patch.type)) {
2098
+ return { ok: false, reason: 'bad-type', detail: `type 必须是 ${ALLOWED_TYPES.join(' / ')} 之一(收到 ${JSON.stringify(args.patch.type)})` }
2099
+ }
2100
+ data[key] = args.patch[key]
2101
+ changed.push(key)
2102
+ }
2103
+ }
2104
+ }
2105
+ if (changed.length === 0) return { ok: false, reason: 'no-change', detail: 'update 需要 content 或 patch 至少一项' }
2106
+ const sources = (Array.isArray(data.source) ? data.source : data.source ? [data.source] : []).map(p => resolveAssetPath(root, p))
2107
+ if (sources.some(p => excludedSource(root, p)) && !policyExcluded(readIndexPolicy(root), hit.path, false)) return { ok: false, reason: 'excluded-source-requires-new-entry', detail: '排除索引的来源不能覆盖正常索引条目,请为该资料新建排除分区条目' }
2108
+ for (const source of sources) await registerDerived(root, source, hit.path, hit.path.startsWith(EXCLUDED_PARTITION + '/') ? hit.path.slice(EXCLUDED_PARTITION.length + 1) : hit.path)
2109
+ data.updated = today()
2110
+ const backupDir = path.join(root, '.kbmeta', 'backups', nowIso().replace(/[:.]/g, '-'))
2111
+ await mkdir(backupDir, { recursive: true })
2112
+ await writeFile(path.join(backupDir, `${args.entryId}.${currentRevision}.md`), buf)
2113
+ // R3:只替换 frontmatter 区块;只改元数据时正文按原始字节拼回(CRLF/LF/混合都保留)
2114
+ await atomicWrite(file, composeWithHeader(parsed.parts, data, typeof args.content === 'string' ? args.content : undefined))
2115
+ const nextBuf = await readFile(file)
2116
+ let indexSynced = true
2117
+ let indexMode = 'incremental'
2118
+ try {
2119
+ const synced = await updateIndexFor(conf, hit.path, 'upsert')
2120
+ indexMode = synced.mode
2121
+ if (synced.mode === 'failed') indexSynced = false
2122
+ } catch (error) {
2123
+ indexSynced = false
2124
+ indexMode = 'failed'
2125
+ await appendFile(path.join(root, '.kbmeta', 'recover-todo.log'), `${nowIso()}\t${args.entryId}\t${hit.path}\treindex-failed\n`, 'utf8')
2126
+ await writeLog('warn', `update 后索引失败(条目已写入):${String(error)}`)
2127
+ }
2128
+ if (reqIdIn !== null) {
2129
+ const store = await readRequests(root)
2130
+ store.items[reqIdIn] = {
2131
+ requestId: reqIdIn, op: 'update', entryId: args.entryId, path: hit.path,
2132
+ revision: sha12(nextBuf), payloadHash, indexSynced, indexMode, partial: !indexSynced, at: nowIso(),
2133
+ }
2134
+ await saveRequests(root, store)
2135
+ }
2136
+ await writeLog('info', `update ${args.entryId} 字段=${changed.join(',')} rev ${currentRevision}→${sha12(nextBuf)}`)
2137
+ return { ok: true, partial: !indexSynced, indexSynced, indexMode, recoveryPending: !indexSynced, entryId: args.entryId, revision: sha12(nextBuf), path: hit.path, changed }
2138
+ }))
2139
+ }
2140
+
2141
+ // ── 检索(R1:索引全文 includes,语义与磁盘扫描逐字一致)────────────
2142
+ async function search(args) {
2143
+ const gate = await configGate()
2144
+ if (!gate.ok) {
2145
+ return { ok: false, reason: gate.refusal.reason, hits: [], coverageNote: gate.refusal.reason === 'unbound' ? '未绑定知识库,未检索。' : '配置降级,未检索。', detail: gate.refusal.detail }
2146
+ }
2147
+ const conf = gate.conf
2148
+ const root = kbRootOf(conf)
2149
+ const limit = Math.min(Math.max(Number(args.limit ?? 5), 1), 20)
2150
+ const query = String(args.query ?? '').trim()
2151
+ if (query === '') return { ok: false, reason: 'empty-query', hits: [], coverageNote: 'query 不能为空' }
2152
+ const lower = query.toLowerCase()
2153
+ const searchPolicyRevision = readIndexPolicy(root).revision
2154
+
2155
+ // 只读一次索引、只判一次新鲜度(P1 里这两步各读一遍索引)
2156
+ const snap = await indexSnapshot(conf)
2157
+ let entries = snap.entries
2158
+ let mode = 'index'
2159
+ let note = ''
2160
+ let generatedAt = snap.generatedAt ?? null
2161
+ if (snap.state !== 'ok' || !snap.freshness.fresh) {
2162
+ // R1:索引不能证明与磁盘一致时,**必须回退扫描**——宁可慢,不能漏
2163
+ const scanned = await scanDisk(conf, root)
2164
+ entries = scanned.entries
2165
+ mode = 'disk-scan'
2166
+ generatedAt = null
2167
+ const why = snap.state !== 'ok'
2168
+ ? `索引${snap.state === 'missing' ? '不存在' : '损坏'}`
2169
+ : `索引已过期(${snap.freshness.reason})`
2170
+ note = `${why},已改为**扫描磁盘**兜底(${scanned.scannedFiles} 个 .md${scanned.scanErrors.length ? `,${scanned.scanErrors.length} 处扫描错误` : ''}${(scanned.skippedLinks ?? []).length ? `,跳过 ${scanned.skippedLinks.length} 个链接目录` : ''});建议 kb_check(rebuild) 重建索引。`
2171
+ }
2172
+
2173
+ const references = await sourceReferences(root, entries, parseFrontmatter, (await readMeta(root)).value?.kbId)
2174
+ // Generated category entries are navigation. Match and cite the current
2175
+ // original; never return an old embedded copy as current evidence.
2176
+ const canonical = new Map()
2177
+ for (const entry of entries) {
2178
+ const source = references.get(entry.path)
2179
+ if (!source) { if (!canonical.has(entry.path)) canonical.set(entry.path, entry); continue }
2180
+ if (policyExcluded(readIndexPolicy(root), source) || (conf.excludeFromSearch || []).some(p => source === p || source.startsWith(p + '/'))) continue
2181
+ const absolute = path.join(root, source), guard = await checkRealPath(root, absolute)
2182
+ if (!guard.ok) continue
2183
+ try {
2184
+ const before = await stat(absolute), buf = await readFile(absolute), info = await stat(absolute)
2185
+ if (before.size !== info.size || before.mtimeMs !== info.mtimeMs || before.ctimeMs !== info.ctimeMs || buf.length !== info.size) continue
2186
+ const original = entryFromBuffer(source, absolute, buf, info.mtimeMs, info.ctimeMs)
2187
+ canonical.set(source, { ...original, title: original.title || entry.title, tags: [...new Set([...original.tags, ...(canonical.get(source)?.tags || []), ...entry.tags])] })
2188
+ } catch { /* Missing sources cannot fall back to stale mirror text. */ }
2189
+ }
2190
+ entries = [...canonical.values()]
2191
+ if(catalogActive(root)){
2192
+ const catalog=await readCatalog(root),records=new Map(catalog.files.filter(f=>f.status==='available').map(f=>[f.path,f]))
2193
+ entries=entries.filter(e=>records.has(e.path)).map(e=>{const f=records.get(e.path);return {...e,title:f.title,kind:f.kind,category:f.category,tags:f.tags}})
2194
+ }
2195
+ const metaHits = []
2196
+ const bodyHits = []
2197
+ const metaPaths = new Set()
2198
+ for (const e of entries) {
2199
+ const inMeta =
2200
+ String(e.title).toLowerCase().includes(lower) ||
2201
+ (e.tags ?? []).some((t) => String(t).toLowerCase().includes(lower)) ||
2202
+ String(e.kind ?? '').toLowerCase().includes(lower) || String(e.category ?? '').toLowerCase().includes(lower)
2203
+ if (!inMeta) continue
2204
+ metaHits.push({ entryId: e.entryId, path: e.path, title: e.title, snippet: `(标题/标签命中)tags=${(e.tags ?? []).join(',') || '-'}`, revision: e.revision })
2205
+ metaPaths.add(e.path)
2206
+ }
2207
+ for (const e of entries) {
2208
+ if (metaPaths.has(e.path)) continue // R1:按 path 归一(旧库 entryId 可能为 null)
2209
+ let text = typeof e.text === 'string' ? e.text : null
2210
+ if (text === null) {
2211
+ // 旧格式索引没有 text:读盘(宁可多读,不能漏)
2212
+ try {
2213
+ text = await readFile(path.join(root, e.path), 'utf8')
2214
+ } catch {
2215
+ continue
2216
+ }
2217
+ }
2218
+ const at = text.toLowerCase().indexOf(lower)
2219
+ if (at >= 0) {
2220
+ const snippet = text.slice(Math.max(0, at - 40), Math.min(text.length, at + query.length + 60)).replace(/\s+/g, ' ')
2221
+ bodyHits.push({ entryId: e.entryId, path: e.path, title: e.title, snippet: '…' + snippet + '…', revision: e.revision })
2222
+ }
2223
+ }
2224
+ // F3:原件与派生条目按**真实来源身份**去重(kbId + sourceRoot + originalPath + mode):
2225
+ // · 只有 attach 且源根就是当前库时,原件才在检索层里 → 才允许折叠;
2226
+ // · copy 的原件在 90-收件箱(不参与检索),不能拿"源相对路径"去匹配目标库里的同名无关文件。
2227
+ let deduped = [...metaHits, ...bodyHits]
2228
+ try {
2229
+ const meta = await readMeta(root)
2230
+ const kbId = meta.state === 'ok' ? meta.value.kbId ?? null : null
2231
+ const sourceEntries = await readImportSources(root)
2232
+ const paths = deduped.map((h) => toPosix(h.path))
2233
+ const pairs = foldGeneratedPairs(paths, sourceEntries, { kbId, root })
2234
+ if (pairs.size > 0) deduped = deduped.filter((h) => !pairs.has(toPosix(h.path)))
2235
+ } catch {
2236
+ /* 没有来源映射就不去重(宁多一条,不少一条) */
2237
+ }
2238
+ const currentPolicy = readIndexPolicy(root)
2239
+ if (currentPolicy.revision !== searchPolicyRevision) return { ok: false, reason: 'index-policy-changed', hits: [], coverageNote: '索引排除策略已变化,请重新检索' }
2240
+ const hits = deduped.filter(e => !policyExcluded(currentPolicy, e.path)).slice(0, limit)
2241
+ const coverageNote =
2242
+ (hits.length === 0 ? '未找到匹配内容。' : '') +
2243
+ (note ? note + ' ' : '') +
2244
+ `正文预筛:未启用(索引条目内置全文,逐条按子串匹配,语义与扫描一致;被排除 0 条);` +
2245
+ `检索方式=${mode};范围=${entries.length} 个条目(标题/标签/正文全文);` +
2246
+ `未纳入:${excludesOf(conf).join('、')}、原件二进制内容、未解析文件;` +
2247
+ (generatedAt ? `索引生成于 ${generatedAt}。` : '未使用索引。')
2248
+ await writeLog('info', `search "${query}" mode=${mode} 命中=${hits.length} 覆盖=${entries.length}`)
2249
+ return { ok: true, hits, coverageNote, mode }
2250
+ }
2251
+
2252
+ // ── 检查(R2:走同一把库级锁;R4:扫描不完整不覆盖完整索引)─────────
2253
+ async function checkLocked(conf) {
2254
+ const root = kbRootOf(conf)
2255
+ const health = await healthOf(conf)
2256
+ // 一次读取、一个快照(旧实现 readIndex + indexFreshness 各读一遍)
2257
+ const snap = await indexSnapshot(conf)
2258
+ const freshness = snap.state === 'ok' ? snap.freshness : { fresh: false, reason: snap.freshness.reason, detail: snap.freshness.detail ?? '' }
2259
+ const oldEntries = snap.entries
2260
+ const fresh = await scanDisk(conf, root)
2261
+ const freshByPath = new Map(fresh.entries.map((e) => [e.path, e]))
2262
+ const oldByPath = new Map(oldEntries.map((e) => [e.path, e]))
2263
+
2264
+ const added = fresh.entries.filter((e) => !oldByPath.has(e.path)).map((e) => e.path)
2265
+ const removed = oldEntries.filter((e) => !freshByPath.has(e.path)).map((e) => e.path)
2266
+ const changed = fresh.entries.filter((e) => oldByPath.has(e.path) && oldByPath.get(e.path).revision !== e.revision).map((e) => e.path)
2267
+
2268
+ const defects = []
2269
+ for (const entry of fresh.entries) {
2270
+ if (entry.path.startsWith('90-收件箱/')) continue // Originals do not require knowledge-note frontmatter.
2271
+ const file = path.join(root, entry.path)
2272
+ let text = ''
2273
+ try {
2274
+ text = await readFile(file, 'utf8')
2275
+ } catch (error) {
2276
+ defects.push({ kind: 'missingFile', path: entry.path, detail: `扫描时列出、读取失败:${(error && (error.code || error.message)) ?? error}` })
2277
+ continue
2278
+ }
2279
+ const parsed = parseFrontmatter(text)
2280
+ for (const field of REQUIRED_FIELDS) {
2281
+ if (parsed.data[field] === undefined || parsed.data[field] === '') defects.push({ kind: 'frontmatter', path: entry.path, detail: `缺字段 ${field}` })
2282
+ }
2283
+ // 2026-10-17:不再要求 frontmatter 带 id —— entryId 由 derivedEntryId(path) 兜底,
2284
+ // 故这里不再产生 noId 缺陷(见 PATCH-NOTES-派生id.md)。
2285
+ if (parsed.valid === false) defects.push({ kind: 'frontmatter', path: entry.path, detail: parsed.reason ?? 'frontmatter 非法' })
2286
+ }
2287
+ for (const p0 of removed) defects.push({ kind: 'missingFile', path: p0, detail: '上一次索引里有、现在磁盘上没有(意外缺失或用户删除,需人工确认)' })
2288
+ for (const err of fresh.scanErrors) defects.push({ kind: 'scanError', path: '-', detail: err })
2289
+ // P1-D:索引过期单独记为缺陷(kbId/排除规则/格式/内容指纹任一不符)
2290
+ if (!freshness.fresh && snap.state === 'ok') {
2291
+ defects.push({ kind: 'index-stale', path: '-.kbmeta/index', detail: `索引已过期:${freshness.reason}${freshness.detail ? ' — ' + freshness.detail : ''}` })
2292
+ }
2293
+
2294
+ // R4:扫描不完整(scanErrors>0)时**不得**用不完整结果覆盖索引 —— 保留旧索引并标 partial
2295
+ const indexWritten = fresh.scanErrors.length === 0
2296
+ if (indexWritten) await writeIndex(conf, fresh.entries)
2297
+ else defects.push({ kind: 'index-not-written', path: '-.kbmeta/index', detail: `扫描不完整(${fresh.scanErrors.length} 处错误),已保留旧索引、未覆盖;恢复记录不删除` })
2298
+ if (!indexWritten && existsSync(path.join(root, '.kbmeta', 'recover-todo.log'))) {
2299
+ await writeLog('warn', '扫描不完整:recover-todo 保留待下次消费')
2300
+ }
2301
+
2302
+ const result = {
2303
+ ok: true,
2304
+ execution: fresh.scanErrors.length === 0 ? 'ok' : 'partial',
2305
+ quality: defects.length === 0 ? 'pass' : 'fail',
2306
+ healthy: health.healthy,
2307
+ healthReason: health.reason,
2308
+ counts: { entries: fresh.entries.length, defects: defects.length, scannedFiles: fresh.scannedFiles, scanErrors: fresh.scanErrors.length, skippedLinks: (fresh.skippedLinks ?? []).length },
2309
+ links: { skipped: fresh.skippedLinks ?? [], policy: conf.followLinks ? 'follow-inside' : 'deny' },
2310
+ diff: { added, removed, changed },
2311
+ defects,
2312
+ rebuiltAt: nowIso(),
2313
+ indexWritten,
2314
+ // 语义保持 P1 原样:index.fresh 反映**本次检查开始时**的新鲜度;
2315
+ // 本次是否已重建看 indexWritten / rebuiltAt(不要用"重建后状态"掩盖过期事实)
2316
+ index: { fresh: freshness.fresh, reason: freshness.reason, detail: freshness.detail ?? '' },
2317
+ }
2318
+ await writeLog(result.quality === 'pass' ? 'info' : 'warn', `check 条目=${result.counts.entries} 缺陷=${defects.length} 增${added.length}/删${removed.length}/改${changed.length}`)
2319
+ return result
2320
+ }
2321
+
2322
+ async function check(args) {
2323
+ const gate = await configGate()
2324
+ if (!gate.ok) {
2325
+ return { ok: false, execution: 'error', quality: 'unknown', defects: [], reason: gate.refusal.reason, detail: gate.refusal.detail }
2326
+ }
2327
+ const conf = gate.conf
2328
+ const root = kbRootOf(conf)
2329
+ // R2:维护性写入(rebuild)必须与 create/update 共用同一把锁,否则会覆盖对方刚写的索引
2330
+ return withLock(root, () => withKbLock(root, 'check', () => checkLocked(conf)))
2331
+ }
2332
+
2333
+ /** 公开检查入口(含 recover):工具与自检共用同一条路径,避免"测的不是跑的" */
2334
+ async function checkEntry(args = {}) {
2335
+ if (args && args.recover) {
2336
+ const drained = await drainRecoverTodo()
2337
+ const result = await check({ ...args, rebuild: true })
2338
+ return { ...result, recover: drained }
2339
+ }
2340
+ return check(args ?? {})
2341
+ }
2342
+
2343
+ /** 已持锁版本的恢复消费(公开入口与自动消费者共用,避免两处逻辑漂移) */
2344
+ async function drainRecoverTodoLocked(conf) {
2345
+ const root = kbRootOf(conf)
2346
+ const file = path.join(root, '.kbmeta', 'recover-todo.log')
2347
+ if (!existsSync(file)) return { ok: true, consumed: 0 }
2348
+ const lines = (await readFile(file, 'utf8')).split('\n').filter(Boolean)
2349
+ const rebuilt = await reindexLocked(conf)
2350
+ if (rebuilt.ok === false) {
2351
+ // 扫描不完整:保留旧索引与恢复记录,等下次再消费(不假装恢复成功)
2352
+ await writeLog('warn', `恢复未完成:扫描不完整(${(rebuilt.scanErrors ?? []).length} 处错误),索引与恢复记录均保留`)
2353
+ return { ok: false, consumed: 0, kept: true, reason: rebuilt.reason, scanErrors: rebuilt.scanErrors ?? [] }
2354
+ }
2355
+ await rm(file, { force: true })
2356
+ await writeLog('info', `recover-todo 已消费 ${lines.length} 条并重建索引`)
2357
+ return { ok: true, consumed: lines.length }
2358
+ }
2359
+
2360
+ async function drainRecoverTodo() {
2361
+ // 结案核验的唯一遗漏:这里原来直接用 getConfig() 缓存,会先重建索引、删掉恢复记录,
2362
+ // 之后 check() 才报 config-degraded —— 属于"先动手后报错"。闸门必须在本函数入口。
2363
+ const gate = await configGate()
2364
+ if (!gate.ok) return { ...gate.refusal, consumed: 0 }
2365
+ const conf = gate.conf
2366
+ const root = kbRootOf(conf)
2367
+ return withLock(root, () => withKbLock(root, 'recover', async () => drainRecoverTodoLocked(conf)))
2368
+ }
2369
+
2370
+ /**
2371
+ * R4 自动恢复消费者。触发点(写死在实现里,注释与代码一致):
2372
+ * ① 插件启动后一次(index.js 调)
2373
+ * ② **每次写成功后一次**(index.js 在 create/update 成功后调)
2374
+ * 忙时(拿不到锁)返回 skipped=lock-*,由下一次触发补;停止时不删 todo(它是恢复证据)。
2375
+ */
2376
+ async function maybeRecover() {
2377
+ const gate = await configGate()
2378
+ if (!gate.ok) return { ok: false, consumed: 0, skipped: gate.refusal.reason }
2379
+ const conf = gate.conf
2380
+ const root = kbRootOf(conf)
2381
+ const todo = path.join(root, '.kbmeta', 'recover-todo.log')
2382
+ if (!existsSync(todo)) return { ok: true, consumed: 0, skipped: 'no-todo' }
2383
+ return withKbLock(root, 'auto-recover', async () => {
2384
+ try {
2385
+ return await drainRecoverTodoLocked(conf)
2386
+ } catch (error) {
2387
+ await writeLog('warn', `自动恢复失败(不影响使用):${String((error && error.message) ?? error)}`)
2388
+ return { ok: false, consumed: 0, skipped: 'error', detail: String((error && error.message) ?? error) }
2389
+ }
2390
+ })
2391
+ }
2392
+
2393
+ async function status({ bindingOnly = false } = {}) {
2394
+ const conf = await getConfigFresh()
2395
+ const cfgHealth = await getConfigHealth()
2396
+ const root = kbRootOf(conf)
2397
+ if (bindingOnly) {
2398
+ const meta = root === null ? null : await readMeta(root)
2399
+ return { kbPath: root === null ? null : toPosix(root), kbId: meta?.state === 'ok' ? meta.value.kbId ?? null : null }
2400
+ }
2401
+ // R6:未绑定 → bound=false / kbPath=null,绝不扫描 cwd、绝不报成"某个真实目录"
2402
+ if (root === null) {
2403
+ return {
2404
+ kbName: null,
2405
+ kbPath: null,
2406
+ bound: false,
2407
+ initialized: false,
2408
+ installState: 'unbound',
2409
+ kbId: null,
2410
+ healthy: false,
2411
+ healthReason: 'unbound',
2412
+ healthDetail: '未绑定知识库(kbPath 为空):不会扫描当前工作目录,写入会被拒绝',
2413
+ config: {
2414
+ file: toPosix(configFile),
2415
+ state: cfgHealth.state,
2416
+ ok: cfgHealth.ok,
2417
+ detail: cfgHealth.detail,
2418
+ recovery: cfgHealth.recovery ?? null,
2419
+ revision: conf.revision ?? null,
2420
+ seededFrom: conf.seededFrom ?? 'config.json',
2421
+ kbPath: '',
2422
+ },
2423
+ stateDir: toPosix(stateDir),
2424
+ realPath: null,
2425
+ index: { fresh: false, reason: 'unbound', detail: '' },
2426
+ lock: { file: null, held: false },
2427
+ followLinks: conf.followLinks === true,
2428
+ linkPolicy: conf.followLinks === true ? 'follow-inside(允许指向库内的链接,仍拒绝逃出库外)' : 'deny(库内链接一律拒绝)',
2429
+ privateDirs: Array.isArray(conf.privateDirs) ? conf.privateDirs : null,
2430
+ effectivePrivateDirs: null,
2431
+ bindingFile: toPosix(bindingFile),
2432
+ binding: null,
2433
+ counts: { entries: 0, indexState: 'unbound', indexedAt: null },
2434
+ logFile: toPosix(logFile),
2435
+ }
2436
+ }
2437
+ const meta = await readMeta(root)
2438
+ const index = await readIndex(conf)
2439
+ const binding = await readJsonState(bindingFile)
2440
+ const health = conf.degraded ? { healthy: false, reason: 'config-degraded', detail: cfgHealth.detail } : await healthOf(conf)
2441
+ // 只算一次新鲜度(旧实现调了两遍,等于走两遍指纹)
2442
+ const freshnessOnce = await indexFreshness(conf)
2443
+ return {
2444
+ kbName: meta.state === 'ok' ? meta.value.name : path.basename(root),
2445
+ kbPath: toPosix(root),
2446
+ bound: true,
2447
+ initialized: meta.state === 'ok' && meta.value.installState === 'complete',
2448
+ installState: meta.state === 'ok' ? (meta.value.installState ?? 'unknown') : meta.state,
2449
+ kbId: meta.state === 'ok' ? (meta.value.kbId ?? null) : null,
2450
+ healthy: health.healthy,
2451
+ healthReason: health.reason,
2452
+ healthDetail: health.detail,
2453
+ config: {
2454
+ file: toPosix(configFile),
2455
+ state: cfgHealth.state,
2456
+ ok: cfgHealth.ok,
2457
+ detail: cfgHealth.detail,
2458
+ recovery: cfgHealth.recovery ?? null,
2459
+ revision: conf.revision,
2460
+ seededFrom: conf.seededFrom ?? 'config.json',
2461
+ kbPath: conf.kbPath,
2462
+ },
2463
+ stateDir: toPosix(stateDir),
2464
+ realPath: await realOf(root),
2465
+ index: (() => {
2466
+ const f = freshnessOnce
2467
+ const labels = { ok: '已同步', 'index-stale-content': '文件清单或属性有变化,等待核对内容', 'index-missing': '索引文件缺失', 'index-corrupt': '索引损坏', 'index-legacy': '旧索引缺少校验信息', 'index-format-old': '索引格式不兼容', 'index-tokenizer-old': '分词版本不兼容', 'index-excludes-changed': '检索排除范围有变化', 'index-kbid-mismatch': '知识库身份不一致,已暂停维护', 'index-fingerprint-unknown': '无法完整读取目录或文件属性' }
2468
+ return { fresh: f.fresh, reason: f.reason, reasonLabel: labels[f.reason] || f.reason, detail: f.detail ?? '', indexedAt: index.generatedAt || null }
2469
+ })(),
2470
+ lock: { file: toPosix(lockFileOf(root)), held: existsSync(lockFileOf(root)) },
2471
+ followLinks: conf.followLinks === true,
2472
+ linkPolicy: conf.followLinks === true ? 'follow-inside(允许指向库内的链接,仍拒绝逃出库外)' : 'deny(库内链接一律拒绝)',
2473
+ // R5:隐私目录可配置(地图据此只给计数);未配置时返回 null,由地图用默认值
2474
+ privateDirs: Array.isArray(conf.privateDirs) ? conf.privateDirs : null,
2475
+ // F2:有效私密策略 = 配置私密根 ∪ 承载私密派生条目的分区(清单/地图/recent/错误详情都用它)
2476
+ effectivePrivateDirs: effectivePrivateDirs(conf.privateDirs, derivedPrivatePartitions(await readImportSources(root))),
2477
+ bindingFile: toPosix(bindingFile),
2478
+ binding: binding.state === 'ok' ? { kbId: binding.value.kbId, kbPath: binding.value.kbPath, boundAt: binding.value.boundAt } : null,
2479
+ counts: { entries: index.state === 'ok' ? index.entries.length : 0, indexState: index.state, indexedAt: index.state === 'ok' ? index.generatedAt : null },
2480
+ logFile: toPosix(logFile),
2481
+ }
2482
+ }
2483
+
2484
+ return {
2485
+ maintainIndex, maintenanceStatus, indexSnapshots, purgePolicyIndex,
2486
+ registerOriginal: async args => {const conf=await getConfigFresh(),root=kbRootOf(conf);if(!catalogActive(root))return null;const b={root,st:{kbId:(await readMeta(root)).value.kbId},privateDirs:effectivePrivateDirs(conf.privateDirs,derivedPrivatePartitions(await readImportSources(root))),core:{_internal:{parseFrontmatter}}};await refreshCatalog(b);return classifyOriginal(b,args)},
2487
+ loadConfig,
2488
+ getConfig,
2489
+ getConfigHealth,
2490
+ setConfig,
2491
+ getConfigFresh,
2492
+ async bindSharedLibrary(target, identity, expectedConfigRevision) {
2493
+ return commitBind(target, { expectedCurrentKbPath: '', expectedConfigRevision, expectedTargetKbId: identity.kbId, sharedInstanceId: identity.instanceId })
2494
+ },
2495
+ bind,
2496
+ init,
2497
+ initializeLibrary,
2498
+ createEntry,
2499
+ updateEntry,
2500
+ search,
2501
+ check,
2502
+ checkEntry,
2503
+ maybeRecover,
2504
+ indexFreshness,
2505
+ status,
2506
+ reindex,
2507
+ drainRecoverTodo,
2508
+ configGate,
2509
+ _internal: {
2510
+ parseFrontmatter, buildFile, isInside, sha12, sha256, composeWithHeader, splitFrontmatter, contentHashOf,
2511
+ // 供定向测试用(不属于公开契约):锁的获取/释放是 R2 的核心不变量
2512
+ acquireKbLock, releaseKbLock, indexSnapshot, fingerprintOf,
2513
+ ioStats: () => ({ ...ioMetrics, indexCache: indexCache.stats() }),
2514
+ assertRuntimeOwner: root => assertServiceOwner(root, cfg.serviceOwnerToken),
2515
+ withMutationLock: (root, fn) => withLock(root, () => withKbLock(root, 'workbench-repair', fn)),
2516
+ },
2517
+ paths: { stateDir, configFile, bindingFile, logFile },
2518
+ }
2519
+ }