@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,466 @@
1
+ // routerFace v1 · 后台面本体。
2
+ //
3
+ // 一个 tick = 读材料(≤maxContextTokens)→ 调一次模型(dryRun 时跳过)
4
+ // → 写一条 journal + 最多 maxSuggestions 条 outbox。不执行任何工具、
5
+ // 不注册任何 turn 监听、不改会话历史。失败只记 status,绝不影响 turn。
6
+ //
7
+ // 刹车(硬边界):
8
+ // - routerFace.enabled 默认 false,关闭时 start() 什么都不做;
9
+ // - 每日 token 预算用完 → state=stopped / reason=daily-budget;
10
+ // - 连续 3 次失败 → state=stopped / reason=consecutive-failures;
11
+ // - dryRun 默认 true,只写 journal,不调 LLM、不写 outbox;
12
+ // - tick 单飞锁 + tickKey 幂等,定时器抖动不会写重。
13
+
14
+ import fs from 'node:fs';
15
+ import {
16
+ FACE_FIRST_TICK_MS,
17
+ FACE_HARD_CONTEXT_FLOOR,
18
+ FACE_MAX_CONSECUTIVE_FAILURES,
19
+ FACE_MAX_JOURNAL_CHARS,
20
+ FACE_MAX_OUTPUT_TOKENS,
21
+ FACE_SESSION_HINT,
22
+ FACE_TICK_TASK,
23
+ normalizeFaceConfig,
24
+ } from './config.mjs';
25
+ import { facePaths } from './paths.mjs';
26
+ import { hasJournalTick, appendJournalOnce, readJournal } from './journal.mjs';
27
+ import { appendOutbox } from './outbox.mjs';
28
+ import { buildFaceContext, summarizeContext } from './context.mjs';
29
+ import { buildFacePrompt, callFaceModel, parseFaceOutput, FACE_SYSTEM_PROMPT } from './llm.mjs';
30
+ import { ensureDir, localDayKey, readJsonFile, writeJsonAtomic } from '../service/paths.mjs';
31
+
32
+ export const FACE_STATUS_VERSION = 1;
33
+ export const FACE_STATE_VERSION = 1;
34
+ const LOCK_STALE_MIN_MS = 5 * 60 * 1000;
35
+
36
+ function cleanText(value, maxChars) {
37
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
38
+ const chars = Array.from(text);
39
+ if (chars.length <= maxChars) return text;
40
+ return `${chars.slice(0, Math.max(1, maxChars - 1)).join('')}…`;
41
+ }
42
+
43
+ function freshState() {
44
+ return {
45
+ v: FACE_STATE_VERSION,
46
+ day: '',
47
+ dayTokens: 0,
48
+ ticks: 0,
49
+ consecutiveFailures: 0,
50
+ stopped: false,
51
+ stopReason: null,
52
+ stopAt: null,
53
+ waitingProvider: false,
54
+ lastTickKey: null,
55
+ lastTickAt: null,
56
+ lastResult: null,
57
+ lastError: null,
58
+ };
59
+ }
60
+
61
+ function mergeState(raw) {
62
+ const state = freshState();
63
+ if (raw && typeof raw === 'object') {
64
+ for (const key of Object.keys(state)) {
65
+ if (raw[key] !== undefined && typeof raw[key] === typeof state[key]) state[key] = raw[key];
66
+ }
67
+ }
68
+ return state;
69
+ }
70
+
71
+ /**
72
+ * 创建后台面。不启动任何定时器;调 start() 才调度。
73
+ *
74
+ * @param {object} options
75
+ * @param {object} options.ctx 宿主 ctx(生产取 llm 用)
76
+ * @param {string} options.memoryRoot
77
+ * @param {object} [options.config] 已归一化配置;缺省用 options.rawConfig 归一化
78
+ * @param {object} [options.rawConfig]
79
+ * @param {object|Function} [options.client] 测试注入的假 LLM
80
+ * @param {() => Date} [options.now]
81
+ * @param {(message:string, error?:any) => void} [options.logger]
82
+ */
83
+ export function createRouterFace(options = {}) {
84
+ const memoryRoot = options.memoryRoot ?? options.config?.memoryRoot ?? null;
85
+ const paths = facePaths(memoryRoot);
86
+ if (!paths) throw new Error('E_FACE_NO_MEMORY_ROOT');
87
+ const config = options.config ?? normalizeFaceConfig(options.rawConfig ?? {}, { memoryRoot });
88
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
89
+ const client = options.client ?? null;
90
+ const logger = typeof options.logger === 'function' ? options.logger : () => {};
91
+ const ctx = options.ctx ?? null;
92
+
93
+ const stateRead = readJsonFile(paths.stateFile);
94
+ const state = mergeState(stateRead.ok ? stateRead.value : null);
95
+ let running = false;
96
+ let disposed = false;
97
+ let tickTimer = null;
98
+ let firstTickTimer = null;
99
+ let statusState = 'idle';
100
+ let statusReason = null;
101
+ let statusSince = new Date(now()).toISOString();
102
+
103
+ function writeState() {
104
+ try {
105
+ ensureDir(paths.dir);
106
+ writeJsonAtomic(paths.stateFile, state);
107
+ } catch (error) {
108
+ logger('face state write failed', error);
109
+ }
110
+ }
111
+
112
+ function statusSnapshot(extra = {}) {
113
+ const at = now();
114
+ return {
115
+ v: FACE_STATUS_VERSION,
116
+ name: 'router-face',
117
+ enabled: config.enabled === true,
118
+ dryRun: config.dryRun !== false,
119
+ tickMs: config.tickMs,
120
+ state: statusState,
121
+ reason: statusReason,
122
+ since: statusSince,
123
+ lastTickAt: state.lastTickAt,
124
+ lastTickKey: state.lastTickKey,
125
+ nextTickAt: tickTimer ? new Date(at.getTime() + config.tickMs).toISOString() : null,
126
+ today: {
127
+ day: state.day || localDayKey(at),
128
+ usedTokens: state.dayTokens,
129
+ dailyTokenBudget: config.dailyTokenBudget,
130
+ ticks: state.ticks,
131
+ },
132
+ consecutiveFailures: state.consecutiveFailures,
133
+ lastError: state.lastError,
134
+ lastResult: state.lastResult,
135
+ files: {
136
+ dir: paths.dir,
137
+ journal: paths.journalFile,
138
+ state: paths.stateFile,
139
+ status: paths.statusFile,
140
+ outbox: paths.outboxFile,
141
+ identity: paths.identityFile,
142
+ },
143
+ ...(extra || {}),
144
+ };
145
+ }
146
+
147
+ function writeStatus(extra = {}) {
148
+ try {
149
+ ensureDir(paths.dir);
150
+ writeJsonAtomic(paths.statusFile, statusSnapshot(extra));
151
+ } catch (error) {
152
+ logger('face status write failed', error);
153
+ }
154
+ }
155
+
156
+ function setStatus(next, reason) {
157
+ if (next !== statusState || reason !== statusReason) {
158
+ statusState = next;
159
+ statusReason = reason ?? null;
160
+ statusSince = new Date(now()).toISOString();
161
+ }
162
+ }
163
+
164
+ function resetDay(at) {
165
+ const day = localDayKey(at);
166
+ if (state.day === day) return false;
167
+ state.day = day;
168
+ state.dayTokens = 0;
169
+ state.ticks = 0;
170
+ state.lastTickKey = null;
171
+ if (state.stopped && state.stopReason === 'daily-budget') {
172
+ state.stopped = false;
173
+ state.stopReason = null;
174
+ state.stopAt = null;
175
+ }
176
+ return true;
177
+ }
178
+
179
+ function stop(reason) {
180
+ state.stopped = true;
181
+ state.stopReason = reason;
182
+ state.stopAt = new Date(now()).toISOString();
183
+ setStatus('stopped', reason);
184
+ clearTimers();
185
+ writeState();
186
+ writeStatus();
187
+ }
188
+
189
+ function clearTimers() {
190
+ if (tickTimer) {
191
+ clearInterval(tickTimer);
192
+ tickTimer = null;
193
+ }
194
+ if (firstTickTimer) {
195
+ clearTimeout(firstTickTimer);
196
+ firstTickTimer = null;
197
+ }
198
+ }
199
+
200
+ function lockStaleMs() {
201
+ return Math.max(LOCK_STALE_MIN_MS, config.tickMs * 2);
202
+ }
203
+
204
+ function acquireLock(at) {
205
+ try {
206
+ fs.mkdirSync(paths.dir, { recursive: true });
207
+ const fd = fs.openSync(paths.lockFile, 'wx');
208
+ fs.writeSync(fd, JSON.stringify({ pid: process.pid, at: at.toISOString() }));
209
+ fs.closeSync(fd);
210
+ return true;
211
+ } catch (error) {
212
+ if (error?.code !== 'EEXIST') return false;
213
+ try {
214
+ const stat = fs.statSync(paths.lockFile);
215
+ if (Date.now() - stat.mtimeMs > lockStaleMs()) {
216
+ fs.unlinkSync(paths.lockFile);
217
+ return acquireLock(at);
218
+ }
219
+ } catch {
220
+ // 锁文件刚被别的进程删掉,当作拿不到,下次再试。
221
+ }
222
+ return false;
223
+ }
224
+ }
225
+
226
+ function releaseLock() {
227
+ try {
228
+ fs.unlinkSync(paths.lockFile);
229
+ } catch {
230
+ // 不存在就算了。
231
+ }
232
+ }
233
+
234
+ function failure(code, detail = null) {
235
+ state.consecutiveFailures += 1;
236
+ state.lastError = { code: String(code ?? 'E_FACE_TICK'), detail: detail ? cleanText(detail, 300) : null, at: new Date(now()).toISOString() };
237
+ state.lastResult = 'error';
238
+ if (state.consecutiveFailures >= FACE_MAX_CONSECUTIVE_FAILURES) {
239
+ stop('consecutive-failures');
240
+ return { ok: false, error: code, stopped: true, reason: 'consecutive-failures' };
241
+ }
242
+ writeState();
243
+ setStatus(state.waitingProvider ? 'waiting-provider' : 'idle', state.waitingProvider ? 'waiting-provider' : 'tick-failed');
244
+ writeStatus();
245
+ return { ok: false, error: code, stopped: false };
246
+ }
247
+
248
+ function dryRunJournal(context, at) {
249
+ const keys = context.sections.map((section) => section.key);
250
+ const todo = context.sections.find((section) => section.key === 'todos');
251
+ const journalRows = readJournal(paths.journalFile, { limit: 5 }).length;
252
+ return cleanText(
253
+ `[dry-run] ${at.toISOString().slice(11, 19)} 完成上下文组装:${summarizeContext(context)};`
254
+ + `段=${keys.join('/') || 'empty'};journal 回看 ${journalRows} 条;待办段=${todo ? '有' : '无'}。`
255
+ + '未调用 LLM,未写 outbox。',
256
+ FACE_MAX_JOURNAL_CHARS,
257
+ );
258
+ }
259
+
260
+ async function tick(reason = 'timer') {
261
+ if (disposed) return { ok: false, skipped: 'disposed' };
262
+ if (running) return { ok: false, skipped: 'busy' };
263
+ running = true;
264
+ let locked = false;
265
+ try {
266
+ const at = now();
267
+ resetDay(at);
268
+ if (state.stopped) {
269
+ setStatus('stopped', state.stopReason);
270
+ return { ok: false, skipped: 'stopped', reason: state.stopReason };
271
+ }
272
+ if (state.dayTokens >= config.dailyTokenBudget) {
273
+ stop('daily-budget');
274
+ return { ok: false, skipped: 'daily-budget' };
275
+ }
276
+ const tickKey = `face-${state.day}-${Math.floor(at.getTime() / config.tickMs)}`;
277
+ if (hasJournalTick(paths.journalFile, tickKey)) {
278
+ state.lastTickKey = tickKey;
279
+ return { ok: true, skipped: 'duplicate-tick', tickKey };
280
+ }
281
+ locked = acquireLock(at);
282
+ if (!locked) {
283
+ setStatus('idle', 'locked');
284
+ return { ok: false, skipped: 'locked' };
285
+ }
286
+
287
+ setStatus('running', reason);
288
+ state.lastTickKey = tickKey;
289
+ state.lastTickAt = at.toISOString();
290
+ writeState();
291
+
292
+ const context = buildFaceContext({
293
+ memoryRoot,
294
+ paths,
295
+ maxContextTokens: Math.max(FACE_HARD_CONTEXT_FLOOR, config.maxContextTokens),
296
+ now,
297
+ });
298
+
299
+ if (config.dryRun !== false) {
300
+ const text = dryRunJournal(context, at);
301
+ const appended = appendJournalOnce(paths.journalFile, {
302
+ tickKey,
303
+ at,
304
+ day: state.day,
305
+ text,
306
+ kind: 'dry-run',
307
+ dryRun: true,
308
+ });
309
+ if (!appended.ok) return failure(appended.error ?? 'E_JOURNAL_WRITE', appended.message);
310
+ state.ticks += 1;
311
+ state.consecutiveFailures = 0;
312
+ state.waitingProvider = false;
313
+ state.lastResult = 'dry-run';
314
+ state.lastError = null;
315
+ writeState();
316
+ setStatus('idle', 'dry-run');
317
+ writeStatus();
318
+ return { ok: true, dryRun: true, tickKey, contextTokens: context.tokens };
319
+ }
320
+
321
+ const remaining = Math.max(0, config.dailyTokenBudget - state.dayTokens);
322
+ if (remaining <= 0) {
323
+ stop('daily-budget');
324
+ return { ok: false, skipped: 'daily-budget' };
325
+ }
326
+ const prompt = buildFacePrompt(context.text, { at: at.toISOString() });
327
+ const call = await callFaceModel({
328
+ ctx,
329
+ config,
330
+ client,
331
+ system: FACE_SYSTEM_PROMPT,
332
+ prompt,
333
+ maxTokens: Math.min(FACE_MAX_OUTPUT_TOKENS, Math.max(128, remaining)),
334
+ });
335
+ if (!call.ok) {
336
+ if (call.error === 'E_NO_LLM') state.waitingProvider = true;
337
+ return failure(call.error ?? 'E_FACE_MODEL', call.reason ?? null);
338
+ }
339
+ const parsed = parseFaceOutput(call.text, {
340
+ maxJournalChars: FACE_MAX_JOURNAL_CHARS,
341
+ maxSuggestions: config.maxSuggestions,
342
+ });
343
+ if (parsed.journal === '') return failure('E_FACE_EMPTY_JOURNAL', call.text ? 'model returned no journal' : null);
344
+
345
+ const inputTokens = Number.isInteger(call.usage?.inputTokens) ? call.usage.inputTokens : 0;
346
+ const outputTokens = Number.isInteger(call.usage?.outputTokens) ? call.usage.outputTokens : 0;
347
+ const spent = inputTokens + outputTokens;
348
+
349
+ const appended = appendJournalOnce(paths.journalFile, {
350
+ tickKey,
351
+ at,
352
+ day: state.day,
353
+ text: parsed.journal,
354
+ kind: FACE_TICK_TASK,
355
+ suggestions: parsed.suggestions,
356
+ usage: call.usage ?? null,
357
+ provider: call.provider ?? '',
358
+ model: call.model ?? '',
359
+ });
360
+ if (!appended.ok) return failure(appended.error ?? 'E_JOURNAL_WRITE', appended.message);
361
+
362
+ let outboxWritten = 0;
363
+ for (const suggestion of parsed.suggestions) {
364
+ const written = appendOutbox(paths.outboxFile, {
365
+ at: at.toISOString(),
366
+ sessionHint: FACE_SESSION_HINT,
367
+ text: suggestion,
368
+ kind: 'suggestion',
369
+ });
370
+ if (written.ok) outboxWritten += 1;
371
+ }
372
+
373
+ state.dayTokens += spent;
374
+ state.ticks += 1;
375
+ state.consecutiveFailures = 0;
376
+ state.waitingProvider = false;
377
+ state.lastResult = 'journal';
378
+ state.lastError = null;
379
+ state.lastUsage = { inputTokens, outputTokens, spent, estimated: call.usage?.estimated === true };
380
+ writeState();
381
+
382
+ if (state.dayTokens >= config.dailyTokenBudget) {
383
+ stop('daily-budget');
384
+ return {
385
+ ok: true,
386
+ tickKey,
387
+ contextTokens: context.tokens,
388
+ spent,
389
+ suggestions: parsed.suggestions.length,
390
+ outboxWritten,
391
+ stopped: true,
392
+ reason: 'daily-budget',
393
+ };
394
+ }
395
+ setStatus('idle', 'ok');
396
+ writeStatus();
397
+ return {
398
+ ok: true,
399
+ tickKey,
400
+ contextTokens: context.tokens,
401
+ spent,
402
+ suggestions: parsed.suggestions.length,
403
+ outboxWritten,
404
+ };
405
+ } catch (error) {
406
+ logger('face tick failed', error);
407
+ return failure(error?.code ?? 'E_FACE_TICK', String(error?.message ?? error));
408
+ } finally {
409
+ if (locked) releaseLock();
410
+ running = false;
411
+ }
412
+ }
413
+
414
+ function start() {
415
+ if (disposed) return { started: false, reason: 'disposed' };
416
+ if (config.enabled !== true) return { started: false, reason: 'disabled' };
417
+ if (tickTimer || firstTickTimer) return { started: true, already: true };
418
+ setStatus(state.stopped ? 'stopped' : 'idle', state.stopReason ?? 'start');
419
+ firstTickTimer = setTimeout(() => {
420
+ firstTickTimer = null;
421
+ void tick('first').catch(() => {});
422
+ }, FACE_FIRST_TICK_MS);
423
+ firstTickTimer.unref?.();
424
+ tickTimer = setInterval(() => {
425
+ void tick('timer').catch(() => {});
426
+ }, config.tickMs);
427
+ tickTimer.unref?.();
428
+ writeStatus();
429
+ return { started: true };
430
+ }
431
+
432
+ function stopTicking(reason = 'manual') {
433
+ clearTimers();
434
+ if (!disposed) {
435
+ state.stopped = true;
436
+ state.stopReason = reason;
437
+ state.stopAt = new Date(now()).toISOString();
438
+ setStatus('stopped', reason);
439
+ writeState();
440
+ writeStatus();
441
+ }
442
+ return { stopped: true, reason };
443
+ }
444
+
445
+ function dispose() {
446
+ clearTimers();
447
+ disposed = true;
448
+ setStatus('stopped', 'disposed');
449
+ writeStatus();
450
+ }
451
+
452
+ function getStatus() {
453
+ return statusSnapshot();
454
+ }
455
+
456
+ return {
457
+ tick,
458
+ start,
459
+ stop: stopTicking,
460
+ dispose,
461
+ getStatus,
462
+ getState: () => ({ ...state }),
463
+ paths,
464
+ config,
465
+ };
466
+ }
@@ -0,0 +1,130 @@
1
+ // routerFace v1 · 前后台共用身份文件。
2
+ //
3
+ // 规则(v1 边界,不要放宽):
4
+ // - 唯一来源是 `<memoryRoot>/IDENTITY.md`,前台 hint 与后台面读同一份;
5
+ // - **只读**:这里没有写入函数,插件永远不会创建或改写它;
6
+ // - 文件不存在 / 读失败 / 内容为空 → 用内置 DEFAULT_IDENTITY;
7
+ // - 解析是宽松的「键:值」行,未知行忽略,绝不因为格式问题抛错。
8
+ //
9
+ // 支持两种键写法(中文全角冒号 / 英文半角冒号):
10
+ // 名字 / name
11
+ // 称呼 / address
12
+ // 必须守的 / rules
13
+ // 说话方式 / voice
14
+
15
+ import fs from 'node:fs';
16
+
17
+ export const IDENTITY_FILE_NAME = 'IDENTITY.md';
18
+ export const IDENTITY_MAX_CHARS = 2000;
19
+ export const IDENTITY_LINE_MAX_CHARS = 120;
20
+
21
+ export const DEFAULT_IDENTITY = [
22
+ '# IDENTITY(内置默认)',
23
+ '名字:(未设置)',
24
+ '称呼:(未设置)',
25
+ '必须守的:不说假话;不确定就明说没查;不为讨好改结论',
26
+ '说话方式:简洁、直接;有情绪可以说,但不要端着;错了直接认,不辩解',
27
+ ].join('\n');
28
+
29
+ const KEY_ALIASES = new Map([
30
+ ['名字', 'name'],
31
+ ['name', 'name'],
32
+ ['称呼', 'address'],
33
+ ['address', 'address'],
34
+ ['必须守的', 'rules'],
35
+ ['必须遵守', 'rules'],
36
+ ['rules', 'rules'],
37
+ ['说话方式', 'voice'],
38
+ ['voice', 'voice'],
39
+ ]);
40
+
41
+ function clean(value) {
42
+ return String(value ?? '')
43
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]+/g, ' ')
44
+ .replace(/\s+/g, ' ')
45
+ .trim();
46
+ }
47
+
48
+ function truncateChars(text, maxChars) {
49
+ const chars = Array.from(String(text ?? ''));
50
+ if (!Number.isInteger(maxChars) || maxChars <= 0 || chars.length <= maxChars) return chars.join('');
51
+ if (maxChars <= 1) return chars.slice(0, maxChars).join('');
52
+ return `${chars.slice(0, maxChars - 1).join('')}…`;
53
+ }
54
+
55
+ /**
56
+ * 读 IDENTITY.md。永不抛错;返回 source 让调用方知道是否用了默认值。
57
+ *
58
+ * @param {string|null} file
59
+ * @returns {{text:string, source:'file'|'default', path:string|null, chars:number, warning?:string}}
60
+ */
61
+ export function readIdentity(file) {
62
+ if (!file) {
63
+ return { text: DEFAULT_IDENTITY, source: 'default', path: null, chars: DEFAULT_IDENTITY.length };
64
+ }
65
+ let text;
66
+ try {
67
+ text = fs.readFileSync(file, 'utf8');
68
+ } catch (error) {
69
+ const warning = error?.code === 'ENOENT' ? 'E_IDENTITY_MISSING' : 'E_IDENTITY_READ';
70
+ return {
71
+ text: DEFAULT_IDENTITY,
72
+ source: 'default',
73
+ path: file,
74
+ chars: DEFAULT_IDENTITY.length,
75
+ warning,
76
+ };
77
+ }
78
+ const cleanText = text.replace(/^\uFEFF/u, '').trim();
79
+ if (cleanText === '') {
80
+ return { text: DEFAULT_IDENTITY, source: 'default', path: file, chars: DEFAULT_IDENTITY.length, warning: 'E_IDENTITY_EMPTY' };
81
+ }
82
+ const capped = truncateChars(cleanText, IDENTITY_MAX_CHARS);
83
+ return {
84
+ text: capped,
85
+ source: 'file',
86
+ path: file,
87
+ chars: Array.from(capped).length,
88
+ ...(capped !== cleanText ? { warning: 'E_IDENTITY_TOO_LONG' } : {}),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * 解析「名字 / 称呼 / 必须守的 / 说话方式」四行。缺失的字段留空串。
94
+ * 只认第一条匹配,后面的同名字段忽略(不覆盖)。
95
+ */
96
+ export function parseIdentity(text) {
97
+ const out = { name: '', address: '', rules: '', voice: '' };
98
+ for (const rawLine of String(text ?? '').split(/\r?\n/u)) {
99
+ const line = rawLine.trim().replace(/^[-*]\s*/u, '');
100
+ if (line === '' || line.startsWith('#')) continue;
101
+ const match = line.match(/^([^::]{1,16})\s*[::]\s*(.+)$/u);
102
+ if (!match) continue;
103
+ const key = KEY_ALIASES.get(match[1].trim());
104
+ if (!key || out[key] !== '') continue;
105
+ const value = clean(match[2]).replace(/^[「『"']+|[」』"']+$/gu, '').trim();
106
+ if (value !== '') out[key] = value;
107
+ }
108
+ return out;
109
+ }
110
+
111
+ /**
112
+ * 把身份压成一行 hint 摘要(前台 hint 用)。
113
+ * 只带名字、称呼和一条「必须守的」,把 700-token 预算留给共享板本身。
114
+ */
115
+ export function renderIdentityLine(identityOrText, options = {}) {
116
+ const maxChars = Number.isInteger(options.maxChars) && options.maxChars > 0
117
+ ? options.maxChars
118
+ : IDENTITY_LINE_MAX_CHARS;
119
+ const parsed = typeof identityOrText === 'string'
120
+ ? parseIdentity(identityOrText)
121
+ : parseIdentity(identityOrText?.text ?? '');
122
+ const parts = [];
123
+ if (parsed.name) parts.push(parsed.name);
124
+ if (parsed.address) parts.push(`称呼:${parsed.address}`);
125
+ if (parsed.rules) parts.push(`守:${parsed.rules}`);
126
+ if (parts.length === 0) return '';
127
+ return `身份:${parts.join(' · ')}`.slice(0, maxChars);
128
+ }
129
+
130
+ export { truncateChars };
@@ -0,0 +1,65 @@
1
+ // routerFace v1 · 公开入口(无副作用:导入不建目录、不读文件、不调模型)。
2
+
3
+ export {
4
+ FACE_CONFIG_VERSION,
5
+ FACE_CONFIG_KEYS,
6
+ FACE_DEFAULTS,
7
+ FACE_INT_SPECS,
8
+ FACE_HARD_CONTEXT_FLOOR,
9
+ FACE_JOURNAL_CONTEXT_ROWS,
10
+ FACE_TODO_LIMIT,
11
+ FACE_MAX_JOURNAL_CHARS,
12
+ FACE_MAX_SUGGESTION_CHARS,
13
+ FACE_MAX_HINT_CHARS,
14
+ FACE_MAX_OUTPUT_TOKENS,
15
+ FACE_MAX_CONSECUTIVE_FAILURES,
16
+ FACE_FIRST_TICK_MS,
17
+ FACE_TICK_TASK,
18
+ FACE_SESSION_HINT,
19
+ normalizeFaceConfig,
20
+ } from './config.mjs';
21
+
22
+ export {
23
+ DEFAULT_IDENTITY,
24
+ IDENTITY_FILE_NAME,
25
+ IDENTITY_MAX_CHARS,
26
+ IDENTITY_LINE_MAX_CHARS,
27
+ parseIdentity,
28
+ readIdentity,
29
+ renderIdentityLine,
30
+ } from './identity.mjs';
31
+
32
+ export {
33
+ BRIDGE_DIR_NAME,
34
+ FACE_DIR_NAME,
35
+ FACE_JOURNAL_FILE_NAME,
36
+ FACE_LOCK_FILE_NAME,
37
+ FACE_STATE_FILE_NAME,
38
+ FACE_STATUS_FILE_NAME,
39
+ OUTBOX_FILE_NAME,
40
+ facePaths,
41
+ } from './paths.mjs';
42
+
43
+ export { JOURNAL_VERSION, JOURNAL_MAX_ROWS, appendJournalOnce, hasJournalTick, readJournal } from './journal.mjs';
44
+
45
+ export {
46
+ OUTBOX_VERSION,
47
+ OUTBOX_MAX_ROWS,
48
+ BRIDGE_TEXT_MAX_CHARS,
49
+ appendOutbox,
50
+ markRead,
51
+ readLatestUnread,
52
+ readOutbox,
53
+ renderBridgeHint,
54
+ } from './outbox.mjs';
55
+
56
+ export { buildFaceContext, excerptSections, summarizeContext } from './context.mjs';
57
+
58
+ export {
59
+ FACE_SYSTEM_PROMPT,
60
+ buildFacePrompt,
61
+ callFaceModel,
62
+ parseFaceOutput,
63
+ } from './llm.mjs';
64
+
65
+ export { FACE_STATE_VERSION, FACE_STATUS_VERSION, createRouterFace } from './face.mjs';