@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
@@ -4,9 +4,10 @@
4
4
  // - up salience +0.5(clamp 0..5,只升);down strength −0.5(clamp 0..9),salience 一列不动;
5
5
  // - down 还要更新 last_used;每轮 ≤2 条、可按 entryId 回滚;反馈账本 feedback.jsonl
6
6
  // (≤2,000 行 / 180d);失败路径写 gate-log 事件 `hg.d20.fail`。
7
- // - 工具入口 memory_feedback 的接线(tools.js)属 W7、本批不改(Q5 选 B);工具入口当前
8
- // 不向模块传 config,因此无 memoryRoot 时按「未接线」抛 E_HG_RECALL_FEEDBACK_UNIMPLEMENTED,
9
- // 保持 fail-closed 与 tools_contract C19b 口径。
7
+ // - 2.3.0(W2.1 D20 接线):tools.js 的 memory_feedback 入口已接上本模块(up/down/rollback/
8
+ // status 全部落盘 + 审计 + 回滚);memory_recall 成功返回后由 tools.js 调 recordRecallUsage
9
+ // 写 used 标记,下一轮召回用 applyFeedbackRanking 按有效 salience/strength 微调排序。
10
+ // 无 memoryRoot 时仍 fail-closed(E_HG_D20_NO_ROOT),不伪造成功。
10
11
  //
11
12
  // fail-closed:任一判定/写卡失败都不静默成功;未落盘前不得改卡。
12
13
 
@@ -50,6 +51,14 @@ export const GATE_EVENT = 'hg.d20.fail';
50
51
  export const FEEDBACK_SCHEMA = 'hardgate-feedback/v1';
51
52
 
52
53
  const DAY_MS = 24 * 60 * 60 * 1000;
54
+ /** 宿主没给 turn 时的「轮」回退粒度(10 分钟):只用于每轮 ≤2 的额度计数,不改变账本语义。 */
55
+ export const ROUND_FALLBACK_MS = 10 * 60 * 1000;
56
+
57
+ function roundKeyOf(input, atMs) {
58
+ if (Number.isInteger(input?.turn) && input.turn >= 0) return input.turn;
59
+ const ms = Number.isFinite(Number(atMs)) ? Number(atMs) : Date.now();
60
+ return Math.floor(ms / ROUND_FALLBACK_MS);
61
+ }
53
62
 
