larness 0.5.1 → 0.6.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 (53) hide show
  1. package/apps/server/dist/{managed-Cw3MVilO.js → address-DpgJ0siq.js} +317 -183
  2. package/apps/server/dist/{args-CrKTPT06.js → args-BdJc1CBU.js} +29 -22
  3. package/apps/server/dist/cli.js +28 -7
  4. package/apps/server/dist/client-CBpatu1B.js +28 -0
  5. package/apps/server/dist/{client-D_Ni3Zpx.js → client-CoxHAiNW.js} +1 -1
  6. package/apps/server/dist/doctor-CGNZt_v3.js +1 -0
  7. package/apps/server/dist/{doctor-CE6cONuz.js → doctor-rpwPrkoS.js} +4 -3
  8. package/apps/server/dist/doctor.js +1 -1
  9. package/apps/server/dist/index.js +1442 -500
  10. package/apps/server/dist/{inspect-XgAc84F9.js → inspect-DUe_-Yma.js} +89 -1
  11. package/apps/server/dist/{lifecycle-C3KV3-Ax.js → lifecycle-Ck4LRKft.js} +7 -4
  12. package/apps/server/dist/managed-CpNf_iJZ.js +191 -0
  13. package/apps/server/dist/status-B6kiOT0f.js +94 -0
  14. package/apps/server/dist/status-C0hriYPD.js +681 -0
  15. package/apps/server/dist/status.js +1 -58
  16. package/apps/server/dist/{supervisor-IYDKL4iU.js → supervisor-BvHyiN7Z.js} +3 -2
  17. package/apps/server/dist/tui.js +5 -5
  18. package/apps/server/dist/unlock-hrRXYx4L.js +87 -0
  19. package/apps/server/drizzle/0039_user_input_requests.sql +20 -0
  20. package/apps/server/drizzle/meta/0039_snapshot.json +5907 -0
  21. package/apps/server/drizzle/meta/_journal.json +7 -0
  22. package/apps/web/dist/assets/{FileEditor-DnQa6Owc.js → FileEditor-2VPjs-RQ.js} +1 -1
  23. package/apps/web/dist/assets/{FileViewer-DKlF-CWF.js → FileViewer-CZcKFZJT.js} +1 -1
  24. package/apps/web/dist/assets/{cssMode-C9KmpsHc.js → cssMode-D-Rled60.js} +1 -1
  25. package/apps/web/dist/assets/{editor.api-BwfHyHQ6.js → editor.api-C3oaU0qj.js} +1 -1
  26. package/apps/web/dist/assets/{freemarker2-D41RlIQ5.js → freemarker2-D50E-mj1.js} +1 -1
  27. package/apps/web/dist/assets/{handlebars-D-7R6ic0.js → handlebars-_Xg_xwtq.js} +1 -1
  28. package/apps/web/dist/assets/{html-CUME4rt-.js → html-BPuGWYaH.js} +1 -1
  29. package/apps/web/dist/assets/{htmlMode-8w7WLhnL.js → htmlMode-CwmSqoNt.js} +1 -1
  30. package/apps/web/dist/assets/{index-BOS3UrP1.js → index-DPZpqlAG.js} +2 -2
  31. package/apps/web/dist/assets/{javascript-_3pdDG34.js → javascript-iFH4qFsX.js} +1 -1
  32. package/apps/web/dist/assets/{jsonMode-DiqocFCf.js → jsonMode-On0Ct3VU.js} +1 -1
  33. package/apps/web/dist/assets/{liquid-j0FoiTXN.js → liquid-BX3WY7Z7.js} +1 -1
  34. package/apps/web/dist/assets/{lspLanguageFeatures-Zj7K2sG4.js → lspLanguageFeatures-BXlOyN1U.js} +1 -1
  35. package/apps/web/dist/assets/main-Bm74KyWu.css +1 -0
  36. package/apps/web/dist/assets/main-GXToakQe.js +157 -0
  37. package/apps/web/dist/assets/{mdx-CGQ8Cw6J.js → mdx-Bzq19TjL.js} +1 -1
  38. package/apps/web/dist/assets/{monaco-CyMA3azg.js → monaco-DCdDhoJ6.js} +3 -3
  39. package/apps/web/dist/assets/{python-BtY34Z9A.js → python-CaZSKPNI.js} +1 -1
  40. package/apps/web/dist/assets/{razor-CzYHpLv5.js → razor-CH1GgILn.js} +1 -1
  41. package/apps/web/dist/assets/{tsMode-GZx3VEv9.js → tsMode-BWGjCNkx.js} +1 -1
  42. package/apps/web/dist/assets/{typescript-CAfvuTDQ.js → typescript-D2FxAaol.js} +1 -1
  43. package/apps/web/dist/assets/{workers-C5BOxOmH.js → workers-BUPNyHSF.js} +1 -1
  44. package/apps/web/dist/assets/{xml-BGX4mtH7.js → xml-nOgwOHKV.js} +1 -1
  45. package/apps/web/dist/assets/{yaml-B2AgBtJB.js → yaml-CyK2AZ1G.js} +1 -1
  46. package/apps/web/dist/index.html +1 -1
  47. package/docs/guides/install.md +3 -0
  48. package/package.json +1 -1
  49. package/apps/server/dist/address-D0ZG5qR4.js +0 -97
  50. package/apps/server/dist/doctor-sPRlI92N.js +0 -1
  51. package/apps/server/dist/status-CV_zWfs6.js +0 -62
  52. package/apps/web/dist/assets/main-DZIruO5x.js +0 -157
  53. package/apps/web/dist/assets/main-gq3n_vn8.css +0 -1
