mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): migrate trajectory cache to incremental SQLite ledger
- Add short-connection WAL trajectory_store.sqlite (and remote ssh-*.sqlite) with transactional .json-to-.bak migration, O(delta) step UPSERTs, undo tail truncation, and ledger_epoch/write_seq cross-process sync - Split steps into string-interned compact accounting tuples (retaining anomaly and step account owners) and lazy detail_json with an explicit 24-session hot LRU and precomputed O(1) cold metadata flags - Archive deleted source conversations permanently across cache rebuilds and skip redundant 404 trajectory RPCs while un-archiving automatically if sources reappear
This commit is contained in:
@@ -18,7 +18,10 @@ import {
|
|||||||
} from './endpoint-registry.mjs';
|
} from './endpoint-registry.mjs';
|
||||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||||
import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs';
|
import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs';
|
||||||
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
import {
|
||||||
|
clearScannerRuntimeMemos,
|
||||||
|
collectAuthoritativeLiveCascadeIds,
|
||||||
|
} from './local-scanner.mjs';
|
||||||
import {
|
import {
|
||||||
SETTINGS_FILE,
|
SETTINGS_FILE,
|
||||||
clearRuntimeCaches,
|
clearRuntimeCaches,
|
||||||
@@ -556,9 +559,12 @@ export function executeRebuildCacheAction(data = undefined, opts = {}) {
|
|||||||
if (!epCtx.ok) {
|
if (!epCtx.ok) {
|
||||||
return buildEndpointErrorResponse(epCtx);
|
return buildEndpointErrorResponse(epCtx);
|
||||||
}
|
}
|
||||||
|
const liveCascadeIds = collectAuthoritativeLiveCascadeIds(
|
||||||
|
epCtx.isRemote ? epCtx.endpoint : null
|
||||||
|
);
|
||||||
const ok = epCtx.isRemote
|
const ok = epCtx.isRemote
|
||||||
? clearRemoteEndpointCaches(epCtx.id)
|
? clearRemoteEndpointCaches(epCtx.id, { liveCascadeIds })
|
||||||
: clearRuntimeCaches();
|
: clearRuntimeCaches({ liveCascadeIds });
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ function resolveDefaultDataDir() {
|
|||||||
export const DATA_DIR = resolveDefaultDataDir();
|
export const DATA_DIR = resolveDefaultDataDir();
|
||||||
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
||||||
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
||||||
|
export const TRAJECTORY_DB_FILE = join(DATA_DIR, 'trajectory_store.sqlite');
|
||||||
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
||||||
export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json');
|
export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json');
|
||||||
export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json');
|
export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json');
|
||||||
@@ -419,6 +420,7 @@ export function computeRuntimeCodeVersion(options = {}) {
|
|||||||
*/
|
*/
|
||||||
const localTrajectoryCacheStore = createTrajectoryCacheStore({
|
const localTrajectoryCacheStore = createTrajectoryCacheStore({
|
||||||
cacheFilePath: CACHE_FILE,
|
cacheFilePath: CACHE_FILE,
|
||||||
|
sqliteFilePath: TRAJECTORY_DB_FILE,
|
||||||
loadJsonFn: loadJson,
|
loadJsonFn: loadJson,
|
||||||
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
|
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
|
||||||
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||||
@@ -426,6 +428,10 @@ const localTrajectoryCacheStore = createTrajectoryCacheStore({
|
|||||||
registerExitHook: true,
|
registerExitHook: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export function getLocalTrajectoryCacheStore() {
|
||||||
|
return localTrajectoryCacheStore;
|
||||||
|
}
|
||||||
|
|
||||||
export function getCachedTrajectory(cascadeId) {
|
export function getCachedTrajectory(cascadeId) {
|
||||||
return localTrajectoryCacheStore.getCachedTrajectory(cascadeId);
|
return localTrajectoryCacheStore.getCachedTrajectory(cascadeId);
|
||||||
}
|
}
|
||||||
@@ -434,6 +440,14 @@ export function getCachedTrajectoryEntryByLower(cascadeId) {
|
|||||||
return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId);
|
return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getHydratedTrajectory(cascadeId) {
|
||||||
|
return localTrajectoryCacheStore.getHydratedTrajectory(cascadeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getHydratedTrajectoryEntryByLower(cascadeId) {
|
||||||
|
return localTrajectoryCacheStore.getHydratedTrajectoryEntryByLower(cascadeId);
|
||||||
|
}
|
||||||
|
|
||||||
export function listCachedTrajectoryEntries() {
|
export function listCachedTrajectoryEntries() {
|
||||||
return localTrajectoryCacheStore.listCachedTrajectoryEntries();
|
return localTrajectoryCacheStore.listCachedTrajectoryEntries();
|
||||||
}
|
}
|
||||||
@@ -518,8 +532,8 @@ export const pluginUpdateState = {
|
|||||||
*
|
*
|
||||||
* @returns {boolean} 是否成功写回空白缓存文件
|
* @returns {boolean} 是否成功写回空白缓存文件
|
||||||
*/
|
*/
|
||||||
export function clearRuntimeCaches() {
|
export function clearRuntimeCaches(options = {}) {
|
||||||
if (!localTrajectoryCacheStore.clearCache()) return false;
|
if (!localTrajectoryCacheStore.clearCache(options)) return false;
|
||||||
externalDeepStatsMemo.sig = '';
|
externalDeepStatsMemo.sig = '';
|
||||||
externalDeepStatsMemo.convos.clear();
|
externalDeepStatsMemo.convos.clear();
|
||||||
localSummaryMemo.sig = '';
|
localSummaryMemo.sig = '';
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import {
|
|||||||
flushTrajectoryCacheNow,
|
flushTrajectoryCacheNow,
|
||||||
getCachedTrajectory,
|
getCachedTrajectory,
|
||||||
getCachedTrajectoryEntryByLower,
|
getCachedTrajectoryEntryByLower,
|
||||||
|
getHydratedTrajectory,
|
||||||
|
getHydratedTrajectoryEntryByLower,
|
||||||
hasPendingTrajectoryCacheSave,
|
hasPendingTrajectoryCacheSave,
|
||||||
listCachedTrajectoryEntries,
|
listCachedTrajectoryEntries,
|
||||||
loadJson,
|
loadJson,
|
||||||
@@ -108,8 +110,8 @@ export function buildRemoteEndpointIdentity({ origin = '', hostLabel = '', stabl
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildRemoteCacheFilePath(stableHostKey) {
|
function buildRemoteCacheFilePaths(stableHostKey) {
|
||||||
if (!stableHostKey) return '';
|
if (!stableHostKey) return { cacheFilePath: '', sqliteFilePath: '' };
|
||||||
const safePrefix = stableHostKey
|
const safePrefix = stableHostKey
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.replace(/[^a-z0-9._-]+/g, '_')
|
.replace(/[^a-z0-9._-]+/g, '_')
|
||||||
@@ -117,7 +119,10 @@ function buildRemoteCacheFilePath(stableHostKey) {
|
|||||||
.slice(0, 32) || 'ssh';
|
.slice(0, 32) || 'ssh';
|
||||||
const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12);
|
const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12);
|
||||||
// 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等)
|
// 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等)
|
||||||
return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`);
|
return {
|
||||||
|
cacheFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`),
|
||||||
|
sqliteFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.sqlite`),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function createRemoteQuotaCache() {
|
function createRemoteQuotaCache() {
|
||||||
@@ -131,9 +136,10 @@ function createRemoteQuotaCache() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function createRemoteEndpointStore(cacheFilePath) {
|
function createRemoteEndpointStore(cacheFilePath, sqliteFilePath = '') {
|
||||||
return createTrajectoryCacheStore({
|
return createTrajectoryCacheStore({
|
||||||
cacheFilePath,
|
cacheFilePath,
|
||||||
|
sqliteFilePath,
|
||||||
loadJsonFn: loadJson,
|
loadJsonFn: loadJson,
|
||||||
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
shouldBypassThrottleFn: (allowThrottleInTest) =>
|
||||||
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
|
||||||
@@ -175,9 +181,9 @@ export function registerRemoteEndpoint(info = {}) {
|
|||||||
|
|
||||||
let entry = remoteEndpointRegistry.get(identity.id);
|
let entry = remoteEndpointRegistry.get(identity.id);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
const cacheFilePath = identity.hasStableHostKey
|
const { cacheFilePath, sqliteFilePath } = identity.hasStableHostKey
|
||||||
? buildRemoteCacheFilePath(identity.stableHostKey)
|
? buildRemoteCacheFilePaths(identity.stableHostKey)
|
||||||
: '';
|
: { cacheFilePath: '', sqliteFilePath: '' };
|
||||||
entry = {
|
entry = {
|
||||||
id: identity.id,
|
id: identity.id,
|
||||||
instanceId: ++nextEndpointInstanceId,
|
instanceId: ++nextEndpointInstanceId,
|
||||||
@@ -192,11 +198,12 @@ export function registerRemoteEndpoint(info = {}) {
|
|||||||
lastSeenMs: nowMs,
|
lastSeenMs: nowMs,
|
||||||
preferTier2UntilMs: 0,
|
preferTier2UntilMs: 0,
|
||||||
inFlightCount: 0,
|
inFlightCount: 0,
|
||||||
store: createRemoteEndpointStore(cacheFilePath),
|
store: createRemoteEndpointStore(cacheFilePath, sqliteFilePath),
|
||||||
quotaSummaryCache: createRemoteQuotaCache(),
|
quotaSummaryCache: createRemoteQuotaCache(),
|
||||||
contextModelCatalog: null,
|
contextModelCatalog: null,
|
||||||
failedFetchCooldownMap: new Map(),
|
failedFetchCooldownMap: new Map(),
|
||||||
liveActivityMemo: new Map(),
|
liveActivityMemo: new Map(),
|
||||||
|
lastKnownLiveCascadeIds: null,
|
||||||
};
|
};
|
||||||
remoteEndpointRegistry.set(identity.id, entry);
|
remoteEndpointRegistry.set(identity.id, entry);
|
||||||
} else {
|
} else {
|
||||||
@@ -315,6 +322,8 @@ export function getEndpointCacheStore(endpointOrId = null) {
|
|||||||
endpointId: LOCAL_ENDPOINT_ID,
|
endpointId: LOCAL_ENDPOINT_ID,
|
||||||
getCachedTrajectory,
|
getCachedTrajectory,
|
||||||
getCachedTrajectoryEntryByLower,
|
getCachedTrajectoryEntryByLower,
|
||||||
|
getHydratedTrajectory,
|
||||||
|
getHydratedTrajectoryEntryByLower,
|
||||||
listCachedTrajectoryEntries,
|
listCachedTrajectoryEntries,
|
||||||
setCachedTrajectory,
|
setCachedTrajectory,
|
||||||
removeCachedTrajectory,
|
removeCachedTrajectory,
|
||||||
@@ -344,15 +353,21 @@ export function getEndpointQuotaCache(endpointOrId = null) {
|
|||||||
* 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。
|
* 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。
|
||||||
*
|
*
|
||||||
* @param {string} endpointId
|
* @param {string} endpointId
|
||||||
|
* @param {{ liveCascadeIds?: Iterable<string> | null }} [options]
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function clearRemoteEndpointCaches(endpointId) {
|
export function clearRemoteEndpointCaches(endpointId, options = {}) {
|
||||||
const ep = getRegisteredRemoteEndpoint(endpointId);
|
const ep = getRegisteredRemoteEndpoint(endpointId);
|
||||||
if (!ep) return false;
|
if (!ep) return false;
|
||||||
const ok = ep.store.clearCache();
|
const liveCascadeIds =
|
||||||
|
options && Object.prototype.hasOwnProperty.call(options, 'liveCascadeIds')
|
||||||
|
? options.liveCascadeIds
|
||||||
|
: ep.lastKnownLiveCascadeIds;
|
||||||
|
const ok = ep.store.clearCache({ liveCascadeIds });
|
||||||
if (!ok) return false;
|
if (!ok) return false;
|
||||||
ep.failedFetchCooldownMap.clear();
|
ep.failedFetchCooldownMap.clear();
|
||||||
ep.liveActivityMemo.clear();
|
ep.liveActivityMemo.clear();
|
||||||
|
ep.lastKnownLiveCascadeIds = null;
|
||||||
ep.contextModelCatalog = null;
|
ep.contextModelCatalog = null;
|
||||||
ep.quotaSummaryCache.ts = 0;
|
ep.quotaSummaryCache.ts = 0;
|
||||||
ep.quotaSummaryCache.lastAttemptTs = 0;
|
ep.quotaSummaryCache.lastAttemptTs = 0;
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
DEEP_STATS_CACHE_CANDIDATES,
|
DEEP_STATS_CACHE_CANDIDATES,
|
||||||
externalDeepStatsMemo,
|
externalDeepStatsMemo,
|
||||||
loadJson,
|
loadJson,
|
||||||
|
localSummaryMemo,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs';
|
import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs';
|
||||||
import {
|
import {
|
||||||
@@ -40,6 +41,7 @@ import {
|
|||||||
readLocalImageDimensionsFromUri,
|
readLocalImageDimensionsFromUri,
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
readLocalSummaryIndex,
|
readLocalSummaryIndex,
|
||||||
|
readLocalSummarySnapshot,
|
||||||
} from './cli-sqlite-reader.mjs';
|
} from './cli-sqlite-reader.mjs';
|
||||||
import { callLsRpc } from './ls-rpc.mjs';
|
import { callLsRpc } from './ls-rpc.mjs';
|
||||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||||
@@ -551,6 +553,50 @@ const failedFetchCooldownMap = new Map();
|
|||||||
const liveActivityMemo = new Map();
|
const liveActivityMemo = new Map();
|
||||||
const transcriptTailMemo = new Map();
|
const transcriptTailMemo = new Map();
|
||||||
const swarmManifestMemo = new Map();
|
const swarmManifestMemo = new Map();
|
||||||
|
let lastKnownLocalLiveCascadeIds = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收集目标端点当前仍存活的原始会话源 ID 集合(供「重建缓存」区分“存活待重扫会话”和“原对话已被删除需永久归档留存会话”)。
|
||||||
|
*
|
||||||
|
* @param {object|null} [endpoint=null]
|
||||||
|
* @returns {Set<string> | null}
|
||||||
|
*/
|
||||||
|
export function collectAuthoritativeLiveCascadeIds(endpoint = null) {
|
||||||
|
if (endpoint && endpoint.isRemote) {
|
||||||
|
return endpoint.lastKnownLiveCascadeIds instanceof Set
|
||||||
|
? new Set(endpoint.lastKnownLiveCascadeIds)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
const convDirs =
|
||||||
|
Array.isArray(CONVERSATION_DIRS) && CONVERSATION_DIRS.length > 0
|
||||||
|
? CONVERSATION_DIRS
|
||||||
|
: [CONVERSATIONS_DIR];
|
||||||
|
const hasAnyLocalConvDir = convDirs.some((d) => Boolean(d && existsSync(d)));
|
||||||
|
localSummaryMemo.sig = '';
|
||||||
|
localSummaryMemo.byRootsKey.clear();
|
||||||
|
brainDirListingMemo.clear();
|
||||||
|
knownExistingTranscriptPaths.clear();
|
||||||
|
const diskConvMap = discoverLocalConversationFiles();
|
||||||
|
const localSnap = readLocalSummarySnapshot();
|
||||||
|
if (!hasAnyLocalConvDir && diskConvMap.size === 0 && !localSnap.available) {
|
||||||
|
return lastKnownLocalLiveCascadeIds instanceof Set
|
||||||
|
? new Set(lastKnownLocalLiveCascadeIds)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
const liveIds = new Set();
|
||||||
|
for (const id of diskConvMap.keys()) liveIds.add(String(id).toLowerCase());
|
||||||
|
for (const id of localSnap.byId.keys()) liveIds.add(String(id).toLowerCase());
|
||||||
|
const localStore = getEndpointCacheStore(null);
|
||||||
|
for (const [rawKey, entry] of localStore.listCachedTrajectoryEntries()) {
|
||||||
|
const lower = String(rawKey || '').toLowerCase();
|
||||||
|
if (!liveIds.has(lower)) continue;
|
||||||
|
for (const ref of entry?.subagentRefs || []) {
|
||||||
|
const refLower = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||||
|
if (refLower) liveIds.add(refLower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return liveIds;
|
||||||
|
}
|
||||||
|
|
||||||
export function clearScannerRuntimeMemos(endpointId = null) {
|
export function clearScannerRuntimeMemos(endpointId = null) {
|
||||||
if (endpointId && endpointId !== 'local') {
|
if (endpointId && endpointId !== 'local') {
|
||||||
@@ -558,6 +604,7 @@ export function clearScannerRuntimeMemos(endpointId = null) {
|
|||||||
if (ep) {
|
if (ep) {
|
||||||
ep.failedFetchCooldownMap.clear();
|
ep.failedFetchCooldownMap.clear();
|
||||||
ep.liveActivityMemo.clear();
|
ep.liveActivityMemo.clear();
|
||||||
|
ep.lastKnownLiveCascadeIds = null;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -568,6 +615,7 @@ export function clearScannerRuntimeMemos(endpointId = null) {
|
|||||||
brainDirListingMemo.clear();
|
brainDirListingMemo.clear();
|
||||||
knownExistingTranscriptPaths.clear();
|
knownExistingTranscriptPaths.clear();
|
||||||
knownBrainCascadeSet = null;
|
knownBrainCascadeSet = null;
|
||||||
|
lastKnownLocalLiveCascadeIds = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function findSwarmMembersPath(cascadeId) {
|
function findSwarmMembersPath(cascadeId) {
|
||||||
@@ -1700,6 +1748,10 @@ export async function enumerateAndSyncConversations({
|
|||||||
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
const isRemote = Boolean(endpoint && endpoint.isRemote);
|
||||||
const cacheStore = getEndpointCacheStore(endpoint);
|
const cacheStore = getEndpointCacheStore(endpoint);
|
||||||
const getEntry = cacheStore.getCachedTrajectory;
|
const getEntry = cacheStore.getCachedTrajectory;
|
||||||
|
const getHydratedEntry =
|
||||||
|
typeof cacheStore.getHydratedTrajectory === 'function'
|
||||||
|
? cacheStore.getHydratedTrajectory
|
||||||
|
: getEntry;
|
||||||
const setEntry = cacheStore.setCachedTrajectory;
|
const setEntry = cacheStore.setCachedTrajectory;
|
||||||
const removeEntry = cacheStore.removeCachedTrajectory;
|
const removeEntry = cacheStore.removeCachedTrajectory;
|
||||||
const listEntries = cacheStore.listCachedTrajectoryEntries;
|
const listEntries = cacheStore.listCachedTrajectoryEntries;
|
||||||
@@ -1828,6 +1880,29 @@ export async function enumerateAndSyncConversations({
|
|||||||
|
|
||||||
const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex();
|
const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex();
|
||||||
const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite();
|
const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite();
|
||||||
|
const observedLiveIds = new Set();
|
||||||
|
for (const k of summariesByLower.keys()) observedLiveIds.add(k);
|
||||||
|
for (const k of localSummaryByLower.keys()) observedLiveIds.add(k);
|
||||||
|
for (const k of diskConvMap.keys()) observedLiveIds.add(k);
|
||||||
|
for (const [rawKey, entry] of listEntries()) {
|
||||||
|
const lower = String(rawKey || '').toLowerCase();
|
||||||
|
if (!observedLiveIds.has(lower)) continue;
|
||||||
|
for (const ref of entry?.subagentRefs || []) {
|
||||||
|
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||||
|
if (refCid) observedLiveIds.add(refCid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const hasAuthoritativeSourceSnapshot = isRemote
|
||||||
|
? summariesByLower.size > 0
|
||||||
|
: summariesByLower.size > 0 || localSummaryByLower.size > 0 || diskConvMap.size > 0;
|
||||||
|
if (hasAuthoritativeSourceSnapshot) {
|
||||||
|
if (isRemote && endpoint) {
|
||||||
|
endpoint.lastKnownLiveCascadeIds = observedLiveIds;
|
||||||
|
} else if (!isRemote) {
|
||||||
|
lastKnownLocalLiveCascadeIds = observedLiveIds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const normalizedPollAccount = normalizeOwnerAccount(currentAccountName);
|
||||||
const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000;
|
const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000;
|
||||||
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
||||||
const rawConversations = [];
|
const rawConversations = [];
|
||||||
@@ -2082,6 +2157,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
* 检查缓存条目是否缺少最新分解字段(含 10 通道上下文细分字段 `toolResultsTokens`)。
|
* 检查缓存条目是否缺少最新分解字段(含 10 通道上下文细分字段 `toolResultsTokens`)。
|
||||||
*/
|
*/
|
||||||
function hasMissingStepFields(cached) {
|
function hasMissingStepFields(cached) {
|
||||||
|
if (cached?._stepFlags) {
|
||||||
|
return Boolean(cached._stepFlags.hasMissingStepFields);
|
||||||
|
}
|
||||||
const steps = cached?.steps || [];
|
const steps = cached?.steps || [];
|
||||||
const lastCachedStep = steps[steps.length - 1];
|
const lastCachedStep = steps[steps.length - 1];
|
||||||
if (!lastCachedStep) return false;
|
if (!lastCachedStep) return false;
|
||||||
@@ -2149,7 +2227,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
|
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
|
||||||
const prev = getEntry(conv.cascadeId);
|
const prev = getHydratedEntry(conv.cascadeId);
|
||||||
let partialTailSteps = [];
|
let partialTailSteps = [];
|
||||||
let hasTailStepInfo = false;
|
let hasTailStepInfo = false;
|
||||||
try {
|
try {
|
||||||
@@ -2222,6 +2300,15 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||||
|
if (
|
||||||
|
steps.length === 0 &&
|
||||||
|
(prev?.steps?.length || 0) > 0 &&
|
||||||
|
!prev.offlineTranscriptFallback &&
|
||||||
|
!conv.inSummaries &&
|
||||||
|
!conv.dbPath
|
||||||
|
) {
|
||||||
|
throw new Error('Empty orphan trajectory; retaining cached usage');
|
||||||
|
}
|
||||||
const nextLast = steps[steps.length - 1];
|
const nextLast = steps[steps.length - 1];
|
||||||
|
|
||||||
// 提取轨迹内携带的子代理归属元数据、旁路提问父归属与派生的子代理引用列表
|
// 提取轨迹内携带的子代理归属元数据、旁路提问父归属与派生的子代理引用列表
|
||||||
@@ -2603,6 +2690,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
(c) => c.cascadeId.toLowerCase() === contextTelemetryCascadeId
|
(c) => c.cascadeId.toLowerCase() === contextTelemetryCascadeId
|
||||||
)?.rootConversationId || contextTelemetryCascadeId;
|
)?.rootConversationId || contextTelemetryCascadeId;
|
||||||
function hasMissingTurnRailFields(cached) {
|
function hasMissingTurnRailFields(cached) {
|
||||||
|
if (cached?._stepFlags) {
|
||||||
|
return Boolean(cached._stepFlags.hasMissingTurnRailFields);
|
||||||
|
}
|
||||||
const steps = cached?.steps || [];
|
const steps = cached?.steps || [];
|
||||||
const lastCachedStep = steps[steps.length - 1];
|
const lastCachedStep = steps[steps.length - 1];
|
||||||
if (!lastCachedStep) return false;
|
if (!lastCachedStep) return false;
|
||||||
@@ -2613,6 +2703,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
if (grpVer >= 3) return false;
|
if (grpVer >= 3) return false;
|
||||||
const steps = cached?.steps || [];
|
const steps = cached?.steps || [];
|
||||||
if (grpVer === 2) {
|
if (grpVer === 2) {
|
||||||
|
if (cached?._stepFlags) {
|
||||||
|
return steps.length > 0 && !cached._stepFlags.hasAnyContextBreakdown;
|
||||||
|
}
|
||||||
return steps.length > 0 && !steps.some((st) => Boolean(st?.contextBreakdown));
|
return steps.length > 0 && !steps.some((st) => Boolean(st?.contextBreakdown));
|
||||||
}
|
}
|
||||||
if (steps.some((st) => st?.isCompactionStep)) {
|
if (steps.some((st) => st?.isCompactionStep)) {
|
||||||
@@ -2640,6 +2733,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
|
|
||||||
function needsWakeupTurnRefresh(conv, cached) {
|
function needsWakeupTurnRefresh(conv, cached) {
|
||||||
if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false;
|
if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false;
|
||||||
|
if (cached?._stepFlags) {
|
||||||
|
return (cached.steps?.length || 0) > 0 && !cached._stepFlags.hasAnyTurnIndex;
|
||||||
|
}
|
||||||
const steps = cached?.steps || [];
|
const steps = cached?.steps || [];
|
||||||
return steps.length > 0 && steps.every((s) => !s?.turnIndex);
|
return steps.length > 0 && steps.every((s) => !s?.turnIndex);
|
||||||
}
|
}
|
||||||
@@ -2649,9 +2745,44 @@ export async function enumerateAndSyncConversations({
|
|||||||
const sig = buildConvSig(conv);
|
const sig = buildConvSig(conv);
|
||||||
if (isFetchInCooldown(conv, sig)) return false;
|
if (isFetchInCooldown(conv, sig)) return false;
|
||||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
const cached = getEntry(conv.cascadeId);
|
let cached = getEntry(conv.cascadeId);
|
||||||
if (!cached || conv.needsInitialLoad) return true;
|
if (!cached || conv.needsInitialLoad) return true;
|
||||||
const lowerCid = conv.cascadeId.toLowerCase();
|
const lowerCid = conv.cascadeId.toLowerCase();
|
||||||
|
const hasLiveBacking = Boolean(
|
||||||
|
conv.inSummaries ||
|
||||||
|
conv.dbPath ||
|
||||||
|
(diskConvMap.get(lowerCid)?.length || 0) > 0 ||
|
||||||
|
observedLiveIds.has(lowerCid)
|
||||||
|
);
|
||||||
|
if (cached.archived && hasLiveBacking) {
|
||||||
|
const unarchived = { ...cached };
|
||||||
|
delete unarchived.archived;
|
||||||
|
setEntry(conv.cascadeId, unarchived);
|
||||||
|
cached = getEntry(conv.cascadeId) || unarchived;
|
||||||
|
cacheDirty = true;
|
||||||
|
} else if (
|
||||||
|
!hasLiveBacking &&
|
||||||
|
(cached.steps?.length || 0) > 0 &&
|
||||||
|
!cached.offlineTranscriptFallback
|
||||||
|
) {
|
||||||
|
if (cached.archived) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hasAuthoritativeSourceSnapshot) {
|
||||||
|
const cachedOwner = normalizeOwnerAccount(cached.accountName);
|
||||||
|
const sameOrUnknownAccount =
|
||||||
|
!normalizedPollAccount || !cachedOwner || cachedOwner === normalizedPollAccount;
|
||||||
|
const parentRefLower = String(
|
||||||
|
conv.rootConversationId || conv.parentConversationId || ''
|
||||||
|
).toLowerCase();
|
||||||
|
const linkedToLiveParent = Boolean(parentRefLower && observedLiveIds.has(parentRefLower));
|
||||||
|
if (sameOrUnknownAccount && !linkedToLiveParent) {
|
||||||
|
setEntry(conv.cascadeId, { ...cached, archived: true });
|
||||||
|
cacheDirty = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const isSelectedFamily =
|
const isSelectedFamily =
|
||||||
lowerCid === contextTelemetryCascadeId ||
|
lowerCid === contextTelemetryCascadeId ||
|
||||||
lowerCid === selectedRootId ||
|
lowerCid === selectedRootId ||
|
||||||
@@ -2748,7 +2879,10 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 保留已有效的历史测速,按批补读需要确认原始状态与生成结束时间的旧步骤。
|
// 保留已有效的历史测速,按批补读需要确认原始状态与生成结束时间的旧步骤。
|
||||||
if (!cached.speedClearedTelemetry && readStepFieldChecks(cached.steps).hasIncompleteTiming) {
|
const hasIncompleteTiming = cached?._stepFlags
|
||||||
|
? Boolean(cached._stepFlags.hasIncompleteTiming)
|
||||||
|
: readStepFieldChecks(cached.steps).hasIncompleteTiming;
|
||||||
|
if (!cached.speedClearedTelemetry && hasIncompleteTiming) {
|
||||||
if (conv.cascadeId.toLowerCase() === selectedRootId || conv.rootConversationId === selectedRootId) return true;
|
if (conv.cascadeId.toLowerCase() === selectedRootId || conv.rootConversationId === selectedRootId) return true;
|
||||||
if (remainingTimingRefreshes > 0) {
|
if (remainingTimingRefreshes > 0) {
|
||||||
remainingTimingRefreshes -= 1;
|
remainingTimingRefreshes -= 1;
|
||||||
|
|||||||
@@ -93,9 +93,16 @@ function roundSessionCost(val) {
|
|||||||
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
|
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
|
function findTrajectoryCacheEntry(cascadeId, cacheStore = null, { hydrate = false } = {}) {
|
||||||
if (!cascadeId) return null;
|
if (!cascadeId) return null;
|
||||||
const store = cacheStore || getEndpointCacheStore(null);
|
const store = cacheStore || getEndpointCacheStore(null);
|
||||||
|
if (hydrate && typeof store.getHydratedTrajectoryEntryByLower === 'function') {
|
||||||
|
return store.getHydratedTrajectoryEntryByLower(cascadeId)?.entry || null;
|
||||||
|
}
|
||||||
|
if (hydrate && typeof store.getHydratedTrajectory === 'function') {
|
||||||
|
const hit = store.getHydratedTrajectory(cascadeId);
|
||||||
|
if (hit) return hit;
|
||||||
|
}
|
||||||
if (typeof store.getCachedTrajectoryEntryByLower === 'function') {
|
if (typeof store.getCachedTrajectoryEntryByLower === 'function') {
|
||||||
return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null;
|
return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null;
|
||||||
}
|
}
|
||||||
@@ -149,6 +156,16 @@ function buildKnownUpstreamModelMap(contextLimits, cacheStore = null) {
|
|||||||
const facts = readTrajectoryModelFacts(entry.steps);
|
const facts = readTrajectoryModelFacts(entry.steps);
|
||||||
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
||||||
if (entry.subagentSpec) continue;
|
if (entry.subagentSpec) continue;
|
||||||
|
if (Array.isArray(entry._stepFlags?.modelLimits) && entry._stepFlags.modelLimits.length > 0) {
|
||||||
|
for (const [key, tokens, at] of entry._stepFlags.modelLimits) {
|
||||||
|
if (!key || !(tokens > 0)) continue;
|
||||||
|
const previous = contextLimits.get(key);
|
||||||
|
if (!previous || at > previous.at) {
|
||||||
|
contextLimits.set(key, { tokens, at });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (facts.limits) {
|
if (facts.limits) {
|
||||||
for (const [key, limit] of facts.limits) {
|
for (const [key, limit] of facts.limits) {
|
||||||
const previous = contextLimits.get(key);
|
const previous = contextLimits.get(key);
|
||||||
@@ -1054,7 +1071,7 @@ function buildActiveConversationAssembly({
|
|||||||
const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`;
|
const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`;
|
||||||
|
|
||||||
const subEntries = subagentSummaries.map((subSum) =>
|
const subEntries = subagentSummaries.map((subSum) =>
|
||||||
findTrajectoryCacheEntry(subSum.cascadeId, cacheStore)
|
findTrajectoryCacheEntry(subSum.cascadeId, cacheStore, { hydrate: true })
|
||||||
);
|
);
|
||||||
const subRawStepsList = subEntries.map((entry) => entry?.steps || []);
|
const subRawStepsList = subEntries.map((entry) => entry?.steps || []);
|
||||||
const combinedFallbackKeys = new Set();
|
const combinedFallbackKeys = new Set();
|
||||||
@@ -1768,7 +1785,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||||
const reportedContextLimits = new Map();
|
const reportedContextLimits = new Map();
|
||||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore);
|
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore);
|
||||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true });
|
||||||
const modelInputs = {
|
const modelInputs = {
|
||||||
catalogRevision: pricingCatalogRevision,
|
catalogRevision: pricingCatalogRevision,
|
||||||
phaseEpoch: getPricingPhaseEpoch(),
|
phaseEpoch: getPricingPhaseEpoch(),
|
||||||
@@ -1972,7 +1989,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
if (cidKey && quickStatsMemo.has(cidKey)) {
|
if (cidKey && quickStatsMemo.has(cidKey)) {
|
||||||
return quickStatsMemo.get(cidKey);
|
return quickStatsMemo.get(cidKey);
|
||||||
}
|
}
|
||||||
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore);
|
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore, { hydrate: true });
|
||||||
const rootSteps = rootEntry?.steps || [];
|
const rootSteps = rootEntry?.steps || [];
|
||||||
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
|
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
|
||||||
|
|
||||||
@@ -2478,7 +2495,9 @@ function resolveValidFastSnapshot(endpoint = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function entryNeedsLazyTelemetryUpgrade(entry) {
|
function entryNeedsLazyTelemetryUpgrade(entry) {
|
||||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false;
|
if (!entry || entry.archived || !Array.isArray(entry.steps) || entry.steps.length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
const grpVer = Number(entry.contextGroupsTelemetry || 0);
|
const grpVer = Number(entry.contextGroupsTelemetry || 0);
|
||||||
const needsUndoCtxUpgrade =
|
const needsUndoCtxUpgrade =
|
||||||
grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown)));
|
grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown)));
|
||||||
@@ -2508,7 +2527,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
if (!activeConvSummary?.cascadeId) return null;
|
if (!activeConvSummary?.cascadeId) return null;
|
||||||
|
|
||||||
const activeCascadeId = activeConvSummary.cascadeId;
|
const activeCascadeId = activeConvSummary.cascadeId;
|
||||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true });
|
||||||
if (!activeEntry) return null;
|
if (!activeEntry) return null;
|
||||||
|
|
||||||
const subagentSummaries = Array.isArray(activeConvSummary.subagents)
|
const subagentSummaries = Array.isArray(activeConvSummary.subagents)
|
||||||
@@ -2523,7 +2542,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
|||||||
needsBackgroundSync = true;
|
needsBackgroundSync = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
|
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore, { hydrate: true });
|
||||||
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
|
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
|
||||||
needsBackgroundSync = true;
|
needsBackgroundSync = true;
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -1,15 +1,64 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Shared lazy-loaded, $O(1)$ case-insensitive, 30s-throttled trajectory cache store
|
* @fileoverview Shared lazy-loaded, $O(1)$ case-insensitive, 30s-throttled trajectory cache store
|
||||||
* reused by both the local sidecar (`config.mjs`) and remote SSH endpoints (`endpoint-registry.mjs`).
|
* reused by both the local sidecar (`config.mjs`) and remote SSH endpoints (`endpoint-registry.mjs`).
|
||||||
|
*
|
||||||
|
* Supports dual persistence backends behind a 100% compatible API:
|
||||||
|
* - SQLite incremental ledger (`trajectory-sqlite-ledger.mjs`) with 24-session hot `detail` LRU
|
||||||
|
* and permanent archived ledger retention when conversations are deleted in Antigravity;
|
||||||
|
* - JSON/in-memory fallback for environments without `node:sqlite` or VM unit-test sandboxes.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { mkdirSync } from 'node:fs';
|
import { mkdirSync } from 'node:fs';
|
||||||
import { dirname } from 'node:path';
|
import { dirname } from 'node:path';
|
||||||
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||||
import { isPlainObject } from './http-helpers.mjs';
|
import { isPlainObject } from './http-helpers.mjs';
|
||||||
|
import { hasBuiltinNodeSqlite } from './sqlite-client.mjs';
|
||||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||||
|
import {
|
||||||
|
computePrecomputedStepFlags,
|
||||||
|
createTrajectorySqliteLedger,
|
||||||
|
} from './trajectory-sqlite-ledger.mjs';
|
||||||
|
|
||||||
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
|
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
|
||||||
|
export const DEFAULT_HOT_SESSION_LRU_LIMIT = 24;
|
||||||
|
const TCS_WAL_SYNC_MIN_INTERVAL_MS = 250;
|
||||||
|
|
||||||
|
function tcsMarkColdSlimSteps(steps) {
|
||||||
|
if (Array.isArray(steps)) {
|
||||||
|
Object.defineProperty(steps, '_isColdSlimSteps', {
|
||||||
|
value: true,
|
||||||
|
enumerable: false,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcsIsColdEntry(entry) {
|
||||||
|
return Boolean(entry && (entry._coldSteps === true || entry.steps?._isColdSlimSteps === true));
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcsDefineHiddenProp(obj, key, value) {
|
||||||
|
if (!obj || typeof obj !== 'object') return;
|
||||||
|
Object.defineProperty(obj, key, {
|
||||||
|
value,
|
||||||
|
enumerable: false,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcsAttachEntryStepFlags(entry, flags) {
|
||||||
|
if (!entry || typeof entry !== 'object') return;
|
||||||
|
const resolved = flags || entry._stepFlags || computePrecomputedStepFlags(entry.steps);
|
||||||
|
tcsDefineHiddenProp(entry, '_stepFlags', resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcsIsVirtualSandboxPath(filePath) {
|
||||||
|
const norm = String(filePath || '').replace(/\\/g, '/');
|
||||||
|
return norm.startsWith('/test/') || norm.startsWith('/test-home/');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalizes and repairs raw trajectory cache JSON into an unprototyped map.
|
* Normalizes and repairs raw trajectory cache JSON into an unprototyped map.
|
||||||
@@ -42,7 +91,9 @@ export function hydrateTrajectoryCacheObject(rawLoaded) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cacheObj[id] = { ...entry, steps: finalSteps };
|
const nextEntry = { ...entry, steps: finalSteps };
|
||||||
|
tcsAttachEntryStepFlags(nextEntry, computePrecomputedStepFlags(finalSteps));
|
||||||
|
cacheObj[id] = nextEntry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { cacheObj, migrated };
|
return { cacheObj, migrated };
|
||||||
@@ -50,26 +101,59 @@ export function hydrateTrajectoryCacheObject(rawLoaded) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates an isolated trajectory cache store with lazy first-read hydration,
|
* Creates an isolated trajectory cache store with lazy first-read hydration,
|
||||||
* case-insensitive canonical key index, and 30-second throttled disk flushes.
|
* case-insensitive canonical key index, 24-session hot detail LRU, and 30-second throttled disk flushes.
|
||||||
*
|
*
|
||||||
* @param {{
|
* @param {{
|
||||||
* cacheFilePath: string,
|
* cacheFilePath?: string,
|
||||||
* loadJsonFn: (filePath: string, fallback: any) => any,
|
* sqliteFilePath?: string,
|
||||||
|
* enableSqlite?: boolean | null,
|
||||||
|
* hotSessionLimit?: number,
|
||||||
|
* loadJsonFn?: (filePath: string, fallback: any) => any,
|
||||||
* writeCacheFn?: (filePath: string, cacheObj: Record<string, any>) => boolean,
|
* writeCacheFn?: (filePath: string, cacheObj: Record<string, any>) => boolean,
|
||||||
* shouldBypassThrottleFn?: (allowThrottleInTest: boolean) => boolean,
|
* shouldBypassThrottleFn?: (allowThrottleInTest: boolean) => boolean,
|
||||||
* registerExitHook?: boolean,
|
* registerExitHook?: boolean,
|
||||||
* }} options
|
* }} options
|
||||||
*/
|
*/
|
||||||
export function createTrajectoryCacheStore({
|
export function createTrajectoryCacheStore({
|
||||||
cacheFilePath,
|
cacheFilePath = '',
|
||||||
loadJsonFn,
|
sqliteFilePath = '',
|
||||||
|
enableSqlite = null,
|
||||||
|
hotSessionLimit = DEFAULT_HOT_SESSION_LRU_LIMIT,
|
||||||
|
loadJsonFn = null,
|
||||||
writeCacheFn = null,
|
writeCacheFn = null,
|
||||||
shouldBypassThrottleFn = () => false,
|
shouldBypassThrottleFn = () => false,
|
||||||
registerExitHook = false,
|
registerExitHook = false,
|
||||||
}) {
|
}) {
|
||||||
|
const maxHotSessions = Math.max(1, Math.floor(Number(hotSessionLimit) || DEFAULT_HOT_SESSION_LRU_LIMIT));
|
||||||
|
const useSqlite =
|
||||||
|
enableSqlite === true
|
||||||
|
? Boolean(sqliteFilePath && hasBuiltinNodeSqlite())
|
||||||
|
: enableSqlite === false
|
||||||
|
? false
|
||||||
|
: Boolean(
|
||||||
|
sqliteFilePath &&
|
||||||
|
hasBuiltinNodeSqlite() &&
|
||||||
|
!tcsIsVirtualSandboxPath(sqliteFilePath)
|
||||||
|
);
|
||||||
|
|
||||||
|
const sqliteLedger = useSqlite
|
||||||
|
? createTrajectorySqliteLedger({
|
||||||
|
sqliteFilePath,
|
||||||
|
legacyJsonPath: cacheFilePath,
|
||||||
|
loadJsonFn,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
let cacheObj = Object.create(null);
|
let cacheObj = Object.create(null);
|
||||||
const byLower = new Map();
|
const byLower = new Map();
|
||||||
|
// Map<lowerId, true> preserving insertion order (oldest -> newest) for hot hydrated sessions
|
||||||
|
const hotLru = new Map();
|
||||||
|
const dirtyUpserts = new Set();
|
||||||
|
const dirtyRemovals = new Set();
|
||||||
|
let pendingEpochBump = false;
|
||||||
let loadedOnce = false;
|
let loadedOnce = false;
|
||||||
|
let lastWalSyncCheckMs = 0;
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
needsSave: false,
|
needsSave: false,
|
||||||
lastSavedAtMs: 0,
|
lastSavedAtMs: 0,
|
||||||
@@ -88,12 +172,85 @@ export function createTrajectoryCacheStore({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const doWrite = writeCacheFn || defaultWriteCache;
|
const doWriteJson = writeCacheFn || defaultWriteCache;
|
||||||
|
|
||||||
|
function finalizeColdEntryInPlace(entry) {
|
||||||
|
if (!entry || typeof entry !== 'object') return entry;
|
||||||
|
const preFlags = entry._stepFlags || null;
|
||||||
|
if (Object.prototype.hasOwnProperty.call(entry, '_coldSteps')) {
|
||||||
|
delete entry._coldSteps;
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(entry, '_stepFlags')) {
|
||||||
|
delete entry._stepFlags;
|
||||||
|
}
|
||||||
|
tcsDefineHiddenProp(entry, '_coldSteps', true);
|
||||||
|
if (preFlags) {
|
||||||
|
tcsDefineHiddenProp(entry, '_stepFlags', preFlags);
|
||||||
|
}
|
||||||
|
tcsMarkColdSlimSteps(entry.steps);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function touchHotSession(lower) {
|
||||||
|
if (!useSqlite || !lower) return;
|
||||||
|
if (hotLru.has(lower)) {
|
||||||
|
hotLru.delete(lower);
|
||||||
|
}
|
||||||
|
hotLru.set(lower, true);
|
||||||
|
evictOverflowHotSessions();
|
||||||
|
}
|
||||||
|
|
||||||
|
function dehydrateSingleSessionToCold(lower) {
|
||||||
|
if (!useSqlite || !sqliteLedger || !lower) return false;
|
||||||
|
if (dirtyUpserts.has(lower)) return false;
|
||||||
|
const canon = byLower.get(lower);
|
||||||
|
const entry = canon ? cacheObj[canon] : null;
|
||||||
|
if (!entry || entry.wasRunning) return false;
|
||||||
|
if (tcsIsColdEntry(entry)) {
|
||||||
|
hotLru.delete(lower);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const curSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||||
|
const flags = entry._stepFlags || computePrecomputedStepFlags(curSteps);
|
||||||
|
const slimSteps = tcsMarkColdSlimSteps(curSteps.map((s) => sqliteLedger.dehydrateStep(s)));
|
||||||
|
entry.steps = slimSteps;
|
||||||
|
tcsDefineHiddenProp(entry, '_coldSteps', true);
|
||||||
|
tcsDefineHiddenProp(entry, '_stepFlags', flags);
|
||||||
|
hotLru.delete(lower);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function evictOverflowHotSessions() {
|
||||||
|
if (!useSqlite || hotLru.size <= maxHotSessions) return;
|
||||||
|
for (const candidateLower of Array.from(hotLru.keys())) {
|
||||||
|
if (hotLru.size <= maxHotSessions) break;
|
||||||
|
dehydrateSingleSessionToCold(candidateLower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function rebuildLowerIndexFromCacheObj(markCold = false) {
|
||||||
|
byLower.clear();
|
||||||
|
hotLru.clear();
|
||||||
|
for (const key of Object.keys(cacheObj)) {
|
||||||
|
const lower = key.toLowerCase();
|
||||||
|
byLower.set(lower, key);
|
||||||
|
if (markCold) {
|
||||||
|
finalizeColdEntryInPlace(cacheObj[key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function ensureLoaded() {
|
function ensureLoaded() {
|
||||||
if (loadedOnce) return;
|
if (loadedOnce) return;
|
||||||
loadedOnce = true;
|
loadedOnce = true;
|
||||||
if (!cacheFilePath) return;
|
if (useSqlite && sqliteLedger) {
|
||||||
|
const hydrated = sqliteLedger.openAndHydrateInitial();
|
||||||
|
cacheObj = hydrated.cacheObj;
|
||||||
|
rebuildLowerIndexFromCacheObj(true);
|
||||||
|
lastWalSyncCheckMs = Date.now();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!cacheFilePath || typeof loadJsonFn !== 'function') return;
|
||||||
const loaded = loadJsonFn(cacheFilePath, {});
|
const loaded = loadJsonFn(cacheFilePath, {});
|
||||||
const hydrated = hydrateTrajectoryCacheObject(loaded);
|
const hydrated = hydrateTrajectoryCacheObject(loaded);
|
||||||
cacheObj = hydrated.cacheObj;
|
cacheObj = hydrated.cacheObj;
|
||||||
@@ -105,6 +262,63 @@ export function createTrajectoryCacheStore({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function syncExternalChangesNow() {
|
||||||
|
if (!useSqlite || !sqliteLedger || !loadedOnce) return false;
|
||||||
|
lastWalSyncCheckMs = Date.now();
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = sqliteLedger.syncExternalChangesIfNeeded();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!res || !res.changed) return false;
|
||||||
|
if (res.fullReset && res.cacheObj) {
|
||||||
|
for (const [cid, entry] of Object.entries(res.cacheObj)) {
|
||||||
|
const lower = cid.toLowerCase();
|
||||||
|
if (dirtyUpserts.has(lower)) continue;
|
||||||
|
finalizeColdEntryInPlace(entry);
|
||||||
|
}
|
||||||
|
// Preserve any local unflushed dirty entries on top of the peer reset
|
||||||
|
const preservedDirty = [];
|
||||||
|
for (const dirtyLower of dirtyUpserts) {
|
||||||
|
const canon = byLower.get(dirtyLower);
|
||||||
|
if (canon && cacheObj[canon]) {
|
||||||
|
preservedDirty.push([canon, cacheObj[canon]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cacheObj = res.cacheObj;
|
||||||
|
rebuildLowerIndexFromCacheObj(true);
|
||||||
|
for (const [canon, dirtyEntry] of preservedDirty) {
|
||||||
|
cacheObj[canon] = dirtyEntry;
|
||||||
|
byLower.set(canon.toLowerCase(), canon);
|
||||||
|
touchHotSession(canon.toLowerCase());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (Array.isArray(res.updatedEntries)) {
|
||||||
|
for (const { cascadeId, lowerId, entry } of res.updatedEntries) {
|
||||||
|
if (dirtyUpserts.has(lowerId) || dirtyRemovals.has(lowerId)) continue;
|
||||||
|
const prevCanon = byLower.get(lowerId);
|
||||||
|
if (prevCanon && prevCanon !== cascadeId) {
|
||||||
|
delete cacheObj[prevCanon];
|
||||||
|
}
|
||||||
|
finalizeColdEntryInPlace(entry);
|
||||||
|
cacheObj[cascadeId] = entry;
|
||||||
|
byLower.set(lowerId, cascadeId);
|
||||||
|
hotLru.delete(lowerId);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncExternalIfDue() {
|
||||||
|
if (!useSqlite || !loadedOnce) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastWalSyncCheckMs < TCS_WAL_SYNC_MIN_INTERVAL_MS) return;
|
||||||
|
syncExternalChangesNow();
|
||||||
|
}
|
||||||
|
|
||||||
function cancelFlushTimer() {
|
function cancelFlushTimer() {
|
||||||
if (state.flushTimer) {
|
if (state.flushTimer) {
|
||||||
try {
|
try {
|
||||||
@@ -119,11 +333,47 @@ export function createTrajectoryCacheStore({
|
|||||||
function flushTrajectoryCacheNow() {
|
function flushTrajectoryCacheNow() {
|
||||||
ensureLoaded();
|
ensureLoaded();
|
||||||
cancelFlushTimer();
|
cancelFlushTimer();
|
||||||
|
|
||||||
|
if (useSqlite && sqliteLedger) {
|
||||||
|
if (dirtyUpserts.size === 0 && dirtyRemovals.size === 0 && !pendingEpochBump) {
|
||||||
|
state.needsSave = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const upserts = [];
|
||||||
|
for (const lower of dirtyUpserts) {
|
||||||
|
const canon = byLower.get(lower);
|
||||||
|
const entry = canon ? cacheObj[canon] : null;
|
||||||
|
if (canon && entry) {
|
||||||
|
upserts.push({ cascadeId: canon, entry });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const removals = Array.from(dirtyRemovals);
|
||||||
|
try {
|
||||||
|
sqliteLedger.flushDeltaBatch({
|
||||||
|
upserts,
|
||||||
|
removals,
|
||||||
|
bumpEpoch: pendingEpochBump,
|
||||||
|
});
|
||||||
|
dirtyUpserts.clear();
|
||||||
|
dirtyRemovals.clear();
|
||||||
|
pendingEpochBump = false;
|
||||||
|
state.needsSave = false;
|
||||||
|
state.lastSavedAtMs = Date.now();
|
||||||
|
lastWalSyncCheckMs = state.lastSavedAtMs;
|
||||||
|
evictOverflowHotSessions();
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed flushing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`);
|
||||||
|
state.needsSave = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!cacheFilePath) {
|
if (!cacheFilePath) {
|
||||||
state.needsSave = false;
|
state.needsSave = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
const ok = doWrite(cacheFilePath, cacheObj);
|
const ok = doWriteJson(cacheFilePath, cacheObj);
|
||||||
state.needsSave = !ok;
|
state.needsSave = !ok;
|
||||||
if (ok) {
|
if (ok) {
|
||||||
state.lastSavedAtMs = Date.now();
|
state.lastSavedAtMs = Date.now();
|
||||||
@@ -135,7 +385,7 @@ export function createTrajectoryCacheStore({
|
|||||||
hasRunningSessions = false,
|
hasRunningSessions = false,
|
||||||
allowThrottleInTest = false,
|
allowThrottleInTest = false,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
if (!cacheFilePath) {
|
if (!useSqlite && !cacheFilePath) {
|
||||||
state.needsSave = false;
|
state.needsSave = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -169,16 +419,103 @@ export function createTrajectoryCacheStore({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearCache() {
|
function hydrateEntryInPlaceIfNeeded(canonId, entry) {
|
||||||
if (cacheFilePath && !doWrite(cacheFilePath, {})) {
|
if (!canonId || !entry) return entry;
|
||||||
|
const lower = canonId.toLowerCase();
|
||||||
|
if (!useSqlite || !sqliteLedger) return entry;
|
||||||
|
if (!tcsIsColdEntry(entry)) {
|
||||||
|
touchHotSession(lower);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
const fullSteps = sqliteLedger.loadHydratedStepsForConversation(canonId, entry);
|
||||||
|
if (Array.isArray(fullSteps)) {
|
||||||
|
const flags = entry._stepFlags || computePrecomputedStepFlags(fullSteps);
|
||||||
|
entry.steps = fullSteps;
|
||||||
|
tcsDefineHiddenProp(entry, '_coldSteps', false);
|
||||||
|
tcsDefineHiddenProp(entry, '_stepFlags', flags);
|
||||||
|
touchHotSession(lower);
|
||||||
|
}
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Non-destructively clears live/empty cached entries to force fresh re-scanning, while
|
||||||
|
* permanently archiving & preserving any conversation with `steps.length > 0` whose source
|
||||||
|
* conversation has already been deleted (`!liveSet.has(lower)` or `entry.archived === true`).
|
||||||
|
*
|
||||||
|
* @param {{ liveCascadeIds?: Iterable<string> | null }} [options]
|
||||||
|
*/
|
||||||
|
function clearCache({ liveCascadeIds = null } = {}) {
|
||||||
|
ensureLoaded();
|
||||||
|
syncExternalChangesNow();
|
||||||
|
|
||||||
|
const liveSet =
|
||||||
|
liveCascadeIds !== null && liveCascadeIds !== undefined
|
||||||
|
? new Set(
|
||||||
|
Array.from(liveCascadeIds, (id) => String(id || '').trim().toLowerCase()).filter(
|
||||||
|
Boolean
|
||||||
|
)
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const retainedEntries = Object.create(null);
|
||||||
|
const removedLowers = [];
|
||||||
|
const archivedUpserts = [];
|
||||||
|
|
||||||
|
for (const [key, entry] of Object.entries(cacheObj)) {
|
||||||
|
const lower = key.toLowerCase();
|
||||||
|
const hasSteps = Array.isArray(entry?.steps) && entry.steps.length > 0;
|
||||||
|
const isDeletedHistorical =
|
||||||
|
hasSteps && (entry.archived === true || (liveSet !== null && !liveSet.has(lower)));
|
||||||
|
if (isDeletedHistorical) {
|
||||||
|
const archivedEntry = entry.archived === true ? entry : { ...entry, archived: true };
|
||||||
|
if (tcsIsColdEntry(entry)) {
|
||||||
|
tcsDefineHiddenProp(archivedEntry, '_coldSteps', true);
|
||||||
|
}
|
||||||
|
if (entry._stepFlags) {
|
||||||
|
tcsDefineHiddenProp(archivedEntry, '_stepFlags', entry._stepFlags);
|
||||||
|
}
|
||||||
|
retainedEntries[key] = archivedEntry;
|
||||||
|
if (entry.archived !== true || dirtyUpserts.has(lower)) {
|
||||||
|
archivedUpserts.push({ cascadeId: key, entry: archivedEntry });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
removedLowers.push(lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (useSqlite && sqliteLedger) {
|
||||||
|
try {
|
||||||
|
sqliteLedger.flushDeltaBatch({
|
||||||
|
upserts: archivedUpserts,
|
||||||
|
removals: removedLowers,
|
||||||
|
bumpEpoch: true,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed clearing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
} else if (cacheFilePath && !doWriteJson(cacheFilePath, retainedEntries)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
cancelFlushTimer();
|
cancelFlushTimer();
|
||||||
loadedOnce = true;
|
loadedOnce = true;
|
||||||
for (const key of Object.keys(cacheObj)) {
|
cacheObj = retainedEntries;
|
||||||
delete cacheObj[key];
|
|
||||||
}
|
|
||||||
byLower.clear();
|
byLower.clear();
|
||||||
|
for (const key of Object.keys(cacheObj)) {
|
||||||
|
const lower = key.toLowerCase();
|
||||||
|
byLower.set(lower, key);
|
||||||
|
}
|
||||||
|
for (const remLower of removedLowers) {
|
||||||
|
hotLru.delete(remLower);
|
||||||
|
dirtyUpserts.delete(remLower);
|
||||||
|
dirtyRemovals.delete(remLower);
|
||||||
|
}
|
||||||
|
for (const { cascadeId } of archivedUpserts) {
|
||||||
|
dirtyUpserts.delete(cascadeId.toLowerCase());
|
||||||
|
}
|
||||||
|
pendingEpochBump = false;
|
||||||
state.needsSave = false;
|
state.needsSave = false;
|
||||||
state.lastSavedAtMs = 0;
|
state.lastSavedAtMs = 0;
|
||||||
return true;
|
return true;
|
||||||
@@ -192,17 +529,10 @@ export function createTrajectoryCacheStore({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
function lookupRawByLower(cascadeId) {
|
||||||
cacheFilePath,
|
|
||||||
cacheState: state,
|
|
||||||
cancelFlushTimer,
|
|
||||||
getCachedTrajectory(cascadeId) {
|
|
||||||
ensureLoaded();
|
|
||||||
return cacheObj[cascadeId];
|
|
||||||
},
|
|
||||||
getCachedTrajectoryEntryByLower(cascadeId) {
|
|
||||||
if (!cascadeId) return null;
|
if (!cascadeId) return null;
|
||||||
ensureLoaded();
|
ensureLoaded();
|
||||||
|
syncExternalIfDue();
|
||||||
const direct = cacheObj[cascadeId];
|
const direct = cacheObj[cascadeId];
|
||||||
if (direct) return { id: String(cascadeId), entry: direct };
|
if (direct) return { id: String(cascadeId), entry: direct };
|
||||||
const canon = byLower.get(String(cascadeId).toLowerCase());
|
const canon = byLower.get(String(cascadeId).toLowerCase());
|
||||||
@@ -210,9 +540,46 @@ export function createTrajectoryCacheStore({
|
|||||||
return { id: canon, entry: cacheObj[canon] };
|
return { id: canon, entry: cacheObj[canon] };
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
cacheFilePath,
|
||||||
|
sqliteFilePath: useSqlite ? sqliteFilePath : '',
|
||||||
|
isSqliteBacked: useSqlite,
|
||||||
|
cacheState: state,
|
||||||
|
cancelFlushTimer,
|
||||||
|
syncExternalChangesNow,
|
||||||
|
getHotSessionCount() {
|
||||||
|
return hotLru.size;
|
||||||
|
},
|
||||||
|
isConversationCold(cascadeId) {
|
||||||
|
const hit = lookupRawByLower(cascadeId);
|
||||||
|
return hit ? tcsIsColdEntry(hit.entry) : false;
|
||||||
|
},
|
||||||
|
getCachedTrajectory(cascadeId) {
|
||||||
|
ensureLoaded();
|
||||||
|
syncExternalIfDue();
|
||||||
|
return cacheObj[cascadeId];
|
||||||
|
},
|
||||||
|
getCachedTrajectoryEntryByLower(cascadeId) {
|
||||||
|
return lookupRawByLower(cascadeId);
|
||||||
|
},
|
||||||
|
getHydratedTrajectory(cascadeId) {
|
||||||
|
const hit = lookupRawByLower(cascadeId);
|
||||||
|
if (!hit) return undefined;
|
||||||
|
return hydrateEntryInPlaceIfNeeded(hit.id, hit.entry);
|
||||||
|
},
|
||||||
|
getHydratedTrajectoryEntryByLower(cascadeId) {
|
||||||
|
const hit = lookupRawByLower(cascadeId);
|
||||||
|
if (!hit) return null;
|
||||||
|
return {
|
||||||
|
id: hit.id,
|
||||||
|
entry: hydrateEntryInPlaceIfNeeded(hit.id, hit.entry),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
listCachedTrajectoryEntries() {
|
listCachedTrajectoryEntries() {
|
||||||
ensureLoaded();
|
ensureLoaded();
|
||||||
|
syncExternalIfDue();
|
||||||
return Object.entries(cacheObj);
|
return Object.entries(cacheObj);
|
||||||
},
|
},
|
||||||
setCachedTrajectory(cascadeId, entry) {
|
setCachedTrajectory(cascadeId, entry) {
|
||||||
@@ -226,6 +593,18 @@ export function createTrajectoryCacheStore({
|
|||||||
) {
|
) {
|
||||||
delete cacheObj[prevCanon];
|
delete cacheObj[prevCanon];
|
||||||
}
|
}
|
||||||
|
if (entry && typeof entry === 'object') {
|
||||||
|
const isStillCold = Boolean(entry.steps?._isColdSlimSteps === true);
|
||||||
|
tcsDefineHiddenProp(entry, '_coldSteps', isStillCold);
|
||||||
|
tcsAttachEntryStepFlags(entry, entry._stepFlags || null);
|
||||||
|
if (useSqlite && lower) {
|
||||||
|
dirtyRemovals.delete(lower);
|
||||||
|
dirtyUpserts.add(lower);
|
||||||
|
if (!isStillCold) {
|
||||||
|
touchHotSession(lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
cacheObj[cascadeId] = entry;
|
cacheObj[cascadeId] = entry;
|
||||||
if (lower) {
|
if (lower) {
|
||||||
byLower.set(lower, String(cascadeId));
|
byLower.set(lower, String(cascadeId));
|
||||||
@@ -234,10 +613,19 @@ export function createTrajectoryCacheStore({
|
|||||||
removeCachedTrajectory(cascadeId) {
|
removeCachedTrajectory(cascadeId) {
|
||||||
ensureLoaded();
|
ensureLoaded();
|
||||||
const lower = String(cascadeId || '').toLowerCase();
|
const lower = String(cascadeId || '').toLowerCase();
|
||||||
if (lower && byLower.get(lower) === cascadeId) {
|
const canon = lower ? byLower.get(lower) : undefined;
|
||||||
byLower.delete(lower);
|
if (canon && Object.prototype.hasOwnProperty.call(cacheObj, canon)) {
|
||||||
|
delete cacheObj[canon];
|
||||||
}
|
}
|
||||||
delete cacheObj[cascadeId];
|
delete cacheObj[cascadeId];
|
||||||
|
if (lower) {
|
||||||
|
byLower.delete(lower);
|
||||||
|
hotLru.delete(lower);
|
||||||
|
if (useSqlite) {
|
||||||
|
dirtyUpserts.delete(lower);
|
||||||
|
dirtyRemovals.add(lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
hasPendingTrajectoryCacheSave() {
|
hasPendingTrajectoryCacheSave() {
|
||||||
ensureLoaded();
|
ensureLoaded();
|
||||||
|
|||||||
@@ -0,0 +1,954 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Incremental SQLite trajectory & permanent usage ledger engine (`trajectory-sqlite-ledger.mjs`).
|
||||||
|
*
|
||||||
|
* Architecture:
|
||||||
|
* 1. Short-lived connections (`open -> WAL/NORMAL/busy_timeout -> tx -> close` in `finally`) prevent Windows
|
||||||
|
* file-handle lock retention (`EBUSY`) across Sidecar, `bridge-daemon.mjs`, and `standalone.mjs`.
|
||||||
|
* 2. Two-tier step storage:
|
||||||
|
* - `accounting_json`: compact 21-slot tuple holding scalar billing/timing/model/anomaly fields; cold
|
||||||
|
* conversations keep only interned slim objects in V8 memory (`~80ms` startup for `57k+` steps).
|
||||||
|
* - `detail_json`: lossless remainder (`contextBreakdown`, `turnPrompt*`, ISO timestamps, context limits, etc.),
|
||||||
|
* lazily hydrated on demand (`~1ms`) only for active/inspected conversations via a 24-entry LRU.
|
||||||
|
* 3. Step-level `O(delta)` incremental `UPSERT` with tail truncation (`DELETE ... WHERE pos >= ?`) on conversation
|
||||||
|
* undo/branching, plus `ledger_epoch` + `write_seq` cross-process WAL synchronization.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||||
|
import { isPlainObject } from './http-helpers.mjs';
|
||||||
|
import {
|
||||||
|
computeSqliteWalSig,
|
||||||
|
getNodeSqliteDatabaseSync,
|
||||||
|
isSqliteBusyError,
|
||||||
|
} from './sqlite-client.mjs';
|
||||||
|
|
||||||
|
export const LEDGER_SCHEMA_VERSION = '1';
|
||||||
|
const TSL_BUSY_TIMEOUT_WRITE_MS = 3000;
|
||||||
|
const TSL_BUSY_TIMEOUT_READ_MS = 1500;
|
||||||
|
const TSL_MAX_BUSY_ATTEMPTS = 3;
|
||||||
|
|
||||||
|
const TSL_FLAG_COMPACTION = 1 << 0;
|
||||||
|
const TSL_FLAG_IMAGE_GEN = 1 << 1;
|
||||||
|
const TSL_FLAG_COMPLETE = 1 << 2;
|
||||||
|
const TSL_FLAG_SPEED_ELIGIBLE = 1 << 3;
|
||||||
|
const TSL_FLAG_VISIBLE_TEXT = 1 << 4;
|
||||||
|
const TSL_FLAG_TOOL_CALLS = 1 << 5;
|
||||||
|
|
||||||
|
const TSL_CORE_STEP_KEYS = new Set([
|
||||||
|
'stepIndex',
|
||||||
|
'createdAtMs',
|
||||||
|
'isCompactionStep',
|
||||||
|
'isImageGenStep',
|
||||||
|
'isComplete',
|
||||||
|
'speedSampleEligible',
|
||||||
|
'hasVisibleText',
|
||||||
|
'hasToolCalls',
|
||||||
|
'modelKey',
|
||||||
|
'responseModel',
|
||||||
|
'apiProvider',
|
||||||
|
'modelDisplayName',
|
||||||
|
'modelSource',
|
||||||
|
'modelIdentityVersion',
|
||||||
|
'inputTokens',
|
||||||
|
'cacheReadTokens',
|
||||||
|
'outputTokens',
|
||||||
|
'thinkingTokens',
|
||||||
|
'responseTokens',
|
||||||
|
'totalDurationSec',
|
||||||
|
'totalTokPerSec',
|
||||||
|
'nativeTtftSec',
|
||||||
|
'speedReason',
|
||||||
|
'measurementVersion',
|
||||||
|
'accountName',
|
||||||
|
'anomaly',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function tslCreateInternPool() {
|
||||||
|
const pool = new Map();
|
||||||
|
return function internString(val) {
|
||||||
|
if (typeof val !== 'string' || val.length === 0) return '';
|
||||||
|
if (val.length > 96) return val;
|
||||||
|
const hit = pool.get(val);
|
||||||
|
if (hit !== undefined) return hit;
|
||||||
|
if (pool.size >= 4096) pool.clear();
|
||||||
|
pool.set(val, val);
|
||||||
|
return val;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes conversation-level `O(1)` step completeness and model-limit metadata
|
||||||
|
* so scanner `toFetch` checks and `buildKnownUpstreamModelMap` never need to hydrate cold `detail_json`.
|
||||||
|
*
|
||||||
|
* @param {object[]} steps
|
||||||
|
* @returns {{
|
||||||
|
* hasMissingStepFields: boolean,
|
||||||
|
* hasMissingTurnRailFields: boolean,
|
||||||
|
* hasAnyTurnIndex: boolean,
|
||||||
|
* hasIncompleteTiming: boolean,
|
||||||
|
* modelLimits: Array<[string, number, number]>,
|
||||||
|
* }}
|
||||||
|
*/
|
||||||
|
export function computePrecomputedStepFlags(steps) {
|
||||||
|
const list = Array.isArray(steps) ? steps : [];
|
||||||
|
if (list.length === 0) {
|
||||||
|
return {
|
||||||
|
hasMissingStepFields: false,
|
||||||
|
hasMissingTurnRailFields: false,
|
||||||
|
hasAnyTurnIndex: false,
|
||||||
|
hasAnyContextBreakdown: false,
|
||||||
|
hasIncompleteTiming: false,
|
||||||
|
modelLimits: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const lastStep = list[list.length - 1];
|
||||||
|
const lastHasContextBdProp = Boolean(
|
||||||
|
lastStep && Object.prototype.hasOwnProperty.call(lastStep, 'contextBreakdown')
|
||||||
|
);
|
||||||
|
const lastHasTurnIdxProp = Boolean(
|
||||||
|
lastStep && Object.prototype.hasOwnProperty.call(lastStep, 'turnIndex')
|
||||||
|
);
|
||||||
|
let missingResponseModel = false;
|
||||||
|
let missingToolResultsTokens = false;
|
||||||
|
let checkedLastBd = false;
|
||||||
|
let hasAnyTurnIndex = false;
|
||||||
|
let hasAnyContextBreakdown = false;
|
||||||
|
let hasIncompleteTiming = false;
|
||||||
|
const limitsMap = new Map();
|
||||||
|
|
||||||
|
for (let i = list.length - 1; i >= 0; i -= 1) {
|
||||||
|
const st = list[i];
|
||||||
|
if (!st || typeof st !== 'object') continue;
|
||||||
|
if (st.contextBreakdown && typeof st.contextBreakdown === 'object') {
|
||||||
|
hasAnyContextBreakdown = true;
|
||||||
|
if (!checkedLastBd) {
|
||||||
|
checkedLastBd = true;
|
||||||
|
missingToolResultsTokens = !Object.prototype.hasOwnProperty.call(
|
||||||
|
st.contextBreakdown,
|
||||||
|
'toolResultsTokens'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(st, 'responseModel')) {
|
||||||
|
missingResponseModel = true;
|
||||||
|
}
|
||||||
|
if (st.turnIndex) {
|
||||||
|
hasAnyTurnIndex = true;
|
||||||
|
}
|
||||||
|
if (st.speedReason === 'incomplete_or_invalid_timing') {
|
||||||
|
hasIncompleteTiming = true;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!st.isCompactionStep &&
|
||||||
|
!st.isImageGenStep &&
|
||||||
|
Number(st.reportedContextLimitTokens) > 0 &&
|
||||||
|
st.modelKey &&
|
||||||
|
st.modelKey !== 'unknown'
|
||||||
|
) {
|
||||||
|
const atMs = Number.isFinite(Number(st.createdAtMs)) ? Number(st.createdAtMs) : 0;
|
||||||
|
const prev = limitsMap.get(st.modelKey);
|
||||||
|
if (!prev || atMs > prev.at) {
|
||||||
|
limitsMap.set(st.modelKey, {
|
||||||
|
tokens: Number(st.reportedContextLimitTokens),
|
||||||
|
at: atMs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const modelLimits = [];
|
||||||
|
for (const [modelKey, info] of limitsMap.entries()) {
|
||||||
|
modelLimits.push([modelKey, info.tokens, info.at]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
hasMissingStepFields: !lastHasContextBdProp || missingResponseModel || missingToolResultsTokens,
|
||||||
|
hasMissingTurnRailFields: !lastHasTurnIdxProp,
|
||||||
|
hasAnyTurnIndex,
|
||||||
|
hasAnyContextBreakdown,
|
||||||
|
hasIncompleteTiming,
|
||||||
|
modelLimits,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits a full normalized step object into a compact 21-slot accounting tuple and an optional detail object.
|
||||||
|
*
|
||||||
|
* @param {object} step
|
||||||
|
* @returns {{ accountingTuple: any[], detailObj: Record<string, any> | null }}
|
||||||
|
*/
|
||||||
|
export function splitStepForStorage(step) {
|
||||||
|
const s = step && typeof step === 'object' ? step : {};
|
||||||
|
let flags = 0;
|
||||||
|
if (s.isCompactionStep) flags |= TSL_FLAG_COMPACTION;
|
||||||
|
if (s.isImageGenStep) flags |= TSL_FLAG_IMAGE_GEN;
|
||||||
|
if (s.isComplete) flags |= TSL_FLAG_COMPLETE;
|
||||||
|
if (s.speedSampleEligible) flags |= TSL_FLAG_SPEED_ELIGIBLE;
|
||||||
|
if (s.hasVisibleText) flags |= TSL_FLAG_VISIBLE_TEXT;
|
||||||
|
if (s.hasToolCalls) flags |= TSL_FLAG_TOOL_CALLS;
|
||||||
|
|
||||||
|
const accountingTuple = [
|
||||||
|
s.stepIndex ?? null,
|
||||||
|
Number(s.createdAtMs || 0),
|
||||||
|
flags,
|
||||||
|
s.modelKey || '',
|
||||||
|
s.responseModel ?? '',
|
||||||
|
s.apiProvider || '',
|
||||||
|
s.modelDisplayName || '',
|
||||||
|
s.modelSource || '',
|
||||||
|
s.modelIdentityVersion ?? null,
|
||||||
|
Number(s.inputTokens || 0),
|
||||||
|
Number(s.cacheReadTokens || 0),
|
||||||
|
Number(s.outputTokens || 0),
|
||||||
|
Number(s.thinkingTokens || 0),
|
||||||
|
s.responseTokens !== undefined && s.responseTokens !== null
|
||||||
|
? Number(s.responseTokens)
|
||||||
|
: Math.max(0, Number(s.outputTokens || 0) - Number(s.thinkingTokens || 0)),
|
||||||
|
s.totalDurationSec ?? null,
|
||||||
|
s.totalTokPerSec ?? null,
|
||||||
|
s.nativeTtftSec ?? null,
|
||||||
|
s.speedReason ?? null,
|
||||||
|
s.measurementVersion ?? null,
|
||||||
|
s.accountName ?? null,
|
||||||
|
s.anomaly ?? null,
|
||||||
|
];
|
||||||
|
|
||||||
|
let detailObj = null;
|
||||||
|
for (const key of Object.keys(s)) {
|
||||||
|
if (TSL_CORE_STEP_KEYS.has(key)) continue;
|
||||||
|
if (s[key] === undefined) continue;
|
||||||
|
if (!detailObj) detailObj = {};
|
||||||
|
detailObj[key] = s[key];
|
||||||
|
}
|
||||||
|
return { accountingTuple, detailObj };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rebuilds a fixed-shape slim step object from a compact accounting tuple (or legacy plain object).
|
||||||
|
*
|
||||||
|
* @param {any[] | Record<string, any>} rawAccounting
|
||||||
|
* @param {(val: string) => string} [internFn]
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v || '') {
|
||||||
|
if (!Array.isArray(rawAccounting)) {
|
||||||
|
if (isPlainObject(rawAccounting)) {
|
||||||
|
const { accountingTuple } = splitStepForStorage(rawAccounting);
|
||||||
|
return buildSlimStepFromAccounting(accountingTuple, internFn);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const t = rawAccounting;
|
||||||
|
const flags = Number(t[2] || 0);
|
||||||
|
const slim = {
|
||||||
|
stepIndex: t[0] ?? null,
|
||||||
|
createdAtMs: Number(t[1] || 0),
|
||||||
|
isCompactionStep: Boolean(flags & TSL_FLAG_COMPACTION),
|
||||||
|
...(flags & TSL_FLAG_IMAGE_GEN ? { isImageGenStep: true } : {}),
|
||||||
|
isComplete: Boolean(flags & TSL_FLAG_COMPLETE),
|
||||||
|
speedSampleEligible: Boolean(flags & TSL_FLAG_SPEED_ELIGIBLE),
|
||||||
|
hasVisibleText: Boolean(flags & TSL_FLAG_VISIBLE_TEXT),
|
||||||
|
hasToolCalls: Boolean(flags & TSL_FLAG_TOOL_CALLS),
|
||||||
|
modelKey: internFn(t[3] || ''),
|
||||||
|
responseModel: internFn(t[4] || ''),
|
||||||
|
apiProvider: internFn(t[5] || ''),
|
||||||
|
modelDisplayName: internFn(t[6] || ''),
|
||||||
|
modelSource: internFn(t[7] || ''),
|
||||||
|
modelIdentityVersion: t[8] ?? null,
|
||||||
|
inputTokens: Number(t[9] || 0),
|
||||||
|
cacheReadTokens: Number(t[10] || 0),
|
||||||
|
outputTokens: Number(t[11] || 0),
|
||||||
|
thinkingTokens: Number(t[12] || 0),
|
||||||
|
responseTokens: Number(t[13] || 0),
|
||||||
|
totalDurationSec: t[14] ?? null,
|
||||||
|
totalTokPerSec: t[15] ?? null,
|
||||||
|
nativeTtftSec: t[16] ?? null,
|
||||||
|
speedReason: t[17] ? internFn(t[17]) : null,
|
||||||
|
measurementVersion: t[18] ?? null,
|
||||||
|
};
|
||||||
|
if (t[19]) {
|
||||||
|
slim.accountName = internFn(t[19]);
|
||||||
|
}
|
||||||
|
if (t[20]) {
|
||||||
|
slim.anomaly = t[20];
|
||||||
|
}
|
||||||
|
return slim;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merges a slim accounting step and parsed `detail_json` object into a complete step object.
|
||||||
|
*
|
||||||
|
* @param {object | any[]} accountingOrSlim
|
||||||
|
* @param {Record<string, any> | null | undefined} detailObj
|
||||||
|
* @param {(val: string) => string} [internFn]
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
export function mergeStepFromStorage(accountingOrSlim, detailObj, internFn) {
|
||||||
|
const base = Array.isArray(accountingOrSlim)
|
||||||
|
? buildSlimStepFromAccounting(accountingOrSlim, internFn)
|
||||||
|
: { ...(accountingOrSlim || {}) };
|
||||||
|
if (detailObj && typeof detailObj === 'object' && !Array.isArray(detailObj)) {
|
||||||
|
return { ...base, ...detailObj };
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a hydrated in-memory step into its cold slim representation, releasing heavy `detail` properties.
|
||||||
|
*
|
||||||
|
* @param {object} step
|
||||||
|
* @param {(val: string) => string} [internFn]
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
export function dehydrateStepForColdMemory(step, internFn) {
|
||||||
|
const { accountingTuple } = splitStepForStorage(step);
|
||||||
|
return buildSlimStepFromAccounting(accountingTuple, internFn);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tslSerializeEntryHeader(entry) {
|
||||||
|
const meta = {};
|
||||||
|
for (const [k, v] of Object.entries(entry || {})) {
|
||||||
|
if (k === 'steps' || k === '_coldSteps') continue;
|
||||||
|
if (v !== undefined) meta[k] = v;
|
||||||
|
}
|
||||||
|
if (!meta._stepFlags && Array.isArray(entry?.steps) && !entry._coldSteps) {
|
||||||
|
meta._stepFlags = computePrecomputedStepFlags(entry.steps);
|
||||||
|
}
|
||||||
|
return meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tslWithSqliteConnection(dbPath, { readOnly = false }, fn) {
|
||||||
|
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||||
|
if (!DatabaseSync) {
|
||||||
|
throw new Error('node:sqlite DatabaseSync unavailable');
|
||||||
|
}
|
||||||
|
if (!readOnly) {
|
||||||
|
mkdirSync(dirname(dbPath), { recursive: true });
|
||||||
|
}
|
||||||
|
for (let attempt = 0; attempt < TSL_MAX_BUSY_ATTEMPTS; attempt += 1) {
|
||||||
|
let db = null;
|
||||||
|
try {
|
||||||
|
db = readOnly ? new DatabaseSync(dbPath, { readOnly: true }) : new DatabaseSync(dbPath);
|
||||||
|
if (readOnly) {
|
||||||
|
db.exec(`PRAGMA busy_timeout = ${TSL_BUSY_TIMEOUT_READ_MS};`);
|
||||||
|
} else {
|
||||||
|
db.exec(
|
||||||
|
`PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = ${TSL_BUSY_TIMEOUT_WRITE_MS};`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return fn(db);
|
||||||
|
} catch (err) {
|
||||||
|
if (attempt + 1 < TSL_MAX_BUSY_ATTEMPTS && isSqliteBusyError(err)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
if (db) {
|
||||||
|
try {
|
||||||
|
db.close();
|
||||||
|
} catch {
|
||||||
|
// Ignore close error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tslEnsureSchema(db) {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS ledger_meta (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS conversations (
|
||||||
|
cascade_id TEXT PRIMARY KEY,
|
||||||
|
lower_id TEXT NOT NULL UNIQUE,
|
||||||
|
is_archived INTEGER NOT NULL DEFAULT 0,
|
||||||
|
step_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
write_seq INTEGER NOT NULL DEFAULT 0,
|
||||||
|
updated_at_ms INTEGER NOT NULL DEFAULT 0,
|
||||||
|
meta_json TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conv_write_seq ON conversations(write_seq);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conv_updated ON conversations(updated_at_ms);
|
||||||
|
CREATE TABLE IF NOT EXISTS steps (
|
||||||
|
cascade_id TEXT NOT NULL,
|
||||||
|
pos INTEGER NOT NULL,
|
||||||
|
accounting_json TEXT NOT NULL,
|
||||||
|
detail_json TEXT,
|
||||||
|
PRIMARY KEY (cascade_id, pos)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
const verRow = db
|
||||||
|
.prepare("SELECT value FROM ledger_meta WHERE key = 'schema_version'")
|
||||||
|
.get();
|
||||||
|
if (!verRow) {
|
||||||
|
db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('schema_version', ?)").run(
|
||||||
|
LEDGER_SCHEMA_VERSION
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const epochRow = db
|
||||||
|
.prepare("SELECT value FROM ledger_meta WHERE key = 'ledger_epoch'")
|
||||||
|
.get();
|
||||||
|
if (!epochRow) {
|
||||||
|
db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('ledger_epoch', '1')").run();
|
||||||
|
}
|
||||||
|
const seqRow = db
|
||||||
|
.prepare("SELECT value FROM ledger_meta WHERE key = 'last_write_seq'")
|
||||||
|
.get();
|
||||||
|
if (!seqRow) {
|
||||||
|
db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', '0')").run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tslReadMetaInt(db, key, fallback = 0) {
|
||||||
|
const row = db.prepare('SELECT value FROM ledger_meta WHERE key = ?').get(key);
|
||||||
|
const num = Number(row?.value);
|
||||||
|
return Number.isFinite(num) && num >= 0 ? Math.floor(num) : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tslArchiveLegacyJsonToBak(legacyJsonPath) {
|
||||||
|
if (!legacyJsonPath || !existsSync(legacyJsonPath)) return;
|
||||||
|
const bakPath = `${legacyJsonPath}.bak`;
|
||||||
|
try {
|
||||||
|
if (existsSync(bakPath)) {
|
||||||
|
rmSync(bakPath, { force: true });
|
||||||
|
}
|
||||||
|
renameSync(legacyJsonPath, bakPath);
|
||||||
|
} catch (err) {
|
||||||
|
if (err && err.code === 'ENOENT') return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a short-connection SQLite trajectory ledger controller for one database file.
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* sqliteFilePath: string,
|
||||||
|
* legacyJsonPath?: string,
|
||||||
|
* loadJsonFn?: (filePath: string, fallback: any) => any,
|
||||||
|
* }} options
|
||||||
|
*/
|
||||||
|
export function createTrajectorySqliteLedger({
|
||||||
|
sqliteFilePath,
|
||||||
|
legacyJsonPath = '',
|
||||||
|
loadJsonFn = null,
|
||||||
|
}) {
|
||||||
|
const internString = tslCreateInternPool();
|
||||||
|
// Tracks per-conversation persisted signatures (`{ metaJson, stepSigs: string[] }`) for O(delta) step writes
|
||||||
|
const persistedByLower = new Map();
|
||||||
|
let localEpoch = 1;
|
||||||
|
let localWriteSeq = 0;
|
||||||
|
let lastSeenWalSig = '';
|
||||||
|
|
||||||
|
function refreshWalSigAfterOwnWrite() {
|
||||||
|
lastSeenWalSig = computeSqliteWalSig(sqliteFilePath).sig;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLegacyEntriesForMigration(rawLoaded) {
|
||||||
|
const dedupedByLower = new Map();
|
||||||
|
if (!isPlainObject(rawLoaded)) return dedupedByLower;
|
||||||
|
for (const [rawId, rawEntry] of Object.entries(rawLoaded)) {
|
||||||
|
const id = String(rawId || '').trim();
|
||||||
|
const lower = id.toLowerCase();
|
||||||
|
if (!lower || !isPlainObject(rawEntry)) continue;
|
||||||
|
const rawSteps = Array.isArray(rawEntry.steps) ? rawEntry.steps.filter(isPlainObject) : [];
|
||||||
|
const normalized = inferCompactionStepModels(
|
||||||
|
rawSteps.map((s) => normalizeCachedStep(s)).filter(Boolean)
|
||||||
|
);
|
||||||
|
const canonId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
|
||||||
|
? lower
|
||||||
|
: id;
|
||||||
|
const prev = dedupedByLower.get(lower);
|
||||||
|
if (!prev || normalized.length >= prev.entry.steps.length) {
|
||||||
|
dedupedByLower.set(lower, {
|
||||||
|
cascadeId: canonId,
|
||||||
|
lowerId: lower,
|
||||||
|
entry: { ...rawEntry, steps: normalized },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dedupedByLower;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed,
|
||||||
|
* and hydrates all conversations in cold slim accounting mode.
|
||||||
|
*/
|
||||||
|
function openAndHydrateInitial() {
|
||||||
|
let migratedLegacy = false;
|
||||||
|
const hasLegacyJsonOnDisk = Boolean(
|
||||||
|
legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)
|
||||||
|
);
|
||||||
|
const dbExistsBefore = existsSync(sqliteFilePath);
|
||||||
|
|
||||||
|
if (!dbExistsBefore || hasLegacyJsonOnDisk) {
|
||||||
|
tslWithSqliteConnection(sqliteFilePath, { readOnly: false }, (db) => {
|
||||||
|
tslEnsureSchema(db);
|
||||||
|
const migRow = db
|
||||||
|
.prepare("SELECT value FROM ledger_meta WHERE key = 'migrated_legacy_json'")
|
||||||
|
.get();
|
||||||
|
if (migRow?.value === '1') return;
|
||||||
|
|
||||||
|
let rawLoaded = null;
|
||||||
|
if (legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)) {
|
||||||
|
rawLoaded = loadJsonFn(legacyJsonPath, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.exec('BEGIN IMMEDIATE');
|
||||||
|
try {
|
||||||
|
const migRowInTx = db
|
||||||
|
.prepare("SELECT value FROM ledger_meta WHERE key = 'migrated_legacy_json'")
|
||||||
|
.get();
|
||||||
|
if (migRowInTx?.value !== '1') {
|
||||||
|
let seq = tslReadMetaInt(db, 'last_write_seq', 0);
|
||||||
|
const nowMs = Date.now();
|
||||||
|
if (rawLoaded && isPlainObject(rawLoaded)) {
|
||||||
|
const deduped = normalizeLegacyEntriesForMigration(rawLoaded);
|
||||||
|
const insConv = db.prepare(`
|
||||||
|
INSERT OR REPLACE INTO conversations (
|
||||||
|
cascade_id, lower_id, is_archived, step_count, write_seq, updated_at_ms, meta_json
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
const insStep = db.prepare(`
|
||||||
|
INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
for (const { cascadeId, lowerId, entry } of deduped.values()) {
|
||||||
|
seq += 1;
|
||||||
|
const steps = entry.steps || [];
|
||||||
|
const header = tslSerializeEntryHeader(entry);
|
||||||
|
const metaJson = JSON.stringify(header);
|
||||||
|
const archivedInt = entry.archived ? 1 : 0;
|
||||||
|
insConv.run(cascadeId, lowerId, archivedInt, steps.length, seq, nowMs, metaJson);
|
||||||
|
const stepSigs = new Array(steps.length);
|
||||||
|
for (let pos = 0; pos < steps.length; pos += 1) {
|
||||||
|
const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]);
|
||||||
|
const accJson = JSON.stringify(accountingTuple);
|
||||||
|
const detJson = detailObj ? JSON.stringify(detailObj) : null;
|
||||||
|
insStep.run(cascadeId, pos, accJson, detJson);
|
||||||
|
stepSigs[pos] = detJson ? `${accJson}\n${detJson}` : accJson;
|
||||||
|
}
|
||||||
|
persistedByLower.set(lowerId, {
|
||||||
|
cascadeId,
|
||||||
|
metaJson,
|
||||||
|
archivedInt,
|
||||||
|
stepSigs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
migratedLegacy = true;
|
||||||
|
}
|
||||||
|
db.prepare(
|
||||||
|
"INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', ?)"
|
||||||
|
).run(String(seq));
|
||||||
|
db.prepare(
|
||||||
|
"INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('migrated_legacy_json', '1')"
|
||||||
|
).run();
|
||||||
|
}
|
||||||
|
db.exec('COMMIT');
|
||||||
|
} catch (err) {
|
||||||
|
try {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
} catch {
|
||||||
|
// Ignore rollback error
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (migratedLegacy || hasLegacyJsonOnDisk) {
|
||||||
|
tslArchiveLegacyJsonToBak(legacyJsonPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return hydrateAllSlimFromDb();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hydrateAllSlimFromDb() {
|
||||||
|
if (!existsSync(sqliteFilePath)) {
|
||||||
|
localEpoch = 1;
|
||||||
|
localWriteSeq = 0;
|
||||||
|
lastSeenWalSig = '';
|
||||||
|
return { cacheObj: Object.create(null) };
|
||||||
|
}
|
||||||
|
const cacheObj = Object.create(null);
|
||||||
|
tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => {
|
||||||
|
localEpoch = tslReadMetaInt(db, 'ledger_epoch', 1);
|
||||||
|
localWriteSeq = tslReadMetaInt(db, 'last_write_seq', 0);
|
||||||
|
const convRows = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT cascade_id, lower_id, is_archived, step_count, meta_json FROM conversations'
|
||||||
|
)
|
||||||
|
.all();
|
||||||
|
const stepRows = db
|
||||||
|
.prepare('SELECT cascade_id, pos, accounting_json FROM steps ORDER BY cascade_id, pos ASC')
|
||||||
|
.all();
|
||||||
|
|
||||||
|
for (const row of convRows) {
|
||||||
|
let meta = {};
|
||||||
|
try {
|
||||||
|
meta = JSON.parse(row.meta_json) || {};
|
||||||
|
} catch {
|
||||||
|
meta = {};
|
||||||
|
}
|
||||||
|
const entry = {
|
||||||
|
...meta,
|
||||||
|
...(row.is_archived ? { archived: true } : {}),
|
||||||
|
_coldSteps: true,
|
||||||
|
steps: [],
|
||||||
|
};
|
||||||
|
if (!row.is_archived && entry.archived) {
|
||||||
|
delete entry.archived;
|
||||||
|
}
|
||||||
|
cacheObj[row.cascade_id] = entry;
|
||||||
|
if (!persistedByLower.has(row.lower_id)) {
|
||||||
|
persistedByLower.set(row.lower_id, {
|
||||||
|
cascadeId: row.cascade_id,
|
||||||
|
metaJson: row.meta_json,
|
||||||
|
archivedInt: row.is_archived ? 1 : 0,
|
||||||
|
stepSigs: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const sRow of stepRows) {
|
||||||
|
const target = cacheObj[sRow.cascade_id];
|
||||||
|
if (!target) continue;
|
||||||
|
let parsedAcc = null;
|
||||||
|
try {
|
||||||
|
parsedAcc = JSON.parse(sRow.accounting_json);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
target.steps.push(buildSlimStepFromAccounting(parsedAcc, internString));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
lastSeenWalSig = computeSqliteWalSig(sqliteFilePath).sig;
|
||||||
|
return { cacheObj };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronously hydrates full `detail_json` rows for a single cold conversation (`<1.5ms`).
|
||||||
|
*
|
||||||
|
* @param {string} cascadeId
|
||||||
|
* @param {object} currentEntry
|
||||||
|
* @returns {object[] | null}
|
||||||
|
*/
|
||||||
|
function loadHydratedStepsForConversation(cascadeId, currentEntry) {
|
||||||
|
if (!cascadeId || !currentEntry || !existsSync(sqliteFilePath)) return null;
|
||||||
|
const slimSteps = Array.isArray(currentEntry.steps) ? currentEntry.steps : [];
|
||||||
|
if (slimSteps.length === 0) return [];
|
||||||
|
|
||||||
|
return tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => {
|
||||||
|
const lower = String(cascadeId).toLowerCase();
|
||||||
|
const convRow = db
|
||||||
|
.prepare('SELECT cascade_id FROM conversations WHERE lower_id = ?')
|
||||||
|
.get(lower);
|
||||||
|
const dbCid = convRow?.cascade_id || cascadeId;
|
||||||
|
const detailRows = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT pos, accounting_json, detail_json FROM steps WHERE cascade_id = ? ORDER BY pos ASC'
|
||||||
|
)
|
||||||
|
.all(dbCid);
|
||||||
|
if (!detailRows || detailRows.length === 0) {
|
||||||
|
return slimSteps.map((s) => ({ ...s }));
|
||||||
|
}
|
||||||
|
const hydrated = new Array(detailRows.length);
|
||||||
|
for (let i = 0; i < detailRows.length; i += 1) {
|
||||||
|
const r = detailRows[i];
|
||||||
|
let acc = null;
|
||||||
|
let det = null;
|
||||||
|
try {
|
||||||
|
acc = JSON.parse(r.accounting_json);
|
||||||
|
} catch {
|
||||||
|
acc = slimSteps[i] || {};
|
||||||
|
}
|
||||||
|
if (r.detail_json) {
|
||||||
|
try {
|
||||||
|
det = JSON.parse(r.detail_json);
|
||||||
|
} catch {
|
||||||
|
det = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hydrated[i] = mergeStepFromStorage(acc, det, internString);
|
||||||
|
}
|
||||||
|
return hydrated;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists dirty conversations and removals incrementally inside a single `BEGIN IMMEDIATE` transaction.
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* upserts: Array<{ cascadeId: string, entry: object }>,
|
||||||
|
* removals: string[],
|
||||||
|
* bumpEpoch?: boolean,
|
||||||
|
* }} batch
|
||||||
|
*/
|
||||||
|
function flushDeltaBatch({ upserts = [], removals = [], bumpEpoch = false } = {}) {
|
||||||
|
if (upserts.length === 0 && removals.length === 0 && !bumpEpoch) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
tslWithSqliteConnection(sqliteFilePath, { readOnly: false }, (db) => {
|
||||||
|
tslEnsureSchema(db);
|
||||||
|
db.exec('BEGIN IMMEDIATE');
|
||||||
|
try {
|
||||||
|
let seq = tslReadMetaInt(db, 'last_write_seq', localWriteSeq);
|
||||||
|
let epoch = tslReadMetaInt(db, 'ledger_epoch', localEpoch);
|
||||||
|
const nowMs = Date.now();
|
||||||
|
|
||||||
|
if (bumpEpoch || removals.length > 0) {
|
||||||
|
epoch += 1;
|
||||||
|
db.prepare(
|
||||||
|
"INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('ledger_epoch', ?)"
|
||||||
|
).run(String(epoch));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (removals.length > 0) {
|
||||||
|
const selByLower = db.prepare(
|
||||||
|
'SELECT cascade_id FROM conversations WHERE lower_id = ?'
|
||||||
|
);
|
||||||
|
const delSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?');
|
||||||
|
const delConv = db.prepare('DELETE FROM conversations WHERE lower_id = ?');
|
||||||
|
for (const rawRem of removals) {
|
||||||
|
const lower = String(rawRem || '').toLowerCase();
|
||||||
|
if (!lower) continue;
|
||||||
|
const existing = selByLower.get(lower);
|
||||||
|
if (existing?.cascade_id) {
|
||||||
|
delSteps.run(existing.cascade_id);
|
||||||
|
}
|
||||||
|
delSteps.run(rawRem);
|
||||||
|
delConv.run(lower);
|
||||||
|
persistedByLower.delete(lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (upserts.length > 0) {
|
||||||
|
const selExisting = db.prepare(
|
||||||
|
'SELECT cascade_id, step_count FROM conversations WHERE lower_id = ?'
|
||||||
|
);
|
||||||
|
const upConv = db.prepare(`
|
||||||
|
INSERT OR REPLACE INTO conversations (
|
||||||
|
cascade_id, lower_id, is_archived, step_count, write_seq, updated_at_ms, meta_json
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
const upStep = db.prepare(`
|
||||||
|
INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
const truncSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ? AND pos >= ?');
|
||||||
|
const delOldCidSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?');
|
||||||
|
|
||||||
|
for (const { cascadeId, entry } of upserts) {
|
||||||
|
if (!cascadeId || !entry || typeof entry !== 'object') continue;
|
||||||
|
const lower = String(cascadeId).toLowerCase();
|
||||||
|
const prevDbRow = selExisting.get(lower);
|
||||||
|
if (prevDbRow?.cascade_id && prevDbRow.cascade_id !== cascadeId) {
|
||||||
|
delOldCidSteps.run(prevDbRow.cascade_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevDigest = persistedByLower.get(lower) || null;
|
||||||
|
const header = tslSerializeEntryHeader(entry);
|
||||||
|
const metaJson = JSON.stringify(header);
|
||||||
|
const archivedInt = entry.archived ? 1 : 0;
|
||||||
|
const steps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||||
|
|
||||||
|
// When an entry is still in `_coldSteps` mode (only metadata such as `signature`, `title`,
|
||||||
|
// or `archived` changed without mutating steps), update ONLY `conversations` in O(1)
|
||||||
|
// without touching `steps` (`detail_json` on disk stays 100% intact)!
|
||||||
|
if (entry._coldSteps && prevDbRow && prevDbRow.step_count === steps.length) {
|
||||||
|
if (
|
||||||
|
prevDigest &&
|
||||||
|
prevDigest.cascadeId === cascadeId &&
|
||||||
|
prevDigest.metaJson === metaJson &&
|
||||||
|
prevDigest.archivedInt === archivedInt
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seq += 1;
|
||||||
|
upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson);
|
||||||
|
persistedByLower.set(lower, {
|
||||||
|
cascadeId,
|
||||||
|
metaJson,
|
||||||
|
archivedInt,
|
||||||
|
stepSigs: prevDigest?.stepSigs || null,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevStepSigs =
|
||||||
|
prevDigest?.cascadeId === cascadeId && Array.isArray(prevDigest.stepSigs)
|
||||||
|
? prevDigest.stepSigs
|
||||||
|
: null;
|
||||||
|
const nextStepSigs = new Array(steps.length);
|
||||||
|
let anyStepWritten = false;
|
||||||
|
|
||||||
|
for (let pos = 0; pos < steps.length; pos += 1) {
|
||||||
|
const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]);
|
||||||
|
const accJson = JSON.stringify(accountingTuple);
|
||||||
|
const detJson = detailObj ? JSON.stringify(detailObj) : null;
|
||||||
|
const sig = detJson ? `${accJson}\n${detJson}` : accJson;
|
||||||
|
nextStepSigs[pos] = sig;
|
||||||
|
if (!prevStepSigs || prevStepSigs[pos] !== sig) {
|
||||||
|
upStep.run(cascadeId, pos, accJson, detJson);
|
||||||
|
anyStepWritten = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevCount = prevDbRow
|
||||||
|
? Number(prevDbRow.step_count || 0)
|
||||||
|
: prevStepSigs
|
||||||
|
? prevStepSigs.length
|
||||||
|
: 0;
|
||||||
|
if (steps.length < prevCount) {
|
||||||
|
truncSteps.run(cascadeId, steps.length);
|
||||||
|
anyStepWritten = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
anyStepWritten ||
|
||||||
|
!prevDigest ||
|
||||||
|
prevDigest.cascadeId !== cascadeId ||
|
||||||
|
prevDigest.metaJson !== metaJson ||
|
||||||
|
prevDigest.archivedInt !== archivedInt ||
|
||||||
|
prevCount !== steps.length
|
||||||
|
) {
|
||||||
|
seq += 1;
|
||||||
|
upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
persistedByLower.set(lower, {
|
||||||
|
cascadeId,
|
||||||
|
metaJson,
|
||||||
|
archivedInt,
|
||||||
|
stepSigs: nextStepSigs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare(
|
||||||
|
"INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', ?)"
|
||||||
|
).run(String(seq));
|
||||||
|
db.exec('COMMIT');
|
||||||
|
localEpoch = epoch;
|
||||||
|
localWriteSeq = seq;
|
||||||
|
} catch (err) {
|
||||||
|
try {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
} catch {
|
||||||
|
// Ignore rollback error
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
refreshWalSigAfterOwnWrite();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks WAL composite signature and pulls incremental updates or epoch resets written by peer processes.
|
||||||
|
*
|
||||||
|
* @returns {{
|
||||||
|
* changed: boolean,
|
||||||
|
* fullReset?: boolean,
|
||||||
|
* cacheObj?: Record<string, any>,
|
||||||
|
* updatedEntries?: Array<{ cascadeId: string, lowerId: string, entry: object }>,
|
||||||
|
* }}
|
||||||
|
*/
|
||||||
|
function syncExternalChangesIfNeeded() {
|
||||||
|
const walInfo = computeSqliteWalSig(sqliteFilePath);
|
||||||
|
if (!walInfo.exists || !walInfo.sig || walInfo.sig === lastSeenWalSig) {
|
||||||
|
return { changed: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
let fullResetNeeded = false;
|
||||||
|
const updatedEntries = [];
|
||||||
|
|
||||||
|
tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => {
|
||||||
|
const dbEpoch = tslReadMetaInt(db, 'ledger_epoch', 1);
|
||||||
|
const dbSeq = tslReadMetaInt(db, 'last_write_seq', 0);
|
||||||
|
if (dbEpoch !== localEpoch) {
|
||||||
|
fullResetNeeded = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (dbSeq <= localWriteSeq) {
|
||||||
|
localWriteSeq = dbSeq;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const changedConvs = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT cascade_id, lower_id, is_archived, step_count, write_seq, meta_json
|
||||||
|
FROM conversations
|
||||||
|
WHERE write_seq > ?
|
||||||
|
ORDER BY write_seq ASC`
|
||||||
|
)
|
||||||
|
.all(localWriteSeq);
|
||||||
|
const selSteps = db.prepare(
|
||||||
|
'SELECT pos, accounting_json FROM steps WHERE cascade_id = ? ORDER BY pos ASC'
|
||||||
|
);
|
||||||
|
for (const row of changedConvs) {
|
||||||
|
let meta = {};
|
||||||
|
try {
|
||||||
|
meta = JSON.parse(row.meta_json) || {};
|
||||||
|
} catch {
|
||||||
|
meta = {};
|
||||||
|
}
|
||||||
|
const sRows = selSteps.all(row.cascade_id);
|
||||||
|
const slimSteps = [];
|
||||||
|
for (const sr of sRows) {
|
||||||
|
try {
|
||||||
|
slimSteps.push(buildSlimStepFromAccounting(JSON.parse(sr.accounting_json), internString));
|
||||||
|
} catch {
|
||||||
|
// Skip malformed step JSON
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const entry = {
|
||||||
|
...meta,
|
||||||
|
...(row.is_archived ? { archived: true } : {}),
|
||||||
|
_coldSteps: true,
|
||||||
|
steps: slimSteps,
|
||||||
|
};
|
||||||
|
if (!row.is_archived && entry.archived) {
|
||||||
|
delete entry.archived;
|
||||||
|
}
|
||||||
|
persistedByLower.set(row.lower_id, {
|
||||||
|
cascadeId: row.cascade_id,
|
||||||
|
metaJson: row.meta_json,
|
||||||
|
archivedInt: row.is_archived ? 1 : 0,
|
||||||
|
stepSigs: null,
|
||||||
|
});
|
||||||
|
updatedEntries.push({
|
||||||
|
cascadeId: row.cascade_id,
|
||||||
|
lowerId: row.lower_id,
|
||||||
|
entry,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
localWriteSeq = dbSeq;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (fullResetNeeded) {
|
||||||
|
persistedByLower.clear();
|
||||||
|
const full = hydrateAllSlimFromDb();
|
||||||
|
return { changed: true, fullReset: true, cacheObj: full.cacheObj };
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSeenWalSig = walInfo.sig;
|
||||||
|
if (updatedEntries.length === 0) {
|
||||||
|
return { changed: false };
|
||||||
|
}
|
||||||
|
return { changed: true, fullReset: false, updatedEntries };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sqliteFilePath,
|
||||||
|
internString,
|
||||||
|
openAndHydrateInitial,
|
||||||
|
loadHydratedStepsForConversation,
|
||||||
|
flushDeltaBatch,
|
||||||
|
syncExternalChangesIfNeeded,
|
||||||
|
dehydrateStep: (step) => dehydrateStepForColdMemory(step, internString),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -28,10 +28,11 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/account-switch.mjs',
|
'../backend/account-switch.mjs',
|
||||||
'../backend/http-helpers.mjs',
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
|
'../backend/sqlite-client.mjs',
|
||||||
|
'../backend/trajectory-sqlite-ledger.mjs',
|
||||||
'../backend/trajectory-cache-store.mjs',
|
'../backend/trajectory-cache-store.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
'../backend/endpoint-registry.mjs',
|
'../backend/endpoint-registry.mjs',
|
||||||
'../backend/sqlite-client.mjs',
|
|
||||||
'../backend/proto-wire.mjs',
|
'../backend/proto-wire.mjs',
|
||||||
'../backend/cli-sqlite-reader.mjs',
|
'../backend/cli-sqlite-reader.mjs',
|
||||||
'../backend/cli-statusline-config.mjs',
|
'../backend/cli-statusline-config.mjs',
|
||||||
|
|||||||
@@ -936,16 +936,21 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou
|
|||||||
const scannerUrl = new URL('../backend/local-scanner.mjs', import.meta.url).href;
|
const scannerUrl = new URL('../backend/local-scanner.mjs', import.meta.url).href;
|
||||||
const configUrl = new URL('../backend/config.mjs', import.meta.url).href;
|
const configUrl = new URL('../backend/config.mjs', import.meta.url).href;
|
||||||
const script = `
|
const script = `
|
||||||
import { readFileSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import { enumerateAndSyncConversations } from ${JSON.stringify(scannerUrl)};
|
import { enumerateAndSyncConversations } from ${JSON.stringify(scannerUrl)};
|
||||||
import { CACHE_FILE, flushTrajectoryCacheNow, getCachedTrajectory } from ${JSON.stringify(configUrl)};
|
import { CACHE_FILE, TRAJECTORY_DB_FILE, flushTrajectoryCacheNow, getCachedTrajectory } from ${JSON.stringify(configUrl)};
|
||||||
|
const { DatabaseSync } = process.getBuiltinModule('node:sqlite');
|
||||||
await enumerateAndSyncConversations({ summariesObj: {}, requestedConvId: '' });
|
await enumerateAndSyncConversations({ summariesObj: {}, requestedConvId: '' });
|
||||||
const entry = getCachedTrajectory(${JSON.stringify(cid)});
|
const entry = getCachedTrajectory(${JSON.stringify(cid)});
|
||||||
flushTrajectoryCacheNow();
|
flushTrajectoryCacheNow();
|
||||||
const onDisk = JSON.parse(readFileSync(CACHE_FILE, 'utf8'));
|
const db = new DatabaseSync(TRAJECTORY_DB_FILE, { readOnly: true });
|
||||||
|
const row = db.prepare('SELECT meta_json FROM conversations WHERE lower_id = ?').get(${JSON.stringify(cid.toLowerCase())});
|
||||||
|
db.close();
|
||||||
|
const onDiskMeta = row?.meta_json ? JSON.parse(row.meta_json) : {};
|
||||||
console.log(JSON.stringify({
|
console.log(JSON.stringify({
|
||||||
memSig: entry?.signature || '',
|
memSig: entry?.signature || '',
|
||||||
diskSig: onDisk[${JSON.stringify(cid)}]?.signature || '',
|
diskSig: onDiskMeta?.signature || '',
|
||||||
|
migratedBakExists: existsSync(CACHE_FILE + '.bak'),
|
||||||
stepCount: entry?.steps?.length || 0,
|
stepCount: entry?.steps?.length || 0,
|
||||||
firstInput: entry?.steps?.[0]?.inputTokens || 0,
|
firstInput: entry?.steps?.[0]?.inputTokens || 0,
|
||||||
}));
|
}));
|
||||||
@@ -961,6 +966,7 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const out = JSON.parse(stdout.trim().split('\n').pop());
|
const out = JSON.parse(stdout.trim().split('\n').pop());
|
||||||
|
assert.equal(out.migratedBakExists, true, 'legacy JSON cache automatically migrated and archived to .bak');
|
||||||
assert.equal(out.stepCount, 1, 'cached sentinel step preserved (SQLite was NOT re-read)');
|
assert.equal(out.stepCount, 1, 'cached sentinel step preserved (SQLite was NOT re-read)');
|
||||||
assert.equal(out.firstInput, 1234, 'cached usage preserved intact');
|
assert.equal(out.firstInput, 1234, 'cached usage preserved intact');
|
||||||
assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`);
|
assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`);
|
||||||
|
|||||||
@@ -0,0 +1,511 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { isDeepStrictEqual, promisify } from 'node:util';
|
||||||
|
import { MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
|
||||||
|
import { createTrajectoryCacheStore } from '../backend/trajectory-cache-store.mjs';
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
function loadJsonHelper(filePath, fallback = null) {
|
||||||
|
try {
|
||||||
|
if (!existsSync(filePath)) return fallback;
|
||||||
|
return JSON.parse(readFileSync(filePath, 'utf8'));
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeRichStep(stepIndex, overrides = {}) {
|
||||||
|
const baseMs = Date.parse('2026-11-20T08:00:00Z') + stepIndex * 5_000;
|
||||||
|
return {
|
||||||
|
stepIndex,
|
||||||
|
isCompactionStep: false,
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M429',
|
||||||
|
modelSource: 'generatorMetadata.chatModel.model',
|
||||||
|
responseModel: 'gemini-4-carbon-high',
|
||||||
|
modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
||||||
|
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
createdAt: new Date(baseMs).toISOString(),
|
||||||
|
createdAtMs: baseMs,
|
||||||
|
hasVisibleText: true,
|
||||||
|
hasToolCalls: false,
|
||||||
|
inputTokens: 10_000 + stepIndex * 100,
|
||||||
|
cacheReadTokens: 40_000,
|
||||||
|
outputTokens: 600,
|
||||||
|
thinkingTokens: 200,
|
||||||
|
responseTokens: 400,
|
||||||
|
estimatedContextTokens: 50_600,
|
||||||
|
maxContextBudgetTokens: 1_000_000,
|
||||||
|
reportedContextLimitTokens: 1_000_000,
|
||||||
|
contextBreakdown: {
|
||||||
|
totalTokens: 50_600,
|
||||||
|
messagesTokens: 32_000,
|
||||||
|
userInputTokens: 8_000,
|
||||||
|
assistantTokens: 14_000,
|
||||||
|
toolResultsTokens: 10_000,
|
||||||
|
subagentTokens: 0,
|
||||||
|
checkpointTokens: 0,
|
||||||
|
systemToolsTokens: 9_600,
|
||||||
|
mcpToolsTokens: 2_000,
|
||||||
|
skillsTokens: 3_000,
|
||||||
|
systemPromptTokens: 3_000,
|
||||||
|
userRulesTokens: 1_000,
|
||||||
|
},
|
||||||
|
measurementVersion: 4,
|
||||||
|
isComplete: true,
|
||||||
|
nativeTtftSec: 1.5,
|
||||||
|
nativeStreamSec: 4.5,
|
||||||
|
viewableDelaySec: 1.6,
|
||||||
|
ttftSec: 1.5,
|
||||||
|
ttftSource: 'generator_metadata',
|
||||||
|
thinkingDurationSec: 1.2,
|
||||||
|
totalDurationSec: 6.0,
|
||||||
|
totalTokPerSec: 100,
|
||||||
|
speedBasis: 'request_total',
|
||||||
|
speedSampleEligible: true,
|
||||||
|
speedReason: null,
|
||||||
|
turnIndex: 1,
|
||||||
|
isTurnStart: stepIndex === 1,
|
||||||
|
turnPrompt: `Prompt for step ${stepIndex}`,
|
||||||
|
turnPromptClean: `Prompt for step ${stepIndex}`,
|
||||||
|
turnHasMedia: false,
|
||||||
|
turnMediaOnly: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeVarint(val) {
|
||||||
|
let v = BigInt(val);
|
||||||
|
if (v < 0n) v = BigInt.asUintN(64, v);
|
||||||
|
const out = [];
|
||||||
|
while (v >= 0x80n) {
|
||||||
|
out.push(Number((v & 0x7fn) | 0x80n));
|
||||||
|
v >>= 7n;
|
||||||
|
}
|
||||||
|
out.push(Number(v));
|
||||||
|
return Buffer.from(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeFieldVarint(fieldNo, val) {
|
||||||
|
return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeFieldBytes(fieldNo, bufOrStr) {
|
||||||
|
const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8');
|
||||||
|
return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeTimestamp(sec) {
|
||||||
|
return encodeFieldBytes(1, Buffer.concat([encodeFieldVarint(1, sec)])).subarray(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeStepMeta({ createdSec, finishedSec, stepIndex, originCid, inputTokens, outputTokens }) {
|
||||||
|
const ts = (sec) => encodeFieldBytes(1, Buffer.concat([encodeFieldVarint(1, sec)])).subarray(2);
|
||||||
|
const mu = Buffer.concat([
|
||||||
|
encodeFieldVarint(1, 1429), // MODEL_PLACEHOLDER_M429 (Carbon High)
|
||||||
|
encodeFieldVarint(2, inputTokens),
|
||||||
|
encodeFieldVarint(3, outputTokens),
|
||||||
|
encodeFieldVarint(6, 24),
|
||||||
|
]);
|
||||||
|
return Buffer.concat([
|
||||||
|
encodeFieldBytes(1, ts(createdSec)),
|
||||||
|
encodeFieldBytes(7, ts(finishedSec)),
|
||||||
|
encodeFieldBytes(9, mu),
|
||||||
|
encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, stepIndex), encodeFieldBytes(4, originCid)])),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('SQLite ledger automatically migrates legacy trajectory_usage_cache.json to .sqlite, archives .bak, and preserves lossless details & anomalies', (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-mig-'));
|
||||||
|
t.after(() => {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const legacyJson = join(tmp, 'trajectory_usage_cache.json');
|
||||||
|
const sqliteFile = join(tmp, 'trajectory_store.sqlite');
|
||||||
|
const mainCid = 'aaaaaaaa-1111-4111-8111-111111111111';
|
||||||
|
const subCid = 'bbbbbbbb-2222-4222-8222-222222222222';
|
||||||
|
|
||||||
|
const step1 = makeRichStep(1, {
|
||||||
|
accountName: 'alice@example.com',
|
||||||
|
anomaly: {
|
||||||
|
count: 2,
|
||||||
|
severity: 'warn',
|
||||||
|
primaryKind: 'rate_limit',
|
||||||
|
totalDelaySec: 8.5,
|
||||||
|
kinds: { rate_limit: 2 },
|
||||||
|
},
|
||||||
|
anomalySig: 'rl:2',
|
||||||
|
});
|
||||||
|
const cpStep = makeRichStep(2, {
|
||||||
|
isCompactionStep: true,
|
||||||
|
modelKey: undefined,
|
||||||
|
responseModel: '',
|
||||||
|
modelDisplayName: '',
|
||||||
|
contextBreakdown: null,
|
||||||
|
inputTokens: 5_000,
|
||||||
|
cacheReadTokens: 0,
|
||||||
|
outputTokens: 300,
|
||||||
|
thinkingTokens: 0,
|
||||||
|
responseTokens: 300,
|
||||||
|
});
|
||||||
|
delete cpStep.modelKey;
|
||||||
|
|
||||||
|
writeFileSync(
|
||||||
|
legacyJson,
|
||||||
|
JSON.stringify({
|
||||||
|
[mainCid.toUpperCase()]: {
|
||||||
|
title: 'Legacy Migrated Root',
|
||||||
|
signature: 'v10-model-identity:sqlite:1::100:200|0:0',
|
||||||
|
accountName: 'bob@example.com',
|
||||||
|
workspaceUri: 'file:///f:/demo/project',
|
||||||
|
subagentRefs: [{ cascadeId: subCid, role: 'Researcher', typeName: 'research', spawnOrder: 0 }],
|
||||||
|
steps: [step1, cpStep],
|
||||||
|
},
|
||||||
|
[subCid]: {
|
||||||
|
title: 'Researcher',
|
||||||
|
parentConversationId: mainCid,
|
||||||
|
rootConversationId: mainCid,
|
||||||
|
subagentSpec: { typeName: 'research', role: 'Researcher' },
|
||||||
|
steps: [makeRichStep(1, { inputTokens: 2_000, outputTokens: 100 })],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
|
||||||
|
const store = createTrajectoryCacheStore({
|
||||||
|
cacheFilePath: legacyJson,
|
||||||
|
sqliteFilePath: sqliteFile,
|
||||||
|
enableSqlite: true,
|
||||||
|
loadJsonFn: loadJsonHelper,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Cold startup list reads slim accounting entries without hydrating detail_json
|
||||||
|
const entries = store.listCachedTrajectoryEntries();
|
||||||
|
assert.equal(entries.length, 2);
|
||||||
|
assert.equal(existsSync(sqliteFile), true);
|
||||||
|
assert.equal(existsSync(legacyJson), false, 'legacy JSON moved out of active path');
|
||||||
|
assert.equal(existsSync(`${legacyJson}.bak`), true, 'legacy JSON safely archived to .bak');
|
||||||
|
|
||||||
|
// Cold entry omits heavy contextBreakdown/turnPrompt, retains anomaly/accountName/inferred compaction model!
|
||||||
|
assert.equal(store.isConversationCold(mainCid), true);
|
||||||
|
const coldMain = store.getCachedTrajectoryEntryByLower(mainCid)?.entry;
|
||||||
|
assert.ok(coldMain);
|
||||||
|
assert.equal(coldMain.steps.length, 2);
|
||||||
|
assert.equal(coldMain.steps[0].contextBreakdown, undefined, 'cold step omits heavy contextBreakdown');
|
||||||
|
assert.equal(coldMain.steps[0].turnPrompt, undefined, 'cold step omits heavy turnPrompt');
|
||||||
|
assert.deepEqual(coldMain.steps[0].anomaly, step1.anomaly, 'cold step preserves anomaly for model ranking');
|
||||||
|
assert.equal(coldMain.steps[0].accountName, 'alice@example.com');
|
||||||
|
assert.equal(coldMain.steps[1].modelKey, 'MODEL_PLACEHOLDER_M429', 'compaction step inferred model during migration');
|
||||||
|
|
||||||
|
// Explicit hydration restores 100% lossless step details
|
||||||
|
const hydratedMain = store.getHydratedTrajectoryEntryByLower(mainCid)?.entry;
|
||||||
|
assert.equal(store.isConversationCold(mainCid), false);
|
||||||
|
assert.deepEqual(hydratedMain.steps[0].contextBreakdown, step1.contextBreakdown);
|
||||||
|
assert.equal(hydratedMain.steps[0].turnPrompt, 'Prompt for step 1');
|
||||||
|
assert.equal(hydratedMain.steps[0].reportedContextLimitTokens, 1_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Hot 24-session LRU evicts cold detail memory, never thrashes during full-list scans, and re-hydrates on demand', (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-lru-'));
|
||||||
|
t.after(() => {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const sqliteFile = join(tmp, 'trajectory_store.sqlite');
|
||||||
|
const store = createTrajectoryCacheStore({
|
||||||
|
sqliteFilePath: sqliteFile,
|
||||||
|
enableSqlite: true,
|
||||||
|
hotSessionLimit: 24,
|
||||||
|
});
|
||||||
|
|
||||||
|
const originalStep0 = makeRichStep(1, {
|
||||||
|
turnPrompt: 'Deep historical architecture prompt #0',
|
||||||
|
anomaly: { count: 1, severity: 'danger', primaryKind: 'timeout', totalDelaySec: 30, kinds: { timeout: 1 } },
|
||||||
|
});
|
||||||
|
|
||||||
|
for (let i = 0; i < 32; i += 1) {
|
||||||
|
const cid = `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`;
|
||||||
|
store.setCachedTrajectory(cid, {
|
||||||
|
title: `Session #${i}`,
|
||||||
|
signature: `v10-model-identity:sqlite:1::${i}`,
|
||||||
|
wasRunning: false,
|
||||||
|
contextGroupsTelemetry: 3,
|
||||||
|
turnRailTelemetry: true,
|
||||||
|
anomalyTelemetry: 1,
|
||||||
|
steps: [i === 0 ? originalStep0 : makeRichStep(1, { turnPrompt: `Prompt #${i}` })],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Before flush, dirty unflushed sessions MUST NOT drop detail_json prematurely!
|
||||||
|
const cid0 = '00000000-0000-4000-8000-000000000000';
|
||||||
|
assert.ok(store.getCachedTrajectory(cid0).steps[0].contextBreakdown, 'dirty unflushed session retains detail');
|
||||||
|
|
||||||
|
// Flush writes all 32 to SQLite, then trims hot LRU down to 24!
|
||||||
|
assert.equal(store.flushTrajectoryCacheNow(), true);
|
||||||
|
assert.equal(store.getHotSessionCount(), 24);
|
||||||
|
assert.equal(store.isConversationCold(cid0), true, 'oldest session #0 evicted to cold slim mode');
|
||||||
|
assert.equal(store.getCachedTrajectory(cid0).steps[0].contextBreakdown, undefined);
|
||||||
|
assert.deepEqual(store.getCachedTrajectory(cid0).steps[0].anomaly, originalStep0.anomaly);
|
||||||
|
|
||||||
|
// Iterating all 32 conversations via getCachedTrajectory / listCachedTrajectoryEntries MUST NOT hydrate cold sessions!
|
||||||
|
for (const [cid] of store.listCachedTrajectoryEntries()) {
|
||||||
|
const e = store.getCachedTrajectory(cid);
|
||||||
|
assert.equal(e.steps.length, 1);
|
||||||
|
}
|
||||||
|
assert.equal(store.isConversationCold(cid0), true, 'scan loop caused zero cold SQLite reads');
|
||||||
|
assert.equal(store.getHotSessionCount(), 24);
|
||||||
|
|
||||||
|
// Explicit hydration of cold session #0 restores exact original step and evicts #8
|
||||||
|
const hydrated0 = store.getHydratedTrajectory(cid0);
|
||||||
|
assert.equal(store.isConversationCold(cid0), false);
|
||||||
|
assert.equal(store.getHotSessionCount(), 24);
|
||||||
|
assert.equal(isDeepStrictEqual(hydrated0.steps[0], originalStep0), true);
|
||||||
|
assert.equal(store.isConversationCold('00000000-0000-4000-8000-000000000008'), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Step-level O(delta) UPSERT, conversation undo tail truncation, and cross-process WAL sync keep zero file locks', (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { DatabaseSync } = sqliteMod;
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-wal-'));
|
||||||
|
t.after(() => {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const sqliteFile = join(tmp, 'trajectory_store.sqlite');
|
||||||
|
const storeWriter = createTrajectoryCacheStore({ sqliteFilePath: sqliteFile, enableSqlite: true });
|
||||||
|
const storeReader = createTrajectoryCacheStore({ sqliteFilePath: sqliteFile, enableSqlite: true });
|
||||||
|
|
||||||
|
const cid = 'cccccccc-3333-4333-8333-333333333333';
|
||||||
|
const s1 = makeRichStep(1, { inputTokens: 1_000 });
|
||||||
|
const s2 = makeRichStep(2, { inputTokens: 2_000 });
|
||||||
|
const s3 = makeRichStep(3, { inputTokens: 3_000 });
|
||||||
|
storeWriter.setCachedTrajectory(cid, {
|
||||||
|
title: 'Incremental Session',
|
||||||
|
signature: 'sig-3',
|
||||||
|
steps: [s1, s2, s3],
|
||||||
|
});
|
||||||
|
storeWriter.flushTrajectoryCacheNow();
|
||||||
|
|
||||||
|
// Reader hydrates initial 3 steps
|
||||||
|
assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 3);
|
||||||
|
|
||||||
|
// Append step #4: verify SQLite now has 4 rows and Reader picks up incremental write_seq update
|
||||||
|
const s4 = makeRichStep(4, { inputTokens: 4_000 });
|
||||||
|
storeWriter.setCachedTrajectory(cid, {
|
||||||
|
title: 'Incremental Session',
|
||||||
|
signature: 'sig-4',
|
||||||
|
steps: [s1, s2, s3, s4],
|
||||||
|
});
|
||||||
|
storeWriter.flushTrajectoryCacheNow();
|
||||||
|
|
||||||
|
storeReader.syncExternalChangesNow();
|
||||||
|
assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 4);
|
||||||
|
assert.equal(storeReader.getCachedTrajectory(cid).steps[3].inputTokens, 4_000);
|
||||||
|
|
||||||
|
// Simulate Undo in Antigravity: steps shrink from 4 back to 2 -> pos 2 & 3 MUST be deleted from SQLite!
|
||||||
|
storeWriter.setCachedTrajectory(cid, {
|
||||||
|
title: 'Incremental Session (Undone)',
|
||||||
|
signature: 'sig-2',
|
||||||
|
steps: [s1, s2],
|
||||||
|
});
|
||||||
|
storeWriter.flushTrajectoryCacheNow();
|
||||||
|
|
||||||
|
const dbCheck = new DatabaseSync(sqliteFile, { readOnly: true });
|
||||||
|
const stepRowCount = dbCheck
|
||||||
|
.prepare('SELECT COUNT(*) AS cnt FROM steps WHERE cascade_id = ?')
|
||||||
|
.get(cid).cnt;
|
||||||
|
dbCheck.close();
|
||||||
|
assert.equal(stepRowCount, 2, 'undone tail steps pos >= 2 truncated cleanly');
|
||||||
|
|
||||||
|
storeReader.syncExternalChangesNow();
|
||||||
|
assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 2);
|
||||||
|
|
||||||
|
// Simulate clearCache on Writer (with cid live -> cleared): Reader syncs epoch bump and removes cid!
|
||||||
|
storeWriter.clearCache({ liveCascadeIds: [cid] });
|
||||||
|
storeReader.syncExternalChangesNow();
|
||||||
|
assert.equal(storeReader.getCachedTrajectory(cid), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Deleting source conversation in Antigravity + clicking Rebuild Cache permanently preserves deleted conversation tokens, costs, and details', async (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { DatabaseSync } = sqliteMod;
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-perm-'));
|
||||||
|
t.after(() => {
|
||||||
|
try {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// Ignore Windows WAL cleanup race
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const geminiDir = join(tmp, 'gemini');
|
||||||
|
const agyDir = join(geminiDir, 'antigravity');
|
||||||
|
const convDir = join(agyDir, 'conversations');
|
||||||
|
const dataDir = join(tmp, 'panel-data');
|
||||||
|
mkdirSync(convDir, { recursive: true });
|
||||||
|
mkdirSync(dataDir, { recursive: true });
|
||||||
|
|
||||||
|
const cidDeleted = 'dddddddd-4444-4444-8444-444444444444';
|
||||||
|
const cidLive = 'eeeeeeee-5555-4555-8555-555555555555';
|
||||||
|
const baseSec = Math.floor(Date.parse('2026-11-18T00:00:00Z') / 1000);
|
||||||
|
|
||||||
|
// Create conversation_summaries.db and both .db files
|
||||||
|
const sumDbPath = join(agyDir, 'conversation_summaries.db');
|
||||||
|
const sumDb = new DatabaseSync(sumDbPath);
|
||||||
|
sumDb.exec(`
|
||||||
|
CREATE TABLE conversation_summaries (
|
||||||
|
conversation_id TEXT PRIMARY KEY,
|
||||||
|
title TEXT,
|
||||||
|
preview TEXT,
|
||||||
|
status TEXT,
|
||||||
|
source TEXT,
|
||||||
|
parent_conversation_id TEXT,
|
||||||
|
nesting_depth INTEGER,
|
||||||
|
agent_name TEXT,
|
||||||
|
not_fully_idle INTEGER,
|
||||||
|
killed INTEGER,
|
||||||
|
step_count INTEGER,
|
||||||
|
last_modified_time TEXT,
|
||||||
|
app_data_dir TEXT,
|
||||||
|
raw_summary BLOB
|
||||||
|
);
|
||||||
|
CREATE TABLE conversation_parents (conversation_id TEXT, parent_id TEXT);
|
||||||
|
`);
|
||||||
|
const insSum = sumDb.prepare(
|
||||||
|
"INSERT INTO conversation_summaries (conversation_id, title, status, parent_conversation_id, step_count, last_modified_time, app_data_dir, raw_summary) VALUES (?, ?, 'CASCADE_RUN_STATUS_IDLE', '', 2, '2026-11-18T00:01:00Z', 'antigravity', ?)"
|
||||||
|
);
|
||||||
|
insSum.run(cidDeleted, 'Deleted Precious Ledger Task', Buffer.alloc(0));
|
||||||
|
insSum.run(cidLive, 'Surviving Live Task', Buffer.alloc(0));
|
||||||
|
sumDb.close();
|
||||||
|
|
||||||
|
const createConvSqlite = (cid, promptText, inTok, outTok) => {
|
||||||
|
const p = join(convDir, `${cid}.db`);
|
||||||
|
const db = new DatabaseSync(p);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||||
|
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||||
|
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||||
|
`);
|
||||||
|
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||||
|
db.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)').run(
|
||||||
|
Buffer.concat([
|
||||||
|
encodeFieldBytes(1, encodeTimestamp(baseSec + 1)),
|
||||||
|
encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, 0), encodeFieldBytes(4, cid)])),
|
||||||
|
]),
|
||||||
|
encodeFieldBytes(19, encodeFieldBytes(2, promptText))
|
||||||
|
);
|
||||||
|
db.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)').run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 10,
|
||||||
|
finishedSec: baseSec + 15,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCid: cid,
|
||||||
|
inputTokens: inTok,
|
||||||
|
outputTokens: outTok,
|
||||||
|
}),
|
||||||
|
encodeFieldBytes(20, encodeFieldBytes(1, 'Completed task'))
|
||||||
|
);
|
||||||
|
db.close();
|
||||||
|
return p;
|
||||||
|
};
|
||||||
|
|
||||||
|
const deletedDbFile = createConvSqlite(cidDeleted, 'Keep my billing forever', 100_000, 10_000);
|
||||||
|
const liveDbFile = createConvSqlite(cidLive, 'Still working on this', 50_000, 5_000);
|
||||||
|
|
||||||
|
const apiUrl = new URL('../backend/api-actions.mjs', import.meta.url).href;
|
||||||
|
const telUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href;
|
||||||
|
const cfgUrl = new URL('../backend/config.mjs', import.meta.url).href;
|
||||||
|
|
||||||
|
const script = `
|
||||||
|
import { unlinkSync } from 'node:fs';
|
||||||
|
import { executeRebuildCacheAction } from ${JSON.stringify(apiUrl)};
|
||||||
|
import { buildTelemetryPayloadInternal } from ${JSON.stringify(telUrl)};
|
||||||
|
import { flushTrajectoryCacheNow, getCachedTrajectory, getHydratedTrajectory } from ${JSON.stringify(cfgUrl)};
|
||||||
|
const { DatabaseSync } = process.getBuiltinModule('node:sqlite');
|
||||||
|
|
||||||
|
// 1. Initial scan records both conversations in trajectory_store.sqlite
|
||||||
|
const before = await buildTelemetryPayloadInternal(${JSON.stringify(cidLive)}, { range: 'all' });
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
const totalTokensBefore = before.consumption.account.totalTokens;
|
||||||
|
|
||||||
|
// 2. Delete cidDeleted completely from Antigravity (.db + summary row), and add a step to cidLive!
|
||||||
|
unlinkSync(${JSON.stringify(deletedDbFile)});
|
||||||
|
const sdb = new DatabaseSync(${JSON.stringify(sumDbPath)});
|
||||||
|
sdb.prepare('DELETE FROM conversation_summaries WHERE conversation_id = ?').run(${JSON.stringify(cidDeleted)});
|
||||||
|
sdb.close();
|
||||||
|
|
||||||
|
// 3. Click Rebuild Cache TWICE in a row!
|
||||||
|
const r1 = executeRebuildCacheAction();
|
||||||
|
const r2 = executeRebuildCacheAction();
|
||||||
|
|
||||||
|
// 4. Rebuild telemetry & inspect both cidLive and deleted cidDeleted
|
||||||
|
const afterLive = await buildTelemetryPayloadInternal(${JSON.stringify(cidLive)}, { range: 'all' });
|
||||||
|
const afterDeleted = await buildTelemetryPayloadInternal(${JSON.stringify(cidDeleted)}, { range: 'all' });
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
|
||||||
|
const cachedDeleted = getCachedTrajectory(${JSON.stringify(cidDeleted)});
|
||||||
|
const hydratedDeleted = getHydratedTrajectory(${JSON.stringify(cidDeleted)});
|
||||||
|
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
r1Ok: r1.ok,
|
||||||
|
r2Ok: r2.ok,
|
||||||
|
totalTokensBefore,
|
||||||
|
totalTokensAfter: afterLive.consumption.account.totalTokens,
|
||||||
|
deletedArchivedFlag: Boolean(cachedDeleted?.archived),
|
||||||
|
deletedStepCount: hydratedDeleted?.steps?.length || 0,
|
||||||
|
deletedTurnPrompt: hydratedDeleted?.steps?.[0]?.turnPrompt || '',
|
||||||
|
deletedViewSteps: afterDeleted.activeConversation?.recentSteps?.length || 0,
|
||||||
|
}));
|
||||||
|
`;
|
||||||
|
|
||||||
|
const { stdout } = await execFileAsync(process.execPath, ['--input-type=module', '-e', script], {
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
ANTIGRAVITY_GEMINI_DIR: geminiDir,
|
||||||
|
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||||
|
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||||
|
ANTIGRAVITY_EXECUTABLE_DATA_DIR: dataDir,
|
||||||
|
ANTIGRAVITY_LS_ADDRESS: 'test.invalid',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const out = JSON.parse(stdout.trim().split('\n').pop());
|
||||||
|
assert.equal(out.r1Ok, true);
|
||||||
|
assert.equal(out.r2Ok, true);
|
||||||
|
// 100k + 10k (cidDeleted) + 50k + 5k (cidLive) = 165,000 tokens -> 100% preserved after deleting cidDeleted + 2x Rebuild Cache!
|
||||||
|
assert.equal(out.totalTokensBefore, 165_000);
|
||||||
|
assert.equal(out.totalTokensAfter, 165_000, 'deleted conversation tokens & cost permanently preserved');
|
||||||
|
assert.equal(out.deletedArchivedFlag, true, 'deleted conversation marked archived');
|
||||||
|
assert.equal(out.deletedStepCount, 1);
|
||||||
|
assert.equal(out.deletedTurnPrompt, 'Keep my billing forever', 'deleted conversation detail_json preserved');
|
||||||
|
assert.equal(out.deletedViewSteps, 1, 'clicking archived deleted conversation still renders step details');
|
||||||
|
assert.equal(existsSync(liveDbFile), true);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user