@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,779 @@
1
+ // src/memory/working-frame.js — v2.6.4 §14.2:连续性最小集(working-frame)
2
+ //
3
+ // 用途:同一话题的连续追问时,把「当前工作焦点」压成 ≤300 字的注入块,
4
+ // 放在 pre-step 注入顺序的 working 位:**[boot, shared, working, recall]**。
5
+ //
6
+ // 文件:<memoryRoot>/.longlive/working/<sessionId>.json(原子写 tmp→rename)
7
+ // <memoryRoot>/.longlive/working/archive/<sessionId>-<frameNo>.json(旧帧,不删)
8
+ // <memoryRoot>/.longlive/working/audit.jsonl(rollback / stale / topic-switch 审计)
9
+ //
10
+ // 时间纪律(复用 Gate-1 P1-2):
11
+ // * TTL 默认 30min(1800000ms),用**单调时钟**计算 elapsed:回拨/前跳都不改变 TTL;
12
+ // * 持久化 `wallWatermarkMs`;检测到墙钟回拨(now + 容差 < watermark)→ fail closed
13
+ // `E_CLOCK_ROLLBACK`(不注入 + 审计),绝不把过期帧当有效帧。
14
+ // * 过期 → 不注入、不删除,帧标 `state:"stale"`(审计可查)。
15
+
16
+ import crypto from 'node:crypto';
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+
20
+ import { stableStringify } from '../codec.js';
21
+ import { acquireLease, releaseLease } from './lock.js';
22
+ import {
23
+ AUTO_TEXT_MARK,
24
+ insertionIndex,
25
+ isHumanMessage,
26
+ isInjectedMessage,
27
+ textOfMessage,
28
+ } from '../identity/inject-position.js';
29
+ import {
30
+ assertFrameReadable,
31
+ attachFrameSubject,
32
+ normalizeRoleSubject,
33
+ verifyProtectedFile,
34
+ writeProtectedJson,
35
+ } from '../role/writeprotect.js';
36
+ import { appendGateLog } from '../recall/gate-log.mjs';
37
+
38
+ export const FRAME_SCHEMA = 'working-frame/v1';
39
+ export const FRAME_TTL_MS = 30 * 60 * 1000;
40
+ export const TOPIC_SIMILARITY_THRESHOLD = 0.35;
41
+ export const INJECTION_ORDER = Object.freeze(['boot', 'shared', 'working', 'recall']);
42
+ export const CLOCK_TOLERANCE_MS = 5000;
43
+
44
+ // —— D12 工作帧四字段(§4 ①;阈值只来自计划:80/80/5/80/540/300/4 KiB/256 KiB)——
45
+ export const WORKING_FIELDS = Object.freeze(['lastUserTask', 'nextStep', 'touchedFiles', 'lastDecision']);
46
+ export const WORKING_FIELD_MAX_CHARS = 80;
47
+ export const WORKING_TOUCHED_FILES_MAX = 5;
48
+ export const WORKING_TOUCHED_TOTAL_CHARS = 300;
49
+ export const WORKING_FOCUS_TOTAL_CHARS = 540;
50
+ export const WORKING_INJECT_MAX_CHARS = 300;
51
+ export const WORKING_UNSET = Object.freeze({ unset: true });
52
+ export const WORKING_AUDIT_MIGRATE_BYTES = 256 * 1024;
53
+ export const WORKING_AUDIT_ROTATE_MAX = 3;
54
+
55
+ export class WorkingFrameError extends Error {
56
+ constructor(code, message, detail = undefined) {
57
+ super(message);
58
+ this.name = 'WorkingFrameError';
59
+ this.code = code;
60
+ if (detail !== undefined) this.detail = detail;
61
+ }
62
+ }
63
+
64
+ export function workingDirOf(memoryRoot) {
65
+ const root = path.resolve(String(memoryRoot ?? ''));
66
+ return {
67
+ root,
68
+ dir: path.join(root, '.longlive', 'working'),
69
+ archiveDir: path.join(root, '.longlive', 'working', 'archive'),
70
+ audit: path.join(root, '.longlive', 'working', 'audit.jsonl'),
71
+ };
72
+ }
73
+
74
+ export function framePathOf(memoryRoot, sessionId) {
75
+ return path.join(workingDirOf(memoryRoot).dir, `${safeSessionId(sessionId)}.json`);
76
+ }
77
+
78
+ function safeSessionId(sessionId) {
79
+ const original = String(sessionId ?? '');
80
+ const raw = original.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 160);
81
+ if (raw === '') throw new WorkingFrameError('E_SESSION_ID', 'working-frame requires sessionId');
82
+ // EA-14: sanitization must not collide different sessions (sess@1 vs sess_1).
83
+ if (raw !== original) {
84
+ const digest = crypto.createHash('sha1').update(original, 'utf8').digest('hex').slice(0, 10);
85
+ return `${raw.slice(0, 140)}_${digest}`;
86
+ }
87
+ return raw;
88
+ }
89
+
90
+ function sha1Short(text) {
91
+ return crypto.createHash('sha1').update(String(text), 'utf8').digest('hex').slice(0, 12);
92
+ }
93
+
94
+ function nowMs(now) {
95
+ const value = typeof now === 'function' ? now() : new Date();
96
+ return value instanceof Date ? value.getTime() : Number(value);
97
+ }
98
+
99
+ function nowIso(now) {
100
+ return new Date(nowMs(now)).toISOString();
101
+ }
102
+
103
+ function writeAtomic(file, content) {
104
+ fs.mkdirSync(path.dirname(file), { recursive: true });
105
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
106
+ fs.writeFileSync(tmp, content, 'utf8');
107
+ fs.renameSync(tmp, file);
108
+ }
109
+
110
+ /** CJK bigrams + ASCII words + version tokens. */
111
+ export function tokenizeFocus(value) {
112
+ const text = Array.isArray(value) ? value.join(' ') : String(value ?? '');
113
+ const tokens = new Set();
114
+ for (const word of text.toLowerCase().match(/[a-z0-9][a-z0-9_.-]*/g) ?? []) tokens.add(word);
115
+ for (const run of text.match(/[\u3400-\u4dbf\u4e00-\u9fff]+/g) ?? []) {
116
+ const chars = Array.from(run);
117
+ if (chars.length === 1) tokens.add(chars[0]);
118
+ for (let i = 0; i + 1 < chars.length; i += 1) tokens.add(chars[i] + chars[i + 1]);
119
+ }
120
+ return [...tokens];
121
+ }
122
+
123
+ export function jaccardSimilarity(left, right) {
124
+ const a = new Set(left);
125
+ const b = new Set(right);
126
+ if (a.size === 0 || b.size === 0) return 0;
127
+ let intersection = 0;
128
+ for (const token of a) if (b.has(token)) intersection += 1;
129
+ return intersection / (a.size + b.size - intersection);
130
+ }
131
+
132
+ /**
133
+ * Pre-step injection order: [boot, shared, working, recall].
134
+ * Blocks are {kind, text}; empty texts are dropped, unknown kinds dropped.
135
+ */
136
+
137
+ /** Human-friendly focus entities from a question (EA-05 caller uses this). */
138
+ export function entitiesFromText(text, limit = 8) {
139
+ const normalized = String(text ?? '');
140
+ const out = [];
141
+ const seen = new Set();
142
+ const push = (value) => {
143
+ const token = String(value ?? '').trim();
144
+ if (token === '' || seen.has(token) || out.length >= limit) return;
145
+ seen.add(token);
146
+ out.push(token);
147
+ };
148
+ for (const run of normalized.match(/[㐀-䶿一-鿿]{2,8}/g) ?? []) push(run);
149
+ for (const word of normalized.match(/[A-Za-z][A-Za-z0-9._-]{1,30}/g) ?? []) push(word);
150
+ for (const version of normalized.match(/v?\d+(?:\.\d+){1,3}/g) ?? []) push(version);
151
+ return out;
152
+ }
153
+
154
+ /**
155
+ * D12: real-user message filter — injected blocks (auto recall / boot / shared) never
156
+ * become the working task. Keeps the 4-field extraction honest.
157
+ */
158
+ export function isRealUserMessage(message) {
159
+ if (!isHumanMessage(message)) return false;
160
+ if (isInjectedMessage(message)) return false;
161
+ return !textOfMessage(message).trimStart().startsWith(AUTO_TEXT_MARK);
162
+ }
163
+
164
+ function clipWorkingText(value, max = WORKING_FIELD_MAX_CHARS) {
165
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
166
+ if (text === '') return '';
167
+ return text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}…`;
168
+ }
169
+
170
+ const WORKING_TOOL_VERBS = 'read|write|edit|open|update|patch|apply_patch|create|delete|glob|grep|ls|stat';
171
+ const WORKING_TOOL_RE = new RegExp(`(?:^|\\s)(?:${WORKING_TOOL_VERBS})\\s+(?:"([^"]+)"|'([^']+)'|(\\S+))`, 'gi');
172
+
173
+ function looksLikePath(token) {
174
+ const value = String(token ?? '').trim().replace(/^[('"\[]+|[)'".,;:\]]+$/g, '');
175
+ if (value === '' || value.length > 200) return false;
176
+ return /[\\/]/.test(value) || /\.(?:js|mjs|cjs|ts|tsx|jsx|json|jsonl|md|txt|ps1|py|css|html|yml|yaml)$/i.test(value);
177
+ }
178
+
179
+ /** touchedFiles: basenames of paths passed to tool verbs, first-appearance order, ≤5, total ≤300. */
180
+ export function touchedFilesFromMessages(messages) {
181
+ const out = [];
182
+ const seen = new Set();
183
+ let total = 0;
184
+ for (const message of Array.isArray(messages) ? messages : []) {
185
+ if (!message || typeof message !== 'object') continue;
186
+ if (message.role !== 'tool' && message.role !== 'toolResult') continue;
187
+ const text = textOfMessage(message);
188
+ if (text === '') continue;
189
+ WORKING_TOOL_RE.lastIndex = 0;
190
+ let match;
191
+ while ((match = WORKING_TOOL_RE.exec(text)) !== null) {
192
+ const target = match[1] ?? match[2] ?? match[3] ?? '';
193
+ if (!looksLikePath(target)) continue;
194
+ const base = String(target).replace(/[\\/]+$/, '').split(/[\\/]/).pop();
195
+ if (!base || seen.has(base)) continue;
196
+ const cost = base.length + (out.length > 0 ? 1 : 0);
197
+ if (out.length >= WORKING_TOUCHED_FILES_MAX) break;
198
+ if (total + cost > WORKING_TOUCHED_TOTAL_CHARS) break;
199
+ seen.add(base);
200
+ out.push(base);
201
+ total += cost;
202
+ }
203
+ }
204
+ return out;
205
+ }
206
+
207
+ function extractWorkingLine(text, pattern) {
208
+ const match = pattern.exec(String(text ?? ''));
209
+ return match ? clipWorkingText(match[1]) : '';
210
+ }
211
+
212
+ const NEXT_STEP_RE = /(?:下一步|接下来|接着|然后)[::,,、\s]*([^\n。;;]{1,120})/;
213
+ const DECISION_RE = /(?:决定|决策|采用|选定|选择)[::,,、\s]*([^\n。;;]{1,120})/;
214
+
215
+ /** Pure extractor for the 4 working fields (null/absent → explicit unset marker, never ''). */
216
+ export function extractWorkingFields(messages = []) {
217
+ const list = Array.isArray(messages) ? messages : [];
218
+ let lastUser = null;
219
+ let lastAssistant = null;
220
+ for (const message of list) {
221
+ if (isRealUserMessage(message)) lastUser = message;
222
+ const role = String(message?.role ?? '');
223
+ if (role === 'assistant' || role === 'ai') lastAssistant = message;
224
+ }
225
+ const userText = lastUser ? textOfMessage(lastUser) : '';
226
+ const assistantText = lastAssistant ? textOfMessage(lastAssistant) : '';
227
+ return {
228
+ lastUserTask: clipWorkingText(userText) || WORKING_UNSET,
229
+ nextStep: extractWorkingLine(assistantText, NEXT_STEP_RE) || WORKING_UNSET,
230
+ touchedFiles: touchedFilesFromMessages(list),
231
+ lastDecision: extractWorkingLine(assistantText, DECISION_RE) || WORKING_UNSET,
232
+ };
233
+ }
234
+
235
+ function normalizeWorkingFields(input) {
236
+ const source = input && typeof input === 'object' ? input : {};
237
+ return {
238
+ lastUserTask: source.lastUserTask ?? WORKING_UNSET,
239
+ nextStep: source.nextStep ?? WORKING_UNSET,
240
+ touchedFiles: Array.isArray(source.touchedFiles) ? source.touchedFiles.slice(0, WORKING_TOUCHED_FILES_MAX) : (source.touchedFiles ?? WORKING_UNSET),
241
+ lastDecision: source.lastDecision ?? WORKING_UNSET,
242
+ };
243
+ }
244
+
245
+ function workingFieldText(value) {
246
+ if (value === undefined || value === null) return '';
247
+ if (Array.isArray(value)) return value.filter((item) => item !== undefined && item !== null && item !== WORKING_UNSET).join('、');
248
+ if (typeof value === 'object') return value.unset === true ? '' : '';
249
+ return String(value).trim();
250
+ }
251
+
252
+ /**
253
+ * EA-05: real per-turn focus updater — extracts the last human message and records
254
+ * this turn's focus into the frame stack (so the NEXT turn can inject it).
255
+ */
256
+ export function updateFrameFromMessages({ store, sessionId, messages, turn = 0 } = {}) {
257
+ const list = Array.isArray(messages) ? messages : [];
258
+ let human = null;
259
+ for (const message of list) {
260
+ if (isHumanMessage(message)) human = message;
261
+ }
262
+ const query = human ? textOfMessage(human) : '';
263
+ if (query.trim() === '') return { ok: false, code: 'E_NO_HUMAN_MESSAGE' };
264
+ const fields = extractWorkingFields(list);
265
+ const result = store.updateFocus({
266
+ sessionId,
267
+ entities: entitiesFromText(query),
268
+ anchors: [],
269
+ turn: Number.isInteger(turn) && turn >= 0 ? turn : 0,
270
+ query,
271
+ fields,
272
+ });
273
+ return { ...result, query, fields };
274
+ }
275
+
276
+ /**
277
+ * EA-04: insert the working-frame injection at the real order slot
278
+ * [boot, shared, working, recall] — before the auto-recall block, after boot/shared.
279
+ */
280
+ export function insertWorkingMessage(messages, message) {
281
+ const list = Array.isArray(messages) ? [...messages] : [];
282
+ if (!message) return list;
283
+ const autoIndex = list.findIndex((entry) => {
284
+ if (!isInjectedMessage(entry)) return false;
285
+ const firstLine = textOfMessage(entry).trimStart().split('\n', 1)[0] ?? '';
286
+ return firstLine.startsWith(AUTO_TEXT_MARK);
287
+ });
288
+ if (autoIndex !== -1) {
289
+ list.splice(autoIndex, 0, message);
290
+ return list;
291
+ }
292
+ let lastInjected = -1;
293
+ for (let index = 0; index < list.length; index += 1) {
294
+ if (isInjectedMessage(list[index])) lastInjected = index;
295
+ }
296
+ if (lastInjected !== -1) {
297
+ list.splice(lastInjected + 1, 0, message);
298
+ return list;
299
+ }
300
+ list.splice(insertionIndex(list), 0, message);
301
+ return list;
302
+ }
303
+
304
+ export function composePreStepBlocks(blocks) {
305
+ const byKind = new Map();
306
+ for (const block of Array.isArray(blocks) ? blocks : []) {
307
+ if (!block || typeof block !== 'object') continue;
308
+ if (!INJECTION_ORDER.includes(block.kind)) continue;
309
+ if (typeof block.text !== 'string' || block.text.trim() === '') continue;
310
+ if (!byKind.has(block.kind)) byKind.set(block.kind, []);
311
+ byKind.get(block.kind).push(block.text.trim());
312
+ }
313
+ const out = [];
314
+ for (const kind of INJECTION_ORDER) {
315
+ for (const text of byKind.get(kind) ?? []) out.push({ kind, text });
316
+ }
317
+ return out;
318
+ }
319
+
320
+ function validateFrame(frame, sessionId) {
321
+ if (!frame || typeof frame !== 'object') throw new WorkingFrameError('E_FRAME_INVALID', 'frame must be an object');
322
+ if (frame.sessionId !== sessionId) throw new WorkingFrameError('E_FRAME_SESSION', 'frame.sessionId mismatch');
323
+ if (!Array.isArray(frame.focus?.entities)) throw new WorkingFrameError('E_FRAME_FOCUS', 'frame.focus.entities required');
324
+ if (!Array.isArray(frame.turnRange) || frame.turnRange.length !== 2) {
325
+ throw new WorkingFrameError('E_FRAME_TURN_RANGE', 'frame.turnRange required');
326
+ }
327
+ return frame;
328
+ }
329
+
330
+ /**
331
+ * Create the working-frame store.
332
+ *
333
+ * @param {object} options
334
+ * @param {string} options.memoryRoot
335
+ * @param {() => Date} [options.now]
336
+ * @param {() => number} [options.monoNow] monotonic clock seam (ms)
337
+ * @param {number} [options.ttlMs]
338
+ * @param {number} [options.clockToleranceMs]
339
+ */
340
+ export function createWorkingFrameStore(options = {}) {
341
+ const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
342
+ if (memoryRoot === '') throw new WorkingFrameError('E_MEMORY_ROOT', 'working-frame requires memoryRoot');
343
+ const paths = workingDirOf(memoryRoot);
344
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
345
+ const monoNow = typeof options.monoNow === 'function'
346
+ ? options.monoNow
347
+ : () => {
348
+ const [seconds, nanoseconds] = process.hrtime();
349
+ return seconds * 1000 + nanoseconds / 1e6;
350
+ };
351
+ const ttlMs = Number.isInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : FRAME_TTL_MS;
352
+ const tolerance = Number.isFinite(options.clockToleranceMs) && options.clockToleranceMs >= 0
353
+ ? options.clockToleranceMs
354
+ : CLOCK_TOLERANCE_MS;
355
+ const bootMono = monoNow();
356
+ const bootWall = nowMs(now);
357
+ // §16.8 A/E:working/** 写保护(宿主独占写 + HMAC 侧车)+ 四元边界。
358
+ const frameSubject = normalizeRoleSubject(options.subject ?? {});
359
+ const frameActor = typeof options.actorKind === 'string' ? options.actorKind : 'host';
360
+
361
+ function effectiveWallMs() {
362
+ const elapsed = Number.isFinite(monoNow()) ? Math.max(0, monoNow() - bootMono) : 0;
363
+ return bootWall + elapsed;
364
+ }
365
+
366
+ // §4 ①:skip 事件内存级去重(同一 session+code 只落一次,防刷盘);门事件一律走生产 gate-log。
367
+ const skipNotified = new Set();
368
+ function gateEvent(sessionId, event, decision, reason, detail = {}) {
369
+ try {
370
+ appendGateLog(memoryRoot, {
371
+ sessionId: sessionId ?? null,
372
+ turn: Number.isInteger(detail.turn) ? detail.turn : 0,
373
+ gate: event,
374
+ decision,
375
+ reason,
376
+ evidence: Array.isArray(detail.evidence) ? detail.evidence : [],
377
+ });
378
+ } catch {
379
+ /* gate log must never block injection */
380
+ }
381
+ }
382
+ function notifySkip(sessionId, code, detail = {}) {
383
+ const key = `${safeSessionId(sessionId)}|${code}`;
384
+ if (skipNotified.has(key)) return;
385
+ skipNotified.add(key);
386
+ // B3 C3:门事件不允许写 skip(gate-log 当日 skip 必须为 0)。帧过期是告警事实,
387
+ // 记 warn + 稳定原因码;事件名同步改成 hg.d12.frame-expired(旧名不再出现)。
388
+ gateEvent(sessionId, 'hg.d12.frame-expired', 'warn', String(code), { turn: detail.turn ?? 0, evidence: [] });
389
+ }
390
+
391
+ // §4 ①:audit.jsonl 首启迁移(>256 KiB 先复制+记录副本 sha,再按行切 ≤256 KiB 分片,rotate≤3)。
392
+ // 失败 fail closed:原 live 文件一字不动。
393
+ let auditMigrated = false;
394
+ function sha256Bytes(buffer) {
395
+ return crypto.createHash('sha256').update(buffer).digest('hex');
396
+ }
397
+ function migrateAuditOnce() {
398
+ if (auditMigrated) return;
399
+ auditMigrated = true;
400
+ try {
401
+ const stat = fs.statSync(paths.audit);
402
+ const liveBytes = stat.size;
403
+ if (!stat.isFile() || liveBytes <= WORKING_AUDIT_MIGRATE_BYTES) return;
404
+ const live = fs.readFileSync(paths.audit);
405
+ const liveSha = sha256Bytes(live);
406
+ const stamp = nowIso(now).replace(/[:.]/g, '-');
407
+ const copyFile = path.join(paths.dir, `audit.migrate-${stamp}.jsonl`);
408
+ fs.mkdirSync(paths.dir, { recursive: true });
409
+ fs.copyFileSync(paths.audit, copyFile);
410
+ const copyBuffer = fs.readFileSync(copyFile);
411
+ const copyBytes = copyBuffer.length;
412
+ const copySha = sha256Bytes(copyBuffer);
413
+ if (copySha !== liveSha) return; // fail closed: copy mismatch, keep original
414
+ const chunks = [];
415
+ let current = '';
416
+ let currentBytes = 0;
417
+ for (const line of live.toString('utf8').split('\n')) {
418
+ if (line === '') continue;
419
+ const lineBytes = Buffer.byteLength(line, 'utf8') + 1;
420
+ if (current !== '' && currentBytes + lineBytes > WORKING_AUDIT_MIGRATE_BYTES) {
421
+ chunks.push(current);
422
+ current = `${line}\n`;
423
+ currentBytes = lineBytes;
424
+ } else {
425
+ current += `${line}\n`;
426
+ currentBytes += lineBytes;
427
+ }
428
+ }
429
+ if (current !== '') chunks.push(current);
430
+ if (chunks.length < 2) return;
431
+ const keep = chunks.slice(-WORKING_AUDIT_ROTATE_MAX);
432
+ for (let index = 0; index < keep.length; index += 1) {
433
+ const isLive = index === keep.length - 1;
434
+ const name = isLive ? 'audit.jsonl' : `audit.${keep.length - 1 - index}.jsonl`;
435
+ writeAtomic(path.join(paths.dir, name), keep[index]);
436
+ }
437
+ for (const name of fs.readdirSync(paths.dir)) {
438
+ const match = /^audit\.(\d+)\.jsonl$/.exec(name);
439
+ if (match && Number(match[1]) >= WORKING_AUDIT_ROTATE_MAX) {
440
+ try { fs.unlinkSync(path.join(paths.dir, name)); } catch { /* rotation cleanup best effort */ }
441
+ }
442
+ }
443
+ gateEvent(null, 'hg.working.audit.migrate', 'warn', 'audit-migrated', {
444
+ evidence: [`liveBytes=${liveBytes}`, `liveSha=${liveSha}`, `copyBytes=${copyBytes}`, `copySha=${copySha}`],
445
+ });
446
+ } catch {
447
+ /* migration is fail-closed: leave the original audit file untouched */
448
+ }
449
+ }
450
+
451
+ function audit(event, detail) {
452
+ try {
453
+ migrateAuditOnce();
454
+ fs.mkdirSync(path.dirname(paths.audit), { recursive: true });
455
+ fs.appendFileSync(paths.audit, `${JSON.stringify({ schema: 'working-frame-audit/v1', at: nowIso(now), event, ...detail })}\n`, 'utf8');
456
+ } catch {
457
+ /* audit is best effort */
458
+ }
459
+ }
460
+
461
+ function clockGuard(frame) {
462
+ const wall = nowMs(now);
463
+ const watermark = Number(frame?.wallWatermarkMs ?? frame?.lastUsedAtMs ?? 0);
464
+ if (Number.isFinite(wall) && watermark > 0 && wall + tolerance < watermark) {
465
+ audit('clock.rollback', { sessionId: frame?.sessionId ?? null, wall, watermark });
466
+ throw new WorkingFrameError('E_CLOCK_ROLLBACK', `系统时钟回拨(now=${new Date(wall).toISOString()} < watermark=${new Date(watermark).toISOString()}),工作帧 fail closed。`, { wall, watermark });
467
+ }
468
+ return wall;
469
+ }
470
+
471
+ function load(sessionId) {
472
+ const id = safeSessionId(sessionId);
473
+ const file = framePathOf(memoryRoot, id);
474
+ const verified = verifyProtectedFile({ memoryRoot, file });
475
+ if (verified.absent) return { present: false, frame: null };
476
+ if (!verified.ok) {
477
+ return { present: true, frame: null, code: verified.code ?? 'E_INTEGRITY_TAMPER', message: verified.message };
478
+ }
479
+ try {
480
+ return { present: true, frame: JSON.parse(verified.text), code: null };
481
+ } catch {
482
+ return { present: true, frame: null, code: 'E_INTEGRITY_TAMPER', message: '受保护帧 JSON 解析失败' };
483
+ }
484
+ }
485
+
486
+ function clampFramePayload(input) {
487
+ const value = JSON.parse(JSON.stringify(input));
488
+ if (Array.isArray(value?.focus?.entities)) {
489
+ value.focus.entities = value.focus.entities.map((entity) => String(entity).slice(0, 200)).slice(0, 50);
490
+ }
491
+ if (Array.isArray(value?.focus?.anchors)) {
492
+ value.focus.anchors = value.focus.anchors.slice(0, 20).map((anchor) => {
493
+ const clone = JSON.parse(JSON.stringify(anchor ?? {}));
494
+ const walk = (node) => {
495
+ if (typeof node === 'string') return node.length > 2000 ? `${node.slice(0, 2000)}…[truncated]` : node;
496
+ if (Array.isArray(node)) return node.map(walk);
497
+ if (node && typeof node === 'object') { for (const key of Object.keys(node)) node[key] = walk(node[key]); }
498
+ return node;
499
+ };
500
+ return walk(clone);
501
+ });
502
+ }
503
+ return value;
504
+ }
505
+
506
+ function save(sessionId, frame) {
507
+ const id = safeSessionId(sessionId);
508
+ const clamped = clampFramePayload(frame);
509
+ const validated = validateFrame(clamped, id);
510
+ const value = attachFrameSubject(validated, { subject: frameSubject });
511
+ const serialized = JSON.stringify(value);
512
+ if (serialized.length > 512 * 1024) {
513
+ throw new WorkingFrameError('E_FRAME_TOO_LARGE', `工作帧超过 512KB 上限(${serialized.length} bytes),拒绝落盘。`);
514
+ }
515
+ const file = framePathOf(memoryRoot, id);
516
+ writeProtectedJson({ memoryRoot, file, value, actorKind: frameActor });
517
+ return { ok: true, path: file, frame: value };
518
+ }
519
+
520
+ function newFrame({ sessionId, entities = [], anchors = [], turn = 0, frameNo = 1, prevFrameId = null, fields = null }) {
521
+ const wall = nowMs(now);
522
+ return {
523
+ schema: FRAME_SCHEMA,
524
+ sessionId,
525
+ frameId: `wf-${sha1Short(`${sessionId}|${frameNo}|${wall}`)}`,
526
+ frameNo,
527
+ turnRange: [Number.isInteger(turn) ? turn : 0, Number.isInteger(turn) ? turn : 0],
528
+ focus: {
529
+ entities: [...new Set(entities.filter((entity) => typeof entity === 'string' && entity.trim() !== ''))].slice(0, 30),
530
+ anchors: Array.isArray(anchors) ? anchors.slice(0, 20) : [],
531
+ ...normalizeWorkingFields(fields),
532
+ },
533
+ ttlMs,
534
+ lastUsedAtMs: wall,
535
+ lastUsedAt: new Date(wall).toISOString(),
536
+ updatedAt: new Date(wall).toISOString(),
537
+ wallWatermarkMs: wall,
538
+ state: 'active',
539
+ prevFrameId,
540
+ };
541
+ }
542
+
543
+ function archiveFrame(sessionId, frame) {
544
+ const id = safeSessionId(sessionId);
545
+ const file = path.join(paths.archiveDir, `${id}-frame-${frame.frameNo ?? 1}-${frame.frameId ?? sha1Short(stableStringify(frame))}.json`);
546
+ writeProtectedJson({
547
+ memoryRoot,
548
+ file,
549
+ value: attachFrameSubject({ ...frame, archivedAt: nowIso(now), state: 'archived' }, { subject: frameSubject }),
550
+ actorKind: frameActor,
551
+ });
552
+ audit('topic.switch.archive', { sessionId: id, frameId: frame.frameId ?? null, frameNo: frame.frameNo ?? null, file });
553
+ return file;
554
+ }
555
+
556
+ function isExpired(frame) {
557
+ if (!frame) return true;
558
+ const lastUsed = Number(frame.lastUsedAtMs ?? 0);
559
+ if (!Number.isFinite(lastUsed) || lastUsed <= 0) return true;
560
+ const effective = effectiveWallMs();
561
+ // EA-13: a FORWARD wall-clock jump must expire the frame, not silently stretch
562
+ // its lifetime. Backward jumps are handled by clockGuard (fail closed).
563
+ const realWall = nowMs(now);
564
+ if (Number.isFinite(realWall) && Number.isFinite(effective) && realWall > effective + tolerance) return true;
565
+ return effective - lastUsed > ttlMs;
566
+ }
567
+
568
+ function topicChanged(frame, queryOrEntities) {
569
+ const incoming = tokenizeFocus(queryOrEntities);
570
+ if (incoming.length === 0) return false;
571
+ // Topic switch is keyed on the frame's focus ENTITIES (anchors are evidence,
572
+ // not topic tokens). Switch only when the new turn shares no entity token and
573
+ // the Jaccard similarity is below threshold; a same-topic follow-up keeps the frame.
574
+ const entityTokens = tokenizeFocus(frame?.focus?.entities ?? []);
575
+ if (entityTokens.length === 0) return true;
576
+ let intersection = 0;
577
+ const entitySet = new Set(entityTokens);
578
+ for (const token of incoming) if (entitySet.has(token)) intersection += 1;
579
+ if (intersection > 0) return false;
580
+ return jaccardSimilarity(incoming, entityTokens) < TOPIC_SIMILARITY_THRESHOLD;
581
+ }
582
+
583
+ /**
584
+ * Per-turn focus update. Same topic merges; expired/topic-switched frames go to archive
585
+ * (never deleted) and a new frame is opened.
586
+ */
587
+ function updateFocus(input = {}) {
588
+ const leaseFile = `${framePathOf(memoryRoot, input.sessionId)}.lock`;
589
+ let lease;
590
+ try {
591
+ lease = acquireLease(leaseFile, { holder: `working-frame:${process.pid}`, ttlMs: 30_000 });
592
+ } catch (error) {
593
+ return { ok: false, code: 'E_FRAME_BUSY', message: `工作帧正在被另一写者更新(E_FRAME_BUSY):${error?.message ?? error}` };
594
+ }
595
+ try {
596
+ return updateFocusUnlocked(input);
597
+ } finally {
598
+ releaseLease(leaseFile, lease.holder);
599
+ }
600
+ }
601
+
602
+ function updateFocusUnlocked({ sessionId, entities = [], anchors = [], turn = 0, query = '', fields = null }) {
603
+ const loaded = load(sessionId);
604
+ const wall = nowMs(now);
605
+ // §16.8 A:帧被篡改/缺侧车 → fail closed,绝不把坏帧当有效帧继续写。
606
+ if (loaded.present && loaded.frame === null) {
607
+ return { ok: false, code: loaded.code ?? 'E_INTEGRITY_TAMPER', message: loaded.message ?? '帧完整性校验失败' };
608
+ }
609
+ if (!loaded.present) {
610
+ const frame = newFrame({ sessionId: safeSessionId(sessionId), entities, anchors, turn, frameNo: 1, fields });
611
+ save(sessionId, frame);
612
+ return { ok: true, switched: true, reason: 'new', frame };
613
+ }
614
+ const current = loaded.frame;
615
+ clockGuard(current);
616
+ const expired = isExpired(current);
617
+ // Topic switch considers BOTH the new question and this turn's extracted entities:
618
+ // a question that reuses the frame's focus entities stays on the same frame.
619
+ const switched = topicChanged(current, query !== '' ? [query, ...(Array.isArray(entities) ? entities : [])] : entities);
620
+ if (expired || switched) {
621
+ const archiveFile = archiveFrame(sessionId, current);
622
+ const frame = newFrame({
623
+ sessionId: safeSessionId(sessionId),
624
+ entities,
625
+ anchors,
626
+ turn,
627
+ frameNo: (current.frameNo ?? 1) + 1,
628
+ prevFrameId: current.frameId ?? null,
629
+ fields,
630
+ });
631
+ save(sessionId, frame);
632
+ return { ok: true, switched: true, reason: expired ? 'expired' : 'topic-switch', archiveFile, frame };
633
+ }
634
+ const mergedEntities = [...new Set([...(current.focus?.entities ?? []), ...entities])].slice(0, 30);
635
+ const mergedAnchors = [...(current.focus?.anchors ?? []), ...anchors];
636
+ const fieldSource = fields ?? current.focus ?? {};
637
+ const next = {
638
+ ...current,
639
+ turnRange: [current.turnRange?.[0] ?? 0, Math.max(current.turnRange?.[1] ?? 0, Number.isInteger(turn) ? turn : 0)],
640
+ focus: {
641
+ entities: mergedEntities,
642
+ anchors: mergedAnchors.slice(0, 20),
643
+ ...normalizeWorkingFields(fieldSource),
644
+ },
645
+ lastUsedAtMs: wall,
646
+ lastUsedAt: new Date(wall).toISOString(),
647
+ updatedAt: new Date(wall).toISOString(),
648
+ wallWatermarkMs: Math.max(Number(current.wallWatermarkMs ?? 0), wall),
649
+ state: 'active',
650
+ };
651
+ save(sessionId, next);
652
+ return { ok: true, switched: false, reason: 'merged', frame: next };
653
+ }
654
+
655
+ /**
656
+ * D12 injection renderer: 4 fields on top of focus/anchors, ≤300 chars.
657
+ * Drop order (whole item): lastUserTask → nextStep → touchedFiles → lastDecision.
658
+ */
659
+ function renderInjectionText(frame) {
660
+ const focus = frame?.focus ?? {};
661
+ const entities = (focus.entities ?? []).slice(0, 8);
662
+ const turnRange = Array.isArray(frame?.turnRange) ? `${frame.turnRange[0]}-${frame.turnRange[1]}` : '?';
663
+ const head = `【工作帧】焦点:${entities.length > 0 ? entities.join('、') : '(无)'}(轮次 ${turnRange})`;
664
+ const anchorLines = (focus.anchors ?? []).map((anchor) => anchor?.oneLine).filter(Boolean).slice(0, 4);
665
+ const fixed = [head];
666
+ if (anchorLines.length > 0) fixed.push(`锚点:${anchorLines.join(';')}`);
667
+ const labels = { lastUserTask: '任务', nextStep: '下一步', touchedFiles: '改动', lastDecision: '决定' };
668
+ const present = {};
669
+ for (const name of WORKING_FIELDS) {
670
+ const text = workingFieldText(focus[name]);
671
+ if (text !== '') present[name] = `${labels[name]}:${text}`;
672
+ }
673
+ const before = WORKING_FIELDS.reduce((sum, name) => sum + (present[name] ? present[name].length : 0), 0);
674
+ const dropOrder = [...WORKING_FIELDS];
675
+ const dropped = [];
676
+ const render = () => [...fixed, ...WORKING_FIELDS.filter((name) => present[name]).map((name) => present[name])].join('\n');
677
+ let text = render();
678
+ while (text.length > WORKING_INJECT_MAX_CHARS && dropOrder.length > 0) {
679
+ const name = dropOrder.shift();
680
+ if (present[name]) {
681
+ delete present[name];
682
+ dropped.push(name);
683
+ text = render();
684
+ }
685
+ }
686
+ if (text.length > WORKING_INJECT_MAX_CHARS) text = `${text.slice(0, WORKING_INJECT_MAX_CHARS - 1)}…`;
687
+ return { text, dropped, before, after: text.length };
688
+ }
689
+
690
+ /** Injection decision: unexpired frame only; rollback fails closed; never delete. */
691
+ function frameForInjection({ sessionId, caller = null }) {
692
+ const loaded = load(sessionId);
693
+ if (!loaded.present) {
694
+ notifySkip(sessionId, 'E_NO_FRAME', { turn: 0 });
695
+ return { inject: false, code: 'E_NO_FRAME' };
696
+ }
697
+ if (loaded.frame === null) {
698
+ const code = loaded.code ?? 'E_INTEGRITY_TAMPER';
699
+ notifySkip(sessionId, code, { turn: 0 });
700
+ return { inject: false, code };
701
+ }
702
+ const frame = loaded.frame;
703
+ const turn = Array.isArray(frame.turnRange) ? frame.turnRange[1] : 0;
704
+ if (caller !== null) {
705
+ try {
706
+ assertFrameReadable(frame, caller);
707
+ } catch (error) {
708
+ notifySkip(sessionId, error.code ?? 'E_FRAME_PRIVATE', { turn });
709
+ return { inject: false, code: error.code ?? 'E_FRAME_PRIVATE', message: error.message };
710
+ }
711
+ }
712
+ try {
713
+ clockGuard(frame);
714
+ } catch (error) {
715
+ notifySkip(sessionId, error.code, { turn });
716
+ return { inject: false, code: error.code, message: error.message };
717
+ }
718
+ if (isExpired(frame)) {
719
+ if (frame.state !== 'stale') {
720
+ try {
721
+ save(sessionId, { ...frame, state: 'stale', updatedAt: nowIso(now) });
722
+ } catch {
723
+ /* stale mark is best effort */
724
+ }
725
+ audit('frame.stale', { sessionId: safeSessionId(sessionId), frameId: frame.frameId ?? null });
726
+ }
727
+ notifySkip(sessionId, 'E_FRAME_EXPIRED', { turn });
728
+ return { inject: false, code: 'E_FRAME_EXPIRED', frame };
729
+ }
730
+ const rendered = renderInjectionText(frame);
731
+ if (rendered.dropped.length > 0) {
732
+ gateEvent(sessionId, 'hg.d12.truncate', 'warn', 'field-budget', {
733
+ turn,
734
+ evidence: [
735
+ `dropped=${rendered.dropped.join(',')}`,
736
+ `before=${rendered.before}`,
737
+ `after=${rendered.after}`,
738
+ ],
739
+ });
740
+ }
741
+ return { inject: true, frame, text: rendered.text, dropped: rendered.dropped };
742
+ }
743
+
744
+ /** ≤300 chars block; truncated in that order: anchors → entities. */
745
+ function renderBlock(frame) {
746
+ const entities = (frame?.focus?.entities ?? []).slice(0, 8);
747
+ const anchorLines = (frame?.focus?.anchors ?? []).map((anchor) => anchor?.oneLine).filter(Boolean).slice(0, 4);
748
+ const turnRange = Array.isArray(frame?.turnRange) ? `${frame.turnRange[0]}-${frame.turnRange[1]}` : '?';
749
+ const parts = [`【工作帧】焦点:${entities.length > 0 ? entities.join('、') : '(无)'}(轮次 ${turnRange})`];
750
+ if (anchorLines.length > 0) parts.push(`锚点:${anchorLines.join(';')}`);
751
+ let text = parts.join(' · ');
752
+ if (text.length > 300) text = text.slice(0, 299) + '…';
753
+ return text;
754
+ }
755
+
756
+ function archive(sessionId) {
757
+ const loaded = load(sessionId);
758
+ if (!loaded.present) return { ok: false, code: 'E_NO_FRAME' };
759
+ const file = archiveFrame(sessionId, loaded.frame);
760
+ return { ok: true, file };
761
+ }
762
+
763
+ return {
764
+ memoryRoot,
765
+ paths,
766
+ ttlMs,
767
+ effectiveWallMs,
768
+ load,
769
+ save,
770
+ updateFocus,
771
+ frameForInjection,
772
+ renderBlock,
773
+ renderInjectionText,
774
+ isExpired,
775
+ topicChanged,
776
+ archive,
777
+ newFrame,
778
+ };
779
+ }