@jjh32456/longlive 0.0.0-stage → 2.0.0

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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,1003 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 1.8.11 · 记忆网络边表构建器(recall-edges/v1)
4
+ *
5
+ * 从可复核的离线来源推导「卡 → 卡」语义边,写入
6
+ * `<memoryRoot>/.longlive/recall/edges.jsonl`(或 --out 指定的文件),供召回层的
7
+ * 1-hop 边扩展(expandEdges)与 backlinks 使用。
8
+ *
9
+ * 三个来源(都可单独关掉):
10
+ * 1) 卡面显式边:frontmatter 里以边类型命名的 key(supersedes / conflicts_with / …)
11
+ * 以及 `edges:` 里的简写项(`<type>: <path>` 或裸路径 → mentions)。
12
+ * 2) 卡体 [[wikilink]] → mentions 边(只记「这张卡引用了那张卡」,不推断方向语义)。
13
+ * 3) links.jsonl 共现:同一 term 下权重最高的若干张卡两两连 same_topic 边
14
+ * (弱关联元数据,固定 confidence 0.5;same_topic 不参与注入扩展)。
15
+ * 4) 决策记录:lifecycle-plan.json 的 `edges[]`(机器可读、带 evidence/quote)。
16
+ *
17
+ * 诚实边界(写进统计输出,不许在验收里含糊):
18
+ * - LINKS-SEED-v3.csv 不在本地可及目录;本构建器**不重建 links.jsonl**,
19
+ * 也不消费 CSV。six-stem 这类新卡进入 link 表只能靠运行期学习边或 edges 扩展。
20
+ * - 目标卡不存在 / 路径归一化失败的边丢进 dropped + badRefs 并计数。
21
+ * - 本工具不读会话、不改记忆卡、不改 frontmatter(lifecycle 迁移归迁移器)。
22
+ *
23
+ * 设计约束:
24
+ * - 幂等:同样的输入 + 同样的已有表 → 输出字节不变(不重写、不写审计);
25
+ * 已有表里不是本构建器产出的边原样保留。
26
+ * - 原子:tmp → fsync → rename;写前把旧表备份到 `backups/`,
27
+ * 写后追加一行审计到 `edges-audit.jsonl`。
28
+ * - 不硬编码个人路径:记忆根来自参数或环境变量。
29
+ *
30
+ * 用法:
31
+ * node scripts/edges-build.mjs --memory-root <记忆根> [--dry-run] [--json]
32
+ * node scripts/edges-build.mjs --memory-root <记忆根> --out <edges.jsonl> [--dry-run]
33
+ * node scripts/edges-build.mjs --rollback <备份文件> --memory-root <记忆根>
34
+ *
35
+ * 记忆根优先级:--memory-root > $DSH_LONGLIVE_MEMORY_ROOT > $DSH_MEM,
36
+ * 给了 --out 且它以 `.longlive/recall/edges.jsonl` 结尾时也可以从它反推。
37
+ */
38
+
39
+ import fs from 'node:fs';
40
+ import path from 'node:path';
41
+ import { createHash } from 'node:crypto';
42
+ import { fileURLToPath } from 'node:url';
43
+
44
+ import { parseFrontmatter } from '../src/recall/cards.mjs';
45
+ import { normalizeCardPath, parseLinksText } from '../src/recall/links.mjs';
46
+ import {
47
+ EDGES_SCHEMA,
48
+ EDGE_TYPES,
49
+ dedupeEdges,
50
+ edgeKey,
51
+ normalizeEdge,
52
+ parseEdgesText,
53
+ serializeEdges,
54
+ symmetrizeEdges,
55
+ } from '../src/recall/edges.js';
56
+
57
+ const SCRIPT = 'edges-build';
58
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
59
+ const PACKAGE_ROOT = path.resolve(HERE, '..');
60
+
61
+ const DEFAULTS = Object.freeze({
62
+ cardsDirs: ['topics', 'procedures', 'handover'],
63
+ maxTerms: 50, // 取权重总和最高的前 N 个 term 做共现
64
+ maxCardsPerTerm: 5, // 每个 term 取权重最高的前 N 张卡
65
+ maxSameTopic: 200, // same_topic 边总数上限
66
+ frontmatterConfidence: 0.8, // 作者显式写下的边
67
+ wikilinkConfidence: 0.5, // 只是引用,不推断语义
68
+ linksConfidence: 0.5, // 同词共现,弱关联(schema 默认值,不发明强度)
69
+ });
70
+
71
+ const USAGE = `用法:
72
+ node scripts/edges-build.mjs --memory-root <记忆根> [--out <edges.jsonl>] [--dry-run] [--json]
73
+ node scripts/edges-build.mjs --rollback <备份 jsonl> --memory-root <记忆根> [--json]
74
+
75
+ 选项:
76
+ --memory-root <路径> 记忆根(缺省读 $DSH_LONGLIVE_MEMORY_ROOT / $DSH_MEM)
77
+ --out <路径> 边表输出路径(缺省 <记忆根>/.longlive/recall/edges.jsonl)
78
+ --plan <路径> lifecycle-plan.json(缺省:<记忆根>/.longlive/lifecycle-plan.json,
79
+ 再退到本包 src/memory/lifecycle-plan.json)
80
+ --links-file <路径> links.jsonl(缺省 <记忆根>/.longlive/recall/links.jsonl)
81
+ --cards-dirs <a,b> 扫卡目录(缺省 topics,procedures,handover)
82
+ --max-terms <n> 共现取前 N 个 term(缺省 ${DEFAULTS.maxTerms})
83
+ --max-cards-per-term <n> 每个 term 取前 N 张卡(缺省 ${DEFAULTS.maxCardsPerTerm})
84
+ --max-same-topic <n> same_topic 边总数上限(缺省 ${DEFAULTS.maxSameTopic})
85
+ --no-cards 不读卡面(显式边 / wikilink)
86
+ --no-links 不读 links.jsonl 共现
87
+ --no-plan 不读 lifecycle-plan.json
88
+ --dry-run 只统计与对比,不写文件、不写审计
89
+ --json 机器可读统计(stdout 只输出一个 JSON 对象)
90
+ --rollback <路径> 把指定备份原子写回目标边表(写前备份当前表 + 审计)
91
+ -h, --help 显示本帮助
92
+
93
+ 来源说明:
94
+ - 卡面:frontmatter 边 key(${EDGE_TYPES.filter((t) => t !== 'same_topic').join(' / ')})与 body [[wikilink]]。
95
+ - links.jsonl 共现 → same_topic(不参与注入扩展,只进网络/backlinks)。
96
+ - lifecycle-plan.json 的 edges[] 是决策记录(显式机器可读)。
97
+ - 本机没有 LINKS-SEED-v3.csv;本工具不重建 links.jsonl,也不消费 CSV。
98
+ `;
99
+
100
+ function parseArgs(argv) {
101
+ const args = {
102
+ memoryRoot: '',
103
+ out: '',
104
+ plan: '',
105
+ linksFile: '',
106
+ cardsDirs: '',
107
+ maxTerms: null,
108
+ maxCardsPerTerm: null,
109
+ maxSameTopic: null,
110
+ noCards: false,
111
+ noLinks: false,
112
+ noPlan: false,
113
+ dryRun: false,
114
+ json: false,
115
+ rollback: '',
116
+ help: false,
117
+ };
118
+ for (let i = 0; i < argv.length; i += 1) {
119
+ const arg = argv[i];
120
+ switch (arg) {
121
+ case '--memory-root': args.memoryRoot = argv[++i] ?? ''; break;
122
+ case '--out': args.out = argv[++i] ?? ''; break;
123
+ case '--plan': args.plan = argv[++i] ?? ''; break;
124
+ case '--links-file': args.linksFile = argv[++i] ?? ''; break;
125
+ case '--cards-dirs': args.cardsDirs = argv[++i] ?? ''; break;
126
+ case '--max-terms': args.maxTerms = Number(argv[++i]); break;
127
+ case '--max-cards-per-term': args.maxCardsPerTerm = Number(argv[++i]); break;
128
+ case '--max-same-topic': args.maxSameTopic = Number(argv[++i]); break;
129
+ case '--no-cards': args.noCards = true; break;
130
+ case '--no-links': args.noLinks = true; break;
131
+ case '--no-plan': args.noPlan = true; break;
132
+ case '--dry-run': args.dryRun = true; break;
133
+ case '--json': args.json = true; break;
134
+ case '--rollback': args.rollback = argv[++i] ?? ''; break;
135
+ case '-h':
136
+ case '--help': args.help = true; break;
137
+ default: throw new Error(`E_UNKNOWN_ARG:不认识的参数 ${arg}`);
138
+ }
139
+ }
140
+ return args;
141
+ }
142
+
143
+ function positiveInt(value, fallback) {
144
+ const n = Number(value);
145
+ return Number.isInteger(n) && n > 0 ? n : fallback;
146
+ }
147
+
148
+ function toPosix(p) {
149
+ return String(p ?? '').replace(/\\/g, '/');
150
+ }
151
+
152
+ function relToRoot(abs, root) {
153
+ const rel = path.relative(root, abs);
154
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return toPosix(abs);
155
+ return toPosix(rel);
156
+ }
157
+
158
+ function clip(text, maxChars = 160) {
159
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
160
+ return flat.length > maxChars ? `${flat.slice(0, Math.max(1, maxChars - 1))}…` : flat;
161
+ }
162
+
163
+ function toList(value) {
164
+ if (value == null) return [];
165
+ if (Array.isArray(value)) return value.flatMap((item) => toList(item));
166
+ if (typeof value === 'string' || typeof value === 'number') {
167
+ const text = String(value).trim();
168
+ return text === '' ? [] : [text];
169
+ }
170
+ return [];
171
+ }
172
+
173
+ /** 相对卡路径(posix、以 .md 结尾、不得是绝对/上级路径);失败返回 ''。 */
174
+ function resolveCardRef(ref, memoryRoot) {
175
+ const raw = String(ref ?? '').trim();
176
+ if (raw === '' || /^https?:\/\//i.test(raw) || raw.startsWith('#')) return '';
177
+ let rel = normalizeCardPath(raw, memoryRoot);
178
+ if (rel === '') return '';
179
+ rel = rel.replace(/^\/+/, '');
180
+ if (path.isAbsolute(rel) || /^[A-Za-z]:\//.test(rel)) return '';
181
+ if (!rel.includes('/')) return ''; // 裸文件名歧义,不猜
182
+ if (!/\.[A-Za-z0-9]+$/.test(rel)) rel += '.md';
183
+ if (rel.split('/').some((segment) => segment === '..' || segment === '.')) return '';
184
+ return rel;
185
+ }
186
+
187
+ function walkMarkdown(dirAbs, prefix = '') {
188
+ const out = [];
189
+ let entries = [];
190
+ try {
191
+ entries = fs.readdirSync(dirAbs, { withFileTypes: true });
192
+ } catch {
193
+ return out;
194
+ }
195
+ for (const entry of entries) {
196
+ if (entry.name.startsWith('.') || entry.isSymbolicLink()) continue;
197
+ const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
198
+ if (entry.isDirectory()) out.push(...walkMarkdown(path.join(dirAbs, entry.name), rel));
199
+ else if (entry.isFile() && /\.md$/i.test(entry.name)) out.push(rel);
200
+ }
201
+ return out;
202
+ }
203
+
204
+ function sha256OfFile(abs, cache) {
205
+ if (cache && cache.has(abs)) return cache.get(abs);
206
+ let sha = null;
207
+ try {
208
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
209
+ sha = createHash('sha256').update(fs.readFileSync(abs)).digest('hex');
210
+ }
211
+ } catch {
212
+ sha = null;
213
+ }
214
+ if (cache) cache.set(abs, sha);
215
+ return sha;
216
+ }
217
+
218
+ function withEvidenceSha(edge, memoryRoot, shaCache) {
219
+ if (!edge || !edge.evidence || !edge.evidence.path) return edge;
220
+ const abs = path.isAbsolute(edge.evidence.path)
221
+ ? edge.evidence.path
222
+ : path.join(memoryRoot, edge.evidence.path);
223
+ const sha = sha256OfFile(abs, shaCache);
224
+ if (!sha || edge.evidence.sha256 === sha) return edge;
225
+ return { ...edge, evidence: { ...edge.evidence, sha256: sha } };
226
+ }
227
+
228
+ /** 在 frontmatter 行范围里定位某个 key / 某个值所在行,给 evidence.lines + quote。 */
229
+ function locateValueLine(lines, endLine, key, value) {
230
+ const limit = Math.max(0, Math.min(endLine, lines.length));
231
+ const keyRe = new RegExp(`^\\s*${String(key).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:`);
232
+ for (let i = 0; i < limit; i += 1) {
233
+ const line = lines[i];
234
+ if (keyRe.test(line) && String(line).includes(value)) return { line: i + 1, quote: clip(line) };
235
+ }
236
+ for (let i = 0; i < limit; i += 1) {
237
+ const line = lines[i];
238
+ if (String(line).includes(value) && /^\s*(?:-|[A-Za-z_]+\s*:)/.test(line)) {
239
+ return { line: i + 1, quote: clip(line) };
240
+ }
241
+ }
242
+ return null;
243
+ }
244
+
245
+ /**
246
+ * 读卡目录:frontmatter 显式边 + `edges:` 简写 + body [[wikilink]] → mentions。
247
+ * 目标卡是否存在在收尾时统一过滤(缺失 → dropped + badRefs)。
248
+ */
249
+ function collectCardEdges({ memoryRoot, dirs, generatedAt, shaCache }) {
250
+ const existsCache = new Map();
251
+ const exists = (rel) => {
252
+ if (existsCache.has(rel)) return existsCache.get(rel);
253
+ const ok = fs.existsSync(path.join(memoryRoot, rel));
254
+ existsCache.set(rel, ok);
255
+ return ok;
256
+ };
257
+ const stats = {
258
+ dirs: [...dirs],
259
+ missingDirs: [],
260
+ scanned: 0,
261
+ noFrontmatter: 0,
262
+ explicit: 0,
263
+ shorthand: 0,
264
+ wikilinks: 0,
265
+ mentions: 0,
266
+ bareLinks: 0,
267
+ bareResolved: 0,
268
+ };
269
+ const rawEdges = [];
270
+ const dropped = [];
271
+ const badRefs = [];
272
+
273
+ const files = [];
274
+ for (const dir of dirs) {
275
+ const abs = path.join(memoryRoot, dir);
276
+ let ok = false;
277
+ try { ok = fs.existsSync(abs) && fs.statSync(abs).isDirectory(); } catch { ok = false; }
278
+ if (!ok) { stats.missingDirs.push(dir); continue; }
279
+ for (const relFile of walkMarkdown(abs)) files.push({ rel: `${dir}/${relFile}`, abs: path.join(abs, relFile) });
280
+ }
281
+ files.sort((a, b) => a.rel.localeCompare(b.rel));
282
+
283
+ // 裸文件名 [[reuse-memory-before-build]]:只在全库唯一命中时解析;
284
+ // 多个同名视为歧义,丢弃进 badRefs(不猜)。
285
+ const byBasename = new Map();
286
+ for (const file of files) {
287
+ const name = path.basename(file.rel, '.md').toLowerCase();
288
+ if (!byBasename.has(name)) byBasename.set(name, []);
289
+ byBasename.get(name).push(file.rel);
290
+ }
291
+ const resolveRef = (ref) => {
292
+ const viaPath = resolveCardRef(ref, memoryRoot);
293
+ if (viaPath !== '') return viaPath;
294
+ const raw = String(ref ?? '').trim().replace(/\\/g, '/');
295
+ if (raw === '' || raw.includes('/') || /^https?:\/\//i.test(raw) || raw.startsWith('#')) return '';
296
+ const hits = byBasename.get(raw.replace(/\.md$/i, '').toLowerCase()) ?? [];
297
+ return hits.length === 1 ? hits[0] : '';
298
+ };
299
+
300
+ for (const file of files) {
301
+ let raw = '';
302
+ try {
303
+ raw = fs.readFileSync(file.abs, 'utf8');
304
+ } catch (error) {
305
+ dropped.push({ kind: 'card-read', from: file.rel, reason: String(error?.code ?? error) });
306
+ continue;
307
+ }
308
+ stats.scanned += 1;
309
+ const clean = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
310
+ const lines = clean.split('\n');
311
+ const parsed = parseFrontmatter(clean);
312
+ if (!parsed.hasFrontmatter) stats.noFrontmatter += 1;
313
+ let fmEnd = 0;
314
+ if (parsed.hasFrontmatter) {
315
+ for (let i = 1; i < lines.length; i += 1) {
316
+ if (lines[i].trim() === '---') { fmEnd = i + 1; break; }
317
+ }
318
+ }
319
+ const data = parsed.data && typeof parsed.data === 'object' ? parsed.data : {};
320
+
321
+ const pushExplicit = (type, refText, source) => {
322
+ const to = resolveRef(refText);
323
+ if (to === '') {
324
+ dropped.push({ kind: source, from: file.rel, type, ref: clip(refText, 120), reason: 'bad-path' });
325
+ badRefs.push({ kind: source, source: file.rel, ref: clip(refText, 120), reason: 'bad-path' });
326
+ return;
327
+ }
328
+ const loc = locateValueLine(lines, fmEnd, type, String(refText).trim());
329
+ rawEdges.push({
330
+ from: file.rel,
331
+ to,
332
+ type,
333
+ confidence: DEFAULTS.frontmatterConfidence,
334
+ source,
335
+ created_at: generatedAt,
336
+ evidence: withEvidenceSha({
337
+ path: file.rel,
338
+ ...(loc ? { lines: [loc.line, loc.line], quote: loc.quote } : {}),
339
+ }, memoryRoot, shaCache),
340
+ });
341
+ };
342
+
343
+ // 1) 以边类型命名的 frontmatter key(作者显式写下)
344
+ for (const type of EDGE_TYPES) {
345
+ for (const ref of toList(data[type])) {
346
+ pushExplicit(type, ref, 'card-frontmatter');
347
+ stats.explicit += 1;
348
+ }
349
+ }
350
+ // 2) `edges:` 简写项:`<type>: <path>` / `<type> <path>` / 裸路径 → mentions
351
+ for (const item of toList(data.edges)) {
352
+ const text = String(item).trim();
353
+ const m = text.match(/^([a-z_]+)\s*[: ]\s*(.+)$/);
354
+ if (m && EDGE_TYPES.includes(m[1])) {
355
+ pushExplicit(m[1], m[2], 'card-frontmatter');
356
+ stats.shorthand += 1;
357
+ continue;
358
+ }
359
+ if (m && !m[1].includes('/')) {
360
+ dropped.push({ kind: 'card-frontmatter', from: file.rel, ref: clip(text, 120), reason: 'unknown-type' });
361
+ badRefs.push({ kind: 'card-frontmatter', source: file.rel, ref: clip(text, 120), reason: 'unknown-type' });
362
+ continue;
363
+ }
364
+ pushExplicit('mentions', text, 'card-frontmatter');
365
+ stats.shorthand += 1;
366
+ }
367
+ // 3) 卡体 [[wikilink]] → mentions(只记引用事实)
368
+ for (let i = fmEnd; i < lines.length; i += 1) {
369
+ const line = lines[i];
370
+ if (!line.includes('[[')) continue;
371
+ const re = /\[\[([^\]|#]+)(?:\|[^\]]*)?\]\]/g;
372
+ let m;
373
+ while ((m = re.exec(line)) !== null) {
374
+ const refText = m[1].trim();
375
+ stats.wikilinks += 1;
376
+ const to = resolveRef(refText);
377
+ if (to === '') {
378
+ stats.bareLinks += 1;
379
+ badRefs.push({ kind: 'wikilink', source: file.rel, line: i + 1, ref: clip(refText, 120), reason: 'ambiguous-or-bad' });
380
+ continue;
381
+ }
382
+ if (!refText.replace(/\\/g, '/').includes('/')) stats.bareResolved += 1;
383
+ rawEdges.push({
384
+ from: file.rel,
385
+ to,
386
+ type: 'mentions',
387
+ confidence: DEFAULTS.wikilinkConfidence,
388
+ source: 'card-wikilink',
389
+ created_at: generatedAt,
390
+ evidence: withEvidenceSha({ path: file.rel, lines: [i + 1, i + 1], quote: clip(line) }, memoryRoot, shaCache),
391
+ });
392
+ stats.mentions += 1;
393
+ }
394
+ }
395
+ }
396
+
397
+ // 目标卡存在性过滤(D5:目标不存在/坏路径丢 dropped 并计数)
398
+ const edges = [];
399
+ for (const edge of rawEdges) {
400
+ if (!exists(edge.from)) {
401
+ dropped.push({ kind: 'missing-source', from: edge.from, to: edge.to, type: edge.type, reason: 'missing-source' });
402
+ continue;
403
+ }
404
+ if (!exists(edge.to)) {
405
+ dropped.push({ kind: 'missing-target', from: edge.from, to: edge.to, type: edge.type, reason: 'missing-target' });
406
+ badRefs.push({ kind: edge.source === 'card-wikilink' ? 'wikilink' : 'frontmatter', source: edge.from, ref: edge.to, reason: 'missing-target' });
407
+ continue;
408
+ }
409
+ edges.push(edge);
410
+ }
411
+ return { edges, dropped, badRefs, stats };
412
+ }
413
+
414
+ /**
415
+ * links.jsonl 共现 → same_topic(弱关联元数据,固定 confidence 0.5)。
416
+ * 取权重总和最高的前 maxTerms 个 term;每个 term 取前 maxCardsPerTerm 张卡两两连边,
417
+ * 方向按权重高→低(同权重按路径升序,保证确定性)。总数受 maxSameTopic 限制。
418
+ */
419
+ function collectLinksEdges({ memoryRoot, linksFile, maxTerms, maxCardsPerTerm, maxSameTopic, generatedAt, shaCache }) {
420
+ const stats = {
421
+ present: false,
422
+ path: linksFile,
423
+ lines: 0,
424
+ bad: 0,
425
+ terms: 0,
426
+ cards: 0,
427
+ missingCards: 0,
428
+ usedTerms: 0,
429
+ pairs: 0,
430
+ sameTopic: 0,
431
+ skippedByCap: 0,
432
+ };
433
+ if (!fs.existsSync(linksFile)) return { edges: [], dropped: [], badRefs: [], stats };
434
+ stats.present = true;
435
+ let text = '';
436
+ try {
437
+ text = fs.readFileSync(linksFile, 'utf8');
438
+ } catch (error) {
439
+ return { edges: [], dropped: [{ kind: 'links-read', path: linksFile, reason: String(error?.code ?? error) }], badRefs: [], stats };
440
+ }
441
+ const parsed = parseLinksText(text, { memoryRoot });
442
+ stats.lines = parsed.lines;
443
+ stats.bad = parsed.bad;
444
+
445
+ const cardOk = new Map();
446
+ const byTerm = new Map();
447
+ for (const edge of parsed.edges) {
448
+ if (!cardOk.has(edge.cardPath)) cardOk.set(edge.cardPath, fs.existsSync(path.join(memoryRoot, edge.cardPath)));
449
+ if (!cardOk.get(edge.cardPath)) continue;
450
+ if (!byTerm.has(edge.term)) byTerm.set(edge.term, []);
451
+ byTerm.get(edge.term).push({ cardPath: edge.cardPath, weight: edge.weight });
452
+ }
453
+ const badRefs = [];
454
+ for (const [cardPath, ok] of cardOk) {
455
+ if (!ok) badRefs.push({ kind: 'links', ref: cardPath, reason: 'missing-card' });
456
+ }
457
+ stats.cards = [...cardOk.keys()].length;
458
+ stats.missingCards = badRefs.length;
459
+ stats.terms = byTerm.size;
460
+
461
+ const rows = [...byTerm.entries()].map(([term, cards]) => {
462
+ cards.sort((a, b) => b.weight - a.weight || a.cardPath.localeCompare(b.cardPath));
463
+ const total = cards.reduce((sum, card) => sum + card.weight, 0);
464
+ return { term, cards, total };
465
+ });
466
+ rows.sort((a, b) => b.total - a.total || a.term.localeCompare(b.term));
467
+ const picked = rows.slice(0, maxTerms);
468
+ stats.usedTerms = picked.length;
469
+
470
+ const linksRel = relToRoot(linksFile, memoryRoot);
471
+ const evidenceBase = withEvidenceSha({ path: linksRel }, memoryRoot, shaCache);
472
+ const edges = [];
473
+ for (const row of picked) {
474
+ const top = row.cards.slice(0, maxCardsPerTerm);
475
+ for (let i = 0; i < top.length; i += 1) {
476
+ for (let j = i + 1; j < top.length; j += 1) {
477
+ const a = top[i];
478
+ const b = top[j];
479
+ const first = a.weight > b.weight || (a.weight === b.weight && a.cardPath <= b.cardPath) ? a : b;
480
+ const second = first === a ? b : a;
481
+ stats.pairs += 1;
482
+ edges.push({
483
+ from: first.cardPath,
484
+ to: second.cardPath,
485
+ type: 'same_topic',
486
+ confidence: DEFAULTS.linksConfidence,
487
+ source: 'links-cooccurrence',
488
+ created_at: generatedAt,
489
+ evidence: {
490
+ ...evidenceBase,
491
+ quote: `共现词「${clip(row.term, 60)}」:${first.cardPath}(w=${first.weight}) ↔ ${second.cardPath}(w=${second.weight})`,
492
+ },
493
+ });
494
+ }
495
+ }
496
+ }
497
+ let kept = edges;
498
+ if (edges.length > maxSameTopic) {
499
+ stats.skippedByCap = edges.length - maxSameTopic;
500
+ kept = edges.slice(0, maxSameTopic);
501
+ }
502
+ stats.sameTopic = kept.length;
503
+ return { edges: kept, dropped: [], badRefs, stats };
504
+ }
505
+
506
+ /**
507
+ * 决策记录(lifecycle-plan/v1)的 edges[]:显式机器可读,带 evidence.path/lines/quote。
508
+ * 目标卡还没迁移出来时按 D5 丢弃并计入 badRefs(迁移完成重建即自动出现)。
509
+ */
510
+ function collectPlanEdges({ memoryRoot, planPath, generatedAt, shaCache }) {
511
+ const stats = { present: false, path: planPath, schema: null, cards: 0, extracts: 0, edges: 0, kept: 0, missingTarget: 0 };
512
+ if (!planPath || !fs.existsSync(planPath)) return { edges: [], dropped: [], badRefs: [], stats, plan: null };
513
+ stats.present = true;
514
+ let plan = null;
515
+ try {
516
+ plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
517
+ } catch (error) {
518
+ return { edges: [], dropped: [{ kind: 'plan-parse', path: planPath, reason: String(error?.message ?? error) }], badRefs: [], stats, plan: null };
519
+ }
520
+ stats.schema = typeof plan?.schema === 'string' ? plan.schema : null;
521
+ stats.cards = Array.isArray(plan?.cards) ? plan.cards.length : 0;
522
+ stats.extracts = Array.isArray(plan?.extracts) ? plan.extracts.length : 0;
523
+ const rawEdges = Array.isArray(plan?.edges) ? plan.edges : [];
524
+ stats.edges = rawEdges.length;
525
+ const planGeneratedAt = typeof plan?.generated_at === 'string' ? plan.generated_at : generatedAt;
526
+
527
+ const edges = [];
528
+ const dropped = [];
529
+ const badRefs = [];
530
+ for (const raw of rawEdges) {
531
+ const edge = normalizeEdge({
532
+ ...raw,
533
+ created_at: raw?.created_at ?? planGeneratedAt,
534
+ source: raw?.source ?? 'lifecycle-plan/v1',
535
+ }, { memoryRoot });
536
+ if (!edge) {
537
+ dropped.push({ kind: 'plan-edge', reason: 'invalid', raw: clip(JSON.stringify(raw), 160) });
538
+ badRefs.push({ kind: 'plan-edge', ref: clip(JSON.stringify(raw), 120), reason: 'invalid' });
539
+ continue;
540
+ }
541
+ const withSha = withEvidenceSha(edge, memoryRoot, shaCache);
542
+ if (!fs.existsSync(path.join(memoryRoot, withSha.from))) {
543
+ dropped.push({ kind: 'plan-edge', from: withSha.from, to: withSha.to, type: withSha.type, reason: 'missing-source' });
544
+ badRefs.push({ kind: 'plan-edge', ref: withSha.from, reason: 'missing-source' });
545
+ continue;
546
+ }
547
+ if (!fs.existsSync(path.join(memoryRoot, withSha.to))) {
548
+ dropped.push({ kind: 'plan-edge', from: withSha.from, to: withSha.to, type: withSha.type, reason: 'missing-target' });
549
+ badRefs.push({ kind: 'plan-edge', ref: withSha.to, reason: 'missing-target' });
550
+ stats.missingTarget += 1;
551
+ continue;
552
+ }
553
+ edges.push(withSha);
554
+ }
555
+ stats.kept = edges.length;
556
+ return { edges, dropped, badRefs, stats, plan };
557
+ }
558
+
559
+ /**
560
+ * INDEX.md 生成段里的路径引用审计(合并单元格 `a.md + b.md` 单独计数)。
561
+ * 这是只读审计,不影响边表内容。
562
+ */
563
+ function collectIndexRefs({ memoryRoot }) {
564
+ const stats = { present: false, path: path.join(memoryRoot, 'INDEX.md'), refs: 0, uniqueRefs: 0, resolved: 0, unresolved: 0, mergedCells: 0 };
565
+ const badRefs = [];
566
+ const indexPath = stats.path;
567
+ if (!fs.existsSync(indexPath)) return { stats, badRefs };
568
+ stats.present = true;
569
+ let text = '';
570
+ try { text = fs.readFileSync(indexPath, 'utf8'); } catch (error) {
571
+ return { stats: { ...stats, error: String(error?.code ?? error) }, badRefs };
572
+ }
573
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
574
+ let start = 0;
575
+ let end = lines.length;
576
+ const begin = lines.findIndex((line) => /<!--\s*BEGIN GENERATED\s*-->/i.test(line));
577
+ const endIdx = lines.findIndex((line) => /<!--\s*END GENERATED\s*-->/i.test(line));
578
+ if (begin >= 0 && endIdx > begin) { start = begin + 1; end = endIdx; }
579
+ stats.scope = begin >= 0 && endIdx > begin ? 'generated' : 'whole-file';
580
+ stats.linesScanned = Math.max(0, end - start);
581
+
582
+ const refRe = /(?:^|[\s|`"'((\[])((?:topics|procedures|handover|journal|flow|raw|archive|vault|index)\/[^\s|`"'<>()[\]{},、;:()]+?\.(?:md|json))/g;
583
+ const unique = new Set();
584
+ const seen = new Set();
585
+ for (let i = start; i < end; i += 1) {
586
+ const line = lines[i];
587
+ if (/\.(?:md|json)\s*[++]\s*(?:topics|procedures|handover|journal|flow|raw|archive|vault|index)\//.test(line)) {
588
+ stats.mergedCells += 1;
589
+ }
590
+ refRe.lastIndex = 0;
591
+ let m;
592
+ while ((m = refRe.exec(line)) !== null) {
593
+ const ref = m[1];
594
+ stats.refs += 1;
595
+ unique.add(ref);
596
+ const key = `${i + 1}\u0000${ref}`;
597
+ if (seen.has(key)) continue;
598
+ seen.add(key);
599
+ const ok = fs.existsSync(path.join(memoryRoot, ref));
600
+ if (ok) {
601
+ stats.resolved += 1;
602
+ } else {
603
+ stats.unresolved += 1;
604
+ badRefs.push({ kind: 'index', line: i + 1, ref, reason: 'unresolved' });
605
+ }
606
+ }
607
+ }
608
+ stats.uniqueRefs = unique.size;
609
+ return { stats, badRefs };
610
+ }
611
+
612
+ function summarizeRawEdges(edges) {
613
+ const byType = {};
614
+ const bySource = {};
615
+ for (const edge of edges) {
616
+ byType[edge.type] = (byType[edge.type] ?? 0) + 1;
617
+ const source = edge.source ?? 'unknown';
618
+ bySource[source] = (bySource[source] ?? 0) + 1;
619
+ }
620
+ return { byType, bySource };
621
+ }
622
+
623
+ function countBy(items, pick) {
624
+ const out = {};
625
+ for (const item of items) {
626
+ const key = pick(item) ?? 'unknown';
627
+ out[key] = (out[key] ?? 0) + 1;
628
+ }
629
+ return out;
630
+ }
631
+
632
+ function emailStamp(date = new Date()) {
633
+ const iso = date.toISOString(); // 2026-11-26T13:00:00.000Z
634
+ return `${iso.slice(0, 10).replace(/-/g, '')}-${iso.slice(11, 19).replace(/:/g, '')}`;
635
+ }
636
+
637
+ function atomicWrite(file, content) {
638
+ fs.mkdirSync(path.dirname(file), { recursive: true });
639
+ const tmp = `${file}.tmp-${process.pid}`;
640
+ let fd = null;
641
+ try {
642
+ fd = fs.openSync(tmp, 'w');
643
+ fs.writeFileSync(fd, content, 'utf8');
644
+ fs.fsyncSync(fd);
645
+ } finally {
646
+ if (fd !== null) fs.closeSync(fd);
647
+ }
648
+ fs.renameSync(tmp, file);
649
+ return { bytes: Buffer.byteLength(content, 'utf8'), sha256: createHash('sha256').update(content, 'utf8').digest('hex') };
650
+ }
651
+
652
+ function backupExisting(file, recallDir) {
653
+ const backupsDir = path.join(recallDir, 'backups');
654
+ fs.mkdirSync(backupsDir, { recursive: true });
655
+ const base = `${path.basename(file, '.jsonl')}.${emailStamp()}.bak`;
656
+ let target = path.join(backupsDir, base);
657
+ for (let i = 1; fs.existsSync(target); i += 1) target = path.join(backupsDir, `${base.slice(0, -4)}-${i}.bak`);
658
+ fs.copyFileSync(file, target);
659
+ return target;
660
+ }
661
+
662
+ function appendAudit(recallDir, row) {
663
+ fs.mkdirSync(recallDir, { recursive: true });
664
+ fs.appendFileSync(path.join(recallDir, 'edges-audit.jsonl'), `${JSON.stringify(row)}\n`, 'utf8');
665
+ }
666
+
667
+ function findSeedCsv(memoryRoot) {
668
+ const candidates = [
669
+ path.join(memoryRoot, 'LINKS-SEED-v3.csv'),
670
+ path.join(memoryRoot, '.longlive', 'recall', 'LINKS-SEED-v3.csv'),
671
+ path.join(PACKAGE_ROOT, 'LINKS-SEED-v3.csv'),
672
+ path.join(PACKAGE_ROOT, 'data', 'LINKS-SEED-v3.csv'),
673
+ path.join(process.cwd(), 'LINKS-SEED-v3.csv'),
674
+ ];
675
+ const found = candidates.filter((file) => {
676
+ try { return fs.existsSync(file) && fs.statSync(file).isFile(); } catch { return false; }
677
+ });
678
+ return { found: found.length > 0, candidates: found.length > 0 ? found.map((file) => toPosix(file)) : candidates.map((file) => toPosix(file)) };
679
+ }
680
+
681
+ function resolveMemoryRoot(args) {
682
+ const explicit = String(args.memoryRoot ?? '').trim();
683
+ if (explicit !== '') return path.resolve(explicit);
684
+ const envRoot = String(process.env.DSH_LONGLIVE_MEMORY_ROOT ?? process.env.DSH_MEM ?? '').trim();
685
+ if (envRoot !== '') return path.resolve(envRoot);
686
+ if (args.out) {
687
+ const out = path.resolve(args.out);
688
+ const suffix = path.join('.longlive', 'recall', 'edges.jsonl');
689
+ if (out.toLowerCase().endsWith(suffix.toLowerCase())) return path.resolve(out, '..', '..', '..');
690
+ }
691
+ return '';
692
+ }
693
+
694
+ /** 固定 evidence 字段顺序(path/sha256/lines/quote),保证同一语义图重复构建字节稳定。 */
695
+ function canonicalEvidence(evidence) {
696
+ if (!evidence || typeof evidence !== 'object') return null;
697
+ const out = { path: evidence.path };
698
+ if (evidence.sha256) out.sha256 = evidence.sha256;
699
+ if (Array.isArray(evidence.lines)) out.lines = evidence.lines.slice(0, 2).map(Number);
700
+ if (evidence.quote) out.quote = evidence.quote;
701
+ return out;
702
+ }
703
+
704
+ function printStats(stats, { json } = {}) {
705
+ if (json) {
706
+ process.stdout.write(`${JSON.stringify(stats, null, 2)}\n`);
707
+ return;
708
+ }
709
+ const lines = [];
710
+ lines.push(`[${SCRIPT}] ${stats.mode} (${stats.dryRun ? 'dry-run' : 'apply'})`);
711
+ lines.push(` memoryRoot: ${stats.memoryRoot}`);
712
+ lines.push(` out: ${stats.outPath}${stats.existingPresent ? '' : '(不存在,将新建)'}`);
713
+ lines.push(` schema: ${EDGES_SCHEMA}`);
714
+ lines.push(` plan: ${stats.sources.plan.present ? `${stats.sources.plan.path}(${stats.sources.plan.kept}/${stats.sources.plan.edges} 条边生效,cards=${stats.sources.plan.cards} extracts=${stats.sources.plan.extracts})` : `无(${stats.sources.plan.path || '未找到'})`}`);
715
+ lines.push(` links: ${stats.sources.links.present ? `${stats.sources.links.path}(lines=${stats.sources.links.lines} bad=${stats.sources.links.bad} terms=${stats.sources.links.terms} cards=${stats.sources.links.cards} → same_topic=${stats.sources.links.sameTopic},用前 ${stats.sources.links.usedTerms} 个 term)` : `无(${stats.sources.links.path})`}`);
716
+ lines.push(` cards: dirs=${stats.sources.cards.dirs.join(',')} scanned=${stats.sources.cards.scanned} explicit=${stats.sources.cards.explicit} shorthand=${stats.sources.cards.shorthand} wikilinks=${stats.sources.cards.wikilinks} mentions=${stats.sources.cards.mentions}${stats.sources.cards.missingDirs.length > 0 ? `(缺目录: ${stats.sources.cards.missingDirs.join(',')})` : ''}`);
717
+ lines.push(` seed CSV: ${stats.seedCsv.found ? `存在但本构建器不消费(links.jsonl 即其产物):${stats.seedCsv.candidates.join(', ')}` : '未找到(无种子 CSV;six-stem 进入 link 表只能靠运行期学习边或 edges 扩展,本工具不重建 links.jsonl)'}`);
718
+ lines.push(` INDEX: ${stats.indexRefs.present ? `${stats.indexRefs.scope} 段 ${stats.indexRefs.linesScanned} 行,refs=${stats.indexRefs.refs} unique=${stats.indexRefs.uniqueRefs} resolved=${stats.indexRefs.resolved} unresolved=${stats.indexRefs.unresolved} mergedCells=${stats.indexRefs.mergedCells}` : '无 INDEX.md'}`);
719
+ lines.push(` build: edges=${stats.build.edges} byType={${Object.entries(stats.build.byType).map(([k, v]) => `${k}:${v}`).join(', ')}} bySource={${Object.entries(stats.build.bySource).map(([k, v]) => `${k}:${v}`).join(', ')}}`);
720
+ lines.push(` deduped=${stats.build.deduped} symmetrized=${stats.build.symmetrized} preservedExisting=${stats.build.preservedExisting} existing={${stats.build.existing.present ? `present,parsed=${stats.build.existing.parsed} badLines=${stats.build.existing.badLines} dropped=${stats.build.existing.dropped} kept=${stats.build.existing.kept}` : '缺省空表'}}`);
721
+ lines.push(` changed: ${stats.changed ? 'yes' : 'no (字节一致,幂等)'} bytes=${stats.bytes} sha256=${stats.sha256}`);
722
+ lines.push(` dropped: ${stats.dropped.count}${Object.keys(stats.dropped.byReason).length > 0 ? ` {${Object.entries(stats.dropped.byReason).map(([k, v]) => `${k}:${v}`).join(', ')}}` : ''}`);
723
+ for (const item of stats.dropped.items.slice(0, 20)) {
724
+ lines.push(` - [${item.reason}] ${item.from ?? item.path ?? item.kind}${item.to ? ` → ${item.to}` : ''}${item.type ? ` (${item.type})` : ''}`);
725
+ }
726
+ if (stats.dropped.count > 20) lines.push(` … 其余 ${stats.dropped.count - 20} 条见 --json`);
727
+ lines.push(` badRefs: ${stats.badRefs.count}${Object.keys(stats.badRefs.byKind).length > 0 ? ` {${Object.entries(stats.badRefs.byKind).map(([k, v]) => `${k}:${v}`).join(', ')}}` : ''}`);
728
+ for (const item of stats.badRefs.items.slice(0, 20)) {
729
+ lines.push(` - [${item.kind}] ${item.source ?? ''}${item.line ? `:${item.line}` : ''} ${item.ref}(${item.reason})`);
730
+ }
731
+ if (stats.badRefs.count > 20) lines.push(` … 其余 ${stats.badRefs.count - 20} 条见 --json`);
732
+ lines.push(` written: ${stats.written ? `yes,backup=${stats.backupPath ?? '-'},audit=${stats.auditPath ?? '-'}` : 'no'}`);
733
+ for (const note of stats.notes) lines.push(` note: ${note}`);
734
+ if (stats.error) lines.push(` error: ${stats.error}`);
735
+ process.stdout.write(`${lines.join('\n')}\n`);
736
+ }
737
+
738
+ function main(argv) {
739
+ let args;
740
+ try {
741
+ args = parseArgs(argv);
742
+ } catch (error) {
743
+ process.stderr.write(`${error.message}\n\n${USAGE}`);
744
+ return 2;
745
+ }
746
+ if (args.help) {
747
+ process.stdout.write(USAGE);
748
+ return 0;
749
+ }
750
+ const memoryRoot = resolveMemoryRoot(args);
751
+ if (memoryRoot === '') {
752
+ process.stderr.write(`${SCRIPT}: E_NO_MEMORY_ROOT:需要 --memory-root、--out,或 $DSH_LONGLIVE_MEMORY_ROOT\n`);
753
+ return 1;
754
+ }
755
+ if (!fs.existsSync(memoryRoot)) {
756
+ process.stderr.write(`${SCRIPT}: E_MEMORY_ROOT_MISSING:找不到记忆根 ${memoryRoot}\n`);
757
+ return 1;
758
+ }
759
+ const recallDir = path.join(memoryRoot, '.longlive', 'recall');
760
+ const outPath = args.out ? path.resolve(args.out) : path.join(recallDir, 'edges.jsonl');
761
+ const linksFile = args.linksFile ? path.resolve(args.linksFile) : path.join(recallDir, 'links.jsonl');
762
+ let planPath = args.plan ? path.resolve(args.plan) : path.join(recallDir, 'lifecycle-plan.json');
763
+ if (!args.plan && !fs.existsSync(planPath)) {
764
+ const packaged = path.join(PACKAGE_ROOT, 'src', 'memory', 'lifecycle-plan.json');
765
+ if (fs.existsSync(packaged)) planPath = packaged;
766
+ }
767
+
768
+ // 回滚模式:把备份原子写回(写前备份当前表 + 审计)。
769
+ if (args.rollback) {
770
+ const rollbackFrom = path.resolve(args.rollback);
771
+ if (!fs.existsSync(rollbackFrom) || fs.statSync(rollbackFrom).size === 0) {
772
+ process.stderr.write(`${SCRIPT}: E_ROLLBACK_SOURCE:备份不存在或为空 ${rollbackFrom}\n`);
773
+ return 1;
774
+ }
775
+ const payload = fs.readFileSync(rollbackFrom, 'utf8');
776
+ const parsed = parseEdgesText(payload, { memoryRoot });
777
+ if (parsed.stats.badLines > 0) {
778
+ process.stderr.write(`${SCRIPT}: E_ROLLBACK_CORRUPT:备份有 ${parsed.stats.badLines} 行解析失败,拒绝回滚\n`);
779
+ return 1;
780
+ }
781
+ const backupPath = fs.existsSync(outPath) ? backupExisting(outPath, path.dirname(outPath)) : null;
782
+ // 回滚必须是字节级还原(备份里可能含 preserved 边、原始顺序与 evidence 字段序);
783
+ // 上面 parseEdgesText 只用于校验备份可用,不复用来重序列化。
784
+ const written = atomicWrite(outPath, payload);
785
+ appendAudit(path.dirname(outPath), {
786
+ action: 'rollback',
787
+ at: new Date().toISOString(),
788
+ from: toPosix(rollbackFrom),
789
+ out: toPosix(outPath),
790
+ edges: parsed.edges.length,
791
+ bytes: written.bytes,
792
+ sha256: written.sha256,
793
+ backupPath: backupPath ? toPosix(backupPath) : null,
794
+ });
795
+ const stats = {
796
+ mode: 'rollback',
797
+ dryRun: false,
798
+ memoryRoot: toPosix(memoryRoot),
799
+ outPath: toPosix(outPath),
800
+ edges: parsed.edges.length,
801
+ bytes: written.bytes,
802
+ sha256: written.sha256,
803
+ backupPath: backupPath ? toPosix(backupPath) : null,
804
+ written: true,
805
+ notes: [`回滚自 ${toPosix(rollbackFrom)}`],
806
+ };
807
+ if (args.json) {
808
+ process.stdout.write(`${JSON.stringify(stats, null, 2)}\n`);
809
+ } else {
810
+ process.stdout.write([
811
+ `[${SCRIPT}] rollback`,
812
+ ` memoryRoot: ${stats.memoryRoot}`,
813
+ ` out: ${stats.outPath}`,
814
+ ` from: ${toPosix(rollbackFrom)}`,
815
+ ` edges: ${stats.edges} bytes=${stats.bytes} sha256=${stats.sha256}`,
816
+ ` backup: ${stats.backupPath ?? '-'}`,
817
+ '',
818
+ ].join('\n'));
819
+ }
820
+ return 0;
821
+ }
822
+
823
+ const generatedAt = new Date().toISOString();
824
+ const shaCache = new Map();
825
+ const cardsDirs = (args.cardsDirs ? String(args.cardsDirs).split(',') : DEFAULTS.cardsDirs)
826
+ .map((dir) => dir.trim()).filter(Boolean);
827
+
828
+ const cardsResult = args.noCards
829
+ ? { edges: [], dropped: [], badRefs: [], stats: { dirs: [], missingDirs: [], scanned: 0, noFrontmatter: 0, explicit: 0, shorthand: 0, wikilinks: 0, mentions: 0, bareLinks: 0, disabled: true } }
830
+ : collectCardEdges({ memoryRoot, dirs: cardsDirs, generatedAt, shaCache });
831
+ const linksResult = args.noLinks
832
+ ? { edges: [], dropped: [], badRefs: [], stats: { present: false, path: linksFile, disabled: true } }
833
+ : collectLinksEdges({
834
+ memoryRoot,
835
+ linksFile,
836
+ maxTerms: positiveInt(args.maxTerms, DEFAULTS.maxTerms),
837
+ maxCardsPerTerm: positiveInt(args.maxCardsPerTerm, DEFAULTS.maxCardsPerTerm),
838
+ maxSameTopic: positiveInt(args.maxSameTopic, DEFAULTS.maxSameTopic),
839
+ generatedAt,
840
+ shaCache,
841
+ });
842
+ const planResult = args.noPlan
843
+ ? { edges: [], dropped: [], badRefs: [], stats: { present: false, path: planPath, disabled: true }, plan: null }
844
+ : collectPlanEdges({ memoryRoot, planPath, generatedAt, shaCache });
845
+ const indexResult = collectIndexRefs({ memoryRoot });
846
+
847
+ const dropped = [...cardsResult.dropped, ...linksResult.dropped, ...planResult.dropped];
848
+ const badRefs = [...cardsResult.badRefs, ...linksResult.badRefs, ...planResult.badRefs, ...indexResult.badRefs];
849
+
850
+ // 已有表:只用来保留非本构建器产出的边 + 复用 created_at(幂等)。
851
+ let existingEdges = [];
852
+ let previousContent = '';
853
+ let existingStats = { parsed: 0, badLines: 0, dropped: 0, deduped: 0, symmetrized: 0, kept: 0 };
854
+ let existingPresent = false;
855
+ if (fs.existsSync(outPath)) {
856
+ try {
857
+ previousContent = fs.readFileSync(outPath, 'utf8');
858
+ const parsed = parseEdgesText(previousContent, { memoryRoot });
859
+ existingEdges = parsed.edges;
860
+ existingStats = parsed.stats;
861
+ existingPresent = true;
862
+ } catch (error) {
863
+ dropped.push({ kind: 'existing-read', path: toPosix(outPath), reason: String(error?.code ?? error) });
864
+ }
865
+ }
866
+ const existingByKey = new Map(existingEdges.map((edge) => [edgeKey(edge), edge]));
867
+
868
+ const built = [...planResult.edges, ...cardsResult.edges, ...linksResult.edges];
869
+ for (const edge of built) {
870
+ if (edge.source === 'lifecycle-plan/v1') {
871
+ // plan 自带 generated_at,本身就是确定值;只有缺失时才退化到本次时间。
872
+ edge.created_at = edge.created_at ?? generatedAt;
873
+ continue;
874
+ }
875
+ // 幂等:非 plan 边沿用已有表同 key 的 created_at;只有首次生成才用本次时间戳。
876
+ const prev = existingByKey.get(edgeKey(edge));
877
+ edge.created_at = prev?.created_at ?? edge.created_at ?? generatedAt;
878
+ }
879
+ const builtKeys = new Set(built.map((edge) => edgeKey(edge)));
880
+ const preserved = existingEdges.filter((edge) => !builtKeys.has(edgeKey(edge)));
881
+ const deduped = dedupeEdges([...built, ...preserved]);
882
+ const symmetric = symmetrizeEdges(deduped.edges);
883
+ const finalEdges = symmetric.edges
884
+ .map((edge) => ({
885
+ from: edge.from,
886
+ to: edge.to,
887
+ type: edge.type,
888
+ evidence: canonicalEvidence(edge.evidence),
889
+ confidence: edge.confidence,
890
+ created_at: edge.created_at ?? null,
891
+ source: edge.source ?? null,
892
+ }))
893
+ .sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.type.localeCompare(b.type));
894
+
895
+ const content = serializeEdges(finalEdges);
896
+ const bytes = Buffer.byteLength(content, 'utf8');
897
+ const sha256 = createHash('sha256').update(content, 'utf8').digest('hex');
898
+ const changed = previousContent !== content;
899
+
900
+ let written = { ok: true, bytes: 0, sha256, backupPath: null };
901
+ if (!args.dryRun && changed) {
902
+ try {
903
+ written.backupPath = existingPresent ? backupExisting(outPath, path.dirname(outPath)) : null;
904
+ written = { ...atomicWrite(outPath, content), ok: true, backupPath: written.backupPath };
905
+ } catch (error) {
906
+ written = { ok: false, bytes: 0, sha256, backupPath: null, error: String(error?.message ?? error) };
907
+ }
908
+ }
909
+ const auditPath = path.join(path.dirname(outPath), 'edges-audit.jsonl');
910
+ if (!args.dryRun && changed && written.ok) {
911
+ try {
912
+ appendAudit(path.dirname(outPath), {
913
+ action: 'build',
914
+ at: generatedAt,
915
+ memoryRoot: toPosix(memoryRoot),
916
+ out: toPosix(outPath),
917
+ edges: finalEdges.length,
918
+ byType: summarizeRawEdges(finalEdges).byType,
919
+ bySource: summarizeRawEdges(finalEdges).bySource,
920
+ dropped: dropped.length,
921
+ badRefs: badRefs.length,
922
+ changed,
923
+ bytes,
924
+ sha256,
925
+ planPath: planResult.stats.present ? toPosix(planPath) : null,
926
+ planSha256: sha256OfFile(planPath, shaCache),
927
+ linksPath: linksResult.stats.present ? toPosix(linksFile) : null,
928
+ linksSha256: sha256OfFile(linksFile, shaCache),
929
+ backupPath: written.backupPath ? toPosix(written.backupPath) : null,
930
+ });
931
+ } catch {
932
+ /* 审计失败不影响边表本身,统计里记不到就别阻塞 */
933
+ }
934
+ }
935
+
936
+ const sourceSummary = summarizeRawEdges(finalEdges);
937
+ const stats = {
938
+ schema: 'edges-build/v1',
939
+ edgeSchema: EDGES_SCHEMA,
940
+ mode: 'build',
941
+ dryRun: args.dryRun === true,
942
+ memoryRoot: toPosix(memoryRoot),
943
+ outPath: toPosix(outPath),
944
+ existingPresent,
945
+ seedCsv: findSeedCsv(memoryRoot),
946
+ sources: {
947
+ cards: cardsResult.stats,
948
+ links: linksResult.stats,
949
+ plan: planResult.stats,
950
+ },
951
+ indexRefs: indexResult.stats,
952
+ build: {
953
+ edges: finalEdges.length,
954
+ ...sourceSummary,
955
+ deduped: deduped.deduped,
956
+ symmetrized: symmetric.added,
957
+ preservedExisting: preserved.length,
958
+ existing: { present: existingPresent, ...existingStats },
959
+ },
960
+ dropped: {
961
+ count: dropped.length,
962
+ byReason: countBy(dropped, (item) => item.reason),
963
+ items: dropped,
964
+ },
965
+ badRefs: {
966
+ count: badRefs.length,
967
+ byKind: countBy(badRefs, (item) => item.kind),
968
+ items: badRefs,
969
+ },
970
+ changed,
971
+ bytes,
972
+ sha256,
973
+ written: args.dryRun ? false : (changed && written.ok === true),
974
+ backupPath: written.backupPath ? toPosix(written.backupPath) : null,
975
+ auditPath: args.dryRun || !changed ? null : toPosix(auditPath),
976
+ planPath: planResult.stats.present ? toPosix(planPath) : null,
977
+ linksPath: linksResult.stats.present ? toPosix(linksFile) : null,
978
+ notes: [
979
+ '无种子 CSV:本构建器不重建 links.jsonl、不消费 LINKS-SEED-v3.csv;six-stem 等新卡进入 link 表只能靠运行期学习边或 edges 扩展。',
980
+ 'same_topic 由 links.jsonl 同词共现推导,固定 confidence 0.5(不发明强度),且不参与注入扩展(只进网络/backlinks)。',
981
+ '目标卡不存在的边按 D5 丢弃并计入 dropped/badRefs;lifecycle-plan 里迁移目标卡缺卡时需先做迁移再重建。',
982
+ ],
983
+ error: written.ok === true ? null : written.error,
984
+ };
985
+ if (args.dryRun) stats.written = false;
986
+ printStats(stats, { json: args.json });
987
+ if (args.dryRun) return dropped.some((item) => item.kind === 'existing-read' || item.kind === 'links-read') ? 1 : 0;
988
+ return written.ok === true ? 0 : 1;
989
+ }
990
+
991
+ const isDirectRun = (() => {
992
+ try {
993
+ return process.argv[1] !== undefined && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
994
+ } catch {
995
+ return false;
996
+ }
997
+ })();
998
+
999
+ if (isDirectRun) {
1000
+ process.exitCode = main(process.argv.slice(2));
1001
+ }
1002
+
1003
+ export { main };