@jjh32456/longlive 2.1.0 → 2.3.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 (51) hide show
  1. package/CHANGELOG.md +108 -1
  2. package/QUICKSTART.md +7 -7
  3. package/README.en.md +13 -1
  4. package/README.md +26 -8
  5. package/SPEC.md +6 -5
  6. package/build-info.json +143 -73
  7. package/cordis.patch.yml +2 -0
  8. package/docs/ARCHITECTURE.md +6 -3
  9. package/docs/CONFIG.md +25 -1
  10. package/docs/FAQ.md +2 -2
  11. package/docs/FEATURES.md +125 -2
  12. package/docs/INDEX-FRESHNESS.md +8 -1
  13. package/docs/OPERATIONS.md +63 -2
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +1 -1
  16. package/docs/TROUBLESHOOTING.md +1 -1
  17. package/package.json +10 -2
  18. package/scripts/assert-install.mjs +124 -0
  19. package/scripts/backlog-report.mjs +98 -0
  20. package/scripts/install-230.mjs +787 -0
  21. package/scripts/lib/eng-common.mjs +428 -0
  22. package/scripts/rebuild-index.mjs +148 -0
  23. package/scripts/restore-drill.mjs +351 -0
  24. package/scripts/run-autoresolve.mjs +123 -0
  25. package/scripts/watchdog-230.mjs +379 -0
  26. package/src/config.js +7 -0
  27. package/src/features.js +35 -0
  28. package/src/gate/action-gate.js +545 -0
  29. package/src/memory/backup-retention.mjs +823 -0
  30. package/src/memory/cards.js +73 -12
  31. package/src/memory/conflict-scan.mjs +356 -0
  32. package/src/memory/conflicts.js +202 -9
  33. package/src/memory/consolidate.js +537 -35
  34. package/src/memory/decay.js +133 -19
  35. package/src/memory/event-index.js +62 -4
  36. package/src/memory/forget-scheduler.mjs +303 -0
  37. package/src/memory/forget-v2.js +94 -8
  38. package/src/memory/index-cache.mjs +216 -0
  39. package/src/memory/index.js +179 -16
  40. package/src/memory/lock.js +53 -12
  41. package/src/memory/maintenance.js +295 -19
  42. package/src/memory/recall-feedback.mjs +159 -17
  43. package/src/memory/recall-v2.js +5 -3
  44. package/src/memory/recall.js +10 -4
  45. package/src/memory/state.js +446 -38
  46. package/src/memory/task-state.mjs +569 -0
  47. package/src/recall/brain.mjs +55 -6
  48. package/src/recall/continuity-volatile.mjs +195 -1
  49. package/src/recall/index.js +8 -0
  50. package/src/tools.js +141 -21
  51. package/src/ui/routes-readonly.js +63 -5
