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

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 +9 -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 +778 -0
  18. package/PROJECT-RECORD.md +789 -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 +11 -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 +4980 -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 +2224 -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 +284 -0
@@ -0,0 +1,909 @@
1
+ // 异构资料 / 旧库导入(接入原目录 · 复制导入)——与 UI、模型工具共用的唯一后端流程。
2
+ //
3
+ // p4(R1–R7 定向整改)后的硬约束:
4
+ // R1 任务清单必须携带目标身份:{target, targetKbId, taskStateDir};执行方用**独立 core**
5
+ // (见 import-service.js),本文件只负责「按清单写目标库」,不读当前绑定。
6
+ // R2 importId 单一校验(^imp-[a-z0-9]{6,16}$);任务目录解析后必须仍在 imports 内,
7
+ // 并做 realpath 复核;源/目标/清单/复制读写各自过 checkRealPath。
8
+ // R3 **先扫描冻结原始清单,再建标准结构**;「是不是生成物」只认清单/来源映射,
9
+ // 不再用「目录名与本插件受管目录同名」推断(旧资料夹的 00-画像/old.txt 不会被跳过)。
10
+ // frontmatter 的 type 参与分类映射;私密来源的派生条目不得落到公开分区。
11
+ // R4 plan 阶段逐文件冻结 sha256+size+mtime;run 前核验,变了就 conflict 停;
12
+ // 终态 = failed=0 && pending=0 && !truncated && errors=0;否则 partial 并列原因。
13
+ // 来源映射按「目标库身份 + 源根目录 + 源相对路径」长期保存在 <目标库>/.kbmeta/import-sources.json,
14
+ // 同一来源再导入走受控 update,不追加副本。
15
+ // R5 文本类(md/txt/log/代码)**全文**进检索;原件与派生条目通过来源映射去重(在 kbcore.search 里做)。
16
+ // R6 空/非法路径不解释成 cwd;目录不存在时若父级可写,由 initializeLibrary 创建。
17
+ // 其余原有约束(不覆盖同名、可中断可续、原件不执行、不冒充全文)保持不变。
18
+ import path from 'node:path'
19
+ import { createHash, randomUUID } from 'node:crypto'
20
+ import { readFile, writeFile, mkdir, stat, rename, copyFile } from 'node:fs/promises'
21
+ import { existsSync } from 'node:fs'
22
+ import { toPosix, normSegs, walkTree, sha256File, privateRootOf, DEFAULT_PRIVATE_DIRS } from './fsindex.js'
23
+ import { checkRealPath, realOf, insideReal } from './kbcore.js'
24
+ import { readIndexPolicy, groupFor, policyFile, savePolicy } from './index-policy.js'
25
+ import { locked } from './workbench-state.js'
26
+
27
+ export const IMPORT_VERSION = 2
28
+
29
+ // R2:唯一的 importId 契约。importIdFor 产出的 id 必须满足它(sha1 前 10 位十六进制)。
30
+ export const IMPORT_ID_RE = /^imp-[a-z0-9]{6,16}$/
31
+ export function isValidImportId(importId) {
32
+ return typeof importId === 'string' && IMPORT_ID_RE.test(importId)
33
+ }
34
+
35
+ // 工具/版本目录:任何情况下都不导入(与内容无关)。
36
+ export const SKIP_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', '.idea', '.vscode', '.DS_Store'])
37
+ // 只在「源目录本身就是一个已初始化的知识库」时跳过:这些层不是知识内容(模板/手册/加工件/原件库/元数据)。
38
+ // 注意:这是**归属层判定**,不是"名字像生成物就跳过"——没有 .kbmeta 的旧资料夹不走这条。
39
+ export const LIBRARY_LAYERS = new Set(['_模板', '_手册', '50-底稿', '90-收件箱', '知识库地图', '.kb', '.kbmeta', '.kb-state', '.kb-import'])
40
+ // 根目录导航文件不是"源内容"
41
+ const ROOT_NAV = new Set(['INDEX.md', 'README.md', '知识库清单.md'])
42
+ // 可映射到分区的类型(与 kbcore 的 KIND_TO_CATEGORY 对齐)
43
+ const IMPORTABLE_KINDS = new Set(['知识', '项目', '人物', '素材', '画像'])
44
+
45
+ const TEXT_EXT = new Set(['.md', '.markdown', '.txt', '.text', '.log'])
46
+ const DOC_EXT = new Set(['.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.odt', '.odp', '.ods', '.rtf'])
47
+ const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tif', '.tiff', '.heic'])
48
+ const AUDIO_EXT = new Set(['.mp3', '.wav', '.m4a', '.flac', '.aac', '.ogg', '.wma'])
49
+ const VIDEO_EXT = new Set(['.mp4', '.mov', '.mkv', '.avi', '.webm', '.wmv', '.flv'])
50
+ const CODE_EXT = new Set(['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.py', '.ps1', '.sh', '.bat', '.cmd', '.json', '.yaml', '.yml', '.toml', '.ini', '.css', '.html', '.htm', '.sql', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs'])
51
+
52
+ const sha1 = (s) => createHash('sha1').update(String(s), 'utf8').digest('hex')
53
+ const sha12Of = (buf) => createHash('sha256').update(buf).digest('hex').slice(0, 12)
54
+ const sha256Of = (buf) => createHash('sha256').update(buf).digest('hex')
55
+ const extOf = (rel) => path.extname(rel).toLowerCase()
56
+ const kbMetaOf = (folder) => path.join(folder, '.kbmeta', 'kb.json')
57
+ const normAbs = (p) => toPosix(path.resolve(String(p))).toLowerCase()
58
+
59
+ // 本机实测:Windows 上 rename 偶发 EPERM/EBUSY(杀软/索引服务持有句柄)。
60
+ // 原子写在生产里不能因为一次抖动就整任务失败 —— 短退避重试,仍然失败再抛。
61
+ async function renameWithRetry(from, to, attempts = 6) {
62
+ const { rename } = await import('node:fs/promises')
63
+ let lastError = null
64
+ for (let i = 0; i < attempts; i += 1) {
65
+ try {
66
+ await rename(from, to)
67
+ return
68
+ } catch (error) {
69
+ lastError = error
70
+ const code = String((error && error.code) ?? '')
71
+ if (!['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(code)) throw error
72
+ await new Promise((r) => setTimeout(r, 20 * 2 ** i))
73
+ }
74
+ }
75
+ throw lastError
76
+ }
77
+
78
+ /** 导入任务的稳定 id:同一目标 + 同一源 + 同一模式 → 同一任务(重试续跑,不会开新任务)。 */
79
+ export function importIdFor(source, target, mode) {
80
+ const key = [normAbs(source), normAbs(target ?? source), mode].join('|')
81
+ return 'imp-' + sha1(key).slice(0, 10)
82
+ }
83
+
84
+ // ── R2:任务目录解析(唯一实现)────────────────────────────────────
85
+ export function importsRootOf(stateDir) {
86
+ return path.resolve(stateDir, 'imports')
87
+ }
88
+
89
+ /** 取最近的已存在祖先的真实路径(任务目录通常还不存在,不能直接 realpath 它)。 */
90
+ async function nearestReal(p) {
91
+ let cur = path.resolve(p)
92
+ for (;;) {
93
+ const real = await realOf(cur)
94
+ if (real !== null) return { real, at: cur }
95
+ const parent = path.dirname(cur)
96
+ if (parent === cur) return { real: null, at: cur }
97
+ cur = parent
98
+ }
99
+ }
100
+
101
+ /**
102
+ * 解析任务目录:先过 id 契约,再核字符串边界,最后核真实路径边界。
103
+ * @returns {{ok:true, dir:string, root:string}|{ok:false, reason:string}}
104
+ */
105
+ export async function resolveImportDir(stateDir, importId) {
106
+ if (!isValidImportId(importId)) return { ok: false, reason: 'bad-import-id' }
107
+ const root = importsRootOf(stateDir)
108
+ const dir = path.join(root, importId)
109
+ const rel = path.relative(root, dir)
110
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return { ok: false, reason: 'import-dir-escape' }
111
+ const realRoot = await realOf(root)
112
+ if (realRoot !== null) {
113
+ const near = await nearestReal(dir)
114
+ if (near.real === null || !insideReal(realRoot, near.real)) return { ok: false, reason: 'import-dir-escape-real' }
115
+ }
116
+ return { ok: true, dir, root }
117
+ }
118
+
119
+ export async function readManifest(stateDir, importId) {
120
+ const r = await resolveImportDir(stateDir, importId)
121
+ if (!r.ok) return null
122
+ try {
123
+ return JSON.parse(await readFile(path.join(r.dir, 'manifest.json'), 'utf8'))
124
+ } catch {
125
+ return null
126
+ }
127
+ }
128
+
129
+ /** 供服务层写回清单(任务身份 / 目标 kbId 等由服务层补齐)。 */
130
+ export async function saveManifest(stateDir, manifest) {
131
+ manifest.updatedAt = new Date().toISOString()
132
+ await writeManifest(stateDir, manifest)
133
+ return manifest
134
+ }
135
+
136
+ async function writeManifest(stateDir, manifest) {
137
+ const r = await resolveImportDir(stateDir, manifest.importId)
138
+ if (!r.ok) throw new Error('导入任务目录非法:' + r.reason)
139
+ await mkdir(r.dir, { recursive: true })
140
+ const tmp = path.join(r.dir, 'manifest.json.tmp-' + randomUUID())
141
+ await writeFile(tmp, JSON.stringify(manifest, null, 2), 'utf8')
142
+ await renameWithRetry(tmp, path.join(r.dir, 'manifest.json'))
143
+ }
144
+
145
+ function cancelPathOf(dir) {
146
+ return path.join(dir, 'cancel')
147
+ }
148
+
149
+ export function recount(manifest) {
150
+ const c = { total: manifest.items.length, done: 0, pending: 0, failed: 0, skipped: 0, waiting: 0, entries: 0, updated: 0 }
151
+ for (const it of manifest.items) {
152
+ if (it.status === 'done') {
153
+ c.done += 1
154
+ if (it.entryPath) c.entries += 1
155
+ if (it.updated === true) c.updated += 1
156
+ } else if (it.status === 'failed') c.failed += 1
157
+ else if (it.status === 'skipped') c.skipped += 1
158
+ else c.pending += 1
159
+ if (it.class === 'doc' || it.class === 'media' || it.class === 'other') c.waiting += 1
160
+ }
161
+ manifest.counts = c
162
+ return c
163
+ }
164
+
165
+ /** 源目录本身是不是「本插件初始化完成的知识库」——决定是否按库的归属层/来源映射排除。 */
166
+ export async function isOwnLibrary(root) {
167
+ const meta = await (async () => {
168
+ try {
169
+ return JSON.parse(await readFile(kbMetaOf(root), 'utf8'))
170
+ } catch {
171
+ return null
172
+ }
173
+ })()
174
+ if (!meta || typeof meta !== 'object') return false
175
+ return meta.schemaVersion === 1 && typeof meta.kbId === 'string' && meta.kbId.trim() !== '' && meta.installState === 'complete'
176
+ }
177
+
178
+ // ── R4:长期来源映射(落在目标库 .kbmeta 里,跟着库身份走)────────────
179
+ export function sourcesFileOf(targetRoot) {
180
+ return path.join(targetRoot, '.kbmeta', 'import-sources.json')
181
+ }
182
+
183
+ export async function readSourceMap(targetRoot) {
184
+ try {
185
+ const raw = JSON.parse(await readFile(sourcesFileOf(targetRoot), 'utf8'))
186
+ if (!raw || (raw.version !== undefined && raw.version !== 1) || !raw.entries || typeof raw.entries !== 'object' || Array.isArray(raw.entries) || Object.values(raw.entries).some(e => !e || typeof e !== 'object' || Array.isArray(e))) throw Error('Invalid source map schema')
187
+ const entries = raw.entries
188
+ return { version: 1, entries }
189
+ } catch (error) {
190
+ if (error.code === 'ENOENT') return { version: 1, entries: {} }
191
+ throw Object.assign(new Error('来源映射无法读取,未覆盖原文件'), { code: 'STATE_CORRUPT', cause: error })
192
+ }
193
+ }
194
+
195
+ export async function writeSourceMap(targetRoot, map) {
196
+ const file = sourcesFileOf(targetRoot)
197
+ await mkdir(path.dirname(file), { recursive: true })
198
+ const payload = { version: 1, updatedAt: new Date().toISOString(), entries: map.entries ?? {} }
199
+ const tmp = `${file}.tmp-${randomUUID()}`
200
+ await writeFile(tmp, JSON.stringify(payload, null, 2), 'utf8')
201
+ await renameWithRetry(tmp, file)
202
+ return payload
203
+ }
204
+
205
+ /**
206
+ * 来源身份 = 目标库身份 + 源根目录 + 源相对路径。
207
+ * 只带 rel 会把不同源目录里的同名文件当成同一来源(R4 复核意见第 2 点)。
208
+ */
209
+ export function sourceKey(kbId, sourceRoot, rel) {
210
+ return [String(kbId ?? '-'), normAbs(sourceRoot), toPosix(rel)].join('|')
211
+ }
212
+
213
+ /** 已生成条目路径集合:只从「清单/来源映射/请求记录」取,不从目录名推断。 */
214
+ export async function generatedPathsOf(targetRoot) {
215
+ const out = new Set()
216
+ const map = await readSourceMap(targetRoot)
217
+ for (const v of Object.values(map.entries)) {
218
+ if (!v || typeof v !== 'object') continue
219
+ if (typeof v.entryPath === 'string') out.add(toPosix(v.entryPath))
220
+ if (Array.isArray(v.entryPaths)) for (const p of v.entryPaths) if (typeof p === 'string') out.add(toPosix(p))
221
+ }
222
+ try {
223
+ const req = JSON.parse(await readFile(path.join(targetRoot, '.kbmeta', 'requests.json'), 'utf8'))
224
+ const items = req && req.items ? req.items : {}
225
+ for (const it of Object.values(items)) {
226
+ if (it && it.op === 'create' && typeof it.path === 'string') out.add(toPosix(it.path))
227
+ }
228
+ } catch {
229
+ /* 没有请求记录就不排除 */
230
+ }
231
+ return out
232
+ }
233
+
234
+ async function canWriteAncestor(dir) {
235
+ let anc = path.resolve(dir)
236
+ while (!existsSync(anc) && path.dirname(anc) !== anc) anc = path.dirname(anc)
237
+ try {
238
+ const { access } = await import('node:fs/promises')
239
+ const { constants } = await import('node:fs')
240
+ await access(anc, constants.W_OK)
241
+ return { ok: true, base: toPosix(anc) }
242
+ } catch (error) {
243
+ return { ok: false, base: toPosix(anc), reason: String((error && (error.code || error.message)) ?? error) }
244
+ }
245
+ }
246
+
247
+ /** 这个目录属于哪一类?——「自动建库/识别」的唯一判据来源。 */
248
+ export async function inspectFolder(folderRaw) {
249
+ const raw = String(folderRaw ?? '').trim()
250
+ const out = { path: raw === '' ? null : toPosix(path.resolve(raw)), exists: false, isDir: false, writable: false, creatable: false, createBase: null, kind: 'unknown', files: 0, dirs: 0, errors: 0, meta: null, reasons: [], truncated: null }
251
+ if (raw === '') {
252
+ out.kind = 'missing'
253
+ out.reasons.push('路径为空(本版不会把空路径当成当前工作目录)')
254
+ return out
255
+ }
256
+ const folder = path.resolve(raw)
257
+ const st = await stat(folder).catch(() => null)
258
+ if (st === null) {
259
+ out.kind = 'missing'
260
+ out.reasons.push('目录不存在')
261
+ const w = await canWriteAncestor(folder)
262
+ out.creatable = w.ok
263
+ out.createBase = w.base
264
+ if (!w.ok) out.reasons.push(`上级不可写(${w.base}:${w.reason})`)
265
+ return out
266
+ }
267
+ out.exists = true
268
+ if (!st.isDirectory()) {
269
+ out.kind = 'not-a-directory'
270
+ out.reasons.push('这个路径不是文件夹')
271
+ return out
272
+ }
273
+ out.isDir = true
274
+ try {
275
+ const probe = path.join(folder, `.kb-probe-${process.pid}-${Math.random().toString(16).slice(2, 8)}`)
276
+ await writeFile(probe, 'ok', 'utf8')
277
+ const { rm } = await import('node:fs/promises')
278
+ await rm(probe, { force: true })
279
+ out.writable = true
280
+ } catch (error) {
281
+ out.reasons.push('目录不可写:' + String((error && (error.code || error.message)) ?? error))
282
+ }
283
+ const metaPath = kbMetaOf(folder)
284
+ if (existsSync(metaPath)) {
285
+ try {
286
+ const meta = JSON.parse(await readFile(metaPath, 'utf8'))
287
+ out.meta = { installState: meta.installState ?? null, kbId: meta.kbId ?? null, schemaVersion: meta.schemaVersion ?? null, name: meta.name ?? null, createdAt: meta.createdAt ?? null, freshSharedSetup: meta.freshSharedSetup === true }
288
+ if (meta.schemaVersion !== 1) {
289
+ out.kind = 'incompatible'
290
+ out.reasons.push(`元数据版本不兼容(schemaVersion=${meta.schemaVersion ?? '缺'},本版支持 1)`)
291
+ } else if (typeof meta.kbId !== 'string' || meta.kbId.trim() === '') {
292
+ out.kind = 'corrupt'
293
+ out.reasons.push('元数据缺 kbId(库身份无效)')
294
+ } else if (meta.installState !== 'complete') {
295
+ out.kind = 'ours-partial'
296
+ out.reasons.push(`本插件的库,初始化未完成(installState=${meta.installState ?? '缺'})`)
297
+ } else {
298
+ out.kind = 'ours'
299
+ out.reasons.push('本插件已有的库:接入时保留 kbId 与既有资料')
300
+ }
301
+ } catch (error) {
302
+ out.kind = 'corrupt'
303
+ out.reasons.push('元数据损坏(无法解析 .kbmeta/kb.json):' + String((error && error.message) ?? error))
304
+ }
305
+ }
306
+ const scan = await walkTree(folder, folder, { maxFiles: 5000, followLinks: false })
307
+ out.files = scan.files.length
308
+ out.dirs = scan.dirs.length
309
+ out.errors = scan.errors.length
310
+ out.truncated = scan.truncated
311
+ if (out.kind === 'unknown') {
312
+ out.kind = out.files === 0 ? 'empty' : 'foreign'
313
+ out.reasons.push(out.files === 0 ? '空目录:可以按标准结构新建知识库' : `普通资料文件夹:${out.files} 个文件,将按结构分类导入`)
314
+ }
315
+ return out
316
+ }
317
+
318
+ function classifyFile(rel) {
319
+ const ext = extOf(rel)
320
+ if (TEXT_EXT.has(ext)) return ext === '.md' || ext === '.markdown' ? 'markdown' : 'text'
321
+ if (DOC_EXT.has(ext)) return 'doc'
322
+ if (IMAGE_EXT.has(ext)) return 'media'
323
+ if (AUDIO_EXT.has(ext) || VIDEO_EXT.has(ext)) return 'media'
324
+ if (CODE_EXT.has(ext)) return 'code'
325
+ return 'other'
326
+ }
327
+
328
+ const TYPE_LABEL = { markdown: 'Markdown 文档', text: '纯文本', doc: '文档(未解析)', media: '图片/音视频(未识别)', code: '代码/配置(仅作资料)', other: '未支持格式' }
329
+ // 与 kbcore 的 KIND_TO_CATEGORY 对齐(只用于「同一来源再导入时分区是否变了」)
330
+ const CATEGORY_OF = { 知识: '20-知识笔记', 项目: '10-项目', 人物: '30-人物关系', 素材: '40-素材资源', 画像: '00-画像' }
331
+
332
+ /** 从 md 头部解析 frontmatter 的 title/type/tags/status(容错:解析失败就当普通文本)。 */
333
+ function looseFrontmatter(head) {
334
+ if (!head.startsWith('---')) return null
335
+ const end = head.indexOf('\n---', 3)
336
+ if (end < 0) return null
337
+ const block = head.slice(3, end)
338
+ const pick = (key) => {
339
+ const m = new RegExp(`^${key}\\s*:\\s*(.+)$`, 'm').exec(block)
340
+ if (!m) return null
341
+ return m[1].trim().replace(/^['"]|['"]$/g, '')
342
+ }
343
+ const tagsRaw = pick('tags')
344
+ const tags = tagsRaw ? tagsRaw.replace(/^\[|\]$/g, '').split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean) : []
345
+ return { title: pick('title'), type: pick('type'), tags, bodyStart: head.indexOf('\n', end + 1) + 1 }
346
+ }
347
+
348
+ /** 目标分区:frontmatter 的 type 参与映射;私密来源一律降到私密分区(画像)。 */
349
+ export function mapEntryKind({ fmType, rel, privateDirs }) {
350
+ const privateHit = privateRootOf(rel, privateDirs ?? DEFAULT_PRIVATE_DIRS)
351
+ const base = typeof fmType === 'string' && IMPORTABLE_KINDS.has(fmType) ? fmType : '知识'
352
+ if (privateHit !== null && base !== '画像') return { kind: '画像', privateHit: String(privateHit), downgraded: true }
353
+ return { kind: base, privateHit: privateHit === null ? null : String(privateHit), downgraded: false }
354
+ }
355
+
356
+ /**
357
+ * 冻结源清单(只读扫描 + 逐文件 sha256;不写目标库)。
358
+ * R3:**先冻结、后建结构** —— 调用方必须先 plan 再 initializeLibrary。
359
+ * R4:plan 阶段就把 sha256/size/mtime 写进清单,运行时只认这份冻结值。
360
+ */
361
+ export async function planImport({ stateDir, source, target, mode, maxFiles = 20000, log = () => {}, isActive = null }) {
362
+ const srcRaw = String(source ?? '').trim()
363
+ if (srcRaw === '') return { error: 'source 不能为空', reason: 'empty-source' }
364
+ const src = path.resolve(srcRaw)
365
+ const tgt = path.resolve(String(target ?? src))
366
+ const importId = importIdFor(src, tgt, mode)
367
+
368
+ // R2:源与目标不得互相包含(同目录允许:attach 就是"在原地建库";父子目录一律拒绝,避免自己导自己)
369
+ const relST = path.relative(src, tgt)
370
+ const relTS = path.relative(tgt, src)
371
+ const srcInTgt = relST !== '' && !relST.startsWith('..') && !path.isAbsolute(relST)
372
+ const tgtInSrc = relTS !== '' && !relTS.startsWith('..') && !path.isAbsolute(relTS)
373
+ if (srcInTgt || tgtInSrc) {
374
+ return { error: '源与目标不能互相包含(父子目录):请换一个独立目录作为源或目标', reason: 'nested-source-target' }
375
+ }
376
+
377
+ // R4:运行中的任务只读不写(重复 plan 不重置进度)
378
+ const existing = await readManifest(stateDir, importId)
379
+ const active = typeof isActive === 'function' ? isActive(importId) : false
380
+ if (existing && (active || existing.stage === 'importing' || existing.stage === 'verifying')) {
381
+ const counts = recount(existing)
382
+ log('warn', `导入计划 ${importId} 正在运行:本次只返回现有清单,未覆盖进度`)
383
+ return { ...existing, running: true, counts, note: '任务正在运行:未覆盖现有清单' }
384
+ }
385
+
386
+ const own = await isOwnLibrary(src)
387
+ const generated = own ? await generatedPathsOf(tgt) : new Set()
388
+ const scan = await walkTree(src, src, { maxFiles, followLinks: false })
389
+ const items = []
390
+ const skippedDirs = []
391
+ const skippedFiles = []
392
+ let hashErrors = 0
393
+ for (const f of scan.files) {
394
+ const rel = toPosix(f.path)
395
+ const segs = normSegs(rel)
396
+ const top = segs[0] ?? ''
397
+ if (SKIP_DIRS.has(top)) {
398
+ if (!skippedDirs.includes(top)) skippedDirs.push(top)
399
+ continue
400
+ }
401
+ // 归属层排除只在「源目录本身是已初始化知识库」时生效(旧资料夹同名目录不算)
402
+ if (own && LIBRARY_LAYERS.has(top)) {
403
+ if (!skippedDirs.includes(top)) skippedDirs.push(top)
404
+ continue
405
+ }
406
+ if (generated.has(rel)) {
407
+ skippedFiles.push(rel)
408
+ continue
409
+ }
410
+ if (!rel.includes('/') && ROOT_NAV.has(rel)) {
411
+ skippedFiles.push(rel)
412
+ continue
413
+ }
414
+ const abs = path.join(src, ...rel.split('/'))
415
+ const boundary = await checkRealPath(src, abs)
416
+ if (!boundary.ok) {
417
+ skippedFiles.push(rel)
418
+ if (!skippedDirs.includes('(链接/越界文件)')) skippedDirs.push('(链接/越界文件)')
419
+ continue
420
+ }
421
+ let sha256 = null
422
+ let hashError = null
423
+ try {
424
+ sha256 = await sha256File(abs)
425
+ } catch (error) {
426
+ hashError = String((error && (error.code || error.message)) ?? error).slice(0, 200)
427
+ hashErrors += 1
428
+ }
429
+ items.push({
430
+ key: rel,
431
+ rel,
432
+ bytes: f.bytes,
433
+ mtimeMs: Math.round(f.mtimeMs),
434
+ class: classifyFile(rel),
435
+ status: hashError === null ? 'pending' : 'failed',
436
+ sha256,
437
+ entryId: null,
438
+ entryPath: null,
439
+ originalPath: null,
440
+ updated: false,
441
+ reason: null,
442
+ error: hashError === null ? null : `计划阶段读取失败:${hashError}`,
443
+ })
444
+ }
445
+ const targetMeta = await (async () => {
446
+ try {
447
+ return JSON.parse(await readFile(kbMetaOf(tgt), 'utf8'))
448
+ } catch {
449
+ return null
450
+ }
451
+ })()
452
+ const manifest = {
453
+ version: IMPORT_VERSION,
454
+ importId,
455
+ mode, // attach(接入原目录)| copy(复制导入)
456
+ source: toPosix(src),
457
+ target: toPosix(tgt),
458
+ targetKbId: targetMeta && typeof targetMeta.kbId === 'string' ? targetMeta.kbId : null,
459
+ taskStateDir: null,
460
+ createdAt: new Date().toISOString(),
461
+ updatedAt: new Date().toISOString(),
462
+ stage: 'planned',
463
+ skippedDirs,
464
+ skippedFiles,
465
+ scan: { files: scan.files.length, dirs: scan.dirs.length, errors: scan.errors.length + hashErrors, truncated: scan.truncated, maxDepth: scan.maxDepth, ownLibrary: own },
466
+ items,
467
+ counts: null,
468
+ }
469
+ recount(manifest)
470
+ await writeManifest(stateDir, manifest)
471
+ log('info', `导入计划 ${importId}:${items.length} 个源文件(跳过 ${skippedDirs.length} 类目录 / ${skippedFiles.length} 个文件),截断=${scan.truncated ? scan.truncated.reason : '无'}`)
472
+ return manifest
473
+ }
474
+
475
+ async function copyPreserve(sourceAbs, targetAbs) {
476
+ await mkdir(path.dirname(targetAbs), { recursive: true })
477
+ await copyFile(sourceAbs, targetAbs)
478
+ }
479
+
480
+ function entryBodyFor(item, originalRel, text) {
481
+ const meta = [
482
+ `- 原件:\`${originalRel}\``,
483
+ `- 大小:${item.bytes} 字节`,
484
+ `- 类型:${TYPE_LABEL[item.class] ?? item.class}`,
485
+ `- 源指纹(sha256):\`${item.sha256}\``,
486
+ ].join('\n')
487
+ if (item.class === 'doc') {
488
+ return ['## 待解析', '', '这个文件已登记并保留原件,但**本版没有做格式解析**(不做 OCR、不做 docx/xlsx/pdf 正文抽取)。', '要看内容请打开上面的原件;解析后应把正文补写到本节,而不是留着这条占位。', '', '## 原件信息', '', meta].join('\n')
489
+ }
490
+ if (item.class === 'media') {
491
+ return ['## 待识别', '', '这个文件已登记并保留原件,但**本版没有做 OCR / 语音转写 / 视频取帧**。', '其中图片可走本地 OCR;音视频需转写后再补正文。', '', '## 原件信息', '', meta].join('\n')
492
+ }
493
+ if (item.class === 'other') {
494
+ return ['## 未支持格式', '', `扩展名 \`${path.extname(item.rel) || '(无)'}\` 不在本版支持的范围内,**原件已原样保留**,没有转换、没有抽取内容。`, '', '## 原件信息', '', meta].join('\n')
495
+ }
496
+ // R5:文本类给**全文**(不是头部摘录)。逐条全文进索引,后半段关键词也能命中。
497
+ const full = String(text ?? '')
498
+ return [
499
+ '## 正文(导入全文)',
500
+ '',
501
+ '> 以下是源文件的**完整文本**(导入时按 UTF-8 读取),用于全文检索;原件仍保留在原位(或 90-收件箱)。',
502
+ '',
503
+ '````text',
504
+ full.trim() === '' ? '(文件为空或无法按 UTF-8 读取)' : full,
505
+ '````',
506
+ '',
507
+ '## 原件信息',
508
+ '',
509
+ meta,
510
+ ].join('\n')
511
+ }
512
+
513
+ /** R4:执行前核验冻结值(源文件被改/被删 → 明确冲突,不猜)。 */
514
+ async function preflight(manifest) {
515
+ const conflicts = []
516
+ for (const item of manifest.items) {
517
+ if (item.status === 'done' || item.status === 'skipped') continue
518
+ const srcAbs = path.join(manifest.source, ...item.rel.split('/'))
519
+ const boundary = await checkRealPath(manifest.source, srcAbs)
520
+ if (!boundary.ok) {
521
+ conflicts.push({ rel: item.rel, reason: boundary.reason, detail: boundary.detail })
522
+ continue
523
+ }
524
+ const st = await stat(srcAbs).catch(() => null)
525
+ if (st === null) {
526
+ conflicts.push({ rel: item.rel, reason: 'source-missing', detail: '源文件已不存在(计划后被移走/改名)' })
527
+ continue
528
+ }
529
+ if (st.size !== item.bytes) {
530
+ conflicts.push({ rel: item.rel, reason: 'source-size-changed', detail: `冻结 ${item.bytes} → 现在 ${st.size}` })
531
+ continue
532
+ }
533
+ const hash = await sha256File(srcAbs).catch((error) => ({ error: String((error && (error.code || error.message)) ?? error) }))
534
+ if (typeof hash !== 'string') {
535
+ conflicts.push({ rel: item.rel, reason: 'source-unreadable', detail: hash.error })
536
+ continue
537
+ }
538
+ if (item.sha256 !== null && hash !== item.sha256) {
539
+ conflicts.push({ rel: item.rel, reason: 'source-hash-changed', detail: `冻结 ${String(item.sha256).slice(0, 12)}… → 现在 ${hash.slice(0, 12)}…` })
540
+ }
541
+ }
542
+ return conflicts
543
+ }
544
+
545
+ /**
546
+ * F1.4:copy 模式的原件归档**按内容版本**落盘(`<批次>/v<sha12>/<rel>`),
547
+ * 同一版本重试复用(校验哈希),新版本不覆盖旧版本。返回库内相对路径。
548
+ */
549
+ async function archiveCopy(manifest, item, buf, contentSha, batchDir) {
550
+ const rel = `${batchDir}/v${contentSha.slice(0, 12)}/${item.rel}`
551
+ const destAbs = path.join(manifest.target, ...rel.split('/'))
552
+ const destCheck = await checkRealPath(manifest.target, destAbs)
553
+ if (!destCheck.ok) throw new Error(`复制目标越界/是链接(${destCheck.reason}):${destCheck.detail ?? ''}`)
554
+ if (existsSync(destAbs)) {
555
+ const cur = await sha256File(destAbs)
556
+ if (cur !== contentSha) throw new Error(`归档副本已被占用且内容不符(${cur.slice(0, 12)} ≠ ${contentSha.slice(0, 12)})`)
557
+ return rel
558
+ }
559
+ await mkdir(path.dirname(destAbs), { recursive: true })
560
+ const tmp = `${destAbs}.tmp-${process.pid}-${Math.random().toString(16).slice(2, 8)}`
561
+ await writeFile(tmp, buf)
562
+ await rename(tmp, destAbs)
563
+ const after = await sha256File(destAbs)
564
+ if (after !== contentSha) throw new Error(`归档写入后哈希不符(${after.slice(0, 12)} ≠ ${contentSha.slice(0, 12)})`)
565
+ return rel
566
+ }
567
+
568
+ /**
569
+ * 执行导入(可续跑)。
570
+ * 只写目标库;**不读当前绑定**。调用方必须传一个已绑定到 manifest.target 的 core(见 import-service)。
571
+ */
572
+ export async function runImport({ core, stateDir, importId, log = () => {}, onProgress = null }) {
573
+ if (!isValidImportId(importId)) return { ok: false, reason: 'bad-import-id', error: 'importId 非法(必须形如 imp-xxxxxxxxxx)' }
574
+ const resolved = await resolveImportDir(stateDir, importId)
575
+ if (!resolved.ok) return { ok: false, reason: resolved.reason, error: '导入任务目录非法:' + resolved.reason }
576
+ const manifest = await readManifest(stateDir, importId)
577
+ if (manifest === null) return { ok: false, error: '找不到导入清单(先 plan 再 run)' }
578
+ if (!core || typeof core.createEntry !== 'function') return { ok: false, error: '缺少写入 core' }
579
+ // 真 core 才做目标身份核验;注入桩(单元测试)没有 status 时跳过(服务层另有强制核验)
580
+ if (typeof core.status === 'function') {
581
+ const st = await core.status()
582
+ if (!st || !st.kbPath) return { ok: false, reason: 'target-unbound', error: '任务目标未绑定' }
583
+ if (normAbs(st.kbPath) !== normAbs(manifest.target)) {
584
+ return { ok: false, reason: 'target-root-mismatch', error: `core 实际根目录 ${st.kbPath} ≠ 任务目标 ${manifest.target}` }
585
+ }
586
+ if (manifest.targetKbId && st.kbId && manifest.targetKbId !== st.kbId) {
587
+ return { ok: false, reason: 'target-kbid-mismatch', error: `任务目标 kbId=${manifest.targetKbId},core 实际 kbId=${st.kbId}` }
588
+ }
589
+ }
590
+ if (manifest.stage === 'done') return { ok: true, manifest, note: '该任务已完成,未重复执行' }
591
+
592
+ // R4:执行前核验(源变了 → conflict,不写任何条目)
593
+ const conflicts = await preflight(manifest)
594
+ if (conflicts.length > 0) {
595
+ manifest.stage = 'conflict'
596
+ manifest.conflicts = conflicts
597
+ manifest.terminalReasons = conflicts.map((c) => `${c.rel}:${c.reason}`).slice(0, 20)
598
+ manifest.updatedAt = new Date().toISOString()
599
+ recount(manifest)
600
+ await writeManifest(stateDir, manifest)
601
+ log('warn', `导入 ${importId} 发现 ${conflicts.length} 处源变化:已停在 conflict,未写入条目(需重新 plan)`)
602
+ return { ok: false, conflict: true, manifest, error: '源文件在计划后发生变化:请重新 plan 再 run' }
603
+ }
604
+
605
+ manifest.stage = 'importing'
606
+ manifest.updatedAt = new Date().toISOString()
607
+ await writeManifest(stateDir, manifest)
608
+
609
+ const conf = typeof core.getConfig === 'function' ? await core.getConfig().catch(() => null) : null
610
+ const privateDirs = Array.isArray(conf?.privateDirs) && conf.privateDirs.length > 0 ? conf.privateDirs : DEFAULT_PRIVATE_DIRS
611
+ const targetKbId = manifest.targetKbId ?? (typeof core.status === 'function' ? (await core.status()).kbId : null)
612
+ const attach = manifest.mode === 'attach'
613
+ const batchDir = `90-收件箱/原件归档/${new Date().toISOString().slice(0, 10)}-导入-${importId.slice(4, 10)}`
614
+ const sourceMap = await readSourceMap(manifest.target)
615
+ let consecutiveFailures = 0
616
+ const results = { created: 0, updated: 0, unchanged: 0, duplicated: 0, failed: 0, skipped: 0 }
617
+
618
+ const fail = async (item, error) => {
619
+ item.status = 'failed'
620
+ item.error = String(error ?? 'unknown').slice(0, 300)
621
+ results.failed += 1
622
+ consecutiveFailures += 1
623
+ }
624
+
625
+ for (const item of manifest.items) {
626
+ if (existsSync(cancelPathOf(resolved.dir))) {
627
+ manifest.stage = 'canceled'
628
+ manifest.updatedAt = new Date().toISOString()
629
+ recount(manifest)
630
+ const { rm } = await import('node:fs/promises')
631
+ await rm(cancelPathOf(resolved.dir), { force: true })
632
+ await writeManifest(stateDir, manifest)
633
+ log('warn', `导入被取消(已完成 ${results.created + results.updated} 条)`)
634
+ return { ok: false, canceled: true, manifest }
635
+ }
636
+ if (item.status === 'done' || item.status === 'skipped') continue
637
+ const srcAbs = path.join(manifest.source, ...item.rel.split('/'))
638
+ try {
639
+ const boundary = await checkRealPath(manifest.source, srcAbs)
640
+ if (!boundary.ok) {
641
+ await fail(item, `源文件路径越界/是链接(${boundary.reason}):${boundary.detail ?? ''}`)
642
+ continue
643
+ }
644
+ // F1.3:冻结内容**只读一次** —— 哈希、正文、复制都用这同一份字节。
645
+ // 之后源文件再变,也不会把新内容混进这次导入(item.sha256 不可变)。
646
+ const buf = await readFile(srcAbs).catch(() => null)
647
+ if (buf === null) {
648
+ await fail(item, '源文件已不存在(计划后被移走/改名)')
649
+ continue
650
+ }
651
+ if (buf.length !== item.bytes) {
652
+ await fail(item, `源文件已变化(大小 ${item.bytes} → ${buf.length}):冻结清单不匹配,未导入`)
653
+ continue
654
+ }
655
+ const contentSha = sha256Of(buf)
656
+ if (item.sha256 === null) {
657
+ // 旧清单(p4 之前)没有哈希:只在这里补一次,之后不可变
658
+ item.sha256 = contentSha
659
+ }
660
+ if (item.sha256 !== contentSha) {
661
+ await fail(item, `源文件内容已变化(冻结 ${String(item.sha256).slice(0, 12)}… → 现在 ${contentSha.slice(0, 12)}…):未使用新内容,需重新 plan`)
662
+ continue
663
+ }
664
+ // F1.4:原件落位(copy 按内容版本归档;attach 留原位)
665
+ let originalRef
666
+ if (attach) {
667
+ originalRef = item.rel
668
+ } else {
669
+ try {
670
+ originalRef = await archiveCopy(manifest, item, buf, contentSha, batchDir)
671
+ } catch (error) {
672
+ await fail(item, `原件归档失败:${String((error && error.message) ?? error)}`)
673
+ continue
674
+ }
675
+ }
676
+ item.originalPath = originalRef
677
+
678
+ const cls = item.class
679
+ const isText = cls === 'markdown' || cls === 'text' || cls === 'code'
680
+ const text = isText ? buf.toString('utf8') : ''
681
+ const fm = cls === 'markdown' ? looseFrontmatter(text) : null
682
+ const titleBase = (fm && fm.title) || path.basename(item.rel, path.extname(item.rel)) || item.rel
683
+ const title = `导入·${titleBase}`.slice(0, 90)
684
+ const mapped = mapEntryKind({ fmType: fm && fm.type, rel: item.rel, privateDirs })
685
+ const tags = ['导入', ...(fm && Array.isArray(fm.tags) ? fm.tags.slice(0, 6) : [])]
686
+ if (!fm || !fm.type) tags.push('待整理')
687
+ if (mapped.privateHit !== null) tags.push('私密')
688
+ const body = entryBodyFor(item, originalRef, text)
689
+ const ver = contentSha.slice(0, 12)
690
+
691
+ // F1:同一来源(目标身份+源根+相对路径)再导入 → 受控 update;不再静默转 create
692
+ const key = sourceKey(targetKbId, manifest.source, item.rel)
693
+ const prev = sourceMap.entries[key]
694
+ const originalRegistration = typeof core.registerOriginal==='function' ? await core.registerOriginal({path:originalRef,kind:mapped.kind,category:CATEGORY_OF[mapped.kind]||mapped.kind,tags}) : null
695
+ let done = false
696
+ if(originalRegistration){if(!originalRegistration.ok)throw Error('原件分类未完成');item.status='done';item.entryId=originalRegistration.entryId;item.entryPath=originalRef;item.entryRevision=originalRegistration.revision;item.error=null;results.created++;done=true}
697
+ if (!done && prev && typeof prev.entryPath === 'string' && prev.entryId) {
698
+ const prevAbs = path.join(manifest.target, ...prev.entryPath.split('/'))
699
+ const lastRev = typeof prev.entryRevision === 'string' && prev.entryRevision.trim() !== '' ? prev.entryRevision : null
700
+ if (!existsSync(prevAbs)) {
701
+ await fail(item, 'entry-missing:上次生成的条目已不存在(不自动重建,避免绕过冲突;请人工确认后重建映射)')
702
+ done = true
703
+ } else if (lastRev === null) {
704
+ await fail(item, 'entry-revision-unknown:来源映射缺少上次生成的 revision,拒绝盲写(需重新建立该来源映射)')
705
+ done = true
706
+ } else if (prev.sha256 === contentSha) {
707
+ // 同一内容版本重试:幂等,不重写条目(不制造新 revision / updated 日期)
708
+ item.status = 'done'
709
+ item.entryId = prev.entryId
710
+ item.entryPath = prev.entryPath
711
+ item.entryRevision = lastRev
712
+ item.updated = true
713
+ item.unchanged = true
714
+ item.error = null
715
+ results.unchanged += 1
716
+ done = true
717
+ consecutiveFailures = 0
718
+ } else {
719
+ const prevCategory = prev.entryPath.split('/')[0]
720
+ const wantCategory = CATEGORY_OF[mapped.kind]
721
+ const categoryChanged = typeof wantCategory === 'string' && prevCategory !== wantCategory
722
+ if (categoryChanged) {
723
+ // 分区需要变化(例如旧库的公开条目其实是画像):新建到正确分区,旧条目改成指针(不删除、不留双份正文)
724
+ const createdNew = await core.createEntry({ kind: mapped.kind, title, content: body, tags, source: originalRef, requestId: `imp:${importId}:${item.rel}:remap:${ver}` })
725
+ if (!createdNew.ok) {
726
+ await fail(item, `remap-create-failed:${createdNew.reason ?? ''} ${createdNew.detail ?? ''}`)
727
+ done = true
728
+ } else {
729
+ const retired = await core.updateEntry({
730
+ entryId: prev.entryId,
731
+ expectedRevision: lastRev,
732
+ content: `## 已迁移\n\n本条目在再次导入时按 frontmatter type / 隐私规则重新映射到 \`${createdNew.path}\`;正文以新条目为准,这里只留指针。\n`,
733
+ patch: { tags: [...tags, '已迁移'], status: '已归档' },
734
+ requestId: `imp:${importId}:${item.rel}:retire:${ver}`,
735
+ })
736
+ if (!retired.ok) {
737
+ // 新条目已建;旧条目没退休成功(可能被用户改过)→ 如实失败,不覆盖
738
+ await fail(item, `remap-retire-failed:${retired.reason ?? (retired.conflict ? '旧条目被改动' : '')} ${retired.detail ?? ''}`)
739
+ } else {
740
+ item.status = 'done'
741
+ item.entryId = createdNew.entryId
742
+ item.entryPath = createdNew.path
743
+ item.entryRevision = createdNew.revision
744
+ item.updated = true
745
+ item.error = null
746
+ results.created += 1
747
+ consecutiveFailures = 0
748
+ }
749
+ done = true
750
+ }
751
+ } else {
752
+ const upd = await core.updateEntry({
753
+ entryId: prev.entryId,
754
+ expectedRevision: lastRev,
755
+ content: body,
756
+ patch: { title, tags, source: originalRef, type: mapped.kind },
757
+ requestId: `imp:${importId}:${item.rel}:upd:${ver}`,
758
+ })
759
+ if (upd.ok || upd.deduplicated) {
760
+ item.status = 'done'
761
+ item.entryId = prev.entryId
762
+ item.entryPath = prev.entryPath
763
+ item.entryRevision = upd.revision
764
+ item.updated = true
765
+ item.error = null
766
+ results.updated += 1
767
+ done = true
768
+ consecutiveFailures = 0
769
+ } else if (upd.conflict) {
770
+ // 期望 revision 不符:用户手改 / 外部改动 —— 不覆盖,也不转 create
771
+ await fail(item, `entry-conflict:条目在两次导入之间被改动(期望 ${lastRev} 实际 ${upd.currentRevision}),未覆盖`)
772
+ done = true
773
+ } else {
774
+ // 更新失败(索引不可用、frontmatter 不支持等)—— **不** 回退 create
775
+ await fail(item, `update-failed:${upd.reason ?? 'unknown'} ${upd.detail ?? ''}`)
776
+ done = true
777
+ }
778
+ }
779
+ }
780
+ }
781
+ if (!done && item.status !== 'failed') {
782
+ const created = await core.createEntry({ kind: mapped.kind, title, content: body, tags, source: originalRef, requestId: `imp:${importId}:${item.rel}:create:${ver}` })
783
+ if (created.ok) {
784
+ item.entryId = created.entryId
785
+ item.entryPath = created.path
786
+ item.entryRevision = created.revision
787
+ item.status = 'done'
788
+ item.error = null
789
+ if (created.deduplicated) results.duplicated += 1
790
+ else results.created += 1
791
+ consecutiveFailures = 0
792
+ } else {
793
+ await fail(item, `${created.reason ?? 'create-failed'}:${created.detail ?? ''}`)
794
+ }
795
+ }
796
+ if (item.status === 'done') {
797
+ const partition = typeof item.entryPath === 'string' ? item.entryPath.split('/')[0] : null
798
+ const isPrivate = mapped.privateHit !== null || mapped.kind === '画像'
799
+ sourceMap.entries[key] = {
800
+ kbId: targetKbId ?? null,
801
+ sourceRoot: toPosix(path.resolve(manifest.source)),
802
+ rel: toPosix(item.rel),
803
+ mode: attach ? 'attach' : 'copy',
804
+ sha256: contentSha,
805
+ size: buf.length,
806
+ mtimeMs: item.mtimeMs,
807
+ entryId: item.entryId,
808
+ entryPath: item.entryPath,
809
+ entryRevision: item.entryRevision ?? null,
810
+ originalPath: originalRef,
811
+ originalSha256: contentSha,
812
+ private: isPrivate,
813
+ privatePartition: isPrivate ? partition : null,
814
+ importId,
815
+ updatedAt: new Date().toISOString(),
816
+ }
817
+ await locked(sourcesFileOf(manifest.target), async () => {
818
+ const latest = await readSourceMap(manifest.target)
819
+ latest.entries[key] = sourceMap.entries[key]
820
+ await writeSourceMap(manifest.target, latest)
821
+ })
822
+ await locked(policyFile(manifest.target), async () => {
823
+ const policy = readIndexPolicy(manifest.target), group = groupFor(policy, originalRef)
824
+ if (group?.pending) { group.pending = false; await savePolicy(manifest.target, policy) }
825
+ })
826
+ }
827
+ } catch (error) {
828
+ await fail(item, String((error && error.message) ?? error))
829
+ }
830
+ recount(manifest)
831
+ manifest.updatedAt = new Date().toISOString()
832
+ await writeManifest(stateDir, manifest)
833
+ if (onProgress) await onProgress(manifest)
834
+ if (consecutiveFailures >= 8) {
835
+ const reasons = [`连续失败 ${consecutiveFailures} 次(已中止)`]
836
+ manifest.stage = 'partial'
837
+ manifest.terminalReasons = reasons
838
+ await writeManifest(stateDir, manifest)
839
+ log('error', `导入连续失败 ${consecutiveFailures} 次,已中止(已完成 ${results.created + results.updated} 条,可修复后重试)`)
840
+ return { ok: false, manifest, aborted: true }
841
+ }
842
+ }
843
+
844
+ // 核验:原件哈希是否仍与清单一致(复制模式核副本、接入模式核源文件)
845
+ manifest.stage = 'verifying'
846
+ await writeManifest(stateDir, manifest)
847
+ const verify = { checked: 0, mismatch: [], skipped: 0 }
848
+ for (const item of manifest.items) {
849
+ if (item.status !== 'done' || item.sha256 === null) continue
850
+ if (verify.checked >= 500) {
851
+ verify.skipped += 1
852
+ continue
853
+ }
854
+ const abs = attach ? path.join(manifest.source, ...item.rel.split('/')) : path.join(manifest.target, ...item.originalPath.split('/'))
855
+ try {
856
+ const h = await sha256File(abs)
857
+ if (h !== item.sha256) verify.mismatch.push({ rel: item.rel, expected: item.sha256, actual: h })
858
+ verify.checked += 1
859
+ } catch (error) {
860
+ verify.mismatch.push({ rel: item.rel, error: String((error && error.message) ?? error) })
861
+ }
862
+ }
863
+ manifest.verify = verify
864
+
865
+ // R4:终态闭环 —— failed / pending / 截断 / 扫描错误 / 哈希不符 任一存在都不能报完整成功
866
+ const c = recount(manifest)
867
+ const reasons = []
868
+ if (c.failed > 0) reasons.push(`失败 ${c.failed} 条`)
869
+ if (c.pending > 0) reasons.push(`未完成 ${c.pending} 条`)
870
+ if (manifest.scan && manifest.scan.truncated) reasons.push(`扫描被截断(${manifest.scan.truncated.reason})`)
871
+ if (manifest.scan && manifest.scan.errors > 0) reasons.push(`扫描错误 ${manifest.scan.errors} 处`)
872
+ if (verify.mismatch.length > 0) reasons.push(`原件哈希不符 ${verify.mismatch.length} 条`)
873
+ manifest.terminalReasons = reasons
874
+ manifest.stage = reasons.length === 0 ? 'done' : 'partial'
875
+ manifest.updatedAt = new Date().toISOString()
876
+ await writeManifest(stateDir, manifest)
877
+ log(manifest.stage === 'done' ? 'info' : 'warn', `导入 ${importId} 结束:stage=${manifest.stage} 新建 ${results.created} / 更新 ${results.updated} / 未变 ${results.unchanged} / 失败 ${results.failed}${reasons.length ? ';原因:' + reasons.join(';') : ''}`)
878
+ return { ok: manifest.stage === 'done', manifest }
879
+ }
880
+
881
+ export async function cancelImport(stateDir, importId) {
882
+ if (!isValidImportId(importId)) return { ok: false, reason: 'bad-import-id', error: 'importId 非法(必须形如 imp-xxxxxxxxxx)' }
883
+ const resolved = await resolveImportDir(stateDir, importId)
884
+ if (!resolved.ok) return { ok: false, reason: resolved.reason, error: '导入任务目录非法:' + resolved.reason }
885
+ const manifest = await readManifest(stateDir, importId)
886
+ if (manifest === null) return { ok: false, reason: 'not-found', error: '找不到导入任务:' + importId }
887
+ await mkdir(resolved.dir, { recursive: true })
888
+ await writeFile(cancelPathOf(resolved.dir), new Date().toISOString(), 'utf8')
889
+ return { ok: true, importId, stage: 'cancel-requested' }
890
+ }
891
+
892
+ export async function listImports(stateDir) {
893
+ const dir = importsRootOf(stateDir)
894
+ try {
895
+ const { readdir } = await import('node:fs/promises')
896
+ const names = await readdir(dir, { withFileTypes: true })
897
+ const out = []
898
+ for (const n of names) {
899
+ if (!n.isDirectory()) continue
900
+ if (!isValidImportId(n.name)) continue
901
+ const m = await readManifest(stateDir, n.name)
902
+ if (m) out.push({ importId: m.importId, mode: m.mode, source: m.source, target: m.target, targetKbId: m.targetKbId ?? null, stage: m.stage, createdAt: m.createdAt, updatedAt: m.updatedAt, counts: m.counts, terminalReasons: m.terminalReasons ?? [] })
903
+ }
904
+ out.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
905
+ return out
906
+ } catch {
907
+ return []
908
+ }
909
+ }