@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
package/src/tools.js CHANGED
@@ -41,7 +41,7 @@ import { forgetV2 } from './memory/forget-v2.js';
41
41
  import { memoryRecall } from './memory/recall.js';
42
42
  import { recallV2 } from './memory/recall-v2.js';
43
43
  import { memoryProcedure, PROCEDURES_DIR, PROCEDURE_ACTIONS } from './memory/procedure.js';
44
- import { memoryFeedback } from './memory/recall-feedback.mjs';
44
+ import { memoryFeedback, recordRecallUsage, applyFeedbackRanking } from './memory/recall-feedback.mjs';
45
45
  import { memoryConflicts } from './memory/conflicts.js';
46
46
  import { memoryWake as wakeTool } from './memory/wake-bridge.mjs';
47
47
  import { withWriteEvidence as landWithWriteEvidence, UNIMPLEMENTED_CODE as LAND_UNIMPLEMENTED_CODE } from './memory/land.mjs';
@@ -58,6 +58,8 @@ import { normalizeTiering, buildTierHint, DEFAULT_TIERING } from './memory/tiers
58
58
  import { liveUpdate, liveList, liveGet, livePrune } from './live.js';
59
59
  import { sessionIdOfLogFile } from './live-target.js';
60
60
  import { privacyScan } from './recall/privacy.mjs';
61
+ import { appendGateLog } from './recall/gate-log.mjs';
62
+ import { ACTION_KEYWORDS, actionKindsForText } from './gate/action-gate.js';
61
63
  import { searchEventsFts, searchEventsReadOnly } from './memory/event-index.js';
62
64
  import {
63
65
  buildTurnItems,
@@ -2019,6 +2021,118 @@ function memoryTool(name, fn) {
2019
2021
  };
2020
2022
  }
2021
2023
 