@@ -0,0 +1,681 @@
1
+ import { C as auditLogs, E as commandExecutions, F as fileVersions, G as resourceActions, J as resourceOperations, K as resourceEvents, T as browserSessions, Y as resourceStreams, ct as terminals, i as inspectInstanceLock, l as loadConfig, mt as newId, q as resourceLocks, st as terminalLeases, t as inspectDatabase, ut as turns } from "./inspect-DUe_-Yma.js";
2
+ import { ct as processAlive, et as isInsideRoot, rt as groupAlive } from "./address-DpgJ0siq.js";
3
+ import { t as SERVER_VERSION } from "./version-ui_X8H2k.js";
4
+ import { r as resolveDataDir } from "./paths-BhVn34MT.js";
5
+ import { t as findMainLogFile } from "./log-files-CFOaEy6O.js";
6
+ import { existsSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { and, asc, count, desc, eq, gt, gte, inArray, lt, sql } from "drizzle-orm";
9
+ import BetterSqlite3 from "better-sqlite3";
10
+ // src/security/sanitize.ts
11
+ const SENSITIVE_KEY = /(password|token|secret|cookie|authorization|pairing|csrf|api[-_]?key|hash)/i;
12
+ function sanitizeAuditDetails(value) {
13
+ if (Array.isArray(value)) return value.map((item) => sanitizeAuditDetails(item));
14
+ if (value !== null && typeof value === "object") {
15
+ const result = {};
16
+ for (const [key, entry] of Object.entries(value)) result[key] = SENSITIVE_KEY.test(key) ? "[Redacted]" : sanitizeAuditDetails(entry);
17
+ return result;
18
+ }
19
+ return value;
20
+ }
21
+ // src/db/repositories/audit.ts
22
+ function appendAudit(db, input) {
23
+ if (input.action.trim().length === 0) throw new Error("audit action must not be empty");
24
+ const row = {
25
+ id: newId("aud"),
26
+ clientSessionId: input.clientSessionId ?? null,
27
+ sessionId: input.sessionId ?? null,
28
+ action: input.action,
29
+ resourceType: input.resourceType ?? null,
30
+ resourceId: input.resourceId ?? null,
31
+ decision: input.decision ?? null,
32
+ detailsJson: JSON.stringify(sanitizeAuditDetails(input.details ?? {})),
33
+ createdAt: input.now ?? Date.now()
34
+ };
35
+ db.insert(auditLogs).values(row).run();
36
+ return row;
37
+ }
38
+ function listRecentAudit(db, limit = 200) {
39
+ const safeLimit = Math.min(Math.max(Math.trunc(limit), 1), 200);
40
+ return db.select().from(auditLogs).orderBy(desc(auditLogs.createdAt), desc(auditLogs.id)).limit(safeLimit).all();
41
+ }
42
+ // src/db/transaction.ts
43
+ function immediateTransaction(db, run) {
44
+ return db.transaction((tx) => run(tx), { behavior: "immediate" });
45
+ }
46
+ // src/modules/resources/repository.ts
47
+ function findOperation(db, client, key, kind = "file.save") {
48
+ return db.select().from(resourceOperations).where(and(eq(resourceOperations.clientSessionId, client), eq(resourceOperations.kind, kind), eq(resourceOperations.idempotencyKey, key))).get() ?? null;
49
+ }
50
+ function pendingOperations(db) {
51
+ return db.select().from(resourceOperations).where(inArray(resourceOperations.status, [
52
+ "PREPARED",
53
+ "WRITING",
54
+ "RECONCILIATION_REQUIRED"
55
+ ])).all();
56
+ }
57
+ function insertOperation(db, row) {
58
+ db.insert(resourceOperations).values(row).run();
59
+ }
60
+ function updateOperation(db, id, values) {
61
+ db.update(resourceOperations).set(values).where(eq(resourceOperations.id, id)).run();
62
+ }
63
+ function cacheFileVersion(db, input) {
64
+ db.insert(fileVersions).values(input).onConflictDoUpdate({
65
+ target: [fileVersions.scopeKey, fileVersions.path],
66
+ set: input
67
+ }).run();
68
+ }
69
+ function appendResourceEvent(db, streamId, type, payload, now) {
70
+ const stream = db.insert(resourceStreams).values({
71
+ streamId,
72
+ lastSeq: 1
73
+ }).onConflictDoUpdate({
74
+ target: resourceStreams.streamId,
75
+ set: { lastSeq: sql`${resourceStreams.lastSeq} + 1` }
76
+ }).returning().get();
77
+ const row = {
78
+ id: newId("evt"),
79
+ streamId,
80
+ seq: stream.lastSeq,
81
+ type,
82
+ payloadJson: JSON.stringify(payload),
83
+ createdAt: now
84
+ };
85
+ db.insert(resourceEvents).values(row).run();
86
+ return row;
87
+ }
88
+ function resourceSequence(db, streamId) {
89
+ return db.select().from(resourceStreams).where(eq(resourceStreams.streamId, streamId)).get()?.lastSeq ?? 0;
90
+ }
91
+ function readResourceEvents(db, streamId, after, limit, cutoff) {
92
+ return db.select().from(resourceEvents).where(and(eq(resourceEvents.streamId, streamId), gt(resourceEvents.seq, after), gte(resourceEvents.createdAt, cutoff))).orderBy(asc(resourceEvents.seq)).limit(limit).all();
93
+ }
94
+ function pruneResourceEvents(db, cutoff) {
95
+ return db.delete(resourceEvents).where(lt(resourceEvents.createdAt, cutoff)).run().changes;
96
+ }
97
+ function getCachedFile(db, scopeKey, path) {
98
+ return db.select().from(fileVersions).where(and(eq(fileVersions.scopeKey, scopeKey), eq(fileVersions.path, path))).get();
99
+ }
100
+ function deleteCachedFile(db, scopeKey, path) {
101
+ db.delete(fileVersions).where(and(eq(fileVersions.scopeKey, scopeKey), eq(fileVersions.path, path))).run();
102
+ }
103
+ function deleteResourceActionsForProject(db, projectId) {
104
+ db.delete(resourceActions).where(eq(resourceActions.projectId, projectId)).run();
105
+ }
106
+ function deleteOperation(db, id) {
107
+ db.delete(resourceOperations).where(eq(resourceOperations.id, id)).run();
108
+ }
109
+ // src/modules/locks/quarantine.ts
110
+ const roots = /* @__PURE__ */ new Map();
111
+ function quarantineRoot(operationId, root) {
112
+ roots.set(operationId, root);
113
+ }
114
+ function clearRootQuarantine(operationId) {
115
+ roots.delete(operationId);
116
+ }
117
+ function rootIsQuarantined(root) {
118
+ return [...roots.values()].some((other) => isInsideRoot(root, other) || isInsideRoot(other, root));
119
+ }
120
+ function quarantinedRoots() {
121
+ return [...new Set(roots.values())];
122
+ }
123
+ // src/modules/locks/repository.ts
124
+ function rootHasWriter(db, root, now, excludeLockId) {
125
+ if (rootIsQuarantined(root)) return true;
126
+ const overlaps = (other) => isInsideRoot(root, other) || isInsideRoot(other, root);
127
+ if (pendingOperations(db).some((operation) => overlaps(operation.rootRealPath) && !(operation.lockId === excludeLockId && operation.status !== "RECONCILIATION_REQUIRED"))) return true;
128
+ return db.select().from(resourceLocks).all().some((lock) => {
129
+ if (lock.id === excludeLockId) return false;
130
+ if (lock.rootRealPath === null || !overlaps(lock.rootRealPath)) return false;
131
+ if (lock.expiresAt <= 0) return false;
132
+ if (lock.expiresAt > now) return true;
133
+ const turn = db.select().from(turns).where(eq(turns.id, lock.executionId)).get();
134
+ return turn !== void 0 && [
135
+ "QUEUED",
136
+ "PREPARING",
137
+ "RUNNING",
138
+ "WAITING_APPROVAL",
139
+ "WAITING_INPUT",
140
+ "CANCELLING"
141
+ ].includes(turn.status);
142
+ });
143
+ }
144
+ function getResourceLockRowById(db, id) {
145
+ return db.select().from(resourceLocks).where(eq(resourceLocks.id, id)).get() ?? null;
146
+ }
147
+ function getResourceLockRow(db, resourceType, resourceId) {
148
+ return db.select().from(resourceLocks).where(and(eq(resourceLocks.resourceType, resourceType), eq(resourceLocks.resourceId, resourceId))).get() ?? null;
149
+ }
150
+ function insertResourceLockRow(db, row) {
151
+ db.insert(resourceLocks).values(row).run();
152
+ return row;
153
+ }
154
+ function updateResourceLockRow(db, id, input) {
155
+ db.update(resourceLocks).set(input).where(eq(resourceLocks.id, id)).run();
156
+ return db.select().from(resourceLocks).where(eq(resourceLocks.id, id)).get() ?? null;
157
+ }
158
+ function renewResourceLockRow(db, input) {
159
+ if (db.update(resourceLocks).set({
160
+ expiresAt: input.expiresAt,
161
+ heartbeatAt: input.heartbeatAt
162
+ }).where(and(eq(resourceLocks.id, input.id), eq(resourceLocks.fencingToken, input.fencingToken), gt(resourceLocks.expiresAt, 0))).run().changes === 0) return null;
163
+ return db.select().from(resourceLocks).where(eq(resourceLocks.id, input.id)).get() ?? null;
164
+ }
165
+ function releaseResourceLockRow(db, input) {
166
+ return db.update(resourceLocks).set({
167
+ expiresAt: 0,
168
+ heartbeatAt: input.now
169
+ }).where(and(eq(resourceLocks.id, input.id), eq(resourceLocks.fencingToken, input.fencingToken))).run().changes > 0;
170
+ }
171
+ // src/modules/commands/repository.ts
172
+ function commandRow(db, id) {
173
+ return db.select().from(commandExecutions).where(eq(commandExecutions.id, id)).get() ?? null;
174
+ }
175
+ function commandByOperation(db, id) {
176
+ return db.select().from(commandExecutions).where(eq(commandExecutions.operationId, id)).get() ?? null;
177
+ }
178
+ function insertCommand(db, row) {
179
+ db.insert(commandExecutions).values(row).run();
180
+ }
181
+ function updateCommand(db, id, fields) {
182
+ db.update(commandExecutions).set(fields).where(eq(commandExecutions.id, id)).run();
183
+ }
184
+ function unfinishedCommands(db) {
185
+ return db.select().from(commandExecutions).where(inArray(commandExecutions.status, [
186
+ "CREATED",
187
+ "RUNNING",
188
+ "CANCELLING"
189
+ ])).all();
190
+ }
191
+ function oldCommands(db, cutoff) {
192
+ return db.select().from(commandExecutions).where(lt(commandExecutions.endedAt, cutoff)).all();
193
+ }
194
+ function operationRow(db, id) {
195
+ return db.select().from(resourceOperations).where(eq(resourceOperations.id, id)).get() ?? null;
196
+ }
197
+ function activeCommandClient(db, id, now, idleTtlMinutes = 30) {
198
+ const row = db.select().from(browserSessions).where(eq(browserSessions.id, id)).get();
199
+ return row !== void 0 && row.revokedAt === null && row.expiresAt > now && row.lastSeenAt + idleTtlMinutes * 6e4 > now;
200
+ }
201
+ function deleteCommand(db, row) {
202
+ const operation = operationRow(db, row.operationId);
203
+ if (!operation || !["COMPLETED", "FAILED"].includes(operation.status)) return;
204
+ db.delete(commandExecutions).where(eq(commandExecutions.id, row.id)).run();
205
+ db.delete(resourceOperations).where(and(eq(resourceOperations.id, row.operationId), eq(resourceOperations.kind, "command.run"))).run();
206
+ }
207
+ // src/modules/terminals/repository.ts
208
+ const terminalRow = (db, id) => db.select().from(terminals).where(eq(terminals.id, id)).get() ?? null;
209
+ function terminalByOperation(db, id) {
210
+ return db.select().from(terminals).where(eq(terminals.operationId, id)).get() ?? null;
211
+ }
212
+ const leaseRow = (db, id) => db.select().from(terminalLeases).where(eq(terminalLeases.terminalId, id)).get() ?? null;
213
+ function insertTerminal(db, row) {
214
+ db.insert(terminals).values(row).run();
215
+ db.insert(terminalLeases).values({ terminalId: row.id }).run();
216
+ }
217
+ function updateTerminal(db, id, fields) {
218
+ db.update(terminals).set(fields).where(eq(terminals.id, id)).run();
219
+ }
220
+ function updateLease(db, id, fields) {
221
+ db.update(terminalLeases).set(fields).where(eq(terminalLeases.terminalId, id)).run();
222
+ }
223
+ function allTerminals(db) {
224
+ return db.select().from(terminals).orderBy(asc(terminals.createdAt), asc(terminals.id)).all();
225
+ }
226
+ function activeTerminals(db) {
227
+ return db.select().from(terminals).where(inArray(terminals.status, [
228
+ "CREATED",
229
+ "RUNNING",
230
+ "STOPPING"
231
+ ])).all();
232
+ }
233
+ function runningTerminalCounts(db) {
234
+ const rows = db.select({
235
+ projectId: terminals.projectId,
236
+ value: count()
237
+ }).from(terminals).where(eq(terminals.status, "RUNNING")).groupBy(terminals.projectId).all();
238
+ return new Map(rows.map((row) => [row.projectId, row.value]));
239
+ }
240
+ function oldTerminals(db, cutoff) {
241
+ return db.select().from(terminals).where(lt(terminals.endedAt, cutoff)).all();
242
+ }
243
+ function deleteTerminal(db, id) {
244
+ db.delete(terminalLeases).where(eq(terminalLeases.terminalId, id)).run();
245
+ db.delete(terminals).where(eq(terminals.id, id)).run();
246
+ }
247
+ function rootHasTerminal(db, root) {
248
+ return activeTerminals(db).some((row) => {
249
+ const op = operationRow(db, row.operationId);
250
+ return op && (isInsideRoot(root, op.rootRealPath) || isInsideRoot(op.rootRealPath, root));
251
+ });
252
+ }
253
+ // src/modules/locks/barriers.ts
254
+ /** The only operation kinds that record an external process identity. */
255
+ const PROCESS_OPERATION_KINDS = /* @__PURE__ */ new Set(["command.run", "terminal.create"]);
256
+ /** File operations carry disk side effects that a PID probe cannot prove. */
257
+ const FILE_OPERATION_KINDS = /* @__PURE__ */ new Set(["file.save", "file.action"]);
258
+ const ACTIVE_TURN_STATUSES = /* @__PURE__ */ new Set([
259
+ "QUEUED",
260
+ "PREPARING",
261
+ "RUNNING",
262
+ "WAITING_APPROVAL",
263
+ "WAITING_INPUT",
264
+ "CANCELLING"
265
+ ]);
266
+ function isFileOperationKind(kind) {
267
+ return FILE_OPERATION_KINDS.has(kind);
268
+ }
269
+ /**
270
+ * Reads the `pid` field of a command / terminal process identity. Anything
271
+ * malformed is treated as "no identity", which only makes the barrier more
272
+ * likely to be retained.
273
+ */
274
+ function identityPid(json) {
275
+ if (json === null || json === void 0 || json.length === 0) return null;
276
+ try {
277
+ const value = JSON.parse(json);
278
+ if (typeof value !== "object" || value === null || !("pid" in value)) return null;
279
+ const pid = value.pid;
280
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : null;
281
+ } catch {
282
+ return null;
283
+ }
284
+ }
285
+ /**
286
+ * Default probe. Alive-by-PID is authoritative; a POSIX process group is also
287
+ * checked so a dead leader with live children still counts as a writer.
288
+ * A failed snapshot is "unknown", never "dead".
289
+ */
290
+ const systemProcessProbe = async (pid) => {
291
+ if (processAlive(pid)) return "alive";
292
+ if (process.platform === "win32") return "dead";
293
+ try {
294
+ return await groupAlive(pid) ? "alive" : "dead";
295
+ } catch {
296
+ return "unknown";
297
+ }
298
+ };
299
+ async function probePids(pids, probe = systemProcessProbe) {
300
+ const unique = [...new Set(pids)];
301
+ const verdicts = /* @__PURE__ */ new Map();
302
+ for (const pid of unique) try {
303
+ verdicts.set(pid, await probe(pid));
304
+ } catch {
305
+ verdicts.set(pid, "unknown");
306
+ }
307
+ return verdicts;
308
+ }
309
+ function classifyOperation(operation, verdicts) {
310
+ if (isFileOperationKind(operation.kind)) return "file_uncertain";
311
+ if (!PROCESS_OPERATION_KINDS.has(operation.kind)) return "settleable";
312
+ if (operation.pid === null) return operation.status === "PREPARED" ? "settleable" : "process_unknown";
313
+ switch (verdicts.get(operation.pid) ?? "unknown") {
314
+ case "dead": return "settleable";
315
+ case "alive": return "live_process";
316
+ default: return "probe_failed";
317
+ }
318
+ }
319
+ function classifyBarriers(input) {
320
+ const operations = input.operations.map((operation) => ({
321
+ ...operation,
322
+ reason: classifyOperation(operation, input.verdicts)
323
+ }));
324
+ const retainedLockIds = new Set(operations.filter((operation) => operation.reason !== "settleable" && operation.lockId.length > 0).map((operation) => operation.lockId));
325
+ return {
326
+ operations,
327
+ locks: input.locks.filter((lock) => lock.expiresAt > 0).map((lock) => {
328
+ if (retainedLockIds.has(lock.id)) return {
329
+ ...lock,
330
+ reason: "pending_operation"
331
+ };
332
+ if (lock.ownerTurnActive) return {
333
+ ...lock,
334
+ reason: "active_turn"
335
+ };
336
+ return {
337
+ ...lock,
338
+ reason: "settleable"
339
+ };
340
+ })
341
+ };
342
+ }
343
+ /**
344
+ * `startup` only clears provable orphans. `force` is an explicit local
345
+ * override: it clears everything except live processes unless `allowLive`.
346
+ */
347
+ function shouldClearBarrier(reason, mode, allowLive) {
348
+ if (mode === "startup") return reason === "settleable";
349
+ if (reason === "live_process") return allowLive;
350
+ return true;
351
+ }
352
+ // src/modules/locks/settlement.ts
353
+ function lockOwnerIsActive(db, lock) {
354
+ const turn = db.select().from(turns).where(eq(turns.id, lock.executionId)).get();
355
+ return turn !== void 0 && ACTIVE_TURN_STATUSES.has(turn.status);
356
+ }
357
+ function executionPid(db, operation) {
358
+ return identityPid((operation.kind === "command.run" ? commandByOperation(db, operation.id) : operation.kind === "terminal.create" ? terminalByOperation(db, operation.id) : null)?.processIdentityJson ?? null);
359
+ }
360
+ function toOperationInput(db, operation) {
361
+ return {
362
+ id: operation.id,
363
+ kind: operation.kind,
364
+ status: operation.status,
365
+ errorCode: operation.errorCode,
366
+ rootRealPath: operation.rootRealPath,
367
+ path: operation.path,
368
+ lockId: operation.lockId,
369
+ fencingToken: operation.fencingToken,
370
+ pid: executionPid(db, operation),
371
+ resultJson: operation.resultJson
372
+ };
373
+ }
374
+ function lockInputs(db) {
375
+ return db.select().from(resourceLocks).all().filter((lock) => lock.expiresAt > 0).map((lock) => ({
376
+ id: lock.id,
377
+ resourceType: lock.resourceType,
378
+ resourceId: lock.resourceId,
379
+ owner: lock.owner,
380
+ executionId: lock.executionId,
381
+ fencingToken: lock.fencingToken,
382
+ rootRealPath: lock.rootRealPath,
383
+ expiresAt: lock.expiresAt,
384
+ ownerTurnActive: lockOwnerIsActive(db, lock)
385
+ }));
386
+ }
387
+ /** Classify every live barrier, probing only the recorded PIDs. */
388
+ async function collectBarrierAudit(db, options = {}) {
389
+ const operations = pendingOperations(db).map((operation) => toOperationInput(db, operation));
390
+ const verdicts = await probePids(operations.flatMap((operation) => operation.pid === null ? [] : [operation.pid]), options.probe ?? systemProcessProbe);
391
+ return classifyBarriers({
392
+ operations,
393
+ locks: lockInputs(db),
394
+ verdicts
395
+ });
396
+ }
397
+ function reconciledResultJson(operation, reconciledBy) {
398
+ let existing = {};
399
+ if (operation.resultJson !== null) try {
400
+ const parsed = JSON.parse(operation.resultJson);
401
+ if (typeof parsed === "object" && parsed !== null) existing = parsed;
402
+ } catch {
403
+ existing = {};
404
+ }
405
+ return JSON.stringify({
406
+ ...existing,
407
+ reconciledBy,
408
+ previousStatus: operation.status,
409
+ ...operation.errorCode === null ? {} : { previousErrorCode: operation.errorCode }
410
+ });
411
+ }
412
+ function applySettlement(input) {
413
+ const clears = (reason) => shouldClearBarrier(reason, input.mode, input.allowLive);
414
+ const operationTargets = input.audit.operations.filter((operation) => clears(operation.reason));
415
+ const retainedOperationIds = new Set(input.audit.operations.filter((operation) => !clears(operation.reason)).map((op) => op.id));
416
+ const lockTargets = input.mode === "force" ? input.audit.locks : input.audit.locks.filter((l) => clears(l.reason));
417
+ const retainedLocks = input.audit.locks.filter((lock) => !lockTargets.includes(lock));
418
+ if (operationTargets.length === 0 && lockTargets.length === 0) return {
419
+ finalized: 0,
420
+ released: 0,
421
+ retained: {
422
+ operations: input.audit.operations.filter((op) => !clears(op.reason)),
423
+ locks: retainedLocks
424
+ }
425
+ };
426
+ const errorCode = input.mode === "force" ? "FORCE_UNLOCKED" : "OUTCOME_UNKNOWN";
427
+ const reconciledBy = input.mode === "force" ? "unlock" : "startup-sweep";
428
+ const releasedOperationIds = /* @__PURE__ */ new Set();
429
+ const activeLockIds = new Set(input.audit.locks.map((lock) => lock.id));
430
+ return immediateTransaction(input.db, (tx) => {
431
+ let finalized = 0;
432
+ let released = 0;
433
+ for (const operation of operationTargets) {
434
+ updateOperation(tx, operation.id, {
435
+ status: "FAILED",
436
+ errorCode,
437
+ resultJson: reconciledResultJson(operation, reconciledBy),
438
+ updatedAt: input.now
439
+ });
440
+ if (operation.kind === "git.action") tx.update(resourceActions).set({
441
+ status: "INTERRUPTED",
442
+ endedAt: input.now,
443
+ resultJson: JSON.stringify({ errorCode })
444
+ }).where(eq(resourceActions.operationId, operation.id)).run();
445
+ if (operation.lockId.length > 0 && activeLockIds.has(operation.lockId) && releaseResourceLockRow(tx, {
446
+ id: operation.lockId,
447
+ fencingToken: operation.fencingToken,
448
+ now: input.now
449
+ })) {
450
+ released += 1;
451
+ releasedOperationIds.add(operation.lockId);
452
+ }
453
+ finalized += 1;
454
+ }
455
+ for (const lock of lockTargets) {
456
+ if (releasedOperationIds.has(lock.id)) continue;
457
+ if (releaseResourceLockRow(tx, {
458
+ id: lock.id,
459
+ fencingToken: lock.fencingToken,
460
+ now: input.now
461
+ })) released += 1;
462
+ }
463
+ appendAudit(tx, {
464
+ action: input.mode === "force" ? "resource.locks.unlocked" : "resource.locks.settled",
465
+ decision: input.mode === "force" ? "allow" : "info",
466
+ resourceType: "lock",
467
+ details: {
468
+ source: input.mode === "force" ? "cli-offline" : "startup",
469
+ allowLive: input.allowLive,
470
+ finalizedOperations: finalized,
471
+ releasedLocks: released,
472
+ retainedOperations: retainedOperationIds.size,
473
+ retainedLocks: retainedLocks.length
474
+ },
475
+ now: input.now
476
+ });
477
+ return {
478
+ finalized,
479
+ released,
480
+ retained: {
481
+ operations: [],
482
+ locks: retainedLocks
483
+ }
484
+ };
485
+ });
486
+ }
487
+ /**
488
+ * Clear every barrier that can be proven ownerless and report the rest.
489
+ *
490
+ * Run after resource recovery and before serving requests: the instance lock
491
+ * rules out a second management server, but only a process probe can rule out
492
+ * an old child, and only an explicit `force` can override an unknown outcome.
493
+ */
494
+ async function settleWriteBarriers(options) {
495
+ const now = options.now?.() ?? Date.now();
496
+ const allowLive = options.allowLive === true;
497
+ const audit = await collectBarrierAudit(options.db, { ...options.probe === void 0 ? {} : { probe: options.probe } });
498
+ const applied = applySettlement({
499
+ db: options.db,
500
+ now,
501
+ mode: options.mode,
502
+ allowLive,
503
+ audit
504
+ });
505
+ const clears = (reason) => shouldClearBarrier(reason, options.mode, allowLive);
506
+ const retained = {
507
+ operations: audit.operations.filter((operation) => !clears(operation.reason)),
508
+ locks: applied.retained.locks
509
+ };
510
+ if (options.mode === "startup" && options.logger) {
511
+ for (const operation of retained.operations) options.logger.warn({
512
+ operationId: operation.id,
513
+ kind: operation.kind,
514
+ status: operation.status,
515
+ reason: operation.reason,
516
+ pid: operation.pid,
517
+ rootRealPath: operation.rootRealPath
518
+ }, "write barrier cannot be proven orphaned; keeping it");
519
+ for (const lock of retained.locks) options.logger.warn({
520
+ lockId: lock.id,
521
+ resourceType: lock.resourceType,
522
+ resourceId: lock.resourceId,
523
+ reason: lock.reason,
524
+ executionId: lock.executionId
525
+ }, "write barrier cannot be proven orphaned; keeping it");
526
+ }
527
+ return {
528
+ mode: options.mode,
529
+ generatedAt: now,
530
+ finalizedOperations: applied.finalized,
531
+ releasedLocks: applied.released,
532
+ retained,
533
+ quarantinedRoots: quarantinedRoots()
534
+ };
535
+ }
536
+ function retainedCount(audit) {
537
+ return audit.operations.length + audit.locks.length;
538
+ }
539
+ function barrierReasonLabel(reason) {
540
+ switch (reason) {
541
+ case "settleable": return "ownerless; can be cleared";
542
+ case "file_uncertain": return "file outcome unknown; verify the file first";
543
+ case "live_process": return "recorded process is still running";
544
+ case "process_unknown": return "started, but no process identity was recorded";
545
+ case "probe_failed": return "process probe failed; retry later";
546
+ case "pending_operation": return "a retained operation still references this lock";
547
+ case "active_turn": return "the owning turn is still active";
548
+ }
549
+ }
550
+ function readOnlyDatabase(file) {
551
+ return new BetterSqlite3(file, {
552
+ readonly: true,
553
+ fileMustExist: true,
554
+ timeout: 2e3
555
+ });
556
+ }
557
+ function hasTable(sqlite, name) {
558
+ return sqlite.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
559
+ }
560
+ function inspectRows(sqlite) {
561
+ if (!hasTable(sqlite, "resource_operations") || !hasTable(sqlite, "resource_locks")) return null;
562
+ const hasCommands = hasTable(sqlite, "command_executions");
563
+ const hasTerminals = hasTable(sqlite, "terminals");
564
+ const hasTurns = hasTable(sqlite, "turns");
565
+ const operations = sqlite.prepare(`SELECT o.id, o.kind, o.status, o.error_code AS errorCode, o.root_real_path AS rootRealPath,
566
+ o.path, o.lock_id AS lockId, o.fencing_token AS fencingToken,
567
+ o.result_json AS resultJson,
568
+ ${hasCommands ? "(SELECT process_identity_json FROM command_executions WHERE operation_id = o.id)" : "NULL"} AS commandIdentity,
569
+ ${hasTerminals ? "(SELECT process_identity_json FROM terminals WHERE operation_id = o.id)" : "NULL"} AS terminalIdentity
570
+ FROM resource_operations o
571
+ WHERE o.status IN ('PREPARED', 'WRITING', 'RECONCILIATION_REQUIRED')
572
+ ORDER BY o.created_at`).all();
573
+ const locks = sqlite.prepare(`SELECT l.id, l.resource_type AS resourceType, l.resource_id AS resourceId, l.owner,
574
+ l.execution_id AS executionId, l.fencing_token AS fencingToken,
575
+ l.root_real_path AS rootRealPath, l.expires_at AS expiresAt,
576
+ ${hasTurns ? "(SELECT status FROM turns WHERE id = l.execution_id)" : "NULL"} AS turnStatus
577
+ FROM resource_locks l
578
+ WHERE l.expires_at > 0
579
+ ORDER BY l.created_at`).all();
580
+ return {
581
+ operations: operations.map((row) => ({
582
+ id: row.id,
583
+ kind: row.kind,
584
+ status: row.status,
585
+ errorCode: row.errorCode,
586
+ rootRealPath: row.rootRealPath,
587
+ path: row.path,
588
+ lockId: row.lockId,
589
+ fencingToken: row.fencingToken,
590
+ pid: identityPid(row.kind === "command.run" ? row.commandIdentity : row.kind === "terminal.create" ? row.terminalIdentity : null),
591
+ resultJson: row.resultJson
592
+ })),
593
+ locks: locks.map((row) => ({
594
+ id: row.id,
595
+ resourceType: row.resourceType,
596
+ resourceId: row.resourceId,
597
+ owner: row.owner,
598
+ executionId: row.executionId,
599
+ fencingToken: row.fencingToken,
600
+ rootRealPath: row.rootRealPath,
601
+ expiresAt: row.expiresAt,
602
+ ownerTurnActive: row.turnStatus !== null && ACTIVE_TURN_STATUSES.has(row.turnStatus)
603
+ }))
604
+ };
605
+ }
606
+ /**
607
+ * Read-only view for `larness status`, `doctor` and `unlock`. Safe while a
608
+ * server is running: no write, no migration, no lock acquisition.
609
+ */
610
+ async function inspectBarriersFile(file, options = {}) {
611
+ if (!existsSync(file)) return null;
612
+ const sqlite = readOnlyDatabase(file);
613
+ try {
614
+ const rows = inspectRows(sqlite);
615
+ if (rows === null) return null;
616
+ const verdicts = await probePids(rows.operations.flatMap((operation) => operation.pid === null ? [] : [operation.pid]), options.probe ?? systemProcessProbe);
617
+ return classifyBarriers({
618
+ ...rows,
619
+ verdicts
620
+ });
621
+ } finally {
622
+ sqlite.close();
623
+ }
624
+ }
625
+ // src/status.ts
626
+ const FORMAL_SERVICES_NOTE = "PM2 services run separately; larness stop does not stop or restart them";
627
+ async function collectStatus(options = {}) {
628
+ const env = options.env ?? process.env;
629
+ const dataDir = options.dataDir ?? resolveDataDir(env);
630
+ const now = options.now ?? Date.now;
631
+ const loaded = await loadConfig({
632
+ dataDir,
633
+ env
634
+ });
635
+ const lock = await inspectInstanceLock(dataDir);
636
+ const database = inspectDatabase(path.join(dataDir, "larness.db"));
637
+ const mainLog = await findMainLogFile(dataDir);
638
+ const running = lock?.alive === true;
639
+ const record = lock?.record ?? null;
640
+ const warnings = [];
641
+ if (loaded.source === "defaults") warnings.push("config.json is missing; the workspace is not initialized");
642
+ if (lock !== null && !running) warnings.push(record ? `stale lock file from pid ${record.pid}; it will be replaced on the next start` : "lock file is unreadable; verify no server is running before removing it");
643
+ if (!running) warnings.push("server is not running");
644
+ if (database === null) warnings.push("database is not initialized; start the server to run migrations");
645
+ else if (!database.ok) warnings.push(`database check failed: ${database.detail}`);
646
+ return {
647
+ version: SERVER_VERSION,
648
+ initialized: database?.initialized ?? false,
649
+ running,
650
+ pid: running ? record?.pid ?? null : null,
651
+ uptimeMs: running && record ? Math.max(0, now() - record.startedAt) : null,
652
+ listen: {
653
+ host: loaded.config.server.host,
654
+ port: loaded.config.server.port
655
+ },
656
+ db: database,
657
+ ipc: null,
658
+ sessions: {
659
+ online: 0,
660
+ pendingPairings: 0
661
+ },
662
+ publicUrl: loaded.config.server.publicUrl,
663
+ webauthn: {
664
+ enabled: loaded.webAuthn.enabled,
665
+ rpId: loaded.webAuthn.rpId,
666
+ origin: loaded.webAuthn.origin,
667
+ reason: loaded.webAuthn.reason
668
+ },
669
+ warnings,
670
+ dataDir,
671
+ mode: running ? record?.mode ?? "unknown" : null,
672
+ dev: running && record?.dev === true,
673
+ logPath: mainLog,
674
+ daemonLogPath: running && record?.mode === "background" ? path.join(dataDir, "logs", "daemon.log") : null,
675
+ formalServices: {
676
+ managedSeparately: true,
677
+ note: FORMAL_SERVICES_NOTE
678
+ }
679
+ };
680
+ }
681
+ export { updateOperation as $, getResourceLockRow as A, rootIsQuarantined as B, commandRow as C, operationRow as D, oldCommands as E, rootHasWriter as F, deleteResourceActionsForProject as G, cacheFileVersion as H, updateResourceLockRow as I, insertOperation as J, findOperation as K, clearRootQuarantine as L, insertResourceLockRow as M, releaseResourceLockRow as N, unfinishedCommands as O, renewResourceLockRow as P, resourceSequence as Q, quarantineRoot as R, commandByOperation as S, insertCommand as T, deleteCachedFile as U, appendResourceEvent as V, deleteOperation as W, pruneResourceEvents as X, pendingOperations as Y, readResourceEvents as Z, terminalByOperation as _, reconciledResultJson as a, updateTerminal as b, isFileOperationKind as c, deleteTerminal as d, immediateTransaction as et, insertTerminal as f, runningTerminalCounts as g, rootHasTerminal as h, lockOwnerIsActive as i, getResourceLockRowById as j, updateCommand as k, activeTerminals as l, oldTerminals as m, barrierReasonLabel as n, listRecentAudit as nt, retainedCount as o, leaseRow as p, getCachedFile as q, inspectBarriersFile as r, settleWriteBarriers as s, collectStatus as t, appendAudit as tt, allTerminals as u, terminalRow as v, deleteCommand as w, activeCommandClient as x, updateLease as y, quarantinedRoots as z };