@@ -0,0 +1,569 @@
1
+ // src/memory/task-state.mjs — 2.3.0 W2.4:任务状态机(working-frame lane)
2
+ //
3
+ // 定位:working-frame(2.0)只在**同一会话**内、TTL 30min、有帧时把焦点注入下一次 pre-step;
4
+ // 它解决「同会话连续追问」,不解决「会话被 truncate / 上下文被 compaction 之后重新接上」。
5
+ // 本模块补这一层:把「在做什么 / 等什么 / 下一步」抽成**机器可读文件**,跨会话/跨进程持久,
6
+ // 由 continuity-volatile 的 pre-step 在**新会话首步**读回来注入(rehydrate)。
7
+ //
8
+ // 与既有三种状态的分工(不重复维护):
9
+ // * STATE.md(记忆根根文件)——**人工**状态卡,本模块只读不写,绝不覆盖(验收测试 T9 断言字节不变)。
10
+ // * flow/current.md(心流快照)——第一人称手写,本模块不读不写。
11
+ // * working-frame 帧(.longlive/working/<sessionId>.json)——同会话焦点 + HMAC 写保护 + TTL;
12
+ // 本模块复用它的纯函数抽取器(isRealUserMessage / extractWorkingFields / touchedFilesFromMessages),
13
+ // 让「用户任务 / 下一步 / 触达文件」与 2.0 工作帧同口径,不再造第二套解析规则。
14
+ //
15
+ // 文件:<memoryRoot>/.longlive/workframe/current.json(原子写 tmp→fsync→rename,0600)
16
+ // 内容 schema = task-state/v1;帧 id 是**内容哈希**(frameId),不含本机路径/账号/绝对盘符,
17
+ // 因此同一任务状态在任何机器上落盘字节一致(可复算、可做夹具断言)。
18
+ //
19
+ // 隐私边界(F8 同口径):
20
+ // * 只存短句(每字段 ≤80 字),不存用户原文长文、不存工具输出正文;
21
+ // * 落盘前统一 scrub:代码块 / 凭据 / URL / 绝对路径 / 邮箱 / 电话 / 高熵令牌 → 占位符;
22
+ // * anchorFiles 只存 basename(不存目录,避免用户名/盘符泄漏);
23
+ // * 子代理 pre-step 不捕获、不读任务状态(子代理与主会话任务状态隔离)。
24
+ //
25
+ // 幂等:同一 (sessionId, turn, step, 字段) 重复捕获 → 不重写(文件字节不变,返回 written:false)。
26
+ // 失败语义:所有异常转 TaskStateError(带 code),由调用方 fail-safe 降级;本模块自身不抛到 pre-step 外层。
27
+
28
+ import crypto from 'node:crypto';
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+
32
+ import { stableStringify } from '../codec.js';
33
+ import {
34
+ extractWorkingFields,
35
+ jaccardSimilarity,
36
+ tokenizeFocus,
37
+ TOPIC_SIMILARITY_THRESHOLD,
38
+ touchedFilesFromMessages,
39
+ } from './working-frame.js';
40
+
41
+ export const TASK_STATE_SCHEMA = 'task-state/v1';
42
+ export const TASK_STATE_VERSION = 1;
43
+ export const TASK_STATE_DIRNAME = 'workframe';
44
+ export const TASK_STATE_FILE = 'current.json';
45
+
46
+ /** 单字段字数上限(与 working-frame 的 80 字同口径,不另造阈值)。 */
47
+ export const TASK_STATE_FIELD_MAX_CHARS = 80;
48
+ /** 注入行总字数上限;< continuity 的 step1 990 / step>1 400 预算,保证 composeBlock 有余量。 */
49
+ export const TASK_STATE_INJECT_MAX_CHARS = 220;
50
+ /** 跨会话 rehydrate 的新鲜度窗口:超过 24h 的旧任务状态不注入(避免拿旧任务污染新话题)。 */
51
+ export const TASK_STATE_FRESH_MS = 24 * 60 * 60 * 1000;
52
+ /** 等什么(waitingFor)里问题文本上限。 */
53
+ export const TASK_STATE_QUESTION_MAX_CHARS = 60;
54
+ /** anchorFiles 上限(与 working-frame 的 5 个同口径)。 */
55
+ export const TASK_STATE_ANCHOR_MAX = 5;
56
+
57
+ export class TaskStateError extends Error {
58
+ constructor(code, message, detail = undefined) {
59
+ super(message);
60
+ this.name = 'TaskStateError';
61
+ this.code = code;
62
+ if (detail !== undefined) this.detail = detail;
63
+ }
64
+ }
65
+
66
+ function errorCode(error, fallback) {
67
+ if (error && typeof error === 'object' && typeof error.code === 'string' && error.code !== '') {
68
+ return error.code;
69
+ }
70
+ return fallback;
71
+ }
72
+
73
+ // ── 路径(全部相对 memoryRoot,不落绝对盘符)────────────────────────────────
74
+
75
+ export function taskStateDirOf(memoryRoot) {
76
+ const root = path.resolve(String(memoryRoot ?? ''));
77
+ return {
78
+ root,
79
+ dir: path.join(root, '.longlive', TASK_STATE_DIRNAME),
80
+ file: path.join(root, '.longlive', TASK_STATE_DIRNAME, TASK_STATE_FILE),
81
+ };
82
+ }
83
+
84
+ export function taskStatePathOf(memoryRoot) {
85
+ return taskStateDirOf(memoryRoot).file;
86
+ }
87
+
88
+ // ── 文本工具 ─────────────────────────────────────────────────────────────────
89
+
90
+ function messageText(message) {
91
+ if (!message || typeof message !== 'object') return '';
92
+ const content = message.content;
93
+ if (typeof content === 'string') return content;
94
+ if (Array.isArray(content)) {
95
+ return content
96
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
97
+ .map((block) => block.text)
98
+ .join('\n');
99
+ }
100
+ if (typeof message.text === 'string') return message.text;
101
+ return '';
102
+ }
103
+
104
+ function collapseInline(value) {
105
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
106
+ }
107
+
108
+ function clipChars(text, max) {
109
+ const limit = Math.max(1, Math.floor(Number(max) || 1));
110
+ if (text.length <= limit) return text;
111
+ return `${text.slice(0, Math.max(0, limit - 1))}…`;
112
+ }
113
+
114
+ // 隐私 scrub 的顺序有讲究:代码块 → 凭据 → URL → 绝对路径 → 邮箱 → 电话 → 高熵令牌。
115
+ // 每一项都换成固定占位符,占位符本身不含任何原文片段。
116
+ const SCRUB_CREDENTIAL_RE =
117
+ /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|token|secret|password|passwd|pwd|密码|口令|密钥|凭据)\s*[:=:]\s*[^\s,,;;]+/gi;
118
+ const SCRUB_CODE_RE = /```[\s\S]*?```/g;
119
+ const SCRUB_URL_RE = /(?:https?|ftp):\/\/[^\s"'<>))]+/gi;
120
+ const SCRUB_WIN_PATH_RE = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|~[\\/])[^\s"'<>|,,;;]*/g;
121
+ const SCRUB_POSIX_PATH_RE = /(?:^|[\s(("'=])\/(?:Users|home|mnt|Volumes|root|tmp|var|opt|etc|private)\/[^\s"'<>|,,;;)]*/g;
122
+ const SCRUB_EMAIL_RE = /[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}/g;
123
+ const SCRUB_CN_PHONE_RE = /(?<!\d)(?:\+?86[-\s]?)?1[3-9]\d{9}(?!\d)/g;
124
+ const SCRUB_LONG_DIGITS_RE = /(?<!\d)\+?\d[\d\s-]{9,}\d(?!\d)/g;
125
+ const SCRUB_HEX_RE = /\b[A-Fa-f0-9]{32,}\b/g;
126
+ const SCRUB_B64_RE = /\b[A-Za-z0-9+/_-]{40,}={0,2}\b/g;
127
+
128
+ /**
129
+ * 隐私 scrub(导出供测试与红队直打):把可能含个人数据的片段替换成固定占位符。
130
+ * 纯函数、确定性:同一输入永远同一输出。
131
+ */
132
+ export function scrubTaskText(value) {
133
+ let text = String(value ?? '');
134
+ if (text === '') return '';
135
+ text = text.replace(SCRUB_CODE_RE, ' [代码] ');
136
+ text = text.replace(SCRUB_CREDENTIAL_RE, '[凭据]');
137
+ text = text.replace(SCRUB_URL_RE, '[链接]');
138
+ text = text.replace(SCRUB_WIN_PATH_RE, '[路径]');
139
+ text = text.replace(SCRUB_POSIX_PATH_RE, (match) => {
140
+ const prefix = /^[\s(("'=]/.test(match) ? match[0] : '';
141
+ return `${prefix}[路径]`;
142
+ });
143
+ text = text.replace(SCRUB_EMAIL_RE, '[邮箱]');
144
+ text = text.replace(SCRUB_CN_PHONE_RE, '[号码]');
145
+ text = text.replace(SCRUB_LONG_DIGITS_RE, '[号码]');
146
+ text = text.replace(SCRUB_HEX_RE, '[令牌]');
147
+ text = text.replace(SCRUB_B64_RE, '[令牌]');
148
+ return text;
149
+ }
150
+
151
+ /** 字段级清洗:scrub + 压成单行 + 截断(默认 80 字)。 */
152
+ export function sanitizeTaskText(value, { maxChars = TASK_STATE_FIELD_MAX_CHARS } = {}) {
153
+ const text = collapseInline(scrubTaskText(value));
154
+ if (text === '') return '';
155
+ return clipChars(text, maxChars);
156
+ }
157
+
158
+ /** anchorFiles:只保留 basename + 安全字符,避免目录/账号/盘符泄漏。 */
159
+ export function sanitizeAnchorFile(value) {
160
+ const raw = String(value ?? '').trim();
161
+ if (raw === '') return '';
162
+ const base = raw.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? '';
163
+ const safe = base
164
+ .replace(/[\u0000-\u001f\u007f]/g, '')
165
+ .replace(/[<>:"|?*]/g, '')
166
+ .trim();
167
+ if (safe === '') return '';
168
+ return clipChars(safe, 60);
169
+ }
170
+
171
+ // ── 抽取(复用 working-frame 的纯函数,保证与 2.0 工作帧同口径)─────────────
172
+
173
+ const CONTINUATION_RE = /^(?:继续|接着|继续做|接着做|再继续|往下做|继续吧|go on|continue|carry on)[。.!!~~\s]*$/i;
174
+ const WAIT_DECISION_RE =
175
+ /(?:等你|等待你|待你|需要你|请你)(?:确认|决定|拍板|回复|答复|选择|确认一下)[::,,、\s]*([^\n。;;??]{1,80})/;
176
+ const QUESTION_LINE_RE = /([^\n。;;!!]{1,120})[??]\s*$/;
177
+
178
+ /** 是否「继续」类短指令(跨会话 rehydrate 的相关性信号之一)。 */
179
+ export function isContinuationText(value) {
180
+ const text = collapseInline(value);
181
+ if (text === '') return false;
182
+ if (CONTINUATION_RE.test(text)) return true;
183
+ return /^(?:继续|接着|往下|再继续)/.test(text) && text.length <= 20;
184
+ }
185
+
186
+ /**
187
+ * 相关性命中:新会话首步的用户文本是否还在同一件事上(防止拿旧任务污染新话题)。
188
+ * 信号:继续类短指令 / 话题相似度(CJK bigram Jaccard,阈值复用 working-frame 的 0.35)/ 触达文件名。
189
+ * 返回 {related, reason, score};无用户文本时视为相关(首步必须显示任务状态)。
190
+ */
191
+ export function isTaskStateRelated(state, userText, { threshold = TOPIC_SIMILARITY_THRESHOLD } = {}) {
192
+ const text = collapseInline(userText);
193
+ if (text === '') return { related: true, reason: 'no-user-text', score: 0 };
194
+ if (isContinuationText(text)) return { related: true, reason: 'continuation', score: 1 };
195
+ const doing = collapseInline(state?.doing);
196
+ if (doing === '') return { related: true, reason: 'empty-doing', score: 0 };
197
+ const score = jaccardSimilarity(tokenizeFocus(doing), tokenizeFocus(text));
198
+ if (score >= threshold) return { related: true, reason: 'topic', score };
199
+ for (const file of Array.isArray(state?.anchorFiles) ? state.anchorFiles : []) {
200
+ if (file !== '' && text.includes(file)) return { related: true, reason: 'anchor-file', score };
201
+ }
202
+ return { related: false, reason: 'unrelated', score };
203
+ }
204
+
205
+ /**
206
+ * 抽取「等什么」:优先显式等待确认句,其次 assistant 末尾问句。
207
+ * 返回 {kind:'decision'|'question', text} 或 null;文本已 scrub + 截断。
208
+ */
209
+ export function extractWaitingFor(assistantText) {
210
+ const text = String(assistantText ?? '').trim();
211
+ if (text === '') return null;
212
+ const tail = text.slice(-400);
213
+ const decision = WAIT_DECISION_RE.exec(tail);
214
+ if (decision) {
215
+ const detail = sanitizeTaskText(decision[1]);
216
+ if (detail !== '') return { kind: 'decision', text: detail };
217
+ return { kind: 'decision', text: '等待你确认' };
218
+ }
219
+ const lines = tail.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
220
+ for (let index = lines.length - 1; index >= 0 && index >= lines.length - 4; index -= 1) {
221
+ const line = lines[index];
222
+ if (!/[??]/.test(line)) continue;
223
+ const match = QUESTION_LINE_RE.exec(line);
224
+ if (!match) continue;
225
+ const question = sanitizeTaskText(match[1], { maxChars: TASK_STATE_QUESTION_MAX_CHARS });
226
+ if (question !== '') return { kind: 'question', text: question };
227
+ return { kind: 'question', text: '等待你回答' };
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * 从 turn/step 上下文(decision.messages:agent 消息 + 工具消息)抽取任务三要素。
234
+ * 纯函数:不写盘、不读盘;返回 {doing, waitingFor, nextStep, anchorFiles, userTaskRaw, assistantQuestion}。
235
+ */
236
+ export function extractTaskFields(messages = []) {
237
+ const list = Array.isArray(messages) ? messages : [];
238
+ const working = extractWorkingFields(list);
239
+ const userTaskRaw =
240
+ working.lastUserTask && working.lastUserTask !== undefined && working.lastUserTask.unset !== true
241
+ ? String(working.lastUserTask)
242
+ : '';
243
+ const nextStepRaw =
244
+ working.nextStep && working.nextStep !== undefined && working.nextStep.unset !== true
245
+ ? String(working.nextStep)
246
+ : '';
247
+ let lastAssistant = null;
248
+ for (const message of list) {
249
+ const role = String(message?.role ?? '');
250
+ if (role === 'assistant' || role === 'ai') lastAssistant = message;
251
+ }
252
+ const assistantText = lastAssistant ? messageText(lastAssistant) : '';
253
+ const waitingFor = extractWaitingFor(assistantText);
254
+ const anchorFiles = [];
255
+ const seen = new Set();
256
+ for (const file of touchedFilesFromMessages(list)) {
257
+ const safe = sanitizeAnchorFile(file);
258
+ if (safe === '' || seen.has(safe)) continue;
259
+ anchorFiles.push(safe);
260
+ seen.add(safe);
261
+ if (anchorFiles.length >= TASK_STATE_ANCHOR_MAX) break;
262
+ }
263
+ return {
264
+ doing: sanitizeTaskText(userTaskRaw),
265
+ waitingFor,
266
+ nextStep: sanitizeTaskText(nextStepRaw),
267
+ anchorFiles,
268
+ userTaskRaw: collapseInline(userTaskRaw),
269
+ assistantQuestion: assistantText,
270
+ };
271
+ }
272
+
273
+ // ── 状态形状 ─────────────────────────────────────────────────────────────────
274
+
275
+ function emptyTaskState() {
276
+ return {
277
+ schema: TASK_STATE_SCHEMA,
278
+ version: TASK_STATE_VERSION,
279
+ frameId: null,
280
+ updatedAt: null,
281
+ sessionId: 'unknown',
282
+ turn: 0,
283
+ step: 0,
284
+ doing: '',
285
+ waitingFor: null,
286
+ nextStep: '',
287
+ anchorFiles: [],
288
+ };
289
+ }
290
+
291
+ function normalizeWaitingFor(value) {
292
+ if (!value || typeof value !== 'object') return null;
293
+ const kind = value.kind === 'decision' || value.kind === 'question' ? value.kind : null;
294
+ const text = sanitizeTaskText(value.text, { maxChars: TASK_STATE_QUESTION_MAX_CHARS });
295
+ if (kind === null || text === '') return null;
296
+ return { kind, text };
297
+ }
298
+
299
+ function normalizeTaskState(raw) {
300
+ const source = raw && typeof raw === 'object' ? raw : {};
301
+ const state = emptyTaskState();
302
+ state.updatedAt = typeof source.updatedAt === 'string' && source.updatedAt !== '' ? source.updatedAt : null;
303
+ state.sessionId =
304
+ typeof source.sessionId === 'string' && source.sessionId.trim() !== '' ? source.sessionId.trim() : 'unknown';
305
+ state.turn = Number.isInteger(source.turn) && source.turn >= 0 ? source.turn : 0;
306
+ state.step = Number.isInteger(source.step) && source.step >= 0 ? source.step : 0;
307
+ state.doing = sanitizeTaskText(source.doing);
308
+ state.waitingFor = normalizeWaitingFor(source.waitingFor);
309
+ state.nextStep = sanitizeTaskText(source.nextStep);
310
+ state.anchorFiles = [];
311
+ if (Array.isArray(source.anchorFiles)) {
312
+ for (const file of source.anchorFiles) {
313
+ const safe = sanitizeAnchorFile(file);
314
+ if (safe === '' || state.anchorFiles.includes(safe)) continue;
315
+ state.anchorFiles.push(safe);
316
+ if (state.anchorFiles.length >= TASK_STATE_ANCHOR_MAX) break;
317
+ }
318
+ }
319
+ state.frameId = typeof source.frameId === 'string' && source.frameId !== '' ? source.frameId : computeFrameId(state);
320
+ return state;
321
+ }
322
+
323
+ /** 内容哈希帧 id:不含时间/会话/本机路径,同一任务状态在任何机器上一致(sha256 前 12 位)。 */
324
+ export function computeFrameId(state) {
325
+ const core = {
326
+ doing: state?.doing ?? '',
327
+ waitingFor: state?.waitingFor ?? null,
328
+ nextStep: state?.nextStep ?? '',
329
+ anchorFiles: state?.anchorFiles ?? [],
330
+ };
331
+ const digest = crypto.createHash('sha256').update(stableStringify(core)).digest('hex');
332
+ return `ts-${digest.slice(0, 12)}`;
333
+ }
334
+
335
+ function stateCore(state) {
336
+ return stableStringify({
337
+ schema: state.schema,
338
+ version: state.version,
339
+ sessionId: state.sessionId,
340
+ turn: state.turn,
341
+ step: state.step,
342
+ doing: state.doing,
343
+ waitingFor: state.waitingFor,
344
+ nextStep: state.nextStep,
345
+ anchorFiles: state.anchorFiles,
346
+ frameId: state.frameId,
347
+ });
348
+ }
349
+
350
+ function sameTaskCore(left, right) {
351
+ return stateCore(left) === stateCore(right);
352
+ }
353
+
354
+ // ── 注入行 ───────────────────────────────────────────────────────────────────
355
+
356
+ /** 把任务状态渲染成一行注入文本(≤220 字);空状态返回 ''。纯函数。 */
357
+ export function renderTaskStateLine(state, { maxChars = TASK_STATE_INJECT_MAX_CHARS } = {}) {
358
+ const source = state && typeof state === 'object' ? state : {};
359
+ const parts = [];
360
+ const doing = sanitizeTaskText(source.doing);
361
+ if (doing !== '') parts.push(`在做什么:${doing}`);
362
+ if (source.waitingFor && source.waitingFor.text) {
363
+ const asking = source.waitingFor.kind === 'decision' ? '等你定' : '等你回答';
364
+ parts.push(`${asking}:${source.waitingFor.text}`);
365
+ }
366
+ const nextStep = sanitizeTaskText(source.nextStep);
367
+ if (nextStep !== '') parts.push(`下一步:${nextStep}`);
368
+ if (parts.length === 0) return '';
369
+ const frameId = typeof source.frameId === 'string' && source.frameId !== '' ? source.frameId : computeFrameId(source);
370
+ const head = `【任务状态 ${frameId}】`;
371
+ const line = `${head}${parts.join('|')}`;
372
+ return clipChars(line, maxChars);
373
+ }
374
+
375
+ // ── 存储(原子写 / 读取 / 捕获 / 幂等)──────────────────────────────────────
376
+
377
+ function readJsonFile(file) {
378
+ let text;
379
+ try {
380
+ text = fs.readFileSync(file, 'utf8');
381
+ } catch (error) {
382
+ if (error && error.code === 'ENOENT') return { ok: false, code: 'E_TASK_STATE_ABSENT', exists: false };
383
+ throw new TaskStateError(errorCode(error, 'E_TASK_STATE_READ'), '读任务状态文件失败', { cause: error?.code });
384
+ }
385
+ let parsed;
386
+ try {
387
+ parsed = JSON.parse(text);
388
+ } catch {
389
+ return { ok: false, code: 'E_TASK_STATE_CORRUPT', exists: true };
390
+ }
391
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
392
+ return { ok: false, code: 'E_TASK_STATE_CORRUPT', exists: true };
393
+ }
394
+ if (parsed.schema !== TASK_STATE_SCHEMA) {
395
+ return { ok: false, code: 'E_TASK_STATE_SCHEMA', exists: true };
396
+ }
397
+ return { ok: true, exists: true, state: normalizeTaskState(parsed) };
398
+ }
399
+
400
+ function writeJsonAtomic(file, value) {
401
+ const dir = path.dirname(file);
402
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
403
+ const tmp = path.join(dir, `.${path.basename(file)}.tmp-${process.pid}-${Date.now()}`);
404
+ const bytes = `${JSON.stringify(value, null, 2)}\n`;
405
+ let fd;
406
+ try {
407
+ fd = fs.openSync(tmp, 'w', 0o600);
408
+ fs.writeFileSync(fd, bytes, 'utf8');
409
+ try {
410
+ fs.fsyncSync(fd);
411
+ } catch {
412
+ // 某些文件系统不支持 fsync,不因耐久性选项失败而丢掉整次写入。
413
+ }
414
+ fs.closeSync(fd);
415
+ fd = undefined;
416
+ fs.renameSync(tmp, file);
417
+ } catch (error) {
418
+ if (fd !== undefined) {
419
+ try { fs.closeSync(fd); } catch { /* ignore */ }
420
+ }
421
+ try { fs.rmSync(tmp, { force: true }); } catch { /* ignore */ }
422
+ throw new TaskStateError(errorCode(error, 'E_TASK_STATE_WRITE'), '写任务状态文件失败', {
423
+ cause: error?.code,
424
+ });
425
+ }
426
+ }
427
+
428
+ function isFresh(state, nowMs) {
429
+ if (!state || !state.updatedAt) return false;
430
+ const stamp = Date.parse(state.updatedAt);
431
+ if (!Number.isFinite(stamp)) return false;
432
+ return nowMs - stamp <= TASK_STATE_FRESH_MS;
433
+ }
434
+
435
+ function mergeTaskState(previous, fields, meta) {
436
+ const state = emptyTaskState();
437
+ const prev = previous && typeof previous === 'object' ? normalizeTaskState(previous) : null;
438
+ state.sessionId = meta.sessionId;
439
+ state.turn = meta.turn;
440
+ state.step = meta.step;
441
+
442
+ const doing = fields.doing ?? '';
443
+ if (doing === '' || (isContinuationText(fields.userTaskRaw) && prev && prev.doing !== '')) {
444
+ state.doing = prev ? prev.doing : '';
445
+ } else {
446
+ state.doing = doing;
447
+ }
448
+
449
+ state.nextStep = fields.nextStep !== undefined && fields.nextStep !== '' ? fields.nextStep : prev ? prev.nextStep : '';
450
+
451
+ if (fields.waitingFor) {
452
+ state.waitingFor = fields.waitingFor;
453
+ } else if (prev && prev.waitingFor && !hasNewUserTurn(prev, meta)) {
454
+ state.waitingFor = prev.waitingFor;
455
+ } else {
456
+ state.waitingFor = null;
457
+ }
458
+
459
+ state.anchorFiles = [];
460
+ const seen = new Set();
461
+ const pushAnchor = (file) => {
462
+ const safe = sanitizeAnchorFile(file);
463
+ if (safe === '' || seen.has(safe) || state.anchorFiles.length >= TASK_STATE_ANCHOR_MAX) return;
464
+ seen.add(safe);
465
+ state.anchorFiles.push(safe);
466
+ };
467
+ for (const file of Array.isArray(fields.anchorFiles) ? fields.anchorFiles : []) pushAnchor(file);
468
+ // 跨到新任务时不继承旧任务的触达文件(避免旧文件把新话题的注入行拖歪)。
469
+ if (prev && meta.keepAnchors !== false) {
470
+ for (const file of prev.anchorFiles) pushAnchor(file);
471
+ }
472
+ state.frameId = computeFrameId(state);
473
+ return state;
474
+ }
475
+
476
+ function hasNewUserTurn(prev, meta) {
477
+ if (!prev) return true;
478
+ return prev.sessionId !== meta.sessionId || prev.turn !== meta.turn;
479
+ }
480
+
481
+ /**
482
+ * 任务状态 store。所有方法只碰 <memoryRoot>/.longlive/workframe/,只读外部文件、绝不写 STATE.md。
483
+ * @param {{memoryRoot: string, now?: ()=>number}} options
484
+ */
485
+ export function createTaskStateStore({ memoryRoot, now } = {}) {
486
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
487
+ throw new TaskStateError('E_NO_MEMORY_ROOT', 'createTaskStateStore 需要 memoryRoot');
488
+ }
489
+ const paths = taskStateDirOf(memoryRoot);
490
+ const clock = typeof now === 'function' ? now : () => Date.now();
491
+
492
+ /** 读取(永不抛):{ok:true,state,fresh} / {ok:false,code,exists}。 */
493
+ function read() {
494
+ try {
495
+ const result = readJsonFile(paths.file);
496
+ if (!result.ok) return result;
497
+ const nowMs = clock();
498
+ return {
499
+ ok: true,
500
+ exists: true,
501
+ state: result.state,
502
+ fresh: isFresh(result.state, nowMs),
503
+ nowMs,
504
+ };
505
+ } catch (error) {
506
+ return { ok: false, code: errorCode(error, 'E_TASK_STATE_READ'), exists: false };
507
+ }
508
+ }
509
+
510
+ /**
511
+ * 捕获一步的任务状态并落盘。
512
+ * @param {{sessionId?:string, turn?:number, step?:number, messages?:object[], previous?:object, keepAnchors?:boolean}} input
513
+ * @returns {{ok:boolean, code?:string, written:boolean, state?:object, fields?:object}}
514
+ */
515
+ function capture({ sessionId = 'unknown', turn = 0, step = 0, messages = [], previous = undefined, keepAnchors = true } = {}) {
516
+ try {
517
+ const nowMs = clock();
518
+ const priorResult = previous === undefined ? read() : { ok: !!previous, state: previous };
519
+ const prior = priorResult && priorResult.ok && priorResult.state ? priorResult.state : null;
520
+ const fields = extractTaskFields(messages);
521
+ const merged = mergeTaskState(prior, fields, {
522
+ sessionId: typeof sessionId === 'string' && sessionId.trim() !== '' ? sessionId.trim() : 'unknown',
523
+ turn: Number.isInteger(turn) && turn >= 0 ? turn : 0,
524
+ step: Number.isInteger(step) && step >= 0 ? step : 0,
525
+ keepAnchors: keepAnchors !== false,
526
+ });
527
+ merged.updatedAt = new Date(nowMs).toISOString();
528
+ if (prior && sameTaskCore(prior, merged)) {
529
+ // 幂等:同一 (session/turn/step/字段) 重复捕获不重写文件(字节不变,updatedAt 保持上次)。
530
+ return { ok: true, written: false, state: prior, fields };
531
+ }
532
+ writeJsonAtomic(paths.file, merged);
533
+ return { ok: true, written: true, state: merged, fields };
534
+ } catch (error) {
535
+ return { ok: false, code: errorCode(error, 'E_TASK_STATE_CAPTURE'), fields: null };
536
+ }
537
+ }
538
+
539
+ /** 渲染注入行(读当前盘上状态);空/坏/过期 → ''。 */
540
+ function renderLine({ allowStale = false } = {}) {
541
+ const result = read();
542
+ if (!result.ok) return { ok: false, code: result.code, text: '' };
543
+ if (!allowStale && !result.fresh) return { ok: false, code: 'E_TASK_STATE_STALE', text: '' };
544
+ const text = renderTaskStateLine(result.state);
545
+ return { ok: text !== '', code: text === '' ? 'E_TASK_STATE_EMPTY' : null, text, state: result.state };
546
+ }
547
+
548
+ function inspect() {
549
+ const result = read();
550
+ return {
551
+ memoryRoot: paths.root,
552
+ file: paths.file,
553
+ ...result,
554
+ preview: result.ok ? renderTaskStateLine(result.state) : '',
555
+ };
556
+ }
557
+
558
+ return { memoryRoot: paths.root, paths, read, capture, renderLine, inspect };
559
+ }
560
+
561
+ export const __test = Object.freeze({
562
+ emptyTaskState,
563
+ normalizeTaskState,
564
+ mergeTaskState,
565
+ sameTaskCore,
566
+ isFresh,
567
+ readJsonFile,
568
+ writeJsonAtomic,
569
+ });