2024
+ /**
2025
+ * 2.3.0 动作前回忆门(lane gate-feedback):
2026
+ * - 回执兜底(RT P1-1):动作类 query 的 memory_recall 成功返回即写 gate='action'/ok 回执,
2027
+ * 不再要求命中 procedures/ 卡——procedureNames 可空,evidence 记 actionKind/动作词/query 长度。
2028
+ * - 回执记 actionKind(逗号分隔、可多类),动作门按同 kind 匹配(RT P1-3)。
2029
+ * - 隐私:evidence 不写 query 原文,只写 queryChars + 命中的动作词。
2030
+ * 只读召回本身不变(不写卡、不建 INDEX);回执写失败一律 fail-open,绝不影响召回结果。
2031
+ */
2032
+ function withActionGateReceipt(name, invoke) {
2033
+ return (args, config) => {
2034
+ const result = invoke(args, config);
2035
+ try {
2036
+ writeActionGateReceipt(name, args, result, config);
2037
+ } catch {
2038
+ /* 回执写失败不影响召回:动作门会按「无回执」处理 */
2039
+ }
2040
+ return result;
2041
+ };
2042
+ }
2043
+
2044
+ function turnOfConfig(config) {
2045
+ if (Number.isInteger(config?.turn) && config.turn >= 0) return config.turn;
2046
+ const execTurn = config?.exec?.turn;
2047
+ return Number.isInteger(execTurn) && execTurn >= 0 ? execTurn : null;
2048
+ }
2049
+
2050
+ /**
2051
+ * W2.1(D20)召回反馈接线:memory_recall 成功返回后
2052
+ * 1. 写 used 标记(账本 feedback.jsonl,只记卡路径/query 长度/动作类别,不记 query 原文);
2053
+ * 2. 把上一轮 up/down 反馈反映到本次排序(无反馈时 identity)。
2054
+ * best-effort:任何一步失败都不得影响召回结果。
2055
+ */
2056
+ /**
2057
+ * D20 used 标记只在反馈账本已存在时追加(用户已开始用 memory_feedback 后)。
2058
+ * 默认的 memory_recall 仍是只读:不建 .longlive/、不写盘(M28「recall must be read-only」契约)。
2059
+ */
2060
+ function feedbackLedgerPresent(memoryRoot) {
2061
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return false;
2062
+ try {
2063
+ return fs.existsSync(path.join(memoryRoot, '.longlive', 'hardgate', 'feedback.jsonl'));
2064
+ } catch {
2065
+ return false;
2066
+ }
2067
+ }
2068
+
2069
+ function withRecallFeedback(name, invoke) {
2070
+ return (args, config) => {
2071
+ const result = invoke(args, config);
2072
+ try {
2073
+ if (!result || result.ok !== true || !Array.isArray(result.results) || result.results.length === 0) return result;
2074
+ const memoryRoot = memRoot(config, process.env);
2075
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return result;
2076
+ const query = typeof args?.query === 'string' ? args.query : '';
2077
+ const caller = resolveCallerSessionId(config);
2078
+ const turn = turnOfConfig(config);
2079
+ if (feedbackLedgerPresent(memoryRoot)) {
2080
+ try {
2081
+ recordRecallUsage({
2082
+ memoryRoot,
2083
+ cards: result.results.map((row) => (typeof row?.path === 'string' ? row.path : '')).filter(Boolean),
2084
+ queryChars: query.length,
2085
+ queryKinds: actionKindsForText(query),
2086
+ sessionId: caller.id ?? undefined,
2087
+ turn,
2088
+ });
2089
+ } catch {
2090
+ /* used 标记写失败只影响反馈统计,不影响召回 */
2091
+ }
2092
+ }
2093
+ try {
2094
+ result.results = applyFeedbackRanking(memoryRoot, result.results);
2095
+ } catch {
2096
+ /* 排序微调失败时保留原排序(确定性优先于反馈) */
2097
+ }
2098
+ } catch {
2099
+ /* 反馈接线整体 fail-open */
2100
+ }
2101
+ return result;
2102
+ };
2103
+ }
2104
+
2105
+ function writeActionGateReceipt(name, args, result, config) {
2106
+ if (!result || result.ok !== true || !Array.isArray(result.results)) return;
2107
+ const query = typeof args?.query === 'string' ? args.query : '';
2108
+ if (query.trim() === '') return;
2109
+ const kinds = actionKindsForText(query);
2110
+ if (kinds.length === 0) return;
2111
+ if (!isPlainObject(config)) return;
2112
+ const memoryRoot = memRoot(config, process.env);
2113
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return;
2114
+ const caller = resolveCallerSessionId(config);
2115
+ const matchedKeywords = ACTION_KEYWORDS.filter((keyword) => query.toLowerCase().includes(keyword.toLowerCase()));
2116
+ const procedures = result.results
2117
+ .filter((row) => row && typeof row.path === 'string' && row.path.startsWith('procedures/'))
2118
+ .map((row) => (typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : row.path));
2119
+ appendGateLog(memoryRoot, {
2120
+ sessionId: caller.id,
2121
+ turn: turnOfConfig(config),
2122
+ gate: 'action',
2123
+ decision: 'ok',
2124
+ reason: `recall-tool:${name}`,
2125
+ evidence: [
2126
+ 'source=memory_recall_tool',
2127
+ `actionKind=${kinds.join(',')}`,
2128
+ `actionWords=${matchedKeywords.join('|')}`,
2129
+ `queryChars=${query.length}`,
2130
+ `resultCount=${result.results.length}`,
2131
+ ...(procedures.length > 0 ? [`procedureNames=${procedures.slice(0, 2).join('|')}`] : []),
2132
+ ],
2133
+ });
2134
+ }
2135
+
2022
2136
  /**
2023
2137
  * M10 双路由:写类 memory 工具的落盘门委托。
2024
2138
  * 新路径 = memory/land.mjs(批次 B,当前 fail-closed 骨架);land 未实现时如实回退到旧路径,
@@ -2953,7 +3067,7 @@ export const TOOLS = [
2953
3067
  archive: { type: 'boolean', description: 'archive:true 走冷档 fail-closed 检索(2.0.0 W3b):返回 {ok, archived:true, items, manifestSha, stats};冷档离线/坏 state 抛 E_HG_ARCHIVE_OFFLINE,manifest schema/index 不符抛 E_HG_ARCHIVE_MIGRATE_MISMATCH;未配置冷档则静默空。默认 false(本地卡召回)。' },
2954
3068
  },
2955
3069
  output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
2956
- invoke: memoryTool('memory_recall', memoryRecall),
3070
+ invoke: withActionGateReceipt('memory_recall', memoryTool('memory_recall', withRecallFeedback('memory_recall', memoryRecall))),
2957
3071
  },
2958
3072
  {
2959
3073
  name: 'memory_recall_v2',
@@ -3070,29 +3184,35 @@ export const TOOLS = [
3070
3184
  {
3071
3185
  name: 'memory_feedback',
3072
3186
  description:
3073
- 'Recall feedback (D20): record one real use of a card (up/down ±0.5 salience, down never lowers ' +
3074
- 'salience), with a bounded feedback.jsonl (<=2000 rows / 180d, <=2 per round, rollbackable). ' +
3075
- 'STATUS ONLY TODAY: action "status" returns a structured UNSET (implemented:false) because the ' +
3076
- 'feedback store belongs to a later batch; write actions throw E_HG_RECALL_FEEDBACK_UNIMPLEMENTED. ' +
3077
- 'Fail-closed: no write, no row, no silent success before the store exists.',
3187
+ 'Recall feedback (D20): record one real use of a card. up = salience +0.5 (clamped 0..5, never lowers); ' +
3188
+ 'down = strength -0.5 (clamped 0..9) and never lowers salience; rollback restores one earlier entry by ' +
3189
+ 'entryId; status reports the bounded feedback.jsonl (<=2000 rows / 180d, <=2 up/down per round). Every ' +
3190
+ 'accepted write lands in <memoryRoot>/.longlive/hardgate/feedback.jsonl and leaves one gate="d20" audit row ' +
3191
+ 'in the gate-log (store + audit are both verifiable; rollback never touches the card prose). ' +
3192
+ 'Actions return {ok, action, field, before, after, entryId, perRound, total} so a later rollback can cite ' +
3193
+ 'the exact entryId. Fail-closed: an unknown card, a missing entryId, a duplicate rollback or a missing ' +
3194
+ 'memoryRoot throws instead of reporting a fake success.',
3078
3195
  parameters: {
3079
- action: { type: 'string', enum: ['status', 'up', 'down', 'rollback'], description: 'status = read-only UNSET report; up/down/rollback require the D20 store (not implemented yet).' },
3080
- card: { type: 'string', description: 'Card path (relative to memoryRoot) the feedback is about.' },
3081
- reason: { type: 'string', description: 'Short reason stored with the feedback row.' },
3196
+ action: { type: 'string', enum: ['status', 'up', 'down', 'rollback'], description: 'status = read-only ledger report; up/down/rollback = write one feedback row (+ audit; rollback restores by entryId).' },
3197
+ card: { type: 'string', description: 'Card path (relative to memoryRoot) the feedback is about (up/down).' },
3198
+ path: { type: 'string', description: 'Alias of card (kept for older callers).' },
3199
+ entryId: { type: 'string', description: 'rollback only: entryId returned by an earlier up/down call.' },
3200
+ reason: { type: 'string', description: 'Short reason stored with the feedback row (not written to the audit log).' },
3082
3201
  },
3083
3202
  output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
3084
- invoke: memoryTool('memory_feedback', (args) => {
3085
- if (args.action === undefined || args.action === 'status') {
3086
- return {
3087
- ok: true,
3088
- status: 'UNSET',
3089
- implemented: false,
3090
- code: 'E_HG_RECALL_FEEDBACK_UNIMPLEMENTED',
3091
- batch: 'D',
3092
- message: 'memory_feedback 的落盘存储属于后续批次;本批只登记工具入口,不写 feedback.jsonl。',
3093
- };
3203
+ invoke: memoryTool('memory_feedback', (args, config) => {
3204
+ const memoryRoot = memRoot(config, process.env);
3205
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') {
3206
+ throw memoryError('E_MEMORY_ROOT_UNSET', 'memory_feedback 需要 memoryRoot(config.memoryRoot / $DSH_LONGLIVE_MEMORY_ROOT)');
3094
3207
  }
3095
- return memoryFeedback(args);
3208
+ const caller = resolveCallerSessionId(config);
3209
+ return memoryFeedback({
3210
+ ...args,
3211
+ card: typeof args.card === 'string' && args.card !== '' ? args.card : args.path,
3212
+ memoryRoot,
3213
+ sessionId: caller.id ?? undefined,
3214
+ turn: turnOfConfig(config) ?? undefined,
3215
+ });
3096
3216
  }),
3097
3217
  },
3098
3218
  {
@@ -1,7 +1,7 @@
1
- // src/ui/routes-readonly.js — M2-F 面板只读数据面(16 条 /api/longlive/*)
1
+ // src/ui/routes-readonly.js — M2-F 面板只读数据面(28 条 /api/longlive/*)
2
2
  //
3
3
  // 契约(MEMORY-RECALL-V2-PROPOSAL v2.6.3 §12.3 / §12.7-G2/G3/G4 / §12.11-R9):
4
- // 22 条只读路由,全部过同一道能力令牌门(panel-auth),面板只走 HTTP、
4
+ // 28 条只读路由,全部过同一道能力令牌门(panel-auth),面板只走 HTTP、
5
5
  // 不直连 SQLite、不读 `.longlive/` 之外的路径。
6
6
  // #16 GET /api/longlive/integrity 返回 R8 manifest 校验状态;ok=false 时
7
7
  // **只读展示保留**,动作面由 actions.js 判 401 E_PANEL_INTEGRITY。
@@ -24,6 +24,13 @@ import { readRecallLogRows, summarizeRecallRows } from '../recall/explain.mjs';
24
24
  import { readChannels } from '../role/channels.js';
25
25
  import { readAttentionView, readPersonalityView, readRelationshipsView } from '../role/readers.js';
26
26
  import { readHandoffBoard } from '../handoff/store.js';
27
+ import {
28
+ renderTaskStateLine,
29
+ sanitizeAnchorFile,
30
+ sanitizeTaskText,
31
+ TASK_STATE_FRESH_MS,
32
+ TASK_STATE_SCHEMA,
33
+ } from '../memory/task-state.mjs';
27
34
 
28
35
  import { REVIEW_SCHEMA, normalizeReviewRow } from './actions.js';
29
36
 
@@ -33,7 +40,7 @@ export const EVENTS_LIMIT_MAX = 200;
33
40
  export const LOG_LIMIT_MAX = 200;
34
41
 
35
42
  /** Producer module that will fill each file in later M2 slices (Gate-1 honesty). */
