@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1237 @@
|
|
|
1
|
+
// 热截断 / hot truncate — cut-only compaction, no model call.
|
|
2
|
+
//
|
|
3
|
+
// The host's compaction seam (`ctx.compaction`) is a service whose implementation
|
|
4
|
+
// decides *when* to compact and *how* a history span becomes one replacement
|
|
5
|
+
// node. This module is the policy-free core of a backend that only ever CUTS:
|
|
6
|
+
//
|
|
7
|
+
// * a cut is a prefix of the current surface made of whole, already completed
|
|
8
|
+
// turns older than the retention window (retainTurns / retainTokens);
|
|
9
|
+
// * the original events are copied to a JSONL archive under
|
|
10
|
+
// <memoryRoot>/.longlive/hot-truncate/ before the surface is touched;
|
|
11
|
+
// * the replacement is one coverage-pointer user message (compact-checkpoint
|
|
12
|
+
// provenance) and a normal compaction/start → summary → end lifecycle;
|
|
13
|
+
// * no LLM is called and no event data is rewritten — only a surface replace
|
|
14
|
+
// is appended, exactly like stock compaction.
|
|
15
|
+
//
|
|
16
|
+
// Everything in this file is host-free and testable with a mock Session/meter.
|
|
17
|
+
// `cut-engine.js` binds it to the real `@deepseek-ai/dsh-compaction` classes.
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
22
|
+
import { memoryRootFromConfig } from '../memory/paths.js';
|
|
23
|
+
import { appendHotTruncateDiag, hotTruncateDiagOptions } from '../hot-truncate-diag.js';
|
|
24
|
+
|
|
25
|
+
/** Provider name recorded on every summary event this engine writes. */
|
|
26
|
+
export const PROVIDER = 'hot-truncate';
|
|
27
|
+
/** Model marker for "no model was called". */
|
|
28
|
+
export const MODEL = 'cut-only';
|
|
29
|
+
/** Archive schema version written in the JSONL header. */
|
|
30
|
+
export const ARCHIVE_SCHEMA = 1;
|
|
31
|
+
/** Subdirectory of the memory root that holds hot-truncate archives. */
|
|
32
|
+
export const ARCHIVE_SUBDIR = path.join('.longlive', 'hot-truncate');
|
|
33
|
+
|
|
34
|
+
export const MODES = Object.freeze(['off', 'cut', 'auto']);
|
|
35
|
+
|
|
36
|
+
export const DEFAULT_OPTIONS = Object.freeze({
|
|
37
|
+
mode: 'cut',
|
|
38
|
+
// Every cut rewrites the context prefix, which invalidates the model's
|
|
39
|
+
// prefix cache: the next turn re-bills the remaining context at full price.
|
|
40
|
+
// A 30k trigger cut once per turn; 300k keeps the cut about every dozen
|
|
41
|
+
// turns, which is the point of this default. Keep 4 completed turns so the
|
|
42
|
+
// model still has the immediately preceding conversation.
|
|
43
|
+
retainTurns: 4,
|
|
44
|
+
retainTokens: 8000,
|
|
45
|
+
minCutTokens: 0,
|
|
46
|
+
autoMinTokens: 350000,
|
|
47
|
+
archiveDir: '',
|
|
48
|
+
memoryRoot: '',
|
|
49
|
+
memRoot: '',
|
|
50
|
+
home: '',
|
|
51
|
+
stock: null,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
function isPlainObject(value) {
|
|
55
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function positiveInteger(value, name, minimum = 0) {
|
|
59
|
+
if (!Number.isInteger(value) || value < minimum) {
|
|
60
|
+
throw new Error(`hot-truncate: ${name} must be an integer >= ${minimum}, got ${JSON.stringify(value)}`);
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function textOrEmpty(value) {
|
|
66
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Normalize the plugin row config. Both `{ hotTruncate: {...} }` and the flat
|
|
71
|
+
* object are accepted so a bundle patch can keep the row text short and an
|
|
72
|
+
* existing profile can move the settings later without a rewrite.
|
|
73
|
+
*
|
|
74
|
+
* Unknown keys are ignored on purpose: this row lives beside the longlive
|
|
75
|
+
* plugin's much larger config, and refusing unknown keys would make a bundle
|
|
76
|
+
* overlay fail the whole plugin.
|
|
77
|
+
*/
|
|
78
|
+
export function normalizeOptions(raw = {}) {
|
|
79
|
+
const source = isPlainObject(raw?.hotTruncate) ? raw.hotTruncate : (isPlainObject(raw) ? raw : {});
|
|
80
|
+
const mode = source.mode === undefined ? DEFAULT_OPTIONS.mode : String(source.mode).toLowerCase();
|
|
81
|
+
if (!MODES.includes(mode)) throw new Error(`hot-truncate: mode must be one of ${MODES.join('|')}, got ${JSON.stringify(source.mode)}`);
|
|
82
|
+
return Object.freeze({
|
|
83
|
+
mode,
|
|
84
|
+
retainTurns: positiveInteger(source.retainTurns ?? DEFAULT_OPTIONS.retainTurns, 'retainTurns', 0),
|
|
85
|
+
retainTokens: positiveInteger(source.retainTokens ?? DEFAULT_OPTIONS.retainTokens, 'retainTokens', 0),
|
|
86
|
+
minCutTokens: positiveInteger(source.minCutTokens ?? DEFAULT_OPTIONS.minCutTokens, 'minCutTokens', 0),
|
|
87
|
+
autoMinTokens: positiveInteger(source.autoMinTokens ?? DEFAULT_OPTIONS.autoMinTokens, 'autoMinTokens', 0),
|
|
88
|
+
archiveDir: textOrEmpty(source.archiveDir),
|
|
89
|
+
memoryRoot: textOrEmpty(source.memoryRoot),
|
|
90
|
+
memRoot: textOrEmpty(source.memRoot),
|
|
91
|
+
home: textOrEmpty(source.home),
|
|
92
|
+
strictMemoryRoot: source.strictMemoryRoot === true,
|
|
93
|
+
stock: isPlainObject(source.stock) ? Object.freeze({ ...source.stock }) : null,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Keys the stock `BasicCompactionEngine` accepts; the fallback filters to them. */
|
|
98
|
+
const STOCK_KEYS = Object.freeze([
|
|
99
|
+
'thresholdRatio', 'retainRatio', 'retainTokens', 'summarizationProvider',
|
|
100
|
+
'summarizationModel', 'maxTokens', 'compactionRetries', 'maxOverflowRetries',
|
|
101
|
+
'modelPolicies', 'auto',
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
/** A stock-compatible view of this row's config, for the fallback path. */
|
|
105
|
+
export function stockConfig(raw = {}) {
|
|
106
|
+
const source = isPlainObject(raw?.hotTruncate) ? raw.hotTruncate : (isPlainObject(raw) ? raw : {});
|
|
107
|
+
const explicit = isPlainObject(source.stock) ? source.stock : {};
|
|
108
|
+
const out = {};
|
|
109
|
+
for (const key of STOCK_KEYS) {
|
|
110
|
+
if (explicit[key] !== undefined) out[key] = explicit[key];
|
|
111
|
+
else if (source[key] !== undefined && !['mode', 'archiveDir', 'memoryRoot', 'memRoot', 'home', 'stock'].includes(key)) out[key] = source[key];
|
|
112
|
+
}
|
|
113
|
+
// BasicCompactionEngine defaults `auto` to true; keep automatic stock
|
|
114
|
+
// compaction alive when hot truncate is disabled or falls back.
|
|
115
|
+
if (out.auto === undefined) out.auto = true;
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Resolve the archive directory. An explicit `archiveDir` (tests, forensic
|
|
121
|
+
* runs) wins; otherwise the memory-root chain used by every longlive feature:
|
|
122
|
+
* memoryRoot → memRoot → $DSH_LONGLIVE_MEMORY_ROOT → $DSH_MEM →
|
|
123
|
+
* <DSH home>/longlive-memory.
|
|
124
|
+
*
|
|
125
|
+
* `memoryRootFromConfig` keeps its contract: an explicitly configured but
|
|
126
|
+
* missing root throws instead of silently growing a second store. The derived
|
|
127
|
+
* default is created on demand.
|
|
128
|
+
*/
|
|
129
|
+
export function resolveArchiveDir(options, env = process.env) {
|
|
130
|
+
const explicit = textOrEmpty(options?.archiveDir);
|
|
131
|
+
if (explicit) {
|
|
132
|
+
const dir = path.resolve(explicit);
|
|
133
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
134
|
+
return dir;
|
|
135
|
+
}
|
|
136
|
+
const config = {
|
|
137
|
+
memoryRoot: options?.memoryRoot ?? '',
|
|
138
|
+
memRoot: options?.memRoot ?? '',
|
|
139
|
+
home: options?.home ?? '',
|
|
140
|
+
strictMemoryRoot: options?.strictMemoryRoot === true,
|
|
141
|
+
};
|
|
142
|
+
const root = memoryRootFromConfig(config, env);
|
|
143
|
+
const dir = path.join(root, ARCHIVE_SUBDIR);
|
|
144
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
145
|
+
return dir;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
// Turn facts
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
/** A user message that replaced a prior surface range (any compaction backend). */
|
|
153
|
+
export function isCheckpointEvent(event, isCompactCheckpointSource) {
|
|
154
|
+
if (!event || event.type !== 'user/message') return false;
|
|
155
|
+
const source = event.data?.source;
|
|
156
|
+
if (!isPlainObject(source)) return false;
|
|
157
|
+
if (typeof isCompactCheckpointSource === 'function') {
|
|
158
|
+
try {
|
|
159
|
+
if (isCompactCheckpointSource(source)) return true;
|
|
160
|
+
} catch {
|
|
161
|
+
// Fall through to the structural checks.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (source.kind === 'spine-checkpoint') return true;
|
|
165
|
+
return source.kind === 'plugin' && source.plugin === 'compact';
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Read this session's immutable event snapshot through the host API.
|
|
170
|
+
*
|
|
171
|
+
* Host 0.2.2-rc.1's `Session` is an event-sourced object with a private `log`;
|
|
172
|
+
* its public reads are `snapshotEvents(fromSeq, toSeqExclusive)` and
|
|
173
|
+
* `eventAt(seq)`. There is no `events` property (reading one yields
|
|
174
|
+
* `undefined`), which is why the first cut silently planned against an empty
|
|
175
|
+
* table. Keep the array fallbacks only for old mocks/tests: the production
|
|
176
|
+
* path is always `snapshotEvents()`.
|
|
177
|
+
*/
|
|
178
|
+
export function sessionEvents(session) {
|
|
179
|
+
if (typeof session?.snapshotEvents === 'function') {
|
|
180
|
+
const events = session.snapshotEvents();
|
|
181
|
+
if (Array.isArray(events)) return events;
|
|
182
|
+
}
|
|
183
|
+
if (Array.isArray(session?.log)) return session.log;
|
|
184
|
+
if (Array.isArray(session?.events)) return session.events;
|
|
185
|
+
return [];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Build the turn lookup tables in one pass over the immutable event log. */
|
|
189
|
+
export function turnTable(session) {
|
|
190
|
+
const events = sessionEvents(session);
|
|
191
|
+
const bySeq = new Map();
|
|
192
|
+
const turnOfSeq = new Map();
|
|
193
|
+
const turns = [];
|
|
194
|
+
const byNumber = new Map();
|
|
195
|
+
let open = null;
|
|
196
|
+
for (const event of events) {
|
|
197
|
+
if (event === null || typeof event !== 'object' || typeof event.seq !== 'number') continue;
|
|
198
|
+
bySeq.set(event.seq, event);
|
|
199
|
+
if (event.type === 'turn/start') {
|
|
200
|
+
open = {
|
|
201
|
+
turn: event.data?.turn,
|
|
202
|
+
startSeq: event.seq,
|
|
203
|
+
endSeq: null,
|
|
204
|
+
completed: false,
|
|
205
|
+
reason: null,
|
|
206
|
+
};
|
|
207
|
+
turns.push(open);
|
|
208
|
+
byNumber.set(open.turn, open);
|
|
209
|
+
}
|
|
210
|
+
if (open !== null) turnOfSeq.set(event.seq, open.turn);
|
|
211
|
+
if (event.type === 'turn/end') {
|
|
212
|
+
const target = byNumber.get(event.data?.turn) ?? open;
|
|
213
|
+
if (target !== null && target !== undefined && target.endSeq === null) {
|
|
214
|
+
target.endSeq = event.seq;
|
|
215
|
+
target.reason = event.data?.reason?.kind ?? null;
|
|
216
|
+
target.completed = target.reason === 'completed';
|
|
217
|
+
}
|
|
218
|
+
open = null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { events, bySeq, turnOfSeq, turns, byNumber, totalTurns: turns.length };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The currently open turn number, or null when the log ends between turns. */
|
|
225
|
+
export function findOpenTurn(events) {
|
|
226
|
+
let open = null;
|
|
227
|
+
for (const event of events ?? []) {
|
|
228
|
+
if (event?.type === 'turn/start') open = event.data?.turn ?? null;
|
|
229
|
+
else if (event?.type === 'turn/end' && open === event.data?.turn) open = null;
|
|
230
|
+
}
|
|
231
|
+
return open;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Reject an append while an unmatched compaction/start exists, except when a
|
|
236
|
+
* later constructor-seed boundary proves that start belongs to an earlier
|
|
237
|
+
* lifecycle (the stock seam's rule).
|
|
238
|
+
*/
|
|
239
|
+
export function activeCompactionStart(events) {
|
|
240
|
+
let start = null;
|
|
241
|
+
let end = null;
|
|
242
|
+
let seed = null;
|
|
243
|
+
for (const event of events ?? []) {
|
|
244
|
+
if (event?.type === 'session/end-seed') seed = event.seq;
|
|
245
|
+
else if (event?.type === 'compaction/start') start = event;
|
|
246
|
+
else if (event?.type === 'compaction/end') end = event;
|
|
247
|
+
}
|
|
248
|
+
if (start === null) return null;
|
|
249
|
+
if (end !== null && end.seq > start.seq) return null;
|
|
250
|
+
if (seed !== null && seed > start.seq) return null;
|
|
251
|
+
return start;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
// Surface grouping and selection
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
function eventTokens(event, tokens) {
|
|
259
|
+
const priced = tokens?.get(event?.seq);
|
|
260
|
+
if (Number.isFinite(priced)) return priced;
|
|
261
|
+
// Only used when the host token meter is unavailable. A conservative byte
|
|
262
|
+
// estimate keeps the retention window from silently shrinking.
|
|
263
|
+
try {
|
|
264
|
+
const raw = event?.data?.message ?? event?.data ?? null;
|
|
265
|
+
return Math.max(1, Math.ceil(String(JSON.stringify(raw) ?? '').length / 3));
|
|
266
|
+
} catch {
|
|
267
|
+
return 1;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Group the current surface into positional runs: completed/aborted turn
|
|
273
|
+
* groups in surface order, with checkpoint replacements kept as their own
|
|
274
|
+
* `checkpoint` groups so they never masquerade as a turn.
|
|
275
|
+
*/
|
|
276
|
+
export function surfaceGroups(session, table, isCheckpointSource) {
|
|
277
|
+
const nodes = session?.surface?.nodes ?? [];
|
|
278
|
+
const groups = [];
|
|
279
|
+
let current = null;
|
|
280
|
+
for (const seq of nodes) {
|
|
281
|
+
const event = table.bySeq.get(seq);
|
|
282
|
+
if (event === undefined) throw new Error(`hot-truncate: surface seq ${seq} has no session event`);
|
|
283
|
+
if (isCheckpointEvent(event, isCheckpointSource)) {
|
|
284
|
+
if (current !== null && current.kind === 'checkpoint') {
|
|
285
|
+
current.seqs.push(seq);
|
|
286
|
+
} else {
|
|
287
|
+
current = { kind: 'checkpoint', turn: null, seqs: [seq], completed: false, known: true };
|
|
288
|
+
groups.push(current);
|
|
289
|
+
}
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const turn = table.turnOfSeq.get(seq);
|
|
293
|
+
const info = turn === undefined ? undefined : table.byNumber.get(turn);
|
|
294
|
+
const turnNumber = info === undefined ? 0 : turn;
|
|
295
|
+
if (current === null || current.kind !== 'turn' || current.turn !== turnNumber) {
|
|
296
|
+
current = {
|
|
297
|
+
kind: 'turn',
|
|
298
|
+
turn: turnNumber,
|
|
299
|
+
seqs: [],
|
|
300
|
+
completed: info?.completed === true,
|
|
301
|
+
known: info !== undefined,
|
|
302
|
+
};
|
|
303
|
+
groups.push(current);
|
|
304
|
+
}
|
|
305
|
+
current.seqs.push(seq);
|
|
306
|
+
}
|
|
307
|
+
return groups;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function groupTokens(group, prices) {
|
|
311
|
+
let total = 0;
|
|
312
|
+
for (const seq of group.seqs) total += prices.get(seq);
|
|
313
|
+
return total;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Turns already archived by an earlier hot-truncate cut.
|
|
318
|
+
*
|
|
319
|
+
* The count is carried on the pointer's source (`hotTruncate.archivedTurns`)
|
|
320
|
+
* instead of being re-derived from summary.shadowedSeqs: a summary span also
|
|
321
|
+
* contains the old pointer node, whose seq maps to the turn that was OPEN when
|
|
322
|
+
* that pointer was written — counting it would inflate M on every later cut.
|
|
323
|
+
*
|
|
324
|
+
* Scan the whole log, not only the live surface: a later stock compaction (or
|
|
325
|
+
* a manual rollback to stock) can shadow our pointer, and the carried count
|
|
326
|
+
* must survive that.
|
|
327
|
+
*/
|
|
328
|
+
export function archivedTurnsBefore(table) {
|
|
329
|
+
let best = 0;
|
|
330
|
+
for (const event of table.events) {
|
|
331
|
+
if (event?.type !== 'user/message') continue;
|
|
332
|
+
const carried = event.data?.source?.hotTruncate?.archivedTurns;
|
|
333
|
+
if (Number.isInteger(carried) && carried > best) best = carried;
|
|
334
|
+
}
|
|
335
|
+
return best;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Text-only token estimate used before the real message exists. */
|
|
339
|
+
function roughPointerTokens(text) {
|
|
340
|
+
// CJK text is roughly one token per character; English paths are cheaper.
|
|
341
|
+
// Overestimating a little is the safe direction (it can only skip a tiny cut).
|
|
342
|
+
return Math.ceil(text.length / 1.8) + 24;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Select the oldest whole closed turns that sit outside the retention window.
|
|
347
|
+
* Returns null when no safe cut exists; every such refusal reports a structured
|
|
348
|
+
* reason through `helpers.onNoPlan` so a silently disabled hot truncate is
|
|
349
|
+
* observable (the engine logs it once per reason).
|
|
350
|
+
*
|
|
351
|
+
* The leading run of `system/message` / `developer/message` nodes (the real
|
|
352
|
+
* system prompt at host-protected position 0) is never moved. A `system/message`
|
|
353
|
+
* re-injected by a host restart further inside the surface is an archived copy
|
|
354
|
+
* of that same prompt (host-tolerated inside a replacement range). Checkpoint
|
|
355
|
+
* nodes at the head of the span are folded into the same cut, which keeps
|
|
356
|
+
* exactly one pointer.
|
|
357
|
+
*/
|
|
358
|
+
export function selectCutPlan(session, options, measurement, helpers = {}) {
|
|
359
|
+
const table = helpers.table ?? turnTable(session);
|
|
360
|
+
const groups = surfaceGroups(session, table, helpers.isCheckpointSource);
|
|
361
|
+
const onNoPlan = typeof helpers.onNoPlan === 'function' ? helpers.onNoPlan : null;
|
|
362
|
+
const noPlan = (reason, detail) => {
|
|
363
|
+
try {
|
|
364
|
+
onNoPlan?.({ reason, detail: detail === undefined ? null : detail });
|
|
365
|
+
} catch {
|
|
366
|
+
// Diagnostics never break a plan.
|
|
367
|
+
}
|
|
368
|
+
return null;
|
|
369
|
+
};
|
|
370
|
+
if (groups.length === 0) return noPlan('no-groups');
|
|
371
|
+
const tokens = new Map();
|
|
372
|
+
for (const node of measurement?.nodes ?? []) {
|
|
373
|
+
if (node && typeof node.seq === 'number' && Number.isFinite(node.tokens)) tokens.set(node.seq, node.tokens);
|
|
374
|
+
}
|
|
375
|
+
const prices = {
|
|
376
|
+
get(seq) {
|
|
377
|
+
const price = tokens.get(seq);
|
|
378
|
+
if (Number.isFinite(price)) return price;
|
|
379
|
+
return eventTokens(table.bySeq.get(seq), tokens);
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
// Walk backwards until the retained suffix satisfies BOTH limits. A turn
|
|
384
|
+
// that is not completed counts toward the token budget but never toward the
|
|
385
|
+
// completed-turn floor, so the retained suffix may temporarily hold a few
|
|
386
|
+
// extra turns while a closed aborted turn sits inside the window.
|
|
387
|
+
let keptTurns = 0;
|
|
388
|
+
let keptTokens = 0;
|
|
389
|
+
let boundary = -1;
|
|
390
|
+
for (let index = groups.length - 1; index >= 0; index -= 1) {
|
|
391
|
+
const group = groups[index];
|
|
392
|
+
keptTokens += groupTokens(group, prices);
|
|
393
|
+
if (group.kind === 'turn' && group.completed) keptTurns += 1;
|
|
394
|
+
if (group.kind === 'turn' && group.completed
|
|
395
|
+
&& keptTurns >= options.retainTurns && keptTokens >= options.retainTokens) {
|
|
396
|
+
boundary = index;
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (boundary <= 0) return noPlan('not-enough-turns', { groups: groups.length });
|
|
401
|
+
|
|
402
|
+
const surfaceNodes = session?.surface?.nodes ?? [];
|
|
403
|
+
if (surfaceNodes.length === 0) return noPlan('no-surface');
|
|
404
|
+
|
|
405
|
+
// 2026-11-06 1.6.7 hardening — no permanent barrier, no silent zero progress.
|
|
406
|
+
//
|
|
407
|
+
// 1.6.6 removed the aborted-turn freeze but treated every group without a
|
|
408
|
+
// usable turn record as an immovable open group and stopped the span before
|
|
409
|
+
// it. Three surface shapes then made the planner return null forever even
|
|
410
|
+
// though whole closed turns older than the retention window existed:
|
|
411
|
+
// * a log truncated mid-turn leaves orphan messages at the surface head
|
|
412
|
+
// (no turn/start) — a turn===0 group at the head (red team E1);
|
|
413
|
+
// * the host appends a user/message between turns — a turn===0 group in
|
|
414
|
+
// the middle (red team E3);
|
|
415
|
+
// * a turn whose turn/end was lost by log truncation — turn N has no
|
|
416
|
+
// endSeq but later turns exist (red team E2).
|
|
417
|
+
//
|
|
418
|
+
// Rules now:
|
|
419
|
+
// * the whole LEADING run of system/message + developer/message nodes is
|
|
420
|
+
// never moved (head instructions; host-protected position 0);
|
|
421
|
+
// * a turn===0 group that carries a system/developer node is a head
|
|
422
|
+
// instruction zone and stays in place; a turn===0 group of plain messages
|
|
423
|
+
// is an orphan prefix and is archived with the cut (recoverable);
|
|
424
|
+
// * a group whose turn has no turn/end is the CURRENT turn only when it is
|
|
425
|
+
// the last started turn; an earlier turn without turn/end is abandoned
|
|
426
|
+
// (the log was truncated inside it) and is cuttable, archived through an
|
|
427
|
+
// inferred range up to the next turn/start;
|
|
428
|
+
// * the planner skips a blocked head barrier and cuts the next run of
|
|
429
|
+
// wholly-cuttable groups; if nothing is cuttable it reports the reason
|
|
430
|
+
// through onNoPlan instead of returning null silently.
|
|
431
|
+
const groupStart = new Array(groups.length);
|
|
432
|
+
const groupEnd = new Array(groups.length);
|
|
433
|
+
const groupOfPosition = new Array(surfaceNodes.length);
|
|
434
|
+
{
|
|
435
|
+
let cursor = 0;
|
|
436
|
+
for (let index = 0; index < groups.length; index += 1) {
|
|
437
|
+
groupStart[index] = cursor;
|
|
438
|
+
for (let offset = 0; offset < groups[index].seqs.length; offset += 1) groupOfPosition[cursor++] = index;
|
|
439
|
+
groupEnd[index] = cursor - 1;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const typeOfSeq = (seq) => table.bySeq.get(seq)?.type;
|
|
443
|
+
const isInstructionSeq = (seq) => typeOfSeq(seq) === 'system/message' || typeOfSeq(seq) === 'developer/message';
|
|
444
|
+
const protectedSeqs = new Set();
|
|
445
|
+
{
|
|
446
|
+
let position = 0;
|
|
447
|
+
while (position < surfaceNodes.length && isInstructionSeq(surfaceNodes[position])) {
|
|
448
|
+
protectedSeqs.add(surfaceNodes[position]);
|
|
449
|
+
position += 1;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const lastStarted = table.turns.length > 0 ? table.turns[table.turns.length - 1] : null;
|
|
453
|
+
const turnInfoOf = (group) => (group.kind === 'turn' && group.turn !== 0 ? table.byNumber.get(group.turn) : undefined);
|
|
454
|
+
const isCurrentTurnGroup = (group) => {
|
|
455
|
+
if (group.kind !== 'turn' || group.turn === 0) return false;
|
|
456
|
+
const info = table.byNumber.get(group.turn);
|
|
457
|
+
if (info === undefined) return true;
|
|
458
|
+
return info.endSeq === null && lastStarted !== null && info.turn === lastStarted.turn;
|
|
459
|
+
};
|
|
460
|
+
const isCuttableGroup = (group) => {
|
|
461
|
+
if (group === undefined) return false;
|
|
462
|
+
if (group.kind === 'checkpoint') return true;
|
|
463
|
+
if (group.kind !== 'turn') return false;
|
|
464
|
+
// A turn===0 group is either an orphan head zone (contains instructions) or
|
|
465
|
+
// a stray message block between turns; only the latter may be archived.
|
|
466
|
+
if (group.turn === 0) return !group.seqs.some((seq) => isInstructionSeq(seq));
|
|
467
|
+
const info = table.byNumber.get(group.turn);
|
|
468
|
+
if (info === undefined) return false;
|
|
469
|
+
return !isCurrentTurnGroup(group);
|
|
470
|
+
};
|
|
471
|
+
// An abandoned turn (no turn/end, but a later turn/start exists) never got a
|
|
472
|
+
// closing event; the archive range is inferred up to the next turn/start so
|
|
473
|
+
// every one of its original events stays recoverable.
|
|
474
|
+
const resolvedEndSeq = (group) => {
|
|
475
|
+
const info = table.byNumber.get(group.turn);
|
|
476
|
+
const lastSurfaceSeq = group.seqs[group.seqs.length - 1];
|
|
477
|
+
if (info === undefined || !Number.isInteger(info.startSeq)) return lastSurfaceSeq;
|
|
478
|
+
if (Number.isInteger(info.endSeq)) return info.endSeq;
|
|
479
|
+
const next = table.turns.find((entry) => Number.isInteger(entry.startSeq) && entry.startSeq > info.startSeq);
|
|
480
|
+
if (next === undefined) return lastSurfaceSeq;
|
|
481
|
+
return Math.max(info.startSeq, next.startSeq - 1);
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
// The span starts after the protected head run and on a user/assistant node
|
|
485
|
+
// (the pointer replaces one); a system copy skipped at the head of a turn
|
|
486
|
+
// stays outside the span exactly like 1.6.6 — it is never moved out.
|
|
487
|
+
let startIndex = 0;
|
|
488
|
+
while (startIndex < surfaceNodes.length && protectedSeqs.has(surfaceNodes[startIndex])) startIndex += 1;
|
|
489
|
+
while (startIndex < surfaceNodes.length) {
|
|
490
|
+
const type = typeOfSeq(surfaceNodes[startIndex]);
|
|
491
|
+
if (type === 'user/message' || type === 'assistant/message') break;
|
|
492
|
+
startIndex += 1;
|
|
493
|
+
}
|
|
494
|
+
if (startIndex >= surfaceNodes.length) return noPlan('no-span-start');
|
|
495
|
+
const firstGroup = groupOfPosition[startIndex];
|
|
496
|
+
|
|
497
|
+
// Earliest run of consecutive cuttable groups that lies entirely before the
|
|
498
|
+
// retention boundary and holds at least one real closed turn. Runs made only
|
|
499
|
+
// of orphan messages/pointers are not worth a surface rewrite: skip them.
|
|
500
|
+
let chosenStart = -1;
|
|
501
|
+
let chosenEnd = -1;
|
|
502
|
+
for (let index = firstGroup; index < boundary; index += 1) {
|
|
503
|
+
if (!isCuttableGroup(groups[index])) continue;
|
|
504
|
+
let runEnd = index;
|
|
505
|
+
while (runEnd + 1 < boundary && isCuttableGroup(groups[runEnd + 1])) runEnd += 1;
|
|
506
|
+
let realTurns = 0;
|
|
507
|
+
for (let cursor = index; cursor <= runEnd; cursor += 1) {
|
|
508
|
+
if (groups[cursor].kind === 'turn' && groups[cursor].turn !== 0) realTurns += 1;
|
|
509
|
+
}
|
|
510
|
+
if (realTurns > 0) { chosenStart = index; chosenEnd = runEnd; break; }
|
|
511
|
+
index = runEnd;
|
|
512
|
+
}
|
|
513
|
+
if (chosenStart < 0) {
|
|
514
|
+
return noPlan('blocked-prefix', {
|
|
515
|
+
firstGroup,
|
|
516
|
+
boundary,
|
|
517
|
+
blocked: groups.slice(firstGroup, boundary).map((group) => `${group.kind}:${group.turn}:${group.completed}`),
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
let spanStart = Math.max(startIndex, groupStart[chosenStart]);
|
|
521
|
+
const endIndex = groupEnd[chosenEnd];
|
|
522
|
+
if (endIndex < spanStart) return noPlan('empty-span', { chosenStart, chosenEnd });
|
|
523
|
+
|
|
524
|
+
// A system/message node *inside* the span is a host-restart re-injection of
|
|
525
|
+
// the same prompt; the host tolerates it inside a replacement range and it is
|
|
526
|
+
// archived together with the old prefix (approved 1.6.6 behaviour).
|
|
527
|
+
const shadowedSeqs = surfaceNodes.slice(spanStart, endIndex + 1);
|
|
528
|
+
const shadowedSet = new Set(shadowedSeqs);
|
|
529
|
+
const touchedGroups = groups.filter((group) => group.seqs.some((seq) => shadowedSet.has(seq)));
|
|
530
|
+
if (touchedGroups.some((group) => isCurrentTurnGroup(group))) return noPlan('current-turn-touched');
|
|
531
|
+
// No half turn: every touched turn group must be fully shadowed. The only
|
|
532
|
+
// allowed exception is a system/developer copy skipped at the head of the
|
|
533
|
+
// first group (it stays on the surface, never half-cut).
|
|
534
|
+
for (const group of touchedGroups) {
|
|
535
|
+
if (group.kind !== 'turn') continue;
|
|
536
|
+
const missing = group.seqs.filter((seq) => !shadowedSet.has(seq));
|
|
537
|
+
if (missing.some((seq) => !isInstructionSeq(seq))) return noPlan('split-group', { turn: group.turn });
|
|
538
|
+
}
|
|
539
|
+
const cutTurnGroups = touchedGroups.filter((group) => {
|
|
540
|
+
if (group.kind !== 'turn' || group.turn === 0) return false;
|
|
541
|
+
return !isCurrentTurnGroup(group);
|
|
542
|
+
});
|
|
543
|
+
if (cutTurnGroups.length === 0) return noPlan('no-turns', { chosenStart, chosenEnd });
|
|
544
|
+
|
|
545
|
+
// Archive every original event of the cut turns, plus any checkpoint node and
|
|
546
|
+
// orphan (turn===0) message that positionally lived inside the replaced span.
|
|
547
|
+
const archivedSeqs = new Set();
|
|
548
|
+
const archiveEvents = [];
|
|
549
|
+
for (const group of cutTurnGroups) {
|
|
550
|
+
const info = table.byNumber.get(group.turn);
|
|
551
|
+
if (info === undefined || !Number.isInteger(info.startSeq)) continue;
|
|
552
|
+
const endSeq = resolvedEndSeq(group);
|
|
553
|
+
for (let seq = info.startSeq; seq <= endSeq; seq += 1) {
|
|
554
|
+
const event = table.bySeq.get(seq);
|
|
555
|
+
if (event === undefined || archivedSeqs.has(seq)) continue;
|
|
556
|
+
archivedSeqs.add(seq);
|
|
557
|
+
archiveEvents.push(event);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
for (const seq of shadowedSeqs) {
|
|
561
|
+
if (archivedSeqs.has(seq)) continue;
|
|
562
|
+
const event = table.bySeq.get(seq);
|
|
563
|
+
if (event === undefined) continue;
|
|
564
|
+
archivedSeqs.add(seq);
|
|
565
|
+
archiveEvents.push(event);
|
|
566
|
+
}
|
|
567
|
+
archiveEvents.sort((left, right) => left.seq - right.seq);
|
|
568
|
+
|
|
569
|
+
const cutTurns = cutTurnGroups.map((group) => {
|
|
570
|
+
const info = table.byNumber.get(group.turn);
|
|
571
|
+
const seqs = group.seqs.filter((seq) => shadowedSet.has(seq));
|
|
572
|
+
return {
|
|
573
|
+
turn: group.turn,
|
|
574
|
+
firstSeq: seqs[0],
|
|
575
|
+
lastSeq: seqs[seqs.length - 1],
|
|
576
|
+
startSeq: info?.startSeq ?? seqs[0],
|
|
577
|
+
endSeq: resolvedEndSeq(group),
|
|
578
|
+
surfaceEvents: seqs.length,
|
|
579
|
+
tokens: seqs.reduce((total, seq) => total + prices.get(seq), 0),
|
|
580
|
+
};
|
|
581
|
+
});
|
|
582
|
+
const shadowedTokenCount = shadowedSeqs.reduce((total, seq) => total + prices.get(seq), 0);
|
|
583
|
+
if (shadowedTokenCount <= 0) return noPlan('zero-token');
|
|
584
|
+
|
|
585
|
+
const lastTouchedIndex = groups.indexOf(touchedGroups[touchedGroups.length - 1]);
|
|
586
|
+
const retainedGroups = groups.slice(lastTouchedIndex + 1);
|
|
587
|
+
const retainedTurns = retainedGroups.filter((group) => group.kind === 'turn' && group.completed).length;
|
|
588
|
+
const retainedTokens = retainedGroups.reduce((total, group) => total + groupTokens(group, prices), 0);
|
|
589
|
+
const archivedBefore = archivedTurnsBefore(table);
|
|
590
|
+
const totalTurns = table.totalTurns;
|
|
591
|
+
const archivedTurns = archivedBefore + cutTurns.length;
|
|
592
|
+
|
|
593
|
+
const placeholderPath = '<archive>';
|
|
594
|
+
const previewText = buildPointerText({
|
|
595
|
+
totalTurns,
|
|
596
|
+
archivedTurns,
|
|
597
|
+
firstTurn: cutTurns[0].turn,
|
|
598
|
+
lastTurn: cutTurns[cutTurns.length - 1].turn,
|
|
599
|
+
cutTurnCount: cutTurns.length,
|
|
600
|
+
shadowedTokenCount,
|
|
601
|
+
surfaceEventCount: shadowedSeqs.length,
|
|
602
|
+
eventCount: archiveEvents.length,
|
|
603
|
+
archivePath: placeholderPath,
|
|
604
|
+
sha256: '',
|
|
605
|
+
retainTurns: options.retainTurns,
|
|
606
|
+
retainTokens: options.retainTokens,
|
|
607
|
+
retainedTurns,
|
|
608
|
+
});
|
|
609
|
+
const pointerTokens = roughPointerTokens(previewText);
|
|
610
|
+
if (shadowedTokenCount < pointerTokens + options.minCutTokens) {
|
|
611
|
+
return noPlan('pointer-too-large', { shadowedTokenCount, pointerTokens });
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
return {
|
|
615
|
+
start: shadowedSeqs[0],
|
|
616
|
+
end: shadowedSeqs[shadowedSeqs.length - 1],
|
|
617
|
+
shadowedSeqs,
|
|
618
|
+
shadowedTokenCount,
|
|
619
|
+
cutTurns,
|
|
620
|
+
archiveEvents,
|
|
621
|
+
archivedSeqs,
|
|
622
|
+
totalTurns,
|
|
623
|
+
archivedBefore,
|
|
624
|
+
archivedTurns,
|
|
625
|
+
retainedTurns,
|
|
626
|
+
retainedTokens,
|
|
627
|
+
pointerTokens,
|
|
628
|
+
cutSurfaceGroups: touchedGroups.length,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// ---------------------------------------------------------------------------
|
|
633
|
+
// Archive
|
|
634
|
+
// ---------------------------------------------------------------------------
|
|
635
|
+
|
|
636
|
+
function utcStamp(now) {
|
|
637
|
+
const date = new Date(now);
|
|
638
|
+
const pad = (value, width = 2) => String(value).padStart(width, '0');
|
|
639
|
+
return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}`
|
|
640
|
+
+ `T${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`
|
|
641
|
+
+ `${pad(date.getUTCMilliseconds(), 3)}Z`;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function messageOf(event) {
|
|
645
|
+
if (event?.type === 'user/message') return event.data;
|
|
646
|
+
if (event?.type === 'assistant/message') return event.data?.message;
|
|
647
|
+
if (event?.type === 'tool/result') return event.data?.message;
|
|
648
|
+
return undefined;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Append-only JSONL archive. Writes header + one line per original event +
|
|
653
|
+
* footer, computes sha256 over the body bytes, fsyncs the file, then renames
|
|
654
|
+
* the temp file into place. A collision gets a numeric suffix; no existing
|
|
655
|
+
* archive is ever opened for writing, overwritten or removed.
|
|
656
|
+
*/
|
|
657
|
+
export function writeArchive({
|
|
658
|
+
dir,
|
|
659
|
+
table,
|
|
660
|
+
plan,
|
|
661
|
+
compactionId,
|
|
662
|
+
sessionId = '',
|
|
663
|
+
now = Date.now(),
|
|
664
|
+
fsImpl = fs,
|
|
665
|
+
}) {
|
|
666
|
+
if (typeof dir !== 'string' || dir.length === 0) throw new Error('hot-truncate: archive directory is missing');
|
|
667
|
+
fsImpl.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
668
|
+
const base = `${utcStamp(now)}-${String(compactionId).slice(0, 8)}`;
|
|
669
|
+
let file = path.join(dir, `${base}.jsonl`);
|
|
670
|
+
for (let suffix = 1; fsImpl.existsSync(file); suffix += 1) {
|
|
671
|
+
file = path.join(dir, `${base}-${suffix}.jsonl`);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
const lines = plan.archiveEvents.map((event) => {
|
|
675
|
+
const record = {
|
|
676
|
+
seq: event.seq,
|
|
677
|
+
turn: table.turnOfSeq.get(event.seq) ?? null,
|
|
678
|
+
type: event.type,
|
|
679
|
+
time: event.time ?? null,
|
|
680
|
+
data: event.data ?? null,
|
|
681
|
+
};
|
|
682
|
+
const message = messageOf(event);
|
|
683
|
+
if (message !== undefined) record.message = message;
|
|
684
|
+
return JSON.stringify(record);
|
|
685
|
+
});
|
|
686
|
+
const body = lines.map((line) => `${line}\n`).join('');
|
|
687
|
+
const sha256 = createHash('sha256').update(body, 'utf8').digest('hex');
|
|
688
|
+
const header = {
|
|
689
|
+
kind: 'hot-truncate/header',
|
|
690
|
+
schema: ARCHIVE_SCHEMA,
|
|
691
|
+
at: new Date(now).toISOString(),
|
|
692
|
+
sessionId: String(sessionId ?? ''),
|
|
693
|
+
compactionId: String(compactionId),
|
|
694
|
+
provider: PROVIDER,
|
|
695
|
+
model: MODEL,
|
|
696
|
+
cutTurns: plan.cutTurns,
|
|
697
|
+
shadowedSeqs: plan.shadowedSeqs,
|
|
698
|
+
eventCount: lines.length,
|
|
699
|
+
bodySha256: sha256,
|
|
700
|
+
};
|
|
701
|
+
const footer = { kind: 'hot-truncate/footer', eventCount: lines.length, bodySha256: sha256 };
|
|
702
|
+
const text = `${JSON.stringify(header)}\n${body}${JSON.stringify(footer)}\n`;
|
|
703
|
+
const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
|
|
704
|
+
try {
|
|
705
|
+
const handle = fsImpl.openSync(tmp, 'wx', 0o600);
|
|
706
|
+
try {
|
|
707
|
+
fsImpl.writeFileSync(handle, text, 'utf8');
|
|
708
|
+
fsImpl.fsyncSync(handle);
|
|
709
|
+
} finally {
|
|
710
|
+
fsImpl.closeSync(handle);
|
|
711
|
+
}
|
|
712
|
+
fsImpl.renameSync(tmp, file);
|
|
713
|
+
} catch (error) {
|
|
714
|
+
try {
|
|
715
|
+
fsImpl.unlinkSync(tmp);
|
|
716
|
+
} catch {
|
|
717
|
+
// The temp file is cleanup, not an archive; leaving it is harmless.
|
|
718
|
+
}
|
|
719
|
+
throw error;
|
|
720
|
+
}
|
|
721
|
+
// Best effort: make the rename durable. Windows often refuses directory
|
|
722
|
+
// handles; failure here does not invalidate the already-fsynced file.
|
|
723
|
+
try {
|
|
724
|
+
const dirHandle = fsImpl.openSync(dir, 'r');
|
|
725
|
+
try {
|
|
726
|
+
fsImpl.fsyncSync(dirHandle);
|
|
727
|
+
} finally {
|
|
728
|
+
fsImpl.closeSync(dirHandle);
|
|
729
|
+
}
|
|
730
|
+
} catch {
|
|
731
|
+
// Not fatal; the file content was fsynced before the rename.
|
|
732
|
+
}
|
|
733
|
+
return { path: file, eventCount: lines.length, sha256, header, body };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// ---------------------------------------------------------------------------
|
|
737
|
+
// Pointer message
|
|
738
|
+
// ---------------------------------------------------------------------------
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* The one user-visible replacement. The first line is the contract sentence
|
|
742
|
+
* required by the defect item: total turns, archived turns, and where the
|
|
743
|
+
* originals live. `session_original(turn=…)` keeps working because compaction
|
|
744
|
+
* never deletes the log — only the surface is rewritten.
|
|
745
|
+
*/
|
|
746
|
+
export function buildPointerText(facts) {
|
|
747
|
+
const {
|
|
748
|
+
totalTurns, archivedTurns, firstTurn, lastTurn, cutTurnCount,
|
|
749
|
+
shadowedTokenCount, surfaceEventCount, eventCount, archivePath, sha256,
|
|
750
|
+
retainTurns, retainTokens, retainedTurns,
|
|
751
|
+
} = facts;
|
|
752
|
+
const range = firstTurn === lastTurn ? `第 ${firstTurn} 轮` : `第 ${firstTurn}–${lastTurn} 轮`;
|
|
753
|
+
const lines = [
|
|
754
|
+
`本会话共 ${totalTurns} 轮,其中 ${archivedTurns} 轮已压缩归档;需要原文用 session_original(turn=…) 或读归档路径:${archivePath}`,
|
|
755
|
+
`本次热截断切掉${range}(${cutTurnCount} 轮 / ${shadowedTokenCount} tokens / ${surfaceEventCount} 个表面事件);只切已结束且早于保留窗口的轮(含被中止/中断的旧轮),当前未完成的轮不切,切点之后的原文未动。`,
|
|
756
|
+
`归档:${eventCount} 条原始事件(JSONL,每行含 seq/turn/原始消息)` + (sha256 ? `,sha256=${sha256.slice(0, 16)}…` : '') + '。',
|
|
757
|
+
`保留窗口:最近 ${retainTurns} 个已完成轮、至少 ${retainTokens} tokens(本次保留 ${retainedTurns} 轮)。`,
|
|
758
|
+
];
|
|
759
|
+
return lines.join('\n');
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// ---------------------------------------------------------------------------
|
|
763
|
+
// Engine factory
|
|
764
|
+
// ---------------------------------------------------------------------------
|
|
765
|
+
|
|
766
|
+
function fallbackCreateUserMessage(input) {
|
|
767
|
+
return Object.freeze({
|
|
768
|
+
id: randomUUID(),
|
|
769
|
+
role: 'user',
|
|
770
|
+
content: input.content,
|
|
771
|
+
source: input.source,
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
function fallbackCheckpointSource(compactionId) {
|
|
776
|
+
return Object.freeze({ kind: 'plugin', plugin: 'compact', compactionId });
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function sessionKey(agent) {
|
|
780
|
+
const id = agent?.session?.id;
|
|
781
|
+
return typeof id === 'string' && id.length > 0 ? id : '__default__';
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Build the engine class around injected host primitives. In production
|
|
786
|
+
* `cut-engine.js` passes the real imports; tests pass small mocks.
|
|
787
|
+
*
|
|
788
|
+
* Required: CompactionEngine (the abstract service base). Everything else has
|
|
789
|
+
* a conservative fallback so a host minor-version difference degrades into a
|
|
790
|
+
* working cut instead of a crash.
|
|
791
|
+
*/
|
|
792
|
+
export function createCutEngine(deps) {
|
|
793
|
+
const {
|
|
794
|
+
CompactionEngine,
|
|
795
|
+
CompactionId = (id) => id,
|
|
796
|
+
ManualCompactionError = null,
|
|
797
|
+
compactCheckpointSource = fallbackCheckpointSource,
|
|
798
|
+
createUserMessage = fallbackCreateUserMessage,
|
|
799
|
+
toolPairingBalancedBefore = null,
|
|
800
|
+
toolPairingBalancedAfter = null,
|
|
801
|
+
isCompactCheckpointSource = null,
|
|
802
|
+
contextOverflowCode = 'CONTEXT_WINDOW_EXCEEDED',
|
|
803
|
+
archiveWriter = writeArchive,
|
|
804
|
+
env = process.env,
|
|
805
|
+
} = deps ?? {};
|
|
806
|
+
if (typeof CompactionEngine !== 'function') throw new Error('hot-truncate: CompactionEngine is required');
|
|
807
|
+
|
|
808
|
+
function manualError(code, message, cause) {
|
|
809
|
+
if (typeof ManualCompactionError === 'function') {
|
|
810
|
+
return new ManualCompactionError(code, message, cause === undefined ? undefined : { cause });
|
|
811
|
+
}
|
|
812
|
+
const error = new Error(message);
|
|
813
|
+
error.code = code;
|
|
814
|
+
if (cause !== undefined) error.cause = cause;
|
|
815
|
+
return error;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function isManualError(error) {
|
|
819
|
+
return typeof ManualCompactionError === 'function' && error instanceof ManualCompactionError;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
function estimateMessage(meter, message) {
|
|
823
|
+
try {
|
|
824
|
+
const value = meter?.estimateMessage?.(message);
|
|
825
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
826
|
+
} catch {
|
|
827
|
+
// fall through
|
|
828
|
+
}
|
|
829
|
+
try {
|
|
830
|
+
return roughPointerTokens(JSON.stringify(message));
|
|
831
|
+
} catch {
|
|
832
|
+
return Number.MAX_SAFE_INTEGER;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
return class HotTruncateEngine extends CompactionEngine {
|
|
837
|
+
static inject = ['tokenMeter', 'sessions'];
|
|
838
|
+
|
|
839
|
+
constructor(ctx, config) {
|
|
840
|
+
super(ctx);
|
|
841
|
+
this.options = normalizeOptions(config);
|
|
842
|
+
this.active = new Set();
|
|
843
|
+
this.warned = new Set();
|
|
844
|
+
this.registerTriggers();
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
log(level, message) {
|
|
848
|
+
const logger = this.ctx?.logger;
|
|
849
|
+
try {
|
|
850
|
+
if (typeof logger?.[level] === 'function') logger[level](message);
|
|
851
|
+
else if (level === 'warn') console.error(message);
|
|
852
|
+
} catch {
|
|
853
|
+
// Logging never breaks a cut.
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
warnOnce(key, message) {
|
|
858
|
+
if (this.warned.has(key)) return;
|
|
859
|
+
this.warned.add(key);
|
|
860
|
+
this.log('warn', message);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
registerTriggers() {
|
|
864
|
+
const ctx = this.ctx;
|
|
865
|
+
if (typeof ctx?.on !== 'function') return;
|
|
866
|
+
// Pressure is the host's normal per-step gate. Our policy is simpler:
|
|
867
|
+
// once a completed turn falls outside the retention window, cut it.
|
|
868
|
+
try {
|
|
869
|
+
ctx.on('agent/pre-step', async ({ agent, signal } = {}, next) => {
|
|
870
|
+
try {
|
|
871
|
+
if (!signal?.aborted) await this.compactIfNeeded(agent, 'pressure', signal);
|
|
872
|
+
} catch (error) {
|
|
873
|
+
this.log('warn', `hot-truncate: pre-step cut skipped: ${error?.message ?? error}`);
|
|
874
|
+
}
|
|
875
|
+
return typeof next === 'function' ? next() : undefined;
|
|
876
|
+
});
|
|
877
|
+
} catch (error) {
|
|
878
|
+
this.warnOnce('trigger-pre-step', `hot-truncate: 无法注册 agent/pre-step:${error?.message ?? error}`);
|
|
879
|
+
}
|
|
880
|
+
// Stock registers this recovery path; cut-only must too, otherwise a
|
|
881
|
+
// provider-confirmed overflow never reaches our gate.
|
|
882
|
+
try {
|
|
883
|
+
ctx.on('agent/request-error', async ({ agent, failure, signal } = {}, next) => {
|
|
884
|
+
try {
|
|
885
|
+
if (failure?.code !== contextOverflowCode || signal?.aborted) return typeof next === 'function' ? next() : undefined;
|
|
886
|
+
const generation = agent?.session?.surface?.replaceGeneration ?? 0;
|
|
887
|
+
await this.compactIfNeeded(agent, 'context-overflow', signal);
|
|
888
|
+
if (signal?.aborted) return typeof next === 'function' ? next() : undefined;
|
|
889
|
+
const after = agent?.session?.surface?.replaceGeneration ?? 0;
|
|
890
|
+
if (after <= generation) return typeof next === 'function' ? next() : undefined;
|
|
891
|
+
return { kind: 'retry' };
|
|
892
|
+
} catch (error) {
|
|
893
|
+
this.log('warn', `hot-truncate: overflow recovery skipped: ${error?.message ?? error}`);
|
|
894
|
+
return typeof next === 'function' ? next() : undefined;
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
} catch (error) {
|
|
898
|
+
this.warnOnce('trigger-request-error', `hot-truncate: 无法注册 agent/request-error:${error?.message ?? error}`);
|
|
899
|
+
}
|
|
900
|
+
if (this.options.mode !== 'auto') return;
|
|
901
|
+
try {
|
|
902
|
+
ctx.on('agent/status', ({ agent, status } = {}) => {
|
|
903
|
+
if (status !== 'idle' || !agent?.session) return;
|
|
904
|
+
if (this.active.has(sessionKey(agent))) return;
|
|
905
|
+
void this.autoCut(agent);
|
|
906
|
+
});
|
|
907
|
+
} catch (error) {
|
|
908
|
+
this.warnOnce('trigger-status', `hot-truncate: 无法注册 agent/status:${error?.message ?? error}`);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** Price the current surface with the host meter, or a safe local estimate. */
|
|
913
|
+
measure(session) {
|
|
914
|
+
try {
|
|
915
|
+
const measured = this.ctx?.tokenMeter?.measure?.(session);
|
|
916
|
+
if (measured && Array.isArray(measured.nodes)) {
|
|
917
|
+
const totalTokens = Number.isFinite(measured.totalTokens)
|
|
918
|
+
? measured.totalTokens
|
|
919
|
+
: measured.nodes.reduce((sum, node) => sum + (Number(node?.tokens) || 0), 0);
|
|
920
|
+
return { totalTokens, nodes: measured.nodes };
|
|
921
|
+
}
|
|
922
|
+
} catch {
|
|
923
|
+
// The local estimate below is only a fallback.
|
|
924
|
+
}
|
|
925
|
+
const table = turnTable(session);
|
|
926
|
+
const nodes = (session?.surface?.nodes ?? []).map((seq) => {
|
|
927
|
+
const event = table.bySeq.get(seq);
|
|
928
|
+
return { seq, tokens: eventTokens(event, null) };
|
|
929
|
+
});
|
|
930
|
+
return { totalTokens: nodes.reduce((sum, node) => sum + node.tokens, 0), nodes };
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
planFor(session, measurement = this.measure(session)) {
|
|
934
|
+
const table = turnTable(session);
|
|
935
|
+
return selectCutPlan(session, this.options, measurement, {
|
|
936
|
+
table,
|
|
937
|
+
isCheckpointSource: isCompactCheckpointSource,
|
|
938
|
+
// "cut, or say why not": a refusal that would otherwise be silent is
|
|
939
|
+
// logged once per reason (warnOnce) so a permanently disabled hot
|
|
940
|
+
// truncate is always observable in the host log.
|
|
941
|
+
onNoPlan: (info) => {
|
|
942
|
+
const reason = String(info?.reason ?? 'unknown');
|
|
943
|
+
const detail = info?.detail === undefined || info?.detail === null ? '' : ` ${JSON.stringify(info.detail)}`;
|
|
944
|
+
this.warnOnce(`no-plan:${reason}`, `hot-truncate: 未切(${reason})${detail}`);
|
|
945
|
+
},
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* Automatic cut gate. Never throws: the host's turn must not be blocked
|
|
951
|
+
* because a cut failed. Returns null when nothing safe can be cut.
|
|
952
|
+
*/
|
|
953
|
+
async compactIfNeeded(agent, trigger, signal) {
|
|
954
|
+
try {
|
|
955
|
+
if (this.options.mode === 'off') return null;
|
|
956
|
+
if (signal?.aborted) return null;
|
|
957
|
+
const session = agent?.session;
|
|
958
|
+
if (!session) return null;
|
|
959
|
+
if (this.active.has(sessionKey(agent))) return null;
|
|
960
|
+
// Automatic compaction events must be enclosed in the open turn; a
|
|
961
|
+
// between-turn caller should use compactNow (manual) instead.
|
|
962
|
+
if (findOpenTurn(sessionEvents(session)) === null) return null;
|
|
963
|
+
const measurement = this.measure(session);
|
|
964
|
+
// The per-step pressure path is automatic, so it must obey the same
|
|
965
|
+
// trigger threshold as the idle path. Without this gate a long session
|
|
966
|
+
// is cut once per completed turn no matter how large autoMinTokens is,
|
|
967
|
+
// which is exactly the cache-invalidating behaviour 1.6.4 removes. An
|
|
968
|
+
// explicit context-overflow recovery still cuts below the threshold:
|
|
969
|
+
// surviving the failed request is more important than the cache.
|
|
970
|
+
if (trigger !== 'context-overflow' && measurement.totalTokens < this.options.autoMinTokens) return null;
|
|
971
|
+
const plan = this.planFor(session, measurement);
|
|
972
|
+
if (plan === null) return null;
|
|
973
|
+
if (activeCompactionStart(sessionEvents(session)) !== null) {
|
|
974
|
+
this.warnOnce('busy-auto', 'hot-truncate: 已有未闭合的 compaction,自动热截断跳过这一轮');
|
|
975
|
+
return null;
|
|
976
|
+
}
|
|
977
|
+
return await this.commit(agent, plan, { signal });
|
|
978
|
+
} catch (error) {
|
|
979
|
+
this.log('warn', `hot-truncate: 自动热截断失败,保留宿主原状态:${error?.message ?? error}`);
|
|
980
|
+
return null;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/**
|
|
985
|
+
* Manual cut. The idle task is reserved synchronously through
|
|
986
|
+
* `agent.runMaintenance` before any asynchronous work, matching the stock
|
|
987
|
+
* backend's manual contract.
|
|
988
|
+
*/
|
|
989
|
+
compactNow(agent, signal, sourceCommandId) {
|
|
990
|
+
signal?.throwIfAborted?.();
|
|
991
|
+
try {
|
|
992
|
+
return agent.runMaintenance(async (agentSignal) => {
|
|
993
|
+
const operationSignal = AbortSignal.any([agentSignal, signal]);
|
|
994
|
+
try {
|
|
995
|
+
operationSignal.throwIfAborted();
|
|
996
|
+
const session = agent?.session;
|
|
997
|
+
if (!session) return null;
|
|
998
|
+
const plan = this.planFor(session);
|
|
999
|
+
if (plan === null) return null;
|
|
1000
|
+
if (activeCompactionStart(sessionEvents(session)) !== null) {
|
|
1001
|
+
throw manualError('busy', 'hot-truncate: 已有未闭合的 compaction');
|
|
1002
|
+
}
|
|
1003
|
+
return await this.commit(agent, plan, {
|
|
1004
|
+
signal: operationSignal,
|
|
1005
|
+
sourceCommandId,
|
|
1006
|
+
});
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
if (agentSignal?.aborted && operationSignal.reason === agentSignal.reason) {
|
|
1009
|
+
throw manualError('cancelled', 'hot-truncate: 手动热截断被取消', error);
|
|
1010
|
+
}
|
|
1011
|
+
operationSignal.throwIfAborted();
|
|
1012
|
+
if (isManualError(error)) throw error;
|
|
1013
|
+
throw manualError('summary', 'hot-truncate: 手动热截断没有提交', error);
|
|
1014
|
+
}
|
|
1015
|
+
});
|
|
1016
|
+
} catch (error) {
|
|
1017
|
+
if (isManualError(error)) throw error;
|
|
1018
|
+
throw manualError('busy', 'hot-truncate: 手动热截断需要空闲的 agent', error);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* Force one positional range. The cut-only policy still applies: the range
|
|
1024
|
+
* must be the plan this engine would have selected, so a direct caller can
|
|
1025
|
+
* never split a turn or cut inside the retention window.
|
|
1026
|
+
*/
|
|
1027
|
+
async compactRegion(start, end, agent, signal) {
|
|
1028
|
+
signal?.throwIfAborted?.();
|
|
1029
|
+
const session = agent?.session;
|
|
1030
|
+
if (!session) throw new Error('hot-truncate: compactRegion requires agent.session');
|
|
1031
|
+
const plan = this.planFor(session);
|
|
1032
|
+
if (plan === null) throw new Error('hot-truncate: no safe completed-turn span to cut');
|
|
1033
|
+
if (plan.start !== start || plan.end !== end) {
|
|
1034
|
+
throw new Error('hot-truncate: compactRegion only cuts the selected oldest completed turns');
|
|
1035
|
+
}
|
|
1036
|
+
if (activeCompactionStart(sessionEvents(session)) !== null) throw manualError('busy', 'hot-truncate: 已有未闭合的 compaction');
|
|
1037
|
+
return this.commit(agent, plan, { signal });
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/** Cut one plan. Archive first, then append start → summary → pointer → end. */
|
|
1041
|
+
async commit(agent, plan, { signal, sourceCommandId } = {}) {
|
|
1042
|
+
signal?.throwIfAborted?.();
|
|
1043
|
+
const session = agent.session;
|
|
1044
|
+
const key = sessionKey(agent);
|
|
1045
|
+
if (this.active.has(key)) return null;
|
|
1046
|
+
this.active.add(key);
|
|
1047
|
+
const compactionId = CompactionId(randomUUID());
|
|
1048
|
+
const openTurn = findOpenTurn(sessionEvents(session));
|
|
1049
|
+
const lifecycle = {
|
|
1050
|
+
compactionId,
|
|
1051
|
+
...(sourceCommandId === undefined ? {} : { sourceCommandId }),
|
|
1052
|
+
turn: openTurn,
|
|
1053
|
+
};
|
|
1054
|
+
let started = false;
|
|
1055
|
+
let closed = false;
|
|
1056
|
+
let archive = null;
|
|
1057
|
+
// 1.8.1-rc.7 audit P1-6: one durable diag row per hot-truncate archive.
|
|
1058
|
+
// The old path wrote only the pointer/log line; an archive without a
|
|
1059
|
+
// matching diag row was indistinguishable from an archive that never
|
|
1060
|
+
// happened when a later surface append failed.
|
|
1061
|
+
const diagStartedAt = Date.now();
|
|
1062
|
+
let diagRoot = this.options.memoryRoot || this.options.memRoot || '';
|
|
1063
|
+
let diagDone = false;
|
|
1064
|
+
let archiveWritten = false;
|
|
1065
|
+
const emitHotTruncateDiag = (result, extra = {}) => {
|
|
1066
|
+
if (!diagRoot || diagDone) return;
|
|
1067
|
+
diagDone = true;
|
|
1068
|
+
try {
|
|
1069
|
+
const written = appendHotTruncateDiag(diagRoot, {
|
|
1070
|
+
sessionId: String(session.id ?? ''),
|
|
1071
|
+
turn: Number.isInteger(openTurn) ? openTurn : null,
|
|
1072
|
+
plannedCut: {
|
|
1073
|
+
startSeq: plan.start,
|
|
1074
|
+
endSeq: plan.end,
|
|
1075
|
+
cutTurns: plan.cutTurns.map((entry) => entry.turn),
|
|
1076
|
+
firstTurn: plan.cutTurns[0]?.turn ?? null,
|
|
1077
|
+
lastTurn: plan.cutTurns[plan.cutTurns.length - 1]?.turn ?? null,
|
|
1078
|
+
},
|
|
1079
|
+
retainTurns: this.options.retainTurns,
|
|
1080
|
+
retainTokens: this.options.retainTokens,
|
|
1081
|
+
tokensBefore: plan.shadowedTokenCount + plan.retainedTokens,
|
|
1082
|
+
tokensCut: plan.shadowedTokenCount,
|
|
1083
|
+
tokensAfter: plan.retainedTokens,
|
|
1084
|
+
archivePath: archive?.path ?? null,
|
|
1085
|
+
archiveWritten,
|
|
1086
|
+
archiveBytes: archive?.path ? (() => { try { return fs.statSync(archive.path).size } catch { return null } })() : null,
|
|
1087
|
+
archiveEvents: archive?.eventCount ?? null,
|
|
1088
|
+
cutTurnCount: plan.cutTurns.length,
|
|
1089
|
+
result,
|
|
1090
|
+
...extra,
|
|
1091
|
+
durationMs: Math.max(0, Date.now() - diagStartedAt),
|
|
1092
|
+
}, hotTruncateDiagOptions({}));
|
|
1093
|
+
if (!written.ok) this.log('warn', `hot-truncate diag write failed: ${written.error ?? 'unknown'}`);
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
this.log('warn', `hot-truncate diag threw: ${error?.message ?? error}`);
|
|
1096
|
+
}
|
|
1097
|
+
};
|
|
1098
|
+
try {
|
|
1099
|
+
// A whole completed turn is balanced by construction, but the host's
|
|
1100
|
+
// own predicate is the authority — a corrupt surface must stop the cut
|
|
1101
|
+
// before anything is written.
|
|
1102
|
+
if (typeof toolPairingBalancedBefore === 'function' || typeof toolPairingBalancedAfter === 'function') {
|
|
1103
|
+
const before = typeof toolPairingBalancedBefore === 'function' ? toolPairingBalancedBefore(session, plan.start) : true;
|
|
1104
|
+
const after = typeof toolPairingBalancedAfter === 'function' ? toolPairingBalancedAfter(session, plan.end) : true;
|
|
1105
|
+
if (before !== true || after !== true) throw new Error('hot-truncate: selected cut is not tool-pairing balanced');
|
|
1106
|
+
}
|
|
1107
|
+
const dir = resolveArchiveDir(this.options, env);
|
|
1108
|
+
if (!diagRoot) {
|
|
1109
|
+
// The shipped compaction row (cordis.patch.yml) does not repeat
|
|
1110
|
+
// memoryRoot; resolveArchiveDir has already chosen the real store.
|
|
1111
|
+
// Recover it from the standard <root>/.longlive/hot-truncate layout.
|
|
1112
|
+
const parent = path.dirname(dir);
|
|
1113
|
+
if (path.basename(dir) === 'hot-truncate' && path.basename(parent) === '.longlive') {
|
|
1114
|
+
diagRoot = path.dirname(parent);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
archive = archiveWriter({
|
|
1118
|
+
dir,
|
|
1119
|
+
table: turnTable(session),
|
|
1120
|
+
plan,
|
|
1121
|
+
compactionId,
|
|
1122
|
+
sessionId: String(session.id ?? ''),
|
|
1123
|
+
now: Date.now(),
|
|
1124
|
+
});
|
|
1125
|
+
if (!archive || typeof archive.path !== 'string') throw new Error('hot-truncate: archive writer returned no path');
|
|
1126
|
+
archiveWritten = true;
|
|
1127
|
+
const facts = {
|
|
1128
|
+
totalTurns: plan.totalTurns,
|
|
1129
|
+
archivedTurns: plan.archivedTurns,
|
|
1130
|
+
firstTurn: plan.cutTurns[0].turn,
|
|
1131
|
+
lastTurn: plan.cutTurns[plan.cutTurns.length - 1].turn,
|
|
1132
|
+
cutTurnCount: plan.cutTurns.length,
|
|
1133
|
+
shadowedTokenCount: plan.shadowedTokenCount,
|
|
1134
|
+
surfaceEventCount: plan.shadowedSeqs.length,
|
|
1135
|
+
eventCount: archive.eventCount,
|
|
1136
|
+
archivePath: archive.path,
|
|
1137
|
+
sha256: archive.sha256,
|
|
1138
|
+
retainTurns: this.options.retainTurns,
|
|
1139
|
+
retainTokens: this.options.retainTokens,
|
|
1140
|
+
retainedTurns: plan.retainedTurns,
|
|
1141
|
+
};
|
|
1142
|
+
const text = buildPointerText(facts);
|
|
1143
|
+
const summary = [{ type: 'text', text }];
|
|
1144
|
+
const pointerMessage = createUserMessage({
|
|
1145
|
+
content: summary,
|
|
1146
|
+
// Carry the cumulative count on the pointer itself. The source stays
|
|
1147
|
+
// a normal compact-checkpoint; `hotTruncate` is an extra field the
|
|
1148
|
+
// MessageSourceMap (merge-extensible) tolerates.
|
|
1149
|
+
source: {
|
|
1150
|
+
...compactCheckpointSource(compactionId, sourceCommandId),
|
|
1151
|
+
hotTruncate: {
|
|
1152
|
+
archivedTurns: plan.archivedTurns,
|
|
1153
|
+
totalTurns: plan.totalTurns,
|
|
1154
|
+
archivePath: archive.path,
|
|
1155
|
+
retainTurns: this.options.retainTurns,
|
|
1156
|
+
retainTokens: this.options.retainTokens,
|
|
1157
|
+
cutTurns: plan.cutTurns.map((entry) => entry.turn),
|
|
1158
|
+
},
|
|
1159
|
+
},
|
|
1160
|
+
});
|
|
1161
|
+
const pointerTokens = estimateMessage(this.ctx?.tokenMeter, pointerMessage);
|
|
1162
|
+
if (pointerTokens + this.options.minCutTokens > plan.shadowedTokenCount) {
|
|
1163
|
+
throw new Error(`hot-truncate: pointer (${pointerTokens}) is not smaller than the cut (${plan.shadowedTokenCount}); leaving the surface alone`);
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const startEvent = session.append('compaction/start', lifecycle);
|
|
1167
|
+
started = true;
|
|
1168
|
+
const summaryEvent = session.append('compaction/summary', {
|
|
1169
|
+
compactionId,
|
|
1170
|
+
...(sourceCommandId === undefined ? {} : { sourceCommandId }),
|
|
1171
|
+
summary,
|
|
1172
|
+
shadowedRange: { start: plan.start, end: plan.end },
|
|
1173
|
+
shadowedSeqs: [...plan.shadowedSeqs],
|
|
1174
|
+
shadowedTokenCount: plan.shadowedTokenCount,
|
|
1175
|
+
provider: PROVIDER,
|
|
1176
|
+
model: MODEL,
|
|
1177
|
+
});
|
|
1178
|
+
// The host's exact replace shape is `{op, startSeq, endSeq}` (three
|
|
1179
|
+
// own keys; `start`/`end` are rejected as `invalid replace surfaceOp`).
|
|
1180
|
+
session.append('user/message', pointerMessage, {
|
|
1181
|
+
surfaceOp: { op: 'replace', startSeq: plan.start, endSeq: plan.end },
|
|
1182
|
+
sourceEventSeqs: [startEvent.seq, summaryEvent.seq, ...plan.shadowedSeqs],
|
|
1183
|
+
});
|
|
1184
|
+
const endEvent = session.append('compaction/end', lifecycle);
|
|
1185
|
+
closed = true;
|
|
1186
|
+
if (openTurn === null && typeof this.ctx?.sessions?.flush === 'function') {
|
|
1187
|
+
await this.ctx.sessions.flush(session);
|
|
1188
|
+
}
|
|
1189
|
+
this.log('info', `hot-truncate: 切掉第 ${plan.cutTurns[0].turn}–${plan.cutTurns[plan.cutTurns.length - 1].turn} 轮,`
|
|
1190
|
+
+ `${plan.shadowedSeqs.length} 事件 / ${plan.shadowedTokenCount} tokens,原文 ${archive.eventCount} 条 → ${archive.path}`);
|
|
1191
|
+
emitHotTruncateDiag('ok');
|
|
1192
|
+
return {
|
|
1193
|
+
compactionId,
|
|
1194
|
+
...(sourceCommandId === undefined ? {} : { sourceCommandId }),
|
|
1195
|
+
startSeq: startEvent.seq,
|
|
1196
|
+
summarySeq: summaryEvent.seq,
|
|
1197
|
+
endSeq: endEvent.seq,
|
|
1198
|
+
summary,
|
|
1199
|
+
shadowedRange: { start: plan.start, end: plan.end },
|
|
1200
|
+
shadowedSeqs: [...plan.shadowedSeqs],
|
|
1201
|
+
shadowedTokenCount: plan.shadowedTokenCount,
|
|
1202
|
+
};
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
if (started && !closed) {
|
|
1205
|
+
try {
|
|
1206
|
+
session.append('compaction/end', { ...lifecycle, error: error?.message ?? String(error) });
|
|
1207
|
+
} catch {
|
|
1208
|
+
// A failed close leaves the unmatched start visible, exactly like
|
|
1209
|
+
// the stock backend; the next cut refuses until a seed boundary.
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
emitHotTruncateDiag('fail', {
|
|
1213
|
+
failReason: `${error?.code ?? 'HOT_TRUNCATE_FAILED'}: ${error?.message ?? String(error)}`,
|
|
1214
|
+
});
|
|
1215
|
+
throw error;
|
|
1216
|
+
} finally {
|
|
1217
|
+
this.active.delete(key);
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/** Mode=auto only: cut at idle, inside an agent maintenance window. */
|
|
1222
|
+
async autoCut(agent) {
|
|
1223
|
+
try {
|
|
1224
|
+
await agent.runMaintenance(async (agentSignal) => {
|
|
1225
|
+
const signal = AbortSignal.any([agentSignal, AbortSignal.timeout(30000)]);
|
|
1226
|
+
const measurement = this.measure(agent.session);
|
|
1227
|
+
if (measurement.totalTokens < this.options.autoMinTokens) return;
|
|
1228
|
+
const plan = this.planFor(agent.session, measurement);
|
|
1229
|
+
if (plan === null) return;
|
|
1230
|
+
await this.commit(agent, plan, { signal });
|
|
1231
|
+
});
|
|
1232
|
+
} catch (error) {
|
|
1233
|
+
this.log('warn', `hot-truncate: idle 热截断跳过:${error?.message ?? error}`);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
};
|
|
1237
|
+
}
|