@floless/app 0.134.4 → 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
 
@@ -43012,7 +43012,7 @@ var require_static = __commonJS({
43012
43012
  "use strict";
43013
43013
  var path = require("node:path");
43014
43014
  var { fileURLToPath: fileURLToPath6 } = require("node:url");
43015
- var { statSync: statSync32 } = require("node:fs");
43015
+ var { statSync: statSync33 } = require("node:fs");
43016
43016
  var { glob } = require_commonjs6();
43017
43017
  var fp = require_plugin2();
43018
43018
  var send = require_send2();
@@ -43375,7 +43375,7 @@ var require_static = __commonJS({
43375
43375
  }
43376
43376
  let pathStat;
43377
43377
  try {
43378
- pathStat = statSync32(rootPath);
43378
+ pathStat = statSync33(rootPath);
43379
43379
  } catch (e) {
43380
43380
  if (e.code === "ENOENT") {
43381
43381
  fastify.log.warn(`"root" path "${rootPath}" must exist`);
@@ -43399,7 +43399,7 @@ var require_static = __commonJS({
43399
43399
  return indexFiles.find((filename) => {
43400
43400
  const p = path.join(root6, pathname, filename);
43401
43401
  try {
43402
- const stats = statSync32(p);
43402
+ const stats = statSync33(p);
43403
43403
  return !stats.isDirectory();
43404
43404
  } catch {
43405
43405
  return false;
@@ -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.134.4" : 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.134.4" : 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]
@@ -56475,7 +56483,7 @@ function checkModelReferences(doc) {
56475
56483
  }
56476
56484
  const compare = (dir, parsedCount) => {
56477
56485
  const declared = axes.filter((a) => isObj(a) && a.dir === dir).length;
56478
- if (declared !== parsedCount) add("$.grid.axes", "grid-axis-count", `${dir} has ${parsedCount} parsed entries but ${declared} declared axes`);
56486
+ if (declared !== parsedCount) add("$.grid.axes", "grid-axis-count", `$.grid.${dir} parses to ${parsedCount} ${dir} ${parsedCount === 1 ? "entry" : "entries"} but $.grid.axes declares ${declared} ${dir} ${declared === 1 ? "axis" : "axes"} \u2014 one axis row per parsed entry, so edit $.grid.${dir} and $.grid.axes together until the counts match`);
56479
56487
  };
56480
56488
  for (const dir of ["x", "y"]) {
56481
56489
  const text5 = str(grid[dir]);
@@ -63011,9 +63019,103 @@ function decodeSnapshots(inputs) {
63011
63019
  var import_node_os21 = require("node:os");
63012
63020
  var import_node_path31 = require("node:path");
63013
63021
 
63022
+ // instructor-request.ts
63023
+ var import_node_crypto20 = require("node:crypto");
63024
+
63025
+ // app-id.ts
63026
+ var APP_ID4 = /^[a-z0-9][a-z0-9._-]*$/i;
63027
+ function isSafeAppId(value) {
63028
+ return typeof value === "string" && APP_ID4.test(value) && safeSegment(value);
63029
+ }
63030
+
63031
+ // instructor-request.ts
63032
+ function normalizeInstructorContext(raw) {
63033
+ if (!raw || typeof raw !== "object") return null;
63034
+ const context = raw;
63035
+ const { tone, facts } = context;
63036
+ if (typeof context.subject !== "string" || !context.subject.trim() || context.subject.length > 300) return null;
63037
+ if (tone !== "idle" && tone !== "armed" && tone !== "blocked") return null;
63038
+ if (!Array.isArray(facts) || facts.length > 12 || !facts.every((fact) => typeof fact === "string" && fact.length <= 500)) return null;
63039
+ if (typeof context.surface !== "string" || !context.surface || context.surface.length > 100) return null;
63040
+ if (context.commandId !== void 0 && (typeof context.commandId !== "string" || context.commandId.length > 200)) return null;
63041
+ if (context.instance !== void 0 && (typeof context.instance !== "string" || context.instance.length > 300)) return null;
63042
+ return {
63043
+ subject: context.subject.trim(),
63044
+ commandId: context.commandId,
63045
+ instance: context.instance,
63046
+ tone,
63047
+ facts,
63048
+ surface: context.surface
63049
+ };
63050
+ }
63051
+ function normalizeInstructorGuideRequest(rawBody) {
63052
+ const body = rawBody && typeof rawBody === "object" ? rawBody : {};
63053
+ const { appId, project, projectLabel, instructorContext: rawContext } = body;
63054
+ const normalizedProjectLabel = typeof projectLabel === "string" ? projectLabel.trim() : void 0;
63055
+ if (appId !== void 0 && !isSafeAppId(appId)) return { error: "appId is invalid" };
63056
+ if (project !== void 0 && !isProjectId(project)) return { error: "project is invalid" };
63057
+ if (projectLabel !== void 0 && !normalizedProjectLabel) {
63058
+ return { error: "projectLabel is invalid" };
63059
+ }
63060
+ if ((project || projectLabel) && (!project || !appId || rawContext === void 0)) {
63061
+ return { error: "complete project scope requires Instructor context" };
63062
+ }
63063
+ const instructorContext = rawContext === void 0 ? void 0 : normalizeInstructorContext(rawContext);
63064
+ if (rawContext !== void 0 && !instructorContext) return { error: "Instructor context is invalid" };
63065
+ if (!appId && !instructorContext) return { error: "a valid appId is required" };
63066
+ return {
63067
+ value: {
63068
+ ...appId ? { appId } : {},
63069
+ ...project ? { project } : {},
63070
+ // Project names have no authored length limit. This field is narration only, so retain a
63071
+ // bounded prefix instead of rejecting an otherwise valid project's Instructor request.
63072
+ ...normalizedProjectLabel ? { projectLabel: normalizedProjectLabel.slice(0, 200) } : {},
63073
+ ...instructorContext ? { instructorContext } : {}
63074
+ }
63075
+ };
63076
+ }
63077
+ function instructorRequestFingerprint(request) {
63078
+ if (request.type !== "guide" || !request.instructorContext) return null;
63079
+ const normalized = normalizeInstructorGuideRequest({
63080
+ appId: request.appId,
63081
+ project: request.project,
63082
+ projectLabel: request.projectLabel,
63083
+ instructorContext: request.instructorContext
63084
+ });
63085
+ if (!normalized.value?.instructorContext) return null;
63086
+ const value = normalized.value;
63087
+ const context = value.instructorContext;
63088
+ const canonical2 = JSON.stringify({
63089
+ type: "guide",
63090
+ appId: value.appId ?? null,
63091
+ project: value.project ?? null,
63092
+ projectLabel: value.projectLabel ?? null,
63093
+ instructorContext: {
63094
+ subject: context.subject,
63095
+ commandId: context.commandId ?? null,
63096
+ instance: context.instance ?? null,
63097
+ tone: context.tone,
63098
+ facts: context.facts,
63099
+ surface: context.surface
63100
+ }
63101
+ });
63102
+ return (0, import_node_crypto20.createHash)("sha256").update(canonical2).digest("hex");
63103
+ }
63104
+ function validatedInstructorAnswer(request) {
63105
+ const run2 = request.run;
63106
+ if (request.type !== "guide" || !request.instructorContext || run2?.state !== "answered") return null;
63107
+ const completion = validateCompletion({ outcome: "answered", answer: run2.answer });
63108
+ if (completion.kind !== "answered") return null;
63109
+ const fingerprint = instructorRequestFingerprint(request);
63110
+ if (!fingerprint || run2.inputFingerprint !== fingerprint) return null;
63111
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(run2.leaseId) || !Number.isFinite(Date.parse(run2.finishedAt ?? ""))) return null;
63112
+ if (run2.lastOutput || run2.question || run2.handoffReady || run2.recoveryReady) return null;
63113
+ return { answer: completion.answer, inputFingerprint: fingerprint, leaseId: run2.leaseId, finishedAt: run2.finishedAt };
63114
+ }
63115
+
63014
63116
  // run-audit.ts
63015
63117
  var import_node_fs32 = require("node:fs");
63016
- var import_node_crypto20 = require("node:crypto");
63118
+ var import_node_crypto21 = require("node:crypto");
63017
63119
  var import_node_os20 = require("node:os");
63018
63120
  var import_node_path30 = require("node:path");
63019
63121
  var MAX_BYTES5 = 5 * 1024 * 1024;
@@ -63027,7 +63129,7 @@ function auditEvent(input) {
63027
63129
  return {
63028
63130
  v: 1,
63029
63131
  at: input.at ?? (/* @__PURE__ */ new Date()).toISOString(),
63030
- eventId: input.eventId ?? (0, import_node_crypto20.randomUUID)(),
63132
+ eventId: input.eventId ?? (0, import_node_crypto21.randomUUID)(),
63031
63133
  event: input.event,
63032
63134
  leaseId: input.leaseId,
63033
63135
  requestId: input.requestId,
@@ -63044,7 +63146,7 @@ function auditEvent(input) {
63044
63146
  function preflightRunAudit() {
63045
63147
  const root6 = ROOT5();
63046
63148
  (0, import_node_fs32.mkdirSync)(root6, { recursive: true, mode: 448 });
63047
- const probe = (0, import_node_path30.join)(root6, `.probe-${process.pid}-${(0, import_node_crypto20.randomUUID)()}`);
63149
+ const probe = (0, import_node_path30.join)(root6, `.probe-${process.pid}-${(0, import_node_crypto21.randomUUID)()}`);
63048
63150
  const fd2 = (0, import_node_fs32.openSync)(probe, "wx", 384);
63049
63151
  try {
63050
63152
  (0, import_node_fs32.writeFileSync)(fd2, "");
@@ -63152,7 +63254,7 @@ var RUN_POLICY = {
63152
63254
  runnable: true,
63153
63255
  calls: (l) => [
63154
63256
  { method: "GET", path: "/api/requests", why: "read the authoritative spec for this request" },
63155
- ...isSafeAppId(l.appId) ? [{ method: "POST", path: "/api/compile", body: { id: l.appId }, why: "compile the workflow after editing its .flo" }] : [],
63257
+ ...isSafeAppId2(l.appId) ? [{ method: "POST", path: "/api/compile", body: { id: l.appId }, why: "compile the workflow after editing its .flo" }] : [],
63156
63258
  { method: "DELETE", path: `/api/requests/${l.requestId}`, why: "clear this request once applied" }
63157
63259
  ],
63158
63260
  // The `.flo` lives in the app's own source directory, NOT in the nominated folder — which is
@@ -63205,7 +63307,7 @@ function steelPreparationTimeoutWhy(req) {
63205
63307
  function runEligibilityFor(req) {
63206
63308
  const policy = policyFor(req.type);
63207
63309
  if (!policy.runnable) return policy;
63208
- if (req.type === "guide" && !req.instructorContext) {
63310
+ if (req.type === "guide" && !normalizeInstructorContext(req.instructorContext)) {
63209
63311
  return { runnable: false, why: "workflow tours are conversations \u2014 use Copy to continue in your terminal" };
63210
63312
  }
63211
63313
  if (req.type !== "revision-read") return { runnable: true, policy };
@@ -63230,7 +63332,7 @@ function runEligibilityFor(req) {
63230
63332
  if (req.prepassReady === true) {
63231
63333
  return {
63232
63334
  runnable: false,
63233
- why: req.filterSaved === true ? "this Drawing Filter is saved \u2014 continue the drawing read in the terminal AI that prepared it" : "this Drawing Filter is ready \u2014 review it and press Save filter, then continue in the terminal AI that prepared it"
63335
+ why: req.filterCheckpointCurrent === true ? "this Drawing Filter is saved \u2014 continue the drawing read in the terminal AI that prepared it" : "this Drawing Filter is ready \u2014 review it and press Save filter, then continue in the terminal AI that prepared it"
63234
63336
  };
63235
63337
  }
63236
63338
  if (!req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0) {
@@ -63254,9 +63356,9 @@ function runEligibilityFor(req) {
63254
63356
  return { runnable: true, policy };
63255
63357
  }
63256
63358
  var SAFE_APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
63257
- var isSafeAppId = (id) => typeof id === "string" && SAFE_APP_ID.test(id);
63359
+ var isSafeAppId2 = (id) => typeof id === "string" && SAFE_APP_ID.test(id);
63258
63360
  function appSourceDir(appId) {
63259
- if (!isSafeAppId(appId)) return null;
63361
+ if (!isSafeAppId2(appId)) return null;
63260
63362
  const root6 = process.env.AWARE_HOME || (0, import_node_path31.join)((0, import_node_os21.homedir)(), ".aware");
63261
63363
  return (0, import_node_path31.join)(root6, "apps", appId);
63262
63364
  }
@@ -63621,100 +63723,6 @@ function onlyThisRequest(body, requestId) {
63621
63723
  return { ...b, requests: b.requests.filter((r) => r?.id === requestId) };
63622
63724
  }
63623
63725
 
63624
- // instructor-request.ts
63625
- var import_node_crypto21 = require("node:crypto");
63626
-
63627
- // app-id.ts
63628
- var APP_ID4 = /^[a-z0-9][a-z0-9._-]*$/i;
63629
- function isSafeAppId2(value) {
63630
- return typeof value === "string" && APP_ID4.test(value) && safeSegment(value);
63631
- }
63632
-
63633
- // instructor-request.ts
63634
- function normalizeInstructorContext(raw) {
63635
- if (!raw || typeof raw !== "object") return null;
63636
- const context = raw;
63637
- const { tone, facts } = context;
63638
- if (typeof context.subject !== "string" || !context.subject.trim() || context.subject.length > 300) return null;
63639
- if (tone !== "idle" && tone !== "armed" && tone !== "blocked") return null;
63640
- if (!Array.isArray(facts) || facts.length > 12 || !facts.every((fact) => typeof fact === "string" && fact.length <= 500)) return null;
63641
- if (typeof context.surface !== "string" || !context.surface || context.surface.length > 100) return null;
63642
- if (context.commandId !== void 0 && (typeof context.commandId !== "string" || context.commandId.length > 200)) return null;
63643
- if (context.instance !== void 0 && (typeof context.instance !== "string" || context.instance.length > 300)) return null;
63644
- return {
63645
- subject: context.subject.trim(),
63646
- commandId: context.commandId,
63647
- instance: context.instance,
63648
- tone,
63649
- facts,
63650
- surface: context.surface
63651
- };
63652
- }
63653
- function normalizeInstructorGuideRequest(rawBody) {
63654
- const body = rawBody && typeof rawBody === "object" ? rawBody : {};
63655
- const { appId, project, projectLabel, instructorContext: rawContext } = body;
63656
- const normalizedProjectLabel = typeof projectLabel === "string" ? projectLabel.trim() : void 0;
63657
- if (appId !== void 0 && !isSafeAppId2(appId)) return { error: "appId is invalid" };
63658
- if (project !== void 0 && !isProjectId(project)) return { error: "project is invalid" };
63659
- if (projectLabel !== void 0 && !normalizedProjectLabel) {
63660
- return { error: "projectLabel is invalid" };
63661
- }
63662
- if ((project || projectLabel) && (!project || !appId || rawContext === void 0)) {
63663
- return { error: "complete project scope requires Instructor context" };
63664
- }
63665
- const instructorContext = rawContext === void 0 ? void 0 : normalizeInstructorContext(rawContext);
63666
- if (rawContext !== void 0 && !instructorContext) return { error: "Instructor context is invalid" };
63667
- if (!appId && !instructorContext) return { error: "a valid appId is required" };
63668
- return {
63669
- value: {
63670
- ...appId ? { appId } : {},
63671
- ...project ? { project } : {},
63672
- // Project names have no authored length limit. This field is narration only, so retain a
63673
- // bounded prefix instead of rejecting an otherwise valid project's Instructor request.
63674
- ...normalizedProjectLabel ? { projectLabel: normalizedProjectLabel.slice(0, 200) } : {},
63675
- ...instructorContext ? { instructorContext } : {}
63676
- }
63677
- };
63678
- }
63679
- function instructorRequestFingerprint(request) {
63680
- if (request.type !== "guide" || !request.instructorContext) return null;
63681
- const normalized = normalizeInstructorGuideRequest({
63682
- appId: request.appId,
63683
- project: request.project,
63684
- projectLabel: request.projectLabel,
63685
- instructorContext: request.instructorContext
63686
- });
63687
- if (!normalized.value?.instructorContext) return null;
63688
- const value = normalized.value;
63689
- const context = value.instructorContext;
63690
- const canonical2 = JSON.stringify({
63691
- type: "guide",
63692
- appId: value.appId ?? null,
63693
- project: value.project ?? null,
63694
- projectLabel: value.projectLabel ?? null,
63695
- instructorContext: {
63696
- subject: context.subject,
63697
- commandId: context.commandId ?? null,
63698
- instance: context.instance ?? null,
63699
- tone: context.tone,
63700
- facts: context.facts,
63701
- surface: context.surface
63702
- }
63703
- });
63704
- return (0, import_node_crypto21.createHash)("sha256").update(canonical2).digest("hex");
63705
- }
63706
- function validatedInstructorAnswer(request) {
63707
- const run2 = request.run;
63708
- if (request.type !== "guide" || !request.instructorContext || run2?.state !== "answered") return null;
63709
- const completion = validateCompletion({ outcome: "answered", answer: run2.answer });
63710
- if (completion.kind !== "answered") return null;
63711
- const fingerprint = instructorRequestFingerprint(request);
63712
- if (!fingerprint || run2.inputFingerprint !== fingerprint) return null;
63713
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(run2.leaseId) || !Number.isFinite(Date.parse(run2.finishedAt ?? ""))) return null;
63714
- if (run2.lastOutput || run2.question || run2.handoffReady || run2.recoveryReady) return null;
63715
- return { answer: completion.answer, inputFingerprint: fingerprint, leaseId: run2.leaseId, finishedAt: run2.finishedAt };
63716
- }
63717
-
63718
63726
  // terminal-runtime.ts
63719
63727
  var import_node_fs34 = require("node:fs");
63720
63728
  var import_node_os22 = require("node:os");
@@ -64140,7 +64148,7 @@ ${isInitialRead ? "Initial" : "Revised"} drawing${req.snapshots.length > 1 ? "s"
64140
64148
  My note: ${req.instruction}` : "";
64141
64149
  const messageHint = isInitialRead ? "<plain-English what was read>" : "<plain-English what changed>";
64142
64150
  const vectorPost = `GET the current contract again and keep its ETag, then POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that current ETag>. The server derives the base version and source provenance from this queued request. The first completed vector drawing publishes History version 1; later reads stage a review and publish only after confirmation. Do NOT DELETE the request yourself. If you can't read the drawing, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
64143
- const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v4 attestation. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), and facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it). The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour). If even one failing dimension does not, that line needs its own row whatever the others say. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, attestation }; a blocked report is a mandatory checklist, so fix every blocker and repeat until status is read-complete. Then POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
64151
+ const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v4 attestation. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour). If even one failing dimension does not, that line needs its own row whatever the others say. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, attestation }; a blocked report is a mandatory checklist, so fix every blocker and repeat until status is read-complete. Then POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
64144
64152
  const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}; only it inventories pages and mints Filter ids. On sheet-identification-required, inspect listed pages, identify each sheet, then retry with { bindings: [{ pageId, sheet, title?, evidenceKind }] }; never guess from other pages or build Filter geometry. On steel-manifest-preparation-busy, wait at least retryAfterMs; retry this step. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator repairs/removes the stale claim. On steel-manifest-extraction-timeout, STOP; do not retry the same drawing set. Relay error and recovery, then phase, elapsed/limit, counts and diagnostic id; null page counts are unknown. Never relay commands, stderr, source, filenames, or paths. A smaller set is required. On steel-manifest-over-budget, STOP and relay recovery. Page scope: remove or split the named dense sheet. Total scope: use smaller revisions. Bytes scope is drawing-data weight, not element count: use the byte shares, heaviest first, to decide what to move or split; if one sheet alone exceeds the limit, putting it in its own revision cannot help. Null scope means extraction overflowed before measurement, so there is no breakdown and the set must be materially smaller. On steel-manifest-extraction-failed, STOP and relay the diagnostic; an identical retry will fail. Never rename Filter geometry or mint its element ids yourself.`;
64145
64153
  if ((req.appTemplateId || req.appId) === "vectorize") {
64146
64154
  if (isInitialRead) {
@@ -64244,7 +64252,7 @@ function desktopHandoffsForRequest(r, base, prompt, marker) {
64244
64252
  if (r.type === "guide") return null;
64245
64253
  if (r.type === "revision-read" && (r.status !== "pending" || r.settledVersion !== void 0)) return null;
64246
64254
  const run2 = r.run;
64247
- if (r.type === "revision-read" && r.prepassReady === true && r.filterSaved !== true) return null;
64255
+ if (r.type === "revision-read" && r.prepassReady === true && r.filterCheckpointCurrent !== true) return null;
64248
64256
  if (!prompt.trim() || !marker.trim() || !run2 || run2.processContained !== true || run2.recoveryReady !== true) return null;
64249
64257
  if (!run2.sessionId || !run2.leaseId || !DESKTOP_RESUMABLE_RUN_STATES.has(run2.state)) return null;
64250
64258
  if (run2.runtime === "codex" && run2.handoffReady !== true) return null;
@@ -64277,7 +64285,7 @@ function resumeCommandForRequest(r) {
64277
64285
  if (r.type === "revision-read" && (r.status !== "pending" || r.settledVersion !== void 0)) return null;
64278
64286
  const run2 = r.run;
64279
64287
  if (!run2 || run2.processContained !== true || !run2.sessionId) return null;
64280
- if (r.type === "revision-read" && r.prepassReady === true && r.filterSaved !== true) return null;
64288
+ if (r.type === "revision-read" && r.prepassReady === true && r.filterCheckpointCurrent !== true) return null;
64281
64289
  if (desktopClaimForLease(run2.leaseId)) return null;
64282
64290
  if (r.type === "revision-read") {
64283
64291
  const lease = getLease(run2.leaseId);
@@ -64404,7 +64412,12 @@ function withPrompt(r, base = selfOrigin()) {
64404
64412
  };
64405
64413
  }
64406
64414
  }
64407
- var NO_ENRICHMENTS = { appTemplateId: void 0, nativeSteelReady: void 0, projectName: void 0 };
64415
+ var NO_ENRICHMENTS = {
64416
+ appTemplateId: void 0,
64417
+ nativeSteelReady: void 0,
64418
+ projectName: void 0,
64419
+ filterCheckpointCurrent: void 0
64420
+ };
64408
64421
  function enrichedView(r, enrich, base = selfOrigin()) {
64409
64422
  let extra = {};
64410
64423
  try {
@@ -64606,7 +64619,7 @@ function strictLaunchBodyValidator() {
64606
64619
  function handoffInstructionFor(request) {
64607
64620
  const original = `${request.marker}
64608
64621
  ${request.prompt}`;
64609
- if (request.type !== "revision-read" || request.filterSaved !== true || !request.project) return original;
64622
+ if (request.type !== "revision-read" || request.filterCheckpointCurrent !== true || !request.project) return original;
64610
64623
  const progressPath = steelProgressPath(request.project, request.id);
64611
64624
  return [
64612
64625
  original,
@@ -68629,8 +68642,8 @@ function readSelectionFromBody(body) {
68629
68642
  return Object.keys(own2).length === 0 ? null : "invalid";
68630
68643
  }
68631
68644
  const raw = own2.memberIds;
68632
- const wellFormed = Array.isArray(raw) && raw.length > 0 && raw.length <= MAX_SELECTION_MEMBERS && raw.every((id) => typeof id === "string" && id.trim() !== "");
68633
- 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";
68634
68647
  return [...new Set(raw)];
68635
68648
  }
68636
68649
  function selectionMemberCount(contractInput) {
@@ -69843,16 +69856,38 @@ var PlanTransformError = class extends Error {
69843
69856
  var refuse = (code, message, plan) => {
69844
69857
  throw new PlanTransformError(code, message, plan && plan.viewKind);
69845
69858
  };
69846
- function gridIntersection(grid, ref, plan) {
69847
- if (!grid || typeof grid !== "object" || !finite2(grid.origin)) {
69848
- 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
+ );
69849
69883
  }
69850
69884
  if (!ref || typeof ref !== "object" || typeof ref.axis_x !== "string" || typeof ref.axis_y !== "string") {
69851
- 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);
69852
69886
  }
69853
69887
  const X = parseSpacings(grid.x), Y = parseSpacings(grid.y);
69854
69888
  if (X.err || Y.err) {
69855
- 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);
69856
69891
  }
69857
69892
  const xs = axisLabelsFor(grid, "x", "num", X.offsets.length);
69858
69893
  const ys = axisLabelsFor(grid, "y", "alpha", Y.offsets.length);
@@ -69864,7 +69899,7 @@ function gridIntersection(grid, ref, plan) {
69864
69899
  if (xi < 0 || yi < 0) {
69865
69900
  return refuse(
69866
69901
  "control-ref-unresolved",
69867
- `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`,
69868
69903
  plan
69869
69904
  );
69870
69905
  }
@@ -69873,27 +69908,27 @@ function gridIntersection(grid, ref, plan) {
69873
69908
  function planTransform(plan) {
69874
69909
  const kind = plan && plan.viewKind;
69875
69910
  if (kind !== "plan") {
69876
- const named = typeof kind === "string" ? kind : "unknown";
69911
+ const named = typeof kind === "string" && kind ? quote(kind) : "unknown";
69877
69912
  return refuse(
69878
69913
  "view-kind-unsupported",
69879
- `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`,
69880
69915
  plan
69881
69916
  );
69882
69917
  }
69883
69918
  if (!finite2(plan.datum_at) || !finite2(plan.control2_at) || !plan.control2_ref) {
69884
69919
  return refuse(
69885
69920
  "registration-incomplete",
69886
- `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`,
69887
69922
  plan
69888
69923
  );
69889
69924
  }
69890
69925
  const ptPerFt = Number(plan.pt_per_ft);
69891
69926
  if (!(ptPerFt > 0) || !Number.isFinite(ptPerFt)) {
69892
- 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);
69893
69928
  }
69894
69929
  const registrationGrid = plan.modelGrid || plan.grid;
69895
- const world0 = plan.datum_ref ? gridIntersection(registrationGrid, plan.datum_ref, plan) : [0, 0];
69896
- 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");
69897
69932
  const scale = mmPerPx(ptPerFt);
69898
69933
  const local1 = [
69899
69934
  (plan.control2_at[0] - plan.datum_at[0]) * scale,
@@ -69902,15 +69937,19 @@ function planTransform(plan) {
69902
69937
  const worldDelta = [world1[0] - world0[0], world1[1] - world0[1]];
69903
69938
  const localLen = Math.hypot(local1[0], local1[1]);
69904
69939
  const worldLen = Math.hypot(worldDelta[0], worldDelta[1]);
69905
- if (!(localLen > 1e-9) || !(worldLen > 1e-9)) {
69906
- 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);
69907
69946
  }
69908
69947
  const fitScale = worldLen / localLen;
69909
69948
  const rotation = Math.atan2(worldDelta[1], worldDelta[0]) - Math.atan2(local1[1], local1[0]);
69910
69949
  const c = Math.cos(rotation) * fitScale;
69911
69950
  const s = Math.sin(rotation) * fitScale;
69912
69951
  if (![c, s, fitScale, world0[0], world0[1]].every(Number.isFinite)) {
69913
- 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);
69914
69953
  }
69915
69954
  return { datumPx: plan.datum_at, world0, mmPerPx: scale, fitScale, rotation, c, s };
69916
69955
  }
@@ -70373,21 +70412,95 @@ function observationZ(observation, observationEnd) {
70373
70412
  const z = observationEnd === 0 ? observation.evidence.observed?.fromZ?.value : observation.evidence.observed?.toZ?.value;
70374
70413
  return z && "known" in z && Number.isFinite(z.known) ? { known: z.known } : null;
70375
70414
  }
70376
- 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) {
70377
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
+ };
70378
70491
  if (!(typeof plan.pt_per_ft === "number" && Number.isFinite(plan.pt_per_ft) && plan.pt_per_ft > 0)) {
70379
- 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`);
70380
70493
  }
70381
70494
  if (observation.evidence.local.pt_per_ft !== plan.pt_per_ft) {
70382
- 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`);
70383
70496
  }
70384
70497
  try {
70385
70498
  if (plan.viewKind === "plan") {
70386
70499
  const z = observationZ(observation, observationEnd);
70387
- 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`);
70388
70501
  const transformed = sheetPxToWorld(local, { ...plan, modelGrid: model.grid }, z);
70389
70502
  const point3 = known(transformed);
70390
- 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`);
70391
70504
  }
70392
70505
  if ((plan.viewKind === "elevation" || plan.viewKind === "section") && plan.sourceRegistration) {
70393
70506
  const registration = plan.sourceRegistration;
@@ -70400,14 +70513,14 @@ function observationPoint(model, plan, observation, observationEnd) {
70400
70513
  y: origin.y + registration.worldU[1] * du + registration.worldV[1] * dv,
70401
70514
  z: { known: origin.z.known + registration.worldU[2] * du + registration.worldV[2] * dv }
70402
70515
  };
70403
- 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`);
70404
70517
  }
70405
70518
  } catch (error) {
70406
- if (error instanceof PlanTransformError) return { kind: "failure", reason: "view-unregistered" };
70519
+ if (error instanceof PlanTransformError) return fail3("view-unregistered", () => error.message);
70407
70520
  const identity = `${plan.sheet}/${observation.id}/end-${observationEnd + 1}`;
70408
70521
  throw new Error(`member-end evidence transform failed unexpectedly for ${identity}`, { cause: error });
70409
70522
  }
70410
- 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`);
70411
70524
  }
70412
70525
  var evidenceKey = (memberId, end) => `${memberId}\0${end}`;
70413
70526
  function finalizedEvidence(accumulator) {
@@ -70437,7 +70550,7 @@ function finalizedEvidence(accumulator) {
70437
70550
  conflict: points.size > 1
70438
70551
  };
70439
70552
  }
70440
- function buildEvidenceIndex(model, plans, deadlineMs) {
70553
+ function buildEvidenceIndex(model, plans, deadlineMs, diagnoses) {
70441
70554
  const accumulators = /* @__PURE__ */ new Map();
70442
70555
  for (const plan of plans) for (const observation of plan.memberObservations ?? []) {
70443
70556
  if (Date.now() > deadlineMs) {
@@ -70465,7 +70578,7 @@ function buildEvidenceIndex(model, plans, deadlineMs) {
70465
70578
  if (accumulator.contributionIds.size > SUPPORT_CENTERLINE_V1.maxObservationsPerEnd) {
70466
70579
  throw new MemberEndAnalysisWorkLimitError("Member-end analysis exceeded the per-end drawing-observation budget.");
70467
70580
  }
70468
- const observed = observationPoint(model, plan, observation, row.observationEnd);
70581
+ const observed = observationPoint(model, plan, observation, row.observationEnd, row.memberId, row.memberEnd, diagnoses);
70469
70582
  const tolerance = thresholdsForDrawingScale(observation.evidence.local.pt_per_ft);
70470
70583
  if (observed.kind === "failure") {
70471
70584
  accumulator.failures.add(observed.reason);
@@ -70546,7 +70659,28 @@ function fromDecision(member, end, role) {
70546
70659
  invalidationId: decision.invalidationId
70547
70660
  };
70548
70661
  }
70549
- 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) {
70550
70684
  const currentPoint = end === 0 ? member.from : member.to;
70551
70685
  const geometryOnly = !evidence.basis;
70552
70686
  const completeTargets = targetsOf(result);
@@ -70572,6 +70706,9 @@ function freshFinding(member, end, role, scope, evidence, result) {
70572
70706
  ...evidence.basis ? { basis: evidence.basis } : {}
70573
70707
  };
70574
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
+ }
70575
70712
  if (evidence.failures.length) return {
70576
70713
  ...base,
70577
70714
  classification: "not-checkable",
@@ -70642,7 +70779,7 @@ function counts(findings) {
70642
70779
  notCheckable: findings.filter((item) => item.classification === "not-checkable").length
70643
70780
  };
70644
70781
  }
70645
- function analyzeSteelMemberEnds(model, scope) {
70782
+ function analyzeSteelMemberEnds(model, scope, retainedMemberIds = /* @__PURE__ */ new Set()) {
70646
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;
70647
70784
  if (normalizedScope2.kind === "conversion" && normalizedScope2.viewIds.length === 0) {
70648
70785
  throw new TypeError("conversion endpoint analysis requires at least one view id");
@@ -70656,7 +70793,8 @@ function analyzeSteelMemberEnds(model, scope) {
70656
70793
  const targetMembers = model.members.map(targetMember).filter((item) => !!item);
70657
70794
  const targetMap = new Map(targetMembers.map((member) => [member.id, member]));
70658
70795
  const deadlineMs = Date.now() + SUPPORT_CENTERLINE_V1.watchdogMs;
70659
- const evidenceIndex = buildEvidenceIndex(model, plans, deadlineMs);
70796
+ const diagnoses = new EvidenceNotes();
70797
+ const evidenceIndex = buildEvidenceIndex(model, plans, deadlineMs, diagnoses);
70660
70798
  const spatialIndex = new MemberEndSpatialIndex(orderedCandidateRecords(targetMembers), deadlineMs);
70661
70799
  const findings = [];
70662
70800
  let subjectEnds = 0;
@@ -70685,10 +70823,10 @@ function analyzeSteelMemberEnds(model, scope) {
70685
70823
  continue;
70686
70824
  }
70687
70825
  if (!analyzed) {
70688
- const finding2 = freshFinding(member, end, role.finding, normalizedScope2, evidence, {
70826
+ const finding2 = freshFinding(member, end, role.finding, normalizedScope2, plans, evidence.analysisScope ?? aScope, evidence, {
70689
70827
  kind: "not-checkable",
70690
70828
  reasons: Object.freeze(["subject-geometry-invalid"])
70691
- });
70829
+ }, diagnoses);
70692
70830
  if (finding2) findings.push(finding2);
70693
70831
  continue;
70694
70832
  }
@@ -70704,18 +70842,21 @@ function analyzeSteelMemberEnds(model, scope) {
70704
70842
  targets: targetMap,
70705
70843
  consumeExactGeometryTest
70706
70844
  });
70707
- 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);
70708
70846
  if (finding) findings.push(finding);
70709
70847
  }
70710
70848
  }
70711
70849
  findings.sort((a, b) => Buffer.compare(Buffer.from(findingSortKey(a)), Buffer.from(findingSortKey(b))));
70850
+ const { notes: evidenceNotes, omitted } = diagnoses.publish(findings, retainedMemberIds);
70712
70851
  return {
70713
70852
  version: 1,
70714
70853
  policy: SUPPORT_CENTERLINE_POLICY,
70715
70854
  contractHash: asHash(model),
70716
70855
  scope: normalizedScope2,
70717
70856
  findings,
70718
- counts: counts(findings)
70857
+ counts: counts(findings),
70858
+ ...evidenceNotes.length ? { evidenceNotes } : {},
70859
+ ...omitted > 0 ? { evidenceNotesOmitted: omitted } : {}
70719
70860
  };
70720
70861
  }
70721
70862
  function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE__ */ new Set(), currentModel) {
@@ -70744,14 +70885,17 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70744
70885
  const literalContractHash = asHash(literal);
70745
70886
  const retainedMemberIdsHash = hashRetainedMemberIds(existingMemberIds);
70746
70887
  if (viewIds.length === 0) {
70747
- const report2 = analyzeSteelMemberEnds(sanitized, { kind: "model-3d" });
70888
+ const report2 = analyzeSteelMemberEnds(sanitized, { kind: "model-3d" }, existingMemberIds);
70748
70889
  return { literalContractHash, finalContractHash: asHash(sanitized), model: sanitized, report: report2, retainedMemberIdsHash };
70749
70890
  }
70750
70891
  const conversionScope = { kind: "conversion", viewIds };
70751
70892
  const evidenceIndex = buildEvidenceIndex(
70752
70893
  sanitized,
70753
70894
  selectedPlans(sanitized, conversionScope),
70754
- 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()
70755
70899
  );
70756
70900
  for (const member of sanitized.members) {
70757
70901
  if (existingMemberIds.has(member.id) || !roleOf(member)) continue;
@@ -70768,7 +70912,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70768
70912
  }
70769
70913
  }
70770
70914
  }
70771
- const conversion = analyzeSteelMemberEnds(sanitized, conversionScope);
70915
+ const conversion = analyzeSteelMemberEnds(sanitized, conversionScope, existingMemberIds);
70772
70916
  const model = cloneModel(sanitized);
70773
70917
  for (const finding of conversion.findings) {
70774
70918
  if (finding.classification !== "aligned-auto" || existingMemberIds.has(finding.memberId)) continue;
@@ -70805,7 +70949,7 @@ function normalizeSteelMemberEndsForRead(literal, existingMemberIds = /* @__PURE
70805
70949
  )
70806
70950
  };
70807
70951
  }
70808
- let report = analyzeSteelMemberEnds(model, { kind: "conversion", viewIds });
70952
+ let report = analyzeSteelMemberEnds(model, { kind: "conversion", viewIds }, existingMemberIds);
70809
70953
  if (existingMemberIds.size) {
70810
70954
  const findings = report.findings.map((finding) => {
70811
70955
  if (finding.classification !== "aligned-auto" || !existingMemberIds.has(finding.memberId)) return finding;
@@ -70845,7 +70989,9 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70845
70989
  const freshEvidence = viewIds.length ? buildEvidenceIndex(
70846
70990
  model,
70847
70991
  selectedPlans(model, { kind: "conversion", viewIds }),
70848
- 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()
70849
70995
  ) : /* @__PURE__ */ new Map();
70850
70996
  const literalized = cloneModel(model);
70851
70997
  const literalMembers = new Map(literalized.members.map((member) => [member.id, member]));
@@ -70884,7 +71030,8 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70884
71030
  }
70885
71031
  const replay = analyzeSteelMemberEnds(
70886
71032
  literalized,
70887
- viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" }
71033
+ viewIds.length ? { kind: "conversion", viewIds } : { kind: "model-3d" },
71034
+ retainedMemberIds
70888
71035
  );
70889
71036
  const replayFindings = new Map(replay.findings.map((finding) => [evidenceKey(finding.memberId, finding.end), finding]));
70890
71037
  for (const [key2, { member, end, observedPoint, decision }] of replaySubjects) {
@@ -70899,7 +71046,7 @@ function reportTrustedFinalSteelMemberEnds(model, retainedMemberIds) {
70899
71046
  );
70900
71047
  }
70901
71048
  }
70902
- 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);
70903
71050
  if (retainedMemberIds.size) {
70904
71051
  const findings = report.findings.map((finding) => {
70905
71052
  if (finding.classification !== "aligned-auto" || !retainedMemberIds.has(finding.memberId)) return finding;
@@ -70946,6 +71093,7 @@ var MAX_FACET_EXCLUSIONS = 5e3;
70946
71093
  var MAX_FACET_VALUE_CHARS = 200;
70947
71094
  var MAX_DISPOSITION_GROUPS = 5e3;
70948
71095
  var MAX_JOINTS = 1e4;
71096
+ var MAX_REPORTED_NOTES_PER_REASON = 1;
70949
71097
  var MAX_MEMBERS = 1e4;
70950
71098
  var MAX_TEXT = 1e3;
70951
71099
  var SHA = /^[0-9a-f]{64}$/;
@@ -71420,18 +71568,20 @@ function evaluateSteelRead(context) {
71420
71568
  const observationAudit = activeObservationElements(candidate, retainedMemberIds);
71421
71569
  const observations2 = observationAudit.elements;
71422
71570
  if (validation.valid) {
71423
- const evidenceReasons = /* @__PURE__ */ new Set([
71424
- "endpoint-elevation-missing",
71425
- "view-scale-invalid",
71426
- "observation-scale-mismatch",
71427
- "view-unregistered",
71428
- "cross-view-conflict"
71429
- ]);
71430
- 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"}` : ""}` : "";
71431
71581
  add(
71432
71582
  "endpoint-evidence",
71433
71583
  endpointEvidence.length ? "block" : "pass",
71434
- 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",
71435
71585
  endpointEvidence
71436
71586
  );
71437
71587
  } else add("endpoint-evidence", "block", "endpoint evidence cannot be evaluated until the v2 contract is valid");
@@ -71551,7 +71701,12 @@ function evaluateSteelRead(context) {
71551
71701
  if (!row || row.status === "resolved" && (!row.targetPageId || !pagesById.has(row.targetPageId))) badRefs.push(ref.id);
71552
71702
  }
71553
71703
  for (const id of refById.keys()) if (!refIds.has(id)) badRefs.push(id);
71554
- add("reference-graph", badRefs.length ? "block" : proof3.references.some((row) => row.status === "missing") ? "warning" : "pass", badRefs.length ? "reference candidates are unaccounted or target foreign pages" : `${refs.length} reference marker(s) reach a fixed accounting point`, badRefs);
71704
+ add(
71705
+ "reference-graph",
71706
+ badRefs.length ? "block" : proof3.references.some((row) => row.status === "missing") ? "warning" : "pass",
71707
+ badRefs.length ? "reference candidates are unaccounted or target foreign pages \u2014 answer exactly the manifest GET's referenceCandidates list (decided by each element's text, so it covers detail/connection markers too, not only reference-marker candidates), and give every resolved row a targetPageId naming a page of THIS manifest" : `${refs.length} reference obligation(s) reach a fixed accounting point`,
71708
+ badRefs
71709
+ );
71555
71710
  const markerCandidates = (inventory ?? storedManifest.manifest.pages.flatMap((page) => page.candidates ?? [])).filter((candidate2) => candidate2.kind === "detail-marker" || candidate2.kind === "connection-marker");
71556
71711
  const markerIds = new Set(markerCandidates.map((marker) => marker.id));
71557
71712
  const dispositionByCandidate = new Map(proof3.candidateDispositions.map((row) => [row.elementId, row]));
@@ -72265,6 +72420,46 @@ function appContractState(appId, app, resolve21 = (id, op, readAppFn) => resolve
72265
72420
  function readAcceptedForRequest(appId, projectId, operation) {
72266
72421
  return readAcceptedContract({ appId, projectId, operation });
72267
72422
  }
72423
+ var acceptedContractIdentityCache = /* @__PURE__ */ new Map();
72424
+ function acceptedContractIdentity(appId, projectId) {
72425
+ const path = contractPath(appId, projectId);
72426
+ const key2 = JSON.stringify([appId, projectId]);
72427
+ const signature = () => {
72428
+ try {
72429
+ const stat4 = (0, import_node_fs41.statSync)(path, { bigint: true });
72430
+ return [stat4.dev, stat4.ino, stat4.size, stat4.mtimeNs, stat4.ctimeNs].join(":");
72431
+ } catch (error) {
72432
+ if (error?.code === "ENOENT") return "absent";
72433
+ throw error;
72434
+ }
72435
+ };
72436
+ assertServable(projectId);
72437
+ for (let attempt = 0; attempt < 2; attempt += 1) {
72438
+ const before = signature();
72439
+ const cached = acceptedContractIdentityCache.get(key2);
72440
+ if (cached?.signature === before) {
72441
+ if (cached.contractEtag !== null && cached.contractType) {
72442
+ assertAcceptableType(
72443
+ cached.contractType,
72444
+ ctxFor({ appId, projectId, operation: "read" }, cached.contractType)
72445
+ );
72446
+ }
72447
+ return { contractType: cached.contractType, contractEtag: cached.contractEtag };
72448
+ }
72449
+ const contract = readAcceptedForRequest(appId, projectId, "read");
72450
+ const identity = {
72451
+ contractType: contract == null ? void 0 : declaredTypeOf(contract),
72452
+ contractEtag: etagOf(contract)
72453
+ };
72454
+ const after = signature();
72455
+ if (before === after) {
72456
+ if (contract == null && before !== "absent") return identity;
72457
+ acceptedContractIdentityCache.set(key2, { signature: after, ...identity });
72458
+ return identity;
72459
+ }
72460
+ }
72461
+ return { contractType: void 0, contractEtag: null };
72462
+ }
72268
72463
  function etagOf(doc) {
72269
72464
  return doc == null ? null : `"${contractHash(doc)}"`;
72270
72465
  }
@@ -75887,6 +76082,22 @@ function steelExclusionPreflight(ledger, filter) {
75887
76082
  }
75888
76083
 
75889
76084
  // revision-request-view.ts
76085
+ function filterCheckpointMatchesCurrent(request, currentEtag) {
76086
+ return request.type === "revision-read" && request.settledVersion === void 0 && request.prepassReady === true && request.filterSaved === true && typeof request.filterSavedEtag === "string" && request.filterSavedEtag.length > 0 && request.filterSavedEtag === currentEtag;
76087
+ }
76088
+ function filterCheckpointIsCurrent(request, currentEtag) {
76089
+ return request.status === "pending" && filterCheckpointMatchesCurrent(request, currentEtag);
76090
+ }
76091
+ function acceptedContractFacts(appId, projectId) {
76092
+ try {
76093
+ return acceptedContractIdentity(appId, projectId);
76094
+ } catch {
76095
+ return { contractType: void 0, contractEtag: null };
76096
+ }
76097
+ }
76098
+ function acceptedContractEtag(appId, projectId) {
76099
+ return acceptedContractFacts(appId, projectId).contractEtag;
76100
+ }
75890
76101
  function revisionRequestStageId(request) {
75891
76102
  if (request.type !== "revision-read" || request.status !== "staged" || !request.project) return void 0;
75892
76103
  const stagingKey = getProjectStagingId(request.project);
@@ -75897,18 +76108,23 @@ function revisionRequestStageId(request) {
75897
76108
  }
75898
76109
  function revisionRequestViewFields(request, memo = {}) {
75899
76110
  const discard = request.type === "revision-read" && request.status === "staged" ? revisionDiscardPolicyFor(request) : void 0;
76111
+ const contractFacts = request.type === "revision-read" && request.appId && request.project ? (memo.contractFacts ?? acceptedContractFacts)(request.appId, request.project) : void 0;
75900
76112
  return {
75901
76113
  appTemplateId: request.appId ? (memo.templateId ?? resolveTemplateId)(request.appId) : void 0,
75902
76114
  nativeSteelReady: request.type === "revision-read" && request.appId && request.project ? (() => {
75903
76115
  const project = getProject(request.project);
75904
- return !!project && sameAppLineage(request.appId, project.app) && (memo.contractType ?? storedContractType)(request.appId, request.project) === STEEL_V2;
76116
+ return !!project && sameAppLineage(request.appId, project.app) && contractFacts?.contractType === STEEL_V2;
75905
76117
  })() : void 0,
75906
76118
  extractorAvailable: request.type === "revision-read" ? steelFilterExtractorAvailable() : void 0,
75907
76119
  headVersion: request.type === "revision-read" && request.project ? (memo.headVersion ?? ((projectId) => listVersions(projectId)[0]?.n ?? 0))(request.project) : void 0,
75908
76120
  stageId: revisionRequestStageId(request),
75909
76121
  canDiscardRevision: discard?.canClear,
75910
76122
  discardWhy: discard?.clearWhy,
75911
- discardState: discard?.clearState
76123
+ discardState: discard?.clearState,
76124
+ filterCheckpointCurrent: request.type === "revision-read" && request.appId && request.project ? filterCheckpointIsCurrent(
76125
+ request,
76126
+ contractFacts?.contractEtag ?? null
76127
+ ) : void 0
75912
76128
  };
75913
76129
  }
75914
76130
  function enrichedRevisionRequestView(request, extra, memo = {}) {
@@ -76130,6 +76346,9 @@ function loadAuthoritativeSteelAuditState(project, requestId, attestation, allow
76130
76346
  })) throw new SteelAuditStateError("steel-source-manifest-changed", "the verified project source bytes no longer match the manifest");
76131
76347
  const parsedAttestation = parseSteelReadAttestation(attestation);
76132
76348
  const current = readAcceptedForRequest(project.app, project.id, "read");
76349
+ if (!filterCheckpointMatchesCurrent(request, etagOf(current))) {
76350
+ throw new SteelAuditStateError("steel-filter-save-missing", "the request has no current exact Filter Save checkpoint");
76351
+ }
76133
76352
  return {
76134
76353
  request,
76135
76354
  storedManifest,
@@ -76941,13 +77160,16 @@ function registerRevisionRoutes(app, deps = {}) {
76941
77160
  const effectiveFilter = savedFilterCurrent ? acceptedFilter : stored2.manifest.filter;
76942
77161
  let layerLineCounts;
76943
77162
  let preflight;
77163
+ let referenceCandidates;
76944
77164
  try {
77165
+ const candidateInventory = stored2.manifest.candidatesRepr === "v2-compact" ? compactManifestInventory(stored2.manifest.pages) : null;
76945
77166
  const ledger = sourceLineInventory({
76946
77167
  pages: stored2.manifest.pages,
76947
77168
  filter: effectiveFilter,
76948
- inventory: stored2.manifest.candidatesRepr === "v2-compact" ? compactManifestInventory(stored2.manifest.pages) : null
77169
+ inventory: candidateInventory
76949
77170
  });
76950
77171
  layerLineCounts = steelReadLayerLineCounts(ledger);
77172
+ referenceCandidates = referenceInventory(effectiveFilter, stored2, candidateInventory).map((row) => ({ elementId: row.id, text: row.text }));
76951
77173
  preflight = steelExclusionPreflight(ledger, effectiveFilter);
76952
77174
  } catch (error) {
76953
77175
  if (!(error instanceof SteelLedgerUnboundError)) throw error;
@@ -76966,6 +77188,7 @@ function registerRevisionRoutes(app, deps = {}) {
76966
77188
  exclusionBasis,
76967
77189
  facetLineCounts: preflight.facetLineCounts,
76968
77190
  facetUncensused: preflight.facetUncensused,
77191
+ referenceCandidates,
76969
77192
  ...savedFilterCurrent ? {
76970
77193
  dismissibleFacetValues: preflight.dismissed,
76971
77194
  proofBudget: preflight.budget,
@@ -77114,7 +77337,8 @@ function registerRevisionRoutes(app, deps = {}) {
77114
77337
  async (req, reply) => withLifecycleLock("project", req.params.id, async () => {
77115
77338
  const project = getProject(req.params.id);
77116
77339
  const request = getRequest(req.params.reqId);
77117
- if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.status !== "pending" || request.settledVersion !== void 0 || request.filterSaved !== true) {
77340
+ const currentEtag = project ? acceptedContractEtag(project.app, project.id) : null;
77341
+ if (!project || !request || request.type !== "revision-read" || request.project !== project.id || !filterCheckpointIsCurrent(request, currentEtag)) {
77118
77342
  return reply.status(404).send({ ok: false, error: "unknown active drawing read" });
77119
77343
  }
77120
77344
  let progress;
@@ -77215,14 +77439,14 @@ function registerRevisionRoutes(app, deps = {}) {
77215
77439
  });
77216
77440
  }
77217
77441
  const dims = new Set(MODE_ORDER);
77218
- const wellFormed = submitted.every((row) => {
77442
+ const wellFormed2 = submitted.every((row) => {
77219
77443
  if (!row || typeof row !== "object" || Array.isArray(row)) return false;
77220
77444
  const entry2 = row;
77221
77445
  if (Object.keys(entry2).length !== 2 || typeof entry2.dim !== "string" || !dims.has(entry2.dim)) return false;
77222
77446
  if (entry2.dim === "thickness") return typeof entry2.value === "number" && Number.isFinite(entry2.value);
77223
77447
  return typeof entry2.value === "string" && entry2.value.length > 0 && entry2.value.length <= MAX_SIGNOFF_STRING_VALUE;
77224
77448
  });
77225
- 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") {
77226
77450
  return reply.status(400).send({
77227
77451
  ok: false,
77228
77452
  code: "steel-exclusion-signoff-invalid",
@@ -77264,7 +77488,7 @@ function registerRevisionRoutes(app, deps = {}) {
77264
77488
  }
77265
77489
  try {
77266
77490
  const saved = recordSteelFilterSave({ requestId: request.id, filter, etag, expectedManifestHash: manifest.manifestHash, exclusionSignOff: signOff });
77267
- const updated2 = patchRequest(request.id, { filterSaved: true, filterSavedEtag: etag, steelSavedFilterHash: saved.savedFilterHash });
77491
+ const updated2 = patchRequestDurable(request.id, { filterSaved: true, filterSavedEtag: etag, steelSavedFilterHash: saved.savedFilterHash });
77268
77492
  if (!updated2) return reply.status(409).send({ ok: false, error: "the revision request changed while recording the Filter Save" });
77269
77493
  broadcast({ type: "request-added", request: requestView(updated2) });
77270
77494
  return { ok: true, request: requestView(updated2) };
@@ -77292,7 +77516,7 @@ function registerRevisionRoutes(app, deps = {}) {
77292
77516
  error: "this request is not governed by the Steel Model completion policy, so an exclusion approval cannot be recorded against it"
77293
77517
  });
77294
77518
  }
77295
- const updated = patchRequest(request.id, { filterSaved: true, filterSavedEtag: etag });
77519
+ const updated = patchRequestDurable(request.id, { filterSaved: true, filterSavedEtag: etag });
77296
77520
  if (!updated) return reply.status(409).send({ ok: false, error: "the revision request changed while recording the Filter Save" });
77297
77521
  broadcast({ type: "request-added", request: requestView(updated) });
77298
77522
  return { ok: true, request: requestView(updated) };
@@ -77481,7 +77705,7 @@ function registerRevisionRoutes(app, deps = {}) {
77481
77705
  }
77482
77706
  const appTemplateId = resolveTemplateId(project.app);
77483
77707
  const candidateType = declaredTypeOf(req.body.contract);
77484
- if (appTemplateId === "steel-model" && request.filterSaved !== true) {
77708
+ if (appTemplateId === "steel-model" && !filterCheckpointMatchesCurrent(request, etagOf(currentForEvidence))) {
77485
77709
  return reply.status(409).send({
77486
77710
  ok: false,
77487
77711
  error: "complete this request's Steel Filter pre-read, then review and Save the Filter before committing the read"
@@ -87214,7 +87438,7 @@ function registerContractRequestRoute(app, deps) {
87214
87438
  { bodyLimit: 25 * 1024 * 1024 },
87215
87439
  async (req, reply) => {
87216
87440
  const { appId, project, instruction, intent, target, snapshots } = req.body ?? {};
87217
- if (!isSafeAppId2(appId)) {
87441
+ if (!isSafeAppId(appId)) {
87218
87442
  return reply.status(400).send({ ok: false, error: "invalid appId" });
87219
87443
  }
87220
87444
  if (typeof instruction !== "string" || !instruction) {
@@ -87248,6 +87472,112 @@ function registerContractRequestRoute(app, deps) {
87248
87472
  );
87249
87473
  }
87250
87474
 
87475
+ // contract-put-route.ts
87476
+ function projectAppMismatch(appId, project) {
87477
+ const found = getProject(project);
87478
+ if (!found) return `unknown project: ${project}`;
87479
+ if (found.app !== appId) return `project "${project}" belongs to app "${found.app}", not "${appId}"`;
87480
+ return null;
87481
+ }
87482
+ function registerContractPutRoute(app, deps) {
87483
+ app.put(
87484
+ "/api/contract/:appId",
87485
+ { bodyLimit: STEEL_CONTRACT_BODY_LIMIT_BYTES },
87486
+ async (req, reply) => {
87487
+ const project = req.query.project || void 0;
87488
+ if (project) {
87489
+ const bad = projectAppMismatch(req.params.appId, project);
87490
+ if (bad) return reply.status(404).send({ ok: false, error: bad });
87491
+ }
87492
+ const prepassRequestId = typeof req.headers["x-floless-prepass-request"] === "string" ? req.headers["x-floless-prepass-request"] : "";
87493
+ const filterRequestId = typeof req.headers["x-floless-filter-request"] === "string" ? req.headers["x-floless-filter-request"] : "";
87494
+ const prepassRequest = prepassRequestId ? getRequest(prepassRequestId) : null;
87495
+ const filterRequest = filterRequestId ? getRequest(filterRequestId) : null;
87496
+ const contractBody = prepassRequest || filterRequest ? withDeterministicFilterIds(req.body) : req.body;
87497
+ if (prepassRequestId && (!project || !prepassRequest || prepassRequest.type !== "revision-read" || prepassRequest.project !== project || prepassRequest.status !== "pending" || prepassRequest.settledVersion !== void 0 || prepassRequest.prepassBaseEtag !== null || !isExactFilterCheckpointShell(contractBody))) {
87498
+ return reply.status(400).send({ ok: false, error: "X-FloLess-Prepass-Request must name this pending initial read and a populated Steel Filter" });
87499
+ }
87500
+ if (filterRequestId && (!project || !filterRequest || filterRequest.type !== "revision-read" || filterRequest.project !== project || filterRequest.status !== "pending" || filterRequest.settledVersion !== void 0)) {
87501
+ return reply.status(400).send({ ok: false, error: "X-FloLess-Filter-Request must name this pending drawing read" });
87502
+ }
87503
+ const boundRequest = prepassRequest ?? filterRequest;
87504
+ if (boundRequest) {
87505
+ const checked = validateSteelFilterSourceCoverage(contractBody, (boundRequest.sourceRefs ?? []).map((file) => file.sha256.toLowerCase()));
87506
+ if (!checked.ok) return reply.status(409).send({ ok: false, code: "filter-source-mismatch", error: "This filter no longer matches the attached drawing set. Reload the Drawing Filter and review it again." });
87507
+ }
87508
+ if (filterRequest && project) {
87509
+ const current = readAcceptedForRequest(req.params.appId, project, "read");
87510
+ if (current == null || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(contractBody) !== STEEL_V2) {
87511
+ return reply.status(409).send({ ok: false, code: "filter-checkpoint-missing", error: "Reload the Drawing Filter from this project and review it again." });
87512
+ }
87513
+ const withoutFilter = (value) => {
87514
+ const copy = structuredClone(value);
87515
+ delete copy.filter;
87516
+ return copy;
87517
+ };
87518
+ if (contractHash(withoutFilter(current)) !== contractHash(withoutFilter(contractBody))) {
87519
+ return reply.status(409).send({ ok: false, code: "filter-write-out-of-scope", error: "The model changed while the Drawing Filter was open. Reload it and review the filter again." });
87520
+ }
87521
+ }
87522
+ const ifMatch = typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : void 0;
87523
+ const ifNoneMatch = typeof req.headers["if-none-match"] === "string" ? req.headers["if-none-match"] : void 0;
87524
+ const persist2 = async () => {
87525
+ const livePrepass = prepassRequestId ? getRequest(prepassRequestId) : null;
87526
+ const liveFilter = filterRequestId ? getRequest(filterRequestId) : null;
87527
+ if (prepassRequestId && (!project || !livePrepass || livePrepass.type !== "revision-read" || livePrepass.project !== project || livePrepass.status !== "pending" || livePrepass.settledVersion !== void 0 || livePrepass.prepassBaseEtag !== null || !isExactFilterCheckpointShell(contractBody))) {
87528
+ return reply.status(400).send({ ok: false, error: "X-FloLess-Prepass-Request must name this pending initial read and a populated Steel Filter" });
87529
+ }
87530
+ if (filterRequestId && (!project || !liveFilter || liveFilter.type !== "revision-read" || liveFilter.project !== project || liveFilter.status !== "pending" || liveFilter.settledVersion !== void 0)) {
87531
+ return reply.status(400).send({ ok: false, error: "X-FloLess-Filter-Request must name this pending drawing read" });
87532
+ }
87533
+ const liveBound = livePrepass ?? liveFilter;
87534
+ if (liveBound) {
87535
+ const checked = validateSteelFilterSourceCoverage(contractBody, (liveBound.sourceRefs ?? []).map((file) => file.sha256.toLowerCase()));
87536
+ if (!checked.ok) return reply.status(409).send({ ok: false, code: "filter-source-mismatch", error: "This filter no longer matches every file in the attached drawing set. Reload the Drawing Filter and review it again." });
87537
+ }
87538
+ const result = await writeContractChecked(req.params.appId, contractBody, project, { origin: "client", ifMatch, ifNoneMatch });
87539
+ reply.header("ETag", result.etag);
87540
+ if (project) clearApproval(project);
87541
+ if (livePrepass) {
87542
+ const updated = patchRequest(livePrepass.id, { prepassReady: true, prepassEtag: result.etag, filterSaved: false, filterSavedEtag: void 0 });
87543
+ if (updated) deps.broadcast({ type: "request-added", request: updated });
87544
+ }
87545
+ if (liveFilter) {
87546
+ const updated = patchRequestDurable(liveFilter.id, {
87547
+ filterSaved: false,
87548
+ filterSavedEtag: void 0,
87549
+ steelSavedFilterHash: void 0
87550
+ });
87551
+ if (!updated) throw new Error("the revision request changed while invalidating its previous Filter Save");
87552
+ deps.broadcast({ type: "request-added", request: deps.requestView(updated) });
87553
+ }
87554
+ deps.broadcast(contractChangedEvent(req.params.appId, project, result.etag, result.storeRevision, req.headers["x-floless-mutation-id"]));
87555
+ return {
87556
+ ok: true,
87557
+ etag: result.etag,
87558
+ storeRevision: result.storeRevision,
87559
+ ...result.invalidatedWorkPointDecisions > 0 ? { contract: result.contract, invalidatedWorkPointDecisions: result.invalidatedWorkPointDecisions } : {},
87560
+ ...result.revalidation ? { revalidation: result.revalidation } : {}
87561
+ };
87562
+ };
87563
+ try {
87564
+ return await (project && (prepassRequestId || filterRequestId) ? withLifecycleLock("project", project, persist2) : persist2());
87565
+ } catch (error) {
87566
+ if (error instanceof PreconditionRequiredError) {
87567
+ return reply.status(428).send({ ok: false, error: error.message, code: error.code });
87568
+ }
87569
+ if (error instanceof PreconditionFailedError) {
87570
+ return reply.status(412).send({ ok: false, error: error.message, code: error.code });
87571
+ }
87572
+ if (error instanceof ContractError) {
87573
+ return reply.status(400).send({ ok: false, error: error.message, ...error.code ? { code: error.code } : {} });
87574
+ }
87575
+ throw error;
87576
+ }
87577
+ }
87578
+ );
87579
+ }
87580
+
87251
87581
  // instructor-guide-route.ts
87252
87582
  function registerInstructorGuideRoute(app, deps) {
87253
87583
  app.post(
@@ -92432,14 +92762,30 @@ function createMaintenanceMarkerStore(markerPath2, options = {}) {
92432
92762
  });
92433
92763
  }
92434
92764
  },
92435
- 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
+ }
92436
92771
  await io.rm(markerPath2, { force: true });
92772
+ return true;
92437
92773
  },
92438
- async quarantine() {
92774
+ async replaceCorrupt(replacement) {
92439
92775
  const quarantinePath = `${markerPath2}.corrupt`;
92440
- await io.rm(quarantinePath, { force: true });
92441
- await io.rename(markerPath2, quarantinePath);
92442
- 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
+ }
92443
92789
  }
92444
92790
  };
92445
92791
  }
@@ -92818,8 +93164,10 @@ var import_node_child_process14 = require("node:child_process");
92818
93164
  var import_promises9 = require("node:fs/promises");
92819
93165
  var import_node_util7 = require("node:util");
92820
93166
  var execFileAsync3 = (0, import_node_util7.promisify)(import_node_child_process14.execFile);
93167
+ var TIMED_OUT = /* @__PURE__ */ Symbol("installer-tree-probe-deadline");
92821
93168
  var INSTALLER_COMMAND_LINE_PATTERN = "@aware-aeco/cli@|\\baware(?:\\.cmd|\\.js)?\\W?\\s+sidecar\\s+install";
92822
93169
  var INSTALLER_RE = new RegExp(INSTALLER_COMMAND_LINE_PATTERN);
93170
+ var PROBE_TIMEOUT_MS = 5e3;
92823
93171
  function matchesInstallerCommandLine(commandLine) {
92824
93172
  return INSTALLER_RE.test(commandLine);
92825
93173
  }
@@ -92870,9 +93218,37 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
92870
93218
  }
92871
93219
  }
92872
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
+ };
92873
93247
  let entries;
92874
93248
  try {
92875
- 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;
92876
93252
  } catch {
92877
93253
  return true;
92878
93254
  }
@@ -92881,7 +93257,9 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
92881
93257
  if (!/^\d+$/.test(entry2) || Number(entry2) === selfPid) continue;
92882
93258
  let raw;
92883
93259
  try {
92884
- raw = await read2(entry2);
93260
+ const value = await withinDeadline(read2(entry2));
93261
+ if (value === TIMED_OUT) return true;
93262
+ raw = value;
92885
93263
  } catch (err2) {
92886
93264
  if (isVanishedProcessError(err2)) continue;
92887
93265
  return true;
@@ -92898,6 +93276,7 @@ async function anyAwareInstallerTreeAlive(deps = {}) {
92898
93276
  }
92899
93277
 
92900
93278
  // aware-update-jobs.ts
93279
+ var MAINTENANCE_RECOVERY = "maintenance-recovery";
92901
93280
  var AwareUpdateConflictError = class extends Error {
92902
93281
  status = 409;
92903
93282
  };
@@ -92909,6 +93288,10 @@ var AwareUpdateGoneError = class extends Error {
92909
93288
  };
92910
93289
  var DEFAULT_OPERATION_TIMEOUT = 10 * 6e4;
92911
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;
92912
93295
  var DEFAULT_RETENTION_TTL = 30 * 6e4;
92913
93296
  var DEFAULT_MAX_RETAINED = 24;
92914
93297
  function frozenHosts(hosts) {
@@ -92945,6 +93328,25 @@ var DeadlineError = class extends Error {
92945
93328
  function remaining(deadline, now) {
92946
93329
  return Math.max(0, deadline - now());
92947
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
+ }
92948
93350
  async function bounded(operation, budgetMs, parentSignal) {
92949
93351
  if (budgetMs <= 0) throw new DeadlineError();
92950
93352
  const controller = new AbortController();
@@ -93010,6 +93412,7 @@ var AwareUpdateJobManager = class {
93010
93412
  let operation = requestedOperation;
93011
93413
  let preResolved = null;
93012
93414
  let target;
93415
+ let recoveryMarker = null;
93013
93416
  if (operation === "bridge-repair") {
93014
93417
  const resolved = await this.#deps.resolveBridgeRepair(this.#currentOwnerOrThrow());
93015
93418
  if (!resolved) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
@@ -93017,9 +93420,22 @@ var AwareUpdateJobManager = class {
93017
93420
  preResolved = resolved.hosts;
93018
93421
  if (!preResolved.length) throw new AwareUpdateConflictError("No installed AWARE bridge needs repair.");
93019
93422
  } else {
93020
- const resolved = await this.#deps.resolveCurrentTarget();
93021
- target = requireExactAwareTarget(resolved.target);
93022
- 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
+ }
93023
93439
  }
93024
93440
  if (this.#active || this.#retrying) throw new AwareUpdateConflictError("An AWARE update is already in progress.");
93025
93441
  if (this.#shuttingDown) throw new AwareUpdateConflictError("FloLess is shutting down.");
@@ -93041,7 +93457,8 @@ var AwareUpdateJobManager = class {
93041
93457
  snapshot: frozenHosts([]),
93042
93458
  startedAt,
93043
93459
  touchedAt: startedAt,
93044
- ...preResolved ? { preResolved } : {}
93460
+ ...preResolved ? { preResolved } : {},
93461
+ ...operation === MAINTENANCE_RECOVERY ? { recoveryMarker } : {}
93045
93462
  });
93046
93463
  this.#active = transaction;
93047
93464
  const settled2 = this.#execute(transaction).catch((error) => this.#unexpectedFailure(transaction, error));
@@ -93128,6 +93545,16 @@ var AwareUpdateJobManager = class {
93128
93545
  if (this.#gone.has(transaction)) throw new AwareUpdateGoneError("This AWARE update result has expired.");
93129
93546
  throw new AwareUpdateNotFoundError("AWARE update transaction not found.");
93130
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
+ }
93131
93558
  async retry(transaction, hostValue) {
93132
93559
  this.#purge();
93133
93560
  if (!AWARE_BRIDGE_HOSTS.includes(hostValue)) {
@@ -93139,6 +93566,7 @@ var AwareUpdateJobManager = class {
93139
93566
  if (this.#gone.has(transaction)) throw new AwareUpdateGoneError("This AWARE update result has expired.");
93140
93567
  throw new AwareUpdateNotFoundError("AWARE update transaction not found.");
93141
93568
  }
93569
+ this.#assertRetryable(record4.status);
93142
93570
  if (record4.retry) {
93143
93571
  if (record4.retry.host !== host) throw new AwareUpdateConflictError("Another bridge retry is already in progress.");
93144
93572
  return cloneStatus(await record4.retry.reserved);
@@ -93165,7 +93593,7 @@ var AwareUpdateJobManager = class {
93165
93593
  const record4 = this.#jobs.get(transaction);
93166
93594
  if (!record4 || record4.status.state !== "running") return;
93167
93595
  const started = this.#now();
93168
- 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;
93169
93597
  const deadline = started + jobBudget;
93170
93598
  const jobController = new AbortController();
93171
93599
  this.#activeController = jobController;
@@ -93174,6 +93602,10 @@ var AwareUpdateJobManager = class {
93174
93602
  try {
93175
93603
  await this.#deps.withExclusive(async (owner2) => this.#deps.withMutationContainment(transaction, owner2, async () => {
93176
93604
  const operation = record4.status.operation;
93605
+ if (operation === MAINTENANCE_RECOVERY) {
93606
+ await this.#executeRecovery(record4, owner2, jobController, deadline);
93607
+ return;
93608
+ }
93177
93609
  this.#running(record4, "snapshot", 0, 0, []);
93178
93610
  const snapshot = record4.preResolved ?? await this.#deps.snapshotPersistentBridges(owner2, record4.status.target);
93179
93611
  this.#assertSnapshot(snapshot);
@@ -93185,7 +93617,7 @@ var AwareUpdateJobManager = class {
93185
93617
  stage: "runtime-install",
93186
93618
  target: record4.status.target,
93187
93619
  snapshot: record4.snapshot,
93188
- operation,
93620
+ operation: markerOperationOf(operation),
93189
93621
  origin: record4.status.origin
93190
93622
  };
93191
93623
  await this.#deps.maintenance.write(marker);
@@ -93318,6 +93750,126 @@ var AwareUpdateJobManager = class {
93318
93750
  this.#purge();
93319
93751
  }
93320
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
+ }
93321
93873
  async #executeRetry(record4, host, resolveReserved, rejectReserved) {
93322
93874
  let reserved = false;
93323
93875
  const retryController = new AbortController();
@@ -93361,7 +93913,8 @@ var AwareUpdateJobManager = class {
93361
93913
  target: status.target,
93362
93914
  host,
93363
93915
  snapshot: record4.snapshot,
93364
- operation: status.operation,
93916
+ // Unreachable — #assertRetryable refuses a recovery job before this — but proven, not assumed.
93917
+ operation: markerOperationOf(status.operation),
93365
93918
  origin: status.origin
93366
93919
  };
93367
93920
  try {
@@ -93509,6 +94062,17 @@ var AwareUpdateJobManager = class {
93509
94062
  #unexpectedFailure(transaction, error) {
93510
94063
  const record4 = this.#jobs.get(transaction);
93511
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
+ }
93512
94076
  this.#setTerminal(record4, {
93513
94077
  state: "runtime-failed",
93514
94078
  transaction,
@@ -93565,22 +94129,31 @@ var AwareUpdateJobManager = class {
93565
94129
  this.#gone.set(transaction, goneUntil);
93566
94130
  }
93567
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
+ }
93568
94138
  function cryptoRandomId() {
93569
94139
  return globalThis.crypto.randomUUID();
93570
94140
  }
93571
94141
  async function recoverInterruptedAwareMaintenance(deps) {
93572
- const read2 = await deps.maintenance.read();
93573
- if (read2.kind === "absent") return "clean";
93574
94142
  return deps.withRecoveryExclusive(async (owner2) => {
94143
+ const read2 = await deps.maintenance.read();
94144
+ if (read2.kind === "absent") return "clean";
93575
94145
  if (read2.kind === "corrupt") {
93576
94146
  if (await deps.anyInstallerTreeAlive()) {
93577
94147
  throw new Error("AWARE maintenance state is corrupt and an installer tree may still be running.");
93578
94148
  }
93579
- await deps.maintenance.quarantine();
93580
- 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)) {
93581
94155
  throw new Error("AWARE maintenance recovery could not verify a usable runtime and bridges.");
93582
94156
  }
93583
- await deps.maintenance.clear();
93584
94157
  return "recovered";
93585
94158
  }
93586
94159
  if (await deps.matchingChildAlive(read2.marker)) {
@@ -93592,7 +94165,6 @@ async function recoverInterruptedAwareMaintenance(deps) {
93592
94165
  if (!await deps.repairAndVerify({ ...read2.marker, stage: "recovery", child: void 0 }, owner2)) {
93593
94166
  throw new Error("AWARE maintenance recovery could not verify a usable runtime and bridges.");
93594
94167
  }
93595
- await deps.maintenance.clear();
93596
94168
  return "recovered";
93597
94169
  });
93598
94170
  }
@@ -93602,7 +94174,8 @@ function sendRouteError(reply, error) {
93602
94174
  if (error instanceof AwareUpdateConflictError || error instanceof AwareUpdateGoneError || error instanceof AwareUpdateNotFoundError) {
93603
94175
  return reply.status(error.status).send({ ok: false, error: error.message });
93604
94176
  }
93605
- 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 });
93606
94179
  }
93607
94180
  function registerAwareUpdateRoutes(app, manager) {
93608
94181
  app.get("/api/aware/update/active", async (_request, reply) => reply.send({ ok: true, job: manager.activeStatus() }));
@@ -95297,7 +95870,7 @@ function registerTerminalRunRoutes(app, deps) {
95297
95870
  if (req.run?.state === "needs-you") {
95298
95871
  return reply.status(409).send({
95299
95872
  ok: false,
95300
- error: req.type === "revision-read" && req.filterSaved !== true ? "Review and Save this request's Steel Filter before continuing its original terminal session." : "This request is parked in its original terminal session. Continue that session instead of starting another run.",
95873
+ error: req.type === "revision-read" && req.filterCheckpointCurrent !== true ? "Review and Save this request's Steel Filter before continuing its original terminal session." : "This request is parked in its original terminal session. Continue that session instead of starting another run.",
95301
95874
  code: "handoff-pending"
95302
95875
  });
95303
95876
  }
@@ -95308,7 +95881,7 @@ function registerTerminalRunRoutes(app, deps) {
95308
95881
  code: "handoff-pending"
95309
95882
  });
95310
95883
  }
95311
- if (req.appId !== void 0 && !isSafeAppId(req.appId)) {
95884
+ if (req.appId !== void 0 && !isSafeAppId2(req.appId)) {
95312
95885
  return reply.status(400).send({ ok: false, error: "This request names a workflow floless can\u2019t identify.", code: "bad-app-id" });
95313
95886
  }
95314
95887
  const asked = request.body?.runtime;
@@ -98148,14 +98721,69 @@ async function startServer() {
98148
98721
  }));
98149
98722
  }
98150
98723
  const awareUpdateJobs = new AwareUpdateJobManager({
98151
- resolveCurrentTarget: async () => {
98152
- const marker = await awareMaintenance.read();
98153
- if (marker.kind !== "absent") {
98154
- 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();
98155
98765
  }
98766
+ return { observedVersion };
98767
+ },
98768
+ resolveCurrentTarget: async () => {
98156
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
+ }
98157
98785
  return {
98158
- target: check.updateAvailable ? check.targetVersion ?? null : null,
98786
+ target: check.targetVersion ?? null,
98159
98787
  // 'none' cannot reach a started job (the target is null and requireExactAwareTarget throws),
98160
98788
  // but map it defensively rather than casting — the check type lets the two disagree.
98161
98789
  operation: check.operation === "bridge-repair" ? "bridge-repair" : "runtime-update"
@@ -98203,7 +98831,10 @@ async function startServer() {
98203
98831
  },
98204
98832
  invalidateVersion: invalidateAwareVersion,
98205
98833
  probeRuntime: () => aware.npmVersion(),
98206
- 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),
98207
98838
  installBridge: async (host, _target, context) => {
98208
98839
  let identityRecorded = Promise.resolve();
98209
98840
  await aware.sidecarInstall(host, {
@@ -98220,8 +98851,10 @@ async function startServer() {
98220
98851
  maintenance: awareMaintenance,
98221
98852
  log: (event) => app.log.info(event, "AWARE update transaction")
98222
98853
  });
98223
- async function repairInterruptedAwareMaintenance(marker, owner2) {
98854
+ let recoveryGeneration = 0;
98855
+ async function repairInterruptedAwareMaintenance(marker, owner2, signal) {
98224
98856
  if (owner2 !== upgradeOwner()) return false;
98857
+ const generation = ++recoveryGeneration;
98225
98858
  refreshInvoker();
98226
98859
  invalidateAwareVersion();
98227
98860
  const target = decideRecoveryTarget({
@@ -98230,6 +98863,15 @@ async function startServer() {
98230
98863
  installed: aware.npmVersion()
98231
98864
  });
98232
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
+ });
98233
98875
  const durable = await awareBridgePending.read();
98234
98876
  const observedHosts = await snapshotPersistentBridges(AWARE_BRIDGE_DIRECTORY);
98235
98877
  let snapshot = Object.freeze(AWARE_BRIDGE_HOSTS.filter((host) => (marker?.snapshot ?? []).includes(host) || observedHosts.includes(host) || durable?.target === target && durable.hosts.includes(host)));
@@ -98243,10 +98885,14 @@ async function startServer() {
98243
98885
  origin: marker?.origin ?? LEGACY_MARKER_ORIGIN
98244
98886
  };
98245
98887
  await awareMaintenance.write(recoveryMarker);
98246
- 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))) {
98247
98891
  await installAwareGlobal(target, () => {
98248
98892
  }, {
98893
+ ...signal ? { signal } : {},
98249
98894
  onChild: async (child) => {
98895
+ if (generation !== recoveryGeneration) return;
98250
98896
  recoveryMarker = { ...recoveryMarker, child };
98251
98897
  await awareMaintenance.write(recoveryMarker);
98252
98898
  }
@@ -98254,32 +98900,22 @@ async function startServer() {
98254
98900
  refreshInvoker();
98255
98901
  invalidateAwareVersion();
98256
98902
  }
98257
- 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 = [];
98258
98907
  for (const host of snapshot) {
98259
- if (await persistentBridgeVersion(AWARE_BRIDGE_DIRECTORY, host) === target) continue;
98260
- await withSidecarWrite(async () => {
98261
- let childRecorded = Promise.resolve();
98262
- await aware.sidecarInstall(host, {
98263
- onSpawn: (child) => {
98264
- if (!child.pid) throw new Error(`The ${host} bridge installer did not expose a child PID`);
98265
- childRecorded = maintenanceChildIdentity(child.pid, {
98266
- childStillRunning: () => child.exitCode === null && child.signalCode === null
98267
- }).then(async (identity) => {
98268
- recoveryMarker = { ...recoveryMarker, host, child: identity };
98269
- await awareMaintenance.write(recoveryMarker);
98270
- });
98271
- childRecorded.catch(() => {
98272
- });
98273
- }
98274
- });
98275
- await childRecorded;
98276
- if (await persistentBridgeVersion(AWARE_BRIDGE_DIRECTORY, host) !== target) {
98277
- throw new Error(`The recovered ${host} bridge did not match AWARE ${target}`);
98278
- }
98279
- });
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
+ );
98280
98918
  }
98281
- await awareBridgePending.clear().catch(() => {
98282
- });
98283
98919
  return true;
98284
98920
  }
98285
98921
  async function recoverAwareMaintenance() {
@@ -98288,9 +98924,23 @@ async function startServer() {
98288
98924
  withRecoveryExclusive: (work) => withAwareExclusive(() => work(upgradeOwner())),
98289
98925
  matchingChildAlive: async (marker) => marker.child ? maintenanceChildMatches(marker.child) : false,
98290
98926
  anyInstallerTreeAlive: () => anyAwareInstallerTreeAlive(),
98291
- repairAndVerify: repairInterruptedAwareMaintenance
98927
+ repairAndVerify: repairInterruptedAwareMaintenance,
98928
+ buildRecoveryMarker
98292
98929
  });
98293
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
+ }
98294
98944
  const SKIP_AUTO_BRIDGE_REPAIR = process.env.FLOLESS_SKIP_AUTO_BRIDGE_REPAIR === "1";
98295
98945
  let autoRepairScheduled = false;
98296
98946
  let autoRepairInFlight = false;
@@ -98612,7 +99262,11 @@ async function startServer() {
98612
99262
  setTimeout(() => process.exit(0), 250);
98613
99263
  });
98614
99264
  app.get("/api/aware/update", async () => {
98615
- 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
+ }));
98616
99270
  });
98617
99271
  registerAwareUpdateRoutes(app, awareUpdateJobs);
98618
99272
  app.get("/api/release-notes", async (req, reply) => {
@@ -98935,7 +99589,7 @@ async function startServer() {
98935
99589
  const root6 = templateIdResolver();
98936
99590
  const nameMemo = /* @__PURE__ */ new Map();
98937
99591
  const headMemo = /* @__PURE__ */ new Map();
98938
- const contractTypeMemo = /* @__PURE__ */ new Map();
99592
+ const contractFactsMemo = /* @__PURE__ */ new Map();
98939
99593
  const headVersion = (project) => {
98940
99594
  const cached = headMemo.get(project);
98941
99595
  if (cached !== void 0) return cached;
@@ -98949,7 +99603,11 @@ async function startServer() {
98949
99603
  }), {
98950
99604
  templateId: root6,
98951
99605
  headVersion,
98952
- contractType: (appId, projectId) => storedContractType(appId, projectId, contractTypeMemo)
99606
+ contractFacts: (appId, projectId) => {
99607
+ const key2 = JSON.stringify([appId, projectId]);
99608
+ if (!contractFactsMemo.has(key2)) contractFactsMemo.set(key2, acceptedContractFacts(appId, projectId));
99609
+ return contractFactsMemo.get(key2);
99610
+ }
98953
99611
  }));
98954
99612
  };
98955
99613
  app.get("/api/projects", async () => ({ ok: true, projects: projectViews(listProjects()) }));
@@ -99505,12 +100163,6 @@ async function startServer() {
99505
100163
  registerSteelPrepassRoute(app, { getProject, clearApproval, broadcast });
99506
100164
  registerKnowledgeRoutes(app);
99507
100165
  registerKbPinRoutes(app, { broadcast });
99508
- function projectAppMismatch(appId, project) {
99509
- const p = getProject(project);
99510
- if (!p) return `unknown project: ${project}`;
99511
- if (p.app !== appId) return `project "${project}" belongs to app "${p.app}", not "${appId}"`;
99512
- return null;
99513
- }
99514
100166
  app.get(
99515
100167
  "/api/projects/:id/contract-lifecycle",
99516
100168
  async (req, reply) => {
@@ -99624,97 +100276,7 @@ async function startServer() {
99624
100276
  return reply.type("image/svg+xml").send((0, import_node_fs80.readFileSync)(file, "utf8"));
99625
100277
  }
99626
100278
  );
99627
- app.put(
99628
- "/api/contract/:appId",
99629
- { bodyLimit: STEEL_CONTRACT_BODY_LIMIT_BYTES },
99630
- // the whole steel contract, rasters included — see steel-contract-body-limit.ts
99631
- async (req, reply) => {
99632
- const project = req.query.project || void 0;
99633
- if (project) {
99634
- const bad = projectAppMismatch(req.params.appId, project);
99635
- if (bad) return reply.status(404).send({ ok: false, error: bad });
99636
- }
99637
- const prepassRequestId = typeof req.headers["x-floless-prepass-request"] === "string" ? req.headers["x-floless-prepass-request"] : "";
99638
- const filterRequestId = typeof req.headers["x-floless-filter-request"] === "string" ? req.headers["x-floless-filter-request"] : "";
99639
- const prepassRequest = prepassRequestId ? getRequest(prepassRequestId) : null;
99640
- const filterRequest = filterRequestId ? getRequest(filterRequestId) : null;
99641
- let contractBody = prepassRequest || filterRequest ? withDeterministicFilterIds(req.body) : req.body;
99642
- if (prepassRequestId && (!project || !prepassRequest || prepassRequest.type !== "revision-read" || prepassRequest.project !== project || prepassRequest.status !== "pending" || prepassRequest.settledVersion !== void 0 || prepassRequest.prepassBaseEtag !== null || !isExactFilterCheckpointShell(contractBody))) {
99643
- return reply.status(400).send({ ok: false, error: "X-FloLess-Prepass-Request must name this pending initial read and a populated Steel Filter" });
99644
- }
99645
- if (filterRequestId && (!project || !filterRequest || filterRequest.type !== "revision-read" || filterRequest.project !== project || filterRequest.status !== "pending" || filterRequest.settledVersion !== void 0)) {
99646
- return reply.status(400).send({ ok: false, error: "X-FloLess-Filter-Request must name this pending drawing read" });
99647
- }
99648
- const boundRequest = prepassRequest ?? filterRequest;
99649
- if (boundRequest) {
99650
- const checked = validateSteelFilterSourceCoverage(contractBody, (boundRequest.sourceRefs ?? []).map((file) => file.sha256.toLowerCase()));
99651
- if (!checked.ok) return reply.status(409).send({ ok: false, code: "filter-source-mismatch", error: "This filter no longer matches the attached drawing set. Reload the Drawing Filter and review it again." });
99652
- }
99653
- if (filterRequest && project) {
99654
- const current = readAcceptedForRequest(req.params.appId, project, "read");
99655
- if (current == null || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(contractBody) !== STEEL_V2) {
99656
- return reply.status(409).send({ ok: false, code: "filter-checkpoint-missing", error: "Reload the Drawing Filter from this project and review it again." });
99657
- }
99658
- const withoutFilter = (value) => {
99659
- const copy = structuredClone(value);
99660
- delete copy.filter;
99661
- return copy;
99662
- };
99663
- if (contractHash(withoutFilter(current)) !== contractHash(withoutFilter(contractBody))) {
99664
- return reply.status(409).send({ ok: false, code: "filter-write-out-of-scope", error: "The model changed while the Drawing Filter was open. Reload it and review the filter again." });
99665
- }
99666
- }
99667
- const ifMatch = typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : void 0;
99668
- const ifNoneMatch = typeof req.headers["if-none-match"] === "string" ? req.headers["if-none-match"] : void 0;
99669
- const persist2 = async () => {
99670
- const livePrepass = prepassRequestId ? getRequest(prepassRequestId) : null;
99671
- const liveFilter = filterRequestId ? getRequest(filterRequestId) : null;
99672
- if (prepassRequestId && (!project || !livePrepass || livePrepass.type !== "revision-read" || livePrepass.project !== project || livePrepass.status !== "pending" || livePrepass.settledVersion !== void 0 || livePrepass.prepassBaseEtag !== null || !isExactFilterCheckpointShell(contractBody))) {
99673
- return reply.status(400).send({ ok: false, error: "X-FloLess-Prepass-Request must name this pending initial read and a populated Steel Filter" });
99674
- }
99675
- if (filterRequestId && (!project || !liveFilter || liveFilter.type !== "revision-read" || liveFilter.project !== project || liveFilter.status !== "pending" || liveFilter.settledVersion !== void 0)) {
99676
- return reply.status(400).send({ ok: false, error: "X-FloLess-Filter-Request must name this pending drawing read" });
99677
- }
99678
- const liveBound = livePrepass ?? liveFilter;
99679
- if (liveBound) {
99680
- const checked = validateSteelFilterSourceCoverage(contractBody, (liveBound.sourceRefs ?? []).map((file) => file.sha256.toLowerCase()));
99681
- if (!checked.ok) return reply.status(409).send({ ok: false, code: "filter-source-mismatch", error: "This filter no longer matches every file in the attached drawing set. Reload the Drawing Filter and review it again." });
99682
- }
99683
- const result = await writeContractChecked(req.params.appId, contractBody, project, { origin: "client", ifMatch, ifNoneMatch });
99684
- reply.header("ETag", result.etag);
99685
- if (project) clearApproval(project);
99686
- if (livePrepass) {
99687
- const updated = patchRequest(livePrepass.id, { prepassReady: true, prepassEtag: result.etag, filterSaved: false, filterSavedEtag: void 0 });
99688
- if (updated) broadcast({ type: "request-added", request: updated });
99689
- }
99690
- broadcast(contractChangedEvent(req.params.appId, project, result.etag, result.storeRevision, req.headers["x-floless-mutation-id"]));
99691
- return {
99692
- ok: true,
99693
- etag: result.etag,
99694
- storeRevision: result.storeRevision,
99695
- ...result.invalidatedWorkPointDecisions > 0 ? { contract: result.contract, invalidatedWorkPointDecisions: result.invalidatedWorkPointDecisions } : {},
99696
- // The write-boundary connection revalidation report (server/contract-gateway.ts). Present only
99697
- // when a client steel move actually ran revalidation; the client threads it into ONE plain-English
99698
- // toast. It is NOT accompanied by the transformed contract on a plain move — the removed/repointed
99699
- // joints already live in the stored contract, and re-installing here would wipe the browser's undo
99700
- // stack (installMemberEndContract clears it), stranding the one-Ctrl+Z-restores-the-joint gesture.
99701
- ...result.revalidation ? { revalidation: result.revalidation } : {}
99702
- };
99703
- };
99704
- try {
99705
- return await (project && (prepassRequestId || filterRequestId) ? withLifecycleLock("project", project, persist2) : persist2());
99706
- } catch (e) {
99707
- if (e instanceof PreconditionRequiredError) {
99708
- return reply.status(428).send({ ok: false, error: e.message, code: e.code });
99709
- }
99710
- if (e instanceof PreconditionFailedError) {
99711
- return reply.status(412).send({ ok: false, error: e.message, code: e.code });
99712
- }
99713
- if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
99714
- throw e;
99715
- }
99716
- }
99717
- );
100279
+ registerContractPutRoute(app, { broadcast, requestView: requestView2 });
99718
100280
  app.get("/api/projects/:id/approval-review", async (req, reply) => {
99719
100281
  try {
99720
100282
  return await withLifecycleLock("project", req.params.id, () => {
@@ -101583,7 +102145,7 @@ async function startServer() {
101583
102145
  { bodyLimit: 25 * 1024 * 1024 },
101584
102146
  async (req, reply) => {
101585
102147
  const { appId, nodeId, instruction, snapshots } = req.body ?? {};
101586
- if (!isSafeAppId2(appId) || !nodeId || !instruction) {
102148
+ if (!isSafeAppId(appId) || !nodeId || !instruction) {
101587
102149
  return reply.status(400).send({ ok: false, error: "appId, nodeId, instruction required" });
101588
102150
  }
101589
102151
  let decoded;
@@ -101607,7 +102169,7 @@ async function startServer() {
101607
102169
  async (req, reply) => {
101608
102170
  const { appId, inputName, instruction, snapshots } = req.body ?? {};
101609
102171
  const sourceName = typeof req.body?.sourceName === "string" ? req.body.sourceName : void 0;
101610
- if (!isSafeAppId2(appId)) return reply.status(400).send({ ok: false, error: "a valid appId is required" });
102172
+ if (!isSafeAppId(appId)) return reply.status(400).send({ ok: false, error: "a valid appId is required" });
101611
102173
  let decoded;
101612
102174
  try {
101613
102175
  decoded = decodeSnapshots(snapshots);
@@ -101699,7 +102261,7 @@ async function startServer() {
101699
102261
  );
101700
102262
  app.post("/api/use-template", async (req, reply) => {
101701
102263
  const { appId, templateId } = req.body ?? {};
101702
- if (!isSafeAppId2(appId) || !templateId) return reply.status(400).send({ ok: false, error: "a valid appId and templateId are required" });
102264
+ if (!isSafeAppId(appId) || !templateId) return reply.status(400).send({ ok: false, error: "a valid appId and templateId are required" });
101703
102265
  const template = getTemplate(templateId);
101704
102266
  if (!template) return reply.status(404).send({ ok: false, error: "template not found" });
101705
102267
  const request = addRequest({ type: "use-template", appId, templateId, template });