dsh-memu-memory 1.4.1 → 1.4.3

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 (389) hide show
  1. package/AGENTS.md +108 -108
  2. package/CHANGELOG.md +169 -848
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -72
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9648
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1035
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4911
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -0
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2518
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1066
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -152
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -48
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -415
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -616
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -0
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -23
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -221
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -212
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,903 +1,938 @@
1
- #!/usr/bin/env node
2
- /**
3
- * EVALUATION ONLY — local fake OpenAI-compatible endpoint for work order B.
4
- *
5
- * This file is a developer measurement harness. It is never imported by
6
- * lib/, never shipped as runtime behaviour, and must not be pointed at real
7
- * user conversations that should be kept. It listens on 127.0.0.1 only, has no
8
- * authentication, and stores only lengths, hashes and marker counts — never
9
- * message bodies.
10
- *
11
- * Why it exists: the mock sees the exact model request the host builds, so the
12
- * injection report can state which memory blocks (and how many) reached the
13
- * model on each request. The marker set is pinned to plugin 1.2.3
14
- * (lib/inject.js); update MARKERS together with that file, not from memory.
15
- *
16
- * Usage:
17
- * node scripts/mock-llm.mjs --port 8123 --log ./mock-llm-2026-11-01.jsonl
18
- * node scripts/mock-llm.mjs --reply-file ./tests/fixtures/mock-llm/reply.txt \
19
- * --port 8123 --log ./mock-llm-2026-11-01.jsonl
20
- * node scripts/mock-llm.mjs --report ./mock-llm-2026-11-01.jsonl > mock-llm-report-2026-11-01.md
21
- *
22
- * Endpoints:
23
- * POST /v1/chat/completions (also /chat/completions for a root base URL)
24
- * GET /v1/models (also /models)
25
- * GET /health (liveness only)
26
- *
27
- * The SSE reply is deliberately plain text: it never claims a tool call, so a
28
- * measurement run cannot turn into a fake tool round.
29
- */
30
- import fs from 'node:fs'
31
- import http from 'node:http'
32
- import path from 'node:path'
33
- import crypto from 'node:crypto'
34
- import { pathToFileURL } from 'node:url'
35
-
36
- /** One JSONL schema version; bump only for a breaking field change. */
37
- export const LOG_VERSION = 1
38
-
39
- /** Model id served by GET /v1/models unless --model overrides it. */
40
- export const DEFAULT_MODEL = 'dsh-mock-llm'
41
-
42
- /** Reply used when --reply-file is absent. */
43
- export const DEFAULT_REPLY = '(测试回复)'
44
-
45
- /** Plugin version whose injection markers are pinned below. */
46
- export const MARKER_SET_VERSION = '1.2.3'
47
-
48
- const MAX_BODY_BYTES = 16 * 1024 * 1024
49
-
50
- /**
51
- * The 1.2.3 injection markers, in report order.
52
- *
53
- * Source of truth: lib/inject.js (verified 2026-11-01 / 1.2.3).
54
- * - `<memory-guide` is a prefix because the open tag carries rules="…".
55
- * - `<memory-cue` / `<memory-texture` / `<memory-context` carry attributes.
56
- * - The replay line is matched literally, including the U+00B7 middle dot.
57
- *
58
- * Adding, renaming or dropping a block in lib/inject.js means changing this table
59
- * in the same commit and bumping MARKER_SET_VERSION; a stale table reports a real
60
- * block as zero injections, which is worse than no measurement.
61
- */
62
- export const MARKERS = Object.freeze([
63
- { key: 'guide', column: 'guide', marker: '<memory-guide', meaning: 'rules guide message (first step / rules change)' },
64
- { key: 'anchor', column: 'anchor', marker: '===== memory anchor =====', meaning: 'anchor title card (no body in 1.2.3)' },
65
- { key: 'due', column: 'due', marker: '<memory-due>', meaning: 'dated memory due today/tomorrow' },
66
- { key: 'anniversary', column: 'anniv', marker: '<memory-anniversary>', meaning: 'annual anniversary block' },
67
- { key: 'cue', column: 'cue', marker: '<memory-cue', meaning: 'random/source cue' },
68
- { key: 'texture', column: 'texture', marker: '<memory-texture', meaning: 'imagined texture line' },
69
- { key: 'media', column: 'media', marker: '<memory-media>', meaning: 'image reference block' },
70
- { key: 'lexicon', column: 'lexicon', marker: '<memory-lexicon>', meaning: 'lexicon B channel' },
71
- { key: 'context', column: 'ctx', marker: '<memory-context', meaning: 'per-turn recall title card' },
72
- { key: 'openLoop', column: 'loop', marker: '[open loop]', meaning: 'open-loop nudge' },
73
- { key: 'freshness', column: 'fresh', marker: '<memory-freshness>', meaning: 'time-sensitivity hint under a recall block' },
74
- { key: 'replay', column: 'replay', marker: '[replay · 压缩前在上下文里的记忆]', meaning: 'post-compaction replay' },
75
- ])
76
-
77
- /** Marker key order used by the matrix and totals. */
78
- export const MARKER_KEYS = Object.freeze(MARKERS.map((item) => item.key))
79
-
80
- const USAGE = `EVALUATION ONLY — local fake OpenAI-compatible server for injection measurement.
81
-
82
- Usage:
83
- node scripts/mock-llm.mjs [options]
84
- node scripts/mock-llm.mjs --report [file] [--log file]
85
-
86
- Options:
87
- --port <n> Loopback port, 0 asks the OS. Default: 8123.
88
- --model <id> Model id served by GET /v1/models and echoed in frames.
89
- Default: ${DEFAULT_MODEL}.
90
- --reply-file <p> Plain-text assistant reply. Default: ${JSON.stringify(DEFAULT_REPLY)}.
91
- --log <p> Append one JSONL record per request (lengths + markers only).
92
- --report [p] Do not start a server; read a JSONL log and print a markdown
93
- report. The path defaults to --log.
94
- -h, --help Show this text.
95
-
96
- Safety:
97
- * Binds 127.0.0.1 only; there is no authentication.
98
- * Message bodies are never written. Only role, character length, a content
99
- hash and marker counts are logged.
100
- * Rotate/delete logs and reports; do not commit captured conversation data.
101
-
102
- Marker set (plugin 1.2.3, lib/inject.js):
103
- ${MARKERS.map((item) => ` ${item.column.padEnd(8)} ${item.marker}`).join('\n')}
104
- `
105
-
106
- /** Count non-overlapping occurrences of one literal marker. */
107
- export function countOccurrences(text, needle) {
108
- if (typeof text !== 'string' || text.length === 0 || !needle) return 0
109
- let count = 0
110
- let at = text.indexOf(needle)
111
- while (at !== -1) {
112
- count += 1
113
- at = text.indexOf(needle, at + needle.length)
114
- }
115
- return count
116
- }
117
-
118
- /** Count every pinned 1.2.3 marker in one block of text. */
119
- export function countMemoryMarkers(text) {
120
- const counts = {}
121
- for (const item of MARKERS) counts[item.key] = countOccurrences(text, item.marker)
122
- return counts
123
- }
124
-
125
- /** Sum marker maps, ignoring unknown keys. */
126
- function sumMarkers(list) {
127
- const total = {}
128
- for (const key of MARKER_KEYS) total[key] = 0
129
- for (const counts of list) {
130
- for (const key of MARKER_KEYS) total[key] += Number(counts?.[key] || 0)
131
- }
132
- return total
133
- }
134
-
135
- /**
136
- * Extract text from an OpenAI chat message or an Anthropic-shaped block list.
137
- * Image/tool blocks contribute no text; the caller counts them structurally.
138
- */
139
- export function messageText(message) {
140
- const content = message?.content
141
- if (typeof content === 'string') return content
142
- if (!Array.isArray(content)) return ''
143
- return content
144
- .map((part) => {
145
- if (typeof part === 'string') return part
146
- if (part && typeof part.text === 'string') return part.text
147
- return ''
148
- })
149
- .filter(Boolean)
150
- .join('\n')
151
- }
152
-
153
- /** Hash that lets a report diff requests without storing their text. */
154
- function contentHash(role, text) {
155
- return crypto.createHash('sha256').update(String(role) + '\u0000' + String(text), 'utf8').digest('hex').slice(0, 16)
156
- }
157
-
158
- const CONTEXT_RE = /<memory-context\b([^>]*)>([\s\S]*?)<\/memory-context>/g
159
- const CARD_LINE_RE = /^\s*-\s+\[([^\]]+)\]/
160
-
161
- /**
162
- * Structural facts about `<memory-context>` blocks in one message.
163
- *
164
- * `bodyLines` counts indented continuation lines. 1.2.3 renders title cards as
165
- * one line per entry; a positive count means body text leaked into the prompt.
166
- */
167
- export function analyzeMemoryContext(text, idSink = null) {
168
- const stats = {
169
- blocks: 0,
170
- ids: 0,
171
- uniqueIds: 0,
172
- cardLines: 0,
173
- bodyLines: 0,
174
- scopes: { private: 0, global: 0, other: 0 },
175
- }
176
- if (typeof text !== 'string' || !text.includes('<memory-context')) return stats
177
- const ids = new Set()
178
- CONTEXT_RE.lastIndex = 0
179
- let block
180
- while ((block = CONTEXT_RE.exec(text)) !== null) {
181
- stats.blocks += 1
182
- const scope = /scope="([^"]+)"/.exec(block[1] || '')?.[1]
183
- if (scope === 'private' || scope === 'global') stats.scopes[scope] += 1
184
- else stats.scopes.other += 1
185
- for (const line of block[2].split(/\r?\n/)) {
186
- const card = CARD_LINE_RE.exec(line)
187
- if (card) {
188
- stats.cardLines += 1
189
- stats.ids += 1
190
- ids.add(card[1])
191
- if (idSink) idSink.add(card[1])
192
- continue
193
- }
194
- if (/^\s{2,}\S/.test(line)) stats.bodyLines += 1
195
- }
196
- }
197
- stats.uniqueIds = ids.size
198
- return stats
199
- }
200
-
201
- /** Analyse one message: role, length, hash, markers and context structure. */
202
- export function analyzeMessage(message, roleOverride = null, idSink = null) {
203
- const role = roleOverride || String(message?.role || 'unknown')
204
- const text = messageText(message)
205
- const context = analyzeMemoryContext(text, idSink)
206
- // The guide message talks *about* `<memory-context>` in its prose
207
- // (system-guide.md). Counting that sentence as a recall block would put a
208
- // phantom ctx hit on every guided turn, so a guide carrier counts only the
209
- // guide tag itself; every other message is counted literally.
210
- const guideCarrier = /^\s*<memory-guide\b/.test(text)
211
- const counts = guideCarrier
212
- ? { guide: countOccurrences(text, '<memory-guide') }
213
- : countMemoryMarkers(text)
214
- const part = {
215
- role,
216
- chars: text.length,
217
- hash: contentHash(role, text),
218
- markers: Object.fromEntries(Object.entries(counts).filter(([, value]) => value > 0)),
219
- }
220
- if (context.blocks > 0) part.context = context
221
- return part
222
- }
223
-
224
- /** Analyse a chat-completions request body without retaining any message text. */
225
- export function analyzeRequestBody(body, model) {
226
- const rawMessages = Array.isArray(body?.messages) ? body.messages : []
227
- const parts = []
228
- const allContextIds = new Set()
229
- // OpenAI chat requests carry the system prompt inside messages. Anthropic's
230
- // Messages shape keeps it top-level; counting it keeps the delta stable if a
231
- // provider base URL is pointed at this mock by mistake.
232
- if (typeof body?.system === 'string' && body.system.trim()) {
233
- parts.push(analyzeMessage({ role: 'system', content: body.system }, 'system', allContextIds))
234
- }
235
- for (const message of rawMessages) parts.push(analyzeMessage(message, null, allContextIds))
236
- const markers = sumMarkers(parts.map((part) => part.markers))
237
- const context = {
238
- blocks: parts.reduce((sum, part) => sum + (part.context?.blocks || 0), 0),
239
- ids: parts.reduce((sum, part) => sum + (part.context?.ids || 0), 0),
240
- uniqueIds: allContextIds.size,
241
- cardLines: parts.reduce((sum, part) => sum + (part.context?.cardLines || 0), 0),
242
- bodyLines: parts.reduce((sum, part) => sum + (part.context?.bodyLines || 0), 0),
243
- scopes: {
244
- private: parts.reduce((sum, part) => sum + (part.context?.scopes?.private || 0), 0),
245
- global: parts.reduce((sum, part) => sum + (part.context?.scopes?.global || 0), 0),
246
- other: parts.reduce((sum, part) => sum + (part.context?.scopes?.other || 0), 0),
247
- },
248
- }
249
- const chars = parts.reduce((sum, part) => sum + part.chars, 0)
250
- const first = parts[0]
251
- const firstNonSystem = parts.find((part) => part.role !== 'system')
252
- // Conversation identity: the system prompt, the first non-system message and
253
- // the model. A single mock instance normally serves one session, but two
254
- // sessions can share a system prompt, so the first user message is part of
255
- // the key that keeps their deltas apart.
256
- const conversation = contentHash(
257
- 'conversation:' + (body?.model || model || ''),
258
- [first ? first.hash : 'no-system', firstNonSystem ? firstNonSystem.hash : 'no-user'].join(':'),
259
- )
260
- return {
261
- model: typeof body?.model === 'string' && body.model ? body.model : model,
262
- messages: rawMessages.length,
263
- chars,
264
- markers,
265
- context,
266
- parts,
267
- conversation,
268
- }
269
- }
270
-
271
- function splitReply(text) {
272
- const chars = Array.from(String(text))
273
- if (chars.length === 0) return []
274
- // 24 frames is enough to exercise incremental delivery; larger replies grow
275
- // the chunk size instead of the frame count.
276
- const chunkSize = Math.max(8, Math.ceil(chars.length / 24))
277
- const chunks = []
278
- for (let i = 0; i < chars.length; i += chunkSize) chunks.push(chars.slice(i, i + chunkSize).join(''))
279
- return chunks
280
- }
281
-
282
- function completionChunk({ id, created, model, delta, finishReason = null }) {
283
- return {
284
- id,
285
- object: 'chat.completion.chunk',
286
- created,
287
- model,
288
- choices: [{ index: 0, delta, finish_reason: finishReason }],
289
- }
290
- }
291
-
292
- function writeSse(res, payload) {
293
- if (res.destroyed || res.writableEnded) return false
294
- res.write('data: ' + JSON.stringify(payload) + '\n\n')
295
- return true
296
- }
297
-
298
- function sendJson(res, status, value, extraHeaders = {}) {
299
- if (res.destroyed || res.writableEnded) return
300
- const body = JSON.stringify(value)
301
- res.writeHead(status, {
302
- 'content-type': 'application/json; charset=utf-8',
303
- 'content-length': Buffer.byteLength(body),
304
- 'cache-control': 'no-store',
305
- 'x-mock-llm': 'evaluation-only',
306
- ...extraHeaders,
307
- })
308
- res.end(body)
309
- }
310
-
311
- function sendError(res, status, message, code = 'invalid_request_error', extraHeaders = {}) {
312
- sendJson(res, status, { error: { message, type: code, code } }, extraHeaders)
313
- }
314
-
315
- function readBody(req, limit = MAX_BODY_BYTES) {
316
- return new Promise((resolve, reject) => {
317
- const chunks = []
318
- let size = 0
319
- let settled = false
320
- req.on('data', (chunk) => {
321
- if (settled) return
322
- size += chunk.length
323
- if (size > limit) {
324
- settled = true
325
- const error = new Error('request body exceeds the mock limit')
326
- error.status = 413
327
- reject(error)
328
- req.destroy()
329
- return
330
- }
331
- chunks.push(chunk)
332
- })
333
- req.on('end', () => {
334
- if (settled) return
335
- settled = true
336
- resolve(Buffer.concat(chunks))
337
- })
338
- req.on('error', (error) => {
339
- if (settled) return
340
- settled = true
341
- reject(error)
342
- })
343
- req.on('aborted', () => {
344
- if (settled) return
345
- settled = true
346
- const error = new Error('client aborted the request body')
347
- error.status = 400
348
- reject(error)
349
- })
350
- })
351
- }
352
-
353
- function appendJsonl(logPath, record) {
354
- if (!logPath) return
355
- fs.mkdirSync(path.dirname(path.resolve(logPath)), { recursive: true })
356
- fs.appendFileSync(logPath, JSON.stringify(record) + '\n', 'utf8')
357
- }
358
-
359
- function nowIso() {
360
- return new Date().toISOString()
361
- }
362
-
363
- /**
364
- * Start one loopback-only mock server.
365
- *
366
- * @param {object} [options]
367
- * @param {number} [options.port] TCP port; 0 asks the OS.
368
- * @param {string} [options.model] Model id to advertise.
369
- * @param {string} [options.reply] Plain-text assistant reply.
370
- * @param {string|null} [options.log] JSONL path to append; null disables it.
371
- * @returns {Promise<{url:string,port:number,model:string,log:string|null,server:http.Server,close:()=>Promise<void>}>}
372
- */
373
- export async function startMockLlm(options = {}) {
374
- const port = Number.isInteger(options.port) ? options.port : 0
375
- if (port < 0 || port > 65535) throw new Error('port must be 0..65535')
376
- const model = typeof options.model === 'string' && options.model.trim() ? options.model.trim() : DEFAULT_MODEL
377
- const reply = typeof options.reply === 'string' ? options.reply : DEFAULT_REPLY
378
- const log = options.log ? path.resolve(options.log) : null
379
- const state = { seq: 0 }
380
-
381
- const server = http.createServer((req, res) => {
382
- void handleRequest({ req, res, state, model, reply, log })
383
- })
384
-
385
- await new Promise((resolve, reject) => {
386
- const onError = (error) => reject(error)
387
- server.once('error', onError)
388
- server.listen(port, '127.0.0.1', () => {
389
- server.off('error', onError)
390
- resolve()
391
- })
392
- })
393
- const address = server.address()
394
- const actualPort = typeof address === 'object' && address ? address.port : port
395
- return {
396
- server,
397
- port: actualPort,
398
- url: `http://127.0.0.1:${actualPort}`,
399
- model,
400
- log,
401
- close: () => new Promise((resolve) => {
402
- server.closeAllConnections?.()
403
- server.close(() => resolve())
404
- }),
405
- }
406
- }
407
-
408
- async function handleRequest({ req, res, state, model, reply, log }) {
409
- const url = new URL(req.url || '/', 'http://127.0.0.1')
410
- const pathname = url.pathname
411
-
412
- if (pathname === '/health') {
413
- if (req.method !== 'GET') return sendError(res, 405, 'GET only', 'method_not_allowed', { allow: 'GET' })
414
- return sendJson(res, 200, { ok: true, model, evaluationOnly: true })
415
- }
416
-
417
- if (pathname === '/v1/models' || pathname === '/models') {
418
- if (req.method !== 'GET') return sendError(res, 405, 'GET only', 'method_not_allowed', { allow: 'GET' })
419
- return sendJson(res, 200, {
420
- object: 'list',
421
- data: [{ id: model, object: 'model', created: 0, owned_by: 'dsh-mock-llm' }],
422
- })
423
- }
424
-
425
- const knownChat = pathname === '/v1/chat/completions' || pathname === '/chat/completions'
426
- if (!knownChat) return sendError(res, 404, 'not found: ' + pathname, 'not_found')
427
- if (req.method !== 'POST') return sendError(res, 405, 'POST only', 'method_not_allowed', { allow: 'POST' })
428
-
429
- let raw
430
- try {
431
- raw = await readBody(req)
432
- } catch (error) {
433
- if (!res.destroyed) sendError(res, error.status || 400, error.message)
434
- return
435
- }
436
-
437
- let body
438
- try {
439
- body = JSON.parse(raw.toString('utf8'))
440
- if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('body must be a JSON object')
441
- } catch (error) {
442
- // Safe status: a bad body is the caller's error, never a partial reply.
443
- sendError(res, 400, 'invalid JSON body: ' + error.message)
444
- return
445
- }
446
-
447
- const analysis = analyzeRequestBody(body, model)
448
- // Reserve the sequence before streaming: concurrent requests must not share
449
- // an id or a JSONL seq even though the append happens at completion.
450
- state.seq += 1
451
- const seq = state.seq
452
- const id = 'chatcmpl-mock-' + seq
453
- const created = Math.floor(Date.now() / 1000)
454
- const started = Date.now()
455
- const aborted = { value: false }
456
- const frames = { sent: 0 }
457
- let status = 200
458
-
459
- req.on('aborted', () => { aborted.value = true })
460
- req.on('error', () => { aborted.value = true })
461
- res.on('error', () => { aborted.value = true })
462
- res.on('close', () => { if (!res.writableEnded) aborted.value = true })
463
-
464
- const recordBase = {
465
- v: LOG_VERSION,
466
- event: 'request',
467
- time: nowIso(),
468
- seq,
469
- model: analysis.model,
470
- conversation: analysis.conversation,
471
- messages: analysis.messages,
472
- chars: analysis.chars,
473
- markers: analysis.markers,
474
- context: analysis.context,
475
- parts: analysis.parts,
476
- }
477
-
478
- try {
479
- if (body.stream === false) {
480
- const completion = {
481
- id,
482
- object: 'chat.completion',
483
- created,
484
- model: analysis.model,
485
- choices: [{
486
- index: 0,
487
- message: { role: 'assistant', content: reply },
488
- finish_reason: 'stop',
489
- }],
490
- usage: {
491
- prompt_tokens: 0,
492
- completion_tokens: Array.from(reply).length,
493
- total_tokens: Array.from(reply).length,
494
- },
495
- }
496
- sendJson(res, 200, completion)
497
- } else {
498
- res.writeHead(200, {
499
- 'content-type': 'text/event-stream; charset=utf-8',
500
- 'cache-control': 'no-cache, no-transform',
501
- connection: 'keep-alive',
502
- 'x-accel-buffering': 'no',
503
- 'x-mock-llm': 'evaluation-only',
504
- })
505
- const base = { id, created, model: analysis.model }
506
- if (writeSse(res, completionChunk({ ...base, delta: { role: 'assistant', content: '' } }))) frames.sent += 1
507
- for (const text of splitReply(reply)) {
508
- if (aborted.value || res.destroyed) break
509
- if (writeSse(res, completionChunk({ ...base, delta: { content: text } }))) frames.sent += 1
510
- }
511
- if (!aborted.value && !res.destroyed) {
512
- // Explicit stop; no tool_calls are ever fabricated.
513
- writeSse(res, completionChunk({ ...base, delta: {}, finishReason: 'stop' }))
514
- frames.sent += 1
515
- res.write('data: [DONE]\n\n')
516
- res.end()
517
- }
518
- }
519
- } catch (error) {
520
- aborted.value = true
521
- if (!res.headersSent) {
522
- status = 500
523
- sendError(res, 500, 'mock stream failed: ' + error.message, 'server_error')
524
- } else {
525
- res.destroy()
526
- }
527
- } finally {
528
- try {
529
- appendJsonl(log, {
530
- ...recordBase,
531
- reply: { mode: body.stream === false ? 'json' : 'sse', chars: Array.from(reply).length, frames: frames.sent },
532
- status,
533
- aborted: aborted.value,
534
- durationMs: Date.now() - started,
535
- })
536
- } catch (error) {
537
- console.error('mock-llm: failed to append JSONL: ' + error.message)
538
- }
539
- }
540
- }
541
-
542
- function isoTime(value) {
543
- const date = new Date(value)
544
- if (Number.isNaN(date.getTime())) return '—'
545
- return date.toISOString().slice(11, 19) + 'Z'
546
- }
547
-
548
- function shortestId(value) {
549
- const text = String(value || '?')
550
- return text.length > 8 ? text.slice(0, 8) : text
551
- }
552
-
553
- function markersFromParts(parts) {
554
- return sumMarkers(parts.map((part) => part.markers || {}))
555
- }
556
-
557
- function hasAnyMarker(markers) {
558
- return MARKER_KEYS.some((key) => Number(markers?.[key] || 0) > 0)
559
- }
560
-
561
- /**
562
- * Build the markdown report for one JSONL log.
563
- *
564
- * Per-request deltas are computed from the per-message hashes: the current
565
- * request's messages are compared with the previous request of the same
566
- * conversation as a multiset. When the message list is not a prefix of the new
567
- * one (compaction, transcript rewrite), the round is marked `rebased` and is
568
- * excluded from zero-injection attribution: the delta cannot be trusted.
569
- *
570
- * @param {string} jsonl raw log contents.
571
- * @param {{logPath?:string}} [options]
572
- * @returns {string} markdown
573
- */
574
- export function renderReport(jsonl, options = {}) {
575
- const lines = String(jsonl || '').split(/\r?\n/).filter((line) => line.trim())
576
- const records = []
577
- let skipped = 0
578
- for (const line of lines) {
579
- let value
580
- try { value = JSON.parse(line) } catch { skipped += 1; continue }
581
- if (!value || typeof value !== 'object') { skipped += 1; continue }
582
- if (value.event !== undefined && value.event !== 'request') continue
583
- if (!value.markers || !Array.isArray(value.parts)) { skipped += 1; continue }
584
- records.push(value)
585
- }
586
-
587
- const out = []
588
- const conversationCount = new Set(records.map((record) => record.conversation || 'unknown')).size
589
- out.push('# Mock LLM injection report')
590
- out.push('')
591
- out.push('> EVALUATION ONLY. Generated from request metadata (lengths, hashes, marker counts); no message body is stored in the log.')
592
- out.push('')
593
- if (options.logPath) out.push(`- log: \`${options.logPath}\``)
594
- out.push(`- generated: ${new Date().toISOString().slice(0, 10)} (UTC)`)
595
- out.push(`- requests: ${records.length}`)
596
- out.push(`- conversations: ${conversationCount}`)
597
- out.push(`- marker set: plugin ${MARKER_SET_VERSION} (${MARKER_KEYS.length} markers)`)
598
- if (skipped) out.push(`- skipped/foreign JSONL lines: ${skipped}`)
599
- if (records.length > 1 && conversationCount === records.length) {
600
- out.push('- warning: every request has a different conversation fingerprint; the delta is not comparable (a changing system prompt, such as a timestamp, breaks the grouping).')
601
- }
602
- out.push('')
603
- out.push('## Legend')
604
- out.push('')
605
- out.push('| col | marker | meaning |')
606
- out.push('| --- | --- | --- |')
607
- for (const item of MARKERS) out.push(`| ${item.column} | \`${item.marker}\` | ${item.meaning} |`)
608
- out.push('')
609
- out.push('`Δ` below counts markers in messages that are **new relative to the previous request of the same conversation**. `·` means zero. `—` in a `rebased` row means the transcript changed shape and the delta is not reliable.')
610
- out.push('')
611
-
612
- const states = []
613
- let previousByConversation = new Map()
614
- let round = 0
615
- for (const record of records) {
616
- round += 1
617
- const conversation = record.conversation || 'unknown'
618
- const parts = Array.isArray(record.parts) ? record.parts : []
619
- const previous = previousByConversation.get(conversation) || null
620
- let mode = 'first'
621
- let newParts = parts
622
- if (previous) {
623
- const previousHashes = previous.map((part) => part.hash)
624
- const currentHashes = parts.map((part) => part.hash)
625
- const prefix = previousHashes.length <= currentHashes.length
626
- && previousHashes.every((hash, index) => hash === currentHashes[index])
627
- mode = prefix ? 'delta' : 'rebased'
628
- if (mode === 'delta') {
629
- const remaining = new Map()
630
- for (const hash of previousHashes) remaining.set(hash, (remaining.get(hash) || 0) + 1)
631
- newParts = []
632
- for (const part of parts) {
633
- const left = remaining.get(part.hash) || 0
634
- if (left > 0) remaining.set(part.hash, left - 1)
635
- else newParts.push(part)
636
- }
637
- }
638
- }
639
- previousByConversation.set(conversation, parts)
640
- const delta = markersFromParts(newParts)
641
- const unreliable = mode === 'rebased'
642
- states.push({
643
- round,
644
- conversation,
645
- record,
646
- mode,
647
- unreliable,
648
- parts,
649
- newParts,
650
- delta,
651
- zero: !unreliable && !hasAnyMarker(delta),
652
- })
653
- }
654
-
655
- out.push('## Per-request marker matrix')
656
- out.push('')
657
- out.push('`#` is the log order (not the per-process `seq`).')
658
- out.push('')
659
- const header = ['#', 'conv', 'time', 'msgs', 'Δmsgs', ...MARKERS.map((item) => item.column), 'ctxIds']
660
- out.push('| ' + header.join(' | ') + ' |')
661
- out.push('| ' + header.map(() => '---').join(' | ') + ' |')
662
- for (const state of states) {
663
- const record = state.record
664
- const cells = []
665
- if (state.unreliable) {
666
- for (let i = 0; i < MARKERS.length; i += 1) cells.push('—')
667
- cells.push('—')
668
- } else {
669
- for (const item of MARKERS) cells.push(state.delta[item.key] ? String(state.delta[item.key]) : '·')
670
- cells.push(state.mode === 'first' ? String(record.context?.ids || 0) : String(sumContextIds(state.newParts)))
671
- }
672
- const row = [
673
- String(state.round),
674
- shortestId(state.conversation),
675
- isoTime(record.time),
676
- String(record.messages ?? 0),
677
- state.unreliable ? '—' : String(state.newParts.length),
678
- ...cells,
679
- ]
680
- out.push('| ' + row.join(' | ') + ' |')
681
- }
682
- out.push('')
683
-
684
- out.push('## Totals by block')
685
- out.push('')
686
- out.push('| col | marker | rounds with Δ>0 | Δ total | requests containing (sum, history included) |')
687
- out.push('| --- | --- | --- | --- | --- |')
688
- for (const item of MARKERS) {
689
- let roundsWithDelta = 0
690
- let deltaTotal = 0
691
- let presentTotal = 0
692
- for (const state of states) {
693
- if (!state.unreliable && Number(state.delta[item.key] || 0) > 0) roundsWithDelta += 1
694
- if (!state.unreliable) deltaTotal += Number(state.delta[item.key] || 0)
695
- presentTotal += Number(state.record.markers?.[item.key] || 0)
696
- }
697
- out.push(`| ${item.column} | \`${item.marker}\` | ${roundsWithDelta} | ${deltaTotal} | ${presentTotal} |`)
698
- }
699
- out.push('')
700
-
701
- const contextStates = states.filter((state) => !state.unreliable && (state.record.context?.blocks || 0) > 0)
702
- out.push('## `<memory-context>` title cards')
703
- out.push('')
704
- if (contextStates.length === 0) {
705
- out.push('None.')
706
- } else {
707
- out.push('| # | conv | blocks | private | global | ids | unique | card lines | body lines |')
708
- out.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- |')
709
- for (const state of contextStates) {
710
- const context = state.record.context
711
- out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${context.blocks || 0} | ${context.scopes?.private || 0} | ${context.scopes?.global || 0} | ${context.ids || 0} | ${context.uniqueIds || 0} | ${context.cardLines || 0} | ${context.bodyLines || 0} |`)
712
- }
713
- out.push('')
714
- out.push('This table shows request totals (history included), not per-turn deltas. `body lines` counts indented continuation lines inside the block: 1.2.3 title cards should keep it at 0, and a positive number means body text reached the prompt.')
715
- }
716
- out.push('')
717
-
718
- const zero = states.filter((state) => state.zero)
719
- out.push('## Zero-injection requests')
720
- out.push('')
721
- out.push(`Count: **${zero.length}** of ${states.length} requests.`)
722
- out.push('')
723
- if (zero.length > 0) {
724
- out.push('| # | conv | msgs | Δmsgs | hint |')
725
- out.push('| --- | --- | --- | --- | --- |')
726
- for (const state of zero) {
727
- out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${state.record.messages ?? 0} | ${state.newParts.length} | ${zeroHint(state)} |`)
728
- }
729
- out.push('')
730
- out.push('Attribution is limited to what the model request itself can prove. Unless a session log is reconciled separately (plan B.6), an unexplained row is a **data gap**, not "no memory was due".')
731
- } else {
732
- out.push('None.')
733
- }
734
- out.push('')
735
-
736
- const rebased = states.filter((state) => state.unreliable)
737
- if (rebased.length > 0) {
738
- out.push('## Rebased requests (delta unavailable)')
739
- out.push('')
740
- out.push(`Count: **${rebased.length}** (transcript was not a prefix of the previous request: compaction or rewrite).`)
741
- out.push('')
742
- out.push('| # | conv | msgs |')
743
- out.push('| --- | --- | --- |')
744
- for (const state of rebased) out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${state.record.messages ?? 0} |`)
745
- out.push('')
746
- }
747
-
748
- out.push('## Notes')
749
- out.push('')
750
- out.push('- The log records request metadata only; it cannot name settings (`autoInject`, `dedupeTurns`, budgets). Record that snapshot beside the run (plan B.4).')
751
- out.push('- `requests containing (sum)` double-counts blocks that stayed in the transcript; use `Δ total` for per-turn injection counts.')
752
- out.push('- A separate model call (title generation, summarization) gets its own `conv` fingerprint; filter those rows before reading a conversation\'s injection rate.')
753
- out.push('- Do not commit captured logs or this report when they came from a real conversation.')
754
- out.push('')
755
- return out.join('\n')
756
- }
757
-
758
- function sumContextIds(parts) {
759
- return parts.reduce((sum, part) => sum + Number(part.context?.ids || 0), 0)
760
- }
761
-
762
- function zeroHint(state) {
763
- if (state.unreliable) return 'rebased: delta unreliable (data gap)'
764
- if (state.newParts.length === 0) return 'no new message (retry or intra-turn step)'
765
- if (!state.newParts.some((part) => part.role === 'system' || part.role === 'user')) return 'new messages carry no user/system text'
766
- const all = state.record.markers || {}
767
- const delta = state.delta || {}
768
- // These are hints read from the request itself, not causes: the mock cannot
769
- // see settings, dedupe state or the plugin activity log.
770
- if (!all.guide && !all.anchor) return 'no guide/anchor anywhere in the request: injection may be off, unbound, or compacted away (data gap)'
771
- if (all.context && !delta.context) return 'history has a recall block but no new one: possible no-match, dedupe, budget or tooShort (needs session log)'
772
- if (all.anchor && !delta.anchor && !delta.guide) return 'anchor already delivered and no new block: possible anchor-only step, no-match or budget (needs session log)'
773
- return 'data gap: no pinned marker in new messages'
774
- }
775
-
776
- function parseArgs(argv) {
777
- const options = {
778
- port: 8123,
779
- model: DEFAULT_MODEL,
780
- replyFile: null,
781
- log: null,
782
- report: null,
783
- help: false,
784
- }
785
- const take = (index, name) => {
786
- const value = argv[index]
787
- if (value === undefined || value.startsWith('--')) throw new Error(name + ' requires a value')
788
- return value
789
- }
790
- for (let i = 0; i < argv.length; i += 1) {
791
- const token = argv[i]
792
- const eq = token.indexOf('=')
793
- const name = eq === -1 ? token : token.slice(0, eq)
794
- const inline = eq === -1 ? null : token.slice(eq + 1)
795
- switch (name) {
796
- case '-h':
797
- case '--help':
798
- options.help = true
799
- break
800
- case '--port': {
801
- const value = inline ?? take(++i, '--port')
802
- const port = Number(value)
803
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('--port must be an integer 0..65535')
804
- options.port = port
805
- break
806
- }
807
- case '--model':
808
- options.model = inline ?? take(++i, '--model')
809
- break
810
- case '--reply-file':
811
- options.replyFile = inline ?? take(++i, '--reply-file')
812
- break
813
- case '--log':
814
- options.log = inline ?? take(++i, '--log')
815
- break
816
- case '--report':
817
- if (inline !== null) options.report = inline
818
- else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) options.report = argv[++i]
819
- else options.report = true
820
- break
821
- default:
822
- throw new Error('unknown option: ' + token)
823
- }
824
- }
825
- return options
826
- }
827
-
828
- async function main(argv = process.argv.slice(2)) {
829
- let options
830
- try {
831
- options = parseArgs(argv)
832
- } catch (error) {
833
- console.error('mock-llm: ' + error.message + '\n')
834
- console.error(USAGE)
835
- return 2
836
- }
837
- if (options.help) {
838
- process.stdout.write(USAGE)
839
- return 0
840
- }
841
- if (options.report !== null) {
842
- const reportPath = options.report === true ? options.log : options.report
843
- if (!reportPath) {
844
- console.error('mock-llm: --report needs a path (or pass --log with the same run)')
845
- return 2
846
- }
847
- let raw
848
- try {
849
- raw = fs.readFileSync(reportPath, 'utf8')
850
- } catch (error) {
851
- console.error('mock-llm: cannot read log ' + reportPath + ': ' + error.message)
852
- return 1
853
- }
854
- process.stdout.write(renderReport(raw, { logPath: path.resolve(reportPath) }))
855
- return 0
856
- }
857
-
858
- let reply = DEFAULT_REPLY
859
- if (options.replyFile) {
860
- try {
861
- reply = fs.readFileSync(options.replyFile, 'utf8')
862
- } catch (error) {
863
- console.error('mock-llm: cannot read --reply-file: ' + error.message)
864
- return 1
865
- }
866
- }
867
-
868
- let instance
869
- try {
870
- instance = await startMockLlm({ port: options.port, model: options.model, reply, log: options.log })
871
- } catch (error) {
872
- if (error?.code === 'EADDRINUSE') {
873
- console.error(`mock-llm: port ${options.port} is already in use; pick another --port or use --port 0`)
874
- return 1
875
- }
876
- console.error('mock-llm: failed to listen: ' + (error?.message || error))
877
- return 1
878
- }
879
- console.log('mock-llm (EVALUATION ONLY) listening on ' + instance.url)
880
- console.log(' POST ' + instance.url + '/v1/chat/completions')
881
- console.log(' GET ' + instance.url + '/v1/models')
882
- if (instance.log) console.log(' JSONL log: ' + instance.log)
883
- else console.log(' JSONL log: disabled (pass --log <path> to record)')
884
- console.log(' No message bodies are stored. Do not expose this port; it is loopback-only and unauthenticated.')
885
-
886
- await new Promise((resolve) => {
887
- const stop = () => resolve()
888
- process.once('SIGINT', stop)
889
- process.once('SIGTERM', stop)
890
- })
891
- await instance.close()
892
- return 0
893
- }
894
-
895
- const invokedDirectly = process.argv[1]
896
- ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
897
- : false
898
- if (invokedDirectly) {
899
- main().then((code) => { process.exitCode = code }).catch((error) => {
900
- console.error('mock-llm: ' + (error?.stack || error))
901
- process.exitCode = 1
902
- })
903
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EVALUATION ONLY — local fake OpenAI-compatible endpoint for request diagnostics.
4
+ *
5
+ * This file is a developer measurement harness. It is never imported by
6
+ * lib/, never shipped as runtime behaviour, and must not be pointed at real
7
+ * user conversations that should be kept. It listens on 127.0.0.1 only, has no
8
+ * authentication, and stores only lengths, hashes and marker counts — never
9
+ * message bodies.
10
+ *
11
+ * Why it exists: the mock sees the exact model request the host builds, so the
12
+ * injection report can state which memory blocks (and how many) reached the
13
+ * model on each request. The marker set is pinned to plugin 1.2.3
14
+ * (lib/inject.js); update MARKERS together with that file, not from memory.
15
+ *
16
+ * Usage:
17
+ * node scripts/mock-llm.mjs --port 8123 --log ./mock-llm-2026-11-01.jsonl
18
+ * node scripts/mock-llm.mjs --reply-file ./tests/fixtures/mock-llm/reply.txt \
19
+ * --port 8123 --log ./mock-llm-2026-11-01.jsonl
20
+ * node scripts/mock-llm.mjs --report ./mock-llm-2026-11-01.jsonl > mock-llm-report-2026-11-01.md
21
+ *
22
+ * Endpoints:
23
+ * POST /v1/chat/completions (also /chat/completions for a root base URL)
24
+ * GET /v1/models (also /models)
25
+ * GET /health (liveness only)
26
+ *
27
+ * The SSE reply is deliberately plain text: it never claims a tool call, so a
28
+ * measurement run cannot turn into a fake tool round.
29
+ */
30
+ import fs from 'node:fs'
31
+ import http from 'node:http'
32
+ import path from 'node:path'
33
+ import crypto from 'node:crypto'
34
+ import { pathToFileURL } from 'node:url'
35
+
36
+ /** One JSONL schema version; bump only for a breaking field change. */
37
+ export const LOG_VERSION = 1
38
+
39
+ /** Model id served by GET /v1/models unless --model overrides it. */
40
+ export const DEFAULT_MODEL = 'dsh-mock-llm'
41
+
42
+ /** Reply used when --reply-file is absent. */
43
+ export const DEFAULT_REPLY = '(测试回复)'
44
+
45
+ /** Plugin version whose injection markers are pinned below. */
46
+ export const MARKER_SET_VERSION = '1.2.3'
47
+
48
+ const MAX_BODY_BYTES = 16 * 1024 * 1024
49
+
50
+ /**
51
+ * The 1.2.3 injection markers, in report order.
52
+ *
53
+ * Source of truth: lib/inject.js (verified 2026-11-01 / 1.2.3).
54
+ * - `<memory-guide` is a prefix because the open tag carries rules="…".
55
+ * - `<memory-cue` / `<memory-texture` / `<memory-context` carry attributes.
56
+ * - The replay line is matched literally, including the U+00B7 middle dot.
57
+ *
58
+ * Adding, renaming or dropping a block in lib/inject.js means changing this table
59
+ * in the same commit and bumping MARKER_SET_VERSION; a stale table reports a real
60
+ * block as zero injections, which is worse than no measurement.
61
+ */
62
+ export const MARKERS = Object.freeze([
63
+ { key: 'guide', column: 'guide', marker: '<memory-guide', meaning: 'rules guide message (first step / rules change)' },
64
+ { key: 'anchor', column: 'anchor', marker: '===== memory anchor =====', meaning: 'anchor title card (no body in 1.2.3)' },
65
+ { key: 'due', column: 'due', marker: '<memory-due>', meaning: 'dated memory due today/tomorrow' },
66
+ { key: 'anniversary', column: 'anniv', marker: '<memory-anniversary>', meaning: 'annual anniversary block' },
67
+ { key: 'cue', column: 'cue', marker: '<memory-cue', meaning: 'random/source cue' },
68
+ { key: 'texture', column: 'texture', marker: '<memory-texture', meaning: 'imagined texture line' },
69
+ { key: 'media', column: 'media', marker: '<memory-media>', meaning: 'image reference block' },
70
+ { key: 'lexicon', column: 'lexicon', marker: '<memory-lexicon>', meaning: 'lexicon B channel' },
71
+ { key: 'context', column: 'ctx', marker: '<memory-context', meaning: 'per-turn recall title card' },
72
+ { key: 'openLoop', column: 'loop', marker: '[open loop]', meaning: 'open-loop nudge' },
73
+ { key: 'freshness', column: 'fresh', marker: '<memory-freshness>', meaning: 'time-sensitivity hint under a recall block' },
74
+ { key: 'replay', column: 'replay', marker: '[replay · 压缩前在上下文里的记忆]', meaning: 'post-compaction replay' },
75
+ ])
76
+
77
+ /** Marker key order used by the matrix and totals. */
78
+ export const MARKER_KEYS = Object.freeze(MARKERS.map((item) => item.key))
79
+
80
+ const USAGE = `EVALUATION ONLY — local fake OpenAI-compatible server for injection measurement.
81
+
82
+ Usage:
83
+ node scripts/mock-llm.mjs [options]
84
+ node scripts/mock-llm.mjs --report [file] [--log file]
85
+
86
+ Options:
87
+ --port <n> Loopback port, 0 asks the OS. Default: 8123.
88
+ --model <id> Model id served by GET /v1/models and echoed in frames.
89
+ Default: ${DEFAULT_MODEL}.
90
+ --reply-file <p> Plain-text assistant reply. Default: ${JSON.stringify(DEFAULT_REPLY)}.
91
+ --log <p> Append one JSONL record per request (lengths + markers only).
92
+ --report [p] Do not start a server; read a JSONL log and print a markdown
93
+ report. The path defaults to --log.
94
+ -h, --help Show this text.
95
+
96
+ Safety:
97
+ * Binds 127.0.0.1 only; there is no authentication.
98
+ * Message bodies are never written. Only role, character length, a content
99
+ hash and marker counts are logged.
100
+ * Rotate/delete logs and reports; do not commit captured conversation data.
101
+
102
+ Marker set (plugin 1.2.3, lib/inject.js):
103
+ ${MARKERS.map((item) => ` ${item.column.padEnd(8)} ${item.marker}`).join('\n')}
104
+ `
105
+
106
+ /** Count non-overlapping occurrences of one literal marker. */
107
+ export function countOccurrences(text, needle) {
108
+ if (typeof text !== 'string' || text.length === 0 || !needle) return 0
109
+ let count = 0
110
+ let at = text.indexOf(needle)
111
+ while (at !== -1) {
112
+ count += 1
113
+ at = text.indexOf(needle, at + needle.length)
114
+ }
115
+ return count
116
+ }
117
+
118
+ /** Count every pinned 1.2.3 marker in one block of text. */
119
+ export function countMemoryMarkers(text) {
120
+ const counts = {}
121
+ for (const item of MARKERS) counts[item.key] = countOccurrences(text, item.marker)
122
+ return counts
123
+ }
124
+
125
+ /** Sum marker maps, ignoring unknown keys. */
126
+ function sumMarkers(list) {
127
+ const total = {}
128
+ for (const key of MARKER_KEYS) total[key] = 0
129
+ for (const counts of list) {
130
+ for (const key of MARKER_KEYS) total[key] += Number(counts?.[key] || 0)
131
+ }
132
+ return total
133
+ }
134
+
135
+ /**
136
+ * Extract text from an OpenAI chat message or an Anthropic-shaped block list.
137
+ * Image/tool blocks contribute no text; the caller counts them structurally.
138
+ */
139
+ export function messageText(message) {
140
+ const content = message?.content
141
+ if (typeof content === 'string') return content
142
+ if (!Array.isArray(content)) return ''
143
+ return content
144
+ .map((part) => {
145
+ if (typeof part === 'string') return part
146
+ if (part && typeof part.text === 'string') return part.text
147
+ return ''
148
+ })
149
+ .filter(Boolean)
150
+ .join('\n')
151
+ }
152
+
153
+ /** Hash that lets a report diff requests without storing their text. */
154
+ function contentHash(role, text) {
155
+ return crypto.createHash('sha256').update(String(role) + '\u0000' + String(text), 'utf8').digest('hex').slice(0, 16)
156
+ }
157
+
158
+ const CONTEXT_RE = /<memory-context\b([^>]*)>([\s\S]*?)<\/memory-context>/g
159
+ const CARD_LINE_RE = /^\s*-\s+\[([^\]]+)\]/
160
+
161
+ /**
162
+ * Structural facts about `<memory-context>` blocks in one message.
163
+ *
164
+ * `bodyLines` counts indented continuation lines. 1.2.3 renders title cards as
165
+ * one line per entry; a positive count means body text leaked into the prompt.
166
+ */
167
+ export function analyzeMemoryContext(text, idSink = null) {
168
+ const stats = {
169
+ blocks: 0,
170
+ ids: 0,
171
+ uniqueIds: 0,
172
+ cardLines: 0,
173
+ bodyLines: 0,
174
+ scopes: { private: 0, global: 0, other: 0 },
175
+ }
176
+ if (typeof text !== 'string' || !text.includes('<memory-context')) return stats
177
+ const ids = new Set()
178
+ CONTEXT_RE.lastIndex = 0
179
+ let block
180
+ while ((block = CONTEXT_RE.exec(text)) !== null) {
181
+ stats.blocks += 1
182
+ const scope = /scope="([^"]+)"/.exec(block[1] || '')?.[1]
183
+ if (scope === 'private' || scope === 'global') stats.scopes[scope] += 1
184
+ else stats.scopes.other += 1
185
+ for (const line of block[2].split(/\r?\n/)) {
186
+ const card = CARD_LINE_RE.exec(line)
187
+ if (card) {
188
+ stats.cardLines += 1
189
+ stats.ids += 1
190
+ ids.add(card[1])
191
+ if (idSink) idSink.add(card[1])
192
+ continue
193
+ }
194
+ if (/^\s{2,}\S/.test(line)) stats.bodyLines += 1
195
+ }
196
+ }
197
+ stats.uniqueIds = ids.size
198
+ return stats
199
+ }
200
+
201
+ /** Analyse one message: role, length, hash, markers and context structure. */
202
+ export function analyzeMessage(message, roleOverride = null, idSink = null) {
203
+ const role = roleOverride || String(message?.role || 'unknown')
204
+ const text = messageText(message)
205
+ const context = analyzeMemoryContext(text, idSink)
206
+ // The guide message talks *about* `<memory-context>` in its prose
207
+ // (system-guide.md). Counting that sentence as a recall block would put a
208
+ // phantom ctx hit on every guided turn, so a guide carrier counts only the
209
+ // guide tag itself; every other message is counted literally.
210
+ const guideCarrier = /^\s*<memory-guide\b/.test(text)
211
+ const counts = guideCarrier
212
+ ? { guide: countOccurrences(text, '<memory-guide') }
213
+ : countMemoryMarkers(text)
214
+ const part = {
215
+ role,
216
+ chars: text.length,
217
+ hash: contentHash(role, text),
218
+ markers: Object.fromEntries(Object.entries(counts).filter(([, value]) => value > 0)),
219
+ }
220
+ if (context.blocks > 0) part.context = context
221
+ return part
222
+ }
223
+
224
+ /** Analyse a chat-completions request body without retaining any message text. */
225
+ export function analyzeRequestBody(body, model) {
226
+ const rawMessages = Array.isArray(body?.messages) ? body.messages : []
227
+ const parts = []
228
+ const allContextIds = new Set()
229
+ // OpenAI chat requests carry the system prompt inside messages. Anthropic's
230
+ // Messages shape keeps it top-level; counting it keeps the delta stable if a
231
+ // provider base URL is pointed at this mock by mistake.
232
+ if (typeof body?.system === 'string' && body.system.trim()) {
233
+ parts.push(analyzeMessage({ role: 'system', content: body.system }, 'system', allContextIds))
234
+ }
235
+ for (const message of rawMessages) parts.push(analyzeMessage(message, null, allContextIds))
236
+ const markers = sumMarkers(parts.map((part) => part.markers))
237
+ const context = {
238
+ blocks: parts.reduce((sum, part) => sum + (part.context?.blocks || 0), 0),
239
+ ids: parts.reduce((sum, part) => sum + (part.context?.ids || 0), 0),
240
+ uniqueIds: allContextIds.size,
241
+ cardLines: parts.reduce((sum, part) => sum + (part.context?.cardLines || 0), 0),
242
+ bodyLines: parts.reduce((sum, part) => sum + (part.context?.bodyLines || 0), 0),
243
+ scopes: {
244
+ private: parts.reduce((sum, part) => sum + (part.context?.scopes?.private || 0), 0),
245
+ global: parts.reduce((sum, part) => sum + (part.context?.scopes?.global || 0), 0),
246
+ other: parts.reduce((sum, part) => sum + (part.context?.scopes?.other || 0), 0),
247
+ },
248
+ }
249
+ const chars = parts.reduce((sum, part) => sum + part.chars, 0)
250
+ const first = parts[0]
251
+ const firstNonSystem = parts.find((part) => part.role !== 'system')
252
+ // Conversation identity: the system prompt, the first non-system message and
253
+ // the model. A single mock instance normally serves one session, but two
254
+ // sessions can share a system prompt, so the first user message is part of
255
+ // the key that keeps their deltas apart.
256
+ const conversation = contentHash(
257
+ 'conversation:' + (body?.model || model || ''),
258
+ [first ? first.hash : 'no-system', firstNonSystem ? firstNonSystem.hash : 'no-user'].join(':'),
259
+ )
260
+ return {
261
+ model: typeof body?.model === 'string' && body.model ? body.model : model,
262
+ messages: rawMessages.length,
263
+ chars,
264
+ markers,
265
+ context,
266
+ parts,
267
+ conversation,
268
+ }
269
+ }
270
+
271
+ function splitReply(text) {
272
+ const chars = Array.from(String(text))
273
+ if (chars.length === 0) return []
274
+ // 24 frames is enough to exercise incremental delivery; larger replies grow
275
+ // the chunk size instead of the frame count.
276
+ const chunkSize = Math.max(8, Math.ceil(chars.length / 24))
277
+ const chunks = []
278
+ for (let i = 0; i < chars.length; i += chunkSize) chunks.push(chars.slice(i, i + chunkSize).join(''))
279
+ return chunks
280
+ }
281
+
282
+ function completionChunk({ id, created, model, delta, finishReason = null }) {
283
+ return {
284
+ id,
285
+ object: 'chat.completion.chunk',
286
+ created,
287
+ model,
288
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
289
+ }
290
+ }
291
+
292
+ function writeSse(res, payload) {
293
+ if (res.destroyed || res.writableEnded) return false
294
+ res.write('data: ' + JSON.stringify(payload) + '\n\n')
295
+ return true
296
+ }
297
+
298
+ function sendJson(res, status, value, extraHeaders = {}) {
299
+ if (res.destroyed || res.writableEnded) return
300
+ const body = JSON.stringify(value)
301
+ res.writeHead(status, {
302
+ 'content-type': 'application/json; charset=utf-8',
303
+ 'content-length': Buffer.byteLength(body),
304
+ 'cache-control': 'no-store',
305
+ 'x-mock-llm': 'evaluation-only',
306
+ ...extraHeaders,
307
+ })
308
+ res.end(body)
309
+ }
310
+
311
+ function sendError(res, status, message, code = 'invalid_request_error', extraHeaders = {}) {
312
+ sendJson(res, status, { error: { message, type: code, code } }, extraHeaders)
313
+ }
314
+
315
+ function readBody(req, limit = MAX_BODY_BYTES) {
316
+ return new Promise((resolve, reject) => {
317
+ const chunks = []
318
+ let size = 0
319
+ let settled = false
320
+ req.on('data', (chunk) => {
321
+ if (settled) return
322
+ size += chunk.length
323
+ if (size > limit) {
324
+ settled = true
325
+ const error = new Error('request body exceeds the mock limit')
326
+ error.status = 413
327
+ reject(error)
328
+ req.destroy()
329
+ return
330
+ }
331
+ chunks.push(chunk)
332
+ })
333
+ req.on('end', () => {
334
+ if (settled) return
335
+ settled = true
336
+ resolve(Buffer.concat(chunks))
337
+ })
338
+ req.on('error', (error) => {
339
+ if (settled) return
340
+ settled = true
341
+ reject(error)
342
+ })
343
+ req.on('aborted', () => {
344
+ if (settled) return
345
+ settled = true
346
+ const error = new Error('client aborted the request body')
347
+ error.status = 400
348
+ reject(error)
349
+ })
350
+ })
351
+ }
352
+
353
+ function appendJsonl(logPath, record) {
354
+ if (!logPath) return
355
+ fs.mkdirSync(path.dirname(path.resolve(logPath)), { recursive: true })
356
+ fs.appendFileSync(logPath, JSON.stringify(record) + '\n', 'utf8')
357
+ }
358
+
359
+ function nowIso() {
360
+ return new Date().toISOString()
361
+ }
362
+
363
+ /**
364
+ * Start one loopback-only mock server.
365
+ *
366
+ * @param {object} [options]
367
+ * @param {number} [options.port] TCP port; 0 asks the OS.
368
+ * @param {string} [options.model] Model id to advertise.
369
+ * @param {string} [options.reply] Plain-text assistant reply.
370
+ * @param {string|null} [options.log] JSONL path to append; null disables it.
371
+ * @returns {Promise<{url:string,port:number,model:string,log:string|null,server:http.Server,close:()=>Promise<void>}>}
372
+ */
373
+ export async function startMockLlm(options = {}) {
374
+ const requestedPort = Number.isInteger(options.port) ? options.port : 0
375
+ if (requestedPort < 0 || requestedPort > 65535) throw new Error('port must be 0..65535')
376
+ const model = typeof options.model === 'string' && options.model.trim() ? options.model.trim() : DEFAULT_MODEL
377
+ const reply = typeof options.reply === 'string' ? options.reply : DEFAULT_REPLY
378
+ const log = options.log ? path.resolve(options.log) : null
379
+ const state = { seq: 0 }
380
+
381
+ // port:0 时可能要重试一次以上——见 FETCH_BLOCKED_PORTS 的注释。
382
+ const attempts = requestedPort === 0 ? 8 : 1
383
+ for (let attempt = 1; ; attempt += 1) {
384
+ const server = http.createServer((req, res) => {
385
+ void handleRequest({ req, res, state, model, reply, log })
386
+ })
387
+ const actualPort = await listenOn(server, requestedPort)
388
+ // 显式指定的端口一律尊重(测试里要用它复现 EADDRINUSE);只有 OS 随机分配的
389
+ // 才需要躲开 fetch 连不上的那批端口。
390
+ if (requestedPort !== 0 || isFetchSafePort(actualPort)) {
391
+ return {
392
+ server,
393
+ port: actualPort,
394
+ url: `http://127.0.0.1:${actualPort}`,
395
+ model,
396
+ log,
397
+ close: () => closeServer(server),
398
+ }
399
+ }
400
+ await closeServer(server)
401
+ if (attempt >= attempts) {
402
+ throw Object.assign(new Error('could not allocate a fetch-safe mock port after ' + attempts + ' attempts'), { code: 'MOCK_LLM_PORT_UNAVAILABLE' })
403
+ }
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Fetch 会拒绝 bad-port 列表中的目标端口,与服务器是否监听无关。
409
+ * 自动分配和显式指定的端口都需要经过此检查,保证本地端点可由 fetch 访问。
410
+ */
411
+ const FETCH_BLOCKED_PORTS = new Set([
412
+ 0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,
413
+ 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139,
414
+ 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554,
415
+ 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190,
416
+ 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080,
417
+ ])
418
+
419
+ /** True when `fetch()` will accept this port (see the Fetch spec's bad-port list). */
420
+ export function isFetchSafePort(port) {
421
+ return Number.isInteger(port) && port > 0 && port <= 65535 && !FETCH_BLOCKED_PORTS.has(port)
422
+ }
423
+
424
+ function listenOn(server, port) {
425
+ return new Promise((resolve, reject) => {
426
+ const onError = (error) => reject(error)
427
+ server.once('error', onError)
428
+ server.listen(port, '127.0.0.1', () => {
429
+ server.off('error', onError)
430
+ const address = server.address()
431
+ resolve(typeof address === 'object' && address ? address.port : port)
432
+ })
433
+ })
434
+ }
435
+
436
+ function closeServer(server) {
437
+ return new Promise((resolve) => {
438
+ server.closeAllConnections?.()
439
+ server.close(() => resolve())
440
+ })
441
+ }
442
+
443
+ async function handleRequest({ req, res, state, model, reply, log }) {
444
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
445
+ const pathname = url.pathname
446
+
447
+ if (pathname === '/health') {
448
+ if (req.method !== 'GET') return sendError(res, 405, 'GET only', 'method_not_allowed', { allow: 'GET' })
449
+ return sendJson(res, 200, { ok: true, model, evaluationOnly: true })
450
+ }
451
+
452
+ if (pathname === '/v1/models' || pathname === '/models') {
453
+ if (req.method !== 'GET') return sendError(res, 405, 'GET only', 'method_not_allowed', { allow: 'GET' })
454
+ return sendJson(res, 200, {
455
+ object: 'list',
456
+ data: [{ id: model, object: 'model', created: 0, owned_by: 'dsh-mock-llm' }],
457
+ })
458
+ }
459
+
460
+ const knownChat = pathname === '/v1/chat/completions' || pathname === '/chat/completions'
461
+ if (!knownChat) return sendError(res, 404, 'not found: ' + pathname, 'not_found')
462
+ if (req.method !== 'POST') return sendError(res, 405, 'POST only', 'method_not_allowed', { allow: 'POST' })
463
+
464
+ let raw
465
+ try {
466
+ raw = await readBody(req)
467
+ } catch (error) {
468
+ if (!res.destroyed) sendError(res, error.status || 400, error.message)
469
+ return
470
+ }
471
+
472
+ let body
473
+ try {
474
+ body = JSON.parse(raw.toString('utf8'))
475
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('body must be a JSON object')
476
+ } catch (error) {
477
+ // Safe status: a bad body is the caller's error, never a partial reply.
478
+ sendError(res, 400, 'invalid JSON body: ' + error.message)
479
+ return
480
+ }
481
+
482
+ const analysis = analyzeRequestBody(body, model)
483
+ // Reserve the sequence before streaming: concurrent requests must not share
484
+ // an id or a JSONL seq even though the append happens at completion.
485
+ state.seq += 1
486
+ const seq = state.seq
487
+ const id = 'chatcmpl-mock-' + seq
488
+ const created = Math.floor(Date.now() / 1000)
489
+ const started = Date.now()
490
+ const aborted = { value: false }
491
+ const frames = { sent: 0 }
492
+ let status = 200
493
+
494
+ req.on('aborted', () => { aborted.value = true })
495
+ req.on('error', () => { aborted.value = true })
496
+ res.on('error', () => { aborted.value = true })
497
+ res.on('close', () => { if (!res.writableEnded) aborted.value = true })
498
+
499
+ const recordBase = {
500
+ v: LOG_VERSION,
501
+ event: 'request',
502
+ time: nowIso(),
503
+ seq,
504
+ model: analysis.model,
505
+ conversation: analysis.conversation,
506
+ messages: analysis.messages,
507
+ chars: analysis.chars,
508
+ markers: analysis.markers,
509
+ context: analysis.context,
510
+ parts: analysis.parts,
511
+ }
512
+
513
+ try {
514
+ if (body.stream === false) {
515
+ const completion = {
516
+ id,
517
+ object: 'chat.completion',
518
+ created,
519
+ model: analysis.model,
520
+ choices: [{
521
+ index: 0,
522
+ message: { role: 'assistant', content: reply },
523
+ finish_reason: 'stop',
524
+ }],
525
+ usage: {
526
+ prompt_tokens: 0,
527
+ completion_tokens: Array.from(reply).length,
528
+ total_tokens: Array.from(reply).length,
529
+ },
530
+ }
531
+ sendJson(res, 200, completion)
532
+ } else {
533
+ res.writeHead(200, {
534
+ 'content-type': 'text/event-stream; charset=utf-8',
535
+ 'cache-control': 'no-cache, no-transform',
536
+ connection: 'keep-alive',
537
+ 'x-accel-buffering': 'no',
538
+ 'x-mock-llm': 'evaluation-only',
539
+ })
540
+ const base = { id, created, model: analysis.model }
541
+ if (writeSse(res, completionChunk({ ...base, delta: { role: 'assistant', content: '' } }))) frames.sent += 1
542
+ for (const text of splitReply(reply)) {
543
+ if (aborted.value || res.destroyed) break
544
+ if (writeSse(res, completionChunk({ ...base, delta: { content: text } }))) frames.sent += 1
545
+ }
546
+ if (!aborted.value && !res.destroyed) {
547
+ // Explicit stop; no tool_calls are ever fabricated.
548
+ writeSse(res, completionChunk({ ...base, delta: {}, finishReason: 'stop' }))
549
+ frames.sent += 1
550
+ res.write('data: [DONE]\n\n')
551
+ res.end()
552
+ }
553
+ }
554
+ } catch (error) {
555
+ aborted.value = true
556
+ if (!res.headersSent) {
557
+ status = 500
558
+ sendError(res, 500, 'mock stream failed: ' + error.message, 'server_error')
559
+ } else {
560
+ res.destroy()
561
+ }
562
+ } finally {
563
+ try {
564
+ appendJsonl(log, {
565
+ ...recordBase,
566
+ reply: { mode: body.stream === false ? 'json' : 'sse', chars: Array.from(reply).length, frames: frames.sent },
567
+ status,
568
+ aborted: aborted.value,
569
+ durationMs: Date.now() - started,
570
+ })
571
+ } catch (error) {
572
+ console.error('mock-llm: failed to append JSONL: ' + error.message)
573
+ }
574
+ }
575
+ }
576
+
577
+ function isoTime(value) {
578
+ const date = new Date(value)
579
+ if (Number.isNaN(date.getTime())) return '—'
580
+ return date.toISOString().slice(11, 19) + 'Z'
581
+ }
582
+
583
+ function shortestId(value) {
584
+ const text = String(value || '?')
585
+ return text.length > 8 ? text.slice(0, 8) : text
586
+ }
587
+
588
+ function markersFromParts(parts) {
589
+ return sumMarkers(parts.map((part) => part.markers || {}))
590
+ }
591
+
592
+ function hasAnyMarker(markers) {
593
+ return MARKER_KEYS.some((key) => Number(markers?.[key] || 0) > 0)
594
+ }
595
+
596
+ /**
597
+ * Build the markdown report for one JSONL log.
598
+ *
599
+ * Per-request deltas are computed from the per-message hashes: the current
600
+ * request's messages are compared with the previous request of the same
601
+ * conversation as a multiset. When the message list is not a prefix of the new
602
+ * one (compaction, transcript rewrite), the round is marked `rebased` and is
603
+ * excluded from zero-injection attribution: the delta cannot be trusted.
604
+ *
605
+ * @param {string} jsonl raw log contents.
606
+ * @param {{logPath?:string}} [options]
607
+ * @returns {string} markdown
608
+ */
609
+ export function renderReport(jsonl, options = {}) {
610
+ const lines = String(jsonl || '').split(/\r?\n/).filter((line) => line.trim())
611
+ const records = []
612
+ let skipped = 0
613
+ for (const line of lines) {
614
+ let value
615
+ try { value = JSON.parse(line) } catch { skipped += 1; continue }
616
+ if (!value || typeof value !== 'object') { skipped += 1; continue }
617
+ if (value.event !== undefined && value.event !== 'request') continue
618
+ if (!value.markers || !Array.isArray(value.parts)) { skipped += 1; continue }
619
+ records.push(value)
620
+ }
621
+
622
+ const out = []
623
+ const conversationCount = new Set(records.map((record) => record.conversation || 'unknown')).size
624
+ out.push('# Mock LLM injection report')
625
+ out.push('')
626
+ out.push('> EVALUATION ONLY. Generated from request metadata (lengths, hashes, marker counts); no message body is stored in the log.')
627
+ out.push('')
628
+ if (options.logPath) out.push(`- log: \`${options.logPath}\``)
629
+ out.push(`- generated: ${new Date().toISOString().slice(0, 10)} (UTC)`)
630
+ out.push(`- requests: ${records.length}`)
631
+ out.push(`- conversations: ${conversationCount}`)
632
+ out.push(`- marker set: plugin ${MARKER_SET_VERSION} (${MARKER_KEYS.length} markers)`)
633
+ if (skipped) out.push(`- skipped/foreign JSONL lines: ${skipped}`)
634
+ if (records.length > 1 && conversationCount === records.length) {
635
+ out.push('- warning: every request has a different conversation fingerprint; the delta is not comparable (a changing system prompt, such as a timestamp, breaks the grouping).')
636
+ }
637
+ out.push('')
638
+ out.push('## Legend')
639
+ out.push('')
640
+ out.push('| col | marker | meaning |')
641
+ out.push('| --- | --- | --- |')
642
+ for (const item of MARKERS) out.push(`| ${item.column} | \`${item.marker}\` | ${item.meaning} |`)
643
+ out.push('')
644
+ out.push('`Δ` below counts markers in messages that are **new relative to the previous request of the same conversation**. `·` means zero. `—` in a `rebased` row means the transcript changed shape and the delta is not reliable.')
645
+ out.push('')
646
+
647
+ const states = []
648
+ let previousByConversation = new Map()
649
+ let round = 0
650
+ for (const record of records) {
651
+ round += 1
652
+ const conversation = record.conversation || 'unknown'
653
+ const parts = Array.isArray(record.parts) ? record.parts : []
654
+ const previous = previousByConversation.get(conversation) || null
655
+ let mode = 'first'
656
+ let newParts = parts
657
+ if (previous) {
658
+ const previousHashes = previous.map((part) => part.hash)
659
+ const currentHashes = parts.map((part) => part.hash)
660
+ const prefix = previousHashes.length <= currentHashes.length
661
+ && previousHashes.every((hash, index) => hash === currentHashes[index])
662
+ mode = prefix ? 'delta' : 'rebased'
663
+ if (mode === 'delta') {
664
+ const remaining = new Map()
665
+ for (const hash of previousHashes) remaining.set(hash, (remaining.get(hash) || 0) + 1)
666
+ newParts = []
667
+ for (const part of parts) {
668
+ const left = remaining.get(part.hash) || 0
669
+ if (left > 0) remaining.set(part.hash, left - 1)
670
+ else newParts.push(part)
671
+ }
672
+ }
673
+ }
674
+ previousByConversation.set(conversation, parts)
675
+ const delta = markersFromParts(newParts)
676
+ const unreliable = mode === 'rebased'
677
+ states.push({
678
+ round,
679
+ conversation,
680
+ record,
681
+ mode,
682
+ unreliable,
683
+ parts,
684
+ newParts,
685
+ delta,
686
+ zero: !unreliable && !hasAnyMarker(delta),
687
+ })
688
+ }
689
+
690
+ out.push('## Per-request marker matrix')
691
+ out.push('')
692
+ out.push('`#` is the log order (not the per-process `seq`).')
693
+ out.push('')
694
+ const header = ['#', 'conv', 'time', 'msgs', 'Δmsgs', ...MARKERS.map((item) => item.column), 'ctxIds']
695
+ out.push('| ' + header.join(' | ') + ' |')
696
+ out.push('| ' + header.map(() => '---').join(' | ') + ' |')
697
+ for (const state of states) {
698
+ const record = state.record
699
+ const cells = []
700
+ if (state.unreliable) {
701
+ for (let i = 0; i < MARKERS.length; i += 1) cells.push('—')
702
+ cells.push('—')
703
+ } else {
704
+ for (const item of MARKERS) cells.push(state.delta[item.key] ? String(state.delta[item.key]) : '·')
705
+ cells.push(state.mode === 'first' ? String(record.context?.ids || 0) : String(sumContextIds(state.newParts)))
706
+ }
707
+ const row = [
708
+ String(state.round),
709
+ shortestId(state.conversation),
710
+ isoTime(record.time),
711
+ String(record.messages ?? 0),
712
+ state.unreliable ? '—' : String(state.newParts.length),
713
+ ...cells,
714
+ ]
715
+ out.push('| ' + row.join(' | ') + ' |')
716
+ }
717
+ out.push('')
718
+
719
+ out.push('## Totals by block')
720
+ out.push('')
721
+ out.push('| col | marker | rounds with Δ>0 | Δ total | requests containing (sum, history included) |')
722
+ out.push('| --- | --- | --- | --- | --- |')
723
+ for (const item of MARKERS) {
724
+ let roundsWithDelta = 0
725
+ let deltaTotal = 0
726
+ let presentTotal = 0
727
+ for (const state of states) {
728
+ if (!state.unreliable && Number(state.delta[item.key] || 0) > 0) roundsWithDelta += 1
729
+ if (!state.unreliable) deltaTotal += Number(state.delta[item.key] || 0)
730
+ presentTotal += Number(state.record.markers?.[item.key] || 0)
731
+ }
732
+ out.push(`| ${item.column} | \`${item.marker}\` | ${roundsWithDelta} | ${deltaTotal} | ${presentTotal} |`)
733
+ }
734
+ out.push('')
735
+
736
+ const contextStates = states.filter((state) => !state.unreliable && (state.record.context?.blocks || 0) > 0)
737
+ out.push('## `<memory-context>` title cards')
738
+ out.push('')
739
+ if (contextStates.length === 0) {
740
+ out.push('None.')
741
+ } else {
742
+ out.push('| # | conv | blocks | private | global | ids | unique | card lines | body lines |')
743
+ out.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- |')
744
+ for (const state of contextStates) {
745
+ const context = state.record.context
746
+ out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${context.blocks || 0} | ${context.scopes?.private || 0} | ${context.scopes?.global || 0} | ${context.ids || 0} | ${context.uniqueIds || 0} | ${context.cardLines || 0} | ${context.bodyLines || 0} |`)
747
+ }
748
+ out.push('')
749
+ out.push('This table shows request totals (history included), not per-turn deltas. `body lines` counts indented continuation lines inside the block: 1.2.3 title cards should keep it at 0, and a positive number means body text reached the prompt.')
750
+ }
751
+ out.push('')
752
+
753
+ const zero = states.filter((state) => state.zero)
754
+ out.push('## Zero-injection requests')
755
+ out.push('')
756
+ out.push(`Count: **${zero.length}** of ${states.length} requests.`)
757
+ out.push('')
758
+ if (zero.length > 0) {
759
+ out.push('| # | conv | msgs | Δmsgs | hint |')
760
+ out.push('| --- | --- | --- | --- | --- |')
761
+ for (const state of zero) {
762
+ out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${state.record.messages ?? 0} | ${state.newParts.length} | ${zeroHint(state)} |`)
763
+ }
764
+ out.push('')
765
+ out.push('Attribution is limited to what the model request itself can prove. Unless a session log is reconciled separately (plan B.6), an unexplained row is a **data gap**, not "no memory was due".')
766
+ } else {
767
+ out.push('None.')
768
+ }
769
+ out.push('')
770
+
771
+ const rebased = states.filter((state) => state.unreliable)
772
+ if (rebased.length > 0) {
773
+ out.push('## Rebased requests (delta unavailable)')
774
+ out.push('')
775
+ out.push(`Count: **${rebased.length}** (transcript was not a prefix of the previous request: compaction or rewrite).`)
776
+ out.push('')
777
+ out.push('| # | conv | msgs |')
778
+ out.push('| --- | --- | --- |')
779
+ for (const state of rebased) out.push(`| ${state.round} | ${shortestId(state.conversation)} | ${state.record.messages ?? 0} |`)
780
+ out.push('')
781
+ }
782
+
783
+ out.push('## Notes')
784
+ out.push('')
785
+ out.push('- The log records request metadata only; it cannot name settings (`autoInject`, `dedupeTurns`, budgets). Record that snapshot beside the run (plan B.4).')
786
+ out.push('- `requests containing (sum)` double-counts blocks that stayed in the transcript; use `Δ total` for per-turn injection counts.')
787
+ out.push('- A separate model call (title generation, summarization) gets its own `conv` fingerprint; filter those rows before reading a conversation\'s injection rate.')
788
+ out.push('- Do not commit captured logs or this report when they came from a real conversation.')
789
+ out.push('')
790
+ return out.join('\n')
791
+ }
792
+
793
+ function sumContextIds(parts) {
794
+ return parts.reduce((sum, part) => sum + Number(part.context?.ids || 0), 0)
795
+ }
796
+
797
+ function zeroHint(state) {
798
+ if (state.unreliable) return 'rebased: delta unreliable (data gap)'
799
+ if (state.newParts.length === 0) return 'no new message (retry or intra-turn step)'
800
+ if (!state.newParts.some((part) => part.role === 'system' || part.role === 'user')) return 'new messages carry no user/system text'
801
+ const all = state.record.markers || {}
802
+ const delta = state.delta || {}
803
+ // These are hints read from the request itself, not causes: the mock cannot
804
+ // see settings, dedupe state or the plugin activity log.
805
+ if (!all.guide && !all.anchor) return 'no guide/anchor anywhere in the request: injection may be off, unbound, or compacted away (data gap)'
806
+ if (all.context && !delta.context) return 'history has a recall block but no new one: possible no-match, dedupe, budget or tooShort (needs session log)'
807
+ if (all.anchor && !delta.anchor && !delta.guide) return 'anchor already delivered and no new block: possible anchor-only step, no-match or budget (needs session log)'
808
+ return 'data gap: no pinned marker in new messages'
809
+ }
810
+
811
+ function parseArgs(argv) {
812
+ const options = {
813
+ port: 8123,
814
+ model: DEFAULT_MODEL,
815
+ replyFile: null,
816
+ log: null,
817
+ report: null,
818
+ help: false,
819
+ }
820
+ const take = (index, name) => {
821
+ const value = argv[index]
822
+ if (value === undefined || value.startsWith('--')) throw new Error(name + ' requires a value')
823
+ return value
824
+ }
825
+ for (let i = 0; i < argv.length; i += 1) {
826
+ const token = argv[i]
827
+ const eq = token.indexOf('=')
828
+ const name = eq === -1 ? token : token.slice(0, eq)
829
+ const inline = eq === -1 ? null : token.slice(eq + 1)
830
+ switch (name) {
831
+ case '-h':
832
+ case '--help':
833
+ options.help = true
834
+ break
835
+ case '--port': {
836
+ const value = inline ?? take(++i, '--port')
837
+ const port = Number(value)
838
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('--port must be an integer 0..65535')
839
+ options.port = port
840
+ break
841
+ }
842
+ case '--model':
843
+ options.model = inline ?? take(++i, '--model')
844
+ break
845
+ case '--reply-file':
846
+ options.replyFile = inline ?? take(++i, '--reply-file')
847
+ break
848
+ case '--log':
849
+ options.log = inline ?? take(++i, '--log')
850
+ break
851
+ case '--report':
852
+ if (inline !== null) options.report = inline
853
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) options.report = argv[++i]
854
+ else options.report = true
855
+ break
856
+ default:
857
+ throw new Error('unknown option: ' + token)
858
+ }
859
+ }
860
+ return options
861
+ }
862
+
863
+ async function main(argv = process.argv.slice(2)) {
864
+ let options
865
+ try {
866
+ options = parseArgs(argv)
867
+ } catch (error) {
868
+ console.error('mock-llm: ' + error.message + '\n')
869
+ console.error(USAGE)
870
+ return 2
871
+ }
872
+ if (options.help) {
873
+ process.stdout.write(USAGE)
874
+ return 0
875
+ }
876
+ if (options.report !== null) {
877
+ const reportPath = options.report === true ? options.log : options.report
878
+ if (!reportPath) {
879
+ console.error('mock-llm: --report needs a path (or pass --log with the same run)')
880
+ return 2
881
+ }
882
+ let raw
883
+ try {
884
+ raw = fs.readFileSync(reportPath, 'utf8')
885
+ } catch (error) {
886
+ console.error('mock-llm: cannot read log ' + reportPath + ': ' + error.message)
887
+ return 1
888
+ }
889
+ process.stdout.write(renderReport(raw, { logPath: path.resolve(reportPath) }))
890
+ return 0
891
+ }
892
+
893
+ let reply = DEFAULT_REPLY
894
+ if (options.replyFile) {
895
+ try {
896
+ reply = fs.readFileSync(options.replyFile, 'utf8')
897
+ } catch (error) {
898
+ console.error('mock-llm: cannot read --reply-file: ' + error.message)
899
+ return 1
900
+ }
901
+ }
902
+
903
+ let instance
904
+ try {
905
+ instance = await startMockLlm({ port: options.port, model: options.model, reply, log: options.log })
906
+ } catch (error) {
907
+ if (error?.code === 'EADDRINUSE') {
908
+ console.error(`mock-llm: port ${options.port} is already in use; pick another --port or use --port 0`)
909
+ return 1
910
+ }
911
+ console.error('mock-llm: failed to listen: ' + (error?.message || error))
912
+ return 1
913
+ }
914
+ console.log('mock-llm (EVALUATION ONLY) listening on ' + instance.url)
915
+ console.log(' POST ' + instance.url + '/v1/chat/completions')
916
+ console.log(' GET ' + instance.url + '/v1/models')
917
+ if (instance.log) console.log(' JSONL log: ' + instance.log)
918
+ else console.log(' JSONL log: disabled (pass --log <path> to record)')
919
+ console.log(' No message bodies are stored. Do not expose this port; it is loopback-only and unauthenticated.')
920
+
921
+ await new Promise((resolve) => {
922
+ const stop = () => resolve()
923
+ process.once('SIGINT', stop)
924
+ process.once('SIGTERM', stop)
925
+ })
926
+ await instance.close()
927
+ return 0
928
+ }
929
+
930
+ const invokedDirectly = process.argv[1]
931
+ ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
932
+ : false
933
+ if (invokedDirectly) {
934
+ main().then((code) => { process.exitCode = code }).catch((error) => {
935
+ console.error('mock-llm: ' + (error?.stack || error))
936
+ process.exitCode = 1
937
+ })
938
+ }