@floless/app 0.147.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.147.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.147.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
 
@@ -101777,9 +101953,48 @@ function memberLabel(member) {
101777
101953
  const id2 = String(member.id ?? "");
101778
101954
  return profile ? `${profile} (${id2})` : id2;
101779
101955
  }
101956
+ function cutOutsideValues(text9, max2) {
101957
+ if (text9.length <= max2) return text9;
101958
+ if (max2 < 1) return "";
101959
+ const values2 = [...text9.matchAll(FEET_INCHES_VALUE)].map((m) => [m.index, m.index + m[0].length]);
101960
+ const outside = (at) => values2.every(([start2, end]) => at <= start2 || at >= end);
101961
+ for (let at = Math.min(max2 - 1, text9.length); at > 0; at -= 1) {
101962
+ if (!/\s/.test(text9[at] ?? "") || !outside(at)) continue;
101963
+ const kept = text9.slice(0, at).trimEnd();
101964
+ if (kept) return `${kept}\u2026`;
101965
+ }
101966
+ return "\u2026";
101967
+ }
101780
101968
  function sentence(parts) {
101781
101969
  const text9 = parts.filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
101782
- return truncateAtWord(text9, MAX_QUESTION2);
101970
+ return cutOutsideValues(text9, MAX_QUESTION2);
101971
+ }
101972
+ function sentenceKeepingEnds(ask2, label2, reason, list3) {
101973
+ const clean3 = (value) => value ? value.replace(/\s+/g, " ").trim() : "";
101974
+ const join131 = (...parts) => parts.filter(Boolean).join(" ");
101975
+ const tail2 = clean3(list3);
101976
+ const why = clean3(reason);
101977
+ const labels = [clean3(label2), ...labelCuts(clean3(label2))];
101978
+ const render = (shown, withReason) => join131(clean3(ask2(shown)), withReason ? why : "", tail2);
101979
+ for (const withReason of why ? [true, false] : [false]) {
101980
+ for (const shown of labels) {
101981
+ const question = render(shown, withReason);
101982
+ if (question.length <= MAX_QUESTION2) return question;
101983
+ }
101984
+ }
101985
+ return cutOutsideValues(render("\u2026", false), MAX_QUESTION2);
101986
+ }
101987
+ function labelCuts(label2) {
101988
+ const values2 = [...label2.matchAll(FEET_INCHES_VALUE)].map((m) => [m.index, m.index + m[0].length]);
101989
+ const outside = (at) => values2.every(([start2, end]) => at <= start2 || at >= end);
101990
+ const cuts = [];
101991
+ for (let at = label2.length - 1; at > 0; at -= 1) {
101992
+ if (!/\s/.test(label2[at] ?? "") || !outside(at)) continue;
101993
+ const kept = label2.slice(0, at).trimEnd();
101994
+ if (kept) cuts.push(`${kept}\u2026`);
101995
+ }
101996
+ cuts.push("\u2026");
101997
+ return [...new Set(cuts)];
101783
101998
  }
