dsh-memu-memory 1.4.2 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
package/scripts/mock-llm.mjs
CHANGED
|
@@ -1,903 +1,938 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* EVALUATION ONLY — local fake OpenAI-compatible endpoint for
|
|
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
|
|
375
|
-
if (
|
|
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
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
server
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
out.push('##
|
|
720
|
-
out.push('')
|
|
721
|
-
out.push(
|
|
722
|
-
out.push('')
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
out.push(
|
|
733
|
-
}
|
|
734
|
-
out.push('')
|
|
735
|
-
|
|
736
|
-
const
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
out.push(
|
|
741
|
-
|
|
742
|
-
out.push('| # | conv |
|
|
743
|
-
out.push('| --- | --- | --- |')
|
|
744
|
-
for (const state of
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
out.push('
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
out.push('')
|
|
755
|
-
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
if (
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
process.
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
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
|
+
}
|