@wrongstack/core 0.313.0 → 0.313.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/dist/chronicle/index.js +84 -6391
  2. package/dist/chronicle/project-server.js +84 -4868
  3. package/dist/chunk-2BUUIMQB.js +225 -0
  4. package/dist/chunk-2FK4WTFF.js +207 -0
  5. package/dist/chunk-2FQL4PDC.js +292 -0
  6. package/dist/chunk-2KKODIQU.js +2256 -0
  7. package/dist/chunk-2YU4WVBW.js +134 -0
  8. package/dist/chunk-3E244UDA.js +356 -0
  9. package/dist/chunk-3XPVB7BA.js +135 -0
  10. package/dist/chunk-4LJJYBAU.js +388 -0
  11. package/dist/chunk-4VWO3ZXL.js +342 -0
  12. package/dist/chunk-4XV6IR37.js +187 -0
  13. package/dist/chunk-4ZHTKJHM.js +183 -0
  14. package/dist/chunk-52RTVH4M.js +361 -0
  15. package/dist/chunk-57GEWK5X.js +26 -0
  16. package/dist/chunk-5DSMEVA4.js +931 -0
  17. package/dist/chunk-5RP3QTRL.js +1223 -0
  18. package/dist/chunk-5S437PRC.js +50 -0
  19. package/dist/chunk-5XDUGTKN.js +511 -0
  20. package/dist/chunk-62V2AFVG.js +422 -0
  21. package/dist/chunk-65RDIOR2.js +2470 -0
  22. package/dist/chunk-6AKOTGLM.js +597 -0
  23. package/dist/chunk-7ZHZE5EO.js +28 -0
  24. package/dist/chunk-A455ATZB.js +140 -0
  25. package/dist/chunk-AD7ZFZCS.js +46 -0
  26. package/dist/chunk-AI4LLQ2U.js +856 -0
  27. package/dist/chunk-ASX6AW36.js +789 -0
  28. package/dist/chunk-AT4V4XGI.js +3522 -0
  29. package/dist/chunk-AWNQ6ED6.js +311 -0
  30. package/dist/chunk-B4AMLZPB.js +9 -0
  31. package/dist/chunk-BAKVJLEV.js +417 -0
  32. package/dist/chunk-BJHVULHO.js +55 -0
  33. package/dist/chunk-CB2HFKTP.js +9 -0
  34. package/dist/chunk-CE4ZOCOI.js +1640 -0
  35. package/dist/chunk-CQQL4ZOQ.js +151 -0
  36. package/dist/chunk-DEIQMBD2.js +65 -0
  37. package/dist/chunk-E6I5RXVK.js +58 -0
  38. package/dist/chunk-EFEHDQGY.js +1589 -0
  39. package/dist/chunk-EODDVJBM.js +82 -0
  40. package/dist/chunk-EPC3GZD4.js +308 -0
  41. package/dist/chunk-FAYRX2AD.js +13 -0
  42. package/dist/chunk-FFSX2QDQ.js +362 -0
  43. package/dist/chunk-FHAMQS7Q.js +5856 -0
  44. package/dist/chunk-FIV4IJL7.js +2263 -0
  45. package/dist/chunk-FNXVT7HF.js +52 -0
  46. package/dist/chunk-FSWCWSTS.js +395 -0
  47. package/dist/chunk-FW5LDDMJ.js +16464 -0
  48. package/dist/chunk-FXQLIX3K.js +211 -0
  49. package/dist/chunk-G5AAKEEZ.js +228 -0
  50. package/dist/chunk-G5S3S5ZN.js +38 -0
  51. package/dist/chunk-GAZEWQEZ.js +231 -0
  52. package/dist/chunk-GFJOMSHG.js +125 -0
  53. package/dist/chunk-GFXZTHNI.js +158 -0
  54. package/dist/chunk-GM54GJBU.js +960 -0
  55. package/dist/chunk-GPQ3NJPR.js +900 -0
  56. package/dist/chunk-GTCU6DZ3.js +1 -0
  57. package/dist/chunk-H5E77KUJ.js +15 -0
  58. package/dist/chunk-H72H4XDU.js +1023 -0
  59. package/dist/chunk-HA4ZYA6T.js +178 -0
  60. package/dist/chunk-I45KAW2N.js +5020 -0
  61. package/dist/chunk-IQ35HMQL.js +1396 -0
  62. package/dist/chunk-IYFBFX34.js +86 -0
  63. package/dist/chunk-JJPMWPB6.js +109 -0
  64. package/dist/chunk-JTHKOYWU.js +663 -0
  65. package/dist/chunk-JVGPR3TS.js +365 -0
  66. package/dist/chunk-JVKB2TBL.js +48 -0
  67. package/dist/chunk-JX7VBZDK.js +31 -0
  68. package/dist/chunk-K3G6JBUC.js +5232 -0
  69. package/dist/chunk-K4YUNKU7.js +589 -0
  70. package/dist/chunk-KBZGE6LN.js +710 -0
  71. package/dist/chunk-KDQJCT2J.js +45 -0
  72. package/dist/chunk-KI4L2DUL.js +560 -0
  73. package/dist/chunk-KJ2ZTQSL.js +47 -0
  74. package/dist/chunk-KSJ5UTP7.js +154 -0
  75. package/dist/chunk-LHOA5DWA.js +28 -0
  76. package/dist/chunk-LX5QWLBL.js +27 -0
  77. package/dist/chunk-LZDDLNCZ.js +279 -0
  78. package/dist/chunk-M2WF6AXG.js +115 -0
  79. package/dist/chunk-M7BS2K6U.js +1 -0
  80. package/dist/chunk-NDBIPFNY.js +102 -0
  81. package/dist/chunk-NEMIWEXC.js +1199 -0
  82. package/dist/chunk-NFAYHPRH.js +323 -0
  83. package/dist/chunk-O37BQ65S.js +21 -0
  84. package/dist/chunk-O74MJHXU.js +187 -0
  85. package/dist/chunk-OJZEX73F.js +112 -0
  86. package/dist/chunk-PAAWLLZX.js +74 -0
  87. package/dist/chunk-PFXFQQRT.js +339 -0
  88. package/dist/chunk-PFZO3C6H.js +14 -0
  89. package/dist/chunk-PHH7LD45.js +113 -0
  90. package/dist/chunk-QRTG4XTI.js +188 -0
  91. package/dist/chunk-QVOVMXJR.js +1351 -0
  92. package/dist/chunk-RCQYT2I4.js +757 -0
  93. package/dist/chunk-RD6DEE36.js +1178 -0
  94. package/dist/chunk-RJIZEJ42.js +30 -0
  95. package/dist/chunk-RPOA7IAE.js +150 -0
  96. package/dist/chunk-SN2DQRL6.js +1172 -0
  97. package/dist/chunk-SQJVFEBV.js +41 -0
  98. package/dist/chunk-SQP64RCS.js +5391 -0
  99. package/dist/chunk-SVT4RNTR.js +49 -0
  100. package/dist/chunk-SWUFN7XM.js +43 -0
  101. package/dist/chunk-SXMVYC5H.js +174 -0
  102. package/dist/chunk-SZ6AYUIZ.js +23 -0
  103. package/dist/chunk-T3KGZBU5.js +3171 -0
  104. package/dist/chunk-TBRL2RCC.js +9 -0
  105. package/dist/chunk-TRT2HRWZ.js +18 -0
  106. package/dist/chunk-TYW2GI5I.js +1077 -0
  107. package/dist/chunk-UIWONWVG.js +4959 -0
  108. package/dist/chunk-VB3H5WWB.js +151 -0
  109. package/dist/chunk-W4A6QA3D.js +258 -0
  110. package/dist/chunk-WBPVKEEE.js +227 -0
  111. package/dist/chunk-WEBMSQP2.js +123 -0
  112. package/dist/chunk-WOEZV3Q4.js +333 -0
  113. package/dist/chunk-WQQON3SV.js +473 -0
  114. package/dist/chunk-WQTOVMGV.js +119 -0
  115. package/dist/chunk-WZO23AWO.js +2779 -0
  116. package/dist/chunk-XBDP4QPW.js +7 -0
  117. package/dist/chunk-XEBHSJLT.js +103 -0
  118. package/dist/chunk-XQ2ECNK3.js +1 -0
  119. package/dist/chunk-XQ2XGIBF.js +2086 -0
  120. package/dist/chunk-Y2GE5TSI.js +355 -0
  121. package/dist/chunk-YBUJCZ57.js +351 -0
  122. package/dist/chunk-YNCVSFGF.js +149 -0
  123. package/dist/chunk-YUPMXOGP.js +282 -0
  124. package/dist/chunk-YY6APYUM.js +49 -0
  125. package/dist/chunk-Z2IJUO45.js +691 -0
  126. package/dist/chunk-ZEHUCJHY.js +129 -0
  127. package/dist/chunk-ZYU2YOJ6.js +1496 -0
  128. package/dist/chunk-ZZ4V3WIZ.js +163 -0
  129. package/dist/coordination/agents/index.js +145 -6260
  130. package/dist/coordination/index.js +365 -34324
  131. package/dist/coordination/mailbox-project-server.js +48 -3276
  132. package/dist/coordination/provider-status-tracker.d.ts +4 -0
  133. package/dist/core/agent.d.ts +14 -1
  134. package/dist/core/index.js +267 -12480
  135. package/dist/core/model-ref.js +5 -23
  136. package/dist/core/provider-runner.d.ts +36 -1
  137. package/dist/design/index.js +50 -1087
  138. package/dist/execution/index.d.ts +1 -1
  139. package/dist/execution/index.js +1599 -21888
  140. package/dist/execution/prompt-enhancer.js +16 -535
  141. package/dist/execution/retry-policy.d.ts +31 -1
  142. package/dist/extension/index.js +7 -311
  143. package/dist/goal/index.js +33 -3435
  144. package/dist/hooks/index.js +14 -1138
  145. package/dist/hq/index.js +112 -5139
  146. package/dist/hq/protocol.js +21 -668
  147. package/dist/index.js +1410 -92656
  148. package/dist/infrastructure/index.js +64 -4811
  149. package/dist/kernel/events/provider-events.d.ts +15 -0
  150. package/dist/kernel/index.js +14 -992
  151. package/dist/models/index.js +40 -1117
  152. package/dist/notifications/index.js +3 -108
  153. package/dist/observability/index.js +17 -279
  154. package/dist/plugin/index.js +584 -14835
  155. package/dist/prompts/index.js +14 -948
  156. package/dist/registry/index.js +9 -822
  157. package/dist/registry-R23UBE7H.js +14 -0
  158. package/dist/replay/index.js +6 -84
  159. package/dist/review-finding-store-DKAV3AS6.js +21 -0
  160. package/dist/review-report-store-OWY3EC3N.js +19 -0
  161. package/dist/security/index.js +114 -2202
  162. package/dist/session-catalog/index.js +36 -2103
  163. package/dist/session-catalog/project-server.js +42 -1435
  164. package/dist/skills/index.js +35 -1578
  165. package/dist/storage/index.js +182 -15600
  166. package/dist/tasking/index.js +10 -676
  167. package/dist/tools/index.js +52 -9590
  168. package/dist/types/config/autonomy.d.ts +5 -0
  169. package/dist/types/config/ui.d.ts +1 -1
  170. package/dist/types/errors.d.ts +18 -0
  171. package/dist/types/index.js +121 -1342
  172. package/dist/types/provider-runner.d.ts +8 -0
  173. package/dist/types/session-markers.js +8 -144
  174. package/dist/utils/error.js +3 -4
  175. package/dist/utils/expect-defined.js +3 -9
  176. package/dist/utils/heap-watchdog.js +6 -706
  177. package/dist/utils/index.js +269 -5685
  178. package/dist/utils/sage-output-block.js +5 -42
  179. package/dist/wiring/proxy-rewrite.d.ts +18 -0
  180. package/dist/wiring/proxy-rewrite.js +18 -121
  181. package/dist/worktree/index.js +6 -887
  182. package/package.json +4 -4
