omp-fabric 1.26.14 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +0 -27
- package/dist/agents/handoff.d.ts +2 -3
- package/dist/agents/handoff.d.ts.map +1 -1
- package/dist/agents/manager.d.ts.map +1 -1
- package/dist/agents/types.d.ts +0 -7
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/chunks/{chunk-5EZWERJY.js → chunk-2BOZMRT5.js} +25 -8
- package/dist/chunks/{chunk-5EZWERJY.js.map → chunk-2BOZMRT5.js.map} +3 -3
- package/dist/chunks/{chunk-TF3MK3TH.js → chunk-4PQDZ3AY.js} +13 -13
- package/dist/chunks/{chunk-5U6HKMJV.js → chunk-4XLJPEI4.js} +3 -5
- package/dist/chunks/{chunk-5U6HKMJV.js.map → chunk-4XLJPEI4.js.map} +1 -1
- package/dist/chunks/{chunk-O5SZML2M.js → chunk-5MH37C4Y.js} +14 -7
- package/dist/chunks/chunk-5MH37C4Y.js.map +7 -0
- package/dist/chunks/{chunk-YWEXP724.js → chunk-7OZDA7YP.js} +5 -5
- package/dist/chunks/{chunk-673LUJCK.js → chunk-7QKSPNXQ.js} +7 -7
- package/dist/chunks/{chunk-PTYCFQEH.js → chunk-ABFK2RPI.js} +2 -2
- package/dist/chunks/{chunk-S3URDR4K.js → chunk-ANHZ3SWB.js} +8 -9
- package/dist/chunks/chunk-ANHZ3SWB.js.map +7 -0
- package/dist/chunks/{chunk-YLMDFMXM.js → chunk-BQ2U44IL.js} +2 -2
- package/dist/chunks/{chunk-RGE6MBYP.js → chunk-CNCRWY4Q.js} +27 -69
- package/dist/chunks/chunk-CNCRWY4Q.js.map +7 -0
- package/dist/chunks/{chunk-HWOL2YVU.js → chunk-CT23CX67.js} +48 -7
- package/dist/chunks/chunk-CT23CX67.js.map +7 -0
- package/dist/chunks/{chunk-3QPIB3H2.js → chunk-EV36BIIO.js} +8 -690
- package/dist/chunks/chunk-EV36BIIO.js.map +7 -0
- package/dist/chunks/{chunk-CA2P7NLW.js → chunk-FA7TNLOV.js} +2 -88
- package/dist/chunks/chunk-FA7TNLOV.js.map +7 -0
- package/dist/chunks/{chunk-BV3EDWSX.js → chunk-FVGI5PSL.js} +4 -1
- package/dist/chunks/chunk-FVGI5PSL.js.map +7 -0
- package/dist/chunks/{chunk-6IPXBDCA.js → chunk-FWFET65L.js} +211 -4
- package/dist/chunks/chunk-FWFET65L.js.map +7 -0
- package/dist/chunks/{chunk-ESPCTYVX.js → chunk-IPI4UOTC.js} +352 -1
- package/dist/chunks/chunk-IPI4UOTC.js.map +7 -0
- package/dist/chunks/{chunk-HCUDF34P.js → chunk-K7IN6FTM.js} +17 -17
- package/dist/chunks/chunk-K7IN6FTM.js.map +7 -0
- package/dist/commands/fabric.d.ts.map +1 -1
- package/dist/compaction/branch-details.d.ts +3 -9
- package/dist/compaction/branch-details.d.ts.map +1 -1
- package/dist/compaction/instructions.d.ts +4 -29
- package/dist/compaction/instructions.d.ts.map +1 -1
- package/dist/compaction/trace-events.d.ts +1 -1
- package/dist/compaction/trace-events.d.ts.map +1 -1
- package/dist/config-migrations.d.ts +1 -1
- package/dist/config-migrations.d.ts.map +1 -1
- package/dist/config.d.ts +0 -18
- package/dist/config.d.ts.map +1 -1
- package/dist/core/action-registry.d.ts.map +1 -1
- package/dist/core/action-registry.js +3 -3
- package/dist/core/action-repair.d.ts +1 -0
- package/dist/core/action-repair.d.ts.map +1 -1
- package/dist/core/compact-controller.d.ts +0 -7
- package/dist/core/compact-controller.d.ts.map +1 -1
- package/dist/entropy/index.js +6 -7
- package/dist/execution-service.d.ts.map +1 -1
- package/dist/fabric-runtime-state.d.ts +0 -64
- package/dist/fabric-runtime-state.d.ts.map +1 -1
- package/dist/fabric-runtime-state.js +260 -141
- package/dist/fabric-runtime-state.js.map +4 -4
- package/dist/fabric-state.d.ts +0 -3
- package/dist/fabric-state.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +131 -247
- package/dist/index.js.map +3 -3
- package/dist/memory/discovery.js +2 -3
- package/dist/memory/normalize.js +1 -2
- package/dist/memory/search.js +2 -3
- package/dist/providers/agents-actions.d.ts.map +1 -1
- package/dist/providers/agents-provider.d.ts.map +1 -1
- package/dist/providers/compact-provider.d.ts.map +1 -1
- package/dist/providers/image-provider.d.ts +1 -0
- package/dist/providers/image-provider.d.ts.map +1 -1
- package/dist/providers/memory-provider.d.ts +0 -11
- package/dist/providers/memory-provider.d.ts.map +1 -1
- package/dist/providers/memory-provider.js +4 -7
- package/dist/residency/host.js +6 -14
- package/dist/residency/omp-entry.js +6 -14
- package/dist/residency/omp-entry.js.map +1 -1
- package/dist/runtime/core-override-guest-types.js +1 -1
- package/dist/runtime/guest-types.d.ts +1 -1
- package/dist/runtime/guest-types.d.ts.map +1 -1
- package/dist/runtime/guest-types.js +1 -1
- package/dist/runtime/node-process-runtime.js +8 -8
- package/dist/runtime/quickjs-runtime.d.ts +1 -1
- package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
- package/dist/runtime/quickjs-runtime.js +2 -2
- package/dist/runtime/type-checker.js +1 -1
- package/dist/type-error-guidance.d.ts.map +1 -1
- package/dist/ui/controller.d.ts +0 -1
- package/dist/ui/controller.d.ts.map +1 -1
- package/dist/ui/conversation.js +5 -5
- package/dist/ui/dashboard.d.ts.map +1 -1
- package/dist/ui/dashboard.js +13 -18
- package/dist/ui/dashboard.js.map +2 -2
- package/dist/ui/settings.d.ts.map +1 -1
- package/dist/ui/settings.js +9 -203
- package/dist/ui/settings.js.map +2 -2
- package/docs/agents.md +1 -3
- package/docs/audit-trace.md +3 -3
- package/docs/configuration.md +14 -6
- package/docs/entropy.md +1 -2
- package/docs/image.md +24 -3
- package/docs/interface.md +0 -35
- package/docs/memory-recall.md +6 -11
- package/docs/programmatic-compaction.md +14 -32
- package/package.json +8 -11
- package/dist/chunks/chunk-3J7BKUNG.js +0 -354
- package/dist/chunks/chunk-3J7BKUNG.js.map +0 -7
- package/dist/chunks/chunk-3QPIB3H2.js.map +0 -7
- package/dist/chunks/chunk-6IPXBDCA.js.map +0 -7
- package/dist/chunks/chunk-BV3EDWSX.js.map +0 -7
- package/dist/chunks/chunk-CA2P7NLW.js.map +0 -7
- package/dist/chunks/chunk-ESPCTYVX.js.map +0 -7
- package/dist/chunks/chunk-G3VKU6GZ.js +0 -1681
- package/dist/chunks/chunk-G3VKU6GZ.js.map +0 -7
- package/dist/chunks/chunk-HCUDF34P.js.map +0 -7
- package/dist/chunks/chunk-HWOL2YVU.js.map +0 -7
- package/dist/chunks/chunk-JL3KVPFJ.js +0 -291
- package/dist/chunks/chunk-JL3KVPFJ.js.map +0 -7
- package/dist/chunks/chunk-O5SZML2M.js.map +0 -7
- package/dist/chunks/chunk-QD2B5FUE.js +0 -15
- package/dist/chunks/chunk-QD2B5FUE.js.map +0 -7
- package/dist/chunks/chunk-QSRTEINF.js +0 -469
- package/dist/chunks/chunk-QSRTEINF.js.map +0 -7
- package/dist/chunks/chunk-QZJB7QTM.js +0 -248
- package/dist/chunks/chunk-QZJB7QTM.js.map +0 -7
- package/dist/chunks/chunk-RGE6MBYP.js.map +0 -7
- package/dist/chunks/chunk-S3URDR4K.js.map +0 -7
- package/dist/chunks/chunk-SMNOQLKU.js +0 -53
- package/dist/chunks/chunk-SMNOQLKU.js.map +0 -7
- package/dist/chunks/chunk-TQQPXV3I.js +0 -58
- package/dist/chunks/chunk-TQQPXV3I.js.map +0 -7
- package/dist/chunks/chunk-UAP6IQIR.js +0 -76
- package/dist/chunks/chunk-UAP6IQIR.js.map +0 -7
- package/dist/chunks/chunk-VE3FWDRH.js +0 -221
- package/dist/chunks/chunk-VE3FWDRH.js.map +0 -7
- package/dist/chunks/chunk-ZHDN5ESL.js +0 -130
- package/dist/chunks/chunk-ZHDN5ESL.js.map +0 -7
- package/dist/compaction/bounds.d.ts +0 -25
- package/dist/compaction/bounds.d.ts.map +0 -1
- package/dist/compaction/branch-summary.d.ts +0 -9
- package/dist/compaction/branch-summary.d.ts.map +0 -1
- package/dist/compaction/enrichers.d.ts +0 -10
- package/dist/compaction/enrichers.d.ts.map +0 -1
- package/dist/compaction/hook.d.ts +0 -117
- package/dist/compaction/hook.d.ts.map +0 -1
- package/dist/compaction/hook.js +0 -21
- package/dist/compaction/hook.js.map +0 -7
- package/dist/compaction/lcm-addresses.d.ts +0 -10
- package/dist/compaction/lcm-addresses.d.ts.map +0 -1
- package/dist/compaction/lcm-doctor.d.ts +0 -60
- package/dist/compaction/lcm-doctor.d.ts.map +0 -1
- package/dist/compaction/lcm-loader.d.ts +0 -12
- package/dist/compaction/lcm-loader.d.ts.map +0 -1
- package/dist/compaction/lcm-maintenance.d.ts +0 -152
- package/dist/compaction/lcm-maintenance.d.ts.map +0 -1
- package/dist/compaction/lcm-model.d.ts +0 -44
- package/dist/compaction/lcm-model.d.ts.map +0 -1
- package/dist/compaction/lcm-recovery.d.ts +0 -7
- package/dist/compaction/lcm-recovery.d.ts.map +0 -1
- package/dist/compaction/lcm-runtime.d.ts +0 -233
- package/dist/compaction/lcm-runtime.d.ts.map +0 -1
- package/dist/compaction/lcm-runtime.js +0 -2863
- package/dist/compaction/lcm-runtime.js.map +0 -7
- package/dist/compaction/lcm-status.d.ts +0 -5
- package/dist/compaction/lcm-status.d.ts.map +0 -1
- package/dist/compaction/normalize.d.ts +0 -83
- package/dist/compaction/normalize.d.ts.map +0 -1
- package/dist/compaction/projections.d.ts +0 -26
- package/dist/compaction/projections.d.ts.map +0 -1
- package/dist/compaction/render.d.ts +0 -11
- package/dist/compaction/render.d.ts.map +0 -1
- package/dist/core/event-loop-slice.d.ts +0 -11
- package/dist/core/event-loop-slice.d.ts.map +0 -1
- package/dist/memory/lcm-adapter.d.ts +0 -111
- package/dist/memory/lcm-adapter.d.ts.map +0 -1
- package/dist/storage/lcm-directory.d.ts +0 -17
- package/dist/storage/lcm-directory.d.ts.map +0 -1
- package/dist/storage/lcm-identity.d.ts +0 -48
- package/dist/storage/lcm-identity.d.ts.map +0 -1
- package/dist/storage/lcm-ledger.d.ts +0 -159
- package/dist/storage/lcm-ledger.d.ts.map +0 -1
- package/dist/storage/lcm-migration.d.ts +0 -87
- package/dist/storage/lcm-migration.d.ts.map +0 -1
- package/dist/storage/lcm-offthread.d.ts +0 -9
- package/dist/storage/lcm-offthread.d.ts.map +0 -1
- package/dist/storage/sqlite.d.ts +0 -19
- package/dist/storage/sqlite.d.ts.map +0 -1
- package/dist/ui/frame.d.ts +0 -7
- package/dist/ui/frame.d.ts.map +0 -1
- package/dist/ui/lcm-dashboard.d.ts +0 -43
- package/dist/ui/lcm-dashboard.d.ts.map +0 -1
- package/dist/ui/lcm-dashboard.js +0 -395
- package/dist/ui/lcm-dashboard.js.map +0 -7
- package/dist/ui/lcm-panel.d.ts +0 -37
- package/dist/ui/lcm-panel.d.ts.map +0 -1
- package/dist/ui/lcm-panel.js +0 -23
- package/dist/ui/lcm-panel.js.map +0 -7
- package/docs/adr/0001-lcm-durable-context-ledger.md +0 -6
- package/docs/certification.md +0 -134
- package/docs/compaction.md +0 -188
- /package/dist/chunks/{chunk-TF3MK3TH.js.map → chunk-4PQDZ3AY.js.map} +0 -0
- /package/dist/chunks/{chunk-YWEXP724.js.map → chunk-7OZDA7YP.js.map} +0 -0
- /package/dist/chunks/{chunk-673LUJCK.js.map → chunk-7QKSPNXQ.js.map} +0 -0
- /package/dist/chunks/{chunk-PTYCFQEH.js.map → chunk-ABFK2RPI.js.map} +0 -0
- /package/dist/chunks/{chunk-YLMDFMXM.js.map → chunk-BQ2U44IL.js.map} +0 -0
|
@@ -1,2863 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
lcmChecks
|
|
3
|
-
} from "../chunks/chunk-SMNOQLKU.js";
|
|
4
|
-
import {
|
|
5
|
-
sqliteDriver
|
|
6
|
-
} from "../chunks/chunk-TQQPXV3I.js";
|
|
7
|
-
import {
|
|
8
|
-
reconcileLcmState
|
|
9
|
-
} from "../chunks/chunk-QD2B5FUE.js";
|
|
10
|
-
import {
|
|
11
|
-
sessionDirNamesForCwd,
|
|
12
|
-
sessionsDirRoot
|
|
13
|
-
} from "../chunks/chunk-YLMDFMXM.js";
|
|
14
|
-
import "../chunks/chunk-6IPXBDCA.js";
|
|
15
|
-
import {
|
|
16
|
-
DEFAULT_LCM_MAX_INPUT_CHARS,
|
|
17
|
-
LcmModelAdapter,
|
|
18
|
-
activeRequestBlock,
|
|
19
|
-
buildLcmPrompt,
|
|
20
|
-
emergencyReduce,
|
|
21
|
-
tailDigest
|
|
22
|
-
} from "../chunks/chunk-JL3KVPFJ.js";
|
|
23
|
-
import {
|
|
24
|
-
canonicalLcmEntry,
|
|
25
|
-
canonicalLcmPayload,
|
|
26
|
-
canonicalProjectIdentity,
|
|
27
|
-
defaultLedgerPath,
|
|
28
|
-
defaultLedgerRoot,
|
|
29
|
-
hash,
|
|
30
|
-
hashLcmPayload,
|
|
31
|
-
isPrunedLcmEntry,
|
|
32
|
-
lcmSummaryAddress,
|
|
33
|
-
renderLcmChildAddresses,
|
|
34
|
-
renderLcmSourceAddresses
|
|
35
|
-
} from "../chunks/chunk-ZHDN5ESL.js";
|
|
36
|
-
import {
|
|
37
|
-
writeJsonAtomic
|
|
38
|
-
} from "../chunks/chunk-KAD7UWT2.js";
|
|
39
|
-
import {
|
|
40
|
-
LCM_RECOVERY_POINTER,
|
|
41
|
-
decodeCompactionInstructions
|
|
42
|
-
} from "../chunks/chunk-QSRTEINF.js";
|
|
43
|
-
import {
|
|
44
|
-
MAX_SUMMARY_BYTES,
|
|
45
|
-
clipUtf8,
|
|
46
|
-
utf8Bytes
|
|
47
|
-
} from "../chunks/chunk-UAP6IQIR.js";
|
|
48
|
-
import "../chunks/chunk-VE3FWDRH.js";
|
|
49
|
-
import "../chunks/chunk-V7DLSDFO.js";
|
|
50
|
-
import "../chunks/chunk-6YR6XPNF.js";
|
|
51
|
-
|
|
52
|
-
// src/compaction/lcm-runtime.ts
|
|
53
|
-
import fs4 from "node:fs";
|
|
54
|
-
|
|
55
|
-
// src/storage/lcm-ledger.ts
|
|
56
|
-
import fs2 from "node:fs";
|
|
57
|
-
import path2 from "node:path";
|
|
58
|
-
import crypto from "node:crypto";
|
|
59
|
-
|
|
60
|
-
// src/storage/lcm-offthread.ts
|
|
61
|
-
import { Worker } from "node:worker_threads";
|
|
62
|
-
var WORKER_SOURCE = String.raw`
|
|
63
|
-
const { parentPort, workerData } = require("node:worker_threads");
|
|
64
|
-
const openReadOnly = (file) => {
|
|
65
|
-
try {
|
|
66
|
-
const { DatabaseSync } = require("node:sqlite");
|
|
67
|
-
return new DatabaseSync(file, { readOnly: true });
|
|
68
|
-
} catch {}
|
|
69
|
-
const { Database } = require("bun:sqlite");
|
|
70
|
-
return new Database(file, { readonly: true });
|
|
71
|
-
};
|
|
72
|
-
let db;
|
|
73
|
-
try {
|
|
74
|
-
db = openReadOnly(workerData.file);
|
|
75
|
-
} catch (error) {
|
|
76
|
-
parentPort.postMessage({ unavailable: error instanceof Error ? error.message : String(error) });
|
|
77
|
-
}
|
|
78
|
-
if (db) {
|
|
79
|
-
try {
|
|
80
|
-
if (workerData.snapshot) db.exec("BEGIN");
|
|
81
|
-
const rows = workerData.statements.map((sql) => ({ ...(db.prepare(sql).get() ?? {}) }));
|
|
82
|
-
if (workerData.snapshot) db.exec("COMMIT");
|
|
83
|
-
parentPort.postMessage({ rows });
|
|
84
|
-
} catch (error) {
|
|
85
|
-
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
|
|
86
|
-
} finally {
|
|
87
|
-
try { db.close(); } catch {}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
`;
|
|
91
|
-
var queryLedgerOffThread = (query) => new Promise((resolve, reject) => {
|
|
92
|
-
if (query.signal?.aborted) {
|
|
93
|
-
reject(new Error("ledger closed"));
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
let worker;
|
|
97
|
-
try {
|
|
98
|
-
worker = new Worker(WORKER_SOURCE, {
|
|
99
|
-
eval: true,
|
|
100
|
-
workerData: { file: query.file, statements: [...query.statements], snapshot: query.snapshot === true }
|
|
101
|
-
});
|
|
102
|
-
} catch {
|
|
103
|
-
resolve(void 0);
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
let settled = false;
|
|
107
|
-
const finish = (settle) => {
|
|
108
|
-
if (settled) return;
|
|
109
|
-
settled = true;
|
|
110
|
-
query.signal?.removeEventListener("abort", onAbort);
|
|
111
|
-
void worker.terminate();
|
|
112
|
-
settle();
|
|
113
|
-
};
|
|
114
|
-
const onAbort = () => finish(() => reject(new Error("ledger closed")));
|
|
115
|
-
query.signal?.addEventListener("abort", onAbort, { once: true });
|
|
116
|
-
worker.once("message", (message) => {
|
|
117
|
-
if (message.unavailable !== void 0) finish(() => resolve(void 0));
|
|
118
|
-
else if (message.error !== void 0) finish(() => reject(new Error(message.error)));
|
|
119
|
-
else if (Array.isArray(message.rows) && message.rows.length === query.statements.length) finish(() => resolve(message.rows));
|
|
120
|
-
else finish(() => resolve(void 0));
|
|
121
|
-
});
|
|
122
|
-
worker.once("error", () => finish(() => resolve(void 0)));
|
|
123
|
-
worker.once("exit", () => finish(() => resolve(void 0)));
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
// src/storage/lcm-directory.ts
|
|
127
|
-
import fs from "node:fs";
|
|
128
|
-
import os from "node:os";
|
|
129
|
-
import path from "node:path";
|
|
130
|
-
var DIRECTORY_FILE = "projects.json";
|
|
131
|
-
var DIRECTORY_VERSION = 1;
|
|
132
|
-
var SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
133
|
-
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
134
|
-
var TEMP_RETENTION_MS = 2 * 24 * 60 * 60 * 1e3;
|
|
135
|
-
var tempRootCandidates = () => {
|
|
136
|
-
const roots = /* @__PURE__ */ new Set();
|
|
137
|
-
for (const root of [os.tmpdir(), "/tmp", "/var/tmp"]) {
|
|
138
|
-
const resolved = path.resolve(root);
|
|
139
|
-
roots.add(resolved);
|
|
140
|
-
try {
|
|
141
|
-
roots.add(fs.realpathSync.native(resolved));
|
|
142
|
-
} catch {
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
return [...roots];
|
|
146
|
-
};
|
|
147
|
-
var isUnderTempRoot = (target) => {
|
|
148
|
-
const resolved = path.resolve(target);
|
|
149
|
-
const candidates = /* @__PURE__ */ new Set([resolved]);
|
|
150
|
-
try {
|
|
151
|
-
candidates.add(fs.realpathSync.native(resolved));
|
|
152
|
-
} catch {
|
|
153
|
-
let probe = resolved;
|
|
154
|
-
while (true) {
|
|
155
|
-
const parent = path.dirname(probe);
|
|
156
|
-
if (parent === probe) break;
|
|
157
|
-
probe = parent;
|
|
158
|
-
try {
|
|
159
|
-
const real = fs.realpathSync.native(probe);
|
|
160
|
-
candidates.add(path.join(real, path.relative(probe, resolved)));
|
|
161
|
-
break;
|
|
162
|
-
} catch {
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
|
|
167
|
-
const normalized = [...candidates].map(normalize);
|
|
168
|
-
return tempRootCandidates().some((root) => {
|
|
169
|
-
const base = normalize(root.endsWith(path.sep) ? root.slice(0, -1) : root);
|
|
170
|
-
return normalized.some((candidate) => candidate === base || candidate.startsWith(base + path.sep));
|
|
171
|
-
});
|
|
172
|
-
};
|
|
173
|
-
var empty = () => ({ version: DIRECTORY_VERSION, sweptAt: 0, projects: [] });
|
|
174
|
-
var directoryFile = (rootDir) => path.join(rootDir, DIRECTORY_FILE);
|
|
175
|
-
var read = (rootDir) => {
|
|
176
|
-
try {
|
|
177
|
-
const parsed = JSON.parse(fs.readFileSync(directoryFile(rootDir), "utf8"));
|
|
178
|
-
if (parsed.version !== DIRECTORY_VERSION || !Array.isArray(parsed.projects)) return empty();
|
|
179
|
-
return {
|
|
180
|
-
version: DIRECTORY_VERSION,
|
|
181
|
-
sweptAt: typeof parsed.sweptAt === "number" ? parsed.sweptAt : 0,
|
|
182
|
-
projects: parsed.projects.filter(
|
|
183
|
-
(record2) => typeof record2?.key === "string" && typeof record2.path === "string" && typeof record2.updatedAt === "number"
|
|
184
|
-
)
|
|
185
|
-
};
|
|
186
|
-
} catch {
|
|
187
|
-
return empty();
|
|
188
|
-
}
|
|
189
|
-
};
|
|
190
|
-
var write = (rootDir, file, owned) => {
|
|
191
|
-
try {
|
|
192
|
-
fs.mkdirSync(rootDir, { recursive: true });
|
|
193
|
-
const current = read(rootDir);
|
|
194
|
-
const merged = new Map(current.projects.map((record2) => [record2.path, record2]));
|
|
195
|
-
for (const path4 of owned) merged.delete(path4);
|
|
196
|
-
for (const record2 of file.projects) merged.set(record2.path, record2);
|
|
197
|
-
writeJsonAtomic(directoryFile(rootDir), {
|
|
198
|
-
version: DIRECTORY_VERSION,
|
|
199
|
-
sweptAt: Math.max(file.sweptAt, current.sweptAt),
|
|
200
|
-
projects: [...merged.values()]
|
|
201
|
-
});
|
|
202
|
-
} catch {
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
|
-
var ledgerFiles = (key, rootDir) => {
|
|
206
|
-
const base = defaultLedgerPath(rootDir, key);
|
|
207
|
-
return [base, `${base}-wal`, `${base}-shm`];
|
|
208
|
-
};
|
|
209
|
-
var stableProjectKey = (rootDir, identity, now = Date.now()) => {
|
|
210
|
-
const canonicalPath = identity.canonicalPath;
|
|
211
|
-
if (!canonicalPath) return identity.key;
|
|
212
|
-
const file = read(rootDir);
|
|
213
|
-
const record2 = file.projects.find((candidate) => candidate.path === canonicalPath);
|
|
214
|
-
const adopted = record2 && record2.key !== identity.key && fs.existsSync(defaultLedgerPath(rootDir, record2.key)) ? record2.key : identity.key;
|
|
215
|
-
write(rootDir, { ...file, projects: [{ key: adopted, path: canonicalPath, updatedAt: now }] }, [canonicalPath]);
|
|
216
|
-
return adopted;
|
|
217
|
-
};
|
|
218
|
-
var sweepLedgers = (rootDir, options) => {
|
|
219
|
-
const now = options.now ?? Date.now();
|
|
220
|
-
const retentionMs = options.retentionMs ?? RETENTION_MS;
|
|
221
|
-
const tempRetentionMs = options.tempRetentionMs ?? TEMP_RETENTION_MS;
|
|
222
|
-
const file = read(rootDir);
|
|
223
|
-
if (!options.force && now - file.sweptAt < SWEEP_INTERVAL_MS) return { removed: [], bytes: 0, skipped: true };
|
|
224
|
-
const removed = [];
|
|
225
|
-
let bytes = 0;
|
|
226
|
-
const kept = [];
|
|
227
|
-
for (const record2 of file.projects) {
|
|
228
|
-
const ledger = defaultLedgerPath(rootDir, record2.key);
|
|
229
|
-
let stats;
|
|
230
|
-
try {
|
|
231
|
-
stats = fs.statSync(ledger);
|
|
232
|
-
} catch {
|
|
233
|
-
if (record2.key !== options.keepKey) continue;
|
|
234
|
-
kept.push(record2);
|
|
235
|
-
continue;
|
|
236
|
-
}
|
|
237
|
-
const retention = isUnderTempRoot(record2.path) ? tempRetentionMs : retentionMs;
|
|
238
|
-
const abandoned = record2.key !== options.keepKey && !fs.existsSync(record2.path) && now - Math.max(stats.mtimeMs, record2.updatedAt) >= retention;
|
|
239
|
-
if (!abandoned) {
|
|
240
|
-
kept.push(record2);
|
|
241
|
-
continue;
|
|
242
|
-
}
|
|
243
|
-
try {
|
|
244
|
-
for (const target of ledgerFiles(record2.key, rootDir)) fs.rmSync(target, { force: true });
|
|
245
|
-
} catch {
|
|
246
|
-
kept.push(record2);
|
|
247
|
-
continue;
|
|
248
|
-
}
|
|
249
|
-
bytes += stats.size;
|
|
250
|
-
removed.push(record2.path);
|
|
251
|
-
}
|
|
252
|
-
write(rootDir, { ...file, sweptAt: now, projects: kept }, file.projects.map((record2) => record2.path));
|
|
253
|
-
return { removed, bytes, skipped: false };
|
|
254
|
-
};
|
|
255
|
-
|
|
256
|
-
// src/storage/lcm-ledger.ts
|
|
257
|
-
var LCM_LEDGER_WARNING_BYTES = 8 * 1024 ** 3;
|
|
258
|
-
var LCM_LEDGER_MAINTENANCE_BYTES = 10 * 1024 ** 3;
|
|
259
|
-
var rowFilter = (options, alias = "") => {
|
|
260
|
-
const column = (name) => alias ? `${alias}.${name}` : name;
|
|
261
|
-
const clauses = [];
|
|
262
|
-
const params = [];
|
|
263
|
-
const list = (values, operator) => {
|
|
264
|
-
if (!values || values.length === 0) return;
|
|
265
|
-
clauses.push(`${column("role")} ${operator} (${values.map(() => "?").join(",")})`);
|
|
266
|
-
params.push(...values);
|
|
267
|
-
};
|
|
268
|
-
list(options.roles, "IN");
|
|
269
|
-
list(options.excludeRoles, "NOT IN");
|
|
270
|
-
if (options.since !== void 0) {
|
|
271
|
-
clauses.push(`${column("created_at")}>=?`);
|
|
272
|
-
params.push(options.since);
|
|
273
|
-
}
|
|
274
|
-
if (options.until !== void 0) {
|
|
275
|
-
clauses.push(`${column("created_at")}<=?`);
|
|
276
|
-
params.push(options.until);
|
|
277
|
-
}
|
|
278
|
-
return { sql: clauses.map((clause) => ` AND ${clause}`).join(""), params };
|
|
279
|
-
};
|
|
280
|
-
var validSearchFilter = (options) => [options.roles, options.excludeRoles].every((values) => values === void 0 || Array.isArray(values) && values.every((value) => typeof value === "string" && value.length > 0)) && [options.since, options.until].every((value) => value === void 0 || Number.isFinite(value));
|
|
281
|
-
var LEDGER_SCHEMA_VERSION = 4;
|
|
282
|
-
var BACKUP_MANIFEST_VERSION = 3;
|
|
283
|
-
var DELETE_MANIFEST_VERSION = 2;
|
|
284
|
-
var PROJECT_KEYED_TABLES = ["projects", "project_aliases", "sessions", "raw_entries", "summary_nodes", "summary_node_revisions", "frontiers", "maintenance_jobs", "maintenance_usage", "repair_ladder"];
|
|
285
|
-
var LCM_SEARCH_SCAN_LIMIT = 5e3;
|
|
286
|
-
var LCM_SCAN_BATCH = 500;
|
|
287
|
-
var SCHEMA = `
|
|
288
|
-
CREATE TABLE IF NOT EXISTS schema_metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
289
|
-
CREATE TABLE IF NOT EXISTS projects (project_key TEXT PRIMARY KEY, identity_json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
290
|
-
CREATE TABLE IF NOT EXISTS project_aliases (alias TEXT PRIMARY KEY, project_key TEXT NOT NULL REFERENCES projects(project_key));
|
|
291
|
-
CREATE TABLE IF NOT EXISTS sessions (project_key TEXT NOT NULL, session_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(project_key, session_id));
|
|
292
|
-
CREATE TABLE IF NOT EXISTS raw_entries (project_key TEXT NOT NULL, session_id TEXT NOT NULL, entry_id TEXT NOT NULL, revision INTEGER NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, content_hash TEXT NOT NULL, payload_json TEXT NOT NULL, parent_entry_id TEXT, branch TEXT, created_at INTEGER NOT NULL, PRIMARY KEY(project_key, session_id, entry_id, revision), UNIQUE(project_key, session_id, entry_id, content_hash));
|
|
293
|
-
CREATE TABLE IF NOT EXISTS summary_nodes (node_id TEXT PRIMARY KEY, project_key TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
294
|
-
CREATE TABLE IF NOT EXISTS summary_node_revisions (node_id TEXT NOT NULL REFERENCES summary_nodes(node_id), revision INTEGER NOT NULL, project_key TEXT NOT NULL, text TEXT NOT NULL, model_hash TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(node_id, revision));
|
|
295
|
-
CREATE TABLE IF NOT EXISTS summary_edges (parent_id TEXT NOT NULL REFERENCES summary_nodes(node_id), child_id TEXT NOT NULL REFERENCES summary_nodes(node_id), PRIMARY KEY(parent_id, child_id));
|
|
296
|
-
CREATE TABLE IF NOT EXISTS frontiers (project_key TEXT NOT NULL, frontier_id TEXT NOT NULL, node_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(project_key, frontier_id, node_id));
|
|
297
|
-
CREATE TABLE IF NOT EXISTS maintenance_jobs (job_id TEXT PRIMARY KEY, project_key TEXT NOT NULL, status TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
298
|
-
CREATE TABLE IF NOT EXISTS maintenance_usage (project_key TEXT NOT NULL, day TEXT NOT NULL, session_id TEXT NOT NULL, calls INTEGER NOT NULL, input_tokens INTEGER NOT NULL, output_tokens INTEGER NOT NULL, cost REAL NOT NULL, wall_ms INTEGER NOT NULL, PRIMARY KEY(project_key,day,session_id));
|
|
299
|
-
CREATE TABLE IF NOT EXISTS repair_ladder (project_key TEXT NOT NULL, fault TEXT NOT NULL, attempts INTEGER NOT NULL, next_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, detail TEXT NOT NULL, PRIMARY KEY(project_key, fault));
|
|
300
|
-
CREATE TABLE IF NOT EXISTS orphaned_rows (migration_version INTEGER NOT NULL, table_name TEXT NOT NULL, row_json TEXT NOT NULL, detected_at INTEGER NOT NULL);
|
|
301
|
-
CREATE INDEX IF NOT EXISTS raw_entries_lookup ON raw_entries(project_key, session_id, entry_id, revision);
|
|
302
|
-
DROP INDEX IF EXISTS raw_entries_recent;
|
|
303
|
-
CREATE INDEX IF NOT EXISTS raw_entries_session_order ON raw_entries(project_key, session_id, created_at, revision);
|
|
304
|
-
CREATE INDEX IF NOT EXISTS summary_nodes_order ON summary_nodes(project_key, created_at, node_id);
|
|
305
|
-
CREATE INDEX IF NOT EXISTS maintenance_jobs_status ON maintenance_jobs(project_key, status);
|
|
306
|
-
CREATE INDEX IF NOT EXISTS summary_edges_child ON summary_edges(child_id, parent_id);
|
|
307
|
-
`;
|
|
308
|
-
var fileHash = (file) => crypto.createHash("sha256").update(fs2.readFileSync(file)).digest("hex");
|
|
309
|
-
var snapshotHash = (db) => {
|
|
310
|
-
const digest = crypto.createHash("sha256");
|
|
311
|
-
for (const [table, order] of [["schema_metadata", "key"], ["projects", "project_key"], ["project_aliases", "alias"], ["sessions", "project_key,session_id"], ["raw_entries", "project_key,session_id,entry_id,revision"], ["summary_nodes", "node_id"], ["summary_edges", "parent_id,child_id"], ["frontiers", "project_key,frontier_id,node_id"], ["maintenance_jobs", "job_id"], ["maintenance_usage", "project_key,day,session_id"], ["repair_ladder", "project_key,fault"], ["orphaned_rows", "migration_version,table_name,row_json"]]) {
|
|
312
|
-
digest.update(`${table}\0`);
|
|
313
|
-
for (const row of db.prepare(`SELECT * FROM ${table} ORDER BY ${order}`).all()) digest.update(`${JSON.stringify(row)}\0`);
|
|
314
|
-
}
|
|
315
|
-
return digest.digest("hex");
|
|
316
|
-
};
|
|
317
|
-
var toRawEntry = (row) => ({ projectKey: row.project_key, sessionId: row.session_id, entryId: row.entry_id, revision: Number(row.revision), role: row.role, content: row.content, contentHash: row.content_hash, payloadHash: row.content_hash, payloadJson: row.payload_json, parentEntryId: row.parent_entry_id, branch: row.branch, createdAt: row.created_at });
|
|
318
|
-
var toRawEntries = (rows) => rows.map(toRawEntry);
|
|
319
|
-
var probeFts5 = (db) => {
|
|
320
|
-
try {
|
|
321
|
-
db.exec("CREATE VIRTUAL TABLE temp.lcm_fts5_probe USING fts5(probe); DROP TABLE temp.lcm_fts5_probe;");
|
|
322
|
-
return true;
|
|
323
|
-
} catch {
|
|
324
|
-
try {
|
|
325
|
-
db.exec("DROP TABLE IF EXISTS temp.lcm_fts5_probe");
|
|
326
|
-
} catch {
|
|
327
|
-
}
|
|
328
|
-
return false;
|
|
329
|
-
}
|
|
330
|
-
};
|
|
331
|
-
var foldToken = (value) => value.normalize("NFD").replace(new RegExp("\\p{M}+", "gu"), "").toLowerCase();
|
|
332
|
-
var tokenize = (value) => value.split(/[^\p{L}\p{N}]+/u).map(foldToken).filter((token2) => token2.length > 0);
|
|
333
|
-
var searchPhrases = (query, mode) => (mode === "phrase" ? [query] : query.split(/\s+/)).map(tokenize).filter((phrase) => phrase.length > 0);
|
|
334
|
-
var ftsExpression = (phrases, match) => phrases.map((phrase) => `"${phrase.join(" ")}"`).join(match === "all" ? " AND " : " OR ");
|
|
335
|
-
var containsPhrase = (tokens, phrase) => {
|
|
336
|
-
for (let start = 0; start + phrase.length <= tokens.length; start++) {
|
|
337
|
-
let hit = true;
|
|
338
|
-
for (let offset = 0; offset < phrase.length; offset++) if (tokens[start + offset] !== phrase[offset]) {
|
|
339
|
-
hit = false;
|
|
340
|
-
break;
|
|
341
|
-
}
|
|
342
|
-
if (hit) return true;
|
|
343
|
-
}
|
|
344
|
-
return false;
|
|
345
|
-
};
|
|
346
|
-
var phrasePredicate = (phrases, match) => match === "all" ? (content) => {
|
|
347
|
-
const tokens = tokenize(content);
|
|
348
|
-
return phrases.every((phrase) => containsPhrase(tokens, phrase));
|
|
349
|
-
} : (content) => {
|
|
350
|
-
const tokens = tokenize(content);
|
|
351
|
-
return phrases.some((phrase) => containsPhrase(tokens, phrase));
|
|
352
|
-
};
|
|
353
|
-
var LedgerDegradedError = class extends Error {
|
|
354
|
-
constructor(message, cause) {
|
|
355
|
-
super(message);
|
|
356
|
-
this.cause = cause;
|
|
357
|
-
this.name = "LedgerDegradedError";
|
|
358
|
-
}
|
|
359
|
-
};
|
|
360
|
-
var LcmLedger = class {
|
|
361
|
-
db;
|
|
362
|
-
project;
|
|
363
|
-
degraded = false;
|
|
364
|
-
dbPath;
|
|
365
|
-
now;
|
|
366
|
-
warningBytes;
|
|
367
|
-
maintenanceBytes;
|
|
368
|
-
writeChain = Promise.resolve();
|
|
369
|
-
transactionDepth = 0;
|
|
370
|
-
closed = false;
|
|
371
|
-
fts = false;
|
|
372
|
-
startupChecksRun = false;
|
|
373
|
-
startupChecksPending;
|
|
374
|
-
closing = new AbortController();
|
|
375
|
-
migrations = [];
|
|
376
|
-
constructor(options = {}) {
|
|
377
|
-
this.now = options.now ?? Date.now;
|
|
378
|
-
this.warningBytes = options.warningBytes ?? LCM_LEDGER_WARNING_BYTES;
|
|
379
|
-
this.maintenanceBytes = options.maintenanceBytes ?? LCM_LEDGER_MAINTENANCE_BYTES;
|
|
380
|
-
if (!Number.isSafeInteger(this.warningBytes) || !Number.isSafeInteger(this.maintenanceBytes) || this.warningBytes < 0 || this.maintenanceBytes < this.warningBytes) {
|
|
381
|
-
throw new Error("invalid ledger size thresholds");
|
|
382
|
-
}
|
|
383
|
-
const identity = canonicalProjectIdentity(options.project ?? { liveCwd: process.cwd() });
|
|
384
|
-
const adopted = options.projectKey ?? (options.dbPath ? identity.key : stableProjectKey(options.rootDir ?? defaultLedgerRoot(), identity, this.now()));
|
|
385
|
-
this.project = adopted === identity.key ? identity : { ...identity, key: adopted };
|
|
386
|
-
const dbPath = options.dbPath ?? defaultLedgerPath(options.rootDir, this.project.key);
|
|
387
|
-
fs2.mkdirSync(path2.dirname(dbPath), { recursive: true });
|
|
388
|
-
this.dbPath = dbPath;
|
|
389
|
-
this.db = new (sqliteDriver())(dbPath);
|
|
390
|
-
try {
|
|
391
|
-
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; PRAGMA wal_autocheckpoint=1000;");
|
|
392
|
-
this.db.exec("BEGIN IMMEDIATE;" + SCHEMA + "COMMIT;");
|
|
393
|
-
const columns = this.db.prepare("PRAGMA table_info(raw_entries)").all();
|
|
394
|
-
if (!columns.some((column) => column.name === "payload_json")) {
|
|
395
|
-
if (Number(this.db.prepare("SELECT count(*) n FROM raw_entries").get().n)) throw new Error("raw payloads missing; reimport authoritative session entries");
|
|
396
|
-
this.db.exec("ALTER TABLE raw_entries ADD COLUMN payload_json TEXT NOT NULL DEFAULT ''");
|
|
397
|
-
}
|
|
398
|
-
this.fts = probeFts5(this.db);
|
|
399
|
-
this.ensureFtsObjects();
|
|
400
|
-
this.db.exec("PRAGMA foreign_keys=ON");
|
|
401
|
-
this.registerProject(this.project);
|
|
402
|
-
} catch (error) {
|
|
403
|
-
this.degraded = true;
|
|
404
|
-
throw new LedgerDegradedError("ledger startup failed", error);
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
get startupChecksComplete() {
|
|
408
|
-
return this.startupChecksRun;
|
|
409
|
-
}
|
|
410
|
-
/** Whole-file scans run on a worker thread so a multi-gigabyte ledger never stalls the host event loop. */
|
|
411
|
-
runStartupChecks() {
|
|
412
|
-
if (this.startupChecksRun) return Promise.resolve();
|
|
413
|
-
this.startupChecksPending ??= this.checkStartup().finally(() => {
|
|
414
|
-
this.startupChecksPending = void 0;
|
|
415
|
-
});
|
|
416
|
-
return this.startupChecksPending;
|
|
417
|
-
}
|
|
418
|
-
async checkStartup() {
|
|
419
|
-
try {
|
|
420
|
-
await this.migrateSchema();
|
|
421
|
-
const [result] = await this.scan(["PRAGMA integrity_check"]);
|
|
422
|
-
if (result?.integrity_check !== "ok") throw new Error(String(result?.integrity_check));
|
|
423
|
-
} catch (error) {
|
|
424
|
-
this.degraded = true;
|
|
425
|
-
throw new LedgerDegradedError("ledger startup checks failed", error);
|
|
426
|
-
}
|
|
427
|
-
this.startupChecksRun = true;
|
|
428
|
-
}
|
|
429
|
-
async scan(statements, snapshot = false) {
|
|
430
|
-
const offThread = await queryLedgerOffThread({ file: this.dbPath, statements, snapshot, signal: this.closing.signal });
|
|
431
|
-
if (offThread) return offThread;
|
|
432
|
-
this.guard();
|
|
433
|
-
if (snapshot && this.transactionDepth === 0) this.db.exec("BEGIN");
|
|
434
|
-
try {
|
|
435
|
-
return statements.map((sql) => ({ ...this.db.prepare(sql).get() ?? {} }));
|
|
436
|
-
} finally {
|
|
437
|
-
if (snapshot && this.transactionDepth === 0) this.db.exec("COMMIT");
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
readRepairLadder(projectKey = this.project.key) {
|
|
441
|
-
return this.readOnly((db) => new Map(db.prepare("SELECT fault,attempts,next_at,detail,updated_at FROM repair_ladder WHERE project_key=?").all(projectKey).map((row) => [row.fault, { attempts: Number(row.attempts), nextAt: Number(row.next_at), detail: row.detail, updatedAt: Number(row.updated_at) }])));
|
|
442
|
-
}
|
|
443
|
-
writeRepairLadder(fault, attempts, nextAt, detail) {
|
|
444
|
-
this.transaction((db) => db.prepare("INSERT INTO repair_ladder(project_key,fault,attempts,next_at,updated_at,detail) VALUES(?,?,?,?,?,?) ON CONFLICT(project_key,fault) DO UPDATE SET attempts=excluded.attempts,next_at=excluded.next_at,updated_at=excluded.updated_at,detail=excluded.detail").run(this.project.key, fault, attempts, nextAt, this.now(), detail));
|
|
445
|
-
}
|
|
446
|
-
clearRepairLadder(fault) {
|
|
447
|
-
this.transaction((db) => db.prepare("DELETE FROM repair_ladder WHERE project_key=? AND fault=?").run(this.project.key, fault));
|
|
448
|
-
}
|
|
449
|
-
get isDegraded() {
|
|
450
|
-
return this.degraded;
|
|
451
|
-
}
|
|
452
|
-
get file() {
|
|
453
|
-
return this.dbPath;
|
|
454
|
-
}
|
|
455
|
-
get bytes() {
|
|
456
|
-
try {
|
|
457
|
-
return fs2.statSync(this.dbPath).size;
|
|
458
|
-
} catch {
|
|
459
|
-
return 0;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
get operationalState() {
|
|
463
|
-
if (this.degraded) return "degraded";
|
|
464
|
-
try {
|
|
465
|
-
const size = fs2.statSync(this.dbPath).size;
|
|
466
|
-
if (size >= this.maintenanceBytes) return "maintenance";
|
|
467
|
-
if (size >= this.warningBytes) return "warning";
|
|
468
|
-
} catch {
|
|
469
|
-
}
|
|
470
|
-
return "healthy";
|
|
471
|
-
}
|
|
472
|
-
markDegraded(error) {
|
|
473
|
-
this.degraded = true;
|
|
474
|
-
return new LedgerDegradedError("ledger is degraded", error);
|
|
475
|
-
}
|
|
476
|
-
registerProject(identity) {
|
|
477
|
-
const now = this.now();
|
|
478
|
-
this.db.prepare("INSERT INTO projects(project_key,identity_json,created_at,updated_at) VALUES(?,?,?,?) ON CONFLICT(project_key) DO UPDATE SET identity_json=excluded.identity_json,updated_at=excluded.updated_at").run(identity.key, JSON.stringify(identity), now, now);
|
|
479
|
-
for (const alias of identity.aliases) {
|
|
480
|
-
const existing = this.db.prepare("SELECT project_key FROM project_aliases WHERE alias=?").get(alias);
|
|
481
|
-
if (existing && existing.project_key !== identity.key) throw new LedgerDegradedError(`ambiguous project alias: ${alias}`);
|
|
482
|
-
this.db.prepare("INSERT OR IGNORE INTO project_aliases(alias,project_key) VALUES(?,?)").run(alias, identity.key);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
get ftsAvailable() {
|
|
486
|
-
return this.fts;
|
|
487
|
-
}
|
|
488
|
-
schemaVersion() {
|
|
489
|
-
const row = this.db.prepare("SELECT value FROM schema_metadata WHERE key='version'").get();
|
|
490
|
-
const version = Number(row?.value ?? 0);
|
|
491
|
-
return Number.isSafeInteger(version) && version > 0 ? version : 0;
|
|
492
|
-
}
|
|
493
|
-
hasObject(type, name) {
|
|
494
|
-
return this.db.prepare("SELECT 1 FROM sqlite_master WHERE type=? AND name=?").get(type, name) !== void 0;
|
|
495
|
-
}
|
|
496
|
-
async indexOutOfStep() {
|
|
497
|
-
if (this.fts !== this.hasObject("table", "raw_entries_fts")) return true;
|
|
498
|
-
if (!this.fts) return false;
|
|
499
|
-
if (!this.hasObject("trigger", "raw_entries_fts_insert")) return true;
|
|
500
|
-
const [indexed, stored] = await this.scan(["SELECT count(*) n FROM raw_entries_fts", "SELECT count(*) n FROM raw_entries"], true);
|
|
501
|
-
return Number(indexed?.n) !== Number(stored?.n);
|
|
502
|
-
}
|
|
503
|
-
async migrateSchema() {
|
|
504
|
-
const version = this.schemaVersion();
|
|
505
|
-
if (version < 2 || await this.indexOutOfStep()) this.migrations.push(this.migrateFullTextIndex());
|
|
506
|
-
if (version < 3 || this.db.prepare("PRAGMA foreign_key_list(summary_edges)").all().length === 0) this.migrations.push(this.migrateDerivedForeignKeys());
|
|
507
|
-
if (version !== LEDGER_SCHEMA_VERSION) this.db.prepare("INSERT INTO schema_metadata(key,value) VALUES('version',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(String(LEDGER_SCHEMA_VERSION));
|
|
508
|
-
}
|
|
509
|
-
ensureFtsObjects() {
|
|
510
|
-
if (!this.fts) return;
|
|
511
|
-
this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS raw_entries_fts USING fts5(content, project_key UNINDEXED, session_id UNINDEXED, entry_id UNINDEXED, revision UNINDEXED)");
|
|
512
|
-
this.db.exec("CREATE TRIGGER IF NOT EXISTS raw_entries_fts_insert AFTER INSERT ON raw_entries BEGIN INSERT INTO raw_entries_fts(content,project_key,session_id,entry_id,revision) VALUES(new.content,new.project_key,new.session_id,new.entry_id,new.revision); END");
|
|
513
|
-
}
|
|
514
|
-
migrateFullTextIndex() {
|
|
515
|
-
if (!this.fts) {
|
|
516
|
-
this.db.exec("DROP TRIGGER IF EXISTS raw_entries_fts_insert");
|
|
517
|
-
return { version: 2, name: "raw-entries-fts", applied: false, reason: "sqlite driver has no fts5 module", counts: { indexed: 0 } };
|
|
518
|
-
}
|
|
519
|
-
let indexed = 0;
|
|
520
|
-
this.transaction((db) => {
|
|
521
|
-
this.ensureFtsObjects();
|
|
522
|
-
indexed = Number(db.prepare("SELECT count(*) n FROM raw_entries").get().n);
|
|
523
|
-
if (Number(db.prepare("SELECT count(*) n FROM raw_entries_fts").get().n) === indexed) return;
|
|
524
|
-
db.exec("DELETE FROM raw_entries_fts");
|
|
525
|
-
db.exec("INSERT INTO raw_entries_fts(content,project_key,session_id,entry_id,revision) SELECT content,project_key,session_id,entry_id,revision FROM raw_entries");
|
|
526
|
-
});
|
|
527
|
-
return { version: 2, name: "raw-entries-fts", applied: true, counts: { indexed } };
|
|
528
|
-
}
|
|
529
|
-
migrateDerivedForeignKeys() {
|
|
530
|
-
const counts = { summary_edges: 0, summary_node_revisions: 0 };
|
|
531
|
-
this.transaction((db) => {
|
|
532
|
-
const detectedAt = this.now();
|
|
533
|
-
const known = "(SELECT node_id FROM summary_nodes)";
|
|
534
|
-
const quarantine = (table, orphaned) => {
|
|
535
|
-
const rows = db.prepare(`SELECT * FROM ${table} WHERE ${orphaned}`).all();
|
|
536
|
-
for (const row of rows) db.prepare("INSERT INTO orphaned_rows(migration_version,table_name,row_json,detected_at) VALUES(?,?,?,?)").run(LEDGER_SCHEMA_VERSION, table, JSON.stringify(row), detectedAt);
|
|
537
|
-
counts[table] = rows.length;
|
|
538
|
-
};
|
|
539
|
-
quarantine("summary_edges", `parent_id NOT IN ${known} OR child_id NOT IN ${known}`);
|
|
540
|
-
db.exec(`CREATE TABLE summary_edges_next (parent_id TEXT NOT NULL REFERENCES summary_nodes(node_id), child_id TEXT NOT NULL REFERENCES summary_nodes(node_id), PRIMARY KEY(parent_id, child_id));
|
|
541
|
-
INSERT INTO summary_edges_next(parent_id,child_id) SELECT parent_id,child_id FROM summary_edges WHERE parent_id IN ${known} AND child_id IN ${known};
|
|
542
|
-
DROP TABLE summary_edges;
|
|
543
|
-
ALTER TABLE summary_edges_next RENAME TO summary_edges;`);
|
|
544
|
-
quarantine("summary_node_revisions", `node_id NOT IN ${known}`);
|
|
545
|
-
db.exec(`CREATE TABLE summary_node_revisions_next (node_id TEXT NOT NULL REFERENCES summary_nodes(node_id), revision INTEGER NOT NULL, project_key TEXT NOT NULL, text TEXT NOT NULL, model_hash TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(node_id, revision));
|
|
546
|
-
INSERT INTO summary_node_revisions_next(node_id,revision,project_key,text,model_hash,created_at) SELECT node_id,revision,project_key,text,model_hash,created_at FROM summary_node_revisions WHERE node_id IN ${known};
|
|
547
|
-
DROP TABLE summary_node_revisions;
|
|
548
|
-
ALTER TABLE summary_node_revisions_next RENAME TO summary_node_revisions;`);
|
|
549
|
-
});
|
|
550
|
-
return { version: 3, name: "derived-foreign-keys", applied: true, counts };
|
|
551
|
-
}
|
|
552
|
-
guard() {
|
|
553
|
-
if (this.degraded) throw new LedgerDegradedError("ledger is degraded");
|
|
554
|
-
}
|
|
555
|
-
assertProjectKey(projectKey) {
|
|
556
|
-
if (projectKey !== this.project.key) throw new Error("project key does not match ledger project");
|
|
557
|
-
}
|
|
558
|
-
async serialize(operation) {
|
|
559
|
-
const previous = this.writeChain;
|
|
560
|
-
let release;
|
|
561
|
-
this.writeChain = new Promise((resolve) => {
|
|
562
|
-
release = resolve;
|
|
563
|
-
});
|
|
564
|
-
await previous;
|
|
565
|
-
try {
|
|
566
|
-
this.guard();
|
|
567
|
-
return operation();
|
|
568
|
-
} finally {
|
|
569
|
-
release();
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
appendRaw(entry) {
|
|
573
|
-
this.guard();
|
|
574
|
-
if (entry.projectKey !== this.project.key) throw new Error("entry project does not match ledger project");
|
|
575
|
-
if (entry.entryId.trim().length === 0) throw new Error("entry ID is required");
|
|
576
|
-
if (typeof entry.payloadJson !== "string" || !entry.payloadJson.trim()) throw new Error("full payload JSON is required");
|
|
577
|
-
let payload;
|
|
578
|
-
try {
|
|
579
|
-
payload = JSON.parse(entry.payloadJson);
|
|
580
|
-
} catch {
|
|
581
|
-
throw new Error("invalid payload JSON");
|
|
582
|
-
}
|
|
583
|
-
if (!payload || typeof payload !== "object" || typeof payload.type !== "string" || typeof payload.id !== "string" || payload.id !== entry.entryId) throw new Error("payload must be a full SessionEntry");
|
|
584
|
-
const payloadJson = canonicalLcmEntry(payload);
|
|
585
|
-
const contentHash = hash(payloadJson);
|
|
586
|
-
const ownsTransaction = this.transactionDepth === 0;
|
|
587
|
-
if (ownsTransaction) this.db.exec("BEGIN IMMEDIATE");
|
|
588
|
-
try {
|
|
589
|
-
const existing = this.db.prepare("SELECT revision,created_at FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? AND content_hash=?").get(entry.projectKey, entry.sessionId, entry.entryId, contentHash);
|
|
590
|
-
if (existing) {
|
|
591
|
-
if (ownsTransaction) this.db.exec("COMMIT");
|
|
592
|
-
return { ...entry, payloadJson, payloadHash: contentHash, revision: existing.revision, contentHash, createdAt: existing.created_at };
|
|
593
|
-
}
|
|
594
|
-
const prior = this.priorRevision(entry.projectKey, entry.sessionId, entry.entryId, contentHash, isPrunedLcmEntry(payload));
|
|
595
|
-
if (prior) {
|
|
596
|
-
if (ownsTransaction) this.db.exec("COMMIT");
|
|
597
|
-
return prior;
|
|
598
|
-
}
|
|
599
|
-
const latest = this.db.prepare("SELECT COALESCE(MAX(revision),0) revision FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=?").get(entry.projectKey, entry.sessionId, entry.entryId);
|
|
600
|
-
const revision = latest.revision + 1;
|
|
601
|
-
const createdAt = entry.createdAt ?? this.now();
|
|
602
|
-
this.db.prepare("INSERT OR IGNORE INTO sessions(project_key,session_id,created_at) VALUES(?,?,?)").run(entry.projectKey, entry.sessionId, createdAt);
|
|
603
|
-
this.db.prepare("INSERT INTO raw_entries(project_key,session_id,entry_id,revision,role,content,content_hash,payload_json,parent_entry_id,branch,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)").run(entry.projectKey, entry.sessionId, entry.entryId, revision, entry.role, entry.content, contentHash, payloadJson, entry.parentEntryId ?? null, entry.branch ?? null, createdAt);
|
|
604
|
-
if (ownsTransaction) this.db.exec("COMMIT");
|
|
605
|
-
return { ...entry, payloadJson, payloadHash: contentHash, revision, contentHash, createdAt };
|
|
606
|
-
} catch (error) {
|
|
607
|
-
if (ownsTransaction) this.db.exec("ROLLBACK");
|
|
608
|
-
const code = error.code;
|
|
609
|
-
if (code === "ENOSPC" || code === "SQLITE_FULL" || String(error).includes("database or disk is full")) this.degraded = true;
|
|
610
|
-
throw new LedgerDegradedError("ledger write failed", error);
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
identities = /* @__PURE__ */ new Map();
|
|
614
|
-
/** A stored revision the host only rewrote (pruned, re-signed, blob-externalized) stays the entry's source. */
|
|
615
|
-
priorRevision(projectKey, sessionId, entryId, identity, pruned) {
|
|
616
|
-
const rows = this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? ORDER BY revision DESC").all(projectKey, sessionId, entryId);
|
|
617
|
-
if (rows.length === 0) return void 0;
|
|
618
|
-
if (pruned) return toRawEntry(rows[0]);
|
|
619
|
-
const match = rows.find((row) => this.identityOf(row) === identity);
|
|
620
|
-
return match ? toRawEntry(match) : void 0;
|
|
621
|
-
}
|
|
622
|
-
identityOf(row) {
|
|
623
|
-
const stored = row.content_hash;
|
|
624
|
-
const cached = this.identities.get(stored);
|
|
625
|
-
if (cached !== void 0) return cached;
|
|
626
|
-
let identity = stored;
|
|
627
|
-
try {
|
|
628
|
-
identity = hash(canonicalLcmEntry(JSON.parse(row.payload_json)));
|
|
629
|
-
} catch {
|
|
630
|
-
}
|
|
631
|
-
if (this.identities.size >= 5e4) this.identities.clear();
|
|
632
|
-
this.identities.set(stored, identity);
|
|
633
|
-
return identity;
|
|
634
|
-
}
|
|
635
|
-
readRaw(projectKey = this.project.key, sessionId) {
|
|
636
|
-
this.guard();
|
|
637
|
-
this.assertProjectKey(projectKey);
|
|
638
|
-
const rows = sessionId ? this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? AND session_id=? ORDER BY created_at,revision,rowid").all(projectKey, sessionId) : this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? ORDER BY created_at,session_id,entry_id,revision").all(projectKey);
|
|
639
|
-
return toRawEntries(rows);
|
|
640
|
-
}
|
|
641
|
-
/** The same rows in the same order as readRaw for one session, read in keyset pages that yield between batches. */
|
|
642
|
-
async readSessionRaw(sessionId, slice) {
|
|
643
|
-
const entries = [];
|
|
644
|
-
let cursor;
|
|
645
|
-
for (; ; ) {
|
|
646
|
-
this.guard();
|
|
647
|
-
const rows = cursor ? this.db.prepare("SELECT rowid AS lcm_rowid,* FROM raw_entries WHERE project_key=? AND session_id=? AND (created_at,revision,rowid)>(?,?,?) ORDER BY created_at,revision,rowid LIMIT ?").all(this.project.key, sessionId, cursor.createdAt, cursor.revision, cursor.rowid, LCM_SCAN_BATCH) : this.db.prepare("SELECT rowid AS lcm_rowid,* FROM raw_entries WHERE project_key=? AND session_id=? ORDER BY created_at,revision,rowid LIMIT ?").all(this.project.key, sessionId, LCM_SCAN_BATCH);
|
|
648
|
-
for (const row of rows) entries.push(toRawEntry(row));
|
|
649
|
-
const last = rows.at(-1);
|
|
650
|
-
if (!last || rows.length < LCM_SCAN_BATCH) return entries;
|
|
651
|
-
cursor = { createdAt: Number(last.created_at), revision: Number(last.revision), rowid: Number(last.lcm_rowid) };
|
|
652
|
-
await slice.pause();
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
readRawPage(projectKey = this.project.key, sessionId, offset = 0, limit = 100) {
|
|
656
|
-
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) throw new Error("invalid raw page");
|
|
657
|
-
this.guard();
|
|
658
|
-
this.assertProjectKey(projectKey);
|
|
659
|
-
const rows = sessionId ? this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? AND session_id=? ORDER BY created_at,revision,rowid LIMIT ? OFFSET ?").all(projectKey, sessionId, limit, offset) : this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? ORDER BY created_at,session_id,entry_id,revision LIMIT ? OFFSET ?").all(projectKey, limit, offset);
|
|
660
|
-
return toRawEntries(rows);
|
|
661
|
-
}
|
|
662
|
-
readRawEntry(projectKey, sessionId, entryId, revision) {
|
|
663
|
-
this.guard();
|
|
664
|
-
this.assertProjectKey(projectKey);
|
|
665
|
-
const row = this.db.prepare("SELECT * FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? AND revision=?").get(projectKey, sessionId, entryId, revision);
|
|
666
|
-
return row ? toRawEntry(row) : void 0;
|
|
667
|
-
}
|
|
668
|
-
searchRaw(projectKey, options) {
|
|
669
|
-
this.guard();
|
|
670
|
-
const key = projectKey ?? this.project.key;
|
|
671
|
-
this.assertProjectKey(key);
|
|
672
|
-
const { offset, limit, sessionId } = options;
|
|
673
|
-
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) throw new Error("invalid raw page");
|
|
674
|
-
const scanLimit = options.scanLimit ?? LCM_SEARCH_SCAN_LIMIT;
|
|
675
|
-
if (!Number.isSafeInteger(scanLimit) || scanLimit < 1) throw new Error("invalid scan limit");
|
|
676
|
-
if (!validSearchFilter(options)) throw new Error("invalid raw search filter");
|
|
677
|
-
const query = options.query?.trim() ?? "";
|
|
678
|
-
if (query.length === 0) return this.recentPage(key, sessionId, offset, limit, rowFilter(options));
|
|
679
|
-
if (options.mode === "regex") {
|
|
680
|
-
let pattern;
|
|
681
|
-
try {
|
|
682
|
-
pattern = new RegExp(query, "iu");
|
|
683
|
-
} catch {
|
|
684
|
-
return { rows: [], total: 0, scanned: 0, complete: false };
|
|
685
|
-
}
|
|
686
|
-
return this.scanPage(key, sessionId, (content) => pattern.test(content), offset, limit, scanLimit, false, rowFilter(options));
|
|
687
|
-
}
|
|
688
|
-
const match = options.match ?? "any";
|
|
689
|
-
const phrases = searchPhrases(query, options.mode);
|
|
690
|
-
if (phrases.length === 0) return { rows: [], total: 0, scanned: 0, complete: true };
|
|
691
|
-
if (this.fts) {
|
|
692
|
-
try {
|
|
693
|
-
return this.indexPage(key, sessionId, ftsExpression(phrases, match), offset, limit, rowFilter(options, "r"), options.order === "relevance");
|
|
694
|
-
} catch {
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
return this.scanPage(key, sessionId, phrasePredicate(phrases, match), offset, limit, scanLimit, true, rowFilter(options));
|
|
698
|
-
}
|
|
699
|
-
recentPage(key, sessionId, offset, limit, filter) {
|
|
700
|
-
const scope = `FROM raw_entries WHERE project_key=?${sessionId ? " AND session_id=?" : ""}${filter.sql}`;
|
|
701
|
-
const params = [key, ...sessionId ? [sessionId] : [], ...filter.params];
|
|
702
|
-
const total = Number(this.db.prepare(`SELECT count(*) n ${scope}`).get(...params).n);
|
|
703
|
-
const rows = this.db.prepare(`SELECT * ${scope} ORDER BY created_at DESC, revision DESC, rowid DESC LIMIT ? OFFSET ?`).all(...params, limit, offset);
|
|
704
|
-
return { rows: toRawEntries(rows), total, scanned: total, complete: true };
|
|
705
|
-
}
|
|
706
|
-
indexPage(key, sessionId, expression, offset, limit, filter, relevance) {
|
|
707
|
-
const source = "FROM raw_entries_fts JOIN raw_entries r ON r.project_key=raw_entries_fts.project_key AND r.session_id=raw_entries_fts.session_id AND r.entry_id=raw_entries_fts.entry_id AND r.revision=CAST(raw_entries_fts.revision AS INTEGER) WHERE raw_entries_fts MATCH ? AND raw_entries_fts.project_key=?" + (sessionId ? " AND raw_entries_fts.session_id=?" : "") + filter.sql;
|
|
708
|
-
const filters = [expression, key, ...sessionId ? [sessionId] : [], ...filter.params];
|
|
709
|
-
const total = Number(this.db.prepare(`SELECT count(*) n ${source}`).get(...filters).n);
|
|
710
|
-
const order = relevance ? "bm25(raw_entries_fts), r.created_at DESC, r.revision DESC, r.rowid DESC" : "r.created_at DESC, r.revision DESC, r.rowid DESC";
|
|
711
|
-
const rows = this.db.prepare(`SELECT r.* ${source} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...filters, limit, offset);
|
|
712
|
-
return { rows: toRawEntries(rows), total, scanned: total, complete: true };
|
|
713
|
-
}
|
|
714
|
-
scanPage(key, sessionId, matches, offset, limit, scanLimit, degraded, filter) {
|
|
715
|
-
const statement = this.db.prepare(`SELECT session_id,entry_id,revision,content FROM raw_entries WHERE project_key=?${sessionId ? " AND session_id=?" : ""}${filter.sql} ORDER BY created_at DESC, revision DESC, rowid DESC LIMIT ? OFFSET ?`);
|
|
716
|
-
const scope = [key, ...sessionId ? [sessionId] : [], ...filter.params];
|
|
717
|
-
const found = [];
|
|
718
|
-
let scanned = 0;
|
|
719
|
-
let exhausted = false;
|
|
720
|
-
while (scanned < scanLimit) {
|
|
721
|
-
const size = Math.min(LCM_SCAN_BATCH, scanLimit - scanned);
|
|
722
|
-
const batch = statement.all(...scope, size, scanned);
|
|
723
|
-
scanned += batch.length;
|
|
724
|
-
for (const row of batch) if (matches(row.content)) found.push({ sessionId: row.session_id, entryId: row.entry_id, revision: Number(row.revision) });
|
|
725
|
-
if (batch.length < size) {
|
|
726
|
-
exhausted = true;
|
|
727
|
-
break;
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
const rows = [];
|
|
731
|
-
for (const identity of found.slice(offset, offset + limit)) {
|
|
732
|
-
const entry = this.readRawEntry(key, identity.sessionId, identity.entryId, identity.revision);
|
|
733
|
-
if (entry) rows.push(entry);
|
|
734
|
-
}
|
|
735
|
-
return { rows, total: found.length, scanned, complete: degraded ? false : exhausted };
|
|
736
|
-
}
|
|
737
|
-
/** Identity columns only, so a coverage scan never loads payloads. */
|
|
738
|
-
readRawKeys(projectKey = this.project.key, sessionId, limit = 1e5) {
|
|
739
|
-
this.guard();
|
|
740
|
-
this.assertProjectKey(projectKey);
|
|
741
|
-
const rows = sessionId ? this.db.prepare("SELECT session_id, entry_id, revision, content_hash FROM raw_entries WHERE project_key=? AND session_id=? ORDER BY created_at,revision,rowid LIMIT ?").all(projectKey, sessionId, limit) : this.db.prepare("SELECT session_id, entry_id, revision, content_hash FROM raw_entries WHERE project_key=? ORDER BY created_at,session_id,entry_id,revision LIMIT ?").all(projectKey, limit);
|
|
742
|
-
return rows.map((row) => ({ sessionId: row.session_id, entryId: row.entry_id, revision: Number(row.revision), contentHash: row.content_hash }));
|
|
743
|
-
}
|
|
744
|
-
/** Total stored payload bytes for one session, as a single aggregate. */
|
|
745
|
-
payloadBytes(projectKey = this.project.key, sessionId) {
|
|
746
|
-
this.guard();
|
|
747
|
-
this.assertProjectKey(projectKey);
|
|
748
|
-
const row = sessionId ? this.db.prepare("SELECT coalesce(sum(length(payload_json)),0) n FROM raw_entries WHERE project_key=? AND session_id=?").get(projectKey, sessionId) : this.db.prepare("SELECT coalesce(sum(length(payload_json)),0) n FROM raw_entries WHERE project_key=?").get(projectKey);
|
|
749
|
-
return Number(row.n);
|
|
750
|
-
}
|
|
751
|
-
readOnly(fn) {
|
|
752
|
-
this.guard();
|
|
753
|
-
return fn(this.db);
|
|
754
|
-
}
|
|
755
|
-
transaction(fn) {
|
|
756
|
-
this.guard();
|
|
757
|
-
if (this.transactionDepth > 0) return fn(this.db);
|
|
758
|
-
this.db.exec("BEGIN IMMEDIATE");
|
|
759
|
-
this.transactionDepth = 1;
|
|
760
|
-
try {
|
|
761
|
-
const result = fn(this.db);
|
|
762
|
-
this.db.exec("COMMIT");
|
|
763
|
-
return result;
|
|
764
|
-
} catch (error) {
|
|
765
|
-
this.db.exec("ROLLBACK");
|
|
766
|
-
throw error;
|
|
767
|
-
} finally {
|
|
768
|
-
this.transactionDepth = 0;
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
checkpoint(mode = "passive") {
|
|
772
|
-
const row = this.db.prepare(`PRAGMA wal_checkpoint(${mode.toUpperCase()})`).get();
|
|
773
|
-
const busy = row.busy ?? 0;
|
|
774
|
-
const logPages = row.log ?? 0;
|
|
775
|
-
return { mode, busy, logPages, checkpointedPages: row.checkpointed ?? 0, truncated: mode === "truncate" && busy === 0 && logPages === 0 };
|
|
776
|
-
}
|
|
777
|
-
backup(destination) {
|
|
778
|
-
this.guard();
|
|
779
|
-
return this.serializeSync(() => {
|
|
780
|
-
const target = path2.resolve(destination);
|
|
781
|
-
fs2.mkdirSync(path2.dirname(target), { recursive: true });
|
|
782
|
-
if (fs2.existsSync(target)) throw new Error("backup destination exists");
|
|
783
|
-
this.db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
|
|
784
|
-
fs2.chmodSync(target, 384);
|
|
785
|
-
const copy = new (sqliteDriver())(target);
|
|
786
|
-
let integrity = "unknown";
|
|
787
|
-
let backupStateSha256 = "";
|
|
788
|
-
const rowCounts = {};
|
|
789
|
-
try {
|
|
790
|
-
integrity = copy.prepare("PRAGMA integrity_check").get().integrity_check ?? "unknown";
|
|
791
|
-
for (const table of ["projects", "sessions", "raw_entries", "summary_nodes", "summary_node_revisions", "summary_edges", "frontiers", "maintenance_jobs", "maintenance_usage", "repair_ladder", "orphaned_rows"]) {
|
|
792
|
-
rowCounts[table] = Number(copy.prepare(`SELECT count(*) n FROM ${table}`).get().n);
|
|
793
|
-
}
|
|
794
|
-
backupStateSha256 = snapshotHash(copy);
|
|
795
|
-
} finally {
|
|
796
|
-
copy.close();
|
|
797
|
-
}
|
|
798
|
-
const manifest = { format: "lcm-ledger-backup", version: BACKUP_MANIFEST_VERSION, source: this.dbPath, destination: target, sourceSha256: fileHash(this.dbPath), backupSha256: fileHash(target), sourceStateSha256: backupStateSha256, rowCounts, integrity, createdAt: this.now() };
|
|
799
|
-
fs2.writeFileSync(`${target}.manifest.json`, JSON.stringify(manifest), { mode: 384 });
|
|
800
|
-
fs2.chmodSync(`${target}.manifest.json`, 384);
|
|
801
|
-
return manifest;
|
|
802
|
-
});
|
|
803
|
-
}
|
|
804
|
-
exportBackup(destination) {
|
|
805
|
-
return this.backup(destination);
|
|
806
|
-
}
|
|
807
|
-
orphanOwner(db, rowJson) {
|
|
808
|
-
let row;
|
|
809
|
-
try {
|
|
810
|
-
row = JSON.parse(rowJson);
|
|
811
|
-
} catch {
|
|
812
|
-
return void 0;
|
|
813
|
-
}
|
|
814
|
-
if (typeof row.project_key === "string") return row.project_key;
|
|
815
|
-
for (const column of ["node_id", "parent_id", "child_id"]) {
|
|
816
|
-
const nodeId = row[column];
|
|
817
|
-
if (typeof nodeId !== "string") continue;
|
|
818
|
-
const owner = db.prepare("SELECT project_key FROM summary_nodes WHERE node_id=?").get(nodeId);
|
|
819
|
-
if (owner?.project_key !== void 0) return owner.project_key;
|
|
820
|
-
}
|
|
821
|
-
return void 0;
|
|
822
|
-
}
|
|
823
|
-
projectFootprint() {
|
|
824
|
-
const key = this.project.key;
|
|
825
|
-
const count = (sql, ...params) => Number(this.db.prepare(sql).get(...params).n);
|
|
826
|
-
const remaining = {};
|
|
827
|
-
for (const table of PROJECT_KEYED_TABLES) remaining[table] = count(`SELECT count(*) n FROM ${table} WHERE project_key=?`, key);
|
|
828
|
-
remaining.summary_edges = count("SELECT count(*) n FROM summary_edges WHERE parent_id IN (SELECT node_id FROM summary_nodes WHERE project_key=?) OR child_id IN (SELECT node_id FROM summary_nodes WHERE project_key=?)", key, key);
|
|
829
|
-
if (this.fts) remaining.raw_entries_fts = count("SELECT count(*) n FROM raw_entries_fts WHERE project_key=?", key);
|
|
830
|
-
const unattributed = {};
|
|
831
|
-
remaining.orphaned_rows = 0;
|
|
832
|
-
for (const row of this.db.prepare("SELECT row_json FROM orphaned_rows").all()) {
|
|
833
|
-
const owner = this.orphanOwner(this.db, row.row_json);
|
|
834
|
-
if (owner === key) remaining.orphaned_rows++;
|
|
835
|
-
else if (owner === void 0) unattributed.orphaned_rows = (unattributed.orphaned_rows ?? 0) + 1;
|
|
836
|
-
}
|
|
837
|
-
const dangling = count("SELECT count(*) n FROM summary_edges WHERE parent_id NOT IN (SELECT node_id FROM summary_nodes) OR child_id NOT IN (SELECT node_id FROM summary_nodes)");
|
|
838
|
-
if (dangling > 0) unattributed.summary_edges = dangling;
|
|
839
|
-
return { remaining, unattributed };
|
|
840
|
-
}
|
|
841
|
-
deleteProject(token2, backupManifest) {
|
|
842
|
-
this.guard();
|
|
843
|
-
if (token2.__brand !== "DeleteConfirmationToken" || token2.projectKey !== this.project.key || token2.value !== hash(`delete:${this.project.key}`)) throw new Error("invalid delete confirmation token");
|
|
844
|
-
if (backupManifest.version !== BACKUP_MANIFEST_VERSION) throw new Error(`backup manifest version ${backupManifest.version} predates this ledger (expected ${BACKUP_MANIFEST_VERSION}); take a fresh backup`);
|
|
845
|
-
const backupDb = fs2.existsSync(backupManifest.destination) ? new (sqliteDriver())(backupManifest.destination) : void 0;
|
|
846
|
-
let backupStateSha256;
|
|
847
|
-
try {
|
|
848
|
-
if (backupDb) backupStateSha256 = snapshotHash(backupDb);
|
|
849
|
-
} finally {
|
|
850
|
-
backupDb?.close();
|
|
851
|
-
}
|
|
852
|
-
if (backupManifest.integrity !== "ok" || backupManifest.source !== this.dbPath || !backupManifest.backupSha256 || backupManifest.backupSha256 !== fileHash(backupManifest.destination) || !backupManifest.sourceStateSha256 || backupManifest.sourceStateSha256 !== backupStateSha256 || backupManifest.sourceSha256 !== fileHash(this.dbPath) || backupManifest.sourceStateSha256 !== snapshotHash(this.db)) throw new Error("backup verification failed");
|
|
853
|
-
this.transaction((db) => {
|
|
854
|
-
const purge = db.prepare("DELETE FROM orphaned_rows WHERE rowid=?");
|
|
855
|
-
for (const row of db.prepare("SELECT rowid AS id, row_json FROM orphaned_rows").all()) {
|
|
856
|
-
if (this.orphanOwner(db, row.row_json) === this.project.key) purge.run(row.id);
|
|
857
|
-
}
|
|
858
|
-
db.prepare("DELETE FROM summary_edges WHERE parent_id IN (SELECT node_id FROM summary_nodes WHERE project_key=?) OR child_id IN (SELECT node_id FROM summary_nodes WHERE project_key=?)").run(this.project.key, this.project.key);
|
|
859
|
-
for (const table of ["raw_entries", "sessions", "frontiers", "summary_node_revisions", "summary_nodes", "maintenance_jobs", "maintenance_usage", "repair_ladder"]) db.prepare(`DELETE FROM ${table} WHERE project_key=?`).run(this.project.key);
|
|
860
|
-
if (this.fts) db.prepare("DELETE FROM raw_entries_fts WHERE project_key=?").run(this.project.key);
|
|
861
|
-
db.prepare("DELETE FROM project_aliases WHERE project_key=?").run(this.project.key);
|
|
862
|
-
db.prepare("DELETE FROM projects WHERE project_key=?").run(this.project.key);
|
|
863
|
-
});
|
|
864
|
-
const integrity = this.db.prepare("PRAGMA integrity_check").get().integrity_check;
|
|
865
|
-
if (integrity !== "ok") throw new Error(`post-delete integrity failed: ${integrity}`);
|
|
866
|
-
const footprint = this.projectFootprint();
|
|
867
|
-
const total = (counts) => Object.values(counts).reduce((sum, value) => sum + value, 0);
|
|
868
|
-
const audit = { format: "lcm-ledger-delete", version: DELETE_MANIFEST_VERSION, projectKey: this.project.key, deletedAt: this.now(), integrity, remaining: total(footprint.remaining), remainingByTable: footprint.remaining, unattributed: total(footprint.unattributed), unattributedByTable: footprint.unattributed };
|
|
869
|
-
fs2.writeFileSync(`${backupManifest.destination}.delete-manifest.json`, JSON.stringify(audit), { mode: 384 });
|
|
870
|
-
}
|
|
871
|
-
serializeSync(operation) {
|
|
872
|
-
this.guard();
|
|
873
|
-
return operation();
|
|
874
|
-
}
|
|
875
|
-
close() {
|
|
876
|
-
if (this.closed) return;
|
|
877
|
-
this.closing.abort();
|
|
878
|
-
this.db.close();
|
|
879
|
-
this.closed = true;
|
|
880
|
-
}
|
|
881
|
-
};
|
|
882
|
-
|
|
883
|
-
// src/storage/lcm-migration.ts
|
|
884
|
-
import crypto2 from "node:crypto";
|
|
885
|
-
import fs3 from "node:fs";
|
|
886
|
-
import path3 from "node:path";
|
|
887
|
-
|
|
888
|
-
// src/core/event-loop-slice.ts
|
|
889
|
-
var EVENT_LOOP_SLICE_MS = 20;
|
|
890
|
-
var yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
891
|
-
var EventLoopSlice = class {
|
|
892
|
-
constructor(budgetMs = EVENT_LOOP_SLICE_MS) {
|
|
893
|
-
this.budgetMs = budgetMs;
|
|
894
|
-
}
|
|
895
|
-
#started = performance.now();
|
|
896
|
-
#yields = 0;
|
|
897
|
-
get due() {
|
|
898
|
-
return performance.now() - this.#started >= this.budgetMs;
|
|
899
|
-
}
|
|
900
|
-
get yields() {
|
|
901
|
-
return this.#yields;
|
|
902
|
-
}
|
|
903
|
-
async yield() {
|
|
904
|
-
this.#yields += 1;
|
|
905
|
-
await yieldToEventLoop();
|
|
906
|
-
this.#started = performance.now();
|
|
907
|
-
}
|
|
908
|
-
async pause() {
|
|
909
|
-
if (this.due) await this.yield();
|
|
910
|
-
}
|
|
911
|
-
};
|
|
912
|
-
|
|
913
|
-
// src/storage/lcm-migration.ts
|
|
914
|
-
var plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
915
|
-
var megabytes = (bytes) => `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
|
916
|
-
var migrationDropReasons = (drops) => {
|
|
917
|
-
const reasons = [];
|
|
918
|
-
if (drops.oversizedFiles > 0) reasons.push(`${plural(drops.oversizedFiles, "session file")} skipped as oversized (${megabytes(drops.oversizedFileBytes)})`);
|
|
919
|
-
if (drops.oversizedLines > 0) reasons.push(`${plural(drops.oversizedLines, "line")} skipped as oversized (${megabytes(drops.oversizedLineBytes)})`);
|
|
920
|
-
if (drops.skippedFiles > 0) reasons.push(`${plural(drops.skippedFiles, "session file")} skipped after the total scan budget`);
|
|
921
|
-
return reasons;
|
|
922
|
-
};
|
|
923
|
-
var hash2 = (data) => crypto2.createHash("sha256").update(data).digest("hex");
|
|
924
|
-
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
925
|
-
var nonblank = (value) => typeof value === "string" && value.trim().length > 0;
|
|
926
|
-
var sourceStillValid = (before, after) => after >= before;
|
|
927
|
-
var SOURCE_READ_ATTEMPTS = 3;
|
|
928
|
-
var SourceChangedError = class extends Error {
|
|
929
|
-
};
|
|
930
|
-
var readSource = (file, maxFileBytes, remainingBytes) => {
|
|
931
|
-
let raced = 0;
|
|
932
|
-
for (let attempt = 0; attempt < SOURCE_READ_ATTEMPTS; attempt += 1) {
|
|
933
|
-
let fd;
|
|
934
|
-
try {
|
|
935
|
-
fd = fs3.openSync(file, "r");
|
|
936
|
-
const before = fs3.fstatSync(fd);
|
|
937
|
-
if (!before.isFile()) return { kind: "not-file", raced };
|
|
938
|
-
if (before.size > maxFileBytes) return { kind: "oversized", raced, size: before.size };
|
|
939
|
-
if (before.size > remainingBytes) return { kind: "over-budget", raced };
|
|
940
|
-
const data = Buffer.allocUnsafe(before.size);
|
|
941
|
-
let offset = 0;
|
|
942
|
-
while (offset < data.length) {
|
|
943
|
-
const size = fs3.readSync(fd, data, offset, data.length - offset, offset);
|
|
944
|
-
if (size === 0) throw new SourceChangedError("source shortened during read");
|
|
945
|
-
offset += size;
|
|
946
|
-
}
|
|
947
|
-
if (!sourceStillValid(before.size, fs3.fstatSync(fd).size)) throw new SourceChangedError("source shrank during read");
|
|
948
|
-
return { kind: "data", raced, data };
|
|
949
|
-
} catch (error) {
|
|
950
|
-
if (error.code === "ENOENT") return { kind: "absent", raced };
|
|
951
|
-
if (!(error instanceof SourceChangedError)) return { kind: "error", raced };
|
|
952
|
-
raced += 1;
|
|
953
|
-
} finally {
|
|
954
|
-
if (fd !== void 0) fs3.closeSync(fd);
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
return { kind: "raced", raced };
|
|
958
|
-
};
|
|
959
|
-
var utc = (value) => {
|
|
960
|
-
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|\+00:00)$/.test(value)) throw new Error("timestamps must be explicit UTC ISO-8601 values");
|
|
961
|
-
const at = Date.parse(value);
|
|
962
|
-
const normalized = value.replace("+00:00", "Z").replace(/Z$/, "");
|
|
963
|
-
if (!Number.isFinite(at) || new Date(at).toISOString().slice(0, 19) !== normalized.slice(0, 19)) throw new Error("invalid UTC timestamp");
|
|
964
|
-
return at;
|
|
965
|
-
};
|
|
966
|
-
function migrationWindow(options) {
|
|
967
|
-
const now = options.now ?? Date.now();
|
|
968
|
-
const since = options.since === void 0 ? now - 72 * 60 * 60 * 1e3 : utc(options.since);
|
|
969
|
-
const until = options.until === void 0 ? now : utc(options.until);
|
|
970
|
-
if (!Number.isFinite(since) || !Number.isFinite(until) || since > until) throw new Error("invalid migration window");
|
|
971
|
-
return { since, until };
|
|
972
|
-
}
|
|
973
|
-
var positive = (value, fallback) => {
|
|
974
|
-
const result = value ?? fallback;
|
|
975
|
-
if (!Number.isSafeInteger(result) || result < 1) throw new Error("scan limits must be positive safe integers");
|
|
976
|
-
return result;
|
|
977
|
-
};
|
|
978
|
-
function discoverMigrationSessions(options) {
|
|
979
|
-
const maxFiles = positive(options.maxFiles, 1e4);
|
|
980
|
-
const maxEntries = positive(options.maxDiscoveryEntries, 1e5);
|
|
981
|
-
const files = /* @__PURE__ */ new Set();
|
|
982
|
-
let incomplete = 0;
|
|
983
|
-
let entries = 0;
|
|
984
|
-
const add = (file) => {
|
|
985
|
-
if (files.size >= maxFiles && !files.has(path3.resolve(file))) {
|
|
986
|
-
incomplete++;
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
files.add(path3.resolve(file));
|
|
990
|
-
};
|
|
991
|
-
if (options.files) {
|
|
992
|
-
for (const file of options.files.slice(0, maxFiles)) add(file);
|
|
993
|
-
if (options.files.length > maxFiles) incomplete++;
|
|
994
|
-
return { files: [...files].sort(), incomplete };
|
|
995
|
-
}
|
|
996
|
-
const list = (dir, visit) => {
|
|
997
|
-
let handle;
|
|
998
|
-
try {
|
|
999
|
-
handle = fs3.opendirSync(dir);
|
|
1000
|
-
let entry;
|
|
1001
|
-
while ((entry = handle.readSync()) !== null) {
|
|
1002
|
-
if (++entries > maxEntries) {
|
|
1003
|
-
incomplete++;
|
|
1004
|
-
break;
|
|
1005
|
-
}
|
|
1006
|
-
visit(entry);
|
|
1007
|
-
}
|
|
1008
|
-
} catch {
|
|
1009
|
-
incomplete++;
|
|
1010
|
-
} finally {
|
|
1011
|
-
handle?.closeSync();
|
|
1012
|
-
}
|
|
1013
|
-
};
|
|
1014
|
-
const scan = (dir) => list(dir, (entry) => {
|
|
1015
|
-
if (entry.isFile() && entry.name.endsWith(".jsonl")) add(path3.join(dir, entry.name));
|
|
1016
|
-
else if (entry.isSymbolicLink() && entry.name.endsWith(".jsonl")) incomplete++;
|
|
1017
|
-
});
|
|
1018
|
-
if (options.candidateDirs) {
|
|
1019
|
-
for (const dir of options.candidateDirs) {
|
|
1020
|
-
if (entries >= maxEntries) {
|
|
1021
|
-
incomplete++;
|
|
1022
|
-
break;
|
|
1023
|
-
}
|
|
1024
|
-
scan(dir);
|
|
1025
|
-
}
|
|
1026
|
-
} else if (options.projectCwd) {
|
|
1027
|
-
const names = sessionDirNamesForCwd(options.projectCwd);
|
|
1028
|
-
let found = false;
|
|
1029
|
-
for (const name of [names.canonical, ...names.legacy]) {
|
|
1030
|
-
const dir = path3.join(sessionsDirRoot(options.agentDir), name);
|
|
1031
|
-
try {
|
|
1032
|
-
if (fs3.statSync(dir).isDirectory()) {
|
|
1033
|
-
found = true;
|
|
1034
|
-
scan(dir);
|
|
1035
|
-
}
|
|
1036
|
-
} catch (error) {
|
|
1037
|
-
if (error.code !== "ENOENT") incomplete++;
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
if (!found) incomplete++;
|
|
1041
|
-
} else {
|
|
1042
|
-
const root = sessionsDirRoot(options.agentDir);
|
|
1043
|
-
list(root, (entry) => {
|
|
1044
|
-
if (entry.isDirectory()) scan(path3.join(root, entry.name));
|
|
1045
|
-
else if (entry.isFile() && entry.name.endsWith(".jsonl")) add(path3.join(root, entry.name));
|
|
1046
|
-
else if (entry.isSymbolicLink()) incomplete++;
|
|
1047
|
-
});
|
|
1048
|
-
}
|
|
1049
|
-
return { files: [...files].sort(), incomplete };
|
|
1050
|
-
}
|
|
1051
|
-
var CHECKPOINT_SCHEMA = "CREATE TABLE IF NOT EXISTS migration_checkpoints (project_key TEXT NOT NULL, session_path TEXT NOT NULL, source_hash TEXT NOT NULL, line_ordinal INTEGER NOT NULL, entry_id TEXT NOT NULL, content_hash TEXT NOT NULL, PRIMARY KEY(project_key,session_path,source_hash,line_ordinal,entry_id,content_hash))";
|
|
1052
|
-
function reconcileSession(options) {
|
|
1053
|
-
return migrateSessions({ ...options, onDemand: true });
|
|
1054
|
-
}
|
|
1055
|
-
async function migrateSessions(options) {
|
|
1056
|
-
const slice = options.slice ?? new EventLoopSlice();
|
|
1057
|
-
const window = migrationWindow(options);
|
|
1058
|
-
const maxFileBytes = positive(options.maxFileBytes, 64 * 1024 ** 2);
|
|
1059
|
-
const maxLineBytes = positive(options.maxLineBytes, 8 * 1024 ** 2);
|
|
1060
|
-
const maxTotalBytes = positive(options.maxTotalBytes, 1024 ** 3);
|
|
1061
|
-
const discovery = discoverMigrationSessions(options);
|
|
1062
|
-
const result = {
|
|
1063
|
-
mode: options.apply ? "apply" : "dry-run",
|
|
1064
|
-
since: new Date(window.since).toISOString(),
|
|
1065
|
-
until: new Date(window.until).toISOString(),
|
|
1066
|
-
counts: { eligible: 0, imported: 0, skippedDuplicate: 0, skippedOutOfWindow: 0, malformed: 0, oversized: 0, absent: 0, incompleteDiscovery: discovery.incomplete, raced: 0, errors: 0 },
|
|
1067
|
-
drops: { oversizedFiles: 0, oversizedFileBytes: 0, oversizedLines: 0, oversizedLineBytes: 0, skippedFiles: 0, entries: 0 },
|
|
1068
|
-
degraded: false,
|
|
1069
|
-
filesScanned: 0,
|
|
1070
|
-
bytesScanned: 0,
|
|
1071
|
-
generations: [],
|
|
1072
|
-
exitCode: 0
|
|
1073
|
-
};
|
|
1074
|
-
const counts = result.counts;
|
|
1075
|
-
const drops = result.drops;
|
|
1076
|
-
const drySeen = /* @__PURE__ */ new Set();
|
|
1077
|
-
files: for (const [position, file] of discovery.files.entries()) {
|
|
1078
|
-
await slice.pause();
|
|
1079
|
-
if (options.signal?.aborted) break;
|
|
1080
|
-
const read2 = readSource(file, maxFileBytes, maxTotalBytes - result.bytesScanned);
|
|
1081
|
-
counts.raced += read2.raced;
|
|
1082
|
-
if (read2.kind !== "data") {
|
|
1083
|
-
switch (read2.kind) {
|
|
1084
|
-
case "absent":
|
|
1085
|
-
counts.absent++;
|
|
1086
|
-
counts.incompleteDiscovery++;
|
|
1087
|
-
break;
|
|
1088
|
-
case "not-file":
|
|
1089
|
-
counts.incompleteDiscovery++;
|
|
1090
|
-
break;
|
|
1091
|
-
case "oversized":
|
|
1092
|
-
counts.oversized++;
|
|
1093
|
-
drops.oversizedFiles++;
|
|
1094
|
-
drops.oversizedFileBytes += read2.size;
|
|
1095
|
-
break;
|
|
1096
|
-
case "over-budget":
|
|
1097
|
-
counts.incompleteDiscovery++;
|
|
1098
|
-
drops.skippedFiles += discovery.files.length - position;
|
|
1099
|
-
break files;
|
|
1100
|
-
case "raced":
|
|
1101
|
-
counts.incompleteDiscovery++;
|
|
1102
|
-
break;
|
|
1103
|
-
default:
|
|
1104
|
-
counts.errors++;
|
|
1105
|
-
counts.incompleteDiscovery++;
|
|
1106
|
-
}
|
|
1107
|
-
continue;
|
|
1108
|
-
}
|
|
1109
|
-
const data = read2.data;
|
|
1110
|
-
result.filesScanned++;
|
|
1111
|
-
result.bytesScanned += data.length;
|
|
1112
|
-
const sourceHash = hash2(data);
|
|
1113
|
-
result.generations.push({ sessionPath: file, sourceHash });
|
|
1114
|
-
let header;
|
|
1115
|
-
let ledger;
|
|
1116
|
-
let database;
|
|
1117
|
-
let sessionId = "";
|
|
1118
|
-
let projectKey = "";
|
|
1119
|
-
let cwd;
|
|
1120
|
-
let ordinal = 0;
|
|
1121
|
-
try {
|
|
1122
|
-
for (let start = 0; start < data.length; ) {
|
|
1123
|
-
if (slice.due) await slice.yield();
|
|
1124
|
-
if (options.signal?.aborted) break;
|
|
1125
|
-
ordinal++;
|
|
1126
|
-
const newline = data.indexOf(10, start);
|
|
1127
|
-
const end = newline < 0 ? data.length : newline;
|
|
1128
|
-
const bytes = data.subarray(start, end);
|
|
1129
|
-
start = newline < 0 ? data.length : end + 1;
|
|
1130
|
-
if (bytes.length > maxLineBytes) {
|
|
1131
|
-
counts.oversized++;
|
|
1132
|
-
drops.oversizedLines++;
|
|
1133
|
-
drops.oversizedLineBytes += bytes.length;
|
|
1134
|
-
drops.entries++;
|
|
1135
|
-
continue;
|
|
1136
|
-
}
|
|
1137
|
-
const content = bytes.toString("utf8").replace(/\r$/, "");
|
|
1138
|
-
if (!content.trim()) continue;
|
|
1139
|
-
let row;
|
|
1140
|
-
try {
|
|
1141
|
-
row = record(JSON.parse(content));
|
|
1142
|
-
} catch {
|
|
1143
|
-
counts.malformed++;
|
|
1144
|
-
continue;
|
|
1145
|
-
}
|
|
1146
|
-
if (!row) {
|
|
1147
|
-
counts.malformed++;
|
|
1148
|
-
continue;
|
|
1149
|
-
}
|
|
1150
|
-
if (row.type === "message_end") continue;
|
|
1151
|
-
if (!header) {
|
|
1152
|
-
if (row.type !== "session") {
|
|
1153
|
-
if (record(row.message)) counts.malformed++;
|
|
1154
|
-
continue;
|
|
1155
|
-
}
|
|
1156
|
-
if (!nonblank(row.id)) {
|
|
1157
|
-
counts.malformed++;
|
|
1158
|
-
break;
|
|
1159
|
-
}
|
|
1160
|
-
header = row;
|
|
1161
|
-
sessionId = row.id;
|
|
1162
|
-
cwd = nonblank(row.cwd) ? row.cwd : options.liveCwd;
|
|
1163
|
-
if (!cwd) {
|
|
1164
|
-
counts.malformed++;
|
|
1165
|
-
break;
|
|
1166
|
-
}
|
|
1167
|
-
const projectInput = options.liveCwd ? { recordedCwd: cwd, liveCwd: options.liveCwd } : { recordedCwd: cwd };
|
|
1168
|
-
projectKey = canonicalProjectIdentity(projectInput).key;
|
|
1169
|
-
if (options.ledger && options.ledger.project.key !== projectKey) {
|
|
1170
|
-
counts.errors++;
|
|
1171
|
-
break;
|
|
1172
|
-
}
|
|
1173
|
-
if (options.apply) {
|
|
1174
|
-
if (options.ledger) ledger = options.ledger;
|
|
1175
|
-
else if (options.ledgerRoot) ledger = new LcmLedger({ rootDir: options.ledgerRoot, project: { recordedCwd: cwd } });
|
|
1176
|
-
else ledger = new LcmLedger({ project: { recordedCwd: cwd } });
|
|
1177
|
-
await ledger.runStartupChecks();
|
|
1178
|
-
database = ledger.db;
|
|
1179
|
-
database.exec(CHECKPOINT_SCHEMA);
|
|
1180
|
-
} else if (options.ledger) database = options.ledger.db;
|
|
1181
|
-
else {
|
|
1182
|
-
const dbPath = defaultLedgerPath(options.ledgerRoot, projectKey);
|
|
1183
|
-
if (fs3.existsSync(dbPath)) database = new (sqliteDriver())(dbPath, { readOnly: true });
|
|
1184
|
-
}
|
|
1185
|
-
continue;
|
|
1186
|
-
}
|
|
1187
|
-
if (row.type === "session" || !nonblank(row.type) || !nonblank(row.id) || row.parentId !== null && row.parentId !== void 0 && typeof row.parentId !== "string") {
|
|
1188
|
-
counts.malformed++;
|
|
1189
|
-
continue;
|
|
1190
|
-
}
|
|
1191
|
-
const message = record(row.message);
|
|
1192
|
-
if (row.type === "message" && (!message || !nonblank(message.role))) {
|
|
1193
|
-
counts.malformed++;
|
|
1194
|
-
continue;
|
|
1195
|
-
}
|
|
1196
|
-
let at;
|
|
1197
|
-
try {
|
|
1198
|
-
at = typeof row.timestamp === "string" ? utc(row.timestamp) : NaN;
|
|
1199
|
-
} catch {
|
|
1200
|
-
at = NaN;
|
|
1201
|
-
}
|
|
1202
|
-
if (!Number.isFinite(at)) {
|
|
1203
|
-
counts.malformed++;
|
|
1204
|
-
continue;
|
|
1205
|
-
}
|
|
1206
|
-
if (!options.onDemand && (at < window.since || at > window.until)) {
|
|
1207
|
-
counts.skippedOutOfWindow++;
|
|
1208
|
-
continue;
|
|
1209
|
-
}
|
|
1210
|
-
counts.eligible++;
|
|
1211
|
-
const payloadJson = canonicalLcmPayload(row);
|
|
1212
|
-
const contentHash = hash2(canonicalLcmEntry(row));
|
|
1213
|
-
const identity = JSON.stringify([projectKey, sessionId, row.id, contentHash]);
|
|
1214
|
-
const progress = { projectKey, sessionPath: file, sourceHash, lineOrdinal: ordinal, entryId: row.id, contentHash };
|
|
1215
|
-
const duplicate = drySeen.has(identity) || database?.prepare("SELECT 1 FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? AND content_hash=?").get(projectKey, sessionId, row.id, contentHash) !== void 0;
|
|
1216
|
-
if (duplicate) counts.skippedDuplicate++;
|
|
1217
|
-
else if (ledger) {
|
|
1218
|
-
const persisted = ledger.appendRaw({
|
|
1219
|
-
projectKey,
|
|
1220
|
-
sessionId,
|
|
1221
|
-
entryId: row.id,
|
|
1222
|
-
role: message && typeof message.role === "string" ? message.role : row.type,
|
|
1223
|
-
content,
|
|
1224
|
-
payloadJson,
|
|
1225
|
-
parentEntryId: typeof row.parentId === "string" ? row.parentId : null,
|
|
1226
|
-
branch: typeof row.branch === "string" ? row.branch : typeof row.branchId === "string" ? row.branchId : null,
|
|
1227
|
-
...cwd ? { recordedCwd: cwd } : {},
|
|
1228
|
-
createdAt: at
|
|
1229
|
-
});
|
|
1230
|
-
if (persisted.contentHash === contentHash) counts.imported++;
|
|
1231
|
-
else counts.skippedDuplicate++;
|
|
1232
|
-
} else if (!duplicate) counts.imported++;
|
|
1233
|
-
drySeen.add(identity);
|
|
1234
|
-
if (ledger) database.prepare("INSERT OR IGNORE INTO migration_checkpoints(project_key,session_path,source_hash,line_ordinal,entry_id,content_hash) VALUES(?,?,?,?,?,?)").run(projectKey, file, sourceHash, ordinal, row.id, contentHash);
|
|
1235
|
-
options.onProgress?.(progress);
|
|
1236
|
-
}
|
|
1237
|
-
if (!header) counts.malformed++;
|
|
1238
|
-
} catch (error) {
|
|
1239
|
-
counts.errors++;
|
|
1240
|
-
if (options.onProgress) throw error;
|
|
1241
|
-
} finally {
|
|
1242
|
-
if (ledger && ledger !== options.ledger) ledger.close();
|
|
1243
|
-
else if (!ledger && database && database !== options.ledger?.db) database.close();
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
result.degraded = drops.entries > 0 || drops.oversizedFiles > 0 || drops.skippedFiles > 0;
|
|
1247
|
-
result.exitCode = counts.errors || counts.malformed || counts.oversized || counts.incompleteDiscovery && !options.allowIncompleteDiscovery ? 1 : 0;
|
|
1248
|
-
return result;
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
// src/compaction/lcm-maintenance.ts
|
|
1252
|
-
import crypto3 from "node:crypto";
|
|
1253
|
-
var DEFAULT_LCM_BUDGET = { calls: Number.POSITIVE_INFINITY, inputTokens: Number.POSITIVE_INFINITY, outputTokens: Number.POSITIVE_INFINITY, cost: Number.POSITIVE_INFINITY, wallMs: Number.POSITIVE_INFINITY, sessionCalls: Number.POSITIVE_INFINITY };
|
|
1254
|
-
var DEFAULT_LEAF_ENTRIES = 32;
|
|
1255
|
-
var NODE_SCAN_LIMIT = 1e5;
|
|
1256
|
-
var NODE_PAGE_SIZE = 500;
|
|
1257
|
-
var EMPTY_TAINT = /* @__PURE__ */ new Set();
|
|
1258
|
-
var DEFAULT_MAINTENANCE_CONCURRENCY = 3;
|
|
1259
|
-
var LEASE_MS = 3e4;
|
|
1260
|
-
var LEASE_SWEEP_GRACE_MS = 6e4;
|
|
1261
|
-
var LcmRejection = class extends Error {
|
|
1262
|
-
reason;
|
|
1263
|
-
constructor(reason) {
|
|
1264
|
-
super(reason);
|
|
1265
|
-
this.name = "LcmRejection";
|
|
1266
|
-
this.reason = reason;
|
|
1267
|
-
}
|
|
1268
|
-
};
|
|
1269
|
-
var isLcmRejection = (error) => error instanceof LcmRejection;
|
|
1270
|
-
var isLcmCapacityRejection = (error) => isLcmRejection(error) && (error.reason === "project lease held" || error.reason === "budget exhausted");
|
|
1271
|
-
var LEGACY_CONTENTION_RETIREMENTS = /* @__PURE__ */ new Set(["job lease held", "project lease held", "LcmRejection: job lease held", "LcmRejection: project lease held"]);
|
|
1272
|
-
var hash3 = (v) => hashLcmPayload(v);
|
|
1273
|
-
var parse = (v) => JSON.parse(String(v));
|
|
1274
|
-
var rawHash = (e) => e.payloadHash;
|
|
1275
|
-
var token = () => crypto3.randomUUID();
|
|
1276
|
-
var LCM_MODEL_LEVELS = [{ mode: "detail", share: 1 }, { mode: "bullets", share: 0.5 }];
|
|
1277
|
-
var CLAIMABLE_JOBS_SQL = `SELECT j.payload FROM maintenance_jobs j
|
|
1278
|
-
JOIN summary_nodes n ON n.node_id=json_extract(j.payload,'$.nodeId') AND n.project_key=j.project_key
|
|
1279
|
-
WHERE j.project_key=?
|
|
1280
|
-
AND (j.status='pending' OR (j.status='running' AND CAST(coalesce(json_extract(j.payload,'$.leaseUntil'),0) AS INTEGER)<=?))
|
|
1281
|
-
AND CAST(json_extract(j.payload,'$.eligibleAt') AS INTEGER)<=?
|
|
1282
|
-
AND CAST(json_extract(j.payload,'$.nextRetryAt') AS INTEGER)<=?
|
|
1283
|
-
AND (? IS NULL OR json_extract(n.payload,'$.sessionId')=?)
|
|
1284
|
-
ORDER BY CAST(json_extract(j.payload,'$.priority') AS INTEGER) DESC, j.created_at, j.job_id
|
|
1285
|
-
LIMIT ?`;
|
|
1286
|
-
var LIVE_LEASES_SQL = `SELECT coalesce(json_extract(n.payload,'$.sessionId'),'') sessionId
|
|
1287
|
-
FROM maintenance_jobs j
|
|
1288
|
-
LEFT JOIN summary_nodes n ON n.node_id=json_extract(j.payload,'$.nodeId') AND n.project_key=j.project_key
|
|
1289
|
-
WHERE j.project_key=? AND j.status='running' AND j.job_id<>? AND CAST(coalesce(json_extract(j.payload,'$.leaseUntil'),0) AS INTEGER)>?`;
|
|
1290
|
-
var LcmMaintenance = class {
|
|
1291
|
-
constructor(ledger, options = {}) {
|
|
1292
|
-
this.ledger = ledger;
|
|
1293
|
-
this.maxConcurrentJobs = options.maxConcurrentJobs ?? DEFAULT_MAINTENANCE_CONCURRENCY;
|
|
1294
|
-
this.projectKey = ledger.project.key;
|
|
1295
|
-
this.now = options.now ?? Date.now;
|
|
1296
|
-
this.ownerId = options.ownerId ?? crypto3.randomUUID();
|
|
1297
|
-
this.policyHash = options.policyHash ?? hash3("lcm-policy-v1");
|
|
1298
|
-
this.maxLeaf = options.maxLeafEntries ?? DEFAULT_LEAF_ENTRIES;
|
|
1299
|
-
this.maxChildren = options.maxCondenseChildren ?? 4;
|
|
1300
|
-
this.maxInputChars = options.maxInputChars ?? 2e5;
|
|
1301
|
-
this.maxOutputChars = options.maxOutputChars ?? 4096;
|
|
1302
|
-
this.modelTimeoutMs = options.modelTimeoutMs ?? 12e4;
|
|
1303
|
-
this.budget = { ...DEFAULT_LCM_BUDGET, ...options.budget };
|
|
1304
|
-
}
|
|
1305
|
-
projectKey;
|
|
1306
|
-
now;
|
|
1307
|
-
ownerId;
|
|
1308
|
-
policyHash;
|
|
1309
|
-
maxLeaf;
|
|
1310
|
-
maxChildren;
|
|
1311
|
-
maxInputChars;
|
|
1312
|
-
maxOutputChars;
|
|
1313
|
-
budget;
|
|
1314
|
-
modelTimeoutMs;
|
|
1315
|
-
maxConcurrentJobs;
|
|
1316
|
-
budgetPolicy() {
|
|
1317
|
-
return { ...this.budget };
|
|
1318
|
-
}
|
|
1319
|
-
get concurrencyLimit() {
|
|
1320
|
-
const raw = typeof this.maxConcurrentJobs === "function" ? this.maxConcurrentJobs() : this.maxConcurrentJobs;
|
|
1321
|
-
return Number.isFinite(raw) ? Math.max(1, Math.floor(raw)) : DEFAULT_MAINTENANCE_CONCURRENCY;
|
|
1322
|
-
}
|
|
1323
|
-
liveLeases(db, at, excludeJobId) {
|
|
1324
|
-
return db.prepare(LIVE_LEASES_SQL).all(this.projectKey, excludeJobId ?? "", at - LEASE_SWEEP_GRACE_MS);
|
|
1325
|
-
}
|
|
1326
|
-
admits(db, at, sessionId, leases) {
|
|
1327
|
-
const day = this.day(at);
|
|
1328
|
-
const project = this.usage(db, day);
|
|
1329
|
-
const session = this.usage(db, day, sessionId);
|
|
1330
|
-
let sessionReserved = 0;
|
|
1331
|
-
for (const lease of leases) if (lease.sessionId === sessionId) sessionReserved += 1;
|
|
1332
|
-
const reserved = leases.length + 1;
|
|
1333
|
-
const fits = (used, cap) => used < cap && used + (project.calls > 0 ? used / project.calls * reserved : 0) <= cap;
|
|
1334
|
-
return project.calls + leases.length < this.budget.calls && fits(project.inputTokens, this.budget.inputTokens) && fits(project.outputTokens, this.budget.outputTokens) && fits(project.cost, this.budget.cost) && fits(project.wallMs, this.budget.wallMs) && session.calls + sessionReserved < this.budget.sessionCalls;
|
|
1335
|
-
}
|
|
1336
|
-
recordRevision(db, node) {
|
|
1337
|
-
if (!node.text) return;
|
|
1338
|
-
const row = db.prepare("SELECT coalesce(max(revision),0) n FROM summary_node_revisions WHERE node_id=?").get(node.nodeId);
|
|
1339
|
-
db.prepare("INSERT OR IGNORE INTO summary_node_revisions(node_id,revision,project_key,text,model_hash,created_at) VALUES(?,?,?,?,?,?)").run(node.nodeId, Number(row.n) + 1, this.projectKey, node.text, node.modelHash, this.now());
|
|
1340
|
-
}
|
|
1341
|
-
revisionsOf(nodeId) {
|
|
1342
|
-
return this.ledger.readOnly((db) => db.prepare("SELECT revision, text, model_hash, created_at FROM summary_node_revisions WHERE node_id=? AND project_key=? ORDER BY revision").all(nodeId, this.projectKey).map((row) => ({ revision: Number(row.revision), text: row.text, modelHash: row.model_hash, createdAt: Number(row.created_at) })));
|
|
1343
|
-
}
|
|
1344
|
-
selectUpgrades(sessionId, activeSources, limit = 1, all = this.listNodes(NODE_SCAN_LIMIT)) {
|
|
1345
|
-
const taint = this.tainted(all);
|
|
1346
|
-
return all.filter((node) => !taint.has(node.nodeId) && node.state === "ready" && node.modelHash === "emergency" && node.policyHash === this.policyHash && (!sessionId || node.sessionId === sessionId) && (!activeSources || node.sources.every((source) => activeSources.has(this.sourceKey(source))))).sort((left, right) => left.depth - right.depth || left.nodeId.localeCompare(right.nodeId)).slice(0, limit);
|
|
1347
|
-
}
|
|
1348
|
-
ancestorsOf(nodeId) {
|
|
1349
|
-
return this.ledger.readOnly((db) => {
|
|
1350
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1351
|
-
const stack = [nodeId];
|
|
1352
|
-
const order = [];
|
|
1353
|
-
while (stack.length > 0) {
|
|
1354
|
-
const current = stack.pop();
|
|
1355
|
-
const parents = db.prepare("SELECT e.parent_id FROM summary_edges e CROSS JOIN summary_nodes parent ON parent.node_id=e.parent_id WHERE e.child_id=? AND parent.project_key=?").all(current, this.projectKey);
|
|
1356
|
-
for (const { parent_id: parent } of parents) {
|
|
1357
|
-
if (seen.has(parent)) continue;
|
|
1358
|
-
seen.add(parent);
|
|
1359
|
-
order.push(parent);
|
|
1360
|
-
stack.push(parent);
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
return order;
|
|
1364
|
-
});
|
|
1365
|
-
}
|
|
1366
|
-
reopen(nodeId, force = false) {
|
|
1367
|
-
return this.ledger.transaction((db) => {
|
|
1368
|
-
const row = db.prepare("SELECT payload FROM summary_nodes WHERE node_id=? AND project_key=?").get(nodeId, this.projectKey);
|
|
1369
|
-
if (!row?.payload) throw new Error("node not found");
|
|
1370
|
-
const node = parse(row.payload);
|
|
1371
|
-
if (node.projectKey !== this.projectKey) throw new Error("node project does not match ledger project");
|
|
1372
|
-
if (!force && node.modelHash !== "emergency") throw new Error("node already carries a model summary");
|
|
1373
|
-
const t = this.now();
|
|
1374
|
-
const job = { ...this.job(node), jobId: `job:upgrade:${token()}:${node.nodeId}`, createdAt: t, updatedAt: t };
|
|
1375
|
-
db.prepare("INSERT INTO maintenance_jobs(job_id,project_key,status,payload,created_at,updated_at) VALUES(?,?,?,?,?,?)").run(job.jobId, this.projectKey, job.state, JSON.stringify(job), job.createdAt, job.updatedAt);
|
|
1376
|
-
return job;
|
|
1377
|
-
});
|
|
1378
|
-
}
|
|
1379
|
-
listNodes(limit = 100, offset = 0) {
|
|
1380
|
-
return this.ledger.readOnly((db) => db.prepare("SELECT payload FROM summary_nodes WHERE project_key=? ORDER BY created_at,node_id LIMIT ? OFFSET ?").all(this.projectKey, limit, offset).map((r) => {
|
|
1381
|
-
const node = parse(r.payload);
|
|
1382
|
-
if (node.projectKey !== this.projectKey) throw new Error("node project does not match ledger project");
|
|
1383
|
-
return node;
|
|
1384
|
-
}));
|
|
1385
|
-
}
|
|
1386
|
-
/** The same nodes in the same order as listNodes(NODE_SCAN_LIMIT), read in keyset pages that yield between batches. */
|
|
1387
|
-
async loadNodes(slice) {
|
|
1388
|
-
const nodes = [];
|
|
1389
|
-
let cursor;
|
|
1390
|
-
while (nodes.length < NODE_SCAN_LIMIT) {
|
|
1391
|
-
const limit = Math.min(NODE_PAGE_SIZE, NODE_SCAN_LIMIT - nodes.length);
|
|
1392
|
-
const rows = this.ledger.readOnly((db) => cursor ? db.prepare("SELECT payload,created_at,node_id FROM summary_nodes WHERE project_key=? AND (created_at,node_id)>(?,?) ORDER BY created_at,node_id LIMIT ?").all(this.projectKey, cursor.createdAt, cursor.nodeId, limit) : db.prepare("SELECT payload,created_at,node_id FROM summary_nodes WHERE project_key=? ORDER BY created_at,node_id LIMIT ?").all(this.projectKey, limit));
|
|
1393
|
-
for (const row of rows) {
|
|
1394
|
-
const node = parse(row.payload);
|
|
1395
|
-
if (node.projectKey !== this.projectKey) throw new Error("node project does not match ledger project");
|
|
1396
|
-
nodes.push(node);
|
|
1397
|
-
}
|
|
1398
|
-
const last = rows.at(-1);
|
|
1399
|
-
if (!last || rows.length < limit) break;
|
|
1400
|
-
cursor = { createdAt: last.created_at, nodeId: last.node_id };
|
|
1401
|
-
await slice.pause();
|
|
1402
|
-
}
|
|
1403
|
-
return nodes;
|
|
1404
|
-
}
|
|
1405
|
-
getNode(nodeId) {
|
|
1406
|
-
return this.ledger.readOnly((db) => {
|
|
1407
|
-
const row = db.prepare("SELECT payload FROM summary_nodes WHERE node_id=? AND project_key=?").get(nodeId, this.projectKey);
|
|
1408
|
-
if (!row?.payload) return void 0;
|
|
1409
|
-
const node = parse(row.payload);
|
|
1410
|
-
if (node.projectKey !== this.projectKey) throw new Error("node project does not match ledger project");
|
|
1411
|
-
return node;
|
|
1412
|
-
});
|
|
1413
|
-
}
|
|
1414
|
-
/** The oversized deterministic leaves and every ancestor that inherited one. */
|
|
1415
|
-
tainted(nodes) {
|
|
1416
|
-
const oversized = nodes.filter((node) => node.kind === "leaf" && node.modelHash === "emergency" && node.sources.length > Math.max(this.maxLeaf, DEFAULT_LEAF_ENTRIES)).map((node) => node.nodeId);
|
|
1417
|
-
if (oversized.length === 0) return EMPTY_TAINT;
|
|
1418
|
-
const parents = /* @__PURE__ */ new Map();
|
|
1419
|
-
for (const node of nodes) for (const child of node.children) parents.set(child, [...parents.get(child) ?? [], node.nodeId]);
|
|
1420
|
-
const excluded = /* @__PURE__ */ new Set();
|
|
1421
|
-
const queue = [...oversized];
|
|
1422
|
-
while (queue.length > 0) {
|
|
1423
|
-
const nodeId = queue.pop();
|
|
1424
|
-
if (excluded.has(nodeId)) continue;
|
|
1425
|
-
excluded.add(nodeId);
|
|
1426
|
-
for (const parent of parents.get(nodeId) ?? []) queue.push(parent);
|
|
1427
|
-
}
|
|
1428
|
-
return excluded;
|
|
1429
|
-
}
|
|
1430
|
-
/** Scoped by the live source set when given; drops a condensed child and a contained node. */
|
|
1431
|
-
getFrontier(sessionId, activeSources) {
|
|
1432
|
-
const all = this.listNodes(NODE_SCAN_LIMIT);
|
|
1433
|
-
const taint = this.tainted(all);
|
|
1434
|
-
const nodes = all.filter((n) => !taint.has(n.nodeId) && n.state === "ready" && n.policyHash === this.policyHash && (!sessionId || activeSources !== void 0 || n.sessionId === sessionId) && (!activeSources || n.sources.every((s) => activeSources.has(this.sourceKey(s)))));
|
|
1435
|
-
const condensed = new Set(nodes.flatMap((n) => n.children));
|
|
1436
|
-
const standing = nodes.filter((n) => !condensed.has(n.nodeId));
|
|
1437
|
-
const ranked = [...standing].sort((a, b) => b.sources.length - a.sources.length || a.nodeId.localeCompare(b.nodeId));
|
|
1438
|
-
const kept = [];
|
|
1439
|
-
const shadowed = /* @__PURE__ */ new Set();
|
|
1440
|
-
for (const node of ranked) {
|
|
1441
|
-
const keys = node.sources.map((s) => this.sourceKey(s));
|
|
1442
|
-
if (kept.some((other) => {
|
|
1443
|
-
const held = new Set(other.sources.map((s) => this.sourceKey(s)));
|
|
1444
|
-
return keys.every((key) => held.has(key));
|
|
1445
|
-
})) {
|
|
1446
|
-
shadowed.add(node.nodeId);
|
|
1447
|
-
continue;
|
|
1448
|
-
}
|
|
1449
|
-
kept.push(node);
|
|
1450
|
-
}
|
|
1451
|
-
return standing.filter((n) => !shadowed.has(n.nodeId));
|
|
1452
|
-
}
|
|
1453
|
-
recentJobs(limit = 200) {
|
|
1454
|
-
return this.ledger.readOnly((db) => db.prepare("SELECT payload FROM maintenance_jobs WHERE project_key=? ORDER BY CASE status WHEN 'failed' THEN 0 WHEN 'running' THEN 1 WHEN 'pending' THEN 2 ELSE 3 END, updated_at DESC LIMIT ?").all(this.projectKey, limit).map((r) => {
|
|
1455
|
-
const job = parse(r.payload);
|
|
1456
|
-
if (job.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1457
|
-
return job;
|
|
1458
|
-
}));
|
|
1459
|
-
}
|
|
1460
|
-
listJobs(limit = 100) {
|
|
1461
|
-
return this.ledger.readOnly((db) => db.prepare("SELECT payload FROM maintenance_jobs WHERE project_key=? ORDER BY created_at,job_id LIMIT ?").all(this.projectKey, limit).map((r) => {
|
|
1462
|
-
const job = parse(r.payload);
|
|
1463
|
-
if (job.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1464
|
-
return job;
|
|
1465
|
-
}));
|
|
1466
|
-
}
|
|
1467
|
-
jobForNode(nodeId) {
|
|
1468
|
-
return this.ledger.readOnly((db) => {
|
|
1469
|
-
const row = db.prepare("SELECT payload FROM maintenance_jobs WHERE job_id=? AND project_key=?").get(`job:${nodeId}`, this.projectKey);
|
|
1470
|
-
if (!row?.payload) return void 0;
|
|
1471
|
-
const job = parse(row.payload);
|
|
1472
|
-
if (job.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1473
|
-
return job;
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
1476
|
-
claimableJobs(sessionId, limit = 64) {
|
|
1477
|
-
const t = this.now();
|
|
1478
|
-
const scope = sessionId ?? null;
|
|
1479
|
-
return this.ledger.readOnly((db) => db.prepare(CLAIMABLE_JOBS_SQL).all(this.projectKey, t - LEASE_SWEEP_GRACE_MS, t, t, scope, scope, limit).map((r) => {
|
|
1480
|
-
const job = parse(r.payload);
|
|
1481
|
-
if (job.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1482
|
-
return job;
|
|
1483
|
-
}));
|
|
1484
|
-
}
|
|
1485
|
-
countJobs(state, updatedSince = 0) {
|
|
1486
|
-
return this.ledger.readOnly((db) => Number(db.prepare("SELECT count(*) n FROM maintenance_jobs WHERE project_key=? AND status=? AND updated_at>=?").get(this.projectKey, state, updatedSince).n));
|
|
1487
|
-
}
|
|
1488
|
-
isClaimable(job) {
|
|
1489
|
-
const t = this.now();
|
|
1490
|
-
return (job.state === "pending" || job.state === "running" && (job.leaseUntil ?? 0) + LEASE_SWEEP_GRACE_MS <= t) && job.eligibleAt <= t && job.nextRetryAt <= t;
|
|
1491
|
-
}
|
|
1492
|
-
sweepExpiredLeases() {
|
|
1493
|
-
return this.ledger.transaction((db) => {
|
|
1494
|
-
const t = this.now() - LEASE_SWEEP_GRACE_MS;
|
|
1495
|
-
const rows = db.prepare("SELECT payload FROM maintenance_jobs WHERE project_key=? AND status=?").all(this.projectKey, "running");
|
|
1496
|
-
const swept = [];
|
|
1497
|
-
for (const row of rows) {
|
|
1498
|
-
const old = parse(row.payload);
|
|
1499
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1500
|
-
if ((old.leaseUntil ?? 0) > t) continue;
|
|
1501
|
-
const now = this.now();
|
|
1502
|
-
const { ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = old;
|
|
1503
|
-
const job = { ...base, state: "pending", error: "lease expired", eligibleAt: now, nextRetryAt: now, updatedAt: now };
|
|
1504
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(job.state, JSON.stringify(job), job.updatedAt, job.jobId, this.projectKey);
|
|
1505
|
-
swept.push(job);
|
|
1506
|
-
}
|
|
1507
|
-
return swept;
|
|
1508
|
-
});
|
|
1509
|
-
}
|
|
1510
|
-
expiredLeases() {
|
|
1511
|
-
const t = this.now() - LEASE_SWEEP_GRACE_MS;
|
|
1512
|
-
return this.ledger.readOnly((db) => Number(db.prepare("SELECT count(*) n FROM maintenance_jobs WHERE project_key=? AND status=? AND coalesce(json_extract(payload,'$.leaseUntil'),0)<=?").get(this.projectKey, "running", t).n));
|
|
1513
|
-
}
|
|
1514
|
-
retryFailedJobs() {
|
|
1515
|
-
return this.ledger.transaction((db) => {
|
|
1516
|
-
const rows = db.prepare("SELECT payload FROM maintenance_jobs WHERE project_key=? AND status=?").all(this.projectKey, "failed");
|
|
1517
|
-
const retried = [];
|
|
1518
|
-
for (const row of rows) {
|
|
1519
|
-
const old = parse(row.payload);
|
|
1520
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1521
|
-
const t = this.now();
|
|
1522
|
-
const { error: _error, ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = old;
|
|
1523
|
-
const job = { ...base, state: "pending", attempts: 0, eligibleAt: t, nextRetryAt: t, updatedAt: t };
|
|
1524
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(job.state, JSON.stringify(job), job.updatedAt, job.jobId, this.projectKey);
|
|
1525
|
-
retried.push(job);
|
|
1526
|
-
}
|
|
1527
|
-
return retried;
|
|
1528
|
-
});
|
|
1529
|
-
}
|
|
1530
|
-
recoverLegacyContentionRetirements() {
|
|
1531
|
-
return this.ledger.transaction((db) => {
|
|
1532
|
-
const rows = db.prepare("SELECT payload FROM maintenance_jobs WHERE project_key=? AND status=?").all(this.projectKey, "failed");
|
|
1533
|
-
const recovered = [];
|
|
1534
|
-
for (const row of rows) {
|
|
1535
|
-
const old = parse(row.payload);
|
|
1536
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1537
|
-
if (old.legacyRecovery || !LEGACY_CONTENTION_RETIREMENTS.has(old.error ?? "")) continue;
|
|
1538
|
-
const t = this.now();
|
|
1539
|
-
const { error: _error, ...base } = old;
|
|
1540
|
-
const job = { ...base, state: "pending", attempts: 0, legacyRecovery: true, eligibleAt: t, nextRetryAt: t, updatedAt: t };
|
|
1541
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(job.state, JSON.stringify(job), job.updatedAt, job.jobId, this.projectKey);
|
|
1542
|
-
recovered.push(job);
|
|
1543
|
-
}
|
|
1544
|
-
return recovered;
|
|
1545
|
-
});
|
|
1546
|
-
}
|
|
1547
|
-
recordFailure(job, error) {
|
|
1548
|
-
return this.ledger.transaction((db) => {
|
|
1549
|
-
const row = db.prepare("SELECT payload FROM maintenance_jobs WHERE job_id=? AND project_key=?").get(job.jobId, this.projectKey);
|
|
1550
|
-
if (!row?.payload) return void 0;
|
|
1551
|
-
const old = parse(row.payload);
|
|
1552
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1553
|
-
const t = this.now();
|
|
1554
|
-
if (old.state === "completed" || old.attempts !== job.attempts) return old;
|
|
1555
|
-
if (old.state === "running" && (old.leaseUntil ?? 0) > t && old.leaseToken !== job.leaseToken) return old;
|
|
1556
|
-
const attempts = old.attempts + 1;
|
|
1557
|
-
const delay = Math.min(9e5, 3e4 * 2 ** (attempts - 1));
|
|
1558
|
-
const { ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = old;
|
|
1559
|
-
const next = { ...base, attempts, error: String(error), state: attempts >= 3 ? "failed" : "pending", eligibleAt: t + delay, nextRetryAt: t + delay, updatedAt: t };
|
|
1560
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(next.state, JSON.stringify(next), next.updatedAt, next.jobId, this.projectKey);
|
|
1561
|
-
return next;
|
|
1562
|
-
});
|
|
1563
|
-
}
|
|
1564
|
-
selectLeaf(entries = this.ledger.readRaw(this.projectKey), activeSources, all = this.listNodes(NODE_SCAN_LIMIT)) {
|
|
1565
|
-
const first = entries[0];
|
|
1566
|
-
if (!first) return [];
|
|
1567
|
-
const taint = this.tainted(all);
|
|
1568
|
-
const nodes = all.filter((n) => !taint.has(n.nodeId) && n.state !== "failed" && n.policyHash === this.policyHash && (n.sessionId === first.sessionId || activeSources !== void 0 && n.state === "ready") && (!activeSources || n.sources.every((s) => activeSources.has(this.sourceKey(s)))));
|
|
1569
|
-
const covered = new Set(nodes.flatMap((n) => n.sources.map((s) => this.sourceKey(s))));
|
|
1570
|
-
const candidates = entries.filter((e) => e.sessionId === first.sessionId && !covered.has(this.sourceKey(e)));
|
|
1571
|
-
const picked = [];
|
|
1572
|
-
let chars = 0;
|
|
1573
|
-
for (const entry of candidates) {
|
|
1574
|
-
if (picked.length >= this.maxLeaf) break;
|
|
1575
|
-
const size = entry.payloadJson.length;
|
|
1576
|
-
if (picked.length > 0 && chars + size > this.maxInputChars) break;
|
|
1577
|
-
picked.push(entry);
|
|
1578
|
-
chars += size;
|
|
1579
|
-
}
|
|
1580
|
-
return picked;
|
|
1581
|
-
}
|
|
1582
|
-
selectCondensation(sessionId, activeSources, all = this.listNodes(NODE_SCAN_LIMIT)) {
|
|
1583
|
-
const taint = this.tainted(all);
|
|
1584
|
-
const nodes = all.filter((n) => !taint.has(n.nodeId) && n.state === "ready" && n.policyHash === this.policyHash && (!sessionId || n.sessionId === sessionId) && (!activeSources || n.sources.every((s) => activeSources.has(this.sourceKey(s)))));
|
|
1585
|
-
const eligible = new Set(nodes.map((n) => n.nodeId));
|
|
1586
|
-
const edges = this.ledger.readOnly((db) => db.prepare("SELECT e.parent_id,e.child_id FROM summary_edges e CROSS JOIN summary_nodes parent ON parent.node_id=e.parent_id AND parent.project_key=? CROSS JOIN summary_nodes child ON child.node_id=e.child_id AND child.project_key=parent.project_key WHERE parent.project_key=?").all(this.projectKey, this.projectKey));
|
|
1587
|
-
const consumed = new Set(edges.filter((e) => eligible.has(e.parent_id)).map((e) => e.child_id));
|
|
1588
|
-
const candidates = nodes.filter((n) => !consumed.has(n.nodeId));
|
|
1589
|
-
const first = candidates[0];
|
|
1590
|
-
if (!first) return [];
|
|
1591
|
-
const depth = Math.min(...candidates.map((n) => n.depth));
|
|
1592
|
-
const sameDepth = candidates.filter((n) => n.depth === depth);
|
|
1593
|
-
if (depth > 0 && sameDepth.length < 2) return [];
|
|
1594
|
-
return candidates.filter((n) => n.projectKey === first.projectKey && n.sessionId === first.sessionId && n.depth === depth).sort((a, b) => a.nodeId.localeCompare(b.nodeId)).slice(0, this.maxChildren);
|
|
1595
|
-
}
|
|
1596
|
-
createLeaf(entries) {
|
|
1597
|
-
if (!entries.length) return void 0;
|
|
1598
|
-
const source = entries.map((e, index) => {
|
|
1599
|
-
if (e.projectKey !== this.projectKey) throw new Error("entry project does not match ledger project");
|
|
1600
|
-
const payload = parse(e.payloadJson);
|
|
1601
|
-
if (typeof payload.type !== "string" || !payload.type || payload.id !== e.entryId) throw new Error("invalid raw payload");
|
|
1602
|
-
if (hash3(payload) !== rawHash(e)) throw new Error("payload hash mismatch");
|
|
1603
|
-
return { sessionId: e.sessionId, entryId: e.entryId, revision: e.revision, payloadHash: rawHash(e) };
|
|
1604
|
-
});
|
|
1605
|
-
this.validateSources(source);
|
|
1606
|
-
const node = { nodeId: `leaf:${hash3({ projectKey: this.projectKey, source, policyHash: this.policyHash })}`, projectKey: this.projectKey, sessionId: entries[0].sessionId, kind: "leaf", sources: source, children: [], depth: 0, sourceHash: hash3(source.map((s) => s.payloadHash)), policyHash: this.policyHash, modelHash: "", state: "pending", createdAt: this.now() };
|
|
1607
|
-
this.publish(node);
|
|
1608
|
-
return node;
|
|
1609
|
-
}
|
|
1610
|
-
createCondensed(children) {
|
|
1611
|
-
if (!children.length) return void 0;
|
|
1612
|
-
if (children.some((c) => c.state !== "ready")) throw new Error("condensation requires ready children");
|
|
1613
|
-
if (new Set(children.map((c) => c.sessionId)).size !== 1 || new Set(children.map((c) => c.depth)).size !== 1) throw new Error("mixed session or depth");
|
|
1614
|
-
const storedChildren = children.map((child) => this.getNode(child.nodeId));
|
|
1615
|
-
if (storedChildren.some((child) => !child || child.projectKey !== this.projectKey)) throw new Error("child project does not match ledger project");
|
|
1616
|
-
if (storedChildren.some((child, index) => JSON.stringify(child) !== JSON.stringify(children[index]))) throw new Error("child payload changed");
|
|
1617
|
-
const source = [...new Map(storedChildren.flatMap((c) => c.sources).map((value) => [this.sourceKey(value), value])).values()];
|
|
1618
|
-
this.validateSources(source);
|
|
1619
|
-
const node = { nodeId: `condensed:${hash3({ projectKey: this.projectKey, children: storedChildren.map((c) => c.nodeId), policyHash: this.policyHash })}`, projectKey: this.projectKey, sessionId: children[0].sessionId, kind: "condensed", sources: source, children: children.map((c) => c.nodeId), depth: Math.max(...children.map((c) => c.depth)) + 1, sourceHash: hash3(children.map((c) => c.sourceHash)), policyHash: this.policyHash, modelHash: "", state: "pending", createdAt: this.now() };
|
|
1620
|
-
this.publish(node);
|
|
1621
|
-
return node;
|
|
1622
|
-
}
|
|
1623
|
-
validateSources(source) {
|
|
1624
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1625
|
-
for (const s of source) {
|
|
1626
|
-
if (seen.has(this.sourceKey(s))) throw new Error("duplicate source identity");
|
|
1627
|
-
seen.add(this.sourceKey(s));
|
|
1628
|
-
}
|
|
1629
|
-
if (new Set(source.map((s) => s.sessionId)).size !== 1) throw new Error("cross-session ranges");
|
|
1630
|
-
}
|
|
1631
|
-
sourceKey(source) {
|
|
1632
|
-
return `${source.entryId}:${source.payloadHash}`;
|
|
1633
|
-
}
|
|
1634
|
-
publish(node) {
|
|
1635
|
-
this.ledger.transaction((db) => {
|
|
1636
|
-
if (node.children.includes(node.nodeId)) throw new Error("cycle");
|
|
1637
|
-
for (const child of node.children) if (!db.prepare("SELECT 1 FROM summary_nodes WHERE node_id=? AND project_key=?").get(child, this.projectKey)) throw new Error("missing child");
|
|
1638
|
-
db.prepare("INSERT OR IGNORE INTO summary_nodes(node_id,project_key,payload,created_at) VALUES(?,?,?,?)").run(node.nodeId, this.projectKey, JSON.stringify(node), node.createdAt);
|
|
1639
|
-
for (const child of node.children) db.prepare("INSERT OR IGNORE INTO summary_edges(parent_id,child_id) VALUES(?,?)").run(node.nodeId, child);
|
|
1640
|
-
const job = this.job(node);
|
|
1641
|
-
db.prepare("INSERT OR IGNORE INTO maintenance_jobs(job_id,project_key,status,payload,created_at,updated_at) VALUES(?,?,?,?,?,?)").run(job.jobId, this.projectKey, job.state, JSON.stringify(job), job.createdAt, job.updatedAt);
|
|
1642
|
-
});
|
|
1643
|
-
}
|
|
1644
|
-
job(node) {
|
|
1645
|
-
const t = this.now();
|
|
1646
|
-
return { jobId: `job:${node.nodeId}`, projectKey: this.projectKey, nodeId: node.nodeId, priority: node.kind === "condensed" ? 20 : 10, eligibleAt: t, state: "pending", attempts: 0, nextRetryAt: t, createdAt: t, updatedAt: t };
|
|
1647
|
-
}
|
|
1648
|
-
claim(jobId, ownerId = this.ownerId) {
|
|
1649
|
-
return this.ledger.transaction((db) => {
|
|
1650
|
-
const row = db.prepare("SELECT payload FROM maintenance_jobs WHERE job_id=? AND project_key=?").get(jobId, this.projectKey);
|
|
1651
|
-
if (!row?.payload) throw new Error("job not found");
|
|
1652
|
-
const old = parse(row.payload);
|
|
1653
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1654
|
-
const t = this.now();
|
|
1655
|
-
const expired = old.state === "running" && (old.leaseUntil ?? 0) + LEASE_SWEEP_GRACE_MS <= t;
|
|
1656
|
-
if (old.state === "running" && !expired) throw new LcmRejection("job lease held");
|
|
1657
|
-
if (old.state !== "pending" && !expired || old.eligibleAt > t || old.nextRetryAt > t) throw new LcmRejection("job not eligible");
|
|
1658
|
-
const leases = this.liveLeases(db, t, old.jobId);
|
|
1659
|
-
if (leases.length >= this.concurrencyLimit) throw new LcmRejection("project lease held");
|
|
1660
|
-
const nodeRow = db.prepare("SELECT payload FROM summary_nodes WHERE node_id=? AND project_key=?").get(old.nodeId, this.projectKey);
|
|
1661
|
-
const sessionId = nodeRow?.payload ? parse(nodeRow.payload).sessionId : "";
|
|
1662
|
-
if (!this.admits(db, t, sessionId, leases)) throw new LcmRejection("budget exhausted");
|
|
1663
|
-
const out = { ...old, state: "running", ownerId, leaseToken: token(), leaseUntil: t + LEASE_MS, updatedAt: t };
|
|
1664
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(out.state, JSON.stringify(out), t, jobId, this.projectKey);
|
|
1665
|
-
return out;
|
|
1666
|
-
});
|
|
1667
|
-
}
|
|
1668
|
-
claimEmergency(jobId, ownerId = this.ownerId) {
|
|
1669
|
-
return this.ledger.transaction((db) => {
|
|
1670
|
-
const row = db.prepare("SELECT payload FROM maintenance_jobs WHERE job_id=? AND project_key=?").get(jobId, this.projectKey);
|
|
1671
|
-
if (!row?.payload) throw new Error("job not found");
|
|
1672
|
-
const old = parse(row.payload);
|
|
1673
|
-
if (old.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1674
|
-
const t = this.now();
|
|
1675
|
-
const expired = old.state === "running" && (old.leaseUntil ?? 0) <= t;
|
|
1676
|
-
if (old.state === "running" && !expired) throw new LcmRejection("job lease held");
|
|
1677
|
-
if (old.state === "completed") throw new Error("job already completed");
|
|
1678
|
-
const out = { ...old, state: "running", ownerId, leaseToken: token(), leaseUntil: t + LEASE_MS, updatedAt: t };
|
|
1679
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(out.state, JSON.stringify(out), t, jobId, this.projectKey);
|
|
1680
|
-
return out;
|
|
1681
|
-
});
|
|
1682
|
-
}
|
|
1683
|
-
renew(job) {
|
|
1684
|
-
return this.fenced(job, (old) => ({ ...old, leaseUntil: this.now() + LEASE_MS, updatedAt: this.now() }));
|
|
1685
|
-
}
|
|
1686
|
-
validateText(text) {
|
|
1687
|
-
if (typeof text !== "string" || text.length === 0) throw new Error("invalid summary text");
|
|
1688
|
-
let length = 0;
|
|
1689
|
-
for (const _ of text) {
|
|
1690
|
-
length += 1;
|
|
1691
|
-
if (length > this.maxOutputChars) throw new Error("summary exceeds output bound");
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1694
|
-
validateShrink(text, inputBytes) {
|
|
1695
|
-
if (!Number.isSafeInteger(inputBytes) || inputBytes < 0) throw new Error("invalid input bound");
|
|
1696
|
-
if (utf8Bytes(text) >= inputBytes) throw new Error("summary does not shrink its input");
|
|
1697
|
-
}
|
|
1698
|
-
withinBudget(sessionId, excludeJobId) {
|
|
1699
|
-
return this.ledger.readOnly((db) => {
|
|
1700
|
-
const at = this.now();
|
|
1701
|
-
return this.admits(db, at, sessionId, this.liveLeases(db, at, excludeJobId));
|
|
1702
|
-
});
|
|
1703
|
-
}
|
|
1704
|
-
accountRejected(sessionId, result) {
|
|
1705
|
-
if (![result.inputTokens, result.outputTokens, result.cost, result.wallMs].every((value) => Number.isFinite(value) && value >= 0)) return;
|
|
1706
|
-
try {
|
|
1707
|
-
this.ledger.transaction((db) => this.account(db, sessionId, result));
|
|
1708
|
-
} catch {
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
complete(job, result, inputBytes) {
|
|
1712
|
-
this.validateText(result.text);
|
|
1713
|
-
this.validateShrink(result.text, inputBytes);
|
|
1714
|
-
return this.ledger.transaction((db) => {
|
|
1715
|
-
const current = this.readJob(db, job.jobId);
|
|
1716
|
-
this.assertLease(current, job);
|
|
1717
|
-
if (current.nodeId !== job.nodeId) throw new Error("job node mismatch");
|
|
1718
|
-
const row = db.prepare("SELECT payload FROM summary_nodes WHERE node_id=? AND project_key=?").get(job.nodeId, this.projectKey);
|
|
1719
|
-
if (!row?.payload) throw new Error("node not found");
|
|
1720
|
-
const node = parse(row.payload);
|
|
1721
|
-
if (node.projectKey !== this.projectKey || node.nodeId !== current.nodeId) throw new Error("node project does not match ledger project");
|
|
1722
|
-
for (const source of node.sources) {
|
|
1723
|
-
const raw = db.prepare("SELECT payload_json,session_id FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? AND revision=?").get(this.projectKey, source.sessionId, source.entryId, source.revision);
|
|
1724
|
-
if (!raw?.payload_json || hash3(parse(raw.payload_json)) !== source.payloadHash || raw.session_id !== source.sessionId) throw new Error("stale source");
|
|
1725
|
-
}
|
|
1726
|
-
if (![result.inputTokens, result.outputTokens, result.cost, result.wallMs].every((value) => Number.isFinite(value) && value >= 0)) throw new Error("invalid model usage");
|
|
1727
|
-
const projectUsage = this.usage(db, this.day(this.now()));
|
|
1728
|
-
const sessionUsage = this.usage(db, this.day(this.now()), node.sessionId);
|
|
1729
|
-
if (projectUsage.calls + 1 > this.budget.calls || projectUsage.inputTokens + result.inputTokens > this.budget.inputTokens || projectUsage.outputTokens + result.outputTokens > this.budget.outputTokens || projectUsage.cost + result.cost > this.budget.cost || projectUsage.wallMs + result.wallMs > this.budget.wallMs || sessionUsage.calls + 1 > this.budget.sessionCalls) throw new Error("budget exhausted");
|
|
1730
|
-
this.recordRevision(db, node);
|
|
1731
|
-
const out = { ...node, state: "ready", text: result.text, modelHash: result.modelHash };
|
|
1732
|
-
this.account(db, node.sessionId, result);
|
|
1733
|
-
db.prepare("UPDATE summary_nodes SET payload=? WHERE node_id=? AND project_key=?").run(JSON.stringify(out), node.nodeId, this.projectKey);
|
|
1734
|
-
const { ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = current;
|
|
1735
|
-
const done = { ...base, state: "completed", updatedAt: this.now() };
|
|
1736
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(done.state, JSON.stringify(done), done.updatedAt, done.jobId, this.projectKey);
|
|
1737
|
-
return out;
|
|
1738
|
-
});
|
|
1739
|
-
}
|
|
1740
|
-
completeEmergency(job, text) {
|
|
1741
|
-
this.validateText(text);
|
|
1742
|
-
return this.ledger.transaction((db) => {
|
|
1743
|
-
const current = this.readJob(db, job.jobId);
|
|
1744
|
-
this.assertLease(current, job);
|
|
1745
|
-
if (current.nodeId !== job.nodeId) throw new Error("job node mismatch");
|
|
1746
|
-
const row = db.prepare("SELECT payload FROM summary_nodes WHERE node_id=? AND project_key=?").get(job.nodeId, this.projectKey);
|
|
1747
|
-
if (!row?.payload) throw new Error("node not found");
|
|
1748
|
-
const node = parse(row.payload);
|
|
1749
|
-
if (node.projectKey !== this.projectKey || node.nodeId !== current.nodeId) throw new Error("node project does not match ledger project");
|
|
1750
|
-
for (const source of node.sources) {
|
|
1751
|
-
const raw = db.prepare("SELECT payload_json,session_id FROM raw_entries WHERE project_key=? AND session_id=? AND entry_id=? AND revision=?").get(this.projectKey, source.sessionId, source.entryId, source.revision);
|
|
1752
|
-
if (!raw?.payload_json || hash3(parse(raw.payload_json)) !== source.payloadHash || raw.session_id !== source.sessionId) throw new Error("stale source");
|
|
1753
|
-
}
|
|
1754
|
-
this.recordRevision(db, node);
|
|
1755
|
-
const out = { ...node, state: "ready", text, modelHash: "emergency" };
|
|
1756
|
-
db.prepare("UPDATE summary_nodes SET payload=? WHERE node_id=? AND project_key=?").run(JSON.stringify(out), node.nodeId, this.projectKey);
|
|
1757
|
-
const { ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = current;
|
|
1758
|
-
const done = { ...base, state: "completed", updatedAt: this.now() };
|
|
1759
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(done.state, JSON.stringify(done), done.updatedAt, done.jobId, this.projectKey);
|
|
1760
|
-
return out;
|
|
1761
|
-
});
|
|
1762
|
-
}
|
|
1763
|
-
fail(job, error) {
|
|
1764
|
-
return this.fenced(job, (old) => {
|
|
1765
|
-
const attempts = old.attempts + 1;
|
|
1766
|
-
const delay = Math.min(9e5, 3e4 * 2 ** (attempts - 1));
|
|
1767
|
-
const { ownerId: _ownerId, leaseToken: _leaseToken, leaseUntil: _leaseUntil, ...base } = old;
|
|
1768
|
-
return { ...base, attempts, error, state: attempts >= 3 ? "failed" : "pending", eligibleAt: this.now() + delay, nextRetryAt: this.now() + delay, updatedAt: this.now() };
|
|
1769
|
-
});
|
|
1770
|
-
}
|
|
1771
|
-
async run(job, model, input, signal = new AbortController().signal) {
|
|
1772
|
-
let sources = [];
|
|
1773
|
-
let claimed;
|
|
1774
|
-
const controller = new AbortController();
|
|
1775
|
-
let renew;
|
|
1776
|
-
const timer = setTimeout(() => controller.abort(), this.modelTimeoutMs);
|
|
1777
|
-
const abort = () => controller.abort();
|
|
1778
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
1779
|
-
const inputBytes = utf8Bytes(input);
|
|
1780
|
-
try {
|
|
1781
|
-
claimed = this.claim(job.jobId, job.ownerId ?? this.ownerId);
|
|
1782
|
-
const node = this.getNode(claimed.nodeId);
|
|
1783
|
-
sources = node?.sources ?? [];
|
|
1784
|
-
const kind = node?.kind ?? "leaf";
|
|
1785
|
-
const sessionId = node?.sessionId ?? "";
|
|
1786
|
-
renew = setInterval(() => {
|
|
1787
|
-
try {
|
|
1788
|
-
if (claimed) claimed = this.renew(claimed);
|
|
1789
|
-
} catch {
|
|
1790
|
-
}
|
|
1791
|
-
}, 1e4);
|
|
1792
|
-
let lastError = new Error("LCM summarization did not converge");
|
|
1793
|
-
for (const [index, level] of LCM_MODEL_LEVELS.entries()) {
|
|
1794
|
-
if (controller.signal.aborted) break;
|
|
1795
|
-
if (index > 0 && !this.withinBudget(sessionId, job.jobId)) break;
|
|
1796
|
-
const target = Math.max(1, Math.min(Math.floor(this.maxOutputChars * level.share), inputBytes - 1));
|
|
1797
|
-
let result;
|
|
1798
|
-
try {
|
|
1799
|
-
result = await Promise.race([
|
|
1800
|
-
model.generate({ prompt: buildLcmPrompt(kind, input, this.maxInputChars, level.mode, target), sessionId, signal: controller.signal }),
|
|
1801
|
-
new Promise((_, reject) => controller.signal.addEventListener("abort", () => reject(new Error("LCM timeout")), { once: true }))
|
|
1802
|
-
]);
|
|
1803
|
-
} catch (error) {
|
|
1804
|
-
lastError = error;
|
|
1805
|
-
continue;
|
|
1806
|
-
}
|
|
1807
|
-
if (utf8Bytes(result.text) >= inputBytes) {
|
|
1808
|
-
this.accountRejected(sessionId, result);
|
|
1809
|
-
lastError = new Error("summary does not shrink its input");
|
|
1810
|
-
continue;
|
|
1811
|
-
}
|
|
1812
|
-
return this.complete(claimed, result, inputBytes);
|
|
1813
|
-
}
|
|
1814
|
-
throw lastError;
|
|
1815
|
-
} catch (error) {
|
|
1816
|
-
if (!claimed) throw error;
|
|
1817
|
-
const fallback = emergencyReduce(input, this.maxOutputChars, sources);
|
|
1818
|
-
try {
|
|
1819
|
-
return this.completeEmergency(claimed, fallback);
|
|
1820
|
-
} catch (fenced) {
|
|
1821
|
-
if (isLcmRejection(fenced) && fenced.reason === "lease fenced") throw fenced;
|
|
1822
|
-
try {
|
|
1823
|
-
this.fail(claimed, String(error));
|
|
1824
|
-
} catch {
|
|
1825
|
-
}
|
|
1826
|
-
throw error;
|
|
1827
|
-
}
|
|
1828
|
-
} finally {
|
|
1829
|
-
clearTimeout(timer);
|
|
1830
|
-
if (renew) clearInterval(renew);
|
|
1831
|
-
signal.removeEventListener("abort", abort);
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
day(ms) {
|
|
1835
|
-
return new Date(ms).toISOString().slice(0, 10);
|
|
1836
|
-
}
|
|
1837
|
-
usage(db, day, sessionId) {
|
|
1838
|
-
const q = sessionId === void 0 ? "SELECT COALESCE(SUM(calls),0) calls,COALESCE(SUM(input_tokens),0) inputTokens,COALESCE(SUM(output_tokens),0) outputTokens,COALESCE(SUM(cost),0) cost,COALESCE(SUM(wall_ms),0) wallMs FROM maintenance_usage WHERE project_key=? AND day=?" : "SELECT COALESCE(SUM(calls),0) calls,COALESCE(SUM(input_tokens),0) inputTokens,COALESCE(SUM(output_tokens),0) outputTokens,COALESCE(SUM(cost),0) cost,COALESCE(SUM(wall_ms),0) wallMs FROM maintenance_usage WHERE project_key=? AND day=? AND session_id=?";
|
|
1839
|
-
const r = sessionId === void 0 ? db.prepare(q).get(this.projectKey, day) : db.prepare(q).get(this.projectKey, day, sessionId);
|
|
1840
|
-
return r;
|
|
1841
|
-
}
|
|
1842
|
-
account(db, sessionId, result) {
|
|
1843
|
-
const d = this.day(this.now());
|
|
1844
|
-
db.prepare("INSERT INTO maintenance_usage(project_key,day,session_id,calls,input_tokens,output_tokens,cost,wall_ms) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(project_key,day,session_id) DO UPDATE SET calls=calls+excluded.calls,input_tokens=input_tokens+excluded.input_tokens,output_tokens=output_tokens+excluded.output_tokens,cost=cost+excluded.cost,wall_ms=wall_ms+excluded.wall_ms").run(this.projectKey, d, sessionId, 1, result.inputTokens, result.outputTokens, result.cost, result.wallMs);
|
|
1845
|
-
}
|
|
1846
|
-
readJob(db, id) {
|
|
1847
|
-
const row = db.prepare("SELECT payload FROM maintenance_jobs WHERE job_id=? AND project_key=?").get(id, this.projectKey);
|
|
1848
|
-
if (!row) throw new Error("job not found");
|
|
1849
|
-
const job = parse(row.payload);
|
|
1850
|
-
if (job.projectKey !== this.projectKey) throw new Error("job project does not match ledger project");
|
|
1851
|
-
return job;
|
|
1852
|
-
}
|
|
1853
|
-
assertLease(current, expected) {
|
|
1854
|
-
if (current.ownerId !== expected.ownerId || current.leaseToken !== expected.leaseToken || current.state !== "running" || (current.leaseUntil ?? 0) < this.now()) throw new LcmRejection("lease fenced");
|
|
1855
|
-
}
|
|
1856
|
-
fenced(job, update) {
|
|
1857
|
-
return this.ledger.transaction((db) => {
|
|
1858
|
-
const old = this.readJob(db, job.jobId);
|
|
1859
|
-
this.assertLease(old, job);
|
|
1860
|
-
const out = update(old);
|
|
1861
|
-
db.prepare("UPDATE maintenance_jobs SET status=?,payload=?,updated_at=? WHERE job_id=? AND project_key=?").run(out.state, JSON.stringify(out), out.updatedAt, out.jobId, this.projectKey);
|
|
1862
|
-
return out;
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
};
|
|
1866
|
-
|
|
1867
|
-
// src/compaction/lcm-runtime.ts
|
|
1868
|
-
var SHUTDOWN_GRACE_MS = 500;
|
|
1869
|
-
var MAX_AUTO_REPAIR_ATTEMPTS = 5;
|
|
1870
|
-
var AUTO_REPAIR_DELAY_MS = 3e4;
|
|
1871
|
-
var AUTO_REPAIR_CLEAR_MS = 18e5;
|
|
1872
|
-
var MAX_REPAIR_LOG = 8;
|
|
1873
|
-
var CLAIMABLE_JOB_LIMIT = 256;
|
|
1874
|
-
var FAILED_JOB_WINDOW_MS = 24 * 60 * 60 * 1e3;
|
|
1875
|
-
var NODE_ADDRESS_LABEL = "address: ";
|
|
1876
|
-
var TAIL_DIGEST_MAX_BYTES = Math.floor(MAX_SUMMARY_BYTES * 0.2);
|
|
1877
|
-
var FRONTIER_REQUEST_BYTES = 4096;
|
|
1878
|
-
var MIN_SHARED_BLOCK_BYTES = 512;
|
|
1879
|
-
var ACTIVE_REQUEST_SHARE = 0.4;
|
|
1880
|
-
var UPGRADE_CANDIDATES = 256;
|
|
1881
|
-
var BLOCK_SEPARATOR = "\n\n";
|
|
1882
|
-
var WITHHELD_EXPAND_LABEL = "; expand: ";
|
|
1883
|
-
var withheldHeadline = (count) => `\u2026 withheld ${count} frontier node${count === 1 ? "" : "s"} that did not fit`;
|
|
1884
|
-
var withheldNotice = (nodeIds, budget) => {
|
|
1885
|
-
const headline = withheldHeadline(nodeIds.length);
|
|
1886
|
-
const addresses = nodeIds.map(lcmSummaryAddress);
|
|
1887
|
-
const line = (kept2, omitted) => `${headline}${WITHHELD_EXPAND_LABEL}${kept2.join(", ")}${omitted > 0 ? `, +${omitted} more` : ""}`;
|
|
1888
|
-
const kept = [];
|
|
1889
|
-
for (const address of addresses) {
|
|
1890
|
-
if (utf8Bytes(line([...kept, address], addresses.length - kept.length - 1)) > budget) break;
|
|
1891
|
-
kept.push(address);
|
|
1892
|
-
}
|
|
1893
|
-
return kept.length === 0 ? headline : line(kept, addresses.length - kept.length);
|
|
1894
|
-
};
|
|
1895
|
-
var clipOversized = (blocks, headBytes, footer, separator, requestBlock = "") => {
|
|
1896
|
-
let widest = 0;
|
|
1897
|
-
for (let index = 1; index < blocks.length; index += 1) if (headBytes[index] > headBytes[widest]) widest = index;
|
|
1898
|
-
const { node } = blocks[widest];
|
|
1899
|
-
const addressLine = `
|
|
1900
|
-
${NODE_ADDRESS_LABEL}${lcmSummaryAddress(node.nodeId)}`;
|
|
1901
|
-
const withheld = blocks.filter((_, index) => index !== widest).map((block) => block.node.nodeId);
|
|
1902
|
-
const requestBytes = requestBlock ? utf8Bytes(requestBlock) + separator : 0;
|
|
1903
|
-
const available = MAX_SUMMARY_BYTES - utf8Bytes(footer) - utf8Bytes(addressLine) - requestBytes;
|
|
1904
|
-
const notice = withheld.length === 0 ? "" : withheldNotice(withheld, Math.max(utf8Bytes(withheldHeadline(withheld.length)), Math.floor(available / 2)));
|
|
1905
|
-
const text = clipUtf8(node.text ?? "", available - (notice ? separator + utf8Bytes(notice) : 0));
|
|
1906
|
-
const head = text ? `${text}${addressLine}` : addressLine.slice(1);
|
|
1907
|
-
const parts = [...requestBlock ? [requestBlock] : [], head, ...notice ? [notice] : []];
|
|
1908
|
-
return `${parts.join(BLOCK_SEPARATOR)}${footer}`;
|
|
1909
|
-
};
|
|
1910
|
-
var renderAddressedFrontier = (frontier, requestLines = [], surround = {}) => {
|
|
1911
|
-
const blocks = frontier.filter((node) => Boolean(node.text)).map((node) => ({ node, head: `${node.text ?? ""}
|
|
1912
|
-
${NODE_ADDRESS_LABEL}${lcmSummaryAddress(node.nodeId)}` }));
|
|
1913
|
-
if (blocks.length === 0) return "";
|
|
1914
|
-
const leads = [requestLines.length > 0 ? `[Compaction Request]
|
|
1915
|
-
${requestLines.join("\n")}` : "", surround.lead ?? ""].filter((block) => block.length > 0);
|
|
1916
|
-
const trail = clipUtf8(surround.trail ?? "", TAIL_DIGEST_MAX_BYTES);
|
|
1917
|
-
const requestBlock = leads.join(BLOCK_SEPARATOR);
|
|
1918
|
-
const footer = `
|
|
1919
|
-
|
|
1920
|
-
${LCM_RECOVERY_POINTER}`;
|
|
1921
|
-
const separator = utf8Bytes(BLOCK_SEPARATOR);
|
|
1922
|
-
const footerBytes = utf8Bytes(footer) + (trail ? utf8Bytes(trail) + separator : 0);
|
|
1923
|
-
const requestBytes = requestBlock ? utf8Bytes(requestBlock) + separator : 0;
|
|
1924
|
-
const headBytes = blocks.map((block) => utf8Bytes(block.head));
|
|
1925
|
-
const floorFor = (kept2) => kept2 === blocks.length ? 0 : separator + utf8Bytes(withheldHeadline(blocks.length - kept2));
|
|
1926
|
-
const kept = [];
|
|
1927
|
-
const withheld = [];
|
|
1928
|
-
let body = requestBytes;
|
|
1929
|
-
for (let index = 0; index < blocks.length; index += 1) {
|
|
1930
|
-
const grown = body + headBytes[index] + (kept.length > 0 || requestBlock ? separator : 0);
|
|
1931
|
-
if (grown + footerBytes + floorFor(kept.length + 1) > MAX_SUMMARY_BYTES) {
|
|
1932
|
-
withheld.push(index);
|
|
1933
|
-
continue;
|
|
1934
|
-
}
|
|
1935
|
-
kept.push(index);
|
|
1936
|
-
body = grown;
|
|
1937
|
-
}
|
|
1938
|
-
if (withheld.length > 0) {
|
|
1939
|
-
const addressLines = blocks.map(({ node }) => `
|
|
1940
|
-
${NODE_ADDRESS_LABEL}${lcmSummaryAddress(node.nodeId)}`);
|
|
1941
|
-
let room2 = MAX_SUMMARY_BYTES - requestBytes - footerBytes - separator * (blocks.length - 1) - addressLines.reduce((total, line) => total + utf8Bytes(line), 0);
|
|
1942
|
-
const textBytes = blocks.map(({ node }) => utf8Bytes(node.text ?? ""));
|
|
1943
|
-
const budget = new Array(blocks.length).fill(0);
|
|
1944
|
-
let open = blocks.map((_unused, index) => index);
|
|
1945
|
-
while (open.length > 0 && room2 > 0) {
|
|
1946
|
-
const share = Math.floor(room2 / open.length);
|
|
1947
|
-
if (share < 1) break;
|
|
1948
|
-
const fitting = open.filter((index) => textBytes[index] <= share);
|
|
1949
|
-
if (fitting.length === 0) {
|
|
1950
|
-
for (const index of open) budget[index] = share;
|
|
1951
|
-
room2 -= share * open.length;
|
|
1952
|
-
break;
|
|
1953
|
-
}
|
|
1954
|
-
for (const index of fitting) {
|
|
1955
|
-
budget[index] = textBytes[index];
|
|
1956
|
-
room2 -= textBytes[index];
|
|
1957
|
-
}
|
|
1958
|
-
open = open.filter((index) => !fitting.includes(index));
|
|
1959
|
-
}
|
|
1960
|
-
if (budget.every((value, index) => value >= Math.min(textBytes[index], MIN_SHARED_BLOCK_BYTES))) {
|
|
1961
|
-
const shared = blocks.map(({ node }, index) => {
|
|
1962
|
-
const text = clipUtf8(node.text ?? "", budget[index]);
|
|
1963
|
-
return text ? `${text}${addressLines[index]}` : addressLines[index].slice(1);
|
|
1964
|
-
});
|
|
1965
|
-
const parts2 = [...requestBlock ? [requestBlock] : [], ...shared, ...trail ? [trail] : []];
|
|
1966
|
-
return `${parts2.join(BLOCK_SEPARATOR)}${footer}`;
|
|
1967
|
-
}
|
|
1968
|
-
}
|
|
1969
|
-
if (kept.length === 0) return clipOversized(blocks, headBytes, `${trail ? `${BLOCK_SEPARATOR}${trail}` : ""}${footer}`, separator, requestBlock);
|
|
1970
|
-
const room = MAX_SUMMARY_BYTES - body - footerBytes - (withheld.length === 0 ? 0 : separator);
|
|
1971
|
-
const notice = withheld.length === 0 ? "" : withheldNotice(withheld.map((index) => blocks[index].node.nodeId), Math.max(utf8Bytes(withheldHeadline(withheld.length)), Math.floor(room / 2)));
|
|
1972
|
-
const perNode = Math.max(0, Math.floor((room - utf8Bytes(notice)) / kept.length) - 1);
|
|
1973
|
-
const rendered = kept.map((index) => {
|
|
1974
|
-
const { node, head } = blocks[index];
|
|
1975
|
-
const addresses = node.sources.length > 0 ? renderLcmSourceAddresses(node.sources, perNode) : renderLcmChildAddresses(node.children, perNode);
|
|
1976
|
-
return addresses && utf8Bytes(addresses) <= perNode ? `${head}
|
|
1977
|
-
${addresses}` : head;
|
|
1978
|
-
});
|
|
1979
|
-
const parts = [...requestBlock ? [requestBlock] : [], ...rendered, ...notice ? [notice] : [], ...trail ? [trail] : []];
|
|
1980
|
-
return `${parts.join(BLOCK_SEPARATOR)}${footer}`;
|
|
1981
|
-
};
|
|
1982
|
-
var LcmRuntime = class {
|
|
1983
|
-
ledger;
|
|
1984
|
-
maintenance;
|
|
1985
|
-
context;
|
|
1986
|
-
resolveOptions;
|
|
1987
|
-
abort = new AbortController();
|
|
1988
|
-
writePending = Promise.resolve();
|
|
1989
|
-
maintenancePending = Promise.resolve();
|
|
1990
|
-
maintenanceRunning = false;
|
|
1991
|
-
maintenanceQueued = false;
|
|
1992
|
-
closed = false;
|
|
1993
|
-
dirty = false;
|
|
1994
|
-
degradedError;
|
|
1995
|
-
activeSources = /* @__PURE__ */ new Set();
|
|
1996
|
-
activeSessionId;
|
|
1997
|
-
persisted = /* @__PURE__ */ new WeakMap();
|
|
1998
|
-
persistedSessionId;
|
|
1999
|
-
lastReconciliation;
|
|
2000
|
-
reconciled = false;
|
|
2001
|
-
/** Subagent sessions share the parent's ledger; only the top-level session migrates and maintains it. */
|
|
2002
|
-
owner;
|
|
2003
|
-
constructor(context, options = {}) {
|
|
2004
|
-
this.context = context;
|
|
2005
|
-
const agent = context.agent;
|
|
2006
|
-
this.owner = agent?.kind !== "sub" && (agent?.depth ?? 0) === 0;
|
|
2007
|
-
this.resolveOptions = typeof options === "function" ? options : () => options;
|
|
2008
|
-
const initial = this.resolveOptions();
|
|
2009
|
-
const recorded = context.sessionManager.getRecordedCwd?.();
|
|
2010
|
-
const liveCwd = recorded || context.cwd;
|
|
2011
|
-
const project = canonicalProjectIdentity({ liveCwd });
|
|
2012
|
-
const ledgerOptions = initial.rootDir === void 0 ? { project: { liveCwd: project.canonicalPath ?? liveCwd } } : { rootDir: initial.rootDir, project: { liveCwd: project.canonicalPath ?? liveCwd } };
|
|
2013
|
-
this.ledger = new LcmLedger(ledgerOptions);
|
|
2014
|
-
this.maintenance = new LcmMaintenance(this.ledger, {
|
|
2015
|
-
...initial,
|
|
2016
|
-
...initial.lcmMaxInputChars === void 0 ? {} : { maxInputChars: initial.lcmMaxInputChars },
|
|
2017
|
-
...initial.lcmMaxOutputChars === void 0 ? {} : { maxOutputChars: initial.lcmMaxOutputChars },
|
|
2018
|
-
...initial.modelTimeoutSeconds === void 0 ? {} : { modelTimeoutMs: initial.modelTimeoutSeconds * 1e3 },
|
|
2019
|
-
maxConcurrentJobs: () => this.resolveOptions().maintenanceConcurrency ?? DEFAULT_MAINTENANCE_CONCURRENCY,
|
|
2020
|
-
budget: {
|
|
2021
|
-
...initial.maxDailyModelCalls ? { calls: initial.maxDailyModelCalls } : {},
|
|
2022
|
-
...initial.maxSessionModelCalls ? { sessionCalls: initial.maxSessionModelCalls } : {},
|
|
2023
|
-
...initial.maxDailyModelSeconds ? { wallMs: initial.maxDailyModelSeconds * 1e3 } : {}
|
|
2024
|
-
}
|
|
2025
|
-
});
|
|
2026
|
-
}
|
|
2027
|
-
get ready() {
|
|
2028
|
-
return this.owner && this.reconciled && this.ledger.startupChecksComplete;
|
|
2029
|
-
}
|
|
2030
|
-
open() {
|
|
2031
|
-
return this.owner ? this.ledger.runStartupChecks() : Promise.resolve();
|
|
2032
|
-
}
|
|
2033
|
-
slice() {
|
|
2034
|
-
return new EventLoopSlice(this.options.sliceMs);
|
|
2035
|
-
}
|
|
2036
|
-
get options() {
|
|
2037
|
-
return this.resolveOptions();
|
|
2038
|
-
}
|
|
2039
|
-
get projectKey() {
|
|
2040
|
-
return this.ledger.project.key;
|
|
2041
|
-
}
|
|
2042
|
-
get signal() {
|
|
2043
|
-
return this.abort.signal;
|
|
2044
|
-
}
|
|
2045
|
-
get status() {
|
|
2046
|
-
return this.degradedMessage() === void 0 ? "healthy" : "degraded";
|
|
2047
|
-
}
|
|
2048
|
-
get error() {
|
|
2049
|
-
return this.degradedError;
|
|
2050
|
-
}
|
|
2051
|
-
get reconciliation() {
|
|
2052
|
-
return this.lastReconciliation;
|
|
2053
|
-
}
|
|
2054
|
-
degradedMessage() {
|
|
2055
|
-
const faults = [];
|
|
2056
|
-
if (this.degradedError !== void 0) faults.push(String(this.degradedError instanceof Error ? this.degradedError.message : this.degradedError));
|
|
2057
|
-
const errors = this.lastReconciliation?.errors ?? 0;
|
|
2058
|
-
if (errors > 0) faults.push(`LCM session reconciliation reported ${errors} error(s)`);
|
|
2059
|
-
const reasons = this.lastReconciliation?.reasons ?? [];
|
|
2060
|
-
if (reasons.length > 0) faults.push(`LCM session reconciliation dropped ${reasons.join("; ")}`);
|
|
2061
|
-
const failed = this.recentlyFailedJobs();
|
|
2062
|
-
if (failed > 0) faults.push(`LCM maintenance left ${failed} job${failed === 1 ? "" : "s"} failed`);
|
|
2063
|
-
return faults.length === 0 ? void 0 : faults.join(" \xB7 ");
|
|
2064
|
-
}
|
|
2065
|
-
recentlyFailedJobs() {
|
|
2066
|
-
try {
|
|
2067
|
-
return this.maintenance.countJobs("failed", Date.now() - FAILED_JOB_WINDOW_MS);
|
|
2068
|
-
} catch {
|
|
2069
|
-
return 0;
|
|
2070
|
-
}
|
|
2071
|
-
}
|
|
2072
|
-
markDirty() {
|
|
2073
|
-
this.dirty = true;
|
|
2074
|
-
}
|
|
2075
|
-
enqueueWrite(operation) {
|
|
2076
|
-
const run = this.writePending.then(operation);
|
|
2077
|
-
this.writePending = run.catch((error) => {
|
|
2078
|
-
this.degradedError = error;
|
|
2079
|
-
});
|
|
2080
|
-
return run;
|
|
2081
|
-
}
|
|
2082
|
-
refreshActiveSources(sessionId, entries) {
|
|
2083
|
-
const ids = new Set(entries.map((entry) => entry.id));
|
|
2084
|
-
const latest = /* @__PURE__ */ new Map();
|
|
2085
|
-
for (const entry of this.ledger.readRaw(this.projectKey, sessionId)) {
|
|
2086
|
-
if (!ids.has(entry.entryId)) continue;
|
|
2087
|
-
const previous = latest.get(entry.entryId);
|
|
2088
|
-
if (!previous || previous.revision < entry.revision) latest.set(entry.entryId, entry);
|
|
2089
|
-
}
|
|
2090
|
-
this.activeSources = new Set(
|
|
2091
|
-
[...latest.values()].map((entry) => this.sourceKey(entry))
|
|
2092
|
-
);
|
|
2093
|
-
this.activeSessionId = sessionId;
|
|
2094
|
-
this.invalidateFrontier();
|
|
2095
|
-
}
|
|
2096
|
-
invalidateFrontier() {
|
|
2097
|
-
this.frontierCache = void 0;
|
|
2098
|
-
}
|
|
2099
|
-
reconcileSelectedSession() {
|
|
2100
|
-
if (this.closed || !this.owner) return Promise.resolve();
|
|
2101
|
-
return this.enqueueWrite(async () => {
|
|
2102
|
-
try {
|
|
2103
|
-
await this.reconcileSessionFile();
|
|
2104
|
-
} finally {
|
|
2105
|
-
this.reconciled = true;
|
|
2106
|
-
}
|
|
2107
|
-
});
|
|
2108
|
-
}
|
|
2109
|
-
async reconcileSessionFile() {
|
|
2110
|
-
const getSessionFile = this.context.sessionManager.getSessionFile;
|
|
2111
|
-
if (typeof getSessionFile !== "function") return;
|
|
2112
|
-
const sessionFile = getSessionFile.call(this.context.sessionManager);
|
|
2113
|
-
if (!sessionFile) return;
|
|
2114
|
-
const recorded = this.context.sessionManager.getRecordedCwd?.();
|
|
2115
|
-
const cwd = recorded || this.context.cwd;
|
|
2116
|
-
const result = await reconcileSession({
|
|
2117
|
-
agentDir: this.options.rootDir ?? process.env.PI_CODING_AGENT_DIR ?? `${process.env.HOME ?? "."}/.omp/agent`,
|
|
2118
|
-
ledger: this.ledger,
|
|
2119
|
-
files: [sessionFile],
|
|
2120
|
-
liveCwd: cwd,
|
|
2121
|
-
projectCwd: cwd,
|
|
2122
|
-
apply: true,
|
|
2123
|
-
slice: this.slice(),
|
|
2124
|
-
signal: this.signal
|
|
2125
|
-
});
|
|
2126
|
-
if (this.closed) return;
|
|
2127
|
-
this.lastReconciliation = {
|
|
2128
|
-
degraded: result.degraded,
|
|
2129
|
-
errors: result.counts.errors,
|
|
2130
|
-
raced: result.counts.raced,
|
|
2131
|
-
absent: result.counts.absent,
|
|
2132
|
-
drops: result.drops,
|
|
2133
|
-
reasons: migrationDropReasons(result.drops)
|
|
2134
|
-
};
|
|
2135
|
-
const sessionId = this.context.sessionManager.getSessionId();
|
|
2136
|
-
this.refreshActiveSources(sessionId, this.context.sessionManager.getBranch());
|
|
2137
|
-
}
|
|
2138
|
-
/** Appends only the entries this session has not stored yet; the rest are already addressed. */
|
|
2139
|
-
readback() {
|
|
2140
|
-
if (this.closed || !this.owner) return Promise.resolve();
|
|
2141
|
-
return this.enqueueWrite(async () => {
|
|
2142
|
-
if (this.closed) return;
|
|
2143
|
-
const slice = this.slice();
|
|
2144
|
-
const entries = this.context.sessionManager.getBranch();
|
|
2145
|
-
const sessionId = this.context.sessionManager.getSessionId();
|
|
2146
|
-
const recorded = this.context.sessionManager.getRecordedCwd?.();
|
|
2147
|
-
if (this.persistedSessionId !== sessionId) {
|
|
2148
|
-
this.persisted = /* @__PURE__ */ new WeakMap();
|
|
2149
|
-
this.persistedSessionId = sessionId;
|
|
2150
|
-
}
|
|
2151
|
-
const active = /* @__PURE__ */ new Set();
|
|
2152
|
-
const pending = [];
|
|
2153
|
-
for (const entry of entries) {
|
|
2154
|
-
if (slice.due) await slice.yield();
|
|
2155
|
-
const payloadJson = canonicalLcmPayload(entry);
|
|
2156
|
-
const contentHash = hash(canonicalLcmEntry(entry));
|
|
2157
|
-
const known = this.persisted.get(entry);
|
|
2158
|
-
if (known?.contentHash === contentHash) active.add(known.key);
|
|
2159
|
-
else pending.push({ entry, payloadJson, contentHash });
|
|
2160
|
-
}
|
|
2161
|
-
for (let next = 0; next < pending.length; ) {
|
|
2162
|
-
if (slice.due) await slice.yield();
|
|
2163
|
-
if (this.closed) return;
|
|
2164
|
-
const first = next;
|
|
2165
|
-
this.ledger.transaction(() => {
|
|
2166
|
-
for (; next < pending.length && (next === first || !slice.due); next += 1) {
|
|
2167
|
-
const { entry, payloadJson, contentHash } = pending[next];
|
|
2168
|
-
const message = entry.type === "message" ? entry.message : void 0;
|
|
2169
|
-
const stored = this.ledger.appendRaw({
|
|
2170
|
-
projectKey: this.projectKey,
|
|
2171
|
-
sessionId,
|
|
2172
|
-
entryId: entry.id,
|
|
2173
|
-
role: message?.role ?? entry.type,
|
|
2174
|
-
content: message ? JSON.stringify(message.content ?? "") : payloadJson,
|
|
2175
|
-
payloadJson,
|
|
2176
|
-
parentEntryId: entry.parentId ?? null,
|
|
2177
|
-
...recorded || this.context.cwd ? { recordedCwd: recorded || this.context.cwd } : {}
|
|
2178
|
-
});
|
|
2179
|
-
const key = this.sourceKey(stored);
|
|
2180
|
-
this.persisted.set(entry, { key, contentHash });
|
|
2181
|
-
active.add(key);
|
|
2182
|
-
}
|
|
2183
|
-
});
|
|
2184
|
-
}
|
|
2185
|
-
this.activeSources = active;
|
|
2186
|
-
this.activeSessionId = sessionId;
|
|
2187
|
-
this.invalidateFrontier();
|
|
2188
|
-
this.dirty = false;
|
|
2189
|
-
this.degradedError = void 0;
|
|
2190
|
-
});
|
|
2191
|
-
}
|
|
2192
|
-
/** Mid-turn sync: the write path already records its own failure. */
|
|
2193
|
-
syncEntries() {
|
|
2194
|
-
if (this.closed) return;
|
|
2195
|
-
void this.readback().catch(() => {
|
|
2196
|
-
});
|
|
2197
|
-
}
|
|
2198
|
-
async syncAndSchedule() {
|
|
2199
|
-
if (this.closed || !this.owner) return;
|
|
2200
|
-
const sessionId = this.context.sessionManager.getSessionId();
|
|
2201
|
-
if (this.dirty || !this.activeSessionId || this.activeSessionId !== sessionId || this.activeSources.size === 0) {
|
|
2202
|
-
await this.readback();
|
|
2203
|
-
}
|
|
2204
|
-
if ((this.lastReconciliation?.absent ?? 0) > 0 && this.sessionFilePresent()) await this.reconcileSelectedSession();
|
|
2205
|
-
this.reclaimExpiredLeases();
|
|
2206
|
-
await this.autoRepair();
|
|
2207
|
-
if (this.maintenanceTrigger() !== void 0) this.scheduleMaintenance();
|
|
2208
|
-
}
|
|
2209
|
-
/** One repair per beat, budgeted per fault class in the ledger so a restart resumes the budget. */
|
|
2210
|
-
async autoRepair() {
|
|
2211
|
-
if (this.closed) return void 0;
|
|
2212
|
-
let ladder;
|
|
2213
|
-
let checks;
|
|
2214
|
-
try {
|
|
2215
|
-
ladder = this.ledger.readRepairLadder();
|
|
2216
|
-
if (ladder.size === 0 && this.degradedMessage() === void 0) return void 0;
|
|
2217
|
-
checks = lcmChecks(this.diagnostics());
|
|
2218
|
-
} catch (error) {
|
|
2219
|
-
this.degradedError = error;
|
|
2220
|
-
return void 0;
|
|
2221
|
-
}
|
|
2222
|
-
const now = Date.now();
|
|
2223
|
-
const actionable = /* @__PURE__ */ new Map();
|
|
2224
|
-
for (const check of checks) {
|
|
2225
|
-
const repair = check.repair;
|
|
2226
|
-
if (!repair || check.severity !== "warn" && check.severity !== "fail") continue;
|
|
2227
|
-
actionable.set(check.id, { check, repair });
|
|
2228
|
-
}
|
|
2229
|
-
for (const [fault, state] of ladder) {
|
|
2230
|
-
if (!actionable.has(fault) && now - state.updatedAt >= AUTO_REPAIR_CLEAR_MS) this.ledger.clearRepairLadder(fault);
|
|
2231
|
-
}
|
|
2232
|
-
const eligible = [...actionable.values()].filter(({ check }) => {
|
|
2233
|
-
const state = ladder.get(check.id);
|
|
2234
|
-
return !state || state.attempts < MAX_AUTO_REPAIR_ATTEMPTS && state.nextAt <= now;
|
|
2235
|
-
});
|
|
2236
|
-
const target = eligible.find(({ check }) => check.severity === "fail") ?? eligible[0];
|
|
2237
|
-
if (!target) return void 0;
|
|
2238
|
-
const outcome = await this.repair(target.repair);
|
|
2239
|
-
const attempts = (ladder.get(target.check.id)?.attempts ?? 0) + 1;
|
|
2240
|
-
this.ledger.writeRepairLadder(target.check.id, attempts, now + AUTO_REPAIR_DELAY_MS * 2 ** (attempts - 1), outcome.detail);
|
|
2241
|
-
return outcome;
|
|
2242
|
-
}
|
|
2243
|
-
/** Reclaims ledgers whose project directory is gone; bounded to one sweep a day. */
|
|
2244
|
-
sweepLedgers() {
|
|
2245
|
-
if (this.closed || !this.owner) return { removed: [], bytes: 0, skipped: true };
|
|
2246
|
-
try {
|
|
2247
|
-
return sweepLedgers(this.options.rootDir ?? defaultLedgerRoot(), { keepKey: this.projectKey });
|
|
2248
|
-
} catch {
|
|
2249
|
-
return { removed: [], bytes: 0, skipped: true };
|
|
2250
|
-
}
|
|
2251
|
-
}
|
|
2252
|
-
reclaimExpiredLeases() {
|
|
2253
|
-
if (this.closed) return 0;
|
|
2254
|
-
try {
|
|
2255
|
-
return this.maintenance.sweepExpiredLeases().length + this.maintenance.recoverLegacyContentionRetirements().length;
|
|
2256
|
-
} catch (error) {
|
|
2257
|
-
this.degradedError = error;
|
|
2258
|
-
return 0;
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
maintenanceTrigger() {
|
|
2262
|
-
const sessionId = this.activeSessionId;
|
|
2263
|
-
if (this.closed || !sessionId || this.activeSources.size === 0) return void 0;
|
|
2264
|
-
try {
|
|
2265
|
-
if (!this.maintenance.withinBudget(sessionId)) return void 0;
|
|
2266
|
-
if (this.maintenanceOccupancyReached()) return "occupancy";
|
|
2267
|
-
if (this.actionableJobs(sessionId, 1).length > 0) return "jobs";
|
|
2268
|
-
const { active, covered } = this.coverage();
|
|
2269
|
-
return active - covered >= Math.max(1, this.options.maxLeafEntries ?? DEFAULT_LEAF_ENTRIES) ? "backlog" : void 0;
|
|
2270
|
-
} catch (error) {
|
|
2271
|
-
this.degradedError = error;
|
|
2272
|
-
return void 0;
|
|
2273
|
-
}
|
|
2274
|
-
}
|
|
2275
|
-
/** Fails open: an unreadable occupancy never disables maintenance. */
|
|
2276
|
-
maintenanceOccupancyReached() {
|
|
2277
|
-
const ratio = this.options.softThresholdRatio;
|
|
2278
|
-
if (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio <= 0) return true;
|
|
2279
|
-
let usage;
|
|
2280
|
-
try {
|
|
2281
|
-
usage = this.context.getContextUsage?.();
|
|
2282
|
-
} catch {
|
|
2283
|
-
return true;
|
|
2284
|
-
}
|
|
2285
|
-
const percent = usage?.percent;
|
|
2286
|
-
if (typeof percent !== "number" || !Number.isFinite(percent)) return true;
|
|
2287
|
-
return percent / 100 >= ratio;
|
|
2288
|
-
}
|
|
2289
|
-
maintain() {
|
|
2290
|
-
return this.syncAndSchedule();
|
|
2291
|
-
}
|
|
2292
|
-
scheduleMaintenance() {
|
|
2293
|
-
if (this.closed || !this.owner) return;
|
|
2294
|
-
if (this.maintenanceRunning) {
|
|
2295
|
-
this.maintenanceQueued = true;
|
|
2296
|
-
return;
|
|
2297
|
-
}
|
|
2298
|
-
this.maintenanceRunning = true;
|
|
2299
|
-
const run = this.maintenancePending.then(async () => {
|
|
2300
|
-
await this.runMaintenance();
|
|
2301
|
-
while (this.maintenanceQueued && !this.closed) {
|
|
2302
|
-
this.maintenanceQueued = false;
|
|
2303
|
-
await this.runMaintenance();
|
|
2304
|
-
}
|
|
2305
|
-
}).finally(() => {
|
|
2306
|
-
this.maintenanceRunning = false;
|
|
2307
|
-
if (!this.maintenanceQueued || this.closed) {
|
|
2308
|
-
this.maintenanceQueued = false;
|
|
2309
|
-
return;
|
|
2310
|
-
}
|
|
2311
|
-
this.maintenanceQueued = false;
|
|
2312
|
-
this.scheduleMaintenance();
|
|
2313
|
-
});
|
|
2314
|
-
this.maintenancePending = run.catch((error) => {
|
|
2315
|
-
this.degradedError = error;
|
|
2316
|
-
});
|
|
2317
|
-
}
|
|
2318
|
-
actionableJobs(sessionId, limit) {
|
|
2319
|
-
const found = [];
|
|
2320
|
-
if (limit <= 0) return found;
|
|
2321
|
-
for (const job of this.maintenance.claimableJobs(sessionId, CLAIMABLE_JOB_LIMIT)) {
|
|
2322
|
-
const node = this.maintenance.getNode(job.nodeId);
|
|
2323
|
-
if (!node || node.sessionId !== sessionId) continue;
|
|
2324
|
-
if (!node.sources.every((source) => this.activeSources.has(this.sourceKey(source)))) continue;
|
|
2325
|
-
found.push({ job, node });
|
|
2326
|
-
if (found.length >= limit) break;
|
|
2327
|
-
}
|
|
2328
|
-
return found;
|
|
2329
|
-
}
|
|
2330
|
-
async runMaintenance() {
|
|
2331
|
-
const sessionId = this.activeSessionId;
|
|
2332
|
-
if (this.closed || !sessionId || this.activeSources.size === 0) return;
|
|
2333
|
-
try {
|
|
2334
|
-
await this.runMaintenancePasses(sessionId);
|
|
2335
|
-
} finally {
|
|
2336
|
-
this.invalidateFrontier();
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
async runMaintenancePasses(sessionId) {
|
|
2340
|
-
const wantsModel = this.options.modelSummaries !== false;
|
|
2341
|
-
let model;
|
|
2342
|
-
try {
|
|
2343
|
-
if (!wantsModel) throw new Error("model summaries are disabled by configuration");
|
|
2344
|
-
model = new LcmModelAdapter(this.context, this.options.summaryModel, true, {
|
|
2345
|
-
...this.options.lcmMaxInputChars === void 0 ? {} : { maxInputChars: this.options.lcmMaxInputChars },
|
|
2346
|
-
...this.options.lcmMaxOutputTokens === void 0 ? {} : { maxOutputTokens: this.options.lcmMaxOutputTokens },
|
|
2347
|
-
...this.options.lcmMaxOutputChars === void 0 ? {} : { maxOutputChars: this.options.lcmMaxOutputChars }
|
|
2348
|
-
});
|
|
2349
|
-
} catch (error) {
|
|
2350
|
-
this.degradedError = error;
|
|
2351
|
-
model = { modelHash: "unavailable", generate: async () => {
|
|
2352
|
-
throw error instanceof Error ? error : new Error(String(error));
|
|
2353
|
-
} };
|
|
2354
|
-
}
|
|
2355
|
-
const fanIn = Math.max(2, this.options.maxCondenseChildren ?? 4);
|
|
2356
|
-
const passes = Math.max(1, this.options.maxMaintenancePasses ?? 4);
|
|
2357
|
-
const runDeadline = Date.now() + Math.max(1, this.options.maintenanceRunSeconds ?? 60) * 1e3;
|
|
2358
|
-
const slice = this.slice();
|
|
2359
|
-
await slice.pause();
|
|
2360
|
-
if (this.closed) return;
|
|
2361
|
-
const raw = (await this.ledger.readSessionRaw(sessionId, slice)).filter(
|
|
2362
|
-
(entry) => this.activeSources.has(this.sourceKey(entry))
|
|
2363
|
-
);
|
|
2364
|
-
if (this.closed) return;
|
|
2365
|
-
const inputFor = (node) => {
|
|
2366
|
-
if (node.kind === "condensed") return node.children.map((id) => this.maintenance.getNode(id)?.text ?? "").filter(Boolean).join("\n\n");
|
|
2367
|
-
return node.sources.map((source) => {
|
|
2368
|
-
const entry = this.ledger.readRawEntry(this.projectKey, source.sessionId, source.entryId, source.revision);
|
|
2369
|
-
if (!entry || entry.payloadHash !== source.payloadHash) throw new Error("stale source");
|
|
2370
|
-
return entry.payloadJson;
|
|
2371
|
-
}).join("\n");
|
|
2372
|
-
};
|
|
2373
|
-
const runJob = async (job, node) => {
|
|
2374
|
-
try {
|
|
2375
|
-
const input = inputFor(node);
|
|
2376
|
-
await this.maintenance.run(job, model, input, this.signal);
|
|
2377
|
-
return "done";
|
|
2378
|
-
} catch (error) {
|
|
2379
|
-
if (isLcmCapacityRejection(error)) return "capacity";
|
|
2380
|
-
if (isLcmRejection(error)) return "rejected";
|
|
2381
|
-
this.degradedError = error;
|
|
2382
|
-
try {
|
|
2383
|
-
this.maintenance.recordFailure(job, error);
|
|
2384
|
-
} catch {
|
|
2385
|
-
}
|
|
2386
|
-
return "done";
|
|
2387
|
-
}
|
|
2388
|
-
};
|
|
2389
|
-
const dispatch = async (items) => {
|
|
2390
|
-
let next = 0;
|
|
2391
|
-
const worker = async (slot) => {
|
|
2392
|
-
while (!this.closed && Date.now() < runDeadline && slot < this.maintenance.concurrencyLimit) {
|
|
2393
|
-
await slice.pause();
|
|
2394
|
-
if (this.closed) return;
|
|
2395
|
-
const item = items[next];
|
|
2396
|
-
if (!item) return;
|
|
2397
|
-
next += 1;
|
|
2398
|
-
if (await runJob(item.job, item.node) === "capacity") return;
|
|
2399
|
-
}
|
|
2400
|
-
};
|
|
2401
|
-
await Promise.all(Array.from({ length: Math.min(this.maintenance.concurrencyLimit, items.length) }, (_unused, slot) => worker(slot)));
|
|
2402
|
-
};
|
|
2403
|
-
this.reclaimExpiredLeases();
|
|
2404
|
-
const inputBound = this.options.lcmMaxInputChars ?? DEFAULT_LCM_MAX_INPUT_CHARS;
|
|
2405
|
-
const fitsBound = (node) => {
|
|
2406
|
-
if (node.sources.length > (this.options.maxLeafEntries ?? DEFAULT_LEAF_ENTRIES) * fanIn) return false;
|
|
2407
|
-
try {
|
|
2408
|
-
return utf8Bytes(inputFor(node)) <= inputBound;
|
|
2409
|
-
} catch {
|
|
2410
|
-
return false;
|
|
2411
|
-
}
|
|
2412
|
-
};
|
|
2413
|
-
for (let pass = 0; pass < passes && !this.closed && Date.now() < runDeadline; pass += 1) {
|
|
2414
|
-
const leaves = [];
|
|
2415
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2416
|
-
while (leaves.length < this.maintenance.concurrencyLimit) {
|
|
2417
|
-
const nodes2 = await this.maintenance.loadNodes(slice);
|
|
2418
|
-
await slice.pause();
|
|
2419
|
-
if (this.closed) return;
|
|
2420
|
-
const rows = this.maintenance.selectLeaf(raw, this.activeSources, nodes2);
|
|
2421
|
-
if (rows.length === 0) break;
|
|
2422
|
-
const created = this.maintenance.createLeaf(rows);
|
|
2423
|
-
const node = created ? this.maintenance.getNode(created.nodeId) : void 0;
|
|
2424
|
-
if (!node || seen.has(node.nodeId)) break;
|
|
2425
|
-
seen.add(node.nodeId);
|
|
2426
|
-
leaves.push(node);
|
|
2427
|
-
}
|
|
2428
|
-
const batch = [];
|
|
2429
|
-
const queued = /* @__PURE__ */ new Set();
|
|
2430
|
-
for (const leaf of leaves) {
|
|
2431
|
-
if (leaf.state !== "pending") continue;
|
|
2432
|
-
const job = this.maintenance.jobForNode(leaf.nodeId);
|
|
2433
|
-
if (job && this.maintenance.isClaimable(job)) {
|
|
2434
|
-
batch.push({ job, node: leaf });
|
|
2435
|
-
queued.add(job.jobId);
|
|
2436
|
-
}
|
|
2437
|
-
}
|
|
2438
|
-
await slice.pause();
|
|
2439
|
-
if (this.closed) return;
|
|
2440
|
-
const pending = this.actionableJobs(sessionId, passes);
|
|
2441
|
-
for (const item of pending) if (!queued.has(item.job.jobId)) {
|
|
2442
|
-
queued.add(item.job.jobId);
|
|
2443
|
-
batch.push(item);
|
|
2444
|
-
}
|
|
2445
|
-
await dispatch(batch);
|
|
2446
|
-
const nodes = await this.maintenance.loadNodes(slice);
|
|
2447
|
-
await slice.pause();
|
|
2448
|
-
if (this.closed) return;
|
|
2449
|
-
const children = this.maintenance.selectCondensation(sessionId, this.activeSources, nodes);
|
|
2450
|
-
if (children.length >= fanIn) {
|
|
2451
|
-
const node = this.maintenance.createCondensed(children);
|
|
2452
|
-
if (node) {
|
|
2453
|
-
const job = this.maintenance.jobForNode(node.nodeId);
|
|
2454
|
-
if (job && this.maintenance.isClaimable(job)) await runJob(job, node);
|
|
2455
|
-
}
|
|
2456
|
-
}
|
|
2457
|
-
if (leaves.length === 0 && pending.length === 0 && children.length < fanIn) {
|
|
2458
|
-
const nodes2 = await this.maintenance.loadNodes(slice);
|
|
2459
|
-
await slice.pause();
|
|
2460
|
-
if (this.closed) return;
|
|
2461
|
-
const upgrade = this.maintenance.selectUpgrades(sessionId, this.activeSources, UPGRADE_CANDIDATES, nodes2).find(fitsBound);
|
|
2462
|
-
if (!upgrade) break;
|
|
2463
|
-
const job = this.maintenance.reopen(upgrade.nodeId);
|
|
2464
|
-
await runJob(job, upgrade);
|
|
2465
|
-
if (this.maintenance.getNode(upgrade.nodeId)?.modelHash !== "emergency") {
|
|
2466
|
-
for (const ancestor of this.maintenance.ancestorsOf(upgrade.nodeId)) {
|
|
2467
|
-
const node = this.maintenance.getNode(ancestor);
|
|
2468
|
-
if (node?.state === "ready") this.maintenance.reopen(ancestor, true);
|
|
2469
|
-
}
|
|
2470
|
-
}
|
|
2471
|
-
continue;
|
|
2472
|
-
}
|
|
2473
|
-
}
|
|
2474
|
-
}
|
|
2475
|
-
compact(input) {
|
|
2476
|
-
const instructions = decodeCompactionInstructions(input.customInstructions);
|
|
2477
|
-
const requestLines = instructions.ok ? instructions.requestLines : [];
|
|
2478
|
-
const persistedEntries = /* @__PURE__ */ new Map();
|
|
2479
|
-
this.ledger.transaction(() => {
|
|
2480
|
-
for (const entry of input.branchEntries) {
|
|
2481
|
-
const message = entry.type === "message" ? entry.message : void 0;
|
|
2482
|
-
const payloadJson = canonicalLcmPayload(entry);
|
|
2483
|
-
const stored = this.ledger.appendRaw({
|
|
2484
|
-
projectKey: this.projectKey,
|
|
2485
|
-
sessionId: input.sessionId,
|
|
2486
|
-
entryId: entry.id,
|
|
2487
|
-
role: message?.role ?? entry.type,
|
|
2488
|
-
content: message ? JSON.stringify(message.content ?? "") : payloadJson,
|
|
2489
|
-
payloadJson,
|
|
2490
|
-
parentEntryId: entry.parentId ?? null
|
|
2491
|
-
});
|
|
2492
|
-
persistedEntries.set(entry.id, stored);
|
|
2493
|
-
}
|
|
2494
|
-
});
|
|
2495
|
-
this.invalidateFrontier();
|
|
2496
|
-
const firstKeptIndex = input.firstKeptEntryId ? input.branchEntries.findIndex((entry) => entry.id === input.firstKeptEntryId) : input.branchEntries.length;
|
|
2497
|
-
const sourceEntries = input.branchEntries.slice(0, firstKeptIndex < 0 ? input.branchEntries.length : firstKeptIndex);
|
|
2498
|
-
const selectedStored = sourceEntries.map((entry) => {
|
|
2499
|
-
const stored = persistedEntries.get(entry.id);
|
|
2500
|
-
if (!stored) throw new Error("compaction source was not persisted");
|
|
2501
|
-
return stored;
|
|
2502
|
-
});
|
|
2503
|
-
const activeSources = new Set(selectedStored.map((entry) => this.sourceKey(entry)));
|
|
2504
|
-
const frontier = this.maintenance.getFrontier(input.sessionId, activeSources);
|
|
2505
|
-
const coveredSources = new Set(frontier.flatMap((node) => node.sources.map((source) => this.sourceKey(source))));
|
|
2506
|
-
const keptEntry = firstKeptIndex >= 0 ? input.branchEntries[firstKeptIndex] : void 0;
|
|
2507
|
-
const keptRole = keptEntry?.type === "message" ? keptEntry.message.role : void 0;
|
|
2508
|
-
const splitTurn = input.isSplitTurn ?? keptRole !== "user";
|
|
2509
|
-
const requestFor = (maxBytes) => splitTurn ? activeRequestBlock(sourceEntries, selectedStored, maxBytes) : "";
|
|
2510
|
-
const instructionDetails = instructions.ok && (instructions.requestLines.length > 0 || instructions.policy.preserveCount > 0) ? { instructionPolicy: instructions.policy } : void 0;
|
|
2511
|
-
const uncovered = selectedStored.flatMap((stored, index) => coveredSources.has(this.sourceKey(stored)) ? [] : [index]);
|
|
2512
|
-
if (uncovered.length === 0) {
|
|
2513
|
-
const summary = renderAddressedFrontier(frontier, requestLines, { lead: requestFor(FRONTIER_REQUEST_BYTES) });
|
|
2514
|
-
if (summary) {
|
|
2515
|
-
return {
|
|
2516
|
-
summary,
|
|
2517
|
-
firstKeptEntryId: input.firstKeptEntryId,
|
|
2518
|
-
tokensBefore: input.tokensBefore,
|
|
2519
|
-
source: "ready-frontier",
|
|
2520
|
-
...instructionDetails ? { details: instructionDetails } : {}
|
|
2521
|
-
};
|
|
2522
|
-
}
|
|
2523
|
-
}
|
|
2524
|
-
if (selectedStored.length === 0) throw new Error("LCM emergency fallback has no persisted sources");
|
|
2525
|
-
const tailEntries = uncovered.length > 0 ? uncovered.map((index) => sourceEntries[index]) : sourceEntries;
|
|
2526
|
-
const tailStored = uncovered.length > 0 ? uncovered.map((index) => selectedStored[index]) : selectedStored;
|
|
2527
|
-
const outputBound = this.options.lcmMaxOutputChars ?? 4096;
|
|
2528
|
-
const nodeTextFor = (entries, stored) => {
|
|
2529
|
-
const digest = tailDigest(entries, stored, Math.min(TAIL_DIGEST_MAX_BYTES, outputBound));
|
|
2530
|
-
if (digest) return digest;
|
|
2531
|
-
const payloads = entries.map((entry) => canonicalLcmPayload(entry)).join("\n");
|
|
2532
|
-
return emergencyReduce(payloads, outputBound, stored.map((entry) => ({ sessionId: entry.sessionId, entryId: entry.entryId, revision: entry.revision, payloadHash: entry.payloadHash })), requestLines);
|
|
2533
|
-
};
|
|
2534
|
-
const fallback = nodeTextFor(tailEntries, tailStored);
|
|
2535
|
-
const compose = (nodeText) => {
|
|
2536
|
-
const partial = frontier.length > 0 ? renderAddressedFrontier(frontier, requestLines, { lead: requestFor(FRONTIER_REQUEST_BYTES), trail: nodeText }) : "";
|
|
2537
|
-
if (partial) return partial;
|
|
2538
|
-
const pointer = nodeText.includes(LCM_RECOVERY_POINTER) ? "" : LCM_RECOVERY_POINTER;
|
|
2539
|
-
const separator = utf8Bytes(BLOCK_SEPARATOR);
|
|
2540
|
-
const room = Math.max(0, outputBound - (pointer ? utf8Bytes(pointer) + separator : 0));
|
|
2541
|
-
const request = requestLines.length > 0 ? `[Compaction Request]
|
|
2542
|
-
${requestLines.join("\n")}` : "";
|
|
2543
|
-
const head = [request, requestFor(Math.floor(room * ACTIVE_REQUEST_SHARE))].filter((block) => block.length > 0);
|
|
2544
|
-
const headBytes = head.length > 0 ? utf8Bytes(head.join(BLOCK_SEPARATOR)) + separator : 0;
|
|
2545
|
-
const tailRoom = Math.max(0, room - headBytes);
|
|
2546
|
-
const tail = tailDigest(tailEntries, tailStored, Math.min(TAIL_DIGEST_MAX_BYTES, tailRoom)) || clipUtf8(nodeText, tailRoom);
|
|
2547
|
-
const body = clipUtf8([...head, tail].join(BLOCK_SEPARATOR), room);
|
|
2548
|
-
return pointer ? `${body}${BLOCK_SEPARATOR}${pointer}` : body;
|
|
2549
|
-
};
|
|
2550
|
-
const leafCap = Math.max(1, this.options.maxLeafEntries ?? DEFAULT_LEAF_ENTRIES);
|
|
2551
|
-
const inputCap = this.options.lcmMaxInputChars ?? DEFAULT_LCM_MAX_INPUT_CHARS;
|
|
2552
|
-
const spans = [];
|
|
2553
|
-
let span = [];
|
|
2554
|
-
let spanChars = 0;
|
|
2555
|
-
for (let index = 0; index < tailStored.length; index += 1) {
|
|
2556
|
-
const size = tailStored[index].payloadJson.length;
|
|
2557
|
-
if (span.length > 0 && (span.length >= leafCap || spanChars + size > inputCap)) {
|
|
2558
|
-
spans.push(span);
|
|
2559
|
-
span = [];
|
|
2560
|
-
spanChars = 0;
|
|
2561
|
-
}
|
|
2562
|
-
span.push(index);
|
|
2563
|
-
spanChars += size;
|
|
2564
|
-
}
|
|
2565
|
-
if (span.length > 0) spans.push(span);
|
|
2566
|
-
for (const indices of spans) {
|
|
2567
|
-
const stored = indices.map((index) => tailStored[index]);
|
|
2568
|
-
const entries = indices.map((index) => tailEntries[index]);
|
|
2569
|
-
const leaf = this.maintenance.createLeaf(stored);
|
|
2570
|
-
if (!leaf) throw new Error("LCM emergency fallback node was not created");
|
|
2571
|
-
const persisted = this.maintenance.getNode(leaf.nodeId);
|
|
2572
|
-
if (persisted?.state === "ready") {
|
|
2573
|
-
if (!persisted.text) throw new Error("LCM emergency fallback text is missing");
|
|
2574
|
-
continue;
|
|
2575
|
-
}
|
|
2576
|
-
const job = this.maintenance.jobForNode(leaf.nodeId);
|
|
2577
|
-
if (!job) throw new Error("LCM emergency fallback job was not created");
|
|
2578
|
-
try {
|
|
2579
|
-
this.maintenance.completeEmergency(this.maintenance.claimEmergency(job.jobId), nodeTextFor(entries, stored));
|
|
2580
|
-
} catch (error) {
|
|
2581
|
-
if (!isLcmRejection(error)) throw error;
|
|
2582
|
-
}
|
|
2583
|
-
}
|
|
2584
|
-
return {
|
|
2585
|
-
summary: compose(fallback),
|
|
2586
|
-
firstKeptEntryId: input.firstKeptEntryId,
|
|
2587
|
-
tokensBefore: input.tokensBefore,
|
|
2588
|
-
source: "emergency",
|
|
2589
|
-
...instructionDetails ? { details: instructionDetails } : {}
|
|
2590
|
-
};
|
|
2591
|
-
}
|
|
2592
|
-
report() {
|
|
2593
|
-
const day = new Date(Date.now()).toISOString().slice(0, 10);
|
|
2594
|
-
const degraded = this.degradedMessage();
|
|
2595
|
-
const ledgerState = this.ledger.operationalState;
|
|
2596
|
-
return this.ledger.readOnly((db) => {
|
|
2597
|
-
const count = (sql, ...params) => Number(db.prepare(sql).get(...params).n);
|
|
2598
|
-
const nodes = db.prepare("SELECT json_extract(payload,'$.kind') kind, json_extract(payload,'$.state') state, json_extract(payload,'$.modelHash') model, count(*) n FROM summary_nodes WHERE project_key=? GROUP BY kind, state, model").all(this.projectKey);
|
|
2599
|
-
const usage = db.prepare("SELECT coalesce(sum(calls),0) calls, coalesce(sum(input_tokens),0) input, coalesce(sum(output_tokens),0) output, coalesce(sum(cost),0) cost, coalesce(sum(wall_ms),0) wallMs FROM maintenance_usage WHERE project_key=? AND day=?").get(this.projectKey, day);
|
|
2600
|
-
const budget = this.maintenance.budgetPolicy();
|
|
2601
|
-
return {
|
|
2602
|
-
projectKey: this.projectKey,
|
|
2603
|
-
sessionId: this.activeSessionId,
|
|
2604
|
-
state: reconcileLcmState(ledgerState, degraded),
|
|
2605
|
-
ledgerState,
|
|
2606
|
-
degraded,
|
|
2607
|
-
summaryModel: this.options.summaryModel,
|
|
2608
|
-
rawEntries: count("SELECT count(*) n FROM raw_entries WHERE project_key=?", this.projectKey),
|
|
2609
|
-
sessionEntries: this.activeSessionId === void 0 ? 0 : count("SELECT count(*) n FROM raw_entries WHERE project_key=? AND session_id=?", this.projectKey, this.activeSessionId),
|
|
2610
|
-
modelNodes: nodes.filter((row) => row.model && row.model !== "emergency").reduce((total, row) => total + row.n, 0),
|
|
2611
|
-
emergencyNodes: nodes.filter((row) => row.model === "emergency").reduce((total, row) => total + row.n, 0),
|
|
2612
|
-
pendingNodes: nodes.filter((row) => row.state !== "ready").reduce((total, row) => total + row.n, 0),
|
|
2613
|
-
pendingJobs: count("SELECT count(*) n FROM maintenance_jobs WHERE project_key=? AND status=?", this.projectKey, "pending"),
|
|
2614
|
-
upgradableNodes: count("SELECT count(*) n FROM summary_nodes WHERE project_key=? AND json_extract(payload,'$.modelHash')=?", this.projectKey, "emergency"),
|
|
2615
|
-
usage: { calls: usage.calls, inputTokens: usage.input, outputTokens: usage.output, cost: usage.cost, wallMs: usage.wallMs },
|
|
2616
|
-
budget: { calls: budget.calls, sessionCalls: budget.sessionCalls, wallMs: budget.wallMs },
|
|
2617
|
-
reconciliation: this.lastReconciliation
|
|
2618
|
-
};
|
|
2619
|
-
});
|
|
2620
|
-
}
|
|
2621
|
-
repairLog = [];
|
|
2622
|
-
branchLength() {
|
|
2623
|
-
try {
|
|
2624
|
-
return this.context.sessionManager.getBranch().length;
|
|
2625
|
-
} catch {
|
|
2626
|
-
return 0;
|
|
2627
|
-
}
|
|
2628
|
-
}
|
|
2629
|
-
sessionFile() {
|
|
2630
|
-
const getSessionFile = this.context.sessionManager.getSessionFile;
|
|
2631
|
-
if (typeof getSessionFile !== "function") return void 0;
|
|
2632
|
-
return getSessionFile.call(this.context.sessionManager) ?? void 0;
|
|
2633
|
-
}
|
|
2634
|
-
sessionFilePresent() {
|
|
2635
|
-
const file = this.sessionFile();
|
|
2636
|
-
return file !== void 0 && fs4.existsSync(file);
|
|
2637
|
-
}
|
|
2638
|
-
countJobs(state, since = 0) {
|
|
2639
|
-
try {
|
|
2640
|
-
return this.maintenance.countJobs(state, since);
|
|
2641
|
-
} catch {
|
|
2642
|
-
return 0;
|
|
2643
|
-
}
|
|
2644
|
-
}
|
|
2645
|
-
diagnostics(report = this.report()) {
|
|
2646
|
-
const coverage = this.coverage();
|
|
2647
|
-
const sessionFile = this.sessionFile();
|
|
2648
|
-
const sessionId = this.activeSessionId;
|
|
2649
|
-
let withinBudget = true;
|
|
2650
|
-
try {
|
|
2651
|
-
withinBudget = sessionId === void 0 || this.maintenance.withinBudget(sessionId);
|
|
2652
|
-
} catch {
|
|
2653
|
-
withinBudget = true;
|
|
2654
|
-
}
|
|
2655
|
-
let expiredLeases = 0;
|
|
2656
|
-
try {
|
|
2657
|
-
expiredLeases = this.maintenance.expiredLeases();
|
|
2658
|
-
} catch {
|
|
2659
|
-
expiredLeases = 0;
|
|
2660
|
-
}
|
|
2661
|
-
return {
|
|
2662
|
-
projectKey: this.projectKey,
|
|
2663
|
-
ledgerPath: this.ledger.file,
|
|
2664
|
-
ledgerBytes: this.ledger.bytes,
|
|
2665
|
-
ledgerState: report.ledgerState,
|
|
2666
|
-
runtimeError: this.degradedError === void 0 ? void 0 : String(this.degradedError instanceof Error ? this.degradedError.message : this.degradedError),
|
|
2667
|
-
sessionId,
|
|
2668
|
-
sessionFile,
|
|
2669
|
-
sessionFilePresent: this.sessionFilePresent(),
|
|
2670
|
-
liveBranchEntries: this.branchLength(),
|
|
2671
|
-
ledgerSessionEntries: report.sessionEntries,
|
|
2672
|
-
ledgerEntries: report.rawEntries,
|
|
2673
|
-
activeSources: coverage.active,
|
|
2674
|
-
coveredSources: coverage.covered,
|
|
2675
|
-
backlogThreshold: Math.max(1, this.options.maxLeafEntries ?? DEFAULT_LEAF_ENTRIES),
|
|
2676
|
-
pendingNodes: report.pendingNodes,
|
|
2677
|
-
pendingJobs: this.countJobs("pending"),
|
|
2678
|
-
runningJobs: this.countJobs("running"),
|
|
2679
|
-
failedJobs: this.recentlyFailedJobs(),
|
|
2680
|
-
expiredLeases,
|
|
2681
|
-
modelSummaries: this.options.modelSummaries !== false,
|
|
2682
|
-
summaryModel: this.options.summaryModel,
|
|
2683
|
-
budgetCalls: report.budget.calls,
|
|
2684
|
-
usedCalls: report.usage.calls,
|
|
2685
|
-
withinBudget,
|
|
2686
|
-
reconciliation: this.lastReconciliation ? {
|
|
2687
|
-
errors: this.lastReconciliation.errors,
|
|
2688
|
-
raced: this.lastReconciliation.raced,
|
|
2689
|
-
absent: this.lastReconciliation.absent,
|
|
2690
|
-
reasons: this.lastReconciliation.reasons
|
|
2691
|
-
} : void 0,
|
|
2692
|
-
repairs: this.repairLog,
|
|
2693
|
-
autoRepairs: this.autoRepairState()
|
|
2694
|
-
};
|
|
2695
|
-
}
|
|
2696
|
-
autoRepairState() {
|
|
2697
|
-
try {
|
|
2698
|
-
return [...this.ledger.readRepairLadder()].map(([fault, state]) => ({ fault, attempts: state.attempts, nextAt: state.nextAt, detail: state.detail })).sort((left, right) => left.fault.localeCompare(right.fault));
|
|
2699
|
-
} catch {
|
|
2700
|
-
return [];
|
|
2701
|
-
}
|
|
2702
|
-
}
|
|
2703
|
-
get repairs() {
|
|
2704
|
-
return this.repairLog;
|
|
2705
|
-
}
|
|
2706
|
-
record(id, changed, detail) {
|
|
2707
|
-
const outcome = { id, changed, detail, at: Date.now() };
|
|
2708
|
-
this.repairLog.unshift(outcome);
|
|
2709
|
-
if (this.repairLog.length > MAX_REPAIR_LOG) this.repairLog.length = MAX_REPAIR_LOG;
|
|
2710
|
-
this.invalidateFrontier();
|
|
2711
|
-
return outcome;
|
|
2712
|
-
}
|
|
2713
|
-
/** Every repair is idempotent and reports the delta it caused. */
|
|
2714
|
-
async repair(id) {
|
|
2715
|
-
if (this.closed) return this.record(id, false, "the runtime is closed");
|
|
2716
|
-
try {
|
|
2717
|
-
if (id === "reconcile") {
|
|
2718
|
-
await this.reconcileSelectedSession();
|
|
2719
|
-
const errors = this.lastReconciliation?.errors ?? 0;
|
|
2720
|
-
if (errors > 0) return this.record(id, false, `still ${errors} unreadable session file(s)`);
|
|
2721
|
-
const absent = this.lastReconciliation?.absent ?? 0;
|
|
2722
|
-
return this.record(id, absent === 0, absent > 0 ? "session file is not on disk yet" : "session file re-read into the ledger");
|
|
2723
|
-
}
|
|
2724
|
-
if (id === "readback") {
|
|
2725
|
-
const before = this.report().sessionEntries;
|
|
2726
|
-
this.degradedError = void 0;
|
|
2727
|
-
this.markDirty();
|
|
2728
|
-
await this.readback();
|
|
2729
|
-
const after = this.report().sessionEntries;
|
|
2730
|
-
return this.record(id, after !== before, `${after - before} entr${after - before === 1 ? "y" : "ies"} imported \xB7 ${after} stored`);
|
|
2731
|
-
}
|
|
2732
|
-
if (id === "leases") {
|
|
2733
|
-
const swept = this.maintenance.sweepExpiredLeases().length;
|
|
2734
|
-
return this.record(id, swept > 0, `${swept} lease(s) released`);
|
|
2735
|
-
}
|
|
2736
|
-
const retried = this.maintenance.retryFailedJobs().length;
|
|
2737
|
-
if (retried > 0) this.scheduleMaintenance();
|
|
2738
|
-
return this.record(id, retried > 0, `${retried} job(s) requeued`);
|
|
2739
|
-
} catch (error) {
|
|
2740
|
-
return this.record(id, false, String(error instanceof Error ? error.message : error));
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
frontierCache;
|
|
2744
|
-
/** One frontier walk shared by preview, coverage, and the coverage map. */
|
|
2745
|
-
frontierSnapshot() {
|
|
2746
|
-
const sessionId = this.activeSessionId ?? "";
|
|
2747
|
-
const cached = this.frontierCache;
|
|
2748
|
-
if (cached && cached.sessionId === sessionId && Date.now() - cached.at < 250) {
|
|
2749
|
-
return { nodes: cached.nodes, covered: cached.covered };
|
|
2750
|
-
}
|
|
2751
|
-
const nodes = sessionId ? this.maintenance.getFrontier(sessionId, this.activeSources) : [];
|
|
2752
|
-
const covered = new Set(nodes.flatMap((node) => node.sources.map((source) => this.sourceKey(source))));
|
|
2753
|
-
this.frontierCache = { at: Date.now(), sessionId, nodes, covered };
|
|
2754
|
-
return { nodes, covered };
|
|
2755
|
-
}
|
|
2756
|
-
/** Content identity, so a fork keeps the summaries built over the entries it inherited. */
|
|
2757
|
-
sourceKey(source) {
|
|
2758
|
-
return `${source.entryId}:${source.payloadHash}`;
|
|
2759
|
-
}
|
|
2760
|
-
/** Assembles what a compaction would serve now. Reads only; it never persists a node. */
|
|
2761
|
-
preview() {
|
|
2762
|
-
const sessionId = this.activeSessionId;
|
|
2763
|
-
if (!sessionId) return { text: "", nodes: 0, summaryBytes: 0, sourceBytes: 0, coveredSources: 0, activeSources: 0 };
|
|
2764
|
-
const { nodes, covered } = this.frontierSnapshot();
|
|
2765
|
-
const text = nodes.map((node) => node.text ?? "").filter(Boolean).join("\n\n");
|
|
2766
|
-
return {
|
|
2767
|
-
text,
|
|
2768
|
-
nodes: nodes.length,
|
|
2769
|
-
summaryBytes: Buffer.byteLength(text, "utf8"),
|
|
2770
|
-
sourceBytes: this.ledger.payloadBytes(this.projectKey, sessionId),
|
|
2771
|
-
coveredSources: covered.size,
|
|
2772
|
-
activeSources: this.activeSources.size
|
|
2773
|
-
};
|
|
2774
|
-
}
|
|
2775
|
-
/** Ordered coverage of the active branch: each entry says whether a ready node holds it. */
|
|
2776
|
-
coverageMap(limit = 2e3) {
|
|
2777
|
-
const sessionId = this.activeSessionId;
|
|
2778
|
-
if (!sessionId) return [];
|
|
2779
|
-
const { covered } = this.frontierSnapshot();
|
|
2780
|
-
return this.ledger.readRawKeys(this.projectKey, sessionId, limit).map((entry) => {
|
|
2781
|
-
const key = this.sourceKey({ entryId: entry.entryId, payloadHash: entry.contentHash });
|
|
2782
|
-
return { key, covered: covered.has(key) };
|
|
2783
|
-
});
|
|
2784
|
-
}
|
|
2785
|
-
jobs(limit = 64) {
|
|
2786
|
-
try {
|
|
2787
|
-
return this.maintenance.recentJobs(limit);
|
|
2788
|
-
} catch {
|
|
2789
|
-
return [];
|
|
2790
|
-
}
|
|
2791
|
-
}
|
|
2792
|
-
nodes(limit = 200, offset = 0) {
|
|
2793
|
-
return this.maintenance.listNodes(limit, offset);
|
|
2794
|
-
}
|
|
2795
|
-
node(nodeId) {
|
|
2796
|
-
const node = this.maintenance.getNode(nodeId);
|
|
2797
|
-
if (!node) return void 0;
|
|
2798
|
-
return { node, revisions: this.maintenance.revisionsOf(nodeId), ancestors: this.maintenance.ancestorsOf(nodeId) };
|
|
2799
|
-
}
|
|
2800
|
-
source(sessionId, entryId, revision) {
|
|
2801
|
-
return this.ledger.readRawEntry(this.projectKey, sessionId, entryId, revision);
|
|
2802
|
-
}
|
|
2803
|
-
coverage() {
|
|
2804
|
-
if (!this.activeSessionId) return { active: 0, covered: 0 };
|
|
2805
|
-
const { covered } = this.frontierSnapshot();
|
|
2806
|
-
let hits = 0;
|
|
2807
|
-
for (const key of this.activeSources) if (covered.has(key)) hits += 1;
|
|
2808
|
-
return { active: this.activeSources.size, covered: hits };
|
|
2809
|
-
}
|
|
2810
|
-
memoryContext() {
|
|
2811
|
-
return {
|
|
2812
|
-
ledger: {
|
|
2813
|
-
projectKey: this.projectKey,
|
|
2814
|
-
readRaw: (sessionId) => this.ledger.readRaw(this.projectKey, sessionId),
|
|
2815
|
-
readRawPage: (sessionId, offset, limit) => this.ledger.readRawPage(this.projectKey, sessionId, offset, limit),
|
|
2816
|
-
readRawEntry: (sessionId, entryId, revision) => this.ledger.readRawEntry(this.projectKey, sessionId, entryId, revision),
|
|
2817
|
-
searchRaw: (options) => this.ledger.searchRaw(this.projectKey, options)
|
|
2818
|
-
},
|
|
2819
|
-
...this.activeSessionId === void 0 ? {} : { currentSessionId: this.activeSessionId },
|
|
2820
|
-
summaries: {
|
|
2821
|
-
listNodes: ({ sessionId, limit }) => this.maintenance.getFrontier(sessionId, sessionId === this.activeSessionId ? this.activeSources : void 0).slice(0, limit).map((node) => ({ ...node, text: node.text ?? "", sources: node.sources.map((source) => ({ entryId: source.entryId, revision: source.revision, contentHash: source.payloadHash })) })),
|
|
2822
|
-
getNode: (nodeId) => {
|
|
2823
|
-
const node = this.maintenance.getNode(nodeId);
|
|
2824
|
-
return node ? { ...node, text: node.text ?? "", sources: node.sources.map((source) => ({ entryId: source.entryId, revision: source.revision, contentHash: source.payloadHash })) } : void 0;
|
|
2825
|
-
}
|
|
2826
|
-
},
|
|
2827
|
-
branchForSession: () => this.activeSessionId === void 0 ? void 0 : { activeSourceKeys: [...this.activeSources], ready: this.status === "healthy" }
|
|
2828
|
-
};
|
|
2829
|
-
}
|
|
2830
|
-
frontier(sessionId) {
|
|
2831
|
-
return this.maintenance.getFrontier(sessionId, sessionId === this.activeSessionId ? this.activeSources : void 0);
|
|
2832
|
-
}
|
|
2833
|
-
raw(sessionId) {
|
|
2834
|
-
return this.ledger.readRaw(this.projectKey, sessionId);
|
|
2835
|
-
}
|
|
2836
|
-
/** Waits for writes, then gives aborted maintenance a bounded grace before detaching the ledger close. */
|
|
2837
|
-
async shutdown() {
|
|
2838
|
-
if (this.closed) return;
|
|
2839
|
-
this.closed = true;
|
|
2840
|
-
this.abort.abort();
|
|
2841
|
-
await this.writePending.catch(() => void 0);
|
|
2842
|
-
const pending = this.maintenancePending.catch(() => void 0);
|
|
2843
|
-
const grace = new Promise((resolve) => {
|
|
2844
|
-
const timer = setTimeout(() => resolve(false), SHUTDOWN_GRACE_MS);
|
|
2845
|
-
timer.unref?.();
|
|
2846
|
-
});
|
|
2847
|
-
if (await Promise.race([pending.then(() => true), grace])) {
|
|
2848
|
-
this.ledger.close();
|
|
2849
|
-
return;
|
|
2850
|
-
}
|
|
2851
|
-
void pending.then(() => {
|
|
2852
|
-
try {
|
|
2853
|
-
this.ledger.close();
|
|
2854
|
-
} catch {
|
|
2855
|
-
}
|
|
2856
|
-
});
|
|
2857
|
-
}
|
|
2858
|
-
};
|
|
2859
|
-
export {
|
|
2860
|
-
LcmRuntime,
|
|
2861
|
-
renderAddressedFrontier
|
|
2862
|
-
};
|
|
2863
|
-
//# sourceMappingURL=lcm-runtime.js.map
|