@njuptlzf/agent-chat-server 0.8.0 → 0.9.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/dist/history-archive.d.ts +116 -0
- package/dist/history-archive.js +352 -0
- package/dist/main.js +15 -1
- package/dist/server.d.ts +3 -0
- package/dist/server.js +35 -0
- package/dist/session.d.ts +21 -0
- package/dist/session.js +25 -2
- package/dist/sqlite-stores.d.ts +25 -2
- package/dist/sqlite-stores.js +263 -24
- package/package.json +65 -65
- package/scripts/agentchat-integrate.mjs +892 -892
- package/src/history-archive.ts +437 -0
- package/src/main.ts +17 -1
- package/src/server.ts +33 -0
- package/src/session.ts +36 -2
- package/src/sqlite-stores.ts +283 -27
package/src/sqlite-stores.ts
CHANGED
|
@@ -9,6 +9,8 @@ import type { Ledger, ReserveInput, ReserveOutcome, SettleInput, SettleOutcome }
|
|
|
9
9
|
import { RESERVATION_TTL_MS } from "./ledger.ts";
|
|
10
10
|
import type { CheckpointStore, RunCheckpoint, RunJobRow } from "./checkpoint-store.ts";
|
|
11
11
|
import type { PhaseCheckpoint } from "./orchestrator/run-spec.ts";
|
|
12
|
+
import { archiveKeyFor, HistoryArchiveUnavailableError, HistoryBodyCache, sessionCacheKey, verifyArchiveObject } from "./history-archive.ts";
|
|
13
|
+
import type { ArchiveSweepOptions, ArchiveSweepReport, HistoryArchiveCapable, HistoryArchiveStore } from "./history-archive.ts";
|
|
12
14
|
import { auditPageWindow } from "./stores.ts";
|
|
13
15
|
import { GENESIS_HASH, assertNoSensitiveKeys, canonicalize, rowHash, segmentsFrom, verifyChain } from "./audit.ts";
|
|
14
16
|
import type { VerifyResult } from "./audit.ts";
|
|
@@ -45,6 +47,12 @@ export function openDatabase(file: string, defaultScope = "", defaultPersona = D
|
|
|
45
47
|
persona TEXT,
|
|
46
48
|
-- 建会话时生效的人格配置版本;0 = manifest,NULL = 更早的老行(不编历史)。
|
|
47
49
|
persona_version INTEGER,
|
|
50
|
+
-- 冷热分层阶段 0:list() 只读这四列,不再解析 entries 正文。
|
|
51
|
+
-- state='local' = 正文在 SQLite;'archived' 留给阶段 1(对象存储),现在不会写入。
|
|
52
|
+
title TEXT NOT NULL DEFAULT '新会话',
|
|
53
|
+
message_count INTEGER NOT NULL DEFAULT 0,
|
|
54
|
+
state TEXT NOT NULL DEFAULT 'local',
|
|
55
|
+
archive_key TEXT,
|
|
48
56
|
PRIMARY KEY (user_id, scope, session_id)
|
|
49
57
|
);
|
|
50
58
|
-- persona 进主键:各个人格各算各的。老库由 migrateScope 重建。
|
|
@@ -308,6 +316,37 @@ function migrateScope(db: DatabaseSync, defaultScope: string, defaultPersona: st
|
|
|
308
316
|
if (!columns("history").includes("persona_version")) {
|
|
309
317
|
db.exec("ALTER TABLE history ADD COLUMN persona_version INTEGER");
|
|
310
318
|
}
|
|
319
|
+
// 会话历史冷热分层阶段 0:瘦表物化列。加列与老行回填放在同一个事务里——
|
|
320
|
+
// 中途崩溃整体回滚,下次打开仍是旧形状,不会留下「列加了一半、摘要没回填」的库。
|
|
321
|
+
const historyCols = columns("history");
|
|
322
|
+
if (historyCols.some((c) => !["title", "message_count", "state", "archive_key"].includes(c))) {
|
|
323
|
+
db.exec("BEGIN");
|
|
324
|
+
try {
|
|
325
|
+
if (!historyCols.includes("title")) db.exec("ALTER TABLE history ADD COLUMN title TEXT NOT NULL DEFAULT '新会话'");
|
|
326
|
+
if (!historyCols.includes("message_count")) db.exec("ALTER TABLE history ADD COLUMN message_count INTEGER NOT NULL DEFAULT 0");
|
|
327
|
+
if (!historyCols.includes("state")) db.exec("ALTER TABLE history ADD COLUMN state TEXT NOT NULL DEFAULT 'local'");
|
|
328
|
+
if (!historyCols.includes("archive_key")) db.exec("ALTER TABLE history ADD COLUMN archive_key TEXT");
|
|
329
|
+
const rows = db
|
|
330
|
+
.prepare("SELECT user_id, scope, session_id, entries FROM history")
|
|
331
|
+
.all() as { user_id: string; scope: string; session_id: string; entries: string }[];
|
|
332
|
+
const backfill = db.prepare(
|
|
333
|
+
"UPDATE history SET title = ?, message_count = ? WHERE user_id = ? AND scope = ? AND session_id = ?",
|
|
334
|
+
);
|
|
335
|
+
for (const r of rows) {
|
|
336
|
+
let summary: Pick<SessionSummary, "title" | "messageCount"> = { title: "新会话", messageCount: 0 };
|
|
337
|
+
try {
|
|
338
|
+
summary = summarizeHistory(JSON.parse(r.entries) as FileEntry[]);
|
|
339
|
+
} catch {
|
|
340
|
+
// 老正文本来就坏:保留默认摘要,不猜标题,也不让开库失败。
|
|
341
|
+
}
|
|
342
|
+
backfill.run(summary.title, summary.messageCount, r.user_id, r.scope, r.session_id);
|
|
343
|
+
}
|
|
344
|
+
db.exec("COMMIT");
|
|
345
|
+
} catch (err) {
|
|
346
|
+
db.exec("ROLLBACK");
|
|
347
|
+
throw err;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
311
350
|
// 轮数闸也要分账(默认助手的 10 轮不该被声明人格吃掉)。老行一律回填默认人格——
|
|
312
351
|
// 它们本来就是默认助手会话,猜成别的会把历史算到声明人格头上。
|
|
313
352
|
if (!columns("runs").includes("persona")) {
|
|
@@ -466,29 +505,212 @@ export function migrateProductDimension(db: DatabaseSync, defaultPersona: string
|
|
|
466
505
|
return report;
|
|
467
506
|
}
|
|
468
507
|
|
|
469
|
-
export class SqliteHistoryStore implements HistoryStore {
|
|
470
|
-
|
|
508
|
+
export class SqliteHistoryStore implements HistoryStore, HistoryArchiveCapable {
|
|
509
|
+
private readonly cache: HistoryBodyCache;
|
|
510
|
+
|
|
511
|
+
constructor(
|
|
512
|
+
private readonly db: DatabaseSync,
|
|
513
|
+
private readonly archiveStore?: HistoryArchiveStore,
|
|
514
|
+
private readonly options: { hot?: boolean; cache?: HistoryBodyCache } = {},
|
|
515
|
+
) {
|
|
516
|
+
if (options.hot && !archiveStore) throw new Error("history hot mode requires an archive store");
|
|
517
|
+
this.cache = options.cache ?? new HistoryBodyCache();
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** 取回归档正文并验内容寻址 hash;未配置或对象损坏都只影响这条已归档会话。 */
|
|
521
|
+
private async readArchived(key: string | null): Promise<string> {
|
|
522
|
+
if (!key || !this.archiveStore) {
|
|
523
|
+
throw new HistoryArchiveUnavailableError("history archive is not configured for this session");
|
|
524
|
+
}
|
|
525
|
+
const body = await this.archiveStore.get(key);
|
|
526
|
+
if (body === null || !verifyArchiveObject(key, body)) {
|
|
527
|
+
throw new HistoryArchiveUnavailableError(`archived history failed hash verification: ${key}`);
|
|
528
|
+
}
|
|
529
|
+
return body;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** local 读 SQLite;remote/archived 先查 LRU,命中零对象 GET,未命中验 hash 后回填。 */
|
|
533
|
+
private async readBody(
|
|
534
|
+
row: { entries: string; state: string; archive_key: string | null },
|
|
535
|
+
userId: string,
|
|
536
|
+
scope: string,
|
|
537
|
+
sessionId: string,
|
|
538
|
+
): Promise<string> {
|
|
539
|
+
if (row.state === "local") return row.entries;
|
|
540
|
+
const sessionKey = sessionCacheKey(userId, scope, sessionId);
|
|
541
|
+
const key = row.archive_key;
|
|
542
|
+
const cached = key ? this.cache.get(sessionKey, key) : undefined;
|
|
543
|
+
if (cached !== undefined) return cached;
|
|
544
|
+
const body = await this.readArchived(key);
|
|
545
|
+
if (key) this.cache.set(sessionKey, key, body);
|
|
546
|
+
return body;
|
|
547
|
+
}
|
|
471
548
|
|
|
472
549
|
async load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined> {
|
|
473
550
|
const row = this.db
|
|
474
|
-
.prepare("SELECT entries FROM history WHERE user_id = ? AND scope = ? AND session_id = ?")
|
|
475
|
-
.get(userId, scope, sessionId) as { entries: string } | undefined;
|
|
476
|
-
|
|
551
|
+
.prepare("SELECT entries, state, archive_key FROM history WHERE user_id = ? AND scope = ? AND session_id = ?")
|
|
552
|
+
.get(userId, scope, sessionId) as { entries: string; state: string; archive_key: string | null } | undefined;
|
|
553
|
+
if (!row) return undefined;
|
|
554
|
+
return JSON.parse(await this.readBody(row, userId, scope, sessionId)) as FileEntry[];
|
|
477
555
|
}
|
|
478
556
|
|
|
479
557
|
async save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void> {
|
|
558
|
+
const body = JSON.stringify(entries);
|
|
559
|
+
const { title, messageCount } = summarizeHistory(entries);
|
|
560
|
+
let storedBody = body;
|
|
561
|
+
let state = "local";
|
|
562
|
+
let archiveKey: string | null = null;
|
|
563
|
+
if (this.options.hot && this.archiveStore) {
|
|
564
|
+
// 对象先写成功再翻指针;写失败就让整次 save 失败,不静默退回本地正文。
|
|
565
|
+
archiveKey = archiveKeyFor(body);
|
|
566
|
+
await this.archiveStore.put(archiveKey, body);
|
|
567
|
+
storedBody = "";
|
|
568
|
+
state = "remote";
|
|
569
|
+
}
|
|
480
570
|
this.db
|
|
481
571
|
.prepare(
|
|
482
|
-
`INSERT INTO history (user_id, scope, session_id, entries, updated_at, persona, persona_version
|
|
572
|
+
`INSERT INTO history (user_id, scope, session_id, entries, updated_at, persona, persona_version, title, message_count, state, archive_key)
|
|
573
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
483
574
|
ON CONFLICT (user_id, scope, session_id) DO UPDATE
|
|
484
575
|
SET entries = excluded.entries,
|
|
485
576
|
updated_at = excluded.updated_at,
|
|
577
|
+
title = excluded.title,
|
|
578
|
+
message_count = excluded.message_count,
|
|
579
|
+
state = excluded.state,
|
|
580
|
+
archive_key = excluded.archive_key,
|
|
486
581
|
-- 首次绑定后不再改写:中途换人格该由端点拦(persona_mismatch),这里是第二道。
|
|
487
582
|
persona = COALESCE(history.persona, excluded.persona),
|
|
488
583
|
-- 版本与人格同一生命周期:第一轮落库那一刻定死,之后改配置也不追认。
|
|
489
584
|
persona_version = COALESCE(history.persona_version, excluded.persona_version)`,
|
|
490
585
|
)
|
|
491
|
-
.run(
|
|
586
|
+
.run(
|
|
587
|
+
userId,
|
|
588
|
+
scope,
|
|
589
|
+
sessionId,
|
|
590
|
+
storedBody,
|
|
591
|
+
new Date().toISOString(),
|
|
592
|
+
persona ?? null,
|
|
593
|
+
personaVersion ?? null,
|
|
594
|
+
title,
|
|
595
|
+
messageCount,
|
|
596
|
+
state,
|
|
597
|
+
archiveKey,
|
|
598
|
+
);
|
|
599
|
+
const sessionKey = sessionCacheKey(userId, scope, sessionId);
|
|
600
|
+
if (state === "remote" && archiveKey) this.cache.set(sessionKey, archiveKey, body);
|
|
601
|
+
else this.cache.delete(sessionKey);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* 后台归档一轮:local 正文先写对象并回读验 hash;remote 正文已在外置,只需验 hash。
|
|
606
|
+
* 成功后条件 UPDATE 翻 archived 并淘汰缓存——与 save 竞态时只留无害孤儿对象。
|
|
607
|
+
*/
|
|
608
|
+
async archiveIdle(options: ArchiveSweepOptions): Promise<ArchiveSweepReport> {
|
|
609
|
+
const report: ArchiveSweepReport = { scanned: 0, archived: 0, skipped: 0, failed: 0 };
|
|
610
|
+
if (!this.archiveStore) return report;
|
|
611
|
+
const cutoff = new Date(Date.now() - options.idleDays * 86_400_000).toISOString();
|
|
612
|
+
const rows = this.db
|
|
613
|
+
.prepare(
|
|
614
|
+
`SELECT user_id, scope, session_id, entries, state, archive_key
|
|
615
|
+
FROM history
|
|
616
|
+
WHERE state IN ('local', 'remote') AND updated_at < ?
|
|
617
|
+
AND (state = 'remote' OR entries <> '')
|
|
618
|
+
ORDER BY updated_at ASC LIMIT ?`,
|
|
619
|
+
)
|
|
620
|
+
.all(cutoff, options.batchSize) as {
|
|
621
|
+
user_id: string; scope: string; session_id: string; entries: string;
|
|
622
|
+
state: "local" | "remote" | string; archive_key: string | null;
|
|
623
|
+
}[];
|
|
624
|
+
report.scanned = rows.length;
|
|
625
|
+
|
|
626
|
+
for (const r of rows) {
|
|
627
|
+
const sessionKey = sessionCacheKey(r.user_id, r.scope, r.session_id);
|
|
628
|
+
try {
|
|
629
|
+
let key: string;
|
|
630
|
+
let body: string;
|
|
631
|
+
if (r.state === "remote") {
|
|
632
|
+
if (!r.archive_key) throw new Error("remote history row without archive_key");
|
|
633
|
+
key = r.archive_key;
|
|
634
|
+
const cached = this.cache.get(sessionKey, key);
|
|
635
|
+
body = cached ?? await this.readArchived(key);
|
|
636
|
+
if (!verifyArchiveObject(key, body)) throw new Error(`archive object failed hash verification: ${key}`);
|
|
637
|
+
} else {
|
|
638
|
+
body = r.entries;
|
|
639
|
+
key = archiveKeyFor(body);
|
|
640
|
+
// 上一轮写完对象却没更指针时,key 已存在且 hash 正确:本轮只补指针,不重写对象。
|
|
641
|
+
const existing = await this.archiveStore.get(key);
|
|
642
|
+
if (existing === null) {
|
|
643
|
+
await this.archiveStore.put(key, body);
|
|
644
|
+
} else if (!verifyArchiveObject(key, existing)) {
|
|
645
|
+
throw new Error(`existing archive object failed hash verification: ${key}`);
|
|
646
|
+
}
|
|
647
|
+
const verified = await this.archiveStore.get(key);
|
|
648
|
+
if (verified === null || !verifyArchiveObject(key, verified)) {
|
|
649
|
+
throw new Error(`archive object failed hash verification: ${key}`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
const updated = r.state === "local"
|
|
653
|
+
? this.db
|
|
654
|
+
.prepare(
|
|
655
|
+
`UPDATE history SET entries = '', state = 'archived', archive_key = ?
|
|
656
|
+
WHERE user_id = ? AND scope = ? AND session_id = ? AND state = 'local'`,
|
|
657
|
+
)
|
|
658
|
+
.run(key, r.user_id, r.scope, r.session_id)
|
|
659
|
+
: this.db
|
|
660
|
+
.prepare(
|
|
661
|
+
`UPDATE history SET entries = '', state = 'archived', archive_key = ?
|
|
662
|
+
WHERE user_id = ? AND scope = ? AND session_id = ? AND state = 'remote' AND archive_key = ?`,
|
|
663
|
+
)
|
|
664
|
+
.run(key, r.user_id, r.scope, r.session_id, key);
|
|
665
|
+
if (updated.changes === 0) {
|
|
666
|
+
report.skipped++;
|
|
667
|
+
} else {
|
|
668
|
+
this.cache.delete(sessionKey);
|
|
669
|
+
report.archived++;
|
|
670
|
+
}
|
|
671
|
+
} catch (err) {
|
|
672
|
+
report.failed++;
|
|
673
|
+
console.warn("[history-archive] archive failed for a session:", err instanceof Error ? err.message : String(err));
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return report;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* 恢复单条会话:验 hash 后按当前模式落点——热模式回 remote(正文仍在外置、刷新缓存),
|
|
681
|
+
* 关闭时回 local(写回 SQLite 正文)。updated_at 不动,不伪造新活动。
|
|
682
|
+
*/
|
|
683
|
+
async restore(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined> {
|
|
684
|
+
const row = this.db
|
|
685
|
+
.prepare("SELECT entries, state, archive_key FROM history WHERE user_id = ? AND scope = ? AND session_id = ?")
|
|
686
|
+
.get(userId, scope, sessionId) as { entries: string; state: string; archive_key: string | null } | undefined;
|
|
687
|
+
if (!row) return undefined;
|
|
688
|
+
if (row.state === "local") return JSON.parse(row.entries) as FileEntry[];
|
|
689
|
+
|
|
690
|
+
const body = await this.readBody(row, userId, scope, sessionId);
|
|
691
|
+
const sessionKey = sessionCacheKey(userId, scope, sessionId);
|
|
692
|
+
if (this.options.hot && row.archive_key) {
|
|
693
|
+
const updated = this.db
|
|
694
|
+
.prepare(
|
|
695
|
+
`UPDATE history SET entries = '', state = 'remote', archive_key = ?
|
|
696
|
+
WHERE user_id = ? AND scope = ? AND session_id = ?
|
|
697
|
+
AND state IN ('remote', 'archived') AND archive_key = ?`,
|
|
698
|
+
)
|
|
699
|
+
.run(row.archive_key, userId, scope, sessionId, row.archive_key);
|
|
700
|
+
if (updated.changes === 0) throw new HistoryArchiveUnavailableError("archive state changed during restore; retry");
|
|
701
|
+
this.cache.set(sessionKey, row.archive_key, body);
|
|
702
|
+
} else {
|
|
703
|
+
const updated = this.db
|
|
704
|
+
.prepare(
|
|
705
|
+
`UPDATE history SET entries = ?, state = 'local', archive_key = NULL
|
|
706
|
+
WHERE user_id = ? AND scope = ? AND session_id = ?
|
|
707
|
+
AND state IN ('remote', 'archived') AND archive_key = ?`,
|
|
708
|
+
)
|
|
709
|
+
.run(body, userId, scope, sessionId, row.archive_key);
|
|
710
|
+
if (updated.changes === 0) throw new HistoryArchiveUnavailableError("archive state changed during restore; retry");
|
|
711
|
+
this.cache.delete(sessionKey);
|
|
712
|
+
}
|
|
713
|
+
return JSON.parse(body) as FileEntry[];
|
|
492
714
|
}
|
|
493
715
|
|
|
494
716
|
async personaOf(userId: string, sessionId: string): Promise<string | null> {
|
|
@@ -505,18 +727,27 @@ export class SqliteHistoryStore implements HistoryStore {
|
|
|
505
727
|
return row?.scope;
|
|
506
728
|
}
|
|
507
729
|
|
|
508
|
-
//
|
|
509
|
-
// sessions per user. Upgrade path: persist `title`/`message_count` columns at save time.
|
|
730
|
+
// 只读索引列:正文不进 list,坏 JSON / 归档后的空 entries 都不影响会话列表。
|
|
510
731
|
async list(userId: string, scope?: string): Promise<SessionSummary[]> {
|
|
511
732
|
const where = scope === undefined ? "user_id = ?" : "user_id = ? AND scope = ?";
|
|
512
733
|
const args = scope === undefined ? [userId] : [userId, scope];
|
|
513
734
|
const rows = this.db
|
|
514
|
-
.prepare(
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
735
|
+
.prepare(
|
|
736
|
+
`SELECT session_id, scope,
|
|
737
|
+
COALESCE(title, '新会话') AS title,
|
|
738
|
+
COALESCE(message_count, 0) AS message_count,
|
|
739
|
+
updated_at, persona
|
|
740
|
+
FROM history WHERE ${where} ORDER BY updated_at DESC LIMIT 50`,
|
|
741
|
+
)
|
|
742
|
+
.all(...args) as { session_id: string; scope: string; title: string; message_count: number; updated_at: string; persona: string | null }[];
|
|
743
|
+
return rows.map((r) => ({
|
|
744
|
+
sessionId: r.session_id,
|
|
745
|
+
scope: r.scope,
|
|
746
|
+
title: r.title,
|
|
747
|
+
updatedAt: r.updated_at,
|
|
748
|
+
messageCount: r.message_count,
|
|
749
|
+
persona: r.persona,
|
|
750
|
+
}));
|
|
520
751
|
}
|
|
521
752
|
}
|
|
522
753
|
|
|
@@ -1156,6 +1387,22 @@ export class SqliteAudit implements AuditStore {
|
|
|
1156
1387
|
|
|
1157
1388
|
/** 同步内核:purge 要在同一同步段里「白名单先入链、再删行」,不能经 await 让出。 */
|
|
1158
1389
|
private appendSync(e: AuditEvent): number {
|
|
1390
|
+
// 「读上一行 hash → 写本行」必须是一个写事务。跨进程并发 append 时,两个进程会读到
|
|
1391
|
+
// 同一个 prev_hash,各写一行——链分叉(2026-11-21 实测:6 进程 × 25 条,3 轮里 1 轮
|
|
1392
|
+
// verify.ok=false、forks=3)。BEGIN IMMEDIATE 拿写锁后再读,天然串行;busy_timeout
|
|
1393
|
+
// 已在 openDatabase 设 5000,排队几毫秒远好于断链。
|
|
1394
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
1395
|
+
try {
|
|
1396
|
+
const id = this.appendRow(e);
|
|
1397
|
+
this.db.exec("COMMIT");
|
|
1398
|
+
return id;
|
|
1399
|
+
} catch (err) {
|
|
1400
|
+
this.db.exec("ROLLBACK");
|
|
1401
|
+
throw err;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
private appendRow(e: AuditEvent): number {
|
|
1159
1406
|
const meta = e.meta ?? {};
|
|
1160
1407
|
assertNoSensitiveKeys(meta);
|
|
1161
1408
|
const body = {
|
|
@@ -1243,19 +1490,28 @@ export class SqliteAudit implements AuditStore {
|
|
|
1243
1490
|
.all(cutoffIso) as Array<{ id: number | bigint; hash: string }>;
|
|
1244
1491
|
if (!doomed.length) return 0;
|
|
1245
1492
|
const ids = doomed.map((d) => Number(d.id));
|
|
1246
|
-
//
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1493
|
+
// 白名单入链与物理删必须在同一事务里:中间崩会让「删了行但没有 purge 背书」,
|
|
1494
|
+
// verify 会把 id 空洞判成恶意删行(断链)。BEGIN IMMEDIATE 同时排他,防并发 purge 互相覆盖。
|
|
1495
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
1496
|
+
try {
|
|
1497
|
+
// ①白名单行先入链(last_hash=段尾行存储 hash,删前读取)。
|
|
1498
|
+
this.appendRow({
|
|
1499
|
+
actor: "system",
|
|
1500
|
+
action: "ops.audit.purge",
|
|
1501
|
+
result: "ok",
|
|
1502
|
+
meta: { cutoff: cutoffIso, count: ids.length, segments: segmentsFrom(doomed.map((d) => ({ id: Number(d.id), hash: d.hash }))) },
|
|
1503
|
+
});
|
|
1504
|
+
// ②再物理删(IN 分块,防变量数上限)。
|
|
1505
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
1506
|
+
const chunk = ids.slice(i, i + 500);
|
|
1507
|
+
this.db.prepare(`DELETE FROM audit_log WHERE id IN (${chunk.map(() => "?").join(",")})`).run(...chunk);
|
|
1508
|
+
}
|
|
1509
|
+
this.db.exec("COMMIT");
|
|
1510
|
+
return ids.length;
|
|
1511
|
+
} catch (err) {
|
|
1512
|
+
this.db.exec("ROLLBACK");
|
|
1513
|
+
throw err;
|
|
1257
1514
|
}
|
|
1258
|
-
return ids.length;
|
|
1259
1515
|
}
|
|
1260
1516
|
}
|
|
1261
1517
|
|