@floless/app 0.109.3 → 0.109.4

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.
@@ -8628,69 +8628,69 @@ var require_error_serializer = __commonJS({
8628
8628
  const obj2 = input && typeof input.toJSON === "function" ? input.toJSON() : input;
8629
8629
  if (obj2 === null) return JSON_STR_EMPTY_OBJECT;
8630
8630
  let value;
8631
- let json = JSON_STR_BEGIN_OBJECT;
8631
+ let json2 = JSON_STR_BEGIN_OBJECT;
8632
8632
  let addComma = false;
8633
8633
  value = obj2["statusCode"];
8634
8634
  if (value !== void 0) {
8635
- !addComma && (addComma = true) || (json += JSON_STR_COMMA);
8636
- json += '"statusCode":';
8637
- json += asNumber(value);
8635
+ !addComma && (addComma = true) || (json2 += JSON_STR_COMMA);
8636
+ json2 += '"statusCode":';
8637
+ json2 += asNumber(value);
8638
8638
  }
8639
8639
  value = obj2["code"];
8640
8640
  if (value !== void 0) {
8641
- !addComma && (addComma = true) || (json += JSON_STR_COMMA);
8642
- json += '"code":';
8641
+ !addComma && (addComma = true) || (json2 += JSON_STR_COMMA);
8642
+ json2 += '"code":';
8643
8643
  if (typeof value !== "string") {
8644
8644
  if (value === null) {
8645
- json += JSON_STR_EMPTY_STRING;
8645
+ json2 += JSON_STR_EMPTY_STRING;
8646
8646
  } else if (value instanceof Date) {
8647
- json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8647
+ json2 += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8648
8648
  } else if (value instanceof RegExp) {
8649
- json += asString(value.source);
8649
+ json2 += asString(value.source);
8650
8650
  } else {
8651
- json += asString(value.toString());
8651
+ json2 += asString(value.toString());
8652
8652
  }
8653
8653
  } else {
8654
- json += asString(value);
8654
+ json2 += asString(value);
8655
8655
  }
8656
8656
  }
8657
8657
  value = obj2["error"];
8658
8658
  if (value !== void 0) {
8659
- !addComma && (addComma = true) || (json += JSON_STR_COMMA);
8660
- json += '"error":';
8659
+ !addComma && (addComma = true) || (json2 += JSON_STR_COMMA);
8660
+ json2 += '"error":';
8661
8661
  if (typeof value !== "string") {
8662
8662
  if (value === null) {
8663
- json += JSON_STR_EMPTY_STRING;
8663
+ json2 += JSON_STR_EMPTY_STRING;
8664
8664
  } else if (value instanceof Date) {
8665
- json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8665
+ json2 += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8666
8666
  } else if (value instanceof RegExp) {
8667
- json += asString(value.source);
8667
+ json2 += asString(value.source);
8668
8668
  } else {
8669
- json += asString(value.toString());
8669
+ json2 += asString(value.toString());
8670
8670
  }
8671
8671
  } else {
8672
- json += asString(value);
8672
+ json2 += asString(value);
8673
8673
  }
8674
8674
  }
8675
8675
  value = obj2["message"];
8676
8676
  if (value !== void 0) {
8677
- !addComma && (addComma = true) || (json += JSON_STR_COMMA);
8678
- json += '"message":';
8677
+ !addComma && (addComma = true) || (json2 += JSON_STR_COMMA);
8678
+ json2 += '"message":';
8679
8679
  if (typeof value !== "string") {
8680
8680
  if (value === null) {
8681
- json += JSON_STR_EMPTY_STRING;
8681
+ json2 += JSON_STR_EMPTY_STRING;
8682
8682
  } else if (value instanceof Date) {
8683
- json += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8683
+ json2 += JSON_STR_QUOTE + value.toISOString() + JSON_STR_QUOTE;
8684
8684
  } else if (value instanceof RegExp) {
8685
- json += asString(value.source);
8685
+ json2 += asString(value.source);
8686
8686
  } else {
8687
- json += asString(value.toString());
8687
+ json2 += asString(value.toString());
8688
8688
  }
8689
8689
  } else {
8690
- json += asString(value);
8690
+ json2 += asString(value);
8691
8691
  }
8692
8692
  }
8693
- return json + JSON_STR_END_OBJECT;
8693
+ return json2 + JSON_STR_END_OBJECT;
8694
8694
  }
8695
8695
  const main2 = anonymous0;
8696
8696
  return main2;
@@ -25193,7 +25193,7 @@ var require_cmp = __commonJS({
25193
25193
  var gte = require_gte();
25194
25194
  var lt = require_lt();
25195
25195
  var lte = require_lte();
25196
- var cmp = (a, op, b, loose) => {
25196
+ var cmp2 = (a, op, b, loose) => {
25197
25197
  switch (op) {
25198
25198
  case "===":
25199
25199
  if (typeof a === "object") {
@@ -25229,7 +25229,7 @@ var require_cmp = __commonJS({
25229
25229
  throw new TypeError(`Invalid operator: ${op}`);
25230
25230
  }
25231
25231
  };
25232
- module2.exports = cmp;
25232
+ module2.exports = cmp2;
25233
25233
  }
25234
25234
  });
25235
25235
 
@@ -25796,7 +25796,7 @@ var require_comparator = __commonJS({
25796
25796
  return false;
25797
25797
  }
25798
25798
  }
25799
- return cmp(version, this.operator, this.semver, this.options);
25799
+ return cmp2(version, this.operator, this.semver, this.options);
25800
25800
  }
25801
25801
  intersects(comp, options) {
25802
25802
  if (!(comp instanceof _Comparator)) {
@@ -25829,10 +25829,10 @@ var require_comparator = __commonJS({
25829
25829
  if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
25830
25830
  return true;
25831
25831
  }
25832
- if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
25832
+ if (cmp2(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
25833
25833
  return true;
25834
25834
  }
25835
- if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
25835
+ if (cmp2(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
25836
25836
  return true;
25837
25837
  }
25838
25838
  return false;
@@ -25841,7 +25841,7 @@ var require_comparator = __commonJS({
25841
25841
  module2.exports = Comparator;
25842
25842
  var parseOptions = require_parse_options();
25843
25843
  var { safeRe: re, t } = require_re();
25844
- var cmp = require_cmp();
25844
+ var cmp2 = require_cmp();
25845
25845
  var debug = require_debug2();
25846
25846
  var SemVer = require_semver();
25847
25847
  var Range = require_range();
@@ -26352,7 +26352,7 @@ var require_semver2 = __commonJS({
26352
26352
  var neq = require_neq();
26353
26353
  var gte = require_gte();
26354
26354
  var lte = require_lte();
26355
- var cmp = require_cmp();
26355
+ var cmp2 = require_cmp();
26356
26356
  var coerce = require_coerce();
26357
26357
  var truncate = require_truncate();
26358
26358
  var Comparator = require_comparator();
@@ -26391,7 +26391,7 @@ var require_semver2 = __commonJS({
26391
26391
  neq,
26392
26392
  gte,
26393
26393
  lte,
26394
- cmp,
26394
+ cmp: cmp2,
26395
26395
  coerce,
26396
26396
  truncate,
26397
26397
  Comparator,
@@ -32061,7 +32061,7 @@ var require_parse_url = __commonJS({
32061
32061
  var require_form_data = __commonJS({
32062
32062
  "node_modules/light-my-request/lib/form-data.js"(exports2, module2) {
32063
32063
  "use strict";
32064
- var { randomUUID: randomUUID12 } = require("node:crypto");
32064
+ var { randomUUID: randomUUID13 } = require("node:crypto");
32065
32065
  var { Readable: Readable3 } = require("node:stream");
32066
32066
  var textEncoder;
32067
32067
  function isFormDataLike(payload) {
@@ -32069,7 +32069,7 @@ var require_form_data = __commonJS({
32069
32069
  }
32070
32070
  function formDataToStream(formdata) {
32071
32071
  textEncoder = textEncoder ?? new TextEncoder();
32072
- const boundary = `----formdata-${randomUUID12()}`;
32072
+ const boundary = `----formdata-${randomUUID13()}`;
32073
32073
  const prefix = `--${boundary}\r
32074
32074
  Content-Disposition: form-data`;
32075
32075
  const escape2 = (str5) => str5.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
@@ -44566,27 +44566,27 @@ var require_stringifyString = __commonJS({
44566
44566
  return true;
44567
44567
  }
44568
44568
  function doubleQuotedString(value, ctx) {
44569
- const json = JSON.stringify(value);
44569
+ const json2 = JSON.stringify(value);
44570
44570
  if (ctx.options.doubleQuotedAsJSON)
44571
- return json;
44571
+ return json2;
44572
44572
  const { implicitKey } = ctx;
44573
44573
  const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
44574
44574
  const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
44575
44575
  let str5 = "";
44576
44576
  let start = 0;
44577
- for (let i = 0, ch2 = json[i]; ch2; ch2 = json[++i]) {
44578
- if (ch2 === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
44579
- str5 += json.slice(start, i) + "\\ ";
44577
+ for (let i = 0, ch2 = json2[i]; ch2; ch2 = json2[++i]) {
44578
+ if (ch2 === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") {
44579
+ str5 += json2.slice(start, i) + "\\ ";
44580
44580
  i += 1;
44581
44581
  start = i;
44582
44582
  ch2 = "\\";
44583
44583
  }
44584
44584
  if (ch2 === "\\")
44585
- switch (json[i + 1]) {
44585
+ switch (json2[i + 1]) {
44586
44586
  case "u":
44587
44587
  {
44588
- str5 += json.slice(start, i);
44589
- const code = json.substr(i + 2, 4);
44588
+ str5 += json2.slice(start, i);
44589
+ const code = json2.substr(i + 2, 4);
44590
44590
  switch (code) {
44591
44591
  case "0000":
44592
44592
  str5 += "\\0";
@@ -44616,23 +44616,23 @@ var require_stringifyString = __commonJS({
44616
44616
  if (code.substr(0, 2) === "00")
44617
44617
  str5 += "\\x" + code.substr(2);
44618
44618
  else
44619
- str5 += json.substr(i, 6);
44619
+ str5 += json2.substr(i, 6);
44620
44620
  }
44621
44621
  i += 5;
44622
44622
  start = i + 1;
44623
44623
  }
44624
44624
  break;
44625
44625
  case "n":
44626
- if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
44626
+ if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) {
44627
44627
  i += 1;
44628
44628
  } else {
44629
- str5 += json.slice(start, i) + "\n\n";
44630
- while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
44629
+ str5 += json2.slice(start, i) + "\n\n";
44630
+ while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') {
44631
44631
  str5 += "\n";
44632
44632
  i += 2;
44633
44633
  }
44634
44634
  str5 += indent;
44635
- if (json[i + 2] === " ")
44635
+ if (json2[i + 2] === " ")
44636
44636
  str5 += "\\";
44637
44637
  i += 1;
44638
44638
  start = i + 1;
@@ -44642,7 +44642,7 @@ var require_stringifyString = __commonJS({
44642
44642
  i += 1;
44643
44643
  }
44644
44644
  }
44645
- str5 = start ? str5 + json.slice(start) : json;
44645
+ str5 = start ? str5 + json2.slice(start) : json2;
44646
44646
  return implicitKey ? str5 : foldFlowLines.foldFlowLines(str5, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
44647
44647
  }
44648
44648
  function singleQuotedString(value, ctx) {
@@ -47064,11 +47064,11 @@ var require_Document = __commonJS({
47064
47064
  throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
47065
47065
  }
47066
47066
  // json & jsonArg are only used from toJSON()
47067
- toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
47067
+ toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
47068
47068
  const ctx = {
47069
47069
  anchors: /* @__PURE__ */ new Map(),
47070
47070
  doc: this,
47071
- keep: !json,
47071
+ keep: !json2,
47072
47072
  mapAsMap: mapAsMap === true,
47073
47073
  mapKeyWarned: false,
47074
47074
  maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
@@ -53792,17 +53792,27 @@ function appVersion() {
53792
53792
  return resolveVersion({
53793
53793
  isSea: isSea2(),
53794
53794
  sqVersionXml: readSqVersionXml(),
53795
- define: true ? "0.109.3" : void 0,
53795
+ define: true ? "0.109.4" : void 0,
53796
53796
  pkgVersion: readPkgVersion()
53797
53797
  });
53798
53798
  }
53799
+ function isNpxPath(modulePath) {
53800
+ if (!modulePath) return false;
53801
+ return /(^|[\\/])_npx([\\/]|$)/.test(modulePath);
53802
+ }
53799
53803
  function resolveChannel(s) {
53800
53804
  if (s.isSea) return "desktop";
53801
- if (typeof s.define === "string") return "npm";
53805
+ if (typeof s.define === "string") return isNpxPath(s.modulePath) ? "npx" : "npm";
53802
53806
  return "dev";
53803
53807
  }
53804
53808
  function appChannel() {
53805
- return resolveChannel({ isSea: isSea2(), define: true ? "0.109.3" : void 0 });
53809
+ return resolveChannel({
53810
+ isSea: isSea2(),
53811
+ define: true ? "0.109.4" : void 0,
53812
+ // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
53813
+ // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
53814
+ modulePath: process.argv[1]
53815
+ });
53806
53816
  }
53807
53817
 
53808
53818
  // workflow-update.ts
@@ -55117,7 +55127,7 @@ function xsectionFor(profile, dims) {
55117
55127
  }
55118
55128
 
55119
55129
  // index.ts
55120
- var import_node_crypto20 = require("node:crypto");
55130
+ var import_node_crypto22 = require("node:crypto");
55121
55131
 
55122
55132
  // ifc-guid.ts
55123
55133
  var import_node_crypto7 = require("node:crypto");
@@ -55861,6 +55871,10 @@ function deleteRequest(id) {
55861
55871
  (0, import_node_fs18.rmSync)((0, import_node_path16.join)(REQUESTS_DIR, file));
55862
55872
  return true;
55863
55873
  }
55874
+ function hasRequestFile(id) {
55875
+ if (!(0, import_node_fs18.existsSync)(REQUESTS_DIR)) return false;
55876
+ return (0, import_node_fs18.readdirSync)(REQUESTS_DIR).some((f) => f.endsWith(`__${id}.json`));
55877
+ }
55864
55878
  function getRequest(id) {
55865
55879
  if (!(0, import_node_fs18.existsSync)(REQUESTS_DIR)) return null;
55866
55880
  const file = (0, import_node_fs18.readdirSync)(REQUESTS_DIR).find((f) => f.endsWith(`__${id}.json`));
@@ -56260,7 +56274,7 @@ function readContractForApp(appId, readAppFn = readApp) {
56260
56274
  }
56261
56275
 
56262
56276
  // project-versions-store.ts
56263
- var import_node_crypto10 = require("node:crypto");
56277
+ var import_node_crypto12 = require("node:crypto");
56264
56278
  var import_node_fs23 = require("node:fs");
56265
56279
  var import_promises2 = require("node:fs/promises");
56266
56280
  var import_node_path21 = require("node:path");
@@ -56270,7 +56284,7 @@ var import_node_fs22 = require("node:fs");
56270
56284
  var import_promises = require("node:fs/promises");
56271
56285
  var import_node_path20 = require("node:path");
56272
56286
  var import_node_os15 = require("node:os");
56273
- var import_node_crypto9 = require("node:crypto");
56287
+ var import_node_crypto11 = require("node:crypto");
56274
56288
 
56275
56289
  // node_modules/fflate/esm/index.mjs
56276
56290
  var import_module = require("module");
@@ -57616,8 +57630,27 @@ function unzipSync(data, opts) {
57616
57630
 
57617
57631
  // revision-staging-store.ts
57618
57632
  var import_node_fs21 = require("node:fs");
57633
+ var import_node_crypto10 = require("node:crypto");
57619
57634
  var import_node_os14 = require("node:os");
57620
57635
  var import_node_path19 = require("node:path");
57636
+
57637
+ // canonical-json.ts
57638
+ var import_node_crypto9 = require("node:crypto");
57639
+ function canonicalJson(v) {
57640
+ const walk2 = (x) => {
57641
+ if (Array.isArray(x)) return x.map(walk2);
57642
+ if (x && typeof x === "object") {
57643
+ const out = {};
57644
+ for (const k of Object.keys(x).sort()) out[k] = walk2(x[k]);
57645
+ return out;
57646
+ }
57647
+ return x;
57648
+ };
57649
+ return JSON.stringify(walk2(v) ?? null);
57650
+ }
57651
+ var hashOf = (v) => (0, import_node_crypto9.createHash)("sha256").update(canonicalJson(v)).digest("hex");
57652
+
57653
+ // revision-staging-store.ts
57621
57654
  function root2() {
57622
57655
  return process.env.FLOLESS_HOME ?? (0, import_node_path19.join)((0, import_node_os14.homedir)(), ".floless");
57623
57656
  }
@@ -57630,12 +57663,56 @@ var safeStagingKey = (v) => {
57630
57663
  return v;
57631
57664
  };
57632
57665
  var stagingDir = (key) => (0, import_node_path19.join)(stagingRoot(), safeStagingKey(key));
57666
+ var metaPath = (stagingKey) => (0, import_node_path19.join)(stagingDir(stagingKey), "staged.json");
57667
+ var docPath = (stagingKey) => (0, import_node_path19.join)(stagingDir(stagingKey), "candidate.json");
57668
+ function stageCandidate(stagingKey, candidate, meta) {
57669
+ const dir = stagingDir(stagingKey);
57670
+ (0, import_node_fs21.mkdirSync)(dir, { recursive: true });
57671
+ const bytes = JSON.stringify(candidate ?? null);
57672
+ const record2 = { stageId: (0, import_node_crypto10.randomUUID)(), ...meta, candidateHash: hashOf(candidate ?? null) };
57673
+ (0, import_node_fs21.writeFileSync)(docPath(stagingKey), bytes);
57674
+ (0, import_node_fs21.writeFileSync)(metaPath(stagingKey), JSON.stringify(record2, null, 2));
57675
+ return record2;
57676
+ }
57677
+ function readStaged(stagingKey) {
57678
+ const record2 = readStagedRecord(stagingKey);
57679
+ if (!record2) return null;
57680
+ if (!(0, import_node_fs21.existsSync)(docPath(stagingKey))) return null;
57681
+ const candidate = readStagedCandidate(stagingKey);
57682
+ if (hashOf(candidate ?? null) !== record2.candidateHash) return null;
57683
+ return { record: record2, candidate };
57684
+ }
57685
+ function readStagedRecord(stagingKey) {
57686
+ try {
57687
+ if (!(0, import_node_fs21.existsSync)(metaPath(stagingKey))) return null;
57688
+ const r = JSON.parse((0, import_node_fs21.readFileSync)(metaPath(stagingKey), "utf8"));
57689
+ return typeof r?.stageId === "string" && typeof r?.requestId === "string" ? r : null;
57690
+ } catch {
57691
+ return null;
57692
+ }
57693
+ }
57694
+ function readStagedCandidate(stagingKey) {
57695
+ try {
57696
+ if (!(0, import_node_fs21.existsSync)(docPath(stagingKey))) return null;
57697
+ return JSON.parse((0, import_node_fs21.readFileSync)(docPath(stagingKey), "utf8"));
57698
+ } catch {
57699
+ return null;
57700
+ }
57701
+ }
57633
57702
  function dropStagingFor(stagingKey) {
57634
57703
  try {
57635
57704
  (0, import_node_fs21.rmSync)(stagingDir(stagingKey), { recursive: true, force: true });
57636
57705
  } catch {
57637
57706
  }
57638
57707
  }
57708
+ function listStagedKeys() {
57709
+ try {
57710
+ if (!(0, import_node_fs21.existsSync)(stagingRoot())) return [];
57711
+ return (0, import_node_fs21.readdirSync)(stagingRoot()).filter((d) => STAGING_KEY.test(d));
57712
+ } catch {
57713
+ return [];
57714
+ }
57715
+ }
57639
57716
 
57640
57717
  // projects-store.ts
57641
57718
  var ProjectError = class extends Error {
@@ -57673,7 +57750,7 @@ function projectDir(id) {
57673
57750
  function archiveDir(id) {
57674
57751
  return (0, import_node_path20.join)(archiveRoot(), safeProjectId(id));
57675
57752
  }
57676
- function mintProjectId(name, draw = () => (0, import_node_crypto9.randomBytes)(3).toString("hex")) {
57753
+ function mintProjectId(name, draw = () => (0, import_node_crypto11.randomBytes)(3).toString("hex")) {
57677
57754
  let id = `${slugify(name)}-${draw()}`;
57678
57755
  while ((0, import_node_fs22.existsSync)(projectDir(id)) || (0, import_node_fs22.existsSync)(archiveDir(id))) id = `${slugify(name)}-${draw()}`;
57679
57756
  return id;
@@ -57684,7 +57761,7 @@ function projectExportsDir(id) {
57684
57761
  function projectKnowledgeDir(id) {
57685
57762
  return (0, import_node_path20.join)(projectDir(id), "knowledge");
57686
57763
  }
57687
- var metaPath = (id) => (0, import_node_path20.join)(projectDir(id), "project.json");
57764
+ var metaPath2 = (id) => (0, import_node_path20.join)(projectDir(id), "project.json");
57688
57765
  function readMetaFile(jsonPath, id) {
57689
57766
  if (!(0, import_node_fs22.existsSync)(jsonPath)) return null;
57690
57767
  try {
@@ -57698,11 +57775,11 @@ function readMetaFile(jsonPath, id) {
57698
57775
  }
57699
57776
  }
57700
57777
  function readMeta(id) {
57701
- return readMetaFile(metaPath(id), id);
57778
+ return readMetaFile(metaPath2(id), id);
57702
57779
  }
57703
57780
  function writeMetaTo(dir, meta) {
57704
57781
  const path = (0, import_node_path20.join)(dir, "project.json");
57705
- const tmp = `${path}.${process.pid}.${(0, import_node_crypto9.randomUUID)()}.tmp`;
57782
+ const tmp = `${path}.${process.pid}.${(0, import_node_crypto11.randomUUID)()}.tmp`;
57706
57783
  (0, import_node_fs22.writeFileSync)(tmp, JSON.stringify(meta, null, 2));
57707
57784
  (0, import_node_fs22.renameSync)(tmp, path);
57708
57785
  }
@@ -57725,11 +57802,25 @@ async function getOrCreateProjectExportSourceId(id) {
57725
57802
  const meta = readMeta(id);
57726
57803
  if (!meta) throw new ProjectError(`unknown project: ${id}`);
57727
57804
  if (typeof meta.exportSourceId === "string" && meta.exportSourceId.trim()) return meta.exportSourceId;
57728
- const exportSourceId = (0, import_node_crypto9.randomUUID)();
57805
+ const exportSourceId = (0, import_node_crypto11.randomUUID)();
57729
57806
  writeMeta({ ...meta, exportSourceId });
57730
57807
  return exportSourceId;
57731
57808
  });
57732
57809
  }
57810
+ function getProjectStagingId(id) {
57811
+ const meta = readMeta(id);
57812
+ return typeof meta?.stagingId === "string" && meta.stagingId.trim() ? meta.stagingId : void 0;
57813
+ }
57814
+ async function getOrCreateProjectStagingId(id) {
57815
+ return withLifecycleLock("project", safeProjectId(id), () => {
57816
+ const meta = readMeta(id);
57817
+ if (!meta) throw new ProjectError(`unknown project: ${id}`);
57818
+ if (typeof meta.stagingId === "string" && meta.stagingId.trim()) return meta.stagingId;
57819
+ const stagingId = (0, import_node_crypto11.randomUUID)();
57820
+ writeMeta({ ...meta, stagingId });
57821
+ return stagingId;
57822
+ });
57823
+ }
57733
57824
  function createProject(input) {
57734
57825
  const name = typeof input.name === "string" ? input.name.trim() : "";
57735
57826
  const app = typeof input.app === "string" ? input.app.trim() : "";
@@ -57738,7 +57829,7 @@ function createProject(input) {
57738
57829
  const id = mintProjectId(name);
57739
57830
  (0, import_node_fs22.mkdirSync)(projectDir(id), { recursive: true });
57740
57831
  const now = (/* @__PURE__ */ new Date()).toISOString();
57741
- const meta = { id, uuid: (0, import_node_crypto9.randomUUID)(), name, app, createdAt: now, updatedAt: now };
57832
+ const meta = { id, uuid: (0, import_node_crypto11.randomUUID)(), name, app, createdAt: now, updatedAt: now };
57742
57833
  writeMeta(meta);
57743
57834
  return meta;
57744
57835
  }
@@ -57989,7 +58080,7 @@ function importProjectZip(data) {
57989
58080
  const now = (/* @__PURE__ */ new Date()).toISOString();
57990
58081
  const meta = {
57991
58082
  id,
57992
- uuid: (0, import_node_crypto9.randomUUID)(),
58083
+ uuid: (0, import_node_crypto11.randomUUID)(),
57993
58084
  name,
57994
58085
  app,
57995
58086
  createdAt: now,
@@ -58039,7 +58130,7 @@ function loadLog(id) {
58039
58130
  function dehydrate(node, blobs) {
58040
58131
  if (typeof node === "string") {
58041
58132
  if (node.length > BLOB_MIN) {
58042
- const hash2 = (0, import_node_crypto10.createHash)("sha256").update(node).digest("hex");
58133
+ const hash2 = (0, import_node_crypto12.createHash)("sha256").update(node).digest("hex");
58043
58134
  blobs.set(hash2, node);
58044
58135
  return { [BLOB_KEY]: hash2 };
58045
58136
  }
@@ -58167,7 +58258,7 @@ async function readVersionSkeletonAsync(id, n) {
58167
58258
  }
58168
58259
 
58169
58260
  // project-contract-hash.ts
58170
- var import_node_crypto11 = require("node:crypto");
58261
+ var import_node_crypto13 = require("node:crypto");
58171
58262
  function stableJson(value) {
58172
58263
  if (value === null || typeof value !== "object") return JSON.stringify(value);
58173
58264
  if (Array.isArray(value)) return `[${value.map((v) => stableJson(v)).join(",")}]`;
@@ -58175,7 +58266,7 @@ function stableJson(value) {
58175
58266
  return `{${Object.keys(obj2).sort().map((k) => `${JSON.stringify(k)}:${stableJson(obj2[k])}`).join(",")}}`;
58176
58267
  }
58177
58268
  function contractHash(contract) {
58178
- return (0, import_node_crypto11.createHash)("sha256").update(stableJson(contract)).digest("hex");
58269
+ return (0, import_node_crypto13.createHash)("sha256").update(stableJson(contract)).digest("hex");
58179
58270
  }
58180
58271
 
58181
58272
  // contract-gateway.ts
@@ -58364,7 +58455,7 @@ function clientCount() {
58364
58455
  }
58365
58456
 
58366
58457
  // knowledge-store.ts
58367
- var import_node_crypto12 = require("node:crypto");
58458
+ var import_node_crypto14 = require("node:crypto");
58368
58459
  var import_node_fs24 = require("node:fs");
58369
58460
  var import_node_path22 = require("node:path");
58370
58461
  var import_yaml6 = __toESM(require_dist6(), 1);
@@ -58414,7 +58505,7 @@ function writeManifest(id, manifest) {
58414
58505
  const dir = projectKnowledgeDir(id);
58415
58506
  (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
58416
58507
  const dest = manifestPath(id);
58417
- const tmp = (0, import_node_path22.join)(dir, `.manifest.json.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`);
58508
+ const tmp = (0, import_node_path22.join)(dir, `.manifest.json.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`);
58418
58509
  (0, import_node_fs24.writeFileSync)(tmp, JSON.stringify(manifest, null, 2));
58419
58510
  (0, import_node_fs24.renameSync)(tmp, dest);
58420
58511
  }
@@ -58491,19 +58582,19 @@ function decodeUpload(inputs) {
58491
58582
  }
58492
58583
  function addSource(id, input) {
58493
58584
  const { buf, mime, filename } = input;
58494
- const sha2563 = (0, import_node_crypto12.createHash)("sha256").update(buf).digest("hex");
58585
+ const sha2563 = (0, import_node_crypto14.createHash)("sha256").update(buf).digest("hex");
58495
58586
  const dir = blobsDir(id);
58496
58587
  (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
58497
58588
  const blobPath = blobPathFor(id, sha2563);
58498
58589
  if (!(0, import_node_fs24.existsSync)(blobPath)) {
58499
- const tmp = `${blobPath}.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`;
58590
+ const tmp = `${blobPath}.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`;
58500
58591
  (0, import_node_fs24.writeFileSync)(tmp, buf);
58501
58592
  (0, import_node_fs24.renameSync)(tmp, blobPath);
58502
58593
  }
58503
58594
  const manifest = readManifest(id);
58504
58595
  const now = (/* @__PURE__ */ new Date()).toISOString();
58505
58596
  const row = {
58506
- sourceId: (0, import_node_crypto12.randomUUID)(),
58597
+ sourceId: (0, import_node_crypto14.randomUUID)(),
58507
58598
  blobSha256: sha2563,
58508
58599
  kind: "file",
58509
58600
  filename,
@@ -58553,7 +58644,7 @@ function writeLockFile(id, lock) {
58553
58644
  const dir = projectKnowledgeDir(id);
58554
58645
  (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
58555
58646
  const dest = lockPath(id);
58556
- const tmp = (0, import_node_path22.join)(dir, `.lock.json.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`);
58647
+ const tmp = (0, import_node_path22.join)(dir, `.lock.json.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`);
58557
58648
  (0, import_node_fs24.writeFileSync)(tmp, JSON.stringify(lock, null, 2));
58558
58649
  (0, import_node_fs24.renameSync)(tmp, dest);
58559
58650
  }
@@ -58614,7 +58705,7 @@ function assertGenerationId(generationId) {
58614
58705
  }
58615
58706
  }
58616
58707
  function mintGenerationId() {
58617
- return (0, import_node_crypto12.randomUUID)();
58708
+ return (0, import_node_crypto14.randomUUID)();
58618
58709
  }
58619
58710
  function generationWikiDir(id, generationId) {
58620
58711
  assertGenerationId(generationId);
@@ -58627,7 +58718,7 @@ function publishGeneration(id, generationId) {
58627
58718
  const dir = vaultDir(id);
58628
58719
  (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
58629
58720
  const dest = currentGenerationPath(id);
58630
- const tmp = (0, import_node_path22.join)(dir, `.current-generation.json.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`);
58721
+ const tmp = (0, import_node_path22.join)(dir, `.current-generation.json.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`);
58631
58722
  (0, import_node_fs24.writeFileSync)(tmp, JSON.stringify(pointer, null, 2));
58632
58723
  (0, import_node_fs24.renameSync)(tmp, dest);
58633
58724
  const manifest = readManifest(id);
@@ -58967,7 +59058,7 @@ function writeOrganizeFile(id, org) {
58967
59058
  const dir = projectKnowledgeDir(id);
58968
59059
  (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
58969
59060
  const dest = organizePath(id);
58970
- const tmp = (0, import_node_path22.join)(dir, `.organize.json.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`);
59061
+ const tmp = (0, import_node_path22.join)(dir, `.organize.json.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`);
58971
59062
  (0, import_node_fs24.writeFileSync)(tmp, JSON.stringify(org, null, 2));
58972
59063
  (0, import_node_fs24.renameSync)(tmp, dest);
58973
59064
  }
@@ -59379,8 +59470,669 @@ function registerKnowledgeRoutes(app) {
59379
59470
  );
59380
59471
  }
59381
59472
 
59473
+ // steel-revision-registry.ts
59474
+ var IGNORED_INPUT = /* @__PURE__ */ new Set([
59475
+ "$.read_notes",
59476
+ "$.plans[].read_notes"
59477
+ ]);
59478
+ var registryKeyOf = (reportedPath) => reportedPath.replace(/\[[^\]]*\]/g, "[]");
59479
+ var REGISTRY = /* @__PURE__ */ new Map([
59480
+ // ── canonical members ────────────────────────────────────────────────────────
59481
+ ["$.members[]", { disposition: "propose", note: "a canonical member" }],
59482
+ // The MATCH KEY. Members are paired by id before diffing, so this can never differ within a pair;
59483
+ // it is listed so the coverage test sees a decision rather than an omission.
59484
+ ["$.members[].id", { disposition: "issue", note: "the member identity, which pairs the documents \u2014 a change to it is an add plus a remove, not an edit" }],
59485
+ // Identity, geometry, engineering. `GUARDED_FIELDS` plus from/to/section, unchanged in meaning.
59486
+ ["$.members[].profile", { disposition: "propose" }],
59487
+ ["$.members[].material", { disposition: "propose" }],
59488
+ ["$.members[].role", { disposition: "propose" }],
59489
+ ["$.members[].memberType", { disposition: "propose" }],
59490
+ ["$.members[].rot", { disposition: "propose" }],
59491
+ ["$.members[].position", { disposition: "propose" }],
59492
+ ["$.members[].from", { disposition: "propose" }],
59493
+ ["$.members[].to", { disposition: "propose" }],
59494
+ ["$.members[].section", { disposition: "propose" }],
59495
+ // P4a MEASURED these as the unenumerated set — real fields on real members that the flat list neither
59496
+ // permitted nor refused. They simply lost. This is the hole the registry exists to close.
59497
+ ["$.members[].bf", { disposition: "propose", absenceEquivalent: false }],
59498
+ ["$.members[].rfi", { disposition: "propose", absenceEquivalent: false }],
59499
+ ["$.members[].mf", { disposition: "propose", absenceEquivalent: false }],
59500
+ ["$.members[].brace", { disposition: "propose" }],
59501
+ // An AUTHORITY claim, and `propose` rather than `issue` DELIBERATELY — see the note below the table.
59502
+ ["$.members[].verified", { disposition: "propose", absenceEquivalent: false }],
59503
+ // Server-stamped at apply time; the AI may not supply either. `$.members[].provenance` is an ENUM
59504
+ // (`read | revision-read | manual | migrated`), not request metadata — see the design §6.1.
59505
+ ["$.members[].source", { disposition: "issue", note: "how the member was created is recorded by whatever created it, not by a revision read" }],
59506
+ ["$.members[].provenance", { disposition: "issue", note: "how a member came to exist is stamped by the server, not asserted by the document" }],
59507
+ // ── member ends ──────────────────────────────────────────────────────────────
59508
+ // The one member property the classifier walks INTO rather than comparing whole, because its keys
59509
+ // carry different authority: `conn` is engineering intent, `connVerified` is a human's confirmation.
59510
+ ["$.members[].ends", { disposition: "propose", descend: true, note: "per-end connection metadata" }],
59511
+ ["$.members[].ends[]", { disposition: "propose", descend: true }],
59512
+ ["$.members[].ends[].conn", { disposition: "propose" }],
59513
+ ["$.members[].ends[].note", { disposition: "propose" }],
59514
+ ["$.members[].ends[].detail", { disposition: "propose" }],
59515
+ ["$.members[].ends[].connVerified", { disposition: "propose", absenceEquivalent: false }],
59516
+ // ── plans (sheets) ───────────────────────────────────────────────────────────
59517
+ // P4c-3 REFUSED every field on an existing sheet and said so in its own comment: plan-level revision
59518
+ // belonged to P6's stage -> review -> confirm rewrite, so inventing a plan-proposal shape a PR early
59519
+ // would have meant redesigning it a PR later. This is that PR (P6b), and these are the entries that
59520
+ // turn "refused, but at least surfaced" into "proposed, so a human can take it".
59521
+ //
59522
+ // The permitted set is the parent plan's (§4.3) and NOT one field wider: *"plan `elevation_in`/datum/
59523
+ // control/title; `memberRefs`"*. Everything else on a plan gets an EXPLICIT `issue` entry rather than
59524
+ // being left to the default — not because the default is wrong, but because the coverage test then
59525
+ // reads a decision instead of an omission, and a reviewer can see that each refusal was chosen.
59526
+ // No `descend`, matching `$.members[]` — and that symmetry is the measured answer, not a guess. The
59527
+ // first cut marked this `descend: true` on the assumption the coverage walk needed it to demand an
59528
+ // entry per plan field. A mutation deleting the flag left the whole suite green: the walk
59529
+ // short-circuits on "this path's parent IS the root", so `descend` is never consulted for a direct
59530
+ // child, and no plan property is a composite the classifier walks INTO (unlike `ends`). An inert flag
59531
+ // that reads as load-bearing is worse than no flag.
59532
+ ["$.plans[]", { disposition: "propose", note: "a sheet" }],
59533
+ // The MATCH KEY, exactly like `$.members[].id`: plans are paired by sheet before diffing, so this can
59534
+ // never differ within a pair. Listed so the coverage test sees a decision.
59535
+ ["$.plans[].sheet", { disposition: "issue", note: "the sheet name, which pairs the documents \u2014 a change to it is an add plus a remove, not an edit" }],
59536
+ // The canonical registration a revision read may genuinely move: where the cut plane sits, which grid
59537
+ // intersection anchors the sheet, what it is called, and which members it presents.
59538
+ ["$.plans[].title", { disposition: "propose" }],
59539
+ ["$.plans[].elevation_in", { disposition: "propose" }],
59540
+ ["$.plans[].datum_at", { disposition: "propose" }],
59541
+ ["$.plans[].datum_ref", { disposition: "propose" }],
59542
+ ["$.plans[].control2_at", { disposition: "propose" }],
59543
+ ["$.plans[].control2_ref", { disposition: "propose" }],
59544
+ ["$.plans[].memberRefs", { disposition: "propose" }],
59545
+ // Drawing evidence. Write-once by §5.2 — a re-read mints new evidence, it does not edit the old trace
59546
+ // in place — so a revision read changing what the source looked like is a defect, not a proposal.
59547
+ ["$.plans[].raster_b64", { disposition: "issue", note: "the page image is the evidence a read was made against; a later read attaches its own rather than rewriting it" }],
59548
+ ["$.plans[].segments", { disposition: "issue", note: "the traced linework is evidence, and evidence is written once" }],
59549
+ ["$.plans[].labels", { disposition: "issue", note: "the text read off the sheet is evidence, and evidence is written once" }],
59550
+ ["$.plans[].clip", { disposition: "issue", note: "the crop applied to the source page belongs to the read that made it" }],
59551
+ // Authored by a HUMAN in the editor, and a revision read has no view on any of it.
59552
+ ["$.plans[].details", { disposition: "issue", note: "placed details are authored in the editor, not read off the drawing" }],
59553
+ ["$.plans[].callouts", { disposition: "issue", note: "detail callouts are authored in the editor" }],
59554
+ ["$.plans[].tos_callouts", { disposition: "issue", note: "top-of-steel callouts are authored in the editor" }],
59555
+ ["$.plans[].dims", { disposition: "issue", note: "dimensions are drawn by the user" }],
59556
+ // Derived by the server or by the editor's own passes — asserting them from a document would let an AI
59557
+ // claim work it did not do.
59558
+ ["$.plans[].autofilled", { disposition: "issue", note: "whether a pass filled this sheet in is recorded by that pass" }],
59559
+ ["$.plans[].deduped", { disposition: "issue", note: "whether duplicates were resolved is recorded by the pass that resolved them" }],
59560
+ // `pt_per_ft` and `frame` are the sheet->world registration. Deliberately NOT proposed, and this is a
59561
+ // judgement worth stating: changing either silently rescales or re-registers every work point on the
59562
+ // sheet, so the effect is nothing like the per-field edits above — it is a transform of all of them.
59563
+ // The parent's permitted list does not include them, and a PR whose subject is "let plans be revised"
59564
+ // is the wrong place to widen the list beyond what was authorised. Refused AND surfaced, so a real
59565
+ // scale correction is visible to the user rather than lost.
59566
+ ["$.plans[].pt_per_ft", { disposition: "issue", note: "the sheet scale re-projects every work point on the plan, so it is not a field-level revision" }],
59567
+ ["$.plans[].frame", { disposition: "issue", note: "the sheet-to-world registration re-places everything on the plan, so it is not a field-level revision" }],
59568
+ // Evidence, and the ONE plan property the classifier does not diff here at all: observations run
59569
+ // through their own three-pass admissibility path, which is where they are actually decided. `auto`
59570
+ // names the path a CLEAN new trace takes; measured, an incoming observation can equally land in
59571
+ // `issues` (a dozen codes across those passes) or in `bindingProposals`, and one omitted from an
59572
+ // existing sheet produces nothing at all. So this entry describes the dominant route, not a promise
59573
+ // about every observation — the first draft of this note said "that is what actually happens to
59574
+ // them", which is the happy path stated as the whole truth.
59575
+ //
59576
+ // The entry is INERT at runtime and exists to satisfy the plan coverage test: the classifier
59577
+ // `continue`s on this key before `entryFor` is ever called, and that `continue` is the load-bearing
59578
+ // line (removing it fails 19 tests, while changing this disposition fails none). Not `descend`, so
59579
+ // the coverage test does not demand an entry per observation field.
59580
+ ["$.plans[].memberObservations", { disposition: "auto", note: "drawing evidence, classified per observation rather than as a plan field" }]
59581
+ ]);
59582
+ function entryFor(registryKey, registry2 = REGISTRY) {
59583
+ const isAncestor = (key) => key !== registryKey && (registryKey.startsWith(key + ".") || registryKey.startsWith(key + "["));
59584
+ for (const [key, entry2] of registry2) {
59585
+ if (isAncestor(key) && entry2.disposition === "issue") return entry2;
59586
+ }
59587
+ return registry2.get(registryKey);
59588
+ }
59589
+ function valuesDiffer(before, after, entry2) {
59590
+ const fold = (v) => v === void 0 || v === null || entry2?.absenceEquivalent !== void 0 && v === entry2.absenceEquivalent ? null : v;
59591
+ const fa = fold(before), fb = fold(after);
59592
+ const rawA = JSON.stringify(fa), rawB = JSON.stringify(fb);
59593
+ if (rawA === rawB) return false;
59594
+ return canonicalJson(fa) !== canonicalJson(fb);
59595
+ }
59596
+
59597
+ // steel-model-revision.ts
59598
+ var SELECT_NOTHING = Object.freeze({
59599
+ proposals: Object.freeze([]),
59600
+ bindingProposals: Object.freeze([])
59601
+ });
59602
+ function assertsVerification(u) {
59603
+ if (u.to.status !== "active") return false;
59604
+ return claimDiffers(u.from.verified, u.to.verified);
59605
+ }
59606
+ var json = canonicalJson;
59607
+ var claimed = (v) => v === true;
59608
+ function claimDiffers(a, b) {
59609
+ const odd = (v) => v !== void 0 && typeof v !== "boolean";
59610
+ if (odd(a) || odd(b)) return true;
59611
+ return claimed(a) !== claimed(b);
59612
+ }
59613
+ function observationsOf(doc) {
59614
+ const out = /* @__PURE__ */ new Map();
59615
+ for (const plan of doc.plans ?? []) {
59616
+ for (const obs of plan.memberObservations ?? []) {
59617
+ if (!out.has(obs.id)) out.set(obs.id, { obs, sheet: plan.sheet });
59618
+ }
59619
+ }
59620
+ return out;
59621
+ }
59622
+ function transitionKind(from, to) {
59623
+ const a = from.status, b = to.status;
59624
+ if (a === "active" && b === "archived") return "archive";
59625
+ if (a === "active" && b === "superseded") return "supersede";
59626
+ if (a !== b) return null;
59627
+ const before = from.memberIds ?? [], after = to.memberIds ?? [];
59628
+ if (json(before) !== json(after)) {
59629
+ return after.length > before.length ? "split" : "rebind";
59630
+ }
59631
+ if (from.verified !== to.verified) return "verify";
59632
+ return null;
59633
+ }
59634
+ function withoutForgedVerification(obs, bindingProposals) {
59635
+ const binding = obs.binding;
59636
+ if (!binding || binding.status !== "active" || binding.verified !== true) return obs;
59637
+ const stripped = { ...binding };
59638
+ delete stripped.verified;
59639
+ bindingProposals.push({ observationId: obs.id, kind: "verify", from: structuredClone(stripped), to: structuredClone(binding) });
59640
+ return { ...obs, binding: stripped };
59641
+ }
59642
+ function withoutMemberClaims(m) {
59643
+ const endClaimed = (m.ends ?? []).some((e) => e && claimed(e.connVerified));
59644
+ if (!claimed(m.verified) && !endClaimed) return m;
59645
+ const { verified: _v2, ...rest } = m;
59646
+ return {
59647
+ ...rest,
59648
+ ...m.ends ? { ends: m.ends.map((e) => {
59649
+ const { connVerified: _c, ...er } = e ?? {};
59650
+ return er;
59651
+ }) } : {}
59652
+ };
59653
+ }
59654
+ function stageRevisionRead(current, incoming) {
59655
+ const accepted = [];
59656
+ const bindingUpdates = [];
59657
+ const bindingProposals = [];
59658
+ const proposals = [];
59659
+ const issues = [];
59660
+ const add = (path, code, message) => issues.push({ path, code, message });
59661
+ const curObs = observationsOf(current);
59662
+ const incMembers = new Map((incoming.members ?? []).map((m) => [m.id, m]));
59663
+ const curMembers = new Map((current.members ?? []).map((m) => [m.id, m]));
59664
+ const currentSheets = new Set((current.plans ?? []).map((p) => p.sheet));
59665
+ const ownIssues = /* @__PURE__ */ new Map();
59666
+ const order = [];
59667
+ const seenIncoming = /* @__PURE__ */ new Set();
59668
+ for (const plan of incoming.plans ?? []) {
59669
+ for (const obs of plan.memberObservations ?? []) {
59670
+ const path = `$.plans[${plan.sheet}].memberObservations[${obs.id}]`;
59671
+ const mine = [];
59672
+ const bad = (p, code, message) => mine.push({ path: p, code, message });
59673
+ if (seenIncoming.has(obs.id)) {
59674
+ bad(path, "observation-id-duplicate", `observation id "${obs.id}" occurs more than once in the incoming read`);
59675
+ }
59676
+ seenIncoming.add(obs.id);
59677
+ const citedSheet = obs.evidence?.source?.sheet;
59678
+ if (citedSheet === void 0) {
59679
+ bad(`${path}.evidence.source.sheet`, "observation-sheet-missing", "evidence names no source sheet, so it cannot be filed against a plan");
59680
+ } else if (citedSheet !== plan.sheet) {
59681
+ bad(`${path}.evidence.source.sheet`, "observation-sheet-mismatch", `evidence cites sheet "${citedSheet}" but lives on plan "${plan.sheet}"`);
59682
+ } else if (!currentSheets.has(plan.sheet)) {
59683
+ bad(`${path}.evidence.source.sheet`, "observation-depends-on-proposal", `sheet "${plan.sheet}" does not exist yet; its evidence cannot be accepted until the plan is confirmed`);
59684
+ }
59685
+ for (const id of obs.binding?.memberIds ?? []) {
59686
+ if (curMembers.has(id)) continue;
59687
+ if (incMembers.has(id)) {
59688
+ bad(`${path}.binding.memberIds`, "observation-depends-on-proposal", `"${id}" is a proposed new member; its evidence cannot be accepted until that member is confirmed`);
59689
+ } else {
59690
+ bad(`${path}.binding.memberIds`, "observation-member-unresolved", `"${id}" does not name a member`);
59691
+ }
59692
+ }
59693
+ ownIssues.set(obs.id, mine);
59694
+ order.push({ plan, obs, path });
59695
+ }
59696
+ }
59697
+ const admissible = new Set([...ownIssues].filter(([, v]) => v.length === 0).map(([k]) => k));
59698
+ const landing = [];
59699
+ const pendingUpdates = [];
59700
+ for (const { obs, path } of order) {
59701
+ const mine = ownIssues.get(obs.id) ?? [];
59702
+ issues.push(...mine);
59703
+ if (mine.length) continue;
59704
+ let rejected = false;
59705
+ for (const target of obs.evidence?.supersedes ?? []) {
59706
+ if (!curObs.has(target) && !admissible.has(target)) {
59707
+ add(`${path}.evidence.supersedes`, "supersedes-unresolved", `"${target}" does not name an observation that will exist after this read`);
59708
+ rejected = true;
59709
+ }
59710
+ }
59711
+ if (rejected) continue;
59712
+ const existing = curObs.get(obs.id);
59713
+ if (!existing) {
59714
+ landing.push({ obs, path });
59715
+ continue;
59716
+ }
59717
+ if (json(existing.obs.evidence) !== json(obs.evidence)) {
59718
+ add(`${path}.evidence`, "evidence-mutated", `observation "${obs.id}" already exists and its evidence differs; a re-read must mint a new observation carrying \`supersedes\` rather than edit immutable evidence in place`);
59719
+ continue;
59720
+ }
59721
+ const sameBinding = (a, b) => !claimDiffers(a.verified, b.verified) && json({ memberIds: a.memberIds ?? [], status: a.status }) === json({ memberIds: b.memberIds ?? [], status: b.status });
59722
+ if (sameBinding(existing.obs.binding, obs.binding)) continue;
59723
+ const kind = transitionKind(existing.obs.binding, obs.binding);
59724
+ if (kind === null) {
59725
+ add(`${path}.binding`, "binding-transition-illegal", `"${existing.obs.binding.status}" -> "${obs.binding.status}" is not a permitted binding transition`);
59726
+ continue;
59727
+ }
59728
+ pendingUpdates.push({ obs, path, kind, from: existing.obs.binding });
59729
+ }
59730
+ const candidates = new Map(landing.map((l) => [l.obs.id, l]));
59731
+ const supersedesOf = (obs) => obs.evidence?.supersedes ?? [];
59732
+ const orphanedBy = /* @__PURE__ */ new Map();
59733
+ for (; ; ) {
59734
+ const authorized = /* @__PURE__ */ new Set();
59735
+ for (const { obs } of candidates.values()) for (const t of supersedesOf(obs)) authorized.add(t);
59736
+ const retiring = /* @__PURE__ */ new Set();
59737
+ for (const p of pendingUpdates) if (p.kind === "supersede" && authorized.has(p.obs.id)) retiring.add(p.obs.id);
59738
+ const willBeSuperseded = (t) => retiring.has(t) || candidates.get(t)?.obs.binding?.status === "superseded" || curObs.get(t)?.obs.binding.status === "superseded";
59739
+ const drop = [];
59740
+ for (const entry2 of candidates.values()) {
59741
+ const orphaned = supersedesOf(entry2.obs).filter((t) => !willBeSuperseded(t));
59742
+ if (orphaned.length) {
59743
+ orphanedBy.set(entry2.obs.id, orphaned);
59744
+ drop.push(entry2);
59745
+ }
59746
+ }
59747
+ if (!drop.length) break;
59748
+ for (const d of drop) candidates.delete(d.obs.id);
59749
+ }
59750
+ {
59751
+ const WHITE = 0, GREY = 1, BLACK = 2;
59752
+ const colour = /* @__PURE__ */ new Map();
59753
+ const inCycle = /* @__PURE__ */ new Set();
59754
+ for (const root4 of candidates.keys()) {
59755
+ if ((colour.get(root4) ?? WHITE) !== WHITE) continue;
59756
+ const stack = [{ id: root4, edges: [...supersedesOf(candidates.get(root4).obs)], i: 0 }];
59757
+ colour.set(root4, GREY);
59758
+ while (stack.length) {
59759
+ const top = stack[stack.length - 1];
59760
+ if (top.i >= top.edges.length) {
59761
+ colour.set(top.id, BLACK);
59762
+ stack.pop();
59763
+ continue;
59764
+ }
59765
+ const next = top.edges[top.i++];
59766
+ if (!candidates.has(next)) continue;
59767
+ const state2 = colour.get(next) ?? WHITE;
59768
+ if (state2 === GREY) {
59769
+ for (const f of stack) inCycle.add(f.id);
59770
+ inCycle.add(next);
59771
+ continue;
59772
+ }
59773
+ if (state2 === BLACK) continue;
59774
+ colour.set(next, GREY);
59775
+ stack.push({ id: next, edges: [...supersedesOf(candidates.get(next).obs)], i: 0 });
59776
+ }
59777
+ }
59778
+ for (const id of inCycle) {
59779
+ const entry2 = candidates.get(id);
59780
+ if (!entry2) continue;
59781
+ add(`${entry2.path}.evidence.supersedes`, "supersedes-cycle", `observation "${id}" is part of a supersedes cycle; a lineage must be a DAG or "which evidence is current" has no answer`);
59782
+ candidates.delete(id);
59783
+ }
59784
+ }
59785
+ for (const { obs, path } of landing) {
59786
+ if (candidates.has(obs.id)) {
59787
+ accepted.push(withoutForgedVerification(obs, bindingProposals));
59788
+ continue;
59789
+ }
59790
+ const orphaned = orphanedBy.get(obs.id);
59791
+ if (orphaned) {
59792
+ add(`${path}.evidence.supersedes`, "supersedes-status", `"${obs.id}" supersedes ${orphaned.map((t) => `"${t}"`).join(", ")}, but that observation will still be active after this read; a replacement and the retirement it justifies stand or fall together`);
59793
+ }
59794
+ }
59795
+ const finalAuthorized = /* @__PURE__ */ new Set();
59796
+ for (const { obs } of candidates.values()) for (const t of supersedesOf(obs)) finalAuthorized.add(t);
59797
+ for (const p of pendingUpdates) {
59798
+ if (p.kind === "supersede" && !finalAuthorized.has(p.obs.id)) {
59799
+ add(`${p.path}.binding.status`, "supersede-without-replacement", `observation "${p.obs.id}" is being superseded but no acceptable incoming observation names it in \`evidence.supersedes\`; superseding without a replacement removes evidence from scoring with nothing put in its place`);
59800
+ continue;
59801
+ }
59802
+ const update = {
59803
+ observationId: p.obs.id,
59804
+ kind: p.kind,
59805
+ from: structuredClone(p.from),
59806
+ to: structuredClone(p.obs.binding)
59807
+ };
59808
+ (assertsVerification(update) ? bindingProposals : bindingUpdates).push(update);
59809
+ }
59810
+ for (const [id, m] of incMembers) {
59811
+ const before = curMembers.get(id);
59812
+ if (!before) {
59813
+ proposals.push({ kind: "member-added", memberId: id, member: withoutMemberClaims(m) });
59814
+ continue;
59815
+ }
59816
+ const fields = [];
59817
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(m)])) {
59818
+ if (key === "ends") continue;
59819
+ const b = before[key];
59820
+ const a = m[key];
59821
+ const entry2 = entryFor(`$.members[].${key}`);
59822
+ if (!valuesDiffer(b, a, entry2)) continue;
59823
+ if (entry2?.disposition === "propose") fields.push({ key, before: b, after: a });
59824
+ else {
59825
+ add(
59826
+ `$.members[${id}].${key}`,
59827
+ "path-refused",
59828
+ `"${key}" may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
59829
+ );
59830
+ }
59831
+ }
59832
+ const beEnds = Array.isArray(before.ends) ? before.ends : [];
59833
+ const aeEnds = Array.isArray(m.ends) ? m.ends : [];
59834
+ if (before.ends !== void 0 && !Array.isArray(before.ends) || m.ends !== void 0 && !Array.isArray(m.ends)) {
59835
+ if (valuesDiffer(before.ends, m.ends)) {
59836
+ add(
59837
+ `$.members[${id}].ends`,
59838
+ "path-refused",
59839
+ '"ends" must be an array of per-end metadata; a revision read may not replace it with something else'
59840
+ );
59841
+ }
59842
+ }
59843
+ for (let i = 0; i < Math.max(beEnds.length, aeEnds.length); i++) {
59844
+ const be = beEnds[i] ?? {};
59845
+ const ae = aeEnds[i] ?? {};
59846
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(be), ...Object.keys(ae)])) {
59847
+ const entry2 = entryFor(`$.members[].ends[].${key}`);
59848
+ if (!valuesDiffer(be[key], ae[key], entry2)) continue;
59849
+ if (entry2?.disposition === "propose") fields.push({ key: `ends[${i}].${key}`, before: be[key], after: ae[key] });
59850
+ else {
59851
+ add(
59852
+ `$.members[${id}].ends[${i}].${key}`,
59853
+ "path-refused-descendant",
59854
+ `"ends[${i}].${key}" may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
59855
+ );
59856
+ }
59857
+ }
59858
+ }
59859
+ if (fields.length) proposals.push({ kind: "member-changed", memberId: id, fields });
59860
+ }
59861
+ const incomingSheets = new Set((incoming.plans ?? []).map((p) => p.sheet));
59862
+ for (const sheet of currentSheets) {
59863
+ if (!incomingSheets.has(sheet)) {
59864
+ add(
59865
+ `$.plans[${sheet}]`,
59866
+ "path-refused",
59867
+ `sheet "${sheet}" is missing from the revision read; a revision may not remove a sheet \u2014 plan-level revision is not staged yet`
59868
+ );
59869
+ }
59870
+ }
59871
+ for (const id of curMembers.keys()) {
59872
+ if (!incMembers.has(id)) proposals.push({ kind: "member-removed", memberId: id });
59873
+ }
59874
+ const curPlans = new Map((current.plans ?? []).map((p) => [p.sheet, p]));
59875
+ const sheetCounts = /* @__PURE__ */ new Map();
59876
+ for (const plan of incoming.plans ?? []) sheetCounts.set(plan.sheet, (sheetCounts.get(plan.sheet) ?? 0) + 1);
59877
+ for (const [sheet, n] of sheetCounts) {
59878
+ if (n < 2) continue;
59879
+ add(
59880
+ `$.plans[${sheet}]`,
59881
+ "plan-sheet-duplicate",
59882
+ `sheet "${sheet}" appears ${n} times in the revision read; a sheet names one plan, so which of the copies is the revision has no answer \u2014 none of them is staged`
59883
+ );
59884
+ }
59885
+ for (const plan of incoming.plans ?? []) {
59886
+ if ((sheetCounts.get(plan.sheet) ?? 0) > 1) continue;
59887
+ const existing = curPlans.get(plan.sheet);
59888
+ if (existing) {
59889
+ const planFields = [];
59890
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(existing), ...Object.keys(plan)])) {
59891
+ if (key === "memberObservations") continue;
59892
+ if (IGNORED_INPUT.has(registryKeyOf(`$.plans[${plan.sheet}].${key}`))) continue;
59893
+ const b = existing[key];
59894
+ const a = plan[key];
59895
+ const entry2 = entryFor(`$.plans[].${key}`);
59896
+ if (!valuesDiffer(b, a, entry2)) continue;
59897
+ if (entry2?.disposition === "propose") planFields.push({ key, before: b, after: a });
59898
+ else {
59899
+ add(
59900
+ `$.plans[${plan.sheet}].${key}`,
59901
+ "path-refused",
59902
+ `"${key}" on an existing sheet may not be changed by a revision read${entry2?.note ? ` \u2014 ${entry2.note}` : ""}`
59903
+ );
59904
+ }
59905
+ }
59906
+ if (planFields.length) proposals.push({ kind: "plan-changed", sheet: plan.sheet, fields: planFields });
59907
+ continue;
59908
+ }
59909
+ const { memberObservations: _refused, ...sheetOnly } = plan;
59910
+ proposals.push({ kind: "plan-added", sheet: plan.sheet, plan: sheetOnly });
59911
+ }
59912
+ const HANDLED_ROOT = /* @__PURE__ */ new Set(["members", "plans"]);
59913
+ const curRoot = current;
59914
+ const incRoot = incoming;
59915
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(curRoot), ...Object.keys(incRoot)])) {
59916
+ if (HANDLED_ROOT.has(key)) continue;
59917
+ if (IGNORED_INPUT.has(registryKeyOf(`$.${key}`))) continue;
59918
+ if (!valuesDiffer(curRoot[key], incRoot[key])) continue;
59919
+ add(
59920
+ `$.${key}`,
59921
+ "path-refused",
59922
+ `"${key}" is model-level structure a revision read may not change \u2014 only members and their drawing evidence are staged here`
59923
+ );
59924
+ }
59925
+ return { accepted, bindingUpdates, bindingProposals, proposals, issues };
59926
+ }
59927
+ var RevisionApplyError = class extends Error {
59928
+ constructor(message) {
59929
+ super(message);
59930
+ this.name = "RevisionApplyError";
59931
+ }
59932
+ };
59933
+ var END_FIELD = /^ends\[(\d+)\]\.(.+)$/;
59934
+ function memberFieldTarget(field) {
59935
+ const m = field.key.match(END_FIELD);
59936
+ if (m && writableLeaf(`$.members[].ends[].${m[2]}`)) return { end: Number(m[1]), key: m[2] };
59937
+ if (writableLeaf(`$.members[].${field.key}`)) return { key: field.key };
59938
+ throw new RevisionApplyError(
59939
+ `applyStagedRevision: "${field.key}" is not a member field a revision read may change \u2014 the staged proposal does not match the registry`
59940
+ );
59941
+ }
59942
+ var writableLeaf = (registryKey) => {
59943
+ const e = entryFor(registryKey);
59944
+ return e?.disposition === "propose" && !e.descend;
59945
+ };
59946
+ function writeField(target, key, after) {
59947
+ if (after === void 0) delete target[key];
59948
+ else target[key] = structuredClone(after);
59949
+ }
59950
+ function applyStagedRevision(current, staged, selection = SELECT_NOTHING) {
59951
+ const next = structuredClone(current);
59952
+ const pick = (bucket, idx, name) => {
59953
+ const seen = /* @__PURE__ */ new Set();
59954
+ return [...idx].sort((a, b) => a - b).map((i) => {
59955
+ if (!Number.isInteger(i) || i < 0 || i >= bucket.length) {
59956
+ throw new RevisionApplyError(`applyStagedRevision: ${name}[${i}] is not an index into the staged ${name} (${bucket.length} staged)`);
59957
+ }
59958
+ if (seen.has(i)) throw new RevisionApplyError(`applyStagedRevision: ${name}[${i}] is selected more than once`);
59959
+ seen.add(i);
59960
+ return bucket[i];
59961
+ });
59962
+ };
59963
+ next.members = next.members ?? [];
59964
+ next.plans = next.plans ?? [];
59965
+ for (const p of pick(staged.proposals, selection.proposals, "proposals")) {
59966
+ switch (p.kind) {
59967
+ case "member-added": {
59968
+ if (p.member?.id !== p.memberId) {
59969
+ throw new RevisionApplyError(`applyStagedRevision: the staged addition names "${p.memberId}" but carries a member with id "${p.member?.id}" \u2014 staging builds both from one member, so this envelope was not produced by it`);
59970
+ }
59971
+ if (next.members.some((m) => m.id === p.member.id)) {
59972
+ throw new RevisionApplyError(`applyStagedRevision: member "${p.memberId}" already exists, so the staged addition does not describe this document`);
59973
+ }
59974
+ next.members.push(structuredClone(p.member));
59975
+ break;
59976
+ }
59977
+ case "member-removed": {
59978
+ const before = next.members.length;
59979
+ next.members = next.members.filter((m) => m.id !== p.memberId);
59980
+ if (next.members.length === before) {
59981
+ throw new RevisionApplyError(`applyStagedRevision: member "${p.memberId}" is not in this document, so the staged removal does not describe it`);
59982
+ }
59983
+ break;
59984
+ }
59985
+ case "member-changed": {
59986
+ const m = next.members.find((x) => x.id === p.memberId);
59987
+ if (!m) throw new RevisionApplyError(`applyStagedRevision: member "${p.memberId}" is not in this document, so the staged change does not describe it`);
59988
+ const baseEnds = Array.isArray(m.ends) ? m.ends.length : 0;
59989
+ for (const f of p.fields) {
59990
+ const t = memberFieldTarget(f);
59991
+ if ("end" in t) {
59992
+ const ends = Array.isArray(m.ends) ? [...m.ends] : [];
59993
+ if (t.end > baseEnds) {
59994
+ throw new RevisionApplyError(`applyStagedRevision: "${f.key}" names end ${t.end} of a member with ${baseEnds} \u2014 a revision may fill the next end, never leave a gap`);
59995
+ }
59996
+ while (ends.length <= t.end) ends.push({});
59997
+ writeField(ends[t.end], t.key, f.after);
59998
+ m.ends = ends;
59999
+ } else {
60000
+ writeField(m, t.key, f.after);
60001
+ }
60002
+ }
60003
+ break;
60004
+ }
60005
+ case "plan-added": {
60006
+ if (p.plan?.sheet !== p.sheet) {
60007
+ throw new RevisionApplyError(`applyStagedRevision: the staged addition names sheet "${p.sheet}" but carries a plan for "${p.plan?.sheet}" \u2014 staging builds both from one plan, so this envelope was not produced by it`);
60008
+ }
60009
+ if (next.plans.some((pl2) => pl2.sheet === p.plan.sheet)) {
60010
+ throw new RevisionApplyError(`applyStagedRevision: sheet "${p.sheet}" already exists, so the staged addition does not describe this document`);
60011
+ }
60012
+ next.plans.push(structuredClone(p.plan));
60013
+ break;
60014
+ }
60015
+ case "plan-changed": {
60016
+ const pl2 = next.plans.find((x) => x.sheet === p.sheet);
60017
+ if (!pl2) throw new RevisionApplyError(`applyStagedRevision: sheet "${p.sheet}" is not in this document, so the staged change does not describe it`);
60018
+ for (const f of p.fields) {
60019
+ if (!writableLeaf(`$.plans[].${f.key}`)) {
60020
+ throw new RevisionApplyError(`applyStagedRevision: "${f.key}" is not a plan field a revision read may change \u2014 the staged proposal does not match the registry`);
60021
+ }
60022
+ writeField(pl2, f.key, f.after);
60023
+ }
60024
+ break;
60025
+ }
60026
+ }
60027
+ }
60028
+ const bySheet = /* @__PURE__ */ new Map();
60029
+ for (const obs of staged.accepted) {
60030
+ const sheet = obs.evidence.source.sheet;
60031
+ bySheet.set(sheet, [...bySheet.get(sheet) ?? [], obs]);
60032
+ }
60033
+ const updates = /* @__PURE__ */ new Map();
60034
+ for (const u of [...staged.bindingUpdates, ...pick(staged.bindingProposals, selection.bindingProposals, "bindingProposals")]) {
60035
+ if (updates.has(u.observationId)) {
60036
+ throw new RevisionApplyError(`applyStagedRevision: two binding updates for observation "${u.observationId}" \u2014 staging files each into exactly one bucket, so this envelope was not produced by it`);
60037
+ }
60038
+ updates.set(u.observationId, u.to);
60039
+ }
60040
+ for (const plan of next.plans) {
60041
+ const arriving = bySheet.get(plan.sheet);
60042
+ if (arriving?.length) {
60043
+ plan.memberObservations = [...plan.memberObservations ?? [], ...structuredClone(arriving)];
60044
+ bySheet.delete(plan.sheet);
60045
+ }
60046
+ for (const obs of plan.memberObservations ?? []) {
60047
+ const to = updates.get(obs.id);
60048
+ if (to) obs.binding = structuredClone(to);
60049
+ }
60050
+ }
60051
+ if (bySheet.size > 0) {
60052
+ throw new Error(`applyStagedRevision: accepted evidence for unknown sheet(s) ${[...bySheet.keys()].join(", ")} \u2014 staging should have refused these`);
60053
+ }
60054
+ return next;
60055
+ }
60056
+
60057
+ // revision-envelope.ts
60058
+ function canonicalEnvelope(staged) {
60059
+ return {
60060
+ accepted: staged.accepted,
60061
+ bindingUpdates: staged.bindingUpdates,
60062
+ bindingProposals: staged.bindingProposals,
60063
+ proposals: staged.proposals.map(withSortedFields),
60064
+ issues: [...staged.issues].sort(byIssue)
60065
+ };
60066
+ }
60067
+ var envelopeHashOf = (staged) => hashOf(canonicalEnvelope(staged));
60068
+ function withSortedFields(p) {
60069
+ if (p.kind !== "member-changed" && p.kind !== "plan-changed") return p;
60070
+ return { ...p, fields: [...p.fields].sort((a, b) => cmp(a.key, b.key)) };
60071
+ }
60072
+ var cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
60073
+ var byIssue = (a, b) => cmp(a.path, b.path) || cmp(a.code, b.code) || cmp(a.message, b.message);
60074
+ function selectionOrError(staged, accept) {
60075
+ if (accept === void 0 || accept === null) return { selection: { proposals: [], bindingProposals: [] } };
60076
+ if (typeof accept !== "object" || Array.isArray(accept)) {
60077
+ return { error: "`accept` must be an object of the form { proposals: number[], bindingProposals: number[] }" };
60078
+ }
60079
+ const src = accept;
60080
+ const BUCKETS = ["proposals", "bindingProposals"];
60081
+ const unknown = Object.keys(src).filter((k) => !BUCKETS.includes(k));
60082
+ if (unknown.length) {
60083
+ return { error: `\`accept\` has no such field${unknown.length > 1 ? "s" : ""}: ${unknown.map((k) => `\`${k}\``).join(", ")} \u2014 it takes \`proposals\` and \`bindingProposals\`` };
60084
+ }
60085
+ const out = { proposals: [], bindingProposals: [] };
60086
+ for (const bucket of BUCKETS) {
60087
+ const raw = Object.hasOwn(src, bucket) ? src[bucket] : void 0;
60088
+ if (raw === void 0 || raw === null) continue;
60089
+ if (!Array.isArray(raw)) return { error: `\`accept.${bucket}\` must be an array of indices` };
60090
+ const size = staged[bucket].length;
60091
+ const seen = /* @__PURE__ */ new Set();
60092
+ for (const v of raw) {
60093
+ if (!Number.isInteger(v)) {
60094
+ return { error: `\`accept.${bucket}\` must contain whole numbers; got ${JSON.stringify(v)}` };
60095
+ }
60096
+ const i = v;
60097
+ if (i < 0 || i >= size) {
60098
+ return { error: `\`accept.${bucket}[${i}]\` is out of range \u2014 this review staged ${size} ${bucket}` };
60099
+ }
60100
+ if (seen.has(i)) return { error: `\`accept.${bucket}\` names index ${i} more than once` };
60101
+ seen.add(i);
60102
+ out[bucket].push(i);
60103
+ }
60104
+ }
60105
+ return { selection: out };
60106
+ }
60107
+ var PLAN_BULK_KEYS = ["raster_b64", "segments", "labels"];
60108
+ function stagedSummary(staged, record2) {
60109
+ return {
60110
+ stageId: record2.stageId,
60111
+ requestId: record2.requestId,
60112
+ accepted: staged.accepted.length,
60113
+ bindingUpdates: staged.bindingUpdates.length,
60114
+ proposals: staged.proposals.map(viewOf),
60115
+ bindingProposals: staged.bindingProposals,
60116
+ issues: staged.issues
60117
+ };
60118
+ }
60119
+ function viewOf(p) {
60120
+ if (p.kind !== "plan-added") return p;
60121
+ const plan = p.plan;
60122
+ const shown = {};
60123
+ const omitted = [];
60124
+ for (const k of Object.keys(plan)) {
60125
+ if (PLAN_BULK_KEYS.includes(k)) {
60126
+ if (plan[k] !== void 0) omitted.push(k);
60127
+ continue;
60128
+ }
60129
+ shown[k] = plan[k];
60130
+ }
60131
+ return { ...p, plan: shown, omitted };
60132
+ }
60133
+
59382
60134
  // project-sources-store.ts
59383
- var import_node_crypto13 = require("node:crypto");
60135
+ var import_node_crypto15 = require("node:crypto");
59384
60136
  var import_node_fs26 = require("node:fs");
59385
60137
  var import_node_path23 = require("node:path");
59386
60138
  var sourcesDir = (id) => (0, import_node_path23.join)(projectDir(id), "sources");
@@ -59392,7 +60144,7 @@ function writeAtomic2(path, buf) {
59392
60144
  }
59393
60145
  function saveSource(id, file) {
59394
60146
  (0, import_node_fs26.mkdirSync)(sourcesDir(id), { recursive: true });
59395
- const sha2563 = (0, import_node_crypto13.createHash)("sha256").update(file.buf).digest("hex");
60147
+ const sha2563 = (0, import_node_crypto15.createHash)("sha256").update(file.buf).digest("hex");
59396
60148
  const ext = safeExt(file.ext);
59397
60149
  const p = (0, import_node_path23.join)(sourcesDir(id), `${sha2563}.${ext}`);
59398
60150
  if (!(0, import_node_fs26.existsSync)(p)) writeAtomic2(p, file.buf);
@@ -60161,14 +60913,14 @@ function registerSheet(input) {
60161
60913
  }
60162
60914
 
60163
60915
  // export-identity.ts
60164
- var import_node_crypto14 = require("node:crypto");
60916
+ var import_node_crypto16 = require("node:crypto");
60165
60917
  function deriveExportSourceId(kind, ownerId, installation = installId()) {
60166
- return `sha256:${(0, import_node_crypto14.createHash)("sha256").update(`floless-export-source-v1\0${kind}\0${installation}\0${ownerId}`, "utf8").digest("hex")}`;
60918
+ return `sha256:${(0, import_node_crypto16.createHash)("sha256").update(`floless-export-source-v1\0${kind}\0${installation}\0${ownerId}`, "utf8").digest("hex")}`;
60167
60919
  }
60168
60920
  function deriveDropExportSourceId(kind, ownerId, nonce, installation = installId()) {
60169
60921
  return deriveExportSourceId(kind, `${ownerId}\0drop\0${nonce}`, installation);
60170
60922
  }
60171
- function canonicalJson(value) {
60923
+ function canonicalJson2(value) {
60172
60924
  const visit = (v) => {
60173
60925
  if (Array.isArray(v)) return v.map(visit);
60174
60926
  if (!v || typeof v !== "object") return v;
@@ -60180,7 +60932,7 @@ function sceneHash(scene) {
60180
60932
  const meta = scene.meta && typeof scene.meta === "object" ? { ...scene.meta } : {};
60181
60933
  delete meta.sceneHash;
60182
60934
  const projection = { ...scene, meta };
60183
- return `sha256:${(0, import_node_crypto14.createHash)("sha256").update(`floless-scene-v1\0${canonicalJson(projection)}`, "utf8").digest("hex")}`;
60935
+ return `sha256:${(0, import_node_crypto16.createHash)("sha256").update(`floless-scene-v1\0${canonicalJson2(projection)}`, "utf8").digest("hex")}`;
60184
60936
  }
60185
60937
 
60186
60938
  // steel-model-read.ts
@@ -62546,6 +63298,37 @@ function revisionReadContractError(appId, contract) {
62546
63298
 
62547
63299
  // revision-routes.ts
62548
63300
  var requestView = (r) => r === null ? null : { ...r, appTemplateId: r.appId ? resolveTemplateId(r.appId) : void 0 };
63301
+ function sweepOrphanedStaged() {
63302
+ for (const key of listStagedKeys()) {
63303
+ const rec = readStagedRecord(key);
63304
+ if (!rec || !hasRequestFile(rec.requestId)) dropStagingFor(key);
63305
+ }
63306
+ }
63307
+ async function stageForReview(reply, project, requestId, candidate) {
63308
+ const current = readAcceptedForRequest(project.app, project.id, "read");
63309
+ if (current == null) {
63310
+ return reply.status(409).send({ ok: false, error: "this project has no contract yet \u2014 a revision read revises an existing model" });
63311
+ }
63312
+ if (declaredTypeOf(current) !== STEEL_V2) {
63313
+ return reply.status(409).send({
63314
+ ok: false,
63315
+ error: `this project holds a "${declaredTypeOf(current)}" contract, and a "${STEEL_V2}" revision read revises a "${STEEL_V2}" model \u2014 migrate the project first`
63316
+ });
63317
+ }
63318
+ const stagingKey = await getOrCreateProjectStagingId(project.id);
63319
+ const staged = stageRevisionRead(current, candidate);
63320
+ const record2 = stageCandidate(stagingKey, candidate, {
63321
+ requestId,
63322
+ envelopeHash: envelopeHashOf(staged),
63323
+ // Carried only so a 409 can say the contract moved. Never a gate — an ordinary editor autosave
63324
+ // moves it constantly and must not starve a review.
63325
+ baseContractHash: etagOf(current),
63326
+ stagedAt: (/* @__PURE__ */ new Date()).toISOString()
63327
+ });
63328
+ const request = patchRequest(requestId, { status: "staged" });
63329
+ broadcast({ type: "request-added", request: requestView(request) });
63330
+ return reply.status(202).send({ ok: true, staged: stagedSummary(staged, record2) });
63331
+ }
62549
63332
  function registerRevisionRoutes(app) {
62550
63333
  app.post(
62551
63334
  "/api/projects/:id/revision-requests",
@@ -62610,6 +63393,18 @@ function registerRevisionRoutes(app) {
62610
63393
  error: guardError
62611
63394
  });
62612
63395
  }
63396
+ sweepOrphanedStaged();
63397
+ try {
63398
+ acceptContract(req.body.contract, { appId: project.app, projectId: project.id, operation: "put" });
63399
+ } catch (e) {
63400
+ if (e instanceof ContractPolicyError) {
63401
+ return reply.status(400).send({ ok: false, error: e.message, code: e.code });
63402
+ }
63403
+ throw e;
63404
+ }
63405
+ if (declaredTypeOf(req.body.contract) === STEEL_V2) {
63406
+ return stageForReview(reply, project, request.id, req.body.contract);
63407
+ }
62613
63408
  try {
62614
63409
  await writeContractChecked(project.app, req.body.contract, project.id, {
62615
63410
  origin: "internal",
@@ -62628,6 +63423,97 @@ function registerRevisionRoutes(app) {
62628
63423
  return { ok: true, version };
62629
63424
  }
62630
63425
  );
63426
+ app.post(
63427
+ "/api/projects/:id/revision-read/confirm",
63428
+ async (req, reply) => {
63429
+ const project = getProject(req.params.id);
63430
+ if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
63431
+ const requestId = typeof req.body?.requestId === "string" ? req.body.requestId : "";
63432
+ const stageId = typeof req.body?.stageId === "string" ? req.body.stageId : "";
63433
+ if (!requestId || !stageId) {
63434
+ return reply.status(400).send({ ok: false, error: "requestId and stageId are both required \u2014 a confirm names the review it is confirming" });
63435
+ }
63436
+ return withLifecycleLock("project", project.id, async () => {
63437
+ const request = getRequest(requestId);
63438
+ if (!request || request.type !== "revision-read" || request.project !== project.id) {
63439
+ return reply.status(410).send({ ok: false, error: "that revision request no longer exists \u2014 re-attach the revised set and read it again" });
63440
+ }
63441
+ if (request.status !== "staged") {
63442
+ return reply.status(409).send({ ok: false, error: `that revision request is "${request.status}", not staged for review` });
63443
+ }
63444
+ const stagingKey = getProjectStagingId(project.id);
63445
+ const st = stagingKey ? readStaged(stagingKey) : null;
63446
+ if (!stagingKey || !st) {
63447
+ return reply.status(410).send({ ok: false, error: "the staged review is no longer available \u2014 read the revised set again" });
63448
+ }
63449
+ if (st.record.requestId !== requestId || st.record.stageId !== stageId) {
63450
+ return reply.status(409).send({
63451
+ ok: false,
63452
+ error: "this review was replaced by a newer read of the same set \u2014 reload the review and confirm that one",
63453
+ code: "stage-superseded"
63454
+ });
63455
+ }
63456
+ const current = readAcceptedForRequest(project.app, project.id, "read");
63457
+ if (current == null || declaredTypeOf(current) !== STEEL_V2) {
63458
+ return reply.status(409).send({ ok: false, error: "this project no longer holds the model this review was staged against" });
63459
+ }
63460
+ const head = listVersions(project.id)[0]?.n ?? 0;
63461
+ if ((request.baseVersion ?? 0) !== head) {
63462
+ return reply.status(409).send({ ok: false, error: `project changed since this read started (base v${request.baseVersion ?? 0}, now v${head}) \u2014 re-read the current version` });
63463
+ }
63464
+ let candidate;
63465
+ try {
63466
+ candidate = acceptContract(st.candidate, { appId: project.app, projectId: project.id, operation: "put" });
63467
+ } catch (e) {
63468
+ if (e instanceof ContractPolicyError) {
63469
+ return reply.status(409).send({ ok: false, error: `this staged review can no longer be applied \u2014 ${e.message}`, code: e.code });
63470
+ }
63471
+ throw e;
63472
+ }
63473
+ const fresh = stageRevisionRead(current, candidate);
63474
+ if (envelopeHashOf(fresh) !== st.record.envelopeHash) {
63475
+ const restaged = stageCandidate(stagingKey, candidate, {
63476
+ requestId: st.record.requestId,
63477
+ envelopeHash: envelopeHashOf(fresh),
63478
+ baseContractHash: etagOf(current),
63479
+ stagedAt: (/* @__PURE__ */ new Date()).toISOString()
63480
+ });
63481
+ return reply.status(409).send({
63482
+ ok: false,
63483
+ error: "the model changed while you were reviewing, so this read means something different now \u2014 here is the current review",
63484
+ code: "stage-restaged",
63485
+ staged: stagedSummary(fresh, restaged)
63486
+ });
63487
+ }
63488
+ const sel = selectionOrError(fresh, req.body?.accept);
63489
+ if ("error" in sel) return reply.status(400).send({ ok: false, error: sel.error });
63490
+ let next;
63491
+ try {
63492
+ next = applyStagedRevision(current, fresh, sel.selection);
63493
+ } catch (e) {
63494
+ if (e instanceof RevisionApplyError) return reply.status(400).send({ ok: false, error: e.message });
63495
+ throw e;
63496
+ }
63497
+ try {
63498
+ await writeContractChecked(project.app, next, project.id, {
63499
+ origin: "internal",
63500
+ why: "a human confirmed this revision review; the compare and this write share one lock (see above)"
63501
+ });
63502
+ } catch (e) {
63503
+ if (e instanceof ContractError) return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
63504
+ throw e;
63505
+ }
63506
+ clearApproval(project.id);
63507
+ const message = typeof req.body?.message === "string" && req.body.message.trim() ? req.body.message.trim() : "Re-read a revised drawing set";
63508
+ const source = request.sourceRefs && request.sourceRefs.length ? { files: request.sourceRefs, requestId: request.id } : void 0;
63509
+ const version = createVersion(project.id, next, { author: "AI", message, gate: null, kind: "revision-read", source });
63510
+ broadcast({ type: "contract-changed", appId: project.app, project: project.id });
63511
+ dropStagingFor(stagingKey);
63512
+ deleteRequest(request.id);
63513
+ return { ok: true, version };
63514
+ });
63515
+ }
63516
+ );
62631
63517
  app.post(
62632
63518
  "/api/projects/:id/revision-requests/:reqId/fail",
62633
63519
  async (req, reply) => {
@@ -62638,6 +63524,8 @@ function registerRevisionRoutes(app) {
62638
63524
  return reply.status(404).send({ ok: false, error: `unknown revision request for this project: ${req.params.reqId}` });
62639
63525
  }
62640
63526
  const error = typeof req.body?.error === "string" && req.body.error.trim() ? req.body.error.trim().slice(0, 2e3) : "the read could not be completed";
63527
+ const key = getProjectStagingId(project.id);
63528
+ if (key && readStagedRecord(key)?.requestId === existing.id) dropStagingFor(key);
62641
63529
  const request = patchRequest(existing.id, { status: "failed", error });
62642
63530
  broadcast({ type: "request-added", request });
62643
63531
  return { ok: true, request: requestView(request) };
@@ -62686,7 +63574,7 @@ function uniqueProjectExportFilename(projectId, preferred) {
62686
63574
  }
62687
63575
 
62688
63576
  // project-export-receipts.ts
62689
- var import_node_crypto15 = require("node:crypto");
63577
+ var import_node_crypto17 = require("node:crypto");
62690
63578
  var import_node_fs28 = require("node:fs");
62691
63579
  var import_node_path26 = require("node:path");
62692
63580
 
@@ -62715,7 +63603,7 @@ var EXTENSIONS = {
62715
63603
  var RESERVED2 = /^\.floless-(?:txn|cleanup|tmp|backup)-/i;
62716
63604
  var projectExportIndexPath = (projectId) => (0, import_node_path26.join)(projectExportsDir(projectId), "index.json");
62717
63605
  function hash(bytes) {
62718
- return (0, import_node_crypto15.createHash)("sha256").update(bytes).digest("hex");
63606
+ return (0, import_node_crypto17.createHash)("sha256").update(bytes).digest("hex");
62719
63607
  }
62720
63608
  function proof(bytes) {
62721
63609
  return bytes ? { exists: true, bytes: bytes.length, sha256: hash(bytes) } : { exists: false, bytes: 0, sha256: null };
@@ -62841,7 +63729,7 @@ function syncDirectory(path) {
62841
63729
  function durableReplace(path, bytes) {
62842
63730
  const dir = (0, import_node_path26.dirname)(path);
62843
63731
  (0, import_node_fs28.mkdirSync)(dir, { recursive: true });
62844
- const tmp = (0, import_node_path26.join)(dir, `.floless-tmp-receipt-${(0, import_node_crypto15.randomUUID)()}`);
63732
+ const tmp = (0, import_node_path26.join)(dir, `.floless-tmp-receipt-${(0, import_node_crypto17.randomUUID)()}`);
62845
63733
  try {
62846
63734
  (0, import_node_fs28.writeFileSync)(tmp, bytes, { flag: "wx" });
62847
63735
  syncFile(tmp);
@@ -63254,7 +64142,7 @@ function registerWorkspaceDataRoutes(app) {
63254
64142
  }
63255
64143
 
63256
64144
  // steel-model-migrate.ts
63257
- var import_node_crypto16 = require("node:crypto");
64145
+ var import_node_crypto18 = require("node:crypto");
63258
64146
 
63259
64147
  // steel-model-migrate-refs.ts
63260
64148
  var key2 = (sheet, id) => JSON.stringify([sheet, id]);
@@ -64236,7 +65124,7 @@ function shortHash(s) {
64236
65124
  return `${h1.toString(36)}${h2.toString(36)}`;
64237
65125
  }
64238
65126
  function blobDigest(s) {
64239
- return `blob:${s.length}:${(0, import_node_crypto16.createHash)("sha256").update(s).digest("base64url").slice(0, 22)}`;
65127
+ return `blob:${s.length}:${(0, import_node_crypto18.createHash)("sha256").update(s).digest("base64url").slice(0, 22)}`;
64240
65128
  }
64241
65129
  function canonicalHash(doc) {
64242
65130
  const norm = (v, key) => {
@@ -64246,7 +65134,7 @@ function canonicalHash(doc) {
64246
65134
  if (isObj3(v)) return Object.fromEntries(Object.keys(v).sort().map((k) => [k, norm(v[k], k)]));
64247
65135
  return v;
64248
65136
  };
64249
- return (0, import_node_crypto16.createHash)("sha256").update(JSON.stringify(norm(doc))).digest("hex");
65137
+ return (0, import_node_crypto18.createHash)("sha256").update(JSON.stringify(norm(doc))).digest("hex");
64250
65138
  }
64251
65139
  var KNOWN_READ_KINDS = /* @__PURE__ */ new Set(["steel-filter-segment"]);
64252
65140
  function previewMigration(v1, ctx) {
@@ -69449,7 +70337,7 @@ async function teklaVersionToBake() {
69449
70337
  }
69450
70338
 
69451
70339
  // ifc-publication.ts
69452
- var import_node_crypto17 = require("node:crypto");
70340
+ var import_node_crypto19 = require("node:crypto");
69453
70341
  var import_node_fs34 = require("node:fs");
69454
70342
  var import_node_os18 = require("node:os");
69455
70343
  var import_node_path30 = require("node:path");
@@ -69475,7 +70363,7 @@ var MAX_TRANSACTIONS = 256;
69475
70363
  var MAX_PHASE_BYTES = 1024 * 1024;
69476
70364
  var MAX_INDEX_SNAPSHOT_BYTES = 512 * 1024;
69477
70365
  function sha2562(bytes) {
69478
- return (0, import_node_crypto17.createHash)("sha256").update(bytes).digest("hex");
70366
+ return (0, import_node_crypto19.createHash)("sha256").update(bytes).digest("hex");
69479
70367
  }
69480
70368
  function proof2(bytes) {
69481
70369
  return { exists: true, bytes: bytes.length, sha256: sha2562(bytes) };
@@ -69505,7 +70393,7 @@ function syncDirectory2(path) {
69505
70393
  function durableReplace2(path, bytes) {
69506
70394
  const dir = (0, import_node_path30.dirname)(path);
69507
70395
  (0, import_node_fs34.mkdirSync)(dir, { recursive: true });
69508
- const tmp = (0, import_node_path30.join)(dir, `.floless-tmp-recovery-${(0, import_node_crypto17.randomUUID)()}`);
70396
+ const tmp = (0, import_node_path30.join)(dir, `.floless-tmp-recovery-${(0, import_node_crypto19.randomUUID)()}`);
69509
70397
  try {
69510
70398
  (0, import_node_fs34.writeFileSync)(tmp, bytes, { flag: "wx" });
69511
70399
  syncFile2(tmp);
@@ -69541,7 +70429,7 @@ function requestIfcTempPath(finalPath) {
69541
70429
  const final = canonicalPath(finalPath);
69542
70430
  if (!plainIfcFilename((0, import_node_path30.basename)(final))) throw new IfcPublicationError("IFC final filename is unsafe.");
69543
70431
  (0, import_node_fs34.mkdirSync)((0, import_node_path30.dirname)(final), { recursive: true });
69544
- return (0, import_node_path30.join)((0, import_node_path30.dirname)(final), `.floless-tmp-ifc-${(0, import_node_crypto17.randomUUID)()}.ifc`);
70432
+ return (0, import_node_path30.join)((0, import_node_path30.dirname)(final), `.floless-tmp-ifc-${(0, import_node_crypto19.randomUUID)()}.ifc`);
69545
70433
  }
69546
70434
  function validateIfc(path) {
69547
70435
  if (!(0, import_node_fs34.existsSync)(path) || (0, import_node_fs34.statSync)(path).size === 0) throw new IfcPublicationError("the IFC export produced no file");
@@ -69560,7 +70448,7 @@ function writePhase(txnDir, journal) {
69560
70448
  if (index < 0) throw new IfcPublicationError(`unknown IFC publication phase "${journal.phase}".`);
69561
70449
  const destination = (0, import_node_path30.join)(txnDir, `${String(index).padStart(3, "0")}-${journal.phase}.json`);
69562
70450
  if ((0, import_node_fs34.existsSync)(destination)) throw new IfcPublicationError(`IFC publication phase "${journal.phase}" already exists.`);
69563
- const temp = (0, import_node_path30.join)(txnDir, `.phase-${(0, import_node_crypto17.randomUUID)()}.tmp`);
70451
+ const temp = (0, import_node_path30.join)(txnDir, `.phase-${(0, import_node_crypto19.randomUUID)()}.tmp`);
69564
70452
  const bytes = Buffer.from(`${JSON.stringify(journal, null, 2)}
69565
70453
  `, "utf8");
69566
70454
  try {
@@ -69880,7 +70768,7 @@ async function publishIfcAtomically(tempPath, finalPath, options) {
69880
70768
  }
69881
70769
  return withLifecycleLock(options.resource.kind, options.resource.key, async () => {
69882
70770
  await recoverIfcPublicationsInDirectory(paths.dir, options.resource);
69883
- const txnId = (0, import_node_crypto17.randomUUID)();
70771
+ const txnId = (0, import_node_crypto19.randomUUID)();
69884
70772
  const txnDir = (0, import_node_path30.join)(paths.dir, `.floless-txn-ifc-${txnId}`);
69885
70773
  const backupPath = (0, import_node_path30.join)(paths.dir, `.floless-backup-ifc-${txnId}.ifc`);
69886
70774
  const priorArtifact = readFileProof(paths.final);
@@ -70029,7 +70917,7 @@ function cleanupIfcTemp(path) {
70029
70917
  }
70030
70918
 
70031
70919
  // export-companion.ts
70032
- var import_node_crypto18 = require("node:crypto");
70920
+ var import_node_crypto20 = require("node:crypto");
70033
70921
  var import_node_fs35 = require("node:fs");
70034
70922
  var import_node_path31 = require("node:path");
70035
70923
  var PREFIX = "floless-export-tmp-";
@@ -70060,7 +70948,7 @@ function removeScratch(path, appsRoot) {
70060
70948
  }
70061
70949
  function createExportCompanion(ownerId, sink, appsRoot = defaultAppsRoot()) {
70062
70950
  const safeOwner = ownerId.replace(/[^a-z0-9._-]/gi, "-").slice(0, 80) || "app";
70063
- const token = (0, import_node_crypto18.randomUUID)();
70951
+ const token = (0, import_node_crypto20.randomUUID)();
70064
70952
  const id = `${PREFIX}${safeOwner}-${sink}-${token}`;
70065
70953
  const root4 = (0, import_node_path31.resolve)(appsRoot);
70066
70954
  const path = (0, import_node_path31.resolve)(root4, id);
@@ -71535,7 +72423,7 @@ function unregisterAutostart() {
71535
72423
 
71536
72424
  // updater.ts
71537
72425
  var import_node_child_process7 = require("node:child_process");
71538
- var import_node_crypto19 = require("node:crypto");
72426
+ var import_node_crypto21 = require("node:crypto");
71539
72427
  var import_node_fs42 = require("node:fs");
71540
72428
  var import_node_stream3 = require("node:stream");
71541
72429
  var import_promises3 = require("node:stream/promises");
@@ -71632,8 +72520,15 @@ function versionGt(a, b) {
71632
72520
  }
71633
72521
  var NPM_LATEST_URL = "https://registry.npmjs.org/@floless/app/latest";
71634
72522
  var NPM_UPDATE_COMMAND = "npm i -g @floless/app@latest";
71635
- async function checkNpmUpdate(cur) {
71636
- const base = { supported: true, channel: "npm", currentVersion: cur };
72523
+ async function checkNpmUpdate(cur, channel = "npm") {
72524
+ const base = {
72525
+ supported: true,
72526
+ channel,
72527
+ currentVersion: cur,
72528
+ // CHANNEL === 'win' + Update.exe: there is no desktop build for any other OS to point at.
72529
+ desktopAvailable: process.platform === "win32",
72530
+ ...channel === "npx" ? { transient: true } : {}
72531
+ };
71637
72532
  try {
71638
72533
  const res = await fetch(NPM_LATEST_URL, { redirect: "follow", signal: AbortSignal.timeout(FEED_TIMEOUT_MS) });
71639
72534
  if (!res.ok) return { ...base, updateAvailable: false, reason: `npm registry returned HTTP ${res.status}` };
@@ -71649,7 +72544,7 @@ async function checkNpmUpdate(cur) {
71649
72544
  async function checkForUpdate() {
71650
72545
  const cur = currentVersion();
71651
72546
  const channel = appChannel();
71652
- if (channel === "npm") return checkNpmUpdate(cur);
72547
+ if (channel === "npm" || channel === "npx") return checkNpmUpdate(cur, channel);
71653
72548
  if (channel !== "desktop") {
71654
72549
  return {
71655
72550
  supported: false,
@@ -71694,7 +72589,7 @@ async function checkForUpdate() {
71694
72589
  return { supported: true, currentVersion: cur, updateAvailable: true, targetVersion: latest.Version, asset: latest };
71695
72590
  }
71696
72591
  async function sha1OfFile(path) {
71697
- const hash2 = (0, import_node_crypto19.createHash)("sha1");
72592
+ const hash2 = (0, import_node_crypto21.createHash)("sha1");
71698
72593
  await (0, import_promises3.pipeline)((0, import_node_fs42.createReadStream)(path), hash2);
71699
72594
  return hash2.digest("hex").toUpperCase();
71700
72595
  }
@@ -71859,12 +72754,12 @@ var CACHE_TTL_MS = 5 * 6e4;
71859
72754
  async function getJson(url, headers = {}) {
71860
72755
  try {
71861
72756
  const res = await fetch(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
71862
- let json = null;
72757
+ let json2 = null;
71863
72758
  try {
71864
- json = await res.json();
72759
+ json2 = await res.json();
71865
72760
  } catch {
71866
72761
  }
71867
- return { status: res.status, json };
72762
+ return { status: res.status, json: json2 };
71868
72763
  } catch {
71869
72764
  return null;
71870
72765
  }
@@ -71989,7 +72884,7 @@ function ping() {
71989
72884
  });
71990
72885
  });
71991
72886
  }
71992
- function probeVersion() {
72887
+ function probeRunning() {
71993
72888
  return new Promise((resolve11) => {
71994
72889
  const req = import_node_http.default.get(HEALTH_URL, { timeout: 1500 }, (res) => {
71995
72890
  let body = "";
@@ -71998,16 +72893,17 @@ function probeVersion() {
71998
72893
  });
71999
72894
  res.on("end", () => {
72000
72895
  try {
72001
- resolve11(JSON.parse(body).appVersion || null);
72896
+ const j = JSON.parse(body);
72897
+ resolve11({ version: j.appVersion || null, channel: j.appChannel || null });
72002
72898
  } catch {
72003
- resolve11(null);
72899
+ resolve11({ version: null, channel: null });
72004
72900
  }
72005
72901
  });
72006
72902
  });
72007
- req.on("error", () => resolve11(null));
72903
+ req.on("error", () => resolve11({ version: null, channel: null }));
72008
72904
  req.on("timeout", () => {
72009
72905
  req.destroy();
72010
- resolve11(null);
72906
+ resolve11({ version: null, channel: null });
72011
72907
  });
72012
72908
  });
72013
72909
  }
@@ -72020,11 +72916,16 @@ function cmpVersion(a, b) {
72020
72916
  }
72021
72917
  return 0;
72022
72918
  }
72023
- function shouldTakeOver(runningVersion, selfVersion) {
72919
+ var EVICTABLE_CHANNELS = /* @__PURE__ */ new Set(["npm", "npx", "dev"]);
72920
+ function shouldTakeOver(runningVersion, selfVersion, channels = {}) {
72024
72921
  if (!runningVersion || !selfVersion) return false;
72025
- return cmpVersion(selfVersion, runningVersion) > 0;
72922
+ const cmp2 = cmpVersion(selfVersion, runningVersion);
72923
+ if (cmp2 !== 0) return cmp2 > 0;
72924
+ const { running = null, self = null } = channels;
72925
+ return self === "desktop" && EVICTABLE_CHANNELS.has(running);
72026
72926
  }
72027
72927
  var _selfVersion = null;
72928
+ var _selfChannel = null;
72028
72929
  async function waitHealthy(timeoutMs = 3e4) {
72029
72930
  const deadline = Date.now() + timeoutMs;
72030
72931
  while (Date.now() < deadline) {
@@ -72087,14 +72988,14 @@ async function ensureServerUp() {
72087
72988
  async function cmdOpen() {
72088
72989
  const postUpdate = consumePostUpdateMarker();
72089
72990
  if (await ping()) {
72090
- const running = await probeVersion();
72091
- if (shouldTakeOver(running, _selfVersion)) {
72092
- log(`floless.app v${running} is already running on ${PORT}; this build is v${_selfVersion} \u2014 taking over`);
72991
+ const running = await probeRunning();
72992
+ if (shouldTakeOver(running.version, _selfVersion, { running: running.channel, self: _selfChannel })) {
72993
+ log(`floless.app v${running.version} (${running.channel ?? "unknown"}) is already running on ${PORT}; this build is v${_selfVersion} (${_selfChannel ?? "unknown"}) \u2014 taking over`);
72093
72994
  stopServer();
72094
72995
  await new Promise((r) => setTimeout(r, 500));
72095
72996
  await ensureServerUp();
72096
72997
  } else {
72097
- log(`already running${running ? ` (v${running})` : ""}`);
72998
+ log(`already running${running.version ? ` (v${running.version}${running.channel ? `, ${running.channel}` : ""})` : ""}`);
72098
72999
  }
72099
73000
  } else {
72100
73001
  await ensureServerUp();
@@ -72161,10 +73062,10 @@ function parseTeardownFlags(argv = []) {
72161
73062
  keepAware: argv.includes("--keep-aware")
72162
73063
  };
72163
73064
  }
72164
- function parseProcessList(json) {
73065
+ function parseProcessList(json2) {
72165
73066
  let parsed;
72166
73067
  try {
72167
- parsed = JSON.parse(json || "[]");
73068
+ parsed = JSON.parse(json2 || "[]");
72168
73069
  } catch {
72169
73070
  return [];
72170
73071
  }
@@ -72283,6 +73184,11 @@ function parseAction(arg) {
72283
73184
  return cmd;
72284
73185
  }
72285
73186
  async function cmdUpdate() {
73187
+ if (/(^|[\\/])_npx([\\/]|$)/.test((0, import_node_url3.fileURLToPath)(__import_meta_url))) {
73188
+ log("this copy is temporary (started with npx), so it cannot update itself");
73189
+ log('install a permanent one with "npm i -g @floless/app@latest", then close FloLess and open it again');
73190
+ return;
73191
+ }
72286
73192
  log('this is the npm build \u2014 update it with "npm i -g @floless/app"');
72287
73193
  log('(the installer build self-updates via "floless-app update")');
72288
73194
  }
@@ -72346,8 +73252,9 @@ async function cmdUninstall(flags = {}) {
72346
73252
  log("done. Finally, remove floless.app itself with: npm uninstall -g @floless/app");
72347
73253
  }
72348
73254
  var ACTIONS = { open: cmdOpen, start: cmdStart, supervise: cmdSupervise, stop: cmdStop, restart: cmdRestart, login: cmdLogin, update: cmdUpdate, uninstall: cmdUninstall };
72349
- async function runAction(arg, flagArgv = [], selfVersion = null) {
73255
+ async function runAction(arg, flagArgv = [], selfVersion = null, selfChannel = null) {
72350
73256
  _selfVersion = selfVersion;
73257
+ _selfChannel = selfChannel;
72351
73258
  const cmd = parseAction(arg);
72352
73259
  const action = ACTIONS[cmd];
72353
73260
  if (!action) {
@@ -74569,6 +75476,11 @@ async function startServer() {
74569
75476
  refusedContractWrites,
74570
75477
  appVersion: appVersion(),
74571
75478
  // the installed build (sq.version), so it's scriptable
75479
+ // How this build is distributed. Published so ANOTHER build's launcher can tell whether the
75480
+ // instance already holding the port can self-update: on equal versions the desktop build takes
75481
+ // over one that cannot (see `shouldTakeOver`). Without this the two are indistinguishable over
75482
+ // HTTP and the weaker instance keeps the port.
75483
+ appChannel: appChannel(),
74572
75484
  webBase: webBaseUrl(),
74573
75485
  // channel-correct public site base, for the changelog deep-link
74574
75486
  awareVersion: awareInstalledVersion() ?? bs.awareVersion,
@@ -75435,7 +76347,7 @@ async function startServer() {
75435
76347
  }
75436
76348
  async function dropExportSourceId(appId, project) {
75437
76349
  const ownerId = project ? await getOrCreateProjectExportSourceId(project) : await getOrCreateWorkflowExportSourceId(appId);
75438
- return deriveDropExportSourceId(project ? "project" : "workflow", ownerId, (0, import_node_crypto20.randomUUID)());
76350
+ return deriveDropExportSourceId(project ? "project" : "workflow", ownerId, (0, import_node_crypto22.randomUUID)());
75439
76351
  }
75440
76352
  app.post("/api/contract/:appId/export-ifc", async (req, reply) => {
75441
76353
  const appId = req.params.appId;
@@ -75504,7 +76416,7 @@ async function startServer() {
75504
76416
  index: parseStepData(artifactBytes),
75505
76417
  bytes: artifactBytes
75506
76418
  });
75507
- const expectedContentSha256 = (0, import_node_crypto20.createHash)("sha256").update(artifactBytes).digest("hex");
76419
+ const expectedContentSha256 = (0, import_node_crypto22.createHash)("sha256").update(artifactBytes).digest("hex");
75508
76420
  const transition = project && projectSnapshot ? prepareProjectExport(project, {
75509
76421
  kind: "ifc",
75510
76422
  filename,
@@ -76233,7 +77145,7 @@ async function startServer() {
76233
77145
  (0, import_node_fs46.rmSync)(tempHome, { recursive: true, force: true });
76234
77146
  return reply.status(502).send({ ok: false, error: `build produced output at ${result.agentDir} but no manifest.yaml` });
76235
77147
  }
76236
- const token = (0, import_node_crypto20.randomUUID)();
77148
+ const token = (0, import_node_crypto22.randomUUID)();
76237
77149
  registerStage(token, tempHome, result.agentId);
76238
77150
  const preview2 = buildPreview(manifest, sourceKind, sourceRef, token);
76239
77151
  if ((0, import_node_fs46.existsSync)((0, import_node_path43.join)(graftAgentsDir(), result.agentId))) {
@@ -77088,7 +78000,7 @@ async function main() {
77088
78000
  if (/flolessapp\.exe$/i.test(process.execPath)) {
77089
78001
  ensureAutostart(resolveRealInstallExe(process.execPath));
77090
78002
  }
77091
- await runAction(argv[0], [], appVersion());
78003
+ await runAction(argv[0], [], appVersion(), appChannel());
77092
78004
  }
77093
78005
  main().catch((err2) => {
77094
78006
  const msg = err2 instanceof Error ? err2.message : String(err2);