@floless/app 0.137.0 → 0.137.2

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.
@@ -55058,7 +55058,7 @@ function appVersion() {
55058
55058
  return resolveVersion({
55059
55059
  isSea: isSea2(),
55060
55060
  sqVersionXml: readSqVersionXml(),
55061
- define: true ? "0.137.0" : void 0,
55061
+ define: true ? "0.137.2" : void 0,
55062
55062
  pkgVersion: readPkgVersion()
55063
55063
  });
55064
55064
  }
@@ -55074,7 +55074,7 @@ function resolveChannel(s) {
55074
55074
  function appChannel() {
55075
55075
  return resolveChannel({
55076
55076
  isSea: isSea2(),
55077
- define: true ? "0.137.0" : void 0,
55077
+ define: true ? "0.137.2" : void 0,
55078
55078
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55079
55079
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55080
55080
  modulePath: process.argv[1]
@@ -58906,14 +58906,53 @@ function normalisePlanViewIds(doc) {
58906
58906
  plans: model.plans.map((raw) => needsId(raw) ? { ...raw, id: raw.sheet } : raw)
58907
58907
  };
58908
58908
  }
58909
+ var hasDerivedId = (plan) => {
58910
+ if (!plan || typeof plan !== "object" || Array.isArray(plan)) return false;
58911
+ const row = plan;
58912
+ return typeof row.sheet === "string" && row.sheet.trim() !== "" && row.id === row.sheet;
58913
+ };
58914
+ function stripDerivedPlanViewIds(doc) {
58915
+ const model = doc;
58916
+ if (!model || typeof model !== "object" || !Array.isArray(model.plans)) return doc;
58917
+ if (typeof model.type === "string" && !model.type.startsWith("steel.model/")) return doc;
58918
+ if (!model.plans.some(hasDerivedId)) return doc;
58919
+ return {
58920
+ ...model,
58921
+ plans: model.plans.map((raw) => {
58922
+ if (!hasDerivedId(raw)) return raw;
58923
+ const { id: _derived, ...rest } = raw;
58924
+ return rest;
58925
+ })
58926
+ };
58927
+ }
58909
58928
 
58910
58929
  // project-contract-hash.ts
58911
58930
  function contractHash(contract) {
58912
58931
  return hashOf(contract);
58913
58932
  }
58914
- function comparableContractHash(contract) {
58933
+ function contractIdentityHash(contract) {
58934
+ return hashOf(stripDerivedPlanViewIds(contract));
58935
+ }
58936
+ function supersededContractIdentityHash(contract) {
58915
58937
  return hashOf(normalisePlanViewIds(contract));
58916
58938
  }
58939
+ function comparableContractHash(contract) {
58940
+ return contractIdentityHash(contract);
58941
+ }
58942
+ function etagsOf(doc) {
58943
+ if (doc == null) return { current: null, superseded: null };
58944
+ const current = `"${contractIdentityHash(doc)}"`;
58945
+ const superseded = `"${supersededContractIdentityHash(doc)}"`;
58946
+ return { current, superseded: superseded === current ? null : superseded };
58947
+ }
58948
+ function recordedEtagsNameDocument(recorded, doc) {
58949
+ const etags = etagsOf(doc);
58950
+ return recorded.map((tag) => recordedEtagNamesContract(tag, etags));
58951
+ }
58952
+ function recordedEtagNamesContract(recorded, etags) {
58953
+ if (!recorded) return false;
58954
+ return recorded === etags.current || etags.superseded !== null && recorded === etags.superseded;
58955
+ }
58917
58956
 
58918
58957
  // connection-review-transition.ts
58919
58958
  var ConnectionReviewTransitionError = class extends Error {
@@ -65286,7 +65325,8 @@ var import_node_os24 = require("node:os");
65286
65325
  // contract-publication.ts
65287
65326
  var import_node_fs36 = require("node:fs");
65288
65327
  var publicationPath = (path) => `${path}.publication.json`;
65289
- var tagOf = (contract) => `"${contractHash(contract)}"`;
65328
+ var tagOf = (contract) => `"${contractIdentityHash(contract)}"`;
65329
+ var supersededTagOf = (contract) => `"${supersededContractIdentityHash(contract)}"`;
65290
65330
  function valid(value) {
65291
65331
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
65292
65332
  const row = value;
@@ -65321,6 +65361,10 @@ function publicationForSnapshot(contractFile, contract) {
65321
65361
  const etag = tagOf(contract);
65322
65362
  const previous = readStored(contractFile);
65323
65363
  if (previous?.etag === etag) return { etag, storeRevision: previous.storeRevision };
65364
+ if (previous && previous.etag === supersededTagOf(contract)) {
65365
+ persist(contractFile, { version: 1, etag, storeRevision: previous.storeRevision });
65366
+ return { etag, storeRevision: previous.storeRevision };
65367
+ }
65324
65368
  const storeRevision = previous ? previous.storeRevision + 1 : 0;
65325
65369
  if (!Number.isSafeInteger(storeRevision)) throw new Error("working-contract storeRevision is exhausted");
65326
65370
  persist(contractFile, { version: 1, etag, storeRevision });
@@ -65935,6 +65979,49 @@ function withDeterministicFilterIds(document) {
65935
65979
  return copy;
65936
65980
  }
65937
65981
 
65982
+ // steel-shell-invariants.ts
65983
+ var SHELL_REGISTRATION_FIELDS = [
65984
+ "id",
65985
+ "sheet",
65986
+ "viewKind",
65987
+ "elevation_in",
65988
+ "pt_per_ft",
65989
+ "datum_at",
65990
+ "datum_ref",
65991
+ "control2_at",
65992
+ "control2_ref",
65993
+ "frame",
65994
+ "sourceRegistration"
65995
+ ];
65996
+ function planRegistrationOf(doc) {
65997
+ const plans = doc?.plans;
65998
+ if (!Array.isArray(plans)) return [];
65999
+ return plans.map((raw) => Object.fromEntries(
66000
+ SHELL_REGISTRATION_FIELDS.filter((key2) => raw && typeof raw === "object" && key2 in raw).map((key2) => [key2, raw[key2]])
66001
+ ));
66002
+ }
66003
+ function shellDeviations(shell, candidate) {
66004
+ const deviations = [];
66005
+ const compare = (invariant, detail, left, right) => {
66006
+ const shellHash = contractHash(left);
66007
+ const candidateHash = contractHash(right);
66008
+ if (shellHash !== candidateHash) deviations.push({ invariant, detail, shellHash, candidateHash });
66009
+ };
66010
+ compare(
66011
+ "grid",
66012
+ "the submitted model changed the saved grid",
66013
+ shell?.grid,
66014
+ candidate?.grid
66015
+ );
66016
+ compare(
66017
+ "registration",
66018
+ "the submitted model changed saved plan registration",
66019
+ planRegistrationOf(shell),
66020
+ planRegistrationOf(candidate)
66021
+ );
66022
+ return deviations;
66023
+ }
66024
+
65938
66025
  // steel-prepass-status.ts
65939
66026
  function hasSteelFilterCheckpoint(document) {
65940
66027
  if (!document || typeof document !== "object" || Array.isArray(document)) return false;
@@ -71725,6 +71812,19 @@ function evaluateSteelRead(context) {
71725
71812
  else if (!checkpointModeCanonical) add("filter-checkpoint", "block", "the saved Filter's match-on mode is empty or not canonical; reopen the Drawing Filter and save it again");
71726
71813
  else if (!checkpointControlValuesOk) add("filter-checkpoint", "block", "the saved Filter has a layer, thickness or colour control whose value is not a value for that control");
71727
71814
  else add("filter-checkpoint", "pass", "candidate uses the exact saved server-owned Filter");
71815
+ if (context.initialFilterCheckpoint) {
71816
+ const deviations = shellDeviations(context.current, candidate);
71817
+ if (deviations.length) {
71818
+ add(
71819
+ "shell-preserved",
71820
+ "block",
71821
+ `${deviations.map((deviation) => deviation.detail).join("; ")} \u2014 an initial read may fill the saved Drawing Filter checkpoint in, but may not restate it`,
71822
+ deviations.map((deviation) => `${deviation.invariant}: shell ${deviation.shellHash} vs candidate ${deviation.candidateHash}`)
71823
+ );
71824
+ } else {
71825
+ add("shell-preserved", "pass", "candidate preserves the saved grid and plan registration");
71826
+ }
71827
+ }
71728
71828
  const validation = validateSteelModelV2(candidate);
71729
71829
  if (!validation.valid) add("contract-validity", "block", `${validation.errors.length} v2 schema/semantic error(s)`, validation.errors.map((error) => `${error.path}: ${error.message}`));
71730
71830
  else add("contract-validity", "pass", "final candidate is valid steel.model/v2");
@@ -72274,16 +72374,14 @@ async function runNativeInitialRead(opts) {
72274
72374
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) throw new ContractTransactionError(`the first read requires a saved ${STEEL_V2} Drawing Filter shell and candidate`, "contract-type-unsupported");
72275
72375
  if (!isExactFilterCheckpointShell(current)) throw new ContractTransactionError("the first read requires the exact zero-model Drawing Filter checkpoint shell", "filter-checkpoint-not-empty");
72276
72376
  if (listVersions(opts.projectId).length) throw new ContractTransactionError("the initial read requires empty project history", "history-already-exists");
72277
- if (`"${contractHash(current)}"` !== opts.filterSavedEtag) throw new ContractTransactionError("the Drawing Filter changed after it was saved", "filter-changed");
72377
+ if (!recordedEtagNamesContract(opts.filterSavedEtag, etagsOf(current))) throw new ContractTransactionError("the Drawing Filter changed after it was saved", "filter-changed");
72278
72378
  const candidate = opts.candidate;
72279
72379
  const shell = current;
72280
72380
  const checked = validateSteelFilter(candidate, opts.source?.files.map((file) => file.sha256.toLowerCase()));
72281
72381
  if (!checked.ok) throw new ContractTransactionError("This filter no longer matches the attached drawing set. Reload the Drawing Filter and review it again.", "filter-invalid", checked.errors);
72282
72382
  if (contractHash(shell.filter) !== contractHash(candidate.filter)) throw new ContractTransactionError("the submitted model does not contain the exact saved Drawing Filter", "filter-changed");
72283
- if (contractHash(shell.grid) !== contractHash(candidate.grid)) throw new ContractTransactionError("the submitted model changed the saved grid", "shell-changed");
72284
- const fields = ["id", "sheet", "viewKind", "elevation_in", "pt_per_ft", "datum_at", "datum_ref", "control2_at", "control2_ref", "frame", "sourceRegistration"];
72285
- const registration = (doc) => (Array.isArray(doc.plans) ? doc.plans : []).map((raw) => Object.fromEntries(fields.filter((key2) => raw && typeof raw === "object" && key2 in raw).map((key2) => [key2, raw[key2]])));
72286
- if (contractHash(registration(shell)) !== contractHash(registration(candidate))) throw new ContractTransactionError("the submitted model changed saved plan registration", "shell-changed");
72383
+ const deviation = shellDeviations(shell, candidate)[0];
72384
+ if (deviation) throw new ContractTransactionError(deviation.detail, "shell-changed");
72287
72385
  const normalized = normalizeSteelMemberEndsForRead(opts.candidate);
72288
72386
  let readAuditReport;
72289
72387
  let storedReadAudit;
@@ -72294,6 +72392,11 @@ async function runNativeInitialRead(opts) {
72294
72392
  candidate: normalized.model,
72295
72393
  attestation: input.attestation,
72296
72394
  current,
72395
+ // Definitionally true here: this function refuses anything but an exact checkpoint shell with
72396
+ // empty history (above), which is the same pair of clauses the routes compute. The check can
72397
+ // only pass by the time it runs — the deviation throw is earlier — but the report is what the
72398
+ // receipt stores, and it must say the same thing the preview said (#962).
72399
+ initialFilterCheckpoint: true,
72297
72400
  normalization: normalized
72298
72401
  });
72299
72402
  if (readAuditReport.status !== "read-complete") {
@@ -72367,7 +72470,7 @@ async function runNativeRevisionRead(opts) {
72367
72470
  if (!current || declaredTypeOf(current) !== STEEL_V2 || declaredTypeOf(opts.candidate) !== STEEL_V2) {
72368
72471
  throw new ContractTransactionError(`a revision read requires an existing ${STEEL_V2} model and a ${STEEL_V2} candidate`, "contract-type-unsupported");
72369
72472
  }
72370
- if (`"${contractHash(current)}"` !== opts.expectedEtag) {
72473
+ if (!recordedEtagNamesContract(opts.expectedEtag, etagsOf(current))) {
72371
72474
  throw new ContractTransactionError("the model changed while this revision was being confirmed", "contract-changed");
72372
72475
  }
72373
72476
  if (opts.source?.readAudit) {
@@ -72753,12 +72856,18 @@ function acceptedContractIdentity(appId, projectId) {
72753
72856
  ctxFor({ appId, projectId, operation: "read" }, cached.contractType)
72754
72857
  );
72755
72858
  }
72756
- return { contractType: cached.contractType, contractEtag: cached.contractEtag };
72859
+ return {
72860
+ contractType: cached.contractType,
72861
+ contractEtag: cached.contractEtag,
72862
+ contractEtagSuperseded: cached.contractEtagSuperseded
72863
+ };
72757
72864
  }
72758
72865
  const contract = readAcceptedForRequest(appId, projectId, "read");
72866
+ const tags = etagsOf(contract);
72759
72867
  const identity = {
72760
72868
  contractType: contract == null ? void 0 : declaredTypeOf(contract),
72761
- contractEtag: etagOf(contract)
72869
+ contractEtag: tags.current,
72870
+ contractEtagSuperseded: tags.superseded
72762
72871
  };
72763
72872
  const after = signature();
72764
72873
  if (before === after) {
@@ -72767,14 +72876,17 @@ function acceptedContractIdentity(appId, projectId) {
72767
72876
  return identity;
72768
72877
  }
72769
72878
  }
72770
- return { contractType: void 0, contractEtag: null };
72879
+ return { contractType: void 0, contractEtag: null, contractEtagSuperseded: null };
72771
72880
  }
72772
72881
  function etagOf(doc) {
72773
- return doc == null ? null : `"${contractHash(doc)}"`;
72882
+ return doc == null ? null : `"${contractIdentityHash(doc)}"`;
72774
72883
  }
72775
72884
  function storeEtag(appId, projectId) {
72776
72885
  return etagOf(readContract(appId, projectId));
72777
72886
  }
72887
+ function storeEtags(appId, projectId) {
72888
+ return etagsOf(readContract(appId, projectId));
72889
+ }
72778
72890
  function storedContractBytesExist(appId, projectId) {
72779
72891
  return (0, import_node_fs41.existsSync)(contractPath(appId, projectId));
72780
72892
  }
@@ -72832,7 +72944,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72832
72944
  return withLifecycleLock(kind, key2, () => {
72833
72945
  assertServable(projectId);
72834
72946
  const current = readContract(appId, projectId);
72835
- const currentTag = etagOf(current);
72947
+ const currentTags = etagsOf(current);
72836
72948
  if (pre.ifNoneMatch === "*" && current != null) {
72837
72949
  throw new PreconditionFailedError(
72838
72950
  "this store already holds a contract \u2014 GET it and send `If-Match: <the ETag>` as the only precondition to replace it"
@@ -72844,7 +72956,7 @@ async function writeContractChecked(appId, doc, projectId, origin) {
72844
72956
  "this store holds no contract to replace \u2014 send `If-None-Match: *` as the only precondition to create one"
72845
72957
  );
72846
72958
  }
72847
- if (pre.ifMatch !== "*" && pre.ifMatch !== currentTag) {
72959
+ if (pre.ifMatch !== "*" && !recordedEtagNamesContract(pre.ifMatch, currentTags)) {
72848
72960
  throw new PreconditionFailedError(
72849
72961
  "the contract changed since you last read it \u2014 GET it again, re-apply your edit to that document, and write with the new `If-Match: <the ETag>`"
72850
72962
  );
@@ -76409,21 +76521,24 @@ function steelExclusionPreflight(ledger, filter) {
76409
76521
  }
76410
76522
 
76411
76523
  // revision-request-view.ts
76412
- function filterCheckpointMatchesCurrent(request, currentEtag) {
76413
- return request.type === "revision-read" && request.settledVersion === void 0 && request.prepassReady === true && request.filterSaved === true && typeof request.filterSavedEtag === "string" && request.filterSavedEtag.length > 0 && request.filterSavedEtag === currentEtag;
76524
+ function contractEtagsOf(facts) {
76525
+ return { current: facts?.contractEtag ?? null, superseded: facts?.contractEtagSuperseded ?? null };
76414
76526
  }
76415
- function filterCheckpointIsCurrent(request, currentEtag) {
76416
- return request.status === "pending" && filterCheckpointMatchesCurrent(request, currentEtag);
76527
+ function filterCheckpointMatchesCurrent(request, current) {
76528
+ return request.type === "revision-read" && request.settledVersion === void 0 && request.prepassReady === true && request.filterSaved === true && typeof request.filterSavedEtag === "string" && request.filterSavedEtag.length > 0 && recordedEtagNamesContract(request.filterSavedEtag, current);
76529
+ }
76530
+ function filterCheckpointIsCurrent(request, current) {
76531
+ return request.status === "pending" && filterCheckpointMatchesCurrent(request, current);
76417
76532
  }
76418
76533
  function acceptedContractFacts(appId, projectId) {
76419
76534
  try {
76420
76535
  return acceptedContractIdentity(appId, projectId);
76421
76536
  } catch {
76422
- return { contractType: void 0, contractEtag: null };
76537
+ return { contractType: void 0, contractEtag: null, contractEtagSuperseded: null };
76423
76538
  }
76424
76539
  }
76425
- function acceptedContractEtag(appId, projectId) {
76426
- return acceptedContractFacts(appId, projectId).contractEtag;
76540
+ function acceptedContractEtags(appId, projectId) {
76541
+ return contractEtagsOf(acceptedContractFacts(appId, projectId));
76427
76542
  }
76428
76543
  function revisionRequestStageId(request) {
76429
76544
  if (request.type !== "revision-read" || request.status !== "staged" || !request.project) return void 0;
@@ -76436,7 +76551,10 @@ function revisionRequestStageId(request) {
76436
76551
  function revisionRequestViewFields(request, memo = {}) {
76437
76552
  const discard = request.type === "revision-read" && request.status === "staged" ? revisionDiscardPolicyFor(request) : void 0;
76438
76553
  const contractFacts = request.type === "revision-read" && request.appId && request.project ? (memo.contractFacts ?? acceptedContractFacts)(request.appId, request.project) : void 0;
76554
+ const etags = contractEtagsOf(contractFacts);
76555
+ const canonicalCheckpointEtag = request.type === "revision-read" && request.appId && request.project && filterCheckpointMatchesCurrent(request, etags) && etags.current ? etags.current : void 0;
76439
76556
  return {
76557
+ ...canonicalCheckpointEtag ? { filterSavedEtag: canonicalCheckpointEtag } : {},
76440
76558
  appTemplateId: request.appId ? (memo.templateId ?? resolveTemplateId)(request.appId) : void 0,
76441
76559
  nativeSteelReady: request.type === "revision-read" && request.appId && request.project ? (() => {
76442
76560
  const project = getProject(request.project);
@@ -76448,10 +76566,7 @@ function revisionRequestViewFields(request, memo = {}) {
76448
76566
  canDiscardRevision: discard?.canClear,
76449
76567
  discardWhy: discard?.clearWhy,
76450
76568
  discardState: discard?.clearState,
76451
- filterCheckpointCurrent: request.type === "revision-read" && request.appId && request.project ? filterCheckpointIsCurrent(
76452
- request,
76453
- contractFacts?.contractEtag ?? null
76454
- ) : void 0
76569
+ filterCheckpointCurrent: request.type === "revision-read" && request.appId && request.project ? filterCheckpointIsCurrent(request, etags) : void 0
76455
76570
  };
76456
76571
  }
76457
76572
  function enrichedRevisionRequestView(request, extra, memo = {}) {
@@ -76673,7 +76788,7 @@ function loadAuthoritativeSteelAuditState(project, requestId, attestation, allow
76673
76788
  })) throw new SteelAuditStateError("steel-source-manifest-changed", "the verified project source bytes no longer match the manifest");
76674
76789
  const parsedAttestation = parseSteelReadAttestation(attestation);
76675
76790
  const current = readAcceptedForRequest(project.app, project.id, "read");
76676
- if (!filterCheckpointMatchesCurrent(request, etagOf(current))) {
76791
+ if (!filterCheckpointMatchesCurrent(request, etagsOf(current))) {
76677
76792
  throw new SteelAuditStateError("steel-filter-save-missing", "the request has no current exact Filter Save checkpoint");
76678
76793
  }
76679
76794
  return {
@@ -76682,7 +76797,13 @@ function loadAuthoritativeSteelAuditState(project, requestId, attestation, allow
76682
76797
  attestation: parsedAttestation,
76683
76798
  current,
76684
76799
  baseVersion: request.baseVersion ?? 0,
76685
- baseHash: current == null ? null : etagOf(current)?.replace(/^"|"$/g, "") ?? null
76800
+ baseHash: current == null ? null : etagOf(current)?.replace(/^"|"$/g, "") ?? null,
76801
+ // Whether the publish gate will hold this candidate to the shell invariants, computed HERE so both
76802
+ // `evaluateSteelRead` call sites get the one answer (#962). The expression is the initial-read
76803
+ // dispatch condition of the commit route, which is what makes the audit's verdict predict the
76804
+ // publish's: same question, same two clauses. A revision read gets `false` and is not asked to
76805
+ // preserve a grid it is entitled to rewrite.
76806
+ initialFilterCheckpoint: (listVersions(project.id)[0]?.n ?? 0) === 0 && isExactFilterCheckpointShell(current)
76686
76807
  };
76687
76808
  }
76688
76809
  function preparedManifestNeedsRegeneration(project, request) {
@@ -76763,7 +76884,7 @@ async function stageForReview(reply, project, requestId, candidate, filterSavedE
76763
76884
  }
76764
76885
  const candidateDoc = candidate;
76765
76886
  const currentDoc = current;
76766
- if (!filterSavedEtag || etagOf(current) !== filterSavedEtag) {
76887
+ if (!recordedEtagNamesContract(filterSavedEtag, etagsOf(current))) {
76767
76888
  return reply.status(409).send({ ok: false, code: "filter-save-changed", error: "the model changed after the Drawing Filter was saved \xE2\u20AC\u201D reload and save it again" });
76768
76889
  }
76769
76890
  if (contractHash(currentDoc.filter) !== contractHash(candidateDoc.filter)) {
@@ -76814,6 +76935,7 @@ async function stageForReviewAudited(reply, project, requestId, candidateInput,
76814
76935
  candidate,
76815
76936
  attestation: state2.attestation,
76816
76937
  current: state2.current,
76938
+ initialFilterCheckpoint: state2.initialFilterCheckpoint,
76817
76939
  normalization: normalized
76818
76940
  });
76819
76941
  if (report.status === "blocked") {
@@ -77664,8 +77786,8 @@ function registerRevisionRoutes(app, deps = {}) {
77664
77786
  async (req, reply) => withLifecycleLock("project", req.params.id, async () => {
77665
77787
  const project = getProject(req.params.id);
77666
77788
  const request = getRequest(req.params.reqId);
77667
- const currentEtag = project ? acceptedContractEtag(project.app, project.id) : null;
77668
- if (!project || !request || request.type !== "revision-read" || request.project !== project.id || !filterCheckpointIsCurrent(request, currentEtag)) {
77789
+ const currentEtags = project ? acceptedContractEtags(project.app, project.id) : { current: null, superseded: null };
77790
+ if (!project || !request || request.type !== "revision-read" || request.project !== project.id || !filterCheckpointIsCurrent(request, currentEtags)) {
77669
77791
  return reply.status(404).send({ ok: false, error: "unknown active drawing read" });
77670
77792
  }
77671
77793
  let progress;
@@ -77707,9 +77829,11 @@ function registerRevisionRoutes(app, deps = {}) {
77707
77829
  if (!project || !request || request.type !== "revision-read" || request.project !== project.id || request.status !== "pending" || request.settledVersion !== void 0) {
77708
77830
  return reply.status(404).send({ ok: false, error: "unknown pending revision request" });
77709
77831
  }
77710
- const etag = typeof req.body?.etag === "string" ? req.body.etag : "";
77832
+ const supplied = typeof req.body?.etag === "string" ? req.body.etag : "";
77711
77833
  const current = readAcceptedForRequest(project.app, project.id, "read");
77712
- if (!request.prepassReady || !etag || etag !== etagOf(current) || !hasSteelFilterCheckpoint(current)) return reply.status(409).send({ ok: false, error: "save the populated Steel Filter that this request pre-read before continuing" });
77834
+ const currentTags = etagsOf(current);
77835
+ if (!request.prepassReady || !recordedEtagNamesContract(supplied, currentTags) || !hasSteelFilterCheckpoint(current)) return reply.status(409).send({ ok: false, error: "save the populated Steel Filter that this request pre-read before continuing" });
77836
+ const etag = currentTags.current;
77713
77837
  if (req.body?.layerSignOff !== void 0) {
77714
77838
  return reply.status(400).send({
77715
77839
  ok: false,
@@ -77899,6 +78023,7 @@ function registerRevisionRoutes(app, deps = {}) {
77899
78023
  candidate,
77900
78024
  attestation: state2.attestation,
77901
78025
  current: state2.current,
78026
+ initialFilterCheckpoint: state2.initialFilterCheckpoint,
77902
78027
  normalization: normalized
77903
78028
  });
77904
78029
  const normalization = {
@@ -78007,15 +78132,15 @@ function registerRevisionRoutes(app, deps = {}) {
78007
78132
  error: "resume this read with If-Match set to the ETag recorded by the Steel Filter Save"
78008
78133
  });
78009
78134
  }
78010
- if (!ifMatchTags.includes(request.filterSavedEtag)) {
78135
+ const liveTags = etagsOf(readAcceptedForRequest(project.app, project.id, "read"));
78136
+ if (!recordedEtagNamesContract(request.filterSavedEtag, liveTags)) {
78011
78137
  return reply.status(412).send({
78012
78138
  ok: false,
78013
78139
  code: "filter-save-changed",
78014
78140
  error: "the Steel Filter contract changed after Save \u2014 re-read it before committing this revision"
78015
78141
  });
78016
78142
  }
78017
- const liveEtag = etagOf(readAcceptedForRequest(project.app, project.id, "read"));
78018
- if (!liveEtag || !ifMatchTags.includes(liveEtag)) {
78143
+ if (!ifMatchTags.some((tag) => recordedEtagNamesContract(tag, liveTags))) {
78019
78144
  return reply.status(412).send({ ok: false, code: "filter-save-changed", error: "the contract changed after Steel Filter Save \u2014 re-read it before committing this revision" });
78020
78145
  }
78021
78146
  }
@@ -78032,7 +78157,7 @@ function registerRevisionRoutes(app, deps = {}) {
78032
78157
  }
78033
78158
  const appTemplateId = resolveTemplateId(project.app);
78034
78159
  const candidateType = declaredTypeOf(req.body.contract);
78035
- if (appTemplateId === "steel-model" && !filterCheckpointMatchesCurrent(request, etagOf(currentForEvidence))) {
78160
+ if (appTemplateId === "steel-model" && !filterCheckpointMatchesCurrent(request, etagsOf(currentForEvidence))) {
78036
78161
  return reply.status(409).send({
78037
78162
  ok: false,
78038
78163
  error: "complete this request's Steel Filter pre-read, then review and Save the Filter before committing the read"
@@ -78575,43 +78700,456 @@ function registerRevisionRoutes(app, deps = {}) {
78575
78700
  );
78576
78701
  }
78577
78702
 
78578
- // member-end-resolution-store.ts
78703
+ // workspace-approved-snapshot.ts
78704
+ var WorkspaceSnapshotError = class extends Error {
78705
+ constructor(status, message, notReviewable, version) {
78706
+ super(message);
78707
+ this.status = status;
78708
+ this.notReviewable = notReviewable;
78709
+ this.version = version;
78710
+ }
78711
+ status;
78712
+ notReviewable;
78713
+ version;
78714
+ };
78715
+ var NoApprovedVersionError = class extends WorkspaceSnapshotError {
78716
+ constructor() {
78717
+ super(409, "project has no approved version");
78718
+ this.name = "NoApprovedVersionError";
78719
+ }
78720
+ };
78721
+ function approvedRows(projectId) {
78722
+ const project = getProject(projectId);
78723
+ if (!project) return [];
78724
+ const allRows = listVersions(projectId);
78725
+ if (project.uuid) {
78726
+ const tainted = allRows.find((v) => v.gate === "model" && v.kind === "approve" && !v.approval);
78727
+ if (tainted) {
78728
+ throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`, void 0, tainted.n);
78729
+ }
78730
+ }
78731
+ const projectTime = Date.parse(project.createdAt);
78732
+ return allRows.filter((v) => v.gate === "model" && v.kind === "approve").filter((v) => v.approval ? !!project.uuid && v.approval.projectUuid === project.uuid : Number.isFinite(projectTime) && Date.parse(v.ts) >= projectTime).map(({ current: _current, ...meta }) => meta);
78733
+ }
78734
+ function latestApprovedVersion(projectId) {
78735
+ return approvedRows(projectId)[0] ?? null;
78736
+ }
78737
+ function listApprovedVersionMetadata(projectId) {
78738
+ return approvedRows(projectId);
78739
+ }
78740
+ function currentApprovedSnapshot(projectId, version) {
78741
+ const project = getProject(projectId);
78742
+ if (!project) throw new WorkspaceSnapshotError(404, `unknown project: ${projectId}`);
78743
+ const rows2 = approvedRows(projectId);
78744
+ const row = version === void 0 ? rows2[0] : rows2.find((v) => v.n === version);
78745
+ if (!row) {
78746
+ if (version === void 0) throw new NoApprovedVersionError();
78747
+ throw new WorkspaceSnapshotError(404, `approved version not found: ${version}`);
78748
+ }
78749
+ const latest = rows2[0];
78750
+ const assertOwned = (candidate, hash3) => {
78751
+ if (candidate.approval) {
78752
+ if (!project.uuid || candidate.approval.projectUuid !== project.uuid) {
78753
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} belongs to another project incarnation`);
78754
+ }
78755
+ if (candidate.approval.candidateHash !== hash3) {
78756
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} failed its content-hash proof`);
78757
+ }
78758
+ return;
78759
+ }
78760
+ const rowTime = Date.parse(candidate.ts);
78761
+ const projectTime = Date.parse(project.createdAt);
78762
+ if (!Number.isFinite(rowTime) || !Number.isFinite(projectTime) || rowTime < projectTime) {
78763
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} has no ownership proof`);
78764
+ }
78765
+ };
78766
+ const contract = readAcceptedVersion(projectId, row.n, { appId: project.app, projectId, operation: "read" });
78767
+ if (contract == null) throw new WorkspaceSnapshotError(409, `approved version ${row.n} is unreadable`);
78768
+ const selectedHash = contractHash(contract);
78769
+ assertOwned(row, selectedHash);
78770
+ const latestContract = latest.n === row.n ? contract : readAcceptedVersion(projectId, latest.n, { appId: project.app, projectId, operation: "read" });
78771
+ if (latestContract == null) throw new WorkspaceSnapshotError(409, `approved version ${latest.n} is unreadable`);
78772
+ const latestHash = contractHash(latestContract);
78773
+ assertOwned(latest, latestHash);
78774
+ const draft = readAcceptedForRequest(project.app, projectId, "read");
78775
+ const comparable = comparableContractHash;
78776
+ const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
78777
+ return {
78778
+ project,
78779
+ version: row,
78780
+ contract,
78781
+ contractHash: selectedHash,
78782
+ currentApprovedAt: project.approvedAt ?? null,
78783
+ dirtySinceApproval,
78784
+ latestApprovedVersion: latest.n,
78785
+ headDiverged: row.n !== latest.n
78786
+ };
78787
+ }
78788
+ function approvedSnapshotForMetadata(projectId, surface, onRefusal) {
78789
+ try {
78790
+ return currentApprovedSnapshot(projectId);
78791
+ } catch (error) {
78792
+ if (error instanceof NoApprovedVersionError) return null;
78793
+ if (error instanceof WorkspaceSnapshotError && error.status === 404) throw error;
78794
+ if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
78795
+ const status = error instanceof WorkspaceSnapshotError ? error.status : error.code;
78796
+ onRefusal?.(error);
78797
+ console.error(
78798
+ `${surface}: project ${projectId} has an approved version the gate refused to serve (${status}) \u2014 reporting no approved head. ${error.message}`
78799
+ );
78800
+ return null;
78801
+ }
78802
+ throw error;
78803
+ }
78804
+ }
78805
+
78806
+ // working-revision-manifest.ts
78579
78807
  var import_node_crypto32 = require("node:crypto");
78580
78808
  var import_node_fs47 = require("node:fs");
78581
78809
  var import_node_path42 = require("node:path");
78810
+ var nativePublicationIdentity = (projectUuid) => `project:${projectUuid}`;
78811
+ var pathOf = (projectId) => (0, import_node_path42.join)(projectDir(projectId), ".floless-working-revision-state-v1.json");
78812
+ var checksumOf = (body) => hashOf(body);
78813
+ function bodyOf(value) {
78814
+ const { checksum: _checksum, ...body } = value;
78815
+ return body;
78816
+ }
78817
+ function assertProject(project) {
78818
+ if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
78819
+ return project.uuid;
78820
+ }
78821
+ function readWorkingRevisionManifest(project) {
78822
+ const uuid = assertProject(project);
78823
+ try {
78824
+ const value = JSON.parse((0, import_node_fs47.readFileSync)(pathOf(project.id), "utf8"));
78825
+ if (value?.schema !== 1 || value.projectUuid !== uuid || !Number.isInteger(value.epoch) || value.epoch < 0) return null;
78826
+ return checksumOf(bodyOf(value)) === value.checksum ? value : null;
78827
+ } catch {
78828
+ return null;
78829
+ }
78830
+ }
78831
+ function ensureWorkingRevisionManifest(input) {
78832
+ const existing = readWorkingRevisionManifest(input.project);
78833
+ if (existing) return existing;
78834
+ const body = {
78835
+ schema: 1,
78836
+ projectUuid: assertProject(input.project),
78837
+ publicationIdentity: input.publicationIdentity,
78838
+ revisionId: (0, import_node_crypto32.randomUUID)(),
78839
+ epoch: 0,
78840
+ source: { kind: "working" },
78841
+ workingBase: input.workingBase,
78842
+ draftHash: hashOf(input.contract),
78843
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
78844
+ };
78845
+ const value = { ...body, checksum: checksumOf(body) };
78846
+ (0, import_node_fs47.mkdirSync)(projectDir(input.project.id), { recursive: true });
78847
+ if (!(0, import_node_fs47.existsSync)(pathOf(input.project.id))) writeJsonAtomic(pathOf(input.project.id), value);
78848
+ return readWorkingRevisionManifest(input.project) ?? value;
78849
+ }
78850
+ function advanceWorkingRevisionManifest(input) {
78851
+ const current = readWorkingRevisionManifest(input.project);
78852
+ if (!current) throw new Error("working revision state is missing or corrupt");
78853
+ if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
78854
+ throw new Error("working revision changed; reload before continuing");
78855
+ }
78856
+ if (current.publicationIdentity !== input.publicationIdentity) throw new Error("working revision belongs to another app publication");
78857
+ const body = {
78858
+ ...bodyOf(current),
78859
+ revisionId: (0, import_node_crypto32.randomUUID)(),
78860
+ epoch: current.epoch + 1,
78861
+ source: input.source,
78862
+ workingBase: input.workingBase,
78863
+ draftHash: hashOf(input.contract),
78864
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
78865
+ };
78866
+ const value = { ...body, checksum: checksumOf(body) };
78867
+ writeJsonAtomic(pathOf(input.project.id), value);
78868
+ return value;
78869
+ }
78870
+ function refreshWorkingDraftHash(input) {
78871
+ const current = readWorkingRevisionManifest(input.project);
78872
+ if (!current) throw new Error("working revision state is missing or corrupt");
78873
+ if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
78874
+ throw new Error("working revision changed; reload before saving");
78875
+ }
78876
+ const body = { ...bodyOf(current), draftHash: hashOf(input.contract), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
78877
+ const value = { ...body, checksum: checksumOf(body) };
78878
+ writeJsonAtomic(pathOf(input.project.id), value);
78879
+ return value;
78880
+ }
78881
+
78882
+ // project-checkpoints-store.ts
78883
+ var import_node_crypto33 = require("node:crypto");
78884
+ var import_node_fs48 = require("node:fs");
78885
+ var import_node_path43 = require("node:path");
78886
+ var HASH_RE3 = /^[0-9a-f]{64}$/;
78887
+ function root5(projectId) {
78888
+ return (0, import_node_path43.join)(projectDir(projectId), ".floless-checkpoints-store-v1");
78889
+ }
78890
+ var objectsDir2 = (projectId) => (0, import_node_path43.join)(root5(projectId), "objects");
78891
+ var eventsPath = (projectId) => (0, import_node_path43.join)(root5(projectId), "events.json");
78892
+ function readEvents(projectId) {
78893
+ try {
78894
+ const parsed = JSON.parse((0, import_node_fs48.readFileSync)(eventsPath(projectId), "utf8"));
78895
+ if (parsed?.schema !== 1 || !Array.isArray(parsed.events)) return { schema: 1, events: [] };
78896
+ return { schema: 1, events: parsed.events.filter(validEvent) };
78897
+ } catch {
78898
+ return { schema: 1, events: [] };
78899
+ }
78900
+ }
78901
+ function validEvent(value) {
78902
+ if (!value || typeof value !== "object") return false;
78903
+ const e = value;
78904
+ return typeof e.eventId === "string" && typeof e.checkpointId === "string" && HASH_RE3.test(e.checkpointId) && (e.kind === "captured" || e.kind === "archived" || e.kind === "incorporated") && typeof e.at === "string" && Number.isInteger(e.revisionEpoch) && typeof e.appIdAtCapture === "string";
78905
+ }
78906
+ function readContent(projectId, id) {
78907
+ if (!HASH_RE3.test(id)) return null;
78908
+ try {
78909
+ const value = JSON.parse((0, import_node_fs48.readFileSync)((0, import_node_path43.join)(objectsDir2(projectId), `${id}.json`), "utf8"));
78910
+ if (value?.schema !== 1 || value.id !== id || hashCheckpoint(value) !== id) return null;
78911
+ return value;
78912
+ } catch {
78913
+ return null;
78914
+ }
78915
+ }
78916
+ function hashCheckpoint(value) {
78917
+ const { id: _id, ...identity } = value;
78918
+ return hashOf(identity);
78919
+ }
78920
+ function requireIdentity(project) {
78921
+ if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
78922
+ return project.uuid;
78923
+ }
78924
+ function appendEvent(projectId, event) {
78925
+ (0, import_node_fs48.mkdirSync)(root5(projectId), { recursive: true });
78926
+ const log2 = readEvents(projectId);
78927
+ const row = { ...event, eventId: (0, import_node_crypto33.randomUUID)(), at: (/* @__PURE__ */ new Date()).toISOString() };
78928
+ log2.events.push(row);
78929
+ writeJsonAtomic(eventsPath(projectId), log2);
78930
+ return row;
78931
+ }
78932
+ function captureProjectCheckpoint(input) {
78933
+ const projectUuid = requireIdentity(input.project);
78934
+ const withoutId = {
78935
+ schema: 1,
78936
+ projectUuid,
78937
+ publicationIdentity: input.publicationIdentity,
78938
+ base: input.base,
78939
+ draftHash: hashOf(input.contract),
78940
+ contract: input.contract
78941
+ };
78942
+ const id = hashCheckpoint(withoutId);
78943
+ (0, import_node_fs48.mkdirSync)(objectsDir2(input.project.id), { recursive: true });
78944
+ const path = (0, import_node_path43.join)(objectsDir2(input.project.id), `${id}.json`);
78945
+ if (!(0, import_node_fs48.existsSync)(path)) writeJsonAtomic(path, { ...withoutId, id });
78946
+ const event = appendEvent(input.project.id, {
78947
+ checkpointId: id,
78948
+ kind: "captured",
78949
+ revisionEpoch: input.revisionEpoch,
78950
+ appIdAtCapture: input.project.app
78951
+ });
78952
+ return describe(input.project.id, { ...withoutId, id }, event.eventId);
78953
+ }
78954
+ function describe(projectId, content, latestEventId) {
78955
+ const events = readEvents(projectId).events.filter((event) => event.checkpointId === content.id);
78956
+ const captures = events.filter((event) => event.kind === "captured");
78957
+ const first = captures[0];
78958
+ const latest = events.at(-1);
78959
+ if (!first || !latest) return null;
78960
+ return {
78961
+ ...content,
78962
+ capturedAt: first.at,
78963
+ archived: latest.kind === "archived",
78964
+ incorporated: events.some((event) => event.kind === "incorporated"),
78965
+ captureCount: captures.length,
78966
+ latestEventId: latestEventId ?? latest.eventId
78967
+ };
78968
+ }
78969
+ function listProjectCheckpoints(project) {
78970
+ const uuid = requireIdentity(project);
78971
+ const ids = [...new Set(readEvents(project.id).events.map((event) => event.checkpointId))];
78972
+ return ids.map((id) => readContent(project.id, id)).filter((v) => v !== null).filter((v) => v.projectUuid === uuid).map((v) => describe(project.id, v)).filter((v) => v !== null).sort((a, b) => b.capturedAt.localeCompare(a.capturedAt));
78973
+ }
78974
+ function readProjectCheckpoint(project, checkpointId) {
78975
+ const content = readContent(project.id, checkpointId);
78976
+ return content && content.projectUuid === requireIdentity(project) ? describe(project.id, content) : null;
78977
+ }
78978
+ function markProjectCheckpoint(project, checkpointId, kind, expectedEventId) {
78979
+ const current = readProjectCheckpoint(project, checkpointId);
78980
+ if (!current) throw new Error(`unknown checkpoint: ${checkpointId}`);
78981
+ if (current.latestEventId !== expectedEventId) throw new Error("checkpoint changed; reload saved work");
78982
+ const event = appendEvent(project.id, { checkpointId, kind, revisionEpoch: 0, appIdAtCapture: project.app });
78983
+ return describe(project.id, current, event.eventId);
78984
+ }
78985
+
78986
+ // project-revision-start-routes.ts
78987
+ function registerProjectRevisionStartRoutes(app, deps) {
78988
+ const { broadcast: broadcast2 } = deps;
78989
+ app.post(
78990
+ "/api/projects/:id/revisions/start",
78991
+ async (req, reply) => {
78992
+ const project = getProject(req.params.id);
78993
+ if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
78994
+ const version = Number(req.body?.version);
78995
+ if (!Number.isInteger(version) || version < 1) return reply.status(400).send({ ok: false, error: "choose a valid approved version" });
78996
+ return withLifecycleLock("project", project.id, async () => {
78997
+ let target;
78998
+ try {
78999
+ target = currentApprovedSnapshot(project.id, version);
79000
+ } catch (error) {
79001
+ if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
79002
+ throw error;
79003
+ }
79004
+ const current = readAcceptedForRequest(project.app, project.id, "read");
79005
+ if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
79006
+ const actualEtags = storeEtags(project.app, project.id);
79007
+ const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
79008
+ if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
79009
+ return reply.status(428).send({ ok: false, error: "Reload History and send the working ETag and revision epoch." });
79010
+ }
79011
+ if (!recordedEtagNamesContract(req.body.expectedEtag, actualEtags)) {
79012
+ return reply.status(409).send({ ok: false, error: "The working copy changed. Reload History before starting." });
79013
+ }
79014
+ const observedManifest = readWorkingRevisionManifest(project);
79015
+ if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) {
79016
+ return reply.status(409).send({ ok: false, error: "The working revision changed. Reload History before starting." });
79017
+ }
79018
+ const publicationIdentity = observedManifest?.publicationIdentity ?? nativePublicationIdentity(project.uuid);
79019
+ let manifest = ensureWorkingRevisionManifest({
79020
+ project,
79021
+ publicationIdentity,
79022
+ contract: current,
79023
+ workingBase: { version: target.latestApprovedVersion, hash: currentApprovedSnapshot(project.id).contractHash }
79024
+ });
79025
+ if (manifest.draftHash !== contractHash(current)) {
79026
+ manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
79027
+ }
79028
+ const latest = currentApprovedSnapshot(project.id);
79029
+ const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
79030
+ const checkpoint = dirty ? captureProjectCheckpoint({
79031
+ project,
79032
+ publicationIdentity,
79033
+ base: manifest.workingBase,
79034
+ contract: current,
79035
+ revisionEpoch: manifest.epoch
79036
+ }) : null;
79037
+ let publication = null;
79038
+ try {
79039
+ const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
79040
+ publication = written;
79041
+ } catch (error) {
79042
+ if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
79043
+ throw error;
79044
+ }
79045
+ clearApproval(project.id);
79046
+ const next = advanceWorkingRevisionManifest({
79047
+ project,
79048
+ expectedEpoch: manifest.epoch,
79049
+ expectedDraftHash: manifest.draftHash,
79050
+ publicationIdentity,
79051
+ contract: normalisePlanViewIds(target.contract),
79052
+ // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
79053
+ // `source.hash` names the version this came from — while `contract:` above is the document the
79054
+ // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
79055
+ // stored canonically made the manifest disagree with the store the instant it was written.
79056
+ source: { kind: "approved", version, hash: target.contractHash },
79057
+ workingBase: { version, hash: target.contractHash }
79058
+ });
79059
+ broadcast2(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
79060
+ return {
79061
+ ok: true,
79062
+ checkpoint,
79063
+ revision: next,
79064
+ workingBaseVersion: version,
79065
+ latestApprovedVersion: latest.version.n,
79066
+ message: checkpoint ? `Saved pending work${checkpoint.base ? ` from v${checkpoint.base.version}` : ""}. Started a DRAFT from v${version}.` : `Started a DRAFT from v${version}.`
79067
+ };
79068
+ }, { label: `starting a revision from v${version}` });
79069
+ }
79070
+ );
79071
+ app.post(
79072
+ "/api/projects/:id/checkpoints/:checkpointId/resume",
79073
+ async (req, reply) => {
79074
+ const project = getProject(req.params.id);
79075
+ if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
79076
+ return withLifecycleLock("project", project.id, async () => {
79077
+ const saved = readProjectCheckpoint(project, req.params.checkpointId);
79078
+ if (!saved) return reply.status(404).send({ ok: false, error: "checkpoint not found" });
79079
+ const current = readAcceptedForRequest(project.app, project.id, "read");
79080
+ if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
79081
+ const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
79082
+ if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
79083
+ return reply.status(428).send({ ok: false, error: "Reload Saved work and send the working ETag and revision epoch." });
79084
+ }
79085
+ if (!recordedEtagNamesContract(req.body.expectedEtag, storeEtags(project.app, project.id))) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
79086
+ const observedManifest = readWorkingRevisionManifest(project);
79087
+ if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) return reply.status(409).send({ ok: false, error: "The working revision changed. Reload Saved work." });
79088
+ const publicationIdentity = saved.publicationIdentity;
79089
+ let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
79090
+ if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
79091
+ const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
79092
+ if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
79093
+ let publication;
79094
+ try {
79095
+ publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
79096
+ } catch (error) {
79097
+ return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
79098
+ }
79099
+ clearApproval(project.id);
79100
+ const next = advanceWorkingRevisionManifest({
79101
+ project,
79102
+ expectedEpoch: manifest.epoch,
79103
+ expectedDraftHash: manifest.draftHash,
79104
+ publicationIdentity,
79105
+ contract: normalisePlanViewIds(saved.contract),
79106
+ source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
79107
+ workingBase: saved.base
79108
+ });
79109
+ broadcast2(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
79110
+ return { ok: true, revision: next, checkpoint: saved, latestApprovedVersion: latest?.version.n ?? null };
79111
+ }, { label: "resuming saved work" });
79112
+ }
79113
+ );
79114
+ }
79115
+
79116
+ // member-end-resolution-store.ts
79117
+ var import_node_crypto34 = require("node:crypto");
79118
+ var import_node_fs49 = require("node:fs");
79119
+ var import_node_path44 = require("node:path");
78582
79120
  var VERSION = 1;
78583
79121
  var RETAIN_MAX = 100;
78584
79122
  var RETAIN_MS = 30 * 24 * 60 * 60 * 1e3;
78585
79123
  var contentHash = (value) => `sha256:${hashOf(value)}`;
78586
- var storeRoot = (projectId) => (0, import_node_path42.join)(projectDir(projectId), ".member-end-resolution");
78587
- var artifactRoot = (projectId) => (0, import_node_path42.join)(storeRoot(projectId), "artifacts");
78588
- var registryPath = (projectId) => (0, import_node_path42.join)(storeRoot(projectId), "tokens.json");
79124
+ var storeRoot = (projectId) => (0, import_node_path44.join)(projectDir(projectId), ".member-end-resolution");
79125
+ var artifactRoot = (projectId) => (0, import_node_path44.join)(storeRoot(projectId), "artifacts");
79126
+ var registryPath = (projectId) => (0, import_node_path44.join)(storeRoot(projectId), "tokens.json");
78589
79127
  function atomicJson(path, value) {
78590
- const temp = `${path}.${process.pid}.${(0, import_node_crypto32.randomUUID)()}.tmp`;
78591
- (0, import_node_fs47.writeFileSync)(temp, JSON.stringify(value));
78592
- (0, import_node_fs47.renameSync)(temp, path);
79128
+ const temp = `${path}.${process.pid}.${(0, import_node_crypto34.randomUUID)()}.tmp`;
79129
+ (0, import_node_fs49.writeFileSync)(temp, JSON.stringify(value));
79130
+ (0, import_node_fs49.renameSync)(temp, path);
78593
79131
  }
78594
79132
  function readRegistry(projectId) {
78595
79133
  const path = registryPath(projectId);
78596
- if (!(0, import_node_fs47.existsSync)(path)) return { version: VERSION, tokens: [] };
79134
+ if (!(0, import_node_fs49.existsSync)(path)) return { version: VERSION, tokens: [] };
78597
79135
  try {
78598
- const value = JSON.parse((0, import_node_fs47.readFileSync)(path, "utf8"));
79136
+ const value = JSON.parse((0, import_node_fs49.readFileSync)(path, "utf8"));
78599
79137
  return value?.version === VERSION && Array.isArray(value.tokens) ? value : { version: VERSION, tokens: [] };
78600
79138
  } catch {
78601
79139
  return { version: VERSION, tokens: [] };
78602
79140
  }
78603
79141
  }
78604
79142
  function persistRegistry(projectId, registry2) {
78605
- (0, import_node_fs47.mkdirSync)(storeRoot(projectId), { recursive: true });
79143
+ (0, import_node_fs49.mkdirSync)(storeRoot(projectId), { recursive: true });
78606
79144
  const now = Date.now();
78607
79145
  const retained = registry2.tokens.filter((record4) => record4.status !== "consumed" || Date.parse(record4.expiresAt) > now).sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt)).slice(0, RETAIN_MAX);
78608
79146
  atomicJson(registryPath(projectId), { version: VERSION, tokens: retained });
78609
79147
  const referenced = new Set(retained.filter((record4) => record4.status !== "consumed" && Date.parse(record4.expiresAt) > now).map((record4) => `${record4.targetArtifact.slice(7)}.json`));
78610
79148
  const artifacts = artifactRoot(projectId);
78611
- if ((0, import_node_fs47.existsSync)(artifacts)) {
78612
- for (const entry2 of (0, import_node_fs47.readdirSync)(artifacts, { withFileTypes: true })) {
79149
+ if ((0, import_node_fs49.existsSync)(artifacts)) {
79150
+ for (const entry2 of (0, import_node_fs49.readdirSync)(artifacts, { withFileTypes: true })) {
78613
79151
  if (entry2.isFile() && /^[a-f0-9]{64}\.json$/.test(entry2.name) && !referenced.has(entry2.name)) {
78614
- (0, import_node_fs47.rmSync)((0, import_node_path42.join)(artifacts, entry2.name));
79152
+ (0, import_node_fs49.rmSync)((0, import_node_path44.join)(artifacts, entry2.name));
78615
79153
  }
78616
79154
  }
78617
79155
  }
@@ -78619,14 +79157,14 @@ function persistRegistry(projectId, registry2) {
78619
79157
  function persistArtifact(projectId, contract) {
78620
79158
  const hash3 = contentHash(contract);
78621
79159
  const root6 = artifactRoot(projectId);
78622
- (0, import_node_fs47.mkdirSync)(root6, { recursive: true });
78623
- const path = (0, import_node_path42.join)(root6, `${hash3.slice(7)}.json`);
78624
- if (!(0, import_node_fs47.existsSync)(path)) atomicJson(path, { hash: hash3, contract });
79160
+ (0, import_node_fs49.mkdirSync)(root6, { recursive: true });
79161
+ const path = (0, import_node_path44.join)(root6, `${hash3.slice(7)}.json`);
79162
+ if (!(0, import_node_fs49.existsSync)(path)) atomicJson(path, { hash: hash3, contract });
78625
79163
  return hash3;
78626
79164
  }
78627
79165
  function readArtifact(projectId, hash3) {
78628
- const path = (0, import_node_path42.join)(artifactRoot(projectId), `${hash3.slice(7)}.json`);
78629
- const value = JSON.parse((0, import_node_fs47.readFileSync)(path, "utf8"));
79166
+ const path = (0, import_node_path44.join)(artifactRoot(projectId), `${hash3.slice(7)}.json`);
79167
+ const value = JSON.parse((0, import_node_fs49.readFileSync)(path, "utf8"));
78630
79168
  if (value?.hash !== hash3 || contentHash(value.contract) !== hash3) throw new Error("member-end undo artifact failed its content hash");
78631
79169
  return value.contract;
78632
79170
  }
@@ -78636,8 +79174,8 @@ function stageResolutionToken(projectId, expectedContract, targetContract, direc
78636
79174
  const targetArtifact = persistArtifact(projectId, targetContract);
78637
79175
  const record4 = {
78638
79176
  version: VERSION,
78639
- token: (0, import_node_crypto32.randomUUID)(),
78640
- operationId: (0, import_node_crypto32.randomUUID)(),
79177
+ token: (0, import_node_crypto34.randomUUID)(),
79178
+ operationId: (0, import_node_crypto34.randomUUID)(),
78641
79179
  direction,
78642
79180
  expectedHash: contentHash(expectedContract),
78643
79181
  targetHash: targetArtifact,
@@ -79020,7 +79558,7 @@ async function applyReviewVerb(verb, projectId, jointId, expected, ifMatch) {
79020
79558
  if (!ifMatch) {
79021
79559
  throw new PreconditionRequiredError("marking a connection reviewed requires If-Match \u2014 the model generation you looked at");
79022
79560
  }
79023
- if (ifMatch !== snapshot.etag) {
79561
+ if (!recordedEtagNamesContract(ifMatch, etagsOf(model))) {
79024
79562
  throw new ConnectionCommandError(
79025
79563
  "the model changed while you were looking at this connection \u2014 reload and check it again before marking it reviewed",
79026
79564
  "contract-changed",
@@ -79323,8 +79861,8 @@ function registerSteelPrepassRoute(app, deps) {
79323
79861
  }
79324
79862
 
79325
79863
  // reference-routes.ts
79326
- var import_node_crypto35 = require("node:crypto");
79327
- var import_node_fs50 = require("node:fs");
79864
+ var import_node_crypto37 = require("node:crypto");
79865
+ var import_node_fs52 = require("node:fs");
79328
79866
 
79329
79867
  // reference-import.ts
79330
79868
  var AGENT2 = "ifc-reference-reader";
@@ -79833,14 +80371,14 @@ async function readReferenceModel(companionId, ifcPath, opts = {}) {
79833
80371
  }
79834
80372
 
79835
80373
  // reference-progress.ts
79836
- var import_node_crypto33 = require("node:crypto");
80374
+ var import_node_crypto35 = require("node:crypto");
79837
80375
  var MAX_BUFFER_BYTES = 8 * 1024 * 1024;
79838
80376
  var SESSION_TTL_MS = 10 * 6e4;
79839
80377
  var UNCLAIMED_TTL_MS = 2 * 6e4;
79840
80378
  var SWEEP_MS = 3e4;
79841
80379
  var sessions = /* @__PURE__ */ new Map();
79842
80380
  function createProgressSession(appId, project) {
79843
- const id = (0, import_node_crypto33.randomUUID)();
80381
+ const id = (0, import_node_crypto35.randomUUID)();
79844
80382
  sessions.set(id, {
79845
80383
  id,
79846
80384
  appId,
@@ -79951,15 +80489,15 @@ var sweep = setInterval(() => {
79951
80489
  sweep.unref?.();
79952
80490
 
79953
80491
  // reference-store.ts
79954
- var import_node_crypto34 = require("node:crypto");
79955
- var import_node_fs49 = require("node:fs");
80492
+ var import_node_crypto36 = require("node:crypto");
80493
+ var import_node_fs51 = require("node:fs");
79956
80494
  var import_promises4 = require("node:fs/promises");
79957
80495
  var import_promises5 = require("node:stream/promises");
79958
- var import_node_path43 = require("node:path");
80496
+ var import_node_path45 = require("node:path");
79959
80497
 
79960
80498
  // reference-binary.ts
79961
80499
  var import_node_zlib = require("node:zlib");
79962
- var import_node_fs48 = require("node:fs");
80500
+ var import_node_fs50 = require("node:fs");
79963
80501
  var import_node_util4 = require("node:util");
79964
80502
  var REFERENCE_BINARY_TYPE = "application/vnd.floless.reference-geometry-v7";
79965
80503
  var REFERENCE_BINARY_HEADER_BYTES = 192;
@@ -80105,14 +80643,14 @@ async function encodeReferenceBinaryAsync(cache2) {
80105
80643
  }
80106
80644
  function readReferenceBinaryHandleManifest(fd2, actualSize) {
80107
80645
  const header = Buffer.alloc(REFERENCE_BINARY_HEADER_BYTES);
80108
- if ((0, import_node_fs48.readSync)(fd2, header, 0, header.length, 0) !== header.length || !header.subarray(0, 8).equals(MAGIC)) throw new Error("not a reference binary");
80646
+ if ((0, import_node_fs50.readSync)(fd2, header, 0, header.length, 0) !== header.length || !header.subarray(0, 8).equals(MAGIC)) throw new Error("not a reference binary");
80109
80647
  if (header.readUInt32LE(8) !== 7 || header.readUInt32LE(12) !== REFERENCE_BINARY_HEADER_BYTES) throw new Error("unsupported reference binary version");
80110
80648
  const total = get64(header, 16);
80111
80649
  if (total !== actualSize || total > MAX_FILE) throw new Error("reference binary length mismatch");
80112
80650
  const offset = get64(header, 24), length2 = get64(header, 32);
80113
80651
  if (offset % 8 || length2 > MAX_META || offset + length2 > total) throw new Error("invalid manifest section");
80114
80652
  const manifest = Buffer.alloc(length2);
80115
- if ((0, import_node_fs48.readSync)(fd2, manifest, 0, length2, offset) !== length2 || referenceCrc32(manifest) !== header.readUInt32LE(40)) throw new Error("manifest checksum mismatch");
80653
+ if ((0, import_node_fs50.readSync)(fd2, manifest, 0, length2, offset) !== length2 || referenceCrc32(manifest) !== header.readUInt32LE(40)) throw new Error("manifest checksum mismatch");
80116
80654
  const parsed = JSON.parse(manifest.toString("utf8"));
80117
80655
  if (!Number.isInteger(parsed.v) || typeof parsed.sourceHash !== "string") throw new Error("reference manifest is incomplete");
80118
80656
  return { v: parsed.v, sourceHash: parsed.sourceHash, filter: parsed.filter ?? null };
@@ -80127,70 +80665,70 @@ function insideProject(projectId, relPath) {
80127
80665
  throw new ReferenceImportError("that reference does not name one of its own files, so it cannot be read or removed");
80128
80666
  }
80129
80667
  const root6 = realish(projectDir(projectId));
80130
- const abs = (0, import_node_path43.resolve)(root6, REFERENCE_DIR, name);
80131
- if (realish((0, import_node_path43.join)(root6, REFERENCE_DIR)) !== (0, import_node_path43.resolve)(root6, REFERENCE_DIR)) {
80668
+ const abs = (0, import_node_path45.resolve)(root6, REFERENCE_DIR, name);
80669
+ if (realish((0, import_node_path45.join)(root6, REFERENCE_DIR)) !== (0, import_node_path45.resolve)(root6, REFERENCE_DIR)) {
80132
80670
  throw new ReferenceImportError("this project\u2019s references folder is a link to somewhere else, so it will not be written to");
80133
80671
  }
80134
- if (!abs.startsWith(root6 + import_node_path43.sep)) {
80672
+ if (!abs.startsWith(root6 + import_node_path45.sep)) {
80135
80673
  throw new ReferenceImportError("that reference points outside its project, so it cannot be read or removed");
80136
80674
  }
80137
80675
  return abs;
80138
80676
  }
80139
80677
  function realish(p) {
80140
80678
  try {
80141
- return import_node_fs49.realpathSync.native((0, import_node_path43.resolve)(p));
80679
+ return import_node_fs51.realpathSync.native((0, import_node_path45.resolve)(p));
80142
80680
  } catch {
80143
- return (0, import_node_path43.resolve)(p);
80681
+ return (0, import_node_path45.resolve)(p);
80144
80682
  }
80145
80683
  }
80146
80684
  var REFERENCE_CACHE_VERSION = 7;
80147
- var legacyJsonCachePath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.json`);
80685
+ var legacyJsonCachePath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.json`);
80148
80686
  var binaryCachePrefix = (refId2) => `.floless-refcache-${safeId2(refId2)}-`;
80149
80687
  var cacheGenerationSequence = 0;
80150
80688
  var activePendingCacheGenerations = /* @__PURE__ */ new Set();
80151
80689
  var cachePruneTimers = /* @__PURE__ */ new Map();
80152
80690
  var CACHE_PENDING_TTL_MS = 10 * 6e4;
80153
80691
  var binaryCachePath = (projectId, refId2, sourceHash, filter, version = REFERENCE_CACHE_VERSION) => {
80154
- const key2 = (0, import_node_crypto34.createHash)("sha256").update(String(version)).update("\0").update(sourceHash).update("\0").update(filterKey(filter) ?? "").digest("hex").slice(0, 20);
80155
- return (0, import_node_path43.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}${key2}.bin`);
80692
+ const key2 = (0, import_node_crypto36.createHash)("sha256").update(String(version)).update("\0").update(sourceHash).update("\0").update(filterKey(filter) ?? "").digest("hex").slice(0, 20);
80693
+ return (0, import_node_path45.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}${key2}.bin`);
80156
80694
  };
80157
- var legacyBinaryCachePath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.bin`);
80158
- var cacheCurrentPath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}current`);
80695
+ var legacyBinaryCachePath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.bin`);
80696
+ var cacheCurrentPath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}current`);
80159
80697
  function currentCacheGeneration(projectId, refId2) {
80160
80698
  const pointer = cacheCurrentPath(projectId, refId2);
80161
- if (!(0, import_node_fs49.existsSync)(pointer)) return null;
80699
+ if (!(0, import_node_fs51.existsSync)(pointer)) return null;
80162
80700
  try {
80163
- const name = (0, import_node_fs49.readFileSync)(pointer, "utf8").trim();
80164
- if (!name || (0, import_node_path43.basename)(name) !== name) return null;
80165
- return cacheGenerationTarget(projectId, refId2, (0, import_node_path43.join)(projectDir(projectId), name), [".bin"]);
80701
+ const name = (0, import_node_fs51.readFileSync)(pointer, "utf8").trim();
80702
+ if (!name || (0, import_node_path45.basename)(name) !== name) return null;
80703
+ return cacheGenerationTarget(projectId, refId2, (0, import_node_path45.join)(projectDir(projectId), name), [".bin"]);
80166
80704
  } catch {
80167
80705
  return null;
80168
80706
  }
80169
80707
  }
80170
80708
  function publishCurrentCacheGeneration(projectId, refId2, generationName) {
80171
80709
  const pointer = cacheCurrentPath(projectId, refId2);
80172
- const pending = `${pointer}.${process.pid}.${(0, import_node_crypto34.randomUUID)()}.part`;
80710
+ const pending = `${pointer}.${process.pid}.${(0, import_node_crypto36.randomUUID)()}.part`;
80173
80711
  try {
80174
- (0, import_node_fs49.writeFileSync)(pending, generationName, "utf8");
80175
- (0, import_node_fs49.renameSync)(pending, pointer);
80712
+ (0, import_node_fs51.writeFileSync)(pending, generationName, "utf8");
80713
+ (0, import_node_fs51.renameSync)(pending, pointer);
80176
80714
  } finally {
80177
- (0, import_node_fs49.rmSync)(pending, { force: true });
80715
+ (0, import_node_fs51.rmSync)(pending, { force: true });
80178
80716
  }
80179
80717
  }
80180
80718
  function binaryCacheCandidates(projectId, refId2, sourceHash, filter) {
80181
80719
  collectStalePendingCacheGenerations(projectId, refId2);
80182
- if ((0, import_node_fs49.existsSync)(cacheCurrentPath(projectId, refId2))) {
80720
+ if ((0, import_node_fs51.existsSync)(cacheCurrentPath(projectId, refId2))) {
80183
80721
  const current = currentCacheGeneration(projectId, refId2);
80184
80722
  if (current) sweepExpiredCacheGenerations(projectId, refId2, current);
80185
80723
  return current ? [current] : [];
80186
80724
  }
80187
80725
  const exact = binaryCachePath(projectId, refId2, sourceHash, filter);
80188
- const generationPrefix = (0, import_node_path43.basename)(exact, ".bin") + "-";
80726
+ const generationPrefix = (0, import_node_path45.basename)(exact, ".bin") + "-";
80189
80727
  let generated = [];
80190
80728
  try {
80191
- generated = (0, import_node_fs49.readdirSync)(projectDir(projectId)).filter((name) => name.startsWith(generationPrefix) && name.endsWith(".bin")).map((name) => (0, import_node_path43.join)(projectDir(projectId), name)).sort((a, b) => {
80729
+ generated = (0, import_node_fs51.readdirSync)(projectDir(projectId)).filter((name) => name.startsWith(generationPrefix) && name.endsWith(".bin")).map((name) => (0, import_node_path45.join)(projectDir(projectId), name)).sort((a, b) => {
80192
80730
  try {
80193
- return (0, import_node_fs49.statSync)(b).mtimeMs - (0, import_node_fs49.statSync)(a).mtimeMs || (0, import_node_path43.basename)(b).localeCompare((0, import_node_path43.basename)(a));
80731
+ return (0, import_node_fs51.statSync)(b).mtimeMs - (0, import_node_fs51.statSync)(a).mtimeMs || (0, import_node_path45.basename)(b).localeCompare((0, import_node_path45.basename)(a));
80194
80732
  } catch {
80195
80733
  return 0;
80196
80734
  }
@@ -80203,13 +80741,13 @@ function binaryCacheCandidates(projectId, refId2, sourceHash, filter) {
80203
80741
  function sweepExpiredCacheGenerations(projectId, refId2, preserve) {
80204
80742
  const staleBefore = Date.now() - CACHE_PENDING_TTL_MS;
80205
80743
  try {
80206
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) {
80744
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) {
80207
80745
  if (!name.startsWith(binaryCachePrefix(refId2)) || !name.endsWith(".bin") && !name.endsWith(".pending")) continue;
80208
- const candidate = (0, import_node_path43.join)(projectDir(projectId), name);
80209
- if ((0, import_node_path43.resolve)(candidate) === (0, import_node_path43.resolve)(preserve)) continue;
80210
- if (activePendingCacheGenerations.has((0, import_node_path43.resolve)(candidate))) continue;
80746
+ const candidate = (0, import_node_path45.join)(projectDir(projectId), name);
80747
+ if ((0, import_node_path45.resolve)(candidate) === (0, import_node_path45.resolve)(preserve)) continue;
80748
+ if (activePendingCacheGenerations.has((0, import_node_path45.resolve)(candidate))) continue;
80211
80749
  try {
80212
- if ((0, import_node_fs49.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs49.rmSync)(candidate, { force: true });
80750
+ if ((0, import_node_fs51.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs51.rmSync)(candidate, { force: true });
80213
80751
  } catch {
80214
80752
  }
80215
80753
  }
@@ -80222,21 +80760,21 @@ function safeId2(refId2) {
80222
80760
  return s;
80223
80761
  }
80224
80762
  async function hashFile(path) {
80225
- const h = (0, import_node_crypto34.createHash)("sha256");
80226
- await (0, import_promises5.pipeline)((0, import_node_fs49.createReadStream)(path), h);
80763
+ const h = (0, import_node_crypto36.createHash)("sha256");
80764
+ await (0, import_promises5.pipeline)((0, import_node_fs51.createReadStream)(path), h);
80227
80765
  return h.digest("hex");
80228
80766
  }
80229
80767
  function copyOriginal(projectId, relPath, sourceAbs, tag) {
80230
80768
  const abs = insideProject(projectId, relPath);
80231
- (0, import_node_fs49.mkdirSync)((0, import_node_path43.dirname)(abs), { recursive: true });
80769
+ (0, import_node_fs51.mkdirSync)((0, import_node_path45.dirname)(abs), { recursive: true });
80232
80770
  const tmp = `${abs}.${safeId2(tag)}.part`;
80233
- (0, import_node_fs49.copyFileSync)(sourceAbs, tmp);
80234
- (0, import_node_fs49.renameSync)(tmp, abs);
80771
+ (0, import_node_fs51.copyFileSync)(sourceAbs, tmp);
80772
+ (0, import_node_fs51.renameSync)(tmp, abs);
80235
80773
  return abs;
80236
80774
  }
80237
80775
  function referenceFilesOnDisk(projectId) {
80238
80776
  try {
80239
- return (0, import_node_fs49.readdirSync)((0, import_node_path43.join)(projectDir(projectId), REFERENCE_DIR)).map((f) => `${REFERENCE_DIR}/${f}`);
80777
+ return (0, import_node_fs51.readdirSync)((0, import_node_path45.join)(projectDir(projectId), REFERENCE_DIR)).map((f) => `${REFERENCE_DIR}/${f}`);
80240
80778
  } catch (e) {
80241
80779
  if (e.code === "ENOENT") return [];
80242
80780
  throw new ReferenceImportError(
@@ -80246,16 +80784,16 @@ function referenceFilesOnDisk(projectId) {
80246
80784
  }
80247
80785
  function originalPath(projectId, relPath) {
80248
80786
  const abs = insideProject(projectId, relPath);
80249
- return (0, import_node_fs49.existsSync)(abs) ? abs : null;
80787
+ return (0, import_node_fs51.existsSync)(abs) ? abs : null;
80250
80788
  }
80251
80789
  async function writeCache2(projectId, refId2, cache2, options = {}) {
80252
80790
  collectStalePendingCacheGenerations(projectId, refId2);
80253
80791
  const binary = binaryCachePath(projectId, refId2, cache2.sourceHash, cache2.filter, cache2.v);
80254
80792
  const sequence = (++cacheGenerationSequence).toString(36).padStart(8, "0");
80255
80793
  const suffix = options.staged ? ".pending" : ".bin";
80256
- const generation = `${binary.slice(0, -4)}-${Date.now().toString(36)}-${sequence}-${(0, import_node_crypto34.randomUUID)()}${suffix}`;
80794
+ const generation = `${binary.slice(0, -4)}-${Date.now().toString(36)}-${sequence}-${(0, import_node_crypto36.randomUUID)()}${suffix}`;
80257
80795
  const binaryTmp = `${generation}.${process.pid}.part`;
80258
- const pendingToken = options.staged ? (0, import_node_path43.resolve)(generation) : null;
80796
+ const pendingToken = options.staged ? (0, import_node_path45.resolve)(generation) : null;
80259
80797
  if (pendingToken) activePendingCacheGenerations.add(pendingToken);
80260
80798
  let encoded;
80261
80799
  try {
@@ -80277,10 +80815,10 @@ async function writeCache2(projectId, refId2, cache2, options = {}) {
80277
80815
  return generation;
80278
80816
  }
80279
80817
  function cacheGenerationTarget(projectId, refId2, path, suffixes) {
80280
- const root6 = (0, import_node_path43.resolve)(projectDir(projectId));
80281
- const target = (0, import_node_path43.resolve)(path);
80282
- const name = (0, import_node_path43.basename)(target);
80283
- if ((0, import_node_path43.dirname)(target) !== root6 || !name.startsWith(binaryCachePrefix(refId2)) || !suffixes.some((suffix) => name.endsWith(suffix))) {
80818
+ const root6 = (0, import_node_path45.resolve)(projectDir(projectId));
80819
+ const target = (0, import_node_path45.resolve)(path);
80820
+ const name = (0, import_node_path45.basename)(target);
80821
+ if ((0, import_node_path45.dirname)(target) !== root6 || !name.startsWith(binaryCachePrefix(refId2)) || !suffixes.some((suffix) => name.endsWith(suffix))) {
80284
80822
  throw new ReferenceImportError("that reference cache generation cannot be changed safely");
80285
80823
  }
80286
80824
  return target;
@@ -80288,24 +80826,24 @@ function cacheGenerationTarget(projectId, refId2, path, suffixes) {
80288
80826
  function commitCacheGeneration(projectId, refId2, pendingPath) {
80289
80827
  const pending = cacheGenerationTarget(projectId, refId2, pendingPath, [".pending"]);
80290
80828
  const committed = `${pending.slice(0, -".pending".length)}.bin`;
80291
- (0, import_node_fs49.renameSync)(pending, committed);
80829
+ (0, import_node_fs51.renameSync)(pending, committed);
80292
80830
  activePendingCacheGenerations.delete(pending);
80293
80831
  return committed;
80294
80832
  }
80295
80833
  function removeCacheGeneration(projectId, refId2, path) {
80296
80834
  const target = cacheGenerationTarget(projectId, refId2, path, [".bin", ".pending"]);
80297
80835
  activePendingCacheGenerations.delete(target);
80298
- (0, import_node_fs49.rmSync)(target, { force: true });
80836
+ (0, import_node_fs51.rmSync)(target, { force: true });
80299
80837
  }
80300
80838
  function collectStalePendingCacheGenerations(projectId, refId2) {
80301
80839
  const staleBefore = Date.now() - CACHE_PENDING_TTL_MS;
80302
80840
  try {
80303
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) {
80841
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) {
80304
80842
  if (!name.startsWith(binaryCachePrefix(refId2)) || !name.endsWith(".pending")) continue;
80305
- const candidate = (0, import_node_path43.resolve)((0, import_node_path43.join)(projectDir(projectId), name));
80843
+ const candidate = (0, import_node_path45.resolve)((0, import_node_path45.join)(projectDir(projectId), name));
80306
80844
  if (activePendingCacheGenerations.has(candidate)) continue;
80307
80845
  try {
80308
- if ((0, import_node_fs49.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs49.rmSync)(candidate, { force: true });
80846
+ if ((0, import_node_fs51.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs51.rmSync)(candidate, { force: true });
80309
80847
  } catch {
80310
80848
  }
80311
80849
  }
@@ -80315,21 +80853,21 @@ function collectStalePendingCacheGenerations(projectId, refId2) {
80315
80853
  }
80316
80854
  }
80317
80855
  function pruneCache(projectId, refId2, committedGeneration, options = {}) {
80318
- const root6 = (0, import_node_path43.resolve)(projectDir(projectId));
80319
- const preserve = (0, import_node_path43.resolve)(committedGeneration);
80320
- const preserveName = (0, import_node_path43.basename)(preserve);
80321
- if ((0, import_node_path43.dirname)(preserve) !== root6 || !preserveName.startsWith(binaryCachePrefix(refId2)) || !preserveName.endsWith(".bin") || !(0, import_node_fs49.existsSync)(preserve)) {
80856
+ const root6 = (0, import_node_path45.resolve)(projectDir(projectId));
80857
+ const preserve = (0, import_node_path45.resolve)(committedGeneration);
80858
+ const preserveName = (0, import_node_path45.basename)(preserve);
80859
+ if ((0, import_node_path45.dirname)(preserve) !== root6 || !preserveName.startsWith(binaryCachePrefix(refId2)) || !preserveName.endsWith(".bin") || !(0, import_node_fs51.existsSync)(preserve)) {
80322
80860
  throw new Error("the committed reference cache generation is unavailable");
80323
80861
  }
80324
80862
  try {
80325
- publishCurrentCacheGeneration(projectId, refId2, (0, import_node_path43.basename)(preserve));
80863
+ publishCurrentCacheGeneration(projectId, refId2, (0, import_node_path45.basename)(preserve));
80326
80864
  } catch (error) {
80327
- (0, import_node_fs49.rmSync)(preserve, { force: true });
80865
+ (0, import_node_fs51.rmSync)(preserve, { force: true });
80328
80866
  throw error;
80329
80867
  }
80330
80868
  const committedAt = /* @__PURE__ */ new Date();
80331
80869
  try {
80332
- (0, import_node_fs49.utimesSync)(preserve, committedAt, committedAt);
80870
+ (0, import_node_fs51.utimesSync)(preserve, committedAt, committedAt);
80333
80871
  } catch {
80334
80872
  }
80335
80873
  sweepExpiredCacheGenerations(projectId, refId2, preserve);
@@ -80355,19 +80893,19 @@ function filterKey(filter) {
80355
80893
  function cachedGeometryBinary(projectId, refId2, expectHash, expectFilter) {
80356
80894
  const candidates = binaryCacheCandidates(projectId, refId2, expectHash, expectFilter);
80357
80895
  for (const path of candidates) {
80358
- if (!(0, import_node_fs49.existsSync)(path)) continue;
80896
+ if (!(0, import_node_fs51.existsSync)(path)) continue;
80359
80897
  let fd2 = null;
80360
80898
  try {
80361
- fd2 = (0, import_node_fs49.openSync)(path, "r");
80362
- const size = (0, import_node_fs49.fstatSync)(fd2).size;
80899
+ fd2 = (0, import_node_fs51.openSync)(path, "r");
80900
+ const size = (0, import_node_fs51.fstatSync)(fd2).size;
80363
80901
  const manifest = readReferenceBinaryHandleManifest(fd2, size);
80364
80902
  if (manifest.v !== REFERENCE_CACHE_VERSION || manifest.sourceHash !== expectHash || filterKey(manifest.filter) !== filterKey(expectFilter)) {
80365
- (0, import_node_fs49.closeSync)(fd2);
80903
+ (0, import_node_fs51.closeSync)(fd2);
80366
80904
  return null;
80367
80905
  }
80368
80906
  return { fd: fd2, size, path };
80369
80907
  } catch (error) {
80370
- if (fd2 !== null) (0, import_node_fs49.closeSync)(fd2);
80908
+ if (fd2 !== null) (0, import_node_fs51.closeSync)(fd2);
80371
80909
  const code = error?.code;
80372
80910
  if (code && ["EACCES", "EBUSY", "EMFILE", "ENFILE"].includes(code)) {
80373
80911
  throw new ReferenceImportError("the reference cache could not be opened \u2014 check the project folder is readable and try again");
@@ -80378,20 +80916,20 @@ function cachedGeometryBinary(projectId, refId2, expectHash, expectFilter) {
80378
80916
  return null;
80379
80917
  }
80380
80918
  function dropCache(projectId, refId2) {
80381
- const timerKey = `${(0, import_node_path43.resolve)(projectDir(projectId))}\0${safeId2(refId2)}`;
80919
+ const timerKey = `${(0, import_node_path45.resolve)(projectDir(projectId))}\0${safeId2(refId2)}`;
80382
80920
  const timer = cachePruneTimers.get(timerKey);
80383
80921
  if (timer) {
80384
80922
  clearTimeout(timer);
80385
80923
  cachePruneTimers.delete(timerKey);
80386
80924
  }
80387
- (0, import_node_fs49.rmSync)(legacyJsonCachePath(projectId, refId2), { force: true });
80388
- (0, import_node_fs49.rmSync)(legacyBinaryCachePath(projectId, refId2), { force: true });
80389
- (0, import_node_fs49.rmSync)(cacheCurrentPath(projectId, refId2), { force: true });
80925
+ (0, import_node_fs51.rmSync)(legacyJsonCachePath(projectId, refId2), { force: true });
80926
+ (0, import_node_fs51.rmSync)(legacyBinaryCachePath(projectId, refId2), { force: true });
80927
+ (0, import_node_fs51.rmSync)(cacheCurrentPath(projectId, refId2), { force: true });
80390
80928
  const prefix = binaryCachePrefix(refId2);
80391
80929
  try {
80392
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) if (name.startsWith(prefix) && (name.endsWith(".bin") || name.endsWith(".pending") || name.endsWith(".part"))) {
80393
- activePendingCacheGenerations.delete((0, import_node_path43.resolve)((0, import_node_path43.join)(projectDir(projectId), name)));
80394
- (0, import_node_fs49.rmSync)((0, import_node_path43.join)(projectDir(projectId), name), { force: true });
80930
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) if (name.startsWith(prefix) && (name.endsWith(".bin") || name.endsWith(".pending") || name.endsWith(".part"))) {
80931
+ activePendingCacheGenerations.delete((0, import_node_path45.resolve)((0, import_node_path45.join)(projectDir(projectId), name)));
80932
+ (0, import_node_fs51.rmSync)((0, import_node_path45.join)(projectDir(projectId), name), { force: true });
80395
80933
  }
80396
80934
  } catch (error) {
80397
80935
  if (error.code !== "ENOENT") throw error;
@@ -80399,10 +80937,10 @@ function dropCache(projectId, refId2) {
80399
80937
  }
80400
80938
  function removeReference(projectId, refId2, relPath) {
80401
80939
  dropCache(projectId, refId2);
80402
- if (relPath) (0, import_node_fs49.rmSync)(insideProject(projectId, relPath), { force: true });
80940
+ if (relPath) (0, import_node_fs51.rmSync)(insideProject(projectId, relPath), { force: true });
80403
80941
  }
80404
80942
  function removeReferenceFile(projectId, relPath) {
80405
- (0, import_node_fs49.rmSync)(insideProject(projectId, relPath), { force: true });
80943
+ (0, import_node_fs51.rmSync)(insideProject(projectId, relPath), { force: true });
80406
80944
  }
80407
80945
  function takenReferencePaths(refs) {
80408
80946
  return new Set((refs ?? []).map((r) => r.file).filter((f) => typeof f === "string"));
@@ -81020,7 +81558,7 @@ function registerReferenceRoutes(app, deps) {
81020
81558
  return reply.status(404).send({ ok: false, error: "the uploaded IFC is no longer available \u2014 drop the file again" });
81021
81559
  }
81022
81560
  const displayName = String(name || "model.ifc");
81023
- const id = (0, import_node_crypto35.randomUUID)();
81561
+ const id = (0, import_node_crypto37.randomUUID)();
81024
81562
  let rel;
81025
81563
  try {
81026
81564
  rel = await withLifecycleLock("project", g.project, () => {
@@ -81190,7 +81728,7 @@ function registerReferenceRoutes(app, deps) {
81190
81728
  const stored2 = entry2.filter;
81191
81729
  const hit = rebuild ? null : cachedGeometryBinary(g.project, entry2.id, sourceHash, stored2);
81192
81730
  if (hit) {
81193
- return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(hit.size)).header("x-floless-reference-cache", "hit").send((0, import_node_fs50.createReadStream)(hit.path, { fd: hit.fd, autoClose: true }));
81731
+ return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(hit.size)).header("x-floless-reference-cache", "hit").send((0, import_node_fs52.createReadStream)(hit.path, { fd: hit.fd, autoClose: true }));
81194
81732
  }
81195
81733
  let preview2 = null;
81196
81734
  try {
@@ -81247,7 +81785,7 @@ function registerReferenceRoutes(app, deps) {
81247
81785
  }
81248
81786
  const built = cachedGeometryBinary(g.project, entry2.id, sourceHash, stored2);
81249
81787
  if (!built) throw new Error("the reference binary was not published");
81250
- return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(built.size)).header("x-floless-reference-cache", "miss").send((0, import_node_fs50.createReadStream)(built.path, { fd: built.fd, autoClose: true }));
81788
+ return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(built.size)).header("x-floless-reference-cache", "miss").send((0, import_node_fs52.createReadStream)(built.path, { fd: built.fd, autoClose: true }));
81251
81789
  } catch (e) {
81252
81790
  if (e instanceof LifecycleLockBusyError) throw e;
81253
81791
  const r = importRefusal(e);
@@ -81329,7 +81867,7 @@ function registerReferenceRoutes(app, deps) {
81329
81867
  };
81330
81868
  try {
81331
81869
  try {
81332
- assertAcceptable((0, import_node_fs50.statSync)(source).size, displayName);
81870
+ assertAcceptable((0, import_node_fs52.statSync)(source).size, displayName);
81333
81871
  } catch (e) {
81334
81872
  const r = importRefusal(e);
81335
81873
  if (r) return reply.status(r.status).send(r.body);
@@ -81934,10 +82472,10 @@ function registerReferenceRoutes(app, deps) {
81934
82472
 
81935
82473
  // bom-export.ts
81936
82474
  var import_node_os27 = require("node:os");
81937
- var import_node_path44 = require("node:path");
82475
+ var import_node_path46 = require("node:path");
81938
82476
 
81939
82477
  // node_modules/write-excel-file/modules/export/writeXlsxFileNode.js
81940
- var import_node_fs51 = __toESM(require("node:fs"), 1);
82478
+ var import_node_fs53 = __toESM(require("node:fs"), 1);
81941
82479
 
81942
82480
  // node_modules/write-excel-file/modules/xlsx/helpers/features/getAdditionalContent.js
81943
82481
  function _createForOfIteratorHelperLoose(r, e) {
@@ -85037,7 +85575,7 @@ function writeXlsxFile(arg1, arg2, arg3) {
85037
85575
  },
85038
85576
  toFile: function toFile(filePath) {
85039
85577
  return createReadableStream().then(function(readableStream) {
85040
- return pipe(readableStream, import_node_fs51.default.createWriteStream(filePath));
85578
+ return pipe(readableStream, import_node_fs53.default.createWriteStream(filePath));
85041
85579
  });
85042
85580
  }
85043
85581
  };
@@ -85299,8 +85837,8 @@ var BOM_EXPORT_KIND = {
85299
85837
  html: "bom-html"
85300
85838
  };
85301
85839
  function bomExportPath(appId, format) {
85302
- const root6 = process.env.FLOLESS_HOME ?? (0, import_node_path44.join)((0, import_node_os27.homedir)(), ".floless");
85303
- return (0, import_node_path44.join)(root6, "exports", appId, `${appId}-bom.${format}`);
85840
+ const root6 = process.env.FLOLESS_HOME ?? (0, import_node_path46.join)((0, import_node_os27.homedir)(), ".floless");
85841
+ return (0, import_node_path46.join)(root6, "exports", appId, `${appId}-bom.${format}`);
85304
85842
  }
85305
85843
  function csvField(v) {
85306
85844
  let s = String(v);
@@ -85478,7 +86016,14 @@ function registerContractAccessRoutes(app, deps) {
85478
86016
  if (!snapshot && req.query.quietMissing === "1") return reply.status(204).send();
85479
86017
  if (!snapshot) return reply.status(404).send({ ok: false, error: "no contract for this app yet" });
85480
86018
  reply.header("ETag", snapshot.etag);
85481
- return snapshot;
86019
+ const asked = (Array.isArray(req.query.recordedEtag) ? req.query.recordedEtag : [req.query.recordedEtag]).filter((tag) => typeof tag === "string" && tag !== "");
86020
+ const recorded = [...new Set(asked)].slice(0, 4);
86021
+ if (!recorded.length) return snapshot;
86022
+ const names2 = deps.recordedEtagsNameDocument(recorded, snapshot.contract);
86023
+ return {
86024
+ ...snapshot,
86025
+ recordedBases: recorded.map((tag, i) => ({ recorded: tag, namesSnapshot: names2[i] === true }))
86026
+ };
85482
86027
  });
85483
86028
  app.post(
85484
86029
  "/api/contract/:appId/scene",
@@ -85699,8 +86244,8 @@ function workspaceContractLifecycle(contract, hasHistory = false) {
85699
86244
  }
85700
86245
 
85701
86246
  // project-export-files.ts
85702
- var import_node_fs52 = require("node:fs");
85703
- var import_node_path45 = require("node:path");
86247
+ var import_node_fs54 = require("node:fs");
86248
+ var import_node_path47 = require("node:path");
85704
86249
  function projectExportFiles(appId, kindOf2 = appId) {
85705
86250
  if (kindOf2 === "vectorize") {
85706
86251
  return [{ kind: "svg", filename: `${appId}.svg` }];
@@ -85729,119 +86274,16 @@ function exportFileBase(projectId, appId, now = /* @__PURE__ */ new Date()) {
85729
86274
  }
85730
86275
  function uniqueProjectExportFilename(projectId, preferred) {
85731
86276
  const dir = projectExportsDir(projectId);
85732
- if (!(0, import_node_fs52.existsSync)((0, import_node_path45.join)(dir, preferred))) return preferred;
85733
- const extension = (0, import_node_path45.extname)(preferred);
86277
+ if (!(0, import_node_fs54.existsSync)((0, import_node_path47.join)(dir, preferred))) return preferred;
86278
+ const extension = (0, import_node_path47.extname)(preferred);
85734
86279
  const stem = preferred.slice(0, preferred.length - extension.length);
85735
86280
  for (let suffix = 2; suffix <= 9999; suffix += 1) {
85736
86281
  const candidate = `${stem}-${suffix}${extension}`;
85737
- if (!(0, import_node_fs52.existsSync)((0, import_node_path45.join)(dir, candidate))) return candidate;
86282
+ if (!(0, import_node_fs54.existsSync)((0, import_node_path47.join)(dir, candidate))) return candidate;
85738
86283
  }
85739
86284
  throw new Error("could not allocate a unique project export filename");
85740
86285
  }
85741
86286
 
85742
- // workspace-approved-snapshot.ts
85743
- var WorkspaceSnapshotError = class extends Error {
85744
- constructor(status, message, notReviewable, version) {
85745
- super(message);
85746
- this.status = status;
85747
- this.notReviewable = notReviewable;
85748
- this.version = version;
85749
- }
85750
- status;
85751
- notReviewable;
85752
- version;
85753
- };
85754
- var NoApprovedVersionError = class extends WorkspaceSnapshotError {
85755
- constructor() {
85756
- super(409, "project has no approved version");
85757
- this.name = "NoApprovedVersionError";
85758
- }
85759
- };
85760
- function approvedRows(projectId) {
85761
- const project = getProject(projectId);
85762
- if (!project) return [];
85763
- const allRows = listVersions(projectId);
85764
- if (project.uuid) {
85765
- const tainted = allRows.find((v) => v.gate === "model" && v.kind === "approve" && !v.approval);
85766
- if (tainted) {
85767
- throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`, void 0, tainted.n);
85768
- }
85769
- }
85770
- const projectTime = Date.parse(project.createdAt);
85771
- return allRows.filter((v) => v.gate === "model" && v.kind === "approve").filter((v) => v.approval ? !!project.uuid && v.approval.projectUuid === project.uuid : Number.isFinite(projectTime) && Date.parse(v.ts) >= projectTime).map(({ current: _current, ...meta }) => meta);
85772
- }
85773
- function latestApprovedVersion(projectId) {
85774
- return approvedRows(projectId)[0] ?? null;
85775
- }
85776
- function listApprovedVersionMetadata(projectId) {
85777
- return approvedRows(projectId);
85778
- }
85779
- function currentApprovedSnapshot(projectId, version) {
85780
- const project = getProject(projectId);
85781
- if (!project) throw new WorkspaceSnapshotError(404, `unknown project: ${projectId}`);
85782
- const rows2 = approvedRows(projectId);
85783
- const row = version === void 0 ? rows2[0] : rows2.find((v) => v.n === version);
85784
- if (!row) {
85785
- if (version === void 0) throw new NoApprovedVersionError();
85786
- throw new WorkspaceSnapshotError(404, `approved version not found: ${version}`);
85787
- }
85788
- const latest = rows2[0];
85789
- const assertOwned = (candidate, hash3) => {
85790
- if (candidate.approval) {
85791
- if (!project.uuid || candidate.approval.projectUuid !== project.uuid) {
85792
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} belongs to another project incarnation`);
85793
- }
85794
- if (candidate.approval.candidateHash !== hash3) {
85795
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} failed its content-hash proof`);
85796
- }
85797
- return;
85798
- }
85799
- const rowTime = Date.parse(candidate.ts);
85800
- const projectTime = Date.parse(project.createdAt);
85801
- if (!Number.isFinite(rowTime) || !Number.isFinite(projectTime) || rowTime < projectTime) {
85802
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} has no ownership proof`);
85803
- }
85804
- };
85805
- const contract = readAcceptedVersion(projectId, row.n, { appId: project.app, projectId, operation: "read" });
85806
- if (contract == null) throw new WorkspaceSnapshotError(409, `approved version ${row.n} is unreadable`);
85807
- const selectedHash = contractHash(contract);
85808
- assertOwned(row, selectedHash);
85809
- const latestContract = latest.n === row.n ? contract : readAcceptedVersion(projectId, latest.n, { appId: project.app, projectId, operation: "read" });
85810
- if (latestContract == null) throw new WorkspaceSnapshotError(409, `approved version ${latest.n} is unreadable`);
85811
- const latestHash = contractHash(latestContract);
85812
- assertOwned(latest, latestHash);
85813
- const draft = readAcceptedForRequest(project.app, projectId, "read");
85814
- const comparable = comparableContractHash;
85815
- const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
85816
- return {
85817
- project,
85818
- version: row,
85819
- contract,
85820
- contractHash: selectedHash,
85821
- currentApprovedAt: project.approvedAt ?? null,
85822
- dirtySinceApproval,
85823
- latestApprovedVersion: latest.n,
85824
- headDiverged: row.n !== latest.n
85825
- };
85826
- }
85827
- function approvedSnapshotForMetadata(projectId, surface, onRefusal) {
85828
- try {
85829
- return currentApprovedSnapshot(projectId);
85830
- } catch (error) {
85831
- if (error instanceof NoApprovedVersionError) return null;
85832
- if (error instanceof WorkspaceSnapshotError && error.status === 404) throw error;
85833
- if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
85834
- const status = error instanceof WorkspaceSnapshotError ? error.status : error.code;
85835
- onRefusal?.(error);
85836
- console.error(
85837
- `${surface}: project ${projectId} has an approved version the gate refused to serve (${status}) \u2014 reporting no approved head. ${error.message}`
85838
- );
85839
- return null;
85840
- }
85841
- throw error;
85842
- }
85843
- }
85844
-
85845
86287
  // approval-partition.ts
85846
86288
  var unchangedNode = (value) => ({ materialize: () => value });
85847
86289
  var atomicNode = (groupId, before, after) => ({
@@ -86426,82 +86868,6 @@ function buildApprovalReview(input) {
86426
86868
  return prepared;
86427
86869
  }
86428
86870
 
86429
- // working-revision-manifest.ts
86430
- var import_node_crypto36 = require("node:crypto");
86431
- var import_node_fs53 = require("node:fs");
86432
- var import_node_path46 = require("node:path");
86433
- var nativePublicationIdentity = (projectUuid) => `project:${projectUuid}`;
86434
- var pathOf = (projectId) => (0, import_node_path46.join)(projectDir(projectId), ".floless-working-revision-state-v1.json");
86435
- var checksumOf = (body) => hashOf(body);
86436
- function bodyOf(value) {
86437
- const { checksum: _checksum, ...body } = value;
86438
- return body;
86439
- }
86440
- function assertProject(project) {
86441
- if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
86442
- return project.uuid;
86443
- }
86444
- function readWorkingRevisionManifest(project) {
86445
- const uuid = assertProject(project);
86446
- try {
86447
- const value = JSON.parse((0, import_node_fs53.readFileSync)(pathOf(project.id), "utf8"));
86448
- if (value?.schema !== 1 || value.projectUuid !== uuid || !Number.isInteger(value.epoch) || value.epoch < 0) return null;
86449
- return checksumOf(bodyOf(value)) === value.checksum ? value : null;
86450
- } catch {
86451
- return null;
86452
- }
86453
- }
86454
- function ensureWorkingRevisionManifest(input) {
86455
- const existing = readWorkingRevisionManifest(input.project);
86456
- if (existing) return existing;
86457
- const body = {
86458
- schema: 1,
86459
- projectUuid: assertProject(input.project),
86460
- publicationIdentity: input.publicationIdentity,
86461
- revisionId: (0, import_node_crypto36.randomUUID)(),
86462
- epoch: 0,
86463
- source: { kind: "working" },
86464
- workingBase: input.workingBase,
86465
- draftHash: hashOf(input.contract),
86466
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
86467
- };
86468
- const value = { ...body, checksum: checksumOf(body) };
86469
- (0, import_node_fs53.mkdirSync)(projectDir(input.project.id), { recursive: true });
86470
- if (!(0, import_node_fs53.existsSync)(pathOf(input.project.id))) writeJsonAtomic(pathOf(input.project.id), value);
86471
- return readWorkingRevisionManifest(input.project) ?? value;
86472
- }
86473
- function advanceWorkingRevisionManifest(input) {
86474
- const current = readWorkingRevisionManifest(input.project);
86475
- if (!current) throw new Error("working revision state is missing or corrupt");
86476
- if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
86477
- throw new Error("working revision changed; reload before continuing");
86478
- }
86479
- if (current.publicationIdentity !== input.publicationIdentity) throw new Error("working revision belongs to another app publication");
86480
- const body = {
86481
- ...bodyOf(current),
86482
- revisionId: (0, import_node_crypto36.randomUUID)(),
86483
- epoch: current.epoch + 1,
86484
- source: input.source,
86485
- workingBase: input.workingBase,
86486
- draftHash: hashOf(input.contract),
86487
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
86488
- };
86489
- const value = { ...body, checksum: checksumOf(body) };
86490
- writeJsonAtomic(pathOf(input.project.id), value);
86491
- return value;
86492
- }
86493
- function refreshWorkingDraftHash(input) {
86494
- const current = readWorkingRevisionManifest(input.project);
86495
- if (!current) throw new Error("working revision state is missing or corrupt");
86496
- if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
86497
- throw new Error("working revision changed; reload before saving");
86498
- }
86499
- const body = { ...bodyOf(current), draftHash: hashOf(input.contract), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
86500
- const value = { ...body, checksum: checksumOf(body) };
86501
- writeJsonAtomic(pathOf(input.project.id), value);
86502
- return value;
86503
- }
86504
-
86505
86871
  // three-way-contract-merge.ts
86506
86872
  var MISSING = /* @__PURE__ */ Symbol("missing");
86507
86873
  var same3 = (a, b) => canonicalJson(a) === canonicalJson(b);
@@ -86737,110 +87103,6 @@ function projectApprovalCandidateAccepted(appId, projectId, candidate) {
86737
87103
  return acceptSteelForRoute(candidate, { appId, projectId }, "stored").accepted;
86738
87104
  }
86739
87105
 
86740
- // project-checkpoints-store.ts
86741
- var import_node_crypto37 = require("node:crypto");
86742
- var import_node_fs54 = require("node:fs");
86743
- var import_node_path47 = require("node:path");
86744
- var HASH_RE3 = /^[0-9a-f]{64}$/;
86745
- function root5(projectId) {
86746
- return (0, import_node_path47.join)(projectDir(projectId), ".floless-checkpoints-store-v1");
86747
- }
86748
- var objectsDir2 = (projectId) => (0, import_node_path47.join)(root5(projectId), "objects");
86749
- var eventsPath = (projectId) => (0, import_node_path47.join)(root5(projectId), "events.json");
86750
- function readEvents(projectId) {
86751
- try {
86752
- const parsed = JSON.parse((0, import_node_fs54.readFileSync)(eventsPath(projectId), "utf8"));
86753
- if (parsed?.schema !== 1 || !Array.isArray(parsed.events)) return { schema: 1, events: [] };
86754
- return { schema: 1, events: parsed.events.filter(validEvent) };
86755
- } catch {
86756
- return { schema: 1, events: [] };
86757
- }
86758
- }
86759
- function validEvent(value) {
86760
- if (!value || typeof value !== "object") return false;
86761
- const e = value;
86762
- return typeof e.eventId === "string" && typeof e.checkpointId === "string" && HASH_RE3.test(e.checkpointId) && (e.kind === "captured" || e.kind === "archived" || e.kind === "incorporated") && typeof e.at === "string" && Number.isInteger(e.revisionEpoch) && typeof e.appIdAtCapture === "string";
86763
- }
86764
- function readContent(projectId, id) {
86765
- if (!HASH_RE3.test(id)) return null;
86766
- try {
86767
- const value = JSON.parse((0, import_node_fs54.readFileSync)((0, import_node_path47.join)(objectsDir2(projectId), `${id}.json`), "utf8"));
86768
- if (value?.schema !== 1 || value.id !== id || hashCheckpoint(value) !== id) return null;
86769
- return value;
86770
- } catch {
86771
- return null;
86772
- }
86773
- }
86774
- function hashCheckpoint(value) {
86775
- const { id: _id, ...identity } = value;
86776
- return hashOf(identity);
86777
- }
86778
- function requireIdentity(project) {
86779
- if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
86780
- return project.uuid;
86781
- }
86782
- function appendEvent(projectId, event) {
86783
- (0, import_node_fs54.mkdirSync)(root5(projectId), { recursive: true });
86784
- const log2 = readEvents(projectId);
86785
- const row = { ...event, eventId: (0, import_node_crypto37.randomUUID)(), at: (/* @__PURE__ */ new Date()).toISOString() };
86786
- log2.events.push(row);
86787
- writeJsonAtomic(eventsPath(projectId), log2);
86788
- return row;
86789
- }
86790
- function captureProjectCheckpoint(input) {
86791
- const projectUuid = requireIdentity(input.project);
86792
- const withoutId = {
86793
- schema: 1,
86794
- projectUuid,
86795
- publicationIdentity: input.publicationIdentity,
86796
- base: input.base,
86797
- draftHash: hashOf(input.contract),
86798
- contract: input.contract
86799
- };
86800
- const id = hashCheckpoint(withoutId);
86801
- (0, import_node_fs54.mkdirSync)(objectsDir2(input.project.id), { recursive: true });
86802
- const path = (0, import_node_path47.join)(objectsDir2(input.project.id), `${id}.json`);
86803
- if (!(0, import_node_fs54.existsSync)(path)) writeJsonAtomic(path, { ...withoutId, id });
86804
- const event = appendEvent(input.project.id, {
86805
- checkpointId: id,
86806
- kind: "captured",
86807
- revisionEpoch: input.revisionEpoch,
86808
- appIdAtCapture: input.project.app
86809
- });
86810
- return describe(input.project.id, { ...withoutId, id }, event.eventId);
86811
- }
86812
- function describe(projectId, content, latestEventId) {
86813
- const events = readEvents(projectId).events.filter((event) => event.checkpointId === content.id);
86814
- const captures = events.filter((event) => event.kind === "captured");
86815
- const first = captures[0];
86816
- const latest = events.at(-1);
86817
- if (!first || !latest) return null;
86818
- return {
86819
- ...content,
86820
- capturedAt: first.at,
86821
- archived: latest.kind === "archived",
86822
- incorporated: events.some((event) => event.kind === "incorporated"),
86823
- captureCount: captures.length,
86824
- latestEventId: latestEventId ?? latest.eventId
86825
- };
86826
- }
86827
- function listProjectCheckpoints(project) {
86828
- const uuid = requireIdentity(project);
86829
- const ids = [...new Set(readEvents(project.id).events.map((event) => event.checkpointId))];
86830
- return ids.map((id) => readContent(project.id, id)).filter((v) => v !== null).filter((v) => v.projectUuid === uuid).map((v) => describe(project.id, v)).filter((v) => v !== null).sort((a, b) => b.capturedAt.localeCompare(a.capturedAt));
86831
- }
86832
- function readProjectCheckpoint(project, checkpointId) {
86833
- const content = readContent(project.id, checkpointId);
86834
- return content && content.projectUuid === requireIdentity(project) ? describe(project.id, content) : null;
86835
- }
86836
- function markProjectCheckpoint(project, checkpointId, kind, expectedEventId) {
86837
- const current = readProjectCheckpoint(project, checkpointId);
86838
- if (!current) throw new Error(`unknown checkpoint: ${checkpointId}`);
86839
- if (current.latestEventId !== expectedEventId) throw new Error("checkpoint changed; reload saved work");
86840
- const event = appendEvent(project.id, { checkpointId, kind, revisionEpoch: 0, appIdAtCapture: project.app });
86841
- return describe(project.id, current, event.eventId);
86842
- }
86843
-
86844
87106
  // export-source.ts
86845
87107
  var import_node_crypto38 = require("node:crypto");
86846
87108
  var import_node_fs55 = require("node:fs");
@@ -86906,8 +87168,7 @@ function captureExportSource(projectId, selector = { kind: "latest-approved" },
86906
87168
  contract = readAcceptedForRequest(project.app, projectId, "read");
86907
87169
  if (contract == null) throw new Error("working copy is unavailable");
86908
87170
  const manifest = readWorkingRevisionManifest(project);
86909
- const actualEtag = etagOf(contract);
86910
- if (selector.expectedEtag && selector.expectedEtag !== actualEtag) throw new Error("working copy changed; reload before exporting");
87171
+ if (selector.expectedEtag && !recordedEtagNamesContract(selector.expectedEtag, etagsOf(contract))) throw new Error("working copy changed; reload before exporting");
86911
87172
  if (selector.expectedEpoch !== void 0 && selector.expectedEpoch !== manifest?.epoch) throw new Error("working revision changed; reload before exporting");
86912
87173
  kind = "working";
86913
87174
  sourceRef = manifest?.revisionId ?? hashOf(contract).slice(0, 12);
@@ -100255,131 +100516,7 @@ async function startServer() {
100255
100516
  }))
100256
100517
  }), { label: "listing saved work" });
100257
100518
  });
100258
- app.post(
100259
- "/api/projects/:id/revisions/start",
100260
- async (req, reply) => {
100261
- const project = getProject(req.params.id);
100262
- if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
100263
- const version = Number(req.body?.version);
100264
- if (!Number.isInteger(version) || version < 1) return reply.status(400).send({ ok: false, error: "choose a valid approved version" });
100265
- return withLifecycleLock("project", project.id, async () => {
100266
- let target;
100267
- try {
100268
- target = currentApprovedSnapshot(project.id, version);
100269
- } catch (error) {
100270
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
100271
- throw error;
100272
- }
100273
- const current = readAcceptedForRequest(project.app, project.id, "read");
100274
- if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
100275
- const actualEtag = storeEtag(project.app, project.id);
100276
- const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
100277
- if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100278
- return reply.status(428).send({ ok: false, error: "Reload History and send the working ETag and revision epoch." });
100279
- }
100280
- if (req.body.expectedEtag !== actualEtag) {
100281
- return reply.status(409).send({ ok: false, error: "The working copy changed. Reload History before starting." });
100282
- }
100283
- const observedManifest = readWorkingRevisionManifest(project);
100284
- if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) {
100285
- return reply.status(409).send({ ok: false, error: "The working revision changed. Reload History before starting." });
100286
- }
100287
- const publicationIdentity = observedManifest?.publicationIdentity ?? nativePublicationIdentity(project.uuid);
100288
- let manifest = ensureWorkingRevisionManifest({
100289
- project,
100290
- publicationIdentity,
100291
- contract: current,
100292
- workingBase: { version: target.latestApprovedVersion, hash: currentApprovedSnapshot(project.id).contractHash }
100293
- });
100294
- if (manifest.draftHash !== contractHash(current)) {
100295
- manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100296
- }
100297
- const latest = currentApprovedSnapshot(project.id);
100298
- const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
100299
- const checkpoint = dirty ? captureProjectCheckpoint({
100300
- project,
100301
- publicationIdentity,
100302
- base: manifest.workingBase,
100303
- contract: current,
100304
- revisionEpoch: manifest.epoch
100305
- }) : null;
100306
- let publication = null;
100307
- try {
100308
- const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
100309
- publication = written;
100310
- } catch (error) {
100311
- if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
100312
- throw error;
100313
- }
100314
- clearApproval(project.id);
100315
- const next = advanceWorkingRevisionManifest({
100316
- project,
100317
- expectedEpoch: manifest.epoch,
100318
- expectedDraftHash: manifest.draftHash,
100319
- publicationIdentity,
100320
- contract: normalisePlanViewIds(target.contract),
100321
- // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
100322
- // `source.hash` names the version this came from — while `contract:` above is the document the
100323
- // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
100324
- // stored canonically made the manifest disagree with the store the instant it was written.
100325
- source: { kind: "approved", version, hash: target.contractHash },
100326
- workingBase: { version, hash: target.contractHash }
100327
- });
100328
- broadcast(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
100329
- return {
100330
- ok: true,
100331
- checkpoint,
100332
- revision: next,
100333
- workingBaseVersion: version,
100334
- latestApprovedVersion: latest.version.n,
100335
- message: checkpoint ? `Saved pending work${checkpoint.base ? ` from v${checkpoint.base.version}` : ""}. Started a DRAFT from v${version}.` : `Started a DRAFT from v${version}.`
100336
- };
100337
- }, { label: `starting a revision from v${version}` });
100338
- }
100339
- );
100340
- app.post(
100341
- "/api/projects/:id/checkpoints/:checkpointId/resume",
100342
- async (req, reply) => {
100343
- const project = getProject(req.params.id);
100344
- if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
100345
- return withLifecycleLock("project", project.id, async () => {
100346
- const saved = readProjectCheckpoint(project, req.params.checkpointId);
100347
- if (!saved) return reply.status(404).send({ ok: false, error: "checkpoint not found" });
100348
- const current = readAcceptedForRequest(project.app, project.id, "read");
100349
- if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
100350
- const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
100351
- if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100352
- return reply.status(428).send({ ok: false, error: "Reload Saved work and send the working ETag and revision epoch." });
100353
- }
100354
- if (req.body.expectedEtag !== storeEtag(project.app, project.id)) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
100355
- const observedManifest = readWorkingRevisionManifest(project);
100356
- if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) return reply.status(409).send({ ok: false, error: "The working revision changed. Reload Saved work." });
100357
- const publicationIdentity = saved.publicationIdentity;
100358
- let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
100359
- if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100360
- const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
100361
- if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
100362
- let publication;
100363
- try {
100364
- publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
100365
- } catch (error) {
100366
- return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
100367
- }
100368
- clearApproval(project.id);
100369
- const next = advanceWorkingRevisionManifest({
100370
- project,
100371
- expectedEpoch: manifest.epoch,
100372
- expectedDraftHash: manifest.draftHash,
100373
- publicationIdentity,
100374
- contract: normalisePlanViewIds(saved.contract),
100375
- source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
100376
- workingBase: saved.base
100377
- });
100378
- broadcast(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
100379
- return { ok: true, revision: next, checkpoint: saved, latestApprovedVersion: latest?.version.n ?? null };
100380
- }, { label: "resuming saved work" });
100381
- }
100382
- );
100519
+ registerProjectRevisionStartRoutes(app, { broadcast });
100383
100520
  app.get("/api/projects/:id/export-sources", async (req, reply) => {
100384
100521
  const project = getProject(req.params.id);
100385
100522
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
@@ -100611,6 +100748,11 @@ async function startServer() {
100611
100748
  resolveAppContract,
100612
100749
  etagOf,
100613
100750
  storeEtag,
100751
+ // Passed BY NAME, never composed here: an expression at this wiring site is one no test can reach
100752
+ // (every route test stubs the dep, every editor test stubs the fetch), and review proved that
100753
+ // rewriting it to an exact compare left the whole suite green while #957 was unfixed in production.
100754
+ // The composition and its tests live in project-contract-hash.
100755
+ recordedEtagsNameDocument,
100614
100756
  postProcessVector: (doc) => postProcess(doc),
100615
100757
  parseSelection: readSelectionFromBody,
100616
100758
  genericBakeHostLabel,