@floless/app 0.148.0 → 0.148.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.
@@ -570,6 +570,36 @@ function secure(path, kind2) {
570
570
  function ensureOwnerOnlyStoragePath(path, kind2) {
571
571
  ensureOwnerOnlyStoragePaths([{ path, kind: kind2 }]);
572
572
  }
573
+ function aclBatchOptions(batch) {
574
+ const environment = {
575
+ ...process.env,
576
+ FLOLESS_ACL_BATCH: JSON.stringify(batch),
577
+ FLOLESS_ACL_PROBE: Buffer.from(ACL_PROBE, "utf16le").toString("base64"),
578
+ FLOLESS_ACL_SET: Buffer.from(ACL_SET, "utf16le").toString("base64")
579
+ };
580
+ delete environment.PSModulePath;
581
+ return {
582
+ encoding: "utf8",
583
+ windowsHide: true,
584
+ timeout: 15e3,
585
+ maxBuffer: 4 * 1024 * 1024,
586
+ env: environment,
587
+ stdio: ["ignore", "pipe", "pipe"]
588
+ };
589
+ }
590
+ function checkAclBatchEvidence(output2, batch) {
591
+ let evidence;
592
+ try {
593
+ evidence = JSON.parse(output2);
594
+ } catch (error62) {
595
+ fail("private storage Windows permissions could not be verified", error62);
596
+ }
597
+ if (!Array.isArray(evidence) || evidence.length !== batch.length) fail("private storage Windows permissions returned invalid evidence");
598
+ for (let i = 0; i < batch.length; i += 1) {
599
+ validateExactWindowsAcl(evidence[i], batch[i].kind);
600
+ if (!evidence[i].protected) fail("private storage Windows permissions are not protected");
601
+ }
602
+ }
573
603
  function ensureOwnerOnlyStoragePaths(items) {
574
604
  if (items.length === 0) return;
575
605
  for (const item of items) ordinary(item.path, item.kind);
@@ -582,35 +612,33 @@ function ensureOwnerOnlyStoragePaths(items) {
582
612
  }
583
613
  return;
584
614
  }
585
- const script = Buffer.from(ACL_BATCH, "utf16le").toString("base64");
586
615
  for (let at = 0; at < items.length; at += 64) {
587
616
  const batch = items.slice(at, at + 64);
588
- const environment = {
589
- ...process.env,
590
- FLOLESS_ACL_BATCH: JSON.stringify(batch),
591
- FLOLESS_ACL_PROBE: Buffer.from(ACL_PROBE, "utf16le").toString("base64"),
592
- FLOLESS_ACL_SET: Buffer.from(ACL_SET, "utf16le").toString("base64")
593
- };
594
- delete environment.PSModulePath;
595
- let evidence;
617
+ let output2;
596
618
  try {
597
- const output2 = (0, import_node_child_process.execFileSync)("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", script], {
598
- encoding: "utf8",
599
- windowsHide: true,
600
- timeout: 15e3,
601
- maxBuffer: 4 * 1024 * 1024,
602
- env: environment,
603
- stdio: ["ignore", "pipe", "pipe"]
604
- });
605
- evidence = JSON.parse(output2);
619
+ output2 = (0, import_node_child_process.execFileSync)("powershell.exe", ACL_BATCH_ARGS(), aclBatchOptions(batch));
606
620
  } catch (error62) {
607
621
  fail("private storage Windows permissions could not be verified", error62);
608
622
  }
609
- if (!Array.isArray(evidence) || evidence.length !== batch.length) fail("private storage Windows permissions returned invalid evidence");
610
- for (let i = 0; i < batch.length; i += 1) {
611
- validateExactWindowsAcl(evidence[i], batch[i].kind);
612
- if (!evidence[i].protected) fail("private storage Windows permissions are not protected");
613
- }
623
+ checkAclBatchEvidence(output2, batch);
624
+ }
625
+ }
626
+ async function ensureOwnerOnlyStoragePathsAsync(items) {
627
+ if (items.length === 0) return;
628
+ if (process.platform !== "win32") {
629
+ ensureOwnerOnlyStoragePaths(items);
630
+ return;
631
+ }
632
+ for (const item of items) ordinary(item.path, item.kind);
633
+ for (let at = 0; at < items.length; at += 64) {
634
+ const batch = items.slice(at, at + 64);
635
+ const output2 = await new Promise((resolveOutput, reject3) => {
636
+ (0, import_node_child_process.execFile)("powershell.exe", ACL_BATCH_ARGS(), aclBatchOptions(batch), (error62, stdout) => {
637
+ if (error62) reject3(error62);
638
+ else resolveOutput(stdout);
639
+ });
640
+ }).catch((error62) => fail("private storage Windows permissions could not be verified", error62));
641
+ checkAclBatchEvidence(output2, batch);
614
642
  }
615
643
  }
616
644
  function resolveValidatedAwareHome(configured) {
@@ -959,7 +987,7 @@ function ensureModelReferenceReaderSigner(awareHome3) {
959
987
  return createAttempt(expected2);
960
988
  }, { timeoutMs: SIGNER_LOCK_TIMEOUT_MS });
961
989
  }