54
63
  function failWithGate(root, code, message) {
55
64
  try {
@@ -109,14 +118,37 @@ function clamp(value, min, max) {
109
118
 
110
119
  function resolveRoot(input, config) {
111
120
  // 只认显式 memoryRoot(input)或显式配置(config.memoryRoot),不落「隐式默认记忆根」:
112
- // tools.js:3095 的 memory_feedback 入口不传 config(Q5 选 B,接线留批 E/H),必须按
113
- // 「未接线」fail-closed 抛 E_HG_RECALL_FEEDBACK_UNIMPLEMENTED(test C19b 口径)。
121
+ // 工具入口(tools.js)接线后由入口把 memRoot(config) 解析结果显式传入;没有根时
122
+ // fail-closed 抛 E_HG_D20_NO_ROOT,不伪造成功、不写任何文件。
114
123
  const direct = typeof input?.memoryRoot === 'string' ? input.memoryRoot.trim() : '';
115
124
  if (direct !== '') return direct;
116
125
  const fromConfig = typeof config?.memoryRoot === 'string' ? config.memoryRoot.trim() : '';
117
126
  return fromConfig;
118
127
  }
119
128
 
129
+ /** 成功反馈的审计行(gate-log):只留 entryId + 卡 sha,不写原始 card 路径 / reason 文本。 */
130
+ function auditFeedback(root, { sessionId, turn, action, row, extra = [] } = {}) {
131
+ try {
132
+ appendGateLog(root, {
133
+ sessionId: typeof sessionId === 'string' && sessionId !== '' ? sessionId : null,
134
+ turn: Number.isInteger(turn) ? turn : 0,
135
+ gate: 'd20',
136
+ decision: 'ok',
137
+ reason: `feedback-${action}`,
138
+ evidence: [
139
+ `entryId=${row?.entryId ?? 'none'}`,
140
+ `cardSha=${sha1Short(row?.card ?? '')}`,
141
+ `field=${row?.field ?? 'none'}`,
142
+ `before=${JSON.stringify(row?.before ?? null)}`,
143
+ `after=${JSON.stringify(row?.after ?? null)}`,
144
+ ...extra,
145
+ ],
146
+ });
147
+ } catch {
148
+ /* 审计写失败不推翻已经落盘的反馈账本:状态以 feedback.jsonl 为准 */
149
+ }
150
+ }
151
+
120
152
  function readLedger(root) {
121
153
  const file = ledgerPath(root);
122
154
  if (!fs.existsSync(file)) return { file, rows: [], corrupt: [] };
@@ -220,7 +252,8 @@ function tryEffective(root, rows, rel) {
220
252
  function perRoundRows(rows, sessionId, turn) {
221
253
  const sid = sessionId ?? null;
222
254
  const tn = Number.isInteger(turn) ? turn : 0;
223
- return rows.filter((row) => row.sessionId === sid && row.turn === tn && row.action !== 'rollback').length;
255
+ // 只数 up/down;rollback / used 审计行不占每轮额度。
256
+ return rows.filter((row) => row.sessionId === sid && row.turn === tn && (row.action === 'up' || row.action === 'down')).length;
224
257
  }
225
258
 
226
259
  function appendRow(root, rows, row, atMs) {
@@ -273,13 +306,8 @@ export function memoryFeedback(input = {}, config = {}) {
273
306
  }
274
307
  const root = resolveRoot(input, config ?? {});
275
308
  if (root === '') {
276
- // 工具入口(tools.js)尚未接线传 config:如实按「未接线」fail-closed,不伪造成功。
277
- const error = new Error(`${UNIMPLEMENTED_CODE}: memoryFeedback requires memoryRoot (tool entry not wired until W7)`);
278
- error.code = UNIMPLEMENTED_CODE;
279
- error.status = 'UNSET';
280
- error.implemented = false;
281
- error.gate = GATE_EVENT;
282
- throw error;
309
+ // 工具入口已接线(2.3.0):没有根仍然 fail-closed,不伪造成功、不写任何文件。
310
+ failWithGate('', 'E_HG_D20_NO_ROOT', 'memoryFeedback requires memoryRoot (input.memoryRoot or config.memoryRoot)');
283
311
  }
284
312
  const action = input.action === undefined ? 'up' : String(input.action);
285
313
  try {
@@ -290,8 +318,16 @@ export function memoryFeedback(input = {}, config = {}) {
290
318
  ok: true,
291
319
  status: 'ok',
292
320
  implemented: true,
321
+ schema: FEEDBACK_SCHEMA,
293
322
  rows: rows.length,
294
323
  corrupt: corrupt.length,
324
+ usedRows: rows.filter((row) => row.action === 'used').length,
325
+ feedbackRows: rows.filter((row) => row.action === 'up' || row.action === 'down').length,
326
+ rollbackRows: rows.filter((row) => row.action === 'rollback').length,
327
+ perRound: perRoundRows(rows, input.sessionId, roundKeyOf(input, Date.now())),
328
+ maxPerRound: MAX_PER_ROUND,
329
+ maxRows: MAX_ROWS,
330
+ retentionDays: RETENTION_DAYS,
295
331
  lastAt: last?.at ?? null,
296
332
  file: ledgerPath(root),
297
333
  };
@@ -299,6 +335,8 @@ export function memoryFeedback(input = {}, config = {}) {
299
335
  const cardRel = input.card ?? input.cardPath;
300
336
  const atMs = nowMsOf(input.now);
301
337
  const { rows } = readLedger(root);
338
+ // 宿主没给 turn 时用 10 分钟桶充当「本轮」,避免每轮额度在 session 生命周期内耗尽。
339
+ const roundInput = { ...input, turn: roundKeyOf(input, atMs) };
302
340
 
303
341
  if (action === 'rollback') {
304
342
  const entryId = typeof input.entryId === 'string' ? input.entryId : '';
@@ -329,17 +367,21 @@ export function memoryFeedback(input = {}, config = {}) {
329
367
  delta: round(-delta),
330
368
  reason: typeof input.reason === 'string' ? input.reason : 'rollback',
331
369
  sessionId: typeof input.sessionId === 'string' ? input.sessionId : null,
332
- turn: Number.isInteger(input.turn) ? input.turn : 0,
370
+ turn: roundInput.turn,
333
371
  at: isoOf(atMs),
334
372
  day: dayString(atMs),
335
373
  };
336
374
  const kept = appendRow(root, rows, row, atMs);
375
+ auditFeedback(root, {
376
+ sessionId: row.sessionId, turn: row.turn, action, row,
377
+ extra: [`rollbackOf=${entryId}`],
378
+ });
337
379
  return { ok: true, action, field, before: row.before, after: row.after, entryId: row.entryId, rollbackOf: entryId, perRound: perRoundRows(kept, row.sessionId, row.turn), total: kept.length };
338
380
  }
339
381
 
340
382
  if (action !== 'up' && action !== 'down') failWithGate(root, 'E_HG_D20_ACTION', `unknown feedback action: ${action}`);
341
- const perRound = perRoundRows(rows, input.sessionId, input.turn);
342
- if (perRound >= MAX_PER_ROUND) failWithGate(root, 'E_HG_D20_PER_ROUND', `per-round feedback limit ${MAX_PER_ROUND} reached (session=${input.sessionId ?? ''}, turn=${input.turn ?? 0})`);
383
+ const perRound = perRoundRows(rows, roundInput.sessionId, roundInput.turn);
384
+ if (perRound >= MAX_PER_ROUND) failWithGate(root, 'E_HG_D20_PER_ROUND', `per-round feedback limit ${MAX_PER_ROUND} reached (session=${roundInput.sessionId ?? ''}, turn=${roundInput.turn})`);
343
385
  const card = readCard(root, cardRel);
344
386
  const field = action === 'up' ? 'salience' : 'strength';
345
387
  const eff = effectiveValues(rows, card);
@@ -349,8 +391,12 @@ export function memoryFeedback(input = {}, config = {}) {
349
391
  else after = clamp(round(before + SALIENCE_DOWN, 2), STRENGTH_MIN, STRENGTH_MAX);
350
392
  // 卡面不写半分值:仅 down 按 Q4 更新 last_used(合法日期列),salience/strength 保持整数。
351
393
  if (action === 'down') writeCard(root, card, { last_used: dayString(atMs) });
352
- const row = buildRow(root, input, card, action, field, before, after, atMs);
394
+ const row = buildRow(root, roundInput, card, action, field, before, after, atMs);
353
395
  const kept = appendRow(root, rows, row, atMs);
396
+ auditFeedback(root, {
397
+ sessionId: row.sessionId, turn: row.turn, action, row,
398
+ extra: [`reasonSha=${sha1Short(row.reason)}`],
399
+ });
354
400
  return {
355
401
  ok: true,
356
402
  action,
@@ -404,3 +450,99 @@ export function readFeedback(input = {}, config = {}) {
404
450
  export function rollbackFeedback(input = {}, config = {}) {
405
451
  return memoryFeedback({ ...input, action: 'rollback' }, config);
406
452
  }
453
+
454
+ /* ------------------------------------------------------------------ *
455
+ * W2.1:召回 used 标记 + 下一轮召回排序反映反馈
456
+ * ------------------------------------------------------------------ */
457
+
458
+ /** 排序微调权重:有效 salience/strength 相对默认基线 3 的偏移(确定性、可复现,无概率)。 */
459
+ export const FEEDBACK_SCORE_WEIGHTS = Object.freeze({ salience: 0.02, strength: 0.01, baseline: 3 });
460
+
461
+ function boostOf(view) {
462
+ if (view === null || view === undefined) return 0;
463
+ const salience = Number(view.salience);
464
+ const strength = Number(view.strength);
465
+ if (!Number.isFinite(salience) || !Number.isFinite(strength)) return 0;
466
+ return round((salience - FEEDBACK_SCORE_WEIGHTS.baseline) * FEEDBACK_SCORE_WEIGHTS.salience
467
+ + (strength - FEEDBACK_SCORE_WEIGHTS.baseline) * FEEDBACK_SCORE_WEIGHTS.strength, 4);
468
+ }
469
+
470
+ /**
471
+ * recordRecallUsage:memory_recall 成功返回后写 used 标记(每个返回的卡一行)。
472
+ * - 只记 card / queryChars / queryKinds / sessionId / turn / at;不记 query 原文(隐私)。
473
+ * - best-effort:调用方负责 try/catch,账本读/写失败不得影响召回结果。
474
+ */
475
+ export function recordRecallUsage(input = {}, config = {}) {
476
+ const root = resolveRoot(input, config);
477
+ if (root === '') return { ok: false, code: 'E_HG_D20_NO_ROOT', used: 0 };
478
+ const cards = Array.isArray(input.cards)
479
+ ? [...new Set(input.cards.filter((item) => typeof item === 'string' && item.trim() !== '').map((item) => item.trim()))]
480
+ : [];
481
+ if (cards.length === 0) return { ok: true, used: 0, total: readLedger(root).rows.length };
482
+ const atMs = nowMsOf(input.now);
483
+ const queryChars = Number.isInteger(input.queryChars) && input.queryChars >= 0 ? input.queryChars : 0;
484
+ const queryKinds = Array.isArray(input.queryKinds)
485
+ ? input.queryKinds.filter((kind) => typeof kind === 'string').slice(0, 8)
486
+ : [];
487
+ const sessionId = typeof input.sessionId === 'string' && input.sessionId !== '' ? input.sessionId : null;
488
+ const turn = Number.isInteger(input.turn) ? input.turn : 0;
489
+ let rows = readLedger(root).rows;
490
+ const entryIds = [];
491
+ for (const card of cards) {
492
+ const row = {
493
+ schema: FEEDBACK_SCHEMA,
494
+ entryId: '',
495
+ action: 'used',
496
+ card,
497
+ queryChars,
498
+ queryKinds,
499
+ sessionId,
500
+ turn,
501
+ at: isoOf(atMs),
502
+ day: dayString(atMs),
503
+ };
504
+ row.entryId = `fb-used-${sha1Short(`${card}|used|${row.at}|${sessionId ?? ''}|${turn}|${entryIds.length}`)}`;
505
+ rows = appendRow(root, rows, row, atMs);
506
+ entryIds.push(row.entryId);
507
+ }
508
+ return { ok: true, used: entryIds.length, entryIds, total: rows.length, file: ledgerPath(root) };
509
+ }
510
+
511
+ /** 单卡有效 salience/strength(无反馈 / 读卡失败返回 null)。 */
512
+ export function effectiveFor(root, rel) {
513
+ try {
514
+ return tryEffective(root, readLedger(root).rows, rel);
515
+ } catch {
516
+ return null;
517
+ }
518
+ }
519
+
520
+ /**
521
+ * applyFeedbackRanking:把上一轮 up/down 反馈反映到召回排序。
522
+ * - 没有 up/down 行时原样返回(identity:零反馈、历史调用行为不变)。
523
+ * - 有反馈时 score 加确定性微调 0.02*(eff.salience-3)+0.01*(eff.strength-3),
524
+ * 再按 adjusted desc / path asc 重排,返回带新 score 的新对象数组。
525
+ */
526
+ export function applyFeedbackRanking(root, results) {
527
+ if (!Array.isArray(results) || results.length < 2) return results;
528
+ let rows;
529
+ try {
530
+ rows = readLedger(root).rows;
531
+ } catch {
532
+ return results;
533
+ }
534
+ if (!rows.some((row) => row.action === 'up' || row.action === 'down')) return results;
535
+ const decorated = [];
536
+ let changed = false;
537
+ for (const row of results) {
538
+ const rel = typeof row?.path === 'string' ? row.path : '';
539
+ const view = rel === '' ? null : tryEffective(root, rows, rel);
540
+ const boost = boostOf(view);
541
+ if (boost !== 0) changed = true;
542
+ decorated.push({ row, adjusted: round((Number(row?.score) || 0) + boost, 6) });
543
+ }
544
+ if (!changed) return results;
545
+ decorated.sort((left, right) => right.adjusted - left.adjusted
546
+ || String(left.row?.path ?? '').localeCompare(String(right.row?.path ?? '')));
547
+ return decorated.map(({ row, adjusted }) => ({ ...row, score: adjusted }));
548
+ }
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
13
  import { memoryRecall } from './recall.js';
14
- import { scanCards } from './index.js';
14
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
15
15
  import { appendAuditRecord } from './audit-records.js';
16
16
  // M11: 统一召回入口(brain.mjs)——空命中时给出候选线索,不改变 hits/证据门形状。
17
17
  import { selectCards as brainSelectCards } from '../recall/brain.mjs';
@@ -132,7 +132,8 @@ export function recallV2(args = {}, config = {}) {
132
132
  const root = memoryRootFromConfig(config);
133
133
 
134
134
  const recalled = memoryRecall({ query, topK: Math.max(topK, 5), status: includeForgotten ? 'any' : 'active' }, { memoryRoot: root });
135
- const cards = new Map((scanCards(root) || []).map((card) => [card.rel, card]));
135
+ // 召回面与 memoryRecall 一致:topics + journal + procedures(程序卡)。
136
+ const cards = new Map((scanCards(root, { dirs: RECALL_SCAN_DIRS }) || []).map((card) => [card.rel, card]));
136
137
  let hits = [];
137
138
  for (const row of Array.isArray(recalled.results) ? recalled.results : []) {
138
139
  if (row?.type === 'event') continue; // D2: event/AutoCard layer is cold archive, not recalled.
@@ -169,7 +170,8 @@ export function recallV2(args = {}, config = {}) {
169
170
  }
170
171
  const gate = evidenceGate({ hits, question: query });
171
172
  // 1.8.2 D2: no auto-card read; hits are curated cards only.
172
- const curatedHits = hits.slice(0, Math.min(2, topK));
173
+ // 2.2.0 lane-B:hits 截断 2→3,避免 procedure 命中被 topics 挤掉。
174
+ const curatedHits = hits.slice(0, Math.min(3, topK));
173
175
  hits = [...curatedHits].slice(0, topK);
174
176
  const finalGate = evidenceGate({ hits, question: query });
175
177
  const fastAnswer = finalGate.fastEligible ? buildFastAnswer({ question: query, hit: hits[0], gate: finalGate }) : null;
@@ -10,7 +10,7 @@
10
10
  // "never decay or merge", not "hidden".
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
- import { scanCards } from './index.js';
13
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
14
14
  import { readVerifiedCardAnchors } from './card-anchors.js';
15
15
  import { searchEventsReadOnly } from './event-index.js';
16
16
  import { isHistoricalQuery, readLifecycle } from './lifecycle.js';
@@ -24,6 +24,9 @@ export const RECALL_STATUSES = Object.freeze(['active', 'locked', 'archived', 'a
24
24
  // SPEC-1.8.11 D9:historical 卡在工具层同样要沉层(与 pre-step 注入的 lifecycleRank 一致),
25
25
  // 但工具层不改条数/过滤:只按权重改分数,同一 lifecycle 内原有分数序不变。
26
26
  export const HISTORICAL_SCORE_WEIGHT = 0.3;
27
+ // 程序卡(procedures/)在召回面给固定加成:动作类 query(发布/安装/回滚/删除…)
28
+ // 必中 procedure 卡;固定系数,不引入概率/阈值判据(工作区 AGENTS.md 第 21 条)。
29
+ export const PROCEDURE_SCORE_WEIGHT = 1.15;
27
30
 
28
31
  const CJK_RUN = /[\u3400-\u9fff]+/g;
29
32
  const ASCII_WORD = /[a-z0-9_]{2,}/g;
@@ -189,7 +192,8 @@ export function memoryRecall(args, config = {}) {
189
192
  // 显式历史查询(以前/旧版/被取代…)不降权;普通查询把 historical 卡乘权重沉下去。
190
193
  const historyQuery = isHistoricalQuery(query);
191
194
 
192
- const scanned = scanCards(root);
195
+ // 召回面扫 topics + journal + procedures(程序卡);索引面 memoryIndex 仍不含 procedures。
196
+ const scanned = scanCards(root, { dirs: RECALL_SCAN_DIRS });
193
197
  const sidecar = readVerifiedCardAnchors({ memoryRoot: root }).links;
194
198
  const includeAuto = args?.includeAuto === true || args?.archive === true;
195
199
  const results = [];
@@ -202,8 +206,10 @@ export function memoryRecall(args, config = {}) {
202
206
  const { score, hits } = scoreCard(query, card);
203
207
  if (score <= 0 || hits.length === 0) continue;
204
208
  const lifecycle = readLifecycle(card);
205
- // historical 只在非历史查询里降权;canonical/普通卡不变(权重 1)。
206
- const weight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
209
+ // historical 只在非历史查询里降权;程序卡给固定加成;canonical/普通卡权重 1。
210
+ const lifecycleWeight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
211
+ const procedureWeight = card.procedure === true ? PROCEDURE_SCORE_WEIGHT : 1;
212
+ const weight = lifecycleWeight * procedureWeight;
207
213
  const weightedScore = weight === 1 ? score : Math.round(score * weight * 100) / 100;
208
214
  const link = sidecar.get(card.rel);
209
215
  results.push({