@floless/app 0.121.0 → 0.122.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52400,6 +52400,13 @@ function parseTrace(text3) {
52400
52400
  // aware-lifecycle-gate.ts
52401
52401
  var import_node_async_hooks2 = require("node:async_hooks");
52402
52402
  var OWNER_BRAND = /* @__PURE__ */ Symbol("aware-lifecycle-owner");
52403
+ var AwareMaintenanceBusyError = class extends Error {
52404
+ code = "maintenance-busy";
52405
+ constructor(message = "AWARE is busy with automatic maintenance.") {
52406
+ super(message);
52407
+ this.name = "AwareMaintenanceBusyError";
52408
+ }
52409
+ };
52403
52410
  function owner() {
52404
52411
  return Object.freeze({ [OWNER_BRAND]: true, id: /* @__PURE__ */ Symbol("aware-owner") });
52405
52412
  }
@@ -52412,9 +52419,12 @@ var AwareLifecycleGate = class {
52412
52419
  #owners = new import_node_async_hooks2.AsyncLocalStorage();
52413
52420
  #readerDepth = /* @__PURE__ */ new Map();
52414
52421
  #queue = [];
52422
+ #idleListeners = /* @__PURE__ */ new Set();
52415
52423
  #readerCount = 0;
52416
52424
  #writer = null;
52417
52425
  #writerDepth = 0;
52426
+ #writerOrigin = "user";
52427
+ #wasIdle = true;
52418
52428
  currentOwner() {
52419
52429
  return this.#owners.getStore() ?? null;
52420
52430
  }
@@ -52426,14 +52436,55 @@ var AwareLifecycleGate = class {
52426
52436
  queuedWriters: this.#queue.filter((w) => w.mode === "exclusive").length
52427
52437
  };
52428
52438
  }
52439
+ /** True while unattended maintenance holds or has queued the writer — the refusal condition. */
52440
+ autoWriterActive() {
52441
+ return this.#writer !== null && this.#writerOrigin === "auto" || this.#queue.some((w) => w.mode === "exclusive" && w.origin === "auto");
52442
+ }
52443
+ /** Nothing running and nothing waiting. The only state unattended work may reserve from. */
52444
+ idle() {
52445
+ return this.#writer === null && this.#readerCount === 0 && this.#queue.length === 0;
52446
+ }
52447
+ /**
52448
+ * Edge-triggered idle notification. Unattended maintenance cannot poll for a moment to run:
52449
+ * polling either misses the window or, worse, tempts a snapshot-then-acquire that a trigger can
52450
+ * slip between. Listeners fire on the transition INTO idle; combine with tryWithExclusiveIfIdle,
52451
+ * which re-tests and reserves atomically, so a listener is only ever a hint to try again.
52452
+ */
52453
+ onIdle(listener) {
52454
+ this.#idleListeners.add(listener);
52455
+ return () => this.#idleListeners.delete(listener);
52456
+ }
52457
+ /**
52458
+ * Test idleness and reserve the writer in ONE synchronous step, or decline without queuing.
52459
+ *
52460
+ * This is the whole reason unattended repair cannot use withExclusive: a queued auto writer
52461
+ * waits behind long-lived trigger sessions that hold shared leases for their entire lifetime.
52462
+ * The gate imposes NO acquisition timeout, so it would wait indefinitely, refuse user work the
52463
+ * whole time under the fail-fast rule, and still repair nothing. Declining is the correct answer
52464
+ * — the caller stays pending and retries on the next idle edge.
52465
+ */
52466
+ async tryWithExclusiveIfIdle(origin, fn) {
52467
+ if (!this.idle()) return { ran: false };
52468
+ const leaseOwner = owner();
52469
+ this.#writer = leaseOwner;
52470
+ this.#writerDepth = 1;
52471
+ this.#writerOrigin = origin;
52472
+ this.#wasIdle = false;
52473
+ const lease = this.#writerLease(leaseOwner);
52474
+ try {
52475
+ return { ran: true, value: await this.runAs(leaseOwner, fn) };
52476
+ } finally {
52477
+ lease.release();
52478
+ }
52479
+ }
52429
52480
  runAs(leaseOwner, fn) {
52430
52481
  return this.#owners.run(leaseOwner, fn);
52431
52482
  }
52432
52483
  acquireShared(signal) {
52433
- return this.#acquire("shared", signal);
52484
+ return this.#acquire("shared", "user", signal);
52434
52485
  }
52435
- acquireExclusive(signal) {
52436
- return this.#acquire("exclusive", signal);
52486
+ acquireExclusive(signal, origin = "user") {
52487
+ return this.#acquire("exclusive", origin, signal);
52437
52488
  }
52438
52489
  async withShared(fn, signal) {
52439
52490
  const lease = await this.acquireShared(signal);
@@ -52443,15 +52494,15 @@ var AwareLifecycleGate = class {
52443
52494
  lease.release();
52444
52495
  }
52445
52496
  }
52446
- async withExclusive(fn, signal) {
52447
- const lease = await this.acquireExclusive(signal);
52497
+ async withExclusive(fn, signal, origin = "user") {
52498
+ const lease = await this.acquireExclusive(signal, origin);
52448
52499
  try {
52449
52500
  return await this.runAs(lease.owner, fn);
52450
52501
  } finally {
52451
52502
  lease.release();
52452
52503
  }
52453
52504
  }
52454
- #acquire(mode, signal) {
52505
+ #acquire(mode, origin, signal) {
52455
52506
  if (signal?.aborted) return Promise.reject(abortError());
52456
52507
  const leaseOwner = this.currentOwner() ?? owner();
52457
52508
  if (this.#writer === leaseOwner) {
@@ -52476,15 +52527,19 @@ var AwareLifecycleGate = class {
52476
52527
  const writerQueued = this.#queue.some((w) => w.mode === "exclusive");
52477
52528
  if (mode === "shared" && this.#writer === null && !writerQueued) {
52478
52529
  this.#grantReader(leaseOwner);
52530
+ this.#wasIdle = false;
52479
52531
  return Promise.resolve(this.#readerLease(leaseOwner));
52480
52532
  }
52481
52533
  if (mode === "exclusive" && this.#writer === null && this.#readerCount === 0) {
52482
52534
  this.#writer = leaseOwner;
52483
52535
  this.#writerDepth = 1;
52536
+ this.#writerOrigin = origin;
52537
+ this.#wasIdle = false;
52484
52538
  return Promise.resolve(this.#writerLease(leaseOwner));
52485
52539
  }
52540
+ if (this.autoWriterActive()) return Promise.reject(new AwareMaintenanceBusyError());
52486
52541
  return new Promise((resolve15, reject) => {
52487
- const waiter = { mode, owner: leaseOwner, resolve: resolve15, reject, ...signal ? { signal } : {} };
52542
+ const waiter = { mode, origin, owner: leaseOwner, resolve: resolve15, reject, ...signal ? { signal } : {} };
52488
52543
  if (signal) {
52489
52544
  waiter.onAbort = () => {
52490
52545
  const index = this.#queue.indexOf(waiter);
@@ -52527,16 +52582,40 @@ var AwareLifecycleGate = class {
52527
52582
  this.#writerDepth--;
52528
52583
  if (this.#writerDepth === 0) {
52529
52584
  this.#writer = null;
52585
+ this.#writerOrigin = "user";
52530
52586
  this.#drain();
52531
52587
  }
52532
52588
  });
52533
52589
  }
52590
+ /**
52591
+ * Edge-triggered, and deliberately so: listeners fire on the transition into idle, never
52592
+ * repeatedly while idle. A listener that throws must not corrupt the gate or stop its peers.
52593
+ */
52594
+ #maybeEmitIdle() {
52595
+ const nowIdle = this.idle();
52596
+ if (!nowIdle) {
52597
+ this.#wasIdle = false;
52598
+ return;
52599
+ }
52600
+ if (this.#wasIdle) return;
52601
+ this.#wasIdle = true;
52602
+ for (const listener of [...this.#idleListeners]) {
52603
+ try {
52604
+ listener();
52605
+ } catch {
52606
+ }
52607
+ }
52608
+ }
52534
52609
  #take(waiter) {
52535
52610
  if (waiter.signal && waiter.onAbort) {
52536
52611
  waiter.signal.removeEventListener("abort", waiter.onAbort);
52537
52612
  }
52538
52613
  }
52539
52614
  #drain() {
52615
+ this.#drainQueue();
52616
+ this.#maybeEmitIdle();
52617
+ }
52618
+ #drainQueue() {
52540
52619
  if (this.#writer !== null || this.#readerCount > 0 || this.#queue.length === 0) return;
52541
52620
  const writerIndex = this.#queue.findIndex((w) => w.mode === "exclusive");
52542
52621
  if (writerIndex >= 0) {
@@ -52545,6 +52624,7 @@ var AwareLifecycleGate = class {
52545
52624
  this.#take(waiter);
52546
52625
  this.#writer = waiter.owner;
52547
52626
  this.#writerDepth = 1;
52627
+ this.#writerOrigin = waiter.origin;
52548
52628
  waiter.resolve(this.#writerLease(waiter.owner));
52549
52629
  return;
52550
52630
  }
@@ -52558,7 +52638,9 @@ var AwareLifecycleGate = class {
52558
52638
  };
52559
52639
  var awareLifecycleGate = new AwareLifecycleGate();
52560
52640
  var withAwareShared = (fn, signal) => awareLifecycleGate.withShared(fn, signal);
52561
- var withAwareExclusive = (fn, signal) => awareLifecycleGate.withExclusive(fn, signal);
52641
+ var withAwareExclusive = (fn, signal, origin = "user") => awareLifecycleGate.withExclusive(fn, signal, origin);
52642
+ var tryWithAwareExclusiveIfIdle = (origin, fn) => awareLifecycleGate.tryWithExclusiveIfIdle(origin, fn);
52643
+ var onAwareIdle = (listener) => awareLifecycleGate.onIdle(listener);
52562
52644
  var acquireAwareShared = (signal) => awareLifecycleGate.acquireShared(signal);
52563
52645
  var runAsAwareOwner = (leaseOwner, fn) => awareLifecycleGate.runAs(leaseOwner, fn);
52564
52646
  var currentAwareOwner = () => awareLifecycleGate.currentOwner();
@@ -54529,7 +54611,7 @@ function appVersion() {
54529
54611
  return resolveVersion({
54530
54612
  isSea: isSea2(),
54531
54613
  sqVersionXml: readSqVersionXml(),
54532
- define: true ? "0.121.0" : void 0,
54614
+ define: true ? "0.122.0" : void 0,
54533
54615
  pkgVersion: readPkgVersion()
54534
54616
  });
54535
54617
  }
@@ -54545,7 +54627,7 @@ function resolveChannel(s) {
54545
54627
  function appChannel() {
54546
54628
  return resolveChannel({
54547
54629
  isSea: isSea2(),
54548
- define: true ? "0.121.0" : void 0,
54630
+ define: true ? "0.122.0" : void 0,
54549
54631
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
54550
54632
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
54551
54633
  modulePath: process.argv[1]
@@ -80542,6 +80624,8 @@ async function persistentBridgeVersion(bridgeDirectory, host, io = nodeBridgeVer
80542
80624
  throw new Error(`Could not safely verify the installed ${host} bridge.`, { cause: error });
80543
80625
  }
80544
80626
  }
80627
+ var LEGACY_MARKER_OPERATION = "runtime-update";
80628
+ var LEGACY_MARKER_ORIGIN = "user";
80545
80629
  var nodeMarkerIo = { mkdir: import_promises5.mkdir, readFile: import_promises5.readFile, writeFile: import_promises5.writeFile, rename: import_promises5.rename, chmod: import_promises5.chmod, rm: import_promises5.rm };
80546
80630
  var MARKER_MAX_BYTES = 4096;
80547
80631
  var TOKEN = /^[A-Za-z0-9._-]{1,128}$/;
@@ -80552,7 +80636,11 @@ function isBridgeHost(value) {
80552
80636
  function validateMarker(value) {
80553
80637
  if (!value || typeof value !== "object") return null;
80554
80638
  const v = value;
80555
- if (v.schema !== 1 || !TOKEN.test(v.transaction ?? "") || !isExactAwareTarget(v.target)) return null;
80639
+ if (v.schema !== 1 && v.schema !== 2 || !TOKEN.test(v.transaction ?? "") || !isExactAwareTarget(v.target)) return null;
80640
+ const operation = v.schema === 1 ? LEGACY_MARKER_OPERATION : v.operation;
80641
+ const origin = v.schema === 1 ? LEGACY_MARKER_ORIGIN : v.origin;
80642
+ if (operation !== "runtime-update" && operation !== "bridge-repair") return null;
80643
+ if (origin !== "user" && origin !== "auto") return null;
80556
80644
  if (!["runtime-install", "runtime-verify", "bridge-install", "bridge-verify", "retry-install", "retry-verify", "recovery"].includes(v.stage ?? "")) return null;
80557
80645
  if (!Array.isArray(v.snapshot) || v.snapshot.some((host) => !isBridgeHost(host)) || new Set(v.snapshot).size !== v.snapshot.length) return null;
80558
80646
  if (v.host != null && !isBridgeHost(v.host)) return null;
@@ -80561,13 +80649,17 @@ function validateMarker(value) {
80561
80649
  if (!Number.isSafeInteger(child.pid) || child.pid <= 0 || !PROCESS_IDENTITY.test(child.startIdentity) || !PROCESS_IDENTITY.test(child.executableIdentity) || (0, import_node_path52.basename)(child.executableIdentity) !== child.executableIdentity) return null;
80562
80650
  }
80563
80651
  return {
80564
- schema: 1,
80652
+ // Normalised on read: a decoded schema-1 marker is handed to callers as a schema-2 value with
80653
+ // conservative defaults, so nothing downstream has to know two shapes.
80654
+ schema: 2,
80565
80655
  transaction: v.transaction,
80566
80656
  stage: v.stage,
80567
80657
  target: v.target,
80568
80658
  ...v.host ? { host: v.host } : {},
80569
80659
  snapshot: Object.freeze([...v.snapshot]),
80570
- ...v.child ? { child: { ...v.child } } : {}
80660
+ ...v.child ? { child: { ...v.child } } : {},
80661
+ operation,
80662
+ origin
80571
80663
  };
80572
80664
  }
80573
80665
  function createMaintenanceMarkerStore(markerPath2, options = {}) {
@@ -80619,6 +80711,80 @@ function createMaintenanceMarkerStore(markerPath2, options = {}) {
80619
80711
  }
80620
80712
  };
80621
80713
  }
80714
+ var PENDING_MAX_BYTES = 1024;
80715
+ function validatePending(value) {
80716
+ if (!value || typeof value !== "object") return null;
80717
+ const v = value;
80718
+ if (v.schema !== 1 || !isExactAwareTarget(v.target)) return null;
80719
+ if (!Array.isArray(v.hosts)) return null;
80720
+ const hosts = [...new Set(v.hosts.filter(isBridgeHost))];
80721
+ if (!hosts.length) return null;
80722
+ return { schema: 1, target: v.target, hosts: Object.freeze(hosts) };
80723
+ }
80724
+ function createBridgePendingStore(pendingPath, options = {}) {
80725
+ const io = options.io ?? nodeMarkerIo;
80726
+ const randomId = options.randomId ?? import_node_crypto30.randomUUID;
80727
+ const directory = (0, import_node_path52.dirname)(pendingPath);
80728
+ return {
80729
+ async read() {
80730
+ let bytes;
80731
+ try {
80732
+ bytes = await io.readFile(pendingPath, "utf8");
80733
+ } catch {
80734
+ return null;
80735
+ }
80736
+ if (Buffer.byteLength(bytes) > PENDING_MAX_BYTES) return null;
80737
+ try {
80738
+ return validatePending(JSON.parse(bytes));
80739
+ } catch {
80740
+ return null;
80741
+ }
80742
+ },
80743
+ async write(pending) {
80744
+ const valid = validatePending(pending);
80745
+ if (!valid) throw new Error("Refused to write an invalid AWARE bridge-repair intent.");
80746
+ const bytes = JSON.stringify(valid);
80747
+ if (Buffer.byteLength(bytes) > PENDING_MAX_BYTES) {
80748
+ throw new Error("Refused to write an oversized AWARE bridge-repair intent.");
80749
+ }
80750
+ await io.mkdir(directory, { recursive: true, mode: 448 });
80751
+ const temp = (0, import_node_path52.join)(directory, `.${(0, import_node_path52.basename)(pendingPath)}.${randomId()}.tmp`);
80752
+ try {
80753
+ await io.writeFile(temp, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
80754
+ await io.rename(temp, pendingPath);
80755
+ await io.chmod(pendingPath, 384);
80756
+ } finally {
80757
+ await io.rm(temp, { force: true }).catch(() => {
80758
+ });
80759
+ }
80760
+ },
80761
+ async clear() {
80762
+ await io.rm(pendingPath, { force: true });
80763
+ }
80764
+ };
80765
+ }
80766
+ function bridgesNeedingRepair(inventory, pending, target) {
80767
+ const hosts = new Set(
80768
+ inventory.filter((bridge) => bridge.status !== "current").map((bridge) => bridge.host)
80769
+ );
80770
+ if (pending && pending.target === target) {
80771
+ for (const host of pending.hosts) hosts.add(host);
80772
+ }
80773
+ return Object.freeze(AWARE_BRIDGE_HOSTS.filter((host) => hosts.has(host)));
80774
+ }
80775
+ function decideRecoveryTarget(input) {
80776
+ const { markerTarget, markerOperation, installed } = input;
80777
+ const exactInstalled = installed && isExactAwareTarget(installed) ? installed : null;
80778
+ const exactMarker = markerTarget && isExactAwareTarget(markerTarget) ? markerTarget : null;
80779
+ if (markerOperation === "bridge-repair") return exactInstalled ?? exactMarker;
80780
+ if (!exactMarker) return exactInstalled;
80781
+ if (exactInstalled && compareExactAwareVersions(exactInstalled, exactMarker) > 0) return exactInstalled;
80782
+ return exactMarker;
80783
+ }
80784
+ function compareExactAwareVersions(a, b) {
80785
+ if (a === b) return 0;
80786
+ return versionGt2(a, b) ? 1 : -1;
80787
+ }
80622
80788
  function sanitizeAwareError(error, fallbackCode = "operation-failed") {
80623
80789
  const raw = error instanceof Error ? error.message : String(error);
80624
80790
  const code = typeof error?.code === "string" ? error.code.toLowerCase().replace(/[^a-z0-9_-]/g, "").slice(0, 48) : fallbackCode;
@@ -80971,12 +81137,19 @@ var AwareUpdateJobManager = class {
80971
81137
  #active = null;
80972
81138
  #starting = null;
80973
81139
  #retrying = null;
81140
+ #shuttingDown = false;
81141
+ /** The in-flight job's controller, so shutdown() can actually abort rather than just wait. */
81142
+ #activeController = null;
80974
81143
  #requestStarts = /* @__PURE__ */ new Map();
80975
81144
  #requestTransactions = /* @__PURE__ */ new Map();
81145
+ #settlements = /* @__PURE__ */ new Map();
80976
81146
  constructor(deps) {
80977
81147
  this.#deps = deps;
80978
81148
  }
80979
- async start(requestId) {
81149
+ async start(requestId, options = {}) {
81150
+ const operation = options.operation ?? "runtime-update";
81151
+ const origin = options.origin ?? "user";
81152
+ if (this.#shuttingDown) throw new AwareUpdateConflictError("FloLess is shutting down.");
80980
81153
  this.#purge();
80981
81154
  if (requestId) {
80982
81155
  const transaction = this.#requestTransactions.get(requestId);
@@ -80985,7 +81158,7 @@ var AwareUpdateJobManager = class {
80985
81158
  if (existing) return cloneStatus(await existing);
80986
81159
  }
80987
81160
  if (this.#active || this.#starting || this.#retrying) throw new AwareUpdateConflictError("An AWARE update is already in progress.");
80988
- const starting = this.#begin();
81161
+ const starting = this.#begin(operation, origin);
80989
81162
  this.#starting = starting;
80990
81163
  if (requestId) this.#requestStarts.set(requestId, starting);
80991
81164
  try {
@@ -80997,25 +81170,118 @@ var AwareUpdateJobManager = class {
80997
81170
  if (requestId && this.#requestStarts.get(requestId) === starting) this.#requestStarts.delete(requestId);
80998
81171
  }
80999
81172
  }
81000
- async #begin() {
81001
- const target = requireExactAwareTarget(await this.#deps.resolveCurrentTarget());
81173
+ async #begin(requestedOperation, origin) {
81174
+ let operation = requestedOperation;
81175
+ let preResolved = null;
81176
+ let target;
81177
+ if (operation === "bridge-repair") {
81178
+ const resolved = await this.#deps.resolveBridgeRepair(this.#currentOwnerOrThrow());
81179
+ if (!resolved) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
81180
+ target = requireExactAwareTarget(resolved.target);
81181
+ preResolved = resolved.hosts;
81182
+ if (!preResolved.length) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
81183
+ } else {
81184
+ const resolved = await this.#deps.resolveCurrentTarget();
81185
+ target = requireExactAwareTarget(resolved.target);
81186
+ operation = resolved.operation;
81187
+ }
81002
81188
  if (this.#active || this.#retrying) throw new AwareUpdateConflictError("An AWARE update is already in progress.");
81189
+ if (this.#shuttingDown) throw new AwareUpdateConflictError("FloLess is shutting down.");
81003
81190
  const transaction = (this.#deps.randomId ?? cryptoRandomId)();
81004
81191
  const status = {
81005
81192
  state: "running",
81006
81193
  transaction,
81007
81194
  stage: "queued",
81008
81195
  target,
81196
+ operation,
81197
+ origin,
81009
81198
  completed: 0,
81010
81199
  total: 0,
81011
81200
  updated: frozenHosts([])
81012
81201
  };
81013
81202
  const startedAt = this.#now();
81014
- this.#jobs.set(transaction, { status, snapshot: frozenHosts([]), startedAt, touchedAt: startedAt });
81203
+ this.#jobs.set(transaction, {
81204
+ status,
81205
+ snapshot: frozenHosts([]),
81206
+ startedAt,
81207
+ touchedAt: startedAt,
81208
+ ...preResolved ? { preResolved } : {}
81209
+ });
81015
81210
  this.#active = transaction;
81016
- void this.#execute(transaction).catch((error) => this.#unexpectedFailure(transaction, error));
81211
+ const settled = this.#execute(transaction).catch((error) => this.#unexpectedFailure(transaction, error));
81212
+ this.#settlements.set(transaction, settled);
81213
+ void settled;
81017
81214
  return cloneStatus(status);
81018
81215
  }
81216
+ /**
81217
+ * Resolves when the job reaches a terminal state. The automatic path awaits this INSIDE its
81218
+ * leased callback so the lease is held for the whole job — without it the callback would return
81219
+ * the moment the job was accepted, drop the lease, and let #execute re-acquire it in a race it
81220
+ * was created to avoid.
81221
+ */
81222
+ async settled(transaction) {
81223
+ await this.#settlements.get(transaction);
81224
+ }
81225
+ #currentOwnerOrThrow() {
81226
+ const owner2 = this.#deps.currentOwner();
81227
+ if (!owner2) throw new Error("A bridge repair must be started inside the exclusive lifecycle lease.");
81228
+ return owner2;
81229
+ }
81230
+ /**
81231
+ * What a browser that started nothing should adopt: the running job, else the most recent
81232
+ * UNACKNOWLEDGED automatic failure. Lease-free by construction — a leased read would queue
81233
+ * behind the very repair it is trying to observe.
81234
+ *
81235
+ * Ordering is by `terminalAt`, never `touchedAt`: `get()` bumps `touchedAt` on every poll, so an
81236
+ * old failure that happens to be polled would otherwise outrank a newer one. Successes are never
81237
+ * surfaced (nothing to act on), and acknowledged failures stop coming back — without that a
81238
+ * dismissed `partial` re-alarms on every page load for the full retention window.
81239
+ */
81240
+ activeStatus() {
81241
+ this.#purge();
81242
+ if (this.#active) {
81243
+ const running = this.#jobs.get(this.#active);
81244
+ if (running && !isTerminal(running.status)) return cloneStatus(running.status);
81245
+ }
81246
+ let best = null;
81247
+ for (const record3 of this.#jobs.values()) {
81248
+ if (record3.status.origin !== "auto" || record3.acknowledged) continue;
81249
+ if (record3.status.state !== "partial" && record3.status.state !== "runtime-failed") continue;
81250
+ if (!best || (record3.terminalAt ?? 0) > (best.terminalAt ?? 0)) best = record3;
81251
+ }
81252
+ return best ? cloneStatus(best.status) : null;
81253
+ }
81254
+ /**
81255
+ * Retire a terminal automatic result the user has seen. Scoped to one transaction and refused
81256
+ * while it is still running: a blanket "the modal closed" acknowledgement could retire a job
81257
+ * that later turns partial, hiding a failure nobody ever saw. Idempotent.
81258
+ */
81259
+ acknowledge(transaction) {
81260
+ this.#purge();
81261
+ const record3 = this.#jobs.get(transaction);
81262
+ if (!record3) {
81263
+ if (this.#gone.has(transaction)) throw new AwareUpdateGoneError("This AWARE update result has expired.");
81264
+ throw new AwareUpdateNotFoundError("AWARE update transaction not found.");
81265
+ }
81266
+ if (!isTerminal(record3.status)) {
81267
+ throw new AwareUpdateConflictError("That AWARE operation has not finished yet.");
81268
+ }
81269
+ record3.acknowledged = true;
81270
+ record3.touchedAt = this.#now();
81271
+ return cloneStatus(record3.status);
81272
+ }
81273
+ /**
81274
+ * Stop admitting work, abort the in-flight child, and await settlement. A bridge-repair marker is
81275
+ * deliberately LEFT in place: it describes unfinished work, and the next launch's recovery is
81276
+ * what finishes it. Clearing it here would look like a clean finish and strand the bridges.
81277
+ */
81278
+ async shutdown() {
81279
+ this.#shuttingDown = true;
81280
+ this.#activeController?.abort(new DeadlineError("FloLess is shutting down."));
81281
+ await Promise.allSettled([this.#starting, ...this.#settlements.values()].filter(Boolean));
81282
+ this.#activeController?.abort(new DeadlineError("FloLess is shutting down."));
81283
+ await Promise.allSettled([...this.#settlements.values()]);
81284
+ }
81019
81285
  get(transaction) {
81020
81286
  this.#purge();
81021
81287
  const record3 = this.#jobs.get(transaction);
@@ -81066,21 +81332,25 @@ var AwareUpdateJobManager = class {
81066
81332
  const jobBudget = this.#deps.jobTimeoutMs ?? DEFAULT_JOB_TIMEOUT;
81067
81333
  const deadline = started + jobBudget;
81068
81334
  const jobController = new AbortController();
81335
+ this.#activeController = jobController;
81069
81336
  const jobTimer = setTimeout(() => jobController.abort(new DeadlineError()), jobBudget);
81070
81337
  jobTimer.unref?.();
81071
81338
  try {
81072
81339
  await this.#deps.withExclusive(async (owner2) => this.#deps.withMutationContainment(transaction, owner2, async () => {
81340
+ const operation = record3.status.operation;
81073
81341
  this.#running(record3, "snapshot", 0, 0, []);
81074
- const snapshot = await this.#deps.snapshotPersistentBridges(owner2, record3.status.target);
81342
+ const snapshot = record3.preResolved ?? await this.#deps.snapshotPersistentBridges(owner2, record3.status.target);
81075
81343
  this.#assertSnapshot(snapshot);
81076
81344
  record3.snapshot = frozenHosts(snapshot);
81077
81345
  this.#running(record3, "runtime-install", 0, snapshot.length, []);
81078
81346
  let marker = {
81079
- schema: 1,
81347
+ schema: 2,
81080
81348
  transaction,
81081
81349
  stage: "runtime-install",
81082
81350
  target: record3.status.target,
81083
- snapshot: record3.snapshot
81351
+ snapshot: record3.snapshot,
81352
+ operation,
81353
+ origin: record3.status.origin
81084
81354
  };
81085
81355
  await this.#deps.maintenance.write(marker);
81086
81356
  let observed = null;
@@ -81088,6 +81358,12 @@ var AwareUpdateJobManager = class {
81088
81358
  try {
81089
81359
  const installedBefore = await this.#deps.probeRuntime(owner2);
81090
81360
  if (installedBefore !== record3.status.target) {
81361
+ if (operation === "bridge-repair") {
81362
+ throw Object.assign(
81363
+ new Error("The installed AWARE runtime changed before the bridge repair began."),
81364
+ { code: "runtime-superseded" }
81365
+ );
81366
+ }
81091
81367
  await bounded(
81092
81368
  (signal) => this.#deps.installRuntime(record3.status.target, {
81093
81369
  owner: owner2,
@@ -81164,6 +81440,17 @@ var AwareUpdateJobManager = class {
81164
81440
  }
81165
81441
  }
81166
81442
  }
81443
+ await this.#persistBridgeIntent(record3, failed);
81444
+ await Promise.resolve(this.#deps.refreshRuntime(owner2)).catch(() => {
81445
+ });
81446
+ this.#deps.invalidateVersion();
81447
+ const afterBridges = await this.#deps.probeRuntime(owner2);
81448
+ if (afterBridges !== record3.status.target) {
81449
+ throw Object.assign(
81450
+ new Error("The installed AWARE runtime changed while the bridges were being refreshed."),
81451
+ { code: "runtime-superseded" }
81452
+ );
81453
+ }
81167
81454
  this.#finishBridges(record3, observed, updated, failed);
81168
81455
  } catch (error) {
81169
81456
  await Promise.resolve(this.#deps.refreshRuntime(owner2)).catch(() => {
@@ -81189,7 +81476,9 @@ var AwareUpdateJobManager = class {
81189
81476
  }), { signal: jobController.signal });
81190
81477
  } finally {
81191
81478
  clearTimeout(jobTimer);
81479
+ if (this.#activeController === jobController) this.#activeController = null;
81192
81480
  if (this.#active === transaction) this.#active = null;
81481
+ this.#settlements.delete(transaction);
81193
81482
  this.#purge();
81194
81483
  }
81195
81484
  }
@@ -81219,6 +81508,8 @@ var AwareUpdateJobManager = class {
81219
81508
  state: "retrying",
81220
81509
  transaction: status.transaction,
81221
81510
  target: status.target,
81511
+ operation: status.operation,
81512
+ origin: status.origin,
81222
81513
  host,
81223
81514
  completed: status.updated.length,
81224
81515
  total: record3.snapshot.length,
@@ -81228,12 +81519,14 @@ var AwareUpdateJobManager = class {
81228
81519
  reserved = true;
81229
81520
  resolveReserved(cloneStatus(record3.status));
81230
81521
  let marker = {
81231
- schema: 1,
81522
+ schema: 2,
81232
81523
  transaction: status.transaction,
81233
81524
  stage: "retry-install",
81234
81525
  target: status.target,
81235
81526
  host,
81236
- snapshot: record3.snapshot
81527
+ snapshot: record3.snapshot,
81528
+ operation: status.operation,
81529
+ origin: status.origin
81237
81530
  };
81238
81531
  try {
81239
81532
  await this.#deps.maintenance.write(marker);
@@ -81259,6 +81552,7 @@ var AwareUpdateJobManager = class {
81259
81552
  if (!verified) throw Object.assign(new Error(`The ${host} bridge version could not be verified.`), { code: "bridge-version-mismatch" });
81260
81553
  const updatedSet = /* @__PURE__ */ new Set([...status.updated, host]);
81261
81554
  const updated = frozenHosts(record3.snapshot.filter((candidate) => updatedSet.has(candidate)));
81555
+ await this.#persistBridgeIntent(record3, otherFailures);
81262
81556
  if (otherFailures.length) {
81263
81557
  this.#setTerminal(record3, {
81264
81558
  state: "partial",
@@ -81280,13 +81574,15 @@ var AwareUpdateJobManager = class {
81280
81574
  } catch (error) {
81281
81575
  const failure = error instanceof DeadlineError ? timeoutFailure(host) : { host, ...sanitizeAwareError(error, "bridge-update-failed") };
81282
81576
  this.#log(record3, "bridge-retry", failure, host);
81577
+ const stillFailing = frozenFailures([...otherFailures, failure]);
81578
+ await this.#persistBridgeIntent(record3, stillFailing);
81283
81579
  this.#setTerminal(record3, {
81284
81580
  state: "partial",
81285
81581
  transaction: status.transaction,
81286
81582
  target: status.target,
81287
81583
  observedVersion: status.observedVersion,
81288
81584
  updated: status.updated,
81289
- failed: frozenFailures([...otherFailures, failure])
81585
+ failed: stillFailing
81290
81586
  });
81291
81587
  } finally {
81292
81588
  await this.#deps.maintenance.clear().catch((error) => {
@@ -81304,6 +81600,28 @@ var AwareUpdateJobManager = class {
81304
81600
  if (this.#retrying === record3.status.transaction) this.#retrying = null;
81305
81601
  }
81306
81602
  }
81603
+ /**
81604
+ * Persist which installed hosts still owe us a matching bridge — or discharge the record when
81605
+ * none do. The single place that decision is written, because getting it wrong in either
81606
+ * direction is expensive: losing it forgets a host whose executable a failed installer removed,
81607
+ * and failing to clear it re-runs a full sidecar reinstall of healthy bridges on every launch.
81608
+ *
81609
+ * A failure here is reported, never swallowed. This store exists precisely to stop a bridge
81610
+ * disappearing silently, so a silent write failure would defeat the mechanism it implements.
81611
+ */
81612
+ async #persistBridgeIntent(record3, failed) {
81613
+ const hosts = frozenHosts(failed.map((failure) => failure.host));
81614
+ try {
81615
+ if (hosts.length) await this.#deps.recordBridgePending(record3.status.target, hosts);
81616
+ else await this.#deps.clearBridgePending();
81617
+ } catch (error) {
81618
+ this.#log(
81619
+ record3,
81620
+ hosts.length ? "bridge-pending-record" : "bridge-pending-clear",
81621
+ sanitizeAwareError(error, "bridge-pending-failed")
81622
+ );
81623
+ }
81624
+ }
81307
81625
  #finishBridges(record3, observedVersion, updated, failed) {
81308
81626
  if (updated.length + failed.length !== record3.snapshot.length) {
81309
81627
  throw new Error("AWARE bridge update did not partition its immutable snapshot.");
@@ -81332,6 +81650,8 @@ var AwareUpdateJobManager = class {
81332
81650
  state: "running",
81333
81651
  transaction: record3.status.transaction,
81334
81652
  target: record3.status.target,
81653
+ operation: record3.status.operation,
81654
+ origin: record3.status.origin,
81335
81655
  stage,
81336
81656
  completed,
81337
81657
  total,
@@ -81340,7 +81660,13 @@ var AwareUpdateJobManager = class {
81340
81660
  record3.touchedAt = this.#now();
81341
81661
  }
81342
81662
  #setTerminal(record3, status) {
81343
- record3.status = { ...status, durationMs: Math.max(0, this.#now() - record3.startedAt) };
81663
+ record3.status = {
81664
+ ...status,
81665
+ // Carried from the record, never from the caller — see TerminalAwareUpdateInput.
81666
+ operation: record3.status.operation,
81667
+ origin: record3.status.origin,
81668
+ durationMs: Math.max(0, this.#now() - record3.startedAt)
81669
+ };
81344
81670
  record3.terminalAt = this.#now();
81345
81671
  record3.touchedAt = record3.terminalAt;
81346
81672
  }
@@ -81443,6 +81769,17 @@ function sendRouteError(reply, error) {
81443
81769
  return reply.status(400).send({ ok: false, error: sanitizeAwareError(error, "invalid-update-request").message });
81444
81770
  }
81445
81771
  function registerAwareUpdateRoutes(app, manager) {
81772
+ app.get("/api/aware/update/active", async (_request, reply) => reply.send({ ok: true, job: manager.activeStatus() }));
81773
+ app.post(
81774
+ "/api/aware/update/status/:transaction/acknowledge",
81775
+ async (request, reply) => {
81776
+ try {
81777
+ return reply.send({ ok: true, ...manager.acknowledge(request.params.transaction) });
81778
+ } catch (error) {
81779
+ return sendRouteError(reply, error);
81780
+ }
81781
+ }
81782
+ );
81446
81783
  app.post("/api/aware/update/apply", async (request, reply) => {
81447
81784
  try {
81448
81785
  const value = request.headers["x-floless-request-id"];
@@ -83524,6 +83861,16 @@ async function startServer() {
83524
83861
  const awareMaintenance = createMaintenanceMarkerStore(
83525
83862
  (0, import_node_path57.join)((0, import_node_os29.homedir)(), ".floless", "aware-maintenance.json")
83526
83863
  );
83864
+ const awareBridgePending = createBridgePendingStore(
83865
+ (0, import_node_path57.join)((0, import_node_os29.homedir)(), ".floless", "aware-bridge-pending.json")
83866
+ );
83867
+ async function staleBridgesForInstalledRuntime() {
83868
+ const target = aware.npmVersion();
83869
+ if (!target || !isExactAwareTarget(target)) return null;
83870
+ const inventory = await inspectPersistentBridgeInventory(AWARE_BRIDGE_DIRECTORY, target);
83871
+ const hosts = bridgesNeedingRepair(inventory, await awareBridgePending.read(), target);
83872
+ return hosts.length ? { target, hosts } : null;
83873
+ }
83527
83874
  function upgradeOwner() {
83528
83875
  const owner2 = currentAwareOwner();
83529
83876
  if (!owner2) throw new Error("AWARE updater is outside its exclusive lifecycle owner");
@@ -83557,11 +83904,27 @@ async function startServer() {
83557
83904
  throw Object.assign(new Error("An interrupted AWARE update must be recovered before starting another."), { code: "maintenance-pending" });
83558
83905
  }
83559
83906
  const check = await checkAwareUpdate(AWARE_BRIDGE_DIRECTORY);
83560
- return check.updateAvailable ? check.targetVersion ?? null : null;
83907
+ return {
83908
+ target: check.updateAvailable ? check.targetVersion ?? null : null,
83909
+ // 'none' cannot reach a started job (the target is null and requireExactAwareTarget throws),
83910
+ // but map it defensively rather than casting — the check type lets the two disagree.
83911
+ operation: check.operation === "bridge-repair" ? "bridge-repair" : "runtime-update"
83912
+ };
83561
83913
  },
83914
+ // Runs inside the caller's exclusive lease, so the installed version it reads cannot move under
83915
+ // it — and it never asks npm what the newest release is. Both properties are load-bearing: this
83916
+ // is what stops a "repair" from installing a newer runtime, or reinstalling an older one.
83917
+ resolveBridgeRepair: async (owner2) => {
83918
+ if (owner2 !== upgradeOwner()) throw new Error("AWARE bridge-repair owner mismatch");
83919
+ return staleBridgesForInstalledRuntime();
83920
+ },
83921
+ recordBridgePending: (target, hosts) => awareBridgePending.write({ schema: 1, target, hosts }),
83922
+ clearBridgePending: () => awareBridgePending.clear(),
83923
+ currentOwner: () => currentAwareOwner(),
83562
83924
  snapshotPersistentBridges: async (_owner, target) => {
83563
83925
  const inventory = await inspectPersistentBridgeInventory(AWARE_BRIDGE_DIRECTORY, target);
83564
- return inventory.filter((bridge) => bridge.status !== "current").map((bridge) => bridge.host);
83926
+ const hosts = bridgesNeedingRepair(inventory, await awareBridgePending.read(), target);
83927
+ return hosts;
83565
83928
  },
83566
83929
  withExclusive: (work, options) => withAwareExclusive(
83567
83930
  () => work(upgradeOwner()),
@@ -83607,18 +83970,26 @@ async function startServer() {
83607
83970
  if (owner2 !== upgradeOwner()) return false;
83608
83971
  refreshInvoker();
83609
83972
  invalidateAwareVersion();
83610
- let target = marker?.target ?? aware.npmVersion();
83973
+ const target = decideRecoveryTarget({
83974
+ markerTarget: marker?.target ?? null,
83975
+ markerOperation: marker?.operation ?? null,
83976
+ installed: aware.npmVersion()
83977
+ });
83611
83978
  if (!target || !/^\d+\.\d+\.\d+$/.test(target)) return false;
83612
- let snapshot = marker?.snapshot ?? await snapshotPersistentBridges(AWARE_BRIDGE_DIRECTORY);
83979
+ const durable = await awareBridgePending.read();
83980
+ const observedHosts = await snapshotPersistentBridges(AWARE_BRIDGE_DIRECTORY);
83981
+ let snapshot = Object.freeze(AWARE_BRIDGE_HOSTS.filter((host) => (marker?.snapshot ?? []).includes(host) || observedHosts.includes(host) || durable?.target === target && durable.hosts.includes(host)));
83613
83982
  let recoveryMarker = {
83614
- schema: 1,
83983
+ schema: 2,
83615
83984
  transaction: marker?.transaction ?? (0, import_node_crypto31.randomUUID)(),
83616
83985
  stage: "recovery",
83617
83986
  target,
83618
- snapshot
83987
+ snapshot,
83988
+ operation: marker?.operation ?? LEGACY_MARKER_OPERATION,
83989
+ origin: marker?.origin ?? LEGACY_MARKER_ORIGIN
83619
83990
  };
83620
83991
  await awareMaintenance.write(recoveryMarker);
83621
- if (aware.npmVersion() !== target) {
83992
+ if (aware.npmVersion() !== target || !await aware.smoke()) {
83622
83993
  await installAwareGlobal(target, () => {
83623
83994
  }, {
83624
83995
  onChild: async (child) => {
@@ -83651,6 +84022,8 @@ async function startServer() {
83651
84022
  }
83652
84023
  });
83653
84024
  }
84025
+ await awareBridgePending.clear().catch(() => {
84026
+ });
83654
84027
  return true;
83655
84028
  }
83656
84029
  async function recoverAwareMaintenance() {
@@ -83662,16 +84035,84 @@ async function startServer() {
83662
84035
  repairAndVerify: repairInterruptedAwareMaintenance
83663
84036
  });
83664
84037
  }
83665
- async function startAwareBootstrap() {
84038
+ const SKIP_AUTO_BRIDGE_REPAIR = process.env.FLOLESS_SKIP_AUTO_BRIDGE_REPAIR === "1";
84039
+ let autoRepairScheduled = false;
84040
+ let autoRepairInFlight = false;
84041
+ let detachAutoRepairIdleWatch = null;
84042
+ function disarmAutoBridgeRepair() {
84043
+ detachAutoRepairIdleWatch?.();
84044
+ detachAutoRepairIdleWatch = null;
84045
+ }
84046
+ async function attemptAutoBridgeRepair() {
84047
+ if (autoRepairInFlight || SKIP_AUTO_BRIDGE_REPAIR) return;
84048
+ autoRepairInFlight = true;
83666
84049
  try {
83667
- await recoverAwareMaintenance();
84050
+ if (!await staleBridgesForInstalledRuntime()) {
84051
+ disarmAutoBridgeRepair();
84052
+ return;
84053
+ }
84054
+ const outcome = await tryWithAwareExclusiveIfIdle("auto", async () => {
84055
+ const status = await awareUpdateJobs.start(void 0, { operation: "bridge-repair", origin: "auto" });
84056
+ app.log.info({ transaction: status.transaction, target: status.target }, "repairing stale AWARE bridges");
84057
+ broadcast({ type: "aware-update", transaction: status.transaction });
84058
+ await awareUpdateJobs.settled(status.transaction);
84059
+ });
84060
+ if (!outcome.ran) return;
84061
+ disarmAutoBridgeRepair();
83668
84062
  } catch (error) {
83669
- app.log.error({ err: error instanceof Error ? error.message : String(error) }, "AWARE maintenance recovery failed");
83670
- return failBootstrapMaintenanceRecovery(bootstrapDeps);
84063
+ const err2 = error instanceof Error ? error : new Error(String(error));
84064
+ const code = error?.code ?? null;
84065
+ const ordinary = error instanceof AwareUpdateConflictError || code === "maintenance-pending" || code === "runtime-superseded";
84066
+ if (ordinary) {
84067
+ app.log.info({ code, err: err2.message }, "automatic AWARE bridge repair declined");
84068
+ } else {
84069
+ app.log.error({ code, err: err2.message, stack: err2.stack }, "automatic AWARE bridge repair failed unexpectedly");
84070
+ }
84071
+ disarmAutoBridgeRepair();
84072
+ } finally {
84073
+ autoRepairInFlight = false;
83671
84074
  }
83672
- return withAwareExclusive(() => runBootstrap(bootstrapDeps));
84075
+ }
84076
+ function scheduleAutoBridgeRepair() {
84077
+ if (autoRepairScheduled || SKIP_AUTO_BRIDGE_REPAIR) return;
84078
+ autoRepairScheduled = true;
84079
+ const backstop = (err2) => app.log.error({ err: String(err2) }, "automatic AWARE bridge repair wrapper rejected");
84080
+ detachAutoRepairIdleWatch = onAwareIdle(() => {
84081
+ void attemptAutoBridgeRepair().catch(backstop);
84082
+ });
84083
+ void attemptAutoBridgeRepair().catch(backstop);
84084
+ }
84085
+ let awareBootstrapInflight = null;
84086
+ async function startAwareBootstrap() {
84087
+ if (awareBootstrapInflight) return awareBootstrapInflight;
84088
+ awareBootstrapInflight = (async () => {
84089
+ try {
84090
+ await recoverAwareMaintenance();
84091
+ } catch (error) {
84092
+ app.log.error({ err: error instanceof Error ? error.message : String(error) }, "AWARE maintenance recovery failed");
84093
+ return failBootstrapMaintenanceRecovery(bootstrapDeps);
84094
+ }
84095
+ const state2 = await withAwareExclusive(() => runBootstrap(bootstrapDeps));
84096
+ if (state2.status === "ready") scheduleAutoBridgeRepair();
84097
+ return state2;
84098
+ })().finally(() => {
84099
+ awareBootstrapInflight = null;
84100
+ });
84101
+ return awareBootstrapInflight;
83673
84102
  }
83674
84103
  app.setErrorHandler((err2, req, reply) => {
84104
+ if (err2 instanceof AwareMaintenanceBusyError) {
84105
+ const job = awareUpdateJobs.activeStatus();
84106
+ const progress = job?.state === "running" && job.total ? { completed: job.completed, total: job.total } : null;
84107
+ return reply.status(409).send({
84108
+ ok: false,
84109
+ error: "aware_maintenance_busy",
84110
+ code: "maintenance-busy",
84111
+ operation: job?.operation ?? "bridge-repair",
84112
+ ...progress ?? {},
84113
+ message: progress ? `FloLess is refreshing your installed bridges (${progress.completed} of ${progress.total}). This will be available again in a moment.` : "FloLess is refreshing your installed bridges. This will be available again in a moment."
84114
+ });
84115
+ }
83675
84116
  if (err2 instanceof AppNotFoundError) {
83676
84117
  return reply.status(404).send({ ok: false, error: err2.message });
83677
84118
  }
@@ -87052,7 +87493,19 @@ async function startServer() {
87052
87493
  const close = async () => {
87053
87494
  cancelAllConnects();
87054
87495
  clearAllStages();
87496
+ detachAutoRepairIdleWatch?.();
87055
87497
  await stopScheduler();
87498
+ const updaterSettled = awareUpdateJobs.shutdown().catch((err2) => app.log.warn({ err: String(err2) }, "AWARE updater shutdown did not settle cleanly"));
87499
+ const shutdownTimedOut = await Promise.race([
87500
+ updaterSettled.then(() => false),
87501
+ new Promise((resolve15) => {
87502
+ const t = setTimeout(() => resolve15(true), 15e3);
87503
+ t.unref?.();
87504
+ })
87505
+ ]);
87506
+ if (shutdownTimedOut) {
87507
+ app.log.warn("AWARE updater still settling at shutdown; exiting anyway \u2014 recovery finishes it next launch");
87508
+ }
87056
87509
  await watcher?.close();
87057
87510
  await app.close();
87058
87511
  process.exit(0);
@@ -86,7 +86,13 @@
86
86
  const status = String(payload.status || payload.state || payload.kind || '').toLowerCase();
87
87
  const target = payload.target || payload.targetVersion || null;
88
88
  const observedVersion = payload.observedVersion || payload.version || payload.runtimeVersion || null;
89
- const base = { transaction, target, observedVersion };
89
+ // Carried on EVERY normalized state, not set once at adoption. normalize() rebuilds state
90
+ // from each status response, so a field applied only when the job was adopted would be lost
91
+ // on the very first poll — restoring "Upgrading AWARE…" over a bridge repair, and
92
+ // re-enabling the modal hijack for a failure the user never initiated.
93
+ const operation = payload.operation === 'bridge-repair' ? 'bridge-repair' : 'runtime-update';
94
+ const origin = payload.origin === 'auto' ? 'auto' : 'user';
95
+ const base = { transaction, target, observedVersion, operation, origin };
90
96
  if (status === 'running') {
91
97
  return {
92
98
  ...base, status, stage: payload.stage || 'preparing',
@@ -114,7 +120,10 @@
114
120
  ...base, status: 'runtime-failed',
115
121
  error: {
116
122
  code: String(error.code || payload.code || 'runtime-update-failed'),
117
- message: String(error.message || payload.message || 'AWARE could not be upgraded.'),
123
+ message: String(error.message || payload.message
124
+ || (operation === 'bridge-repair'
125
+ ? "AWARE's installed bridges could not be refreshed."
126
+ : 'AWARE could not be upgraded.')),
118
127
  },
119
128
  };
120
129
  }
@@ -152,7 +161,10 @@
152
161
  check = probed.response.ok ? probed.body : null;
153
162
  } catch { /* current readiness remains unknown */ }
154
163
  return emit({
155
- status: 'expired', transaction: null, check,
164
+ // origin carried through so a terminal state the user never initiated is still
165
+ // recognisable as such. Belt and braces alongside adopt() no longer storing: every
166
+ // state the subscriber may act on has to say where it came from.
167
+ status: 'expired', transaction: null, check, origin: state.origin || 'user',
156
168
  message: wasLostAfterRestart
157
169
  ? 'The previous upgrade could not be recovered after the server restarted. Current AWARE status was checked again.'
158
170
  : 'The previous upgrade result expired. Current AWARE status was checked again.',
@@ -161,12 +173,17 @@
161
173
  if (!result.response.ok) {
162
174
  const message = result.body.error || `Could not read AWARE upgrade status (HTTP ${result.response.status}).`;
163
175
  return emit({ status: 'runtime-failed', transaction, target: state.target, observedVersion: null,
176
+ // Identity is immutable, and DEFAULTED because start()/resume() emit before any poll
177
+ // has supplied it — copying a bare `state.operation` there copies undefined, which
178
+ // renders as a runtime upgrade anyway. The defaults match normalize()'s own.
179
+ operation: state.operation || 'runtime-update', origin: state.origin || 'user',
164
180
  error: { code: 'status-request-failed', message: String(message) } });
165
181
  }
166
182
  let next;
167
183
  try { next = normalize(result.body, transaction); }
168
184
  catch (error) {
169
185
  return emit({ status: 'runtime-failed', transaction, target: state.target, observedVersion: null,
186
+ operation: state.operation || 'runtime-update', origin: state.origin || 'user',
170
187
  error: { code: 'transaction-mismatch', message: error.message } });
171
188
  }
172
189
  emit(next);
@@ -245,6 +262,62 @@
245
262
  return poll(transaction, myGeneration);
246
263
  }
247
264
 
265
+ /**
266
+ * Adopt a job the SERVER started — an automatic bridge repair this browser has no stored
267
+ * transaction for, or an automatic failure that happened before it connected.
268
+ *
269
+ * Deliberately hits /active rather than the ordinary check route: the repair holds AWARE's
270
+ * exclusive lease, and the check route takes a shared one, so polling it to discover the repair
271
+ * would block on the very thing being discovered.
272
+ *
273
+ * Single-flight and idempotent — it is called at init AND on the aware-update SSE event, and
274
+ * both can land together.
275
+ */
276
+ let adopting = null;
277
+ async function adopt() {
278
+ if (adopting) return adopting;
279
+ adopting = (async () => {
280
+ let result;
281
+ try {
282
+ result = await request('/api/aware/update/active');
283
+ } catch {
284
+ return state; // discovery is best-effort; the pill's own poll remains the fallback
285
+ }
286
+ if (!result.response.ok) return state;
287
+ const job = result.body && result.body.job;
288
+ const transaction = transactionOf(job);
289
+ if (!transaction) return state;
290
+ // Already following this one (resume() got there first, or a duplicate SSE event).
291
+ if (state.transaction === transaction && state.status !== 'idle') return state;
292
+ generation += 1;
293
+ const myGeneration = generation;
294
+ // Deliberately NOT stored, unlike start(). Storage exists so a reload can resume a job the
295
+ // USER began; an adopted job is rediscovered from /active, which is the server's own
296
+ // authority and needs no client memory. Storing it caused a real regression: after a
297
+ // server restart the stored id 404s, poll() emits `expired` — a state with no origin, and
298
+ // one the subscriber treats as worth interrupting for — so a repair the user never started
299
+ // threw a modal over the workspace on the next load. Not storing removes the path entirely.
300
+ let next;
301
+ try { next = normalize({ ...job, transaction }, transaction); }
302
+ catch { return state; }
303
+ emit({ ...next, adopted: true });
304
+ if (terminal(next)) return next;
305
+ return poll(transaction, myGeneration);
306
+ })().finally(() => { adopting = null; });
307
+ return adopting;
308
+ }
309
+
310
+ /** Retire a terminal automatic result the user has now seen. Best-effort. */
311
+ async function acknowledge(transaction) {
312
+ const id = transaction || state.transaction;
313
+ if (!id) return state;
314
+ try {
315
+ await request(`/api/aware/update/status/${encodeURIComponent(id)}/acknowledge`, { method: 'POST' });
316
+ clearStored();
317
+ } catch { /* the server retires it on its own retention timer regardless */ }
318
+ return state;
319
+ }
320
+
248
321
  async function check() {
249
322
  const result = await request('/api/aware/update');
250
323
  if (!result.response.ok) throw new Error(result.body.error || `Could not check AWARE updates (HTTP ${result.response.status}).`);
@@ -289,7 +362,7 @@
289
362
  }
290
363
 
291
364
  return {
292
- start, resume, retryFailed, check,
365
+ start, resume, adopt, acknowledge, retryFailed, check,
293
366
  getState: () => state,
294
367
  getStoredTransaction: readStored,
295
368
  subscribe(listener) {
package/dist/web/aware.js CHANGED
@@ -146,6 +146,10 @@
146
146
  $messages.scrollTop = $messages.scrollHeight;
147
147
  };
148
148
 
149
+ // Declared here, above its first use in api(), rather than beside the recovery helper that reads
150
+ // it — a `let` referenced before its declaration executes is a TDZ crash, not a false.
151
+ let awareMaintenanceRefused = false;
152
+
149
153
  async function api(path, opts) {
150
154
  const res = await fetch(path, {
151
155
  headers: { 'content-type': 'application/json' },
@@ -153,7 +157,19 @@
153
157
  });
154
158
  const body = await res.json().catch(() => ({ ok: false, error: `HTTP ${res.status}` }));
155
159
  if (!res.ok || body.ok === false) {
156
- const err = new Error(body.error || `HTTP ${res.status}`);
160
+ // Centralised so EVERY caller that spawns `aware` reports the refusal honestly rather than
161
+ // showing the raw `aware_maintenance_busy` code. The server refuses instead of queuing
162
+ // because the wait would start before any child exists — invisible to every timeout and
163
+ // uncancellable by Stop — so what reaches the user has to explain itself and say how far
164
+ // along the repair is.
165
+ if (body.code === 'maintenance-busy') {
166
+ // Remembered so the terminal transition can re-run whatever was turned away. Set here
167
+ // rather than at each call site: every `aware`-spawning route funnels through api().
168
+ awareMaintenanceRefused = true;
169
+ }
170
+ const err = new Error(
171
+ (body.code === 'maintenance-busy' && body.message) || body.error || `HTTP ${res.status}`,
172
+ );
157
173
  err.body = body; // preserve the in-band payload (e.g. credentialIssue) for callers
158
174
  throw err;
159
175
  }
@@ -5192,21 +5208,56 @@
5192
5208
  let awareUpgradeFloor = null, awareUpgradeFloorUntil = 0;
5193
5209
  let awareUpdateCheck = null;
5194
5210
  let applyAwareUpdate = null;
5211
+ /**
5212
+ * The one place the "needs attention" pill is painted, so its four properties cannot drift apart
5213
+ * across the three call sites that reach this state. The tooltip matters more than it looks: the
5214
+ * static markup default says an AWARE *upgrade* is available, so a pill that reaches this state
5215
+ * without passing through an offer branch would otherwise hover-explain the wrong thing entirely.
5216
+ */
5217
+ function paintAwareAttentionPill() {
5218
+ if (!$awareUpdate) return;
5219
+ $awareUpdate.hidden = false;
5220
+ $awareUpdate.disabled = false;
5221
+ $awareUpdate.textContent = 'Installed bridges need attention';
5222
+ $awareUpdate.dataset.tip = 'A bridge repair did not finish — open it to see which bridge and try again';
5223
+ $awareUpdate.setAttribute('aria-haspopup', 'dialog');
5224
+ }
5225
+
5226
+ /**
5227
+ * Terminal states whose remaining problem is BRIDGES, whoever started the job.
5228
+ *
5229
+ * Scoped to the operation on purpose: `partial` always means some bridges failed, but a
5230
+ * `runtime-failed` on a runtime UPGRADE is the upgrade failing — labelling that "Installed
5231
+ * bridges need attention" would be the same class of lie this change set out to remove, and the
5232
+ * ordinary re-check below correctly re-offers the upgrade instead.
5233
+ */
5234
+ const awareNeedsAttention = (s) => !!s && (s.status === 'partial'
5235
+ || (s.status === 'runtime-failed' && (s.operation || awareUpgradeOperation) === 'bridge-repair'));
5236
+
5237
+ /**
5238
+ * True when the live job state owns the pill and this generic re-check must keep its hands off.
5239
+ *
5240
+ * Checked BOTH before the fetch and again after it. Before-only was not enough and the gap was
5241
+ * observed, not theorised: at page load this runs while the controller is still `idle`, sails
5242
+ * past the guard, and by the time the response lands `adopt()` has discovered a failed automatic
5243
+ * repair and painted the attention pill — which the stale in-flight answer then overwrote with a
5244
+ * cheerful "Repair 1 installed bridge", erasing the only sign anything had gone wrong.
5245
+ */
5246
+ function awareJobOwnsPill() {
5247
+ const s = window.awareUpdateController && window.awareUpdateController.getState();
5248
+ if (!s) return false;
5249
+ if (s.status === 'starting' || s.status === 'running' || s.status === 'retrying') return true;
5250
+ if (awareNeedsAttention(s)) { paintAwareAttentionPill(); return true; }
5251
+ return false;
5252
+ }
5253
+
5195
5254
  async function refreshAwareUpdate() {
5196
5255
  if (!$awareUpdate) return;
5197
- if (window.awareUpdateController) {
5198
- const updateState = window.awareUpdateController.getState();
5199
- if (updateState.status === 'starting' || updateState.status === 'running' || updateState.status === 'retrying') return;
5200
- if (updateState.status === 'partial') {
5201
- $awareUpdate.hidden = false;
5202
- $awareUpdate.disabled = false;
5203
- $awareUpdate.textContent = 'Installed bridges need attention';
5204
- return;
5205
- }
5206
- }
5256
+ if (awareJobOwnsPill()) return;
5207
5257
  try {
5208
5258
  const r = await fetch('/api/aware/update');
5209
5259
  const d = await r.json();
5260
+ if (awareJobOwnsPill()) return; // the job resolved while this request was in flight
5210
5261
  awareUpdateCheck = r.ok ? d : null;
5211
5262
  if (r.ok && d.updateAvailable && d.targetVersion && d.operation === 'bridge-repair') {
5212
5263
  const count = Array.isArray(d.bridges) ? d.bridges.filter((row) => row.status !== 'current').length : 0;
@@ -5263,6 +5314,16 @@
5263
5314
 
5264
5315
  function closeAwareUpgradeModal() {
5265
5316
  if (!$awareUpgradeModal) return;
5317
+ // Retire an AUTOMATIC terminal result the user has now seen, or /active keeps handing it back
5318
+ // on every page load for the whole retention window. Scoped to this transaction and refused
5319
+ // server-side while it is still running, so closing the modal mid-repair cannot retire a job
5320
+ // that has not failed yet.
5321
+ if (awareUpdateClient) {
5322
+ const s = awareUpdateClient.getState();
5323
+ if (s.origin === 'auto' && (s.status === 'partial' || s.status === 'runtime-failed')) {
5324
+ awareUpdateClient.acknowledge(s.transaction).catch(() => {});
5325
+ }
5326
+ }
5266
5327
  hideModal($awareUpgradeModal);
5267
5328
  const restore = awareUpgradeReturnFocus;
5268
5329
  awareUpgradeReturnFocus = null;
@@ -5328,7 +5389,12 @@
5328
5389
  $awareUpgradeResults.insertAdjacentHTML('afterbegin', `<div class="aware-update-summary">${escapeHtml(s.retryError)}</div>`);
5329
5390
  }
5330
5391
  } else if (status === 'runtime-failed') {
5331
- $awareUpgradeLive.textContent = 'AWARE could not be upgraded.';
5392
+ // A bridge repair can terminalize here too (a failed preflight, smoke, or a runtime that
5393
+ // moved underneath it) — and it never set out to upgrade anything, so the generic wording
5394
+ // would be simply untrue.
5395
+ $awareUpgradeLive.textContent = operation === 'bridge-repair'
5396
+ ? "AWARE's installed bridges could not be refreshed."
5397
+ : 'AWARE could not be upgraded.';
5332
5398
  const reason = s.error && s.error.message ? s.error.message : 'Check your connection and try again.';
5333
5399
  $awareUpgradeResults.innerHTML = `<div class="aware-update-summary">${escapeHtml(reason)}</div>`;
5334
5400
  } else if (status === 'expired') {
@@ -5337,6 +5403,21 @@
5337
5403
  }
5338
5404
  }
5339
5405
 
5406
+ /**
5407
+ * Re-run the loads that unattended maintenance refused while it held the writer.
5408
+ *
5409
+ * The gate answers `maintenance-busy` rather than queuing — the wait it would otherwise impose
5410
+ * starts before any child exists, so nothing times it out and Stop cannot cancel it. But that
5411
+ * refusal also lands on ordinary reads like loadApps(), which have no reason to know about
5412
+ * bridges: without this the workflow list would simply stay empty until something else happened
5413
+ * to reload it. Only for `auto` work; a user-initiated upgrade already owns its own modal flow.
5414
+ */
5415
+ function awareMaintenanceRecover(s) {
5416
+ if (s.origin !== 'auto' || !awareMaintenanceRefused) return;
5417
+ awareMaintenanceRefused = false;
5418
+ loadApps().catch(() => { /* the picker keeps its own empty/error state */ });
5419
+ }
5420
+
5340
5421
  async function openAwareUpgrade(version, returnFocusTo) {
5341
5422
  if (!$awareUpgradeModal || !awareUpdateClient) {
5342
5423
  showToast('Could not open the AWARE update dialog.', 'warn');
@@ -5348,7 +5429,10 @@
5348
5429
  }
5349
5430
  const current = awareUpdateClient.getState();
5350
5431
  let target = version || awareUpgradeTarget || ($awareUpdate && $awareUpdate.dataset.target) || '';
5351
- if (!target && !awareBusy(current.status) && current.status !== 'partial') {
5432
+ // A registry hiccup must not swallow a terminal state we already hold: without widening this
5433
+ // to every attention state, a runtime-failed repair returns early with a toast and the modal
5434
+ // explaining the failure never opens.
5435
+ if (!target && !awareBusy(current.status) && !awareNeedsAttention(current)) {
5352
5436
  try {
5353
5437
  const check = await awareUpdateClient.check();
5354
5438
  awareUpdateCheck = check;
@@ -5363,7 +5447,11 @@
5363
5447
  awareUpgradeInventory = Array.isArray(check.bridges) ? check.bridges : [];
5364
5448
  awareUpgradeTarget = target;
5365
5449
  awareUpgradeReturnFocus = returnFocusTo || document.activeElement;
5366
- paintAwareUpgrade(awareBusy(current.status) || current.status === 'partial'
5450
+ // `runtime-failed` belongs here alongside `partial`. Without it, clicking the attention pill
5451
+ // synthesized a fresh IDLE offer — whose paint clears the results panel and empties the live
5452
+ // region — so the operation-specific explanation ("AWARE's installed bridges could not be
5453
+ // refreshed.") was composed and then never shown to anyone.
5454
+ paintAwareUpgrade(awareBusy(current.status) || awareNeedsAttention(current)
5367
5455
  ? current : { status: 'idle', transaction: null, target: awareUpgradeTarget });
5368
5456
  showModal($awareUpgradeModal);
5369
5457
  setTimeout(() => {
@@ -5379,30 +5467,51 @@
5379
5467
  if (awareUpdateClient && $awareUpgradeModal) {
5380
5468
  awareUpdateClient.subscribe((s) => {
5381
5469
  const busy = awareBusy(s.status);
5470
+ // The job's OWN operation, not the module variable openAwareUpgrade sets. A repair the
5471
+ // server started never opened the modal, so the variable still says 'runtime-update' and the
5472
+ // pill would announce "Upgrading AWARE…" while it is in fact refreshing bridges.
5473
+ const operation = s.operation || awareUpgradeOperation;
5382
5474
  if ($awareUpdate) {
5383
5475
  $awareUpdate.disabled = busy;
5384
5476
  $awareUpdate.setAttribute('aria-busy', busy ? 'true' : 'false');
5385
5477
  if (busy) {
5386
5478
  $awareUpdate.hidden = false;
5479
+ // The ↑ glyph means "a runtime upgrade is on offer" everywhere else in this footer;
5480
+ // every bridge-repair label deliberately goes without it, and a retry is bridge work.
5387
5481
  $awareUpdate.textContent = s.status === 'retrying'
5388
- ? '↑ Retrying bridge…'
5389
- : awareUpgradeOperation === 'bridge-repair' ? 'Repairing installed bridges…' : '↑ Upgrading AWARE…';
5390
- } else if (s.status === 'partial') {
5391
- $awareUpdate.hidden = false;
5392
- $awareUpdate.textContent = 'Installed bridges need attention';
5482
+ ? 'Retrying bridge…'
5483
+ : operation === 'bridge-repair' ? 'Repairing installed bridges…' : '↑ Upgrading AWARE…';
5484
+ } else if (awareNeedsAttention(s)) {
5485
+ // Every suppressed automatic failure must land on an ENABLED attention pill. Without the
5486
+ // runtime-failed arm the pill stays frozen on "Repairing installed bridges…" forever,
5487
+ // because the modal that would otherwise have explained it never opened.
5488
+ paintAwareAttentionPill();
5393
5489
  }
5394
5490
  }
5395
5491
  _updateApplying = busy ? 'aware' : (_updateApplying === 'aware' ? null : _updateApplying);
5396
5492
  paintAwareUpgrade(s);
5397
5493
  if (s.status === 'partial' || s.status === 'runtime-failed' || s.status === 'expired') {
5398
- if (!$awareUpgradeModal.classList.contains('show')) {
5494
+ // Stealing focus is right for a repair the user CLICKED — they are watching and it carries
5495
+ // recovery actions. It is wrong for one the server started: a modal thrown over the
5496
+ // workspace on launch is precisely the interruption "run it in the background" was chosen
5497
+ // to avoid. The attention pill above carries it instead, and opens this on demand.
5498
+ awareMaintenanceRecover(s);
5499
+ const hijack = s.origin !== 'auto';
5500
+ if (hijack && !$awareUpgradeModal.classList.contains('show')) {
5399
5501
  awareUpgradeReturnFocus = document.activeElement;
5400
5502
  showModal($awareUpgradeModal);
5401
5503
  setTimeout(() => (!$awareUpgradeRetry.hidden ? $awareUpgradeRetry : $awareUpgradeCancel).focus(), 0);
5504
+ } else if (!hijack && awareNeedsAttention(s)) {
5505
+ // Suppressing the modal must not mean suppressing the NEWS. Without this the quieter
5506
+ // outcome was louder than the urgent one: an automatic success toasted, while an
5507
+ // automatic failure — drag-out still broken — changed a footer label nobody was told to
5508
+ // look at. paintAwareUpgrade(s) ran just above, so this copy is already the right one.
5509
+ showToast($awareUpgradeLive.textContent, 'warn');
5402
5510
  }
5403
5511
  refreshAwareUpdate();
5404
5512
  } else if (s.status === 'success') {
5405
5513
  const version = s.observedVersion || s.target;
5514
+ awareMaintenanceRecover(s);
5406
5515
  const wv = document.getElementById('aware-version');
5407
5516
  if (wv && version) {
5408
5517
  wv.textContent = 'AWARE ' + version;
@@ -5443,12 +5552,29 @@
5443
5552
  if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
5444
5553
  else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
5445
5554
  };
5446
- awareUpdateClient.resume();
5555
+ // SERIALIZED, not fired together. A stored transaction lost across a server restart makes
5556
+ // resume() 404, clear storage, and fall through to the LEASED check route — which blocks
5557
+ // behind a running repair. Awaiting resume() first means adopt() then finds the live job
5558
+ // instead of the browser never learning about it.
5559
+ (async () => {
5560
+ // resume() is allowed to FAIL here — a transaction lost across a server restart is the
5561
+ // ordinary case — and adopt() must still run. Awaiting it unguarded meant one rejected
5562
+ // resume skipped discovery entirely, which is precisely the situation adopt() exists for.
5563
+ try { await awareUpdateClient.resume(); } catch { /* stale transaction; discovery continues */ }
5564
+ await awareUpdateClient.adopt();
5565
+ })().catch(() => {});
5447
5566
  }
5448
5567
 
5449
5568
  if ($awareUpdate) {
5450
5569
  $awareUpdate.onclick = () => {
5451
- if (awareUpdateClient && awareUpdateClient.getState().status === 'partial') {
5570
+ // Both attention states, not just `partial`. A runtime-failed automatic repair paints the
5571
+ // same pill but has no `dataset.operation` (paintAwareAttentionPill does not set it, and the
5572
+ // offer branches that would are now unreachable because awareJobOwnsPill bails first), so it
5573
+ // fell through to the release-notes popover with an empty version — the pill whose tooltip
5574
+ // says "open it to see which bridge" opened the changelog. It also made the failure
5575
+ // unacknowledgeable, since acknowledge only fires when this modal closes, so the warn toast
5576
+ // returned on every load for the full retention window.
5577
+ if (awareUpdateClient && awareNeedsAttention(awareUpdateClient.getState())) {
5452
5578
  openAwareUpgrade('', $awareUpdate);
5453
5579
  return;
5454
5580
  }
@@ -6232,6 +6358,11 @@
6232
6358
  // (installing only) → dim ticker; `status`/`reason` drive the card state.
6233
6359
  if (m.line != null) setBootstrapLogLine(m.line);
6234
6360
  if (m.status) updateBootstrap({ status: m.status, reason: m.reason ?? null, remediation: m.remediation ?? null });
6361
+ } else if (m.type === 'aware-update') {
6362
+ // The server started an automatic bridge repair. Adopt it now so an ALREADY-OPEN tab shows
6363
+ // it immediately; the init-time adopt() only covers tabs opened after it began. adopt() is
6364
+ // single-flight and idempotent, so the two racing is fine.
6365
+ if (window.awareUpdateController) window.awareUpdateController.adopt().catch(() => {});
6235
6366
  } else if (m.type === 'render-progress') {
6236
6367
  // Relayed as a DOM event rather than widening the bridge: workspaces.js owns the Exports
6237
6368
  // card and is the only listener, and a render can outlive several repaints of it.
@@ -578,7 +578,10 @@
578
578
  </div>
579
579
  </div>
580
580
 
581
- <div class="toast-container" id="toast-container"></div>
581
+ <!-- polite live region: toasts are the only channel for a few system conditions the user did not
582
+ trigger (the maintenance-busy refusal above all), and without this a screen-reader user gets
583
+ silence where a sighted user gets an explanation. -->
584
+ <div class="toast-container" id="toast-container" role="status" aria-live="polite"></div>
582
585
 
583
586
  <!-- Reusable styled prompt/form modal — used for node inputs (double-click an
584
587
  input node) and Tweak. Replaces native window.prompt so dialogs match the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.121.0",
3
+ "version": "0.122.0",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {