@floless/app 0.135.0 → 0.135.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.
@@ -19728,15 +19728,15 @@ var require_quote = __commonJS({
19728
19728
  '"': '\\"',
19729
19729
  "\\": "\\\\"
19730
19730
  };
19731
- function quote(s) {
19731
+ function quote3(s) {
19732
19732
  rxEscapable.lastIndex = 0;
19733
19733
  return '"' + (rxEscapable.test(s) ? s.replace(rxEscapable, (a) => {
19734
19734
  const c = escaped[a];
19735
19735
  return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
19736
19736
  }) : s) + '"';
19737
19737
  }
19738
- exports2.default = quote;
19739
- quote.code = 'require("ajv/dist/runtime/quote").default';
19738
+ exports2.default = quote3;
19739
+ quote3.code = 'require("ajv/dist/runtime/quote").default';
19740
19740
  }
19741
19741
  });
19742
19742
 
@@ -49443,9 +49443,9 @@ var require_lexer = __commonJS({
49443
49443
  }
49444
49444
  }
49445
49445
  *parseQuotedScalar() {
49446
- const quote = this.charAt(0);
49447
- let end = this.buffer.indexOf(quote, this.pos + 1);
49448
- if (quote === "'") {
49446
+ const quote3 = this.charAt(0);
49447
+ let end = this.buffer.indexOf(quote3, this.pos + 1);
49448
+ if (quote3 === "'") {
49449
49449
  while (end !== -1 && this.buffer[end + 1] === "'")
49450
49450
  end = this.buffer.indexOf("'", end + 2);
49451
49451
  } else {
@@ -52967,8 +52967,8 @@ function runRawWithEnvUnlocked(args, env2, timeoutMs, onSpawn, signal) {
52967
52967
  function runRawWithEnv(args, env2, timeoutMs, onSpawn, signal) {
52968
52968
  return withAwareShared(() => runRawWithEnvUnlocked(args, env2, timeoutMs, onSpawn, signal), signal);
52969
52969
  }
52970
- async function runJson(args, timeoutMs) {
52971
- const { code, stdout, stderr } = await runRawWithEnv([...args, "--json"], void 0, timeoutMs);
52970
+ async function runJson(args, timeoutMs, signal) {
52971
+ const { code, stdout, stderr } = await runRawWithEnv([...args, "--json"], void 0, timeoutMs, void 0, signal);
52972
52972
  let env2;
52973
52973
  try {
52974
52974
  env2 = JSON.parse(stdout);
@@ -53823,10 +53823,18 @@ async function connectList() {
53823
53823
  }
53824
53824
  var awareImpl = {
53825
53825
  npmVersion: awareNpmVersion,
53826
- /** Cheap readiness probe — true if `aware app list --json` returns ok. */
53827
- async smoke() {
53826
+ /**
53827
+ * Cheap readiness probe — true if `aware app list --json` returns ok.
53828
+ *
53829
+ * "Cheap" is relative: this is a real child process with a RUN_TIMEOUT_MS (60s) ceiling, and it
53830
+ * is the call observed timing out at exactly that in the field. Recovery runs it while holding
53831
+ * the exclusive lease, so it takes a signal — without one, an abort could only release the lease
53832
+ * after the full 60s, which is precisely the unbounded hold the budget exists to prevent.
53833
+ * Callers with no deadline (bootstrap, startup recovery) pass nothing and keep today's behaviour.
53834
+ */
53835
+ async smoke(signal) {
53828
53836
  try {
53829
- await this.list();
53837
+ await this.list(signal);
53830
53838
  return true;
53831
53839
  } catch {
53832
53840
  return false;
@@ -53837,8 +53845,8 @@ var awareImpl = {
53837
53845
  hostBridgeStatus,
53838
53846
  hostInstances,
53839
53847
  /** GET /api/apps */
53840
- async list() {
53841
- const { data } = await runJson(["app", "list"]);
53848
+ async list(signal) {
53849
+ const { data } = await runJson(["app", "list"], void 0, signal);
53842
53850
  return data.apps ?? [];
53843
53851
  },
53844
53852
  /** GET /api/agents — installed agent catalog (honors --json). */
@@ -55050,7 +55058,7 @@ function appVersion() {
55050
55058
  return resolveVersion({
55051
55059
  isSea: isSea2(),
55052
55060
  sqVersionXml: readSqVersionXml(),
55053
- define: true ? "0.135.0" : void 0,
55061
+ define: true ? "0.135.1" : void 0,
55054
55062
  pkgVersion: readPkgVersion()
55055
55063
  });
55056
55064
  }
@@ -55066,7 +55074,7 @@ function resolveChannel(s) {
55066
55074
  function appChannel() {
55067
55075
  return resolveChannel({
55068
55076
  isSea: isSea2(),
55069
- define: true ? "0.135.0" : void 0,
55077
+ define: true ? "0.135.1" : void 0,
55070
55078
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55071
55079
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55072
55080
  modulePath: process.argv[1]
@@ -68634,8 +68642,8 @@ function readSelectionFromBody(body) {
68634
68642
  return Object.keys(own2).length === 0 ? null : "invalid";
68635
68643
  }
68636
68644
  const raw = own2.memberIds;
68637
- const wellFormed = Array.isArray(raw) && raw.length > 0 && raw.length <= MAX_SELECTION_MEMBERS && raw.every((id) => typeof id === "string" && id.trim() !== "");
68638
- if (!wellFormed) return "invalid";
68645
+ const wellFormed2 = Array.isArray(raw) && raw.length > 0 && raw.length <= MAX_SELECTION_MEMBERS && raw.every((id) => typeof id === "string" && id.trim() !== "");
68646
+ if (!wellFormed2) return "invalid";
68639
68647
  return [...new Set(raw)];
68640
68648
  }
68641
68649
  function selectionMemberCount(contractInput) {
@@ -69848,16 +69856,38 @@ var PlanTransformError = class extends Error {
69848
69856
  var refuse = (code, message, plan) => {
69849
69857
  throw new PlanTransformError(code, message, plan && plan.viewKind);
69850
69858
  };
69851
- function gridIntersection(grid, ref, plan) {
69852
- if (!grid || typeof grid !== "object" || !finite2(grid.origin)) {
69853
- return refuse("grid-unavailable", `sheet "${plan.sheet || "?"}" has no model grid to resolve its registration controls`, plan);
69859
+ var MAX_QUOTED_CHARS = 48;
69860
+ var CONTROL_CHARS = new RegExp("[\\u0000-\\u001f\\u007f]", "g");
69861
+ var LONE_SURROGATE = new RegExp("[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]", "g");
69862
+ var wellFormed = (text5) => typeof text5.toWellFormed === "function" ? text5.toWellFormed() : text5.replace(LONE_SURROGATE, "\uFFFD");
69863
+ var clipQuoted = (value, max2 = MAX_QUOTED_CHARS) => {
69864
+ const text5 = wellFormed(typeof value === "string" && value ? value : "?").replace(CONTROL_CHARS, " ");
69865
+ if (max2 <= 0) return "";
69866
+ if (text5.length <= max2) return text5;
69867
+ let end = max2 - 1;
69868
+ const code = text5.charCodeAt(end - 1);
69869
+ if (end > 0 && code >= 55296 && code <= 56319) end--;
69870
+ return `${text5.slice(0, end)}\u2026`;
69871
+ };
69872
+ var quote = (value) => clipQuoted(value);
69873
+ function gridIntersection(grid, ref, plan, field) {
69874
+ if (!grid || typeof grid !== "object") {
69875
+ return refuse("grid-unavailable", `sheet "${quote(plan.sheet)}" has no model grid to resolve its registration controls`, plan);
69876
+ }
69877
+ if (!finite2(grid.origin)) {
69878
+ return refuse(
69879
+ "grid-unavailable",
69880
+ `sheet "${quote(plan.sheet)}" cannot resolve its registration controls: $.grid.origin is missing or unreadable \u2014 it must be two finite world-mm numbers giving where the first x and y grid axes cross`,
69881
+ plan
69882
+ );
69854
69883
  }
69855
69884
  if (!ref || typeof ref !== "object" || typeof ref.axis_x !== "string" || typeof ref.axis_y !== "string") {
69856
- return refuse("control-ref-invalid", `sheet "${plan.sheet || "?"}" has an unreadable registration control`, plan);
69885
+ return refuse("control-ref-invalid", `sheet "${quote(plan.sheet)}" has an unreadable ${field}: a registration control needs string axis_x and axis_y labels`, plan);
69857
69886
  }
69858
69887
  const X = parseSpacings(grid.x), Y = parseSpacings(grid.y);
69859
69888
  if (X.err || Y.err) {
69860
- return refuse("grid-spacing-invalid", `sheet "${plan.sheet || "?"}" cannot use an invalid model-grid spacing string`, plan);
69889
+ const bad = X.err ? "$.grid.x" : "$.grid.y";
69890
+ return refuse("grid-spacing-invalid", `sheet "${quote(plan.sheet)}" cannot use ${bad}: ${quote(X.err || Y.err)}`, plan);
69861
69891
  }
69862
69892
  const xs = axisLabelsFor(grid, "x", "num", X.offsets.length);
69863
69893
  const ys = axisLabelsFor(grid, "y", "alpha", Y.offsets.length);
@@ -69869,7 +69899,7 @@ function gridIntersection(grid, ref, plan) {
69869
69899
  if (xi < 0 || yi < 0) {
69870
69900
  return refuse(
69871
69901
  "control-ref-unresolved",
69872
- `sheet "${plan.sheet || "?"}" registration control ${ref.axis_x}/${ref.axis_y} does not resolve uniquely on the model grid`,
69902
+ `sheet "${quote(plan.sheet)}" ${field} names ${quote(ref.axis_x)}/${quote(ref.axis_y)}, which is not exactly one x and one y label on the model grid`,
69873
69903
  plan
69874
69904
  );
69875
69905
  }
@@ -69878,27 +69908,27 @@ function gridIntersection(grid, ref, plan) {
69878
69908
  function planTransform(plan) {
69879
69909
  const kind = plan && plan.viewKind;
69880
69910
  if (kind !== "plan") {
69881
- const named = typeof kind === "string" ? kind : "unknown";
69911
+ const named = typeof kind === "string" && kind ? quote(kind) : "unknown";
69882
69912
  return refuse(
69883
69913
  "view-kind-unsupported",
69884
- `sheet "${plan && plan.sheet || "?"}" is a ${named} view; ${named} views are not supported by the plan transform`,
69914
+ `sheet "${quote(plan && plan.sheet)}" is a ${named} view; ${named} views are not supported by the plan transform`,
69885
69915
  plan
69886
69916
  );
69887
69917
  }
69888
69918
  if (!finite2(plan.datum_at) || !finite2(plan.control2_at) || !plan.control2_ref) {
69889
69919
  return refuse(
69890
69920
  "registration-incomplete",
69891
- `sheet "${plan.sheet || "?"}" needs two resolved registration controls before it can be edited`,
69921
+ `sheet "${quote(plan.sheet)}" needs $.datum_at, $.control2_at and $.control2_ref before it can be edited`,
69892
69922
  plan
69893
69923
  );
69894
69924
  }
69895
69925
  const ptPerFt = Number(plan.pt_per_ft);
69896
69926
  if (!(ptPerFt > 0) || !Number.isFinite(ptPerFt)) {
69897
- return refuse("scale-invalid", `sheet "${plan.sheet || "?"}" has no positive drawing scale`, plan);
69927
+ return refuse("scale-invalid", `sheet "${quote(plan.sheet)}" has no positive $.pt_per_ft, so it has no drawing scale`, plan);
69898
69928
  }
69899
69929
  const registrationGrid = plan.modelGrid || plan.grid;
69900
- const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan) : [0, 0];
69901
- const world1 = gridIntersection(registrationGrid, plan.control2_ref, plan);
69930
+ const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan, "$.datum_ref") : [0, 0];
69931
+ const world1 = gridIntersection(registrationGrid, plan.control2_ref, plan, "$.control2_ref");
69902
69932
  const scale = mmPerPx(ptPerFt);
69903
69933
  const local1 = [
69904
69934
  (plan.control2_at[0] - plan.datum_at[0]) * scale,
@@ -69907,15 +69937,19 @@ function planTransform(plan) {
69907
69937
  const worldDelta = [world1[0] - world0[0], world1[1] - world0[1]];
69908
69938
  const localLen = Math.hypot(local1[0], local1[1]);
69909
69939
  const worldLen = Math.hypot(worldDelta[0], worldDelta[1]);
69910
- if (!(localLen > 1e-9) || !(worldLen > 1e-9)) {
69911
- return refuse("registration-degenerate", `sheet "${plan.sheet || "?"}" has coincident registration controls`, plan);
69940
+ if (!(localLen > 1e-9)) {
69941
+ return refuse("registration-degenerate", `sheet "${quote(plan.sheet)}" has coincident registration controls: $.datum_at and $.control2_at are the same point on the sheet`, plan);
69942
+ }
69943
+ if (!(worldLen > 1e-9)) {
69944
+ const datum = plan.datum_ref ? "$.datum_ref and $.control2_ref resolve to the same grid intersection" : "$.control2_ref resolves to the model origin, which is where an absent $.datum_ref already puts the datum";
69945
+ return refuse("registration-degenerate", `sheet "${quote(plan.sheet)}" has coincident registration controls: ${datum}`, plan);
69912
69946
  }
69913
69947
  const fitScale = worldLen / localLen;
69914
69948
  const rotation = Math.atan2(worldDelta[1], worldDelta[0]) - Math.atan2(local1[1], local1[0]);
69915
69949
  const c = Math.cos(rotation) * fitScale;
69916
69950
  const s = Math.sin(rotation) * fitScale;
69917
69951
  if (![c, s, fitScale, world0[0], world0[1]].every(Number.isFinite)) {
69918
- return refuse("registration-invalid", `sheet "${plan.sheet || "?"}" has a non-finite registration transform`, plan);
69952
+ return refuse("registration-invalid", `sheet "${quote(plan.sheet)}" has a non-finite registration transform`, plan);
69919
69953
  }
69920
69954
  return { datumPx: plan.datum_at, world0, mmPerPx: scale, fitScale, rotation, c, s };
69921
69955
  }
@@ -70378,21 +70412,95 @@ function observationZ(observation, observationEnd) {
70378
70412
  const z = observationEnd === 0 ? observation.evidence.observed?.fromZ?.value : observation.evidence.observed?.toZ?.value;
70379
70413
  return z && "known" in z && Number.isFinite(z.known) ? { known: z.known } : null;
70380
70414
  }
70381
- function observationPoint(model, plan, observation, observationEnd) {
70415
+ var MAX_EVIDENCE_NOTE_JSON_BYTES = 260;
70416
+ var MAX_NOTES_PER_REASON = 2;
70417
+ var quote2 = (value) => clipQuoted(value);
70418
+ var ENDPOINT_EVIDENCE_BLOCKING_REASONS = /* @__PURE__ */ new Set([
70419
+ "endpoint-elevation-missing",
70420
+ "view-scale-invalid",
70421
+ "observation-scale-mismatch",
70422
+ "view-unregistered",
70423
+ "cross-view-conflict"
70424
+ ]);
70425
+ var EvidenceNotes = class _EvidenceNotes {
70426
+ byEndpoint = /* @__PURE__ */ new Map();
70427
+ static key(memberId, end, reason) {
70428
+ return `${memberId}\0${end}\0${reason}`;
70429
+ }
70430
+ /**
70431
+ * First note wins for an endpoint+reason — it is the first failure the reader has to fix anyway —
70432
+ * EXCEPT when `comprehensive` says this one accounts for every offender at once. A scope-level
70433
+ * refusal names all the unregistered sheets in the scope, where a per-observation one names the one
70434
+ * sheet that observation came from; publishing the narrower of the two is true but sends the author
70435
+ * round the repair-and-re-audit loop once per sheet, which is what #925 is about.
70436
+ */
70437
+ record(memberId, end, reason, note, comprehensive = false) {
70438
+ const key2 = _EvidenceNotes.key(memberId, end, reason);
70439
+ if (this.byEndpoint.has(key2) && !comprehensive) return;
70440
+ let text5 = note;
70441
+ while (text5.length > 0 && Buffer.byteLength(JSON.stringify(text5), "utf8") > MAX_EVIDENCE_NOTE_JSON_BYTES) {
70442
+ text5 = clipQuoted(text5, text5.length - 1);
70443
+ }
70444
+ this.byEndpoint.set(key2, text5);
70445
+ }
70446
+ /**
70447
+ * Sorted so the report is deterministic whatever order plans and endpoints were visited in.
70448
+ *
70449
+ * `omitted` is the count the per-reason cap left out, and it exists so the REFUSAL can be honest:
70450
+ * without it the audit could only count what it received, and would say "1 further diagnosis" while
70451
+ * three were dropped here. A message that undercounts what is left to fix is its own version of the
70452
+ * bug this issue reports.
70453
+ */
70454
+ publish(findings, retainedMemberIds) {
70455
+ const byReason = /* @__PURE__ */ new Map();
70456
+ const seen = /* @__PURE__ */ new Map();
70457
+ for (const finding of findings) {
70458
+ if (retainedMemberIds.has(finding.memberId)) continue;
70459
+ for (const reason of finding.reasonCodes) {
70460
+ if (!ENDPOINT_EVIDENCE_BLOCKING_REASONS.has(reason)) continue;
70461
+ const note = this.byEndpoint.get(_EvidenceNotes.key(finding.memberId, finding.end, reason));
70462
+ if (note === void 0) continue;
70463
+ let all = seen.get(reason);
70464
+ if (!all) {
70465
+ all = /* @__PURE__ */ new Set();
70466
+ seen.set(reason, all);
70467
+ }
70468
+ all.add(note);
70469
+ let notes2 = byReason.get(reason);
70470
+ if (!notes2) {
70471
+ notes2 = /* @__PURE__ */ new Set();
70472
+ byReason.set(reason, notes2);
70473
+ }
70474
+ if (notes2.size < MAX_NOTES_PER_REASON) notes2.add(note);
70475
+ }
70476
+ }
70477
+ const notes = [...byReason].flatMap(([reason, kept]) => [...kept].sort().map((note) => ({ reason, note }))).sort((a, b) => a.reason.localeCompare(b.reason) || a.note.localeCompare(b.note));
70478
+ const distinct = [...seen.values()].reduce((total, all) => total + all.size, 0);
70479
+ return { notes, omitted: distinct - notes.length };
70480
+ }
70481
+ };
70482
+ function observationPoint(model, plan, observation, observationEnd, memberId, memberEnd, diagnoses) {
70382
70483
  const local = observation.evidence.local.wp[observationEnd];
70484
+ const fail3 = (reason, note) => {
70485
+ diagnoses.record(memberId, memberEnd, reason, note({
70486
+ sheet: `sheet "${quote2(plan.sheet)}"`,
70487
+ obs: `observation "${quote2(observation.id)}"`
70488
+ }));
70489
+ return { kind: "failure", reason };
70490
+ };
70383
70491
  if (!(typeof plan.pt_per_ft === "number" && Number.isFinite(plan.pt_per_ft) && plan.pt_per_ft > 0)) {
70384
- return { kind: "failure", reason: "view-scale-invalid" };
70492
+ return fail3("view-scale-invalid", ({ sheet }) => `${sheet} has no positive $.pt_per_ft, so its drawing scale cannot place an observation`);
70385
70493
  }
70386
70494
  if (observation.evidence.local.pt_per_ft !== plan.pt_per_ft) {
70387
- return { kind: "failure", reason: "observation-scale-mismatch" };
70495
+ return fail3("observation-scale-mismatch", ({ sheet, obs }) => `${sheet} is registered at ${plan.pt_per_ft} pt/ft but ${obs} records ${observation.evidence.local.pt_per_ft} pt/ft`);
70388
70496
  }
70389
70497
  try {
70390
70498
  if (plan.viewKind === "plan") {
70391
70499
  const z = observationZ(observation, observationEnd);
70392
- if (!z) return { kind: "failure", reason: "endpoint-elevation-missing" };
70500
+ if (!z) return fail3("endpoint-elevation-missing", ({ sheet, obs }) => `${sheet} is a plan view, so this endpoint's elevation must come from ${obs} observed.${observationEnd === 0 ? "fromZ" : "toZ"}, which is absent or unknown`);
70393
70501
  const transformed = sheetPxToWorld(local, { ...plan, modelGrid: model.grid }, z);
70394
70502
  const point3 = known(transformed);
70395
- return point3 ? { kind: "point", point: point3 } : { kind: "failure", reason: "view-unregistered" };
70503
+ return point3 ? { kind: "point", point: point3 } : fail3("view-unregistered", ({ sheet, obs }) => `${sheet} registration maps ${obs} to a non-finite world point`);
70396
70504
  }
70397
70505
  if ((plan.viewKind === "elevation" || plan.viewKind === "section") && plan.sourceRegistration) {
70398
70506
  const registration = plan.sourceRegistration;
@@ -70405,14 +70513,14 @@ function observationPoint(model, plan, observation, observationEnd) {
70405
70513
  y: origin.y + registration.worldU[1] * du + registration.worldV[1] * dv,
70406
70514
  z: { known: origin.z.known + registration.worldU[2] * du + registration.worldV[2] * dv }
70407
70515
  };
70408
- return known(point3) ? { kind: "point", point: point3 } : { kind: "failure", reason: "view-unregistered" };
70516
+ return known(point3) ? { kind: "point", point: point3 } : fail3("view-unregistered", ({ sheet, obs }) => `${sheet} sourceRegistration maps ${obs} to a non-finite world point`);
70409
70517
  }
70410
70518
  } catch (error) {
70411
- if (error instanceof PlanTransformError) return { kind: "failure", reason: "view-unregistered" };
70519
+ if (error instanceof PlanTransformError) return fail3("view-unregistered", () => error.message);
70412
70520
  const identity = `${plan.sheet}/${observation.id}/end-${observationEnd + 1}`;
70413
70521
  throw new Error(`member-end evidence transform failed unexpectedly for ${identity}`, { cause: error });
70414
70522
  }
70415
- return { kind: "failure", reason: "view-unregistered" };
70523
+ return fail3("view-unregistered", ({ sheet }) => plan.viewKind === "elevation" || plan.viewKind === "section" ? `${sheet} is ${plan.viewKind === "section" ? "a section" : "an elevation"} view with no sourceRegistration, so a drawing observation on it cannot be placed in the model` : `${sheet} has viewKind "${plan.viewKind}"; only a registered plan, elevation or section view can place a drawing observation`);
70416
70524
  }
70417
70525
  var evidenceKey = (memberId, end) => `${memberId}\0${end}`;
70418
70526
  function finalizedEvidence(accumulator) {
@@ -70442,7 +70550,7 @@ function finalizedEvidence(accumulator) {
70442
70550
  conflict: points.size > 1
70443
70551
  };
70444
70552
  }
70445
- function buildEvidenceIndex(model, plans, deadlineMs) {
70553
+ function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70446
70554
  const accumulators = /* @__PURE__ */ new Map();
70447
70555
  for (const plan of plans) for (const observation of plan.memberObservations ?? []) {
70448
70556
  if (Date.now() > deadlineMs) {
@@ -70470,7 +70578,7 @@ function buildEvidenceIndex(model, plans, deadlineMs) {
70470
70578
  if (accumulator.contributionIds.size > SUPPORT_CENTERLINE_V1.maxObservationsPerEnd) {
70471
70579
  throw new MemberEndAnalysisWorkLimitError("Member-end analysis exceeded the per-end drawing-observation budget.");
70472
70580
  }
70473
- const observed = observationPoint(model, plan, observation, row.observationEnd);
70581
+ const observed = observationPoint(model, plan, observation, row.observationEnd, row.memberId, row.memberEnd, diagnoses);
70474
70582
  const tolerance = thresholdsForDrawingScale(observation.evidence.local.pt_per_ft);
70475
70583
  if (observed.kind === "failure") {
70476
70584
  accumulator.failures.add(observed.reason);
@@ -70551,7 +70659,28 @@ function fromDecision(member, end, role) {
70551
70659
  invalidationId: decision.invalidationId
70552
70660
  };
70553
70661
  }
70554
- function freshFinding(member, end, role, scope, evidence, result) {
70662
+ function unregisteredScopeNote(plans) {
70663
+ const offenders = plans.filter((plan) => !((plan.viewKind === "elevation" || plan.viewKind === "section") && !!plan.sourceRegistration));
70664
+ const remedy = offenders.every((plan) => plan.viewKind === "elevation" || plan.viewKind === "section") ? "every selected view in this elevation/section scope needs sourceRegistration before any endpoint in it can be analysed; missing on" : "only an elevation or section view carrying sourceRegistration can place geometry in this scope, and no other view kind can carry one; not usable";
70665
+ const named = offenders.slice(0, 3).map((plan) => `"${quote2(plan.sheet)}"`).join(", ");
70666
+ const more = offenders.length > 3 ? ` and ${offenders.length - 3} more` : "";
70667
+ return `${remedy}: ${named}${more}`;
70668
+ }
70669
+ function recordDerivedNotes(plans, analysis, evidence, subjectReasons, memberId, end, diagnoses) {
70670
+ if (subjectReasons.includes("view-unregistered") && analysis.kind === "elevation" && !analysis.registered) {
70671
+ diagnoses.record(memberId, end, "view-unregistered", unregisteredScopeNote(plans), true);
70672
+ }
70673
+ if (evidence.conflict) {
70674
+ const points = new Set((evidence.basis?.origins ?? []).map((origin) => JSON.stringify(origin.observedPoint)));
70675
+ diagnoses.record(
70676
+ memberId,
70677
+ end,
70678
+ "cross-view-conflict",
70679
+ `a member endpoint's drawing observations disagree \u2014 they place it at ${points.size} different world points, so no single drawing-backed point exists`
70680
+ );
70681
+ }
70682
+ }
70683
+ function freshFinding(member, end, role, scope, plans, analysis, evidence, result, diagnoses) {
70555
70684
  const currentPoint = end === 0 ? member.from : member.to;
70556
70685
  const geometryOnly = !evidence.basis;
70557
70686
  const completeTargets = targetsOf(result);
@@ -70577,6 +70706,9 @@ function freshFinding(member, end, role, scope, evidence, result) {
70577
70706
  ...evidence.basis ? { basis: evidence.basis } : {}
70578
70707
  };
70579
70708
  const subjectReasons = result.kind === "not-checkable" ? result.reasons.map((reason) => reasonMap[reason]) : [];
70709
+ if (evidence.conflict || subjectReasons.includes("view-unregistered")) {
70710
+ recordDerivedNotes(plans, analysis, evidence, subjectReasons, member.id, end, diagnoses);
70711
+ }
70580
70712
  if (evidence.failures.length) return {
70581
70713
  ...base,
70582
70714
  classification: "not-checkable",
@@ -70647,7 +70779,7 @@ function counts(findings) {
70647
70779
  notCheckable: findings.filter((item) => item.classification === "not-checkable").length
70648
70780
  };
70649
70781
  }
70650
- function analyzeSteelMemberEnds(model, scope) {
70782
+ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ */ new Set()) {
70651
70783
  const normalizedScope2 = scope.kind === "conversion" ? { kind: "conversion", viewIds: [...new Set(scope.viewIds)].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))) } : scope;
70652
70784
  if (normalizedScope2.kind === "conversion" && normalizedScope2.viewIds.length === 0) {
70653
70785
  throw new TypeError("conversion endpoint analysis requires at least one view id");
@@ -70661,7 +70793,8 @@ function analyzeSteelMemberEnds(model, scope) {
70661
70793
  const targetMembers = model.members.map(targetMember).filter((item) => !!item);
70662
70794
  const targetMap = new Map(targetMembers.map((member) => [member.id, member]));
70663
70795
  const deadlineMs = Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs;
70664
- const evidenceIndex = buildEvidenceIndex(model, plans, deadlineMs);
70796
+ const diagnoses = new EvidenceNotes();
70797
+ const evidenceIndex = buildEvidenceIndex(model, plans, deadlineMs, diagnoses);
70665
70798
  const spatialIndex = new MemberEndSpatialIndex(orderedCandidateRecords(targetMembers), deadlineMs);
70666
70799
  const findings = [];
70667
70800
  let subjectEnds = 0;
@@ -70690,10 +70823,10 @@ function analyzeSteelMemberEnds(model, scope) {
70690
70823
  continue;
70691
70824
  }
70692
70825
  if (!analyzed) {
70693
- const finding2 = freshFinding(member, end, role.finding, normalizedScope2, evidence, {
70826
+ const finding2 = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, {
70694
70827
  kind: "not-checkable",
70695
70828
  reasons: Object.freeze(["subject-geometry-invalid"])
70696
- });
70829
+ }, diagnoses);
70697
70830
  if (finding2) findings.push(finding2);
70698
70831
  continue;
70699
70832
  }
@@ -70709,18 +70842,21 @@ function analyzeSteelMemberEnds(model, scope) {
70709
70842
  targets: targetMap,
70710
70843
  consumeExactGeometryTest
70711
70844
  });
70712
- const finding = freshFinding(member, end, role.finding, normalizedScope2, evidence, result);
70845
+ const finding = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, result, diagnoses);
70713
70846
  if (finding) findings.push(finding);
70714
70847
  }
70715
70848
  }
70716
70849
  findings.sort((a, b) => Buffer.compare(Buffer.from(findingSortKey(a)), Buffer.from(findingSortKey(b))));
70850
+ const { notes: evidenceNotes, omitted } = diagnoses.publish(findings, retainedMemberIds);
70717
70851
  return {
70718
70852
  version: 1,
70719
70853
  policy: SUPPORT_CENTERLINE_POLICY,
70720
70854
  contractHash: asHash(model),
70721
70855
  scope: normalizedScope2,
70722
70856
  findings,
70723
- counts: counts(findings)
70857
+ counts: counts(findings),
70858
+ ...evidenceNotes.length ? { evidenceNotes } : {},
70859
+ ...omitted > 0 ? { evidenceNotesOmitted: omitted } : {}
70724
70860
  };
70725
70861
  }
70726
70862
  function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE__ */ new Set(), currentModel) {
@@ -70749,14 +70885,17 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70749
70885
  const literalContractHash = asHash(literal);
70750
70886
  const retainedMemberIdsHash = hashRetainedMemberIds(existingMemberIds);
70751
70887
  if (viewIds.length === 0) {
70752
- const report2 = analyzeSteelMemberEnds(sanitized, { kind: "model-3d" });
70888
+ const report2 = analyzeSteelMemberEnds(sanitized, { kind: "model-3d" }, existingMemberIds);
70753
70889
  return { literalContractHash, finalContractHash: asHash(sanitized), model: sanitized, report: report2, retainedMemberIdsHash };
70754
70890
  }
70755
70891
  const conversionScope = { kind: "conversion", viewIds };
70756
70892
  const evidenceIndex = buildEvidenceIndex(
70757
70893
  sanitized,
70758
70894
  selectedPlans(sanitized, conversionScope),
70759
- Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs
70895
+ Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs,
70896
+ // Discarded on purpose: this index only decides which literal endpoints match their immutable
70897
+ // observation. Nothing is published from here — `analyzeSteelMemberEnds` below builds the report.
70898
+ new EvidenceNotes()
70760
70899
  );
70761
70900
  for (const member of sanitized.members) {
70762
70901
  if (existingMemberIds.has(member.id) || !roleOf(member)) continue;
@@ -70773,7 +70912,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70773
70912
  }
70774
70913
  }
70775
70914
  }
70776
- const conversion = analyzeSteelMemberEnds(sanitized, conversionScope);
70915
+ const conversion = analyzeSteelMemberEnds(sanitized, conversionScope, existingMemberIds);
70777
70916
  const model = cloneModel(sanitized);
70778
70917
  for (const finding of conversion.findings) {
70779
70918
  if (finding.classification !== "aligned-auto" || existingMemberIds.has(finding.memberId)) continue;
@@ -70810,7 +70949,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70810
70949
  )
70811
70950
  };
70812
70951
  }
70813
- let report = analyzeSteelMemberEnds(model, { kind: "conversion", viewIds });
70952
+ let report = analyzeSteelMemberEnds(model, { kind: "conversion", viewIds }, existingMemberIds);
70814
70953
  if (existingMemberIds.size) {
70815
70954
  const findings = report.findings.map((finding) => {
70816
70955
  if (finding.classification !== "aligned-auto" || !existingMemberIds.has(finding.memberId)) return finding;
@@ -70850,7 +70989,9 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70850
70989
  const freshEvidence = viewIds.length ? buildEvidenceIndex(
70851
70990
  model,
70852
70991
  selectedPlans(model, { kind: "conversion", viewIds }),
70853
- Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs
70992
+ Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs,
70993
+ // Discarded on purpose, as above: this index feeds the replay comparison, not the report.
70994
+ new EvidenceNotes()
70854
70995
  ) : /* @__PURE__ */ new Map();
70855
70996
  const literalized = cloneModel(model);
70856
70997
  const literalMembers = new Map(literalized.members.map((member) => [member.id, member]));
@@ -70889,7 +71030,8 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70889
71030
  }
70890
71031
  const replay = analyzeSteelMemberEnds(
70891
71032
  literalized,
70892
- viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" }
71033
+ viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" },
71034
+ retainedMemberIds
70893
71035
  );
70894
71036
  const replayFindings = new Map(replay.findings.map((finding) => [evidenceKey(finding.memberId, finding.end), finding]));
70895
71037
  for (const [key2, { member, end, observedPoint, decision }] of replaySubjects) {
@@ -70904,7 +71046,7 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70904
71046
  );
70905
71047
  }
70906
71048
  }
70907
- let report = analyzeSteelMemberEnds(model, viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" });
71049
+ let report = analyzeSteelMemberEnds(model, viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" }, retainedMemberIds);
70908
71050
  if (retainedMemberIds.size) {
70909
71051
  const findings = report.findings.map((finding) => {
70910
71052
  if (finding.classification !== "aligned-auto" || !retainedMemberIds.has(finding.memberId)) return finding;
@@ -70951,6 +71093,7 @@ var MAX_FACET_EXCLUSIONS = 5e3;
70951
71093
  var MAX_FACET_VALUE_CHARS = 200;
70952
71094
  var MAX_DISPOSITION_GROUPS = 5e3;
70953
71095
  var MAX_JOINTS = 1e4;
71096
+ var MAX_REPORTED_NOTES_PER_REASON = 1;
70954
71097
  var MAX_MEMBERS = 1e4;
70955
71098
  var MAX_TEXT = 1e3;
70956
71099
  var SHA = /^[0-9a-f]{64}$/;
@@ -71425,18 +71568,20 @@ function evaluateSteelRead(context) {
71425
71568
  const observationAudit = activeObservationElements(candidate, retainedMemberIds);
71426
71569
  const observations2 = observationAudit.elements;
71427
71570
  if (validation.valid) {
71428
- const evidenceReasons = /* @__PURE__ */ new Set([
71429
- "endpoint-elevation-missing",
71430
- "view-scale-invalid",
71431
- "observation-scale-mismatch",
71432
- "view-unregistered",
71433
- "cross-view-conflict"
71434
- ]);
71435
- const endpointEvidence = context.normalization.report.findings.filter((finding) => !retainedMemberIds.has(finding.memberId)).flatMap((finding) => finding.reasonCodes.filter((reason) => evidenceReasons.has(reason)).map((reason) => `${finding.memberId}:${finding.end}:${reason}`));
71571
+ const evidenceReasons = ENDPOINT_EVIDENCE_BLOCKING_REASONS;
71572
+ const blockingFindings = context.normalization.report.findings.filter((finding) => !retainedMemberIds.has(finding.memberId)).filter((finding) => finding.reasonCodes.some((reason) => evidenceReasons.has(reason)));
71573
+ const endpointEvidence = blockingFindings.flatMap((finding) => finding.reasonCodes.filter((reason) => evidenceReasons.has(reason)).map((reason) => `${finding.memberId}:${finding.end}:${reason}`));
71574
+ const blockingReasons = new Set(blockingFindings.flatMap((finding) => finding.reasonCodes.filter((reason) => evidenceReasons.has(reason))));
71575
+ const relevant = (context.normalization.report.evidenceNotes ?? []).filter((row) => blockingReasons.has(row.reason));
71576
+ const byReason = /* @__PURE__ */ new Map();
71577
+ for (const row of relevant) byReason.set(row.reason, [...byReason.get(row.reason) ?? [], row.note]);
71578
+ const shown = [...byReason].sort(([a], [b]) => a.localeCompare(b)).flatMap(([, notes]) => [...new Set(notes)].sort().slice(0, MAX_REPORTED_NOTES_PER_REASON));
71579
+ const rest = new Set(relevant.map((row) => row.note)).size - shown.length + (context.normalization.report.evidenceNotesOmitted ?? 0);
71580
+ const diagnosis = shown.length ? `: ${shown.join("; ")}${rest > 0 ? `; and ${rest} further distinct ${rest === 1 ? "diagnosis" : "diagnoses"}` : ""}` : "";
71436
71581
  add(
71437
71582
  "endpoint-evidence",
71438
71583
  endpointEvidence.length ? "block" : "pass",
71439
- endpointEvidence.length ? `${endpointEvidence.length} new-member endpoint evidence diagnostic(s) require correction` : "new-member endpoint drawing evidence is complete and consistent",
71584
+ endpointEvidence.length ? `${endpointEvidence.length} new-member endpoint-evidence ${endpointEvidence.length === 1 ? "diagnostic requires" : "diagnostics require"} correction${diagnosis}` : "new-member endpoint drawing evidence is complete and consistent",
71440
71585
  endpointEvidence
71441
71586
  );
71442
71587
  } else add("endpoint-evidence", "block", "endpoint evidence cannot be evaluated until the v2 contract is valid");
@@ -77294,14 +77439,14 @@ function registerRevisionRoutes(app, deps = {}) {
77294
77439
  });
77295
77440
  }
77296
77441
  const dims = new Set(MODE_ORDER);
77297
- const wellFormed = submitted.every((row) => {
77442
+ const wellFormed2 = submitted.every((row) => {
77298
77443
  if (!row || typeof row !== "object" || Array.isArray(row)) return false;
77299
77444
  const entry2 = row;
77300
77445
  if (Object.keys(entry2).length !== 2 || typeof entry2.dim !== "string" || !dims.has(entry2.dim)) return false;
77301
77446
  if (entry2.dim === "thickness") return typeof entry2.value === "number" && Number.isFinite(entry2.value);
77302
77447
  return typeof entry2.value === "string" && entry2.value.length > 0 && entry2.value.length <= MAX_SIGNOFF_STRING_VALUE;
77303
77448
  });
77304
- if (!wellFormed || typeof bodyObj.mode !== "string" || typeof bodyObj.manifestHash !== "string" || typeof bodyObj.controlsHash !== "string") {
77449
+ if (!wellFormed2 || typeof bodyObj.mode !== "string" || typeof bodyObj.manifestHash !== "string" || typeof bodyObj.controlsHash !== "string") {
77305
77450
  return reply.status(400).send({
77306
77451
  ok: false,
77307
77452
  code: "steel-exclusion-signoff-invalid",
@@ -92617,14 +92762,30 @@ function createMaintenanceMarkerStore(markerPath2, options = {}) {
92617
92762
  });
92618
92763
  }
92619
92764
  },
92620
- async clear() {
92765
+ async clear(expectTransaction) {
92766
+ if (expectTransaction !== void 0) {
92767
+ const current = await this.read();
92768
+ if (current.kind === "valid" && current.marker.transaction !== expectTransaction) return false;
92769
+ if (current.kind === "corrupt") return false;
92770
+ }
92621
92771
  await io.rm(markerPath2, { force: true });
92772
+ return true;
92622
92773
  },
92623
- async quarantine() {
92774
+ async replaceCorrupt(replacement) {
92624
92775
  const quarantinePath = `${markerPath2}.corrupt`;
92625
- await io.rm(quarantinePath, { force: true });
92626
- await io.rename(markerPath2, quarantinePath);
92627
- await io.chmod(quarantinePath, 384);
92776
+ let corrupt = null;
92777
+ try {
92778
+ corrupt = await io.readFile(markerPath2, "utf8");
92779
+ } catch {
92780
+ corrupt = null;
92781
+ }
92782
+ await this.write(replacement);
92783
+ if (corrupt === null) return;
92784
+ try {
92785
+ await io.rm(quarantinePath, { force: true });
92786
+ await io.writeFile(quarantinePath, corrupt, { encoding: "utf8", flag: "wx", mode: 384 });
92787
+ } catch {
92788
+ }
92628
92789
  }
92629
92790
  };
92630
92791
  }
@@ -93003,8 +93164,10 @@ var import_node_child_process14 = require("node:child_process");
93003
93164
  var import_promises9 = require("node:fs/promises");
93004
93165
  var import_node_util7 = require("node:util");
93005
93166
  var execFileAsync3 = (0, import_node_util7.promisify)(import_node_child_process14.execFile);
93167
+ var TIMED_OUT = /* @__PURE__ */ Symbol("installer-tree-probe-deadline");
93006
93168
  var INSTALLER_COMMAND_LINE_PATTERN = "@aware-aeco/cli@|\\baware(?:\\.cmd|\\.js)?\\W?\\s+sidecar\\s+install";
93007
93169
  var INSTALLER_RE = new RegExp(INSTALLER_COMMAND_LINE_PATTERN);
93170
+ var PROBE_TIMEOUT_MS = 5e3;
93008
93171
  function matchesInstallerCommandLine(commandLine) {
93009
93172
  return INSTALLER_RE.test(commandLine);
93010
93173
  }
@@ -93055,9 +93218,37 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
93055
93218
  }
93056
93219
  }
93057
93220
  if (platform === "linux") {
93221
+ const now = deps.now ?? (() => performance.now());
93222
+ const deadline = now() + PROBE_TIMEOUT_MS;
93223
+ const withinDeadline = async (work) => {
93224
+ const settled2 = work.then(
93225
+ (value) => ({ ok: true, value }),
93226
+ (error) => ({ ok: false, error })
93227
+ );
93228
+ const left = deadline - now();
93229
+ if (left <= 0) return TIMED_OUT;
93230
+ let timer;
93231
+ let outcome;
93232
+ try {
93233
+ outcome = await Promise.race([
93234
+ settled2,
93235
+ new Promise((resolve21) => {
93236
+ timer = setTimeout(() => resolve21(TIMED_OUT), left);
93237
+ timer.unref?.();
93238
+ })
93239
+ ]);
93240
+ } finally {
93241
+ if (timer) clearTimeout(timer);
93242
+ }
93243
+ if (outcome === TIMED_OUT) return TIMED_OUT;
93244
+ if (!outcome.ok) throw outcome.error;
93245
+ return outcome.value;
93246
+ };
93058
93247
  let entries;
93059
93248
  try {
93060
- entries = await (deps.listProcDir ?? (() => (0, import_promises9.readdir)("/proc")))();
93249
+ const listed = await withinDeadline((deps.listProcDir ?? (() => (0, import_promises9.readdir)("/proc")))());
93250
+ if (listed === TIMED_OUT) return true;
93251
+ entries = listed;
93061
93252
  } catch {
93062
93253
  return true;
93063
93254
  }
@@ -93066,7 +93257,9 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
93066
93257
  if (!/^\d+$/.test(entry2) || Number(entry2) === selfPid) continue;
93067
93258
  let raw;
93068
93259
  try {
93069
- raw = await read2(entry2);
93260
+ const value = await withinDeadline(read2(entry2));
93261
+ if (value === TIMED_OUT) return true;
93262
+ raw = value;
93070
93263
  } catch (err2) {
93071
93264
  if (isVanishedProcessError(err2)) continue;
93072
93265
  return true;
@@ -93083,6 +93276,7 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
93083
93276
  }
93084
93277
 
93085
93278
  // aware-update-jobs.ts
93279
+ var MAINTENANCE_RECOVERY = "maintenance-recovery";
93086
93280
  var AwareUpdateConflictError = class extends Error {
93087
93281
  status = 409;
93088
93282
  };
@@ -93094,6 +93288,10 @@ var AwareUpdateGoneError = class extends Error {
93094
93288
  };
93095
93289
  var DEFAULT_OPERATION_TIMEOUT = 10 * 6e4;
93096
93290
  var DEFAULT_JOB_TIMEOUT = 30 * 6e4;
93291
+ var RECOVERY_BUDGET_MS = 15 * 6e4;
93292
+ var RECOVERY_UNCANCELLABLE_TAIL_MS = IDENTITY_ATTEMPTS * IDENTITY_ATTEMPT_TIMEOUT_MS + PROBE_TIMEOUT_MS;
93293
+ var RECOVERY_GRACE_MS = 2 * 6e4;
93294
+ var RECOVERY_WORK_BUDGET_MS = RECOVERY_BUDGET_MS - RECOVERY_GRACE_MS;
93097
93295
  var DEFAULT_RETENTION_TTL = 30 * 6e4;
93098
93296
  var DEFAULT_MAX_RETAINED = 24;
93099
93297
  function frozenHosts(hosts) {
@@ -93130,6 +93328,25 @@ var DeadlineError = class extends Error {
93130
93328
  function remaining(deadline, now) {
93131
93329
  return Math.max(0, deadline - now());
93132
93330
  }
93331
+ function settledWithin(work, budgetMs, fallback2, signal) {
93332
+ const guarded = work.then((value) => value, () => fallback2);
93333
+ if (budgetMs <= 0 || signal?.aborted) return Promise.resolve(fallback2);
93334
+ return new Promise((resolve21) => {
93335
+ const done = (value) => {
93336
+ cleanup();
93337
+ resolve21(value);
93338
+ };
93339
+ const onAbort = () => done(fallback2);
93340
+ const timer = setTimeout(() => done(fallback2), budgetMs);
93341
+ timer.unref?.();
93342
+ const cleanup = () => {
93343
+ clearTimeout(timer);
93344
+ signal?.removeEventListener("abort", onAbort);
93345
+ };
93346
+ signal?.addEventListener("abort", onAbort, { once: true });
93347
+ void guarded.then(done);
93348
+ });
93349
+ }
93133
93350
  async function bounded(operation, budgetMs, parentSignal) {
93134
93351
  if (budgetMs <= 0) throw new DeadlineError();
93135
93352
  const controller = new AbortController();
@@ -93195,6 +93412,7 @@ var AwareUpdateJobManager = class {
93195
93412
  let operation = requestedOperation;
93196
93413
  let preResolved = null;
93197
93414
  let target;
93415
+ let recoveryMarker = null;
93198
93416
  if (operation === "bridge-repair") {
93199
93417
  const resolved = await this.#deps.resolveBridgeRepair(this.#currentOwnerOrThrow());
93200
93418
  if (!resolved) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
@@ -93202,9 +93420,22 @@ var AwareUpdateJobManager = class {
93202
93420
  preResolved = resolved.hosts;
93203
93421
  if (!preResolved.length) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
93204
93422
  } else {
93205
- const resolved = await this.#deps.resolveCurrentTarget();
93206
- target = requireExactAwareTarget(resolved.target);
93207
- operation = resolved.operation;
93423
+ const recovery = await this.#deps.probeRecovery();
93424
+ if (recovery.pending) {
93425
+ if (!recovery.target) {
93426
+ throw Object.assign(
93427
+ new Error("An earlier AWARE update did not finish, and FloLess cannot tell which version to return to. Reinstall AWARE, then relaunch FloLess."),
93428
+ { code: "recovery-target-unknown" }
93429
+ );
93430
+ }
93431
+ target = requireExactAwareTarget(recovery.target);
93432
+ recoveryMarker = recovery.marker;
93433
+ operation = MAINTENANCE_RECOVERY;
93434
+ } else {
93435
+ const resolved = await this.#deps.resolveCurrentTarget();
93436
+ target = requireExactAwareTarget(resolved.target);
93437
+ operation = resolved.operation;
93438
+ }
93208
93439
  }
93209
93440
  if (this.#active || this.#retrying) throw new AwareUpdateConflictError("An AWARE update is already in progress.");
93210
93441
  if (this.#shuttingDown) throw new AwareUpdateConflictError("FloLess is shutting down.");
@@ -93226,7 +93457,8 @@ var AwareUpdateJobManager = class {
93226
93457
  snapshot: frozenHosts([]),
93227
93458
  startedAt,
93228
93459
  touchedAt: startedAt,
93229
- ...preResolved ? { preResolved } : {}
93460
+ ...preResolved ? { preResolved } : {},
93461
+ ...operation === MAINTENANCE_RECOVERY ? { recoveryMarker } : {}
93230
93462
  });
93231
93463
  this.#active = transaction;
93232
93464
  const settled2 = this.#execute(transaction).catch((error) => this.#unexpectedFailure(transaction, error));
@@ -93313,6 +93545,16 @@ var AwareUpdateJobManager = class {
93313
93545
  if (this.#gone.has(transaction)) throw new AwareUpdateGoneError("This AWARE update result has expired.");
93314
93546
  throw new AwareUpdateNotFoundError("AWARE update transaction not found.");
93315
93547
  }
93548
+ /**
93549
+ * A recovery job can never reach `partial`, so bridge retry has nothing to act on. Asserted
93550
+ * rather than left implicit: the invariant is what makes `retry()` safe, and an invariant nobody
93551
+ * checks is a comment.
93552
+ */
93553
+ #assertRetryable(status) {
93554
+ if (status.operation === MAINTENANCE_RECOVERY) {
93555
+ throw new AwareUpdateConflictError("A maintenance recovery has no bridges to retry.");
93556
+ }
93557
+ }
93316
93558
  async retry(transaction, hostValue) {
93317
93559
  this.#purge();
93318
93560
  if (!AWARE_BRIDGE_HOSTS.includes(hostValue)) {
@@ -93324,6 +93566,7 @@ var AwareUpdateJobManager = class {
93324
93566
  if (this.#gone.has(transaction)) throw new AwareUpdateGoneError("This AWARE update result has expired.");
93325
93567
  throw new AwareUpdateNotFoundError("AWARE update transaction not found.");
93326
93568
  }
93569
+ this.#assertRetryable(record4.status);
93327
93570
  if (record4.retry) {
93328
93571
  if (record4.retry.host !== host) throw new AwareUpdateConflictError("Another bridge retry is already in progress.");
93329
93572
  return cloneStatus(await record4.retry.reserved);
@@ -93350,7 +93593,7 @@ var AwareUpdateJobManager = class {
93350
93593
  const record4 = this.#jobs.get(transaction);
93351
93594
  if (!record4 || record4.status.state !== "running") return;
93352
93595
  const started = this.#now();
93353
- const jobBudget = this.#deps.jobTimeoutMs ?? DEFAULT_JOB_TIMEOUT;
93596
+ const jobBudget = record4.status.operation === MAINTENANCE_RECOVERY ? this.#deps.recoveryBudgetMs ?? RECOVERY_BUDGET_MS : this.#deps.jobTimeoutMs ?? DEFAULT_JOB_TIMEOUT;
93354
93597
  const deadline = started + jobBudget;
93355
93598
  const jobController = new AbortController();
93356
93599
  this.#activeController = jobController;
@@ -93359,6 +93602,10 @@ var AwareUpdateJobManager = class {
93359
93602
  try {
93360
93603
  await this.#deps.withExclusive(async (owner2) => this.#deps.withMutationContainment(transaction, owner2, async () => {
93361
93604
  const operation = record4.status.operation;
93605
+ if (operation === MAINTENANCE_RECOVERY) {
93606
+ await this.#executeRecovery(record4, owner2, jobController, deadline);
93607
+ return;
93608
+ }
93362
93609
  this.#running(record4, "snapshot", 0, 0, []);
93363
93610
  const snapshot = record4.preResolved ?? await this.#deps.snapshotPersistentBridges(owner2, record4.status.target);
93364
93611
  this.#assertSnapshot(snapshot);
@@ -93370,7 +93617,7 @@ var AwareUpdateJobManager = class {
93370
93617
  stage: "runtime-install",
93371
93618
  target: record4.status.target,
93372
93619
  snapshot: record4.snapshot,
93373
- operation,
93620
+ operation: markerOperationOf(operation),
93374
93621
  origin: record4.status.origin
93375
93622
  };
93376
93623
  await this.#deps.maintenance.write(marker);
@@ -93503,6 +93750,126 @@ var AwareUpdateJobManager = class {
93503
93750
  this.#purge();
93504
93751
  }
93505
93752
  }
93753
+ /**
93754
+ * Discharge an interrupted update, then STOP.
93755
+ *
93756
+ * Deliberately does not fall through into snapshot/install/verify. Recovery already verifies the
93757
+ * runtime it repaired, and a second verifier that can disagree would fail a machine the first one
93758
+ * just declared healthy — turning a successful recovery into a fresh marker.
93759
+ */
93760
+ async #executeRecovery(record4, owner2, jobController, deadline) {
93761
+ const transaction = record4.status.transaction;
93762
+ const target = record4.status.target;
93763
+ const authority = await this.#deps.probeRecovery();
93764
+ if (!authority.pending) {
93765
+ const observed = await this.#deps.probeRuntime(owner2);
93766
+ const good = !!observed && compareExactAwareVersions(observed, target) >= 0 && await this.#deps.smokeRuntime(owner2, jobController.signal);
93767
+ if (!good) {
93768
+ this.#setTerminal(record4, {
93769
+ state: "runtime-failed",
93770
+ transaction,
93771
+ target,
93772
+ code: "recovery-unverified",
93773
+ message: observed ? `The interrupted AWARE update was already cleared, but AWARE v${observed} is not ready to use.` : "The interrupted AWARE update was already cleared, but AWARE did not report a version."
93774
+ });
93775
+ return;
93776
+ }
93777
+ this.#setTerminal(record4, {
93778
+ state: "success",
93779
+ transaction,
93780
+ target,
93781
+ observedVersion: observed,
93782
+ updated: frozenHosts([])
93783
+ });
93784
+ return;
93785
+ }
93786
+ if (authority.target !== target || authority.marker !== record4.recoveryMarker) {
93787
+ this.#setTerminal(record4, {
93788
+ state: "runtime-failed",
93789
+ transaction,
93790
+ target,
93791
+ code: "marker-superseded",
93792
+ message: "The interrupted AWARE update changed while this recovery was starting. Try again."
93793
+ });
93794
+ return;
93795
+ }
93796
+ this.#running(record4, "recovering", 0, 0, []);
93797
+ let outcome;
93798
+ try {
93799
+ outcome = await bounded(
93800
+ (signal) => this.#deps.recoverMaintenance(owner2, signal),
93801
+ // The grace comes off what is LEFT, not only off the whole budget. `#recoveryWorkBudget()`
93802
+ // reserved it once; the second term did not, so once the authority read and the probes
93803
+ // above had eaten most of the deadline, `remaining` alone became the smaller number and
93804
+ // handed the work every millisecond that was left — reserving nothing for a tail that
93805
+ // cannot be cancelled, which is the one thing the budget exists to bound. When nothing is
93806
+ // left, bounded() refuses immediately rather than starting work it cannot finish; that is
93807
+ // a DeadlineError, which is mapped to `recovery-incomplete` — paused, marker kept,
93808
+ // resumable — and not a failure.
93809
+ //
93810
+ // On a forward-running clock the second term always wins (`remaining <= total`), so the
93811
+ // first is not doing day-to-day work. It stays as the floor for a clock that steps
93812
+ // BACKWARDS — an NTP correction mid-job would otherwise inflate `remaining` past the whole
93813
+ // budget — and it is the reason no test can pin that arm on its own.
93814
+ Math.min(
93815
+ this.#recoveryWorkBudget(),
93816
+ remaining(deadline, () => this.#now()) - this.#recoveryGrace()
93817
+ ),
93818
+ jobController.signal
93819
+ );
93820
+ } catch (error) {
93821
+ const still = await settledWithin(
93822
+ this.#deps.probeRecovery(),
93823
+ remaining(deadline, () => this.#now()),
93824
+ { pending: true, target: null, marker: null },
93825
+ // The JOB's own signal, as well as the arithmetic. `remaining()` is wall-clock, so a clock
93826
+ // that steps backwards mid-job — a suspended laptop, an NTP correction — inflates it and
93827
+ // the arithmetic alone would grant far more than the reserve. The job timer is a real
93828
+ // setTimeout and is not fooled by that, so honouring its abort here is what keeps the
93829
+ // lease bounded when the arithmetic cannot be trusted.
93830
+ jobController.signal
93831
+ );
93832
+ const sanitized = sanitizeAwareError(error, "recovery-failed");
93833
+ const timedOut = error instanceof DeadlineError || error?.name === "AbortError";
93834
+ this.#setTerminal(record4, {
93835
+ state: "runtime-failed",
93836
+ transaction,
93837
+ target,
93838
+ // A typed refusal SURVIVES the pending-marker fallback. `marker-superseded` is thrown
93839
+ // precisely when a replacement marker exists, so the probe below always sees one — and the
93840
+ // generic 'maintenance-pending' then overwrote the one code that says what happened.
93841
+ code: timedOut ? "recovery-incomplete" : sanitized.code === "marker-superseded" ? "marker-superseded" : still.pending ? "maintenance-pending" : sanitized.code,
93842
+ message: timedOut ? "Recovering the interrupted AWARE update is taking longer than one attempt allows. It will continue where it left off." : sanitized.message
93843
+ });
93844
+ return;
93845
+ }
93846
+ if (!outcome.observedVersion) {
93847
+ this.#setTerminal(record4, {
93848
+ state: "runtime-failed",
93849
+ transaction,
93850
+ target,
93851
+ code: "recovery-unverified",
93852
+ message: "The interrupted AWARE update was cleared, but AWARE did not pass its readiness check."
93853
+ });
93854
+ return;
93855
+ }
93856
+ this.#setTerminal(record4, {
93857
+ state: "success",
93858
+ transaction,
93859
+ target,
93860
+ observedVersion: outcome.observedVersion,
93861
+ updated: frozenHosts([])
93862
+ });
93863
+ }
93864
+ #recoveryGrace() {
93865
+ return this.#deps.recoveryGraceMs ?? RECOVERY_GRACE_MS;
93866
+ }
93867
+ #recoveryWorkBudget() {
93868
+ const total = this.#deps.recoveryBudgetMs ?? RECOVERY_BUDGET_MS;
93869
+ const grace = this.#recoveryGrace();
93870
+ if (total === RECOVERY_BUDGET_MS && grace === RECOVERY_GRACE_MS) return RECOVERY_WORK_BUDGET_MS;
93871
+ return Math.max(1, total - grace);
93872
+ }
93506
93873
  async #executeRetry(record4, host, resolveReserved, rejectReserved) {
93507
93874
  let reserved = false;
93508
93875
  const retryController = new AbortController();
@@ -93546,7 +93913,8 @@ var AwareUpdateJobManager = class {
93546
93913
  target: status.target,
93547
93914
  host,
93548
93915
  snapshot: record4.snapshot,
93549
- operation: status.operation,
93916
+ // Unreachable — #assertRetryable refuses a recovery job before this — but proven, not assumed.
93917
+ operation: markerOperationOf(status.operation),
93550
93918
  origin: status.origin
93551
93919
  };
93552
93920
  try {
@@ -93694,6 +94062,17 @@ var AwareUpdateJobManager = class {
93694
94062
  #unexpectedFailure(transaction, error) {
93695
94063
  const record4 = this.#jobs.get(transaction);
93696
94064
  if (!record4 || isTerminal(record4.status)) return;
94065
+ const aborted = error instanceof DeadlineError || error?.name === "AbortError";
94066
+ if (aborted && record4.status.operation === MAINTENANCE_RECOVERY) {
94067
+ this.#setTerminal(record4, {
94068
+ state: "runtime-failed",
94069
+ transaction,
94070
+ target: record4.status.target,
94071
+ code: "recovery-incomplete",
94072
+ message: "Recovering the interrupted AWARE update is taking longer than one attempt allows. It will continue where it left off."
94073
+ });
94074
+ return;
94075
+ }
93697
94076
  this.#setTerminal(record4, {
93698
94077
  state: "runtime-failed",
93699
94078
  transaction,
@@ -93750,22 +94129,31 @@ var AwareUpdateJobManager = class {
93750
94129
  this.#gone.set(transaction, goneUntil);
93751
94130
  }
93752
94131
  };
94132
+ function markerOperationOf(operation) {
94133
+ if (operation === MAINTENANCE_RECOVERY) {
94134
+ throw new Error("a maintenance-recovery job must never write a maintenance marker");
94135
+ }
94136
+ return operation;
94137
+ }
93753
94138
  function cryptoRandomId() {
93754
94139
  return globalThis.crypto.randomUUID();
93755
94140
  }
93756
94141
  async function recoverInterruptedAwareMaintenance(deps) {
93757
- const read2 = await deps.maintenance.read();
93758
- if (read2.kind === "absent") return "clean";
93759
94142
  return deps.withRecoveryExclusive(async (owner2) => {
94143
+ const read2 = await deps.maintenance.read();
94144
+ if (read2.kind === "absent") return "clean";
93760
94145
  if (read2.kind === "corrupt") {
93761
94146
  if (await deps.anyInstallerTreeAlive()) {
93762
94147
  throw new Error("AWARE maintenance state is corrupt and an installer tree may still be running.");
93763
94148
  }
93764
- await deps.maintenance.quarantine();
93765
- if (!await deps.repairAndVerify(null, owner2)) {
94149
+ const replacement = await deps.buildRecoveryMarker();
94150
+ if (!replacement) {
94151
+ throw new Error("AWARE maintenance state is corrupt and no usable recovery target could be derived.");
94152
+ }
94153
+ await deps.maintenance.replaceCorrupt(replacement);
94154
+ if (!await deps.repairAndVerify(replacement, owner2)) {
93766
94155
  throw new Error("AWARE maintenance recovery could not verify a usable runtime and bridges.");
93767
94156
  }
93768
- await deps.maintenance.clear();
93769
94157
  return "recovered";
93770
94158
  }
93771
94159
  if (await deps.matchingChildAlive(read2.marker)) {
@@ -93777,7 +94165,6 @@ async function recoverInterruptedAwareMaintenance(deps) {
93777
94165
  if (!await deps.repairAndVerify({ ...read2.marker, stage: "recovery", child: void 0 }, owner2)) {
93778
94166
  throw new Error("AWARE maintenance recovery could not verify a usable runtime and bridges.");
93779
94167
  }
93780
- await deps.maintenance.clear();
93781
94168
  return "recovered";
93782
94169
  });
93783
94170
  }
@@ -93787,7 +94174,8 @@ function sendRouteError(reply, error) {
93787
94174
  if (error instanceof AwareUpdateConflictError || error instanceof AwareUpdateGoneError || error instanceof AwareUpdateNotFoundError) {
93788
94175
  return reply.status(error.status).send({ ok: false, error: error.message });
93789
94176
  }
93790
- return reply.status(400).send({ ok: false, error: sanitizeAwareError(error, "invalid-update-request").message });
94177
+ const sanitized = sanitizeAwareError(error, "invalid-update-request");
94178
+ return reply.status(400).send({ ok: false, error: sanitized.message, code: sanitized.code });
93791
94179
  }
93792
94180
  function registerAwareUpdateRoutes(app, manager) {
93793
94181
  app.get("/api/aware/update/active", async (_request, reply) => reply.send({ ok: true, job: manager.activeStatus() }));
@@ -98333,14 +98721,69 @@ async function startServer() {
98333
98721
  }));
98334
98722
  }
98335
98723
  const awareUpdateJobs = new AwareUpdateJobManager({
98336
- resolveCurrentTarget: async () => {
98337
- const marker = await awareMaintenance.read();
98338
- if (marker.kind !== "absent") {
98339
- throw Object.assign(new Error("An interrupted AWARE update must be recovered before starting another."), { code: "maintenance-pending" });
98724
+ /**
98725
+ * Is an interrupted update outstanding, and what would recovering it aim at?
98726
+ *
98727
+ * No registry call — `decideRecoveryTarget` reads the marker and the installed version — which is
98728
+ * what lets a recovery job carry a complete identity from creation and keeps a 15-second npm
98729
+ * fetch out of the exclusive lease.
98730
+ */
98731
+ probeRecovery: async () => {
98732
+ const read2 = await awareMaintenance.read();
98733
+ if (read2.kind === "absent") return { pending: false, target: null, marker: null };
98734
+ const marker = read2.kind === "valid" ? read2.marker : null;
98735
+ return {
98736
+ pending: true,
98737
+ target: decideRecoveryTarget({
98738
+ markerTarget: marker?.target ?? null,
98739
+ markerOperation: marker?.operation ?? null,
98740
+ installed: aware.npmVersion()
98741
+ }),
98742
+ // A corrupt marker has no readable transaction; `null` is then its identity, and two corrupt
98743
+ // reads compare equal — which is correct, since neither can be told apart from the other.
98744
+ marker: marker?.transaction ?? null
98745
+ };
98746
+ },
98747
+ /**
98748
+ * Runs INSIDE the job's exclusive lease and is handed the job's own owner, so the recovery takes
98749
+ * no lease of its own. Awaiting a lease-acquiring promise while holding the lease would deadlock.
98750
+ */
98751
+ recoverMaintenance: async (owner2, signal) => {
98752
+ await recoverInterruptedAwareMaintenance({
98753
+ maintenance: awareMaintenance,
98754
+ withRecoveryExclusive: (work) => work(owner2),
98755
+ matchingChildAlive: async (marker) => marker.child ? maintenanceChildMatches(marker.child) : false,
98756
+ anyInstallerTreeAlive: () => anyAwareInstallerTreeAlive(),
98757
+ repairAndVerify: (marker, repairOwner) => repairInterruptedAwareMaintenance(marker, repairOwner, signal),
98758
+ buildRecoveryMarker
98759
+ });
98760
+ const observedVersion = aware.npmVersion();
98761
+ const stale = await staleBridgesForInstalledRuntime().catch(() => null);
98762
+ if (stale?.hosts.length) {
98763
+ disarmAutoBridgeRepair();
98764
+ scheduleAutoBridgeRepair();
98340
98765
  }
98766
+ return { observedVersion };
98767
+ },
98768
+ resolveCurrentTarget: async () => {
98341
98769
  const check = await checkAwareUpdate(AWARE_BRIDGE_DIRECTORY);
98770
+ if (!check.updateAvailable) {
98771
+ if (!check.currentVersion && check.targetVersion) {
98772
+ return { target: check.targetVersion, operation: "runtime-update" };
98773
+ }
98774
+ if (!check.targetVersion) {
98775
+ throw Object.assign(
98776
+ new Error("FloLess could not reach the AWARE release feed, so it cannot tell whether an update is available. Check your connection and try again."),
98777
+ { code: "registry-unreachable" }
98778
+ );
98779
+ }
98780
+ throw Object.assign(
98781
+ new Error(`AWARE v${check.currentVersion} is already the current release \u2014 there is nothing to update.`),
98782
+ { code: "runtime-current" }
98783
+ );
98784
+ }
98342
98785
  return {
98343
- target: check.updateAvailable ? check.targetVersion ?? null : null,
98786
+ target: check.targetVersion ?? null,
98344
98787
  // 'none' cannot reach a started job (the target is null and requireExactAwareTarget throws),
98345
98788
  // but map it defensively rather than casting — the check type lets the two disagree.
98346
98789
  operation: check.operation === "bridge-repair" ? "bridge-repair" : "runtime-update"
@@ -98388,7 +98831,10 @@ async function startServer() {
98388
98831
  },
98389
98832
  invalidateVersion: invalidateAwareVersion,
98390
98833
  probeRuntime: () => aware.npmVersion(),
98391
- smokeRuntime: async () => aware.smoke(),
98834
+ // The signal is threaded, not dropped. smoke() runs `aware app list --json` with a 60s
98835
+ // ceiling and recovery runs it holding the exclusive lease, so an unsignalled call can hold
98836
+ // that lease for a full minute past an expired deadline and then publish success.
98837
+ smokeRuntime: async (_owner, signal) => aware.smoke(signal),
98392
98838
  installBridge: async (host, _target, context) => {
98393
98839
  let identityRecorded = Promise.resolve();
98394
98840
  await aware.sidecarInstall(host, {
@@ -98405,8 +98851,10 @@ async function startServer() {
98405
98851
  maintenance: awareMaintenance,
98406
98852
  log: (event) => app.log.info(event, "AWARE update transaction")
98407
98853
  });
98408
- async function repairInterruptedAwareMaintenance(marker, owner2) {
98854
+ let recoveryGeneration = 0;
98855
+ async function repairInterruptedAwareMaintenance(marker, owner2, signal) {
98409
98856
  if (owner2 !== upgradeOwner()) return false;
98857
+ const generation = ++recoveryGeneration;
98410
98858
  refreshInvoker();
98411
98859
  invalidateAwareVersion();
98412
98860
  const target = decideRecoveryTarget({
@@ -98415,6 +98863,15 @@ async function startServer() {
98415
98863
  installed: aware.npmVersion()
98416
98864
  });
98417
98865
  if (!target || !/^\d+\.\d+\.\d+$/.test(target)) return false;
98866
+ await awareMaintenance.write({
98867
+ schema: 2,
98868
+ transaction: marker?.transaction ?? (0, import_node_crypto48.randomUUID)(),
98869
+ stage: "recovery",
98870
+ target,
98871
+ snapshot: Object.freeze([]),
98872
+ operation: marker?.operation ?? LEGACY_MARKER_OPERATION,
98873
+ origin: marker?.origin ?? LEGACY_MARKER_ORIGIN
98874
+ });
98418
98875
  const durable = await awareBridgePending.read();
98419
98876
  const observedHosts = await snapshotPersistentBridges(AWARE_BRIDGE_DIRECTORY);
98420
98877
  let snapshot = Object.freeze(AWARE_BRIDGE_HOSTS.filter((host) => (marker?.snapshot ?? []).includes(host) || observedHosts.includes(host) || durable?.target === target && durable.hosts.includes(host)));
@@ -98428,10 +98885,14 @@ async function startServer() {
98428
98885
  origin: marker?.origin ?? LEGACY_MARKER_ORIGIN
98429
98886
  };
98430
98887
  await awareMaintenance.write(recoveryMarker);
98431
- if (aware.npmVersion() !== target || !await aware.smoke()) {
98888
+ const installedNow = aware.npmVersion();
98889
+ const superseded = !!installedNow && isExactAwareTarget(installedNow) && compareExactAwareVersions(installedNow, target) > 0;
98890
+ if (!superseded && (installedNow !== target || !await aware.smoke(signal))) {
98432
98891
  await installAwareGlobal(target, () => {
98433
98892
  }, {
98893
+ ...signal ? { signal } : {},
98434
98894
  onChild: async (child) => {
98895
+ if (generation !== recoveryGeneration) return;
98435
98896
  recoveryMarker = { ...recoveryMarker, child };
98436
98897
  await awareMaintenance.write(recoveryMarker);
98437
98898
  }
@@ -98439,32 +98900,22 @@ async function startServer() {
98439
98900
  refreshInvoker();
98440
98901
  invalidateAwareVersion();
98441
98902
  }
98442
- if (aware.npmVersion() !== target || !await aware.smoke()) return false;
98903
+ const after = aware.npmVersion();
98904
+ const good = !!after && isExactAwareTarget(after) && compareExactAwareVersions(after, target) >= 0 && await aware.smoke(signal);
98905
+ if (!good) return false;
98906
+ const outstanding = [];
98443
98907
  for (const host of snapshot) {
98444
- if (await persistentBridgeVersion(AWARE_BRIDGE_DIRECTORY, host) === target) continue;
98445
- await withSidecarWrite(async () => {
98446
- let childRecorded = Promise.resolve();
98447
- await aware.sidecarInstall(host, {
98448
- onSpawn: (child) => {
98449
- if (!child.pid) throw new Error(`The ${host} bridge installer did not expose a child PID`);
98450
- childRecorded = maintenanceChildIdentity(child.pid, {
98451
- childStillRunning: () => child.exitCode === null && child.signalCode === null
98452
- }).then(async (identity) => {
98453
- recoveryMarker = { ...recoveryMarker, host, child: identity };
98454
- await awareMaintenance.write(recoveryMarker);
98455
- });
98456
- childRecorded.catch(() => {
98457
- });
98458
- }
98459
- });
98460
- await childRecorded;
98461
- if (await persistentBridgeVersion(AWARE_BRIDGE_DIRECTORY, host) !== target) {
98462
- throw new Error(`The recovered ${host} bridge did not match AWARE ${target}`);
98463
- }
98464
- });
98908
+ if (await persistentBridgeVersion(AWARE_BRIDGE_DIRECTORY, host) !== target) outstanding.push(host);
98909
+ }
98910
+ if (outstanding.length) {
98911
+ await awareBridgePending.write({ schema: 1, target, hosts: Object.freeze(outstanding) });
98912
+ }
98913
+ if (!await awareMaintenance.clear(recoveryMarker.transaction)) {
98914
+ throw Object.assign(
98915
+ new Error("The interrupted AWARE update changed while it was being finished."),
98916
+ { code: "marker-superseded" }
98917
+ );
98465
98918
  }
98466
- await awareBridgePending.clear().catch(() => {
98467
- });
98468
98919
  return true;
98469
98920
  }
98470
98921
  async function recoverAwareMaintenance() {
@@ -98473,9 +98924,23 @@ async function startServer() {
98473
98924
  withRecoveryExclusive: (work) => withAwareExclusive(() => work(upgradeOwner())),
98474
98925
  matchingChildAlive: async (marker) => marker.child ? maintenanceChildMatches(marker.child) : false,
98475
98926
  anyInstallerTreeAlive: () => anyAwareInstallerTreeAlive(),
98476
- repairAndVerify: repairInterruptedAwareMaintenance
98927
+ repairAndVerify: repairInterruptedAwareMaintenance,
98928
+ buildRecoveryMarker
98477
98929
  });
98478
98930
  }
98931
+ async function buildRecoveryMarker() {
98932
+ const target = decideRecoveryTarget({ markerTarget: null, markerOperation: null, installed: aware.npmVersion() });
98933
+ if (!target || !isExactAwareTarget(target)) return null;
98934
+ return {
98935
+ schema: 2,
98936
+ transaction: (0, import_node_crypto48.randomUUID)(),
98937
+ stage: "recovery",
98938
+ target,
98939
+ snapshot: Object.freeze([]),
98940
+ operation: LEGACY_MARKER_OPERATION,
98941
+ origin: LEGACY_MARKER_ORIGIN
98942
+ };
98943
+ }
98479
98944
  const SKIP_AUTO_BRIDGE_REPAIR = process.env.FLOLESS_SKIP_AUTO_BRIDGE_REPAIR === "1";
98480
98945
  let autoRepairScheduled = false;
98481
98946
  let autoRepairInFlight = false;
@@ -98797,7 +99262,11 @@ async function startServer() {
98797
99262
  setTimeout(() => process.exit(0), 250);
98798
99263
  });
98799
99264
  app.get("/api/aware/update", async () => {
98800
- return withAwareShared(async () => ({ ok: true, ...await checkAwareUpdate(AWARE_BRIDGE_DIRECTORY) }));
99265
+ return withAwareShared(async () => ({
99266
+ ok: true,
99267
+ ...await checkAwareUpdate(AWARE_BRIDGE_DIRECTORY),
99268
+ recoveryPending: (await awareMaintenance.read()).kind !== "absent"
99269
+ }));
98801
99270
  });
98802
99271
  registerAwareUpdateRoutes(app, awareUpdateJobs);
98803
99272
  app.get("/api/release-notes", async (req, reply) => {