@@ -0,0 +1,856 @@
1
+ import {
2
+ SESSION_CATALOG_DEFAULT_LEASE_MS,
3
+ SESSION_CATALOG_DEFAULT_RESERVATION_MS,
4
+ SESSION_CATALOG_MAX_AGENTS
5
+ } from "./chunk-E6I5RXVK.js";
6
+ import {
7
+ loadDatabaseSync
8
+ } from "./chunk-GM54GJBU.js";
9
+ import {
10
+ DefaultSecretScrubber
11
+ } from "./chunk-3E244UDA.js";
12
+ import {
13
+ isSessionTranscriptFileName
14
+ } from "./chunk-AD7ZFZCS.js";
15
+ import {
16
+ isPidAlive
17
+ } from "./chunk-TRT2HRWZ.js";
18
+ import {
19
+ atomicWrite
20
+ } from "./chunk-7ZHZE5EO.js";
21
+
22
+ // src/session-catalog/store.ts
23
+ import { randomBytes, randomUUID } from "node:crypto";
24
+ import * as fs2 from "node:fs";
25
+ import * as path2 from "node:path";
26
+
27
+ // src/session-catalog/store-rebuild.ts
28
+ import * as fs from "node:fs";
29
+ import * as path from "node:path";
30
+
31
+ // src/session-catalog/store-schema.ts
32
+ import { createHash, timingSafeEqual } from "node:crypto";
33
+ var SCHEMA_VERSION = 1;
34
+ var MAX_LEASE_MS = 12e4;
35
+ var MAX_RESERVATION_MS = 6e4;
36
+ var MAX_MAINTENANCE_MS = 5 * 6e4;
37
+ var MAX_PAGE = 1e3;
38
+ function hashSecret(secret) {
39
+ return createHash("sha256").update(secret).digest("hex");
40
+ }
41
+ function secretMatches(secret, expectedHex) {
42
+ const actual = Buffer.from(hashSecret(secret), "hex");
43
+ const expected = Buffer.from(expectedHex, "hex");
44
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
45
+ }
46
+ function boundedMs(value, fallback, max) {
47
+ return Math.min(max, Math.max(1e3, Number.isFinite(value) ? Math.floor(value) : fallback));
48
+ }
49
+ function parseJson(value) {
50
+ return JSON.parse(value);
51
+ }
52
+ function conflict(message) {
53
+ const error = new Error(message);
54
+ error.name = "SessionOwnershipConflictError";
55
+ return error;
56
+ }
57
+ function assertId(value, label = "session id") {
58
+ if (!value || value.length > 256 || value.includes("\\") || value.startsWith("/") || value.includes("..")) {
59
+ throw new TypeError(`Invalid ${label}`);
60
+ }
61
+ }
62
+ function boundPresenceValue(value, depth) {
63
+ if (typeof value === "string") {
64
+ return value.length <= 6e3 ? value : `${value.slice(0, 5988)}\u2026[truncated]`;
65
+ }
66
+ if (value === null || typeof value !== "object") return value;
67
+ if (depth >= 8) return "[truncated depth]";
68
+ if (Array.isArray(value)) {
69
+ return value.slice(0, 64).map((item) => boundPresenceValue(item, depth + 1));
70
+ }
71
+ const result = {};
72
+ for (const [key, item] of Object.entries(value).slice(0, 64)) {
73
+ result[key] = boundPresenceValue(item, depth + 1);
74
+ }
75
+ return result;
76
+ }
77
+ function configureCatalogDatabase(db) {
78
+ db.exec(
79
+ "PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000; PRAGMA synchronous=NORMAL;"
80
+ );
81
+ }
82
+ function initializeCatalogSchema(db) {
83
+ db.exec(`
84
+ CREATE TABLE IF NOT EXISTS catalog_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
85
+ CREATE TABLE IF NOT EXISTS sessions (
86
+ session_id TEXT PRIMARY KEY,
87
+ transcript_relative_path TEXT NOT NULL,
88
+ summary_relative_path TEXT NOT NULL,
89
+ summary_json TEXT NOT NULL,
90
+ transcript_size INTEGER NOT NULL DEFAULT 0,
91
+ transcript_mtime_ms REAL NOT NULL DEFAULT 0,
92
+ summary_revision INTEGER NOT NULL DEFAULT 1,
93
+ indexed_at TEXT NOT NULL,
94
+ damaged INTEGER NOT NULL DEFAULT 0
95
+ );
96
+ CREATE TABLE IF NOT EXISTS session_leases (
97
+ session_id TEXT PRIMARY KEY,
98
+ lease_id TEXT NOT NULL UNIQUE,
99
+ lease_secret_hash TEXT NOT NULL,
100
+ owner_instance_id TEXT NOT NULL,
101
+ owner_pid INTEGER NOT NULL,
102
+ owner_started_at TEXT NOT NULL,
103
+ entry_json TEXT NOT NULL,
104
+ agent_revision INTEGER NOT NULL DEFAULT 0,
105
+ status TEXT NOT NULL,
106
+ last_heartbeat_at INTEGER NOT NULL,
107
+ lease_expires_at INTEGER NOT NULL
108
+ );
109
+ CREATE TABLE IF NOT EXISTS resume_reservations (
110
+ reservation_id TEXT PRIMARY KEY,
111
+ target_session_id TEXT NOT NULL UNIQUE,
112
+ requester_instance_id TEXT NOT NULL,
113
+ current_session_id TEXT,
114
+ created_at INTEGER NOT NULL,
115
+ expires_at INTEGER NOT NULL
116
+ );
117
+ CREATE TABLE IF NOT EXISTS maintenance_leases (
118
+ session_id TEXT PRIMARY KEY,
119
+ operation TEXT NOT NULL,
120
+ holder_id TEXT NOT NULL,
121
+ lease_id TEXT NOT NULL UNIQUE,
122
+ acquired_at INTEGER NOT NULL,
123
+ expires_at INTEGER NOT NULL
124
+ );
125
+ CREATE INDEX IF NOT EXISTS idx_sessions_activity ON sessions(indexed_at DESC);
126
+ CREATE INDEX IF NOT EXISTS idx_leases_expiry ON session_leases(lease_expires_at);
127
+ CREATE INDEX IF NOT EXISTS idx_reservations_expiry ON resume_reservations(expires_at);
128
+ CREATE INDEX IF NOT EXISTS idx_maintenance_expiry ON maintenance_leases(expires_at);
129
+ `);
130
+ db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("schema_version", String(SCHEMA_VERSION));
131
+ db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("generation", "0");
132
+ const row = db.prepare("SELECT value FROM catalog_meta WHERE key=?").get("schema_version");
133
+ if (Number(row.value) !== SCHEMA_VERSION)
134
+ throw new Error(`Unsupported session catalog schema ${row.value}`);
135
+ }
136
+
137
+ // src/session-catalog/store-rebuild.ts
138
+ function walkSessionFiles(root, suffix) {
139
+ const result = [];
140
+ const visit = (dir) => {
141
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
142
+ if (entry.isDirectory()) {
143
+ if (entry.name !== "_cas" && entry.name !== "_trash") visit(path.join(dir, entry.name));
144
+ } else if (entry.isFile() && entry.name.endsWith(suffix))
145
+ result.push(path.join(dir, entry.name));
146
+ }
147
+ };
148
+ visit(root);
149
+ return result;
150
+ }
151
+ function summarizeTranscriptFile(transcriptFilePath, id) {
152
+ const lines = fs.readFileSync(transcriptFilePath, "utf8").split(/\r?\n/);
153
+ let start;
154
+ let endedAt;
155
+ let lastActivityAt;
156
+ let messageCount = 0;
157
+ let iterationCount = 0;
158
+ let toolCallCount = 0;
159
+ let compactionCount = 0;
160
+ let tokenTotal = 0;
161
+ for (const line of lines) {
162
+ if (!line) continue;
163
+ let event;
164
+ try {
165
+ event = parseJson(line);
166
+ } catch {
167
+ continue;
168
+ }
169
+ lastActivityAt = event.ts;
170
+ if (event.type === "session_start") start = event;
171
+ if (event.type === "session_end") endedAt = event.ts;
172
+ if (event.type === "message_appended" && (event.message.role === "user" || event.message.role === "assistant"))
173
+ messageCount++;
174
+ if (event.type === "llm_response") {
175
+ iterationCount++;
176
+ tokenTotal += event.usage.input + event.usage.output + (event.usage.cacheRead ?? 0) + (event.usage.cacheWrite ?? 0);
177
+ }
178
+ if (event.type === "tool_call_end") toolCallCount++;
179
+ if (event.type === "compaction") compactionCount++;
180
+ }
181
+ if (!start) throw new Error("missing session_start");
182
+ return {
183
+ id,
184
+ title: id,
185
+ startedAt: start.ts,
186
+ ...endedAt ? { endedAt } : {},
187
+ model: start.model,
188
+ provider: start.provider,
189
+ tokenTotal,
190
+ ...lastActivityAt ? { lastActivityAt } : {},
191
+ messageCount,
192
+ iterationCount,
193
+ toolCallCount,
194
+ compactionCount
195
+ };
196
+ }
197
+ function rebuildCatalogIndex(db, sessionsDir, containedPathFn, transactionFn, bumpGenerationFn) {
198
+ const summaries = walkSessionFiles(sessionsDir, ".summary.json");
199
+ const transcripts = walkSessionFiles(sessionsDir, ".jsonl").filter(
200
+ (file) => isSessionTranscriptFileName(path.basename(file))
201
+ );
202
+ const ids = /* @__PURE__ */ new Set();
203
+ for (const file of [...summaries, ...transcripts]) {
204
+ const relative2 = path.relative(sessionsDir, file).replaceAll("\\", "/");
205
+ ids.add(relative2.replace(/\.summary\.json$|\.jsonl$/, ""));
206
+ }
207
+ let indexed = 0;
208
+ let damaged = 0;
209
+ transactionFn(() => {
210
+ db.prepare("DELETE FROM sessions").run();
211
+ for (const id of ids) {
212
+ try {
213
+ const summaryFile = containedPathFn(`${id}.summary.json`);
214
+ const summary = fs.existsSync(summaryFile) ? parseJson(fs.readFileSync(summaryFile, "utf8")) : summarizeTranscriptFile(containedPathFn(`${id}.jsonl`), id);
215
+ if (!summary || summary.id !== id) throw new Error("summary identity mismatch");
216
+ const transcript = containedPathFn(`${id}.jsonl`);
217
+ const stat = fs.existsSync(transcript) ? fs.statSync(transcript) : void 0;
218
+ const now = (/* @__PURE__ */ new Date()).toISOString();
219
+ db.prepare(
220
+ "INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,transcript_size,transcript_mtime_ms,summary_revision,indexed_at,damaged) VALUES (?,?,?,?,?,?,?,?,0)"
221
+ ).run(
222
+ id,
223
+ `${id}.jsonl`,
224
+ `${id}.summary.json`,
225
+ JSON.stringify(summary),
226
+ stat?.size ?? 0,
227
+ stat?.mtimeMs ?? 0,
228
+ 1,
229
+ now
230
+ );
231
+ indexed++;
232
+ } catch {
233
+ const now = (/* @__PURE__ */ new Date()).toISOString();
234
+ const fallback = {
235
+ id,
236
+ title: id,
237
+ startedAt: now,
238
+ model: "",
239
+ provider: "",
240
+ tokenTotal: 0
241
+ };
242
+ db.prepare(
243
+ "INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,summary_revision,indexed_at,damaged) VALUES (?,?,?,?,1,?,1)"
244
+ ).run(id, `${id}.jsonl`, `${id}.summary.json`, JSON.stringify(fallback), now);
245
+ damaged++;
246
+ }
247
+ }
248
+ db.prepare(
249
+ "INSERT INTO catalog_meta(key,value) VALUES ('last_reconciliation',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"
250
+ ).run((/* @__PURE__ */ new Date()).toISOString());
251
+ bumpGenerationFn();
252
+ });
253
+ return { indexed, damaged };
254
+ }
255
+
256
+ // src/session-catalog/store.ts
257
+ var SessionCatalogStore = class {
258
+ constructor(projectDir) {
259
+ this.projectDir = projectDir;
260
+ this.sessionsDir = path2.join(projectDir, "sessions");
261
+ fs2.mkdirSync(this.sessionsDir, { recursive: true, mode: 448 });
262
+ this.databasePath = path2.join(this.sessionsDir, "catalog.sqlite");
263
+ const Database = loadDatabaseSync();
264
+ this.db = new Database(this.databasePath);
265
+ try {
266
+ this.configureDatabase();
267
+ this.initialize();
268
+ } catch (error) {
269
+ const message = error instanceof Error ? error.message : String(error);
270
+ if (!/SQLITE_CORRUPT|SQLITE_NOTADB|database disk image is malformed|file is not a database/i.test(
271
+ message
272
+ )) {
273
+ this.db.close();
274
+ throw error;
275
+ }
276
+ this.db.close();
277
+ const quarantine = `${this.databasePath}.corrupt-${Date.now()}`;
278
+ try {
279
+ fs2.renameSync(this.databasePath, quarantine);
280
+ } catch {
281
+ }
282
+ for (const suffix of ["-wal", "-shm"]) {
283
+ try {
284
+ fs2.renameSync(`${this.databasePath}${suffix}`, `${quarantine}${suffix}`);
285
+ } catch {
286
+ }
287
+ }
288
+ this.db = new Database(this.databasePath);
289
+ this.configureDatabase();
290
+ this.initialize();
291
+ }
292
+ this.reapExpired();
293
+ const rowCount = Number(
294
+ this.db.prepare("SELECT COUNT(*) AS count FROM sessions").get().count
295
+ );
296
+ if (rowCount === 0 && walkSessionFiles(this.sessionsDir, ".jsonl").some((file) => !file.endsWith("_index.jsonl"))) {
297
+ this.rebuildCatalog();
298
+ }
299
+ }
300
+ projectDir;
301
+ databasePath;
302
+ sessionsDir;
303
+ db;
304
+ scrubber = new DefaultSecretScrubber();
305
+ configureDatabase() {
306
+ configureCatalogDatabase(this.db);
307
+ }
308
+ close() {
309
+ this.db.close();
310
+ }
311
+ initialize() {
312
+ initializeCatalogSchema(this.db);
313
+ }
314
+ transaction(run) {
315
+ this.db.exec("BEGIN IMMEDIATE");
316
+ try {
317
+ const result = run();
318
+ this.db.exec("COMMIT");
319
+ return result;
320
+ } catch (error) {
321
+ this.db.exec("ROLLBACK");
322
+ throw error;
323
+ }
324
+ }
325
+ bumpGeneration() {
326
+ this.db.prepare("UPDATE catalog_meta SET value=CAST(value AS INTEGER)+1 WHERE key='generation'").run();
327
+ return this.generation();
328
+ }
329
+ generation() {
330
+ const row = this.db.prepare("SELECT value FROM catalog_meta WHERE key='generation'").get();
331
+ return Number(row.value) || 0;
332
+ }
333
+ reapExpired(now = Date.now()) {
334
+ this.db.prepare("DELETE FROM resume_reservations WHERE expires_at<=?").run(now);
335
+ this.db.prepare("DELETE FROM maintenance_leases WHERE expires_at<=?").run(now);
336
+ const rows = this.db.prepare("SELECT * FROM session_leases WHERE lease_expires_at<=?").all(now);
337
+ for (const row of rows) {
338
+ if (!isPidAlive(row.owner_pid)) {
339
+ this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
340
+ } else if (row.status !== "lost") {
341
+ this.db.prepare("UPDATE session_leases SET status='lost' WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
342
+ }
343
+ }
344
+ }
345
+ maintenanceExists(sessionId) {
346
+ return Boolean(
347
+ this.db.prepare("SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND expires_at>?").get(sessionId, Date.now())
348
+ );
349
+ }
350
+ leaseRow(sessionId) {
351
+ return this.db.prepare("SELECT * FROM session_leases WHERE session_id=?").get(sessionId);
352
+ }
353
+ foreignLiveLease(sessionId, callerPid = process.pid) {
354
+ const live = this.leaseRow(sessionId);
355
+ return Boolean(live) && live.owner_pid !== callerPid;
356
+ }
357
+ verifyCredential(credential) {
358
+ assertId(credential.sessionId);
359
+ const row = this.leaseRow(credential.sessionId);
360
+ if (!row || row.lease_id !== credential.leaseId || row.owner_instance_id !== credential.ownerInstanceId || !secretMatches(credential.leaseSecret, row.lease_secret_hash)) {
361
+ throw conflict(`Session ${credential.sessionId} lease proof is invalid or no longer owned`);
362
+ }
363
+ return row;
364
+ }
365
+ createLease(entry, ownerInstanceId, leaseMs) {
366
+ assertId(entry.sessionId);
367
+ if (!ownerInstanceId || ownerInstanceId.length > 256)
368
+ throw new TypeError("Invalid owner instance id");
369
+ if (!Number.isSafeInteger(entry.pid) || entry.pid <= 0)
370
+ throw new TypeError("Invalid owner pid");
371
+ const now = Date.now();
372
+ const leaseId = randomUUID();
373
+ const leaseSecret = randomBytes(32).toString("hex");
374
+ const expiresAt = now + boundedMs(leaseMs, SESSION_CATALOG_DEFAULT_LEASE_MS, MAX_LEASE_MS);
375
+ this.db.prepare(`INSERT INTO session_leases(
376
+ session_id,lease_id,lease_secret_hash,owner_instance_id,owner_pid,owner_started_at,
377
+ entry_json,agent_revision,status,last_heartbeat_at,lease_expires_at
378
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(
379
+ entry.sessionId,
380
+ leaseId,
381
+ hashSecret(leaseSecret),
382
+ ownerInstanceId,
383
+ entry.pid,
384
+ entry.startedAt,
385
+ JSON.stringify(entry),
386
+ 0,
387
+ entry.status,
388
+ now,
389
+ expiresAt
390
+ );
391
+ return { sessionId: entry.sessionId, leaseId, leaseSecret, ownerInstanceId, expiresAt };
392
+ }
393
+ claimNew(entry, ownerInstanceId, leaseMs) {
394
+ return this.transaction(() => {
395
+ this.reapExpired();
396
+ const existing = this.leaseRow(entry.sessionId);
397
+ if (existing)
398
+ throw conflict(
399
+ `Session ${entry.sessionId} is already open in another running wstack (pid ${existing.owner_pid}).`
400
+ );
401
+ if (this.maintenanceExists(entry.sessionId))
402
+ throw conflict(`Session ${entry.sessionId} is under maintenance`);
403
+ const reserved = this.db.prepare(
404
+ "SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
405
+ ).get(entry.sessionId, Date.now());
406
+ if (reserved) throw conflict(`Session ${entry.sessionId} is reserved for resume`);
407
+ const credential = this.createLease(entry, ownerInstanceId, leaseMs);
408
+ this.bumpGeneration();
409
+ return credential;
410
+ });
411
+ }
412
+ reconnectLease(credential) {
413
+ return this.transaction(() => {
414
+ const row = this.verifyCredential(credential);
415
+ if (row.owner_pid !== process.pid && !isPidAlive(row.owner_pid))
416
+ throw conflict(`Session ${credential.sessionId} owner process is no longer alive`);
417
+ const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
418
+ this.db.prepare(
419
+ "UPDATE session_leases SET lease_expires_at=?,last_heartbeat_at=?,status=? WHERE session_id=? AND lease_id=?"
420
+ ).run(
421
+ expiresAt,
422
+ Date.now(),
423
+ row.status === "lost" ? "idle" : row.status,
424
+ row.session_id,
425
+ row.lease_id
426
+ );
427
+ return { ...credential, expiresAt };
428
+ });
429
+ }
430
+ reserveResume(targetSessionId, requesterInstanceId, currentSessionId, reservationMs) {
431
+ assertId(targetSessionId);
432
+ return this.transaction(() => {
433
+ this.reapExpired();
434
+ const live = this.leaseRow(targetSessionId);
435
+ if (live)
436
+ throw conflict(
437
+ `Session ${targetSessionId} is already open in another running wstack (pid ${live.owner_pid}).`
438
+ );
439
+ if (this.maintenanceExists(targetSessionId))
440
+ throw conflict(`Session ${targetSessionId} is under maintenance`);
441
+ const catalog = this.db.prepare("SELECT 1 AS yes FROM sessions WHERE session_id=?").get(targetSessionId);
442
+ if (!catalog && !fs2.existsSync(this.containedPath(`${targetSessionId}.jsonl`)))
443
+ throw new Error(`Session not found: ${targetSessionId}`);
444
+ const reservationId = randomUUID();
445
+ const now = Date.now();
446
+ const expiresAt = now + boundedMs(reservationMs, SESSION_CATALOG_DEFAULT_RESERVATION_MS, MAX_RESERVATION_MS);
447
+ try {
448
+ this.db.prepare(
449
+ "INSERT INTO resume_reservations(reservation_id,target_session_id,requester_instance_id,current_session_id,created_at,expires_at) VALUES (?,?,?,?,?,?)"
450
+ ).run(
451
+ reservationId,
452
+ targetSessionId,
453
+ requesterInstanceId,
454
+ currentSessionId ?? null,
455
+ now,
456
+ expiresAt
457
+ );
458
+ } catch {
459
+ throw conflict(`Session ${targetSessionId} is already reserved for resume`);
460
+ }
461
+ this.bumpGeneration();
462
+ return { reservationId, targetSessionId, requesterInstanceId, expiresAt };
463
+ });
464
+ }
465
+ activateReservation(reservation, entry, leaseMs) {
466
+ return this.transaction(() => {
467
+ this.reapExpired();
468
+ const row = this.db.prepare("SELECT * FROM resume_reservations WHERE reservation_id=?").get(reservation.reservationId);
469
+ if (!row || row.target_session_id !== reservation.targetSessionId || row.requester_instance_id !== reservation.requesterInstanceId || row.expires_at <= Date.now())
470
+ throw conflict("Resume reservation expired or is not owned by this requester");
471
+ if (entry.sessionId !== row.target_session_id)
472
+ throw new TypeError("Reservation target and session entry differ");
473
+ if (this.leaseRow(entry.sessionId) || this.maintenanceExists(entry.sessionId))
474
+ throw conflict(`Session ${entry.sessionId} can no longer be activated`);
475
+ const credential = this.createLease(entry, reservation.requesterInstanceId, leaseMs);
476
+ this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=?").run(row.reservation_id);
477
+ this.bumpGeneration();
478
+ return credential;
479
+ });
480
+ }
481
+ cancelReservation(reservationId, requesterInstanceId) {
482
+ this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=? AND requester_instance_id=?").run(reservationId, requesterInstanceId);
483
+ }
484
+ heartbeat(credential, status) {
485
+ return this.transaction(() => {
486
+ const row = this.verifyCredential(credential);
487
+ const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
488
+ const nextStatus = status ?? (row.status === "closing" ? "closing" : row.status === "lost" ? "idle" : row.status);
489
+ const entry = parseJson(row.entry_json);
490
+ entry.status = nextStatus;
491
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
492
+ this.db.prepare(
493
+ "UPDATE session_leases SET status=?,entry_json=?,last_heartbeat_at=?,lease_expires_at=? WHERE session_id=? AND lease_id=?"
494
+ ).run(
495
+ nextStatus,
496
+ JSON.stringify(entry),
497
+ Date.now(),
498
+ expiresAt,
499
+ row.session_id,
500
+ row.lease_id
501
+ );
502
+ return { ...credential, expiresAt };
503
+ });
504
+ }
505
+ publishAgents(credential, revision, agents) {
506
+ if (!Number.isSafeInteger(revision) || revision < 0)
507
+ throw new TypeError("Invalid presence revision");
508
+ if (!Array.isArray(agents) || agents.length > SESSION_CATALOG_MAX_AGENTS)
509
+ throw new TypeError(`Agent snapshot exceeds ${SESSION_CATALOG_MAX_AGENTS} agents`);
510
+ const boundedAgents = boundPresenceValue(
511
+ this.scrubber.scrubObject(agents),
512
+ 0
513
+ );
514
+ const encoded = JSON.stringify(boundedAgents);
515
+ if (encoded.length > 1024 * 1024) throw new TypeError("Agent snapshot exceeds 1 MiB");
516
+ return this.transaction(() => {
517
+ const row = this.verifyCredential(credential);
518
+ if (revision <= row.agent_revision) return { accepted: false, revision: row.agent_revision };
519
+ const entry = parseJson(row.entry_json);
520
+ entry.agents = boundedAgents;
521
+ entry.agentCount = boundedAgents.length;
522
+ entry.status = boundedAgents.some((agent) => agent.status !== "idle") ? "active" : "idle";
523
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
524
+ this.db.prepare(
525
+ "UPDATE session_leases SET entry_json=?,agent_revision=?,status=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
526
+ ).run(
527
+ JSON.stringify(entry),
528
+ revision,
529
+ entry.status,
530
+ Date.now(),
531
+ row.session_id,
532
+ row.lease_id
533
+ );
534
+ this.bumpGeneration();
535
+ return { accepted: true, revision };
536
+ });
537
+ }
538
+ markClosing(credential) {
539
+ const row = this.verifyCredential(credential);
540
+ const entry = parseJson(row.entry_json);
541
+ entry.status = "closing";
542
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
543
+ this.db.prepare(
544
+ "UPDATE session_leases SET status='closing',entry_json=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
545
+ ).run(JSON.stringify(entry), Date.now(), row.session_id, row.lease_id);
546
+ this.bumpGeneration();
547
+ }
548
+ release(credential) {
549
+ this.transaction(() => {
550
+ const row = this.verifyCredential(credential);
551
+ this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
552
+ this.bumpGeneration();
553
+ });
554
+ }
555
+ listLive() {
556
+ this.reapExpired();
557
+ return this.db.prepare(
558
+ "SELECT entry_json,status,last_heartbeat_at FROM session_leases ORDER BY last_heartbeat_at DESC"
559
+ ).all().map((row) => ({
560
+ ...parseJson(row.entry_json),
561
+ status: row.status,
562
+ lastHeartbeatAt: new Date(row.last_heartbeat_at).toISOString()
563
+ }));
564
+ }
565
+ getLive(sessionId) {
566
+ return this.listLive().find((entry) => entry.sessionId === sessionId) ?? null;
567
+ }
568
+ containedPath(relative2) {
569
+ assertId(relative2.replace(/\.(jsonl|summary\.json)$/, ""), "session path");
570
+ const root = path2.resolve(this.sessionsDir);
571
+ const candidate = path2.resolve(root, relative2);
572
+ const prefix = `${root}${path2.sep}`;
573
+ if (candidate !== root && !(process.platform === "win32" ? candidate.toLowerCase().startsWith(prefix.toLowerCase()) : candidate.startsWith(prefix)))
574
+ throw new TypeError("Session path escapes sessions directory");
575
+ return candidate;
576
+ }
577
+ upsertSummary(summary, transcriptRelativePath = `${summary.id}.jsonl`, summaryRelativePath = `${summary.id}.summary.json`) {
578
+ assertId(summary.id);
579
+ summary = this.scrubber.scrubObject(summary);
580
+ const normalizedTranscript = transcriptRelativePath.replaceAll("\\", "/");
581
+ const normalizedSummary = summaryRelativePath.replaceAll("\\", "/");
582
+ if (normalizedTranscript !== `${summary.id}.jsonl` || normalizedSummary !== `${summary.id}.summary.json`) {
583
+ throw new TypeError("Session catalog paths must match the canonical session identity");
584
+ }
585
+ transcriptRelativePath = normalizedTranscript;
586
+ summaryRelativePath = normalizedSummary;
587
+ const transcript = this.containedPath(transcriptRelativePath);
588
+ const stat = fs2.existsSync(transcript) ? fs2.statSync(transcript) : void 0;
589
+ const now = (/* @__PURE__ */ new Date()).toISOString();
590
+ return this.transaction(() => {
591
+ const prior = this.db.prepare("SELECT summary_revision FROM sessions WHERE session_id=?").get(summary.id);
592
+ const revision = (prior?.summary_revision ?? 0) + 1;
593
+ this.db.prepare(`INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,transcript_size,transcript_mtime_ms,summary_revision,indexed_at,damaged)
594
+ VALUES (?,?,?,?,?,?,?,?,0) ON CONFLICT(session_id) DO UPDATE SET transcript_relative_path=excluded.transcript_relative_path,summary_relative_path=excluded.summary_relative_path,summary_json=excluded.summary_json,transcript_size=excluded.transcript_size,transcript_mtime_ms=excluded.transcript_mtime_ms,summary_revision=excluded.summary_revision,indexed_at=excluded.indexed_at,damaged=0`).run(
595
+ summary.id,
596
+ transcriptRelativePath,
597
+ summaryRelativePath,
598
+ JSON.stringify(summary),
599
+ stat?.size ?? 0,
600
+ stat?.mtimeMs ?? 0,
601
+ revision,
602
+ now
603
+ );
604
+ this.bumpGeneration();
605
+ return {
606
+ ...summary,
607
+ transcriptRelativePath,
608
+ summaryRelativePath,
609
+ transcriptSize: stat?.size ?? 0,
610
+ transcriptMtimeMs: stat?.mtimeMs ?? 0,
611
+ summaryRevision: revision,
612
+ indexedAt: now,
613
+ damaged: false
614
+ };
615
+ });
616
+ }
617
+ catalogRecord(row) {
618
+ return {
619
+ ...parseJson(row.summary_json),
620
+ transcriptRelativePath: row.transcript_relative_path,
621
+ summaryRelativePath: row.summary_relative_path,
622
+ transcriptSize: row.transcript_size,
623
+ transcriptMtimeMs: row.transcript_mtime_ms,
624
+ summaryRevision: row.summary_revision,
625
+ indexedAt: row.indexed_at,
626
+ damaged: row.damaged !== 0
627
+ };
628
+ }
629
+ listCatalog(criteria = {}) {
630
+ const requestedLimit = criteria.limit ?? 100;
631
+ if (!Number.isFinite(requestedLimit)) throw new TypeError("Invalid session catalog limit");
632
+ const bounded = Math.min(MAX_PAGE, Math.max(1, Math.floor(requestedLimit)));
633
+ const clauses = [];
634
+ const values = [];
635
+ const jsonText = (field) => `CASE WHEN json_valid(summary_json) THEN json_extract(summary_json,'$.${field}') END`;
636
+ const literalLike = (value) => `%${value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_")}%`;
637
+ const search = criteria.search?.trim();
638
+ if (search) {
639
+ const pattern = literalLike(search);
640
+ clauses.push(
641
+ `(session_id LIKE ? ESCAPE '\\' OR ${jsonText("title")} LIKE ? ESCAPE '\\' OR ${jsonText("name")} LIKE ? ESCAPE '\\')`
642
+ );
643
+ values.push(pattern, pattern, pattern);
644
+ }
645
+ if (criteria.since) {
646
+ clauses.push(`${jsonText("startedAt")}>=?`);
647
+ values.push(criteria.since);
648
+ }
649
+ if (criteria.until) {
650
+ clauses.push(`${jsonText("startedAt")}<=?`);
651
+ values.push(criteria.until);
652
+ }
653
+ if (criteria.provider) {
654
+ clauses.push(`${jsonText("provider")}=?`);
655
+ values.push(criteria.provider);
656
+ }
657
+ if (criteria.model) {
658
+ clauses.push(`${jsonText("model")}=?`);
659
+ values.push(criteria.model);
660
+ }
661
+ if (criteria.minTokens !== void 0) {
662
+ if (!Number.isFinite(criteria.minTokens)) throw new TypeError("Invalid minimum token count");
663
+ clauses.push(`CAST(COALESCE(${jsonText("tokenTotal")},0) AS REAL)>=?`);
664
+ values.push(criteria.minTokens);
665
+ }
666
+ if (criteria.titleContains) {
667
+ clauses.push(`${jsonText("title")} LIKE ? ESCAPE '\\'`);
668
+ values.push(literalLike(criteria.titleContains.toLocaleLowerCase()));
669
+ }
670
+ const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
671
+ const rows = this.db.prepare(
672
+ `SELECT * FROM sessions${where} ORDER BY COALESCE(${jsonText("lastActivityAt")},${jsonText("endedAt")},${jsonText("startedAt")}) DESC,${jsonText("startedAt")} DESC,session_id ASC LIMIT ?`
673
+ ).all(...values, bounded);
674
+ return rows.map((row) => this.catalogRecord(row));
675
+ }
676
+ getSummary(sessionId) {
677
+ const row = this.db.prepare("SELECT * FROM sessions WHERE session_id=?").get(sessionId);
678
+ return row ? this.catalogRecord(row) : null;
679
+ }
680
+ resolveId(query) {
681
+ const normalized = query.trim();
682
+ if (!normalized) throw new Error("Session not found: (empty query)");
683
+ if (this.getSummary(normalized)) return normalized;
684
+ const rows = this.db.prepare(
685
+ "SELECT session_id FROM sessions WHERE session_id LIKE ? OR session_id LIKE ? LIMIT 3"
686
+ ).all(`%/${normalized}`, `${normalized}%`);
687
+ const ids = [...new Set(rows.map((row) => row.session_id))];
688
+ if (ids.length === 1) return ids[0];
689
+ if (ids.length === 0) throw new Error(`Session not found: ${query}`);
690
+ throw new Error(`Ambiguous session id "${query}": ${ids.join(", ")}`);
691
+ }
692
+ async rename(sessionId, name) {
693
+ const current = this.getSummary(this.resolveId(sessionId));
694
+ if (!current) throw new Error(`Session not found: ${sessionId}`);
695
+ const trimmed = name.trim();
696
+ const summary = { ...current };
697
+ for (const key of [
698
+ "transcriptRelativePath",
699
+ "summaryRelativePath",
700
+ "transcriptSize",
701
+ "transcriptMtimeMs",
702
+ "summaryRevision",
703
+ "indexedAt",
704
+ "damaged"
705
+ ])
706
+ delete summary[key];
707
+ const previous = { ...summary };
708
+ if (trimmed) summary.name = this.scrubber.scrub(trimmed).slice(0, 500);
709
+ else delete summary.name;
710
+ const summaryPath = this.containedPath(current.summaryRelativePath);
711
+ fs2.mkdirSync(path2.dirname(summaryPath), { recursive: true, mode: 448 });
712
+ await atomicWrite(summaryPath, `${JSON.stringify(summary)}
713
+ `, { mode: 384 });
714
+ try {
715
+ return this.upsertSummary(
716
+ summary,
717
+ current.transcriptRelativePath,
718
+ current.summaryRelativePath
719
+ );
720
+ } catch (error) {
721
+ await atomicWrite(summaryPath, `${JSON.stringify(previous)}
722
+ `, { mode: 384 }).catch(
723
+ () => void 0
724
+ );
725
+ throw error;
726
+ }
727
+ }
728
+ acquireMaintenance(sessionId, operation, holderId, leaseMs, holderPid) {
729
+ assertId(sessionId);
730
+ return this.transaction(() => {
731
+ this.reapExpired();
732
+ const live = this.leaseRow(sessionId);
733
+ if (live && (operation === "delete" || this.foreignLiveLease(sessionId, holderPid))) {
734
+ throw conflict(`Session ${sessionId} is live`);
735
+ }
736
+ const reservation = this.db.prepare(
737
+ "SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
738
+ ).get(sessionId, Date.now());
739
+ if (reservation) throw conflict(`Session ${sessionId} is reserved for resume`);
740
+ const leaseId = randomUUID();
741
+ const now = Date.now();
742
+ const expiresAt = now + boundedMs(leaseMs, 6e4, MAX_MAINTENANCE_MS);
743
+ try {
744
+ this.db.prepare(
745
+ "INSERT INTO maintenance_leases(session_id,operation,holder_id,lease_id,acquired_at,expires_at) VALUES (?,?,?,?,?,?)"
746
+ ).run(sessionId, operation, holderId, leaseId, now, expiresAt);
747
+ } catch {
748
+ throw conflict(`Session ${sessionId} already has maintenance in progress`);
749
+ }
750
+ return { sessionId, operation, holderId, leaseId, expiresAt };
751
+ });
752
+ }
753
+ releaseMaintenance(lease) {
754
+ this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=?").run(lease.sessionId, lease.leaseId, lease.holderId);
755
+ }
756
+ delete(sessionId, lease) {
757
+ const row = this.db.prepare(
758
+ "SELECT * FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
759
+ ).get(sessionId, lease.leaseId, lease.holderId, lease.operation, Date.now());
760
+ if (!row || lease.operation !== "delete")
761
+ throw conflict("A valid delete maintenance lease is required");
762
+ const record = this.getSummary(sessionId);
763
+ if (!record) throw new Error(`Session not found: ${sessionId}`);
764
+ const transcript = this.containedPath(record.transcriptRelativePath);
765
+ const artifacts = [
766
+ transcript,
767
+ this.containedPath(record.summaryRelativePath),
768
+ this.containedPath(`${sessionId}.plan.json`),
769
+ this.containedPath(`${sessionId}.tasks.json`),
770
+ this.containedPath(`${sessionId}.todos.json`),
771
+ path2.join(path2.dirname(transcript), path2.basename(sessionId))
772
+ ];
773
+ const trashRoot = path2.join(this.sessionsDir, "_trash", lease.leaseId);
774
+ fs2.mkdirSync(trashRoot, { recursive: true, mode: 448 });
775
+ const moved = [];
776
+ try {
777
+ artifacts.forEach((artifact, index) => {
778
+ if (!fs2.existsSync(artifact)) return;
779
+ const target = path2.join(trashRoot, `${index}-${path2.basename(artifact)}`);
780
+ fs2.renameSync(artifact, target);
781
+ moved.push({ from: artifact, to: target });
782
+ });
783
+ this.transaction(() => {
784
+ const current = this.db.prepare(
785
+ "SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
786
+ ).get(sessionId, lease.leaseId, lease.holderId, "delete", Date.now());
787
+ if (!current) throw conflict("Delete maintenance lease expired while staging artifacts");
788
+ this.db.prepare("DELETE FROM sessions WHERE session_id=?").run(sessionId);
789
+ this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=?").run(sessionId);
790
+ this.bumpGeneration();
791
+ });
792
+ } catch (error) {
793
+ for (const item of moved.reverse()) {
794
+ try {
795
+ fs2.mkdirSync(path2.dirname(item.from), { recursive: true, mode: 448 });
796
+ fs2.renameSync(item.to, item.from);
797
+ } catch {
798
+ }
799
+ }
800
+ throw error;
801
+ }
802
+ try {
803
+ fs2.rmSync(trashRoot, { recursive: true, force: true });
804
+ const trashParent = path2.dirname(trashRoot);
805
+ if (fs2.readdirSync(trashParent).length === 0) fs2.rmdirSync(trashParent);
806
+ } catch {
807
+ }
808
+ }
809
+ prune(maxAgeDays, holderId) {
810
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) throw new TypeError("Invalid prune age");
811
+ const cutoff = Date.now() - maxAgeDays * 864e5;
812
+ const candidates = this.db.prepare("SELECT session_id FROM sessions WHERE transcript_mtime_ms<?").all(cutoff);
813
+ let deleted = 0;
814
+ for (const { session_id: id } of candidates) {
815
+ try {
816
+ const lease = this.acquireMaintenance(id, "delete", holderId);
817
+ this.delete(id, lease);
818
+ deleted++;
819
+ } catch (error) {
820
+ if (error.name !== "SessionOwnershipConflictError") throw error;
821
+ }
822
+ }
823
+ return deleted;
824
+ }
825
+ rebuildCatalog() {
826
+ return rebuildCatalogIndex(
827
+ this.db,
828
+ this.sessionsDir,
829
+ (rel) => this.containedPath(rel),
830
+ (run) => this.transaction(run),
831
+ () => this.bumpGeneration()
832
+ );
833
+ }
834
+ health(base) {
835
+ this.reapExpired();
836
+ const count = (table, where = "") => Number(
837
+ this.db.prepare(`SELECT COUNT(*) AS count FROM ${table} ${where}`).get().count
838
+ );
839
+ const reconciliation = this.db.prepare("SELECT value FROM catalog_meta WHERE key='last_reconciliation'").get();
840
+ return {
841
+ ...base,
842
+ catalogRows: count("sessions"),
843
+ damagedRows: count("sessions", "WHERE damaged<>0"),
844
+ liveLeases: count("session_leases"),
845
+ reservations: count("resume_reservations"),
846
+ maintenanceLeases: count("maintenance_leases"),
847
+ generation: this.generation(),
848
+ ...reconciliation ? { lastReconciliation: reconciliation.value } : {}
849
+ };
850
+ }
851
+ };
852
+
853
+ export {
854
+ SessionCatalogStore
855
+ };
856
+ //# sourceMappingURL=chunk-AI4LLQ2U.js.map