101784
101999
  function sheetList(checked2) {
101785
102000
  if (!checked2.length) return false;
@@ -101865,7 +102080,7 @@ function deriveContractRfis(model) {
101865
102080
  kind: "unknown-elevation",
101866
102081
  status: "open",
101867
102082
  silent: false,
101868
- question: sentence([`What is the top-of-steel elevation at the ${fact.end === 0 ? "start" : "end"} of ${memberLabel(raw)}?`, fact.why, sheetList(fact.checked)]),
102083
+ question: sentenceKeepingEnds((shown) => `What is the top-of-steel elevation at the ${fact.end === 0 ? "start" : "end"} of ${shown}?`, memberLabel(raw), fact.why, sheetList(fact.checked)),
101869
102084
  subjects: [{ memberId: raw.id, end: fact.end }],
101870
102085
  checked: fact.checked,
101871
102086
  drawingTarget: targets[0],
@@ -101955,11 +102170,12 @@ function deriveContractRfis(model) {
101955
102170
  id: rfiId(gapKey),
101956
102171
  gapKey,
101957
102172
  kind: "unknown-elevation",
101958
- question: sentence([
101959
- isAssumed(z11) ? `Is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${label2} correct?` : `What is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${label2}?`,
102173
+ question: sentenceKeepingEnds(
102174
+ (shown) => isAssumed(z11) ? `Is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${shown} correct?` : `What is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${shown}?`,
102175
+ label2,
101960
102176
  why || "The read did not record what the set says about it.",
101961
102177
  sheetList(checked2)
101962
- ]),
102178
+ ),
101963
102179
  subjects: [{ memberId: raw.id, end }],
101964
102180
  checked: checked2,
101965
102181
  silent: !why,
@@ -102434,7 +102650,7 @@ function boundRfis(all) {
102434
102650
  }
102435
102651
  return { rows: kept, omitted };
102436
102652
  }
102437
- var import_node_crypto29, ID_HEX, MAX_QUESTION2, MAX_LEGACY_GAP_ALIASES, RFI_CLASS_LIMITS, MAX_NAMED_VALUES, MAX_GROUP_SUBJECTS, isObj8, rfiId, TEMPLATE_REASON, isUnknown, isAssumed, isUnresolvedElevation, markerGapIdentity, untracedMemberGapKey, unknownSizeGapKey, rfiIdForGapKey, mm3, MAX_NAMED_ID, namedId, usableNote;
102653
+ var import_node_crypto29, ID_HEX, MAX_QUESTION2, MAX_LEGACY_GAP_ALIASES, RFI_CLASS_LIMITS, MAX_NAMED_VALUES, MAX_GROUP_SUBJECTS, isObj8, rfiId, TEMPLATE_REASON, isUnknown, isAssumed, isUnresolvedElevation, FEET_INCHES_VALUE, markerGapIdentity, untracedMemberGapKey, unknownSizeGapKey, rfiIdForGapKey, mm3, MAX_NAMED_ID, namedId, usableNote;
102438
102654
  var init_steel_read_rfis = __esm({
102439
102655
  "steel-read-rfis.ts"() {
102440
102656
  "use strict";
@@ -102504,6 +102720,7 @@ var init_steel_read_rfis = __esm({
102504
102720
  isUnknown = (z11) => isObj8(z11) && z11.unknown === true;
102505
102721
  isAssumed = (z11) => isObj8(z11) && z11.assumed === true;
102506
102722
  isUnresolvedElevation = (z11) => isUnknown(z11) || isAssumed(z11);
102723
+ FEET_INCHES_VALUE = /\d+\s*'\s*-?\s*\d+(?:\s+\d+\/\d+)?\s*"?|\d+\s+\d+\/\d+\s*"/g;
102507
102724
  markerGapIdentity = (kind2, sourceHash, pageId, elementId) => compositeGapIdentity(kind2, [sourceHash, pageId, elementId]);
102508
102725
  untracedMemberGapKey = (observationId, memberId) => compositeGapIdentity("untraced-member", [observationId, memberId]).gapKey;
102509
102726
  unknownSizeGapKey = (memberId) => `unknown-size:${memberId}`;
@@ -103264,18 +103481,25 @@ function placeUnprovenElevation(input2) {
103264
103481
  return { kind: "unplaceable", reason: "plan-states-no-elevation" };
103265
103482
  }
103266
103483
  const elevationMm = input2.plan.elevationMm;
103484
+ const serverWhy = input2.plan.basis === "level-with-other-end" ? levelledToOtherEndWhy(cited.sheet) : placedAtPlanWhy(cited.sheet);
103267
103485
  return {
103268
103486
  kind: "place",
103269
103487
  elevation: {
103270
103488
  known: elevationMm,
103271
103489
  assumed: true,
103272
- why: input2.plan.basis === "level-with-other-end" ? levelledToOtherEndWhy(cited.sheet) : placedAtPlanWhy(cited.sheet),
103490
+ why: withReaderAccount(serverWhy, input2.elevation),
103273
103491
  checked: mergeChecked(cited, input2.elevation),
103274
103492
  ...carriedCandidates(input2.elevation)
103275
103493
  },
103276
103494
  placed: { discardedZ: "known" in input2.elevation ? input2.elevation.known : elevationMm, cited }
103277
103495
  };
103278
103496
  }
103497
+ function withReaderAccount(serverWhy, elevation2) {
103498
+ if (!("unknown" in elevation2)) return serverWhy;
103499
+ const account = typeof elevation2.why === "string" ? elevation2.why.replace(/\s+/g, " ").trim() : "";
103500
+ if (!account || TEMPLATE_REASON.test(account)) return serverWhy;
103501
+ return `${serverWhy}${READER_ACCOUNT_LEAD}${account}`;
103502
+ }
103279
103503
  function carriedCandidates(elevation2) {
103280
103504
  return "unknown" in elevation2 && elevation2.candidates?.length ? { candidates: elevation2.candidates } : {};
103281
103505
  }
@@ -103294,14 +103518,16 @@ function citablePage(observations2, pageOf) {
103294
103518
  }
103295
103519
  return null;
103296
103520
  }
103297
- var MAX_CHECKED_PAGES, placedAtPlanWhy, levelledToOtherEndWhy, unplaceableWhy;
103521
+ var MAX_CHECKED_PAGES, placedAtPlanWhy, levelledToOtherEndWhy, READER_ACCOUNT_LEAD, unplaceableWhy;
103298
103522
  var init_elevation_resolution = __esm({
103299
103523
  "elevation-resolution.ts"() {
103300
103524
  "use strict";
103301
103525
  init_steel_model_v2();
103526
+ init_steel_read_rfis();
103302
103527
  MAX_CHECKED_PAGES = 20;
103303
- placedAtPlanWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and nothing read there gives it an elevation. It has been placed at a plan elevation so the member is built and can be seen, but a plan elevation is a cut plane, not a stated top of steel \u2014 it is unverified until someone confirms it.`;
103304
- levelledToOtherEndWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and nothing read there gives it an elevation. The other end of this member does have one, so this end has been levelled to it \u2014 which assumes the member is flat, and the drawings do not say that. It is unverified until someone confirms it.`;
103528
+ placedAtPlanWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and no height read there was tied to this end. It has been placed at a plan elevation so the member is built and can be seen, but a plan elevation is a cut plane, not a stated top of steel \u2014 it is unverified until someone confirms it.`;
103529
+ levelledToOtherEndWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and no height read there was tied to this end. The other end of this member does have one, so this end has been levelled to it \u2014 which assumes the member is flat, and the drawings do not say that. It is unverified until someone confirms it.`;
103530
+ READER_ACCOUNT_LEAD = " The read's own account: ";
103305
103531
  unplaceableWhy = (sheet) => `The drawings do not settle this endpoint's height, and this model states no plan elevation to place it at either \u2014 ${sheet} is the sheet it was read on. The value submitted with the read has been kept so the member is built, but nothing on the drawings supports it and it is unverified until someone confirms it.`;
103306
103532
  }
103307
103533
  });
@@ -116472,9 +116698,10 @@ function drawnAtNote(value, basis2, sheet) {
116472
116698
  }
116473
116699
  }
116474
116700
  function placementBasis(why, sheet) {
116475
- if (why === placedAtPlanWhy(sheet)) return "plan";
116476
- if (why === levelledToOtherEndWhy(sheet)) return "level-with-other-end";
116477
- if (why === unplaceableWhy(sheet)) return "submitted";
116701
+ const is = (sentence2) => typeof why === "string" && (why === sentence2 || why.startsWith(`${sentence2}${READER_ACCOUNT_LEAD}`));
116702
+ if (is(placedAtPlanWhy(sheet))) return "plan";
116703
+ if (is(levelledToOtherEndWhy(sheet))) return "level-with-other-end";
116704
+ if (is(unplaceableWhy(sheet))) return "submitted";
116478
116705
  return "unstated";
116479
116706
  }
116480
116707
  function uncheckedBeyondFirst(candidate2) {
@@ -117867,7 +118094,7 @@ function deleteRequest(id2) {
117867
118094
  }
117868
118095
  }
117869
118096
  }
117870
- clearRequestScratch(id2);
118097
+ clearRequestScratch(id2, "its request is being deleted");
117871
118098
  (0, import_node_fs44.rmSync)((0, import_node_path39.join)(REQUESTS_DIR, file2));
117872
118099
  clearRequestSettlement(id2);
117873
118100
  return true;
@@ -117876,10 +118103,15 @@ function requestIdFromFile(file2) {
117876
118103
  const match = /__([^_/\\]+)\.json$/i.exec(file2);
117877
118104
  return match && REQUEST_ID2.test(match[1]) ? match[1] : null;
117878
118105
  }
117879
- function clearRequestScratch(id2) {
118106
+ function clearRequestScratch(id2, reason) {
117880
118107
  if (!REQUEST_ID2.test(id2)) return true;
117881
118108
  try {
118109
+ const existed = (0, import_node_fs44.existsSync)(requestScratchPath(id2));
117882
118110
  const outcome = removeRequestScratch(id2);
118111
+ if (existed && outcome.removed) {
118112
+ console.log(`[request-work] removed the scratch directory of request ${id2}: ${reason}.`);
118113
+ }
118114
+ if (outcome.removed) unmeasurableScratch.delete(id2);
117883
118115
  if (!outcome.removed) {
117884
118116
  console.warn(outcome.retained.length ? `[floless-store] kept ${outcome.retained.length} named diagnostic(s) under ${outcome.path}: ${outcome.retained.join(", ")}` : `[floless-store] could not remove the scratch directory ${outcome.path} for request ${id2}`);
117885
118117
  }
@@ -117906,7 +118138,7 @@ function sweepIdleRequestScratch(options2) {
117906
118138
  if (id2.toLowerCase() === keep) continue;
117907
118139
  try {
117908
118140
  if (!hasRequestFile(id2)) {
117909
- if (clearRequestScratch(id2)) removed.push(id2);
118141
+ if (clearRequestScratch(id2, "it has no request row")) removed.push(id2);
117910
118142
  continue;
117911
118143
  }
117912
118144
  const request = getRequest(id2);
@@ -117918,18 +118150,35 @@ function sweepIdleRequestScratch(options2) {
117918
118150
  continue;
117919
118151
  }
117920
118152
  const state3 = options2.liveness(request);
117921
- if (state3 === "live") continue;
117922
- if (state3 === "unobservable") {
118153
+ let reason;
118154
+ if (state3 === "gone") {
118155
+ reason = "its conversation no longer exists";
118156
+ } else if (state3 === "idle" || state3 === "unobservable") {
117923
118157
  const newest = activity(id2);
117924
- if (newest === null || now2 - newest < idleMs) continue;
118158
+ if (newest !== null) unmeasurableScratch.delete(id2);
118159
+ if (newest === null) {
118160
+ if (!unmeasurableScratch.has(id2)) {
118161
+ unmeasurableScratch.add(id2);
118162
+ console.warn(`[request-work] cannot tell when request ${id2}'s scratch directory was last written; keeping it.`);
118163
+ }
118164
+ continue;
118165
+ }
118166
+ if (now2 - newest < idleMs) continue;
118167
+ reason = `${state3 === "idle" ? "its conversation is settled" : "the server cannot observe its reader"} and nothing in it has been written for ${formatIdle(now2 - newest)}`;
118168
+ } else {
118169
+ continue;
117925
118170
  }
117926
- if (clearRequestScratch(id2)) removed.push(id2);
118171
+ if (clearRequestScratch(id2, reason)) removed.push(id2);
117927
118172
  } catch (error62) {
117928
118173
  console.warn(`[floless-store] cannot decide whether request ${id2}'s scratch is idle; leaving it:`, error62);
117929
118174
  }
117930
118175
  }
117931
118176
  return removed;
117932
118177
  }
118178
+ function formatIdle(ms2) {
118179
+ const minutes = Math.floor(ms2 / 6e4);
118180
+ return minutes >= 120 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${minutes} min`;
118181
+ }
117933
118182
  function hasRequestFile(id2) {
117934
118183
  if (!(0, import_node_fs44.existsSync)(REQUESTS_DIR)) return false;
117935
118184
  return (0, import_node_fs44.readdirSync)(REQUESTS_DIR).some((f) => f.endsWith(`__${id2}.json`));
@@ -118014,7 +118263,7 @@ function clearCapturedRequests(snapshot2, protectRequest = () => false) {
118014
118263
  continue;
118015
118264
  }
118016
118265
  const orphanScratchId = requestIdFromFile(file2);
118017
- if (orphanScratchId) clearRequestScratch(orphanScratchId);
118266
+ if (orphanScratchId) clearRequestScratch(orphanScratchId, "its unreadable request row is being cleared");
118018
118267
  try {
118019
118268
  (0, import_node_fs44.rmSync)((0, import_node_path39.join)(REQUESTS_DIR, file2));
118020
118269
  removed++;
@@ -118072,7 +118321,7 @@ function decodeSnapshots(inputs) {
118072
118321
  return { buf, ext, role: s.role ?? "locator" };
118073
118322
  });
118074
118323
  }
118075
- var import_node_crypto37, import_node_fs44, import_node_os25, import_node_path39, ROOT4, TEMPLATES_FILE, REQUESTS_DIR, REQUEST_SETTLEMENTS_DIR, REQUEST_SETTLEMENT_HISTORY_DIR, PROMOTION_SETTLEMENT_INDEX, PROMOTION_SETTLEMENT_QUARANTINE_DIR, REQUEST_DISCARDS_DIR, REQUEST_DISCARD_HISTORY_DIR, REQUEST_PUBLICATION_STALE_MS, STEEL_FAVS_FILE, TYPE_SET, requestPublicationHookForTest, REQUEST_ID2, SETTLEMENT_HASH, SETTLEMENT_TEXT, SETTLEMENT_MAX_BYTES, SETTLEMENT_INDEX_MAX_BYTES, SETTLEMENT_DIAGNOSTIC_MAX, PROMOTION_SETTLEMENT_MAX_HISTORY, PROMOTION_SETTLEMENT_MAX_AGE_MS, emptyPromotionIndex, UNOBSERVABLE_SCRATCH_IDLE_MS, unreadableScratchRows, flolessRoot, SnapshotError, MAX_SNAPSHOTS, MAX_BYTES3;
118324
+ var import_node_crypto37, import_node_fs44, import_node_os25, import_node_path39, ROOT4, TEMPLATES_FILE, REQUESTS_DIR, REQUEST_SETTLEMENTS_DIR, REQUEST_SETTLEMENT_HISTORY_DIR, PROMOTION_SETTLEMENT_INDEX, PROMOTION_SETTLEMENT_QUARANTINE_DIR, REQUEST_DISCARDS_DIR, REQUEST_DISCARD_HISTORY_DIR, REQUEST_PUBLICATION_STALE_MS, STEEL_FAVS_FILE, TYPE_SET, requestPublicationHookForTest, REQUEST_ID2, SETTLEMENT_HASH, SETTLEMENT_TEXT, SETTLEMENT_MAX_BYTES, SETTLEMENT_INDEX_MAX_BYTES, SETTLEMENT_DIAGNOSTIC_MAX, PROMOTION_SETTLEMENT_MAX_HISTORY, PROMOTION_SETTLEMENT_MAX_AGE_MS, emptyPromotionIndex, UNOBSERVABLE_SCRATCH_IDLE_MS, unreadableScratchRows, unmeasurableScratch, flolessRoot, SnapshotError, MAX_SNAPSHOTS, MAX_BYTES3;
118076
118325
  var init_floless_store = __esm({
118077
118326
  "floless-store.ts"() {
118078
118327
  "use strict";
@@ -118120,6 +118369,7 @@ var init_floless_store = __esm({
118120
118369
  emptyPromotionIndex = () => ({ v: 1, entries: [] });
118121
118370
  UNOBSERVABLE_SCRATCH_IDLE_MS = 2 * 60 * 6e4;
118122
118371
  unreadableScratchRows = /* @__PURE__ */ new Set();
118372
+ unmeasurableScratch = /* @__PURE__ */ new Set();
118123
118373
  flolessRoot = ROOT4;
118124
118374
  SnapshotError = class extends Error {
118125
118375
  };
@@ -120919,9 +121169,19 @@ async function recoverProjectTransactions(projectId2) {
120919
121169
  }
120920
121170
  return outcomes;
120921
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
+ }
120922
121182
  async function recoverAllProjectTransactions(listIds) {
120923
121183
  const out = [];
120924
- for (const id2 of listIds()) {
121184
+ for (const id2 of projectsWithTransactionDirs(listIds)) {
120925
121185
  try {
120926
121186
  out.push(...await recoverProjectTransactions(id2));
120927
121187
  } catch (error62) {
@@ -121304,6 +121564,7 @@ var init_contract_transaction = __esm({
121304
121564
  init_contract_store();
121305
121565
  init_project_versions_store();
121306
121566
  init_lifecycle_lock();
121567
+ init_read_scope();
121307
121568
  init_project_contract_hash();
121308
121569
  init_contract_policy();
121309
121570
  init_steel_plan_view_id_normalise();
@@ -124948,6 +125209,15 @@ except Exception:
124948
125209
  });
124949
125210
 
124950
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
+ }
124951
125221
  function importedPlacementClaims(contract) {
124952
125222
  if (!contract || typeof contract !== "object" || contract.type !== "steel.model/v2") return { contract, corrected: 0 };
124953
125223
  const model = contract;
@@ -125622,7 +125892,7 @@ async function duplicateProject(id2, name, onCreated, operationId = (0, import_n
125622
125892
  const srcRoot = projectDir(src.id);
125623
125893
  (0, import_node_fs53.cpSync)(srcRoot, copyRoot, {
125624
125894
  recursive: true,
125625
- filter: (p) => !p.endsWith("project.json") && !isReservedProjectInternalPath(p) && !isProjectRootSidecar(srcRoot, p, RFI_FILENAME) && !isProjectRootSidecar(srcRoot, p, RFI_POISON_FILENAME)
125895
+ filter: (p) => !p.endsWith("project.json") && !isReservedProjectInternalPath(p) && !isProjectRootSidecar(srcRoot, p, RFI_FILENAME) && !isProjectRootSidecar(srcRoot, p, RFI_POISON_FILENAME) && !isProjectRootSidecar(srcRoot, p, CHAT_DIRECTORY_NAME)
125626
125896
  });
125627
125897
  try {
125628
125898
  dropSignOffsFor(copy.id);
@@ -125712,7 +125982,18 @@ function archiveProject(id2) {
125712
125982
  if ((0, import_node_fs53.existsSync)(dest)) throw new ProjectError(`already archived: ${id2}`);
125713
125983
  markCurrentWorkspaceProjectMove(id2, "archive", "prepared");
125714
125984
  if (meta3) writeMeta({ ...meta3, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
125715
- (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
+ }
125716
125997
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dir));
125717
125998
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dest));
125718
125999
  markCurrentWorkspaceProjectMove(id2, "archive", "moved");
@@ -125737,18 +126018,28 @@ function unarchiveProject(id2) {
125737
126018
  const dest = (0, import_node_path47.join)(projectsRoot(), locator);
125738
126019
  if ((0, import_node_fs53.existsSync)(dest)) throw new ProjectError(`a live project with that id already exists: ${id2}`);
125739
126020
  markCurrentWorkspaceProjectMove(id2, "restore", "prepared");
125740
- (0, import_node_fs53.renameSync)(src, dest);
126021
+ withFolderInUseRefusal("restore", meta3.name, () => (0, import_node_fs53.renameSync)(src, dest));
125741
126022
  syncDirectoryBestEffort((0, import_node_path47.dirname)(src));
125742
126023
  syncDirectoryBestEffort((0, import_node_path47.dirname)(dest));
125743
126024
  markCurrentWorkspaceProjectMove(id2, "restore", "moved");
125744
126025
  return meta3;
125745
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
+ }
125746
126035
  function deleteArchivedProject(id2) {
125747
126036
  const dir = archiveDir(id2);
125748
126037
  if (!(0, import_node_fs53.existsSync)(dir)) throw new ProjectError(`not archived: ${id2}`);
125749
126038
  assertNoApprovalRecovery(dir);
125750
- const stagingId = readMetaFile((0, import_node_path47.join)(dir, "project.json"), (0, import_node_path47.basename)(dir))?.stagingId;
125751
- (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 }));
125752
126043
  if (stagingId) dropStagingFor(stagingId);
125753
126044
  }
125754
126045
  function sniffThumbnailExt(data) {
@@ -127122,7 +127413,7 @@ async function importProjectZip(data, rfiOperationId = (0, import_node_crypto44.
127122
127413
  return { project: meta3, rfiTransfer, ...revitPortable ? { revitPortable: true } : {}, ...revitSource ? { revitSource } : {} };
127123
127414
  }, seams.destination);
127124
127415
  }
127125
- var import_node_fs53, import_node_child_process14, import_promises20, import_node_path47, import_node_os28, import_node_crypto44, import_node_stream2, ProjectError, 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;
127126
127417
  var init_projects_store = __esm({
127127
127418
  "projects-store.ts"() {
127128
127419
  "use strict";
@@ -127164,6 +127455,19 @@ var init_projects_store = __esm({
127164
127455
  }
127165
127456
  code;
127166
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"]);
127470
+ CHAT_DIRECTORY_NAME = "chats";
127167
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;
127168
127472
  NO_INCARNATION_REFUSAL = "This project can\u2019t be approved \u2014 duplicate it from the Workspaces list to sign off";
127169
127473
  writeMeta = (meta3, directory) => {
@@ -132394,7 +132698,13 @@ function preparationInterruptionDiagnosticText(req) {
132394
132698
  const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
132395
132699
  return `Diagnostic ${detail.diagnosticId}; ${detail.phase} phase; ${detail.elapsedMs} ms of ${detail.timeoutMs} ms; ${detail.workload.sourceCount} source(s).`;
132396
132700
  }
132397
- function runEligibilityFor(req) {
132701
+ function chatCanStartRequest(view) {
132702
+ if (view.canRun === true) return true;
132703
+ if (view.type !== "revision-read") return false;
132704
+ if (view.run !== void 0 || runEligibilityFor(view).runnable) return false;
132705
+ return runEligibilityFor(view, { interactive: true }).runnable;
132706
+ }
132707
+ function runEligibilityFor(req, opts = {}) {
132398
132708
  const policy = policyFor(req.type);
132399
132709
  if (!policy.runnable) return policy;
132400
132710
  if (req.type === "guide" && !normalizeInstructorContext(req.instructorContext)) {
@@ -132443,22 +132753,24 @@ function runEligibilityFor(req) {
132443
132753
  why: steelPreparationTimeoutWhy(req)
132444
132754
  };
132445
132755
  }
132446
- if (!req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0) {
132756
+ const firstRead = !req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0;
132757
+ if (firstRead && !(opts.interactive && req.project && req.appId)) {
132447
132758
  return { runnable: false, why: "this is the first drawing read for the project \u2014 your terminal AI must create the starting project checkpoint and wait for you to review and save the Drawing Filter" };
132448
132759
  }
132449
132760
  if (req.appTemplateId !== "steel-model") {
132450
132761
  return { runnable: false, why: "headless revision pre-read is available only for an existing steel model" };
132451
132762
  }
132452
- if (req.nativeSteelReady !== true) {
132763
+ if (!firstRead && req.nativeSteelReady !== true) {
132453
132764
  return { runnable: false, why: "headless revision pre-read requires a current native steel model" };
132454
132765
  }
132455
132766
  if (!Array.isArray(req.sourceRefs) || req.sourceRefs.length === 0 || req.sourceRefs.some((ref) => !ref || typeof ref !== "object" || typeof ref.ext !== "string" || ref.ext.toLowerCase() !== "pdf")) {
132456
- return { runnable: false, why: "headless revision pre-read currently requires the queued drawing set to be PDF" };
132767
+ return { runnable: false, why: "the drawing set must be PDF files" };
132457
132768
  }
132458
132769
  if (req.extractorAvailable === false) {
132459
- return { runnable: false, why: "headless revision pre-read needs a local Python runtime with PyMuPDF installed" };
132770
+ return { runnable: false, why: "this computer needs a local Python runtime with PyMuPDF installed to read the drawings" };
132460
132771
  }
132461
- if (Number.isInteger(req.headVersion) && req.baseVersion !== req.headVersion) {
132772
+ const queuedAgainst = firstRead ? req.baseVersion ?? 0 : req.baseVersion;
132773
+ if (firstRead && !Number.isInteger(req.headVersion) || Number.isInteger(req.headVersion) && queuedAgainst !== req.headVersion) {
132462
132774
  return { runnable: false, why: "the project changed after this revision was queued \u2014 attach the drawings again against the current version" };
132463
132775
  }
132464
132776
  return { runnable: true, policy };
@@ -133552,7 +133864,7 @@ For an unbuilt-connection relationship question, a verified connection marker is
133552
133864
  const scratch = `
133553
133865
  Every helper script or throwaway file this read needs belongs in temporary scratch space. ${scratchDestination} Do NOT write a .ps1, .mjs or any other helper into the project folder or beside the drawings: that folder is the user's own document, not a workspace. Nothing you want to survive the request belongs in temporary scratch space.${readIsolationClause(req.id, req.project ?? "", (req.appTemplateId || req.appId) !== "vectorize")}`;
133554
133866
  const vectorPost = `GET the current contract again and keep its ETag, then POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that current ETag>. The server derives the base version and source provenance from this queued request. The first completed vector drawing publishes History version 1; later reads stage a review and publish only after confirmation. Do NOT DELETE the request yourself. If you can't read the drawing, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133555
- const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so a plan whose elevation the set does not state outright is a QUESTION: ASK THE USER for it before you read members from that sheet - one question per view, not one per member - and never author elevation_mm from your own guess. But do not ask cold for what the set carries: look at the sheets first - the datums[] you recorded in the design-set knowledge, a level on a building section or frame elevation that this plan's title names, a T.O. STEEL note that governs the whole plan's framing (a general note, "U.N.O."; never one member's callout, which governs only its own end), and the page picture - and where you can read a level, POST /api/projects/${req.project}/revision-requests/${req.id}/plan-elevation-proposal with { plan: { viewId, sourceHash, pageId }, readings: [{ value, asRead, page: { sourceHash, pageId, sheet }, quote, elementIds } or, for a callout drawn rather than written, { value, asRead, page, near }] }, where viewId is that plan's id in the project's plans[] (on a first read, the checkpoint shell's; for a plan a revised set adds, the id you will give it; a sheet that carries several plan views is refused, so ask about each of those with no proposal, naming the view) and value is your conversion of asRead to world millimetres. RELAY its proposal.ask verbatim - it quotes what you read and names the sheet, says when a reading was read off a picture and not checked, and asks whether this plan is at that level - and author elevation_mm only after the user confirms or corrects it. Readings that disagree come back as a choice from lowest to highest with none preferred: never pick one yourself. Propose only what you READ: never another plan's elevation, a cut plane, or arithmetic. Ask with no proposal only when the whole set is silent, and then name the sheets you checked. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole" or "unreviewed", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the best corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. It is CORROBORATION AND NOT A VERDICT \u2014 it does not decide which reading the proposer chose, so do not present it as the reason the number is right. Name every outcome.runnersUp row too. A competing reading is now RARER than it was: the proposer reads each chain out of a single printed dimension row and refuses one that skips a dimension sitting alongside it, which removes most sub-multiple readings before they are ever reported. So an EMPTY runnersUp is the normal case and is not itself reassurance, while a row that does survive is a reading the drawing genuinely supports twice over \u2014 say so, and never as a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. A page-side mismatch or a stored-manifest fault may need one regeneration even after this request has published its Filter checkpoint and the saved Filter still matches its copy in the manifest: POST this request's /steel-manifest ONCE with no bindings so FloLess rebuilds the server-held drawing scan. If that POST returns 409 revision-filter-prepared, the server did not authorise recovery; STOP and tell the user what the questions say \u2014 do not retry. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: the response also carries questionBriefing, a response-only sibling the server derives for exactly this: it groups the questions, ranks the groups, and gives each one a plain category, what not answering it costs, how many are affected, how many are already filed, and a few exact locations. RELAY IT - do not re-derive the grouping and do not re-order it, because the ranking is the server's. Its affected count is QUESTIONS, not members - two unknown endpoints on one member are two, and a layer question is about no member at all. Its alreadyFiled can be null, which means the RFI file could not be read and NOT that nothing is filed. Read each group's ways out off its routes rather than reciting all three. file-rfi is withheld in exactly two cases and you do not have to work out which: a group whose questions EVERY ONE have an open, sent or answered record, because offering another for one of those is forbidden; and every group when the RFI file could not be read at all, because nothing may be filed until current RFI state can be checked. A CLOSED record withholds nothing - its question returning is filed as a linked successor - so a group can be filed end to end and still carry file-rfi. Your FIRST turn about questions says, in this order and before the user asks for any of it: the totals by priority; then groups[0] in full - it is already the most urgent because the server ordered them - what it is, what it costs, how many questions, and its named locations ("S-203, page 7", or the member to select); then ONE answerable question about that group and nothing else. Whatever groups[0] is, that is what you lead with; an EMPTY groups list means the read raised no questions, so say so rather than manufacturing one. Then work group by group: take the answer, re-audit, say what moved, go to the next. A BARE COUNT IS NEVER THE ANSWER - an earlier version of this instruction let a read reply "140 review questions" and stop, and the user had to ask repeatedly before one sheet was named. Never open with "Should I publish all N as RFIs?" either; that is the same non-answer wearing a question mark, and it asks somebody to dispose of work nobody has described to them. exactEvidenceUnavailable is marked on a LOCATION and never on a group, and it means there is no exact area to highlight rather than no idea where to look. When that location still carries a sheet - which every whole-sheet question does, including every unreviewed-page one - name the sheet as somewhere to look and say the read cannot point at a spot on it; never name a whole sheet as if it were the exact spot. Only where a location has no sheet, no member, no joint and no Filter row say the set does not show where it is. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133867
+ const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Before you submit any unknown, read that sheet's drawn heights: fetch ALL NINE enlarged tiles of the sheet (GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest/pages/<pageId>/picture?part=1 through part=9), transcribe every top-of-steel callout drawn on it, and for each one that lies at this end's grid intersection or along this member's line but that you cannot tie to this end, add it to that unknown's candidates [{ value, asRead, near, page: { sourceHash, pageId, sheet } }] (at most five, nearest first; never as known) - one blanket unknown over a sheet that shows callouts is the failure, not the answer. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so a plan whose elevation the set does not state outright is a QUESTION: ASK THE USER for it before you read members from that sheet - one question per view, not one per member - and never author elevation_mm from your own guess. But do not ask cold for what the set carries: look at the sheets first - the datums[] you recorded in the design-set knowledge, a level on a building section or frame elevation that this plan's title names, a T.O. STEEL note that governs the whole plan's framing (a general note, "U.N.O."; never one member's callout, which governs only its own end), and the page picture - and where you can read a level, POST /api/projects/${req.project}/revision-requests/${req.id}/plan-elevation-proposal with { plan: { viewId, sourceHash, pageId }, readings: [{ value, asRead, page: { sourceHash, pageId, sheet }, quote, elementIds } or, for a callout drawn rather than written, { value, asRead, page, near }] }, where viewId is that plan's id in the project's plans[] (on a first read, the checkpoint shell's; for a plan a revised set adds, the id you will give it; a sheet that carries several plan views is refused, so ask about each of those with no proposal, naming the view) and value is your conversion of asRead to world millimetres. RELAY its proposal.ask verbatim - it quotes what you read and names the sheet, says when a reading was read off a picture and not checked, and asks whether this plan is at that level - and author elevation_mm only after the user confirms or corrects it. Readings that disagree come back as a choice from lowest to highest with none preferred: never pick one yourself. Propose only what you READ: never another plan's elevation, a cut plane, or arithmetic. Ask with no proposal only when the whole set is silent, and then name the sheets you checked. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole" or "unreviewed", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the best corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. It is CORROBORATION AND NOT A VERDICT \u2014 it does not decide which reading the proposer chose, so do not present it as the reason the number is right. Name every outcome.runnersUp row too. A competing reading is now RARER than it was: the proposer reads each chain out of a single printed dimension row and refuses one that skips a dimension sitting alongside it, which removes most sub-multiple readings before they are ever reported. So an EMPTY runnersUp is the normal case and is not itself reassurance, while a row that does survive is a reading the drawing genuinely supports twice over \u2014 say so, and never as a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. A page-side mismatch or a stored-manifest fault may need one regeneration even after this request has published its Filter checkpoint and the saved Filter still matches its copy in the manifest: POST this request's /steel-manifest ONCE with no bindings so FloLess rebuilds the server-held drawing scan. If that POST returns 409 revision-filter-prepared, the server did not authorise recovery; STOP and tell the user what the questions say \u2014 do not retry. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: the response also carries questionBriefing, a response-only sibling the server derives for exactly this: it groups the questions, ranks the groups, and gives each one a plain category, what not answering it costs, how many are affected, how many are already filed, and a few exact locations. RELAY IT - do not re-derive the grouping and do not re-order it, because the ranking is the server's. Its affected count is QUESTIONS, not members - two unknown endpoints on one member are two, and a layer question is about no member at all. Its alreadyFiled can be null, which means the RFI file could not be read and NOT that nothing is filed. Read each group's ways out off its routes rather than reciting all three. file-rfi is withheld in exactly two cases and you do not have to work out which: a group whose questions EVERY ONE have an open, sent or answered record, because offering another for one of those is forbidden; and every group when the RFI file could not be read at all, because nothing may be filed until current RFI state can be checked. A CLOSED record withholds nothing - its question returning is filed as a linked successor - so a group can be filed end to end and still carry file-rfi. Your FIRST turn about questions says, in this order and before the user asks for any of it: the totals by priority; then groups[0] in full - it is already the most urgent because the server ordered them - what it is, what it costs, how many questions, and its named locations ("S-203, page 7", or the member to select); then ONE answerable question about that group and nothing else. Whatever groups[0] is, that is what you lead with; an EMPTY groups list means the read raised no questions, so say so rather than manufacturing one. Then work group by group: take the answer, re-audit, say what moved, go to the next. A BARE COUNT IS NEVER THE ANSWER - an earlier version of this instruction let a read reply "140 review questions" and stop, and the user had to ask repeatedly before one sheet was named. Never open with "Should I publish all N as RFIs?" either; that is the same non-answer wearing a question mark, and it asks somebody to dispose of work nobody has described to them. exactEvidenceUnavailable is marked on a LOCATION and never on a group, and it means there is no exact area to highlight rather than no idea where to look. When that location still carries a sheet - which every whole-sheet question does, including every unreviewed-page one - name the sheet as somewhere to look and say the read cannot point at a spot on it; never name a whole sheet as if it were the exact spot. Only where a location has no sheet, no member, no joint and no Filter row say the set does not show where it is. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133556
133868
  const scaleQuestionBriefing = `When the response carries scaleQuestionBriefing, require version: 2 and use that response-only object as the server's authoritative presentation of every ask-and-confirm scale question: RELAY questions in its exact order and copy each question, confirmLabel, technicalDetails, all counts, and every evidence label and summary exactly; do not re-derive, merge, omit, or reorder them from scaleProposals. In that case, do not relay any competing ask-and-confirm narrative from the lower-level scaleProposals fields described later in this instruction. Open evidence only through the exact server-issued locations[].openPath, using that location's actionLabel exactly as the Markdown link text. Never expose a raw source path, make a file:// link, or construct an evidence route yourself. A page location is an honest whole-sheet fallback, not an exact highlight. A Winning X dimension chain or Winning Y dimension chain is the fitter's complete, ordered chain membership; the manifest separately rechecks each listed element's page ownership, text kind, and normalized magnitude. Relay that producer-owned claim exactly, but never call it independent proof or confirmation. General dimension references are the broader proposal inputs and are not identified as members of a complete winning chain. A truncated producer chain gets no winning-chain row. Winning-chain locations are budgeted before general dimensions across the whole response; response truncation and producer truncation are different facts. None of these locations makes the scale confirmed. `;
133557
133869
  const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}; only it inventories pages and mints Filter ids. On sheet-identification-required, inspect listed pages, identify each, then retry with { bindings: [{ pageId, sheet, title?, evidenceKind }] }. evidenceKind is exactly one of "plan", "elevation", "section", "detail", "schedule", "notes", "foundation", or "other"; never guess another value from a drawing title. Never guess from other pages or build Filter geometry. On steel-manifest-preparation-busy, steel-manifest-inspection-interrupted, or steel-manifest-extraction-interrupted, wait at least retryAfterMs and retry this step for the SAME request; the request, completed page identification, and drawing set remain attached. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator clears it. For an interruption, relay error and recovery, then phase, elapsed/limit, counts and diagnostic id; null page counts are unknown. Never relay commands, stderr, source, filenames, or paths. On steel-manifest-over-budget, STOP and relay recovery. Page scope: remove or split that dense sheet. Total scope: smaller revisions. Bytes scope is drawing-data weight, not element count: move or split the heaviest sheets first; one sheet over the limit cannot be isolated to help. Null scope means extraction overflowed before measurement: no breakdown; the set must be far smaller. Only complete true covers the whole set; with false or null the figures are lower bounds and the recovery may not suffice. On steel-manifest-extraction-failed, STOP and relay the diagnostic; an identical retry fails. Never rename Filter geometry or mint element ids.`;
133558
133870
  const notReadLayers = `A Filter layer row with notRead: true was withheld by FloLess's extraction, not switched off by the user: every line it draws (typically grid lines and bubbles, dimension lines, section and callout marks) is left out of the elements, and the Drawing Filter shows it dimmed with a disabled tick box. Nobody can tick it, and saving the Filter again changes nothing, so NEVER ask the user to include, tick or re-save for a notRead layer, and never treat one being off as a gap in the saved selection. Live text is not withheld: grid labels, dimension strings and callout text that the PDF holds as text arrive as kind "text" elements (usually under layer "TEXT", never under the notRead layer itself) with positions in the page's point frame, so look there first. Lettering DRAWN as linework on a notRead layer was withheld with the rest of it, so a label you cannot find among the text elements is not proof the sheet lacks it: once the Filter is saved, read it and the withheld linework off the page picture (GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest/pages/<pageId>/picture, part=0 for the whole sheet, 1-9 for enlarged tiles; if it answers 404, follow what its error says). The picture is context for grids, dimensions and annotation only: members still come from elements the saved selection keeps. A scaleProposals refusal saying no grid family was found is usually that same withholding, and in every case it is computed from the extracted elements, not from what the Filter selects, so no Filter change can alter it: follow its outcome.action as described below, never answer it with a Filter change. Where a notRead layer genuinely limits what you can read, say so as a statement in your report, naming the layer and what it stopped you reading, and carry on with the rest; ask only a question whose answer the user can actually give.`;
@@ -133772,6 +134084,7 @@ function withPrompt(r, base2 = selfOrigin()) {
133772
134084
  const prompt = instructionFor(r);
133773
134085
  const marker = markerFor(r, base2, prompt);
133774
134086
  const eligibility = runEligibilityFor(r);
134087
+ const interactive = eligibility.runnable ? eligibility : runEligibilityFor(r, { interactive: true });
133775
134088
  const preparationEntry = r.type === "revision-read" ? steelPreparationEntryFor(r) : null;
133776
134089
  const retryablePreparationRefusal = r.type === "revision-read" && hasRetryablePreparationRefusal(r);
133777
134090
  const preparationRetryable = r.type === "revision-read" && preparationEntry?.allowed === true && (retryablePreparationRefusal || r.status === "pending" && hasPreparationInterruptionDiagnostic(r));
@@ -133782,17 +134095,22 @@ function withPrompt(r, base2 = selfOrigin()) {
133782
134095
  const clearPolicy = requestClearPolicyFor(r);
133783
134096
  const activeRun2 = projectedRun?.state === "queued" || projectedRun?.state === "running";
133784
134097
  const canCopy = marker !== "" && !activeRun2 && !isFilterAiChangeRequest(r) && !isFilterAiQuestionRequest(r) && (r.type !== "revision-read" || r.status === "pending" && r.prepassReady !== true && preparationEntry?.allowed === true);
134098
+ const status = retryablePreparationRefusal && r.status === "failed" ? "pending" : r.status;
134099
+ const canRun = eligibility.runnable && !hasAttempt;
133785
134100
  return {
133786
134101
  ...r,
133787
- status: retryablePreparationRefusal && r.status === "failed" ? "pending" : r.status,
134102
+ status,
133788
134103
  run: projectedRun,
133789
134104
  prompt,
133790
134105
  marker: terminalPreparationRefusal ? "" : marker,
133791
134106
  preparationState: preparationEntry?.state ?? null,
133792
134107
  preparationRetryable,
133793
134108
  preparationDiagnostic: hasPreparationInterruptionDiagnostic(r) ? preparationInterruptionDiagnosticText(r) : null,
133794
- canRun: eligibility.runnable && !hasAttempt,
133795
- runWhy: eligibility.runnable ? null : eligibility.why,
134109
+ canRun,
134110
+ runWhy: eligibility.runnable ? null : interactive.runnable ? eligibility.why : interactive.why,
134111
+ // The chat start route's own verdict (chat-routes `acceptRequestChat` + index.ts `canStart`), so
134112
+ // the upload modal never offers a Start in AI Chat that route answers with a 409.
134113
+ chatCanStart: r.type === "guide" || Boolean(r.intakeSubmissionId) || chatCanStartRequest({ ...r, status, run: projectedRun, canRun }),
133796
134114
  canCopy,
133797
134115
  ...clearPolicy,
133798
134116
  resumeCommand: terminalPreparationRefusal ? null : resumeCommandForRequest(r),
@@ -133822,6 +134140,7 @@ function withPrompt(r, base2 = selfOrigin()) {
133822
134140
  canCopy: false,
133823
134141
  canRun: false,
133824
134142
  runWhy: null,
134143
+ chatCanStart: false,
133825
134144
  ...clearPolicy,
133826
134145
  resumeCommand: resumeCommandForRequest(r),
133827
134146
  desktopHandoffs: null
@@ -138124,6 +138443,15 @@ function affectsProjectListing(path, event) {
138124
138443
  if (parts.length === 3 && parts[0] === ".archive" && parts[2] === "project.json") return true;
138125
138444
  return (event === "addDir" || event === "unlinkDir") && (parts.length === 1 || parts.length === 2 && parts[0] === ".archive");
138126
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
+ }
138127
138455
  function waitUntilReady(watcher) {
138128
138456
  return new Promise((resolveReady, rejectReady) => {
138129
138457
  const timer = setTimeout(() => finish2(new Error("workspace root watcher did not become ready in time")), READY_TIMEOUT_MS);
@@ -138152,6 +138480,7 @@ function startWorkspaceRootWatcher(initialRoot, emit = broadcast) {
138152
138480
  // Workspace roots can contain Windows shell folders such as Documents\My Music.
138153
138481
  // Do not follow those links: they are outside the selected root and may be unreadable.
138154
138482
  followSymlinks: false,
138483
+ ignored: (path) => workspaceWatchIgnored(root9.path, path),
138155
138484
  awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 }
138156
138485
  });
138157
138486
  watcher.on("all", (event, path) => {
@@ -138731,7 +139060,7 @@ function normalizeTeklaReadOperations(value) {
138731
139060
  if (!Array.isArray(value) || !value.length || value.length > TEKLA_CHAT_READ_OPERATIONS.length || new Set(value).size !== value.length || value.some((item) => !TEKLA_CHAT_READ_OPERATIONS.includes(item))) return null;
138732
139061
  return TEKLA_CHAT_READ_OPERATIONS.filter((operation) => value.includes(operation));
138733
139062
  }
138734
- var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_ALLOWANCE_HISTORY_LIMIT;
139063
+ var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_LINKED_PART_CHECK_LIMIT, TEKLA_ALLOWANCE_SCOPE, TEKLA_ALLOWANCE_HISTORY_LIMIT, TEKLA_LINKED_PARTS_CHECKS;
138735
139064
  var init_chat_types = __esm({
138736
139065
  "chat-types.ts"() {
138737
139066
  "use strict";
@@ -138749,7 +139078,127 @@ var init_chat_types = __esm({
138749
139078
  [TEKLA_SELECTION_TOOL_NAME]: TEKLA_SELECTION_READ_OPERATION
138750
139079
  });
138751
139080
  TEKLA_SELECTION_ROW_LIMIT = 200;
139081
+ TEKLA_LINKED_PART_CHECK_LIMIT = 1e3;
139082
+ TEKLA_ALLOWANCE_SCOPE = 2;
138752
139083
  TEKLA_ALLOWANCE_HISTORY_LIMIT = 20;
139084
+ TEKLA_LINKED_PARTS_CHECKS = ["unavailable", "partial"];
139085
+ }
139086
+ });
139087
+
139088
+ // chat-subjects.ts
139089
+ function subjectKinds(source) {
139090
+ return KINDS2[source];
139091
+ }
139092
+ function codePoints(text9, max2, ellipsis = false) {
139093
+ const points = [...text9];
139094
+ if (points.length <= max2) return text9;
139095
+ return ellipsis ? `${points.slice(0, max2 - 1).join("").trimEnd()}\u2026` : points.slice(0, max2).join("").trimEnd();
139096
+ }
139097
+ function tidy(text9) {
139098
+ return text9.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
139099
+ }
139100
+ function subjectItem(value, source, kinds) {
139101
+ const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
139102
+ if (!row2) throw new ChatSubjectsError("a selected object is not an object");
139103
+ if (typeof row2.kind !== "string" || !kinds.has(row2.kind)) throw new ChatSubjectsError("a selected object has an unknown kind");
139104
+ const id2 = row2.id;
139105
+ if (typeof id2 !== "string" || !id2.trim() || id2.length > MAX_SUBJECT_ID || CONTROL.test(id2) || id2 === "__proto__") {
139106
+ throw new ChatSubjectsError("a selected object has an invalid id");
139107
+ }
139108
+ if (isSnapshotSource(source) && ENTITY_ID2.exec(id2)?.[1] !== row2.kind) throw new ChatSubjectsError("a selected object has an invalid id");
139109
+ if (isLiveSource(source) && !TEKLA_GUID.test(id2)) throw new ChatSubjectsError("a selected object has an invalid id");
139110
+ const label2 = typeof row2.label === "string" ? codePoints(tidy(row2.label), MAX_SUBJECT_LABEL) : "";
139111
+ return { kind: row2.kind, id: id2, label: label2 || codePoints(id2, MAX_SUBJECT_LABEL) };
139112
+ }
139113
+ function subjectList(value, source, kinds, max2) {
139114
+ if (!Array.isArray(value) || value.length > max2 * 4) throw new ChatSubjectsError("the selected objects are not a list");
139115
+ const seen = /* @__PURE__ */ new Set();
139116
+ const items = [];
139117
+ for (const raw of value) {
139118
+ const item = subjectItem(raw, source, kinds);
139119
+ const key5 = `${item.kind}\0${item.id}`;
139120
+ if (seen.has(key5)) continue;
139121
+ seen.add(key5);
139122
+ items.push(item);
139123
+ }
139124
+ if (items.length > max2) throw new ChatSubjectsError(`more than ${max2} selected objects`);
139125
+ return items;
139126
+ }
139127
+ function normalizeChatSubjects(value) {
139128
+ if (value === void 0 || value === null) return null;
139129
+ const row2 = typeof value === "object" && !Array.isArray(value) ? value : null;
139130
+ if (!row2) throw new ChatSubjectsError("the selection is not an object");
139131
+ const kinds = typeof row2.source === "string" && Object.hasOwn(KINDS2, row2.source) ? KINDS2[row2.source] : null;
139132
+ if (!kinds) throw new ChatSubjectsError("the selection comes from an unsupported model");
139133
+ const source = row2.source;
139134
+ const revision = row2.revision === void 0 || row2.revision === null ? null : row2.revision;
139135
+ const revisionOk = isLiveSource(source) ? false : isSnapshotSource(source) ? typeof revision === "string" && HEX645.test(revision) : typeof revision === "number" && Number.isSafeInteger(revision) && revision >= 0;
139136
+ if (revision !== null && !revisionOk) throw new ChatSubjectsError("the selection has an invalid model revision");
139137
+ if (!isSnapshotSource(source) && row2.sourceDigest !== void 0) throw new ChatSubjectsError("only a snapshot model names its source file");
139138
+ const digest7 = row2.sourceDigest === void 0 || row2.sourceDigest === null ? null : row2.sourceDigest;
139139
+ if (digest7 !== null && (typeof digest7 !== "string" || !HEX645.test(digest7))) throw new ChatSubjectsError("the selection has an invalid source file");
139140
+ const identity4 = isSnapshotSource(source) ? { sourceDigest: digest7 } : {};
139141
+ if (row2.items !== void 0 && row2.group !== void 0) throw new ChatSubjectsError("the selection is both a list and a group");
139142
+ if (row2.items !== void 0) {
139143
+ const items = subjectList(row2.items, source, kinds, MAX_LISTED_SUBJECTS);
139144
+ if (!items.length) throw new ChatSubjectsError("the selection is empty");
139145
+ return { source, revision, ...identity4, items };
139146
+ }
139147
+ const group = row2.group && typeof row2.group === "object" && !Array.isArray(row2.group) ? row2.group : null;
139148
+ if (!group) throw new ChatSubjectsError("the selection has no objects");
139149
+ const count4 = group.count;
139150
+ if (typeof count4 !== "number" || !Number.isSafeInteger(count4) || count4 <= MAX_LISTED_SUBJECTS || count4 > MAX_GROUP_COUNT) {
139151
+ throw new ChatSubjectsError("the selection group has an invalid size");
139152
+ }
139153
+ const sample = subjectList(group.sample, source, kinds, MAX_GROUP_SAMPLE);
139154
+ if (sample.length > count4) throw new ChatSubjectsError("the selection sample is larger than the group");
139155
+ return { source, revision, ...identity4, group: { count: count4, sample } };
139156
+ }
139157
+ function subjectNote(text9) {
139158
+ const line = String(text9 || "").split(/\r?\n/).map(tidy).find(Boolean);
139159
+ return line ? codePoints(line, MAX_SUBJECT_NOTE, true) : "A message with attachments";
139160
+ }
139161
+ function subjectLinkNote(text9) {
139162
+ if (typeof text9 !== "string") return "";
139163
+ const line = text9.split(/\r?\n|\r/).map(tidy).find(Boolean);
139164
+ return line ? codePoints(line, MAX_LINK_NOTE, true) : "";
139165
+ }
139166
+ var MAX_LISTED_SUBJECTS, MAX_GROUP_SAMPLE, MAX_GROUP_COUNT, MAX_SUBJECT_ID, MAX_SUBJECT_LABEL, MAX_SUBJECT_NOTE, KINDS2, CHAT_SUBJECT_SOURCES, isLiveSource, isSnapshotSource, SUBJECT_SOURCE_NOUNS, ChatSubjectsError, CONTROL, HEX645, ENTITY_ID2, TEKLA_GUID, MAX_LINK_NOTE;
139167
+ var init_chat_subjects = __esm({
139168
+ "chat-subjects.ts"() {
139169
+ "use strict";
139170
+ MAX_LISTED_SUBJECTS = 200;
139171
+ MAX_GROUP_SAMPLE = 50;
139172
+ MAX_GROUP_COUNT = 1e6;
139173
+ MAX_SUBJECT_ID = 200;
139174
+ MAX_SUBJECT_LABEL = 120;
139175
+ MAX_SUBJECT_NOTE = 120;
139176
+ KINDS2 = {
139177
+ steel: /* @__PURE__ */ new Set(["member", "joint", "detail"]),
139178
+ revit: /* @__PURE__ */ new Set(["element"]),
139179
+ "tekla-parser": /* @__PURE__ */ new Set(["element"]),
139180
+ tekla: /* @__PURE__ */ new Set(["part"])
139181
+ };
139182
+ CHAT_SUBJECT_SOURCES = Object.freeze(["steel", "revit", "tekla-parser", "tekla"]);
139183
+ isLiveSource = (source) => source === "tekla";
139184
+ isSnapshotSource = (source) => source === "revit" || source === "tekla-parser";
139185
+ SUBJECT_SOURCE_NOUNS = Object.freeze({
139186
+ steel: ["Steel Model object", "Steel Model objects"],
139187
+ revit: ["Revit element", "Revit elements"],
139188
+ "tekla-parser": ["Tekla object", "Tekla objects"],
139189
+ tekla: ["Tekla part", "Tekla parts"]
139190
+ });
139191
+ ChatSubjectsError = class extends Error {
139192
+ constructor(message2) {
139193
+ super(message2);
139194
+ this.name = "ChatSubjectsError";
139195
+ }
139196
+ };
139197
+ CONTROL = /[\u0000-\u001f\u007f]/;
139198
+ HEX645 = /^[0-9a-f]{64}$/;
139199
+ ENTITY_ID2 = /^([a-z][a-z0-9-]*):(\S+)$/;
139200
+ TEKLA_GUID = /^(?!0{8}-0{4}-0{4}-0{4}-0{12}$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
139201
+ MAX_LINK_NOTE = 160;
138753
139202
  }
138754
139203
  });
138755
139204
 
@@ -138772,7 +139221,7 @@ function boundedText2(value) {
138772
139221
  const chars = Array.from(value.replace(/[\u0000-\u001f\u007f]/gu, " ").trim());
138773
139222
  return chars.length <= FIELD_LIMIT ? chars.join("") : `${chars.slice(0, FIELD_LIMIT - 1).join("")}\u2026`;
138774
139223
  }
138775
- function parseSelection(result2) {
139224
+ function parseSelection(result2, linkedParts) {
138776
139225
  const invalid8 = refusal("invalid-result", "FloLess could not read the Tekla selection result. Check that Tekla and its bridge are available, then try again.");
138777
139226
  if (typeof result2.selectionTooLarge !== "boolean" || typeof result2.selectionChanged !== "boolean") return invalid8;
138778
139227
  if (result2.selectionTooLarge) {
@@ -138784,6 +139233,7 @@ function parseSelection(result2) {
138784
139233
  const { parts, partCount, totalWeightKg, complete, weightMissing, otherObjectCount } = result2;
138785
139234
  if (!Array.isArray(parts) || parts.length > TEKLA_SELECTION_ROW_LIMIT || !isCount3(partCount) || partCount < parts.length || !isWeight(totalWeightKg) || typeof complete !== "boolean" || !isCount3(weightMissing) || weightMissing > partCount || !isCount3(otherObjectCount)) return invalid8;
138786
139235
  const rows2 = [];
139236
+ const guids = /* @__PURE__ */ new Set();
138787
139237
  for (const row2 of parts) {
138788
139238
  if (!row2 || typeof row2 !== "object" || Array.isArray(row2)) return invalid8;
138789
139239
  const item = row2;
@@ -138793,7 +139243,9 @@ function parseSelection(result2) {
138793
139243
  const material = boundedText2(item.material);
138794
139244
  if (mark === null || name === null || profile === null || material === null) return invalid8;
138795
139245
  if (item.weightKg !== null && !isWeight(item.weightKg)) return invalid8;
138796
- rows2.push({ mark, name, profile, material, weightKg: item.weightKg === null ? null : item.weightKg });
139246
+ if (typeof item.guid !== "string" || !TEKLA_GUID.test(item.guid) || guids.has(item.guid)) return invalid8;
139247
+ guids.add(item.guid);
139248
+ rows2.push({ mark, name, profile, material, weightKg: item.weightKg === null ? null : item.weightKg, guid: item.guid });
138797
139249
  }
138798
139250
  const weightless = rows2.filter((row2) => row2.weightKg === null).length;
138799
139251
  if (weightless > weightMissing) return invalid8;
@@ -138801,7 +139253,23 @@ function parseSelection(result2) {
138801
139253
  const listed = rows2.reduce((sum2, row2) => sum2 + (row2.weightKg ?? 0), 0);
138802
139254
  if (weightless !== weightMissing || Math.abs(listed - totalWeightKg) > 0.01 + 1e-9 * totalWeightKg) return invalid8;
138803
139255
  }
138804
- return { parts: rows2, partCount, totalWeightKg, truncated: partCount > rows2.length, complete, weightMissing, otherObjectCount };
139256
+ const selection = {
139257
+ parts: rows2,
139258
+ partCount,
139259
+ totalWeightKg,
139260
+ truncated: partCount > rows2.length,
139261
+ complete,
139262
+ weightMissing,
139263
+ otherObjectCount
139264
+ };
139265
+ if (!linkedParts) return selection;
139266
+ const { missingLinkedParts: missing, linkedPartsChecked: checked2 } = result2;
139267
+ const asked = new Set(linkedParts);
139268
+ if (!Array.isArray(missing) || checked2 !== linkedParts.length || new Set(missing).size !== missing.length || missing.some((guid3) => typeof guid3 !== "string" || !asked.has(guid3) || guids.has(guid3))) return { ...selection, linkedPartsCheck: "unavailable" };
139269
+ return { ...selection, linkedPartsChecked: checked2, missingLinkedParts: missing };
139270
+ }
139271
+ function validLinkedParts(value) {
139272
+ return Array.isArray(value) && value.length <= TEKLA_LINKED_PART_CHECK_LIMIT && new Set(value).size === value.length && value.every((guid3) => typeof guid3 === "string" && TEKLA_GUID.test(guid3));
138805
139273
  }
138806
139274
  function validateTeklaLibraryBinding(input2, canonical3 = canonicalLocalTeklaFile) {
138807
139275
  const invalid8 = { ok: false, message: "FloLess could not use this Tekla model library for Chat. Verify the model read in Graft again, then continue in AI Chat." };
@@ -138823,12 +139291,20 @@ function validateTeklaLibraryBinding(input2, canonical3 = canonicalLocalTeklaFil
138823
139291
  }
138824
139292
  return { ok: true, sourcePath: source, hostVersion, operations };
138825
139293
  }
138826
- async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal, operation = TEKLA_MODEL_READ_OPERATION) {
139294
+ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal, operation = TEKLA_MODEL_READ_OPERATION, opts = {}) {
138827
139295
  const code = Object.hasOwn(OPERATION_CODE, operation) ? OPERATION_CODE[operation] : void 0;
138828
139296
  if (!code) {
138829
139297
  console.warn("[tekla-library-read] refused an unknown read", { operation });
138830
139298
  return refusal("invalid-result", "FloLess does not know this Tekla read, so it read nothing. Update FloLess, then try again.");
138831
139299
  }
139300
+ const linkedParts = opts.linkedParts;
139301
+ if (linkedParts !== void 0 && (operation !== TEKLA_SELECTION_READ_OPERATION || !validLinkedParts(linkedParts))) {
139302
+ console.warn("[tekla-library-read] refused an unsound list of linked parts", {
139303
+ operation,
139304
+ count: Array.isArray(linkedParts) ? linkedParts.length : null
139305
+ });
139306
+ return refusal("invalid-request", "FloLess could not prepare the check of parts linked to earlier questions, so it read nothing. Try again; if it keeps happening, report the issue.");
139307
+ }
138832
139308
  if (typeof sourcePath2 !== "string" || sourcePath2.length > 2048) {
138833
139309
  return refusal("invalid-source", "Choose the Tekla model library again, then inspect it.");
138834
139310
  }
@@ -138844,7 +139320,7 @@ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal,
138844
139320
  if (signal?.aborted) return stoppedRefusal();
138845
139321
  let receipt;
138846
139322
  try {
138847
- receipt = await deps.probe(code, selectedVersion, signal);
139323
+ receipt = await deps.probe(code, selectedVersion, signal, linkedParts ? { linkedParts: [...linkedParts] } : void 0);
138848
139324
  } catch (error62) {
138849
139325
  if (signal?.aborted) return stoppedRefusal();
138850
139326
  console.warn("[tekla-library-read] the bridge call failed", { error: error62 instanceof Error ? error62.message : String(error62) });
@@ -138901,7 +139377,7 @@ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal,
138901
139377
  verifiedAt: deps.now()
138902
139378
  };
138903
139379
  if (operation === TEKLA_SELECTION_READ_OPERATION) {
138904
- const selection = parseSelection(result2);
139380
+ const selection = parseSelection(result2, linkedParts);
138905
139381
  if ("ok" in selection) return selection;
138906
139382
  verification.selection = selection;
138907
139383
  }
@@ -138911,7 +139387,13 @@ async function runTeklaLibraryRead(sourcePath2, opts = {}) {
138911
139387
  if (inFlight) return refusal("busy", "A Tekla read is already in progress. Wait for it to finish, then try again.");
138912
139388
  inFlight = true;
138913
139389
  try {
138914
- return await verifyTeklaLibraryRead(sourcePath2, opts.deps ?? DEFAULT_DEPS2, opts.signal, opts.operation);
139390
+ return await verifyTeklaLibraryRead(
139391
+ sourcePath2,
139392
+ opts.deps ?? DEFAULT_DEPS2,
139393
+ opts.signal,
139394
+ opts.operation,
139395
+ opts.linkedParts ? { linkedParts: opts.linkedParts } : {}
139396
+ );
138915
139397
  } finally {
138916
139398
  inFlight = false;
138917
139399
  }
@@ -138931,6 +139413,7 @@ var init_tekla_library_read = __esm({
138931
139413
  import_node_path76 = require("node:path");
138932
139414
  init_aware_adapter();
138933
139415
  init_chat_types();
139416
+ init_chat_subjects();
138934
139417
  SOURCE_PATTERN = TEKLA_MODEL_LIBRARY_PATTERN;
138935
139418
  MODEL_NAME_CODE = `using Tekla.Structures.Model;
138936
139419
  var teklaModel = new Model();
@@ -138946,7 +139429,8 @@ var teklaModel = new Model();
138946
139429
  var connected = teklaModel.GetConnectionStatus();
138947
139430
  var modelName = string.Empty;
138948
139431
  var parts = new System.Collections.Generic.List<object>();
138949
- int partCount = 0, weightMissing = 0, otherObjectCount = 0, visited = 0;
139432
+ var missingLinkedParts = new System.Collections.Generic.List<string>();
139433
+ int partCount = 0, weightMissing = 0, otherObjectCount = 0, visited = 0, linkedPartsChecked = 0;
138950
139434
  double totalWeightKg = 0;
138951
139435
  bool complete = true, selectionChanged = false, selectionTooLarge = false;
138952
139436
  if (connected) {
@@ -139003,7 +139487,15 @@ if (connected) {
139003
139487
  double weight = 0;
139004
139488
  bool hasWeight = part.GetReportProperty("WEIGHT", ref weight) && !double.IsNaN(weight) && !double.IsInfinity(weight) && weight >= 0;
139005
139489
  if (hasWeight) totalWeightKg += weight; else weightMissing++;
139006
- if (parts.Count < ${TEKLA_SELECTION_ROW_LIMIT}) parts.Add(new { mark, name, profile, material, weightKg = hasWeight ? (double?)weight : null });
139490
+ if (parts.Count < ${TEKLA_SELECTION_ROW_LIMIT}) parts.Add(new { mark, name, profile, material, weightKg = hasWeight ? (double?)weight : null,
139491
+ guid = part.Identifier.GUID.ToString() });
139492
+ }
139493
+ var linkedList = args != null && args.ContainsKey("linkedParts") ? args["linkedParts"] as System.Collections.Generic.List<object> : null;
139494
+ if (linkedList != null) foreach (var entry in linkedList) {
139495
+ var text = entry as string; System.Guid linkedGuid;
139496
+ if (text == null || !System.Guid.TryParse(text, out linkedGuid)) continue;
139497
+ linkedPartsChecked++;
139498
+ if (!(teklaModel.SelectModelObject(new Tekla.Structures.Identifier(linkedGuid)) is Tekla.Structures.Model.Part)) missingLinkedParts.Add(text);
139007
139499
  }
139008
139500
  var secondIds = new System.Collections.Generic.List<int>();
139009
139501
  var again = new Tekla.Structures.Model.UI.ModelObjectSelector().GetSelectedObjects();
@@ -139019,14 +139511,14 @@ if (connected) {
139019
139511
  }
139020
139512
  }
139021
139513
  return new { connected, modelName, assemblyPath = typeof(Model).Assembly.Location, parts, partCount,
139022
- totalWeightKg, complete, weightMissing, otherObjectCount, selectionChanged, selectionTooLarge };`;
139514
+ totalWeightKg, complete, weightMissing, otherObjectCount, selectionChanged, selectionTooLarge, missingLinkedParts, linkedPartsChecked };`;
139023
139515
  OPERATION_CODE = Object.freeze({
139024
139516
  [TEKLA_MODEL_READ_OPERATION]: MODEL_NAME_CODE,
139025
139517
  [TEKLA_SELECTION_READ_OPERATION]: SELECTION_CODE
139026
139518
  });
139027
139519
  DEFAULT_DEPS2 = {
139028
139520
  canonical: canonicalLocalTeklaFile,
139029
- probe: (code, version2, signal) => aware.execTekla(code, { version: version2, signal }),
139521
+ probe: (code, version2, signal, args) => aware.execTekla(code, { version: version2, signal, ...args ? { args } : {} }),
139030
139522
  now: () => (/* @__PURE__ */ new Date()).toISOString()
139031
139523
  };
139032
139524
  isCount3 = (value) => Number.isSafeInteger(value) && value >= 0;
@@ -139900,115 +140392,79 @@ var init_workflow_publication = __esm({
139900
140392
  }
139901
140393
  });
139902
140394
 
139903
- // chat-subjects.ts
139904
- function subjectKinds(source) {
139905
- return KINDS2[source];
139906
- }
139907
- function codePoints(text9, max2, ellipsis = false) {
139908
- const points = [...text9];
139909
- if (points.length <= max2) return text9;
139910
- return ellipsis ? `${points.slice(0, max2 - 1).join("").trimEnd()}\u2026` : points.slice(0, max2).join("").trimEnd();
140395
+ // ../web/model-property-display.js
140396
+ function teklaPropertyGroups(rows2) {
140397
+ const properties = [], udas = [], nativeGroups = /* @__PURE__ */ new Map();
140398
+ for (const row2 of Array.isArray(rows2) ? rows2 : []) {
140399
+ const isUda = row2.isUda === true || row2.groupName === "User-defined attributes" || row2.groupName === "User-defined attributes (UDA)" || row2.groupName === "UDA";
140400
+ if (isUda) {
140401
+ udas.push(row2);
140402
+ continue;
140403
+ }
140404
+ if (row2.semantic && Number.isSafeInteger(row2.groupOrdinal)) {
140405
+ const key5 = `${row2.groupOrdinal}\0${row2.groupName}`;
140406
+ const group = nativeGroups.get(key5) || { key: key5, name: row2.groupName, ordinal: row2.groupOrdinal, rows: [], expanded: true };
140407
+ group.rows.push(row2);
140408
+ nativeGroups.set(key5, group);
140409
+ continue;
140410
+ }
140411
+ if (/^(?:Raw\b|provenance|Reader coverage|Technical details|System)/i.test(row2.groupName || "")) continue;
140412
+ if (row2.groupName === "Overview" && ["Object kind", "Subtype"].includes(row2.name)) continue;
140413
+ if (row2.groupName === "Source identity" && row2.name === "Native type") continue;
140414
+ const item = row2.name === "Object ID" ? { ...row2, name: "ID" } : row2;
140415
+ properties.push(item);
140416
+ }
140417
+ const ordered = (values2) => values2.slice().sort((a, b) => (a.propertyOrdinal ?? 0) - (b.propertyOrdinal ?? 0));
140418
+ return [
140419
+ ...[...nativeGroups.values()].sort((a, b) => a.ordinal - b.ordinal).map((group) => ({ ...group, rows: ordered(group.rows) })),
140420
+ ...properties.length ? [{ key: "tekla-properties", name: "Properties", rows: properties, expanded: true }] : [],
140421
+ ...udas.length ? [{ key: "tekla-udas", name: "User-defined attributes (UDA)", rows: ordered(udas), expanded: false }] : []
140422
+ ];
139911
140423
  }
139912
- function tidy(text9) {
139913
- return text9.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
140424
+ function teklaObjectFields(entity, rows2 = []) {
140425
+ const source = teklaPropertyGroups(rows2).filter((group) => group.key !== "tekla-udas").flatMap((group) => group.rows);
140426
+ const value = (name) => source.find((row2) => row2.name === name)?.value;
140427
+ return {
140428
+ name: value("Name") ?? null,
140429
+ profile: value("Profile") ?? null,
140430
+ id: value("ID") ?? entity.objectId ?? (/^element:([0-9]+)$/.exec(entity.id || "")?.[1] ?? null)
140431
+ };
139914
140432
  }
139915
- function subjectItem(value, source, kinds) {
139916
- const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
139917
- if (!row2) throw new ChatSubjectsError("a selected object is not an object");
139918
- if (typeof row2.kind !== "string" || !kinds.has(row2.kind)) throw new ChatSubjectsError("a selected object has an unknown kind");
139919
- const id2 = row2.id;
139920
- if (typeof id2 !== "string" || !id2.trim() || id2.length > MAX_SUBJECT_ID || CONTROL.test(id2) || id2 === "__proto__") {
139921
- throw new ChatSubjectsError("a selected object has an invalid id");
139922
- }
139923
- if (isSnapshotSource(source) && ENTITY_ID2.exec(id2)?.[1] !== row2.kind) throw new ChatSubjectsError("a selected object has an invalid id");
139924
- const label2 = typeof row2.label === "string" ? codePoints(tidy(row2.label), MAX_SUBJECT_LABEL) : "";
139925
- return { kind: row2.kind, id: id2, label: label2 || codePoints(id2, MAX_SUBJECT_LABEL) };
140433
+ function teklaObjectLabel(entity, rows2 = []) {
140434
+ const fields = teklaObjectFields(entity, rows2);
140435
+ return [
140436
+ fields.name != null ? `Name: ${fields.name}` : null,
140437
+ fields.profile != null ? `Profile: ${fields.profile}` : null,
140438
+ fields.id != null ? `ID: ${fields.id}` : null
140439
+ ].filter(Boolean).join(" \xB7 ") || entity.typeName || "Tekla object";
139926
140440
  }
139927
- function subjectList(value, source, kinds, max2) {
139928
- if (!Array.isArray(value) || value.length > max2 * 4) throw new ChatSubjectsError("the selected objects are not a list");
139929
- const seen = /* @__PURE__ */ new Set();
139930
- const items = [];
139931
- for (const raw of value) {
139932
- const item = subjectItem(raw, source, kinds);
139933
- const key5 = `${item.kind}\0${item.id}`;
139934
- if (seen.has(key5)) continue;
139935
- seen.add(key5);
139936
- items.push(item);
140441
+ var init_model_property_display = __esm({
140442
+ "../web/model-property-display.js"() {
140443
+ init_display_units();
139937
140444
  }
139938
- if (items.length > max2) throw new ChatSubjectsError(`more than ${max2} selected objects`);
139939
- return items;
140445
+ });
140446
+
140447
+ // ../web/model-chat-questions.js
140448
+ function subjectLabelText(text9) {
140449
+ return [...String(text9 || "").replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim()].slice(0, 120).join("").trimEnd();
139940
140450
  }
139941
- function normalizeChatSubjects(value) {
139942
- if (value === void 0 || value === null) return null;
139943
- const row2 = typeof value === "object" && !Array.isArray(value) ? value : null;
139944
- if (!row2) throw new ChatSubjectsError("the selection is not an object");
139945
- const kinds = typeof row2.source === "string" && Object.hasOwn(KINDS2, row2.source) ? KINDS2[row2.source] : null;
139946
- if (!kinds) throw new ChatSubjectsError("the selection comes from an unsupported model");
139947
- const source = row2.source;
139948
- const revision = row2.revision === void 0 || row2.revision === null ? null : row2.revision;
139949
- const revisionOk = isSnapshotSource(source) ? typeof revision === "string" && HEX645.test(revision) : typeof revision === "number" && Number.isSafeInteger(revision) && revision >= 0;
139950
- if (revision !== null && !revisionOk) throw new ChatSubjectsError("the selection has an invalid model revision");
139951
- if (!isSnapshotSource(source) && row2.sourceDigest !== void 0) throw new ChatSubjectsError("only a snapshot model names its source file");
139952
- const digest7 = row2.sourceDigest === void 0 || row2.sourceDigest === null ? null : row2.sourceDigest;
139953
- if (digest7 !== null && (typeof digest7 !== "string" || !HEX645.test(digest7))) throw new ChatSubjectsError("the selection has an invalid source file");
139954
- const identity4 = isSnapshotSource(source) ? { sourceDigest: digest7 } : {};
139955
- if (row2.items !== void 0 && row2.group !== void 0) throw new ChatSubjectsError("the selection is both a list and a group");
139956
- if (row2.items !== void 0) {
139957
- const items = subjectList(row2.items, source, kinds, MAX_LISTED_SUBJECTS);
139958
- if (!items.length) throw new ChatSubjectsError("the selection is empty");
139959
- return { source, revision, ...identity4, items };
140451
+ function modelSubjectLabel(source, entity, rows2 = []) {
140452
+ if (source === "tekla") {
140453
+ const what2 = entity?.mark || entity?.name || "Tekla part";
140454
+ return entity?.profile ? `${what2} \xB7 ${entity.profile}` : what2;
139960
140455
  }
139961
- const group = row2.group && typeof row2.group === "object" && !Array.isArray(row2.group) ? row2.group : null;
139962
- if (!group) throw new ChatSubjectsError("the selection has no objects");
139963
- const count4 = group.count;
139964
- if (typeof count4 !== "number" || !Number.isSafeInteger(count4) || count4 <= MAX_LISTED_SUBJECTS || count4 > MAX_GROUP_COUNT) {
139965
- throw new ChatSubjectsError("the selection group has an invalid size");
140456
+ const id2 = String(entity?.id ?? "");
140457
+ if (source === "tekla-parser") {
140458
+ const fields = teklaObjectFields(entity || {}, rows2);
140459
+ const label2 = teklaObjectLabel(entity || {}, rows2);
140460
+ return fields.id == null ? `${label2} \xB7 ${id2}` : label2;
139966
140461
  }
139967
- const sample = subjectList(group.sample, source, kinds, MAX_GROUP_SAMPLE);
139968
- if (sample.length > count4) throw new ChatSubjectsError("the selection sample is larger than the group");
139969
- return { source, revision, ...identity4, group: { count: count4, sample } };
139970
- }
139971
- function subjectNote(text9) {
139972
- const line = String(text9 || "").split(/\r?\n/).map(tidy).find(Boolean);
139973
- return line ? codePoints(line, MAX_SUBJECT_NOTE, true) : "A message with attachments";
139974
- }
139975
- function subjectLinkNote(text9) {
139976
- if (typeof text9 !== "string") return "";
139977
- const line = text9.split(/\r?\n|\r/).map(tidy).find(Boolean);
139978
- return line ? codePoints(line, MAX_LINK_NOTE, true) : "";
140462
+ const what = entity?.name || entity?.typeName || entity?.categoryName || entity?.category || "Revit element";
140463
+ return `${what} \xB7 ${id2}`;
139979
140464
  }
139980
- var MAX_LISTED_SUBJECTS, MAX_GROUP_SAMPLE, MAX_GROUP_COUNT, MAX_SUBJECT_ID, MAX_SUBJECT_LABEL, MAX_SUBJECT_NOTE, KINDS2, CHAT_SUBJECT_SOURCES, isSnapshotSource, SUBJECT_SOURCE_NOUNS, ChatSubjectsError, CONTROL, HEX645, ENTITY_ID2, MAX_LINK_NOTE;
139981
- var init_chat_subjects = __esm({
139982
- "chat-subjects.ts"() {
139983
- "use strict";
139984
- MAX_LISTED_SUBJECTS = 200;
139985
- MAX_GROUP_SAMPLE = 50;
139986
- MAX_GROUP_COUNT = 1e6;
139987
- MAX_SUBJECT_ID = 200;
139988
- MAX_SUBJECT_LABEL = 120;
139989
- MAX_SUBJECT_NOTE = 120;
139990
- KINDS2 = {
139991
- steel: /* @__PURE__ */ new Set(["member", "joint", "detail"]),
139992
- revit: /* @__PURE__ */ new Set(["element"]),
139993
- "tekla-parser": /* @__PURE__ */ new Set(["element"])
139994
- };
139995
- CHAT_SUBJECT_SOURCES = Object.freeze(["steel", "revit", "tekla-parser"]);
139996
- isSnapshotSource = (source) => source !== "steel";
139997
- SUBJECT_SOURCE_NOUNS = Object.freeze({
139998
- steel: ["Steel Model object", "Steel Model objects"],
139999
- revit: ["Revit element", "Revit elements"],
140000
- "tekla-parser": ["Tekla object", "Tekla objects"]
140001
- });
140002
- ChatSubjectsError = class extends Error {
140003
- constructor(message2) {
140004
- super(message2);
140005
- this.name = "ChatSubjectsError";
140006
- }
140007
- };
140008
- CONTROL = /[\u0000-\u001f\u007f]/;
140009
- HEX645 = /^[0-9a-f]{64}$/;
140010
- ENTITY_ID2 = /^([a-z][a-z0-9-]*):(\S+)$/;
140011
- MAX_LINK_NOTE = 160;
140465
+ var init_model_chat_questions = __esm({
140466
+ "../web/model-chat-questions.js"() {
140467
+ init_model_property_display();
140012
140468
  }
140013
140469
  });
140014
140470
 
@@ -140018,7 +140474,7 @@ function emptySubjectIndex() {
140018
140474
  }
140019
140475
  function parseLink(value) {
140020
140476
  const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
140021
- if (!row2 || !str6(row2.messageEventId, 64) || !str6(row2.chatId, 64) || !str6(row2.source, 32) || !str6(row2.kind, 32) || !str6(row2.id, 200) || typeof row2.label !== "string" || typeof row2.note !== "string" || !Number.isSafeInteger(row2.sequence) || !str6(row2.createdAt, 64) || !(row2.revision === null || isRevision(row2.revision)) || !(row2.sourceDigest === void 0 || row2.sourceDigest === null || digestOf(row2.sourceDigest) !== null) || typeof row2.origin !== "string" || !ORIGINS.has(row2.origin) || !str6(row2.linkEventId, 64) || !Number.isSafeInteger(row2.linkSequence) || typeof row2.aiNote !== "string" || !str6(row2.askedAt, 64)) return null;
140477
+ if (!row2 || !str6(row2.messageEventId, 64) || !str6(row2.chatId, 64) || !str6(row2.source, 32) || !str6(row2.kind, 32) || !str6(row2.id, 200) || typeof row2.label !== "string" || typeof row2.note !== "string" || !Number.isSafeInteger(row2.sequence) || !str6(row2.createdAt, 64) || !(row2.revision === null || isRevision(row2.revision)) || !(row2.sourceDigest === void 0 || row2.sourceDigest === null || digestOf(row2.sourceDigest) !== null) || typeof row2.origin !== "string" || !ORIGINS.has(row2.origin) || !str6(row2.linkEventId, 64) || !Number.isSafeInteger(row2.linkSequence) || typeof row2.aiNote !== "string" || !str6(row2.askedAt, 64) || row2.source === "tekla" && !TEKLA_GUID.test(row2.id)) return null;
140022
140478
  return {
140023
140479
  messageEventId: row2.messageEventId,
140024
140480
  chatId: row2.chatId,
@@ -140093,8 +140549,45 @@ function aiLinksOfEvent(event) {
140093
140549
  }
140094
140550
  return links;
140095
140551
  }
140552
+ function teklaReadLinkRows(event) {
140553
+ const payload = event.payload;
140554
+ const question = asRow(payload.linkedQuestion);
140555
+ const parts = payload.parts;
140556
+ if (!question || !event.turnId || payload.status !== "verified-for-selection-read" || payload.operation !== TEKLA_SELECTION_READ_OPERATION || payload.complete !== true || payload.truncated !== false || !Array.isArray(parts) || !parts.length || parts.length > MAX_LISTED_SUBJECTS || !str6(question.messageEventId, 64) || !Number.isSafeInteger(question.messageSequence) || question.messageSequence >= event.sequence || typeof question.question !== "string" || !isIso(question.askedAt)) return [];
140557
+ const seen = /* @__PURE__ */ new Set();
140558
+ const links = [];
140559
+ for (const item of parts) {
140560
+ const part = asRow(item);
140561
+ const guid3 = part?.guid;
140562
+ if (!part || typeof guid3 !== "string" || !TEKLA_GUID.test(guid3) || seen.has(guid3)) return [];
140563
+ seen.add(guid3);
140564
+ links.push({
140565
+ messageEventId: question.messageEventId,
140566
+ chatId: event.chatId,
140567
+ sequence: question.messageSequence,
140568
+ source: "tekla",
140569
+ kind: "part",
140570
+ id: guid3,
140571
+ label: subjectLabelText(modelSubjectLabel("tekla", part)),
140572
+ note: question.question,
140573
+ revision: null,
140574
+ sourceDigest: null,
140575
+ createdAt: event.createdAt,
140576
+ origin: "read",
140577
+ linkEventId: event.eventId,
140578
+ linkSequence: event.sequence,
140579
+ aiNote: "",
140580
+ askedAt: question.askedAt
140581
+ });
140582
+ }
140583
+ return links;
140584
+ }
140096
140585
  function subjectLinksOfEvent(event) {
140586
+ return linksOfEvent(event).filter((link2) => link2.source !== "tekla" || TEKLA_GUID.test(link2.id));
140587
+ }
140588
+ function linksOfEvent(event) {
140097
140589
  if (event.type === "chat-subjects") return aiLinksOfEvent(event);
140590
+ if (event.type === "tekla-read") return teklaReadLinkRows(event);
140098
140591
  if (event.type !== "user-message") return [];
140099
140592
  const payload = event.payload;
140100
140593
  const subjects = payload.subjects && typeof payload.subjects === "object" && !Array.isArray(payload.subjects) ? payload.subjects : null;
@@ -140145,8 +140638,8 @@ function foldSubjectEvent(index, event) {
140145
140638
  const links = subjectLinksOfEvent(event);
140146
140639
  if (!links.length) return false;
140147
140640
  const first = links[0];
140148
- if (first.origin === "selection") return addSubjectLinks(index, links);
140149
- const same6 = (link2) => link2.chatId === first.chatId && link2.messageEventId === first.messageEventId && link2.origin === first.origin;
140641
+ if (ADD_ONLY.has(first.origin)) return addSubjectLinks(index, links);
140642
+ const same6 = (link2) => link2.chatId === first.chatId && link2.messageEventId === first.messageEventId && link2.origin === first.origin && link2.source === first.source;
140150
140643
  if (index.links.some((link2) => same6(link2) && link2.linkSequence > first.linkSequence)) return false;
140151
140644
  const before = index.links.length;
140152
140645
  index.links = index.links.filter((link2) => !(same6(link2) && link2.linkSequence < first.linkSequence));
@@ -140158,20 +140651,24 @@ function forgetSubjectChats(index, keep) {
140158
140651
  for (const chatId of Object.keys(index.chats)) if (!keep(chatId)) delete index.chats[chatId];
140159
140652
  return index.links.length + Object.keys(index.chats).length !== before;
140160
140653
  }
140161
- var SUBJECT_INDEX_VERSION, SUBJECT_INDEX_FILE, ORIGINS, str6, isRevision, revisionOf, digestOf, asRow, linkKey;
140654
+ var SUBJECT_INDEX_VERSION, SUBJECT_INDEX_FILE, ORIGINS, ADD_ONLY, str6, isRevision, revisionOf, digestOf, asRow, isIso, linkKey;
140162
140655
  var init_chat_subject_index = __esm({
140163
140656
  "chat-subject-index.ts"() {
140164
140657
  "use strict";
140658
+ init_chat_types();
140165
140659
  init_chat_subjects();
140166
- SUBJECT_INDEX_VERSION = 2;
140660
+ init_model_chat_questions();
140661
+ SUBJECT_INDEX_VERSION = 3;
140167
140662
  SUBJECT_INDEX_FILE = "subject-index.json";
140168
- ORIGINS = /* @__PURE__ */ new Set(["selection", "ai-note", "ai-answer"]);
140663
+ ORIGINS = /* @__PURE__ */ new Set(["selection", "read", "ai-note", "ai-answer"]);
140664
+ ADD_ONLY = /* @__PURE__ */ new Set(["selection", "read"]);
140169
140665
  str6 = (value, max2 = 4096) => typeof value === "string" && value.length > 0 && value.length <= max2;
140170
140666
  isRevision = (value) => Number.isSafeInteger(value) || typeof value === "string" && HEX645.test(value);
140171
140667
  revisionOf = (value) => isRevision(value) ? value : null;
140172
140668
  digestOf = (value) => typeof value === "string" && HEX645.test(value) ? value : null;
140173
140669
  asRow = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
140174
- linkKey = (link2) => `${link2.linkEventId}\0${link2.kind}\0${link2.id}`;
140670
+ isIso = (value) => str6(value, 64) && Number.isFinite(Date.parse(value));
140671
+ linkKey = (link2) => ADD_ONLY.has(link2.origin) ? `${link2.origin}\0${link2.messageEventId}\0${link2.kind}\0${link2.id}` : `${link2.linkEventId}\0${link2.kind}\0${link2.id}`;
140175
140672
  }
140176
140673
  });
140177
140674
 
@@ -140407,12 +140904,42 @@ function releaseLock(id2, requestId) {
140407
140904
  }
140408
140905
  return true;
140409
140906
  }
140907
+ function emptyRetentionSweep() {
140908
+ return { reconciled: 0, blockedProjectUuids: /* @__PURE__ */ new Set(), blockedUnsignedProjectIds: /* @__PURE__ */ new Set(), unattributed: [] };
140909
+ }
140410
140910
  function beginKnowledgeRetentionReconciliation() {
140411
140911
  generationGcEnabled = false;
140912
+ gcBlockedProjects = /* @__PURE__ */ new Set();
140412
140913
  }
140413
- 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
+ ] : []);
140414
140919
  generationGcEnabled = true;
140415
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
+ }
140416
140943
  function retentionPinPath(id2, pinId) {
140417
140944
  if (!isGenerationId(pinId)) throw new KnowledgeError("invalid retention pin id");
140418
140945
  return (0, import_node_path80.join)(retentionPinsDir(id2), `${pinId}.json`);
@@ -140972,7 +141499,7 @@ function failOrganize(id2, requestId, opts) {
140972
141499
  releaseLock(id2, requestId);
140973
141500
  }
140974
141501
  function gcOldGenerations(id2, currentGenerationId) {
140975
- if (!generationGcEnabled) return;
141502
+ if (!generationGcEnabled || gcBlockedForProject(id2)) return;
140976
141503
  const dir = generationsDir(id2);
140977
141504
  if (!(0, import_node_fs80.existsSync)(dir)) return;
140978
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);
@@ -140997,7 +141524,7 @@ function gcOldGenerations(id2, currentGenerationId) {
140997
141524
  }
140998
141525
  }
140999
141526
  }
141000
- 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;
141001
141528
  var init_knowledge_store = __esm({
141002
141529
  "knowledge-store.ts"() {
141003
141530
  "use strict";
@@ -141006,6 +141533,7 @@ var init_knowledge_store = __esm({
141006
141533
  import_node_path80 = require("node:path");
141007
141534
  import_yaml9 = __toESM(require_dist(), 1);
141008
141535
  init_projects_store();
141536
+ init_workspace_root_store();
141009
141537
  init_durable_replace();
141010
141538
  KnowledgeError = class extends Error {
141011
141539
  code;
@@ -141040,6 +141568,8 @@ var init_knowledge_store = __esm({
141040
141568
  retentionPinsDir = (id2) => (0, import_node_path80.join)(vaultDir(id2), "retention-pins");
141041
141569
  activeGenerationReaders = /* @__PURE__ */ new Map();
141042
141570
  generationGcEnabled = true;
141571
+ gcBlockedProjects = /* @__PURE__ */ new Set();
141572
+ gcLookupFailuresLogged = /* @__PURE__ */ new Set();
141043
141573
  WIKI_SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/;
141044
141574
  KB_MAX_NODES = 300;
141045
141575
  KB_MAX_TOTAL_BYTES = 8 * 1024 * 1024;
@@ -141331,7 +141861,9 @@ function parseTeklaAllowance(row2) {
141331
141861
  if (row2.allowedForChat !== void 0) {
141332
141862
  const allowed = row2.allowedForChat;
141333
141863
  if (!allowed || typeof allowed !== "object" || Array.isArray(allowed) || !isIsoDate(allowed.grantedAt) || typeof allowed.approvalId !== "string" || !UUID20.test(allowed.approvalId)) throw invalid8();
141334
- result2.allowedForChat = { grantedAt: allowed.grantedAt, approvalId: allowed.approvalId.toLowerCase() };
141864
+ if (allowed.scope === TEKLA_ALLOWANCE_SCOPE) {
141865
+ result2.allowedForChat = { grantedAt: allowed.grantedAt, approvalId: allowed.approvalId.toLowerCase(), scope: TEKLA_ALLOWANCE_SCOPE };
141866
+ }
141335
141867
  }
141336
141868
  if (row2.allowanceRevision !== void 0) {
141337
141869
  if (!isRevision2(row2.allowanceRevision)) throw invalid8();
@@ -141365,7 +141897,7 @@ function grantTeklaAllowance(binding, approvalId, at = (/* @__PURE__ */ new Date
141365
141897
  const id2 = approvalId.toLowerCase();
141366
141898
  return {
141367
141899
  ...withAllowanceDecision(binding, { action: "grant", at, revision, approvalId: id2 }),
141368
- allowedForChat: { grantedAt: at, approvalId: id2 }
141900
+ allowedForChat: { grantedAt: at, approvalId: id2, scope: TEKLA_ALLOWANCE_SCOPE }
141369
141901
  };
141370
141902
  }
141371
141903
  async function revokeChatTeklaAllowance(owner3, chatId) {
@@ -142127,12 +142659,42 @@ function parseTeklaSelectedPart(value) {
142127
142659
  const texts = [row2.mark, row2.name, row2.profile, row2.material];
142128
142660
  if (texts.some((text9) => typeof text9 !== "string" || Array.from(text9).length > TEKLA_PART_TEXT_LIMIT || /[\u0000-\u001f\u007f]/u.test(text9))) return null;
142129
142661
  if (row2.weightKg !== null && !isWeight2(row2.weightKg)) return null;
142662
+ if (row2.guid !== void 0 && (typeof row2.guid !== "string" || !TEKLA_GUID.test(row2.guid))) return null;
142130
142663
  return {
142131
142664
  mark: row2.mark,
142132
142665
  name: row2.name,
142133
142666
  profile: row2.profile,
142134
142667
  material: row2.material,
142135
- weightKg: row2.weightKg
142668
+ weightKg: row2.weightKg,
142669
+ ...row2.guid !== void 0 ? { guid: row2.guid } : {}
142670
+ };
142671
+ }
142672
+ function parseLinkedPartCheck(row2, listed, invalid8) {
142673
+ const { linkedPartsChecked: checked2, missingLinkedParts: missing, linkedPartsUnchecked: unchecked, linkedPartsCheck: shortfall } = row2;
142674
+ if (shortfall !== void 0 && !TEKLA_LINKED_PARTS_CHECKS.includes(shortfall)) throw invalid8();
142675
+ const marker = shortfall !== void 0 ? { linkedPartsCheck: shortfall } : {};
142676
+ if (checked2 === void 0 && missing === void 0 && unchecked === void 0) return marker;
142677
+ if (shortfall === "unavailable" || !isCount4(checked2) || checked2 > TEKLA_LINKED_PART_CHECK_LIMIT || !Array.isArray(missing) || missing.length > checked2 || new Set(missing).size !== missing.length || missing.some((guid3) => typeof guid3 !== "string" || !TEKLA_GUID.test(guid3) || listed.has(guid3)) || unchecked !== void 0 && !isCount4(unchecked)) throw invalid8();
142678
+ return { linkedPartsChecked: checked2, missingLinkedParts: [...missing], ...unchecked !== void 0 ? { linkedPartsUnchecked: unchecked } : {}, ...marker };
142679
+ }
142680
+ function teklaReadLinkedQuestion(resolved, events, turnId, payload) {
142681
+ const parts = payload.parts ?? [];
142682
+ if (resolved.owner.kind !== "project" || payload.status !== "verified-for-selection-read" || payload.complete !== true || payload.truncated !== false || !parts.length || parts.some((part) => !part.guid)) return void 0;
142683
+ const question = events.find((event) => event.type === "user-message" && event.turnId === turnId);
142684
+ if (!question) return void 0;
142685
+ const linked = new Set(parts.map((part) => part.guid));
142686
+ for (const event of events) {
142687
+ if (event.type !== "tekla-read" || event.turnId !== turnId || !event.payload.linkedQuestion) continue;
142688
+ for (const part of Array.isArray(event.payload.parts) ? event.payload.parts : []) {
142689
+ if (typeof part?.guid === "string") linked.add(part.guid);
142690
+ }
142691
+ }
142692
+ if (linked.size > MAX_LISTED_SUBJECTS) return void 0;
142693
+ return {
142694
+ messageEventId: question.eventId,
142695
+ messageSequence: question.sequence,
142696
+ question: subjectNote(typeof question.payload.text === "string" ? question.payload.text : ""),
142697
+ askedAt: question.createdAt
142136
142698
  };
142137
142699
  }
142138
142700
  function parseChatTeklaReadPayload(value) {
@@ -142158,7 +142720,9 @@ function parseChatTeklaReadPayload(value) {
142158
142720
  if (!selection) return verified;
142159
142721
  const parts = Array.isArray(row2.parts) && row2.parts.length <= TEKLA_SELECTION_ROW_LIMIT ? row2.parts.map(parseTeklaSelectedPart) : null;
142160
142722
  if (!parts || parts.some((part) => part === null) || !isCount4(row2.partCount) || row2.partCount < parts.length || !isWeight2(row2.totalWeightKg) || row2.truncated !== row2.partCount > parts.length || typeof row2.complete !== "boolean" || !isCount4(row2.weightMissing) || row2.weightMissing > row2.partCount || !isCount4(row2.otherObjectCount)) throw invalid8();
142161
- return {
142723
+ const guids = parts.map((part) => part.guid).filter((guid3) => guid3 !== void 0);
142724
+ if (new Set(guids).size !== guids.length) throw invalid8();
142725
+ const listed = {
142162
142726
  ...verified,
142163
142727
  parts,
142164
142728
  partCount: row2.partCount,
@@ -142168,6 +142732,7 @@ function parseChatTeklaReadPayload(value) {
142168
142732
  weightMissing: row2.weightMissing,
142169
142733
  otherObjectCount: row2.otherObjectCount
142170
142734
  };
142735
+ return { ...listed, ...parseLinkedPartCheck(row2, new Set(guids), invalid8) };
142171
142736
  }
142172
142737
  if (typeof row2.code !== "string" || !/^[a-z][a-z-]{0,63}$/u.test(row2.code) || typeof row2.message !== "string" || !row2.message.trim() || row2.message.length > 2048 || row2.modelName !== void 0 || row2.hostPid !== void 0) throw invalid8();
142173
142738
  return { ...base2, code: row2.code, message: row2.message };
@@ -142185,21 +142750,24 @@ async function appendChatTeklaReadIfTurnCurrent(owner3, chatId, expected2, paylo
142185
142750
  const parsed = parseChatTeklaReadPayload(payload);
142186
142751
  const resolved = resolveOwner2(owner3);
142187
142752
  const id2 = assertUuid2(chatId, "chat identity");
142188
- return withChatMutation(resolved, id2, "recording Tekla read", () => {
142753
+ return withChatMutation(resolved, id2, "recording Tekla read", async () => {
142189
142754
  const chat = readChatAt(resolved, id2);
142190
- const recorded = readEventJournal(resolved, chat).find((event2) => event2.eventId === parsed.approvalId);
142755
+ const events = readEventJournal(resolved, chat);
142756
+ const recorded = events.find((event2) => event2.eventId === parsed.approvalId);
142191
142757
  if (recorded) return { appended: true, event: recorded };
142192
142758
  const active2 = chat.activeTurn;
142193
142759
  if (!active2 || active2.turnId !== expected2.turnId.toLowerCase() || active2.ownershipGeneration !== expected2.ownershipGeneration.toLowerCase() || active2.connectionRevision !== expected2.connectionRevision.toLowerCase() || chat.connectionRevision !== expected2.connectionRevision.toLowerCase() || active2.dispatchState !== "acknowledged" || chat.state !== "running" && chat.state !== "awaiting-approval" || !stillWanted()) {
142194
142760
  return { appended: false };
142195
142761
  }
142762
+ const linkedQuestion = teklaReadLinkedQuestion(resolved, events, active2.turnId, parsed);
142196
142763
  const event = appendChatEventLocked(resolved, id2, {
142197
142764
  eventId: parsed.approvalId,
142198
142765
  turnId: expected2.turnId,
142199
142766
  clientSubmissionId: expected2.clientSubmissionId,
142200
142767
  type: "tekla-read",
142201
- payload: parsed
142768
+ payload: { ...parsed, ...linkedQuestion ? { linkedQuestion } : {} }
142202
142769
  });
142770
+ await indexSubjectLinks(resolved, event);
142203
142771
  return { appended: true, event };
142204
142772
  });
142205
142773
  }
@@ -142277,39 +142845,114 @@ async function appendChatKnowledgeCitation(owner3, chatId, input2) {
142277
142845
  return event;
142278
142846
  });
142279
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
+ }
142280
142883
  function reconcileChatKnowledgeRetention() {
142281
- const owners = [
142282
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
142283
- ...listArchivedProjects().map((project) => ({ kind: "project", projectId: project.id })),
142284
- ...listWorkflowOwnerships({ includeArchived: true }).map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
142285
- ];
142286
- let reconciled = 0;
142287
- for (const owner3 of owners) {
142288
- 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) {
142289
142923
  const scopedProjectId = chat.owner.projectId;
142290
- for (const event of listChatEvents(owner3, chat.chatId)) {
142291
- if (event.type !== "knowledge-citation") continue;
142292
- const payload = event.payload;
142293
- if (!scopedProjectId || payload.citationId !== event.eventId || payload.projectId !== scopedProjectId || !isGenerationId(payload.generationId) || !Array.isArray(payload.pages)) {
142294
- throw new ChatStoreError("stored Knowledge citation is invalid", 409, "chat-knowledge-citation-invalid");
142295
- }
142296
- const slugs = payload.pages.map((page) => page?.slug);
142297
- if (slugs.some((slug) => !isWikiSlug(slug))) {
142298
- 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;
142299
142946
  }
142300
- const pin = reconcileGenerationRetentionPin(scopedProjectId, {
142301
- pinId: event.eventId,
142302
- generationId: payload.generationId,
142303
- ownerKind: "chat-citation",
142304
- ownerId: `${chat.chatId}:${event.eventId}`,
142305
- pages: slugs
142306
- });
142307
- if (pin.state !== "committed") commitGenerationRetentionPin(scopedProjectId, pin.pinId);
142308
- 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);
142309
142952
  }
142310
142953
  }
142311
142954
  }
142312
- return reconciled;
142955
+ return result2;
142313
142956
  }
142314
142957
  function parseEvent2(value, expectedChatId) {
142315
142958
  const row2 = value;
@@ -142329,19 +142972,26 @@ function reconcileChatEventJournals() {
142329
142972
  return withReadScope(reconcileChatEventJournalsNow);
142330
142973
  }
142331
142974
  function reconcileChatEventJournalsNow() {
142332
- const owners = [
142333
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
142334
- ...listArchivedProjects().map((project) => ({ kind: "project", projectId: project.id })),
142335
- ...listWorkflowOwnerships({ includeArchived: true }).map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
142336
- ];
142337
142975
  let repaired = 0;
142338
- for (const owner3 of owners) {
142339
- const resolved = resolveOwner2(owner3);
142340
- for (const chat of listChats(owner3, { includeArchived: true })) {
142341
- const events = readEventJournal(resolved, chat);
142342
- if (events.length === chat.lastEventSequence) continue;
142343
- repairEventMetadata(resolved, chat, events);
142344
- 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
+ }
142345
142995
  }
142346
142996
  }
142347
142997
  return repaired;
@@ -142875,17 +143525,15 @@ function resurveyFollowupReceipts(waiting, targeted) {
142875
143525
  async function recoverChatFollowups(target) {
142876
143526
  const targeted = Boolean(target);
142877
143527
  let waiting = withReadScope(() => {
142878
- const owners = target ? [target.owner] : [
142879
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
142880
- ...listWorkflowOwnerships().map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
142881
- ];
143528
+ const owners = target ? [target.owner] : startupChatOwners({ includeArchived: false });
142882
143529
  const surveyed = [];
142883
143530
  for (const owner3 of owners) {
142884
143531
  let ownedChats;
142885
143532
  try {
142886
143533
  ownedChats = target ? [readChat(owner3, target.chatId)] : listChats(owner3, { includeArchived: true });
142887
143534
  } catch (error62) {
142888
- 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);
142889
143537
  continue;
142890
143538
  }
142891
143539
  for (const chat of ownedChats) {
@@ -143023,17 +143671,14 @@ function listQueuedChatFollowupConversations() {
143023
143671
  return withReadScope(listQueuedChatFollowupConversationsNow);
143024
143672
  }
143025
143673
  function listQueuedChatFollowupConversationsNow() {
143026
- const owners = [
143027
- ...listProjects().map((project) => ({ kind: "project", projectId: project.id })),
143028
- ...listWorkflowOwnerships().map((workflow) => ({ kind: "workflow", workflowId: workflow.workflowId }))
143029
- ];
143674
+ const owners = startupChatOwners({ includeArchived: false });
143030
143675
  const queued = [];
143031
143676
  for (const owner3 of owners) {
143032
143677
  let chats;
143033
143678
  try {
143034
143679
  chats = listChats(owner3);
143035
143680
  } catch (error62) {
143036
- console.error("[chat] queued follow-up resume could not list an owner:", error62);
143681
+ reportOwnerFailure("queued follow-up resume", owner3, error62);
143037
143682
  continue;
143038
143683
  }
143039
143684
  for (const chat of chats) {
@@ -143276,7 +143921,7 @@ async function updateChatTurnIntent(owner3, chatId, turnId, mutate) {
143276
143921
  return saved;
143277
143922
  });
143278
143923
  }
143279
- 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;
143280
143925
  var init_chat_store = __esm({
143281
143926
  "chat-store.ts"() {
143282
143927
  "use strict";
@@ -143359,14 +144004,19 @@ var init_chat_store = __esm({
143359
144004
  "truncated",
143360
144005
  "complete",
143361
144006
  "weightMissing",
143362
- "otherObjectCount"
144007
+ "otherObjectCount",
144008
+ "linkedPartsChecked",
144009
+ "missingLinkedParts",
144010
+ "linkedPartsUnchecked",
144011
+ "linkedPartsCheck"
143363
144012
  ];
143364
- TEKLA_PART_KEYS = ["mark", "name", "profile", "material", "weightKg"];
144013
+ TEKLA_PART_KEYS = ["mark", "name", "profile", "material", "weightKg", "guid"];
143365
144014
  TEKLA_PART_TEXT_LIMIT = 64;
143366
144015
  TEKLA_READ_PAYLOAD_BUDGET = MAX_EVENT_BYTES - 16 * 1024;
143367
144016
  isCount4 = (value) => Number.isSafeInteger(value) && value >= 0;
143368
144017
  isWeight2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
143369
144018
  MAX_SUBJECT_LINK_CALLS_PER_TURN = 10;
144019
+ startupOwnerNotes = /* @__PURE__ */ new Set();
143370
144020
  subjectIndexWarnings = /* @__PURE__ */ new Set();
143371
144021
  isMissing = (error62) => error62?.code === "ENOENT" || error62 instanceof ChatStoreError && error62.status === 404;
143372
144022
  PROMOTABLE_FOLLOWUP_STATES = ["queued-next", "admitting", "sending", "unknown"];
@@ -163739,76 +164389,26 @@ var init_zod = __esm({
163739
164389
  }
163740
164390
  });
163741
164391
 
163742
- // ../web/model-property-display.js
163743
- function teklaPropertyGroups(rows2) {
163744
- const properties = [], udas = [], nativeGroups = /* @__PURE__ */ new Map();
163745
- for (const row2 of Array.isArray(rows2) ? rows2 : []) {
163746
- const isUda = row2.isUda === true || row2.groupName === "User-defined attributes" || row2.groupName === "User-defined attributes (UDA)" || row2.groupName === "UDA";
163747
- if (isUda) {
163748
- udas.push(row2);
163749
- continue;
163750
- }
163751
- if (row2.semantic && Number.isSafeInteger(row2.groupOrdinal)) {
163752
- const key5 = `${row2.groupOrdinal}\0${row2.groupName}`;
163753
- const group = nativeGroups.get(key5) || { key: key5, name: row2.groupName, ordinal: row2.groupOrdinal, rows: [], expanded: true };
163754
- group.rows.push(row2);
163755
- nativeGroups.set(key5, group);
163756
- continue;
164392
+ // chat-subject-link.ts
164393
+ function teklaReadParts(events, turnId) {
164394
+ const question = /* @__PURE__ */ new Map();
164395
+ const read3 = /* @__PURE__ */ new Map();
164396
+ const readThisTurn = /* @__PURE__ */ new Set();
164397
+ for (const event of events) {
164398
+ const payload = event.type === "tekla-read" ? event.payload : null;
164399
+ if (!payload || payload.status !== "verified-for-selection-read" || payload.operation !== TEKLA_SELECTION_READ_OPERATION || !Array.isArray(payload.parts)) continue;
164400
+ const linked = event.turnId === turnId && Boolean(asRow2(payload.linkedQuestion));
164401
+ for (const item of payload.parts) {
164402
+ const part = asRow2(item);
164403
+ if (!part || typeof part.guid !== "string" || !TEKLA_GUID.test(part.guid)) continue;
164404
+ const label2 = modelSubjectLabel("tekla", part);
164405
+ read3.set(part.guid, label2);
164406
+ if (event.turnId === turnId) readThisTurn.add(part.guid);
164407
+ if (linked) question.set(part.guid, label2);
163757
164408
  }
163758
- if (/^(?:Raw\b|provenance|Reader coverage|Technical details|System)/i.test(row2.groupName || "")) continue;
163759
- if (row2.groupName === "Overview" && ["Object kind", "Subtype"].includes(row2.name)) continue;
163760
- if (row2.groupName === "Source identity" && row2.name === "Native type") continue;
163761
- const item = row2.name === "Object ID" ? { ...row2, name: "ID" } : row2;
163762
- properties.push(item);
163763
- }
163764
- const ordered = (values2) => values2.slice().sort((a, b) => (a.propertyOrdinal ?? 0) - (b.propertyOrdinal ?? 0));
163765
- return [
163766
- ...[...nativeGroups.values()].sort((a, b) => a.ordinal - b.ordinal).map((group) => ({ ...group, rows: ordered(group.rows) })),
163767
- ...properties.length ? [{ key: "tekla-properties", name: "Properties", rows: properties, expanded: true }] : [],
163768
- ...udas.length ? [{ key: "tekla-udas", name: "User-defined attributes (UDA)", rows: ordered(udas), expanded: false }] : []
163769
- ];
163770
- }
163771
- function teklaObjectFields(entity, rows2 = []) {
163772
- const source = teklaPropertyGroups(rows2).filter((group) => group.key !== "tekla-udas").flatMap((group) => group.rows);
163773
- const value = (name) => source.find((row2) => row2.name === name)?.value;
163774
- return {
163775
- name: value("Name") ?? null,
163776
- profile: value("Profile") ?? null,
163777
- id: value("ID") ?? entity.objectId ?? (/^element:([0-9]+)$/.exec(entity.id || "")?.[1] ?? null)
163778
- };
163779
- }
163780
- function teklaObjectLabel(entity, rows2 = []) {
163781
- const fields = teklaObjectFields(entity, rows2);
163782
- return [
163783
- fields.name != null ? `Name: ${fields.name}` : null,
163784
- fields.profile != null ? `Profile: ${fields.profile}` : null,
163785
- fields.id != null ? `ID: ${fields.id}` : null
163786
- ].filter(Boolean).join(" \xB7 ") || entity.typeName || "Tekla object";
163787
- }
163788
- var init_model_property_display = __esm({
163789
- "../web/model-property-display.js"() {
163790
- init_display_units();
163791
- }
163792
- });
163793
-
163794
- // ../web/model-chat-questions.js
163795
- function modelSubjectLabel(source, entity, rows2 = []) {
163796
- const id2 = String(entity?.id ?? "");
163797
- if (source === "tekla-parser") {
163798
- const fields = teklaObjectFields(entity || {}, rows2);
163799
- const label2 = teklaObjectLabel(entity || {}, rows2);
163800
- return fields.id == null ? `${label2} \xB7 ${id2}` : label2;
163801
164409
  }
163802
- const what = entity?.name || entity?.typeName || entity?.categoryName || entity?.category || "Revit element";
163803
- return `${what} \xB7 ${id2}`;
164410
+ return { question, read: read3, readThisTurn };
163804
164411
  }
163805
- var init_model_chat_questions = __esm({
163806
- "../web/model-chat-questions.js"() {
163807
- init_model_property_display();
163808
- }
163809
- });
163810
-
163811
- // chat-subject-link.ts
163812
164412
  function steelSubjectLabels(doc) {
163813
164413
  const labels = /* @__PURE__ */ new Map();
163814
164414
  const root9 = doc && typeof doc === "object" && !Array.isArray(doc) ? doc : {};
@@ -163873,7 +164473,7 @@ function rawInput(value) {
163873
164473
  if (row2.note !== void 0 && typeof row2.note !== "string") return "note must be text.";
163874
164474
  return { role: row2.role, subjects, note: row2.note };
163875
164475
  }
163876
- var import_node_crypto67, LINK_SUBJECTS_TOOL_NAME, LINK_SUBJECTS_DESCRIPTION, LINK_SUBJECTS_ROUTING, LINK_SUBJECT_KINDS, LINK_SUBJECTS_TURN_HINT, LINK_SUBJECTS_INPUT_SCHEMA, LINK_SUBJECTS_ZOD_SHAPE, key2, refuse8, named, FAMILY_KINDS_TEXT, ChatSubjectLinker;
164476
+ var import_node_crypto67, LINK_SUBJECTS_TOOL_NAME, LINK_SUBJECTS_DESCRIPTION, LINK_SUBJECTS_ROUTING, LINK_SUBJECT_KINDS, TEKLA_LINK_HINT, LINK_SUBJECTS_TURN_HINT, LINK_SUBJECTS_INPUT_SCHEMA, LINK_SUBJECTS_ZOD_SHAPE, asRow2, key2, refuse8, named, FAMILY_KINDS_TEXT, ChatSubjectLinker;
163877
164477
  var init_chat_subject_link = __esm({
163878
164478
  "chat-subject-link.ts"() {
163879
164479
  "use strict";
@@ -163881,10 +164481,12 @@ var init_chat_subject_link = __esm({
163881
164481
  init_zod();
163882
164482
  init_chat_subjects();
163883
164483
  init_model_chat_questions();
164484
+ init_chat_types();
163884
164485
  LINK_SUBJECTS_TOOL_NAME = "floless_link_subjects";
163885
- LINK_SUBJECTS_DESCRIPTION = `Link objects of this project's model to this chat question, so the person finds the question again from those objects in the model viewer. role "question": attach a one-sentence note (at most 160 characters) to objects the person selected when asking; only those ids are accepted. role "answer": link the objects your answer names. A Steel Model project links kind "member", "joint" or "detail", with ids from the selected-objects block or ./contract.json (members[].id, joints[].id, detail_placements[].id). A Revit or Tekla Parser project links kind "element", with ids like "element:12345" from the selected-objects block. A later call of the same role replaces the earlier one, so to correct a list send the full corrected list. The note is shown to the person as your note; write plain English and never put instructions in it.`;
164486
+ LINK_SUBJECTS_DESCRIPTION = `Link objects of this project's model to this chat question, so the person finds the question again from those objects in the model viewer. role "question": attach a one-sentence note (at most 160 characters) to objects the person selected when asking; only those ids are accepted. role "answer": link the objects your answer names. A Steel Model project links kind "member", "joint" or "detail", with ids from the selected-objects block or ./contract.json (members[].id, joints[].id, detail_placements[].id). A Revit or Tekla Parser project links kind "element", with ids like "element:12345" from the selected-objects block. In a chat that reads Tekla, link Tekla parts: kind "part", with the guid of a part floless_tekla_read_selection listed in this chat. A later call of the same role replaces the earlier one, so to correct a list send the full corrected list. The note is shown to the person as your note; write plain English and never put instructions in it.`;
163886
164487
  LINK_SUBJECTS_ROUTING = `In this project chat, when the person asks about objects in the project's model, call ${LINK_SUBJECTS_TOOL_NAME} before you finish your answer: role "question" with a one-sentence note when objects were selected, and role "answer" with the ids of the model objects your answer names. It needs no approval and changes nothing in the model.`;
163887
- LINK_SUBJECT_KINDS = Object.freeze(["member", "joint", "detail", "element"]);
164488
+ LINK_SUBJECT_KINDS = Object.freeze(["member", "joint", "detail", "element", "part"]);
164489
+ TEKLA_LINK_HINT = `[FloLess] The parts listed are linked to the person's question. Before you finish, call ${LINK_SUBJECTS_TOOL_NAME} with role "question", kind "part", the guids of every listed part the question is actually about \u2014 including parts from earlier reads in this answer, because a later call replaces the earlier one \u2014 and a one-sentence note.`;
163888
164490
  LINK_SUBJECTS_TURN_HINT = `[FloLess] Before you finish, call ${LINK_SUBJECTS_TOOL_NAME} with role "question", these objects' ids and a one-sentence note on what the person asked about them.`;
163889
164491
  LINK_SUBJECTS_INPUT_SCHEMA = Object.freeze({
163890
164492
  type: "object",
@@ -163918,6 +164520,7 @@ var init_chat_subject_link = __esm({
163918
164520
  subjects: external_exports.array(external_exports.object({ kind: external_exports.enum(LINK_SUBJECT_KINDS), id: external_exports.string().min(1).max(200) }).strict()).min(1).max(MAX_LISTED_SUBJECTS),
163919
164521
  note: external_exports.string().max(2e3).optional()
163920
164522
  };
164523
+ asRow2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
163921
164524
  key2 = (kind2, id2) => `${kind2}\0${id2}`;
163922
164525
  refuse8 = (text9) => ({ success: false, text: text9 });
163923
164526
  named = (item) => `${item.kind} ${JSON.stringify(item.id)}`;
@@ -163937,12 +164540,17 @@ var init_chat_subject_link = __esm({
163937
164540
  if (chat.owner.kind !== "project" || !chat.owner.projectId) {
163938
164541
  return refuse8("This chat is not a project chat, so it has no model objects to link.");
163939
164542
  }
164543
+ const raw = rawInput(input2.arguments);
164544
+ if (typeof raw === "string") return refuse8(`FloLess did not link anything. ${raw}`);
164545
+ const parts = raw.subjects.filter((item) => item.kind === "part").length;
164546
+ if (parts === raw.subjects.length) return this.linkTeklaParts(chat, turn, raw, input2.callId);
164547
+ if (parts) {
164548
+ return refuse8("FloLess did not link anything: link one model\u2019s objects per call \u2014 Tekla parts separately from this project\u2019s model objects.");
164549
+ }
163940
164550
  const family = this.deps.modelFamily(chat.owner.projectId);
163941
164551
  if (family === "unsupported") {
163942
164552
  return refuse8("Object links are not available for this project\u2019s model yet, so FloLess did not link anything.");
163943
164553
  }
163944
- const raw = rawInput(input2.arguments);
163945
- if (typeof raw === "string") return refuse8(`FloLess did not link anything. ${raw}`);
163946
164554
  const kinds = subjectKinds(family);
163947
164555
  const foreign = raw.subjects.find((item) => !kinds.has(item.kind));
163948
164556
  if (foreign) return refuse8(`FloLess did not link anything: unknown kind ${JSON.stringify(foreign.kind)}. ${FAMILY_KINDS_TEXT[family]}`);
@@ -163991,21 +164599,81 @@ var init_chat_subject_link = __esm({
163991
164599
  return refuse8(`FloLess did not link anything: a "question" note may name only the selected objects, and ${outside.slice(0, 5).map(named).join(", ")}${outside.length > 5 ? ` and ${outside.length - 5} more` : ""} ${outside.length === 1 ? "was" : "were"} not selected.`);
163992
164600
  }
163993
164601
  }
164602
+ const notFound = model ? items.filter((item) => !model.labels.has(key2(item.kind, item.id))) : [];
164603
+ return this.record(chat, turn, raw.role, input2.callId, {
164604
+ role: raw.role,
164605
+ source: family,
164606
+ revision,
164607
+ ...sourceDigest2 !== void 0 ? { sourceDigest: sourceDigest2 } : {},
164608
+ items,
164609
+ aiNote,
164610
+ toolCallId: input2.callId
164611
+ }, { checked: Boolean(model), notFound });
164612
+ }
164613
+ /**
164614
+ * A call naming live Tekla parts (#1653 stage 4). Each GUID must be one FloLess itself read from Tekla in this chat:
164615
+ * for a note, a part this question's own reads linked; for an answer, any part a verified read listed here. An id
164616
+ * that cannot be verified is refused, never stored unchecked — a live model has no snapshot to check it against later.
164617
+ */
164618
+ async linkTeklaParts(chat, turn, raw, callId) {
164619
+ if (!chat.teklaModelRead?.operations.includes(TEKLA_SELECTION_READ_OPERATION) || !this.deps.teklaParts) {
164620
+ return refuse8("This chat does not read Tekla, so it has no Tekla parts to link. FloLess did not link anything.");
164621
+ }
164622
+ const aiNote = subjectLinkNote(raw.note);
164623
+ if (raw.role === "question" && !aiNote) return refuse8('FloLess did not link anything. A "question" link needs a one-sentence note.');
164624
+ let known3;
164625
+ try {
164626
+ known3 = this.deps.teklaParts({ kind: "project", projectId: chat.owner.projectId }, chat.chatId, turn.turnId);
164627
+ } catch (error62) {
164628
+ console.warn("[chat] object links: the Tekla reads of this chat could not be read", JSON.stringify({
164629
+ chatId: chat.chatId,
164630
+ error: error62 instanceof Error ? error62.message : String(error62)
164631
+ }));
164632
+ return refuse8("FloLess could not check which Tekla parts this chat read, so it did not link anything. You may try once more.");
164633
+ }
164634
+ const allowed = raw.role === "question" ? known3.question : known3.read;
164635
+ const readNotLinked = 'FloLess did not link anything: the parts read in this answer were not linked to this question, because that read was cut short, stopped at its limit, or listed more parts than one question can link. Name them with role "answer" instead; do not read the selection again for this.';
164636
+ if (raw.role === "question" && !allowed.size) {
164637
+ if (raw.subjects.some((item) => known3.readThisTurn.has(item.id))) return refuse8(readNotLinked);
164638
+ return refuse8("No Tekla parts are linked to this question yet: read the selection with floless_tekla_read_selection first. FloLess did not link anything.");
164639
+ }
164640
+ const outside = raw.subjects.filter((item) => !allowed.has(item.id));
164641
+ if (raw.role === "question" && outside.some((item) => known3.readThisTurn.has(item.id))) return refuse8(readNotLinked);
164642
+ if (outside.length) {
164643
+ const list3 = `${outside.slice(0, 5).map(named).join(", ")}${outside.length > 5 ? ` and ${outside.length - 5} more` : ""}`;
164644
+ const verb = outside.length === 1 ? "was" : "were";
164645
+ return refuse8(raw.role === "question" ? `FloLess did not link anything: a "question" note may name only the parts linked to this question by its reads, and ${list3} ${verb} not linked to this question.` : `FloLess did not link anything: ${list3} ${verb} not read from Tekla in this chat. Read them with floless_tekla_read_selection, then link them.`);
164646
+ }
164647
+ let items;
164648
+ try {
164649
+ items = normalizeChatSubjects({
164650
+ source: "tekla",
164651
+ revision: null,
164652
+ items: raw.subjects.map((item) => ({ ...item, label: allowed.get(item.id) ?? item.id }))
164653
+ }).items;
164654
+ } catch (error62) {
164655
+ if (error62 instanceof ChatSubjectsError) return refuse8(`FloLess did not link anything: ${error62.message}.`);
164656
+ throw error62;
164657
+ }
164658
+ return this.record(
164659
+ chat,
164660
+ turn,
164661
+ raw.role,
164662
+ callId,
164663
+ { role: raw.role, source: "tekla", revision: null, items, aiNote, toolCallId: callId },
164664
+ { checked: true, notFound: [] }
164665
+ );
164666
+ }
164667
+ /** Appends one call's links conditionally on its turn, announces them, and tells the chat model what was kept. */
164668
+ async record(chat, turn, role, callId, link2, report) {
164669
+ const items = link2.items;
163994
164670
  let appended;
163995
164671
  try {
163996
164672
  appended = await this.deps.append({ kind: "project", projectId: chat.owner.projectId }, chat.chatId, {
163997
164673
  turnId: turn.turnId,
163998
164674
  ownershipGeneration: turn.ownershipGeneration,
163999
164675
  connectionRevision: turn.connectionRevision
164000
- }, subjectLinkEventId(chat.chatId, turn.turnId, input2.callId), {
164001
- role: raw.role,
164002
- source: family,
164003
- revision,
164004
- ...sourceDigest2 !== void 0 ? { sourceDigest: sourceDigest2 } : {},
164005
- items,
164006
- aiNote,
164007
- toolCallId: input2.callId
164008
- });
164676
+ }, subjectLinkEventId(chat.chatId, turn.turnId, callId), link2);
164009
164677
  } catch (error62) {
164010
164678
  console.warn("[chat] object links could not be saved", JSON.stringify({
164011
164679
  chatId: chat.chatId,
@@ -164020,7 +164688,7 @@ var init_chat_subject_link = __esm({
164020
164688
  return refuse8("The question has already finished, so FloLess did not link anything.");
164021
164689
  }
164022
164690
  const recorded = appended.event.payload;
164023
- const sameCall = recorded.role === raw.role && Array.isArray(recorded.items) && recorded.items.length === items.length && recorded.items.every((item, index) => item.kind === items[index].kind && item.id === items[index].id);
164691
+ const sameCall = recorded.role === role && Array.isArray(recorded.items) && recorded.items.length === items.length && recorded.items.every((item, index) => item.kind === items[index].kind && item.id === items[index].id);
164024
164692
  if (!sameCall) {
164025
164693
  return refuse8("FloLess already recorded this call with different objects, so it did not change them. Call again to link a new list.");
164026
164694
  }
@@ -164029,12 +164697,12 @@ var init_chat_subject_link = __esm({
164029
164697
  } catch (error62) {
164030
164698
  console.warn("[chat] object links were saved but not announced live", error62 instanceof Error ? error62.message : String(error62));
164031
164699
  }
164032
- const notFound = model ? items.filter((item) => !model.labels.has(key2(item.kind, item.id))) : [];
164700
+ const { checked: checked2, notFound } = report;
164033
164701
  return { success: true, text: JSON.stringify({
164034
164702
  linked: items.length,
164035
- role: raw.role,
164036
- ...model ? { notFound: notFound.map(named) } : { checked: false },
164037
- message: (raw.role === "question" ? `Noted ${items.length} selected object${items.length === 1 ? "" : "s"}.` : `Linked ${items.length} object${items.length === 1 ? "" : "s"} to your answer.`) + (!model ? " FloLess could not read the project\u2019s model, so the ids were not checked." : "") + (notFound.length ? ` ${notFound.length} ${notFound.length === 1 ? "is" : "are"} not in the current model and will show under objects not in the model; to correct them, call again with the full corrected list.` : "")
164703
+ role,
164704
+ ...checked2 ? { notFound: notFound.map(named) } : { checked: false },
164705
+ message: (role === "question" ? `Noted ${items.length} selected object${items.length === 1 ? "" : "s"}.` : `Linked ${items.length} object${items.length === 1 ? "" : "s"} to your answer.`) + (!checked2 ? " FloLess could not read the project\u2019s model, so the ids were not checked." : "") + (notFound.length ? ` ${notFound.length} ${notFound.length === 1 ? "is" : "are"} not in the current model and will show under objects not in the model; to correct them, call again with the full corrected list.` : "")
164038
164706
  }) };
164039
164707
  }
164040
164708
  };
@@ -164050,13 +164718,13 @@ function teklaChatAllowable(chat, approval) {
164050
164718
  const binding = chat.teklaModelRead;
164051
164719
  if (approval.explicitOnly !== true || !approval.tool || !Object.hasOwn(TEKLA_TOOL_OPERATIONS, approval.tool) || !binding) return false;
164052
164720
  const operation = TEKLA_TOOL_OPERATIONS[approval.tool];
164053
- return binding.operations.includes(operation) && teklaReadApprovalSummary(binding, operation) === approval.summary;
164721
+ return binding.operations.includes(operation) && teklaReadApprovalSummary(binding, operation, chat.owner.kind === "project") === approval.summary;
164054
164722
  }
164055
164723
  function teklaChatAllowanceCovers(chat, approval) {
164056
164724
  return Boolean(chat.teklaModelRead?.allowedForChat) && teklaChatAllowable(chat, approval);
164057
164725
  }
164058
- function teklaReadApprovalSummary(binding, operation = TEKLA_MODEL_READ_OPERATION) {
164059
- const what = operation === TEKLA_SELECTION_READ_OPERATION ? "the parts selected in the open Tekla model" : "the open Tekla model name";
164726
+ function teklaReadApprovalSummary(binding, operation = TEKLA_MODEL_READ_OPERATION, checksLinkedParts = true) {
164727
+ const what = operation !== TEKLA_SELECTION_READ_OPERATION ? "the open Tekla model name" : checksLinkedParts ? "the parts selected in the open Tekla model, and whether parts linked to earlier questions are still in it," : "the parts selected in the open Tekla model";
164060
164728
  return `Read ${what} through ${binding.sourcePath} (Tekla ${binding.hostVersion}). Nothing in the model changes.`;
164061
164729
  }
164062
164730
  function ownerInput(chat) {
@@ -164147,7 +164815,7 @@ var init_chat_integration_tools = __esm({
164147
164815
  kind: "tekla-read",
164148
164816
  integration: "tekla-model-library",
164149
164817
  label: "Tekla model library",
164150
- description: "Read the parts currently selected in the model open in Tekla Structures, through the model library bound to this FloLess chat: for each part the assembly mark, name, profile, material and weight (kg), plus the part count and total weight. Selected assemblies are read as their parts; at most 200 parts are listed. It is read-only; FloLess handles approval for every call and checks it live. It returns a verified result or a refusal; report a refusal as it is and do not try another route to the selection.",
164818
+ description: "Read the parts currently selected in the model open in Tekla Structures, through the model library bound to this FloLess chat: for each part the assembly mark, name, profile, material, weight (kg) and guid, plus the part count and total weight. Selected assemblies are read as their parts; at most 200 parts are listed. It is read-only; FloLess handles approval for every call and checks it live. It returns a verified result or a refusal; report a refusal as it is and do not try another route to the selection.",
164151
164819
  inputSchema: Object.freeze({ type: "object", properties: Object.freeze({}), additionalProperties: false })
164152
164820
  }),
164153
164821
  Object.freeze({
@@ -164203,7 +164871,7 @@ var init_chat_integration_tools = __esm({
164203
164871
  const spec = this.spec(toolName);
164204
164872
  if (!spec) return { summary: "FloLess refused an unknown integration tool." };
164205
164873
  if (spec.kind === "tekla-read") {
164206
- const summary2 = chat.teklaModelRead && isBound(chat, spec) ? teklaReadApprovalSummary(chat.teklaModelRead, TEKLA_TOOL_OPERATIONS[spec.name]) : this.unboundText(toolName);
164874
+ const summary2 = chat.teklaModelRead && isBound(chat, spec) ? teklaReadApprovalSummary(chat.teklaModelRead, TEKLA_TOOL_OPERATIONS[spec.name], chat.owner.kind === "project") : this.unboundText(toolName);
164207
164875
  return { summary: summary2, explicitOnly: true, tool: spec.name };
164208
164876
  }
164209
164877
  const binding = chat.integrationBindings.find((candidate2) => candidate2.integration === spec.integration);
@@ -171207,7 +171875,7 @@ function requestScratchLiveness(request) {
171207
171875
  failure2 = error62;
171208
171876
  }
171209
171877
  if (state3 === "unreadable") {
171210
- if (chatIsGone(failure2)) return "idle";
171878
+ if (chatIsGone(failure2)) return "gone";
171211
171879
  if (!reportedUnreadableScratch.has(request.id)) {
171212
171880
  reportedUnreadableScratch.add(request.id);
171213
171881
  console.warn(`[request-work] cannot read the conversation of request ${request.id}; keeping its scratch until it can be read:`, failure2);
@@ -171221,6 +171889,12 @@ function chatIsGone(error62) {
171221
171889
  const e = error62;
171222
171890
  return e.name === "ChatStoreError" && e.status === 404 && typeof e.message === "string" && e.message.startsWith("unknown chat:");
171223
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
+ }
171224
171898
  function scratchLivenessForChatState(state3) {
171225
171899
  if (state3 === null) return "unobservable";
171226
171900
  if (state3 === "unreadable") return "live";
@@ -190614,9 +191288,7 @@ var init_complete_model_report_controller = __esm({
190614
191288
  function isReportLockDirectoryName(name) {
190615
191289
  return name.endsWith(".lock") || LOCK_RESIDUE.test(name);
190616
191290
  }
190617
- function secureCompleteReportRoot(root9) {
190618
- (0, import_node_fs105.mkdirSync)(root9, { recursive: true, mode: 448 });
190619
- ensureOwnerOnlyStoragePath(root9, "directory");
191291
+ function reportRootChildren(root9) {
190620
191292
  const children = [];
190621
191293
  for (const name of (0, import_node_fs105.readdirSync)(root9)) {
190622
191294
  const path = (0, import_node_path103.join)(root9, name);
@@ -190626,7 +191298,17 @@ function secureCompleteReportRoot(root9) {
190626
191298
  else if (stat4.isDirectory() && isReportLockDirectoryName(name)) children.push({ path, kind: "directory" });
190627
191299
  else throw new Error("Complete report private storage contains an unexpected entry.");
190628
191300
  }
190629
- 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));
190630
191312
  }
190631
191313
  var import_node_fs105, import_node_path103, LOCK_RESIDUE;
190632
191314
  var init_complete_report_private_storage = __esm({
@@ -190908,7 +191590,7 @@ var init_complete_report_registry = __esm({
190908
191590
  }
190909
191591
  async ensureRoot() {
190910
191592
  if (!this.secured) {
190911
- secureCompleteReportRoot(this.root);
191593
+ await secureCompleteReportRootAsync(this.root);
190912
191594
  this.secured = true;
190913
191595
  }
190914
191596
  }
@@ -191397,7 +192079,7 @@ var init_complete_report_quota = __esm({
191397
192079
  }
191398
192080
  async setup() {
191399
192081
  if (!this.secured) {
191400
- secureCompleteReportRoot(this.root);
192082
+ await secureCompleteReportRootAsync(this.root);
191401
192083
  this.secured = true;
191402
192084
  }
191403
192085
  }
@@ -191664,6 +192346,13 @@ var init_complete_report_run_journal = __esm({
191664
192346
  this.secured = true;
191665
192347
  }
191666
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
+ }
191667
192356
  path(id2) {
191668
192357
  if (!ID4.test(id2)) throw new ReportRunJournalError();
191669
192358
  return (0, import_node_path106.join)(this.root, `${id2}.json`);
@@ -192111,6 +192800,16 @@ var init_complete_report_runtime_clock = __esm({
192111
192800
  sample(monotonicNowMs = import_node_perf_hooks4.performance.now()) {
192112
192801
  if (!Number.isFinite(monotonicNowMs) || monotonicNowMs < 0) throw new ReportRuntimeClockError();
192113
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) {
192114
192813
  return withSecurityStateLock(this.path, () => {
192115
192814
  const active2 = readState(this.activePath);
192116
192815
  if (active2 !== null) {
@@ -192281,6 +192980,14 @@ var init_complete_report_retired_store = __esm({
192281
192980
  }
192282
192981
  list() {
192283
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() {
192284
192991
  const entries = (0, import_node_fs111.readdirSync)(this.root);
192285
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();
192286
192993
  return entries.filter((name) => name.endsWith(".json")).sort().map((name) => {
@@ -192425,7 +193132,7 @@ async function auditTombstone(tombstone, deps, bootId) {
192425
193132
  async function maintainReportHistory(deps, mode, maxDue = 4, allowNewRetirement = true) {
192426
193133
  const bootId = deps.bootId();
192427
193134
  const retiring = deps.journal.list().filter((row2) => row2.state === "retiring");
192428
- const tombstones = deps.retired.list();
193135
+ const tombstones = await deps.retired.listAsync();
192429
193136
  if (mode === "boot") {
192430
193137
  for (const row2 of retiring) await deps.quota.restoreRetirementCharge(row2.id, row2.budget);
192431
193138
  for (const tombstone of tombstones) await deps.quota.restoreRetirementCharge(tombstone.id, tombstone.row.budget);
@@ -192455,7 +193162,7 @@ async function maintainReportHistory(deps, mode, maxDue = 4, allowNewRetirement
192455
193162
  if (!allowNewRetirement) return;
192456
193163
  let observed;
192457
193164
  try {
192458
- observed = deps.observedRuntimeMs();
193165
+ observed = await deps.observedRuntimeMs();
192459
193166
  } catch (error62) {
192460
193167
  deps.onError?.("manual-expiry", error62);
192461
193168
  return;
@@ -192983,28 +193690,85 @@ function registerRequestListRoute(app, deps) {
192983
193690
  const mark = (stage) => {
192984
193691
  stages[stage] = Math.round(import_node_perf_hooks5.performance.now() - startedAt);
192985
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;
192986
193698
  const stored2 = deps.listRequests();
192987
193699
  mark("list");
192988
193700
  const published = /* @__PURE__ */ new Map();
192989
- const readScope = deps.readScope ?? ((fn2) => fn2());
193701
+ const ownerGone = /* @__PURE__ */ new Set();
192990
193702
  const answered = deps.publishAnswer ? stored2.flatMap((request) => {
192991
193703
  const answer = validatedRequestAnswer(request);
192992
193704
  const provider3 = request.run?.runtime;
192993
193705
  return answer && (provider3 === "claude" || provider3 === "codex") ? [{ request, answer, provider: provider3 }] : [];
192994
193706
  }) : [];
192995
193707
  let toPublish = [];
192996
- 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() {
192997
193760
  for (const { request, answer } of answered) {
192998
193761
  try {
192999
193762
  const link2 = deps.publishedAnswer?.(request, answer);
193000
193763
  if (link2) published.set(request.id, link2);
193001
- } catch {
193764
+ } catch (error62) {
193765
+ if (deps.ownerGone?.(error62)) ownerGone.add(request.id);
193002
193766
  }
193767
+ yield;
193003
193768
  }
193004
- 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));
193005
193770
  if (answered.length) mark("published-check");
193006
- };
193007
- const projectRows = () => {
193771
+ if (toPublish.length) yield PUBLISH;
193008
193772
  const chatPublications = stored2.flatMap((request) => {
193009
193773
  const result2 = validatedRequestAnswer(request);
193010
193774
  if (!result2) return [];
@@ -193018,92 +193782,76 @@ function registerRequestListRoute(app, deps) {
193018
193782
  answerEventId: link2.answerEventId
193019
193783
  }];
193020
193784
  });
193021
- const requestRows = deps.requestViews(stored2.filter((request) => {
193785
+ const unpublished = stored2.filter((request) => {
193022
193786
  const answer = validatedRequestAnswer(request);
193023
193787
  return !answer || !published.has(request.id);
193024
- }));
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
+ }
193025
193794
  mark("views");
193026
193795
  const byId2 = new Map(stored2.map((request) => [request.id, request]));
193027
193796
  for (const row2 of requestRows) {
193028
- const request = typeof row2.id === "string" ? byId2.get(row2.id) : void 0;
193029
- if (request && (isFilterAiChangeRequest(request) || isFilterAiQuestionRequest(request))) {
193030
- row2.filterAiAdmissionUnconfirmed = filterAiAdmissionUnconfirmed(request);
193031
- row2.filterAiNotStarted = readFilterAiNotStarted(request) !== null;
193032
- }
193033
- const warnOnce = (requestId, phase2, error62) => {
193034
- const key5 = `${requestId ?? ""}:${phase2}`;
193035
- if (requestId && warnedInvalidChatLinks.has(key5)) return;
193036
- if (requestId && warnedInvalidChatLinks.size >= MAX_WARNED_CHAT_KEYS) {
193037
- if (warnedInvalidChatLinks.has(WARN_SATURATED)) return;
193038
- app.log.error(
193039
- { cap: MAX_WARNED_CHAT_KEYS },
193040
- "too many Requests have unreadable chat sidecars to report one by one \u2014 later ones are shown on their rows only"
193041
- );
193042
- warnedInvalidChatLinks.add(WARN_SATURATED);
193043
- return;
193044
- }
193045
- app.log.error(
193046
- { requestId, phase: phase2, err: String(error62) },
193047
- phase2 === "link" ? "could not read Request chat link" : "could not read Request chat state"
193048
- );
193049
- if (requestId) warnedInvalidChatLinks.add(key5);
193050
- };
193051
- let link2;
193052
- let chatState = null;
193053
- try {
193054
- link2 = request ? deps.chatLink?.(request) : null;
193055
- } catch (error62) {
193056
- warnOnce(request?.id, "link", error62);
193057
- 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;
193058
193811
  }
193059
- 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();
193060
193835
  try {
193061
- 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);
193062
193843
  } catch (error62) {
193063
- warnOnce(request.id, "state", error62);
193064
- chatState = "unreadable";
193065
- }
193066
- }
193067
- if (link2) {
193068
- if (request?.id) warnedInvalidChatLinks.delete(`${request.id}:link`);
193069
- if (request?.id && chatState !== "unreadable") warnedInvalidChatLinks.delete(`${request.id}:state`);
193070
- row2.chatConversation = {
193071
- chatId: link2.chatId,
193072
- executionOwner: link2.executionOwner,
193073
- chatState,
193074
- answerEventId: link2.answerEventId ?? null
193075
- };
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();
193076
193848
  }
193849
+ mark("publish");
193850
+ pass = openPass();
193851
+ continue;
193077
193852
  }
193078
- mark("chat-links");
193079
- return { ok: true, requests: requestRows, chatPublications };
193080
- };
193081
- let body = readScope(() => {
193082
- checkPublished();
193083
- return toPublish.length === 0 ? projectRows() : null;
193084
- });
193085
- if (!body) {
193086
- await Promise.all(toPublish.map(async ({ request, answer, provider: provider3 }) => {
193087
- try {
193088
- const link2 = await withLifecycleLock(
193089
- "internal-export",
193090
- `request-${request.id}`,
193091
- () => deps.publishAnswer({ request, answer, provider: provider3 }),
193092
- { label: "publishing Request answer to chat" }
193093
- );
193094
- if (link2) published.set(request.id, link2);
193095
- } catch (error62) {
193096
- app.log.error({ requestId: request.id, err: String(error62) }, "could not publish Request answer to AI Chat");
193097
- }
193098
- }));
193099
- mark("publish");
193100
- body = readScope(projectRows);
193853
+ await yieldToEventLoop();
193101
193854
  }
193102
- const totalMs = Math.round(import_node_perf_hooks5.performance.now() - startedAt);
193103
- if (totalMs >= (deps.slowMs ?? SLOW_REQUEST_LIST_MS)) {
193104
- app.log.warn({ totalMs, stages, requests: stored2.length, lockedPublishes: toPublish.length }, "slow Requests list read");
193105
- }
193106
- return body;
193107
193855
  }
193108
193856
  let inFlight2 = null;
193109
193857
  let queued = null;
@@ -193122,7 +193870,7 @@ function registerRequestListRoute(app, deps) {
193122
193870
  }
193123
193871
  app.get("/api/requests", () => coalescedList());
193124
193872
  }
193125
- 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;
193126
193874
  var init_request_list_route = __esm({
193127
193875
  "request-list-route.ts"() {
193128
193876
  "use strict";
@@ -193130,7 +193878,14 @@ var init_request_list_route = __esm({
193130
193878
  init_instructor_request();
193131
193879
  init_lifecycle_lock();
193132
193880
  init_filter_ai_request();
193881
+ init_read_scope();
193133
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
+ });
193134
193889
  }
193135
193890
  });
193136
193891
 
@@ -195254,6 +196009,7 @@ var init_model_editor_state = __esm({
195254
196009
  // model-project-deletion.ts
195255
196010
  async function deleteArchivedModelProject(options2) {
195256
196011
  const { module: module2, projectUuid } = options2;
196012
+ options2.assertProjectRemovable();
195257
196013
  if (projectUuid && (module2 === "revit" || module2 === "tekla")) {
195258
196014
  await options2.deleteEditorState(projectUuid);
195259
196015
  }
@@ -196813,6 +197569,7 @@ var init_revit_import = __esm({
196813
197569
  init_durable_replace();
196814
197570
  init_lifecycle_lock();
196815
197571
  init_projects_store();
197572
+ init_read_scope();
196816
197573
  init_revit_project_lock();
196817
197574
  init_revit_project_lifecycle();
196818
197575
  init_revit_reader_trust();
@@ -197060,7 +197817,14 @@ var init_revit_import = __esm({
197060
197817
  let authorizationRetained = 0;
197061
197818
  const accessRetained = /* @__PURE__ */ new Set();
197062
197819
  const retainedJournalOperations = /* @__PURE__ */ new Set();
197063
- 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) {
197064
197828
  let retainedOperationId = null;
197065
197829
  try {
197066
197830
  const path = (0, import_node_path117.join)(projectDir(project.id), PUBLICATION_JOURNAL);
@@ -207218,25 +207982,45 @@ function writePin(appId, pin) {
207218
207982
  return withPinLock(() => writePinUnlocked(appId, pin));
207219
207983
  }
207220
207984
  function reconcileWorkflowKnowledgeRetention() {
207221
- if (!(0, import_node_fs136.existsSync)(pinsDir())) return 0;
207222
- 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
+ });
207223
207996
  for (const entry2 of (0, import_node_fs136.readdirSync)(pinsDir(), { withFileTypes: true })) {
207224
207997
  if (!entry2.isFile() || !entry2.name.endsWith(".json")) continue;
207225
207998
  const appId = (0, import_node_path132.basename)(entry2.name, ".json");
207226
- const pin = readPinUnlocked(appId);
207227
- if (!pin) throw new KbPinError(`stored workflow Knowledge pin is unreadable: ${appId}`, "invalid-pages");
207228
- if (!pin.retentionPinId) continue;
207229
- const retention = reconcileGenerationRetentionPin(pin.projectId, {
207230
- pinId: pin.retentionPinId,
207231
- generationId: pin.generationId,
207232
- ownerKind: "workflow",
207233
- ownerId: appId,
207234
- pages: pin.pages.map((page) => page.slug)
207235
- });
207236
- if (retention.state !== "committed") commitGenerationRetentionPin(pin.projectId, retention.pinId);
207237
- 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
+ }
207238
208022
  }
207239
- return count4;
208023
+ return result2;
207240
208024
  }
207241
208025
  function movePinBytesUnlocked(fromAppId, toAppId) {
207242
208026
  const from = pinPath(fromAppId);
@@ -207280,6 +208064,8 @@ var init_kb_pin_store = __esm({
207280
208064
  import_node_path132 = require("node:path");
207281
208065
  import_node_os62 = require("node:os");
207282
208066
  init_knowledge_store();
208067
+ init_projects_store();
208068
+ init_read_scope();
207283
208069
  init_write_json_atomic();
207284
208070
  init_lifecycle_lock();
207285
208071
  KbPinError = class extends Error {
@@ -207680,7 +208466,8 @@ function registerCompleteReportDiscoveryRoute(app, deps) {
207680
208466
  deps.authorizeEditor(request);
207681
208467
  if (!deps.ready()) return reply.status(503).send({
207682
208468
  ok: false,
207683
- 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."
207684
208471
  });
207685
208472
  const routine = deps.routine(request.params.routineId);
207686
208473
  if (!routine || routine.workflow !== "tekla-model-report" && routine.workflow !== "floless-workspace-model-report") {
@@ -213837,6 +214624,82 @@ var init_workspace_mutation_recovery = __esm({
213837
214624
  }
213838
214625
  });
213839
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
+
213840
214703
  // workspace-aware-process.ts
213841
214704
  function operationOwner(spec) {
213842
214705
  const root9 = activeWorkspaceRoot();
@@ -226585,7 +227448,7 @@ async function probeClaudeRuntime() {
226585
227448
  }
226586
227449
  if (launch.managed) return { binary: launch.file, version: TESTED_CLAUDE_VERSION, managed: true };
226587
227450
  const binary = launch.file;
226588
- 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 });
226589
227452
  const version2 = cleanText(result2.stdout, 256).match(/\d+\.\d+\.\d+/u)?.[0] ?? "";
226590
227453
  if (version2 !== TESTED_CLAUDE_VERSION) {
226591
227454
  throw new Error(`FloLess supports Claude Code ${TESTED_CLAUDE_VERSION}; installed version is ${version2 || "unknown"}`);
@@ -226634,7 +227497,7 @@ function terminalReceipt(chat, turn) {
226634
227497
  error: cleanText(event.payload.terminalError, 8192) || "Claude turn failed"
226635
227498
  };
226636
227499
  }
226637
- 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;
226638
227501
  var init_chat_provider_claude = __esm({
226639
227502
  "chat-provider-claude.ts"() {
226640
227503
  "use strict";
@@ -226652,7 +227515,7 @@ var init_chat_provider_claude = __esm({
226652
227515
  init_managed_runtime();
226653
227516
  init_managed_runtime_pins();
226654
227517
  init_chat_provider();
226655
- execFile14 = (0, import_node_util13.promisify)(import_node_child_process29.execFile);
227518
+ execFile15 = (0, import_node_util13.promisify)(import_node_child_process29.execFile);
226656
227519
  CLAUDE_PROBE_TIMEOUT = "Claude capability check timed out";
226657
227520
  READ_ONLY_TOOLS = ["Read", "Glob", "Grep", "WebFetch", "WebSearch"];
226658
227521
  ISOLATED_READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
@@ -227512,7 +228375,7 @@ async function probeCodexRuntime() {
227512
228375
  }
227513
228376
  if (launch.managed) return { binary: launch.file, version: CODEX_HEADLESS_VERSION.replace(/^codex-cli\s+/u, ""), env: launch.env, managed: true };
227514
228377
  const binary = launch.file;
227515
- 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 });
227516
228379
  const version2 = cleanText2(result2.stdout, 256).replace(/^codex-cli\s+/u, "");
227517
228380
  if (`codex-cli ${version2}` !== CODEX_HEADLESS_VERSION) {
227518
228381
  throw new Error(`FloLess supports ${CODEX_HEADLESS_VERSION}; installed Codex is ${version2 || "unknown"}`);
@@ -227567,7 +228430,7 @@ function codexItemEvent(itemValue, sawDelta) {
227567
228430
  if (type === "contextCompaction") return { providerItemId: id2, type: "compaction", payload: { provider: "codex" } };
227568
228431
  return null;
227569
228432
  }
227570
- 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;
227571
228434
  var init_chat_provider_codex = __esm({
227572
228435
  "chat-provider-codex.ts"() {
227573
228436
  "use strict";
@@ -227583,7 +228446,7 @@ var init_chat_provider_codex = __esm({
227583
228446
  init_terminal_runtime();
227584
228447
  init_managed_runtime();
227585
228448
  init_chat_provider();
227586
- execFile15 = (0, import_node_util14.promisify)(import_node_child_process30.execFile);
228449
+ execFile16 = (0, import_node_util14.promisify)(import_node_child_process30.execFile);
227587
228450
  MAX_PROTOCOL_LINE = 16 * 1024 * 1024;
227588
228451
  REQUEST_TIMEOUT_MS2 = 3e4;
227589
228452
  TURN_TIMEOUT_MS = 24 * 60 * 60 * 1e3;
@@ -228402,7 +229265,7 @@ async function defaultExec(file2, args, env2) {
228402
229265
  const batch = process.platform === "win32" && /\.(cmd|bat)$/iu.test(file2);
228403
229266
  const [exe2, argv] = batch ? ["cmd.exe", ["/d", "/s", "/c", file2, ...args]] : [file2, [...args]];
228404
229267
  try {
228405
- 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 });
228406
229269
  return { stdout, stderr, code: 0 };
228407
229270
  } catch (error62) {
228408
229271
  return execOutcome(error62);
@@ -228425,7 +229288,7 @@ function unrecognisedDetail(reason, result2) {
228425
229288
  const output2 = snippet(`${result2.stderr} ${result2.stdout}`);
228426
229289
  return output2 ? `${reason} (exit ${result2.code}: ${output2})` : `${reason} (exit ${result2.code}, no output)`;
228427
229290
  }
228428
- 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;
228429
229292
  var init_provider_sign_in = __esm({
228430
229293
  "provider-sign-in.ts"() {
228431
229294
  "use strict";
@@ -228435,7 +229298,7 @@ var init_provider_sign_in = __esm({
228435
229298
  import_node_util15 = require("node:util");
228436
229299
  init_provider_home();
228437
229300
  init_terminal_runtime();
228438
- execFile16 = (0, import_node_util15.promisify)(import_node_child_process31.execFile);
229301
+ execFile17 = (0, import_node_util15.promisify)(import_node_child_process31.execFile);
228439
229302
  CLAUDE_UNRECOGNISED = "unrecognised claude auth status output";
228440
229303
  CODEX_UNRECOGNISED = "unrecognised codex login status output";
228441
229304
  SIGN_IN_CACHE_MS = 1e4;
@@ -230473,6 +231336,22 @@ var init_chat_integration_relay = __esm({
230473
231336
  });
230474
231337
 
230475
231338
  // chat-tekla-read-relay.ts
231339
+ function newestLinkedParts(links, limit = TEKLA_LINKED_PART_CHECK_LIMIT) {
231340
+ const ids2 = [];
231341
+ const seen = /* @__PURE__ */ new Set();
231342
+ for (const link2 of [...links].sort((a, b) => b.createdAt.localeCompare(a.createdAt))) {
231343
+ if (seen.has(link2.id)) continue;
231344
+ seen.add(link2.id);
231345
+ ids2.push(link2.id);
231346
+ }
231347
+ return { ids: ids2.slice(0, limit), unchecked: Math.max(0, ids2.length - limit) };
231348
+ }
231349
+ async function teklaLinkedPartsToCheck(owner3) {
231350
+ if (owner3.kind !== "project") return null;
231351
+ const listed = await listChatSubjectLinks(owner3, "tekla");
231352
+ const found = newestLinkedParts(listed.links);
231353
+ return listed.partial ? { ...found, partial: true } : found;
231354
+ }
230476
231355
  function ownerInput6(chat) {
230477
231356
  return chat.owner.kind === "project" ? { kind: "project", projectId: chat.owner.projectId } : { kind: "workflow", workflowId: chat.owner.workflowId };
230478
231357
  }
@@ -230491,24 +231370,27 @@ function canonicalJson2(value) {
230491
231370
  }
230492
231371
  function differingCardFields(recorded, own5) {
230493
231372
  const mine = own5;
230494
- const keys = [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(mine)])].filter((key5) => key5 !== "approvalId");
231373
+ const skip = /* @__PURE__ */ new Set(["approvalId", "linkedQuestion", ...LINKED_PART_CHECK_FIELDS]);
231374
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(mine)])].filter((key5) => !skip.has(key5));
230495
231375
  return keys.filter((key5) => canonicalJson2(recorded[key5]) !== canonicalJson2(mine[key5])).sort();
230496
231376
  }
230497
231377
  function refusalMessage(result2) {
230498
231378
  return result2.code === "busy" ? "Another Tekla read was already running, so FloLess used this approval without reading the model. Ask again when the other read finishes." : result2.message;
230499
231379
  }
230500
- var NOT_VERIFIED, LEDGER_LIMIT, DEFAULT_DEPS8, READ_FAILED_MESSAGE, RECORD_FAILED_MESSAGE, STOPPED_MESSAGE, UNREAD_RECORD_CODES, ChatTeklaReadRelay;
231380
+ var NOT_VERIFIED, LEDGER_LIMIT, DEFAULT_DEPS8, READ_FAILED_MESSAGE, RECORD_FAILED_MESSAGE, STOPPED_MESSAGE, UNREAD_RECORD_CODES, LINKED_PART_CHECK_FIELDS, ChatTeklaReadRelay;
230501
231381
  var init_chat_tekla_read_relay = __esm({
230502
231382
  "chat-tekla-read-relay.ts"() {
230503
231383
  "use strict";
230504
231384
  init_chat_store();
230505
231385
  init_chat_integration_tools();
231386
+ init_chat_subject_link();
230506
231387
  init_tekla_library_read();
230507
231388
  init_chat_types();
230508
231389
  NOT_VERIFIED = "The generated Graft agent and its other commands were not run or verified.";
230509
231390
  LEDGER_LIMIT = 256;
230510
231391
  DEFAULT_DEPS8 = {
230511
- read: (sourcePath2, operation, signal) => runTeklaLibraryRead(sourcePath2, { signal, operation }),
231392
+ read: (sourcePath2, operation, signal, linkedParts) => runTeklaLibraryRead(sourcePath2, { signal, operation, ...linkedParts ? { linkedParts } : {} }),
231393
+ linkedParts: teklaLinkedPartsToCheck,
230512
231394
  append: appendChatTeklaReadIfTurnCurrent,
230513
231395
  publish: () => {
230514
231396
  },
@@ -230519,6 +231401,7 @@ var init_chat_tekla_read_relay = __esm({
230519
231401
  RECORD_FAILED_MESSAGE = "FloLess could not record the check, so this result is not verified. Ask again.";
230520
231402
  STOPPED_MESSAGE = "The Tekla read was stopped before it finished. Ask again if you still need it.";
230521
231403
  UNREAD_RECORD_CODES = ["chat-record-unreadable", "chat-record-unsafe"];
231404
+ LINKED_PART_CHECK_FIELDS = ["linkedPartsChecked", "missingLinkedParts", "linkedPartsUnchecked", "linkedPartsCheck"];
230522
231405
  ChatTeklaReadRelay = class {
230523
231406
  deps;
230524
231407
  /** approvalId -> the one outcome of that approval. At most one host read per approval in this process. */
@@ -230578,7 +231461,7 @@ var init_chat_tekla_read_relay = __esm({
230578
231461
  }
230579
231462
  const operation = TEKLA_TOOL_OPERATIONS[approval.tool];
230580
231463
  const binding = chat.teklaModelRead;
230581
- if (!binding || !binding.operations.includes(operation) || teklaReadApprovalSummary(binding, operation) !== approval.summary) {
231464
+ if (!binding || !binding.operations.includes(operation) || teklaReadApprovalSummary(binding, operation, chat.owner.kind === "project") !== approval.summary) {
230582
231465
  this.deps.log("the bound Tekla library did not match the approval, so the read was refused", {
230583
231466
  approvalId,
230584
231467
  chatId: chat.chatId,
@@ -230587,20 +231470,39 @@ var init_chat_tekla_read_relay = __esm({
230587
231470
  return unverified("library-not-bound", "The Tekla model library for this chat changed or was removed, so FloLess did not read the model. Verify the model read again in Graft into agent, then choose Continue in AI Chat.");
230588
231471
  }
230589
231472
  const signal = input2.signal;
230590
- const result2 = await this.deps.read(binding.sourcePath, operation, signal);
231473
+ let linked = null;
231474
+ let listing;
231475
+ if (operation === TEKLA_SELECTION_READ_OPERATION) {
231476
+ try {
231477
+ linked = await this.deps.linkedParts(owner3);
231478
+ if (linked?.partial) listing = "partial";
231479
+ } catch (error62) {
231480
+ listing = "unavailable";
231481
+ this.deps.log("the parts linked to earlier questions could not be listed, so this read checks none", {
231482
+ approvalId,
231483
+ chatId: chat.chatId,
231484
+ error: error62 instanceof Error ? error62.message : String(error62)
231485
+ });
231486
+ }
231487
+ }
231488
+ const result2 = await this.deps.read(binding.sourcePath, operation, signal, linked?.ids);
230591
231489
  if (signal?.aborted) return unverified("stopped", STOPPED_MESSAGE);
230592
231490
  const base2 = { approvalId, operation, library: binding.sourcePath, hostVersion: binding.hostVersion };
230593
231491
  let payload;
230594
231492
  if (!result2.ok) {
230595
231493
  payload = { ...base2, status: "unverified", checkedAt: this.deps.now(), code: result2.code, message: refusalMessage(result2) };
230596
231494
  } else if (operation === TEKLA_SELECTION_READ_OPERATION && result2.verification.operation === operation && result2.verification.selection) {
231495
+ const selection = result2.verification.selection;
231496
+ const check3 = selection.linkedPartsCheck ?? listing;
230597
231497
  payload = {
230598
231498
  ...base2,
230599
231499
  status: "verified-for-selection-read",
230600
231500
  checkedAt: result2.verification.verifiedAt,
230601
231501
  modelName: result2.verification.modelName,
230602
231502
  hostPid: result2.verification.hostPid,
230603
- ...result2.verification.selection
231503
+ ...selection,
231504
+ ...linked?.unchecked && selection.missingLinkedParts ? { linkedPartsUnchecked: linked.unchecked } : {},
231505
+ ...check3 ? { linkedPartsCheck: check3 } : {}
230604
231506
  };
230605
231507
  } else if (operation !== TEKLA_SELECTION_READ_OPERATION && result2.verification.operation === operation) {
230606
231508
  payload = {
@@ -230658,8 +231560,15 @@ var init_chat_tekla_read_relay = __esm({
230658
231560
  } catch {
230659
231561
  }
230660
231562
  if (!result2.ok) return unverified(result2.code, refusalMessage(result2));
230661
- const { approvalId: _approvalId, ...card } = payload;
230662
- return { success: true, text: JSON.stringify({ ...card, notVerified: NOT_VERIFIED }) };
231563
+ const recordedCard = appended.event.payload;
231564
+ const { approvalId: _approvalId, ...own5 } = payload;
231565
+ const card = { ...own5 };
231566
+ for (const key5 of LINKED_PART_CHECK_FIELDS) {
231567
+ if (recordedCard[key5] === void 0) delete card[key5];
231568
+ else card[key5] = recordedCard[key5];
231569
+ }
231570
+ const linkedToQuestion = Boolean(recordedCard.linkedQuestion);
231571
+ return { success: true, text: JSON.stringify({ ...card, notVerified: NOT_VERIFIED, ...linkedToQuestion ? { linkHint: TEKLA_LINK_HINT } : {} }) };
230663
231572
  }
230664
231573
  };
230665
231574
  }
@@ -230911,6 +231820,9 @@ function beginGoogleConnectFenceLifetime(options2) {
230911
231820
  }
230912
231821
  async function startServer() {
230913
231822
  installCrashHandlers();
231823
+ const bootStartedAt = Date.now();
231824
+ const bootPhases = {};
231825
+ let bootPhaseStarted = bootStartedAt;
230914
231826
  const logger = true ? true : { transport: { target: "pino-pretty" } };
230915
231827
  const app = (0, import_fastify.default)({ logger });
230916
231828
  if (productionDistributionProfile.features.providerDiscovery && !process.env.AWARE_MODEL_REFERENCE_PROVIDER) {
@@ -231843,6 +232755,9 @@ async function startServer() {
231843
232755
  if (err2 instanceof EditorSessionAuthError) {
231844
232756
  return reply.status(err2.status).send({ ok: false, error: err2.code, message: err2.message });
231845
232757
  }
232758
+ if (err2 instanceof ProjectFolderInUseError) {
232759
+ return reply.status(409).send({ ok: false, error: err2.message, code: err2.code });
232760
+ }
231846
232761
  if (err2 instanceof ProjectError) {
231847
232762
  return reply.status(400).send({ ok: false, error: err2.message });
231848
232763
  }
@@ -231951,6 +232866,9 @@ async function startServer() {
231951
232866
  rvtDefaults: rvtDefaultAppsStatus().status,
231952
232867
  coreDefaults: rvtCoreAppsStatus().status,
231953
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() },
231954
232872
  license: (await getLicenseStatus2()).state
231955
232873
  // UI + launcher branch on this
231956
232874
  };
@@ -232721,10 +233639,10 @@ async function startServer() {
232721
233639
  projectName: requestProjectName(x)
232722
233640
  }));
232723
233641
  const requestViews = (list3) => {
232724
- const root9 = templateIdResolver();
232725
- const nameMemo = /* @__PURE__ */ new Map();
232726
- const headMemo = /* @__PURE__ */ new Map();
232727
- 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());
232728
233646
  const headVersion = (project) => {
232729
233647
  const cached2 = headMemo.get(project);
232730
233648
  if (cached2 !== void 0) return cached2;
@@ -232916,6 +233834,10 @@ async function startServer() {
232916
233834
  else if (identity4) initializeDuplicatedRevitProject(project.id, identity4.accountId, identity4.entitlementRevision);
232917
233835
  }
232918
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
+ }
232919
233841
  app.post("/api/projects/:id/archive", async (req, reply) => {
232920
233842
  try {
232921
233843
  return await withProjectMutationLock(req.params.id, async (locked) => {
@@ -232931,6 +233853,7 @@ async function startServer() {
232931
233853
  return { ok: true };
232932
233854
  });
232933
233855
  } catch (e) {
233856
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
232934
233857
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
232935
233858
  if (e instanceof ChatCoordinatorError) return reply.status(e.status).send({ ok: false, error: e.message, code: e.code });
232936
233859
  throw e;
@@ -232977,6 +233900,7 @@ async function startServer() {
232977
233900
  }
232978
233901
  return restored;
232979
233902
  } catch (e) {
233903
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
232980
233904
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
232981
233905
  throw e;
232982
233906
  }
@@ -232992,6 +233916,7 @@ async function startServer() {
232992
233916
  await deleteArchivedModelProject({
232993
233917
  module: archived ? moduleForTemplate(resolveTemplateId(archived.app))?.key ?? null : null,
232994
233918
  projectUuid: archived?.uuid ?? null,
233919
+ assertProjectRemovable: () => assertArchivedProjectRemovable(projectId2),
232995
233920
  deleteEditorState: (uuid5) => modelEditorStateStore.deleteProject(uuid5),
232996
233921
  deleteProject: () => deleteArchivedProject(projectId2),
232997
233922
  releaseRevitSource: (uuid5) => modelSourceStore.releaseProject(uuid5)
@@ -232999,6 +233924,7 @@ async function startServer() {
232999
233924
  return { ok: true };
233000
233925
  });
233001
233926
  } catch (e) {
233927
+ if (e instanceof ProjectFolderInUseError) return projectFolderInUseReply(reply, req.params.id, e);
233002
233928
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
233003
233929
  throw e;
233004
233930
  }
@@ -234295,6 +235221,7 @@ ${view.prompt}` : "";
234295
235221
  const completeReportRuntimeClock = new CompleteReportRuntimeClock((0, import_node_path145.join)(completeReportRoot, "runtime-clock"));
234296
235222
  const completeReportRetired = new CompleteReportRetiredStore((0, import_node_path145.join)(completeReportRoot, "retired"));
234297
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.";
234298
235225
  let nextReportHistoryAt = 0;
234299
235226
  const reportHistoryPruneAvailable = () => {
234300
235227
  const installed = awareInstalledVersion();
@@ -234340,7 +235267,7 @@ ${view.prompt}` : "";
234340
235267
  if (!completeReportReady) throw new WorkspaceModelQueryError(
234341
235268
  503,
234342
235269
  "model-report-recovery-pending",
234343
- "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
234344
235271
  );
234345
235272
  const selection = parseCompleteReportSelection(body);
234346
235273
  const context = activeCompleteReportRun;
@@ -234568,6 +235495,7 @@ ${view.prompt}` : "";
234568
235495
  function resumeDeferredRevitPublications(access, force = false) {
234569
235496
  return deferredRevitRecoveryDriver.onAccess(access, force);
234570
235497
  }
235498
+ bootPhaseStarted = Date.now();
234571
235499
  try {
234572
235500
  const boot = await revitImportOrchestrator.recoverAtStartup();
234573
235501
  if (boot.retained > 0) deferredRevitRecoveryDriver.notePendingWork();
@@ -234575,6 +235503,7 @@ ${view.prompt}` : "";
234575
235503
  app.log.error({ err: error62 instanceof Error ? error62.message : error62 }, "Revit import recovery failed");
234576
235504
  deferredRevitRecoveryDriver.notePendingWork();
234577
235505
  }
235506
+ bootPhases.revitImportRecovery = Date.now() - bootPhaseStarted;
234578
235507
  if (workspaceRootState().available) {
234579
235508
  for (const project of listProjects()) {
234580
235509
  if (moduleForTemplate(resolveTemplateId(project.app))?.key !== "revit" || !project.uuid) continue;
@@ -237447,6 +238376,9 @@ ${view.prompt}` : "";
237447
238376
  }
237448
238377
  });
237449
238378
  }
238379
+ function isCompleteReportTemplate(templateId) {
238380
+ return templateId === "tekla-model-report" || templateId === "floless-workspace-model-report";
238381
+ }
237450
238382
  async function prepareCompleteReportRun(id2, inputs, controller, routineId) {
237451
238383
  const template = resolveTemplateId(id2);
237452
238384
  const module2 = template === "tekla-model-report" ? "tekla" : template === "floless-workspace-model-report" ? "revit" : null;
@@ -237454,7 +238386,7 @@ ${view.prompt}` : "";
237454
238386
  if (!completeReportReady) throw new WorkspaceModelQueryError(
237455
238387
  503,
237456
238388
  "model-report-recovery-pending",
237457
- "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
237458
238390
  );
237459
238391
  if (id2 !== template) throw new WorkspaceModelQueryError(
237460
238392
  409,
@@ -237654,6 +238586,11 @@ ${view.prompt}` : "";
237654
238586
  if (row2?.state === "reserved" || row2?.state === "running") completeReportRunJournal.finishSettlement(context.reservationId);
237655
238587
  }
237656
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
+ );
237657
238594
  return withLifecycleLock("internal-export", "complete-report-recovery", async () => {
237658
238595
  const guard = {
237659
238596
  controller: new AbortController(),
@@ -237890,6 +238827,9 @@ ${view.prompt}` : "";
237890
238827
  const model = id2 === "tekla-parser" ? "Tekla" : "Revit";
237891
238828
  return reply.status(403).send({ ok: false, error: `${model} conversion must start from its project Source step`, code: "setup-unavailable" });
237892
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
+ }
237893
238833
  await admitInstalledWorkflowRuntime(id2);
237894
238834
  const blocked = hostRunBlocked(appProviderUncached(id2));
237895
238835
  if (blocked) return reply.send({ ok: false, error: blocked, blocked: true, simulate: !!simulate });
@@ -237972,7 +238912,7 @@ ${view.prompt}` : "";
237972
238912
  if (!completeReportReady) throw new WorkspaceModelQueryError(
237973
238913
  503,
237974
238914
  "model-report-recovery-pending",
237975
- "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
237976
238916
  );
237977
238917
  authorizeModelEditor(request);
237978
238918
  const handle = request.params.handle ?? "";
@@ -238402,7 +239342,8 @@ ${view.prompt}` : "";
238402
239342
  canPublishAnswer: (request) => requestChatOwner(request) !== null,
238403
239343
  chatLink: requestChatLink,
238404
239344
  chatState: requestChatState,
238405
- readScope: withReadScope
239345
+ ownerGone: chatOwnerIsGone,
239346
+ readPass: openReadPass
238406
239347
  });
238407
239348
  registerDesktopHandoffRoutes(app, {
238408
239349
  requestView: (id2) => requestView2(getRequest(id2)),
@@ -238458,7 +239399,9 @@ ${view.prompt}` : "";
238458
239399
  const snapshot2 = await readContractSnapshot({ appId: getProject(projectId2)?.app ?? "steel-model", projectId: projectId2 });
238459
239400
  return snapshot2 ? { revision: snapshot2.storeRevision, labels: steelSubjectLabels(snapshot2.contract) } : null;
238460
239401
  },
238461
- publish: (event) => chatCoordinator.publishEvent(event)
239402
+ publish: (event) => chatCoordinator.publishEvent(event),
239403
+ // Live Tekla parts (#1653 stage 4) are verified against this chat's own selection receipts, never the project model.
239404
+ teklaParts: (owner3, chatId, turnId) => teklaReadParts(listChatEvents(owner3, chatId), turnId)
238462
239405
  });
238463
239406
  const chatIntegrationTools = new ChatIntegrationToolHost(new ChatIntegrationRelay(chatProviders, aware), chatTeklaReadRelay, chatSubjectLinker);
238464
239407
  claudeChatProvider.setIntegrationTools(chatIntegrationTools);
@@ -238504,7 +239447,13 @@ ${view.prompt}` : "";
238504
239447
  // A new project’s first drawing request is intentionally staged before any prepass exists.
238505
239448
  // Chat is the first action that should process it, so do not apply the normal headless-run
238506
239449
  // readiness gate to this durable intake request.
238507
- canStart: (request) => request.intakeSubmissionId ? true : requestView2(request)?.canRun === true
239450
+ // An imported or existing project's first read has no intake id, and AI Chat is still the
239451
+ // interactive terminal AI its first-read refusal asks for (#1779) — so the same exception applies.
239452
+ canStart: (request) => {
239453
+ if (request.intakeSubmissionId) return true;
239454
+ const view = requestView2(request);
239455
+ return view ? chatCanStartRequest(view) : false;
239456
+ }
238508
239457
  },
238509
239458
  projectIntakes: {
238510
239459
  accepted: readAcceptedProjectChatIntake,
@@ -239032,6 +239981,7 @@ ${v.prompt}` : "";
239032
239981
  process.on("SIGTERM", () => {
239033
239982
  void shutdown("SIGTERM");
239034
239983
  });
239984
+ bootPhaseStarted = Date.now();
239035
239985
  try {
239036
239986
  if (workspaceRootState().available) {
239037
239987
  for (const line of await recoverAllProjectTransactions(() => listProjects().map((p) => p.id))) {
@@ -239043,23 +239993,41 @@ ${v.prompt}` : "";
239043
239993
  app.log.info({ error: error62.message }, "skipped project contract recovery while the selected workspace root is unavailable");
239044
239994
  } else throw error62;
239045
239995
  }
239996
+ bootPhases.contractRecovery = Date.now() - bootPhaseStarted;
239046
239997
  beginKnowledgeRetentionReconciliation();
239998
+ bootPhaseStarted = Date.now();
239047
239999
  try {
239048
240000
  if (workspaceRootState().available) {
239049
- reconcileWorkflowKnowledgeRetention();
239050
- 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();
239051
240018
  }
239052
- completeKnowledgeRetentionReconciliation();
239053
240019
  } catch (error62) {
239054
240020
  app.log.warn(
239055
240021
  { error: error62 instanceof Error ? error62.message : String(error62) },
239056
240022
  "Knowledge retention reconciliation failed; generation cleanup remains disabled"
239057
240023
  );
239058
240024
  }
240025
+ bootPhases.knowledgeRetention = Date.now() - bootPhaseStarted;
239059
240026
  async function runCompleteReportRecovery(mode) {
239060
240027
  await withLifecycleLock("internal-export", "complete-report-recovery", async () => {
240028
+ await completeReportRunJournal.prepare();
239061
240029
  const rows2 = completeReportRunJournal.list();
239062
- const tombstones = completeReportRetired.list();
240030
+ const tombstones = await completeReportRetired.listAsync();
239063
240031
  const knownHandles = /* @__PURE__ */ new Set();
239064
240032
  for (const row2 of rows2) {
239065
240033
  if (row2.sealed) knownHandles.add(row2.sealed.handle);
@@ -239105,33 +240073,44 @@ ${v.prompt}` : "";
239105
240073
  quota: completeReportQuota,
239106
240074
  retired: completeReportRetired,
239107
240075
  bootId: reportOsBootId,
239108
- observedRuntimeMs: () => completeReportRuntimeClock.sample(),
240076
+ observedRuntimeMs: () => completeReportRuntimeClock.sampleAsync(),
239109
240077
  prune: pruneRunArtifacts,
239110
240078
  usage: readRunArtifactUsage,
239111
240079
  onError: (id2, error62) => app.log.warn({ id: id2, err: String(error62) }, "saved report cleanup deferred")
239112
240080
  }, mode === "boot" ? "boot" : "periodic", 4, reportHistoryPruneAvailable());
239113
240081
  }, { label: "checking interrupted model reports", expectedMs: 6e4 });
239114
240082
  }
239115
- try {
240083
+ let completeReportRecoveryChecking = false;
240084
+ let nextCompleteReportRecoveryAt = 0;
240085
+ let completeReportRecoveryBackoffMs = 15e3;
240086
+ async function recoverCompleteReportsAtBoot() {
239116
240087
  (0, import_node_fs151.mkdirSync)(completeReportRoot, { recursive: true, mode: 448 });
239117
- ensureOwnerOnlyStoragePath(completeReportRoot, "directory");
240088
+ await ensureOwnerOnlyStoragePathsAsync([{ path: completeReportRoot, kind: "directory" }]);
240089
+ await completeReportRunJournal.prepare();
239118
240090
  const protectedBeforeRecovery = new Set(completeReportRunJournal.list().map((row2) => row2.id));
239119
240091
  await runCompleteReportRecovery("boot");
239120
240092
  for (const row2 of completeReportRunJournal.list()) protectedBeforeRecovery.add(row2.id);
239121
240093
  protectReportAwareProcessOwners(protectedBeforeRecovery);
239122
240094
  completeReportReady = true;
239123
240095
  nextReportHistoryAt = Date.now() + 5 * 6e4;
239124
- } catch (error62) {
239125
- app.log.error({ err: String(error62) }, "complete model reports remain unavailable until recovery succeeds");
239126
- }
239127
- let completeReportRecoveryChecking = false;
239128
- let nextCompleteReportRecoveryAt = 0;
239129
- let completeReportRecoveryBackoffMs = 15e3;
239130
- try {
239131
- completeReportRuntimeClock.sample();
239132
- } catch (error62) {
239133
- app.log.warn({ err: String(error62) }, "report history clock unavailable; manual report expiry disabled");
239134
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
+ });
239135
240114
  setInterval(() => {
239136
240115
  try {
239137
240116
  completeReportRuntimeClock.sample();
@@ -239140,7 +240119,7 @@ ${v.prompt}` : "";
239140
240119
  }
239141
240120
  }, 60 * 6e4).unref();
239142
240121
  setInterval(() => {
239143
- if (completeReportRecoveryChecking) return;
240122
+ if (completeReportRecoveryChecking || !startupReports.mayRetry()) return;
239144
240123
  const now2 = Date.now();
239145
240124
  if (now2 < nextCompleteReportRecoveryAt) return;
239146
240125
  const mode = completeReportReady ? "retry" : "boot";
@@ -239150,18 +240129,18 @@ ${v.prompt}` : "";
239150
240129
  if (!pending && (!reportHistoryPruneAvailable() || now2 < nextReportHistoryAt)) return;
239151
240130
  } catch (error62) {
239152
240131
  completeReportReady = false;
240132
+ startupReports.markPaused();
239153
240133
  app.log.warn({ err: String(error62) }, "complete model reports paused until recovery succeeds");
239154
240134
  return;
239155
240135
  }
239156
240136
  }
239157
240137
  completeReportRecoveryChecking = true;
239158
240138
  void (async () => {
239159
- const protectedBeforeRecovery = mode === "boot" ? new Set(completeReportRunJournal.list().map((row2) => row2.id)) : null;
239160
- await runCompleteReportRecovery(mode);
239161
- if (protectedBeforeRecovery) {
239162
- for (const row2 of completeReportRunJournal.list()) protectedBeforeRecovery.add(row2.id);
239163
- protectReportAwareProcessOwners(protectedBeforeRecovery);
239164
- completeReportReady = true;
240139
+ if (mode === "boot") {
240140
+ await recoverCompleteReportsAtBoot();
240141
+ startupReports.markReady();
240142
+ } else {
240143
+ await runCompleteReportRecovery(mode);
239165
240144
  }
239166
240145
  completeReportRecoveryBackoffMs = 15e3;
239167
240146
  nextCompleteReportRecoveryAt = 0;
@@ -239174,11 +240153,11 @@ ${v.prompt}` : "";
239174
240153
  completeReportRecoveryChecking = false;
239175
240154
  });
239176
240155
  }, 15e3).unref();
239177
- void reconcileWorkspaceMutationOwnersOnBoot().then((count4) => {
239178
- if (count4) app.log.info({ count: count4 }, "reconciled completed workspace owner(s)");
239179
- }).catch((error62) => app.log.error({ err: String(error62) }, "workspace mutation owner reconciliation failed"));
239180
240156
  await app.listen({ port: PORT2, host: HOST });
239181
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"));
239182
240161
  await continueAfterAwareReady(await awareBootstrapCompletion);
239183
240162
  await ensureWorkspaceAgentReady();
239184
240163
  if (true) {
@@ -239465,6 +240444,7 @@ var init_index = __esm({
239465
240444
  init_watch();
239466
240445
  init_workspace_mutation_recovery();
239467
240446
  init_workspace_root_store();
240447
+ init_startup_report_recovery();
239468
240448
  init_workspace_mutation_registry();
239469
240449
  init_run_lease();
239470
240450
  init_workspace_aware_process();