@jjh32456/longlive 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,1181 @@
1
+ // 0.7.5 — automatic visible truncation at turn boundaries: log / dryrun / request.
2
+ //
3
+ // The request is built from a snapshot re-read right before the write, not from
4
+ // the turn/end read: the app keeps appending for a few milliseconds after
5
+ // turn/end (observed: 295 -> 298 events in 8 ms), and a plan computed from the
6
+ // stale read describes a file that no longer exists. The plan therefore records
7
+ // `snapshotEvents` / `snapshotMessages` / `snapshotAt`, and the watchdog
8
+ // (scripts/auto-truncate-run.ps1) reports how far the actual cut drifted from
9
+ // them in its result JSON.
10
+ //
11
+ // One evaluation per session per `cooldownMinutes`; the trigger is the host's
12
+ // `turn/end` event (see heartbeat.js, which already owns the `session/event`
13
+ // listener). The modes are deliberately shaped like the manual tool:
14
+ //
15
+ // log — parse + plan only; appends one JSON line; never opens the session
16
+ // log for writing;
17
+ // dryrun — the full plan path (`truncateVisibleSession({dryRun:true})`) plus
18
+ // the plan in the same log; still no write to the session log;
19
+ // request — plan, then atomically write a request file for an out-of-app
20
+ // orchestrator. It never writes the session log. A config that still
21
+ // says "apply" is treated as "request" and recorded in the log as
22
+ // modeAlias:"apply->request"; there is no in-app write mode any more.
23
+ //
24
+ // Why apply had to go: the running host keeps the session in memory and its
25
+ // writer on the old sequence. Rewriting the file underneath it produces a
26
+ // sequence gap and a torn JSONL record on the next append (the 0.7.0 round
27
+ // measured 77 -> 3532). Only an out-of-app process, after the host has exited,
28
+ // may cut the file — scripts/truncate-cli.mjs, driven by auto-truncate-run.ps1.
29
+ //
30
+ // The estimate is intentionally blunt: `MESSAGE_TYPES` data JSON / 4, the same
31
+ // heuristic the tool reports. It counts host-injected `user/message` blocks as
32
+ // message text, so it can overshoot. Per the 0.7.1 spec that is not a reason to
33
+ // skip: the configured threshold is the only decision rule, and every log line
34
+ // records the estimate basis explicitly.
35
+
36
+ import fs from 'node:fs';
37
+ import path from 'node:path';
38
+ import crypto from 'node:crypto';
39
+ import { fileURLToPath } from 'node:url';
40
+
41
+ import { parseSession } from './codec.js';
42
+ import { appendJsonlRotated, normalizeLogRotation } from './log-rotation.js';
43
+ import { recordAutoTruncateStatus } from './auto-truncate-status.js';
44
+ import {
45
+ AUTO_TRUNCATE_LOG_TOKENS,
46
+ CONTEXT_WINDOW_TOKENS,
47
+ INPUT_COMPACT_AT_TOKENS,
48
+ OUTPUT_RESERVE_NORMAL_TOKENS,
49
+ SAFETY_TOKENS,
50
+ THRESHOLD_POLICY_WARNING,
51
+ classifyFoldFailure,
52
+ evaluateFoldTrigger,
53
+ evaluateTruncateBudget,
54
+ foldRetrySchedule,
55
+ thresholdEnforceability,
56
+ } from './policy/threshold-policy.js';
57
+ import {
58
+ DEFAULT_BOUNDARY_RETRIES,
59
+ DEFAULT_FIRST_USER_CAP_CHARS,
60
+ nextArchivePath,
61
+ planVisibleTruncation,
62
+ readInflight,
63
+ resolveVisibleCut,
64
+ sessionEstimate,
65
+ truncateVisibleSession,
66
+ } from './truncate-visible.js';
67
+
68
+ // 1.6.0 safety default (abuse assessment §4.1): automatic truncation is off
69
+ // unless a profile opts in. The default mode is dryrun, so even an explicit
70
+ // `autoTruncate: {}` cannot cut a session by accident; `mode:'request'` also
71
+ // requires enabled:true, and the runner additionally needs the watchdog.
72
+ //
73
+ // 1.8.10: tokensThreshold is an *external session-log* notice line (12M tokens
74
+ // ≈ 60MB at ~5 B/token), not the 350k model-context line. request mode runs the
75
+ // external watchdog, which cuts and restarts without asking; keep dryrun unless
76
+ // the operator explicitly wants automatic cuts.
77
+ export const AUTO_TRUNCATE_DEFAULTS = Object.freeze({
78
+ enabled: true,
79
+ mode: 'dryrun',
80
+ tokensThreshold: AUTO_TRUNCATE_LOG_TOKENS,
81
+ minTurns: 12,
82
+ cooldownMinutes: 60,
83
+ keepTurns: 12,
84
+ keepTokens: 80_000,
85
+ // 0.8.0-rc.11: the carried first user message is bounded, and an unstable
86
+ // boundary is retried by dropping one more turn at a time.
87
+ firstUserCapChars: DEFAULT_FIRST_USER_CAP_CHARS,
88
+ boundaryRetries: DEFAULT_BOUNDARY_RETRIES,
89
+ // app.exe / app.profile written into the request file for the orchestrator.
90
+ // An empty appExe means "use process.execPath" (inside Electron that is the
91
+ // running app; under node it is node.exe, which a test or a dry run can read).
92
+ appExe: '',
93
+ profile: 'desktop',
94
+ });
95
+
96
+ export const AUTO_TRUNCATE_MODES = Object.freeze(['log', 'dryrun', 'request']);
97
+ // 0.7.0's in-app write mode. Accepted at parse time only to be rewritten to
98
+ // request; it is never executed and never written to the session log.
99
+ export const AUTO_TRUNCATE_LEGACY_MODES = Object.freeze(['apply']);
100
+
101
+ export const AUTO_TRUNCATE_STATE_FILE = 'auto-truncate-state.json';
102
+ export const AUTO_TRUNCATE_LOG_DIR = 'logs';
103
+ export const AUTO_TRUNCATE_LOG_FILE = 'auto-truncate.log';
104
+ export const AUTO_TRUNCATE_REQUEST_FILE = 'auto-truncate.request.json';
105
+
106
+ export const AUTO_ESTIMATE_BASIS =
107
+ 'MESSAGE_TYPES data JSON/4 (same heuristic as session_truncate_visible); host-injected user/message rows count too';
108
+
109
+ export const AUTO_TRUNCATE_ERRORS = Object.freeze({
110
+ BAD_CONFIG: 'AUTO_BAD_CONFIG',
111
+ BAD_MODE: 'AUTO_BAD_MODE',
112
+ LOG_WRITE: 'AUTO_LOG_WRITE',
113
+ EVALUATE: 'AUTO_EVALUATE_FAILED',
114
+ });
115
+
116
+ const MAX_STATE_SESSIONS = 200;
117
+ const MAX_SEEN_SESSIONS = 256;
118
+
119
+ function autoError(code, message) {
120
+ const error = new Error(message);
121
+ error.code = code;
122
+ return error;
123
+ }
124
+
125
+ function asPositiveInt(name, value, min) {
126
+ if (!Number.isInteger(value) || value < min) {
127
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
128
+ `autoTruncate.${name} must be an integer >= ${min} (got ${JSON.stringify(value)})`);
129
+ }
130
+ return value;
131
+ }
132
+
133
+ /**
134
+ * Merge the raw plugin config (`config.autoTruncate`) with the defaults.
135
+ *
136
+ * Invalid values throw instead of being silently clamped: a typo in `mode`
137
+ * must not turn "apply" into "log" (or the reverse) behind the operator's back.
138
+ */
139
+ export function normalizeAutoTruncateConfig(raw) {
140
+ if (raw == null) return { ...AUTO_TRUNCATE_DEFAULTS };
141
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
142
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG, 'autoTruncate must be an object');
143
+ }
144
+ const merged = { ...AUTO_TRUNCATE_DEFAULTS, ...raw };
145
+ if (typeof merged.enabled !== 'boolean') {
146
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
147
+ `autoTruncate.enabled must be boolean (got ${JSON.stringify(merged.enabled)})`);
148
+ }
149
+ // 0.7.0 configs say "apply". Rewrite them to the request mode *before* the
150
+ // mode check, and remember the alias so every log line names what happened.
151
+ // A typo like "APPLY" still throws: only the exact legacy word is accepted.
152
+ if (AUTO_TRUNCATE_LEGACY_MODES.includes(merged.mode)) {
153
+ merged.mode = 'request';
154
+ merged.modeAlias = 'apply->request';
155
+ } else {
156
+ delete merged.modeAlias;
157
+ }
158
+ if (!AUTO_TRUNCATE_MODES.includes(merged.mode)) {
159
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_MODE,
160
+ `autoTruncate.mode must be one of ${AUTO_TRUNCATE_MODES.join('|')} `
161
+ + `(legacy ${AUTO_TRUNCATE_LEGACY_MODES.join('|')} is accepted as request; got ${JSON.stringify(merged.mode)})`);
162
+ }
163
+ if (typeof merged.appExe !== 'string') {
164
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
165
+ `autoTruncate.appExe must be a string (got ${JSON.stringify(merged.appExe)})`);
166
+ }
167
+ merged.appExe = merged.appExe.trim();
168
+ if (typeof merged.profile !== 'string' || merged.profile.trim() === '') {
169
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
170
+ `autoTruncate.profile must be a non-empty string (got ${JSON.stringify(merged.profile)})`);
171
+ }
172
+ merged.profile = merged.profile.trim();
173
+ asPositiveInt('tokensThreshold', merged.tokensThreshold, 1);
174
+ asPositiveInt('minTurns', merged.minTurns, 1);
175
+ asPositiveInt('cooldownMinutes', merged.cooldownMinutes, 0);
176
+ asPositiveInt('keepTurns', merged.keepTurns, 1);
177
+ asPositiveInt('keepTokens', merged.keepTokens, 1);
178
+ asPositiveInt('firstUserCapChars', merged.firstUserCapChars, 1);
179
+ asPositiveInt('boundaryRetries', merged.boundaryRetries, 0);
180
+ // 1.8.1-rc.7 diagnostics log rotation is an optional passthrough block. It is
181
+ // deliberately absent from AUTO_TRUNCATE_DEFAULTS so the settings schema node
182
+ // count stays stable; when present it is validated here, otherwise the shared
183
+ // log-rotation defaults (8 MiB / 14 days / 5 files / daily) apply.
184
+ if (merged.logMaxBytes !== undefined) asPositiveInt('logMaxBytes', merged.logMaxBytes, 64 * 1024);
185
+ if (merged.logMaxFiles !== undefined) asPositiveInt('logMaxFiles', merged.logMaxFiles, 1);
186
+ if (merged.logMaxAgeDays !== undefined) {
187
+ if (!Number.isInteger(merged.logMaxAgeDays) || merged.logMaxAgeDays < 0) {
188
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
189
+ `autoTruncate.logMaxAgeDays must be an integer >= 0 (got ${JSON.stringify(merged.logMaxAgeDays)})`);
190
+ }
191
+ }
192
+ if (merged.logRotateDaily !== undefined && typeof merged.logRotateDaily !== 'boolean') {
193
+ throw autoError(AUTO_TRUNCATE_ERRORS.BAD_CONFIG,
194
+ `autoTruncate.logRotateDaily must be boolean (got ${JSON.stringify(merged.logRotateDaily)})`);
195
+ }
196
+ return merged;
197
+ }
198
+
199
+ export function autoTruncatePaths(memoryRoot) {
200
+ const root = path.join(memoryRoot, '.longlive');
201
+ return {
202
+ statePath: path.join(root, AUTO_TRUNCATE_STATE_FILE),
203
+ logDir: path.join(root, AUTO_TRUNCATE_LOG_DIR),
204
+ logPath: path.join(root, AUTO_TRUNCATE_LOG_DIR, AUTO_TRUNCATE_LOG_FILE),
205
+ requestPath: path.join(root, AUTO_TRUNCATE_LOG_DIR, AUTO_TRUNCATE_REQUEST_FILE),
206
+ };
207
+ }
208
+
209
+ function emptyState() {
210
+ return { version: 1, sessions: {} };
211
+ }
212
+
213
+ /** Tolerant read: a missing/corrupt state file just means "no prior runs". */
214
+ export function readAutoTruncateState(memoryRoot) {
215
+ try {
216
+ const raw = fs.readFileSync(autoTruncatePaths(memoryRoot).statePath, 'utf8');
217
+ const parsed = JSON.parse(raw);
218
+ if (parsed && typeof parsed === 'object' && parsed.sessions && typeof parsed.sessions === 'object') {
219
+ return parsed;
220
+ }
221
+ return emptyState();
222
+ } catch {
223
+ return emptyState();
224
+ }
225
+ }
226
+
227
+ function writeAutoTruncateState(memoryRoot, state) {
228
+ const { statePath } = autoTruncatePaths(memoryRoot);
229
+ const entries = Object.entries(state.sessions);
230
+ if (entries.length > MAX_STATE_SESSIONS) {
231
+ entries.sort((a, b) => (b[1]?.lastEvaluatedAt ?? 0) - (a[1]?.lastEvaluatedAt ?? 0));
232
+ state.sessions = Object.fromEntries(entries.slice(0, MAX_STATE_SESSIONS));
233
+ }
234
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
235
+ const tmp = `${statePath}.tmp-${process.pid}-${Date.now()}`;
236
+ fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);
237
+ fs.renameSync(tmp, statePath);
238
+ }
239
+
240
+ /**
241
+ * Atomically publish the request: write a sibling tmp file, then rename it over
242
+ * the final name. A reader sees either the old file or the complete new one.
243
+ *
244
+ * The tmp write is inside the try so a short/failed write (ENOSPC, quota,
245
+ * antivirus) removes the partial file instead of leaving a 12-byte request that
246
+ * the next evaluation would quarantine forever.
247
+ */
248
+ function writeRequestAtomic(fsImpl, requestPath, request) {
249
+ const dir = path.dirname(requestPath);
250
+ fsImpl.mkdirSync(dir, { recursive: true });
251
+ const tmp = `${requestPath}.tmp-${process.pid}-${Date.now()}`;
252
+ const body = `${JSON.stringify(request, null, 2)}\n`;
253
+ const cleanup = () => {
254
+ try { fsImpl.unlinkSync(tmp); } catch { /* nothing left to clean */ }
255
+ };
256
+ try {
257
+ fsImpl.writeFileSync(tmp, body);
258
+ fsImpl.renameSync(tmp, requestPath);
259
+ } catch (error) {
260
+ cleanup();
261
+ throw error;
262
+ }
263
+ return { requestPath, tmp, bytes: Buffer.byteLength(body) };
264
+ }
265
+
266
+ /**
267
+ * A corrupt request is evidence, not a permanent blocker: move it aside under a
268
+ * timestamped name, then let this evaluation publish a fresh request.
269
+ */
270
+ function quarantineRequestFile(fsImpl, requestPath, now) {
271
+ const dir = path.dirname(requestPath);
272
+ const stampText = new Date(now).toISOString()
273
+ .replace(/\.\d{3}Z$/, '')
274
+ .replace('T', '-')
275
+ .replace(/:/g, '');
276
+ const stem = path.basename(requestPath).replace(/\.json$/i, '');
277
+ let target = path.join(dir, `${stem}.corrupt-${stampText}.json`);
278
+ for (let n = 1; fsImpl.existsSync(target); n += 1) {
279
+ target = path.join(dir, `${stem}.corrupt-${stampText}-${n}.json`);
280
+ }
281
+ try {
282
+ fsImpl.renameSync(requestPath, target);
283
+ return { ok: true, from: requestPath, to: target };
284
+ } catch (error) {
285
+ return { ok: false, from: requestPath, error: error?.code ?? error?.message ?? String(error) };
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Read an existing request without ever overwriting it. `null` means "absent";
291
+ * any other failure returns a marker object so the caller can refuse to write
292
+ * (a corrupt or unreadable request is still someone's pending request).
293
+ */
294
+ function readRequestFile(fsImpl, requestPath) {
295
+ let raw;
296
+ try {
297
+ raw = fsImpl.readFileSync(requestPath, 'utf8');
298
+ } catch (error) {
299
+ if (error?.code === 'ENOENT') return null;
300
+ return { unreadable: true, code: error?.code ?? null };
301
+ }
302
+ try {
303
+ const parsed = JSON.parse(raw);
304
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
305
+ return { corrupt: true };
306
+ } catch {
307
+ return { corrupt: true };
308
+ }
309
+ }
310
+
311
+ /** Append exactly one JSON line; returns the line length or throws. */
312
+ export function appendAutoTruncateLog(memoryRoot, entry, options = {}) {
313
+ const { logDir, logPath } = autoTruncatePaths(memoryRoot);
314
+ fs.mkdirSync(logDir, { recursive: true });
315
+ const written = appendJsonlRotated(logPath, entry, normalizeLogRotation(options));
316
+ return { logPath, line: '', bytes: written.bytes, rotated: written.rotated, rotatedTo: written.rotatedTo };
317
+ }
318
+
319
+ /**
320
+ * Locate `<home>/sessions/<scope>/<id>/session.v4.jsonl.zstd`. The host event
321
+ * gives us an id, not a path; the plugin is root-scoped, so this scan replaces
322
+ * guessing a scope name.
323
+ */
324
+ export function findSessionFile(home, sessionId) {
325
+ if (typeof home !== 'string' || home === '' || typeof sessionId !== 'string') return null;
326
+ const sessionsRoot = path.join(home, 'sessions');
327
+ let scopes;
328
+ try {
329
+ scopes = fs.readdirSync(sessionsRoot, { withFileTypes: true });
330
+ } catch {
331
+ return null;
332
+ }
333
+ for (const scope of scopes) {
334
+ if (!scope.isDirectory()) continue;
335
+ const candidate = path.join(sessionsRoot, scope.name, sessionId, 'session.v4.jsonl.zstd');
336
+ try {
337
+ if (fs.statSync(candidate).isFile()) return candidate;
338
+ } catch {
339
+ /* not this scope */
340
+ }
341
+ }
342
+ return null;
343
+ }
344
+
345
+ function clockMs(now) {
346
+ const value = typeof now === 'function' ? now() : now;
347
+ if (value instanceof Date) return value.getTime();
348
+ const ms = Number(value);
349
+ return Number.isFinite(ms) ? ms : Date.now();
350
+ }
351
+
352
+ function percentileDrop(before, after) {
353
+ if (!before) return 0;
354
+ return Number((((before - after) / before) * 100).toFixed(2));
355
+ }
356
+
357
+ /**
358
+ * Create the per-plugin truncator. `onTurnEnd` is sync and never throws: the
359
+ * host calls it from the `session/event` feed, where an exception would be a
360
+ * host-level failure for a maintenance side task.
361
+ */
362
+ export function createAutoTruncator(options = {}) {
363
+ const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
364
+ ? options.memoryRoot.trim()
365
+ : null;
366
+ const home = options.home ?? null;
367
+ const config = normalizeAutoTruncateConfig(options.autoTruncate);
368
+ // 1.8.10: autoTruncate.tokensThreshold is the external-log notice line and no
369
+ // longer inherits fold.triggerTokens (the 350k model-context line). The 1.8.3
370
+ // mapping cut 350k-token logs every hour under heavy tool use (2026-11-26).
371
+ const now = options.now ?? Date.now;
372
+ const fsImpl = options.fs ?? fs;
373
+ // Written into the request so the orchestrator knows what to close, restart
374
+ // and verify. Inside Electron process.execPath IS the app; a test or dry run
375
+ // can override it. pluginDir is the package root (where scripts/ lives).
376
+ const appExe = config.appExe !== ''
377
+ ? config.appExe
378
+ : (typeof process.execPath === 'string' ? process.execPath : '');
379
+ const pluginDir = options.pluginDir
380
+ ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
381
+ const logger = options.logger && typeof options.logger.warn === 'function' ? options.logger : null;
382
+ const policyEnforceability = thresholdEnforceability();
383
+ if (logger && config.enabled) {
384
+ // 1.8.3: expose the policy-vs-enforceability boundary once per startup.
385
+ logger.warn(`[threshold-policy] ${THRESHOLD_POLICY_WARNING}`);
386
+ }
387
+ const logOptions = {
388
+ maxBytes: config.logMaxBytes,
389
+ maxAgeDays: config.logMaxAgeDays,
390
+ maxFiles: config.logMaxFiles,
391
+ rotateDaily: config.logRotateDaily,
392
+ };
393
+ const appendLog = (entry) => appendAutoTruncateLog(memoryRoot, entry, logOptions);
394
+
395
+ // Publish an initial status immediately so a panel can show mode=dryrun (and
396
+ // "no evaluation yet") before the first turn/end. A write failure only warns.
397
+ if (memoryRoot) {
398
+ try {
399
+ recordAutoTruncateStatus(memoryRoot, {
400
+ mode: config.mode,
401
+ enabled: config.enabled,
402
+ thresholds: {
403
+ tokensThreshold: config.tokensThreshold,
404
+ minTurns: config.minTurns,
405
+ keepTurns: config.keepTurns,
406
+ keepTokens: config.keepTokens,
407
+ boundaryRetries: config.boundaryRetries,
408
+ },
409
+ outcome: 'startup',
410
+ }, { now: clockMs(now) });
411
+ } catch (error) {
412
+ if (logger) logger.warn(`[auto-truncate] initial status write failed: ${error?.message ?? error}`);
413
+ }
414
+ }
415
+
416
+ const seen = new Map();
417
+ const foldWarnings = new Set();
418
+ const truncateWarnings = new Map();
419
+
420
+ function rememberTurn(sessionId, turn) {
421
+ seen.set(sessionId, turn);
422
+ while (seen.size > MAX_SEEN_SESSIONS) {
423
+ seen.delete(seen.keys().next().value);
424
+ }
425
+ }
426
+
427
+ function stateFor(sessionId) {
428
+ const state = readAutoTruncateState(memoryRoot);
429
+ return state.sessions?.[sessionId] ?? null;
430
+ }
431
+
432
+ function markEvaluated(sessionId, at, turn, estimate, outcome, policy = null) {
433
+ const state = readAutoTruncateState(memoryRoot);
434
+ state.sessions[sessionId] = {
435
+ lastEvaluatedAt: at,
436
+ lastTurn: turn ?? null,
437
+ tokens: estimate.tokens,
438
+ turns: estimate.turns,
439
+ mode: config.mode,
440
+ status: outcome,
441
+ ...(policy ? {
442
+ outputReserveMode: policy.outputReserveMode ?? 'normal',
443
+ outputReserveTokens: policy.outputReserveTokens ?? OUTPUT_RESERVE_NORMAL_TOKENS,
444
+ lastPolicyAction: policy.action ?? null,
445
+ } : {}),
446
+ };
447
+ writeAutoTruncateState(memoryRoot, state);
448
+ }
449
+
450
+ function baseEntry({ sessionId, sessionPath, at, estimate, threshold }) {
451
+ return {
452
+ time: new Date(at).toISOString(),
453
+ sessionId,
454
+ sessionPath,
455
+ mode: config.mode,
456
+ // 1.8.3 shared-window budget: input estimate, actual-output estimate (when
457
+ // supplied by the host) and the reserve used for this decision.
458
+ estimatedInputTokens: estimate.tokens,
459
+ estimatedOutputTokens: threshold.actualOutputTokens ?? null,
460
+ outputReserveTokens: threshold.reserveTokens ?? OUTPUT_RESERVE_NORMAL_TOKENS,
461
+ actual_output_tokens: threshold.actualOutputTokens ?? null,
462
+ finish_reason: threshold.finishReason ?? null,
463
+ truncated: threshold.truncated === true,
464
+ reserve_class: threshold.reserveMode ?? 'long',
465
+ fold_failed: threshold.foldFailureReason ?? null,
466
+ fold_busy: threshold.foldFailureReason === 'busy',
467
+ fold_retry_at: threshold.foldRetryAt ?? null,
468
+ fold_retry_turn: threshold.foldRetryTurn ?? null,
469
+ // Fold (host compaction) and truncate (direct cut) are separate events.
470
+ foldTriggered: threshold.foldTriggered === true,
471
+ foldBeforeTokens: estimate.tokens,
472
+ foldAfterTokens: null,
473
+ truncateReason: threshold.policyAction === 'handoff' ? threshold.policyReason : null,
474
+ truncateExecution: threshold.policyAction === 'handoff' ? 'NEXT_SAFE_OFFLINE' : null,
475
+ escalation_exit: threshold.policyAction === 'handoff' ? 'restart-or-external-visible-truncate' : null,
476
+ restart_required: threshold.policyAction === 'handoff',
477
+ escalation_round: threshold.escalationRound ?? null,
478
+ truncatePending: threshold.policyAction === 'handoff',
479
+ truncateHandoffLine: threshold.inputHardLimitTokens ?? null,
480
+ finishReason: typeof threshold.finishReason === 'string' ? threshold.finishReason : null,
481
+ truncated: threshold.truncated === true,
482
+ foldFailed: threshold.foldFailed === true,
483
+ foldFailureReason: threshold.foldFailureReason ?? null,
484
+ foldRetryNextTurn: threshold.foldRetryNextTurn === true,
485
+ truncateBeforeTokens: estimate.tokens,
486
+ truncateAfterTokens: null,
487
+ ...(threshold.policy ? { policy: threshold.policy } : {}),
488
+ ...(config.modeAlias ? { modeAlias: config.modeAlias } : {}),
489
+ estimate: {
490
+ tokens: estimate.tokens,
491
+ turns: estimate.turns,
492
+ events: estimate.events,
493
+ messages: estimate.messages,
494
+ userMessages: estimate.userMessages,
495
+ basis: AUTO_ESTIMATE_BASIS,
496
+ },
497
+ threshold,
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Evaluate one finished turn.
503
+ *
504
+ * @param {object} info
505
+ * @param {string} info.sessionId host session id (already lowercase)
506
+ * @param {number} [info.turn] `event.data.turn`
507
+ * @param {string} [info.sessionPath] explicit path (tests); otherwise resolved
508
+ * @returns {object} a small status record (never throws)
509
+ */
510
+ function evaluateOnTurnEnd(info = {}) {
511
+ const status = { status: 'skipped' };
512
+ try {
513
+ const sessionId = typeof info.sessionId === 'string' ? info.sessionId : '';
514
+ if (!config.enabled) return { ...status, reason: 'disabled' };
515
+ if (!memoryRoot) return { ...status, reason: 'no-memory-root' };
516
+ if (sessionId === '') return { ...status, reason: 'no-session-id' };
517
+
518
+ const turn = Number.isInteger(info.turn) ? info.turn : null;
519
+ // One turn, one evaluation: a repeated turn/end (host replay) costs
520
+ // nothing. Across restarts the cooldown is the next line of defence.
521
+ if (turn !== null && seen.get(sessionId) === turn) {
522
+ return { ...status, reason: 'duplicate-turn', turn };
523
+ }
524
+ if (turn !== null) rememberTurn(sessionId, turn);
525
+
526
+ const at = clockMs(now);
527
+ const prior = stateFor(sessionId);
528
+ const cooldownMs = config.cooldownMinutes * 60_000;
529
+ if (prior && Number.isFinite(prior.lastEvaluatedAt) && at - prior.lastEvaluatedAt < cooldownMs) {
530
+ return {
531
+ ...status,
532
+ reason: 'cooldown',
533
+ retryAfterMs: cooldownMs - (at - prior.lastEvaluatedAt),
534
+ };
535
+ }
536
+
537
+ const sessionPath = info.sessionPath ?? findSessionFile(home, sessionId);
538
+ if (!sessionPath) return { ...status, reason: 'session-file-not-found' };
539
+
540
+ let inflight = null;
541
+ try {
542
+ inflight = readInflight(sessionPath);
543
+ } catch {
544
+ // A corrupt record means "someone may be writing"; skip rather than
545
+ // race a half-finished operation.
546
+ return { ...status, reason: 'inflight-unreadable' };
547
+ }
548
+ if (inflight) return { ...status, reason: 'inflight' };
549
+
550
+ const buf = fsImpl.readFileSync(sessionPath);
551
+ const parsed = parseSession(buf);
552
+ const estimate = sessionEstimate(parsed);
553
+ const actualOutputTokens = Number.isFinite(Number(info.actualOutputTokens)) && Number(info.actualOutputTokens) >= 0
554
+ ? Number(info.actualOutputTokens)
555
+ : null;
556
+ const longOutput = prior?.outputReserveMode === 'long' ? true : null;
557
+ const foldFailure = info.foldOutcome ? classifyFoldFailure(info.foldOutcome) : null;
558
+ const foldRetry = foldFailure ? foldRetrySchedule({ turn: Number.isInteger(turn) ? turn : 0, now: at }) : null;
559
+ const fold = evaluateFoldTrigger({ inputTokens: estimate.tokens });
560
+ const policy = evaluateTruncateBudget({
561
+ inputTokens: estimate.tokens,
562
+ actualOutputTokens,
563
+ longOutput,
564
+ contextWindowTokens: CONTEXT_WINDOW_TOKENS,
565
+ safetyTokens: SAFETY_TOKENS,
566
+ });
567
+ const requiresCut = policy.action === 'handoff';
568
+ let truncateWarningRound = 0;
569
+ if (requiresCut) {
570
+ truncateWarningRound = (truncateWarnings.get(sessionId) ?? 0) + 1;
571
+ truncateWarnings.set(sessionId, truncateWarningRound);
572
+ }
573
+ if (foldFailure && logger) {
574
+ logger.warn(`[fold-policy] fold ${foldFailure.reason}: retry next turn (not silent)`);
575
+ }
576
+ if (fold.triggered && logger) {
577
+ // Fold needs host compaction; the plugin only records/warns here.
578
+ logger.warn(`[fold-policy] input=${fold.inputTokens} >= fold.triggerTokens=${fold.triggerTokens}; `
579
+ + 'host compaction is required, but this plugin cannot force a fold in the current pre-step');
580
+ }
581
+ if (requiresCut && logger && (truncateWarningRound === 1 || truncateWarningRound % 3 === 0)) {
582
+ logger.warn(`[truncate-policy] 升级出口/重启建议:必须重启或外部执行 visible-truncate; `
583
+ + `reason=${policy.reason} input=${policy.inputTokens} reserve=${policy.reserveTokens} `
584
+ + `safety=${policy.safetyTokens} round=${truncateWarningRound} (NEXT_SAFE_OFFLINE; no in-turn block)`);
585
+ }
586
+ const threshold = {
587
+ tokens: config.tokensThreshold,
588
+ minTurns: config.minTurns,
589
+ // 1.8.3 shared-window budget: policy compact at 350K and the hard
590
+ // input+reserve+safety line both trigger; pure output-over-reserve only
591
+ // warns and raises the next-turn reserve.
592
+ exceeded: (estimate.tokens >= config.tokensThreshold && estimate.turns > config.minTurns) || requiresCut,
593
+ actualOutputTokens,
594
+ reserveTokens: policy.outputReserveTokens,
595
+ reserveMode: policy.reserveMode ?? 'long',
596
+ inputHardLimitTokens: policy.inputHardLimitTokens,
597
+ policyAction: policy.action,
598
+ policyReason: policy.reason,
599
+ escalationRound: truncateWarningRound || null,
600
+ escalationExit: requiresCut ? 'restart-or-external-visible-truncate' : null,
601
+ foldTriggered: fold.triggered,
602
+ finishReason: typeof info.finishReason === 'string' ? info.finishReason : null,
603
+ truncated: info.truncated === true,
604
+ foldFailed: foldFailure?.foldFailed === true,
605
+ foldFailureReason: foldFailure?.reason ?? null,
606
+ foldRetryNextTurn: foldFailure?.retryNextTurn === true,
607
+ foldRetryAt: foldRetry?.retryAt ?? null,
608
+ foldRetryTurn: foldRetry?.retryTurn ?? null,
609
+ outputOverReserve: policy.outputOverReserve,
610
+ nextReserveMode: policy.reserveMode === 'long' || policy.action === 'switch-long-output-or-segment' ? 'long' : 'normal',
611
+ policy: {
612
+ action: policy.action,
613
+ reason: policy.reason,
614
+ inputTokens: policy.inputTokens,
615
+ reserveTokens: policy.reserveTokens,
616
+ inputHardLimitTokens: policy.inputHardLimitTokens,
617
+ safetyTokens: policy.safetyTokens,
618
+ outputOverReserve: policy.outputOverReserve,
619
+ enforced: policyEnforceability.enforced,
620
+ hostMaxTokensConfigurable: policyEnforceability.hostMaxTokensConfigurable,
621
+ },
622
+ };
623
+
624
+ // Below the threshold the evaluation still consumes the cooldown window:
625
+ // the spec's debounce is per-session evaluation, not per-action.
626
+ markEvaluated(sessionId, at, turn, estimate, threshold.exceeded ? 'over' : 'below', {
627
+ outputReserveMode: threshold.nextReserveMode,
628
+ outputReserveTokens: policy.outputReserveTokens,
629
+ action: policy.action,
630
+ });
631
+ if (actualOutputTokens !== null && (policy.action === 'switch-long-output-or-segment' || policy.outputOverReserve || policy.action === 'handoff')) {
632
+ // 1.8.3: never silently ignore an actual output that outgrew its
633
+ // reserve; the next turn uses the long-output reserve.
634
+ if (logger) {
635
+ logger.warn(`[threshold-policy] actual_output=${actualOutputTokens} reserve=${policy.outputReserveTokens} `
636
+ + `input=${policy.inputTokens}; next-turn reserve=long (${INPUT_COMPACT_AT_TOKENS / 1000}K compact line); `
637
+ + `action=${policy.action}`);
638
+ }
639
+ }
640
+ if (!threshold.exceeded) {
641
+ return {
642
+ ...status,
643
+ ...(foldFailure ? { status: 'fold-warning', foldFailure } : {}),
644
+ ...(policy.action === 'switch-long-output-or-segment' ? { status: 'policy-warning' } : {}),
645
+ reason: policy.action === 'switch-long-output-or-segment' ? 'actual-output-over-reserve' : 'below-threshold',
646
+ estimate, threshold, policy,
647
+ };
648
+ }
649
+
650
+ const common = baseEntry({ sessionId, sessionPath, at, estimate, threshold });
651
+
652
+ if (config.mode === 'log') {
653
+ const plan = planVisibleTruncation(parsed, {
654
+ keepTurns: config.keepTurns,
655
+ keepTokens: config.keepTokens,
656
+ firstUserCapChars: config.firstUserCapChars,
657
+ });
658
+ const entry = {
659
+ ...common,
660
+ action: plan.needed ? 'planned' : 'none',
661
+ session: {
662
+ origin: parsed.header?.origin ?? null,
663
+ parentSession: parsed.header?.parentSession ?? null,
664
+ },
665
+ plan: plan.needed
666
+ ? {
667
+ needed: true,
668
+ feasible: plan.feasible,
669
+ cut: {
670
+ turn: plan.cutTurn,
671
+ startSeq: plan.cutTurnStartSeq,
672
+ droppedTurns: plan.droppedTurnCount,
673
+ keptTurns: plan.keptTurnCount,
674
+ },
675
+ projected: {
676
+ dropEvents: plan.dropped.events,
677
+ dropTokens: plan.dropped.tokens,
678
+ dropPercent: percentileDrop(plan.original.tokens, plan.original.tokens - plan.dropped.tokens),
679
+ // 0.8.0-rc.11: this is the estimate of the *rewritten* log
680
+ // (head + archive card + capped carry + kept turns), not
681
+ // original minus dropped, which used to omit all synthetics.
682
+ afterTokensEstimate: plan.budget?.afterTokens
683
+ ?? Math.max(0, plan.original.tokens - plan.dropped.tokens),
684
+ keepTokens: plan.keepTokens,
685
+ fits: plan.budget?.fits ?? null,
686
+ },
687
+ budget: plan.budget ?? null,
688
+ firstUserMessage: plan.firstUserMessage,
689
+ firstUserCarry: plan.firstUserCarry ?? null,
690
+ firstUserMessageNote: plan.firstUserMessageNote ?? null,
691
+ infeasible: plan.infeasible ?? null,
692
+ }
693
+ : { needed: false, reason: plan.reason },
694
+ };
695
+ const written = appendLog(entry);
696
+ return { status: 'logged', action: entry.action, logPath: written.logPath, entry };
697
+ }
698
+
699
+ if (config.mode === 'dryrun') {
700
+ const result = truncateVisibleSession(sessionPath, {
701
+ dryRun: true,
702
+ keepTurns: config.keepTurns,
703
+ keepTokens: config.keepTokens,
704
+ firstUserCapChars: config.firstUserCapChars,
705
+ boundaryRetries: config.boundaryRetries,
706
+ now: at,
707
+ // Dry runs do not archive, so no diag row is written here; passing the
708
+ // root keeps the option surface uniform for the real CLI/manual path.
709
+ memoryRoot,
710
+ turn,
711
+ logger,
712
+ diagOptions: logOptions,
713
+ });
714
+ if (result.feasible === false) {
715
+ // 0.8.0-rc.11: an infeasible dry run is a result, not an exception.
716
+ // It must appear in auto-truncate.log with the attempts, otherwise a
717
+ // failing planner is indistinguishable from "nothing to do".
718
+ const entry = {
719
+ ...common,
720
+ action: 'dryrun-infeasible',
721
+ dryRun: true,
722
+ feasible: false,
723
+ code: result.code,
724
+ reason: result.reason,
725
+ attempts: result.attempts,
726
+ limit: result.limit ?? result.plan?.infeasible?.limit ?? null,
727
+ session: {
728
+ origin: parsed.header?.origin ?? null,
729
+ parentSession: parsed.header?.parentSession ?? null,
730
+ },
731
+ plan: { needed: true, feasible: false, reason: result.reason },
732
+ wroteSessionFile: false,
733
+ };
734
+ const written = appendLog(entry);
735
+ return {
736
+ status: 'dryrun-infeasible',
737
+ action: entry.action,
738
+ code: entry.code,
739
+ logPath: written.logPath,
740
+ entry,
741
+ limit: entry.limit ?? null,
742
+ };
743
+ }
744
+ const entry = {
745
+ ...common,
746
+ action: result.needed ? 'dryrun-planned' : 'none',
747
+ dryRun: true,
748
+ feasible: true,
749
+ session: {
750
+ origin: parsed.header?.origin ?? null,
751
+ parentSession: parsed.header?.parentSession ?? null,
752
+ },
753
+ plan: result.needed
754
+ ? {
755
+ needed: true,
756
+ feasible: true,
757
+ cut: result.cut,
758
+ dropped: result.dropped,
759
+ kept: result.kept,
760
+ after: result.after,
761
+ budget: result.budget ?? null,
762
+ attempts: result.attempts ?? null,
763
+ droppedTurns: result.droppedTurns?.length ?? 0,
764
+ keptTurnsDetail: result.keptTurns?.length ?? 0,
765
+ archivePath: result.archivePath,
766
+ firstUserMessage: result.firstUserMessage ?? null,
767
+ firstUserCarry: result.firstUserCarry ?? null,
768
+ firstUserMessageNote: result.firstUserMessageNote ?? null,
769
+ }
770
+ : { needed: false, reason: result.reason ?? null },
771
+ wroteSessionFile: false,
772
+ };
773
+ const written = appendLog(entry);
774
+ return { status: 'dryrun', action: entry.action, logPath: written.logPath, entry };
775
+ }
776
+
777
+ // request: plan, then hand the actual file operation to an out-of-app
778
+ // orchestrator. Nothing below may open the session log for writing: the
779
+ // running host still holds the old sequence in memory, so an in-process
780
+ // rewrite would corrupt its next append (0.7.0 measured 77 -> 3532).
781
+ // The turn/end snapshot above was taken a few milliseconds before this
782
+ // point, and the app keeps appending right after turn/end: a VM run read
783
+ // 295 events / 91 messages when the request was written, the app appended
784
+ // seq 295-297 eight milliseconds later, and the watchdog then cut the 298
785
+ // event file, so the request's estimate and plan were three events short of
786
+ // what actually ran. Re-read the file once, here, and build both from the
787
+ // same snapshot the watchdog will meet. One extra I/O buys a plan that
788
+ // cannot be stale by construction.
789
+ let snapshotParsed = parsed;
790
+ let snapshotEstimate = estimate;
791
+ let snapshotAt = new Date(at).toISOString();
792
+ let snapshotSource = 'turn-end';
793
+ try {
794
+ const freshParsed = parseSession(fsImpl.readFileSync(sessionPath));
795
+ if (freshParsed.header?.id === parsed.header?.id) {
796
+ snapshotParsed = freshParsed;
797
+ snapshotEstimate = sessionEstimate(freshParsed);
798
+ snapshotAt = new Date(clockMs(now)).toISOString();
799
+ snapshotSource = 'pre-request';
800
+ }
801
+ } catch (error) {
802
+ // A failed re-read must not invent numbers: keep the turn/end snapshot
803
+ // and say which one the request was built from.
804
+ snapshotSource = `turn-end (re-read failed: ${error?.code ?? error?.message ?? String(error)})`;
805
+ }
806
+
807
+ const plan = planVisibleTruncation(snapshotParsed, {
808
+ keepTurns: config.keepTurns,
809
+ keepTokens: config.keepTokens,
810
+ firstUserCapChars: config.firstUserCapChars,
811
+ });
812
+ const sessionInfo = {
813
+ origin: snapshotParsed.header?.origin ?? parsed.header?.origin ?? null,
814
+ parentSession: snapshotParsed.header?.parentSession ?? parsed.header?.parentSession ?? null,
815
+ };
816
+ const { requestPath } = autoTruncatePaths(memoryRoot);
817
+
818
+ // Single-flight: a request already waiting for the orchestrator is never
819
+ // overwritten. The log records the pending one, then this evaluation ends.
820
+ // A corrupt request (half-written JSON from an older build, a killed
821
+ // writer) is quarantined and replaced: one bad byte must not block every
822
+ // future evaluation forever.
823
+ let existing = readRequestFile(fsImpl, requestPath);
824
+ let quarantine = null;
825
+ if (existing !== null && existing.corrupt) {
826
+ quarantine = quarantineRequestFile(fsImpl, requestPath, at);
827
+ if (quarantine.ok) existing = null;
828
+ }
829
+ if (existing !== null) {
830
+ const entry = {
831
+ ...common,
832
+ action: 'request-pending',
833
+ requestPending: true,
834
+ requestPath,
835
+ requestId: typeof existing.requestId === 'string' ? existing.requestId : null,
836
+ pendingAt: typeof existing.at === 'string' ? existing.at : null,
837
+ pendingState: existing.corrupt
838
+ ? 'corrupt'
839
+ : (existing.unreadable ? 'unreadable' : 'valid'),
840
+ quarantine: quarantine && !quarantine.ok ? quarantine : null,
841
+ session: sessionInfo,
842
+ plan: plan.needed
843
+ ? {
844
+ needed: true,
845
+ cut: {
846
+ turn: plan.cutTurn,
847
+ startSeq: plan.cutTurnStartSeq,
848
+ droppedTurns: plan.droppedTurnCount,
849
+ keptTurns: plan.keptTurnCount,
850
+ },
851
+ projected: {
852
+ dropEvents: plan.dropped.events,
853
+ dropTokens: plan.dropped.tokens,
854
+ afterTokensEstimate: plan.budget?.afterTokens
855
+ ?? Math.max(0, plan.original.tokens - plan.dropped.tokens),
856
+ },
857
+ }
858
+ : { needed: false, reason: plan.reason },
859
+ wroteSessionFile: false,
860
+ };
861
+ const written = appendLog(entry);
862
+ return {
863
+ status: 'request-pending',
864
+ action: entry.action,
865
+ requestId: entry.requestId,
866
+ requestPath,
867
+ logPath: written.logPath,
868
+ entry,
869
+ };
870
+ }
871
+
872
+ // 0.8.0-rc.11: verify the cut by building it before writing a request.
873
+ // rc.10 wrote the request from a plan that could not be stabilized, and
874
+ // the failure only surfaced later (or was swallowed entirely). A request
875
+ // now carries a cut that has already encoded cleanly, or a readable
876
+ // `request-infeasible` log line instead of a silently impossible plan.
877
+ const resolved = resolveVisibleCut(snapshotParsed, {
878
+ keepTurns: config.keepTurns,
879
+ keepTokens: config.keepTokens,
880
+ firstUserCapChars: config.firstUserCapChars,
881
+ boundaryRetries: config.boundaryRetries,
882
+ archivePath: nextArchivePath(path.resolve(sessionPath), at),
883
+ now: at,
884
+ });
885
+
886
+ if (!resolved.needed) {
887
+ const entry = {
888
+ ...common,
889
+ action: 'none',
890
+ session: sessionInfo,
891
+ plan: { needed: false, reason: resolved.plan?.reason ?? plan.reason },
892
+ pendingState: quarantine?.ok ? 'quarantined' : undefined,
893
+ quarantinedFile: quarantine?.ok ? quarantine.to : undefined,
894
+ wroteSessionFile: false,
895
+ };
896
+ const written = appendLog(entry);
897
+ return {
898
+ status: 'request-none',
899
+ action: entry.action,
900
+ requestPath,
901
+ logPath: written.logPath,
902
+ entry,
903
+ };
904
+ }
905
+
906
+ if (!resolved.feasible) {
907
+ const entry = {
908
+ ...common,
909
+ action: 'request-infeasible',
910
+ feasible: false,
911
+ code: resolved.code,
912
+ reason: resolved.reason,
913
+ attempts: resolved.attempts,
914
+ requestPath,
915
+ session: sessionInfo,
916
+ plan: { needed: true, feasible: false, reason: resolved.reason },
917
+ pendingState: quarantine?.ok ? 'quarantined' : undefined,
918
+ quarantinedFile: quarantine?.ok ? quarantine.to : undefined,
919
+ wroteSessionFile: false,
920
+ };
921
+ const written = appendLog(entry);
922
+ return {
923
+ status: 'request-infeasible',
924
+ action: entry.action,
925
+ code: entry.code,
926
+ requestPath,
927
+ logPath: written.logPath,
928
+ entry,
929
+ };
930
+ }
931
+
932
+ const verified = resolved.plan;
933
+ const verifiedAfterTokens = resolved.built?.tokens
934
+ ?? verified.budget?.afterTokens
935
+ ?? Math.max(0, verified.original.tokens - verified.dropped.tokens);
936
+
937
+ const request = {
938
+ version: 1,
939
+ requestId: crypto.randomUUID(),
940
+ at: new Date(at).toISOString(),
941
+ sessionPath: path.resolve(sessionPath),
942
+ sessionId,
943
+ reason: 'tokens-over-threshold',
944
+ estimate: {
945
+ tokens: snapshotEstimate.tokens,
946
+ threshold: threshold.tokens,
947
+ events: snapshotEstimate.events,
948
+ messages: snapshotEstimate.messages,
949
+ source: snapshotSource,
950
+ },
951
+ plan: {
952
+ cut: verified.cutTurn,
953
+ dropped: verified.dropped.events,
954
+ kept: verified.kept.events,
955
+ keepTurns: config.keepTurns,
956
+ keepTokens: config.keepTokens,
957
+ firstUserCapChars: verified.firstUserCapChars,
958
+ attempts: resolved.attempts.length,
959
+ feasible: true,
960
+ // The estimate of the rewritten log (head + archive card + capped
961
+ // carry + kept turns), which is what the next turn will actually pay.
962
+ projectedTokens: verifiedAfterTokens,
963
+ // What the plan was computed from. The watchdog compares these two
964
+ // against the file it actually cut and reports any difference in its
965
+ // result JSON, so a plan that aged can never look like a match.
966
+ snapshotEvents: snapshotEstimate.events,
967
+ snapshotMessages: snapshotEstimate.messages,
968
+ snapshotAt,
969
+ },
970
+ app: {
971
+ exe: appExe,
972
+ profile: config.profile,
973
+ },
974
+ pluginDir,
975
+ };
976
+
977
+ try {
978
+ writeRequestAtomic(fsImpl, requestPath, request);
979
+ } catch (error) {
980
+ const failure = {
981
+ ...common,
982
+ action: 'request-failed',
983
+ code: error?.code ?? 'AUTO_REQUEST_WRITE',
984
+ message: error?.message ?? String(error),
985
+ requestPath,
986
+ pendingState: quarantine?.ok ? 'quarantined' : undefined,
987
+ quarantinedFile: quarantine?.ok ? quarantine.to : undefined,
988
+ wroteSessionFile: false,
989
+ };
990
+ try {
991
+ const written = appendLog(failure);
992
+ return { status: 'request-failed', code: failure.code, logPath: written.logPath, entry: failure };
993
+ } catch (logError) {
994
+ return { status: 'request-failed', code: failure.code, logError: logError.message };
995
+ }
996
+ }
997
+
998
+ const entry = {
999
+ ...common,
1000
+ action: 'request-written',
1001
+ requestId: request.requestId,
1002
+ requestPath,
1003
+ request,
1004
+ pendingState: quarantine?.ok ? 'quarantined' : undefined,
1005
+ quarantinedFile: quarantine?.ok ? quarantine.to : undefined,
1006
+ session: sessionInfo,
1007
+ plan: {
1008
+ needed: true,
1009
+ snapshot: {
1010
+ source: snapshotSource,
1011
+ at: snapshotAt,
1012
+ events: snapshotEstimate.events,
1013
+ messages: snapshotEstimate.messages,
1014
+ },
1015
+ cut: {
1016
+ turn: verified.cutTurn,
1017
+ startSeq: verified.cutTurnStartSeq,
1018
+ droppedTurns: verified.droppedTurnCount,
1019
+ keptTurns: verified.keptTurnCount,
1020
+ },
1021
+ projected: {
1022
+ dropEvents: verified.dropped.events,
1023
+ dropTokens: verified.dropped.tokens,
1024
+ dropPercent: percentileDrop(verified.original.tokens, verifiedAfterTokens),
1025
+ afterTokensEstimate: verifiedAfterTokens,
1026
+ },
1027
+ },
1028
+ wroteSessionFile: false,
1029
+ };
1030
+ const written = appendLog(entry);
1031
+ return {
1032
+ status: 'request-written',
1033
+ action: entry.action,
1034
+ requestId: request.requestId,
1035
+ requestPath,
1036
+ logPath: written.logPath,
1037
+ entry,
1038
+ };
1039
+ } catch (error) {
1040
+ // 0.8.0-rc.11: an unexpected failure is a recorded outcome now. rc.10
1041
+ // returned {status:'error'} to a caller that ignored it, and wrote
1042
+ // nothing to auto-truncate.log — so a broken planner looked exactly like
1043
+ // a quiet session. This never throws: if the log itself cannot be
1044
+ // written, the code/message still travel in the return value.
1045
+ const code = error?.code ?? AUTO_TRUNCATE_ERRORS.EVALUATE;
1046
+ const message = error?.message ?? String(error);
1047
+ const entry = {
1048
+ time: new Date(clockMs(now)).toISOString(),
1049
+ sessionId: info?.sessionId ?? null,
1050
+ sessionPath: info?.sessionPath ?? null,
1051
+ mode: config.mode,
1052
+ action: 'error',
1053
+ code,
1054
+ message,
1055
+ details: error?.details ?? null,
1056
+ attempts: error?.attempts ?? error?.details?.attempts ?? null,
1057
+ wroteSessionFile: false,
1058
+ };
1059
+ let logPath = null;
1060
+ let logError = null;
1061
+ if (memoryRoot) {
1062
+ try {
1063
+ logPath = appendLog(entry).logPath;
1064
+ } catch (writeError) {
1065
+ logError = writeError?.message ?? String(writeError);
1066
+ }
1067
+ }
1068
+ return {
1069
+ status: 'error',
1070
+ reason: 'exception',
1071
+ code,
1072
+ message,
1073
+ entry,
1074
+ logPath,
1075
+ ...(logError ? { logError } : {}),
1076
+ };
1077
+ }
1078
+ }
1079
+
1080
+ function publishStatus(result, info) {
1081
+ if (!memoryRoot) return null;
1082
+ const entry = result?.entry ?? null;
1083
+ const status = result?.status ?? 'unknown';
1084
+ const action = entry?.action ?? null;
1085
+ const overExceeded = Boolean(result?.threshold?.exceeded || entry?.threshold?.exceeded);
1086
+ const infeasible = /infeasible/u.test(status) || /infeasible/u.test(action ?? '');
1087
+ const error = status === 'error' || action === 'error' || status === 'request-failed' || action === 'request-failed';
1088
+ const skipped = status === 'skipped';
1089
+ const delta = { evaluations: skipped ? 0 : 1 };
1090
+ if (skipped) delta.skipped = 1;
1091
+ else if (overExceeded) delta.over = 1;
1092
+ else if (infeasible) delta.infeasible = 1;
1093
+ else if (error) delta.error = 1;
1094
+ else if (status === 'logged') delta.logged = 1;
1095
+ else if (status === 'dryrun') delta.dryrun = 1;
1096
+ else if (status === 'request-written') delta.requestWritten = 1;
1097
+ else if (status === 'request-pending') delta.requestPending = 1;
1098
+ else if (status === 'request-none') delta.noop = 1;
1099
+ if (infeasible) delta.infeasible = 1;
1100
+ if (error) delta.error = 1;
1101
+
1102
+ const at = new Date(clockMs(now)).toISOString();
1103
+ const overSample = overExceeded ? {
1104
+ sessionId: info?.sessionId ?? null,
1105
+ tokens: entry?.estimate?.tokens ?? result?.estimate?.tokens ?? null,
1106
+ turns: entry?.estimate?.turns ?? result?.estimate?.turns ?? null,
1107
+ turn: Number.isInteger(info?.turn) ? info.turn : entry?.lastTurn ?? null,
1108
+ at,
1109
+ } : null;
1110
+ const lastError = error ? {
1111
+ at,
1112
+ sessionId: info?.sessionId ?? null,
1113
+ code: result?.code ?? entry?.code ?? 'AUTO_EVALUATE_FAILED',
1114
+ message: String(result?.message ?? entry?.message ?? result?.reason ?? 'error').slice(0, 500),
1115
+ } : null;
1116
+ const lastInfeasible = infeasible ? {
1117
+ at,
1118
+ sessionId: info?.sessionId ?? null,
1119
+ code: result?.code ?? entry?.code ?? 'AUTO_INFEASIBLE',
1120
+ reason: String(result?.reason ?? entry?.reason ?? entry?.message ?? 'infeasible').slice(0, 500),
1121
+ limit: result?.limit ?? entry?.limit ?? null,
1122
+ } : null;
1123
+ const warning = error
1124
+ ? `evaluation error: ${lastError.code} ${lastError.message}`
1125
+ : (infeasible
1126
+ ? `infeasible cut: ${lastInfeasible.code} ${lastInfeasible.reason}`
1127
+ : (overExceeded
1128
+ ? `session ${info?.sessionId ?? '?'} is over threshold (${result?.threshold?.tokens ?? entry?.threshold?.tokens ?? '?'} tokens)`
1129
+ : null));
1130
+ let published = null;
1131
+ try {
1132
+ published = recordAutoTruncateStatus(memoryRoot, {
1133
+ mode: config.mode,
1134
+ enabled: config.enabled,
1135
+ thresholds: {
1136
+ tokensThreshold: config.tokensThreshold,
1137
+ minTurns: config.minTurns,
1138
+ keepTurns: config.keepTurns,
1139
+ keepTokens: config.keepTokens,
1140
+ boundaryRetries: config.boundaryRetries,
1141
+ },
1142
+ delta,
1143
+ outcome: result?.status ?? 'unknown',
1144
+ overSample,
1145
+ error: lastError,
1146
+ infeasible: lastInfeasible,
1147
+ warning,
1148
+ }, { now: clockMs(now) });
1149
+ } catch (statusError) {
1150
+ if (logger) logger.warn(`[auto-truncate] status write failed: ${statusError?.message ?? statusError}`);
1151
+ }
1152
+ if (warning && logger) logger.warn(`[auto-truncate] ${warning}`);
1153
+ return published;
1154
+ }
1155
+
1156
+ // Public entry: evaluate, then always publish the operator-visible status.
1157
+ // evaluateOnTurnEnd never throws; the status publish is also guarded so a
1158
+ // broken status file can never fail the host's turn/end feed.
1159
+ function onTurnEnd(info = {}) {
1160
+ const result = evaluateOnTurnEnd(info);
1161
+ try {
1162
+ publishStatus(result, info);
1163
+ } catch (error) {
1164
+ if (logger) logger.warn(`[auto-truncate] status publish failed: ${error?.message ?? error}`);
1165
+ }
1166
+ return result;
1167
+ }
1168
+
1169
+ return {
1170
+ config,
1171
+ onTurnEnd,
1172
+ evaluate: onTurnEnd,
1173
+ logPath: memoryRoot ? autoTruncatePaths(memoryRoot).logPath : null,
1174
+ statePath: memoryRoot ? autoTruncatePaths(memoryRoot).statePath : null,
1175
+ requestPath: memoryRoot ? autoTruncatePaths(memoryRoot).requestPath : null,
1176
+ statusPath: memoryRoot ? path.join(memoryRoot, '.longlive', 'auto-truncate-status.json') : null,
1177
+ appExe,
1178
+ pluginDir,
1179
+ logger,
1180
+ };
1181
+ }