cortico-world-memory-core 0.1.1 → 0.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.
- package/CHANGELOG.md +38 -0
- package/ENV_PROMPT.md +1 -1
- package/README.md +29 -4
- package/assets/screenshots/graph.png +0 -0
- package/assets/screenshots/maintenance.png +0 -0
- package/assets/screenshots/table.png +0 -0
- package/assets/screenshots/timeline.png +0 -0
- package/describe.json +264 -0
- package/icon.svg +32 -0
- package/package.json +72 -49
- package/src/config.ts +19 -4
- package/src/recall.ts +6 -2
- package/src/site.ts +1 -0
- package/src/store.ts +211 -16
- package/src/tools.ts +7 -2
- package/src/world.ts +151 -31
- package/webui/app.js +141 -44
- package/webui/style.css +7 -0
package/src/store.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* 卡片表、对话原文、日程与状态的文件层。
|
|
3
3
|
* 只碰本插件自己的数据目录;四套旧记忆由 importer.ts 只读导入,不改原文件。
|
|
4
4
|
*/
|
|
5
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
5
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
|
|
@@ -68,6 +68,22 @@ export interface CoreState {
|
|
|
68
68
|
proactiveCount?: number;
|
|
69
69
|
lastNightlyDay?: string;
|
|
70
70
|
rawWatermark?: number;
|
|
71
|
+
/** 水位是按哪一版捕获逻辑推进的。旧版用了错的 range 语义,水位不可信,见 CAPTURE_WATERMARK_VERSION。 */
|
|
72
|
+
watermarkVersion?: number;
|
|
73
|
+
/** 历史原文回放只做一次,做完记下时间。 */
|
|
74
|
+
backfillDoneAt?: string;
|
|
75
|
+
/** 回放开始时间:只在开始那一刻倒水位,中断后下次接着跑,不重复从头扫。 */
|
|
76
|
+
backfillStartedAt?: string;
|
|
77
|
+
/** 上一次捕获的体检结果:扫了多少、留下多少、被白名单挡掉的 key 样例。 */
|
|
78
|
+
captureDebug?: {
|
|
79
|
+
at: string;
|
|
80
|
+
scanned: number;
|
|
81
|
+
kept: number;
|
|
82
|
+
keys: string[];
|
|
83
|
+
/** 回放没跑完时,本轮从哪扫到哪,方便看进度。 */
|
|
84
|
+
backfillFrom?: number;
|
|
85
|
+
backfillTo?: number;
|
|
86
|
+
};
|
|
71
87
|
}
|
|
72
88
|
|
|
73
89
|
export function ensureDir(dir: string): void {
|
|
@@ -396,12 +412,31 @@ export class CardStore {
|
|
|
396
412
|
return groups.sort((x, y) => y.score - x.score);
|
|
397
413
|
}
|
|
398
414
|
|
|
399
|
-
/**
|
|
400
|
-
|
|
415
|
+
/**
|
|
416
|
+
* 疑似作废:一类是文案里自己写了「取消了 / 改到 / 作废」,
|
|
417
|
+
* 另一类是放旧了没人再碰——90 天没被召回、从没带过权重、权重还低。
|
|
418
|
+
* 两类都只是候选,仍然要人点一下才退休。
|
|
419
|
+
*/
|
|
420
|
+
stale(limit = 50, now = Date.now()): Card[] {
|
|
401
421
|
const re = /取消|黄了|作废|不去了|改成|改到|算了|不用了/;
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
422
|
+
const hit: Card[] = [];
|
|
423
|
+
const aged: Card[] = [];
|
|
424
|
+
for (const c of this.active()) {
|
|
425
|
+
if (re.test(c.text)) {
|
|
426
|
+
hit.push(c);
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
const born = Date.parse(c.createdAt);
|
|
430
|
+
if (!Number.isFinite(born)) continue;
|
|
431
|
+
const last = Date.parse(c.lastUsedAt ?? '') || born;
|
|
432
|
+
const quietDays = (now - last) / 86_400_000;
|
|
433
|
+
if (quietDays < 90) continue;
|
|
434
|
+
if ((c.uses || 0) > 1) continue;
|
|
435
|
+
if (c.weight > 0.45) continue;
|
|
436
|
+
if (c.kind === 'promise' && !c.done) continue;
|
|
437
|
+
aged.push(c);
|
|
438
|
+
}
|
|
439
|
+
return [...hit.sort((a, b) => b.createdAt.localeCompare(a.createdAt)), ...aged]
|
|
405
440
|
.slice(0, limit);
|
|
406
441
|
}
|
|
407
442
|
|
|
@@ -492,16 +527,31 @@ export class CardStore {
|
|
|
492
527
|
}
|
|
493
528
|
}
|
|
494
529
|
|
|
530
|
+
const DAY_FMT = new Intl.DateTimeFormat('sv-SE', { year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
531
|
+
|
|
532
|
+
/** 事件属于哪一天(本地时区),归档文件按这个命名。 */
|
|
533
|
+
function dayKeyOf(iso: string | undefined): string {
|
|
534
|
+
const at = Date.parse(iso ?? '');
|
|
535
|
+
if (!Number.isFinite(at)) return '';
|
|
536
|
+
return DAY_FMT.format(new Date(at));
|
|
537
|
+
}
|
|
538
|
+
|
|
495
539
|
export class RawLog {
|
|
496
540
|
private entries: RawEntry[] = [];
|
|
497
541
|
private readonly file: string;
|
|
542
|
+
private readonly archiveDir: string;
|
|
498
543
|
private readonly retentionDays: number;
|
|
544
|
+
private readonly archiveDays: number;
|
|
499
545
|
|
|
500
|
-
constructor(dir: string, retentionDays: number) {
|
|
546
|
+
constructor(dir: string, retentionDays: number, archiveDays = 90) {
|
|
501
547
|
this.retentionDays = Math.max(1, Number(retentionDays) || 7);
|
|
548
|
+
this.archiveDays = Math.max(0, Number(archiveDays) || 0);
|
|
502
549
|
ensureDir(dir);
|
|
503
550
|
this.file = join(dir, 'turns.jsonl');
|
|
551
|
+
this.archiveDir = join(dir, 'archive');
|
|
552
|
+
ensureDir(this.archiveDir);
|
|
504
553
|
this.load();
|
|
554
|
+
this.purgeArchive();
|
|
505
555
|
}
|
|
506
556
|
|
|
507
557
|
private load(): void {
|
|
@@ -509,23 +559,140 @@ export class RawLog {
|
|
|
509
559
|
if (!existsSync(this.file)) return;
|
|
510
560
|
const cutoff = Date.now() - this.retentionDays * 86_400_000;
|
|
511
561
|
const kept: RawEntry[] = [];
|
|
562
|
+
const expired: RawEntry[] = [];
|
|
512
563
|
for (const line of readFileSync(this.file, 'utf8').split('\n')) {
|
|
513
564
|
if (!line.trim()) continue;
|
|
514
565
|
try {
|
|
515
566
|
const e = JSON.parse(line) as RawEntry;
|
|
516
567
|
if (!e || typeof e.text !== 'string') continue;
|
|
517
|
-
|
|
568
|
+
const at = Date.parse(e.ts);
|
|
569
|
+
if (!Number.isFinite(at)) continue;
|
|
570
|
+
(at >= cutoff ? kept : expired).push(e);
|
|
518
571
|
} catch {
|
|
519
572
|
// 跳过坏行
|
|
520
573
|
}
|
|
521
574
|
}
|
|
522
575
|
this.entries = kept;
|
|
576
|
+
// 文件可能是「老版本写的最后几行 + 补录回来的开头几行」拼起来的,按 cursor 归一,
|
|
577
|
+
// 不然原文页会按数组顺序显示成 8:25 → 10:32 → 8:24 这种乱序
|
|
578
|
+
this.sortEntries();
|
|
579
|
+
// 过期的挪进按天归档,不再直接抹掉:要翻旧日子用 mode=archive
|
|
580
|
+
// 传已归档游标:启动时文件里可能还留着上次归档过的行(老版本写的),别再写一遍
|
|
581
|
+
if (expired.length) this.archive(expired, this.archivedCursors());
|
|
523
582
|
this.rewrite();
|
|
524
583
|
} catch {
|
|
525
584
|
this.entries = [];
|
|
526
585
|
}
|
|
527
586
|
}
|
|
528
587
|
|
|
588
|
+
/** 归档里已经有过的游标。只在启动时算一次,避免重启后把同一行反复写进归档。 */
|
|
589
|
+
private archivedCursors(): Set<number> {
|
|
590
|
+
const set = new Set<number>();
|
|
591
|
+
for (const { file } of this.archiveFiles()) {
|
|
592
|
+
try {
|
|
593
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
594
|
+
if (!line.trim()) continue;
|
|
595
|
+
try {
|
|
596
|
+
const e = JSON.parse(line) as RawEntry;
|
|
597
|
+
if (typeof e.cursor === 'number') set.add(e.cursor);
|
|
598
|
+
} catch {
|
|
599
|
+
// 跳过坏行
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
} catch {
|
|
603
|
+
// 读不出就当作没归档过
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return set;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** 按天追加到 archive/YYYY-MM-DD.jsonl,只写不读,读的时候再按需扫。 */
|
|
610
|
+
private archive(items: readonly RawEntry[], seen?: Set<number>): void {
|
|
611
|
+
const buckets = new Map<string, string[]>();
|
|
612
|
+
for (const e of items) {
|
|
613
|
+
if (seen?.has(e.cursor)) continue;
|
|
614
|
+
const day = dayKeyOf(e.ts);
|
|
615
|
+
if (!day) continue;
|
|
616
|
+
const line = JSON.stringify(e);
|
|
617
|
+
const list = buckets.get(day);
|
|
618
|
+
if (list) list.push(line);
|
|
619
|
+
else buckets.set(day, [line]);
|
|
620
|
+
}
|
|
621
|
+
for (const [day, lines] of buckets) {
|
|
622
|
+
try {
|
|
623
|
+
appendFileSync(join(this.archiveDir, `${day}.jsonl`), `${lines.join('\n')}\n`, 'utf8');
|
|
624
|
+
} catch {
|
|
625
|
+
// 归档失败不影响热数据
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
private archiveFiles(desc = false): Array<{ day: string; file: string }> {
|
|
631
|
+
try {
|
|
632
|
+
const names = readdirSync(this.archiveDir)
|
|
633
|
+
.filter((n) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n))
|
|
634
|
+
.sort();
|
|
635
|
+
if (desc) names.reverse();
|
|
636
|
+
return names.map((n) => ({ day: n.slice(0, 10), file: join(this.archiveDir, n) }));
|
|
637
|
+
} catch {
|
|
638
|
+
return [];
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** 归档保留天数,0 = 永久。 */
|
|
643
|
+
private purgeArchive(): void {
|
|
644
|
+
if (!this.archiveDays) return;
|
|
645
|
+
const cutoff = dayKeyOf(new Date(Date.now() - this.archiveDays * 86_400_000).toISOString());
|
|
646
|
+
for (const { day, file } of this.archiveFiles()) {
|
|
647
|
+
if (day >= cutoff) continue;
|
|
648
|
+
try {
|
|
649
|
+
unlinkSync(file);
|
|
650
|
+
} catch {
|
|
651
|
+
// ignore
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** 归档概况,给界面显示。 */
|
|
657
|
+
stats(): { days: number; bytes: number; oldest: string } {
|
|
658
|
+
const files = this.archiveFiles();
|
|
659
|
+
let bytes = 0;
|
|
660
|
+
for (const f of files) {
|
|
661
|
+
try {
|
|
662
|
+
bytes += statSync(f.file).size;
|
|
663
|
+
} catch {
|
|
664
|
+
// ignore
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return { days: files.length, bytes, oldest: files[0]?.day ?? '' };
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** 翻归档:默认最近 30 天,最多 8000 行。只给 mode=archive 用,不进常规召回。 */
|
|
671
|
+
readArchive(days = 30, maxEntries = 8000): RawEntry[] {
|
|
672
|
+
const span = Math.max(1, Math.min(365, Number(days) || 30));
|
|
673
|
+
const fromDay = dayKeyOf(new Date(Date.now() - span * 86_400_000).toISOString());
|
|
674
|
+
const out: RawEntry[] = [];
|
|
675
|
+
for (const { day, file } of this.archiveFiles(true)) {
|
|
676
|
+
if (out.length >= maxEntries) break;
|
|
677
|
+
if (day < fromDay) continue;
|
|
678
|
+
try {
|
|
679
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
680
|
+
if (!line.trim()) continue;
|
|
681
|
+
try {
|
|
682
|
+
const e = JSON.parse(line) as RawEntry;
|
|
683
|
+
if (e && typeof e.text === 'string') out.push(e);
|
|
684
|
+
} catch {
|
|
685
|
+
// 跳过坏行
|
|
686
|
+
}
|
|
687
|
+
if (out.length >= maxEntries) break;
|
|
688
|
+
}
|
|
689
|
+
} catch {
|
|
690
|
+
// ignore
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
return out.sort((a, b) => a.cursor - b.cursor);
|
|
694
|
+
}
|
|
695
|
+
|
|
529
696
|
private rewrite(): void {
|
|
530
697
|
try {
|
|
531
698
|
writeFileSync(this.file, this.entries.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf8');
|
|
@@ -551,19 +718,47 @@ export class RawLog {
|
|
|
551
718
|
this.rewrite();
|
|
552
719
|
}
|
|
553
720
|
|
|
721
|
+
/** cursor 是宿主分配的单调节,拿它排最可靠;ts 在补录数据里不一定跟 cursor 同序。 */
|
|
722
|
+
private sortEntries(): void {
|
|
723
|
+
this.entries.sort((a, b) => a.cursor - b.cursor);
|
|
724
|
+
}
|
|
725
|
+
|
|
554
726
|
add(items: RawEntry[]): number {
|
|
555
727
|
if (!items.length) return 0;
|
|
556
|
-
|
|
728
|
+
// 回放时一次几千行,用 Set 判重,别拿 some() 平方级扫
|
|
729
|
+
const have = new Set(this.entries.map((e) => e.cursor));
|
|
730
|
+
const fresh = items.filter((item) => !have.has(item.cursor));
|
|
557
731
|
if (!fresh.length) return 0;
|
|
558
732
|
this.entries.push(...fresh);
|
|
559
733
|
const cutoff = Date.now() - this.retentionDays * 86_400_000;
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
734
|
+
const keep: RawEntry[] = [];
|
|
735
|
+
const expired: RawEntry[] = [];
|
|
736
|
+
for (const e of this.entries) {
|
|
737
|
+
const at = Date.parse(e.ts);
|
|
738
|
+
if (!Number.isFinite(at) || at < cutoff) expired.push(e);
|
|
739
|
+
else keep.push(e);
|
|
740
|
+
}
|
|
741
|
+
// 超过 4000 行的老行也归档,不丢
|
|
742
|
+
if (keep.length > 4000) {
|
|
743
|
+
const over = keep.length - 4000;
|
|
744
|
+
expired.push(...keep.slice(0, over));
|
|
745
|
+
this.entries = keep.slice(over);
|
|
746
|
+
} else {
|
|
747
|
+
this.entries = keep;
|
|
748
|
+
}
|
|
749
|
+
if (expired.length) this.archive(expired);
|
|
750
|
+
this.sortEntries();
|
|
751
|
+
// 只把「还在热数据里」的新行写文件。过期的新行已经进归档了,留在 turns.jsonl 里
|
|
752
|
+
// 会让下次启动再归档一遍(回放时会重复写)。
|
|
753
|
+
const hot = new Set(this.entries.map((e) => e.cursor));
|
|
754
|
+
const writable = fresh.filter((e) => hot.has(e.cursor));
|
|
755
|
+
if (writable.length) {
|
|
756
|
+
try {
|
|
757
|
+
appendFileSync(this.file, writable.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf8');
|
|
758
|
+
} catch {
|
|
759
|
+
// ignore
|
|
760
|
+
}
|
|
566
761
|
}
|
|
567
|
-
return
|
|
762
|
+
return writable.length;
|
|
568
763
|
}
|
|
569
764
|
}
|
package/src/tools.ts
CHANGED
|
@@ -47,12 +47,17 @@ export const TOOL_SPECS: ToolSpec[] = [
|
|
|
47
47
|
name: 'mcore_recall',
|
|
48
48
|
description:
|
|
49
49
|
'查记忆。不传 query 就是最近几条;传 query 按内容搜,最近 7 天的对话原文和工作区的笔记文件也会一起搜;'
|
|
50
|
-
+ 'mode=open
|
|
50
|
+
+ 'mode=open 看还没做完的承诺与今天的安排;mode=archive 翻归档里的旧对话(要带 query)。'
|
|
51
|
+
+ '对方提到人、事、日期、旧约定,或问「你还记得吗」时先查再答。',
|
|
51
52
|
parameters: obj(
|
|
52
53
|
{
|
|
53
54
|
query: { type: 'string', description: '要查的内容,几个关键词就够' },
|
|
54
55
|
kind: { type: 'string', enum: ['fact', 'self', 'episode', 'promise', 'note'], description: '只看某一类' },
|
|
55
|
-
mode: {
|
|
56
|
+
mode: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
enum: ['search', 'recent', 'open', 'archive'],
|
|
59
|
+
description: '默认 search;没给 query 按 recent 处理',
|
|
60
|
+
},
|
|
56
61
|
days: { type: 'integer', minimum: 1, maximum: 3650, description: '只看最近这么多天' },
|
|
57
62
|
limit: { type: 'integer', minimum: 1, maximum: 12, description: '最多几条,默认 5' },
|
|
58
63
|
},
|
package/src/world.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { join } from 'node:path';
|
|
|
13
13
|
import { randomUUID } from 'node:crypto';
|
|
14
14
|
import type { ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
|
|
15
15
|
import type { WorldContext } from 'cortico/world.ts';
|
|
16
|
-
import { MEMORY_CORE_CONFIG_GROUP, type MemoryCoreConfig } from './config.ts';
|
|
16
|
+
import { MEMORY_CORE_CONFIG_GROUP, MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
|
|
17
17
|
import { TOOL_SPECS } from './tools.ts';
|
|
18
18
|
import {
|
|
19
19
|
CARD_KINDS,
|
|
@@ -38,6 +38,16 @@ const ENV_PROMPT_FILE = fileURLToPath(new URL('../ENV_PROMPT.md', import.meta.ur
|
|
|
38
38
|
const WEB_DIR = fileURLToPath(new URL('../webui/', import.meta.url));
|
|
39
39
|
const TICK_MS = 60_000;
|
|
40
40
|
|
|
41
|
+
/**
|
|
42
|
+
* 捕获水位的可信版本号。
|
|
43
|
+
* v1 用 `range({fromCursor, limit})` 分页,但宿主的 limit 是「从区间末尾取」,
|
|
44
|
+
* 一次就把水位推到历史末尾、前面的全跳过。升到 v2 后旧水位作废,自动重放一遍。
|
|
45
|
+
*/
|
|
46
|
+
const CAPTURE_WATERMARK_VERSION = 2;
|
|
47
|
+
/** 一次 range 的窗口宽度。cursor 是全局连续的,按窗口边界推进,窗口内没有匹配也能往前走。
|
|
48
|
+
* 取大一点:宿主每次 range 都要遍历一遍分片,窗口太碎会让回放变成几百次全表扫描。 */
|
|
49
|
+
const CAPTURE_BATCH = 2_000;
|
|
50
|
+
|
|
41
51
|
function clip(text: string, limit: number): string {
|
|
42
52
|
const s = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
43
53
|
return s.length > limit ? `${s.slice(0, limit)}…` : s;
|
|
@@ -53,22 +63,46 @@ function str(value: unknown, limit = 200): string {
|
|
|
53
63
|
return typeof value === 'string' ? clip(value, limit) : '';
|
|
54
64
|
}
|
|
55
65
|
|
|
56
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* 事件正文外层常裹着东西,剥干净的才是对方说的话:
|
|
68
|
+
* - `[星邮消息] {"text":"..."}` —— JSON 壳;
|
|
69
|
+
* - `[11-03 周二 18:04] [typed] 月:在吗` —— 宿主加的抬头(时间 / 输入方式 / 说话人);
|
|
70
|
+
* - `【QQ私聊 22:37 月(QQ:1940008084)】:#-479828398 有点` —— QQ 那层壳 + 消息号;
|
|
71
|
+
* - `[23:34] [answer] 月回答「…」:选了第 1 项「…」` —— 选项卡的答案,只留选了什么。
|
|
72
|
+
*/
|
|
57
73
|
function extractUserText(raw: string): string {
|
|
58
|
-
|
|
59
|
-
const m = /^\[[^\]]{0,12}消息\]\s*(\{[\s\S]*\})$/.exec(text
|
|
74
|
+
let text = String(raw ?? '').trim();
|
|
75
|
+
const m = /^\[[^\]]{0,12}消息\]\s*(\{[\s\S]*\})$/.exec(text);
|
|
60
76
|
if (m) {
|
|
61
77
|
try {
|
|
62
78
|
const obj = JSON.parse(m[1]) as Record<string, unknown>;
|
|
63
79
|
for (const key of ['text', 'message', 'content', 'msg']) {
|
|
64
80
|
const v = obj[key];
|
|
65
|
-
if (typeof v === 'string' && v.trim())
|
|
81
|
+
if (typeof v === 'string' && v.trim()) {
|
|
82
|
+
text = v.trim();
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
66
85
|
}
|
|
67
86
|
} catch {
|
|
68
87
|
// 不是 JSON 就按原样
|
|
69
88
|
}
|
|
70
89
|
}
|
|
71
|
-
|
|
90
|
+
// 宿主给每层壳的顺序不固定(【】、#消息号、[时间] [输入方式]、说话人:),
|
|
91
|
+
// 一轮一轮剥到不再变化为止;名字那一步排除数字开头,免得把「18:30 开会」吃掉。
|
|
92
|
+
let out = text;
|
|
93
|
+
for (let i = 0; i < 4; i += 1) {
|
|
94
|
+
const next = out
|
|
95
|
+
.replace(/^【[^】]{0,40}】[::]?\s*/, '')
|
|
96
|
+
.replace(/^#-?\d+\s*/, '')
|
|
97
|
+
.replace(/^\[[^\]]{0,24}\]\s*/, '')
|
|
98
|
+
.replace(/^(?![\[\d])[^\s::\d]{1,12}[::]\s*/, '');
|
|
99
|
+
if (next === out) break;
|
|
100
|
+
out = next;
|
|
101
|
+
}
|
|
102
|
+
return out
|
|
103
|
+
.replace(/^[^「」]{0,6}回答「[^」]{0,80}」[::]\s*/, '')
|
|
104
|
+
.replace(/^自己写了[::]\s*/, '')
|
|
105
|
+
.trim();
|
|
72
106
|
}
|
|
73
107
|
|
|
74
108
|
export class MemoryCoreWorld implements World {
|
|
@@ -96,7 +130,11 @@ export class MemoryCoreWorld implements World {
|
|
|
96
130
|
this.dataDir = join(base, 'memory-core');
|
|
97
131
|
ensureDir(this.dataDir);
|
|
98
132
|
this.store = new CardStore(this.dataDir);
|
|
99
|
-
this.raw = new RawLog(
|
|
133
|
+
this.raw = new RawLog(
|
|
134
|
+
this.dataDir,
|
|
135
|
+
Math.max(1, Number(ctx.cfg?.rawRetentionDays ?? 7)),
|
|
136
|
+
Math.max(0, Number(ctx.cfg?.rawArchiveDays ?? 90)),
|
|
137
|
+
);
|
|
100
138
|
this.state = createInitialState(new Date(), this.tz(), this.cfg());
|
|
101
139
|
this.load();
|
|
102
140
|
}
|
|
@@ -166,7 +204,11 @@ export class MemoryCoreWorld implements World {
|
|
|
166
204
|
{
|
|
167
205
|
label: '对话原文',
|
|
168
206
|
state: cfg.captureTurns ? 'online' : 'offline',
|
|
169
|
-
hint: cfg.captureTurns
|
|
207
|
+
hint: cfg.captureTurns
|
|
208
|
+
? `${this.raw.size} 行,近 ${cfg.rawRetentionDays} 天${
|
|
209
|
+
this.raw.stats().days ? ` · 归档 ${this.raw.stats().days} 天` : ''
|
|
210
|
+
}`
|
|
211
|
+
: '已关闭',
|
|
170
212
|
},
|
|
171
213
|
],
|
|
172
214
|
badges: [
|
|
@@ -333,6 +375,7 @@ export class MemoryCoreWorld implements World {
|
|
|
333
375
|
scopes: this.store.scopes(),
|
|
334
376
|
},
|
|
335
377
|
docs: { enabled: Boolean(cfg.workspaceScanEnabled), count: docs.length, dirs: cfg.workspaceScanEnabled ? expandDirs(cfg.workspaceDirs, this.ctx.botDir) : [] },
|
|
378
|
+
archive: this.raw.stats(),
|
|
336
379
|
site: { port: origin ? Number(new URL(origin).port) : 0, origin },
|
|
337
380
|
};
|
|
338
381
|
}
|
|
@@ -557,6 +600,16 @@ export class MemoryCoreWorld implements World {
|
|
|
557
600
|
return lines.length ? lines.join('\n') : '没有未完成的事。';
|
|
558
601
|
}
|
|
559
602
|
|
|
603
|
+
if (mode === 'archive') {
|
|
604
|
+
if (!query) return '翻归档要带 query,给几个关键词。';
|
|
605
|
+
const span = num(args.days, 30, 1, 3650);
|
|
606
|
+
const hits = rankRaw(this.raw.readArchive(span), query, Math.max(1, Math.min(limit, 8)));
|
|
607
|
+
if (!hits.length) return `归档里没找到「${clip(query, 20)}」。`;
|
|
608
|
+
const out: string[] = ['【归档原文】'];
|
|
609
|
+
for (const hit of hits) out.push(`· [${formatLocal(hit.ts, tz).slice(0, 10)}] ${clip(hit.text, 110)}`);
|
|
610
|
+
return out.join('\n').slice(0, maxChars + 40);
|
|
611
|
+
}
|
|
612
|
+
|
|
560
613
|
const cards = rankCards(this.store.active(), {
|
|
561
614
|
query: mode === 'search' ? query : undefined,
|
|
562
615
|
kind: str(args.kind, 20) || undefined,
|
|
@@ -684,7 +737,10 @@ export class MemoryCoreWorld implements World {
|
|
|
684
737
|
try {
|
|
685
738
|
const now = new Date();
|
|
686
739
|
advance(this.state, now, this.tz(), this.cfg());
|
|
687
|
-
this.capture(
|
|
740
|
+
this.capture(
|
|
741
|
+
Boolean(this.cfg().captureBackfill)
|
|
742
|
+
&& (Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION || !this.state.backfillDoneAt),
|
|
743
|
+
);
|
|
688
744
|
await this.maybeContext(now);
|
|
689
745
|
await this.maybeRemind(now);
|
|
690
746
|
await this.maybeProactive(now);
|
|
@@ -701,38 +757,102 @@ export class MemoryCoreWorld implements World {
|
|
|
701
757
|
}
|
|
702
758
|
}
|
|
703
759
|
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
760
|
+
/**
|
|
761
|
+
* 白名单正则。老版本默认值 `^(starpost\.private\.|qq\.|desktop-pet\.message)` 一个真实 key 都匹配不上
|
|
762
|
+
* (实际是 `private:1940008084`、`desktop-pet.chat` 这种),读到这个旧默认就换成新的,免得用户
|
|
763
|
+
* 明明没动过设置却一直录不到东西。
|
|
764
|
+
*/
|
|
765
|
+
private senderRe(cfg: MemoryCoreConfig): RegExp {
|
|
766
|
+
const raw = String(cfg.captureSenders ?? '').trim();
|
|
767
|
+
const legacy = '^(starpost\\.private\\.|qq\\.|desktop-pet\\.message)';
|
|
768
|
+
const pattern = !raw || raw === legacy ? MEMORY_CORE_DEFAULTS.captureSenders : raw;
|
|
707
769
|
try {
|
|
708
|
-
|
|
770
|
+
return new RegExp(pattern);
|
|
709
771
|
} catch {
|
|
710
|
-
|
|
772
|
+
return new RegExp(MEMORY_CORE_DEFAULTS.captureSenders);
|
|
711
773
|
}
|
|
712
|
-
|
|
713
|
-
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* 从宿主的 external 事件流里捞对方说的话。
|
|
778
|
+
*
|
|
779
|
+
* 宿主 `range` 的语义有两处容易踩:`limit` 是**从区间末尾取**,不是从头取;
|
|
780
|
+
* 只有不传 fromCursor 时才走「倒着凑最近 N 条」的快路径。所以拿
|
|
781
|
+
* `{fromCursor, limit}` 当分页会一次跳到历史末尾——v1 就是这么把 2.5 万条
|
|
782
|
+
* 外对话全跳过的。这里改用 toCursor 开窗,一窗一窗往前推。
|
|
783
|
+
*/
|
|
784
|
+
private capture(backfill = false): void {
|
|
785
|
+
const cfg = this.cfg();
|
|
786
|
+
const host = this.host;
|
|
787
|
+
if (!cfg.captureTurns || !host?.store) return;
|
|
788
|
+
const re = this.senderRe(cfg);
|
|
789
|
+
// 旧版水位是按错的 limit 语义推出来的,不可信:重放一遍
|
|
790
|
+
if (backfill && Number(this.state.watermarkVersion ?? 0) < CAPTURE_WATERMARK_VERSION) {
|
|
791
|
+
this.state.rawWatermark = 0;
|
|
792
|
+
this.state.watermarkVersion = CAPTURE_WATERMARK_VERSION;
|
|
793
|
+
this.state.backfillStartedAt = new Date().toISOString();
|
|
794
|
+
this.state.backfillDoneAt = undefined;
|
|
795
|
+
}
|
|
796
|
+
// 区间上界:只取最后一条,读一个分片就够
|
|
797
|
+
let head = 0;
|
|
714
798
|
try {
|
|
715
|
-
|
|
799
|
+
const last = host.store.range({ limit: 1 });
|
|
800
|
+
head = last.length ? last[0].cursor : 0;
|
|
716
801
|
} catch {
|
|
717
802
|
return;
|
|
718
803
|
}
|
|
719
|
-
|
|
720
|
-
|
|
804
|
+
let from = Number(this.state.rawWatermark ?? 0) || 0;
|
|
805
|
+
if (from > head) from = 0; // 宿主换过数据目录,cursor 从头开始
|
|
806
|
+
const minLen = Math.max(1, Number(cfg.captureMinLength) || 4);
|
|
721
807
|
const items: RawEntry[] = [];
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
808
|
+
const keys = new Set<string>();
|
|
809
|
+
let scanned = 0;
|
|
810
|
+
// 实时每拍最多追 4 窗(2000 条)防积压;回放一次最多 400 窗(20 万条)
|
|
811
|
+
const budget = backfill ? 400 : 4;
|
|
812
|
+
let rounds = 0;
|
|
813
|
+
let drained = from >= head;
|
|
814
|
+
while (!drained && rounds < budget) {
|
|
815
|
+
rounds += 1;
|
|
816
|
+
const to = Math.min(from + CAPTURE_BATCH, head);
|
|
817
|
+
let events: readonly { cursor: number; ts: string; senderKey?: string; text: string }[] = [];
|
|
818
|
+
try {
|
|
819
|
+
events = host.store.range({ fromCursor: from + 1, toCursor: to, origin: 'external' });
|
|
820
|
+
} catch {
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
scanned += events.length;
|
|
824
|
+
for (const e of events) {
|
|
825
|
+
const key = e.senderKey ?? '';
|
|
826
|
+
if (!re.test(key)) {
|
|
827
|
+
// 记几个被挡掉的 key,出问题时一眼能看出是白名单还是正文的问题
|
|
828
|
+
if (key && keys.size < 6) keys.add(key);
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
const text = clip(extractUserText(e.text), 200);
|
|
832
|
+
// 单字、纯表情、`[取消]` 这类系统回执、图片 blob 描述,都不进原文库
|
|
833
|
+
if (!text || text.length < minLen) continue;
|
|
834
|
+
if (/\[blob\b/i.test(text)) continue;
|
|
835
|
+
if (/^\[(表情包|CQ:|图片)/.test(text)) continue;
|
|
836
|
+
if (/^[\p{P}\p{S}\s]+$/u.test(text)) continue;
|
|
837
|
+
if (/^\[[^\]]{0,12}\]$/.test(text.trim())) continue;
|
|
838
|
+
items.push({ cursor: e.cursor, ts: e.ts, sender: key.slice(0, 40), text });
|
|
839
|
+
}
|
|
840
|
+
// 按窗口边界推进,不按「最后一个匹配到的 cursor」:窗口里可能一条 external 都没有
|
|
841
|
+
from = to;
|
|
842
|
+
if (from >= head) drained = true;
|
|
733
843
|
}
|
|
734
844
|
this.raw.add(items);
|
|
735
|
-
|
|
845
|
+
this.state.rawWatermark = from;
|
|
846
|
+
if (backfill && drained) this.state.backfillDoneAt = new Date().toISOString();
|
|
847
|
+
if (scanned || items.length) {
|
|
848
|
+
this.state.captureDebug = {
|
|
849
|
+
at: new Date().toISOString(),
|
|
850
|
+
scanned,
|
|
851
|
+
kept: items.length,
|
|
852
|
+
keys: items.length ? [] : [...keys],
|
|
853
|
+
...(backfill && !drained ? { backfillFrom: from, backfillTo: head } : {}),
|
|
854
|
+
};
|
|
855
|
+
}
|
|
736
856
|
}
|
|
737
857
|
|
|
738
858
|
private countToday(): number {
|