962
- var import_node_crypto3, import_node_child_process, import_node_fs6, import_node_os, import_node_path4, SECRET_PREFIX, JOURNAL_SCHEMA, SECRET_NAME, PUBLIC_NAME, JOURNAL_NAME, LOCK_STATE_NAME, SIGNER_LOCK_TIMEOUT_MS, UUID, SHA256, ALLOWED_WINDOWS_SIDS, ACL_PROBE, ACL_SET, ACL_BATCH, SignerIntegrityError;
990
+ var import_node_crypto3, import_node_child_process, import_node_fs6, import_node_os, import_node_path4, SECRET_PREFIX, JOURNAL_SCHEMA, SECRET_NAME, PUBLIC_NAME, JOURNAL_NAME, LOCK_STATE_NAME, SIGNER_LOCK_TIMEOUT_MS, UUID, SHA256, ALLOWED_WINDOWS_SIDS, ACL_PROBE, ACL_SET, ACL_BATCH, SignerIntegrityError, ACL_BATCH_ARGS;
963
991
  var init_model_reference_reader_signer = __esm({
964
992
  "model-reference-reader-signer.ts"() {
965
993
  "use strict";
@@ -994,6 +1022,13 @@ var init_model_reference_reader_signer = __esm({
994
1022
  cause;
995
1023
  code = "setup-integrity-failure";
996
1024
  };
1025
+ ACL_BATCH_ARGS = () => [
1026
+ "-NoLogo",
1027
+ "-NoProfile",
1028
+ "-NonInteractive",
1029
+ "-EncodedCommand",
1030
+ Buffer.from(ACL_BATCH, "utf16le").toString("base64")
1031
+ ];
997
1032
  }
998
1033
  });
999
1034
 
@@ -1634,7 +1669,7 @@ function appVersion() {
1634
1669
  return resolveVersion({
1635
1670
  isSea: isSea(),
1636
1671
  sqVersionXml: readSqVersionXml(),
1637
- define: true ? "0.148.0" : void 0,
1672
+ define: true ? "0.148.1" : void 0,
1638
1673
  pkgVersion: readPkgVersion()
1639
1674
  });
1640
1675
  }
@@ -1650,7 +1685,7 @@ function resolveChannel(s) {
1650
1685
  function appChannel() {
1651
1686
  return resolveChannel({
1652
1687
  isSea: isSea(),
1653
- define: true ? "0.148.0" : void 0,
1688
+ define: true ? "0.148.1" : void 0,
1654
1689
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
1655
1690
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
1656
1691
  modulePath: process.argv[1]
@@ -2155,6 +2190,7 @@ function sessionGeneration() {
2155
2190
  return `${subject}:${t.sessionId ?? "legacy"}`;
2156
2191
  }
2157
2192
  function invalidateLicenseCache() {
2193
+ seatEpoch += 1;
2158
2194
  mem = null;
2159
2195
  invalidatedSeq = checkSeq;
2160
2196
  lastDenialAt = 0;
@@ -2302,84 +2338,200 @@ function sessionEndedStatus() {
2302
2338
  function onSeatLost(cb) {
2303
2339
  onSeatLostCb = cb;
2304
2340
  }
2305
- async function ensureSeat(token2, seq, generation) {
2306
- if (seat || seatClaiming || seatLost) return;
2307
- const stillCurrent = () => !seatLost && seq > invalidatedSeq && sessionGeneration() === generation;
2341
+ function seatRequestFailure(what, error62) {
2342
+ const name = error62?.name;
2343
+ if (name === "TimeoutError" || name === "AbortError") return `the ${what} got no answer within ${Math.round(seatRequestTimeoutMs / 1e3)} s`;
2344
+ return `the ${what} could not reach the seat service (${error62?.message ?? String(error62)})`;
2345
+ }
2346
+ async function seatErrorCode(res) {
2347
+ try {
2348
+ const body = JSON.parse(await readBoundedText(res, USER_STATUS_MAX_BYTES));
2349
+ return typeof body.error_code === "string" ? body.error_code.slice(0, 64) : null;
2350
+ } catch {
2351
+ return null;
2352
+ }
2353
+ }
2354
+ async function claimSeat(token2, stillCurrent) {
2355
+ const current = () => !seatLost && stillCurrent();
2356
+ if (seatClaiming) return { ok: false, reason: "another seat claim is still running" };
2357
+ if (!current()) return { ok: false, reason: "the session changed before the seat claim" };
2308
2358
  seatClaiming = true;
2309
2359
  try {
2310
- const res = await fetch(`${env().apiBase}/seats/claim`, {
2311
- method: "POST",
2312
- headers: { Authorization: `Bearer ${token2}`, "Content-Type": "application/json" },
2313
- body: JSON.stringify({ device_fingerprint: installId(), device_name: (0, import_node_os6.hostname)(), os_version: `${process.platform} ${process.arch}` })
2314
- });
2315
- if (!res.ok) return;
2316
- if (!stillCurrent()) {
2360
+ let res;
2361
+ try {
2362
+ res = await fetch(`${env().apiBase}/seats/claim`, {
2363
+ method: "POST",
2364
+ headers: { Authorization: `Bearer ${token2}`, "Content-Type": "application/json" },
2365
+ body: JSON.stringify({ device_fingerprint: installId(), device_name: (0, import_node_os6.hostname)(), os_version: `${process.platform} ${process.arch}` }),
2366
+ signal: AbortSignal.timeout(seatRequestTimeoutMs)
2367
+ });
2368
+ } catch (error62) {
2369
+ return { ok: false, reason: seatRequestFailure("seat claim", error62) };
2370
+ }
2371
+ if (!res.ok) {
2372
+ const code = await seatErrorCode(res);
2373
+ return { ok: false, reason: `the seat claim was answered HTTP ${res.status}${code ? ` ${code}` : ""}`, ...res.status >= 400 && res.status < 500 ? { refused: true } : {} };
2374
+ }
2375
+ if (!current()) {
2317
2376
  await discardBody(res);
2318
- return;
2377
+ return { ok: false, reason: "the session changed during the seat claim" };
2319
2378
  }
2320
- const b = await res.json();
2321
- if (!b.seat_id || !b.nonce || !b.hmac_secret) return;
2322
- if (!stillCurrent()) return;
2379
+ let b;
2380
+ try {
2381
+ b = JSON.parse(await readBoundedText(res, USER_STATUS_MAX_BYTES));
2382
+ } catch (error62) {
2383
+ return { ok: false, reason: seatRequestFailure("seat claim answer", error62) };
2384
+ }
2385
+ if (!b.seat_id || !b.nonce || !b.hmac_secret) return { ok: false, reason: "the seat claim answer was incomplete" };
2386
+ if (!current()) return { ok: false, reason: "the session changed during the seat claim" };
2323
2387
  seat = { seatId: b.seat_id, nonce: b.nonce, hmacSecret: b.hmac_secret };
2324
- if (hbTimer) clearInterval(hbTimer);
2325
- hbTimer = setInterval(() => {
2326
- void seatHeartbeat();
2327
- }, SEAT_HEARTBEAT_MS);
2328
- } catch {
2388
+ return { ok: true };
2329
2389
  } finally {
2330
2390
  seatClaiming = false;
2331
2391
  }
2332
2392
  }
2393
+ async function ensureSeat(token2, seq, generation) {
2394
+ if (seat || seatClaiming || seatLost) return;
2395
+ const claimed2 = await claimSeat(token2, () => seq > invalidatedSeq && sessionGeneration() === generation);
2396
+ if (!claimed2.ok) {
2397
+ if (!claimed2.refused && claimed2.reason !== lastSeatClaimFailure) {
2398
+ lastSeatClaimFailure = claimed2.reason;
2399
+ console.warn(`[licensing] could not claim a seat for this session: ${claimed2.reason}. Retrying on the next licence check.`);
2400
+ }
2401
+ return;
2402
+ }
2403
+ lastSeatClaimFailure = null;
2404
+ if (hbTimer) clearInterval(hbTimer);
2405
+ hbTimer = setInterval(() => {
2406
+ void seatHeartbeat();
2407
+ }, SEAT_HEARTBEAT_MS);
2408
+ }
2409
+ function heartbeatTrouble(reason) {
2410
+ reclaimsInARow = 0;
2411
+ if (hbStreak) {
2412
+ hbStreak.failures += 1;
2413
+ if (hbStreak.reason === reason) return;
2414
+ hbStreak.reason = reason;
2415
+ } else {
2416
+ hbStreak = { since: Date.now(), failures: 1, reason };
2417
+ }
2418
+ console.warn(`[licensing] seat heartbeat failed: ${reason}. The seat service releases a seat after 15 minutes without a heartbeat; retrying every ${Math.round(SEAT_HEARTBEAT_MS / 1e3)} s.`);
2419
+ }
2420
+ function heartbeatHealthy(note) {
2421
+ const streak = hbStreak;
2422
+ hbStreak = null;
2423
+ if (streak) {
2424
+ console.warn(`[licensing] seat heartbeat recovered${note ? ` (${note})` : ""} after ${streak.failures} failed or skipped attempt(s) over ${Math.round((Date.now() - streak.since) / 1e3)} s; last failure: ${streak.reason}`);
2425
+ } else if (note) {
2426
+ console.warn(`[licensing] seat heartbeat: ${note}`);
2427
+ }
2428
+ }
2429
+ async function reclaimSeat(token2, stillCurrent, why) {
2430
+ const claimed2 = await claimSeat(token2, stillCurrent);
2431
+ if (!claimed2.ok) {
2432
+ if (stillCurrent()) heartbeatTrouble(`${why}, and re-claiming the seat failed: ${claimed2.reason}`);
2433
+ return;
2434
+ }
2435
+ reclaimsInARow += 1;
2436
+ heartbeatHealthy(`${why}; re-claimed the seat`);
2437
+ if (reclaimsInARow === 3) {
2438
+ console.warn("[licensing] the seat had to be re-claimed 3 times in a row: another FloLess process is probably using this install's seat (for example a second copy of the app, or a development server sharing its data folder)");
2439
+ }
2440
+ }
2333
2441
  async function seatHeartbeat() {
2334
- if (!seat || hbInFlight) return;
2442
+ if (!seat) return;
2443
+ if (hbInFlight) {
2444
+ heartbeatTrouble("the previous heartbeat was still running, so this one was skipped");
2445
+ return;
2446
+ }
2335
2447
  hbInFlight = true;
2448
+ const epoch = seatEpoch;
2449
+ const generation = sessionGeneration();
2450
+ const stillCurrent = () => seatEpoch === epoch && sessionGeneration() === generation;
2336
2451
  try {
2337
- const token2 = await ensureFreshToken().catch(() => null);
2338
- if (!token2) return;
2339
- const hmac = (0, import_node_crypto4.createHmac)("sha256", seat.hmacSecret).update(seat.nonce).digest("hex");
2452
+ let token2;
2453
+ try {
2454
+ token2 = await ensureFreshToken();
2455
+ } catch (error62) {
2456
+ heartbeatTrouble(`the sign-in token could not be refreshed (${error62?.message ?? String(error62)})`);
2457
+ return;
2458
+ }
2459
+ if (!token2) {
2460
+ heartbeatTrouble("there is no usable sign-in token (signed out, or the session expired)");
2461
+ return;
2462
+ }
2463
+ const sent = seat;
2464
+ if (!sent || !stillCurrent()) return;
2465
+ const hmac = (0, import_node_crypto4.createHmac)("sha256", sent.hmacSecret).update(sent.nonce).digest("hex");
2340
2466
  let res;
2341
2467
  try {
2342
2468
  res = await fetch(`${env().apiBase}/seats/heartbeat`, {
2343
2469
  method: "POST",
2344
2470
  headers: { Authorization: `Bearer ${token2}`, "Content-Type": "application/json" },
2345
- body: JSON.stringify({ seat_id: seat.seatId, nonce: seat.nonce, hmac })
2471
+ body: JSON.stringify({ seat_id: sent.seatId, nonce: sent.nonce, hmac }),
2472
+ // Covers the body read below too. A heartbeat the service DID process before the answer was lost
2473
+ // has rotated the nonce: the next tick then gets INVALID_NONCE and re-claims (see reclaimSeat).
2474
+ signal: AbortSignal.timeout(seatRequestTimeoutMs)
2346
2475
  });
2347
- } catch {
2476
+ } catch (error62) {
2477
+ heartbeatTrouble(seatRequestFailure("heartbeat", error62));
2478
+ return;
2479
+ }
2480
+ if (seat !== sent || !stillCurrent()) {
2481
+ await discardBody(res);
2348
2482
  return;
2349
2483
  }
2350
2484
  if (res.status === 401) {
2351
2485
  let reason = "unknown";
2486
+ let code;
2352
2487
  try {
2353
- const b = await res.json();
2488
+ const b = JSON.parse(await readBoundedText(res, USER_STATUS_MAX_BYTES));
2354
2489
  reason = b.details?.reason ?? b.reason ?? reason;
2490
+ code = b.error_code;
2355
2491
  } catch {
2356
2492
  }
2493
+ if (seat !== sent || !stillCurrent()) return;
2494
+ const streak = hbStreak ? `, after ${hbStreak.failures} failed or skipped heartbeat(s) over ${Math.round((Date.now() - hbStreak.since) / 1e3)} s (last: ${hbStreak.reason})` : "";
2495
+ console.warn(`[licensing] seat heartbeat refused with HTTP 401${typeof code === "string" ? ` ${code.slice(0, 64)}` : ""} (reason: ${String(reason).slice(0, 64)})${streak}; this session's seat is gone`);
2357
2496
  loseSeat(reason);
2358
2497
  return;
2359
2498
  }
2360
- if (!res.ok) return;
2499
+ if (!res.ok) {
2500
+ const code = await seatErrorCode(res);
2501
+ if (seat !== sent || !stillCurrent()) return;
2502
+ if (res.status === 400 && code === "INVALID_NONCE") {
2503
+ await reclaimSeat(token2, stillCurrent, "the seat service rejected the heartbeat nonce (INVALID_NONCE)");
2504
+ return;
2505
+ }
2506
+ heartbeatTrouble(`the seat service answered HTTP ${res.status}${code ? ` ${code}` : ""}`);
2507
+ return;
2508
+ }
2361
2509
  let next;
2510
+ let unreadable = null;
2362
2511
  try {
2363
- next = (await res.json()).next_nonce;
2364
- } catch {
2512
+ next = JSON.parse(await readBoundedText(res, USER_STATUS_MAX_BYTES)).next_nonce;
2513
+ } catch (error62) {
2514
+ unreadable = seatRequestFailure("heartbeat answer", error62);
2365
2515
  }
2366
- if (next) {
2367
- seat.nonce = next;
2516
+ if (seat !== sent || !stillCurrent()) return;
2517
+ if (typeof next === "string" && next) {
2518
+ sent.nonce = next;
2519
+ reclaimsInARow = 0;
2520
+ heartbeatHealthy();
2368
2521
  return;
2369
2522
  }
2370
- seat = null;
2371
- if (hbTimer) {
2372
- clearInterval(hbTimer);
2373
- hbTimer = null;
2374
- }
2523
+ await reclaimSeat(token2, stillCurrent, unreadable ?? "the heartbeat answer carried no next nonce");
2375
2524
  } finally {
2376
2525
  hbInFlight = false;
2377
2526
  }
2378
2527
  }
2379
2528
  function loseSeat(reason) {
2529
+ seatEpoch += 1;
2380
2530
  seatLost = true;
2381
2531
  seatLostReason = normalizeSeatReason(reason);
2382
2532
  seat = null;
2533
+ hbStreak = null;
2534
+ reclaimsInARow = 0;
2383
2535
  invalidateLicenseCache();
2384
2536
  if (hbTimer) {
2385
2537
  clearInterval(hbTimer);
@@ -2388,6 +2540,10 @@ function loseSeat(reason) {
2388
2540
  onSeatLostCb?.(seatLostReason);
2389
2541
  }
2390
2542
  function resetSeat() {
2543
+ seatEpoch += 1;
2544
+ hbStreak = null;
2545
+ reclaimsInARow = 0;
2546
+ lastSeatClaimFailure = null;
2391
2547
  seatLost = false;
2392
2548
  seatLostReason = void 0;
2393
2549
  seat = null;
@@ -2497,7 +2653,7 @@ function installId() {
2497
2653
  writeJson(p, id2);
2498
2654
  return id2;
2499
2655
  }
2500
- var import_node_fs12, import_node_path10, import_node_os5, import_node_child_process5, import_node_crypto4, import_node_module2, import_node_os6, ENVS, trustedApiOrigins, OFFLINE_GRACE_MS, MEM_CACHE_MS, REFRESH_SKEW_MS, USER_STATUS_TIMEOUT_DEFAULT_MS, userStatusTimeoutMs, USER_STATUS_MAX_BYTES, tokenPath, cachePath, STORE_FILES, _migrated, storedSessionRevoked, NetworkError, tokenResolutionInFlight, TOKEN_REFRESH_TIMEOUT_DEFAULT_MS, tokenRefreshTimeoutMs, TOKEN_REFRESH_MAX_BYTES, TOKEN_RESOLUTION_BUDGET_MS, licensingDiagnostics, mem, seatLost, seatLostReason, GATE_MAX_STALE_MS, checkSeq, committedSeq, invalidatedSeq, checkInFlight, lastDenialAt, passes, HEALTH_LICENSE_WAIT_MS, healthCheckInFlight, SEAT_HEARTBEAT_MS, seat, seatClaiming, hbInFlight, hbTimer, onSeatLostCb, SIGNED_OUT_TOMBSTONE, errorCode, DESKTOP_SESSION_TTL_MS, DESKTOP_POLL_MS;
2656
+ var import_node_fs12, import_node_path10, import_node_os5, import_node_child_process5, import_node_crypto4, import_node_module2, import_node_os6, ENVS, trustedApiOrigins, OFFLINE_GRACE_MS, MEM_CACHE_MS, REFRESH_SKEW_MS, USER_STATUS_TIMEOUT_DEFAULT_MS, userStatusTimeoutMs, USER_STATUS_MAX_BYTES, SEAT_REQUEST_TIMEOUT_DEFAULT_MS, seatRequestTimeoutMs, seatEpoch, tokenPath, cachePath, STORE_FILES, _migrated, storedSessionRevoked, NetworkError, tokenResolutionInFlight, TOKEN_REFRESH_TIMEOUT_DEFAULT_MS, tokenRefreshTimeoutMs, TOKEN_REFRESH_MAX_BYTES, TOKEN_RESOLUTION_BUDGET_MS, licensingDiagnostics, mem, seatLost, seatLostReason, GATE_MAX_STALE_MS, checkSeq, committedSeq, invalidatedSeq, checkInFlight, lastDenialAt, passes, HEALTH_LICENSE_WAIT_MS, healthCheckInFlight, SEAT_HEARTBEAT_MS, seat, seatClaiming, hbInFlight, hbTimer, onSeatLostCb, lastSeatClaimFailure, hbStreak, reclaimsInARow, SIGNED_OUT_TOMBSTONE, errorCode, DESKTOP_SESSION_TTL_MS, DESKTOP_POLL_MS;
2501
2657
  var init_licensing = __esm({
2502
2658
  "licensing.ts"() {
2503
2659
  "use strict";
@@ -2519,6 +2675,9 @@ var init_licensing = __esm({
2519
2675
  USER_STATUS_TIMEOUT_DEFAULT_MS = 1e4;
2520
2676
  userStatusTimeoutMs = USER_STATUS_TIMEOUT_DEFAULT_MS;
2521
2677
  USER_STATUS_MAX_BYTES = 64 * 1024;
2678
+ SEAT_REQUEST_TIMEOUT_DEFAULT_MS = 15e3;
2679
+ seatRequestTimeoutMs = SEAT_REQUEST_TIMEOUT_DEFAULT_MS;
2680
+ seatEpoch = 0;
2522
2681
  tokenPath = () => (0, import_node_path10.join)(storeDir(), "floless-license.json");
2523
2682
  cachePath = () => (0, import_node_path10.join)(storeDir(), "floless-license-cache.json");
2524
2683
  STORE_FILES = ["floless-license.json", "floless-license-cache.json", "floless-install-id"];
@@ -2550,6 +2709,9 @@ var init_licensing = __esm({
2550
2709
  hbInFlight = false;
2551
2710
  hbTimer = null;
2552
2711
  onSeatLostCb = null;
2712
+ lastSeatClaimFailure = null;
2713
+ hbStreak = null;
2714
+ reclaimsInARow = 0;
2553
2715
  SIGNED_OUT_TOMBSTONE = JSON.stringify({ signedOut: true });
2554
2716
  errorCode = (error62) => error62?.code ?? String(error62);
2555
2717
  DESKTOP_SESSION_TTL_MS = 15 * 6e4;
@@ -38427,7 +38589,7 @@ function verifyAwareWorkflowPublication(receipt) {
38427
38589
  const installedSourceDigest = sha256File(source);
38428
38590
  const lockValue = (0, import_yaml.parse)((0, import_node_fs17.readFileSync)(lock, "utf8"));
38429
38591
  const sourceHash = lockValue && typeof lockValue === "object" && !Array.isArray(lockValue) ? lockValue["source-hash"] : null;
38430
- return sourceHash === installedSourceDigest;
38592
+ return sourceHash === `sha256:${installedSourceDigest}`;
38431
38593
  } catch {
38432
38594
  return false;
38433
38595
  }
@@ -43195,6 +43357,18 @@ function withReadScope(fn2) {
43195
43357
  scope = null;
43196
43358
  }
43197
43359
  }
43360
+ function openReadPass() {
43361
+ const memo2 = /* @__PURE__ */ new Map();
43362
+ return (fn2) => {
43363
+ if (scope) return fn2();
43364
+ scope = memo2;
43365
+ try {
43366
+ return fn2();
43367
+ } finally {
43368
+ scope = null;
43369
+ }
43370
+ };
43371
+ }
43198
43372
  function memoInReadScope(key5, compute) {
43199
43373
  if (!scope) return compute();
43200
43374
  if (scope.has(key5)) return scope.get(key5);
@@ -96170,6 +96344,7 @@ function scanProjectDirectories(root9, archived = false, options2 = {}) {
96170
96344
  );
96171
96345
  }
96172
96346
  function scanProjectDirectoriesNow(root9, archived, options2) {
96347
+ projectScans += 1;
96173
96348
  assertWorkspaceRootCurrent(root9);
96174
96349
  const collection = projectCollectionDirectory(root9, archived);
96175
96350
  if (!(0, import_node_fs32.existsSync)(collection)) return [];
@@ -96243,7 +96418,7 @@ async function withProjectDirectoryCapability(root9, projectId2, fn2, archived =
96243
96418
  capability.active = false;
96244
96419
  }
96245
96420
  }
96246
- var import_node_fs32, import_node_path30, import_node_async_hooks4, MAX_PROJECT_META_BYTES, candidateReservations, ProjectDirectoryError;
96421
+ var import_node_fs32, import_node_path30, import_node_async_hooks4, MAX_PROJECT_META_BYTES, candidateReservations, ProjectDirectoryError, projectScans;
96247
96422
  var init_project_directory = __esm({
96248
96423
  "project-directory.ts"() {
96249
96424
  "use strict";
@@ -96264,6 +96439,7 @@ var init_project_directory = __esm({
96264
96439
  this.name = "ProjectDirectoryError";
96265
96440
  }
96266
96441
  };
96442
+ projectScans = 0;
96267
96443
  }
96268
96444
  });
96269
96445
 
@@ -120993,9 +121169,19 @@ async function recoverProjectTransactions(projectId2) {
120993
121169
  }
120994
121170
  return outcomes;
120995
121171
  }
121172
+ function projectsWithTransactionDirs(listIds) {
121173
+ return withReadScope(() => listIds().filter((id2) => {
121174
+ try {
121175
+ const dir = projectDir(id2);
121176
+ return (0, import_node_fs47.readdirSync)(dir, { withFileTypes: true }).some((e) => e.isDirectory() && e.name.startsWith(PREFIX) && !e.name.includes(".retired-"));
121177
+ } catch {
121178
+ return true;
121179
+ }
121180
+ }));
121181
+ }
120996
121182
  async function recoverAllProjectTransactions(listIds) {
120997
121183
  const out = [];
120998
- for (const id2 of listIds()) {
121184
+ for (const id2 of projectsWithTransactionDirs(listIds)) {
120999
121185
  try {
121000
121186
  out.push(...await recoverProjectTransactions(id2));
121001
121187
  } catch (error62) {
@@ -121378,6 +121564,7 @@ var init_contract_transaction = __esm({
121378
121564
  init_contract_store();
121379
121565
  init_project_versions_store();
121380
121566
  init_lifecycle_lock();
121567
+ init_read_scope();
121381
121568
  init_project_contract_hash();
121382
121569
  init_contract_policy();
121383
121570
  init_steel_plan_view_id_normalise();
@@ -125022,6 +125209,15 @@ except Exception:
125022
125209
  });
125023
125210
 
125024
125211
  // projects-store.ts
125212
+ function withFolderInUseRefusal(action, projectName, move) {
125213
+ try {
125214
+ return move();
125215
+ } catch (error62) {
125216
+ const code = error62?.code;
125217
+ if (code && FOLDER_IN_USE_CODES.has(code)) throw new ProjectFolderInUseError(action, projectName, error62);
125218
+ throw error62;
125219
+ }
125220
+ }
125025
125221
  function importedPlacementClaims(contract) {
125026
125222
  if (!contract || typeof contract !== "object" || contract.type !== "steel.model/v2") return { contract, corrected: 0 };
125027
125223
  const model = contract;
@@ -125786,7 +125982,18 @@ function archiveProject(id2) {
125786
125982
  if ((0, import_node_fs53.existsSync)(dest)) throw new ProjectError(`already archived: ${id2}`);
125787
125983
  markCurrentWorkspaceProjectMove(id2, "archive", "prepared");
125788
125984
  if (meta3) writeMeta({ ...meta3, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
125789
- (0, import_node_fs53.renameSync)(dir, dest);
125985
+ try {
125986
+ withFolderInUseRefusal("archive", meta3?.name ?? null, () => (0, import_node_fs53.renameSync)(dir, dest));
125987
+ } catch (error62) {
125988
+ if (meta3) {
125989
+ try {
125990
+ writeMeta(meta3);
125991
+ } catch (restoreError) {
125992
+ console.warn(`[projects] could not restore ${id2}'s activity time after a failed archive:`, restoreError);
125993
+ }
125994
+ }
125995
+ throw error62;
125996
+ }
125790
125997
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dir));
125791
125998
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dest));
125792
125999
  markCurrentWorkspaceProjectMove(id2, "archive", "moved");
@@ -125811,18 +126018,28 @@ function unarchiveProject(id2) {
125811
126018
  const dest = (0, import_node_path47.join)(projectsRoot(), locator);
125812
126019
  if ((0, import_node_fs53.existsSync)(dest)) throw new ProjectError(`a live project with that id already exists: ${id2}`);
125813
126020
  markCurrentWorkspaceProjectMove(id2, "restore", "prepared");
125814
- (0, import_node_fs53.renameSync)(src, dest);
126021
+ withFolderInUseRefusal("restore", meta3.name, () => (0, import_node_fs53.renameSync)(src, dest));
125815
126022
  syncDirectoryBestEffort((0, import_node_path47.dirname)(src));
125816
126023
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dest));
125817
126024
  markCurrentWorkspaceProjectMove(id2, "restore", "moved");
125818
126025
  return meta3;
125819
126026
  }
126027
+ function assertArchivedProjectRemovable(id2) {
126028
+ const dir = archiveDir(id2);
126029
+ if (!(0, import_node_fs53.existsSync)(dir)) throw new ProjectError(`not archived: ${id2}`);
126030
+ assertArchivedFolderRemovable(dir, readMetaFile((0, import_node_path47.join)(dir, "project.json"), (0, import_node_path47.basename)(dir))?.name ?? null);
126031
+ }
126032
+ function assertArchivedFolderRemovable(dir, projectName) {
126033
+ withFolderInUseRefusal("delete", projectName, () => (0, import_node_fs53.renameSync)(dir, dir));
126034
+ }
125820
126035
  function deleteArchivedProject(id2) {
125821
126036
  const dir = archiveDir(id2);
125822
126037
  if (!(0, import_node_fs53.existsSync)(dir)) throw new ProjectError(`not archived: ${id2}`);
125823
126038
  assertNoApprovalRecovery(dir);
125824
- const stagingId = readMetaFile((0, import_node_path47.join)(dir, "project.json"), (0, import_node_path47.basename)(dir))?.stagingId;
125825
- (0, import_node_fs53.rmSync)(dir, { recursive: true, force: true });
126039
+ const archivedMeta = readMetaFile((0, import_node_path47.join)(dir, "project.json"), (0, import_node_path47.basename)(dir));
126040
+ const stagingId = archivedMeta?.stagingId;
126041
+ assertArchivedFolderRemovable(dir, archivedMeta?.name ?? null);
126042
+ withFolderInUseRefusal("delete-partial", archivedMeta?.name ?? null, () => (0, import_node_fs53.rmSync)(dir, { recursive: true, force: true }));
125826
126043
  if (stagingId) dropStagingFor(stagingId);
125827
126044
  }
125828
126045
  function sniffThumbnailExt(data) {
@@ -127196,7 +127413,7 @@ async function importProjectZip(data, rfiOperationId = (0, import_node_crypto44.
127196
127413
  return { project: meta3, rfiTransfer, ...revitPortable ? { revitPortable: true } : {}, ...revitSource ? { revitSource } : {} };
127197
127414
  }, seams.destination);
127198
127415
  }
127199
- var import_node_fs53, import_node_child_process14, import_promises20, import_node_path47, import_node_os28, import_node_crypto44, import_node_stream2, ProjectError, CHAT_DIRECTORY_NAME, RESERVED_PROJECT_INTERNAL, NO_INCARNATION_REFUSAL, writeMeta, FRESH_DESTINATION_RETRY, THUMBNAIL_EXTS, MAX_THUMBNAIL_BYTES, THUMBNAIL_MEDIA_TYPES, ZIP_SLICE, yieldToLoop, IMPORT_MAX_FILES, IMPORT_MAX_UNCOMPRESSED, ARCHIVED_PDF_PAGE_GEOMETRY, ArchivedPdfInspectionError, RFI_INVENTORY_LIMITS;
127416
+ var import_node_fs53, import_node_child_process14, import_promises20, import_node_path47, import_node_os28, import_node_crypto44, import_node_stream2, ProjectError, ProjectFolderInUseError, FOLDER_IN_USE_CODES, CHAT_DIRECTORY_NAME, RESERVED_PROJECT_INTERNAL, NO_INCARNATION_REFUSAL, writeMeta, FRESH_DESTINATION_RETRY, THUMBNAIL_EXTS, MAX_THUMBNAIL_BYTES, THUMBNAIL_MEDIA_TYPES, ZIP_SLICE, yieldToLoop, IMPORT_MAX_FILES, IMPORT_MAX_UNCOMPRESSED, ARCHIVED_PDF_PAGE_GEOMETRY, ArchivedPdfInspectionError, RFI_INVENTORY_LIMITS;
127200
127417
  var init_projects_store = __esm({
127201
127418
  "projects-store.ts"() {
127202
127419
  "use strict";
@@ -127238,6 +127455,18 @@ var init_projects_store = __esm({
127238
127455
  }
127239
127456
  code;
127240
127457
  };
127458
+ ProjectFolderInUseError = class extends ProjectError {
127459
+ constructor(action, projectName, osError) {
127460
+ const subject = projectName ? `\u201C${projectName}\u201D` : "this project";
127461
+ const first = action === "archive" ? `Couldn\u2019t move ${subject} to the Trash` : action === "restore" ? `Couldn\u2019t restore ${subject} from the Trash` : action === "delete" ? `Couldn\u2019t delete ${subject} permanently` : `Couldn\u2019t finish deleting ${subject}`;
127462
+ const partial2 = action === "delete-partial" ? " Some of its files may already be removed." : "";
127463
+ super(`${first} because the computer wouldn\u2019t let FloLess change its folder. This usually means a file inside it is open in another program.${partial2} Close any of its files (in File Explorer, an editor or a viewer) and try again.`, "project-folder-in-use");
127464
+ this.osError = osError;
127465
+ this.name = "ProjectFolderInUseError";
127466
+ }
127467
+ osError;
127468
+ };
127469
+ FOLDER_IN_USE_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
127241
127470
  CHAT_DIRECTORY_NAME = "chats";
127242
127471
  RESERVED_PROJECT_INTERNAL = /(?:^|[\\/])(?:\.member-end-resolution(?:[\\/]|$)|\.floless-model-lifecycle\.json$|\.floless-revit-publication\.json$|\.floless-revit-publication-quarantine(?:[\\/]|$)|\.floless-(?:txn|cleanup|tmp|backup|activation|refcache|checkpoints|working-revision|export-handle|approval-operation)-|contract\.json\.publication\.json$)/i;
127243
127472
  NO_INCARNATION_REFUSAL = "This project can\u2019t be approved \u2014 duplicate it from the Workspaces list to sign off";
@@ -138214,6 +138443,15 @@ function affectsProjectListing(path, event) {
138214
138443
  if (parts.length === 3 && parts[0] === ".archive" && parts[2] === "project.json") return true;
138215
138444
  return (event === "addDir" || event === "unlinkDir") && (parts.length === 1 || parts.length === 2 && parts[0] === ".archive");
138216
138445
  }
138446
+ function workspaceWatchIgnored(rootPath, path) {
138447
+ const child = relativeWorkspacePath(rootPath, path);
138448
+ if (child === null) return false;
138449
+ const parts = child.split("/");
138450
+ if (parts.length === 1) return false;
138451
+ if (parts.length === 2) return !(parts[0] === ".archive" || parts[1] === "project.json");
138452
+ if (parts.length === 3) return !(parts[0] === ".archive" && parts[2] === "project.json");
138453
+ return true;
138454
+ }
138217
138455
  function waitUntilReady(watcher) {
138218
138456
  return new Promise((resolveReady, rejectReady) => {
138219
138457
  const timer = setTimeout(() => finish2(new Error("workspace root watcher did not become ready in time")), READY_TIMEOUT_MS);
@@ -138242,6 +138480,7 @@ function startWorkspaceRootWatcher(initialRoot, emit = broadcast) {
138242
138480
  // Workspace roots can contain Windows shell folders such as Documents\My Music.
138243
138481
  // Do not follow those links: they are outside the selected root and may be unreadable.
138244
138482
  followSymlinks: false,
138483
+ ignored: (path) => workspaceWatchIgnored(root9.path, path),
138245
138484
  awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 }
138246
138485
  });
138247
138486
  watcher.on("all", (event, path) => {
@@ -140665,12 +140904,42 @@ function releaseLock(id2, requestId) {
140665
140904
  }
140666
140905
  return true;
140667
140906
  }
140907
+ function emptyRetentionSweep() {
140908
+ return { reconciled: 0, blockedProjectUuids: /* @__PURE__ */ new Set(), blockedUnsignedProjectIds: /* @__PURE__ */ new Set(), unattributed: [] };
140909
+ }
140668
140910
  function beginKnowledgeRetentionReconciliation() {
140669
140911
  generationGcEnabled = false;
140912
+ gcBlockedProjects = /* @__PURE__ */ new Set();
140670
140913
  }
140671
- function completeKnowledgeRetentionReconciliation() {
140914
+ function completeKnowledgeRetentionReconciliation(blocked = null) {
140915
+ gcBlockedProjects = new Set(blocked ? [
140916
+ ...[...blocked.projectUuids].map((uuid5) => `${blocked.rootId}:uuid:${uuid5}`),
140917
+ ...[...blocked.unsignedProjectIds ?? []].map((id2) => `${blocked.rootId}:id:${id2}`)
140918
+ ] : []);
140672
140919
  generationGcEnabled = true;
140673
140920
  }
140921
+ function applyKnowledgeRetentionSweeps(rootId, sweeps) {
140922
+ const unattributed = sweeps.flatMap((sweep3) => sweep3.unattributed);
140923
+ if (unattributed.length) return { gc: "closed", unattributed };
140924
+ const heldUuids = [...new Set(sweeps.flatMap((sweep3) => [...sweep3.blockedProjectUuids]))];
140925
+ const heldUnsignedIds = [...new Set(sweeps.flatMap((sweep3) => [...sweep3.blockedUnsignedProjectIds]))];
140926
+ completeKnowledgeRetentionReconciliation({ rootId, projectUuids: heldUuids, unsignedProjectIds: heldUnsignedIds });
140927
+ return { gc: "open", heldUuids, heldUnsignedIds };
140928
+ }
140929
+ function gcBlockedForProject(id2) {
140930
+ if (gcBlockedProjects.size === 0) return false;
140931
+ try {
140932
+ const rootId = activeWorkspaceRoot().rootId;
140933
+ const uuid5 = getProject(id2)?.uuid;
140934
+ return gcBlockedProjects.has(uuid5 ? `${rootId}:uuid:${uuid5}` : `${rootId}:id:${id2}`);
140935
+ } catch (error62) {
140936
+ if (!gcLookupFailuresLogged.has(id2)) {
140937
+ gcLookupFailuresLogged.add(id2);
140938
+ console.warn(`knowledge-store: kept every generation of ${id2}; could not check whether its cleanup is held: ${error62 instanceof Error ? error62.message : error62}`);
140939
+ }
140940
+ return true;
140941
+ }
140942
+ }
140674
140943
  function retentionPinPath(id2, pinId) {
140675
140944
  if (!isGenerationId(pinId)) throw new KnowledgeError("invalid retention pin id");
140676
140945
  return (0, import_node_path80.join)(retentionPinsDir(id2), `${pinId}.json`);
@@ -141230,7 +141499,7 @@ function failOrganize(id2, requestId, opts) {
141230
141499
  releaseLock(id2, requestId);
141231
141500
  }
141232
141501
  function gcOldGenerations(id2, currentGenerationId) {
141233
- if (!generationGcEnabled) return;
141502
+ if (!generationGcEnabled || gcBlockedForProject(id2)) return;
141234
141503
  const dir = generationsDir(id2);
141235
141504
  if (!(0, import_node_fs80.existsSync)(dir)) return;
141236
141505
  const entries = (0, import_node_fs80.readdirSync)(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => ({ name: e.name, mtimeMs: (0, import_node_fs80.statSync)((0, import_node_path80.join)(dir, e.name)).mtimeMs })).sort((a, b) => b.mtimeMs - a.mtimeMs);
@@ -141255,7 +141524,7 @@ function gcOldGenerations(id2, currentGenerationId) {
141255
141524
  }
141256
141525
  }
141257
141526
  }
141258
- var import_node_crypto65, import_node_fs80, import_node_path80, import_yaml9, KnowledgeError, EMPTY_MANIFEST, manifestPath, blobsDir, BLOB_SHA256_RE, MAX_FILES, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MIME_PDF, MIME_PNG, MIME_JPEG, MIME_TXT, MIME_CSV, MIME_MD, RAW_MIME_LIST, RAW_MIMES, TEXT_MIME_BY_EXT, LOCK_STALE_MS, lockPath, GENERATION_ID_RE, GEN_KEEP, vaultDir, generationsDir, currentGenerationPath, retentionPinsDir, activeGenerationReaders, generationGcEnabled, WIKI_SLUG_RE, KB_MAX_NODES, KB_MAX_TOTAL_BYTES, KB_MAX_VISITS, KB_MAX_PAGE_BYTES, REAL_IO, VAULT_START, VAULT_END, FRONTMATTER_RE, WIKILINK_RE, KB_FEED_Q_THRESHOLD, KB_FEED_MAX_LIMIT, KB_FEED_SNIPPET_LEN, KB_FEED_MAX_TOKENS, organizePath;
141527
+ var import_node_crypto65, import_node_fs80, import_node_path80, import_yaml9, KnowledgeError, EMPTY_MANIFEST, manifestPath, blobsDir, BLOB_SHA256_RE, MAX_FILES, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MIME_PDF, MIME_PNG, MIME_JPEG, MIME_TXT, MIME_CSV, MIME_MD, RAW_MIME_LIST, RAW_MIMES, TEXT_MIME_BY_EXT, LOCK_STALE_MS, lockPath, GENERATION_ID_RE, GEN_KEEP, vaultDir, generationsDir, currentGenerationPath, retentionPinsDir, activeGenerationReaders, generationGcEnabled, gcBlockedProjects, gcLookupFailuresLogged, WIKI_SLUG_RE, KB_MAX_NODES, KB_MAX_TOTAL_BYTES, KB_MAX_VISITS, KB_MAX_PAGE_BYTES, REAL_IO, VAULT_START, VAULT_END, FRONTMATTER_RE, WIKILINK_RE, KB_FEED_Q_THRESHOLD, KB_FEED_MAX_LIMIT, KB_FEED_SNIPPET_LEN, KB_FEED_MAX_TOKENS, organizePath;
141259
141528
  var init_knowledge_store = __esm({
141260
141529
  "knowledge-store.ts"() {
141261
141530
  "use strict";
@@ -141264,6 +141533,7 @@ var init_knowledge_store = __esm({
141264
141533
  import_node_path80 = require("node:path");
141265
141534
  import_yaml9 = __toESM(require_dist(), 1);
141266
141535
  init_projects_store();
141536
+ init_workspace_root_store();
141267
141537
  init_durable_replace();
141268
141538
  KnowledgeError = class extends Error {
141269
141539
  code;
@@ -141298,6 +141568,8 @@ var init_knowledge_store = __esm({
141298
141568
  retentionPinsDir = (id2) => (0, import_node_path80.join)(vaultDir(id2), "retention-pins");
141299
141569
  activeGenerationReaders = /* @__PURE__ */ new Map();
141300
141570
  generationGcEnabled = true;
141571
+ gcBlockedProjects = /* @__PURE__ */ new Set();
141572
+ gcLookupFailuresLogged = /* @__PURE__ */ new Set();
141301
141573
  WIKI_SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/;
141302
141574
  KB_MAX_NODES = 300;
141303
141575
  KB_MAX_TOTAL_BYTES = 8 * 1024 * 1024;
@@ -142573,39 +142845,114 @@ async function appendChatKnowledgeCitation(owner3, chatId, input2) {
142573
142845
  return event;
142574
142846
  });
142575
142847
  }
142848
+ function noteStartupOwnerProblem(key5, line) {
142849
+ if (startupOwnerNotes.has(key5)) return;
142850
+ startupOwnerNotes.add(key5);
142851
+ console.warn(line);
142852
+ }
142853
+ function ownerLabel(owner3) {
142854
+ return owner3.kind === "project" ? `project ${owner3.projectId}` : `workflow ${owner3.workflowId}`;
142855
+ }
142856
+ function noteStartupOwnerFailure(pass, owner3, error62) {
142857
+ const message2 = error62 instanceof Error ? error62.message : String(error62);
142858
+ noteStartupOwnerProblem(
142859
+ `${pass}|${ownerLabel(owner3)}|${message2}`,
142860
+ `[chat] ${pass}: skipped ${ownerLabel(owner3)} \u2014 ${message2}`
142861
+ );
142862
+ }
142863
+ function reportOwnerFailure(pass, owner3, error62) {
142864
+ console.error(`[chat] ${pass} could not list ${ownerLabel(owner3)}:`, error62);
142865
+ }
142866
+ function startupChatOwners(options2) {
142867
+ const projects = options2.includeArchived ? [...listProjects(), ...listArchivedProjects()] : listProjects();
142868
+ const owners = [];
142869
+ for (const project of projects) {
142870
+ if (!project.uuid) {
142871
+ noteStartupOwnerProblem(
142872
+ `unsigned|${project.id}`,
142873
+ `[chat] project ${project.id} has no identity (no uuid in project.json), so its conversations cannot be opened; start-up chat recovery skips it`
142874
+ );
142875
+ continue;
142876
+ }
142877
+ owners.push({ kind: "project", projectId: project.id });
142878
+ }
142879
+ const workflows = options2.includeArchived ? listWorkflowOwnerships({ includeArchived: true }) : listWorkflowOwnerships();
142880
+ for (const workflow of workflows) owners.push({ kind: "workflow", workflowId: workflow.workflowId });
142881
+ return owners;
142882
+ }
142576
142883
  function reconcileChatKnowledgeRetention() {
142577
- const owners = [
142578
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
142579
- ...listArchivedProjects().map((project) => ({ kind: "project", projectId: project.id })),
142580
- ...listWorkflowOwnerships({ includeArchived: true }).map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
142581
- ];
142582
- let reconciled = 0;
142583
- for (const owner3 of owners) {
142584
- for (const chat of listChats(owner3, { includeArchived: true })) {
142884
+ return withReadScope(reconcileChatKnowledgeRetentionNow);
142885
+ }
142886
+ function reconcileChatKnowledgeRetentionNow() {
142887
+ const result2 = emptyRetentionSweep();
142888
+ const uuidById = /* @__PURE__ */ new Map();
142889
+ const unsignedIds = /* @__PURE__ */ new Set();
142890
+ for (const [archived, rows2] of [[false, listProjects()], [true, listArchivedProjects()]]) {
142891
+ for (const project of rows2) {
142892
+ if (project.uuid) {
142893
+ uuidById.set(project.id, project.uuid);
142894
+ continue;
142895
+ }
142896
+ unsignedIds.add(project.id);
142897
+ try {
142898
+ const dir = archived ? projectDirectoryForId(project.id, true) : projectDir(project.id);
142899
+ const chats = (0, import_node_path81.join)(dir, "chats");
142900
+ if ((0, import_node_fs81.existsSync)(chats) && (0, import_node_fs81.readdirSync)(chats).length > 0) result2.blockedUnsignedProjectIds.add(project.id);
142901
+ } catch {
142902
+ result2.blockedUnsignedProjectIds.add(project.id);
142903
+ }
142904
+ }
142905
+ }
142906
+ const charge = (projectId2, why) => {
142907
+ const uuid5 = projectId2 ? uuidById.get(projectId2) : void 0;
142908
+ if (uuid5) result2.blockedProjectUuids.add(uuid5);
142909
+ else if (projectId2 && unsignedIds.has(projectId2)) result2.blockedUnsignedProjectIds.add(projectId2);
142910
+ else result2.unattributed.push(why);
142911
+ };
142912
+ for (const owner3 of startupChatOwners({ includeArchived: true })) {
142913
+ const ownerProjectId = owner3.kind === "project" ? owner3.projectId : void 0;
142914
+ let ownedChats;
142915
+ try {
142916
+ ownedChats = listChats(owner3, { includeArchived: true });
142917
+ } catch (error62) {
142918
+ noteStartupOwnerFailure("Knowledge citation recovery", owner3, error62);
142919
+ charge(ownerProjectId, `${ownerLabel(owner3)} could not be listed`);
142920
+ continue;
142921
+ }
142922
+ for (const chat of ownedChats) {
142585
142923
  const scopedProjectId = chat.owner.projectId;
142586
- for (const event of listChatEvents(owner3, chat.chatId)) {
142587
- if (event.type !== "knowledge-citation") continue;
142588
- const payload = event.payload;
142589
- if (!scopedProjectId || payload.citationId !== event.eventId || payload.projectId !== scopedProjectId || !isGenerationId(payload.generationId) || !Array.isArray(payload.pages)) {
142590
- throw new ChatStoreError("stored Knowledge citation is invalid", 409, "chat-knowledge-citation-invalid");
142591
- }
142592
- const slugs = payload.pages.map((page) => page?.slug);
142593
- if (slugs.some((slug) => !isWikiSlug(slug))) {
142594
- throw new ChatStoreError("stored Knowledge citation pages are invalid", 409, "chat-knowledge-citation-invalid");
142924
+ let namedProjectId;
142925
+ try {
142926
+ for (const event of listChatEvents(owner3, chat.chatId)) {
142927
+ if (event.type !== "knowledge-citation") continue;
142928
+ const payload = event.payload;
142929
+ namedProjectId = typeof payload.projectId === "string" ? payload.projectId : void 0;
142930
+ if (!scopedProjectId || payload.citationId !== event.eventId || payload.projectId !== scopedProjectId || !isGenerationId(payload.generationId) || !Array.isArray(payload.pages)) {
142931
+ throw new ChatStoreError("stored Knowledge citation is invalid", 409, "chat-knowledge-citation-invalid");
142932
+ }
142933
+ const slugs = payload.pages.map((page) => page?.slug);
142934
+ if (slugs.some((slug) => !isWikiSlug(slug))) {
142935
+ throw new ChatStoreError("stored Knowledge citation pages are invalid", 409, "chat-knowledge-citation-invalid");
142936
+ }
142937
+ const pin = reconcileGenerationRetentionPin(scopedProjectId, {
142938
+ pinId: event.eventId,
142939
+ generationId: payload.generationId,
142940
+ ownerKind: "chat-citation",
142941
+ ownerId: `${chat.chatId}:${event.eventId}`,
142942
+ pages: slugs
142943
+ });
142944
+ if (pin.state !== "committed") commitGenerationRetentionPin(scopedProjectId, pin.pinId);
142945
+ result2.reconciled += 1;
142595
142946
  }
142596
- const pin = reconcileGenerationRetentionPin(scopedProjectId, {
142597
- pinId: event.eventId,
142598
- generationId: payload.generationId,
142599
- ownerKind: "chat-citation",
142600
- ownerId: `${chat.chatId}:${event.eventId}`,
142601
- pages: slugs
142602
- });
142603
- if (pin.state !== "committed") commitGenerationRetentionPin(scopedProjectId, pin.pinId);
142604
- reconciled += 1;
142947
+ } catch (error62) {
142948
+ noteStartupOwnerFailure("Knowledge citation recovery", owner3, error62);
142949
+ const why = `conversation ${chat.chatId} of ${ownerLabel(owner3)} could not be reconciled`;
142950
+ charge(scopedProjectId ?? ownerProjectId, why);
142951
+ if (namedProjectId && namedProjectId !== (scopedProjectId ?? ownerProjectId)) charge(namedProjectId, why);
142605
142952
  }
142606
142953
  }
142607
142954
  }
142608
- return reconciled;
142955
+ return result2;
142609
142956
  }
142610
142957
  function parseEvent2(value, expectedChatId) {
142611
142958
  const row2 = value;
@@ -142625,19 +142972,26 @@ function reconcileChatEventJournals() {
142625
142972
  return withReadScope(reconcileChatEventJournalsNow);
142626
142973
  }
142627
142974
  function reconcileChatEventJournalsNow() {
142628
- const owners = [
142629
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
142630
- ...listArchivedProjects().map((project) => ({ kind: "project", projectId: project.id })),
142631
- ...listWorkflowOwnerships({ includeArchived: true }).map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
142632
- ];
142633
142975
  let repaired = 0;
142634
- for (const owner3 of owners) {
142635
- const resolved = resolveOwner2(owner3);
142636
- for (const chat of listChats(owner3, { includeArchived: true })) {
142637
- const events = readEventJournal(resolved, chat);
142638
- if (events.length === chat.lastEventSequence) continue;
142639
- repairEventMetadata(resolved, chat, events);
142640
- repaired += 1;
142976
+ for (const owner3 of startupChatOwners({ includeArchived: true })) {
142977
+ let resolved;
142978
+ let ownedChats;
142979
+ try {
142980
+ resolved = resolveOwner2(owner3);
142981
+ ownedChats = listChats(owner3, { includeArchived: true });
142982
+ } catch (error62) {
142983
+ noteStartupOwnerFailure("event journal repair", owner3, error62);
142984
+ continue;
142985
+ }
142986
+ for (const chat of ownedChats) {
142987
+ try {
142988
+ const events = readEventJournal(resolved, chat);
142989
+ if (events.length === chat.lastEventSequence) continue;
142990
+ repairEventMetadata(resolved, chat, events);
142991
+ repaired += 1;
142992
+ } catch (error62) {
142993
+ noteStartupOwnerFailure("event journal repair", owner3, error62);
142994
+ }
142641
142995
  }
142642
142996
  }
142643
142997
  return repaired;
@@ -143171,17 +143525,15 @@ function resurveyFollowupReceipts(waiting, targeted) {
143171
143525
  async function recoverChatFollowups(target) {
143172
143526
  const targeted = Boolean(target);
143173
143527
  let waiting = withReadScope(() => {
143174
- const owners = target ? [target.owner] : [
143175
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
143176
- ...listWorkflowOwnerships().map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
143177
- ];
143528
+ const owners = target ? [target.owner] : startupChatOwners({ includeArchived: false });
143178
143529
  const surveyed = [];
143179
143530
  for (const owner3 of owners) {
143180
143531
  let ownedChats;
143181
143532
  try {
143182
143533
  ownedChats = target ? [readChat(owner3, target.chatId)] : listChats(owner3, { includeArchived: true });
143183
143534
  } catch (error62) {
143184
- console.error("[chat] follow-up recovery could not list an owner:", error62);
143535
+ if (target) reportOwnerFailure("follow-up recovery", owner3, error62);
143536
+ else noteStartupOwnerFailure("follow-up recovery", owner3, error62);
143185
143537
  continue;
143186
143538
  }
143187
143539
  for (const chat of ownedChats) {
@@ -143319,17 +143671,14 @@ function listQueuedChatFollowupConversations() {
143319
143671
  return withReadScope(listQueuedChatFollowupConversationsNow);
143320
143672
  }
143321
143673
  function listQueuedChatFollowupConversationsNow() {
143322
- const owners = [
143323
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
143324
- ...listWorkflowOwnerships().map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
143325
- ];
143674
+ const owners = startupChatOwners({ includeArchived: false });
143326
143675
  const queued = [];
143327
143676
  for (const owner3 of owners) {
143328
143677
  let chats;
143329
143678
  try {
143330
143679
  chats = listChats(owner3);
143331
143680
  } catch (error62) {
143332
- console.error("[chat] queued follow-up resume could not list an owner:", error62);
143681
+ reportOwnerFailure("queued follow-up resume", owner3, error62);
143333
143682
  continue;
143334
143683
  }
143335
143684
  for (const chat of chats) {
@@ -143572,7 +143921,7 @@ async function updateChatTurnIntent(owner3, chatId, turnId, mutate) {
143572
143921
  return saved;
143573
143922
  });
143574
143923
  }
143575
- var import_node_crypto66, import_node_fs81, import_node_path81, UUID20, REQUEST_UUID, SHA25611, CHAT_FILE, CHAT_DIRECTORY, EVENTS_DIRECTORY, TURNS_DIRECTORY, FOLLOWUPS_DIRECTORY, ATTACHMENTS_DIRECTORY, REQUEST_LINKS_DIRECTORY, MAX_CHAT_BYTES, MAX_EVENT_BYTES, MAX_USER_MESSAGE_EVENT_BYTES, MAX_TURN_BYTES, MAX_SUBJECT_INDEX_BYTES, MAX_FOLLOWUP_BYTES, MAX_TEXT_BYTES, MAX_DRAFT_BYTES, MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, MAX_IMAGES_PER_MESSAGE, MAX_INTEGRATION_BINDINGS, MAX_ATTACHMENT_TOTAL_BYTES, SECRET_KEY, MEDIA_EXTENSIONS, ChatStoreError, UNREADABLE_CHAT_MESSAGE, reportedUnreadable, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight2, MAX_SUBJECT_LINK_CALLS_PER_TURN, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
143924
+ var import_node_crypto66, import_node_fs81, import_node_path81, UUID20, REQUEST_UUID, SHA25611, CHAT_FILE, CHAT_DIRECTORY, EVENTS_DIRECTORY, TURNS_DIRECTORY, FOLLOWUPS_DIRECTORY, ATTACHMENTS_DIRECTORY, REQUEST_LINKS_DIRECTORY, MAX_CHAT_BYTES, MAX_EVENT_BYTES, MAX_USER_MESSAGE_EVENT_BYTES, MAX_TURN_BYTES, MAX_SUBJECT_INDEX_BYTES, MAX_FOLLOWUP_BYTES, MAX_TEXT_BYTES, MAX_DRAFT_BYTES, MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, MAX_IMAGES_PER_MESSAGE, MAX_INTEGRATION_BINDINGS, MAX_ATTACHMENT_TOTAL_BYTES, SECRET_KEY, MEDIA_EXTENSIONS, ChatStoreError, UNREADABLE_CHAT_MESSAGE, reportedUnreadable, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight2, MAX_SUBJECT_LINK_CALLS_PER_TURN, startupOwnerNotes, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
143576
143925
  var init_chat_store = __esm({
143577
143926
  "chat-store.ts"() {
143578
143927
  "use strict";
@@ -143667,6 +144016,7 @@ var init_chat_store = __esm({
143667
144016
  isCount4 = (value) => Number.isSafeInteger(value) && value >= 0;
143668
144017
  isWeight2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
143669
144018
  MAX_SUBJECT_LINK_CALLS_PER_TURN = 10;
144019
+ startupOwnerNotes = /* @__PURE__ */ new Set();
143670
144020
  subjectIndexWarnings = /* @__PURE__ */ new Set();
143671
144021
  isMissing = (error62) => error62?.code === "ENOENT" || error62 instanceof ChatStoreError && error62.status === 404;
143672
144022
  PROMOTABLE_FOLLOWUP_STATES = ["queued-next", "admitting", "sending", "unknown"];
@@ -171539,6 +171889,12 @@ function chatIsGone(error62) {
171539
171889
  const e = error62;
171540
171890
  return e.name === "ChatStoreError" && e.status === 404 && typeof e.message === "string" && e.message.startsWith("unknown chat:");
171541
171891
  }
171892
+ function chatOwnerIsGone(error62) {
171893
+ if (!error62 || typeof error62 !== "object") return false;
171894
+ const e = error62;
171895
+ if (e.status !== 404 || typeof e.message !== "string") return false;
171896
+ return e.name === "ChatStoreError" && e.message.startsWith("unknown or unsigned project:") || e.name === "WorkflowOwnershipError" && (e.message.startsWith("unknown workflow:") || e.message.startsWith("unknown or unsigned project:"));
171897
+ }
171542
171898
  function scratchLivenessForChatState(state3) {
171543
171899
  if (state3 === null) return "unobservable";
171544
171900
  if (state3 === "unreadable") return "live";
@@ -190932,9 +191288,7 @@ var init_complete_model_report_controller = __esm({
190932
191288
  function isReportLockDirectoryName(name) {
190933
191289
  return name.endsWith(".lock") || LOCK_RESIDUE.test(name);
190934
191290
  }
190935
- function secureCompleteReportRoot(root9) {
190936
- (0, import_node_fs105.mkdirSync)(root9, { recursive: true, mode: 448 });
190937
- ensureOwnerOnlyStoragePath(root9, "directory");
191291
+ function reportRootChildren(root9) {
190938
191292
  const children = [];
190939
191293
  for (const name of (0, import_node_fs105.readdirSync)(root9)) {
190940
191294
  const path = (0, import_node_path103.join)(root9, name);
@@ -190944,7 +191298,17 @@ function secureCompleteReportRoot(root9) {
190944
191298
  else if (stat4.isDirectory() && isReportLockDirectoryName(name)) children.push({ path, kind: "directory" });
190945
191299
  else throw new Error("Complete report private storage contains an unexpected entry.");
190946
191300
  }
190947
- ensureOwnerOnlyStoragePaths(children);
191301
+ return children;
191302
+ }
191303
+ function secureCompleteReportRoot(root9) {
191304
+ (0, import_node_fs105.mkdirSync)(root9, { recursive: true, mode: 448 });
191305
+ ensureOwnerOnlyStoragePath(root9, "directory");
191306
+ ensureOwnerOnlyStoragePaths(reportRootChildren(root9));
191307
+ }
191308
+ async function secureCompleteReportRootAsync(root9) {
191309
+ (0, import_node_fs105.mkdirSync)(root9, { recursive: true, mode: 448 });
191310
+ await ensureOwnerOnlyStoragePathsAsync([{ path: root9, kind: "directory" }]);
191311
+ await ensureOwnerOnlyStoragePathsAsync(reportRootChildren(root9));
190948
191312
  }
190949
191313
  var import_node_fs105, import_node_path103, LOCK_RESIDUE;
190950
191314
  var init_complete_report_private_storage = __esm({
@@ -191226,7 +191590,7 @@ var init_complete_report_registry = __esm({
191226
191590
  }
191227
191591
  async ensureRoot() {
191228
191592
  if (!this.secured) {
191229
- secureCompleteReportRoot(this.root);
191593
+ await secureCompleteReportRootAsync(this.root);
191230
191594
  this.secured = true;
191231
191595
  }
191232
191596
  }
@@ -191715,7 +192079,7 @@ var init_complete_report_quota = __esm({
191715
192079
  }
191716
192080
  async setup() {
191717
192081
  if (!this.secured) {
191718
- secureCompleteReportRoot(this.root);
192082
+ await secureCompleteReportRootAsync(this.root);
191719
192083
  this.secured = true;
191720
192084
  }
191721
192085
  }
@@ -191982,6 +192346,13 @@ var init_complete_report_run_journal = __esm({
191982
192346
  this.secured = true;
191983
192347
  }
191984
192348
  }
192349
+ /** Run the one-time storage audit without blocking the event loop, before recovery reads (#1826). */
192350
+ async prepare() {
192351
+ if (!this.secured) {
192352
+ await secureCompleteReportRootAsync(this.root);
192353
+ this.secured = true;
192354
+ }
192355
+ }
191985
192356
  path(id2) {
191986
192357
  if (!ID4.test(id2)) throw new ReportRunJournalError();
191987
192358
  return (0, import_node_path106.join)(this.root, `${id2}.json`);
@@ -192429,6 +192800,16 @@ var init_complete_report_runtime_clock = __esm({
192429
192800
  sample(monotonicNowMs = import_node_perf_hooks4.performance.now()) {
192430
192801
  if (!Number.isFinite(monotonicNowMs) || monotonicNowMs < 0) throw new ReportRuntimeClockError();
192431
192802
  secureCompleteReportRoot(this.root);
192803
+ return this.sampleSecured(monotonicNowMs);
192804
+ }
192805
+ /** `sample()` without blocking the event loop on the storage audit — for background report recovery. */
192806
+ async sampleAsync() {
192807
+ await secureCompleteReportRootAsync(this.root);
192808
+ const monotonicNowMs = import_node_perf_hooks4.performance.now();
192809
+ if (!Number.isFinite(monotonicNowMs) || monotonicNowMs < 0) throw new ReportRuntimeClockError();
192810
+ return this.sampleSecured(monotonicNowMs);
192811
+ }
192812
+ sampleSecured(monotonicNowMs) {
192432
192813
  return withSecurityStateLock(this.path, () => {
192433
192814
  const active2 = readState(this.activePath);
192434
192815
  if (active2 !== null) {
@@ -192599,6 +192980,14 @@ var init_complete_report_retired_store = __esm({
192599
192980
  }
192600
192981
  list() {
192601
192982
  secureCompleteReportRoot(this.root);
192983
+ return this.listSecured();
192984
+ }
192985
+ /** `list()` without blocking the event loop on the storage audit — for background report recovery. */
192986
+ async listAsync() {
192987
+ await secureCompleteReportRootAsync(this.root);
192988
+ return this.listSecured();
192989
+ }
192990
+ listSecured() {
192602
192991
  const entries = (0, import_node_fs111.readdirSync)(this.root);
192603
192992
  if (entries.some((name) => !(name.endsWith(".json") && ID5.test(name.slice(0, -5))) && !RETIRED_LOCK.test(name) && !DURABLE_TEMP.test(name))) throw new RetiredReportStoreError();
192604
192993
  return entries.filter((name) => name.endsWith(".json")).sort().map((name) => {
@@ -192743,7 +193132,7 @@ async function auditTombstone(tombstone, deps, bootId) {
192743
193132
  async function maintainReportHistory(deps, mode, maxDue = 4, allowNewRetirement = true) {
192744
193133
  const bootId = deps.bootId();
192745
193134
  const retiring = deps.journal.list().filter((row2) => row2.state === "retiring");
192746
- const tombstones = deps.retired.list();
193135
+ const tombstones = await deps.retired.listAsync();
192747
193136
  if (mode === "boot") {
192748
193137
  for (const row2 of retiring) await deps.quota.restoreRetirementCharge(row2.id, row2.budget);
192749
193138
  for (const tombstone of tombstones) await deps.quota.restoreRetirementCharge(tombstone.id, tombstone.row.budget);
@@ -192773,7 +193162,7 @@ async function maintainReportHistory(deps, mode, maxDue = 4, allowNewRetirement
192773
193162
  if (!allowNewRetirement) return;
192774
193163
  let observed;
192775
193164
  try {
192776
- observed = deps.observedRuntimeMs();
193165
+ observed = await deps.observedRuntimeMs();
192777
193166
  } catch (error62) {
192778
193167
  deps.onError?.("manual-expiry", error62);
192779
193168
  return;
@@ -193301,28 +193690,85 @@ function registerRequestListRoute(app, deps) {
193301
193690
  const mark = (stage) => {
193302
193691
  stages[stage] = Math.round(import_node_perf_hooks5.performance.now() - startedAt);
193303
193692
  };
193693
+ const sliceMs = deps.sliceMs ?? REQUEST_LIST_SLICE_MS;
193694
+ const openPass = deps.readPass ?? openReadPass;
193695
+ let slices = 0;
193696
+ let longestSliceMs = 0;
193697
+ let longestPublishMs = 0;
193304
193698
  const stored2 = deps.listRequests();
193305
193699
  mark("list");
193306
193700
  const published = /* @__PURE__ */ new Map();
193307
- const readScope = deps.readScope ?? ((fn2) => fn2());
193701
+ const ownerGone = /* @__PURE__ */ new Set();
193308
193702
  const answered = deps.publishAnswer ? stored2.flatMap((request) => {
193309
193703
  const answer = validatedRequestAnswer(request);
193310
193704
  const provider3 = request.run?.runtime;
193311
193705
  return answer && (provider3 === "claude" || provider3 === "codex") ? [{ request, answer, provider: provider3 }] : [];
193312
193706
  }) : [];
193313
193707
  let toPublish = [];
193314
- const checkPublished = () => {
193708
+ const attachChat = (row2, byId2) => {
193709
+ const request = typeof row2.id === "string" ? byId2.get(row2.id) : void 0;
193710
+ if (request && (isFilterAiChangeRequest(request) || isFilterAiQuestionRequest(request))) {
193711
+ row2.filterAiAdmissionUnconfirmed = filterAiAdmissionUnconfirmed(request);
193712
+ row2.filterAiNotStarted = readFilterAiNotStarted(request) !== null;
193713
+ }
193714
+ const warnOnce = (requestId, phase2, error62) => {
193715
+ const key5 = `${requestId ?? ""}:${phase2}`;
193716
+ if (requestId && warnedInvalidChatLinks.has(key5)) return;
193717
+ if (requestId && warnedInvalidChatLinks.size >= MAX_WARNED_CHAT_KEYS) {
193718
+ if (warnedInvalidChatLinks.has(WARN_SATURATED)) return;
193719
+ app.log.error(
193720
+ { cap: MAX_WARNED_CHAT_KEYS },
193721
+ "too many Requests have unreadable chat sidecars to report one by one \u2014 later ones are shown on their rows only"
193722
+ );
193723
+ warnedInvalidChatLinks.add(WARN_SATURATED);
193724
+ return;
193725
+ }
193726
+ app.log.error(
193727
+ { requestId, phase: phase2, err: String(error62) },
193728
+ phase2 === "link" ? "could not read Request chat link" : "could not read Request chat state"
193729
+ );
193730
+ if (requestId) warnedInvalidChatLinks.add(key5);
193731
+ };
193732
+ let link2;
193733
+ let chatState = null;
193734
+ try {
193735
+ link2 = request ? deps.chatLink?.(request) : null;
193736
+ } catch (error62) {
193737
+ warnOnce(request?.id, "link", error62);
193738
+ link2 = null;
193739
+ }
193740
+ if (link2 && request) {
193741
+ try {
193742
+ chatState = deps.chatState?.(request, (error62) => warnOnce(request.id, "state", error62)) ?? null;
193743
+ } catch (error62) {
193744
+ warnOnce(request.id, "state", error62);
193745
+ chatState = "unreadable";
193746
+ }
193747
+ }
193748
+ if (link2) {
193749
+ if (request?.id) warnedInvalidChatLinks.delete(`${request.id}:link`);
193750
+ if (request?.id && chatState !== "unreadable") warnedInvalidChatLinks.delete(`${request.id}:state`);
193751
+ row2.chatConversation = {
193752
+ chatId: link2.chatId,
193753
+ executionOwner: link2.executionOwner,
193754
+ chatState,
193755
+ answerEventId: link2.answerEventId ?? null
193756
+ };
193757
+ }
193758
+ };
193759
+ function* readSteps() {
193315
193760
  for (const { request, answer } of answered) {
193316
193761
  try {
193317
193762
  const link2 = deps.publishedAnswer?.(request, answer);
193318
193763
  if (link2) published.set(request.id, link2);
193319
- } catch {
193764
+ } catch (error62) {
193765
+ if (deps.ownerGone?.(error62)) ownerGone.add(request.id);
193320
193766
  }
193767
+ yield;
193321
193768
  }
193322
- toPublish = answered.filter(({ request }) => !published.has(request.id) && (deps.canPublishAnswer?.(request) ?? true));
193769
+ toPublish = answered.filter(({ request }) => !published.has(request.id) && !ownerGone.has(request.id) && (deps.canPublishAnswer?.(request) ?? true));
193323
193770
  if (answered.length) mark("published-check");
193324
- };
193325
- const projectRows = () => {
193771
+ if (toPublish.length) yield PUBLISH;
193326
193772
  const chatPublications = stored2.flatMap((request) => {
193327
193773
  const result2 = validatedRequestAnswer(request);
193328
193774
  if (!result2) return [];
@@ -193336,92 +193782,76 @@ function registerRequestListRoute(app, deps) {
193336
193782
  answerEventId: link2.answerEventId
193337
193783
  }];
193338
193784
  });
193339
- const requestRows = deps.requestViews(stored2.filter((request) => {
193785
+ const unpublished = stored2.filter((request) => {
193340
193786
  const answer = validatedRequestAnswer(request);
193341
193787
  return !answer || !published.has(request.id);
193342
- }));
193788
+ });
193789
+ const requestRows = [];
193790
+ for (let at = 0; at === 0 || at < unpublished.length; at += VIEW_BATCH) {
193791
+ requestRows.push(...deps.requestViews(unpublished.slice(at, at + VIEW_BATCH)));
193792
+ yield;
193793
+ }
193343
193794
  mark("views");
193344
193795
  const byId2 = new Map(stored2.map((request) => [request.id, request]));
193345
193796
  for (const row2 of requestRows) {
193346
- const request = typeof row2.id === "string" ? byId2.get(row2.id) : void 0;
193347
- if (request && (isFilterAiChangeRequest(request) || isFilterAiQuestionRequest(request))) {
193348
- row2.filterAiAdmissionUnconfirmed = filterAiAdmissionUnconfirmed(request);
193349
- row2.filterAiNotStarted = readFilterAiNotStarted(request) !== null;
193350
- }
193351
- const warnOnce = (requestId, phase2, error62) => {
193352
- const key5 = `${requestId ?? ""}:${phase2}`;
193353
- if (requestId && warnedInvalidChatLinks.has(key5)) return;
193354
- if (requestId && warnedInvalidChatLinks.size >= MAX_WARNED_CHAT_KEYS) {
193355
- if (warnedInvalidChatLinks.has(WARN_SATURATED)) return;
193356
- app.log.error(
193357
- { cap: MAX_WARNED_CHAT_KEYS },
193358
- "too many Requests have unreadable chat sidecars to report one by one \u2014 later ones are shown on their rows only"
193359
- );
193360
- warnedInvalidChatLinks.add(WARN_SATURATED);
193361
- return;
193362
- }
193363
- app.log.error(
193364
- { requestId, phase: phase2, err: String(error62) },
193365
- phase2 === "link" ? "could not read Request chat link" : "could not read Request chat state"
193366
- );
193367
- if (requestId) warnedInvalidChatLinks.add(key5);
193368
- };
193369
- let link2;
193370
- let chatState = null;
193371
- try {
193372
- link2 = request ? deps.chatLink?.(request) : null;
193373
- } catch (error62) {
193374
- warnOnce(request?.id, "link", error62);
193375
- link2 = null;
193797
+ attachChat(row2, byId2);
193798
+ yield;
193799
+ }
193800
+ mark("chat-links");
193801
+ return { ok: true, requests: requestRows, chatPublications };
193802
+ }
193803
+ const steps = readSteps();
193804
+ let pass = openPass();
193805
+ for (; ; ) {
193806
+ const sliceStart = import_node_perf_hooks5.performance.now();
193807
+ const step = pass(() => {
193808
+ for (; ; ) {
193809
+ const next = steps.next();
193810
+ if (next.done || next.value === PUBLISH || import_node_perf_hooks5.performance.now() - sliceStart >= sliceMs) return next;
193376
193811
  }
193377
- if (link2 && request) {
193812
+ });
193813
+ slices += 1;
193814
+ longestSliceMs = Math.max(longestSliceMs, import_node_perf_hooks5.performance.now() - sliceStart);
193815
+ if (step.done) {
193816
+ const body = step.value;
193817
+ const totalMs = Math.round(import_node_perf_hooks5.performance.now() - startedAt);
193818
+ if (totalMs >= (deps.slowMs ?? SLOW_REQUEST_LIST_MS)) {
193819
+ app.log.warn({
193820
+ totalMs,
193821
+ stages,
193822
+ requests: stored2.length,
193823
+ lockedPublishes: toPublish.length,
193824
+ ownerGone: ownerGone.size,
193825
+ slices,
193826
+ longestSliceMs: Math.round(longestSliceMs),
193827
+ longestPublishMs: Math.round(longestPublishMs)
193828
+ }, "slow Requests list read");
193829
+ }
193830
+ return body;
193831
+ }
193832
+ if (step.value === PUBLISH) {
193833
+ for (const { request, answer, provider: provider3 } of toPublish) {
193834
+ const publishStart = import_node_perf_hooks5.performance.now();
193378
193835
  try {
193379
- chatState = deps.chatState?.(request, (error62) => warnOnce(request.id, "state", error62)) ?? null;
193836
+ const link2 = await withLifecycleLock(
193837
+ "internal-export",
193838
+ `request-${request.id}`,
193839
+ () => deps.publishAnswer({ request, answer, provider: provider3 }),
193840
+ { label: "publishing Request answer to chat" }
193841
+ );
193842
+ if (link2) published.set(request.id, link2);
193380
193843
  } catch (error62) {
193381
- warnOnce(request.id, "state", error62);
193382
- chatState = "unreadable";
193383
- }
193384
- }
193385
- if (link2) {
193386
- if (request?.id) warnedInvalidChatLinks.delete(`${request.id}:link`);
193387
- if (request?.id && chatState !== "unreadable") warnedInvalidChatLinks.delete(`${request.id}:state`);
193388
- row2.chatConversation = {
193389
- chatId: link2.chatId,
193390
- executionOwner: link2.executionOwner,
193391
- chatState,
193392
- answerEventId: link2.answerEventId ?? null
193393
- };
193844
+ app.log.error({ requestId: request.id, err: String(error62) }, "could not publish Request answer to AI Chat");
193845
+ }
193846
+ longestPublishMs = Math.max(longestPublishMs, import_node_perf_hooks5.performance.now() - publishStart);
193847
+ await yieldToEventLoop();
193394
193848
  }
193849
+ mark("publish");
193850
+ pass = openPass();
193851
+ continue;
193395
193852
  }
193396
- mark("chat-links");
193397
- return { ok: true, requests: requestRows, chatPublications };
193398
- };
193399
- let body = readScope(() => {
193400
- checkPublished();
193401
- return toPublish.length === 0 ? projectRows() : null;
193402
- });
193403
- if (!body) {
193404
- await Promise.all(toPublish.map(async ({ request, answer, provider: provider3 }) => {
193405
- try {
193406
- const link2 = await withLifecycleLock(
193407
- "internal-export",
193408
- `request-${request.id}`,
193409
- () => deps.publishAnswer({ request, answer, provider: provider3 }),
193410
- { label: "publishing Request answer to chat" }
193411
- );
193412
- if (link2) published.set(request.id, link2);
193413
- } catch (error62) {
193414
- app.log.error({ requestId: request.id, err: String(error62) }, "could not publish Request answer to AI Chat");
193415
- }
193416
- }));
193417
- mark("publish");
193418
- body = readScope(projectRows);
193419
- }
193420
- const totalMs = Math.round(import_node_perf_hooks5.performance.now() - startedAt);
193421
- if (totalMs >= (deps.slowMs ?? SLOW_REQUEST_LIST_MS)) {
193422
- app.log.warn({ totalMs, stages, requests: stored2.length, lockedPublishes: toPublish.length }, "slow Requests list read");
193853
+ await yieldToEventLoop();
193423
193854
  }
193424
- return body;
193425
193855
  }
193426
193856
  let inFlight2 = null;
193427
193857
  let queued = null;
@@ -193440,7 +193870,7 @@ function registerRequestListRoute(app, deps) {
193440
193870
  }
193441
193871
  app.get("/api/requests", () => coalescedList());
193442
193872
  }
193443
- var import_node_perf_hooks5, SLOW_REQUEST_LIST_MS;
193873
+ var import_node_perf_hooks5, SLOW_REQUEST_LIST_MS, REQUEST_LIST_SLICE_MS, VIEW_BATCH, PUBLISH, yieldToEventLoop;
193444
193874
  var init_request_list_route = __esm({
193445
193875
  "request-list-route.ts"() {
193446
193876
  "use strict";
@@ -193448,7 +193878,14 @@ var init_request_list_route = __esm({
193448
193878
  init_instructor_request();
193449
193879
  init_lifecycle_lock();
193450
193880
  init_filter_ai_request();
193881
+ init_read_scope();
193451
193882
  SLOW_REQUEST_LIST_MS = 1e3;
193883
+ REQUEST_LIST_SLICE_MS = 50;
193884
+ VIEW_BATCH = 8;
193885
+ PUBLISH = /* @__PURE__ */ Symbol("publish");
193886
+ yieldToEventLoop = () => new Promise((resolve56) => {
193887
+ setImmediate(resolve56);
193888
+ });
193452
193889
  }
193453
193890
  });
193454
193891
 
@@ -195572,6 +196009,7 @@ var init_model_editor_state = __esm({
195572
196009
  // model-project-deletion.ts
195573
196010
  async function deleteArchivedModelProject(options2) {
195574
196011
  const { module: module2, projectUuid } = options2;
196012
+ options2.assertProjectRemovable();
195575
196013
  if (projectUuid && (module2 === "revit" || module2 === "tekla")) {
195576
196014
  await options2.deleteEditorState(projectUuid);
195577
196015
  }
@@ -197131,6 +197569,7 @@ var init_revit_import = __esm({
197131
197569
  init_durable_replace();
197132
197570
  init_lifecycle_lock();
197133
197571
  init_projects_store();
197572
+ init_read_scope();
197134
197573
  init_revit_project_lock();
197135
197574
  init_revit_project_lifecycle();
197136
197575
  init_revit_reader_trust();
@@ -197378,7 +197817,14 @@ var init_revit_import = __esm({
197378
197817
  let authorizationRetained = 0;
197379
197818
  const accessRetained = /* @__PURE__ */ new Set();
197380
197819
  const retainedJournalOperations = /* @__PURE__ */ new Set();
197381
- for (const project of listProjects()) {
197820
+ const journaled = withReadScope(() => listProjects().filter((project) => {
197821
+ try {
197822
+ return (0, import_node_fs119.existsSync)((0, import_node_path117.join)(projectDir(project.id), PUBLICATION_JOURNAL));
197823
+ } catch {
197824
+ return true;
197825
+ }
197826
+ }));
197827
+ for (const project of journaled) {
197382
197828
  let retainedOperationId = null;
197383
197829
  try {
197384
197830
  const path = (0, import_node_path117.join)(projectDir(project.id), PUBLICATION_JOURNAL);
@@ -207536,25 +207982,45 @@ function writePin(appId, pin) {
207536
207982
  return withPinLock(() => writePinUnlocked(appId, pin));
207537
207983
  }
207538
207984
  function reconcileWorkflowKnowledgeRetention() {
207539
- if (!(0, import_node_fs136.existsSync)(pinsDir())) return 0;
207540
- let count4 = 0;
207985
+ const result2 = emptyRetentionSweep();
207986
+ if (!(0, import_node_fs136.existsSync)(pinsDir())) return result2;
207987
+ const { uuidById, unsignedIds } = withReadScope(() => {
207988
+ const map2 = /* @__PURE__ */ new Map();
207989
+ const unsigned = /* @__PURE__ */ new Set();
207990
+ for (const project of [...listProjects(), ...listArchivedProjects()]) {
207991
+ if (project.uuid) map2.set(project.id, project.uuid);
207992
+ else unsigned.add(project.id);
207993
+ }
207994
+ return { uuidById: map2, unsignedIds: unsigned };
207995
+ });
207541
207996
  for (const entry2 of (0, import_node_fs136.readdirSync)(pinsDir(), { withFileTypes: true })) {
207542
207997
  if (!entry2.isFile() || !entry2.name.endsWith(".json")) continue;
207543
207998
  const appId = (0, import_node_path132.basename)(entry2.name, ".json");
207544
- const pin = readPinUnlocked(appId);
207545
- if (!pin) throw new KbPinError(`stored workflow Knowledge pin is unreadable: ${appId}`, "invalid-pages");
207546
- if (!pin.retentionPinId) continue;
207547
- const retention = reconcileGenerationRetentionPin(pin.projectId, {
207548
- pinId: pin.retentionPinId,
207549
- generationId: pin.generationId,
207550
- ownerKind: "workflow",
207551
- ownerId: appId,
207552
- pages: pin.pages.map((page) => page.slug)
207553
- });
207554
- if (retention.state !== "committed") commitGenerationRetentionPin(pin.projectId, retention.pinId);
207555
- count4 += 1;
207999
+ let projectId2 = null;
208000
+ try {
208001
+ const pin = readPinUnlocked(appId);
208002
+ if (!pin) throw new KbPinError(`stored workflow Knowledge pin is unreadable: ${appId}`, "invalid-pages");
208003
+ projectId2 = pin.projectId;
208004
+ if (!pin.retentionPinId) continue;
208005
+ const retention = reconcileGenerationRetentionPin(pin.projectId, {
208006
+ pinId: pin.retentionPinId,
208007
+ generationId: pin.generationId,
208008
+ ownerKind: "workflow",
208009
+ ownerId: appId,
208010
+ pages: pin.pages.map((page) => page.slug)
208011
+ });
208012
+ if (retention.state !== "committed") commitGenerationRetentionPin(pin.projectId, retention.pinId);
208013
+ result2.reconciled += 1;
208014
+ } catch (error62) {
208015
+ const uuid5 = projectId2 ? uuidById.get(projectId2) : void 0;
208016
+ const why = `workflow ${appId} Knowledge pin: ${error62 instanceof Error ? error62.message : String(error62)}`;
208017
+ console.warn(`[knowledge] start-up retention check could not reconcile ${why}`);
208018
+ if (uuid5) result2.blockedProjectUuids.add(uuid5);
208019
+ else if (projectId2 && unsignedIds.has(projectId2)) result2.blockedUnsignedProjectIds.add(projectId2);
208020
+ else result2.unattributed.push(why);
208021
+ }
207556
208022
  }
207557
- return count4;
208023
+ return result2;
207558
208024
  }
207559
208025
  function movePinBytesUnlocked(fromAppId, toAppId) {
207560
208026
  const from = pinPath(fromAppId);
@@ -207598,6 +208064,8 @@ var init_kb_pin_store = __esm({
207598
208064
  import_node_path132 = require("node:path");
207599
208065
  import_node_os62 = require("node:os");
207600
208066
  init_knowledge_store();
208067
+ init_projects_store();
208068
+ init_read_scope();
207601
208069
  init_write_json_atomic();
207602
208070
  init_lifecycle_lock();
207603
208071
  KbPinError = class extends Error {
@@ -207998,7 +208466,8 @@ function registerCompleteReportDiscoveryRoute(app, deps) {
207998
208466
  deps.authorizeEditor(request);
207999
208467
  if (!deps.ready()) return reply.status(503).send({
208000
208468
  ok: false,
208001
- error: "FloLess is checking an earlier model report. Check again in a few minutes. If reports stay paused, use Report an issue."
208469
+ code: "model-report-recovery-pending",
208470
+ error: "FloLess is still checking an earlier model report, so reports are paused for a moment. Try again shortly. If this keeps happening, use Report an issue."
208002
208471
  });
208003
208472
  const routine = deps.routine(request.params.routineId);
208004
208473
  if (!routine || routine.workflow !== "tekla-model-report" && routine.workflow !== "floless-workspace-model-report") {
@@ -214155,6 +214624,82 @@ var init_workspace_mutation_recovery = __esm({
214155
214624
  }
214156
214625
  });
214157
214626
 
214627
+ // startup-report-recovery.ts
214628
+ function refusesReportRunDuringRecovery(input2) {
214629
+ return !input2.simulate && !input2.dryRun && !input2.ready && (input2.templateId === "tekla-model-report" || input2.templateId === "floless-workspace-model-report");
214630
+ }
214631
+ function createStartupReportRecovery(deps) {
214632
+ const now2 = deps.now ?? Date.now;
214633
+ const setTimer = deps.setTimer ?? ((run2, ms2) => setTimeout(run2, ms2));
214634
+ const clearTimer = deps.clearTimer ?? ((timer) => clearTimeout(timer));
214635
+ let started = null;
214636
+ let firstSettled = false;
214637
+ let sweepSettled = false;
214638
+ let ready = false;
214639
+ let paused = false;
214640
+ const markReady = () => {
214641
+ paused = false;
214642
+ if (ready) return;
214643
+ ready = true;
214644
+ try {
214645
+ deps.onReady();
214646
+ } catch (error62) {
214647
+ deps.log.warn({ err: String(error62) }, "report readiness notification failed");
214648
+ }
214649
+ };
214650
+ return {
214651
+ start() {
214652
+ if (started) return started;
214653
+ started = (async () => {
214654
+ const began = now2();
214655
+ deps.log.info({}, "complete report recovery started");
214656
+ const watchdog = setTimer(() => {
214657
+ paused = true;
214658
+ deps.log.error(
214659
+ { durationMs: now2() - began },
214660
+ "complete report recovery has not finished; model reports stay paused until it does"
214661
+ );
214662
+ }, deps.stuckAfterMs ?? 5 * 6e4);
214663
+ watchdog?.unref?.();
214664
+ try {
214665
+ await deps.attempt();
214666
+ deps.log.info({ durationMs: now2() - began, outcome: "ready" }, "complete report recovery finished");
214667
+ markReady();
214668
+ } catch (error62) {
214669
+ paused = true;
214670
+ deps.log.error(
214671
+ { durationMs: now2() - began, outcome: "paused", err: error62 },
214672
+ "complete report recovery failed; model reports remain paused until a retry succeeds"
214673
+ );
214674
+ } finally {
214675
+ clearTimer(watchdog);
214676
+ firstSettled = true;
214677
+ }
214678
+ try {
214679
+ await deps.sweepOwners();
214680
+ } catch (error62) {
214681
+ deps.log.error({ err: String(error62) }, "workspace mutation owner reconciliation failed");
214682
+ } finally {
214683
+ sweepSettled = true;
214684
+ }
214685
+ })();
214686
+ return started;
214687
+ },
214688
+ mayRetry: () => firstSettled && sweepSettled,
214689
+ markReady,
214690
+ markPaused() {
214691
+ ready = false;
214692
+ paused = true;
214693
+ },
214694
+ state: () => ready ? "ready" : paused ? "paused" : "checking"
214695
+ };
214696
+ }
214697
+ var init_startup_report_recovery = __esm({
214698
+ "startup-report-recovery.ts"() {
214699
+ "use strict";
214700
+ }
214701
+ });
214702
+
214158
214703
  // workspace-aware-process.ts
214159
214704
  function operationOwner(spec) {
214160
214705
  const root9 = activeWorkspaceRoot();
@@ -226903,7 +227448,7 @@ async function probeClaudeRuntime() {
226903
227448
  }
226904
227449
  if (launch.managed) return { binary: launch.file, version: TESTED_CLAUDE_VERSION, managed: true };
226905
227450
  const binary = launch.file;
226906
- const result2 = await execFile14(binary, ["--version"], { windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
227451
+ const result2 = await execFile15(binary, ["--version"], { windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
226907
227452
  const version2 = cleanText(result2.stdout, 256).match(/\d+\.\d+\.\d+/u)?.[0] ?? "";
226908
227453
  if (version2 !== TESTED_CLAUDE_VERSION) {
226909
227454
  throw new Error(`FloLess supports Claude Code ${TESTED_CLAUDE_VERSION}; installed version is ${version2 || "unknown"}`);
@@ -226952,7 +227497,7 @@ function terminalReceipt(chat, turn) {
226952
227497
  error: cleanText(event.payload.terminalError, 8192) || "Claude turn failed"
226953
227498
  };
226954
227499
  }
226955
- var import_node_child_process29, import_node_crypto119, import_node_fs145, import_node_util13, execFile14, CLAUDE_PROBE_TIMEOUT, READ_ONLY_TOOLS, ISOLATED_READ_TOOLS, ISOLATED_WRITE_TOOLS, CLAUDE_TOOL_SHAPES, TurnRef, DEFAULT_WARM_DEPS, LiveClaudeInput, ClaudeChatProvider;
227500
+ var import_node_child_process29, import_node_crypto119, import_node_fs145, import_node_util13, execFile15, CLAUDE_PROBE_TIMEOUT, READ_ONLY_TOOLS, ISOLATED_READ_TOOLS, ISOLATED_WRITE_TOOLS, CLAUDE_TOOL_SHAPES, TurnRef, DEFAULT_WARM_DEPS, LiveClaudeInput, ClaudeChatProvider;
226956
227501
  var init_chat_provider_claude = __esm({
226957
227502
  "chat-provider-claude.ts"() {
226958
227503
  "use strict";
@@ -226970,7 +227515,7 @@ var init_chat_provider_claude = __esm({
226970
227515
  init_managed_runtime();
226971
227516
  init_managed_runtime_pins();
226972
227517
  init_chat_provider();
226973
- execFile14 = (0, import_node_util13.promisify)(import_node_child_process29.execFile);
227518
+ execFile15 = (0, import_node_util13.promisify)(import_node_child_process29.execFile);
226974
227519
  CLAUDE_PROBE_TIMEOUT = "Claude capability check timed out";
226975
227520
  READ_ONLY_TOOLS = ["Read", "Glob", "Grep", "WebFetch", "WebSearch"];
226976
227521
  ISOLATED_READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
@@ -227830,7 +228375,7 @@ async function probeCodexRuntime() {
227830
228375
  }
227831
228376
  if (launch.managed) return { binary: launch.file, version: CODEX_HEADLESS_VERSION.replace(/^codex-cli\s+/u, ""), env: launch.env, managed: true };
227832
228377
  const binary = launch.file;
227833
- const result2 = await execFile15(binary, ["--version"], { windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
228378
+ const result2 = await execFile16(binary, ["--version"], { windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
227834
228379
  const version2 = cleanText2(result2.stdout, 256).replace(/^codex-cli\s+/u, "");
227835
228380
  if (`codex-cli ${version2}` !== CODEX_HEADLESS_VERSION) {
227836
228381
  throw new Error(`FloLess supports ${CODEX_HEADLESS_VERSION}; installed Codex is ${version2 || "unknown"}`);
@@ -227885,7 +228430,7 @@ function codexItemEvent(itemValue, sawDelta) {
227885
228430
  if (type === "contextCompaction") return { providerItemId: id2, type: "compaction", payload: { provider: "codex" } };
227886
228431
  return null;
227887
228432
  }
227888
- var import_node_child_process30, import_node_util14, import_node_readline3, import_node_fs146, execFile15, MAX_PROTOCOL_LINE, REQUEST_TIMEOUT_MS2, TURN_TIMEOUT_MS, CODEX_PROBE_TIMEOUT, ACCOUNT_CHANGED, STALLED, DISABLED_CONNECTOR_FEATURES, CodexChatProvider;
228433
+ var import_node_child_process30, import_node_util14, import_node_readline3, import_node_fs146, execFile16, MAX_PROTOCOL_LINE, REQUEST_TIMEOUT_MS2, TURN_TIMEOUT_MS, CODEX_PROBE_TIMEOUT, ACCOUNT_CHANGED, STALLED, DISABLED_CONNECTOR_FEATURES, CodexChatProvider;
227889
228434
  var init_chat_provider_codex = __esm({
227890
228435
  "chat-provider-codex.ts"() {
227891
228436
  "use strict";
@@ -227901,7 +228446,7 @@ var init_chat_provider_codex = __esm({
227901
228446
  init_terminal_runtime();
227902
228447
  init_managed_runtime();
227903
228448
  init_chat_provider();
227904
- execFile15 = (0, import_node_util14.promisify)(import_node_child_process30.execFile);
228449
+ execFile16 = (0, import_node_util14.promisify)(import_node_child_process30.execFile);
227905
228450
  MAX_PROTOCOL_LINE = 16 * 1024 * 1024;
227906
228451
  REQUEST_TIMEOUT_MS2 = 3e4;
227907
228452
  TURN_TIMEOUT_MS = 24 * 60 * 60 * 1e3;
@@ -228720,7 +229265,7 @@ async function defaultExec(file2, args, env2) {
228720
229265
  const batch = process.platform === "win32" && /\.(cmd|bat)$/iu.test(file2);
228721
229266
  const [exe2, argv] = batch ? ["cmd.exe", ["/d", "/s", "/c", file2, ...args]] : [file2, [...args]];
228722
229267
  try {
228723
- const { stdout, stderr } = await execFile16(exe2, argv, { env: env2, windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
229268
+ const { stdout, stderr } = await execFile17(exe2, argv, { env: env2, windowsHide: true, timeout: 1e4, maxBuffer: 256 * 1024 });
228724
229269
  return { stdout, stderr, code: 0 };
228725
229270
  } catch (error62) {
228726
229271
  return execOutcome(error62);
@@ -228743,7 +229288,7 @@ function unrecognisedDetail(reason, result2) {
228743
229288
  const output2 = snippet(`${result2.stderr} ${result2.stdout}`);
228744
229289
  return output2 ? `${reason} (exit ${result2.code}: ${output2})` : `${reason} (exit ${result2.code}, no output)`;
228745
229290
  }
228746
- var import_node_child_process31, import_node_fs147, import_node_path142, import_node_util15, execFile16, CLAUDE_UNRECOGNISED, CODEX_UNRECOGNISED, SIGN_IN_CACHE_MS, SIGN_IN_LAUNCH_COOLDOWN_MS, MAX_TEXT2, SignInLaunchError, LABELS2, UNSAFE_PATH, MAX_DETAIL, CONTROL_CHARS2, MAX_AUTH_BYTES2, ProviderSignIn;
229291
+ var import_node_child_process31, import_node_fs147, import_node_path142, import_node_util15, execFile17, CLAUDE_UNRECOGNISED, CODEX_UNRECOGNISED, SIGN_IN_CACHE_MS, SIGN_IN_LAUNCH_COOLDOWN_MS, MAX_TEXT2, SignInLaunchError, LABELS2, UNSAFE_PATH, MAX_DETAIL, CONTROL_CHARS2, MAX_AUTH_BYTES2, ProviderSignIn;
228747
229292
  var init_provider_sign_in = __esm({
228748
229293
  "provider-sign-in.ts"() {
228749
229294
  "use strict";
@@ -228753,7 +229298,7 @@ var init_provider_sign_in = __esm({
228753
229298
  import_node_util15 = require("node:util");
228754
229299
  init_provider_home();
228755
229300
  init_terminal_runtime();
228756
- execFile16 = (0, import_node_util15.promisify)(import_node_child_process31.execFile);
229301
+ execFile17 = (0, import_node_util15.promisify)(import_node_child_process31.execFile);
228757
229302
  CLAUDE_UNRECOGNISED = "unrecognised claude auth status output";
228758
229303
  CODEX_UNRECOGNISED = "unrecognised codex login status output";
228759
229304
  SIGN_IN_CACHE_MS = 1e4;
@@ -231275,6 +231820,9 @@ function beginGoogleConnectFenceLifetime(options2) {
231275
231820
  }
231276
231821
  async function startServer() {
231277
231822
  installCrashHandlers();
231823
+ const bootStartedAt = Date.now();
231824
+ const bootPhases = {};
231825
+ let bootPhaseStarted = bootStartedAt;
231278
231826
  const logger = true ? true : { transport: { target: "pino-pretty" } };
231279
231827
  const app = (0, import_fastify.default)({ logger });
231280
231828
  if (productionDistributionProfile.features.providerDiscovery && !process.env.AWARE_MODEL_REFERENCE_PROVIDER) {
@@ -232207,6 +232755,9 @@ async function startServer() {
232207
232755
  if (err2 instanceof EditorSessionAuthError) {
232208
232756
  return reply.status(err2.status).send({ ok: false, error: err2.code, message: err2.message });
232209
232757
  }
232758
+ if (err2 instanceof ProjectFolderInUseError) {
232759
+ return reply.status(409).send({ ok: false, error: err2.message, code: err2.code });
232760
+ }
232210
232761
  if (err2 instanceof ProjectError) {
232211
232762
  return reply.status(400).send({ ok: false, error: err2.message });
232212
232763
  }
@@ -232315,6 +232866,9 @@ async function startServer() {
232315
232866
  rvtDefaults: rvtDefaultAppsStatus().status,
232316
232867
  coreDefaults: rvtCoreAppsStatus().status,
232317
232868
  sseClients: clientCount(),
232869
+ // Start-up work that runs after the server listens (#1826). `checking`: saved model reports are still
232870
+ // being verified, so report routes refuse for now; `paused`: a check failed and is being retried.
232871
+ startup: { reports: startupReports.state() },
232318
232872
  license: (await getLicenseStatus2()).state
232319
232873
  // UI + launcher branch on this
232320
232874
  };
@@ -233085,10 +233639,10 @@ async function startServer() {
233085
233639
  projectName: requestProjectName(x)
233086
233640
  }));
233087
233641
  const requestViews = (list3) => {
233088
- const root9 = templateIdResolver();
233089
- const nameMemo = /* @__PURE__ */ new Map();
233090
- const headMemo = /* @__PURE__ */ new Map();
233091
- const contractFactsMemo = /* @__PURE__ */ new Map();
233642
+ const root9 = memoInReadScope("request-views:template-id", templateIdResolver);
233643
+ const nameMemo = memoInReadScope("request-views:project-names", () => /* @__PURE__ */ new Map());
233644
+ const headMemo = memoInReadScope("request-views:head-versions", () => /* @__PURE__ */ new Map());
233645
+ const contractFactsMemo = memoInReadScope("request-views:contract-facts", () => /* @__PURE__ */ new Map());
233092
233646
  const headVersion = (project) => {
233093
233647
  const cached2 = headMemo.get(project);
233094
233648
  if (cached2 !== void 0) return cached2;
@@ -233280,6 +233834,10 @@ async function startServer() {
233280
233834
  else if (identity4) initializeDuplicatedRevitProject(project.id, identity4.accountId, identity4.entitlementRevision);
233281
233835
  }
233282
233836
  });
233837
+ function projectFolderInUseReply(reply, projectId2, error62) {
233838
+ app.log.warn({ projectId: projectId2, err: String(error62.osError) }, "project folder is in use; move refused");
233839
+ return reply.status(409).send({ ok: false, error: error62.message, code: error62.code });
233840
+ }
233283
233841
  app.post("/api/projects/:id/archive", async (req, reply) => {
233284
233842
  try {
233285
233843
  return await withProjectMutationLock(req.params.id, async (locked) => {
@@ -233295,6 +233853,7 @@ async function startServer() {
233295
233853
  return { ok: true };
233296
233854
  });
233297
233855
  } catch (e) {
233856
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
233298
233857
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
233299
233858
  if (e instanceof ChatCoordinatorError) return reply.status(e.status).send({ ok: false, error: e.message, code: e.code });
233300
233859
  throw e;
@@ -233341,6 +233900,7 @@ async function startServer() {
233341
233900
  }
233342
233901
  return restored;
233343
233902
  } catch (e) {
233903
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
233344
233904
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
233345
233905
  throw e;
233346
233906
  }
@@ -233356,6 +233916,7 @@ async function startServer() {
233356
233916
  await deleteArchivedModelProject({
233357
233917
  module: archived ? moduleForTemplate(resolveTemplateId(archived.app))?.key ?? null : null,
233358
233918
  projectUuid: archived?.uuid ?? null,
233919
+ assertProjectRemovable: () => assertArchivedProjectRemovable(projectId2),
233359
233920
  deleteEditorState: (uuid5) => modelEditorStateStore.deleteProject(uuid5),
233360
233921
  deleteProject: () => deleteArchivedProject(projectId2),
233361
233922
  releaseRevitSource: (uuid5) => modelSourceStore.releaseProject(uuid5)
@@ -233363,6 +233924,7 @@ async function startServer() {
233363
233924
  return { ok: true };
233364
233925
  });
233365
233926
  } catch (e) {
233927
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
233366
233928
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
233367
233929
  throw e;
233368
233930
  }
@@ -234659,6 +235221,7 @@ ${view.prompt}` : "";
234659
235221
  const completeReportRuntimeClock = new CompleteReportRuntimeClock((0, import_node_path145.join)(completeReportRoot, "runtime-clock"));
234660
235222
  const completeReportRetired = new CompleteReportRetiredStore((0, import_node_path145.join)(completeReportRoot, "retired"));
234661
235223
  let completeReportReady = false;
235224
+ const REPORT_RECOVERY_PENDING_MESSAGE = "FloLess is still checking an earlier model report, so reports are paused for a moment. Try again shortly. If this keeps happening, use Report an issue.";
234662
235225
  let nextReportHistoryAt = 0;
234663
235226
  const reportHistoryPruneAvailable = () => {
234664
235227
  const installed = awareInstalledVersion();
@@ -234704,7 +235267,7 @@ ${view.prompt}` : "";
234704
235267
  if (!completeReportReady) throw new WorkspaceModelQueryError(
234705
235268
  503,
234706
235269
  "model-report-recovery-pending",
234707
- "FloLess is checking an earlier model report. Reports are temporarily paused. Check again in a few minutes. If they stay paused, use Report an issue."
235270
+ REPORT_RECOVERY_PENDING_MESSAGE
234708
235271
  );
234709
235272
  const selection = parseCompleteReportSelection(body);
234710
235273
  const context = activeCompleteReportRun;
@@ -234932,6 +235495,7 @@ ${view.prompt}` : "";
234932
235495
  function resumeDeferredRevitPublications(access, force = false) {
234933
235496
  return deferredRevitRecoveryDriver.onAccess(access, force);
234934
235497
  }
235498
+ bootPhaseStarted = Date.now();
234935
235499
  try {
234936
235500
  const boot = await revitImportOrchestrator.recoverAtStartup();
234937
235501
  if (boot.retained > 0) deferredRevitRecoveryDriver.notePendingWork();
@@ -234939,6 +235503,7 @@ ${view.prompt}` : "";
234939
235503
  app.log.error({ err: error62 instanceof Error ? error62.message : error62 }, "Revit import recovery failed");
234940
235504
  deferredRevitRecoveryDriver.notePendingWork();
234941
235505
  }
235506
+ bootPhases.revitImportRecovery = Date.now() - bootPhaseStarted;
234942
235507
  if (workspaceRootState().available) {
234943
235508
  for (const project of listProjects()) {
234944
235509
  if (moduleForTemplate(resolveTemplateId(project.app))?.key !== "revit" || !project.uuid) continue;
@@ -237811,6 +238376,9 @@ ${view.prompt}` : "";
237811
238376
  }
237812
238377
  });
237813
238378
  }
238379
+ function isCompleteReportTemplate(templateId) {
238380
+ return templateId === "tekla-model-report" || templateId === "floless-workspace-model-report";
238381
+ }
237814
238382
  async function prepareCompleteReportRun(id2, inputs, controller, routineId) {
237815
238383
  const template = resolveTemplateId(id2);
237816
238384
  const module2 = template === "tekla-model-report" ? "tekla" : template === "floless-workspace-model-report" ? "revit" : null;
@@ -237818,7 +238386,7 @@ ${view.prompt}` : "";
237818
238386
  if (!completeReportReady) throw new WorkspaceModelQueryError(
237819
238387
  503,
237820
238388
  "model-report-recovery-pending",
237821
- "FloLess is checking an earlier model report. Reports are temporarily paused. Check again in a few minutes. If they stay paused, use Report an issue."
238389
+ REPORT_RECOVERY_PENDING_MESSAGE
237822
238390
  );
237823
238391
  if (id2 !== template) throw new WorkspaceModelQueryError(
237824
238392
  409,
@@ -238018,6 +238586,11 @@ ${view.prompt}` : "";
238018
238586
  if (row2?.state === "reserved" || row2?.state === "running") completeReportRunJournal.finishSettlement(context.reservationId);
238019
238587
  }
238020
238588
  async function runVerifiedCompleteReport(id2, inputs, routineId) {
238589
+ if (!completeReportReady) throw new WorkspaceModelQueryError(
238590
+ 503,
238591
+ "model-report-recovery-pending",
238592
+ REPORT_RECOVERY_PENDING_MESSAGE
238593
+ );
238021
238594
  return withLifecycleLock("internal-export", "complete-report-recovery", async () => {
238022
238595
  const guard = {
238023
238596
  controller: new AbortController(),
@@ -238254,6 +238827,9 @@ ${view.prompt}` : "";
238254
238827
  const model = id2 === "tekla-parser" ? "Tekla" : "Revit";
238255
238828
  return reply.status(403).send({ ok: false, error: `${model} conversion must start from its project Source step`, code: "setup-unavailable" });
238256
238829
  }
238830
+ if (refusesReportRunDuringRecovery({ templateId: resolveTemplateId(id2), simulate: !!simulate, dryRun: !!dryRun, ready: completeReportReady })) {
238831
+ return reply.send({ ok: false, error: REPORT_RECOVERY_PENDING_MESSAGE, code: "model-report-recovery-pending" });
238832
+ }
238257
238833
  await admitInstalledWorkflowRuntime(id2);
238258
238834
  const blocked = hostRunBlocked(appProviderUncached(id2));
238259
238835
  if (blocked) return reply.send({ ok: false, error: blocked, blocked: true, simulate: !!simulate });
@@ -238336,7 +238912,7 @@ ${view.prompt}` : "";
238336
238912
  if (!completeReportReady) throw new WorkspaceModelQueryError(
238337
238913
  503,
238338
238914
  "model-report-recovery-pending",
238339
- "FloLess is checking an earlier model report. Reports are temporarily paused. Check again in a few minutes. If they stay paused, use Report an issue."
238915
+ REPORT_RECOVERY_PENDING_MESSAGE
238340
238916
  );
238341
238917
  authorizeModelEditor(request);
238342
238918
  const handle = request.params.handle ?? "";
@@ -238766,7 +239342,8 @@ ${view.prompt}` : "";
238766
239342
  canPublishAnswer: (request) => requestChatOwner(request) !== null,
238767
239343
  chatLink: requestChatLink,
238768
239344
  chatState: requestChatState,
238769
- readScope: withReadScope
239345
+ ownerGone: chatOwnerIsGone,
239346
+ readPass: openReadPass
238770
239347
  });
238771
239348
  registerDesktopHandoffRoutes(app, {
238772
239349
  requestView: (id2) => requestView2(getRequest(id2)),
@@ -239404,6 +239981,7 @@ ${v.prompt}` : "";
239404
239981
  process.on("SIGTERM", () => {
239405
239982
  void shutdown("SIGTERM");
239406
239983
  });
239984
+ bootPhaseStarted = Date.now();
239407
239985
  try {
239408
239986
  if (workspaceRootState().available) {
239409
239987
  for (const line of await recoverAllProjectTransactions(() => listProjects().map((p) => p.id))) {
@@ -239415,23 +239993,41 @@ ${v.prompt}` : "";
239415
239993
  app.log.info({ error: error62.message }, "skipped project contract recovery while the selected workspace root is unavailable");
239416
239994
  } else throw error62;
239417
239995
  }
239996
+ bootPhases.contractRecovery = Date.now() - bootPhaseStarted;
239418
239997
  beginKnowledgeRetentionReconciliation();
239998
+ bootPhaseStarted = Date.now();
239419
239999
  try {
239420
240000
  if (workspaceRootState().available) {
239421
- reconcileWorkflowKnowledgeRetention();
239422
- reconcileChatKnowledgeRetention();
240001
+ const decision = applyKnowledgeRetentionSweeps(
240002
+ activeWorkspaceRoot().rootId,
240003
+ [reconcileWorkflowKnowledgeRetention(), reconcileChatKnowledgeRetention()]
240004
+ );
240005
+ if (decision.gc === "closed") {
240006
+ app.log.warn(
240007
+ { failures: decision.unattributed.slice(0, 10), count: decision.unattributed.length },
240008
+ "Knowledge retention reconciliation failed; generation cleanup remains disabled"
240009
+ );
240010
+ } else if (decision.heldUuids.length || decision.heldUnsignedIds.length) {
240011
+ app.log.warn(
240012
+ { projectUuids: decision.heldUuids, unsignedProjects: decision.heldUnsignedIds },
240013
+ "Knowledge retention reconciliation failed for some projects; generation cleanup stays off for those projects only"
240014
+ );
240015
+ }
240016
+ } else {
240017
+ completeKnowledgeRetentionReconciliation();
239423
240018
  }
239424
- completeKnowledgeRetentionReconciliation();
239425
240019
  } catch (error62) {
239426
240020
  app.log.warn(
239427
240021
  { error: error62 instanceof Error ? error62.message : String(error62) },
239428
240022
  "Knowledge retention reconciliation failed; generation cleanup remains disabled"
239429
240023
  );
239430
240024
  }
240025
+ bootPhases.knowledgeRetention = Date.now() - bootPhaseStarted;
239431
240026
  async function runCompleteReportRecovery(mode) {
239432
240027
  await withLifecycleLock("internal-export", "complete-report-recovery", async () => {
240028
+ await completeReportRunJournal.prepare();
239433
240029
  const rows2 = completeReportRunJournal.list();
239434
- const tombstones = completeReportRetired.list();
240030
+ const tombstones = await completeReportRetired.listAsync();
239435
240031
  const knownHandles = /* @__PURE__ */ new Set();
239436
240032
  for (const row2 of rows2) {
239437
240033
  if (row2.sealed) knownHandles.add(row2.sealed.handle);
@@ -239477,33 +240073,44 @@ ${v.prompt}` : "";
239477
240073
  quota: completeReportQuota,
239478
240074
  retired: completeReportRetired,
239479
240075
  bootId: reportOsBootId,
239480
- observedRuntimeMs: () => completeReportRuntimeClock.sample(),
240076
+ observedRuntimeMs: () => completeReportRuntimeClock.sampleAsync(),
239481
240077
  prune: pruneRunArtifacts,
239482
240078
  usage: readRunArtifactUsage,
239483
240079
  onError: (id2, error62) => app.log.warn({ id: id2, err: String(error62) }, "saved report cleanup deferred")
239484
240080
  }, mode === "boot" ? "boot" : "periodic", 4, reportHistoryPruneAvailable());
239485
240081
  }, { label: "checking interrupted model reports", expectedMs: 6e4 });
239486
240082
  }
239487
- try {
240083
+ let completeReportRecoveryChecking = false;
240084
+ let nextCompleteReportRecoveryAt = 0;
240085
+ let completeReportRecoveryBackoffMs = 15e3;
240086
+ async function recoverCompleteReportsAtBoot() {
239488
240087
  (0, import_node_fs151.mkdirSync)(completeReportRoot, { recursive: true, mode: 448 });
239489
- ensureOwnerOnlyStoragePath(completeReportRoot, "directory");
240088
+ await ensureOwnerOnlyStoragePathsAsync([{ path: completeReportRoot, kind: "directory" }]);
240089
+ await completeReportRunJournal.prepare();
239490
240090
  const protectedBeforeRecovery = new Set(completeReportRunJournal.list().map((row2) => row2.id));
239491
240091
  await runCompleteReportRecovery("boot");
239492
240092
  for (const row2 of completeReportRunJournal.list()) protectedBeforeRecovery.add(row2.id);
239493
240093
  protectReportAwareProcessOwners(protectedBeforeRecovery);
239494
240094
  completeReportReady = true;
239495
240095
  nextReportHistoryAt = Date.now() + 5 * 6e4;
239496
- } catch (error62) {
239497
- app.log.error({ err: String(error62) }, "complete model reports remain unavailable until recovery succeeds");
239498
- }
239499
- let completeReportRecoveryChecking = false;
239500
- let nextCompleteReportRecoveryAt = 0;
239501
- let completeReportRecoveryBackoffMs = 15e3;
239502
- try {
239503
- completeReportRuntimeClock.sample();
239504
- } catch (error62) {
239505
- app.log.warn({ err: String(error62) }, "report history clock unavailable; manual report expiry disabled");
239506
240096
  }
240097
+ const startupReports = createStartupReportRecovery({
240098
+ attempt: recoverCompleteReportsAtBoot,
240099
+ // A report-linked AWARE owner is never part of the generic kill sweep. This sweep runs only after the
240100
+ // first recovery attempt has protected every journaled reservation (or leaves all AWARE owners
240101
+ // protected when that audit failed).
240102
+ sweepOwners: async () => {
240103
+ const count4 = await reconcileWorkspaceMutationOwnersOnBoot();
240104
+ if (count4) app.log.info({ count: count4 }, "reconciled completed workspace owner(s)");
240105
+ },
240106
+ // A browser that opened while reports were paused asks again now, instead of waiting for its own retry.
240107
+ onReady: () => {
240108
+ for (const routine of listRoutines()) {
240109
+ if (isCompleteReportTemplate(routine.workflow)) broadcast(completeReportInvalidation(routine.id, routine.workflow));
240110
+ }
240111
+ },
240112
+ log: app.log
240113
+ });
239507
240114
  setInterval(() => {
239508
240115
  try {
239509
240116
  completeReportRuntimeClock.sample();
@@ -239512,7 +240119,7 @@ ${v.prompt}` : "";
239512
240119
  }
239513
240120
  }, 60 * 6e4).unref();
239514
240121
  setInterval(() => {
239515
- if (completeReportRecoveryChecking) return;
240122
+ if (completeReportRecoveryChecking || !startupReports.mayRetry()) return;
239516
240123
  const now2 = Date.now();
239517
240124
  if (now2 < nextCompleteReportRecoveryAt) return;
239518
240125
  const mode = completeReportReady ? "retry" : "boot";
@@ -239522,18 +240129,18 @@ ${v.prompt}` : "";
239522
240129
  if (!pending && (!reportHistoryPruneAvailable() || now2 < nextReportHistoryAt)) return;
239523
240130
  } catch (error62) {
239524
240131
  completeReportReady = false;
240132
+ startupReports.markPaused();
239525
240133
  app.log.warn({ err: String(error62) }, "complete model reports paused until recovery succeeds");
239526
240134
  return;
239527
240135
  }
239528
240136
  }
239529
240137
  completeReportRecoveryChecking = true;
239530
240138
  void (async () => {
239531
- const protectedBeforeRecovery = mode === "boot" ? new Set(completeReportRunJournal.list().map((row2) => row2.id)) : null;
239532
- await runCompleteReportRecovery(mode);
239533
- if (protectedBeforeRecovery) {
239534
- for (const row2 of completeReportRunJournal.list()) protectedBeforeRecovery.add(row2.id);
239535
- protectReportAwareProcessOwners(protectedBeforeRecovery);
239536
- completeReportReady = true;
240139
+ if (mode === "boot") {
240140
+ await recoverCompleteReportsAtBoot();
240141
+ startupReports.markReady();
240142
+ } else {
240143
+ await runCompleteReportRecovery(mode);
239537
240144
  }
239538
240145
  completeReportRecoveryBackoffMs = 15e3;
239539
240146
  nextCompleteReportRecoveryAt = 0;
@@ -239546,11 +240153,11 @@ ${v.prompt}` : "";
239546
240153
  completeReportRecoveryChecking = false;
239547
240154
  });
239548
240155
  }, 15e3).unref();
239549
- void reconcileWorkspaceMutationOwnersOnBoot().then((count4) => {
239550
- if (count4) app.log.info({ count: count4 }, "reconciled completed workspace owner(s)");
239551
- }).catch((error62) => app.log.error({ err: String(error62) }, "workspace mutation owner reconciliation failed"));
239552
240156
  await app.listen({ port: PORT2, host: HOST });
239553
240157
  app.log.info(`floless.app on http://${HOST}:${PORT2} (aware npm ${getBootstrapState().awareVersion ?? "unresolved"})`);
240158
+ app.log.info({ listenMs: Date.now() - bootStartedAt, phasesMs: bootPhases }, "startup phases");
240159
+ void startupReports.start();
240160
+ void completeReportRuntimeClock.sampleAsync().catch((error62) => app.log.warn({ err: String(error62) }, "report history clock unavailable; manual report expiry disabled"));
239554
240161
  await continueAfterAwareReady(await awareBootstrapCompletion);
239555
240162
  await ensureWorkspaceAgentReady();
239556
240163
  if (true) {
@@ -239837,6 +240444,7 @@ var init_index = __esm({
239837
240444
  init_watch();
239838
240445
  init_workspace_mutation_recovery();
239839
240446
  init_workspace_root_store();
240447
+ init_startup_report_recovery();
239840
240448
  init_workspace_mutation_registry();
239841
240449
  init_run_lease();
239842
240450
  init_workspace_aware_process();