36
- /** R4 P1-6:27 条只读路由的显式 id 预留表(先冻结名字与 id,实现按表注册,不改号段)。 */
43
+ /** R4 P1-6:28 条只读路由的显式 id 预留表(先冻结名字与 id,实现按表注册,不改号段)。 */
37
44
  export const ROUTE_ID_BY_NAME = Object.freeze({
38
45
  flags: 1,
39
46
  board: 2,
@@ -65,6 +72,8 @@ export const ROUTE_ID_BY_NAME = Object.freeze({
65
72
  personality: 26,
66
73
  // 27 release-check:channels
67
74
  channels: 27,
75
+ // 28 W5 体验:workframe(2.3.0 W2.4 task-state 只读展示)
76
+ workframe: 28,
68
77
  })
69
78
 
70
79
  export const READONLY_ROUTES = Object.freeze([
@@ -97,6 +106,8 @@ export const READONLY_ROUTES = Object.freeze([
97
106
  { id: 26, path: '/api/longlive/personality', schema: 'personality/v1', producer: 'src/role/personality.js(state-truth)', dynamic: false },
98
107
  // #27 channels:release-check 注册(state-truth 只提供 src/role/channels.js#readChannels 读取器)。
99
108
  { id: 27, path: '/api/longlive/channels', schema: 'channels/v1', producer: 'src/role/channels.js#readChannels(state-truth 读取器)+ release-check 注册 #27', dynamic: false },
109
+ // #28 workframe:W5 体验只读展示(W2.4 写 `.longlive/workframe/current.json`;面板不新增写路径)。
110
+ { id: 28, path: '/api/longlive/workframe', schema: 'workframe/v1', producer: 'src/memory/task-state.mjs#createTaskStateStore(W2.4 写、W5 只读展示,脱敏)', dynamic: false },
100
111
  ]);
101
112
 
102
113
  /** G3 detail route lives under #12 (one logical route, exact list + `/<id>`). */
@@ -471,6 +482,52 @@ function createDefaultReaders(options) {
471
482
  personality: () => readPersonalityView({ memoryRoot, now, auditKey }),
472
483
  // #27 channels:只读状态(1.8.0 只做宿主内注册与只读,不接真实 QQ 协议,§16.7)。
473
484
  channels: () => readChannels({ memoryRoot, now, auditKey }),
485
+ // #28 workframe:只读展示 `.longlive/workframe/current.json`(W2.4 写、W5 面板展示)。
486
+ // 隐私:面板只回显已 scrub 的短字段,再洗一遍;不暴露 store.inspect() 的 memoryRoot/file 绝对路径;
487
+ // anchorFiles 只回 basename;未知字段一律不回显(白名单)。不新增任何写路径。
488
+ workframe: () => {
489
+ const read = readJson(path.join(base, 'workframe', 'current.json'));
490
+ if (!read.ok) {
491
+ return {
492
+ schema: 'workframe/v1',
493
+ present: false,
494
+ code: read.code === 'ENOENT' ? 'E_WORKFRAME_ABSENT' : read.code,
495
+ };
496
+ }
497
+ const raw = read.value && typeof read.value === 'object' && !Array.isArray(read.value) ? read.value : null;
498
+ if (raw === null || raw.schema !== TASK_STATE_SCHEMA) {
499
+ return { schema: 'workframe/v1', present: false, code: 'E_WORKFRAME_SCHEMA' };
500
+ }
501
+ const updatedMs = typeof raw.updatedAt === 'string' ? Date.parse(raw.updatedAt) : NaN;
502
+ const ageMs = Number.isFinite(updatedMs) ? Math.max(0, now().getTime() - updatedMs) : null;
503
+ const waiting = raw.waitingFor;
504
+ const waitingFor =
505
+ waiting && typeof waiting === 'object' && (waiting.kind === 'decision' || waiting.kind === 'question')
506
+ && typeof waiting.text === 'string' && waiting.text.trim() !== ''
507
+ ? { kind: waiting.kind, text: sanitizeTaskText(waiting.text, { maxChars: 60 }) }
508
+ : null;
509
+ const anchorFiles = Array.isArray(raw.anchorFiles)
510
+ ? [...new Set(raw.anchorFiles.map((file) => sanitizeAnchorFile(file)).filter(Boolean))].slice(0, 5)
511
+ : [];
512
+ const view = {
513
+ schema: 'workframe/v1',
514
+ present: true,
515
+ // 24h 之外标 stale(与 W2.4 注入的新鲜度窗口同口径),仍只读展示,不让旧任务“假装新鲜”。
516
+ fresh: ageMs !== null && ageMs <= TASK_STATE_FRESH_MS,
517
+ stale: !(ageMs !== null && ageMs <= TASK_STATE_FRESH_MS),
518
+ updatedAt: Number.isFinite(updatedMs) ? new Date(updatedMs).toISOString() : null,
519
+ ageMs,
520
+ sessionId: sanitizeTaskText(raw.sessionId, { maxChars: 64 }),
521
+ turn: Number.isInteger(raw.turn) && raw.turn >= 0 ? raw.turn : 0,
522
+ step: Number.isInteger(raw.step) && raw.step >= 0 ? raw.step : 0,
523
+ frameId: typeof raw.frameId === 'string' ? sanitizeTaskText(raw.frameId, { maxChars: 32 }) : null,
524
+ doing: sanitizeTaskText(raw.doing),
525
+ waitingFor,
526
+ nextStep: sanitizeTaskText(raw.nextStep),
527
+ anchorFiles,
528
+ };
529
+ return { ...view, preview: renderTaskStateLine(view) };
530
+ },
474
531
  integrity: () => {
475
532
  if (options.integrity && typeof options.integrity.status === 'function') {
476
533
  return { schema: 'integrity/v1', ...options.integrity.status() };
@@ -643,6 +700,7 @@ export function createReadonlyRouter(options = {}) {
643
700
  [25, () => readers.relationships()],
644
701
  [26, () => readers.personality()],
645
702
  [27, () => readers.channels()],
703
+ [28, () => readers.workframe()],
646
704
  ]);
647
705
  for (const route of READONLY_ROUTES) {
648
706
  if (!HANDLERS_BY_ID.has(route.id)) {
@@ -673,7 +731,7 @@ function warnOnce(key, error) {
673
731
  }
674
732
 
675
733
  /**
676
- * Register the 16 read-only routes on the host Web server.
734
+ * Register the 28 read-only routes on the host Web server.
677
735
  * A profile without a Web server simply gets no route; activation never depends on it.
678
736
  */
679
737
  export function registerReadonlyRoutes(ctx, options = {}) {
@@ -737,7 +795,7 @@ export function registerReadonlyRoutes(ctx, options = {}) {
737
795
  }
738
796
  }
739
797
  // G3 detail route (`/api/longlive/distill/<id>`) is served by a prefix
740
- // route so it does not widen the documented 16-route count.
798
+ // route so it does not widen the documented 28-route count.
741
799
  try {
742
800
  const dispose = webServer.register({ kind: 'prefix', path: DISTILL_DETAIL_PREFIX, handler: handleRequest });
743
801
  if (typeof dispose === 'function' && typeof webCtx.effect === 'function') {