@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,578 @@
1
+ #!/usr/bin/env node
2
+ // longlive-doctor — check and install dsh-longlive's optional peers.
3
+ //
4
+ // Four modes, all documented by --help:
5
+ // 1. default: read-only table, exit 1 when something is missing;
6
+ // 2. --json: one machine-readable object on stdout;
7
+ // 3. --setup: print the whole plan, require the literal uppercase YES, then
8
+ // run `dsh plugin add <name>` once per missing peer. `--yes` skips the
9
+ // prompt for pipes/CI. Every completed run appends one audit line.
10
+ // 4. --apply: the older per-dependency [y/N] flow, kept for compatibility.
11
+ //
12
+ // It uses only Node built-ins. Nothing is installed unless --setup or --apply
13
+ // is explicit, cancellation writes nothing at all, and a failed child process
14
+ // is reported with its exit code and captured output instead of swallowed.
15
+
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { spawnSync } from 'node:child_process';
19
+ import nodeReadline from 'node:readline';
20
+ import readline from 'node:readline/promises';
21
+ import { fileURLToPath } from 'node:url';
22
+ import {
23
+ checkOptionalDeps,
24
+ optionalPeerNames,
25
+ resolveDshHome,
26
+ scanProfiles,
27
+ } from '../src/deps.js';
28
+ import { VERSION } from '../src/version.js';
29
+ import { adapterHealth } from '../src/adapters/registry.js';
30
+ import { cleanupStaleLocks } from '../src/util/stale-locks.js';
31
+
32
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
33
+ const ROOT = path.resolve(HERE, '..');
34
+ const PLUGIN = '@jjh32456/longlive';
35
+ const AUDIT_FILE = 'longlive-doctor-audit.log';
36
+
37
+ let manifest = {};
38
+ try {
39
+ manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
40
+ } catch {
41
+ manifest = {};
42
+ }
43
+ const peerRanges = manifest.peerDependencies ?? {};
44
+ const declaredPeers = optionalPeerNames(manifest);
45
+
46
+ function usage() {
47
+ return [
48
+ 'longlive-doctor — 检查 dsh-longlive 的可选依赖',
49
+ '',
50
+ '用法:',
51
+ ' 1. node scripts/longlive-doctor.mjs 只读检查(表格);有缺失 exit 1',
52
+ ' 2. node scripts/longlive-doctor.mjs --json 机器可读 JSON;适合脚本/CI',
53
+ ' 3. node scripts/longlive-doctor.mjs --setup 先打印完整计划,输入大写 YES 才执行 dsh plugin add',
54
+ ' 加 --yes 跳过确认(管道/CI);非交互且没带 --yes 会 exit 2',
55
+ ' 4. node scripts/longlive-doctor.mjs --apply 逐个 [y/N] 确认后执行(旧流程,保留)',
56
+ ' 用 --profile <name> 只检查某个 profile',
57
+ '',
58
+ '退出码:',
59
+ ' 0 全部已启用 / 安装命令执行成功 / 用户取消',
60
+ ' 1 有缺失 / 未检测到 profile / 安装失败',
61
+ ' 2 用法错误(含 --setup、--apply 在非交互环境未加 --yes)',
62
+ '',
63
+ ].join('\n');
64
+ }
65
+
66
+ class UsageError extends Error {}
67
+
68
+ function parseArgs(argv) {
69
+ const options = { help: false, json: false, apply: false, setup: false, yes: false, profile: null };
70
+ for (let index = 0; index < argv.length; index += 1) {
71
+ const arg = argv[index];
72
+ if (arg === '--help' || arg === '-h') {
73
+ options.help = true;
74
+ } else if (arg === '--json') {
75
+ options.json = true;
76
+ } else if (arg === '--apply') {
77
+ options.apply = true;
78
+ } else if (arg === '--setup') {
79
+ options.setup = true;
80
+ } else if (arg === '--yes' || arg === '-y') {
81
+ options.yes = true;
82
+ } else if (arg === '--profile') {
83
+ const value = argv[index + 1];
84
+ if (!value || value.startsWith('-')) throw new UsageError('--profile 需要一个 profile 名称');
85
+ options.profile = value;
86
+ index += 1;
87
+ } else if (arg.startsWith('--profile=')) {
88
+ const value = arg.slice('--profile='.length);
89
+ if (!value) throw new UsageError('--profile 需要一个 profile 名称');
90
+ options.profile = value;
91
+ } else {
92
+ throw new UsageError(`未知参数:${arg}`);
93
+ }
94
+ }
95
+ if (options.setup && options.apply) throw new UsageError('--setup 与 --apply 只能选一个');
96
+ if (options.setup && options.json) throw new UsageError('--setup 不能与 --json 同用');
97
+ return options;
98
+ }
99
+
100
+ function findDsh(env) {
101
+ const explicit = env.DSH_BIN;
102
+ if (typeof explicit === 'string' && explicit.trim() !== '') return explicit.trim();
103
+ const pathValue = env.PATH ?? env.Path ?? '';
104
+ const names = process.platform === 'win32'
105
+ ? ['dsh.cmd', 'dsh.exe', 'dsh.bat', 'dsh']
106
+ : ['dsh'];
107
+ for (const dir of pathValue.split(path.delimiter)) {
108
+ if (!dir) continue;
109
+ for (const name of names) {
110
+ const candidate = path.join(dir, name);
111
+ try {
112
+ if (fs.statSync(candidate).isFile()) return candidate;
113
+ } catch {
114
+ /* keep looking */
115
+ }
116
+ }
117
+ }
118
+ return null;
119
+ }
120
+
121
+ function quoteCommand(value) {
122
+ return /\s/.test(value) ? `"${value}"` : value;
123
+ }
124
+
125
+ function commandLine(dsh, name, profile) {
126
+ // `dsh plugin` requires --profile; without it the CLI exits 1 before pnpm runs.
127
+ const target = typeof profile === 'string' && profile.trim() !== '' ? profile.trim() : null;
128
+ return target
129
+ ? `${quoteCommand(dsh)} plugin --profile ${quoteCommand(target)} add ${name}`
130
+ : `${quoteCommand(dsh)} plugin add ${name}`;
131
+ }
132
+
133
+ function targetProfiles(profile) { return String(profile ?? '')
134
+ .split(',')
135
+ .map((name) => name.trim())
136
+ .filter(Boolean);
137
+ }
138
+
139
+ function excerpt(value, limit = 600) {
140
+ const text = String(value ?? '').trim();
141
+ if (!text) return '';
142
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
143
+ }
144
+
145
+ function buildEntries(result) {
146
+ const names = [];
147
+ for (const name of [...declaredPeers, ...result.missing, ...result.present]) {
148
+ if (!names.includes(name)) names.push(name);
149
+ }
150
+ const profiles = targetProfiles(result.profile);
151
+ const target = profiles.length === 1 ? profiles[0] : null;
152
+ return names.map((name) => {
153
+ const present = result.present.includes(name);
154
+ const missing = result.missing.includes(name);
155
+ return {
156
+ name,
157
+ range: peerRanges[name] ?? null,
158
+ status: present ? '已启用' : (missing ? '缺失' : '未检测'),
159
+ present,
160
+ installCommand: target ? `dsh plugin --profile ${target} add ${name}` : `dsh plugin add ${name}`,
161
+ optional: true,
162
+ };
163
+ });
164
+ }
165
+
166
+ function recheck(home, profile) {
167
+ return checkOptionalDeps({ home, profile, dependencies: declaredPeers });
168
+ }
169
+
170
+ async function confirmInstall(name) {
171
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
172
+ try {
173
+ const answer = await rl.question(`为 ${name} 执行 dsh plugin add?[y/N] `);
174
+ return /^y(es)?$/i.test(answer.trim());
175
+ } finally {
176
+ rl.close();
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Read one line. Resolves null on EOF, Ctrl+C or close — all of which the
182
+ * setup wizard treats as cancellation. Nothing is written by this function.
183
+ */
184
+ function askLine(prompt) {
185
+ return new Promise((resolve) => {
186
+ const rl = nodeReadline.createInterface({ input: process.stdin, output: process.stderr });
187
+ let settled = false;
188
+ const finish = (value) => {
189
+ if (settled) return;
190
+ settled = true;
191
+ try {
192
+ rl.close();
193
+ } catch {
194
+ /* already closed */
195
+ }
196
+ resolve(value);
197
+ };
198
+ rl.on('SIGINT', () => finish(null));
199
+ rl.on('close', () => finish(null));
200
+ rl.question(prompt, (answer) => finish(answer));
201
+ });
202
+ }
203
+
204
+ function installOne(name, env, profile) {
205
+ const dsh = findDsh(env);
206
+ const command = dsh ? commandLine(dsh, name, profile) : `dsh plugin add ${name}`;
207
+ const where = profile ? `(profile ${profile})` : '';
208
+ if (!dsh) {
209
+ return {
210
+ name,
211
+ profile: profile ?? null,
212
+ ok: false,
213
+ exitCode: null,
214
+ command,
215
+ stdout: '',
216
+ stderr: '',
217
+ message: '找不到 dsh 命令:请把 DSH CLI 加进 PATH,或设置 DSH_BIN 指向可执行文件。',
218
+ };
219
+ }
220
+ const child = spawnSync(command, {
221
+ shell: true,
222
+ encoding: 'utf8',
223
+ timeout: 180000,
224
+ windowsHide: true,
225
+ env,
226
+ });
227
+ if (child.error) {
228
+ return {
229
+ name,
230
+ profile: profile ?? null,
231
+ ok: false,
232
+ exitCode: null,
233
+ command,
234
+ stdout: String(child.stdout ?? ''),
235
+ stderr: String(child.stderr ?? ''),
236
+ message: `无法执行 dsh(${child.error.code ?? child.error.message}):${command}`,
237
+ };
238
+ }
239
+ const ok = child.status === 0;
240
+ const detail = excerpt(child.stderr) || excerpt(child.stdout);
241
+ return {
242
+ name,
243
+ profile: profile ?? null,
244
+ ok,
245
+ exitCode: child.status,
246
+ command,
247
+ stdout: String(child.stdout ?? ''),
248
+ stderr: String(child.stderr ?? ''),
249
+ message: ok
250
+ ? `已安装 ${name}${where},重启宿主后 engram_* / memory_save 生效。`
251
+ : `dsh plugin add ${name} 失败${where}(exit ${child.status}):${detail || '子进程没有输出'}`,
252
+ };
253
+ }
254
+
255
+ function printTable({ home, profile, rows, entries, applied, ok }) {
256
+ const lines = [];
257
+ lines.push(`longlive-doctor · ${PLUGIN} ${VERSION}`);
258
+ lines.push(`DSH home: ${home}`);
259
+ lines.push(`profile: ${profile ?? '(无)'}(扫描到 ${rows.filter((row) => row.manifest).length} 个可读 profile)`);
260
+ lines.push('');
261
+ if (rows.length === 0) {
262
+ lines.push('未检测到 profile:请先安装并至少启动一次 DSH,或检查 DSH_HOME。');
263
+ } else if (rows.every((row) => !row.manifest)) {
264
+ lines.push('没有可读的 profile 清单(profiles/*/package.json 全部无法解析)。');
265
+ }
266
+ lines.push('依赖 状态 安装命令');
267
+ lines.push('-------------------------------- -------- ------------------------------------------');
268
+ for (const entry of entries) {
269
+ const command = entry.present ? '—' : entry.installCommand;
270
+ lines.push(`${entry.name.padEnd(32)} ${entry.status.padEnd(8)} ${command}`);
271
+ }
272
+ lines.push('');
273
+ if (applied.length > 0) {
274
+ lines.push('安装结果:');
275
+ for (const item of applied) {
276
+ lines.push(` ${item.ok ? 'OK ' : 'FAIL'} ${item.name} ${item.message}`);
277
+ }
278
+ lines.push('');
279
+ }
280
+ const independence = adapterHealth();
281
+ lines.push('核心独立性(插件适配器):');
282
+ lines.push(` ${independence.ok ? 'ok' : 'degraded'} · 适配器:${independence.rows.map((row) => `${row.id}=${row.mode}`).join(', ') || '无'}`);
283
+ lines.push(' 第三方插件缺席时核心照常工作:只少该插件的可选能力,降级项显式标 degraded。');
284
+ if (ok) {
285
+ lines.push('全部可选依赖已启用。');
286
+ } else {
287
+ lines.push('有缺失:按上面的命令安装,装完重启宿主。缺失不影响剪对话(核心工具照常工作)。');
288
+ }
289
+ process.stdout.write(`${lines.join('\n')}\n`);
290
+ }
291
+
292
+ /** The complete plan, printed before any prompt or child process. */
293
+ function buildSetupPlan({ home, profile, missing, env }) {
294
+ const dsh = findDsh(env);
295
+ const lines = [];
296
+ lines.push(`longlive-doctor · ${PLUGIN} ${VERSION}`);
297
+ lines.push(`DSH home: ${home}`);
298
+ lines.push(`目标 profile: ${profile ?? '(未检测到)'}`);
299
+ const profileNames = targetProfiles(profile);
300
+ for (const name of profileNames) {
301
+ lines.push(` profile 清单: ${path.join(home, 'profiles', name, 'package.json')}`);
302
+ }
303
+ if (profileNames.length === 0) {
304
+ lines.push(' !没有可确定的 profile:`dsh plugin` 必须带 --profile,');
305
+ lines.push(' 请先至少启动一次 DSH,或用 --profile <name> 指定后再跑 --setup。');
306
+ }
307
+ lines.push('');
308
+ lines.push('将要做的事:');
309
+ if (missing.length === 0) {
310
+ lines.push(' 可选依赖已全部启用,无需安装。');
311
+ } else {
312
+ lines.push(` 安装 ${missing.length} 个可选依赖:`);
313
+ for (const entry of missing) {
314
+ const range = entry.range ? `(版本约束 ${entry.range})` : '';
315
+ lines.push(` - ${entry.name}${range}`);
316
+ }
317
+ lines.push(' 将执行的命令:');
318
+ for (const entry of missing) {
319
+ if (profileNames.length === 0) {
320
+ lines.push(` ${dsh ? commandLine(dsh, entry.name) : `dsh plugin add ${entry.name}`}`);
321
+ } else {
322
+ for (const name of profileNames) {
323
+ lines.push(` ${dsh ? commandLine(dsh, entry.name, name) : `dsh plugin --profile ${name} add ${entry.name}`}`);
324
+ }
325
+ }
326
+ }
327
+ if (!dsh) {
328
+ lines.push(' !PATH 里没有 dsh:执行会失败;请先设置 DSH_BIN 或把 DSH CLI 加进 PATH。');
329
+ }
330
+ const target = profileNames.length > 0 ? profileNames.join(', ') : '目标 profile';
331
+ lines.push(` 安装完成后需要重启宿主(退出并重新启动,或重新加载 profile ${target})才会生效。`);
332
+ lines.push(' doctor 不会自动重启宿主。');
333
+ }
334
+ lines.push('');
335
+ return `${lines.join('\n')}\n`;
336
+ }
337
+
338
+ function appendAudit(home, { consent, deps, result, exitCode, env }) {
339
+ const line = JSON.stringify({
340
+ timestamp: new Date().toISOString(),
341
+ user: env.USERNAME || env.USER || 'unknown',
342
+ consent,
343
+ deps,
344
+ result,
345
+ exitCode,
346
+ });
347
+ try {
348
+ fs.mkdirSync(home, { recursive: true });
349
+ fs.appendFileSync(path.join(home, AUDIT_FILE), `${line}\n`, 'utf8');
350
+ } catch (error) {
351
+ // An audit write failure must never change whether the install counts.
352
+ process.stderr.write(`audit 日志写入失败(不影响安装结果):${error?.message ?? error}\n`);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * --setup: plan -> explicit uppercase YES (or --yes) -> install -> audit.
358
+ * Returns the process exit code. Cancellation returns 0 after writing nothing.
359
+ */
360
+ async function runSetup({ home, profile, entries, env, options }) {
361
+ const missing = entries.filter((entry) => !entry.present);
362
+ process.stdout.write(buildSetupPlan({ home, profile, missing, env }));
363
+
364
+ if (missing.length === 0) {
365
+ process.stdout.write('没有需要安装的依赖。\n');
366
+ return 0;
367
+ }
368
+
369
+ const interactive = Boolean(process.stdin.isTTY) || env.DSH_DOCTOR_TEST_TTY === '1';
370
+ let consent;
371
+ if (options.yes) {
372
+ consent = '--yes';
373
+ } else {
374
+ if (!interactive) {
375
+ process.stderr.write(
376
+ '--setup 在非交互环境(管道/CI)需要 --yes 确认;本次没有执行任何安装,也没有写任何文件。\n');
377
+ return 2;
378
+ }
379
+ const answer = await askLine('确认执行请输入大写 YES(其它任何输入都会取消):');
380
+ if (answer !== 'YES') {
381
+ process.stdout.write('已取消,未做任何改动。\n');
382
+ return 0;
383
+ }
384
+ consent = 'typed-YES';
385
+ }
386
+
387
+ const targets = targetProfiles(profile);
388
+ if (targets.length === 0) {
389
+ process.stderr.write(
390
+ '没有可确定的 profile:`dsh plugin` 必须带 --profile。请先启动一次 DSH,或用 --profile <name> 重跑;本次没有执行任何安装。\n');
391
+ return 1;
392
+ }
393
+
394
+ const applied = [];
395
+ for (const entry of missing) {
396
+ for (const target of targets) {
397
+ applied.push(installOne(entry.name, env, target));
398
+ }
399
+ }
400
+ const failed = applied.filter((item) => !item.ok);
401
+ const exitCode = failed.length === 0 ? 0 : 1;
402
+
403
+ process.stdout.write('安装结果:\n');
404
+ for (const item of applied) {
405
+ if (item.ok) process.stdout.write(` OK ${item.name} ${item.message}\n`);
406
+ }
407
+ if (failed.length > 0) {
408
+ process.stderr.write('安装失败:\n');
409
+ for (const item of failed) {
410
+ process.stderr.write(` FAIL ${item.name} ${item.message}\n`);
411
+ }
412
+ process.stderr.write('longlive 本体没有改动;看上面的片段修好后重跑 --setup。\n');
413
+ } else {
414
+ const target = String(profile ?? '').split(',').map((name) => name.trim()).filter(Boolean).join(', ');
415
+ process.stdout.write(
416
+ `重启宿主后生效:退出 DSH 并重新启动(或重新加载 profile ${target || '目标 profile'})。doctor 不会自动重启。\n`);
417
+ }
418
+
419
+ appendAudit(home, {
420
+ consent,
421
+ deps: [...new Set(applied.map((item) => item.name))],
422
+ result: exitCode === 0 ? 'ok' : 'failed',
423
+ exitCode,
424
+ env,
425
+ });
426
+ return exitCode;
427
+ }
428
+
429
+ /** Candidate memory roots for stale-lock cleanup (env → home default → profile config). */
430
+ function memoryRootCandidates(home, env) {
431
+ const roots = new Set();
432
+ for (const key of ['DSH_LONGLIVE_MEMORY_ROOT', 'DSH_MEM']) {
433
+ const value = typeof env?.[key] === 'string' ? env[key].trim() : '';
434
+ if (value !== '') roots.add(value);
435
+ }
436
+ roots.add(path.join(home, 'longlive-memory'));
437
+ const profilesDir = path.join(home, 'profiles');
438
+ let dirs = [];
439
+ try {
440
+ dirs = fs.readdirSync(profilesDir, { withFileTypes: true });
441
+ } catch {
442
+ dirs = [];
443
+ }
444
+ for (const dir of dirs) {
445
+ if (!dir.isDirectory()) continue;
446
+ for (const name of ['cordis.patch.yml', 'cordis.yml', 'config.yml', 'config.yaml']) {
447
+ try {
448
+ const text = fs.readFileSync(path.join(profilesDir, dir.name, name), 'utf8');
449
+ const match = text.match(/^\s*memoryRoot:\s*["']?([^"'\r\n#]+)/m);
450
+ if (match) roots.add(match[1].trim());
451
+ } catch {
452
+ /* profile without that config file */
453
+ }
454
+ }
455
+ }
456
+ return [...roots].filter((root) => {
457
+ try {
458
+ return path.isAbsolute(root) && fs.existsSync(root);
459
+ } catch {
460
+ return false;
461
+ }
462
+ });
463
+ }
464
+
465
+ /** S1: doctor 也清理陈旧锁(与启动时同一判定;缺失 memoryRoot 时静默跳过)。 */
466
+ function cleanupDoctorLocks(home, env) {
467
+ const report = { scanned: 0, removed: [], errors: [], roots: [] };
468
+ for (const root of memoryRootCandidates(home, env)) {
469
+ report.roots.push(root);
470
+ try {
471
+ const result = cleanupStaleLocks({ memoryRoot: root, env, logger: { warn() {} } });
472
+ report.scanned += result.scanned;
473
+ report.removed.push(...result.removed.map((item) => ({ root, ...item })));
474
+ report.errors.push(...result.errors.map((item) => ({ root, ...item })));
475
+ } catch (error) {
476
+ report.errors.push({ root, error: String(error?.message ?? error) });
477
+ }
478
+ }
479
+ return report;
480
+ }
481
+
482
+ async function main() {
483
+ const options = parseArgs(process.argv.slice(2));
484
+ if (options.help) {
485
+ process.stdout.write(usage());
486
+ return;
487
+ }
488
+
489
+ const env = process.env;
490
+ const home = resolveDshHome(env);
491
+ const rows = scanProfiles(home);
492
+ let result = recheck(home, options.profile ?? undefined);
493
+ let entries = buildEntries(result);
494
+
495
+ if (options.setup) {
496
+ process.exitCode = await runSetup({
497
+ home,
498
+ profile: result.profile,
499
+ entries,
500
+ env,
501
+ options,
502
+ });
503
+ return;
504
+ }
505
+
506
+ const applied = [];
507
+ const staleLocks = cleanupDoctorLocks(home, env);
508
+ if (options.apply && entries.some((entry) => !entry.present)) {
509
+ if (!process.stdin.isTTY && !options.yes) {
510
+ process.stderr.write('--apply 在非交互环境需要 --yes 确认;本次没有执行任何安装。\n');
511
+ process.exitCode = 2;
512
+ return;
513
+ }
514
+ for (const entry of entries.filter((row) => !row.present)) {
515
+ if (!options.yes) {
516
+ const confirmed = await confirmInstall(entry.name);
517
+ if (!confirmed) {
518
+ applied.push({
519
+ name: entry.name,
520
+ ok: false,
521
+ skipped: true,
522
+ exitCode: null,
523
+ command: entry.installCommand,
524
+ stdout: '',
525
+ stderr: '',
526
+ message: '用户取消,未执行。',
527
+ });
528
+ continue;
529
+ }
530
+ }
531
+ applied.push(installOne(entry.name, env, targetProfiles(result.profile).length === 1 ? targetProfiles(result.profile)[0] : null));
532
+ }
533
+ result = recheck(home, options.profile ?? undefined);
534
+ entries = buildEntries(result);
535
+ }
536
+
537
+ const noProfiles = rows.length === 0;
538
+ const ok = result.ok && !noProfiles;
539
+
540
+ if (options.json) {
541
+ const payload = {
542
+ ok,
543
+ plugin: PLUGIN,
544
+ version: VERSION,
545
+ home,
546
+ profile: result.profile,
547
+ profiles: rows.filter((row) => row.manifest).map((row) => row.name),
548
+ unreadableProfiles: rows
549
+ .filter((row) => row.error)
550
+ .map((row) => ({ name: row.name, error: String(row.error?.message ?? row.error) })),
551
+ dependencies: entries,
552
+ independence: adapterHealth(),
553
+ missing: entries.filter((entry) => !entry.present).map((entry) => entry.name),
554
+ present: entries.filter((entry) => entry.present).map((entry) => entry.name),
555
+ staleLocks,
556
+ };
557
+ if (options.apply) payload.applied = applied;
558
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
559
+ } else {
560
+ printTable({ home, profile: result.profile, rows, entries, applied, ok });
561
+ if (staleLocks.scanned > 0) {
562
+ process.stdout.write(`陈旧锁:扫描 ${staleLocks.scanned} 个,清理 ${staleLocks.removed.length} 个` +
563
+ `${staleLocks.errors.length > 0 ? `,失败 ${staleLocks.errors.length} 个` : ''}\n`);
564
+ }
565
+ }
566
+
567
+ process.exitCode = ok ? 0 : 1;
568
+ }
569
+
570
+ main().catch((error) => {
571
+ if (error instanceof UsageError) {
572
+ process.stderr.write(`${error.message}\n\n${usage()}`);
573
+ process.exitCode = 2;
574
+ return;
575
+ }
576
+ process.stderr.write(`longlive-doctor: ${error?.stack ?? error?.message ?? error}\n`);
577
+ process.exitCode = 2;
578
+ });
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Read-only D1/D4 ledger endpoint.
4
+ *
5
+ * The plugin has no HTTP server by design (see docs/PANEL-INTEGRATION.md).
6
+ * The panel and the Router read the ledger in one of two ways:
7
+ *
8
+ * 1. read `<memoryRoot>/.longlive/metrics/turns.jsonl` directly, or
9
+ * 2. run this script for a one-line JSON summary:
10
+ *
11
+ * node scripts/metrics-read.mjs --memory-root <root>
12
+ * node scripts/metrics-read.mjs --memory-root <root> --json --limit 50
13
+ *
14
+ * Exit code is 0 even when the ledger does not exist yet; the payload carries
15
+ * `exists:false`. This is a metrics endpoint, not a health check.
16
+ */
17
+
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { readMetricsSummary, readTurnLedger, ledgerPath, calibrationPath } from '../src/metrics/store.mjs';
21
+
22
+ function parseArgs(argv) {
23
+ const out = { memoryRoot: '', sessionId: '', limit: 0, json: false, help: false };
24
+ for (let index = 0; index < argv.length; index += 1) {
25
+ const arg = argv[index];
26
+ if (arg === '--json') out.json = true;
27
+ else if (arg === '--help' || arg === '-h') out.help = true;
28
+ else if (arg === '--memory-root' || arg === '--mem-root') out.memoryRoot = argv[++index] ?? '';
29
+ else if (arg === '--session' || arg === '--session-id') out.sessionId = argv[++index] ?? '';
30
+ else if (arg === '--limit') out.limit = Number.parseInt(argv[++index] ?? '', 10) || 0;
31
+ else if (arg.startsWith('--memory-root=')) out.memoryRoot = arg.slice('--memory-root='.length);
32
+ else if (arg.startsWith('--session=')) out.sessionId = arg.slice('--session='.length);
33
+ else if (arg.startsWith('--limit=')) out.limit = Number.parseInt(arg.slice('--limit='.length), 10) || 0;
34
+ }
35
+ return out;
36
+ }
37
+
38
+ function resolveMemoryRoot(explicit) {
39
+ if (typeof explicit === 'string' && explicit.trim() !== '') return path.resolve(explicit.trim());
40
+ for (const key of ['DSH_LONGLIVE_MEMORY_ROOT', 'DSH_MEMORY_ROOT', 'DSH_MEM']) {
41
+ const value = process.env[key];
42
+ if (typeof value === 'string' && value.trim() !== '') return path.resolve(value.trim());
43
+ }
44
+ const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME.trim() !== ''
45
+ ? process.env.DSH_HOME.trim()
46
+ : path.join(os.homedir(), '.dsh');
47
+ return path.join(home, 'longlive-memory');
48
+ }
49
+
50
+ const args = parseArgs(process.argv.slice(2));
51
+ if (args.help) {
52
+ process.stdout.write(
53
+ 'usage: node scripts/metrics-read.mjs [--memory-root <root>] [--session <id>] [--limit N] [--json]\n' +
54
+ ' default: one-line JSON summary (router_status.ledger shape)\n' +
55
+ ' --json : the ledger rows (newest N when --limit is set)\n',
56
+ );
57
+ process.exit(0);
58
+ }
59
+
60
+ const memoryRoot = resolveMemoryRoot(args.memoryRoot);
61
+ if (args.json) {
62
+ const ledger = readTurnLedger({ memoryRoot, sessionId: args.sessionId, limit: args.limit });
63
+ process.stdout.write(`${JSON.stringify({
64
+ ok: ledger.ok,
65
+ path: ledger.path,
66
+ exists: ledger.exists,
67
+ total: ledger.total,
68
+ skipped: ledger.skipped,
69
+ bytes: ledger.bytes,
70
+ rows: ledger.rows,
71
+ })}\n`);
72
+ } else {
73
+ const summary = readMetricsSummary({ memoryRoot, sessionId: args.sessionId, limit: args.limit || 500 });
74
+ process.stdout.write(`${JSON.stringify({
75
+ ...summary,
76
+ ledgerPath: ledgerPath(memoryRoot),
77
+ statePath: calibrationPath(memoryRoot),
78
+ })}\n`);
79
+ }